From d64e10f4dd25976bdbf5c8804b85624bae3b6d00 Mon Sep 17 00:00:00 2001 From: SoftFever Date: Wed, 18 Nov 2026 16:50:32 +0800 Subject: [PATCH] Regroup the slicer's MCP commands and let each run from its arguments Outside the Design tab an agent had 175 commands, 50 of them in the tool list. There are now 118, named by what they act on (`object_`, `plate_`, `preset_`, `filament_`, `plugin_` and so on), and 115 are listed. Each takes its target and values in the call, acts on the selection when it names no target and says what it acted on; an old name is refused. Printers and system filaments install and uninstall, preferences read and write, plugins enable, reload, uninstall and refresh, and objects reorder, with no dialog to drive. The Speed Dial keeps its 129 tiles under the same ids. Eight defects in the rows these commands share with the menus are fixed. For a person: an object row that cannot run says why instead of "Select an object first.", rows that failed no longer claim success, Duplicate Plate can be undone, and Refresh Plugins picked while a refresh runs now runs after it instead of beside it. --- docs/HLSD/design-commands.md | 16 +- docs/HLSD/design-tab.md | 20 +- docs/HLSD/mcp-server.md | 2065 ++-- docs/HLSD/plugin-permissions.md | 2 +- docs/HLSD/preset-cache.md | 6 +- docs/HLSD/preset-plugin-api.md | 6 +- localization/i18n/list.txt | 7 + .../web/dialog/ActionReplay/action_replay.js | 6 +- .../web/dialog/ActionReplay/replay_editor.js | 2 +- .../dialog/ActionReplay/replay_editor.test.js | 26 +- resources/web/mcp/page_agent.js | 28 +- scripts/CAD/gen_offer_table.py | 12 +- scripts/CAD/tool_atlas.json | 4 +- scripts/check_operation_calls.py | 43 +- scripts/operation_calls_baseline.txt | 38 +- src/libslic3r/PresetBundle.hpp | 8 +- src/slic3r/CMakeLists.txt | 14 + src/slic3r/GUI/ActionIds.hpp | 15 + src/slic3r/GUI/ActionRegistry.cpp | 16 +- src/slic3r/GUI/ActionRegistry.hpp | 10 +- src/slic3r/GUI/ActionReplayDialog.cpp | 12 +- src/slic3r/GUI/ActionReplayDialog.hpp | 6 +- src/slic3r/GUI/AuiMgr.cpp | 17 + src/slic3r/GUI/AuiMgr.hpp | 3 + src/slic3r/GUI/CAD/DesignOffer.hpp | 30 +- src/slic3r/GUI/CAD/DesignPanel.cpp | 2 +- src/slic3r/GUI/CAD/DesignPanel.hpp | 2 +- src/slic3r/GUI/CloneDialog.cpp | 37 +- src/slic3r/GUI/CommandCatalog.cpp | 40 +- src/slic3r/GUI/CommandCatalog.hpp | 91 +- src/slic3r/GUI/CommandTypes.hpp | 2 +- src/slic3r/GUI/FilamentMapPanel.cpp | 130 +- src/slic3r/GUI/FilamentMapPanel.hpp | 45 +- src/slic3r/GUI/FileArchiveDialog.cpp | 9 +- src/slic3r/GUI/FileArchiveDialog.hpp | 4 + src/slic3r/GUI/GCodeViewer.cpp | 49 +- src/slic3r/GUI/GCodeViewer.hpp | 5 +- src/slic3r/GUI/GLCanvas3D.hpp | 1 + src/slic3r/GUI/GUI_App.cpp | 35 +- src/slic3r/GUI/GUI_App.hpp | 9 +- src/slic3r/GUI/GUI_Factories.cpp | 4 + src/slic3r/GUI/GUI_Factories.hpp | 3 + src/slic3r/GUI/GUI_ObjectList.cpp | 351 +- src/slic3r/GUI/GUI_ObjectList.hpp | 57 +- src/slic3r/GUI/Jobs/OrientJob.cpp | 15 +- src/slic3r/GUI/Jobs/OrientJob.hpp | 8 +- src/slic3r/GUI/MainFrame.cpp | 6 +- src/slic3r/GUI/Mcp/AutomationRuntime.hpp | 12 +- src/slic3r/GUI/Mcp/JobRegistry.cpp | 2 +- src/slic3r/GUI/Mcp/JobRegistry.hpp | 8 +- src/slic3r/GUI/Mcp/LaunchRun.cpp | 2 +- src/slic3r/GUI/Mcp/McpArguments.cpp | 124 +- src/slic3r/GUI/Mcp/McpArguments.hpp | 35 +- src/slic3r/GUI/Mcp/McpCore.cpp | 22 +- src/slic3r/GUI/Mcp/McpCore.hpp | 4 +- src/slic3r/GUI/Mcp/McpEndpoint.cpp | 2 +- src/slic3r/GUI/Mcp/McpJournal.cpp | 46 +- src/slic3r/GUI/Mcp/McpJournal.hpp | 16 +- src/slic3r/GUI/Mcp/McpOptions.hpp | 2 +- src/slic3r/GUI/Mcp/McpPersonContext.hpp | 23 +- src/slic3r/GUI/Mcp/McpPersonRun.cpp | 6 +- src/slic3r/GUI/Mcp/McpPersonRun.hpp | 6 +- src/slic3r/GUI/Mcp/McpProtocol.cpp | 8 +- src/slic3r/GUI/Mcp/McpRecorder.cpp | 18 +- src/slic3r/GUI/Mcp/McpRecorder.hpp | 12 +- src/slic3r/GUI/Mcp/McpReplay.cpp | 22 +- src/slic3r/GUI/Mcp/McpReplay.hpp | 13 +- src/slic3r/GUI/Mcp/McpReplaySummary.cpp | 148 +- src/slic3r/GUI/Mcp/McpReplaySummary.hpp | 10 +- src/slic3r/GUI/Mcp/McpServerInfo.cpp | 87 +- src/slic3r/GUI/Mcp/McpStdioBridge.cpp | 4 +- src/slic3r/GUI/Mcp/McpTargets.cpp | 303 + src/slic3r/GUI/Mcp/McpTargets.hpp | 73 + src/slic3r/GUI/Mcp/McpTools.hpp | 327 +- src/slic3r/GUI/Mcp/McpToolsActions.cpp | 99 +- src/slic3r/GUI/Mcp/McpToolsApi.cpp | 90 +- src/slic3r/GUI/Mcp/McpToolsApp.cpp | 231 +- src/slic3r/GUI/Mcp/McpToolsCad.cpp | 16 +- src/slic3r/GUI/Mcp/McpToolsCad.hpp | 8 +- src/slic3r/GUI/Mcp/McpToolsCommon.cpp | 46 +- src/slic3r/GUI/Mcp/McpToolsConfig.cpp | 2113 +++- src/slic3r/GUI/Mcp/McpToolsInstall.cpp | 337 + src/slic3r/GUI/Mcp/McpToolsLayers.cpp | 242 +- src/slic3r/GUI/Mcp/McpToolsPlugins.cpp | 396 + src/slic3r/GUI/Mcp/McpToolsPreferences.cpp | 255 + src/slic3r/GUI/Mcp/McpToolsProject.cpp | 477 +- src/slic3r/GUI/Mcp/McpToolsPython.cpp | 59 +- src/slic3r/GUI/Mcp/McpToolsRecord.cpp | 70 +- src/slic3r/GUI/Mcp/McpToolsReplay.cpp | 18 +- src/slic3r/GUI/Mcp/McpToolsScene.cpp | 1878 ++- src/slic3r/GUI/Mcp/McpToolsUi.cpp | 182 +- src/slic3r/GUI/Mcp/McpToolsView.cpp | 555 +- src/slic3r/GUI/Mcp/ModalTracker.cpp | 10 +- src/slic3r/GUI/Mcp/ModalTracker.hpp | 2 +- src/slic3r/GUI/Mcp/RecordingSettings.hpp | 10 +- src/slic3r/GUI/Mcp/UiInspector.cpp | 101 +- src/slic3r/GUI/Mcp/UiInspector.hpp | 20 +- src/slic3r/GUI/Mcp/UiInvoker.cpp | 6 +- src/slic3r/GUI/Mcp/UiRefs.hpp | 8 +- src/slic3r/GUI/Mcp/VideoEncode.hpp | 2 +- src/slic3r/GUI/Mcp/VideoOverlay.cpp | 18 +- src/slic3r/GUI/Mcp/WebPages.hpp | 4 +- src/slic3r/GUI/Mcp/WindowControl.cpp | 4 +- src/slic3r/GUI/Mcp/WindowControl.hpp | 10 +- src/slic3r/GUI/Mcp/WindowNames.hpp | 4 +- src/slic3r/GUI/NativeCommandRows.hpp | 107 + src/slic3r/GUI/NativeCommands.cpp | 2121 ++-- src/slic3r/GUI/NativeCommands.hpp | 105 +- src/slic3r/GUI/Operations/ExportOps.cpp | 54 +- src/slic3r/GUI/Operations/ExportOps.hpp | 42 +- src/slic3r/GUI/Operations/InstallOps.cpp | 923 ++ src/slic3r/GUI/Operations/InstallOps.hpp | 203 + src/slic3r/GUI/Operations/ObjectOps.cpp | 1244 ++ src/slic3r/GUI/Operations/ObjectOps.hpp | 508 + src/slic3r/GUI/Operations/Outcome.cpp | 56 + src/slic3r/GUI/Operations/Outcome.hpp | 4 + src/slic3r/GUI/Operations/PlateOps.cpp | 116 +- src/slic3r/GUI/Operations/PlateOps.hpp | 64 +- src/slic3r/GUI/Operations/PluginOps.cpp | 618 + src/slic3r/GUI/Operations/PluginOps.hpp | 260 + src/slic3r/GUI/Operations/PreferenceOps.cpp | 943 ++ src/slic3r/GUI/Operations/PreferenceOps.hpp | 124 + src/slic3r/GUI/Operations/PresetOps.cpp | 301 + src/slic3r/GUI/Operations/PresetOps.hpp | 124 + src/slic3r/GUI/Operations/ProjectOps.cpp | 128 +- src/slic3r/GUI/Operations/ProjectOps.hpp | 68 +- src/slic3r/GUI/Plater.cpp | 605 +- src/slic3r/GUI/Plater.hpp | 94 +- src/slic3r/GUI/PluginsDialog.cpp | 454 +- src/slic3r/GUI/PluginsDialog.hpp | 12 +- src/slic3r/GUI/Preferences.cpp | 1304 +- src/slic3r/GUI/Preferences.hpp | 25 +- src/slic3r/GUI/RecordingDialog.hpp | 2 +- src/slic3r/GUI/RecordingIndicator.cpp | 2 +- src/slic3r/GUI/RunScriptPanel.cpp | 4 +- src/slic3r/GUI/RunScriptPanel.hpp | 2 +- src/slic3r/GUI/Selection.cpp | 29 +- src/slic3r/GUI/Selection.hpp | 5 +- src/slic3r/GUI/SyncAmsInfoDialog.cpp | 170 +- src/slic3r/GUI/SyncAmsInfoDialog.hpp | 14 +- src/slic3r/GUI/Tab.cpp | 23 +- src/slic3r/GUI/Tab.hpp | 9 +- src/slic3r/GUI/WebGuideDialog.cpp | 517 +- src/slic3r/GUI/WebGuideDialog.hpp | 3 +- src/slic3r/Utils/FixModelByCgal.cpp | 42 +- src/slic3r/Utils/FixModelByCgal.hpp | 13 +- src/slic3r/plugin/PluginAuditManager.hpp | 2 +- src/slic3r/plugin/PluginOperations.hpp | 2 +- src/slic3r/plugin/PythonPluginBridge.cpp | 2 +- src/slic3r/plugin/PythonRunScope.hpp | 4 +- src/slic3r/plugin/PythonScriptRunner.cpp | 2 +- src/slic3r/plugin/PythonScriptRunner.hpp | 10 +- src/slic3r/plugin/host/PluginHostApp.cpp | 8 +- src/slic3r/plugin/host/PluginHostTools.cpp | 26 +- src/slic3r/plugin/host/PluginHostUi.cpp | 4 +- tests/automation/test_command_catalog.cpp | 74 +- tests/automation/test_mcp_core.cpp | 204 +- tests/automation/test_mcp_protocol.cpp | 40 +- tests/automation/test_mcp_replay.cpp | 171 +- tests/automation/test_mcp_replay_summary.cpp | 373 +- tests/data/command_catalog.json | 10042 +++++++++------- tests/data/speed_dial_tile_calls.json | 826 ++ tests/data/speed_dial_tiles.json | 905 ++ tests/slic3rutils/retired_names.hpp | 88 + tests/slic3rutils/test_action_source.cpp | 196 +- tests/slic3rutils/test_command_catalog.cpp | 770 +- tests/slic3rutils/test_mcp_cad.cpp | 32 +- tests/slic3rutils/test_mcp_config.cpp | 850 +- tests/slic3rutils/test_mcp_core.cpp | 36 +- tests/slic3rutils/test_mcp_protocol.cpp | 22 +- tests/slic3rutils/test_mcp_recording.cpp | 144 +- tests/slic3rutils/test_mcp_results.cpp | 149 +- tests/slic3rutils/test_mcp_scene.cpp | 808 +- tests/slic3rutils/test_mcp_tools.cpp | 766 +- tests/slic3rutils/test_mcp_web.cpp | 2 +- tests/slic3rutils/test_object_list.cpp | 109 + tests/slic3rutils/test_operations.cpp | 1869 ++- tests/slic3rutils/test_plugin_host_api.cpp | 16 +- .../slic3rutils/test_python_script_runner.cpp | 98 +- tools/mcp/README.md | 303 +- tools/mcp/cad_gui.py | 80 +- tools/mcp/gen_skill_reference.py | 116 +- tools/mcp/orca_mcp.py | 44 +- tools/mcp/run_sweep.py | 2 +- tools/mcp/smoke_test.json | 40 +- tools/mcp/sweep.json | 23 + tools/mcp/test_action_replay_hidden.py | 68 +- tools/mcp/test_additions_refusals.py | 259 + tools/mcp/test_cad_click_edit.py | 2 +- tools/mcp/test_cad_commands.py | 68 +- tools/mcp/test_cad_context_menu.py | 8 +- tools/mcp/test_cad_examples.py | 8 +- tools/mcp/test_cad_failed_job.py | 24 +- tools/mcp/test_cad_replay.py | 24 +- tools/mcp/test_cad_sketching.py | 14 +- tools/mcp/test_cad_slow_build.py | 32 +- tools/mcp/test_cancel_pending_slice.py | 22 +- tools/mcp/test_command_line.py | 45 +- tools/mcp/test_every_tile.py | 769 ++ tools/mcp/test_export_running_job.py | 42 +- tools/mcp/test_install_filaments.py | 262 + tools/mcp/test_install_printers.py | 346 + tools/mcp/test_list_windows.py | 34 +- tools/mcp/test_operation_routes.py | 130 +- tools/mcp/test_orca_mcp_attach.py | 12 +- tools/mcp/test_person_forms.py | 348 + tools/mcp/test_plugin_commands.py | 335 + tools/mcp/test_plugin_tools.py | 116 +- tools/mcp/test_preferences.py | 331 + tools/mcp/test_printer_extruders.py | 238 + tools/mcp/test_project_open_settings.py | 100 + tools/mcp/test_recovery_under_load.py | 14 +- tools/mcp/test_ref_locator_export.py | 52 +- tools/mcp/test_rows_refusals.py | 587 + tools/mcp/test_runtime_lifecycle.py | 82 +- tools/mcp/test_send_gcode.py | 81 +- tools/mcp/test_set_view_camera.py | 86 +- tools/mcp/test_set_view_preview.py | 56 +- tools/mcp/test_set_window.py | 110 +- tools/mcp/test_sidebar_floating.py | 137 + tools/mcp/test_speed_dial_open.py | 22 +- tools/mcp/test_stdio_bridge.py | 10 +- tools/mcp/test_web_ui.py | 515 +- tools/mcp/test_webview_modal.py | 40 +- tools/mcp/test_worker_admission.py | 50 +- tools/mcp/tests/agent_forms.json | 74 +- tools/mcp/tests/cad_canvas.json | 66 +- tools/mcp/tests/cad_doc.json | 168 +- tools/mcp/tests/cad_features.json | 92 +- tools/mcp/tests/cad_sketch_edit.json | 80 +- tools/mcp/tests/cad_sketch_to_solid.json | 76 +- tools/mcp/tests/cad_topology_targets.json | 68 +- tools/mcp/tests/calibration.json | 128 +- tools/mcp/tests/context_menus.json | 56 +- tools/mcp/tests/dialogs_canvas_input.json | 60 +- tools/mcp/tests/filaments_and_files.json | 141 + .../mcp/tests/fixtures/filaments_and_files.py | 93 + tools/mcp/tests/fixtures/objects_files.py | 122 + tools/mcp/tests/fixtures/ops_presets.py | 50 +- tools/mcp/tests/fixtures/ops_undo.py | 6 +- .../tests/fixtures/presets_and_plate_map.py | 67 + tools/mcp/tests/fixtures/settings_targets.py | 53 + tools/mcp/tests/gizmos.json | 466 +- tools/mcp/tests/layers.json | 278 +- tools/mcp/tests/multicolor.json | 130 +- .../tests/new_project_keeps_layer_gcode.json | 54 +- tools/mcp/tests/objects_files.json | 132 + tools/mcp/tests/objects_order.json | 47 + tools/mcp/tests/objects_state.json | 93 + ...ops_assign_filament_preset_multi_slot.json | 616 +- .../ops_assign_filament_preset_one_slot.json | 524 +- tools/mcp/tests/ops_export_gcode.json | 180 +- tools/mcp/tests/ops_export_model_3mf.json | 80 +- tools/mcp/tests/ops_export_sliced_3mf.json | 139 +- tools/mcp/tests/ops_export_stl.json | 80 +- tools/mcp/tests/ops_import_models.json | 255 +- tools/mcp/tests/ops_import_presets.json | 127 +- tools/mcp/tests/ops_new_project.json | 188 +- tools/mcp/tests/ops_open_project.json | 203 +- tools/mcp/tests/ops_save_project_as.json | 97 +- tools/mcp/tests/ops_select_plate.json | 163 +- tools/mcp/tests/ops_select_preset.json | 508 +- tools/mcp/tests/ops_send_gcode_to_host.json | 70 +- tools/mcp/tests/ops_set_instance_count.json | 184 +- tools/mcp/tests/ops_set_plate_locked.json | 126 +- tools/mcp/tests/ops_show_layer_range.json | 202 +- tools/mcp/tests/ops_start_arrange.json | 134 +- tools/mcp/tests/ops_start_slice.json | 204 +- tools/mcp/tests/plate_icons.json | 56 +- tools/mcp/tests/plates.json | 172 +- .../mcp_tools_fixture/mcp_tools_fixture.py | 14 +- .../mcp_web_fixture/mcp_web_fixture.py | 22 +- tools/mcp/tests/presets.json | 479 +- tools/mcp/tests/presets_and_plate_map.json | 73 + tools/mcp/tests/preview.json | 216 +- tools/mcp/tests/recording.json | 92 +- tools/mcp/tests/rows.json | 110 +- tools/mcp/tests/rows_objects.json | 61 + tools/mcp/tests/rows_placement.json | 107 + tools/mcp/tests/rows_plates.json | 66 + tools/mcp/tests/rows_structure.json | 64 + tools/mcp/tests/scene.json | 496 +- tools/mcp/tests/settings_targets.json | 125 + tools/mcp/tests/slice_stats.json | 86 +- tools/mcp/tests/tiles_ask.json | 65 + tools/mcp/tests/view_switches.json | 108 + tools/mcp/tests/web_dialogs.json | 60 +- 287 files changed, 40484 insertions(+), 16770 deletions(-) create mode 100644 src/slic3r/GUI/Mcp/McpTargets.cpp create mode 100644 src/slic3r/GUI/Mcp/McpTargets.hpp create mode 100644 src/slic3r/GUI/Mcp/McpToolsInstall.cpp create mode 100644 src/slic3r/GUI/Mcp/McpToolsPlugins.cpp create mode 100644 src/slic3r/GUI/Mcp/McpToolsPreferences.cpp create mode 100644 src/slic3r/GUI/NativeCommandRows.hpp create mode 100644 src/slic3r/GUI/Operations/InstallOps.cpp create mode 100644 src/slic3r/GUI/Operations/InstallOps.hpp create mode 100644 src/slic3r/GUI/Operations/ObjectOps.cpp create mode 100644 src/slic3r/GUI/Operations/ObjectOps.hpp create mode 100644 src/slic3r/GUI/Operations/PluginOps.cpp create mode 100644 src/slic3r/GUI/Operations/PluginOps.hpp create mode 100644 src/slic3r/GUI/Operations/PreferenceOps.cpp create mode 100644 src/slic3r/GUI/Operations/PreferenceOps.hpp create mode 100644 tests/data/speed_dial_tile_calls.json create mode 100644 tests/data/speed_dial_tiles.json create mode 100644 tests/slic3rutils/retired_names.hpp create mode 100644 tools/mcp/test_additions_refusals.py create mode 100644 tools/mcp/test_every_tile.py create mode 100644 tools/mcp/test_install_filaments.py create mode 100644 tools/mcp/test_install_printers.py create mode 100644 tools/mcp/test_person_forms.py create mode 100644 tools/mcp/test_plugin_commands.py create mode 100644 tools/mcp/test_preferences.py create mode 100644 tools/mcp/test_printer_extruders.py create mode 100644 tools/mcp/test_project_open_settings.py create mode 100644 tools/mcp/test_rows_refusals.py create mode 100644 tools/mcp/test_sidebar_floating.py create mode 100644 tools/mcp/tests/filaments_and_files.json create mode 100644 tools/mcp/tests/fixtures/filaments_and_files.py create mode 100644 tools/mcp/tests/fixtures/objects_files.py create mode 100644 tools/mcp/tests/fixtures/presets_and_plate_map.py create mode 100644 tools/mcp/tests/fixtures/settings_targets.py create mode 100644 tools/mcp/tests/objects_files.json create mode 100644 tools/mcp/tests/objects_order.json create mode 100644 tools/mcp/tests/objects_state.json create mode 100644 tools/mcp/tests/presets_and_plate_map.json create mode 100644 tools/mcp/tests/rows_objects.json create mode 100644 tools/mcp/tests/rows_placement.json create mode 100644 tools/mcp/tests/rows_plates.json create mode 100644 tools/mcp/tests/rows_structure.json create mode 100644 tools/mcp/tests/settings_targets.json create mode 100644 tools/mcp/tests/tiles_ask.json create mode 100644 tools/mcp/tests/view_switches.json diff --git a/docs/HLSD/design-commands.md b/docs/HLSD/design-commands.md index dafd91053f..f5e391a146 100644 --- a/docs/HLSD/design-commands.md +++ b/docs/HLSD/design-commands.md @@ -10,13 +10,13 @@ Replay and recordings show, and what the journal records and replays. This document is the command set: how the commands are named and grouped, what each does and takes, how a call opens a tool for a person instead of running, and how the commands relate to the right-click menu's -rows. How the server serves them (the catalog, `search_tools`, the gate, the journal) is in +rows. How the server serves them (the catalog, `tool_search`, the gate, the journal) is in [mcp-server.md](mcp-server.md), and the tab itself in [design-tab.md](design-tab.md). One table defines them all: `scripts/CAD/tool_atlas.json`. `scripts/CAD/gen_offer_table.py` writes `src/slic3r/GUI/CAD/DesignOffer.hpp` from it, and the commands' code is `src/slic3r/GUI/Mcp/McpToolsCad.cpp`. What every command takes and replies is in its entry's tool block, which the agent reads through -`search_tools {tool}`; `tests/data/command_catalog.json` holds every command's schema, tiles and examples as +`tool_search {tool}`; `tests/data/command_catalog.json` holds every command's schema, tiles and examples as an agent sees them. ## Naming @@ -35,7 +35,7 @@ variable, body and feature. - `construct_`: reference planes, axes and coordinate systems. - `feature_`: one entry of the history: describe, edit, suppress, move, rename, delete. - `body_`: one body as an object: name and colour it, delete it, place it, describe and measure it. - `body_transform` is here too, since `transform` is the Prepare tab's command. + `body_transform` is here too, since `object_transform` is the Prepare tab's command. 2. **One command per operation, and one argument for its variants.** `type` says which kind of thing the command makes, or which way it makes it: a shape, a pattern's layout, a hole's kind, how a plane is defined. A shape drawn more than one way names the way (`rectangle_3_point`). @@ -52,7 +52,7 @@ whole bodies. ## The command set -The commands are listed under the headings `search_tools`' description names them under, in its order: +The commands are listed under the headings `tool_search`' description names them under, in its order: Document, Sketch, Solid, Surface, Construct, Inspect, Bodies, History and Menu rows. Main arguments only; every argument, its default and its range are in the command's schema. @@ -217,7 +217,7 @@ These take no arguments and do what their row of the right-click menu does. ### Outside the Design table -`undo` and `redo` with `{history: "design"}` step the Design history. `set_view` with `tab: "design"` takes +`undo` and `redo` with `{history: "design"}` step the Design history. `view_set` with `tab: "design"` takes the Design view's options: `camera: "sketch_normal"`, which looks straight at the open sketch and is refused with none open; `section` `{on, z, keep}`, a horizontal cut at world `z` (left out, the model's middle) that keeps the lower or the upper half; and `origin_planes`, `world_axes`, `origin` and `bed`, which show or hide @@ -322,7 +322,7 @@ and a pattern's layout as `type` in the commands' words. A feature's type name ( ### How a failure shows -A command that fails is an error (`code` `-32000`) and leaves the design as it was, so `export_replay` leaves +A command that fails is an error (`code` `-32000`) and leaves the design as it was, so `replay_export` leaves it out. That holds for argument errors and for a rebuild the engine rejects alike. Twenty-one commands instead report a rejected rebuild in their reply, `ok` false or `error` not empty, after the same rollback, so such a call is journaled and replays the same rejection: `body_transform`, `boolean`, `construct_axis`, @@ -451,12 +451,12 @@ address, and changing one is a breaking change. own row's tile is under the command's key (`orca_command:sketch_trim:orca`); a folded row keeps its tile under its own id (`orca_command:sk_array:orca`) with its row's title and icon. - A pick of a folded row's tile runs its command with the row's arguments, with the MCP server on or off. - Its action shows an agent no arguments, and `run_action` takes none for it, or exactly the row's; that is + Its action shows an agent no arguments, and `action_run` takes none for it, or exactly the row's; that is what the journal records, so a replay runs it again. - A call of a command with a row's arguments is titled as that row's tile wherever a person is shown the call: a job notice, a recording's caption, an Action Replay step (`replay_what_text()`). - A folded tile that is not shown is named, when a call asks for it, with the call that runs it from any - tab: `call_tool {"tool": "sketch_pattern", "args": {"type": "linear"}}`. + tab: `tool_call {"tool": "sketch_pattern", "args": {"type": "linear"}}`. - The MCP skill's reference (`tools/mcp/gen_skill_reference.py`) gives a command a row of its own only when it has an action of its own, and one row per folded tile with its arguments. diff --git a/docs/HLSD/design-tab.md b/docs/HLSD/design-tab.md index 8f1d08441c..bd7d39a89b 100644 --- a/docs/HLSD/design-tab.md +++ b/docs/HLSD/design-tab.md @@ -385,7 +385,7 @@ fold into eight commands, the 24 shape rows into `sketch_draw` among them. An en may name the arguments that choose its own row (`args`), as Boolean's Join row is `boolean {operation: "join"}`, so that each of a command's variants opens the same way. Two rows have neither an action nor a block, Pattern on Curve and Align to, and are shown greyed: they are no command. Every command has a `section`, its heading in -the names index the MCP server's `search_tools` gives, and `feature_row` marks the four rows whose action works +the names index the MCP server's `tool_search` gives, and `feature_row` marks the four rows whose action works on the Feature tree's selected row (Edit, Rename, Delete and Constrain sketch). `modal` marks the three entries whose action opens a dialog that waits for an answer: a modal one for SVG (a file picker) and Color, which holds the call that opened it until it is answered, and the Design tab's own modeless dialog for Text, @@ -398,9 +398,9 @@ for a checked-in header, not documentation. ## Automation surface The document is automated through the app's MCP server, on every platform, with the Design tab's commands, one -per command entry of its table, in the command catalog's group `Design`: `search_tools {group: "Design"}` -lists them, `search_tools {tool}` gives one's arguments, how its failure shows and runnable examples, and -`call_tool {tool, args}` runs one. They are named in the industry's terminology, as popular CAD programs such +per command entry of its table, in the command catalog's group `Design`: `tool_search {group: "Design"}` +lists them, `tool_search {tool}` gives one's arguments, how its failure shows and runnable examples, and +`tool_call {tool, args}` runs one. They are named in the industry's terminology, as popular CAD programs such as Fusion 360, Onshape and SolidWorks use it, with a prefix for where each works (`sketch_`, `surface_`, `construct_`, `feature_`, `body_`, and none for the model), and one argument for a variant: `type` for which kind of thing it makes, `operation` for what the result does to the bodies already there. A person picks the @@ -421,7 +421,7 @@ does and takes and which menu rows call it, is in [design-commands.md](design-co An agent's call needs the MCP server on (`--mcp`, or Preferences), and every command, a person's tile included, needs the CAD feature on (Preferences > Features, or `--cad` for one run). The catalog holds them only when the feature is on at startup, as the main window makes the Design page only then, so turning it on takes a restart; -with it off they are unknown commands, whose error says how a person turns it on, as `get_app_state`'s +with it off they are unknown commands, whose error says how a person turns it on, as `app_state`'s `cad_note` does. Turned off while OrcaSlicer runs, the tab stays until the restart, but the Speed Dial has no tile of it. A call is refused (`-32002`) while the Design tab is busy: none runs while a rebuild owns the document, `change` and `sketch` commands do not run under an open feature card, the Text dialog, Constrain mode @@ -477,7 +477,7 @@ moves and turns a body as the Move / Rotate card does, lays a face on the bed as it back where the model has it. Like the gizmo it is outside the history and not saved, and a placement follows its body when the bodies are renumbered, by the transient id of the feature that made it. `describe_design` reports each body's placement. The section view and the view's switches are set by value -through `set_view {tab: "design"}` (`section {on, z, keep}`, `origin_planes`, `world_axes`, `origin`, `bed`), +through `view_set {tab: "design"}` (`section {on, z, keep}`, `origin_planes`, `world_axes`, `origin`, `bed`), which the toolbar and the rows only toggle, and its `camera: "sketch_normal"` is the `N` key, refused with no sketch open. @@ -521,10 +521,10 @@ angle to the helix axis. Thread, sweep and loft automation rebuilds through `rec as the cards do, so the window stays live during a long build. The viewport is a canvas target like Prepare's for the app's MCP server (`DesignCanvas::gl_canvas()`): -`set_view {tab: "design"}` shows the tab and points its camera, `screenshot` captures the view +`view_set {tab: "design"}` shows the tab and points its camera, `window_screenshot` captures the view (sketch overlay and status line included) and composites it into window captures, `mouse_gesture` clicks and drags it at pixels, so a left click picks and a right click opens the offer, and -`list_widgets` lists its in-canvas value fields. Keys sent with `press_keys` reach the panel's +`widget_list` lists its in-canvas value fields. Keys sent with `keyboard_press` reach the panel's `wxEVT_CHAR_HOOK` as a real key press does, travelling up from the focused widget, so Escape, Enter and the tool shortcuts behave as they do for a person. @@ -564,7 +564,7 @@ catalog holds: one per command entry and none for a folded or a greyed row, a si block and a block for every silent form, the folded rows' tiles, which call opens a tool and which runs, their schemas and summaries, and examples that call only real commands with arguments their schemas take; `scripts/CAD/test_gen_offer_table.py` checks the generator's refusals. On a live application launched with `tools/mcp/orca_mcp.py launch --cad`, the replays -`tools/mcp/tests/cad_*.json` drive the commands through `call_tool`, the live tests `tools/mcp/test_cad_replay.py`, +`tools/mcp/tests/cad_*.json` drive the commands through `tool_call`, the live tests `tools/mcp/test_cad_replay.py`, `test_cad_slow_build.py` and `test_cad_failed_job.py` cover journaling and replay, the app staying live through a long rebuild, and a call whose job fails after its reply, `tools/mcp/test_cad_examples.py` runs every command's examples, each on a fresh design, and @@ -573,7 +573,7 @@ answer. The GUI tests `tools/mcp/test_cad_sketching.py`, `test_cad_context_menu.py` and `test_cad_click_edit.py` drive the tab as a person does, through the server's UI tools: they draw on the canvas with clicks and typed values, run the offer's verbs from a right click and type into the value fields with -no click into them, and grade what the reading commands and `list_widgets` report back. They +no click into them, and grade what the reading commands and `widget_list` report back. They need an English UI and no CI job runs them; `tools/mcp/README.md` says how to run them. Three checks in `scripts/CAD/` drive a running app through its MCP server as an agent does and diff --git a/docs/HLSD/mcp-server.md b/docs/HLSD/mcp-server.md index 25d3292c3b..bdde8c0e52 100644 --- a/docs/HLSD/mcp-server.md +++ b/docs/HLSD/mcp-server.md @@ -77,7 +77,7 @@ A tool result is one compact JSON text block plus any image blocks; no tool decl Claude Code shows its model a tool's description and input schema but never its output schema, and fails a call whose structured content does not match that schema, so a schema would teach its agents nothing and could turn a call that already ran into an error. Clients that prefer structured content -over the content blocks would also drop the images and `list_widgets`'s tree. Tool failures, invalid +over the content blocks would also drop the images and `widget_list`'s tree. Tool failures, invalid arguments included, are `isError` results the model can act on; an unknown tool is a JSON-RPC `-32602` error naming close matches, or the catalog that does have the name (see Tool catalog). `validate_arguments()` checks arguments against the tool's schema first. Before it, @@ -90,23 +90,25 @@ as `save_path` where the tool has no `path` of its own. A value in another JSON number, boolean, array or object written as a string, an index as a string where a name may also go (`"0"` for a plate), a single item for an array, also where null may stand for the array. A value outside its argument's enum moves to the one other argument whose enum takes it, when the call -leaves that out: `set_view`'s `canvas: "front"` is its `camera`. Each enum lists only its own values, +leaves that out: `view_set`'s `canvas: "front"` is its `camera`. Each enum lists only its own values, since listing a camera direction under both had agents give it to the wrong one. Anything that still does not fit is left for the validator to report. The bench's transcripts are where these come from: each was an agent's first guess, many times over, and each cost a failed call and a retry. -The server `instructions` (under the 4096 characters clients keep) give the workflow: `get_app_state`, -act, then check the result with the reading tools, keeping screenshots for what those do not report. -The rest is in three sections, by what the tools are for: running the session, acting on project data, +The server `instructions` (under the 4096 characters clients keep) give the workflow: `app_state`, +act, then check the result with the reading commands, keeping screenshots for what those do not report. +The rest is in three sections, by what the commands are for: running the session, acting on project data, which an agent should prefer, and driving the GUI itself. -They say to prefer typed tools over clicks and never retry a call that returned a job, point to -`get_settings`' meta and search for what a setting does, say how a gizmo opens and is driven (and that -`pick_gizmo_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 `set_view` rather than a drag, and which indices are 0-based. -They also point to `search_tools {query}` as the one search across every catalog an agent calls into: -the commands, among them those `tools/list` never shows (the Speed Dial's commands, the Design tab's and -the operations plugins offer, so nothing else tells an agent they exist), the Speed Dial's other actions, -settings and the Python API. An agent rarely +They say to prefer the commands that act on project data over clicks and never retry a call that returned a +job, that commands are named place first, then verb, and `tool_search {group}` lists a place's, that a call +with exactly a tile's arguments may ask as a person's pick does while any other runs from its arguments, +point to `settings_get {query}` and its meta for what a setting does, 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 also point to `tool_search {query}` as the one search across every catalog an agent calls into: +the commands, among them those `tools/list` never shows (the three menu rows that take no arguments, the +Design tab's and the operations plugins offer, so nothing else tells an agent they exist), the Speed Dial's +other actions, settings and the Python API. An agent rarely knows which catalog answers "how do I add a brim", and each catalog has its own search with its own arguments. Clients that defer tools load only their names and the instructions at first, so the instructions are how an agent without a skill learns which tool to @@ -117,7 +119,7 @@ load. The bearer token is 32 random bytes as 64 hex characters in `/mcp/token`: directory 0700 and file created 0600 with `O_CREAT|O_EXCL` on POSIX, the per-user ACL of `%APPDATA%` on Windows. It stays out of AppConfig, whose writes and backups use default permissions. `ORCA_MCP_TOKEN` overrides -it for one run, and stays out of the process list; `get_app_state.mcp.token_source` (`file` or +it for one run, and stays out of the process list; `app_state.mcp.token_source` (`file` or `ORCA_MCP_TOKEN`) says which is in force. Every start of the endpoint reads the file, so deleting it and turning the server off and on in Preferences issues a new token. While serving, `/mcp/server.json` holds `{url, port, pid, version, token}` with the token in @@ -135,7 +137,7 @@ dialogs. `--run` alone starts the runtime without the endpoint, and so do Action Script panel, a plugin's tool call and a person's recording or long command when the server is off. Each front end gets the runtime from `GUI_App::automation()`, which starts it on first use and returns nullptr while OrcaSlicer closes or the runtime stops; `automation_if_started()` returns it, stopping or -not, and never starts it. `get_app_state.ready` stays false until `post_init()` calls `mark_ready()`, +not, and never starts it. `app_state.ready` stays false until `post_init()` calls `mark_ready()`, the Prepare canvas has loaded OpenGL and the main window has built its tab pages, and tools that need the main window fail with "still starting". Starting on Home, the canvas loads OpenGL at idle after `post_init()` (MainFrame's GL prebuild), and before that a 3MF save would draw its thumbnail with no GL @@ -152,7 +154,7 @@ built the font waits for its first render to measure its text. A front end asks for what it uses. `AutomationRuntime::start()` brings up the dispatch core, the jobs, the UI invoker, the modal tracker, the recorder and the list of presses held on web pages: all that a person's recording or a long command a person picked from the Speed Dial needs, the recorder drawing the -modal dialogs from the tracker's stack. The GUI instruments are the UI inspector behind `list_widgets` +modal dialogs from the tracker's stack. The GUI instruments are the UI inspector behind `widget_list` and the input tools, the menu capture, ImGui item recording and, on Wayland, the window-state hooks (`track_window_states()`). `enable_gui_instruments()` turns them on for the front ends that drive the GUI: `McpEndpoint::open()` when it opens, the command line's run (`start_launch_run()`) and a plugin's @@ -224,7 +226,7 @@ Preferences turns the server on with `GUI_App::open_mcp_endpoint()` and off with `GUI_App::close_mcp_endpoint()`, which closes only the endpoint. The runtime, running jobs and a launch run carry on, because the call that opened Preferences may itself be an MCP call still on the stack, and turning the server on again opens the same endpoint, with the protocol it had, on the same port. -Preferences reads the endpoint through `GUI_App::mcp_endpoint()`, and `get_app_state.mcp` is the +Preferences reads the endpoint through `GUI_App::mcp_endpoint()`, and `app_state.mcp` is the endpoint's `describe()`: whether it serves and, while it does, its port, URL, token source, token file and discovery file; in a session that never opened it, `{serving: false}`. The port field shows the port in use, `--mcp-port`'s included, and only an edit of it is saved and reopens the endpoint, through @@ -262,25 +264,25 @@ out and paints it only in a frame, and after each frame it shows it waits for th go-ahead, which doesn't come. Waits on the UI then time out, a list can't scroll to a row and the 3D views capture blank, none of it for the reason the call would give. `undrawn_window()` asks the main window's frame clock for a frame and waits up to half a second for it to run, so only a call that -failed asks it: a `poll_ui()` timeout, a blank canvas capture and a row `click` can't place say the +failed asks it: a `poll_ui()` timeout, a blank canvas capture and a row `widget_click` can't place say the window isn't being drawn when it isn't. `GuardClass` decides what may run when: | Class | Tools | Runs behind a modal or inside another call | |---|---|---| -| `Inspect` | get_app_state, wait, get_log, list tools, get_settings, screenshot, list_widgets, start_recording, stop_recording, encode_recording | yes | -| `Recover` | answer_dialog, auto_answer_dialogs, GUI input aimed at the topmost modal, set_window | yes | +| `Inspect` | app_state, app_wait, app_log, the searches and lists (tool_search, action_search, object_list, plate_list, preset_list, settings_list, printer_list_models, plugin_list, window_list), the reads (settings_get, plate_get_settings, project_get_settings, preferences_get, plate_slice_stats, script_search_api), window_screenshot, widget_list, replay_export, recording_start, recording_stop, recording_encode | yes | +| `Recover` | dialog_answer, dialog_auto_answer, job_cancel, GUI input aimed at the topmost modal, window_set | yes | | `Mutate` | everything else | no | The closure checks the guards on the UI thread, since the app can change between posting and running. A closing app or a stopped runtime fails the call with "shutting down". A frame being recreated fails it with "retry". A mutate call is refused while a modal dialog is open, and the refusal lists the dialogs. It is also refused when it would run inside another UI call's nested -event loop: a modal, `ProgressDialog::Update` or `wxYield`. The GUI input tools (`click`, -`set_widget_value`, `press_keys`) and `answer_dialog` run as recover calls. Once a target resolves outside the +event loop: a modal, `ProgressDialog::Update` or `wxYield`. The GUI input tools (`widget_click`, +`widget_set_value`, `keyboard_press`) and `dialog_answer` run as recover calls. Once a target resolves outside the topmost modal, they apply the mutate checks themselves (`UiInvoker::require_mutate()`), along with -operation admission (`McpCore::admit()`). `cancel_job` is a recover call too, so neither a dialog the +operation admission (`McpCore::admit()`). `job_cancel` is a recover call too, so neither a dialog the operation opened nor another call's nested loop keeps it out. `NativeCommand::inline_call` decides where a call runs. Pure observation tools run on the request @@ -290,7 +292,7 @@ in dialogs included, since a click can open another modal (Preferences, Keyboard keeps the last 64 results, plus finished jobs whose parent (a running replay) may still wait for them, up to 1024 in all. The request thread waits up to `NativeCommand::budget_ms` (45 s, under Codex's 60 s tool timeout); after that the reply is `{status: "running", job, tool, note}` and the -job keeps going until `wait {for: "job"}` (at most 50 s per call) returns its result. The server +job keeps going until `app_wait {for: "job"}` (at most 50 s per call) returns its result. The server never retries a mutating call, and every envelope tells the model not to either. The environment variable `ORCA_MCP_REPLY_BUDGET_MS`, read when the runtime starts and logged when set, caps every command's budget at that many milliseconds; it only lowers a budget, never raises one, and exists for @@ -300,8 +302,8 @@ tests that need a call to outlive its budget without waiting 45 s for it. request thread posts a probe closure, which runs inside a wx dialog's loop and returns the `ModalTracker` snapshot as JSON; no `wxDialog*` crosses threads. With a modal open, the reply is `{status: "blocked_by_dialog", job, dialogs}`. Its note says how to answer the topmost dialog: -`answer_dialog` for a wx dialog or a native message box whose buttons are listed, a person for any -other dialog marked `native: true` (a picker, or any native dialog on macOS), which `answer_dialog` +`dialog_answer` for a wx dialog or a native message box whose buttons are listed, a person for any +other dialog marked `native: true` (a picker, or any native dialog on macOS), which `dialog_answer` can't press. On macOS a file picker, folder picker or message box pauses wx's pending events while it is open @@ -350,15 +352,16 @@ Slicing and G-code export finish in the background process. Their handlers call `ToolContext::begin_operation()` in a short UI closure before starting the work; that fails if another operation runs. An export starts in that same closure. A slice first waits for the background update that a change made just before has scheduled, which validates the new state, and -then requests the slice. A `cancel_job` that comes while it waits moves on `Plater::slice_cancel_seq()`, +then requests the slice. A `job_cancel` that comes while it waits moves on `Plater::slice_cancel_seq()`, so the slice never starts and reports its plates `cancelled`. `poll_ui()` then checks on the work through `observe_ui()` every 200 ms, so a dialog that opens meanwhile doesn't stop the watch, until -the work ends or the deadline passes. The deadline is `slice.timeout_s` (default 30 minutes) for a -slice and 10 minutes for an export. +the work ends or the deadline passes. The deadline is `plate_slice`'s `timeout_s` (default 30 minutes) +for a slice and 10 minutes for an export. **Worker jobs.** Arrange, orient, Fill bed and the jobs of the Text, SVG and texture gizmos run on -the Plater's UI job worker, whatever started them: the typed `arrange`, `run_action obj_arrange`, a -GL toolbar item, an ImGui button such as the Arrange options panel's, or a gizmo control. `McpCore` +the Plater's UI job worker, whatever started them: `object_arrange` or `object_auto_orient`, called or +run as a tile, a GL toolbar item, an ImGui button such as the Arrange options panel's, or a gizmo +control. `McpCore` watches that worker through `WorkerHooks` (busy and cancel, both on the UI thread). A call that finds the worker idle at the start of one of its UI closures and busy at the end of that closure, or of a later one (a toolbar event or a render queued by the call starts the job between closures), has @@ -367,9 +370,9 @@ own job then ends only once the worker is idle again, its finalization included, `ModelInstance` pointers until then. (`Worker::is_idle()` reads true from the moment the worker takes the finalize message, so a dialog finalization opens, such as an arrange's geometry error, ends the hold early; the modal guard keeps changes out until it closes.) Its reply waits within the reply budget and -then becomes a running job, as for any call. `cancel_job` (or the call's own timeout, 30 minutes unless -the tool sets a shorter one, as `arrange` does) asks the job to stop, but `Worker::cancel()` does not -wait, so the call keeps the operation until the worker is idle and then fails as cancelled. `cancel_job` +then becomes a running job, as for any call. `job_cancel` (or the call's own timeout, 30 minutes unless +the tool sets a shorter one, as `object_arrange` does) asks the job to stop, but `Worker::cancel()` does not +wait, so the call keeps the operation until the worker is idle and then fails as cancelled. `job_cancel` stops only a job an MCP call claimed. The worker doesn't record who queued a job, so a job a person starts while a call is still between its closures, after one that found the worker idle, is claimed by that call too: its reply then waits for that job. The window is the call's own length, a @@ -383,7 +386,7 @@ no call holds, a person's (typing in the Text gizmo) or one not yet claimed, cha arrives (operations only, since the worker lives on the UI thread) and again in each of its UI closures, where operations start, so a call admitted just before an operation began still can't change the project under it. Inline tools, recover tools answering the topmost modal and -`allowed_during_operation` tools (`cancel_job`) still run; the GUI input tools apply the same check once +`allowed_during_operation` tools (`job_cancel`) still run; the GUI input tools apply the same check once their target is outside the topmost modal. **Identity.** An operation must never take another's completion for its own. `Plater` numbers @@ -426,17 +429,17 @@ flush and prime tower grams. The silent-mode time and extruder changes, which th out, come from the result's estimates, and only when the printer has them. The summary is read in the poll closure that decides the outcome, since a UI call of its own would wait behind the preview's loading of the new result; the serializer's one pass over the moves is short next to -that. `cancel_job` also drops a pending automatic reslice: it stops the delay timer, +that. `job_cancel` also drops a pending automatic reslice: it stops the delay timer, whose callback wx then never delivers, and moves on a generation that a zero-delay reslice already queued with `CallAfter` checks. An export is numbered in `export_seq` once scheduled, so an unchanged number means it never started; otherwise its `ExportRecord` ends `ok`, `failed`, -`cancelled` or `superseded`. A G-code export with a path is refused while slicing runs, and -`run_action export_gcode` needs a path: without one it would ask in a native file dialog that MCP -can't fill in. The +`cancelled` or `superseded`. A G-code export with a path is refused while slicing runs. Without a +path, `project_export {format: "gcode"}` is its tile's call and asks in a native file dialog, which +a caller answers only with a `dialog_auto_answer` rule registered first. The decision logic is in `Operations/RunStatus`, which uses neither wx nor `Plater` (see The operations layer). -**Idle.** `wait {for: "idle"}` holds when no modal is open, nothing slices (`Plater::is_slicing_any()`: +**Idle.** `app_wait {for: "idle"}` holds when no modal is open, nothing slices (`Plater::is_slicing_any()`: the background process, Slice All, a scheduled background update or a pending automatic reslice) and the UI job worker (arrange, orient) is idle, and no gizmo on any canvas reports `GLGizmoBase::is_busy()`: work a gizmo started in the background whose result it has yet to show @@ -448,20 +451,22 @@ the UI thread. ## The operations layer -Three interfaces ask the app to do things by name: the Speed Dial's commands, the MCP tools, and the +Three interfaces ask the app to do things by name: the Speed Dial's tiles, the MCP commands, and the plugin API (`orca.host`). What one of them does is often what another does too: exporting G-code is a -command, a tool, and a command run through `run_action`. The checks, the refusal and its wording, the -undo snapshot and the order of the owner calls of such a function are in one place, +tile, a call of `project_export` and the tile run through `action_run`. The checks, the refusal and its +wording, the undo snapshot and the order of the owner calls of such a function are in one place, `src/slic3r/GUI/Operations/` (namespace `Slic3r::GUI::Ops`), and the three interfaces convert their -arguments and results around it. A command keeps its key and arguments, a tool its name, arguments and -reply, and a binding its signature; what they share is the rule. +arguments and results around it. Where a dialog does the same work (the Clone dialog, the Preferences +dialog, the Plugins window, the Printer Selection and System Filaments dialogs, the AMS sync dialog, Fix +Model), the dialog calls the operation too, so a command and the dialog cannot differ. A command keeps +its key, arguments and reply, and a binding its signature; what they share is the rule. **What is an operation.** An effect, or a rule about one owner's state that its own widgets also apply, is a public method of the owner (`Plater`, `Sidebar`, `Tab`, `GCodeViewer`) or a function in -its header: `Tab::can_delete_preset()` is what the tab's Delete and the `delete_preset` tool both ask, -and `locked_save_location()` what the Save preset dialog and `save_preset` both follow. What an +its header: `Tab::can_delete_preset()` is what the tab's Delete and the `preset_delete` command both +ask, and `locked_save_location()` what the Save preset dialog and `preset_save` both follow. What an automation caller invokes by name is an operation, for every function that more than one interface -reaches and for every function added from now on. A caller calls an operation to change something +reaches and for every function a new command adds. A caller calls an operation to change something and an owner to read. A tool that changes something through a function with one entry point is left as it is: nothing can drift there until a second entry point appears, and then the rule applies to it. @@ -479,14 +484,14 @@ the result or a `Refusal`: The palette shows `translated()`. A tool and a Python exception carry `english()`, and a tool's error also carries the code (`code`) and puts the names under the key it has always used (`similar`, -`presets`). `run_action` replies with the English text and the code too, where the command ran an +`presets`). `action_run` replies with the English text and the code too, where the command ran an operation, so a command's refusal reads the same through every route. A caller may add a hint after -the text (the `export` tool's `wait {for:"idle"}`), never a second wording. A check of an argument's +the text (the `project_export` tool's `app_wait {for:"idle"}`), never a second wording. A check of an argument's form (a path that does not resolve, an argument its schema refuses, an extension the tool does not write) stays with the caller that owns the argument. **Undo.** An operation takes the undo snapshot its function takes, once, after its checks pass. A -tool may still make one call one undo step with `Plater::SingleSnapshot`, as `set_settings` does; +tool may still make one call one undo step with `Plater::SingleSnapshot`, as `settings_set` does; that is the tool's own contract. **Threads and waits.** An operation runs on the UI thread and returns at once. It does not marshal @@ -505,8 +510,8 @@ open a dialog of its own (a STEP file's mesh options, the modified-presets quest `Plater::load_project()`, the Transfer-or-discard prompt of `Tab::select_preset()` when no answer is given). A call that stops there behaves as any call behind a dialog: a tool replies `blocked_by_dialog`, and a plugin's call waits for the person. A path that asks a person keeps its -owner method: with no arguments, and for `load_project` and `new_project` with or without them, a -command is the asking path and calls the owner. +owner method: a command's person's form (a call with exactly one of its tiles' arguments) is the asking +path and calls the owner. **The plugin API.** Where an operation exists for what a binding does, the binding calls it and takes its refusals, raised as the exception type the binding has always raised for that case. Its @@ -523,21 +528,34 @@ nothing from it, and `plugin/` includes nothing from `GUI/Mcp`. | File | Operations | Reached by | |---|---|---| -| `ExportOps` | `start_gcode_export`, `gcode_export_state` | command `export_gcode`, tool `export`, `run_action` | -| | `export_sliced_3mf`, `export_model_3mf`, `export_stl` | commands `export_sliced_file`, `export_all_sliced_file`, `export_3mf`, `export_stl`; tool `export` | -| | `send_gcode_to_host` | command `send_gcode` | -| `ProjectOps` | `import_models` | command `import_file`, tool `open_files` | -| | `open_project`, `new_project` | tools `open_files`, `new_project` | -| | `save_project_as` | command `save_project_as`, tool `save_project` | -| | `set_instance_count` | command `obj_set_instances` | -| `PlateOps` | `select_plate` | command `plate_goto`; the exports of `ExportOps` that write their file at once, for a plate their caller names | -| | `set_plate_locked` | command `plate_toggle_lock`, tool `set_settings` (the plate's lock icon calls the same owner effect) | -| | `start_arrange` | command `obj_arrange`, tool `arrange` | -| | `start_slice` | commands `slice_and_preview`, `slice_all`; tool `slice` | -| | `show_layer_range` | command `go_to_layer`, tool `set_view` | -| `PresetOps` | `resolve_preset`, `select_preset` | tool `select_preset`, the plugin API's `begin_update(preset_name)` | -| | `assign_filament_preset` | tool `select_preset`, the plugin API's `begin_update(slot_number, preset_name)` (the sidebar's selector calls the same owner effect, `Sidebar::select_filament_preset()`) | -| | `import_presets` | command `import_configs` | +| `ExportOps` | `start_gcode_export`, `gcode_export_state` | `project_export` with `format` gcode | +| | `export_sliced_3mf`, `export_model_3mf`, `export_stl`, `export_toolpaths_obj` | `project_export` with the other formats | +| | `send_gcode_to_host` | `printer_send` | +| `ProjectOps` | `import_models`, `open_project`, `new_project`, `save_project_as` | `project_import`, `project_open`, `project_new`, `project_save` | +| | `set_instance_count` | `object_set_instances` | +| `ObjectOps` | `add_primitive`, `delete_objects`, `rename_object`, `separate_instances`, `split_object`, `assemble_objects` | `object_add_primitive`, `object_delete`, `object_rename` (and `object_add_primitive`'s `name`), `object_separate_instances`, `object_split`, `object_assemble` | +| | `order_objects`, `reorder_objects` | `object_order` with `by`, and with `order`, which makes the drops `ObjectList::OnDrop()` makes for a drag in the object list | +| | `drop_objects`, `mirror_objects`, `center_objects`, `scale_to_fit`, `orient_objects` | `object_drop`, `object_mirror`, `object_center`, `object_scale_to_fit`, `object_auto_orient` | +| | `set_objects_printable`, `set_objects_auto_drop` | `object_set_printable` (the object list's Printable cell sets the flag through the same `set_printable()`); `object_set_auto_drop` and the 3D view's Auto Drop | +| | `fix_objects`, `clone_objects`, `reload_parts` | `object_fix` and Fix Model; `object_clone` and the Clone dialog; `object_reload_from_disk` | +| | `change_part_type`, `replace_part` | `part_change_type`, `part_replace` | +| `PlateOps` | `select_plate` | `plate_select`, `plate_rename`; the exports of `ExportOps` that write their file at once, for a plate their caller names | +| | `set_plate_locked`, `delete_plate`, `duplicate_plate`, `rename_plate` | `plate_lock`, `plate_delete`, `plate_duplicate`, `plate_rename` | +| | `start_arrange` | `object_arrange` | +| | `start_slice` | `plate_slice` | +| | `show_layer_range` | `view_set`'s layer arguments and its Go to layer tile | +| | `show_prepare_view`, `shown_prepare_canvas` | the commands that act on the Prepare view's selection: its canvas, shown and with its scene loaded | +| `PresetOps` | `resolve_preset`, `select_preset` | `preset_select`, the plugin API's `begin_update(preset_name)` | +| | `assign_filament_preset` | `preset_select`, the plugin API's `begin_update(slot_number, preset_name)` (the sidebar's selector calls the same owner effect, `Sidebar::select_filament_preset()`) | +| | `import_presets`, `sync_presets` | `preset_import`, `preset_sync` | +| | `add_filament_slot`, `delete_filament_slot`, `add_mixed_filament` | `filament_add`, `filament_delete`, `filament_add_mixed` | +| | `sync_filaments_from_ams` | `filament_sync_ams`; the AMS sync dialog applies its choice through the same `apply_ams_sync()` | +| `InstallOps` | `printer_models`, `install_printers`, `uninstall_printers` | `printer_list_models`, `printer_install`, `printer_uninstall` | +| | `install_filaments`, `uninstall_filaments` | `filament_install`, `filament_uninstall` | +| | `printer_profile_data`, `apply_install_set` | the Printer Selection and System Filaments dialogs, whose Confirm applies the installed set as the commands do | +| `PreferenceOps` | `preferences`, `set_preferences`, `apply_preference` | the table `preferences_get` lists and the Preferences dialog builds its rows from; `preferences_set`; each control's effect, run by the dialog and by `preferences_set` | +| `PluginOps` | `set_plugin_enabled`, `uninstall_plugin`, `reload_plugin` | `plugin_enable`, `plugin_uninstall`, `plugin_reload`, and the Plugins window's switches and row menu | +| | `start_plugin_refresh` | `plugin_refresh` and Refresh Plugins | | `RunStatus` | `slice_status`, `export_status`, `classify_plates` | the status rules of a slice and an export, free of wx and `Plater` | **What every route gets.** An operation holds what every route of its function does, so these are @@ -560,21 +578,21 @@ the same whichever interface asks: A check only one route makes stays with that route, as a step of its own before the call: -- The `arrange` tool refuses a locked or an empty plate it was given by index; the `obj_arrange` - command names no plate. Fill bed is the tool's alone. +- `object_arrange` refuses a locked or an empty plate it was given by index; its tile names no plate. + Fill bed is a call's alone. - The plugin API refuses a filament slot whose preset is empty or does not resolve, since its - transaction edits that preset; the `select_preset` tool only assigns one. + transaction edits that preset; `preset_select` only assigns one. **Keeping it so.** Two checks, neither of which reads what a handler does: -- `NativeCommand` has a field naming the operations a command reaches (`reaching()` where a tool is - registered, the `reaches` table of the Speed Dial's commands). It is in no listing. A unit test - (`test_operations`) walks `NativeCommands::instance()` and requires every listed command that is not - read-only and every palette command that takes arguments (one with a tile that is not listed, whose - schema has an argument beside `silent`) to name an operation or to be on the test's exception list, - with the reason: it runs what its arguments name, it drives the GUI, it changes the session and not the - project, its function has one entry point, it is an asking path, or it calls the undo and redo of a - history (`undo`, `redo`). A new tool or command that takes arguments has to say which it is. +- `NativeCommand::operations` names the operations a command reaches (`reaching()` where it is + registered), and the command reference lists them. A unit test (`test_operations`) walks + `NativeCommands::instance()` and requires every command outside the Design tab that is not read-only + to name an operation or to be on the test's one exception list (`kExceptions`), with the reason: it + runs what its arguments name, it drives the GUI, it changes the session and not the project, its + function has one entry point, it runs its menu row's function (which adds a shape, opens a window or + changes a setting of the app), or it calls the undo and redo of a history (`undo`, `redo`). An entry + that names operations fails the test, so a new command has to say which it is. - `scripts/check_operation_calls.py`, run by the `Check operation calls` workflow, bans in the callers' files (`NativeCommands.cpp`, the `McpTools*.cpp` files but the Design commands' `McpToolsCad.cpp`, `plugin/host/*.cpp`) the owner methods the operations call, by name. A banned call that stays, because @@ -587,86 +605,144 @@ getters. That is for review: a caller's handler converts, calls, and shapes the ## Tool catalog -A tool's name says what it does in the words the GUI uses, so a person's request and an agent's search for a -tool meet: `set_height_ranges` edits what the object list calls height ranges (Height Range Modifier), -`set_variable_layer_height` runs the Variable layer height panel, and `run_replay` runs what Action Replay calls -a replay file. Where the GUI has no name for the thing, the name is a plain verb and noun (`list_widgets`, -`answer_dialog`), and a word the GUI uses for something else is avoided: `run_script` would read as the Run -Script panel, which runs Python. +A command's name is its place, then its verb, every word in full: `object_delete`, `plate_add`, +`preset_select`, as the Design tab has `body_delete`. The place is the thing the command acts on, in the +singular and in the GUI's word (`settings` and `preferences` are the GUI's words as they stand); a read is +its place, then what it returns (`app_state`, `plate_slice_stats`). `undo` and `redo` alone have no place: +they are shared with the Design tab and act on the tab shown. The verb and what follows it are the GUI's +words too, so a person's request and an agent's search meet: `object_set_height_ranges` edits what the +object list calls height ranges (Height Range Modifier), `object_set_variable_layer_height` runs the +Variable layer height panel, and `replay_run` runs what Action Replay calls a replay file. Where the GUI has +no name for the thing, the words are plain (`widget_list`, `dialog_answer`), and a word the GUI uses for +something else is avoided: a `script` command runs Python, as the Run Script panel does. -What each tool does, the arguments it takes and what it replies are in its description, which `tools/list` -gives a client and the command reference `tests/data/command_catalog.json` holds for a reader (see Making a -feature reachable). By area, the tools are: +One job has one command. A menu row and the tool that does its job are one command, and the row is a +tile of it (see Speed Dial catalog); one argument picks the variant (`format`, `shape`, `axis`, `type`, +`mode`, `window`, `page`) where the GUI has a row for each. What each command does, the arguments it takes +and what it replies are in its description, which `tools/list` gives a client and the command reference +`tests/data/command_catalog.json` holds for a reader (see Making a feature reachable). A command's group is +the heading of its place, and `tools/list` gives the places in this order: -**App.** `get_app_state`, `wait` and `get_log`. +**Tools and actions.** `tool_search`, `tool_call`, `action_search` and `action_run`. -**Speed Dial.** `search_actions` and `run_action`. +**The app.** `app_state`, `app_wait`, `app_log`, `undo`, `redo`, `app_open_web_page`, +`app_check_for_updates`, `app_show_config_folder`, `app_benchmark_3d_scene`, `preferences_get`, +`preferences_set` and `job_cancel`. -**Project.** `open_files`, `new_project`, `generate_calibration_test`, `save_project` and `export`. +**The project.** `project_open`, `project_import`, `project_new`, `project_save`, `project_export`, +`project_get_settings` and `project_set_settings`. -**Presets.** `list_presets`, `select_preset`, `get_settings`, `set_settings`, `save_preset` and `delete_preset`. +**Objects.** `object_list`, `object_select`, `object_transform`, `object_add_primitive`, +`object_add_handy_model`, `object_add_text`, `object_add_svg`, `object_delete`, `object_rename`, +`object_set_instances`, `object_separate_instances`, `object_split`, `object_assemble`, `object_order`, +`object_drop`, `object_mirror`, `object_center`, `object_scale_to_fit`, `object_auto_orient`, +`object_set_printable`, `object_set_auto_drop`, `object_fix`, `object_clone`, `object_reload_from_disk`, +`object_arrange`, `object_set_height_ranges` and `object_set_variable_layer_height`. -**Objects.** `list_objects`, `list_plates`, `select_objects`, `transform`, `add_part`, `arrange`, -`set_height_ranges` and `set_variable_layer_height`. +**Parts.** `part_add`, `part_change_type` and `part_replace`. -**Slice.** `slice`, `cancel_job` and `set_custom_gcode_at_layer`. +**Plates.** `calibration_generate_test`, `plate_get_settings`, `plate_set_settings`, `plate_list`, +`plate_add`, `plate_delete`, `plate_duplicate`, `plate_rename`, `plate_lock`, `plate_select`, `plate_slice`, +`plate_set_custom_gcode` and `plate_slice_stats`. -**View.** `set_view`, `screenshot` and `get_slice_stats`. +**Presets and settings.** `preset_list`, `preset_select`, `preset_save`, `preset_delete`, `settings_list`, +`settings_get`, `settings_set`, `preset_import`, `preset_export`, `preset_sync`, `preset_migrate_filaments`, +`settings_set_mode` and `settings_toggle_developer_mode`. -**Recording.** `start_recording`, `stop_recording` and `encode_recording`. +**Filaments.** `filament_add`, `filament_delete`, `filament_add_mixed`, `filament_sync_ams`, +`filament_install` and `filament_uninstall`. -**GUI.** `list_windows`, `set_window`, `list_widgets`, `click`, `set_widget_value`, `press_keys`, -`mouse_gesture`, `pick_gizmo_file`, `answer_dialog`, `auto_answer_dialogs` and `run_javascript`. +**Printers and prints.** `printer_send`, `printer_list_models`, `printer_install` and `printer_uninstall`. -**Replays and scripts.** `run_replay`, `export_replay`, `run_script` and `search_python_api`. +**Plugins.** `plugin_list`, `plugin_install_local`, `plugin_enable`, `plugin_reload`, `plugin_uninstall` and +`plugin_refresh`. -**API.** `search_tools` and `call_tool`. +**View and windows.** `view_set`, `window_open`, `window_list` and `window_set`. -The tools are commands of the process's command catalog (`CommandCatalog`, `NativeCommands::instance()`; see -Speed Dial catalog), beside the Speed Dial's: a tool is a `NativeCommand` with `listed` set, which -`tools/list` shows in the order the tools were added. Startup builds the catalog, with no automation runtime: -`register_all_commands()` adds the Speed Dial's commands, then each tool family in a fixed order of calls -(app, api, project, config, scene, layer, view, replay, python, record, action, ui), each through its -`register_*_tools(catalog)`, and between record and action the Design tab's commands, which no listing shows, -in a CAD build with the CAD feature on (`register_cad_commands()`; see Design tab), so `tools/list` starts -with the app's state, the search and the generic call, and ends with the tools that drive the GUI. A tool is -made with `inspect_tool()`, `mutate_tool()`, `record_tool()` or `recover_input_tool()`, which take its group -first and build it through `long_command()` with its function unchanged, so it runs where its call does. A -function reaches the automation runtime through its call's context, `ToolContext::runtime()`: the core gives the -runtime that owns it (`McpCore::set_runtime()`), a person's pick starts the runtime without the endpoint, and a core -built on its own, as in a unit test, refuses, which ends the call in an error. Every key is unique across the -catalog, tools and Speed Dial commands together. +**Recordings, replays and scripts.** `window_screenshot`, `window_save_screenshot`, `replay_run`, +`replay_export`, `script_run`, `script_search_api`, `script_toggle_panel`, `recording_start`, +`recording_stop` and `recording_encode`. -Every command is called by its key: `tools/call`, `call_tool`, a replay step and a script's call reach a -Speed Dial command (`obj_arrange`, `load_project`) as they reach a tool, run and journal it as its own -call, and the Action Replay window describes such a step as `run_action` of its tile -(`describe_step()`). `tools/list` and the editors' tool list (`editor_tool_catalog()`) read the listed -commands only, in the order they were added, so they show the typed tools. `search_tools` reads every +**Driving the GUI.** `widget_list`, `widget_click`, `widget_set_value`, `keyboard_press`, `mouse_gesture`, +`gizmo_pick_file`, `dialog_answer`, `dialog_auto_answer` and `webview_run_javascript`. + +Every command that runs from its arguments is `listed`, so `tools/list` shows it. Three are not: the menu +rows that take no arguments, `window_save_screenshot`, `script_toggle_panel` and +`settings_toggle_developer_mode`, which `tool_search` finds and `tool_call` runs, as it does the Design +tab's commands, which no listing shows. A screenshot is a recording's still, so the two screenshot commands +are grouped with the recordings, not with the windows; `calibration_generate_test`, which builds a test +plate's project, is under Plates, and the two preferences commands are under The app, since a preference is +kept by the app and not in a preset or a project. + +The commands are the process's command catalog (`CommandCatalog`, `NativeCommands::instance()`). Startup +builds it, with no automation runtime: `register_all_commands()` gathers each family of commands in a fixed +order of calls (app, api, project, config, preference, install, scene, layer, view, plugin, replay, python, +record, action, ui), each through its `register_*_tools(catalog)` in its `McpTools*.cpp`, gives each the +group of its place (`NativeCommands::place_heading()`, which reads the name's first word; a name with no +place throws), and sorts them stably by place: `tool_search`, `tool_call` and `app_state` first, as what an +agent starts with, then the places in the order above, each place's commands in their families' order. The +Design tab's commands come before Driving the GUI, in a CAD build with the CAD feature on +(`register_cad_commands()`; see Design tab), and the source of the operations plugins offer is added beside +them. A command is made with `inspect_tool()`, `mutate_tool()`, `record_tool()` or `recover_input_tool()`, +which build it through `long_command()` with its function unchanged, so it runs where its call does, or, for +one made from menu rows, with `row_command()`, which builds it through `ui_command()` with the rows as its +tiles; a row's function is in namespace `Rows` (`NativeCommandRows.hpp`), beside the helpers the rows share +in `NativeCommands.cpp`. `reaching()` names the operations a command reaches. A function reaches the +automation runtime through its call's context, `ToolContext::runtime()`: the core gives the runtime that +owns it (`McpCore::set_runtime()`), a person's pick starts the runtime without the endpoint, and a core +built on its own, as in a unit test, refuses, which ends the call in an error. Every key is unique across +the catalog. + +Every command is called by its key: `tools/call`, `tool_call`, a replay step and a script's call reach every +command alike and journal it as its own call. `tools/list` and the editors' tool list +(`editor_tool_catalog()`) read the listed commands, in the catalog's order. `tool_search` reads every command, then the plugin operations of the catalog's source (`search_commands()`; see Plugins and the -tools), so its one inventory finds a Speed Dial command's key as it finds a tool's. +tools), so its one inventory finds an unlisted row's key or a Design command's as it finds a listed one's. -Four commands are both a tool and a tile: `new_project`, `save_project`, `start_recording` and -`stop_recording`. Each is registered once, in its tool's family, through `with_person_form()`, which gives the -tool the tile's title, icon and group (`Commands`) and its schema `silent` (`Mcp::with_silent()`). Called with -no arguments, each does what a person's pick does: New Project asks about unsaved changes, Save Project -saves to the project's file or asks for one, Start Recording opens its dialog, and Stop Recording stops the -recording without waiting for its file and shows the person where it went; an agent's call of that form -replies `blocked_by_dialog` while a dialog asks. New Project's and Save Project's tools are mutate calls, -so their form is refused where any mutate call is. The recording tools run behind dialogs, but Start -Recording's form, which opens a dialog, is refused while a modal dialog is open or another call's nested -loop runs (`UiInvoker::require_mutate()`); Stop Recording's form, which opens nothing, runs where the tool -does. With arguments, or `silent: true`, it is the tool, which asks nothing, and the journal keeps -`silent`, so a replay of it asks nothing either. `save_project`'s path is required once any argument is -given, under `then`; `start_recording` given arguments records for up to an hour unless `max_seconds` +A command's tiles are its menu rows, which a person picks in the Speed Dial (see Speed Dial catalog). A +call whose arguments are exactly those of one of its tiles, a command's own tile being `{}`, is the person's +form: it does what a person's pick of that tile does, so it may ask in a dialog, which an agent's call +replies as `blocked_by_dialog`, or act on the selection. Any other call runs from its arguments and opens +nothing, and where a command's own function needs nothing more than a tile gives, `silent: true` +(`Mcp::with_silent()`) runs it from its arguments without asking. So `project_export {format: "gcode"}` +asks for the file and `project_export {format: "gcode", path}` writes it; `object_add_primitive {shape: +"cube"}` asks for the size and `{shape: "cube", silent: true}` takes the built-in one. The journal keeps +`silent`, so a replay of such a call asks nothing either. A call of the person's form is refused while a +modal dialog is open or another call's nested loop runs (`UiInvoker::require_mutate()`), also for a command +whose guard lets it run behind dialogs, unless that form opens nothing: `recording_stop {}` stops the +recording wherever the command runs. `project_save`'s `path` is required in every call that is not one of +its tiles', under `then`; `recording_start` given arguments records for up to an hour unless `max_seconds` says otherwise, and its reply says the limit it runs under. -Each tool has a group (`NativeCommand::group`), the way it acts: `core` (the session, recovery from -dialogs, replays and Python), `api` (project data by index and name, JSON in and out, and the operations -plugins offer) or `ui` (the GUI itself); the four tools that are also tiles are in their tile's group, -`Commands`. Every caller reaches every tool, and the group only filters: `search_tools {group}` keeps the -commands and operations of one group, the Speed Dial's sections (`Object`, `View` and the rest) among the -groups, compared in any case, and its matches and `{tool}` replies say each one's group. A group no command -has is refused as an unknown name is, "Unknown group: …", naming the groups there are (`groups`). +Two things have no silent form, so the caller answers their dialogs. `preset_export` always opens the +Export Preset Bundle dialog, on the folder `path` names when one is given. And the questions the app's +loader asks while it reads a file (a STEP file's mesh options, the AMF and CAD 3MF options, the names +clean-up, inches or metres, one object of several parts) open for `project_import`, `part_add` and +`part_replace` with a path as they do for a person: those calls open no file dialog, and where the loader +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 +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 +selected is the object, and an instance or a part stands for its object only where the command says so. +Nothing selected is refused ("Nothing is selected: name the objects, or select them first.", +`nothing_selected`), so is a selection of a kind the command does not take (`wrong_selection`), and a +command of one target refuses a selection of several (`one_object_only`). Where a row acted on the object +list's own rows, a call that names no targets reads those rows too (`object_assemble`, `part_change_type`, +`object_split`, and `object_delete`'s person's form), since the list and the 3D selection disagree when +every instance, or every part, of an object is selected. The reply names what the command acted on +(`targets_reply()`: `objects`, `instances`, `parts`, each with its index, id and name), so a caller that gave +no target learns what the selection was, and a command that makes, removes or renumbers things replies with +their indices as they are afterwards. `object_delete` names what it deleted with the indices they had, and +under `kept` what it was asked for and did not delete, with its indices afterwards: its person's form leaves +the object list to delete, which goes from the last item and stops at one it refuses (an object's last solid +part) or asks about (a cut object), and `Ops::deleted_targets()` finds what went by identity, since the delete +moved the indices. A plate command with no `plate` acts on the current plate, and its +reply names it. Each tool also has an access label, which `tools/list` sends as MCP's annotations. Clients act on it differently: Codex asks a person before every call of a destructive tool (unless it is also read-only), @@ -675,47 +751,55 @@ permission rules whatever the label says, runs read-only calls in parallel and r So the label marks what a call does by its nature, not everything a call could reach, which would put a confirmation on calls an agent makes all the time. -`read_only`: the tool changes nothing in the app or the project. `screenshot` is read-only, since its -PNG replaces no file without `overwrite`; `export_replay`, which can clear the journal, is not. -`destructive`: every call deletes what a person made, with no undo: `delete_preset`, which takes the -preset's file and its cloud copy. A tool that can lose work only when an argument asks for it is not: -`new_project`, `generate_calibration_test` and `open_files` drop unsaved changes only with `discard_changes`, and an -output replaces a file only with `overwrite: true`. Nor is `encode_recording`, which deletes only a recording this -session made, once its MP4 has replaced it. Nor is a tool that runs what its arguments name: the input tools (`click`, `set_widget_value`, `press_keys`, `mouse_gesture`), which press -whatever is on screen, a Delete button included, `run_action`, `call_tool`, `run_replay` and -`run_script`. What they run may be destructive, but the client sees both in the arguments, and the -label would ask on every call. `open_world` (`openWorldHint`): the tool can reach outside OrcaSlicer, to a -printer, the cloud account or the network: `save_preset` (user presets sync), `delete_preset` (the cloud -copy), `run_javascript` (the page's own reach), and through what they run `run_action` (`send_gcode`, -`sync_presets`), `call_tool`, `run_replay` and `run_script`, 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. +`read_only`: the command changes nothing in the app or the project. `window_screenshot` is read-only, +since its PNG replaces no file without `overwrite`; `replay_export`, which can clear the journal, is not. +`destructive`: every call deletes what a person made, with no undo: `preset_delete`, which takes the +preset's file and its cloud copy, and `plugin_uninstall`, which removes the plugin's files. A command that +can lose work only when an argument asks for it is not: `project_new`, `calibration_generate_test` and +`project_open` drop unsaved changes only with `discard_changes`, and an output replaces a file only with +`overwrite: true`. Nor is `recording_encode`, which deletes only a recording this session made, once its +MP4 has replaced it, nor a command whose deletion has undo (`object_delete`, `plate_delete`). Nor is a +command that runs what its arguments name: the input commands (`widget_click`, `widget_set_value`, +`keyboard_press`, `mouse_gesture`), which press whatever is on screen, a Delete button included, +`action_run`, `tool_call`, `replay_run` and `script_run`. What they run may be destructive, but the client +sees both in the arguments, and the label would ask on every call. A command made from menu rows is neither +read-only nor destructive. `open_world` (`openWorldHint`): the command can reach outside OrcaSlicer, to a +printer, the cloud account or the network: `preset_save` (user presets sync), `preset_delete` (the cloud +copy), `webview_run_javascript` (the page's own reach); of the commands made from rows `printer_send`, +`preset_sync`, `filament_sync_ams`, `app_check_for_updates`, `app_open_web_page` and `plugin_refresh`; +`plugin_enable` and `plugin_reload`, which run a plugin's code and download a cloud plugin, and +`plugin_uninstall`, whose Unsubscribe reaches the account; 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 tools that take an object index (`set_settings` object and part scopes, `transform`, `add_part`, -`set_height_ranges`, `set_variable_layer_height`) also take an optional `object_id`, and where they take a -part index a `part_id`; `select_objects` takes `object_ids`, `instance_object_ids` and `part_ids`, one per -entry of `objects`, `instances` and `parts`: the `ObjectID` values `list_objects` 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. `list_objects`' description says what the ids are for -and names the tools that take them, so each property only points back at it. Ids are allocated per -process, so a tool that takes them names them in its `id_args`, which `with_expected_ids()` reads from its -schema where the tool is registered, and the core gives the journal its calls without them -(`without_expected_ids()`, which looks the command up in the catalog), through `call_tool` and inline -`run_replay` steps too, and a replay addresses by index; a `run_script` step's code and `args`, and a plugin +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. Descriptions keep one order: what the tool does, the arguments that change it, `Reply:` with the -fields it has, then edge cases; a long one puts each case on a line of its own (the scopes of -`get_settings` and `set_settings`, `click`'s web pages). What several tools share is written once, -since every session loads the whole tool list: the locator grammar in `list_widgets`'s description, +fields it has, then edge cases; a long one puts each case on a line of its own (the types and targets +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 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` and the like), `canvas` a 3D view, `path` the file a tool is about, and `save_path` where a capture -writes its file beside its reply. So the point `set_view`'s camera looks at is `look_at`, which +writes its file beside its reply. So the point `view_set`'s camera looks at is `look_at`, which `camera_state` reads back under the same name, and a drag's intermediate points are `waypoints`. -The main window is `main` wherever a tool names it, as `list_windows` calls its kind; `window` is +The main window is `main` wherever a tool names it, as `window_list` calls its kind; `window` is another kind there. A part of an object is `part` in arguments and replies, the Objects panel's word for what the model calls a volume, which leaves `mesh_volume` and `scaled_volume` to mean cubic millimetres. A tool that takes one plate calls it `plate`, an index; one that also takes @@ -725,25 +809,26 @@ any of them. Where a tool takes two unlike things of one word, each says whose it is: `discard_changes` drops the project's unsaved changes, `preset_changes` keeps, transfers or discards the presets'. -An agent calls into two catalogs by name: the commands (the typed tools, the Speed Dial's commands, the -Design tab's and the operations plugins offer) and the Speed Dial's actions, which `run_action` runs. -`search_tools {query}` finds a name in either, and a command runs by its key through `tools/call` and -`call_tool`, with `search_tools` giving the schema of one `tools/list` does not show. Its description +An agent calls into two catalogs by name: the commands (those `tools/list` shows, the three menu rows it +does not, the Design tab's and the operations plugins offer) and the Speed Dial's actions, which +`action_run` runs. +`tool_search {query}` finds a name in either, and a command runs by its key through `tools/call` and +`tool_call`, with `tool_search` giving the schema of one `tools/list` does not show. Its description names the Design commands while the catalog holds them (see Design tab), so an agent knows of them before it searches. A name that misses is answered with the closest names of the catalog asked and nothing else, unless the catalog leaves that command out (`CommandCatalog::leave_out()`): then it says why. A catalog built with the CAD feature off leaves out the Design commands, and says that the feature was off when OrcaSlicer started and how a person turns it on. `CommandCatalog::unknown_command()` builds the error for every lookup of a command that -misses: `tools/call`, `call_tool`, `search_tools {tool}`, a replay step and a plugin's or script's call. -`run_action` gives the closest action ids, and says that `search_actions` finds an action and -`search_tools` a command, since the name may be a command's that has no tile; a tile's key runs its -command. For a Design tile that is not shown it says when the tile is there instead, and that `call_tool` +misses: `tools/call`, `tool_call`, `tool_search {tool}`, a replay step and a plugin's or script's call. +`action_run` gives the closest action ids, and says that `action_search` finds an action and +`tool_search` a command, since the name may be a command's that has no tile; a tile's key runs its +command. For a Design tile that is not shown it says when the tile is there instead, and that `tool_call` runs its command from any tab, or, when the catalog leaves its command out, why. Each tool family lives in its own `McpTools*.cpp`. List tools take `limit` and `offset` and reply -`{items, offset, total}` (`page()`; `list_objects`, a tree, has `plates` and `outside` in place of -`items`), with `next_offset` while more remain: `search_actions` too. The server instructions give that +`{items, offset, total}` (`page()`; `object_list`, a tree, has `plates` and `outside` in place of +`items`), with `next_offset` while more remain: `action_search` too. The server instructions give that shape once, rather than every description, and each `limit` states its default. `McpPaths.hpp` requires absolute paths, since a relative one would resolve against `/log`, the GUI's working directory; an output's directory must exist, and an existing file is replaced only with @@ -751,15 +836,15 @@ directory; an output's directory must exist, and an existing file is replaced on `path_from_utf8()` and `path_to_utf8()` convert, through wide strings on Windows, where boost's narrow conversion would use the ANSI code page. -### list_objects +### object_list -`list_objects` lays the model out as the Objects panel does: `plates`, each `{index, name, objects}` +`object_list` lays the model out as the Objects panel does: `plates`, each `{index, name, objects}` with the objects that have an instance on it, then `outside`, the objects with an instance on no plate. `objects_by_plate()` builds it from `object_info()` and `volume_info()` (McpToolsScene.cpp, libslic3r only, so unit tests build them from a `Model`) and a callback that says which plate an instance is on. The handler's is `instance_plate()`: the plate registry's answer or, for an instance the registry does not hold, as Fill bed leaves its new ones, the first plate the instance stands on, -so the copies that fill a plate are listed on it. `list_plates` counts a plate's objects the same +so the copies that fill a plate are listed on it. `plate_list` counts a plate's objects the same way. On request the handler adds each instance's canvas rectangle. The reply differs from the panel in two places, both so that a row says all an agent needs to act @@ -787,22 +872,31 @@ column: an object's `extruder`, 1 when unset; a part's own, else its object's; a it sets one, since a modifier without one leaves the filament of what it covers alone; none for negative parts, support blockers and enforcers, and precise seams. A precise seam has `type: "precise_seam"` and its `subtype` (`center`, `left`, `right`, `enforced`, `blocked`, `neutral`, the 3MF -names without their prefix). The `transform` reply on a part carries the same entry as `part_info`. An -object with height range modifiers lists them as `layer_config_ranges` (`layer_config_ranges_json()`), -each with its whole config serialized as `get_settings` serializes values, so a range always shows -its `layer_height` and `extruder`, and the list can be handed back to `set_height_ranges` unchanged. An -object whose `layer_height_profile` has more than a flat bottom-to-top pair, which the object list marks +names without their prefix). The `object_transform` reply on a part carries the same entry as +`part_info`. An object with height range modifiers lists them as `layer_config_ranges` +(`layer_config_ranges_json()`), each `{min_z, max_z, values}` with its whole config serialized as +`settings_get` serializes values, so a range always shows its `layer_height` and `extruder`; its `min_z` +and `max_z` are what `object_set_height_ranges` keeps a range by and what the target `height_range` of +the settings commands names it by. An object whose `layer_height_profile` has more than a flat bottom-to-top +pair, which the object list marks as a variable layer height, reports it as `layer_height_profile: {points, min_height, max_height}` (`layer_height_profile_json()`): the number of (z, height) points and the extreme heights, to 0.001 mm. The points themselves stay in the 3MF's `layer_heights_profile.txt`. -### transform +An object also has `auto_drop`, `brim_ears` (how many), `overrides`, the keys of the settings it sets +itself (`settings_get` with the target `object` reads them), and `mesh_errors`, what the object list's +warning icon reads (`Ops::mesh_errors()`): `open_edges`, `manifold` (no open edge) and the counts the loader +or a repair left (`degenerate_facets`, `edges_fixed`, `facets_removed`, `facets_reversed`, +`backwards_edges`), which `object_fix` reports before and after its repair. + +### object_transform `position` is where the instance or part goes, as the Move panel shows it, the same move as an -absolute `translate` whatever `mode` says for rotate and scale; add_part takes the same name for a new -part's place. +absolute `translate` whatever `mode` says for rotate and scale; `part_add` takes the same name for a new +part's place. With no `object` it acts on the instance or part selected in the Prepare view, or on +instance 0 of the object selected. -On an instance, `transform` writes the `ModelInstance` directly: a relative rotation composes as +On an instance, `object_transform` writes the `ModelInstance` directly: a relative rotation composes as Euler angles, and a rotation or scale applies to that instance only, where the panel applies it to every instance of the object. `size` sets mm along the object's own axes (its model parts' box, unrotated, times the instance's scale; a single number @@ -811,7 +905,7 @@ two plates' origins, applied last. Then the bounding box is invalidated before `ModelObject::ensure_on_bed()`, so a scale that grows an object drops it onto the bed instead of leaving it sunk, and the instance is registered with the plate it is on now (`PartPlateList::notify_instance_update()`, then `ObjectList::update_plate_values_for_items()`), as -`GLCanvas3D::do_move()` does for a person's moves. Slicing and `list_objects` read plates from that +`GLCanvas3D::do_move()` does for a person's moves. Slicing and `object_list` read plates from that registry. On a part (`part`), it takes the Object manipulation panel's path. It refuses the assemble view, an @@ -825,9 +919,9 @@ scale or a `size` (mesh box times the part's scale, in the object's frame) becom current scale, as the panel computes them, since `Selection::scale()` multiplies a part's scale whatever the transformation type. A part's rotation is relative only. -### add_part +### part_add -`add_part` runs what the object's context menu Add items run. It refuses the assemble view, an open +`part_add` runs what the object's context menu Add items run. It refuses the assemble view, an open gizmo and an object with more than one instance, since adding a shape folds instance 0's rotation and scale into the parts (`ObjectList::apply_object_instance_transfrom_to_all_volumes()`), which the other instances would not follow. It selects the object's row, which the menu's functions act on, @@ -844,20 +938,21 @@ primitive", "Load Part" or "Load Modifier"; a file that fails to load leaves it, (`Selection::translate()`, `do_move("")`), all inside one `Plater::SingleSnapshot`, so the call is one undo step. The new part is found by pointer, since `ModelObject::sort_volumes()` orders parts by type. SVG files are refused: SVG parts come from the SVG gizmo, which places them where the -camera looks. +camera looks. With no `object` it adds to the object selected in the Prepare view, or to the object of the +selected instance or part. -### arrange +### object_arrange -`arrange` runs what the GUI runs: with `plates: "all"`, `set_prepare_state(PREPARE_STATE_DEFAULT)` and +`object_arrange` runs what the GUI runs: with `plates: "all"`, `set_prepare_state(PREPARE_STATE_DEFAULT)` and `Plater::arrange()`, as the toolbar does; with a plate index or `"current"`, `select_plate()`, `PREPARE_STATE_MENU` and `arrange()`, as the plate's Arrange icon does, without its `last_arrange_job_is_finished()` flag, which a cancelled job never clears; with `fill_object`, the object's row selected and `fill_bed_with_instances()` or `fill_bed_with_copies()`, which fill the object's own plate. Each takes one "Arrange" undo snapshot. An arrangement shows the Prepare view first and runs -with a gizmo open, as the toolbar's does (`Ops::start_arrange()`, which the `obj_arrange` command -calls too), and is refused while another job runs. Fill bed selects the object's row, so it refuses -the assemble view and an open gizmo as the tools that select do. The tool also refuses a locked or -empty plate given by index, `fill_object` with `plates`, and an object Fill bed refuses +with a gizmo open, as the toolbar's does (`Ops::start_arrange()`, which a person's pick of its tile, +Auto-Arrange, calls too), and is refused while another job runs. Fill bed selects the object's row, so it +refuses the assemble view and an open gizmo as the commands that select do. The command also refuses a +locked or empty plate given by index, `fill_object` with `plates`, and an object Fill bed refuses (`can_increase_instances()`). `spacing`, `rotate`, `align_y` and `multi_material` go into the current print mode's `GLCanvas3D::ArrangeSettings`, which both jobs read, by the panel's rules (`apply_arrange_args()`: @@ -874,27 +969,32 @@ leaves alone (`skipped_plates`: locked, or printing in another sequence than the setting asked for did not apply (one plate in another sequence is arranged with automatic spacing). An arrange sorts the model's objects by arrange order (`PartPlateList::rebuild_plates_after_arrangement()`), so indices may change. After `timeout_s` -(default 300) the call cancels the job. +(default 300) the call cancels the job. Called with no arguments, as its tile, it arranges every unlocked +plate with the panel's saved settings, as the toolbar does, and an automated call of that form waits and +replies as any other call; a person's pick starts the arrangement and returns. -### set_height_ranges +### object_set_height_ranges -`set_height_ranges` gives an object's whole set of height ranges (`ModelObject::layer_config_ranges`), +`object_set_height_ranges` gives an object's whole set of height ranges (`ModelObject::layer_config_ranges`), which a person builds with the object list's Height Range Modifier, its "+" buttons and the range -editors in the sidebar, one gesture and one undo step at a time. Each range starts from what the object -list gives a new one, `ObjectList::get_default_layer_config()` (the object's layer height, else the -process's, and filament 0, the object's), then takes its `values`, parsed strictly. The keys are those a -range's page and the object list's Add settings menus offer (`layer_range_option_keys()`): `layer_height`, -the per-region settings with a category, without support settings or, with one filament, per-feature -filaments and wipe options, and `extruder`, the range row's filament column. A `layer_height` given is -checked against the bounds the range editor enforces (`get_min_layer_height()` / -`get_max_layer_height()` for the range's filament: the printer's per-nozzle values indexed by filament +editors in the sidebar, one gesture and one undo step at a time. A range is `{min_z, max_z}`. One given with +the `min_z` and `max_z` of a range the object has keeps that range's settings; a new one starts from what the +object list gives a new range, `ObjectList::get_default_layer_config()` (the object's layer height, else the +process's, and filament 0, the object's). A range's settings are not this command's: `settings_get` and +`settings_set` read and write them with the target `height_range`, the range named by its `min_z` and +`max_z`, so they are set in one place with an object's and a part's. There they take the keys a range's page +and the object list's Add settings menus offer (`layer_range_option_keys()`, the `region` list of +`settings_list`, `layer_height` among them), and a `layer_height` given is checked against the bounds the +range editor enforces (`check_height_range_layer_height()`: `get_min_layer_height()` / +`get_max_layer_height()` for the range's filament, the printer's per-nozzle values indexed by filament number, so the first serves a single-nozzle printer). Ranges may touch but not overlap: the slicer would trim an overlap silently (`layer_height_profile_from_ranges()`), and from an agent it is a mistake. A range above the object is kept, as the GUI keeps it, and slicing cuts it; the reply gives the object's -height. All of this is checked before anything changes, and a call that gives the ranges the object -already has changes nothing and takes no undo step. +height and its ranges as `object_list` shows them. All of this is checked before anything changes, and a +call that gives the ranges the object already has changes nothing and takes no undo step. With no +`object` it acts on the object selected in the Prepare view. -Like `add_part`, it refuses the assemble view and an open gizmo and switches to Prepare. To change the +Like `part_add`, it refuses the assemble view and an open gizmo and switches to Prepare. To change the ranges it selects the object's row, so no Layers row and no sidebar range editor stays in use, then takes one snapshot ("Edit height ranges"), writes the new ranges, rebuilds the Layers rows from the model with `ObjectList::reload_layer_rows()` (shared with pasting ranges) and calls @@ -905,15 +1005,16 @@ layer height. The dialog the menu shows when the process uses mixed colour subla heights instead of the ranges' `layer_height` (`PrintObject::update_layer_height_profile()` falls back to the ranges only without a valid profile). -### set_variable_layer_height +### object_set_variable_layer_height -`set_variable_layer_height` runs what the Variable layer height panel's Adaptive, Smooth and Reset buttons +`object_set_variable_layer_height` runs what the Variable layer height panel's Adaptive, Smooth and Reset buttons post: `GLCanvas3D::adaptive_layer_height_profile(quality)`, `smooth_layer_height_profile({radius, keep_min})` and `reset_layer_height_profile()`, each with the GUI's undo snapshot ("Variable layer height - Adaptive", "- Smooth all", "- Reset"), followed by a background update and the object list's variable mark. The defaults are the panel's (quality 0.5, radius 5, keep min off), fixed rather than read from the panel, so a replay does not depend on what a person last set there; an argument of another action is -refused. Like the panel, it works on the selected object: it refuses the assemble view and an open gizmo, +refused. Like the panel, it works on the selected object, so it selects the object named (with none, the +object selected in the Prepare view): it refuses the assemble view and an open gizmo, switches to Prepare, selects the object's row, and requires `Plater::can_layers_editing()`, the rule that enables the toolbar item (FFF, the object above the bed, the layer editing shader loaded), naming the condition that fails. It does not open the panel. Reset of an object without a profile changes nothing @@ -935,12 +1036,12 @@ also passes on the warning the panel shows when the process mixes colours in sub stored per object, saved in the 3MF, and discarded by the slicer when it no longer ends at the object's top (after a scale, for example). -### set_custom_gcode_at_layer +### plate_set_custom_gcode -`set_custom_gcode_at_layer` places what the Preview layer slider's right-click menu adds at the start of a layer +`plate_set_custom_gcode` places what the Preview layer slider's right-click menu adds at the start of a layer (Add Pause, Add Custom G-code, Add Custom Template, Change Filament > Filament N) and removes them, on one plate. The codes are a plate's `Model::plates_custom_gcodes` entry, saved in the 3MF -(`custom_gcode_per_layer.xml`) and read back by `list_plates` as `layer_gcode`, with the same type names +(`custom_gcode_per_layer.xml`) and read back by `plate_list` as `layer_gcode`, with the same type names (`pause`, `custom`, `template`, `change_filament`, and `color_change` for an old project's colour change, which the slider never adds). The slider is the source of truth: the plater's handler of its tick event writes the slider's whole set over the plate's entry, and the slider is not refilled while the plate's slice @@ -950,8 +1051,8 @@ edits the slider with its own functions (`IMSlider::add_code_as_tick()`, `add_cu `GLCanvas3D::send_layer_ticks_changes()`, what each Preview frame does, then waits for the handler: the plate's entry rewritten, its slice invalidated, the project dirty and its revision raised. -Codes sit on the layers of the plate's slice. `layer` is the slider's value plus one, as `set_view` and -`get_slice_stats` number layers; `z` takes the layer whose top is at or above it +Codes sit on the layers of the plate's slice. `layer` is the slider's value plus one, as `view_set` and +`plate_slice_stats` number layers; `z` takes the layer whose top is at or above it (`IMSlider::get_tick_from_value(z, true)`, the rule the slider uses for a stored height), so a code is always stored at a layer's top, where the slider and the G-code generator agree on its layer. The reply gives both for every code. A plate's layers are in the slider only while the Preview shows that plate's @@ -978,36 +1079,61 @@ undo archive does not hold the plates' codes), and the slider drops codes it can the plate: filament changes once the objects use different filaments, every code on a plate printed by object or across a spiral vase change. The journal records the plate the call resolved. -### Object and part settings +### Settings of an object, a part or a height range -The object and part scopes of `get_settings` and `set_settings` take the keys the object list -offers to add to an object, or to a part or modifier: `SettingsFactory::get_options()` less what -`SettingsFactory::is_improper_category()` hides with the current filament count, the rule of the -list's Add Settings menu. Keys a person cannot add there, such as the internal `print_extruder_id`, -the process-wide `print_sequence` or, with one filament, the per-feature filaments, are refused rather -than stored and ignored by slicing. Parts and modifiers take region keys only. +The settings commands take two arguments where a person picks two things (`settings_get`, `settings_set`): +`type`, which settings (printer, process or filament, as the preset commands have it), and `target`, where +they apply, named for the rows a person selects in the Process panel's Global and Objects modes: `global`, +the default, the preset being edited; `object`, an object or an assembly, named by `object`; `part`, a part +or a modifier of it, named by `object` and `part`; `height_range`, one of an object's height ranges, named by +`object`, `min_z` and `max_z`. With no `object` the target is the object or part selected in Prepare. A +target other than `global` holds process settings alone, since the app has no filament or printer setting on +an object (`TabPrintModel`), so with another `type` it is refused (`settings_request_error()`, which also +refuses an argument of another target and a part named by its object alone, before anything is read). -`extruder`, the object's or part's filament, is the one key outside that list. `set_settings` writes -it through `ObjectList::set_extruder_for_items()`, the Change Filament code without the selection, -so a call leaves the user's selection alone. An object's filament clears its parts' own; 0 or null -is Default, which is filament 1 on an object, the object's filament on a part and no filament -override on a modifier. A single-part object has no part row, so its part 0 sets the object's -filament, and the reply notes it. Filament numbers (`extruder`, the per-feature and the support -filaments) past the project's slots are refused before anything changes, and the support filaments -refuse a mixed slot, as their combos do. A call is one undo step (`Plater::SingleSnapshot`). +What a target takes is what its row offers to add (`target_options()`): an object, the keys the object +list offers to add to an object (`SettingsFactory::get_options()` less what +`SettingsFactory::is_improper_category()` hides with the current filament count, the rule of the list's Add +Settings menu); a part or a modifier, the region keys among them; a height range, `layer_height` and those +region keys (`layer_range_option_keys()`). `settings_list` with `type` `object` or `region` lists them. Keys +a person cannot add there, such as the internal `print_extruder_id`, the process-wide `print_sequence` or, +with one filament, the per-feature filaments, are refused rather than stored and ignored by slicing, and the +refusal says where the key is set (`untaken_setting_error()`: "layer_height is set on an object or a height +range, not on a part", or that it is set globally only). -In these scopes each `get_settings` item has `effective` and `source`, resolved as the object's -settings tab shows it: the part's override (`part`), else the object's (`object`), else the process -being edited (`process`), else the option's default (`default`). An `extruder` of 0 is no override. -An object's item also lists in `parts` the parts and modifiers that override the key; their values -apply only inside their own volume, and the reply's `note` says so. +`extruder`, the target's filament, is the one key outside those lists. `settings_set` writes it through +`ObjectList::set_extruder_for_items()`, the Change Filament code without the selection, so a call leaves +the user's selection alone. An object's filament clears its parts' own; 0 or null is Default, which is +filament 1 on an object, the object's filament on a part and no filament override on a modifier. A +single-part object has no part row, so its part 0 sets the object's filament, and the reply notes it. +Filament numbers (`extruder`, the per-feature and the support filaments) past the project's slots are +refused before anything changes, and the support filaments refuse a mixed slot, as their combos do. A +height range's `layer_height` is checked as its range editor checks it (see `object_set_height_ranges`). A +null value removes an override; `reset_to` and `reset_all` are refused on these targets. A call is one undo +step (`Plater::SingleSnapshot`). + +Read on such a target, `settings_get` with no `keys` gives what the target overrides, and with `keys` or +`query` any setting it takes. Each item has `value`, the target's own (null where it has none), and +`effective` and `source`, resolved in the order the slicer applies them (`effective_setting()`): the height +range's own value (`height_range`), else the part's (`part`), else the object's (`object`), else the +process being edited (`global`), else the option's default (`default`). An `extruder` of 0 is no override. +An object's or a height range's item also lists in `parts` the parts and modifiers that override the key, +whose values apply only inside their own volume, and an object's or a part's lists in `height_ranges` the +ranges that override it between their heights. Inside a region modifier, a mesh or a painted one, that +sets none of the key, the slicer gives the region the value of the region the modifier overlaps +(`region_config_from_model_volume()` starts from it): a model part's, or that of a region modifier of +either kind before it in the object's list, since the slicer chains both kinds alike. Which volumes it +overlaps is not worked out, so where one of those sets the key the modifier's item gives no value as the +one it prints with: `effective` is null, `source` is `overlapped_part`, `object_effective` and +`object_source` are what the object's chain resolves to, and `parts` lists the volumes that set it. The +reply names the target (`objects` or `parts`, and `height_range`). ### Saving presets -`save_preset` saves the printer, process or filament preset being edited, unsaved changes included, +`preset_save` saves the printer, process or filament preset being edited, unsaved changes included, through `Tab::save_preset()` with the name given, the call the Save preset dialog's OK leads to, so no dialog opens and the saved preset is selected. A filament is first made the one the filament tab -edits for `filament_slot`, as `set_settings` does, and saving it moves every slot that used the old +edits for `filament_slot`, as `settings_set` does, and saving it moves every slot that used the old preset to the new one, as in the GUI. The name is checked by the dialog's own `check_preset_name()`, and its status decides: an invalid name is refused with the dialog's text, and the name of another existing preset needs `overwrite`, while the selected preset's own name is @@ -1020,16 +1146,20 @@ datadir, not the project, so a replay or script meant to be rerun passes `overwr warning, the unresolved-plugin confirmation or the unsaved-changes prompt of a slot switch makes the reply `blocked_by_dialog`. -There is no subset of edits to save. `set_settings {"reset_all": true, "values": {...}}` on a preset -scope first discards every unsaved change with `Tab::on_roll_back_value()`, the tab's undo button, -then applies the values in the same call, so `save_preset` keeps exactly those. The reply lists the -discarded keys in `reverted`. The values are parsed before the reset, so a bad one leaves the edits in -place. The object and part scopes refuse `reset_all`; a null value removes an override there. +There is no subset of edits to save. `settings_set {"reset_all": true, "values": {...}}` on a preset +(the target `global`) first discards every unsaved change with `Tab::on_roll_back_value()`, the tab's +undo button, then applies the values in the same call, so `preset_save` keeps exactly those. The reply +lists the discarded keys in `reverted`. The values are parsed before the reset, so a bad one leaves the +edits in place. The other targets refuse `reset_all`; a null value removes an override there. ### Reading, comparing and changing preset values -`get_settings` reads the preset being edited (for a filament, the slot's preset, edited or not), or -with `preset` any saved preset of the scope, selected or not, without selecting it: the named preset +`settings_get` reads the settings named (`keys`) or searched for (`query`), or with `compare` those that +differ from another preset, or what a target other than `global` overrides; a call with none of these is +refused, since `settings_list` lists all of a type's settings, so no call of `settings_get` is a second +way to list them. On the target `global` it reads the preset being edited (for a filament, the slot's +preset, edited or not), or with `preset` any saved preset of the type, selected or not, without selecting +it: the named preset is read as saved, without the edits the tab holds. `preset` and `filament_slot` are exclusive, and a name that matches no preset is refused with the closest names. `compare` lists only the keys, among those named or matched, that differ from another preset: a saved preset by name, `:saved` (the read @@ -1039,30 +1169,38 @@ against). `:` cannot be part of a preset name, so the two never clash with one. `PresetCollection::dirty_options()` with the Compare presets dialog's rules: printer and filament vectors are compared entry by entry (an item then carries `index`), a printer with fewer extruders is compared from the other side, and both presets have one printer technology. Each item has `value` -(the preset read) and `other`; the bookkeeping `*_settings_id` keys are left out. `list_presets` +(the preset read) and `other`; the bookkeeping `*_settings_id` keys are left out. `preset_list` reports `inherits` and `project: true` for presets kept inside the project. -An enum's meta lists `labels`, the untranslated texts its combo shows, in the order of `values`, so -a person's wording maps to a value. A preset scope's whole listing (no `keys`, `query` or `where`) leaves -meta out unless `include_meta` asks for it: a page of a hundred keys with meta runs to about 50,000 -characters, and an agent that lists everything is scanning values; the keys it then names or searches -for come with their meta. +`settings_list` lists all the settings of a `type`, which has no default, in one reply, each with its +value and no meta: `process`, `printer` and `filament` read the preset being edited, a saved one with +`preset`, or a slot's with `filament_slot` (a process list runs to about 400 settings and 20 KB, a +printer's to 220 and 40 KB, most of it G-code blocks); `object` lists the process settings an object or an +assembly takes and `region` those a part, a modifier or a height range takes, whose `layer_height` item +says a height range alone takes it (`targets: ["height_range"]`), each with the process preset's value, +which an object or a region prints with unless it sets its own. `settings_list` takes no target: what an +object, a part or a height range overrides is `settings_get` on that target with no `keys`. With +`where`, or with `include_meta`, its items carry their meta and come 100 a page +(`settings_list_page()`): a page of a hundred keys with meta runs to about 50,000 characters, and an agent +that lists everything is scanning values; the keys it then names or searches for come with their meta. +An enum's meta lists `labels`, the untranslated texts its combo shows, in the order of `values`, so a +person's wording maps to a value. What a setting does comes with its value. Meta has `description`, the option's whole untranslated tooltip (what it does, when to change it, what it affects), and `where`, the page and group of its row on the settings tab. `where` comes from the sidebar's settings index (`Search::SettingsIndex`), which the settings tabs fill as they build their pages and the Speed Dial reads for its own setting actions; a setting with no row on a page has none, and an object's or part's settings are placed on -the process tab. The help text sits in `get_settings` rather than in a tool of its own because that is -where agents look: in the bench, agents read settings with `get_settings` three to five times as often +the process tab. The help text sits in `settings_get` rather than in a command of its own because that is +where agents look: in the bench, agents read settings with the settings reads three to five times as often as they called a separate explanation tool, and with the tooltips out of the meta they set a draft shield without skirt loops and a support threshold measured from the wrong side, mistakes the same agents avoided when the tooltip came with the value. The size stays bounded by the rule above: only keys that are named, searched for or listed with their group carry meta. -`where` lists one group ("Strength > Walls") or a whole page of the scope with values and meta; a -name the scope has no page or group for is an error that lists them all, which is the map of the -tabs. `query` serves an agent that knows what a setting should do but not its name +`settings_list`'s `where` lists one group ("Strength > Walls") or a whole page of the type with values +and meta; a name the type has no page or group for is an error that lists them all, which is the map of +the tabs. `settings_get`'s `query` serves an agent that knows what a setting should do but not its name (`rank_settings()`). A query word matches a word of a key, label or description that starts with it, so "retract" finds "retraction" while "to" does not match inside "toolchange"; words under three letters count only when the query has nothing longer, since most help texts have them. Settings @@ -1071,16 +1209,16 @@ With no weighting by how rare a word is, a generic word such as "reduce" counts "stringing", so the tool asks for a few distinctive words. A search returns the best 20 unless `limit` asks for more. -Without a `scope`, a search and named keys look through the process, filament and printer settings +Without a `type`, a search and named keys look through the process, filament and printer settings being edited, since a question about an effect rarely knows which tab answers it (stringing is retraction on the printer tab and its overrides on the filament's), and an agent naming a key seldom -knows which tab holds it; each item names its `scope`, the first of the three that has the key. Every -other read without a scope (`where`, the whole listing, `preset`, `compare`) reads the process, and -`set_settings` writes it: a write takes one scope, whose values apply together as one undo step, so it -never spreads over several by itself. A key the scope lacks is listed in `unknown_keys`, and `scope_of` -names the scope that has it (those three, then the project's) when another does; `set_settings` -refuses such a key with that scope named, so an agent that passed a filament key with no scope learns -where it belongs instead of reading "unknown". +knows which tab holds it; each item names its `type`, the first of the three that has the key. Every +other read without a type (`preset`, `compare`) reads the process, and `settings_set` writes it: a write +takes one type, whose values apply together, so it never spreads over several by itself. A key the type +lacks is listed in `unknown_keys`, and `type_of` names where it is a setting (another type, or `project` +for the project's own settings: `type_of_key()`); `settings_set` refuses such a key with that type named, +so an agent that passed a filament key with no type learns where it belongs instead of reading +"unknown". Many process, filament and printer values hold one entry per extruder variant (an extruder type and nozzle flow type, such as the X1C's "Direct Drive Standard" and "Direct Drive High Flow"), the machine @@ -1090,34 +1228,46 @@ For such a value with more than one entry, the meta lists `variants`, what each variant switch find it (`DynamicPrintConfig::get_index_for_extruder()` with the printer's `extruder_type` and the project's `nozzle_volume_type`). The tab edits one variant at a time: its field shows the variant in use and typing writes that entry. So a single value for such a key goes to -the entries in use, `set_settings` writes one entry as `{"key": {"index": i, "value": v}}`, and an +the entries in use, `settings_set` writes one entry as `{"key": {"index": i, "value": v}}`, and an array writes them all. Either way the whole vector, with the entries replaced, goes through the tab's transaction (`Tab::apply_preset_config_values()`), whose commit runs the key's handling as a field edit does, and the other entries stay as they are. A value with another number of entries is refused, with the entries and the one in use in the error and its details: written as given, it would collapse the vector and leave the preset inconsistent with its variants. Values of one entry, and vectors that are not -per variant or per extruder, take a single value. Object and part overrides take whole values. +per variant or per extruder, take a single value. The overrides of the other targets take whole values. -`set_settings` replies with `changed`: every key of the edited config (preset, object or part) whose -value differs after the call, including the settings the app adjusted in turn, such as spiral vase -setting one wall loop and no top shell layers once its dialog is confirmed, and the keys `reset_all` -reverted. Dependency order within one call is not resolved; a call can be split instead. +Three printer values are set as the app sets them, not typed into the tab. `extruders_count` goes alone, +as a change of the Printer settings' Extruders field does (`TabPrinter::change_extruders_count()`). +`nozzle_volume_type`, one per extruder, is each extruder's nozzle flow type as its card in the sidebar +picks it. A `nozzle_diameter` that another variant of the printer model has selects that variant's +printer preset, as the sidebar's nozzle diameter does, and may come with `nozzle_volume_type` alone +(other keys go in a second call); each flow type is checked against what the new preset's nozzle card +offers before anything changes, and read back after the picks (`pick_nozzles()`). The switch asks about +the printer's unsaved changes (`blocked_by_dialog`) unless `reset_all` discards them first; the discard +stays if the switch is not made. + +`settings_set` replies with `changed`: every key of the edited config (preset, object, part or height +range) whose value differs after the call, including the settings the app adjusted in turn, such as +spiral vase setting one wall loop and no top shell layers once its dialog is confirmed, and the keys +`reset_all` reverted. A preset's change is not in the undo history; a target's is one undo step. +Dependency order within one call is not resolved; a call can be split instead. ### Unsaved preset changes -On a preset scope, a `null` value takes the key back to the saved preset's value, as the key's undo -arrow does, and with `reset_to: "parent"` to the value of the preset it inherits from (the `:parent` -of `compare`), as its lock icon does. The value joins the call's other values in the tab's -transaction, so its handling runs as for a typed value. `reset_to` without a null value, and in the -object and part scopes, is refused. +On a preset (the target `global`), a `null` value takes the key back to the saved preset's value, as the +key's undo arrow does, and with `reset_to: "parent"` to the value of the preset it inherits from (the +`:parent` of `compare`), as its lock icon does. The value joins the call's other values in the tab's +transaction, so its handling runs as for a typed value. `reset_to` without a null value, and on the other +targets, is refused. -`select_preset` finds the name in the selector the GUI picks from (`Ops::resolve_preset()`, which the +`preset_select` finds the name in the selector the GUI picks from (`Ops::resolve_preset()`, which the plugin API's `begin_update()` uses too): the sidebar's filament combo of the slot, or the tab's combo, by the label shown or the internal name. It then selects the printer or process preset (`Ops::select_preset()`), or assigns the filament to its slot as a pick in the slot's selector does (`Ops::assign_filament_preset()`, `Sidebar::select_filament_preset()`). A selector lists the visible, compatible presets, and a hidden one is a system filament or printer the setup wizard has not added, -which a fresh data folder has for all but a few. Such a name is shown first (`show_hidden_preset()`): +which a fresh data folder has for all but a few: `preset_list` lists those only with +`include_uninstalled`, each with `installed: false`. Such a name is shown first (`show_hidden_preset()`): the preset becomes visible in memory and the selectors are rebuilt, as they show the selected preset and the filaments an AMS holds, so the wizard's list in `OrcaSlicer.conf`, and what the next start shows, stays as it is; the reply names it in `shown`. A printer shown this way also shows its model's default @@ -1130,7 +1280,7 @@ asked for is refused too (`other_preset_selected`), and that preset stays select `Tab::select_preset()` asks about unsaved changes through `Tab::may_discard_current_dirty_preset()`: for the preset it leaves, and for each modified preset a process or printer switch may replace (the -filament, or the process and filament). `select_preset`'s `preset_changes` sets `Tab::m_dirty_preset_answer` +filament, or the process and filament). `preset_select`'s `preset_changes` sets `Tab::m_dirty_preset_answer` for the one switch, so every prompt is answered with the dialog's Transfer or Discard without showing it, and the switch then does what it does after a person's answer. Transfer moves what the dialog would list: the changed options a settings page shows in the current mode, so a setting the @@ -1143,7 +1293,7 @@ other extruder variants' values is shown only to a person. With several filament not move the filament tab when a slot's filament changes (`Plater::priv::filament_preset_picked()`), so no prompt opens there: the edits stay with the preset the tab edits, and the reply's `modified` lists them. -`new_project` without `preset_changes`, or with `"keep"`, keeps modified presets for the new project, as +`project_new` without `preset_changes`, or with `"keep"`, keeps modified presets for the new project, as New Project's Keep does with every option. `"discard"` is the prompt's Discard, `GUI_App::discard_current_preset_changes()`, called only when a preset is modified, since it reloads the presets, which can ask about the printer's. Modified presets make the project dirty, so @@ -1151,15 +1301,15 @@ the presets, which can ask about the printer's. Modified presets make the projec Both replies carry `discarded` and `modified` when presets had or have unsaved changes, each `{type: {name, keys}}`: a change is discarded when the preset edited afterwards no longer holds its -value, and modified lists the unsaved changes left. Only presets that `list_presets` calls modified +value, and modified lists the unsaved changes left. Only presets that `preset_list` calls modified count, with the keys of their preset type; the full comparison also lists bookkeeping keys that only one of the two configs has. ### Deleting presets -`delete_preset` deletes a user preset or one kept inside the project, with its file and its cloud copy, +`preset_delete` deletes a user preset or one kept inside the project, with its file and its cloud copy, through the GUI's own delete, so no confirmation opens; it is marked destructive, so clients that gate -such tools ask first. What may be deleted is checked first, as the GUI offers and checks it: the tab +such commands ask first. What may be deleted is checked first, as the GUI offers and checks it: the tab shows its Delete button only for user and project presets, refuses a base preset that other presets inherit from (they would no longer load), and for a custom printer (a base printer that is not a system one) asks before deleting the user presets made for it alone, which `delete_attached` answers. The @@ -1181,20 +1331,23 @@ the preset being edited again, which would drop its unsaved changes (filament) o (process), so they are refused while it has any. The reply carries `selected`, the preset of that type selected afterwards, `filaments`, each slot's -preset, and `discarded`/`modified` as `select_preset`'s. A replay needs the preset to exist, -so replays create it first with `save_preset`. +preset, and `discarded`/`modified` as `preset_select`'s. A replay needs the preset to exist, +so replays create it first with `preset_save`. ### Project settings -The project scope of `get_settings` and `set_settings` covers the settings of the project itself -(`PresetBundle::project_config`) that a person sets in the sidebar, on the canvas or in their dialogs: +`project_get_settings` and `project_set_settings` read and write the settings of the project itself, +which it stores outside any preset (`PresetBundle::project_config`), as a plate's are stored on the plate: +they are not print settings a preset or an object holds, so they have commands of their own beside the +settings commands. They are what a person sets in the sidebar, on the canvas or in their dialogs: `curr_bed_type`, `filament_colour`, `flush_volumes_matrix`, `flush_multiplier`, `prime_volume_mode` and `wipe_tower_x`/`wipe_tower_y`, plus the read-only `filament_is_mixed` and, on a printer with -several extruders, the read-only `filament_map_mode` and `filament_map`. A generic config write would -skip what each control does after setting its value, so `set_settings` writes every key through that -control's own code. Everything is checked before anything changes, `null` is refused (project values -always exist), and `{"index": i, "value": v}` sets one slot's colour, one matrix cell or one plate's -tower position. +several extruders, the read-only `filament_map_mode` and `filament_map`; `project_get_settings` with no +`keys` returns them all, each with its value and meta (`meta.offered`, the choices this printer has, and +`meta.read_only`). A generic config write would skip what each control does after setting its value, so +`project_set_settings` writes every key through that control's own code. Everything is checked before +anything changes, `null` is refused (project values always exist), and `{"index": i, "value": v}` sets +one slot's colour, one matrix cell or one plate's tower position. - `curr_bed_type` goes through the plate type selector (`Sidebar::set_bed_type_accord_combox()`, whose handler updates the project, the printer's remembered plate type and the plates on the global type). @@ -1232,38 +1385,56 @@ colour comes from its components and it is never flushed. `filament_is_mixed` te are, and their colours and matrix rows and columns are refused unless left as they are, as the dialog keeps them. The filament grouping is set per plate in the Filament grouping dialog, and every plate carries its own mode from the start, so a project-wide `filament_map_mode` or `filament_map` -would not change a slice: both are listed for reading only. Nothing here except the tower position -enters the undo stack, as in the GUI. +would not change a slice: both are listed for reading only, and a plate's are written with +`plate_set_settings`. Nothing here except the tower position enters the undo stack, as in the GUI. ### Plate settings -The plate scope of `get_settings` and `set_settings` (`plate`, the current plate by default) holds what -the Plate Settings dialog sets on a plate: `curr_bed_type`, `print_sequence`, `spiral_mode`, -`first_layer_print_sequence` and `other_layers_print_sequence`, plus the plate's `name` and `locked`, which -its icons set. Values take the forms the dialog offers: an enum value, a boolean, a filament order that +`plate_get_settings` and `plate_set_settings` (`plate`, the current plate by default) read and write +what the Plate Settings dialog sets on a plate and the plate stores (`PartPlate::m_config`): +`curr_bed_type`, `print_sequence`, `spiral_mode`, `first_layer_print_sequence` and +`other_layers_print_sequence`; and on a printer with several extruders what the plate's Filament grouping +dialog sets, `filament_map_mode` and, with the mode "Manual", `filament_map`, the extruder of each +filament (1-based). The plate's name and lock are commands of their own, `plate_rename` and `plate_lock`, +as a person sets them with the plate's icons. Values take the forms the dialog offers: an enum value, a +boolean, a filament order that lists every slot once (the dialog's drag canvas), and layer ranges `[{from, to, order}]` starting at layer 2 (the first layer has its own order), sorted and not overlapping, `to` left out for the dialog's "End". `null` is the dialog's "Same as Global" or "Auto". The dialog's Auto/Customize choices are not separate -keys: an order given is Customize. `get_settings` lists each key with `value`, the plate's own (null where -it follows the global setting or Auto), and `effective`, what the plate prints with. +keys: an order given is Customize. `plate_get_settings` lists each key with `value`, the plate's own (null +where it follows the global setting or Auto), `effective`, what the plate prints with, and meta +(`meta.offered`, the plate types or grouping modes this printer has); `unknown_keys` lists the keys a +plate does not have. -`set_settings` checks everything first, then selects the plate as its settings and name icons do and +`plate_set_settings` checks everything first, then selects the plate as its settings icon does and passes the plate's values, changed by the call, to `Plater::apply_plate_settings()`, the dialog's OK split from the dialog. It is called only when one of them changes, since the OK marks the project dirty. The plate types are those the sidebar's selector offers (`meta.offered`), none while it is hidden. The custom filament orders are refused while a slot is a mixed filament, where the dialog greys them out. Turning spiral vase on asks the dialog's question about the settings it changes, so the reply can be -`blocked_by_dialog`. `locked` goes through `PartPlateList::lock_plate()` as the lock icon does, and only -when it differs, so setting it twice leaves the plate locked (the palette's `plate_toggle_lock` stays a -toggle). `name` goes through `Plater::rename_plate()`. The call is one undo step (`Plater::SingleSnapshot`; -the dialog itself takes none, the plate tab one per change). The journal records the plate the call -resolved, so a replay sets the same plate. The reply has `applied` (the plate's own values), `effective` -and `changed`. The plate tab's `skirt_start_angle` and the per-plate filament grouping are not in the -scope. +`blocked_by_dialog`. The grouping mode and map are written as the Filament grouping dialog's OK writes +them (`PartPlate::set_filament_map_mode()`, `set_filament_maps()`). On a printer with a multi-nozzle +extruder, a manual grouping is refused where an extruder it gives a filament the plate prints has no nozzle +of the volume type that filament needs, the check that disables the dialog's OK on its Custom page +(`manual_map_nozzle_shortage()`, which both call). The call is one undo step +(`Plater::SingleSnapshot`; the dialog itself takes none, the plate tab one per change). The journal records +the plate the call resolved, so a replay sets the same plate. The reply has `applied` (the plate's own +values), `effective` and `changed`. The plate tab's `skirt_start_angle` is not among them. -`list_plates` reports every plate with these values as it prints them, `overrides` (the keys it sets -itself), `current`, `objects` (how many objects have an instance on it; `list_objects` lists them), `sliced` (an -up-to-date slice), `wipe_tower` (the project's tower position for the plate) and `layer_gcode`, the +`plate_rename` names a plate as its name icon does (`Ops::rename_plate()`, `Plater::rename_plate()`): a +plate other than the current one is made current first, and the name the plate has already changes +nothing. `plate_lock` locks or unlocks a plate as its lock icon does (`Ops::set_plate_locked()`, +`PartPlateList::lock_plate()`), and only when it differs, so `locked: true` twice leaves the plate locked; +without `locked` it toggles, as its tile does. `plate_delete` and `plate_duplicate` take `plate` too +(`Ops::delete_plate()`, `Ops::duplicate_plate()`, the plate menu's functions with the plate given), and +reply with every plate afterwards; a duplicate is one undo step and is refused while slicing and at the +most plates a project holds. `plate_select` makes a plate current as a click on it does. + +`plate_list` reports every plate with its `name`, `locked`, these values as it prints them, `overrides` +(the keys it sets itself), `current`, `objects` (how many objects have an instance on it; `object_list` +lists them), `origin` and `size` (its front left corner and its width and depth on the bed, in the bed +coordinates object positions are given in, so that a caller can place an object on a plate by numbers), +`sliced` (an up-to-date slice), `wipe_tower` (the project's tower position for the plate) and `layer_gcode`, the plate's entry of `Model::plates_custom_gcodes`: the Preview slider's ticks, pauses, custom G-code, templates and filament changes, each `{z, layer, type, filament, color, gcode}` by height. `z` is rounded to the G-code's 0.001 mm. `layer` is the number the slider shows for the code, found by the slider's rule @@ -1274,38 +1445,73 @@ layer. ### Preferences -The preferences scope of `get_settings` reads the app configuration's `app` section, where the -Preferences dialog keeps its settings: `{"scope": "preferences", "keys": [...]}` returns each key's value as -stored (`"true"`, `"1"`, an enum's stored text) and `unknown_keys` for keys the section does not hold. -Keys are required, since the section also holds account and device state and nothing outside the dialog -lists which keys it shows. `set_settings` refuses the scope: a preference changes in the dialog, whose -handlers carry its effects (dark mode, the language, which recreates the GUI, the network plug-in, stealth -mode, render settings redrawn after the dialog closes, and this server's own `mcp_enabled` and `mcp_port`, -which close the endpoint the call came through). Writing the key would skip all of them. +The Preferences dialog keeps the app's preferences in the app configuration's `app` section, and one +table says which they are: `Ops::preferences()` (`Operations/PreferenceOps`), a row for each control +named after the key it stores, with its tab (general, files, behaviour, control, graphics, online or +developer), section, label, kind (checkbox, choice, number or text), a choice's values and labels, a +number's range, the fallback the dialog shows where nothing is stored, whether the row is shown in this +run, whether its value is read only at the next start, and, where a call may not write it, the reason. The dialog builds its plain rows from the table and +the rest with a function of its own per key, so the dialog, `preferences_get` and `preferences_set` cannot +differ. A preference is kept by the app, not in a preset or a project, so the two commands are under The +app, apart from the settings commands. -The dialog's controls are named after their AppConfig keys, so `list_widgets` shows the key and -`set_widget_value {"target": {"name": "export_statistics", "within": "Preferences"}, "value": true}` changes one -through its own handler. The Speed Dial's `open_preferences` takes `[:]` (`general`, `files`, -`behaviour`, `control`, `graphics`, `online` or `developer`) and opens the dialog there through `GUI_App::open_preferences()`, -scrolled to the key's control and focused; a key on another tab is shown on its own tab. Checkboxes, -number and text fields and the language combobox change this way. The other comboboxes (those of -`create_item_combobox()`, the log level, the login region and the network plug-in version) save from a -handler on their drop-down list, where a person's pick arrives, while `set_widget_value` sends the selection to the -combobox itself: it shows the new choice and saves nothing. +`preferences_get` with no argument lists every preference the dialog shows, tab by tab in its order, each +with `key`, `tab`, `section`, `label` (in English), `kind`, `value` (what the dialog shows: true or false +for a checkbox, a number for a number field), a choice's `choices` (`{value, label}`), a number's `min` and +`max`, `stored: false` where nothing is stored and the value is the fallback, `restart_needed: true` for a +preference read at the next start (the rows the dialog marks "(Requires restart)": a write is stored at +once and changes nothing before then), and `refused` for a key `preferences_set` does not write. The +switch and the port of this server read as their controls show them (`Ops::shown_texts()`, which the +dialog's rows read too): the switch is on while the server runs and the port is the one it is on, also +where the session's `--mcp` and `--mcp-port` started it without storing either, so their `stored` says +only whether the configuration holds a value. `keys`, `query` and `tab` narrow the list together. A named key the +dialog does not show is read as the app configuration stores it, and one that is neither is listed under +`unknown_keys`: the section also holds account and device state, which is read only by name. + +`preferences_set` writes `{key: value}` as the controls do (`Ops::set_preferences()`): a checkbox as true +or false, a choice as one of its values, a number within its range, and the downloads folder as the +absolute path of an existing folder. Every key and value is checked first, so a call with one refused key +changes nothing; then the changed keys are written together, the configuration is saved, and each key's +effect runs through `Ops::apply_preference()`, in the keys' order, which the dialog's controls call too (the +preview redrawn, the sidebar's lists, the settings' mode, the backup timer, the log level, the theme, the +preset sync started or stopped, stealth mode's sign-out of the cloud accounts). A key whose value is +already the one given runs nothing. Refused by name, with the table's reason: a key the dialog does not +show, and a key whose control opens a dialog, restarts OrcaSlicer, signs out or reaches outside it (the +language, the login region, the network plug-in, file associations, the mixed-temperature warning, and +this server's own `mcp_enabled` and `mcp_port`, which would end or move the connection the call came +through). The switch that lets Python scripts run unrestricted is no row of the table at all: only a person +turns it on. While the Preferences dialog is open, a call that changes something is refused, as the +dialog is modal, so the rows of an open dialog change only through its own controls. Not in the undo +history. The reply has `changed`, each key with `before` and `after` typed as `preferences_get` gives them, +`stored_before: false` where nothing was stored and `before` is the fallback the dialog showed, and +`restart_needed: true` for a key read at the next start; and `unchanged`. + +A refused preference changes in the dialog, whose controls carry their effects. `window_open {"window": +"preferences", "tab": , "key": }` opens the dialog there through `GUI_App::open_preferences()`, +scrolled to the key's control and focused; a key on another tab is shown on its own tab. The dialog's +controls are named after their keys, so `widget_list` shows the key and `widget_set_value {"target": +{"name": "export_statistics", "within": "Preferences"}, "value": true}` changes one through its own +handler. Checkboxes, number and text fields and the language combobox change this way. The other +comboboxes (those of `create_item_combobox()`, the log level, the login region and the network plug-in +version) save from a handler on their drop-down list, where a person's pick arrives, while +`widget_set_value` sends the selection to the combobox itself: it shows the new choice and saves nothing. ### Calibration tests -`generate_calibration_test` runs a Calibration menu test (temperature, max volumetric speed, pressure advance as tower, -line or pattern, flow ratio in its four passes, retraction, VFA, cornering, input shaping frequency and -damping) one level below its dialog: it calls the same `Plater::calib_*` the dialog's OK calls, with -the `Calib_Params` the dialog would build, and never shows the dialog. The dialogs only collect and check -numbers, so their rules are shared with the tool in `libslic3r/calib.cpp`: `calib_default_params()` (the -values each dialog opens with), `check_calib_params()` (what each dialog refuses, as an enum, so each -dialog keeps its own message box and the tool states the rule with the values given), -`cornering_end_limits()`, `has_junction_deviation()`, `belt_temp_tower_asset()` and the VFA dialog's -auto-adjust, `fit_vfa_speed()` with `vfa_candidate_layer_heights()`. The input shaper types offered per -firmware come from `shaper_type_values()` beside the dialogs. A parameter the test does not take is -refused, so a misplaced argument never passes silently. +`calibration_generate_test` runs a Calibration menu test (`test`: temperature, max volumetric speed, +pressure advance as tower, line or pattern, flow ratio in its four passes, retraction, VFA, cornering, input +shaping frequency and damping) one level below its dialog: it calls the same `Plater::calib_*` the dialog's +OK calls, with the `Calib_Params` the dialog would build. Called with `test` alone, the call of its tile +(one per menu row, whose ids are the rows' ids: `calib_temperature` and the rest), it opens that test's +dialog, as the Calibration menu does (`blocked_by_dialog`), and the dialog's OK runs the test; any value of +the test, or `silent: true`, runs it without the dialog. The dialogs only collect and check numbers, so +their rules are shared with the command in `libslic3r/calib.cpp`: `calib_default_params()` (the values each +dialog opens with), `check_calib_params()` (what each dialog refuses, as an enum, so each dialog keeps its +own message box and the command states the rule with the values given), `cornering_end_limits()`, +`has_junction_deviation()`, `belt_temp_tower_asset()` and the VFA dialog's auto-adjust, `fit_vfa_speed()` +with `vfa_candidate_layer_heights()`. The input shaper types offered per firmware come from +`shaper_type_values()` beside the dialogs. A parameter the test does not take is refused, so a misplaced +argument never passes silently. Two choices that only refill the dialogs' fields are not parameters: the pressure advance defaults follow the printer's `extruder_type` (the dialog's Extruder type radio, which starts at Direct Drive whatever the @@ -1319,35 +1525,171 @@ height or end speed, and a warning says when the upper blocks stay above the fil Every test starts a new project, whose prompts the tool answers itself (`skip_confirm` on each `calib_*`): a project with unsaved changes needs `discard_changes`, and modified presets need `preset_changes`, `"keep"` to run the test with them or `"discard"` to drop them first through -`GUI_App::discard_current_preset_changes()`. Unlike `new_project`, which keeps modified presets silently, -`generate_calibration_test` refuses without `preset_changes` and lists the modified keys: a previous test's settings would +`GUI_App::discard_current_preset_changes()`. Unlike `project_new`, which keeps modified presets silently, +`calibration_generate_test` refuses without `preset_changes` and lists the modified keys: a previous test's +settings would otherwise spoil this one. With `"discard"` the test's rules and defaults come from the saved printer preset, which is what remains. The tests write their filament settings to the preset the filament tab edits, while the test objects print with slot 1, so the tool first points the tab at slot 1's preset -(`edit_filament_slot()`, the switch `set_settings` uses for a slot), as a person must; the reply's +(`edit_filament_slot()`, the switch `settings_set` uses for a slot), as a person must; the reply's `presets_changed.filament` says `filament_slot: 1` and `tab_switched_from` when the tab moved. A tab that -edits another slot's modified preset is refused with `"keep"`. `run_action calib_*` keeps the GUI's -behaviour. +edits another slot's modified preset is refused with `"keep"`. The reply has `test`, `project`, `params` (the values used, in the tool's units: max volumetric speed in mm³/s, a pattern's default acceleration and speed read back from the process), `objects`, `names`, -`plates`, `presets_changed` (per preset type, the settings the test changed, as `set_settings`' -`changed`), `result_keys` (the scope and keys where the measured value belongs), `warnings`, `adjusted`, -and `discarded` and `modified` as `new_project` reports them. The journal records the call with its +`plates`, `presets_changed` (per preset type, the settings the test changed, as `settings_set`' +`changed`), `result_keys` (the `type` and `keys` where the measured value belongs), `warnings`, +`adjusted`, and `discarded` and `modified` as `project_new` reports them. The journal records the call with its effective parameters, defaults included, so a replay does not depend on the dialogs' defaults; VFA's end speed is recorded as asked and a pattern's default acceleration and speed are left out, since both are computed from the presets again on replay. To keep a measured value, the agent leaves the test with -`new_project {"discard_changes": true, "preset_changes": "discard"}`, sets the value with `set_settings` and saves -it with `save_preset`; staying in the test project, `set_settings {"reset_all": true, "values": ...}` on -the preset's scope drops the test's settings there and sets the value in one call. The Speed Dial's `calib_*` commands still open -the dialogs, and their descriptions point at `generate_calibration_test`. +`project_new {"discard_changes": true, "preset_changes": "discard"}`, sets the value with `settings_set` +and saves it with `preset_save`; staying in the test project, `settings_set {"reset_all": true, "values": +...}` with the preset's `type` drops the test's settings there and sets the value in one call. + +### Object commands + +Each object command does one menu row's job, or a few rows' with the argument that picks the variant, and +takes its targets as Tool catalog says, so a call names what to act on and a tile acts on the selection, +as its row does. What it does is an operation of `ObjectOps` (see The operations layer), which the row's +own GUI function calls where it has one, so a pick and a call cannot differ. A few have more to say than +their descriptions: + +- `object_order` orders a plate's objects (the current plate, or `plate`, or with `all` every plate), which + sets the object list and print order. With `by` (name, filament, height, size) it does what the plate + menu's Order By does (`ObjectList::order_objects()`), ascending or with `descending`; called as its tile, + with `by` alone, it keeps Order By's toggle and reverses the order the objects already have, which a call + with any other argument never does. With `order`, the objects of the plate in the order wanted + (`Ops::reorder_objects()`), it makes the drops a drag in the object list makes (`ObjectList::OnDrop()`), so a + call reaches what a person can only drag: `order` names each of the plate's objects once, by index, and the + other plates' objects keep their order. One undo step; the reply gives the new order. +- `object_fix` repairs the meshes as Fix Model does (`ObjectList::fix_through_cgal()` through + `Ops::fix_objects()`) with no progress dialog and no notification: the call waits for the repair, during + which the window does not redraw, and `job_cancel {job}` cancels it. What was repaired before a cancel, + a part of the object it stopped in among them, keeps its new mesh and is shown with it; the reply, in the + error's details, says which object the cancel stopped. Each object's `mesh_errors` before and after are in + the reply, as `object_list` gives them. +- `object_clone` makes copies as the Clone dialog does (`Ops::clone_objects()`, over `Selection::clone()`), + which the dialog calls too; `arrange` defaults to the dialog's choice, the `auto_arrange` preference, and + the call waits for the arrangement. +- `object_reload_from_disk` reloads parts from their files (`Ops::reload_parts()`, the work of + `Plater::priv::reload_from_disk()`); a part whose file is gone is not asked for but listed under `missing`, + and cut objects are refused, since a reload would replace a cut part with its whole file. `part_replace` + replaces one part's mesh as Replace 3D file does (`Ops::replace_part()`), keeping its settings, type, + filament, placement and, with the `keep_painting` preference on, its painting. +- `object_set_printable` sets the flag the object list's Printable cell toggles, and `object_set_auto_drop` + the 3D view's Auto Drop, which only says whether the object drops when it is next moved: the call drops + nothing. +- `object_split` into objects asks Split's Auto-Drop question as its tile; a call answers it with `keep_z`, + or is refused (`auto_drop_question`) where pieces would float. `object_delete` refuses what Delete would + ask about (part of a cut object, an object's last solid part) with the question as its reason, and its tile + leaves those to the object list, which asks. + +### Filament slots and the AMS + +`filament_add`, `filament_delete` and `filament_add_mixed` change the project's filament slots as the +sidebar's filament list does (`Ops::add_filament_slot()`, `Ops::delete_filament_slot()`, +`Ops::add_mixed_filament()`, see Commands that replace a dialog). `filament_add_mixed` adds what the Add +Mixed Filament dialog's OK adds with no gradient (`Sidebar::ensure_mixed_filament()`): `components`, two or +more physical slots of one filament type, each named once, and `ratios`, whole percentages adding up to 100; +a mix the project has already is not added again, and the reply names its slot. None of the three is in the +undo history, as in the GUI. + +`filament_sync_ams` takes the filament list from the AMS of the printer selected on the Device tab. As its +tile, with no arguments, it opens the sync dialog where the project has objects. With `mode` it does what +the dialog's Synchronize now does with that choice, on what the dialog first shows, without the dialog +(`Ops::sync_filaments_from_ams()`, which the dialog applies its choice through too, `Ops::apply_ams_sync()`): +`map` maps each of the project's filaments to a slot, as the dialog's Mapping first does, and takes a +project with objects; `overwrite` replaces the list with the slots' filaments. No printer, no AMS, no +filament, or a printer of another model is refused, saying so (`Ops::ams_sync_refusal()`). The reply lists +each slot's preset and colour afterwards, and the slots whose filament was unknown and mapped to a generic +preset. + +### Installing printers and filaments + +What a person installs is what the Printer Selection and System Filaments dialogs list: the printer models +of every vendor the app ships, and the system filaments. Installed is what the app configuration's models +and filaments sections name, which the presets' visibility follows (`Preset::set_visible_from_appconfig()`): +the selectors offer an installed printer or filament, and `preset_list` lists the others only with +`include_uninstalled`, each with `installed: false`. The dialogs' work is in `Operations/InstallOps`, which +their Confirm calls (`Ops::apply_install_set()`) and the commands call: + +- `printer_list_models` lists every printer model with its vendor, nozzles and installed nozzles, from the + data the Printer Selection dialog lists (`Ops::printer_profile_data()`). That loads every vendor into a + preset bundle of its own, which takes a while, so it is kept in `/cache/wizard_profile_data.json` + while the vendors' versions match; the first call after the shipped profiles change can reply with a job. +- `printer_install` and `printer_uninstall` add or remove the named models' nozzles and keep the rest of the + installed set, where the dialog writes the whole set (`Ops::install_printers()`, `Ops::uninstall_printers()`): + a vendor's bundle is installed from the shipped profiles, the presets are reloaded and a newly added + printer selected, as the dialog's Confirm does. A reload drops the presets' unsaved changes, so while there + are some `preset_changes` says what becomes of them, and without it the call is refused. Removing the last + installed model is refused, and a selected printer that is removed is replaced by another installed one. A + call that changes nothing reloads nothing. The installed filaments are written back with the printers: a + configuration with no filaments section, which installs every filament, gets one naming every system + filament the selectors offer, so that none is hidden. The reload can install a printer's default + filaments where no installed filament fits it, which the reply lists; where a vendor profile lists + default filaments of its own (`VendorProfile::default_filaments`, which only an INI bundle fills, so none + of the shipped JSON profiles does), it also swaps a @System filament for the vendor's own. Two failures + come after a change: `vendors_not_installed`, where a vendor's profiles cannot be copied from the shipped + ones, leaves the installed set as it was, but the profiles copied before it stay in the configuration + folder and, with `preset_changes: discard`, the presets' unsaved changes are gone; `presets_not_reloaded` + has written both sections and not reloaded the presets. Each error says so. +- `filament_install` and `filament_uninstall` add or remove names in the filaments section + (`Ops::install_filaments()`, `Ops::uninstall_filaments()`) and apply it as the app's start does + (`PresetBundle::load_installed_filaments()`), with no full reload, so the presets' unsaved changes are kept. + A name is a preset's, or the short name the dialog's row shows, which stands for that filament on every + installed printer it fits; `filament_install` also takes a vendor and a filament type. A filament a slot + of the project uses is not uninstalled. A printer that no installed filament fits gets its default + filaments again, as the next start would give them, and the reply lists them. + +None of them is in the undo history: the installed set is the app's, not the project's. + +### Plugin commands + +The plugin commands do what the Plugins window does, by the plugin's key, through `Operations/PluginOps`, +which the window's switches and row menus call too: + +- `plugin_list` lists the window's rows as data (`Ops::plugin_rows()`): key, name, version, whether a package + is installed and the plugin enabled (loaded), status, source (local, subscribed, mine or orphaned), a loaded + plugin's capabilities and its error. +- `plugin_enable` turns a plugin, or with `capability` one of its capabilities, on or off, as the row's + switches do (`Ops::set_plugin_enabled()`). A plugin turned on is loaded, after a cloud plugin that is not + installed is downloaded and installed, and the call waits for its load to end (up to five minutes, + `Ops::load_plugin_and_wait()`); a plugin that asks for a permission while it loads asks in its permission + dialog (`blocked_by_dialog`), which the caller answers. +- `plugin_reload` loads a plugin again after its files changed, as the row's Reload does, and with + `clear_cache` as Delete cache and reload; a cloud plugin is installed again, as its Reinstall does + (`Ops::reload_plugin()`). +- `plugin_uninstall` removes a plugin without asking, as the row's Delete does once confirmed, or for a cloud + plugin subscribed to its Unsubscribe, which also ends the subscription in the account + (`Ops::uninstall_plugin()`). It is labelled destructive: a person's plugin and its files go for good. +- `plugin_install_local` installs a `.py` or `.whl` file by path, as the window's Install local plugin + does, without its file dialog. A plugin of that name already installed is replaced only with `overwrite: + true`; without it the call is refused with the question the window asks. Its tile, with no arguments, + asks for the file and, before it replaces an installed plugin, in Orca's own "Overwrite Plugin" message + dialog. +- `plugin_refresh` does what Refresh Plugins does: the installed plugins are rescanned and the plugin hub's + list fetched again, off the UI thread (`Ops::start_plugin_refresh()`). Refreshes take turns: each call and + each pick of Refresh Plugins is a run of its own, and one asked for while others wait or run begins once + they have returned (`Ops::RefreshRun`), so the call's reply comes from a rescan that began after it was + asked. The call waits for its own run to end and replies with the plugins as `plugin_list` gives them. + `job_cancel` stops the wait, not the refresh. A person's pick starts its run and returns, and its own + notification says how it went. A run that would begin while OrcaSlicer closes does not scan. + +The work the window does behind a progress dialog (a download, an uninstall, a reload) runs off the UI +thread in a command too, with no dialog: the operation plans on the UI thread, does the work on a thread of +its own and finishes on the UI thread. However the operation ends, a refusal or a throw, the Plugins window is +brought up to date, and an error after a step that changed the plugin (a cloud download before a refused load, +an unload before a failed removal) says how the plugin is left and carries its row under `plugin`. An empty +`capability` of `plugin_enable` is refused (`empty_capability`): the operation reads no capability as the +plugin itself. ### Design tab: the Design commands The Design tab's sketches, features, reads and measurements, feature and body edits and its commit to the plate are commands of the catalog (`Mcp/McpToolsCad.cpp`) in the group `Design`, not listed, so agents that never open the Design tab pay in `tools/list` for their names alone. The command set itself, how the commands -are named and what each takes, is in [design-commands.md](design-commands.md). The names end `search_tools`' +are named and what each takes, is in [design-commands.md](design-commands.md). The names end `tool_search`' description while the catalog holds the commands (`design_command_index()`): that they are the Design tab's CAD commands and what those cover, that one is looked up before it is called, that a command whose schema has `silent` does what its menu row does when called with no arguments unless `silent` is true, so `interference @@ -1362,9 +1704,9 @@ tool are in the palette, whose tiles for them the Speed Dial has while the Desig catalog). `register_all_commands()` adds them through `register_cad_commands()` only when the catalog is built with the CAD feature on (`CatalogOptions::cad`, which startup takes in the editor from the value in force: the `enable_cad_feature` preference, or `--cad` for the run). With it off the catalog holds none, and records that -it leaves them out (`leave_out_cad_commands()`), a folded row's id among them, which names a tile: `call_tool +it leaves them out (`leave_out_cad_commands()`), a folded row's id among them, which names a tile: `tool_call {tool: "hole"}` is an unknown command whose error says the feature was off when OrcaSlicer started and how a -person turns it on, and `get_app_state` carries `cad_note`, how a person turns the feature on (`cad_note()`, +person turns it on, and `app_state` carries `cad_note`, how a person turns the feature on (`cad_note()`, in the editor while the catalog holds no Design command or the feature is off). The catalog is sealed at startup and the main window makes the Design page only then, so turning the feature on or off takes effect after a restart, but for the Speed Dial's Design tiles, which go as soon as it is turned off (see Speed Dial @@ -1380,7 +1722,7 @@ and feature. No prefix means the 3D model: the commands that build and change th (`sketch_fillet`, `sketch_mirror`, `sketch_pattern`); `surface_` the commands that make sheet bodies; `construct_` reference planes, axes and coordinate systems; `feature_` one entry of the history; `body_` one body as an object, named and coloured, deleted, placed, described and measured, and `body_transform`, since -bare `transform` is Prepare's. A name is whole words, never an abbreviation. +bare `object_transform` is Prepare's. A name is whole words, never an abbreviation. One command does one operation: a menu row and the argument command for its job are one command, and a row that only picks a variant is a way of calling its command. One argument picks the variant. `type` says which @@ -1442,7 +1784,7 @@ command of each entry that is one (`design_command()`, through `cad_command()`), `read_only` and `idempotent` for a `read` block, and has the entry's icon. Its description is the summary, the details, with `ok_false` how a rejected rebuild shows, and, for a command whose rows a call's arguments choose, those argument sets each with its rows' names (`opening_calls()`), so that a search for "polar array" or -"rounded rectangle" finds `sketch_pattern` or `sketch_draw` (`search_tools` matches keys, titles and +"rounded rectangle" finds `sketch_pattern` or `sketch_draw` (`tool_search` matches keys, titles and descriptions, not schemas). A menu-only command's description is its hint and what its call does: what its right-click menu row does, which may open a tool, start a sketch tool, act at once or tell the person why it cannot, with the status line in the reply, and the mode it runs in, "only in an open sketch" or "only outside @@ -1524,18 +1866,18 @@ kind, `mcp_busy()`'s reason after the action (a card, a dialog or a sketch now o the tab's status line (`DesignPanel::mcp_status()`). It claims nothing about what the action did, which may be to open a card, arm a sketch tool, act at once, or say on the status line why it cannot (Loft with fewer than two profile sketches). A modal dialog the action opens holds the call, which the core reports as blocked by -it, as for `new_project {}`; Text's dialog is modeless, so `sketch_text {}` replies at once with a `busy` that +it, as for `project_new {}`; Text's dialog is modeless, so `sketch_text {}` replies at once with a `busy` that names it, and its own Cancel or Escape closes it. For a person's pick, a refusal is shown in the UI's language where its text is a msgid, as these three refusals are. `describe_design` gives `selection`, `{kind, id}`, the selection the right-click menu would be built for, by its `OfferSel` and its atlas id (`kDesignSelectionIds`), `picked_plane`, the reference plane picked in the view, and `feature_row`, the Feature list's selected row. -An agent finds them as it finds any command: `search_tools {group: "Design"}` lists their names, a query -finds them among the commands with their input schemas, and `search_tools {tool}` gives one's group, -`read_only`, description, input schema and examples. `call_tool {tool, args}` runs one, its arguments +An agent finds them as it finds any command: `tool_search {group: "Design"}` lists their names, a query +finds them among the commands with their input schemas, and `tool_search {tool}` gives one's group, +`read_only`, description, input schema and examples. `tool_call {tool, args}` runs one, its arguments validated against its schema, and replies `{"result": ...}`, the tool's own reply; a replay step calls one -by its name or through `call_tool`, and `orca_mcp.py`'s `call_command()` from Python. An unknown name is +by its name or through `tool_call`, and `orca_mcp.py`'s `call_command()` from Python. An unknown name is answered as any unknown command is: with the closest key, or, for a Design command's name in a run started with the CAD feature off, with how a person turns it on. @@ -1546,7 +1888,7 @@ this order. The MCP server is up before the main window, so first come `ui_plate CAD feature off (Preferences > Features); and a Design panel that cannot be built (`-32001`: no page was made at startup, the page is mid-build, or its build failed), whose message says to retry and then restart. The panel is otherwise built on the first call, since in a headless session nobody clicks the tab; -`get_app_state.design_tab` says whether this session has the page. Then come a busy Design tab (`-32002`), +`app_state.design_tab` says whether this session has the page. Then come a busy Design tab (`-32002`), and a `generation` that is not an unsigned integer (`-32602`) or not the model's (`-32010`). Before the generation is read, the project's recipe is loaded into an empty document (`DesignPanel::hydrate_from_model()`), as showing the tab would. @@ -1564,7 +1906,7 @@ would not let the edit land there. `select_geometry` and `body_place` are `chang view means something else under a card, a sketch, Constrain mode, a Move or the Text dialog. A Design command that fails is an error (an `isError` result with `code` `-32000`, `OCCT: …` for a kernel -exception) and leaves the design as it was, so `export_replay` drops it and a replay never repeats a +exception) and leaves the design as it was, so `replay_export` drops it and a replay never repeats a call that did nothing. That holds for argument errors and for a rebuild the kernel rejects alike. The exceptions are the silent forms whose block has `ok_false`, whose descriptions say so (`boolean`, `mirror`, `shell`, `draft`, `rib`, the surface tools, `delete_face`, `import_step`, `set_variable` and others): @@ -1802,10 +2144,10 @@ body's index and the lower one follows it. Thread, sweep and loft rebuild as their cards do, through `DesignPanel::recompute_guarded()`: the kernel works on a worker thread while the UI thread waits in `wxYield()` behind a progress dialog that appears after 300 ms. A long thread or sweep takes seconds, and meanwhile the window paints -and inspection tools answer from inside that loop: `get_app_state`, `list_widgets` (the dialog is a -non-modal `wxProgressDialog` titled "Design") and `screenshot`, of the window or of the dialog's own +and inspection tools answer from inside that loop: `app_state`, `widget_list` (the dialog is a +non-modal `wxProgressDialog` titled "Design") and `window_screenshot`, of the window or of the dialog's own ref. On Windows the dialog is the system's task dialog, run on a thread of its own, so it is no wx -window and `list_widgets` does not list it; the other tools answer as elsewhere. Mutating calls, +window and `widget_list` does not list it; the other tools answer as elsewhere. Mutating calls, another Design command and `undo` among them, are refused by `UiInvoker` as running inside the rebuilding call ("Busy: thread is still running"), and `mcp_busy()` refuses every Design command while a rebuild's worker owns the document, the GUI's own rebuilds included. A call past the reply budget @@ -1839,7 +2181,8 @@ the Bodies row's Move and Place on Face: where the body goes for Commit to Plate no undo step, and the project file does not keep it; a placement follows its body when the bodies are renumbered, by the transient `uid` of the feature that made it (`CadFeature::uid`). -`undo` and `redo` are the Speed Dial's commands (`NativeCommands.cpp`), shared by the Design tab and +`undo` and `redo` are commands of The app, each with a tile of its own (`McpToolsApp.cpp`), shared by the +Design tab and the project, and act on the history of the tab shown, as Edit > Undo and Redo and the top bar's buttons do: the Design tab's while `MainFrame::shown_design_panel()` is not null, else the project's. `history`, `design` or `project`, names one for automation, which acts whatever tab is shown: a Design @@ -1857,7 +2200,7 @@ and after (`Plater::undo_redo_string_getter()`), which change only when the acti with "Nothing was undone in the project's history" (or redone) when neither changed. Success means an entry of the history was taken back or put back, as the Undo list shows it, not that the project differs afterwards: the plater classes a snapshot by its type, and an action can leave one that changed nothing (renaming an object to the name it -has). That is an automated call's, `run_action` of the tile +has). That is an automated call's, `action_run` of the tile included: a person's pick from the Speed Dial does what the Edit menu's item does, and where the menu greys that item it does nothing and shows nothing: on the Design tab's history through `menu_undo_redo()` where `menu_can_undo_redo()` allows, and on the project's only where `Plater::can_undo()` (or `can_redo()`) holds, @@ -1891,7 +2234,7 @@ choice, as they are; given none, the call uses the button's, which `describe_des List's delete path, under one outer snapshot so the commit and the deletions are a single undo step. It refuses before anything changes: an index out of range or repeated, an object that is part of a cut (deleting one asks the person first), an open gizmo, a design with no body, or every -body hidden. The reply gives the new objects' `list_objects` indices after the deletions. +body hidden. The reply gives the new objects' `object_list` indices after the deletions. `commit_to_plate` is the one Design command that changes Prepare's model. It needs no refusal of its own: the mutate guard a Design command's call runs under keeps it out of a modal dialog and out of another call's nested event loop. @@ -1904,7 +2247,7 @@ body as native B-rep where it is placed, under the server's output-path rules. `import_step`, `import_mesh` and `body_compare`'s `reference.step` take an absolute, existing path, like every file the server reads. -`set_view {tab: "design"}` shows the Design tab, and while it is shown `camera` points the Design +`view_set {tab: "design"}` shows the Design tab, and while it is shown `camera` points the Design view as its own controls do: a direction through `DesignCanvas::set_view()`, `default` its Home view (iso, fitted), `fit_objects` its `fit_view()`, `fit_selection` the pick's box, refused when nothing is picked, and `sketch_normal` straight at the open sketch, refused with none open @@ -1917,13 +2260,13 @@ lower or the upper half, and `origin_planes`, `world_axes`, `origin` and `bed` s planes, the world axes, the Origin row's pickable planes and the bed, each through a setter by value; the reply's `design` reads them back. They are refused during a rebuild, and without `tab: "design"`. `fit_bed`, `canvas` and the Preview fields are refused with the Design tab, since they show Prepare or Preview. The -Design view is a canvas target for `list_widgets`, the input tools and screenshots (see GUI automation and +Design view is a canvas target for `widget_list`, the input tools and screenshots (see GUI automation and Screenshots). A change made only in the Design tab marks the project modified, as other project data outside Prepare's undo stack does: `sync_recipe_to_model()` sets the plater's dirty flag besides the -backup's change mark. So `get_app_state.project.dirty`, the window title and `open_files` / -`new_project {discard_changes}` agree with the unsaved-changes prompt that Open and New Project +backup's change mark. So `app_state.project.dirty`, the window title and `project_open` / +`project_new {discard_changes}` agree with the unsaved-changes prompt that Open and New Project show. A project holding only a design loads no objects, and `Plater::load_project()` names it after its file all the same, since a loaded recipe counts as a loaded project. @@ -1956,64 +2299,80 @@ Design commands. ## Speed Dial catalog -`search_actions` and `run_action` serve the Speed Dial's `ActionRegistry`: built-in commands, plates, -recent projects, plugin scripts and pages, and, on request, settings. Built-in commands are -`NativeCommand`s, added by `register_all_commands()` (`NativeCommands.cpp`). Beside what the palette -shows, each has what automation reads: `description` (English, for agents), `input_schema` (the JSON -Schema of its arguments) and `completion` (`Deferred` when the effect finishes in the background after the -command returns). `describe_commands()` fills the descriptions from one table, with a key-prefix rule for -calibration dialogs (pointing at `generate_calibration_test`), camera views and primitives; -`CommandAction` copies them, the schema and the command's key into the `AppAction`. +`action_search` and `action_run` serve the Speed Dial's `ActionRegistry`: the commands' tiles, plates, +recent projects, plugin scripts and pages, and, on request, settings. A tile is a menu row a person picks: +one of a command's `tiles` (`NativeCommand::tiles`, made with `NativeCommands::tile()`: `{key, title, +group, icon, description, args, input?, input_arg?}`, which the command reference writes), or a command's +own tile (`in_palette`), whose key is the command's. A menu row and the command that does its job are one +command, so the rows of one job are tiles of one command, each with the arguments that pick its variant: +Mirror > Along X Axis is `object_mirror {axis: "x"}` under the id `obj_mirror_x`, Export G-code is +`project_export {format: "gcode"}` under `export_gcode`, and the nine view directions are `view_set {camera}` +tiles. Eight commands, whose names are their rows' ids, have a tile of their own: `plate_add`, +`plate_delete`, `plate_duplicate`, `plate_rename`, `filament_add`, `filament_delete`, `undo` and `redo`. + +A tile keeps what a person sees of its row: its id (`orca_command::orca`, the row's id as the key, +whatever its command is named), its title, its Speed Dial section (the item's `group`, or the command's +`tile_group` for its own tile, since a command's `group` is its place's heading and one command's tiles come +from several sections: `export_gcode` is in Slice & Export, `export_stl_multi` in Export), its icon and the +value its second phase collects (`input`). A person's pins and run counts are stored under the id, so the +ids of the rows a released build stored stay the ids of tiles. `tests/data/speed_dial_tiles.json` holds the +129 tiles (key, title, section, icon, input), and the unit test "every Speed Dial tile of today is still a +tile" finds each in the palette with that presentation and no other; "a row's id is a tile's key, not a +command" holds that no row's id is a command's name. The commands live in one `CommandCatalog` (`CommandCatalog.hpp`, which includes no wx), built once at startup -by `NativeCommands::build()` before the automation runtime starts, and sealed: from then on it never changes and any -thread reads it (`NativeCommands::instance()`, `find()`). A process that never calls `build()`, -such as the unit tests and the stdio bridge, gets it built on first use; nothing in the GUI process reads it -before startup builds it, the automation runtime included, which `GUI_App` starts after `build()`. -`register_all_commands()` adds the Speed Dial's commands, then the typed tools (see Tool catalog). Those with -`in_palette` have a tile, and `ActionRegistry` makes an action of each of them (`palette_commands()`) and of -nothing else in the catalog: no typed tool has one, but the four that are also a Speed Dial command. The -Design tab's are the exception: `palette_commands()` leaves group `Design` out, and +by `NativeCommands::build()` before the automation runtime starts, and sealed: from then on it never changes and +any thread reads it (`NativeCommands::instance()`, `find()`). A process that never calls `build()`, such as +the unit tests and the stdio bridge, gets it built on first use; nothing in the GUI process reads it before +startup builds it, the automation runtime included, which `GUI_App` starts after `build()`. +`NativeCommands::palette_tiles()` returns the tiles a person picks whatever tab is shown, in the catalog's +order, a command's own tile first and then each item of its tiles, and `ActionRegistry` makes an action of +each, once, at the snapshot: these tiles depend on no tab or mode. `make_action()` makes it: a +`CommandAction` with the tile's id, its title (`NativeCommands::tile_title()`, translated in the command's +`title_context()`), its section and icon, the tile's description as what automation reads, and its `args` +as the action's `preset`, so a pick runs the command with the tile's arguments (`tile_call_args()`) through +`NativeCommands::run()` with a person's context, with the MCP server on or off. A tile shows an agent no +arguments, but a tile that collects a value: that one takes the value alone, under its `input` token, typed +as the command's argument it goes to. `find_tile()` maps a tile's id to its command and tile. + +The Design tab's tiles are the exception: `palette_tiles()` leaves group `Design` out, and `ActionRegistry::materialize_design_actions()`, which `materialize_live()` runs beside the plate and recent-project families for `snapshot()`, `describe()` and `find_live()`, holds a tile for each entry of the Design table with an action that is offered in the tab's mode, in the table's order (`Mcp::design_tiles()`, by `Mcp::offered_in_mode()`), while `MainFrame::shown_design_panel()` is not null and the CAD feature is on, and none otherwise, so the Speed Dial has the sketch's tiles in an open sketch, the model's outside one, and no Design tile on another tab, nor once the feature is turned off: the tab stays until the restart, but -`cad_gate()` would refuse every pick of its tiles. A command with an action of its own has its tile under its -key (`orca_command:sketch_trim:orca`); a menu row folded into a command keeps its tile under the row's id -(`orca_command:sk_array:orca`), one of the command's `tiles` (`NativeCommand::tiles`: `{key, title, icon, -description, args}`, which the command reference writes), with the row's title and icon. Its action -(`CommandAction` made from the tile) shows an agent no arguments and holds the row's as its `preset`, which -`CommandAction::run()` gives the command in place of the call's: so a pick runs the command with the row's -arguments, as `call_tool {"tool": "sketch_pattern", "args": {"type": "linear"}}` does, through -`NativeCommands::run()` with a person's context, with the MCP server on or off, and `find_tile()` maps a -tile's id to its command and tile. 89 tiles in all: 52 commands' own and 37 folded rows'. A tile's title is -`NativeCommands::tile_title()`: for a Design command, the entry's name translated with the `Design` context -(`title_context()`), as the right-click menu translates it, and its icon is the entry's. Every place that -shows a person a command's title translates it so: the Action Replay window's step and its summary line, a -person's job notices ("Started", "Finished"), the tool list of the replay and script editors, and a -recording's caption of a call (`CaptionBoard` keeps the context beside the title). A call of a command with a -folded row's arguments is titled as that row's tile wherever a person is shown it (`call_title()`, -`tile_with_args()`): a recording's caption (`McpRecorder::call_started()`) and an Action Replay step, whose -description names the tile -(`describe_step()`'s `what` has `tile`, which `replay_what_text()` titles). Every entry's name is marked for -translation in that context (`gen_offer_table.py` writes it as `L_CONTEXT`), also an entry's with no menu row, -which has no tile but is shown in these places. A pin of a Design tile stays in the stored favourites while its -tile is not live, and only leaves the bar that is shown (`prune_favourites()`, `is_design_tile_id()`, which goes -by the Design table's entries with an action, a folded row's among them, so also when the CAD feature was off -at startup). Every other pin with no live action is dropped, a pin stored under an id the table does not have -among them, and the pins around it are kept. A build without CAD has no Design tile, and drops such a pin as -any other. The bar's limit of ten is on what it shows: the first ten live pins in their stored order. A pin is -refused only while the bar shows ten (`add_favourite()`), so a hidden pin never fills it, and a live pin past -the tenth stays stored and comes onto the bar once a pin before it is unpinned. After each pin, unpin and reorder -the open Speed Dial's page is sent the bar as the registry then shows it (`SpeedDialWebDialog::send_favourites()`, -`ActionRegistry::favourites_bar()`), which replaces the page's own after the click's instant change, so the page -never shows fewer pins than the registry counts. Reordering the bar moves the -pins it shows among their own places, and every other pin keeps its place (`reordered_favourites()`). Ordinary -use stores at most thirty pins, ten for each of the three sets of live actions the bar is shown with (the -Design tab's model, a sketch, and every other tab); reading the stored list cuts it to -`ActionRegistry::kFavStoredLimit` (100), so a corrupt configuration cannot grow it. +`cad_gate()` would refuse every pick of its tiles. A Design command with an action of its own has its tile +under its key (`orca_command:sketch_trim:orca`); a menu row folded into a Design command keeps its tile under +the row's id (`orca_command:sk_array:orca`), one of the command's `tiles`, with the row's title and icon, and +a pick runs the command with the row's arguments, as `tool_call {"tool": "sketch_pattern", "args": {"type": +"linear"}}` does. 89 Design tiles in all: 52 commands' own and 37 folded rows'. A Design command's own tile, +unlike any other command's, takes its command's arguments. For a Design command, a tile's title is the +entry's name translated with the `Design` context (`title_context()`), as the right-click menu translates it, +and its icon is the entry's. Every place that shows a person a command's title translates it so: the Action +Replay window's step and its summary line, a person's job notices ("Started", "Finished"), the tool list of +the replay and script editors, and a recording's caption of a call (`CaptionBoard` keeps the context beside +the title). A call of a command with exactly a tile's arguments is titled as that tile wherever a person is +shown it (`call_title()`, `tile_with_args()`, which skips a tile that collects a value): a recording's caption +(`McpRecorder::call_started()`, through `shown_title()`, which also titles `action_run` of a tile as the +tile) and an Action Replay step, whose description names the tile (`describe_step()`'s `what` has `tile`, +which `replay_what_text()` titles). Every Design entry's name is marked for translation in that context +(`gen_offer_table.py` writes it as `L_CONTEXT`), also an entry's with no menu row, which has no tile but is +shown in these places. A pin of a Design tile stays in the stored favourites while its tile is not live, and +only leaves the bar that is shown (`prune_favourites()`, `is_design_tile_id()`, which goes by the Design +table's entries with an action, a folded row's among them, so also when the CAD feature was off at startup). +Every other pin with no live action is dropped, a pin stored under an id the table does not have among them, +and the pins around it are kept. A build without CAD has no Design tile, and drops such a pin as any other. +The bar's limit of ten is on what it shows: the first ten live pins in their stored order. A pin is refused +only while the bar shows ten (`add_favourite()`), so a hidden pin never fills it, and a live pin past the +tenth stays stored and comes onto the bar once a pin before it is unpinned. After each pin, unpin and reorder +the open Speed Dial's page is sent the bar as the registry then shows it +(`SpeedDialWebDialog::send_favourites()`, `ActionRegistry::favourites_bar()`), which replaces the page's own +after the click's instant change, so the page never shows fewer pins than the registry counts. Reordering +the bar moves the pins it shows among their own places, and every other pin keeps its place +(`reordered_favourites()`). Ordinary use stores at most thirty pins, ten for each of the three sets of live +actions the bar is shown with (the Design tab's model, a sketch, and every other tab); reading the stored +list cuts it to `ActionRegistry::kFavStoredLimit` (100), so a corrupt configuration cannot grow it. ### One function, JSON arguments @@ -2029,16 +2388,16 @@ endpoint, so every tile runs with the server off. A pick starts the automation r needs it: through its context (`runtime()`, `submit()`), as a long command does, or through `GUI_App::automation()`, as a person's recording and the Action Replay and Run Script windows do. -Two helpers wrap the function a command's author writes and place it on the thread it needs: +Helpers wrap the function a command's author writes and place it on the thread it needs: - `ui_command(key, title, group, schema, fn, completion)`: `fn(args)` runs on the UI thread and returns an `AppActionRunResult`, what a person's pick shows. Picked by a person, it runs in place, and the reply carries that result as its `notice`. Called by automation, it runs in one `ctx.run_ui()` closure, then `settle()`, and `from_run_result()` makes the reply: `{ran, level, message?}` with the fields of the result's `reply`; an error for an Error or Busy level and for a command that did nothing, worded from an - operation's refusal in English with `{code, names?}` as details. With `CommandCompletion::Deferred` and - arguments, the closure first holds the project as an operation (`ctx.begin_operation()`), takes the - plater's export ticket around `fn`, and the call waits for the file (`await_gcode_export()`). + operation's refusal in English with `{code, names?}` as details. A command made from menu rows is one + (`row_command()`): `fn` runs the row its variant argument names, on the targets the call names, else on + what is selected. - `long_command(key, title, group, schema, fn, inline_call)`: `fn(args, ctx)` runs where its call does, on the job's thread for an automated call. Picked by a person it is started as a job and returns at once (`ctx.submit()`), since it must not hold the UI thread; a command with `inline_call` runs in place @@ -2047,7 +2406,25 @@ Two helpers wrap the function a command's author writes and place it on the thre operation admission, is not journaled, and its job carries the person mark (`JobRegistry::person_in()`), so a script it runs runs as the person's. The pick replies at once with the notice "Started:" and the command's title, or an Error when no job started (another operation holds the project, the app is - closing); the job's result shows as a notification when it ends. + closing); the job's result shows as a notification when it ends. So a pick of Slice and Preview or Slice + All Plates, tiles of `plate_slice`, starts the slice as a job, where a call waits for its result. +- `with_row_forms(tool, person, ...)` and `with_person_form(tool, person, ...)`: a typed command whose tiles + are rows that ask, or that act on what a person selected. Its person's forms are `{}` for its own tile + and the `args` of each item that collects no value (`Mcp::person_forms()`); a call that is one of them + (`Mcp::person_form(command, args)`) runs `person` with those arguments on the UI thread, as `ui_command()` + runs a function, and any other call is the command's own function. `with_person_form()` is for a command + whose own function needs what its person's forms leave out (a path a dialog asks for): `Mcp::with_silent()` + adds `silent` to the schema, which only `true` fits, and moves the own function's `required` list under + `"if": {"not": {"enum": []}}, "then": {"required": [...]}` (or `"if": + {"minProperties": 1}` where the only person's form is `{}`), which the validator reads as "required unless + the call is a person's form"; it reads no other use of `if`. A call with `silent` is the own function, + given `silent` with the other arguments, so the journal records the call as silent. Where a row does what + the command does (the nine camera tiles of `view_set`, Select All and Deselect All of `object_select`, + Auto-Arrange, Auto-Orient, Refresh Plugins), its tile is one of the command's `own_forms`: an automated call + of it runs the command's own function and replies as any call, + and a person's pick runs the same function in place, on the UI thread, showing what the row showed. A + person's pick of a tile that collects a value (Go to layer, Go to tab) runs in place too, given the tile's + call; an automated call of it is the command's own. The palette and the menus call `NativeCommands::run(key, args)`: it checks the arguments, runs the command with a person's context and returns the notice for `notify_result()`, or an Error holding the message when @@ -2056,137 +2433,115 @@ other exception is the command's defect, not an answer to show a person: `run()` key and lets it through to the application's handler (`GUI_App::OnExceptionInMainLoop()`), which treats it as one from any other event handler, so running out of memory still ends the app there. -A command whose silent form needs a value has a person's form too, which asks for it: with no arguments -(`Mcp::person_form()`), a command opens its dialog as a person's pick does; with arguments that stand for -the dialog, it runs without asking. A path skips a file dialog, the Primitive size dialog's dimensions skip -that dialog, and so on (the tables below). Over automation this holds too: `export_gcode {}` opens its file -dialog and replies `blocked_by_dialog`. A command with one form, which needs its value, requires it in its -schema: Go to layer (`percent`) and Go to tab (`tab`), whose value the palette collects in its second phase -(`input`) and passes as `{"percent": 50}` or `{"tab": "preview"}`; called without it, they are refused. -A two-form command whose silent form also needs no argument takes `silent: true` (`Mcp::with_silent()`): -it adds `silent` to the schema, which only `true` fits, and moves the silent form's `required` list under -`"if": {"minProperties": 1}, "then": {"required": [...]}`, which the validator reads as "required once any -argument is given"; it reads no other use of `if`. `with_person_form()` makes such a command of a typed -tool and the tile's person's form, which runs as a `ui_command()` function does: `new_project`, -`save_project`, `start_recording` and `stop_recording` (see Tool catalog). Their silent form is the tool's -own function, which gets the arguments as given, `silent` included, so the journal records the call as -silent. +Two tiles collect a value in the Speed Dial's second phase and have no dialog: Go to tab and Go to layer, the +tiles `go_to_tab` and `go_to_layer` of `view_set`, whose `input` tokens are `tab` and `percent`. The page sends +the value under the token, and the tile passes it on under its command's argument (`input_arg`: +`layer_percent` for `percent`; `tab` keeps its name), so `{"percent": 50}` runs `view_set {layer_percent: +50}`; a page id that a word of `view_set`'s `tab` names (`kTabWords`) is given as that word, the Device tab's +`monitor` as `device`. Go to Plate is the tile `plate_goto` of `plate_select`, with `{plate: 0}`: the first +plate, as the row did when given none, and the plate family of the Speed Dial calls the command with each +plate. -### search_actions and run_action +### action_search and action_run `ActionRegistry::describe(Query)` lists the actions, sorted by group and title, one page of them (`{items, offset, total}`). It can filter by group, lists settings only when asked, and keeps the actions whose id, title, group, source or description holds its `text`, including the English aliases. Each entry has `id`, the English `title` and `group`, `kind`, `description`, `command` (the catalog key) for a command's tile, its `input_schema` when it takes arguments, and `completes: "export"` -for an export. Built-in ids look like `orca_command::orca`. +for a command whose effect lands in the background. Built-in ids look like `orca_command::orca`. -`search_actions` gives `describe()` no text. An agent's query is a few words ("delete object"), +`action_search` gives `describe()` no text. An agent's query is a few words ("delete object"), which no action holds as one text, so `rank_actions()` (McpToolsActions.cpp) scores the listing with the `match_score()` every other search uses: a word matches where a word of what the action is called, or of its description, starts with it. An action is called by its key, its title and its group, as the palette shows one by group and title: Delete Selected is the Object group's delete, though its own title names no object. The actions matching more of the words come first, then those -matching more of them in what they are called, then the shorter key, which is the plainer command: -`obj_delete` before `obj_delete_all`. The key is scored without the `orca_command:` -and `:orca` around it, which would make "orca" and "command" match every built-in. `search_tools` +matching more of them in what they are called, then the shorter key, which is the plainer tile: +the tile `obj_delete` before `obj_delete_all`. The key is scored without the `orca_command:` +and `:orca` around it, which would make "orca" and "command" match every built-in. `tool_search` ranks its `actions` with the same function, so the query that found an action there finds it, and the rest, here. Its `actions` are the actions that are no command (plates, recent projects, plugin scripts and pages): a command's tile carries its key (`describe()`'s `command`), and the command is among -`search_tools`' commands already, so it appears there once. +`tool_search`' commands already, so it appears there once. -`run_action {id, args}` also takes the key alone (`plate_add`) when only one action has it, as agents and -the tools' own messages write it. It resolves the id on the UI thread with `ActionRegistry::find_live()`, +`action_run {id, args}` also takes the key alone (`plate_add`) when only one action has it, as agents and +the commands' own messages write it. It resolves the id on the UI thread with `ActionRegistry::find_live()`, which first re-materialises the families whose membership follows live state (plates, recent projects, the Design tab's tiles; settings are not, being thousands), so the call after one that added a plate, opened a sketch or switched the tab finds the tiles of the app as it is then, and no longer one that is gone. The Speed Dial's own picks run from the snapshot it was opened with. An unknown id returns up to three close ids, scored by edit distance against both the full id and its key, a key that contains the request -(`delete_all` in `obj_delete_all`) counting as closest, and says where to find an action or a command (see -Tool catalog); the id or key of a Design tile that is not live says instead that the tile is there only while -the Design tab is shown in its mode with the CAD feature on, and names the call that runs its command from any -tab, with a folded row's arguments (`call_tool {"tool": "sketch_pattern", "args": {"type": "linear"}}`), or, in -a run started with the feature off, that it was off then and how a person turns it on, as `call_tool` does -(`unknown_action()`). A command's tile runs the command's own function: `args` are checked against its schema, -and it runs through a `Mcp::TileContext`, which is `run_action`'s own context except that a command rewriting -its journal entry does so inside `run_action`'s, as `{"id": ..., "args": ...}`, so a recorded session replays -through `run_action`; the reply's `ran` is the resolved id. A folded row's tile takes no `args`, or exactly the -row's (`action_args_error()`), and runs its command with the row's, which its journal entry records, so its -replay runs the same tool. Any other action (a plugin's script or page, a plate's, a setting's, a recent project's) takes -no arguments, so `args` other than `{}` are refused, saying so (`action_args_error()`); it runs through +(`delete_all` in the tile id `obj_delete_all`) counting as closest, and says where to find an action or a +command (see Tool catalog); the id or key of a Design tile that is not live says instead that the tile is +there only while the Design tab is shown in its mode with the CAD feature on, and names the call that runs its +command from any tab, with a folded row's arguments (`tool_call {"tool": "sketch_pattern", "args": {"type": +"linear"}}`), or, in a run started with the feature off, that it was off then and how a person turns it on, as +`tool_call` does (`unknown_action()`). + +A command's tile takes no `args`, or exactly its own, and a tile that collects a value takes that value alone +(`action_args_error()`); a Design command's own tile takes its command's arguments. To run a command with +other arguments an agent calls the command. `action_run` gives the tile's command what a person's pick gives +it (`tile_call_args()`), so the tile runs as a call with its arguments does: a tile that asks in a dialog asks, +and the reply is `blocked_by_dialog`. `action_run` is an automated call, so for the tiles that are the command's +own forms (the camera tiles, Select All and Deselect All, Auto-Arrange, Auto-Orient, Refresh Plugins) it +replies as the command does. The +command runs through a `Mcp::TileContext`, which is `action_run`'s own context except that a command rewriting +its journal entry does so inside `action_run`'s: the step is journaled as `action_run {"id": , "args": }` (`tile_journal_args()`), so a recorded session replays +through `action_run` and the replay is never refused for arguments the tile does not take; a Design command's +own tile, which takes its command's arguments, keeps the command's rewrite. The reply's `ran` is the resolved +id, added only when the command ran. Any other action (a plugin's script or page, a plate's, a setting's, a +recent project's) takes no arguments, so `args` other than `{}` are refused, saying so; it runs through `ActionRegistry::run(id, args, record_stats=false)`, so agent runs never reorder the palette, and replies as a command does. ### Commands that replace a dialog -Given its arguments, a command skips its dialog and calls an entry point that has none: an operation of -`GUI/Operations` where a tool does the same thing (see The operations layer). A path is absolute; an output -takes `overwrite: true` to replace a file that exists. `path_argument()` resolves `{"path", "overwrite"?}` and -turns a bad or missing path into an Error result. +A call with exactly a tile's arguments is the person's form and asks as the row does; any other call runs +from its arguments and opens nothing. For most tiles the row acts at once, and its call differs from a call +with arguments only in its targets, which the selection gives. These are the tiles that ask, with the call +that does the same without asking: -| Command | Arguments | Entry point | +| Command, called as its tile | It asks | The call that does not ask | |---|---|---| -| `load_project` | `path`: `.3mf` | `Plater::load_project(path)`, which asks about unsaved changes as Open Project does | -| `import_file` | `path`: model file | `Ops::import_models()`: the file's geometry (a project file's settings are not loaded), as one undo step | -| `import_configs` | `path`: `.json`, `.zip`, `.orca_printer`, `.orca_filament`, `.orca_bundle`; `.gcode`; `on_conflict` | `Ops::import_presets()`; for G-code `MainFrame::load_config_file(path)` | -| `save_project_as` | `path`: output `.3mf`, `overwrite` | `Ops::save_project_as()` | -| `export_gcode` | `path`: output `.gcode`, `overwrite` | `Ops::start_gcode_export()`; completion `Deferred` | -| `export_sliced_file`, `export_all_sliced_file` | `path`: output `.gcode.3mf`, `overwrite` | `Ops::export_sliced_3mf()` | -| `export_stl` | `path`: output `.stl`, `overwrite` | `Ops::export_stl()` | -| `export_3mf` | `path`: output `.3mf`, `overwrite` | `Ops::export_model_3mf()` | -| `export_stl_multi` | `path`: existing directory | `Plater::export_stl(..., multiple, dir)` | -| `add_primitive_svg` | `path`: `.svg` | `GLGizmoSVG::create_volume(path, type)`: a new object, or a part of the selected one; a job | -| `export_config` | `path`: existing directory | `ExportConfigsDialog(parent, dir)`: the dialog opens, and its OK writes there | -| `install_local_plugin` | `path`: `.py`, `.whl` | `install_local_plugin_package(path, parent, message)`, the Plugins dialog's install: it asks before replacing an installed plugin, in Orca's own "Overwrite Plugin" message dialog, which `answer_dialog` answers on every platform. Cancel makes the command an error saying that the plugin was not installed. A file that is not a `.py` or `.whl` is refused before that. A package that fails inspection or installation is an Error whose message is "Plugin installation failed:" and the reason, such as a `.py` without a name in its PEP 723 `[tool.orcaslicer.plugin]` table | -| `open_preferences` | `tab`, `key` | `GUI_App::open_preferences(tab, key)`: the dialog opens on that tab, scrolled to the preference | -| `plate_goto` | `plate`: 0-based | `Ops::select_plate()` | +| `project_open {}` | the unsaved changes question, then the Open dialog | `path`, with `discard_changes` where the project has unsaved changes | +| `project_import {}`, `project_import {archive: true}` | a file dialog; the archive, then its file list | `paths`, and `entries` for an archive | +| `project_new {}` | the unsaved changes question | `discard_changes`, `preset_changes`, or `silent: true` | +| `project_save {}`, `project_save {save_as: true}` | a file, when the project has none; always | `path` | +| `project_export {format}`, also with `plates: "all"` or `per_object: true` | a file or folder dialog | `path` | +| `object_add_primitive {shape}` | the size, in the Primitive size dialog | `size`, or `silent: true` for the built-in size | +| `object_rename {}`, `plate_rename {}` | the name | `name` | +| `object_set_instances {}` | the count | `count` or `delta` | +| `object_split {into}` | Split's Auto-Drop question, where pieces would float | `keep_z` | +| `object_delete {}` | the object list's message or question for a cut object or a last solid part | the targets; the question becomes the refusal | +| `object_add_svg {}` | a file dialog | `path` | +| `calibration_generate_test {test}` | the test's dialog | any value of the test, or `silent: true` | +| `preset_import {}` | a file dialog | `path` | +| `plugin_install_local {}` | a file dialog, and whether to replace an installed plugin | `path`, with `overwrite` | +| `filament_sync_ams {}` | the sync dialog | `mode` | +| `recording_start {}` | the Start Recording dialog | any argument, or `silent: true` | +| `window_open {window}`, `app_open_web_page {page}` | nothing: opening is the job | the same call | -The six shape commands (`add_primitive_cube`, `_cylinder`, `_sphere`, `_cone`, `_disc`, `_torus`) -take `size`, the dimensions the Primitive size dialog asks for in its order (`[40, 40, 10]`, `[90, 4]`), -and then call `ObjectList::load_generic_subobject(type, INVALID, true, size)`, which skips the dialog. A -size with the wrong count of positive numbers is an Error result. With an object selected they add -nothing (`ObjectList::can_add_shape_object()`), and say so as an Error, in the palette too. +A silent call that meets the question a row asks on the way takes the answer as an argument or refuses with +the question as its reason: Split's Auto-Drop question (`keep_z`, else `auto_drop_question`), deleting part +of a cut object, replacing an installed plugin (`overwrite`), unsaved preset changes (`preset_changes`). -The object structure commands stand for the object list's context-menu items and the plate menu's -Order By. Like those items, they act on the object list's selected rows, which `select_objects` sets: +Two things have no silent form, and the caller answers their dialog: -| Command | Arguments | Entry point | Refused when | -|---|---|---|---| -| `obj_type_part`, `_negative`, `_modifier`, `_support_blocker`, `_support_enforcer`, `_precise_seam` | none | `ObjectList::set_volume_type(type, true, false)` | a selected row is not a part; the object's last solid part; a text or SVG part to a support or seam type | -| `obj_rename` | `name` | `ObjectList::rename_item(item, name)` | not one object or part row; characters a file name cannot hold | -| `obj_set_instances` | `count`: 1-1000 | `Ops::set_instance_count()` | no object selected; a count below 1 (use `obj_delete`) or above 1000; a cut object; an unprintable instance | -| `obj_assemble` | none | `ObjectList::merge(true)` | fewer than two object rows; a cut object | -| `obj_instances_to_objects` | none | `ObjectList::split_instances()` | no object with more than one instance selected | -| `obj_order_by_name`, `_filament`, `_height`, `_size` | `all`: every plate | `ObjectList::order_objects(order, all)` | no objects to order; a gizmo is open | +| What | The dialog | How a caller answers it | +|---|---|---| +| `preset_export`, every call | the Export Preset Bundle dialog, on the folder `path` names when one is given | click the label of the kind (`widget_click`), check the presets' rows (`widget_set_value` on the checkboxes named after the printer preset or filament they stand for), press OK (`dialog_answer`) and answer the result message; a dialog closed without exporting makes the call an error | +| the loader's questions during `project_import`, `part_add` and `part_replace` with a path | a STEP file's mesh options, the AMF and CAD 3MF options, the names clean-up, inches or metres, one object of several parts (`Plater::load_files()`) | the call replies `blocked_by_dialog`, and `dialog_answer` answers it; no file dialog opens | -Change Type checks the rows itself: with no part row selected, `set_volume_type()` falls back to the -3D selection, which for a selected object holds every part, a change no menu offers. That function -returns why it changed nothing and shows it only for the menu (`show_errors`), so the rule stays in -one place. `rename_item(item, name)` and `set_number_of_copies(num)` are the work of the Rename and -Set number of instances items without their dialogs, which the items keep; with no arguments, the -commands open those dialogs. Order By keeps the menu's toggle: choosing the order the objects already -have reverses it. +Commands that open a dialog whatever their arguments do so as well: `printer_send` (the print host's dialog, +see Print host uploads), `app_benchmark_3d_scene` (Start or Cancel), `preset_migrate_filaments`, and +`app_check_for_updates` with its answer. A path is absolute, and an output takes `overwrite: true` to replace +a file that exists; `path_argument()` resolves `{"path", "overwrite"?}` for the rows that take one and turns +a bad or missing path into an Error result. -A command whose effect its message does not carry sets `AppActionRunResult::reply`, a JSON object -whose fields an automated call's reply has and the palette never shows. `obj_order_by_*` reply with -the sorted plates' objects in their new order (`order: [{object, name, plate}]`) and `descending`, -`obj_assemble` with the new object's `object` and `name`, `obj_instances_to_objects` with the -`objects` the instances are in, and `obj_set_instances` with `object` and `instances`. - -Commands that open a dialog whatever their arguments, such as `export_config`, `plate_rename` or `send_gcode` -(see Print host uploads), return `blocked_by_dialog`, and the agent answers the dialog; the plate scope sets a -name without one. - -`filament_add` and `filament_delete` are the filament list's + and - buttons and a slot's Delete menu item -(`Sidebar::add_filament()` and `Sidebar::delete_filament()`, then the slot counter). They run where the -buttons show, for printers that take several filaments through one extruder, and not on a G-code file; -elsewhere, and at the slot limit or with one slot left, they return Info. A new slot goes after the -physical slots, so mixed filaments move up by one with the objects on them; the message names the new -slot. `filament_delete` takes a 1-based `filament_slot`, the last physical one without it, and remaps the objects on -it as the GUI does. A mixed filament is refused (an Error): it is deleted from the mixed filament list. - -`import_configs` with a path imports presets as the Import Configs dialog does, through -`MainFrame::import_configs()`, the dialog's work split from its file picker and result message: the files +`preset_import` with a path imports presets as the Import Configs dialog does, through +`Ops::import_presets()`, the dialog's work split from its file picker and result message: the files go to `PresetBundle::import_presets()`, and the presets are reloaded and the sidebar refreshed. A preset file (`.json`) is imported alone, a `.zip` or bundle (`.orca_printer`, `.orca_filament`, `.orca_bundle`) with every preset inside it. The dialog asks about each preset that exists already; the command answers @@ -2198,64 +2553,68 @@ preset names before and after; a call that changes nothing is an Error with the the printer first. A `.gcode` loads the settings it was sliced with through `MainFrame::load_config_file(path)`. -`export_config` with a directory opens the Export Preset Bundle dialog, given that directory: its -OK writes there instead of asking for a folder. The agent picks the kind by clicking its label -(`click`), checks presets with `set_widget_value` on their checkboxes, which are named after the preset, printer -or filament they stand for, presses OK with `answer_dialog`, and answers the result message. The command -is an Error when the dialog is closed without exporting. Preset files are not exported without the -dialog: its archive functions read its own checkboxes. +A command made from rows that refuses says why, each refusal in its own words (an `Ops::Refusal`, shown in +the UI's language to a person and read in English by a call): a pick shows it at its level, Info for most, +and an automated call replies `isError`. `filament_add` and `filament_delete` are the filament list's + and - +buttons and a slot's Delete and Merge with menu items (`Ops::add_filament_slot()`, +`Ops::delete_filament_slot()`): +they run where the buttons show, for printers that take several filaments through one extruder, and refuse +elsewhere, at the slot limit, for the only physical slot and for a mixed filament, which is deleted from the +mixed filament list. A new slot goes after the physical slots, so mixed filaments move up by one with the +objects on them. `filament_delete` takes a 1-based `filament_slot`, the last physical one without it, and +`merge_into`, the slot its objects go to in place of the first. `preset_sync` refuses while no account is +signed in, and `filament_sync_ams` with no printer, no AMS or no filament. -A command that does nothing, such as an object command with nothing selected, returns its message -with `AppActionRunResult::done` false. The palette shows it at its level, Info for most; an automated -call replies `isError`. `obj_arrange` and `obj_orient` say why they did nothing (no -objects, or another background job running) and reset the prepare state a plate's Arrange or Auto -Rotate icon leaves behind, so they act on every plate as the toolbar does. Their job is the call's -operation (see Worker jobs), so `run_action` returns once it is done. +A command whose effect its message does not carry sets `AppActionRunResult::reply`, a JSON object whose +fields an automated call's reply has and the palette never shows (`row_reply()`): `object_order` replies with +the new order (`order: [{object, name, plate}]`) and `descending`, `object_assemble` with the new object's +`object` and `name`, `object_separate_instances` with the `objects` the instances are in, and +`object_set_instances` with `object` and `instances`. A refusal after a dialog the person answered or read, +which told them why, shows nothing more to the person, and a call learns it (`quiet_refusal()`): a cancelled +rename is `not_renamed`, a save that wrote nothing `project_not_saved`. `object_arrange {}` and +`object_auto_orient {}` say why they did nothing (no objects, or another background job running); their job +is the call's operation (see Worker jobs), so the call, and `action_run` of their tiles, returns once it is +done. ### Making a feature reachable -Most features need only a Speed Dial command: +A feature is a command, named for its place, then its verb (see Tool catalog), declared in the +`McpTools*.cpp` of its place beside the commands of that place: -1. Add it in `register_all_commands()` with a key, title, group and function, through `add()` or - `add_with_icon()`, which build it with `ui_command()`. Give it a row in `describe_commands()` with an - English description of what it does and what it returns. -2. If it opens a dialog, give it the arguments that stand for the dialog: - `add(...).input_schema = Mcp::object_schema({...})`. With no arguments the function opens the dialog - (`Mcp::person_form(args)`); with them, it resolves them (`path_argument()` for a file) and calls an entry - point that shows no dialog. It must not prompt; it returns an Error result instead. -3. If the effect finishes in the background after the function returns, pass - `CommandCompletion::Deferred` to `ui_command()` so that a call given the file waits for it. +1. Build it with `inspect_tool()` for pure observation, which runs inline, read-only and unjournaled, or with + `mutate_tool()` for anything that changes the app, which runs as a journaled job under the mutate guard; + label it as Tool catalog says (`destructive`, `open_world`). Build the schema with `object_schema()`, + `prop()`, `enum_prop()` and `array_prop()`, and its targets with `with_targets()`; it is validated before + the handler runs, so `arg_string()` and its siblings can read the arguments. Describe it in English: what + it does, its arguments, `Reply:` with what the reply holds, and when it is a job. Give it one to three + `examples` and its key in `kPlaces` of the catalog test, and, where it is one, in that test's read-only or + destructive set; a new place word needs a heading in `place_heading()`. +2. What it does goes into an operation of `GUI/Operations` (see The operations layer): its checks, its + refusals and their wording, its undo snapshot. The handler reads its arguments, resolves its targets + (`resolve_targets()`), calls the operation, throws `refused()` with the refusal or shapes the reply + (`targets_reply()` for what it acted on), and the command names the operation through `reaching()`, or + joins the exception list of `test_operations` with its reason. Throw `ToolFailure` with a message the + model can act on for what is the command's own to check, such as the form of an argument. Do all wx work + in `ctx.run_ui()`, get the plater with `ui_plater()`, which fails until the main window is up, call + `settle()` after a change so queued events are handled before the reply, and page lists with `page()`. + For work that finishes later, call `ctx.begin_operation()`, wait with `poll_ui()`, and give the work an + identity, as slicing and export do. Work on the UI job worker needs none of that: the call that starts it + holds it as its operation (see Worker jobs). +3. Where a menu row does the job, the row is a tile of the command (`NativeCommands::tile()`), with the + arguments that pick its variant and the section, title and icon the row has, and the command takes its + person's form for it (`row_command()`, `with_row_forms()` or `with_person_form()`). A row that asks keeps + its owner's asking path for that form; the call with arguments must not prompt, and refuses instead. A row + with no argument form is a command that is not `listed`. -The command then appears in the palette, in `search_actions` and `run_action`, and in replays. - -What the command does goes into an operation of `GUI/Operations` (see The operations layer): its -checks, its refusals and their wording, its undo snapshot. The function reads its arguments, calls the -operation and answers `refused()` with the refusal or a result, and names the operation in the -`reaches` table. With no arguments, a command that asks the person calls the owner's method. - -When an agent needs structured arguments or results, or has to wait for the effect, add a typed -tool to the matching `McpTools*.cpp`. Use `inspect_tool()` for pure observation, which runs inline, -read-only and unjournaled. Use `mutate_tool()` for anything that changes the app; it runs as a -journaled job under the mutate guard and may be marked `destructive`, and a tool that reaches outside -the app sets `open_world` (see Tool catalog). Build the schema with -`object_schema()`, `prop()`, `enum_prop()` and `array_prop()`. It is validated before the handler -runs, so `arg_string()` and its siblings can read the arguments. Do all wx work in `ctx.run_ui()`, -and get the plater with `ui_plater()`, which fails until the main window is up. A tool that changes -something calls an operation of `GUI/Operations` for it, the one its command calls where there is -one, throws `refused()` for the operation's refusal and is registered through `reaching()` with the -operations it calls. Throw `ToolFailure` with a message the model can act on for what is the tool's own -to check, such as the form of an argument. Call `settle()` after a change so queued events are handled -before the reply, and page lists with `page()`. For work that finishes later, call -`ctx.begin_operation()`, wait with `poll_ui()`, and give the work an identity, as slicing and -export do. Work on the UI job worker needs none of that: the call that starts it holds it as its -operation (see Worker jobs). Describe the tool in English, including what the reply holds and when it is a job. +The command then appears in `tools/list`, in `tool_search`, its tiles in the palette, `action_search` and +`action_run`, and its calls in replays. A new or changed command changes the command reference, `tests/data/command_catalog.json`: the `catalog_reference()` (`CommandCatalog.hpp`) of the catalog a run with the Design tab holds, every added -command in the order it was added with its key, English title, group, description, schema, examples, -whether it is listed and has a tile, its access labels, guard, completion and the operations it names. It -is where a reader outside the app sees every command, and the skill's list of the Speed Dial's commands is -written from it (`tools/mcp/gen_skill_reference.py`). The unit test "the checked-in command reference +command in the order it was added with its key, English title, group, description, schema, examples, tiles, +whether it is listed and has a tile of its own, its access labels, guard, completion and the operations it +names. It is where a reader outside the app sees every command, and the skill's list of the Speed Dial's +tiles is written from it (`tools/mcp/gen_skill_reference.py`). The unit test "the checked-in command reference matches the catalog" fails until it is regenerated: run `slic3rutils_tests "[Reference]"` with `ORCA_UPDATE_COMMAND_REFERENCE=1` in the environment and check the file in. The test compares the file with its line ends made LF, since a checkout may turn them into CRLF, and a build without CAD does not check it. @@ -2263,7 +2622,7 @@ A plugin's operations are not in it: they are not the build's. ## GUI automation -`list_widgets` (`UiInspector`) returns a compact text tree of the shown top-level windows, each +`widget_list` (`UiInspector`) returns a compact text tree of the shown top-level windows, each followed by the popups that opened from it, the rows of their lists, the menus, the GL toolbar items and gizmos, and each canvas's last-frame ImGui items, capped by `max_nodes` and filtered by `query`. The tree is a second text block of the result, and each shown web page's elements are listed under @@ -2275,7 +2634,7 @@ option's definition. Failing that, the label to its left on the same row names i tooltip. A control's state reads `[checked]` or `[unchecked]`, or `[mixed]` for a checkbox that shows neither (a three-state one undetermined, Orca's `CheckBox` half-checked for an unset nullable setting). An option of a selector Orca builds of buttons (`RadioGroup`, `TabCtrl`, `MultiSwitchButton`) -is a button that reads checked while it is the selected one (`selector_option()`), so `set_widget_value true` +is a button that reads checked while it is the selected one (`selector_option()`), so `widget_set_value true` selects it, and a `SwitchButton` with a label at each end has the one it is on as its value. The inspector, the menu capture, ImGui item recording and, on Wayland, the window-state hooks are the @@ -2297,15 +2656,17 @@ stable across runs and is what the journal stores. A locator is one of: - `{web: "Next", kind, css, within, index}` for an element of a web page, by its label, kind or a CSS selector (see Web pages below). -`select_objects` selects objects, instances and parts and replies with the selection as `get_app_state.selection` -gives it (`selection_state()`): in `select_objects`'s own indices, the objects, the instances they are selected +`object_select` selects objects, instances and parts and replies with the selection as `app_state.selection` +gives it (`selection_state()`): in `object_select`'s own indices, the objects, the instances they are selected in and, when the selection holds parts rather than whole instances, those parts. An agent reads it -before an operation that acts on the selection: `run_action` runs the object operations the catalog -has (delete, split, mirror, center, drop, instances, arrange, orient, change type, rename, assemble, -set as individual objects, order by), and `set_settings` with the object or part scope edits their -settings and filament. `add_part` adds parts, modifiers and support shapes, -`set_height_ranges` sets height range modifiers, and `set_variable_layer_height` runs the Variable layer -height panel's buttons. `set_custom_gcode_at_layer` does what the Preview layer slider's right-click menu does. +before a command it calls with no targets, which acts on the selection (see Tool catalog): the object +commands (`object_delete`, `object_split`, `object_mirror`, `object_center`, `object_drop`, +`object_set_instances`, `object_auto_orient`, `part_change_type`, `object_rename`, `object_assemble`, +`object_separate_instances`, `object_order` and the others) take their targets by index too, and their +reply names what they acted on. `settings_set` with the target `object` or `part` edits their +settings and filament. `part_add` adds parts, modifiers and support shapes, +`object_set_height_ranges` sets height range modifiers, and `object_set_variable_layer_height` runs the Variable layer +height panel's buttons. `plate_set_custom_gcode` does what the Preview layer slider's right-click menu does. The rest of the object menu is reached through a right click on the object in the 3D view, or on its row of the object list, with `popup_item` (see Menus below). @@ -2324,9 +2685,9 @@ gestures and ImGui items get synthesized wx events with a render between steps. plain window gets the context menu event a person's would: on macOS wx makes it from the right press the window's handlers pass on, elsewhere the system sends it, so the click sends it there. A GL toolbar item's visibility and enabled state are brought up to date (`GLToolbar::update_items_state()`, what the -canvas's idle handler does) before `list_widgets` lists them and before a click checks them, so an -item a `select_objects` just enabled is not read as disabled. A main menu item likewise gets the state a -person opening its menu sees before `list_widgets` lists it and before a click checks it: the menu's +canvas's idle handler does) before `widget_list` lists them and before a click checks them, so an +item a `object_select` just enabled is not read as disabled. A main menu item likewise gets the state a +person opening its menu sees before `widget_list` lists it and before a click checks it: the menu's `wxEVT_UPDATE_UI` handlers run with the main frame as their source (`update_menu_ui()`), as the frame does when a menu of its menu bar opens and `PopupMenu()` does for the menus Windows' top bar shows. Until then an item keeps the state of the last time a person opened its menu, so View > Default View would still read @@ -2337,7 +2698,7 @@ button) is refused, naming that window. `ImGuiWrapper::set_item_recording()` supplies the ImGui items (see below). `SyntheticInput` holds a gesture's keys, buttons and pointer for code that reads hardware state through `get_key_state()` and `get_mouse_state()`: the canvas, gizmos, and the object list's Ctrl/Shift multi-select. Mouse -modifiers take the names `press_keys` chords use, through `KeyChord::parse_modifier()`, so `ctrl` means +modifiers take the names `keyboard_press` chords use, through `KeyChord::parse_modifier()`, so `ctrl` means the shortcut modifier (Command on macOS) in both, and `rawctrl` the macOS Control key. Held keys are released however the gesture ends; a `mouse_gesture` `down` keeps its button held, and a `move` drags with it, until an `up`, another gesture (one that fails included; a request the server @@ -2359,9 +2720,9 @@ its own hook sees the keys sent to its widgets, as the Design tab's does for Esc tool shortcuts, and the main frame's hook still sees what none below it takes. The Design tab's view is a `GLCanvas3D` of its own (`DesignCanvas::gl_canvas()`), outside the -plater's three. `live_canvases()` lists the plater's, which `get_app_state.gizmo` and the idle checks -read, since the Design view has no gizmos; `ui_canvases()` adds the Design view for what `list_widgets`, the input -tools and screenshots reach: `list_widgets` lists its ImGui items, `click` and `press_keys` act on it, +plater's three. `live_canvases()` lists the plater's, which `app_state.gizmo` and the idle checks +read, since the Design view has no gizmos; `ui_canvases()` adds the Design view for what `widget_list`, the input +tools and screenshots reach: `widget_list` lists its ImGui items, `widget_click` and `keyboard_press` act on it, and `mouse_gesture` takes `canvas: "design"` (`"current"` is the view shown, `shown_canvas()`). A click there goes to the Design view's own handlers, so a left click picks a face, edge or body and a right click opens the offer menu, which is listed or run like any other. Points of the model name @@ -2370,32 +2731,32 @@ gives its faces. ### Windows -`list_windows` (`UiInspector::windows()`) lists the open windows without their widgets, in `list_widgets`'s +`window_list` (`UiInspector::windows()`) lists the open windows without their widgets, in `widget_list`'s order: the main window, the windows that don't block in the order they were created, then the modal stack, the topmost last. wx keeps top-level windows in creation order, not stacking order, so only the -modal stack orders by what is on top. Each window has the ref `list_widgets` gives its node, with the same -locator, so `screenshot` captures that window by it, `list_widgets` lists it alone by it, the input tools take it, all as +modal stack orders by what is on top. Each window has the ref `widget_list` gives its node, with the same +locator, so `window_screenshot` captures that window by it, `widget_list` lists it alone by it, the input tools take it, all as `target`, and the journal records the locator; its title is what `within` takes. A window says whether it is modal and whether it shows a web view (outside a hidden pane), with its size and, where the platform knows it (not Wayland, `window_positions_known()`), its place on screen, its state (normal, maximized or minimized) and whether it has a resize border (the main window always does). `UiInspector::window_entry()` -builds one window's entry, which `set_window` replies with too. A native dialog of the modal stack, which -only `answer_dialog` reaches, is listed with `native` and no ref, whether or not wx reports it shown. A window named `kHiddenFromAutomation` is listed by its title and kind with `hidden` and +builds one window's entry, which `window_set` replies with too. A native dialog of the modal stack, which +only `dialog_answer` reaches, is listed with `native` and no ref, whether or not wx reports it shown. A window named `kHiddenFromAutomation` is listed by its title and kind with `hidden` and nothing more: without a ref no tool acts on it, and an agent learns why a window it was told about is out of its reach. The Python scripts window is the one modal window the tracker leaves off its stack, so it is listed among the others, `modal` from `wxDialog::IsModal()`. ### Sizing and placing windows -`set_window` sizes, moves, maximizes, minimizes and raises a window `list_windows` gives a ref: the main +`window_set` sizes, moves, maximizes, minimizes and raises a window `window_list` gives a ref: the main window (`main`, the default), the topmost modal dialog (`dialog`), or the window a ref or locator is in, so a widget's ref names its window and a replay's `{label: "Preferences"}` finds the dialog again. It -refuses a native dialog, which `answer_dialog` answers, a window named `kHiddenFromAutomation`, a popup, +refuses a native dialog, which `dialog_answer` answers, a window named `kHiddenFromAutomation`, a popup, which the window it opened from places, and a window no longer shown. On macOS a native dialog holds the UI thread, so a call made while one is open waits on it as every call that needs the UI thread does (`blocked_by_dialog`) and never reaches that refusal. A dialog that doesn't block is hidden when it closes, so its ref still resolves; that refusal and the one for a stale ref point to -`list_windows`. A window's geometry changes nothing in the project, so `set_window` is a recover call +`window_list`. A window's geometry changes nothing in the project, so `window_set` is a recover call allowed during an operation that applies no mutate checks: it runs behind a modal dialog, on it, or on any other window. A floating dock panel is sized and moved through its own frame, so the dock manager records its floating size and place as after a drag. @@ -2420,8 +2781,8 @@ once it is back (`finish_restore()`), and it returns to the size and place it ha size given meanwhile is kept, as it leaves the window no longer zoomed. Then come the size, held to the window's minimum and maximum (what its sizer needs), the position (`wxSIZE_ALLOW_MINUS_ONE`: -1 is a place on a screen left of or above the primary one), the state and the raise. A window without a resize border is resized all the same. Sizes and -positions are wx window coordinates, as `list_windows` and `get_app_state` report them: physical pixels -on Windows, points on macOS, logical pixels on GTK. The argument normalizer reads `list_windows`'s flat +positions are wx window coordinates, as `window_list` and `app_state` report them: physical pixels +on Windows, points on macOS, logical pixels on GTK. The argument normalizer reads `window_list`'s flat `x`/`y` and `width`/`height` as `position` and `size`. On Wayland a size is the window the compositor shows, which a window screenshot captures @@ -2437,21 +2798,21 @@ A window manager may apply a request later (X11), animate it (macOS) or change i 50 ms (`poll_until()`, which returns null on timeout or cancellation instead of throwing) until two readings of the screen rect and state in a row agree and show the state asked for, `normal` after a size or position. For the main window it also waits, asking for a frame each poll, until the shown 3D view has drawn at its new size: -the camera's viewport, which only a frame sets, must match the canvas, or a `set_view` fit or a +the camera's viewport, which only a frame sets, must match the canvas, or a `view_set` fit or a `screen_rect` that follows would use the old size. The Design tab swaps its camera into the plater's slot while it is shown, so the one check covers every 3D view. A minimized window and a hidden canvas draw no frames, so neither is waited for. After 3 s (5 s for a minimize on Wayland, `state_change_timeout()`) the call replies with what it read and a note. A call cancelled during the wait fails, and so does one whose window closes, saying the request was applied. -The reply is the window's `list_windows` entry, from the same `window_entry()` with a new ref, in -`set_window`'s own form: `title`, `kind`, `ref`, `size`, `position` (not on Wayland), `state` and +The reply is the window's `window_list` entry, from the same `window_entry()` with a new ref, in +`window_set`'s own form: `title`, `kind`, `ref`, `size`, `position` (not on Wayland), `state` and `resizable`, plus `scale` (`GetContentScaleFactor()`, screenshot pixels per window unit), `display` (the work area of the display it is on, the primary one for a minimized window on none), `active` with `raise`, and `adjusted`, the requested fields the result differs from, with a `note` on whether a size limit or the window manager did it, or on what the wait did not see: the window holding still in the state asked for, or the 3D view drawing at its size, with `undrawn_window()`'s reason when the window is -not being drawn (`add_window_notes()`). `get_app_state.displays` gives each display's work area, scale and +not being drawn (`add_window_notes()`). `app_state.displays` gives each display's work area, scale and whether it is primary, so an agent can choose a position. On Windows a change takes effect at once, but `raise` may only flash the taskbar button while another app @@ -2475,13 +2836,13 @@ created. Wayland has no request to place a window or to read where it is, and no portal offers one; only compositor-private interfaces do (KWin's scripting, sway's IPC), and GNOME has none. So a call with `position` is refused there, naming `GDK_BACKEND=x11`, under which the app runs through XWayland and every -field works. `list_windows`, `set_window` and `get_app_state.window` leave positions out. Size, +field works. `window_list`, `window_set` and `app_state.window` leave positions out. Size, maximize and normal work. GTK never reports a minimized window, but the compositor's `suspended` state (xdg-shell 6) reaches it as a fully obscured visibility notify, which emission hooks installed with the GUI instruments record on the window (`track_window_states()`). Hidden is not minimized: KWin hides a minimized window at once, but also one on another virtual desktop and every window while the screens are off, and Mutter hides any window it has not shown for 3 s. So a window reads minimized while it is hidden -and a minimize from `set_window` stands, which ends once the window shows, takes the focus or closes. A +and a minimize from `window_set` stands, which ends once the window shows, takes the focus or closes. A minimize the person makes from the desktop reads `normal`, since nothing tells the app of it. The wait for a minimize lasts 5 s on Wayland, as Mutter hides the window 3 s after it, and sway never minimizes a window. @@ -2510,8 +2871,8 @@ another, shows its menu, and a call working inside that dialog has a window of i The capture does what `wxWindowBase::PopupMenu()` does before it shows a menu: it sets the invoking window and calls `UpdateUI()`, so the `wxEVT_UPDATE_UI` handlers MenuFactory binds on the main frame -set each item's enabled and checked state as a person would see them. `click`, `mouse_gesture` and -`press_keys` arm a capture in the closure that delivers their input (`arm_menu()`). The first menu that +set each item's enabled and checked state as a person would see them. `widget_click`, `mouse_gesture` and +`keyboard_press` arm a capture in the closure that delivers their input (`arm_menu()`). The first menu that opens goes to it: without `popup_item` it is listed in the reply as `popup_menu` (`items`, and the `disabled` and `checked` ones) and nothing runs, as if the person pressed Escape; with one, that item runs: a check item is toggled or a radio item checked, then `SendEvent()` on the submenu holding it, @@ -2524,7 +2885,7 @@ returns; the reply then lists it under `dialogs`. The call waits for that queued and reads the capture. A later menu in the same call is closed unseen and counted (`menus_closed`); a menu that opens in a window where nothing is armed (a call that queues a menu to open later) is closed unseen too. The last three such menus, with the tool whose window took them, are in -`get_app_state.closed_menus`. +`app_state.closed_menus`. A menu path is the item labels joined with `>`, each without the key the menu shows after it (`MainFrame::menu_item_label()`), matched without case; a trailing `...` may be left out. That is the @@ -2538,7 +2899,7 @@ the numbering and the matching, so a path recorded with another slot in use stil item. A path that names a submenu, a disabled item or nothing fails with the items to pick from, and so does a `popup_item` when the input opened no menu (a right click on empty space while objects are selected, in the Preview, or with a gizmo open). Paths are the UI language's text, as other locators -are. With `x`/`y`, `click` clicks that point of a custom-drawn widget (such as the Design tab's +are. With `x`/`y`, `widget_click` clicks that point of a custom-drawn widget (such as the Design tab's feature tree) as well as of a 3D canvas; a native control, which acts on what the system tells it rather than on wx mouse events, is refused. @@ -2559,8 +2920,10 @@ branches included; a modal dialog's message reads its lists through a bounded `l only shown rows, up to its limit. A click on a list control's row selects it with `SetItemState()`, for which the control sends `wxEVT_LIST_ITEM_SELECTED`, natively on Windows and from the generic control's highlighting elsewhere; a double click sends `wxEVT_LIST_ITEM_ACTIVATED`. An object list row also says what it stands -for by the indices `list_objects` uses (`plate 1`, `object 0 part 1, modifier`, `object 0 layer -range 0-2`). A table's rows are named by their `Name` cell (the object settings table's part rows +for by the indices `object_list` uses (`plate 1`, `object 0 part 1, modifier`, `object 0 layer +range 0-2`), with `, has settings` where the row's settings of its own show as the icon that resets them +(a plate's, an object's, a part's or a height range's). A table's rows are named by their `Name` cell (the +object settings table's part rows by the part), else by their row label; a sort indicator after a column title is left out, and a table that hides its column labels and draws its titles as its first row is read with that row as the titles. A drop-down row in a group has the group's label above it; the picked row is the checked @@ -2592,16 +2955,16 @@ native list starts editing an editable icon cell instead, which the object list actions, so a click that names such a column sends `wxEVT_DATAVIEW_ITEM_EDITING_STARTED` too. A double click sends `wxEVT_DATAVIEW_ITEM_ACTIVATED` (the object list frames the object, or opens the filament editor on the Filament column), a right click `wxEVT_DATAVIEW_ITEM_CONTEXT_MENU`, whose menu -is captured like any other. `set_widget_value` with true or false sets a checkbox cell through +is captured like any other. `widget_set_value` with true or false sets a checkbox cell through `ChangeValue()`, as the toggle renderer does, which tells the owner. A list box row is selected with `wxEVT_LISTBOX` and a checklist row ticked with `wxEVT_CHECKLISTBOX`; a drop-down row is picked with `DropDown::ClickItem()`, which does what a release over it does; a table row's cell is made current -with `GoToCell()` (`wxEVT_GRID_SELECT_CELL`), and its cells are not edited: `set_settings` with the -object scope writes the same values. A Design list row is clicked at its centre, or at the action +with `GoToCell()` (`wxEVT_GRID_SELECT_CELL`), and its cells are not edited: `settings_set` with the +target `object` writes the same values. A Design list row is clicked at its centre, or at the action icon whose tooltip `column` gives, through the list's own mouse handlers. Popups (`wxPopupWindow`: the print button's menu, drop-down lists) report themselves top-level but -are children of the window they opened from. `list_widgets` lists each shown one as a `popup` right +are children of the window they opened from. `widget_list` lists each shown one as a `popup` right after its window (`popups_of()`), and `target: "popup"` lists only them. A widget in a popup belongs to that window (`owning_window()`), so it is inside the topmost modal for the input guards when its popup opened from there, and its locator's `within` names that window. A screenshot of a widget in @@ -2611,7 +2974,7 @@ a popup is refused: a screenshot of its window shows the popup. A plate and its icons in the Prepare view (delete, orient, arrange, lock, settings, name, move to front, filament grouping, IDEX mode) are GL picking models, which a person reaches only by pointing at -them. `list_widgets` lists under the Prepare canvas a `plate_icon` node for each plate, named as the +them. `widget_list` lists under the Prepare canvas a `plate_icon` node for each plate, named as the object list names it, then the icons of the current plate; the lock icon carries the plate's lock state. A locator `{plate_icon, plate}` names any plate's icon by the picking action `PartPlate` gives it: `plate` (the plate itself), `delete`, `orient`, `arrange`, `lock`, `settings`, `name`, @@ -2642,7 +3005,7 @@ hooks (`IMGUI_ENABLE_TEST_ENGINE`) report every item a frame adds while are on; otherwise ImGui skips each hook with one branch. `ImGuiWrapper` keeps the items of each canvas's last frame: id, label, window, rectangle and status flags, whether the item lies outside the visible part of its window, and whether it is the text field ImGui feeds keys to as the frame ends -(the active item, while `InputTextState` is its), which `list_widgets` marks `[focused]` as it does +(the active item, while `InputTextState` is its), which `widget_list` marks `[focused]` as it does the focused window. A field that asks for the keyboard (`SetKeyboardFocusHere()`) takes it a frame after the one that first draws it, and keys sent before then are lost, so a client types into it once it shows focused. The hooks reach the recorder through `ImGuiContext::TestEngine`, so they @@ -2665,7 +3028,7 @@ a reorder it names the control now in its place. Call sites give each control a through the code's own click test. Nothing about the controls changes for a person, and the call costs one branch while recording is off. -`list_widgets` lists each ImGui window (its scroll range when it scrolls), then its items and text in +`widget_list` lists each ImGui window (its scroll range when it scrolls), then its items and text in reading order. An item is listed by its shown label, or, for a field with none, by the text left of it on its row, which only the first field after that text takes; its name is the one it was given or its label's `##` part (`##cursor_radius` → `cursor_radius`). Orca's icon glyphs are not label text. @@ -2677,7 +3040,7 @@ windows it is a child of, to bring it into view (`SetScrollFromPosY()`, then two draws no item for rows out of view, such as Texture Displacement's library, is scrolled with the mouse wheel over its window, as a person does. -`set_widget_value` on an ImGui item acts by its kind and reads the value back, failing when the field shows +`widget_set_value` on an ImGui item acts by its kind and reads the value back, failing when the field shows something else (numbers compared at the precision it prints): a checkbox, radio button or named toggle is clicked when its state differs; an input is clicked, its text selected and replaced, then Return pressed; a multiline input gets Return only between lines; a drag or a slider that takes @@ -2689,14 +3052,14 @@ A gizmo is listed per canvas as its toolbar shows it (`GLGizmosManager::is_on_to on the Prepare canvas Simplify and SVG too while they can open (Simplify when activable, SVG on a selected SVG part). Clicking one does what its icon does (`click_toolbar_icon()`): it opens, or closes the open one; Text with no text selected starts a job that creates a text part and opens the -gizmo, which `click` waits for. A `gizmo` locator takes the name `get_app_state.gizmo` gives, or +gizmo, which `widget_click` waits for. A `gizmo` locator takes the name `app_state.gizmo` gives, or the English title of its toolbar button where that differs (Support Painting for FdmSupports), in -any case; the reply uses the first, and an unknown name's error lists them. `get_app_state.gizmo` +any case; the reply uses the first, and an unknown name's error lists them. `app_state.gizmo` names the open gizmo and its canvas. The -assemble view is entered and left with `set_view canvas` (leaving does what its Return button does; +assemble view is entered and left with `view_set canvas` (leaving does what its Return button does; entering returns once the canvas has loaded its objects, which waits for its GL surface on Wayland), -and `select_objects` and `list_objects` act on it while it is shown. Grabbers are not dragged: a gizmo's -panel fields or `transform` set those values. Pickers inside a gizmo go through `pick_gizmo_file`, whose +and `object_select` and `object_list` act on it while it is shown. Grabbers are not dragged: a gizmo's +panel fields or `object_transform` set those values. Pickers inside a gizmo go through `gizmo_pick_file`, whose actions are the bodies of those pickers (`GLGizmoSVG::change_file()`, `save_svg_as()`, `GLGizmoTextureDisplacement::import_texture()`). @@ -2724,7 +3087,7 @@ target takes `point` or `spot`, not both. What a drag does off the model is the user's to choose: Preferences maps each button to rotate, pan or nothing (`left_mouse_drag_action`, `middle_mouse_drag_action`, `right_mouse_drag_action`, rotate, pan and pan by default), and the touchpad camera style turns the camera with Alt+move and pans with -Shift+move instead. So the tools never turn the camera with a drag. `set_view` `orbit` moves it around +Shift+move instead. So the tools never turn the camera with a drag. `view_set` `orbit` moves it around what it looks at by degrees, yaw to its right and pitch up, placing it with `Camera::look_at()` from its position so the result is the same on every install; it is how an agent looks from between the named directions, which the bench showed agents otherwise reach by dragging the canvas edge on the @@ -2746,11 +3109,11 @@ point picking and the painters to their Shift and Alt modes. ### Camera -`set_view` sets the camera of the 3D view shown. Prepare, Preview and the assemble view share the +`view_set` sets the camera of the 3D view shown. Prepare, Preview and the assemble view share the plater's camera, and the Design tab swaps its own into that slot while it is shown (`DesignCanvas::enter_viewport()`), so `Plater::get_camera()` is always the shown view's and one code path serves all of them. `look_at` is the point the camera looks at, in mm in the view's world -coordinates, as `list_objects` gives positions. On the Design tab these are the Design view's, the +coordinates, as `object_list` gives positions. On the Design tab these are the Design view's, the frame the Design commands' world points use, where `describe_design`'s `modeling_origin` is the sketch planes' origin. `Camera::set_target()` moves the camera parallel, keeping its direction and distance. `zoom` is viewport pixels per mm at the target's depth, which are screenshot pixels: exact @@ -2765,7 +3128,7 @@ fit on the camera (`requires_zoom_to_bed`, `requires_zoom_to_volumes`, `requires before that frame. So when any of the three is given, the call first polls (`poll_until()`, every 20 ms for up to 2 s) until no fit is pending, asking the shown view to draw each time. A `camera` makes the same poll also wait until the shown view has drawn at its canvas's size (`view_drawn_at_size()`, -which `set_window` waits on too): a fit, which `default`, the `fit_*` cameras and the Design directions +which `window_set` waits on too): a fit, which `default`, the `fit_*` cameras and the Design directions make, uses the camera's viewport, which only a frame sets, so after a resize while another tab showed it would fit the old size. After 2 s the call applies the fields anyway and says in a `note` which of the two it did not see; a call cancelled meanwhile fails instead. @@ -2773,17 +3136,17 @@ the two it did not see; a call cancelled meanwhile fails instead. Whenever a camera field is given, the reply carries `camera_state`, read after a last `settle()`: `type` (`ortho` or `perspective`, the Preference the `K` key toggles, which says whether `zoom` holds everywhere), `look_at` and `position` in mm, `zoom`, `click_px_per_mm` (the zoom over the canvas's -scale, in the logical pixels `click` and `mouse_gesture` take) and `elevation` and `azimuth` in +scale, in the logical pixels `widget_click` and `mouse_gesture` take) and `elevation` and `azimuth` in `orbit`'s convention. `camera_angles()` reads the angles for both, without the orbit's one-degree stop short of vertical, so a camera straight above reads 90. The `camera` and `orbit` echoes stay beside it, -since replays check `/camera`. `get_app_state.camera` is the same `camera_state()` for the 3D view +since replays check `/camera`. `app_state.camera` is the same `camera_state()` for the 3D view shown, left out when none is shown. ### Dialogs and web views `ModalTracker`, a `wxModalDialogHook`, sees every `ShowModal()`, native dialogs included, and publishes the snapshot `[{title, message, class, native, buttons}]`, which other threads read. Read on -the UI thread, as `get_app_state`, the `blocked_by_dialog` probe, the guards' refusals and the input tools' +the UI thread, as `app_state`, the `blocked_by_dialog` probe, the guards' refusals and the input tools' `dialogs` read it, the snapshot describes the open dialogs again first. So it shows a dialog as it is now: text the dialog filled in once it showed (a printer's name, a list from a scan), a field typed in, a page switched. Should describing fail, the last description stands. Only a native dialog that holds @@ -2791,13 +3154,13 @@ the UI thread (macOS) leaves readers with the description published before it; i change. A dialog that can't be described is listed by its title, class, `native` and `web` flags, with no message or buttons, so the guards still see it and a rule matches it by its title. Message boxes and file and folder pickers are native; a box's message is its text, and a picker's is its prompt, such as "Choose Download Directory", since its title is often empty. Colour and -font choosers are not classified as native, because on GTK they are wx dialogs that `answer_dialog` -ends; on macOS and Windows they are OS choosers, best answered ahead with an `auto_answer_dialogs` rule. +font choosers are not classified as native, because on GTK they are wx dialogs that `dialog_answer` +ends; on macOS and Windows they are OS choosers, best answered ahead with an `dialog_auto_answer` rule. A wx dialog's message reads it as a person does, so an agent can tell what the dialog asks and what each button will do without a screenshot (`DialogReader`). Each shown child becomes a cell. Nested dialogs, popups, web views and canvases are left out; a nested dialog is described on its own. -Controls are read through the readers `list_widgets` uses (`kind_of`, `value_of`, `checked_of`, +Controls are read through the readers `widget_list` uses (`kind_of`, `value_of`, `checked_of`, `selector_choices`, `list_rows`), so the two say the same about each one: - Static text, html and custom widgets that show a label (`StaticLine` titles) read as their text, and @@ -2812,7 +3175,7 @@ Controls are read through the readers `list_widgets` uses (`kind_of`, `value_of` - A selector Orca builds of buttons (`RadioGroup`, `TabCtrl`, `MultiSwitchButton`), a `SwitchButton` with a label at each end, and a notebook's tabs read as one line, `(*) A | ( ) B`; an icon option reads as its tooltip. A notebook's tabs are followed by the page shown. -- A list reads one line per shown row, up to 25, then a line saying `list_widgets` lists the rest. +- A list reads one line per shown row, up to 25, then a line saying `widget_list` lists the rest. - A gauge reads `[45%]`. - A disabled control adds ` (disabled)`. Disabled is judged between the control and its dialog, so a dialog under another modal does not read as all disabled. @@ -2861,14 +3224,14 @@ label. Web dialogs are read through their page (below). `buttons` lists the wx buttons a dialog shows, with `enabled: false` for a disabled one. The options of a selector made of buttons (`RadioGroup`, `TabCtrl`, `MultiSwitchButton`) are not listed, since pressing -one only selects it. `answer_dialog`, and a rule, still find such an option by its label (its tooltip +one only selects it. `dialog_answer`, and a rule, still find such an option by its label (its tooltip for an icon option, in full even where a message cut at its cap shows only its start) and select it, and -`list_widgets` shows the selected option checked, under the same full label. `set_widget_value false` on the +`widget_list` shows the selected option checked, under the same full label. `widget_set_value false` on the selected one, or on a selected radio button or radio box, is refused, since an option is unselected by selecting another. Other radio buttons and switches are set -with `click` or `set_widget_value true`, and notebook tabs with `click` on the tab. +with `widget_click` or `widget_set_value true`, and notebook tabs with `widget_click` on the tab. -`answer_dialog` presses the topmost wx dialog's button, so the dialog's own handler runs. +`dialog_answer` presses the topmost wx dialog's button, so the dialog's own handler runs. `press_dialog_button()` tells what it did: - **Pressed:** the button was pressed. @@ -2876,23 +3239,23 @@ with `click` or `set_widget_value true`, and notebook tabs with `click` on the t without a Cancel button. One whose Cancel or Close is on a page it does not show ends the same way. - **Disabled:** the button is shown but disabled, so nothing is pressed or stood in for. The dialog disabled it on purpose: OK while a name is invalid, Send until a box is ticked, Cancel while a - cancel is under way. `answer_dialog` refuses a disabled button, its message showing what the dialog + cancel is under way. `dialog_answer` refuses a disabled button, its message showing what the dialog still needs. - **Hidden:** the button is only on a page the dialog does not show, such as a wizard's Finish, so - nothing is pressed or stood in for, and `answer_dialog` refuses it. Buttons are looked up among the + nothing is pressed or stood in for, and `dialog_answer` refuses it. Buttons are looked up among the dialog's own windows, not a popup's or a nested dialog's. - **Failed:** a native message box could not be pressed. -On Windows and Linux `answer_dialog` also presses an open native message box. The tracker lists the +On Windows and Linux `dialog_answer` also presses an open native message box. The tracker lists the buttons wx gives the box for its style (Yes and No or OK, and Cancel; not Help, which on Windows shows help without closing the box), and a press goes to the OS's box by message. On Windows that is a `WM_COMMAND` to a message box, or a `TDM_CLICK_BUTTON` to the task dialog wx shows where Windows has one, found among the UI thread's windows by class and caption, the active one first. On GTK it is `gtk_dialog_response()` on the dialog's widget. The box closes once its own loop runs again, which -`answer_dialog` waits up to 1 s for, so its reply says `closed`. A box that is no longer shown is +`dialog_answer` waits up to 1 s for, so its reply says `closed`. A box that is no longer shown is refused. On macOS a message box lists no buttons, since no call reaches one (above). -A picker, and on macOS any native dialog, can only be answered ahead with an `auto_answer_dialogs` rule: +A picker, and on macOS any native dialog, can only be answered ahead with an `dialog_auto_answer` rule: a regex and a button, and for a file or folder picker a path. The regex is searched in three places: - the title and message joined by a newline @@ -2920,30 +3283,30 @@ never from `SetPath()`; for the same reason a single-select picker's caller that instead of `GetPath()` gets an empty list from a path answer on Windows and macOS. On GTK a path rule cancels every picker it matches, since a GTK picker's `GetPath()` has no path until it has shown. A path rule answers pickers only, as they open: never a wx dialog or message box it matches, nor a picker -already open. `get_app_state.auto_answer_rules` and the tool's reply list a rule's `path` and +already open. `app_state.auto_answer_rules` and the tool's reply list a rule's `path` and `overwrite`. The replay summary (`describe_step()`) flags a step that sets a path rule outside the run's output folder as writing a file, since which picker the rule will answer, and whether that picker saves, is not known until one opens. A wx dialog that matches a rule opens, and the tracker presses the button once the dialog's modal loop -runs (`press_dialog_button()`, queued on the dialog), as `answer_dialog` does. Its buttons do the +runs (`press_dialog_button()`, queued on the dialog), as `dialog_answer` does. Its buttons do the dialog's work in their handlers (`UnsavedChangesDialog`'s Transfer and Discard, `CloneDialog`'s Fill), which a returned id would skip. The rule counts as used once the press pressed the button or ended the dialog. A button disabled by then leaves the dialog open, logged, and a modal opened above it before -then leaves it to `answer_dialog`. +then leaves it to `dialog_answer`. -A new rule also answers a matching dialog that is already open, as `answer_dialog` would, a message +A new rule also answers a matching dialog that is already open, as `dialog_answer` would, a message box included where it can be pressed. The first rule that names one of its buttons decides: if that button is disabled or hidden, the dialog stays open and the reply says `disabled: true` or `hidden: true` (a hidden Cancel or Close ends the dialog, as above). A prompt posted around the same time, such as the restore prompt after startup, is handled whether it opens before or after the rule. A replay's or script's rules end with it, a client's call replaces its earlier rules, and -`get_app_state` lists the rules in force. +`app_state` lists the rules in force. A dialog that hosts a web view is described with `web: true`; its controls are on its page, which -`list_widgets target=dialog` lists and the input tools drive like any widget (see Web pages below). It +`widget_list target=dialog` lists and the input tools drive like any widget (see Web pages below). It has no text of its own, so a rule matches it by title. Its page is the one its shown web view holds; a web -view the dialog keeps hidden has no page to press on. `answer_dialog` looks a name or label up as a +view the dialog keeps hidden has no page to press on. `dialog_answer` looks a name or label up as a wx button label first, then among the page's buttons and links, waiting up to 3 s for one to show (each ask expires with those 3 s, so the page never presses one later), and clicks it there, hit tested as a click is, so the page's own handler runs (`{pressed: true, web: true}`). With no such @@ -2958,7 +3321,7 @@ only time a complete document is shown and restarts when the document changes, s bootstrap page replaced by its content is waited out; past it, or after 2 s with no web view shown, `cancel` and `close` end the dialog natively and any other answer gives up, logged. -`run_javascript` runs JavaScript in a page through its agent, as a recover call: in a web view of the +`webview_run_javascript` runs JavaScript in a page through its agent, as a recover call: in a web view of the topmost modal dialog whatever the dialog, in one under it never, and elsewhere with a mutate call's checks. Without a target the topmost dialog's web view is used, else the only shown one; a web view's locator names it by kind (`class: "webview"`), since its class differs per platform, and a page @@ -2983,7 +3346,7 @@ nothing of their own. The agent is installed as a non-enumerable property, out o enumeration of `window`. Scripts go through `WebView::RunScriptAsync()`, whose completion holds only the callback: WebView2's -`ExecuteScript` handler, WKWebView's `evaluateJavaScript` block, WebKitGTK's `run_javascript` +`ExecuteScript` handler, WKWebView's `evaluateJavaScript` block, WebKitGTK's `webview_run_javascript` callback. wx's own `RunScriptAsync()` keeps a plain pointer to the web view in its callback on every port, and a page may close its dialog, destroying the web view, at any time. `PageCalls` start calls on the UI thread and wait for them on the job thread, a destruction watcher ending the wait for a @@ -3009,7 +3372,7 @@ hidden checkbox is listed as its label, and open shadow roots and same-origin fr navigation or reload changes, so a ref from before is stale ("the page changed"). Page lines have their own budget, `max_web_nodes` (default 300), so a large page never pushes widgets listed after it out of `max_nodes`. With a modal dialog open only the topmost dialog's pages are read, since no input -reaches the others, which get the note `behind a modal dialog`. `list_widgets` waits up to 2 s for a +reaches the others, which get the note `behind a modal dialog`. `widget_list` waits up to 2 s for a page still loading, then reads every page at once, for up to 3 s together. A locator `{web, kind, css, within, index}` matches the label exactly, else case aside, else as a @@ -3028,14 +3391,14 @@ among the matches of every candidate page and its configuration frames, as a rep (`journal_index()`); with no `index` when one of them was not heard from (silent, failing the search or unable to run the agent) or the action took the element away, so a replay that finds several asks for one rather than taking another. A screenshot of a page element is journalled as one of its web view, which it -captures. A web view's own ref is no page element: `click` and `set_widget_value` refuse it, pointing to -the page's elements, and `press_keys` sends to its page's focused element. +captures. A web view's own ref is no page element: `widget_click` and `widget_set_value` refuse it, pointing to +the page's elements, and `keyboard_press` sends to its page's focused element. An action runs synchronously in one task of the page. The element is scrolled into view and hit tested: one covered at its centre is refused naming what covers it, a disabled one and a file input are refused. A click sends what a person's does — pointer and mouse over, down (focusing the element), -up, then `click` — so the browser's default actions follow: a label reaches its control, a link -navigates, a submit button submits its form with itself as the submitter. `set_widget_value` sets a value +up, then `widget_click` — so the browser's default actions follow: a label reaches its control, a link +navigates, a submit button submits its form with itself as the submitter. `widget_set_value` sets a value through the element's own setter and sends `input` and `change`, which framework-controlled fields follow; a choice is picked by its option's text, a checkbox through a click, editable text through `insertText`. Keys go as `keydown`, `keypress`, the default action (text, Enter submitting the form @@ -3048,7 +3411,7 @@ command is unavailable or refuses (WebKit), the text goes in, or a character goe as the command would. `mouse_gesture` gestures send pointer events from a synthetic pointer whose capture the agent emulates while it is pressed, as a canvas that captures the pointer (the colour picker's spectrum) needs; a `down`'s button and modifiers stay pressed through later moves until its `up`, or -until any other gesture, click, `answer_dialog` or auto-answer press, a widget's included and even +until any other gesture, click, `dialog_answer` or auto-answer press, a widget's included and even one the tool then refuses, releases them where they were pressed. A move or an `up` keeps a press only on the agent that holds it: a page's own, or one of its configuration frames', which are told apart, so an `up` on a frame's page ends a press in the frame. Each agent has one synthetic pointer, which every @@ -3089,7 +3452,7 @@ after the action (a fragment change, which WebView2 reports no URL for on a page once the 300 ms have passed, by asking the page for its document's token, which a reload or a form posted to the same URL changes; not by `IsBusy()`, which WebView2 also reports while a page only works. Failing those, the reply's `page` says what the action changed on its page: the page outlines -itself before the action, a line per element (with its value, state and the notes `list_widgets` +itself before the action, a line per element (with its value, state and the notes `widget_list` gives it, such as a select's options) and per run of text, under an id the tool gives the action, and is asked afterwards which lines it lists now that it did not (`added`) and which it no longer lists (`removed`), counted as a multiset so an element rebuilt as it was, or text that moved, is no @@ -3103,7 +3466,7 @@ worked, and `posted` how many messages the page itself sent the host meanwhile, handler say. An outline is dropped once compared, and a page keeps at most 16, none past a minute. A change that comes later is the next snapshot's to show. -A URL a reply shows (`navigated`'s, `run_javascript`'s, a web view's value in `list_widgets`) reads +A URL a reply shows (`navigated`'s, `webview_run_javascript`'s, a web view's value in `widget_list`) reads `REDACTED` for the user info of its authority and for the value of each query or fragment parameter one of whose name's words names a credential (`token`, `key`, `secret`, `password`, `auth`, `session`, `signature`, `code` and the like; `redact_url()`), after OpenTelemetry's rule for URLs in telemetry. @@ -3135,12 +3498,12 @@ Limits: a web view in a popup window is not read, which in Orca is the setting t (`MarkdownTip`, a transient popup); a dialog whose web view is hidden is answered as a wx dialog; a page element's screenshot captures its whole web view, not a crop of the element; points in a frame that a CSS transform or zoom scales are where the untransformed frame would put them; a page button -whose handler outlasts `answer_dialog`'s 3 s may still be running when `cancel` or `close` ends the +whose handler outlasts `dialog_answer`'s 3 s may still be running when `cancel` or `close` ends the dialog natively; cross-origin frames other than plugin configuration UIs are listed but not read. ## Screenshots -`screenshot` captures on the UI thread and encodes off it. It has three targets. +`window_screenshot` captures on the UI thread and encodes off it. It has three targets. - `canvas`: the visible 3D view, the Design view while the Design tab is shown, exactly as drawn, toolbars and ImGui panels included (the Design view's sketch overlay and status line too), on @@ -3148,14 +3511,14 @@ dialog natively; cross-origin frames other than plugin configuration UIs are lis before the swap; it fails, saying why, when the canvas is hidden or mid-frame. That frame is often the first since a tool's change, yet it shows the change settled, since slider moves reach the toolpaths before they are drawn and the capture first draws any extra frames the change asked for: - a capture right after `set_view` shows the layers its slider shows and the legend laid out. + a capture right after `view_set` shows the layers its slider shows and the legend laid out. - `main`: the main window's client area from `capture_native_window()`: its own pixels or, where the capture reads the screen (X11, macOS 14.4 and later), our windows over it as well, never another application's, with every visible 3D canvas composited in from its canvas capture, since window capture loses OpenGL content on several platforms. - `dialog`: the topmost modal, captured like a window. - a widget's ref or locator: its top-level window captured like a window (a window that is not - modal, such as an object's settings, has no other target: `list_windows` gives its ref) and cropped to the widget, or the + modal, such as an object's settings, has no other target: `window_list` gives its ref) and cropped to the widget, or the canvas capture for a 3D canvas. A tab is cropped to its page, which must be the one shown. The journal records the locator. @@ -3266,11 +3629,11 @@ block is scaled to `max_dim` on the long edge (default 1280, clamped to 256–20 ## Recording -`start_recording` records what OrcaSlicer shows into a video while an agent, a replay, a script or a person -works, and `encode_recording` turns it into an MP4 to attach to an issue. Recording has to stay light, +`recording_start` records what OrcaSlicer shows into a video while an agent, a replay, a script or a person +works, and `recording_encode` turns it into an MP4 to attach to an issue. Recording has to stay light, since it runs while the app works: frames are kept as JPEG in a Matroska file (MJPEG), and the H.265 encode, which costs far more, comes after it. There is no audio. `McpRecorder` holds at most one -recording; `get_app_state.recording` shows it while it runs. +recording; `app_state.recording` shows it while it runs. The recorder starts with the runtime and needs none of the GUI instruments. It is built from the modal tracker, whose stack it draws, the UI generation its kept canvas frames belong to, whether the main window is @@ -3279,9 +3642,9 @@ Recording with the server off starts the runtime without the instruments: its ca are recorded all the same, and the person's own menus show as they do without automation. **Capture.** The UI thread captures a frame per tick of a one-shot `wxTimer`, which fires inside -modal loops too. `start_recording` takes the first frame in its own UI closure: it fixes the video's +modal loops too. `recording_start` takes the first frame in its own UI closure: it fixes the video's size (fit to `max_dim`, rounded down to even numbers for 4:2:0), and a failure fails the call before -any file exists. The `main` target is the main window as `screenshot` captures it, with the modal +any file exists. The `main` target is the main window as `window_screenshot` captures it, with the modal stack (`ModalTracker::stack()`, outermost first, so in stacking order) composited at each dialog's client offset, resampled to the main window's content scale off MSW. Modeless windows and native dialogs are left out: `wxTopLevelWindows` is creation order, not stacking order. Where the capture @@ -3308,7 +3671,7 @@ does. The pointer follows the same placement (`drawn_shift()`). It follows wx's AppKit's menu tracking and native dialogs do not send, so it is not drawn moving inside a menu. The result's `note` is the last frame's: which of these applies, then what that frame's capture approximated, so a macOS recording that fell back to drawing views says so. `capture_frame()` stores it -under the recorder's mutex, since `stop_recording` reports from another thread while a tick may be +under the recorder's mutex, since `recording_stop` reports from another thread while a tick may be capturing. The `canvas` target is `shown_canvas()`. A recording captures with `CaptureOptions::hide_covering` off, so X11 never hides and re-shows Action Replay at each frame. @@ -3342,9 +3705,9 @@ the Segment, Cluster sizes and Duration written as unknown and patched on close, closed (a crash) still reads up to its last frame. Matroska rather than AVI because frames keep their real, uneven times; one file rather than a folder of JPEGs because it plays as it is. -**Ending.** `stop_recording` first captures one more frame in a UI closure, when the UI thread can run +**Ending.** `recording_stop` first captures one more frame in a UI closure, when the UI thread can run it, so the last call's effect is in the video even if the timer has not ticked since. A recording ends on -`stop_recording`, after `max_seconds`, at 4 GiB, on a write error, when +`recording_stop`, after `max_seconds`, at 4 GiB, on a write error, when the replay or script that started it ends (`run_replay_job()`, which names a file still being written after 30 s as the result's `unfinished_recording`), when the endpoint closes for a client's (`close_client_scope()`; a run's carries on), and at exit. Ending from any thread sets a flag the next tick @@ -3356,23 +3719,25 @@ threads on the UI thread, and a step after the replay sees a closed file. At exi file, then drops what is still queued and leaves the sink to its threads, which own its state. A recording counts as active until its file is closed, for the one-at-a-time rule and for encodes. -**Encoding up front.** `start_recording` takes the Start Recording dialog's encoding keys (`encode`, +**Encoding up front.** `recording_start` takes the Start Recording dialog's encoding keys (`encode`, `encode_preset`, `codec`, `crf`, `speed`, `profile`, `keep_raw_video_file`), checked by `apply_recording_overrides()` with its defaults, the Balanced preset, and refuses `encode` without an ffmpeg before anything records. The encode deletes the `.mkv` once the MP4 is written unless `keep_raw_video_file` -keeps it, as every encode does (see Encoding). The recording keeps `encode_recording`'s arguments (`RecordingOptions::encode`), and the `stop_recording` +keeps it, as every encode does (see Encoding). The recording keeps `recording_encode`'s arguments (`RecordingOptions::encode`), and the `recording_stop` that reports it, once its file is closed, starts the encode with `start_encode()` (`McpToolsRecord.cpp`): a job of -its own, outside the journal (a replayed `start_recording` asks for it again), whose envelope the report +its own, outside the journal (a replayed `recording_start` asks for it again), whose envelope the report carries as `encode`, so the agent waits for the MP4 by that job's id. A recording that ended on its own -is encoded when the next `stop_recording` reports it; one nothing reports, a client's that ended with -the endpoint, is not encoded. An agent can still encode any recording later with `encode_recording`. +is encoded when the next `recording_stop` reports it; one nothing reports, a client's that ended with +the endpoint, is not encoded. An agent can still encode any recording later with `recording_encode`. -**From the app.** The Speed Dial commands `take_screenshot`, `start_recording` and `stop_recording`, which -the Help menu also has, give a person screenshots and recordings without an agent: a PNG of the main window, -and a recording of it for up to an hour. Both go in the person's Downloads folder unless they chose another. -`start_recording` and `stop_recording` are the tools too, of which this is the form with no arguments -(`with_person_form()`, see Tool catalog); given arguments, or `silent: true`, they are the tools above, and -`start_recording` then also records for up to an hour unless `max_seconds` says otherwise. +**From the app.** The Speed Dial tiles Take Screenshot, Start Recording and Stop Recording (the tiles +`take_screenshot`, `start_recording` and `stop_recording` of the commands `window_save_screenshot`, +`recording_start` and `recording_stop`), which the Help menu also has, give a person screenshots and +recordings without an agent: a PNG of the main window, and a recording of it for up to an hour. Both go in +the person's Downloads folder unless they chose another. `window_save_screenshot` takes no arguments and is +not listed; `recording_start {}` and `recording_stop {}` are the person's forms of the commands above +(`with_person_form()`, see Tool catalog): given arguments, or `silent: true`, they run from their +arguments, and `recording_start` then also records for up to an hour unless `max_seconds` says otherwise. Start Recording opens `RecordingDialog`, which splits its settings by the file they make. Record holds the JPEG quality of the `.mkv` and a switch for each overlay, the pointer and the caption, both off unless the person turns them on. Encode to MP4 holds whether ffmpeg encodes it once it ends, with a built-in preset or @@ -3380,17 +3745,17 @@ codec, CRF, speed and profile, and whether the `.mkv` stays beside the MP4 (off on); it is off and disabled when no ffmpeg is found, and says how to get one. A rail joins the two stages and shows whether the second runs. The dialog remembers what it starts with in AppConfig's `recording` section (`RecordingSettings`). The encode is -`encode_recording` itself, run by `McpRecorder::encode_when_closed()` as an unjournaled job that the runtime +`recording_encode` itself, run by `McpRecorder::encode_when_closed()` as an unjournaled job that the runtime follows (`follow()`) once the recording's file is closed (`McpRecorder::wait_closed()`, in the call's `ready`), so it can be cancelled like any encode. No reply -names the job, which only exists once the file is closed: an agent finds it in `get_app_state.jobs` and waits +names the job, which only exists once the file is closed: an agent finds it in `app_state.jobs` and waits for it by its id, as the command's description says. Start Recording starts the runtime without the endpoint when the server is off, as Action Replay and the Run Script panel do. The person's recording has its own owner (`kPersonOwner`), so neither a run's end nor the endpoint closing ends it. Whatever ends it tells the person where it went, in a notification whose button opens the folder: Stop Recording itself, which stops any recording, an agent's too, ending it as `stopped_in_app`; or `RecordingOptions::ended`, which the recorder runs on the UI thread when an agent's -`stop_recording`, the time or size limit, or a write error ends it, and which starts the encode. A second +`recording_stop`, the time or size limit, or a write error ends it, and which starts the encode. A second notification then names the MP4, or says why it could not be made. **The REC pill.** While a recording runs, whoever started it, the main window's tab bar shows a REC pill @@ -3415,7 +3780,7 @@ and a replay still running between them shows again once its step has faded. Cli captioned. With `pointer`, a `wxEventFilter` sees every mouse and click-type command event, a person's and the ones the GUI tools synthesize alike: mouse events move the pointer, presses add a ripple, and a button, checkbox, toggle or radio command with no press on it just before is a click made without the -mouse (`click`), shown at the control's centre. Events in windows the frame doesn't show, and in +mouse (`widget_click`), shown at the control's centre. Events in windows the frame doesn't show, and in windows hidden from automation, are ignored. Both are off unless asked for, `captions` and `pointer` turning on one each; without the pointer no filter is installed. @@ -3433,11 +3798,11 @@ only when it changes, as a coverage mask (`wxMemoryDC`, white on black) the enco What a caption adds must not leak secrets, although the screen itself shows whatever its fields show. A setting whose key names a password, API key, access code, token or secret (`is_sensitive_key()`; -`printhost_apikey` is a plain text field) shows `•••` for its value; `set_widget_value` shows its value only +`printhost_apikey` is a plain text field) shows `•••` for its value; `widget_set_value` shows its value only for a non-sensitive setting located by its key, since a field located by its label, or a ref not yet -resolved, may be a password box; and `press_keys` shows its chord, never its text. +resolved, may be a password box; and `keyboard_press` shows its chord, never its text. -**Encoding.** The bundled FFmpeg only decodes, so `encode_recording` runs the system `ffmpeg`: +**Encoding.** The bundled FFmpeg only decodes, so `recording_encode` runs the system `ffmpeg`: `ORCA_FFMPEG`, else `PATH`, else on macOS the Homebrew and MacPorts folders, which an app started from Finder doesn't have on its `PATH`. Its path is never a tool argument, so a call can't run an arbitrary program. The command keeps the recording's timestamps to the millisecond: variable frame rate (`-fps_mode vfr`, @@ -3451,7 +3816,7 @@ falls to almost nothing while the window is still and rises for the motion, wher spend it evenly; the video's length in the reply is the MP4's movie header's (`mp4_duration()`); an ffmpeg without the encoder is refused, naming what is needed. It runs without a console window, polled every 100 ms and terminated when the call is cancelled -(`NativeCommand::cancellable`: `cancel_job {job}` stops it through `JobRegistry::request_stop()`). On Windows it is +(`NativeCommand::cancellable`: `job_cancel {job}` stops it through `JobRegistry::request_stop()`). On Windows it is ended with `TerminateProcess()` on its handle and waited for on that handle, since `TerminateProcess()` returns before the process is gone and boost's `terminate()` closes the handle right after it; a child not gone within 5 s keeps its files, which the error names, and its source and destination stay reserved for @@ -3463,24 +3828,24 @@ call's own, renamed over the destination on success; the call's files (that, ffm read) are removed whatever the outcome, and no other call's. An encode is asked for to get the MP4, so once the MP4 is written it deletes the `.mkv` unless -`keep_raw_video_file` keeps it, the one name `encode_recording`, `start_recording` and the Start Recording dialog +`keep_raw_video_file` keeps it, the one name `recording_encode`, `recording_start` and the Start Recording dialog share; an encode that fails or is cancelled leaves it. It deletes only a recording this session made (`RecordingFiles::is_finished()`): any other `.mkv` is the person's own file, which stays, and the reply's `raw_video_file_deleted` and `note` say so. ## Preview data -`get_slice_stats` reads what the Preview shows for a plate without selecting the plate. Its tables +`plate_slice_stats` reads what the Preview shows for a plate without selecting the plate. Its tables come from the plate's `gcode_statistics_json()`, the serializer behind the slice reply's statistics and the exported `statistics.json`, which sums the moves as the legend does: `summary` is the slice reply's `plate_summary()` with the prepare and travel times and the travel distance; `features` has each feature type's seconds, share of the normal-mode print time and grams, keyed by the English `;FEATURE:` names (`ExtrusionEntity::role_to_string()`), and a `Travel` row (the shares leave out retractions, wipes, Z moves, tool changes and the prepare time, as the legend's do); `layers`, -paged, numbers layers as the slider's value (G-code layer index + 1, which `set_view {layer}` and -`get_app_state.preview` use) and carries each one's Z, so tools that number layers by the slider's label +paged, numbers layers as the slider's value (G-code layer index + 1, which `view_set {layer}` and +`app_state.preview` use) and carries each one's Z, so tools that number layers by the slider's label can be joined on Z. `objects` lists the G-code's object instances, which it names by object and -instance number; an entry gets the `list_objects` index only when one model object has that name. +instance number; an entry gets the `object_list` index only when one model object has that name. The wx-free shaping (`preview_features()`, `preview_layers()`, `preview_objects()`) is unit tested. `view` is the legend's state, read from the libvgcode viewer it draws from @@ -3491,7 +3856,7 @@ the layer slider's range with its Z, which feature types and options are visible type's colour range. The viewer recomputes ranges at its next frame after a legend change, so the closure draws the Preview first; the ranges span the whole print but count travels, wipes and Custom extrusions only while those rows are shown. For another plate `view` is null and a `note` says how to -show it. `get_app_state.preview` is the same state without the legend, or null when the Preview holds no +show it. `app_state.preview` is the same state without the legend, or null when the Preview holds no toolpaths of the current plate. The tool refuses while anything slices or exports (`Plater::is_slicing_any()`), since a worker may be @@ -3502,13 +3867,13 @@ a sliced 3MF, a plate the Preview has not shown keeps only the file's totals, wi refused with "slice again for layer data". The serializer's pass over the moves runs on the UI thread, about 15 ms on a plate of 4 million moves. -`set_view` changes the Preview through the functions the legend's own controls call +`view_set` changes the Preview through the functions the legend's own controls call (`GCodeViewer::pick_view_type()` for the combo, `toggle_extrusion_role_visibility()` and `toggle_option_visibility()` for its rows, `set_time_mode()` for the mode button), so a call leaves the Preview as the same clicks would. Picking a view type therefore shows every feature type again when it is Line Type, and is written to the app config as `preview_last_view_type`, which the "Last used" preview default restores. Before a slice there is no legend to pick from, and `view_type` only -sets the type the next toolpaths show. `legend` names rows as `get_slice_stats` lists them, in any case +sets the type the next toolpaths show. `legend` names rows as `plate_slice_stats` lists them, in any case and with `_` or a space between words, and clicks a row only when its state differs. Hiding a row the print lacks, a feature type or option some other print has, does nothing, since agents hiding everything but one feature name rows from the whole list. The viewer keeps one visibility set, so feature types can be set @@ -3523,25 +3888,28 @@ last. ## Print host uploads Sending G-code to a print host (OctoPrint, Moonraker, PrusaLink, Duet and the others in -`PrintHost::get_print_host()`) goes through the GUI's own dialog. The Speed Dial command -`send_gcode` ("Send G-code to printer host", the dialog's title) calls `Plater::send_gcode_legacy()`, -which the Print button calls for such a printer: it opens the Send dialog, whose file name an agent -sets with `set_widget_value` and whose Upload or Upload and Print button it presses with `answer_dialog`. +`PrintHost::get_print_host()`) goes through the GUI's own dialog. `printer_send`, whose tile is +`send_gcode` ("Send G-code to printer host", the dialog's title), runs `Ops::send_gcode_to_host()`, which +calls `Plater::send_gcode_legacy()`, as the Print button does for such a printer: it opens the Send +dialog, whose file name an agent +sets with `widget_set_value` and whose Upload or Upload and Print button it presses with `dialog_answer`. The plate is then sliced if needed, its G-code exported in the background process, and the upload queued. Host settings are printer settings (`host_type`, `print_host`, `printhost_apikey`, and -`bbl_use_printhost` on a Bambu printer), written with `set_settings {scope: "printer"}`. Where the +`bbl_use_printhost` on a Bambu printer), written with `settings_set {type: "printer"}`. Where the Print button would not send to a print host, the command fails and says why: the printer prints through the Bambu network or printer agents (`PresetBundle::use_bbl_network()`, `use_printer_agents`), or has no `print_host`, the condition `MainFrame::can_send_gcode()` gives the -button. It is journaled like any `run_action`, so a replay uploads again. +button. It is journaled like any call, so a replay uploads again. Its arguments (the plates, the printer, the +file name, the storage) belong to the design of printing and the Device tab, which `printer_send` leaves to +the dialog. -`get_app_state.uploads` lists the session's rows of the upload queue (`PrintHostQueueDialog`), as the +`app_state.uploads` lists the session's rows of the upload queue (`PrintHostQueueDialog`), as the queue window shows them: `id` (its ID column, from 1), `state` (`queued`, `uploading`, `error`, `cancelling`, `cancelled` or `completed`), `progress` (percent), `host`, `filename`, and `error`, the queue's message, when there is one. Uploads a person started are listed too, so an agent can wait for any of them by polling. A failed upload also opens the queue's error dialog (`PrintHostQueueDialog::on_error()`), which blocks changes until it is closed with -`answer_dialog`. +`dialog_answer`. Two properties of the queue make its rows a reliable answer. A row reads `completed` only once the host has accepted the file: while the bytes go out, `PrintHostJobQueue::sent_percent()` stops at 99, @@ -3555,15 +3923,15 @@ thread's progress and error events go to, so the row exists before any of them i ## Replays and the journal ```jsonc -{ "orca_replay_version": "0.1.0", "name": "repro #12345", +{ "orca_replay_version": "0.2.0", "name": "repro #12345", "vars": {"model": "${replay_dir}/part.stl"}, "steps": [ - {"tool": "open_files", "args": {"paths": ["${vars.model}"]}}, - {"tool": "slice", "expect": {"/plates/0/outcome": {"eq": "ok"}}}, - {"tool": "run_action", "args": {"id": "orca_command:open_preferences:orca"}, "await": false, "save_as": "prefs"}, - {"tool": "answer_dialog", "args": {"dialog": {"title": "Preferences"}, "button": "close"}}, - {"tool": "wait", "args": {"for": "job", "job": "${jobs.prefs}"}}, - {"tool": "screenshot", "args": {"target": "canvas", "save_path": "${out_dir}/preview.png", "overwrite": true}} + {"tool": "project_import", "args": {"paths": ["${vars.model}"]}}, + {"tool": "plate_slice", "expect": {"/plates/0/outcome": {"eq": "ok"}}}, + {"tool": "window_open", "args": {"window": "preferences"}, "await": false, "save_as": "prefs"}, + {"tool": "dialog_answer", "args": {"dialog": {"title": "Preferences"}, "button": "close"}}, + {"tool": "app_wait", "args": {"for": "job", "job": "${jobs.prefs}"}}, + {"tool": "window_screenshot", "args": {"target": "canvas", "save_path": "${out_dir}/preview.png", "overwrite": true}} ]} ``` @@ -3572,23 +3940,25 @@ an exported replay is stamped with. A minor version adds tools or fields, so a b its own major version up to its own minor version; a major version renames or removes them. While the major version is 0 any change may break a replay, so a build reads only its own minor version. A replay a build can't read is refused before any step runs, saying whether it needs a newer -OrcaSlicer. +OrcaSlicer (`version_error()`). Format `0.2.0` names the commands as the Tool catalog names them, so a +replay of an earlier format, written with other names, is refused with that message rather than with an +unknown tool in its first step. -A replay is JSON with comments allowed. `run_replay` runs a file or an inline replay as a job whose +A replay is JSON with comments allowed. `replay_run` runs a file or an inline replay as a job whose steps call tools as its children (`ToolContext::call_child()`), so steps are not journaled and a -replay's `wait {for: "idle"}` doesn't wait for the replay. An inline replay is the replay object or +replay's `app_wait {for: "idle"}` doesn't wait for the replay. An inline replay is the replay object or its JSON text, comments included, so a caller holding a replay file's text passes it as read; the journal records the text as the object it parses to. Every string is substituted recursively with `${replay_dir}`, `${out_dir}`, `${env:NAME}`, `${vars.NAME}` and `${jobs.NAME}`; a string that -is just one placeholder becomes the referenced JSON value. A replay's own `run_replay` step +is just one placeholder becomes the referenced JSON value. A replay's own `replay_run` step gives its nested replay as an object: the outer run splices placeholders into a text replay as plain text, so a value holding a quote or a backslash, such as a Windows path, breaks its JSON. A step that returns a job is awaited, up to `timeout_s` (default 120), before its `expect` is checked; a wait that times out with a dialog open names the topmost one, since a step can't answer a dialog it opened. `"await": false` returns the job at once and stores it under `save_as`, so later steps can answer a dialog it opened and then -`wait` for it. `expect` maps JSON pointers into the result to matchers (`eq ne gt ge lt le contains +`app_wait` for it. `expect` maps JSON pointers into the result to matchers (`eq ne gt ge lt le contains regex exists empty`). A failed step or expectation stops the run unless the step is `optional`. -Auto-answer rules registered by a replay end with it. `vars` passed to `run_replay` override the +Auto-answer rules registered by a replay end with it. `vars` passed to `replay_run` override the replay's. A step naming an unknown tool makes the replay invalid before anything runs; so does any field of the wrong type, and broken JSON is reported with its line and column. The result, also written to `/result.json`, is `{passed, name, failed_step, steps: [{index, tool, args, ok, @@ -3600,9 +3970,9 @@ file's `out_dir` defaults to `.out` beside it. An inline replay's d `replay-` in the output folder (`output_dir()`), which is also its `${replay_dir}`. The engine (`McpReplay.cpp`, wx-free) and the job around it (`run_replay_job()` in -`McpToolsReplay.cpp`) are shared by `run_replay`, `--run` and Action Replay. A run +`McpToolsReplay.cpp`) are shared by `replay_run`, `--run` and Action Replay. A run stops before its next step, and stops waiting on a step's job, once the runtime stops or a stop was -asked for any job in its lineage (`JobRegistry::request_stop()`), so a nested `run_replay` stops with +asked for any job in its lineage (`JobRegistry::request_stop()`), so a nested `replay_run` stops with the run that holds it. Stop requests last the session, and `JobRegistry` records each job's ancestor chain when it is created, so a descendant still reaches its root after finished ancestors are forgotten. A step during which the stop came is failed as `cancelled` whatever it returned (a @@ -3628,8 +3998,8 @@ directory, since the GUI changes it. wx ignores `OnExit()`'s return value, so `G ### Action Replay -File › Action Replay… and the Speed Dial command `open_action_replay` (an id kept because exported -replays and agent sessions already call it) open `ActionReplayDialog`, where a person opens or writes a +File › Action Replay…, `window_open {window: "action_replay"}` and its Speed Dial tile (whose id is +`open_action_replay`) open `ActionReplayDialog`, where a person opens or writes a replay file, reads its steps and replays it whole or one step at a time. It is a `WebViewHostDialog` page (`resources/web/dialog/ActionReplay/`), modeless and one at a time (`MainFrame::show_action_replay()`). It takes JSON replay files only. A `.py` file, picked with the picker's "All files" or dropped on the @@ -3667,25 +4037,27 @@ message keys, and `code_editor.js` hands them to `ace.config.setMessages()`. Eac chords its editor binds (`editor_keys`), which the main frame's menu rule reads (Keys, under Run Script panel). Action Replay's language is a JSON mode of its own (`orca_replay`, `replay_editor.js`). -`start_replay_run()` (`McpPersonRun.cpp`) runs the replay as a job of `run_replay`'s kind but outside the +`start_replay_run()` (`McpPersonRun.cpp`) runs the replay as a job of `replay_run`'s kind but outside the session journal, since a person's run is not an agent's call, with the person mark. The runtime follows the job (`follow()`) past a `running` or `blocked_by_dialog` reply to its result, which it posts once. Step reports and the result reach the dialog through the runtime's dispatcher as `PersonRun` events, which the dialog drops once it is gone. `PersonRun::stop()` latches, so a stop asked before the job exists still counts, requests the stop for the job (`JobRegistry::request_stop()`) -and cancels its operation as `cancel_job` does. Every call the run and its nested replays make -then sees `ToolContext::cancelled()`, so a step that waits, such as `wait`, returns at once. `suspend()` and `stop()` +and cancels its operation as `job_cancel` does. Every call the run and its nested replays make +then sees `ToolContext::cancelled()`, so a step that waits, such as `app_wait`, returns at once. `suspend()` and `stop()` stop every run first (`stop_followed()`), while the main window they run in is still the current one. Before a run the dialog describes each step with `describe_step()` (`McpReplaySummary.cpp`, wx-free): what it acts on, and flags for effects beyond the open project (writes a file outside the output folder, changes presets, replaces the project, sends to a printer). It reads the arguments after substitution, and nested replays as their run sees them: an inline one with the outer -replay's placeholders already applied, as `run_replay` substitutes the whole step first, and a file +replay's placeholders already applied, as `replay_run` substitutes the whole step first, and a file with its own vars and output folder; a step whose effect can't be read (a plugin action, a nested replay too deep or unreadable) gets every flag. Flags only inform. A -replacing step either checks unsaved changes itself (`new_project`, `open_files` of a project, -`generate_calibration_test`) or goes through the app's own save question (`close_with_confirm()`). When the project +replacing step either checks unsaved changes itself (`project_new` and `calibration_generate_test` called with +their arguments, `project_open` of a project) or goes through the app's own save question +(`close_with_confirm()`): a call of a tile's arguments, which asks as the tile does (`project_new {}`, +`project_open {}`, `calibration_generate_test {test}`), and `project_open` of a G-code file. When the project has unsaved changes and the steps to run hold a step of the first kind, or one of the second kind with a step that can answer a dialog, the dialog asks whether to save first. Yes saves; No lets the run's replacing tools treat the run as `discard_changes: true`: the run's handler marks its job as it starts @@ -3693,9 +4065,9 @@ run's replacing tools treat the run as `discard_changes: true`: the run's handle call's lineage when it checks (`discard_allowed_in()`), so changes are dropped only when a step really replaces the project. The runner never answers the app's own question. -The window is named `kHiddenFromAutomation`: `list_widgets` and locators skip it, `list_windows` lists +The window is named `kHiddenFromAutomation`: `widget_list` and locators skip it, `window_list` lists it as hidden with no ref, -`run_javascript` never picks its web views, a key sent without a target never goes to the focus inside it, and on X11, +`webview_run_javascript` never picks its web views, a key sent without a target never goes to the focus inside it, and on X11, where a window capture reads the screen, it hides for the moment of the capture. Every prompt and file dialog it opens is named so too, so no auto-answer rule a replay registers answers the person's own question. Its own wording is @@ -3704,63 +4076,63 @@ agents read in English, is shown as a detail under a translated lead. Tool title `L()` so the dialog can show them translated while `tools/list` keeps the English. The session journal records client calls to journaled tools in order: every mutate tool, plus -`wait` and `screenshot`, which a replay needs. It keeps at most 5000 calls and 64 MiB of their +`app_wait` and `window_screenshot`, which a replay needs. It keeps at most 5000 calls and 64 MiB of their arguments (serialized), so a long CAD run's large `sketch_draw` calls can't grow it without bound: after each change it drops the oldest calls whose outcome is known until it is within both. A call still waiting for its reply or its job keeps its place, so calls still waiting may hold it over for a while; once they finish they are dropped like any other call, oldest first, and only while the journal is still over a bound. GUI tools record locators instead of refs through -`ToolContext::set_journal_args()`. `export_replay` returns it, and with `path` writes it, through `Journal::to_replay()`; `clear` +`ToolContext::set_journal_args()`. `replay_export` returns it, and with `path` writes it, through `Journal::to_replay()`; `clear` starts a new recording. `Journal::to_replay()` drops failed calls and an input call that only listed the menu it opened when the next call repeats it with a `popup_item` (otherwise it stays: its right click changed the selection), turns a call that returned a job into a step with `"await": false` and -`"save_as": "jobN"`, points the `wait {for: "job"}` that followed at `${jobs.jobN}` (dropping waits +`"save_as": "jobN"`, points the `app_wait {for: "job"}` that followed at `${jobs.jobN}` (dropping waits on jobs it never saw start) and rewrites screenshot paths to `${out_dir}/`. It moves a -recording's path there too (`start_recording` records the one it used), and an encode's `save_path`, and -an encode's source when an earlier `start_recording` recorded it; another source stays where it is. A -`run_action` of a command's tile, named by its key or its full id, is rewritten as a call of that command, +recording's path there too (`recording_start` records the one it used), and an encode's `save_path`, and +an encode's source when an earlier `recording_start` recorded it; another source stays where it is. A +`action_run` of a command's tile, named by its key or its full id, is rewritten as a call of that command, inside the tile's `{id, args}`, so a recording started from the Start Recording tile moves the same way. A call that runs as a job is judged by its job's final result, not by its reply. `McpCore` tells the journal the job's id when it starts it (`Journal::job_started()`) and its result when the handler returns (`Journal::job_ended()`), before `JobRegistry::finish()`, so an export right after the -`wait` that saw the result already knows it. A job that fails after its reply came back as +`app_wait` that saw the result already knows it. A job that fails after its reply came back as `running` is dropped like a call that failed at once, so a replay never repeats a call that did nothing (a slow CAD rebuild that then fails). A call whose outcome is still open, because its job -is still running or it has not replied yet, is left out, and `export_replay`'s reply lists it in +is still running or it has not replied yet, is left out, and `replay_export`'s reply lists it in `left_out_running: [{tool, job}]` (`job` is absent for a call that is not one); a later export includes it once its job has succeeded. A call whose reply was `blocked_by_dialog` stays in the replay while its job runs and whatever its job's result: the steps after it answer its dialog, and a replay without it would fail at the first of them. A call whose job was still running when a later -call acted with a modal open (`answer_dialog`, or a recover tool's input while +call acted with a modal open (`dialog_answer`, or a recover tool's input while `UiInvoker::open_dialogs()` lists one) stays the same way, whether it had replied yet or not, since that dialog may be one its job opened; the journal can't tell whose dialog it was, so it keeps every such job, as a step with `"await": false`. Its replayed reply can come before the dialog opens, so each -call that acted with a modal open is preceded in the replay by `wait {"for": "dialog"}`, expected to +call that acted with a modal open is preceded in the replay by `app_wait {"for": "dialog"}`, expected to be satisfied. Only the call's own job counts as its job: a -`wait` that timed out names the job it waits on in its reply, and stays a plain step. +`app_wait` that timed out names the job it waits on in its reply, and stays a plain step. ## Python scripts A Python script is a `.py` file or a code string that runs on the plugin interpreter as an embedded macro: the main program of a run inside OrcaSlicer, with the whole plugin API (`orca.host`), without being packaged as a plugin. A person runs one in the Run Script panel or with `--run file.py`; an agent sends one with -`run_script {code, args, timeout_s, filename}`; a plugin's code may call `run_script` too. A script that runs +`script_run {code, args, timeout_s, filename}`; a plugin's code may call `script_run` too. A script that runs under `python file.py` runs the same way here, and code written for a plugin's `execute()` (windows, progress, presets, storage) runs from a script unchanged. A script is not a plugin: it gets no permission prompt and no grants, is never in the Plugins list, and ends when its work ends, leaving nothing loaded. It always runs; one setting decides whether the plugin permission checks hold it (The setting, below). **Entry contract.** `run_python_code()` (`plugin/PythonScriptRunner.cpp`) runs the code on the calling thread, the -MCP job that runs `run_script`, holding an interpreter lease and the GIL, as a session with one file work (Run +MCP job that runs `script_run`, holding an interpreter lease and the GIL, as a session with one file work (Run Script panel, below). The code is text, compiled as Python compiles any code string, so a coding line in it changes nothing; a file's bytes are decoded first as Python reads a source file, by its BOM or its PEP 263 declaration, else as UTF-8 (`decode_python_source()`). It runs as the main program, in a `types.ModuleType("__main__")` of its own, with `args` bound and `orca` importable. A run is a *file run* when `filename` names an existing file (a saved script's in the panel and `--run`'s do): `__file__` and `sys.argv` (`[path]`) name it, its folder serves its imports, and its PEP 723 dependencies are installed first. -Any other name (the default ``, a bare traceback name) is code sent as text, which gets none of that; +Any other name (the default ``, a bare traceback name) is code sent as text, which gets none of that; `filename` still names it in tracebacks. The value left in `result` is read once when the body returns; in code sent as text, one that is not JSON (a dict with string keys, a list, a string, a finite number, a boolean or None, nested) makes the run `raised`, while in a file run, where a standalone script may well have a variable of that @@ -3768,7 +4140,7 @@ name, it is no result, and the output ends with a line saying it was not JSON. ` finishes the run. Output is captured up to 256 KiB by a stream installed once over `sys.stdout` and `sys.stderr` that routes writes by the run bound to the writing thread: the run's own thread, the threads it starts, its pool tasks and its window callbacks; other threads print through. The outcome is `finished`, `raised` (with the -traceback), `cancelled` or `timed_out`, reported in a successful result, as `run_replay` reports a failed step. +traceback), `cancelled` or `timed_out`, reported in a successful result, as `replay_run` reports a failed step. **The run scope.** `PythonRunScope` (`plugin/PythonRunScope.hpp`) is the run's state that its threads, pool tasks and window callbacks share: identity, file, tool bridge, the work it waits for, admission, and whether its UI is @@ -3854,8 +4226,8 @@ records its modules only after its import returns), and then runs at the next en run's code, on its thread, under its identity and watcher, with the output in its capture. A daemon thread still running after the run sees the run's globals, and its evicted helpers', cleared, and is refused tool calls. -**Cancellation.** A watcher thread interrupts the run with `PyThreadState_SetAsyncExc` when `cancel_job {job}` stops -the job (`run_script` is `cancellable`) or the time budget (`timeout_s`, default 300 s; the panel's session has +**Cancellation.** A watcher thread interrupts the run with `PyThreadState_SetAsyncExc` when `job_cancel {job}` stops +the job (`script_run` is `cancellable`) or the time budget (`timeout_s`, default 300 s; the panel's session has none, since its Stop ends what runs) runs out, again every second until it ends. What it interrupts follows the run's phase, which is set, and read before each interrupt, under the GIL: in *Body* (the code) and *Exit* (`atexit` functions, the result's own code, the UI teardown, the namespace's finalizers, the folder's teardown, dropping what the script @@ -3883,7 +4255,7 @@ code. The install isn't covered by the watcher; uv's 120 s timeout bounds it. **Identity.** A person's script runs under the audit identity `(script)`, an agent's under `(mcp)` (`kScriptIdentityPerson`, `kScriptIdentityAgent`); `JobRegistry::person_in()` tells them apart by the run's lineage, since the jobs of Action Replay, the panel, `--run` and a person's pick of a long command carry the -person mark while they are unfinished (Threading). So a `run_script` that the panel's session calls through +person mark while they are unfinished (Threading). So a `script_run` that the panel's session calls through `orca.host.tools` runs as the person's too. The plugin audit ([plugin-permissions.md](plugin-permissions.md)) judges a script under its identity as it judges a plugin, with one difference: a script has no install state to hold a grant, so it is never asked, and what the implicit @@ -3892,11 +4264,11 @@ callbacks of a run carry its identity. A run owns what its calls leave behind, a (`begin_run_scope()`): auto-answer rules, a recording and a held press end with it. No plugin has one of the identities as its key, so a plugin is never judged as a script: a local plugin's key keeps only the letters, digits, `_`, `-` and `.` of its file name (`make_local_plugin_key()`), and a cloud plugin's is its UUID. A -plugin's `run_script` runs under the plugin's own identity and grants instead, with the same +plugin's `script_run` runs under the plugin's own identity and grants instead, with the same main-program environment, but its windows, callbacks and storage stay the plugin's. **The setting.** One switch, `python_scripts_unrestricted`, off by default, decides how a person's scripts and an -agent's `run_script` are judged (a plugin's `run_script` is the plugin's and ignores it), and the command line's +agent's `script_run` are judged (a plugin's `script_run` is the plugin's and ignores it), and the command line's `--unrestricted-scripts` turns it on for one run without writing it. Off, a script is restricted: its Python code reads and writes OrcaSlicer's data folder, reads the resources folder, the standard library and, in a file run, the folder of its file (`PythonRunScope::allow_folder_reads()`, a scoped root on @@ -3912,7 +4284,7 @@ see it and `ModalTracker` leaves it off the stack, so no dialog tool or auto-ans command line option writes the key. Two functions keep the saved setting apart from the value in force: `python_scripts_setting()` is the key, which the dialog and the Preferences row show and the dialog writes, and `python_scripts_unrestricted()` is the key or the run's flag (`set_python_scripts_for_run()`, called once at -startup), which the audit gets and `get_app_state.python.scripts_unrestricted` reads, so an agent learns what its +startup), which the audit gets and `app_state.python.scripts_unrestricted` reads, so an agent learns what its script may do before it plans a run rather than from a refusal. While the flag is on, the row adds "(on for this run by the command line)" and the dialog says the flag is on under its checkbox. @@ -3920,8 +4292,9 @@ run by the command line)" and the dialog says the flag is on under its checkbox. (message boxes, progress dialogs, HTML windows, dock panels, notifications), the staged preset update, bundle reload and the 3MF copy; nothing is plugin-only. `orca.host.plugin.storage()` is a script's own folder, the folder of its file, which a restricted script reads but doesn't write; code sent as text has none. `orca.host.tools.call(name, args)` and `run_replay(replay, vars)`, whose -replay is a dict or its JSON text (`plugin/host/PluginHostTools.cpp`), reach the tools from any thread of the run -while it lasts, through the run's bridge: its calls are `ToolContext::call_child()` of the `run_script` job, so +replay is a dict or its JSON text and which calls `replay_run` (the Python API keeps its own function names; +`plugin/host/PluginHostTools.cpp`), reach the commands by their names from any thread of the run +while it lasts, through the run's bridge: its calls are `ToolContext::call_child()` of the `script_run` job, so each has its tool's guards, admission and undo, and the GIL is released while it waits. At the end the bridge closes, and the run waits for calls already inside it before its `ToolContext` goes. An error result raises `orca.host.tools.ToolError` with its data as `details`. Code with no audit identity at all is refused. @@ -3944,17 +4317,17 @@ counted as active work; it runs on the UI thread, so it is refused tool calls (t and hands its work to the script's own code, through a `queue.Queue` say, which can call them. While a modal the run opened is up, tool calls that change the project are refused by the modal guard, the run's own included, so interactive macros use modeless windows. A script's dock panel keeps its saved layout under the script identity and -its title. A plugin's `run_script` leaves all of this to the plugin. +its title. A plugin's `script_run` leaves all of this to the plugin. -**Idle.** A `run_script` job doesn't count as busy for `wait {for: "idle"}` (`JobRegistry::set_idle()`); the +**Idle.** A `script_run` job doesn't count as busy for `app_wait {for: "idle"}` (`JobRegistry::set_idle()`); the calls it makes, and what they start, do. A macro waiting for the person in its window would otherwise hold every agent's idle wait, and a `tools/mcp` driver run from the panel against the same app would wait on its own run. -**Journal and replay.** `run_script` is journaled as one step holding its code, kept when the code failed -partway; its tool calls are not journaled. In a replay a `run_script` step's `code` is never +**Journal and replay.** `script_run` is journaled as one step holding its code, kept when the code failed +partway; its tool calls are not journaled. In a replay a `script_run` step's `code` is never substituted, and a step whose outcome is not `finished` fails. -**The reference.** `search_python_api` serves the reference `python_api_reference()` builds from the running +**The reference.** `script_search_api` serves the reference `python_api_reference()` builds from the running build's `orca` package: `orca.host`, and the classes, events and pages plugins build on. It walks the modules and lists each public class, function, method, property, named instance (such as `orca.host.preset.process`) and constant (such as `orca.host.ui.PD_CAN_ABORT`) with its signature and @@ -3971,8 +4344,9 @@ matrix arrays need and which the bundled Python lacks unless a file run's PEP 72 ### Run Script panel -File › Run Script (the Global shortcut Ctrl+Shift+T, ⌘⇧T on macOS) and the Speed Dial command -`toggle_run_script_panel` show or hide the Run Script panel (`RunScriptPanel`, page `resources/web/dialog/RunScript/`), +File › Run Script (the Global shortcut Ctrl+Shift+T, ⌘⇧T on macOS) and the command `script_toggle_panel`, whose +Speed Dial tile has the id `toggle_run_script_panel`, show or hide the Run Script panel (`RunScriptPanel`, page +`resources/web/dialog/RunScript/`), a dock pane of the Plater under the 3D view and the sidebar, where a person edits a `.py` file in `# %%` cells and runs a cell, the whole file or a console line in a live session. Showing it selects Prepare when the current tab is neither Prepare nor Preview; the menu item's check mark is whether it is on screen. @@ -4008,8 +4382,8 @@ with streaming, quoting, Cell events and cell results off and a stop closing eve keeps the run described above. **The session job.** `start_python_session()` (`McpToolsPython.cpp`) hosts the panel's session as an unjournaled -person's `run_script` job (`run_python_session_job()`), which the runtime follows (`follow()`) on a thread that -`stop()` joins and `stop_followed()` stops. The job is idle for `wait {for: "idle"}` as any `run_script` job is, so agents' and +person's `script_run` job (`run_python_session_job()`), which the runtime follows (`follow()`) on a thread that +`stop()` joins and `stop_followed()` stops. The job is idle for `app_wait {for: "idle"}` as any `script_run` job is, so agents' and plugins' runs overlap with it, sharing no state, tracebacks included. It owns what its calls leave behind for the whole session, as a run does (`begin_run_scope()`): auto-answer rules, recordings, held presses. Between works its rule layer is paused (`ModalTracker::set_paused()`; the rules listing shows it as paused), so a rule a cell @@ -4017,7 +4391,7 @@ registered never answers the person's own dialogs between runs and answers again the session registers between works starts paused, and leaves the dialog open then to the person too), and its held presses are released as each work ends (`release_run_presses()`). Its `orca.host.tools` calls are child calls of a `LineageNode`, a running idle job under the session's job that only parents calls: a stop requests the stop for the -node and cancels its operations (`cancel_operations_of()`), so every call in flight, inline ones such as `wait` +node and cancels its operations (`cancel_operations_of()`), so every call in flight, inline ones such as `app_wait` included, returns at once while the session goes on, and the next work after a stop starts once that cancelling is done, under a renewed node. @@ -4034,7 +4408,7 @@ what the teardown runs can be interrupted, as a stop asked once the session is e nothing else was live; then its windows close and its folder's helpers are evicted. **Lifetime.** `RunScriptPanel` is owned by `GUI_App`, so the script's text, file, unsaved state, session and recent -scripts (AppConfig `run_script` › `recent`, newest first, at most 10) outlive the pane (`RunScriptPane`), which a +scripts (AppConfig `script_run` › `recent`, newest first, at most 10) outlive the pane (`RunScriptPane`), which a main-window rebuild (a language change) destroys: `MainFrame::shutdown()` calls `main_window_closing()`, which stops and ends the session and stops reading its events, and the end of `GUI_App::recreate_GUI()` calls `main_window_rebuilt()`, which builds the pane again, with an empty console, if it was shown. The pane is built the @@ -4049,7 +4423,7 @@ every row. The page lays a JSON result out (an array or object stays on one line result whose layout would be more than four times as long stays on one line), keeping its numbers and strings as Python wrote them, in the editor's JSON colours, and counts what it shows toward the console's 2 MiB. Besides each cell's bar in the margin, the toolbar's Cells menu draws dividers, header bands or shaded cells, and can tint the cell at the cursor, as Ace -full-line markers behind the text for the cells on screen; the choice is AppConfig `run_script` › `cell_style` and +full-line markers behind the text for the cells on screen; the choice is AppConfig `script_run` › `cell_style` and `highlight_cell`. Ace has no cells, so the + in the margin a row below the last line, which adds a `# %% ` cell at the end, is the page's own element, placed after each render. The divider between the editor and the console sets the editor's share of the width, so a resized pane keeps its proportions; a drag stops at 220 px of editor and 200 px of @@ -4057,14 +4431,14 @@ console, and its arrow keys, Home and End and double-click (back to 60%) work as grip hide a side, as does a drag that ends 48 px past a side's smallest width; a hidden side leaves a strip at its edge that brings it back at its width: the editor's shows each cell's bar, the console's a dot for a run going, output not seen, or a failed run. The console's side hides only while it shows the console, never the start page. The share and -the hidden side are AppConfig `run_script` › `split` and `hidden_side`, saved when a drag +the hidden side are AppConfig `script_run` › `split` and `hidden_side`, saved when a drag ends rather than as it moves. **Out of the tools' reach.** Like Action Replay's page, the page navigates nowhere but its own loads: a dropped `.py` opens in the panel, and any other navigation is vetoed. The pane is named `kHiddenFromAutomation`, as are the frame it floats in (`AuiMgr::CreateFloatingFrame()`) and every prompt and file dialog it opens. `skipped_by_walks()` keeps the walks of -`list_widgets`, locators and `run_javascript`'s search for a web view out of it, and a key sent without a target never -goes to the focus inside it, so a script never acts on the panel that runs it. `list_windows` lists the floating +`widget_list`, locators and `webview_run_javascript`'s search for a web view out of it, and a key sent without a target never +goes to the focus inside it, so a script never acts on the panel that runs it. `window_list` lists the floating frame as hidden, with no ref. Docked, the panel is part of the main window and shows in its screenshots and recordings; floating, it is a window of its own and stays out of them, as the person's own dialogs do. @@ -4086,7 +4460,7 @@ that has the focus (the console prompt) takes the forwarded Undo, Redo and Selec A plugin's code calls the tools through `orca.host.tools`, with no permission of its own: any loaded plugin can do what an agent can, work in the GUI, answer dialogs, replace the project, write presets and files. The tools run OrcaSlicer's own code, which the plugin audit doesn't judge, so a plugin's grants bound its Python -code and not what it asks the tools to do. A plugin's `run_script` is the plugin's own code: its identity and +code and not what it asks the tools to do. A plugin's `script_run` is the plugin's own code: its identity and grants, its windows and storage, though it runs as a main program as any script does. A plugin's call waits for the UI thread, so it comes only from a thread nothing there waits for: a Script @@ -4099,8 +4473,8 @@ call then holds a lease the runtime's drain waits for. A caller that stops waiti marks its admission abandoned, so no lease is taken that nobody releases. The call runs as `McpCore::call_plugin()`: a top-level job owned by the plugin (`JobRegistry::owner()`), never journaled, whose children inherit the plugin -(`ToolContext::caller_plugin()`). The session tools are scoped to the plugin: `export_replay` is refused, -and `cancel_job {job}` and `wait {for: "job"}` act only on its own jobs (`require_own_job()`). What its calls +(`ToolContext::caller_plugin()`). The session tools are scoped to the plugin: `replay_export` is refused, +and `job_cancel {job}` and `app_wait {for: "job"}` act only on its own jobs (`require_own_job()`). What its calls leave behind (auto-answer rules, a recording, a held press) belongs to the plugin's scope (`begin_plugin_scope()`), which ends when the plugin unloads. From the moment the plugin manager unloads it, no call of the plugin starts, inline or as a job, nor a child of one of its jobs, a call admitted just @@ -4123,10 +4497,10 @@ Its operations are staged and offered once the plugin's load has committed (`PluginOperations::activate()`, in one step under the lock an unload's withdrawal takes); any exit of a load that did not commit, an exception included, drops them, and they are withdrawn when the plugin unloads. An operation is reached as -`plugin..` through `call_tool`, `orca.host.tools.call` and replay steps, and never +`plugin..` through `tool_call`, `orca.host.tools.call` and replay steps, and never appears in `tools/list`: they are a source of the command catalog (`CommandSource`, added by -`register_api_tools()`), whose `CommandCatalog::lookup()` resolves those names after the catalog's own -commands, and whose `source_commands()` `search_tools` lists. +`register_plugin_operations()`), whose `CommandCatalog::lookup()` resolves those names after the catalog's own +commands, and whose `source_commands()` `tool_search` lists. It runs as a job, under the mutate guard and journaled when it changes something, under the inspect guard otherwise; its handler runs under the plugin's identity and grants, and each call is logged with the plugin and the caller. A call is refused once the plugin has unloaded, by the plugin manager's state, and @@ -4134,29 +4508,31 @@ by `PluginOperations::invoke()` when the operation found is no longer the one of offered again by a new load). The call's job is the caller's, so an operation already running when its plugin unloads runs to its end; its own tool calls are refused from then on. -**`search_tools` and `call_tool`.** `search_tools` reads one inventory (`search_commands()`): every +**`tool_search` and `tool_call`.** `tool_search` reads one inventory (`search_commands()`): every command of the catalog and the operations its source holds. `{tool}` gives any command's description, -schema, group, `read_only` and `listed`, and its examples when it has some (the Design commands, and `undo` -and `redo` with them), and a call with neither `tool` nor `query` lists every name. Its `group` narrows the names and +schema, group, `read_only` and `listed`, and its examples when it has some (the Design commands, `undo` and +`redo`, and the commands that close a gap the menu rows left, such as `object_fix`, `printer_install` and +`plugin_enable`), and a call with neither `tool` nor `query` lists every name. Its `group` narrows the names and the command matches to one group (see Tool catalog); the other catalogs' matches beside them are not narrowed. Its search by words is the one search across catalogs: the best five commands that match (more with `limit`), each `{name, group, summary, listed}`, the summary the first sentence of its description. A -listed command's schema is in `tools/list`; one that is not listed, a Speed Dial command, a Design command or a +listed command's schema is in `tools/list`; one that is not listed, a menu row with no arguments, a Design +command or a plugin's operation, also carries its `input_schema`, and its description where that says more than the summary, which nothing else shows (an operation's first sentence only says a plugin offers it). A command is matched on its key, its title and its description, -and among equal matches a listed one comes first. The reply's `use` says that `call_tool {tool, args}` +and among equal matches a listed one comes first. The reply's `use` says that `tool_call {tool, args}` runs a command that is not listed. Beside them come the best five of each other catalog with its total and how to use it: the Speed Dial's actions that are no command, the settings being edited -(`search_settings()`, as `get_settings` searches without a scope) and the Python reference. Every catalog is ranked +(`search_settings()`, as `settings_get` searches without a type) and the Python reference. Every catalog is ranked the same way (`query_words()`, `match_score()`): a query word matches where a word of the name or text starts with it, CamelCase parts included, and entries matching more words, then more of them in the name, come first. Scores of different catalogs don't compare, so each keeps its own list. Actions and settings are read on the UI thread: when it can't run the call (a native dialog holds it, or it is busy) the search leaves those two out, and before the main window exists (the server starts ahead of it) it leaves out the settings. The commands, operations and Python reference answer whatever the -UI thread is doing. `call_tool {tool, args}` runs any command of the catalog, listed or not, and is dispatched +UI thread is doing. `tool_call {tool, args}` runs any command of the catalog, listed or not, and is dispatched before it runs (`resolve_call()`, in the protocol, in child calls and in the plugin caller): the target's arguments are normalized and validated, and the call runs as the target's own, with its guard, mode, budget and journal flag, so the journal records the target. @@ -4205,7 +4581,7 @@ arguments its schema rejects are an "Invalid arguments" result, and a protocol v support is a 400. Reconnecting the MCP server lists its tools. The bridge does not look for an instance before each message it answers offline: the handshake follows the startup lookup at once, and each lookup costs a connection attempt while nothing runs. A request gets 5 s to connect, 30 s to be sent and 120 s for its reply (a tool replies -within its 45 s budget, `wait` within 50 s), so a server that never replies can't hang the agent. +within its 45 s budget, `app_wait` within 50 s), so a server that never replies can't hang the agent. A line that is valid JSON but not one message object, such as a batch, gets an error reply. ## Configuration @@ -4222,7 +4598,7 @@ meanwhile. `GUI_InitParams` holds these two flags. Each of the two settings has two readers: the saved setting (`python_scripts_setting()`, `GUI_App::cad_feature_setting()`), which Preferences shows with "(on for this run by the command line)" beside it while the flag is on, and the value in force (`python_scripts_unrestricted()`, -`GUI_App::is_enable_cad_feature()`), which the rest of the app reads, `get_app_state` included. The AppConfig +`GUI_App::is_enable_cad_feature()`), which the rest of the app reads, `app_state` included. The AppConfig `app` section holds `mcp_enabled` (false) and `mcp_port` (13619). Preferences › General › AI features opens with a line on what agents can do and who can connect, then has five rows: @@ -4299,25 +4675,31 @@ describes and flags a replay's steps; `test_mcp_setup` the HTTP and stdio setups In `tests/slic3rutils/`, the files of the same name hold the cases that need the GUI library: `test_mcp_core` a context with no runtime and a tile's journal update; `test_mcp_protocol` the order of the process catalog's `tools/list` and the tool families the stdio bridge lists; `test_command_catalog` the -process catalog itself: unique keys, the palette's commands, which are listed, the merged commands' schemas -and forms, a tool list built without a runtime, a Speed Dial command found by the one lookup, each command's -`id_args` against its schema, the history `undo` and `redo` take, and the command reference (tagged -`[Reference]`): the checked-in file against the catalog, and that its entries hold what `tools/list` tells a -client and both forms of a two-form command. The others there: `test_operations` (tagged `[Operations]`) -the slice and export outcomes, an operation's `Outcome` and `Refusal`, and the catalogs' operation -names and exception lists; `test_mcp_ui` labels, +process catalog itself: unique keys, the commands under their places' headings in the tool list's order, +which are listed, the Speed Dial's 129 tiles held as data in `tests/data/speed_dial_tiles.json` (tagged +`[SpeedDial]`: each found with its id, title, section, icon and input, every row's id a tile's key and no +command, every tile's arguments fitting its command's schema), the person's forms of the commands with tiles +and what a pick of a tile runs in place, the names of `retired_names.hpp`, which no command has, the +access labels (`preset_delete` and `plugin_uninstall` alone destructive), a tool list built without a runtime, +each command's `id_args` against its schema, the history `undo` and `redo` take, and the command reference +(tagged `[Reference]`): the checked-in file against the catalog, and that its entries hold what `tools/list` +tells a client and both forms of a two-form command. The others there: `test_operations` (tagged +`[Operations]`) the slice and export outcomes, an operation's `Outcome` and `Refusal`, the checks each +operation makes over a `Model` or a table built in the test (what an operation refuses and works out is a +function over data; what it then does through the Plater is checked on the app), the operation names +commands give and its one exception list; `test_mcp_ui` labels, snapshot text, ref liveness, synthetic key state, a key's way through the hooks of its target's parents (with a display), how ImGui items are labelled and named, value matching and the model-target projection and surface check (`CanvasTarget`); `test_mcp_results` what covers a canvas click (`imgui_window_at()`), the surface meshes of a modifier target, fresh GL toolbar state, the auto-answer press and a picker's path answer (with a display), the slice reply's plate summary, -`get_slice_stats`'s feature, layer and object tables, the legend rows' names, the slider's layer for +`plate_slice_stats`'s feature, layer and object tables, the legend rows' names, the slider's layer for a height, menu paths and listings, the UI activity hook, the journal's dropped listing clicks and calls whose job failed or still runs (with a replay of the export), the menu capture on real wx menus, row paths and their snapshot text, (with a display) the rows of real trees, lists, checklists and tables, clicks and checkbox input on them, and popups' owning windows, plate icon names and bed picking ids, an upload's percentage while its bytes go out, and -the `send_gcode` command's catalog entry; +`printer_send`'s catalog entry; `test_imgui_wrapper` the ImGui recorder (named items, kinds, values, text, clipping) on frames drawn without OpenGL; `test_mcp_web` a page's lines and their window pixels, web locators, chords as DOM keys per @@ -4328,13 +4710,15 @@ dialog's description, a web dialog rule's wx buttons and web view handles; budget, non-blocking push, finish, abort and failed frames, the video transform, overlays and frame repeats, captions and what they hide, the ffmpeg command and listings, the files recordings and encodes reserve, and the journal's recording paths; `test_mcp_tools` setting serialization, how a query ranks -the Speed Dial's actions, each typed tool's group, `search_tools`' one inventory and its group filter, and which arguments the journal leaves out; `test_mcp_config` the object and part scopes' keys and -effective values, the names and places `save_preset` accepts, enum labels and descriptions, the settings search, -per-variant entries and their writes, preset comparison, `changed`, which unsaved changes a call discarded, which presets -`delete_preset` refuses or deletes with a custom printer, the project scope's slot colours, -flushing multipliers and matrix, and the plate scope's filament orders and layer ranges and -`list_plates`' layer numbers and layer G-codes, the preferences scope's keys, the scripts setting's saved value and value in -force, and `generate_calibration_test`'s arguments, +the Speed Dial's actions, what `action_run` takes and journals for a tile, a call with a tile's arguments +against one with more, `tool_search`' one inventory and its groups, the tool names of `retired_names.hpp` that are no +command, and which arguments the journal leaves out; `test_mcp_config` the keys and effective values of the +settings commands' targets, the names and places `preset_save` accepts, enum labels and descriptions, the +settings search, per-variant entries and their writes, preset comparison, `changed`, which unsaved changes a +call discarded, which presets `preset_delete` refuses or deletes with a custom printer, the project's slot +colours, flushing multipliers and matrix, a plate's filament orders, layer ranges and filament map and +`plate_list`' layer numbers and layer G-codes, `preferences_get`'s list and `preferences_set`'s checks, the +scripts setting's saved value and value in force, and `calibration_generate_test`'s arguments, defaults, the dialogs' shared rules, VFA's auto-adjust and the parameters the journal records. End to end, `tools/mcp/orca_mcp.py` launches the app on Linux on the XWayland of a private headless compositor (KWin, else mutter, which is not tested yet), which gives it the GPU's OpenGL and a window manager, or, on a machine without a desktop, @@ -4342,41 +4726,41 @@ on a private Xvfb display (with `-noreset`, and the pointer parked in a corner s a screenshot); on macOS and Windows it opens the app on the desktop. It runs `tools/mcp/smoke_test.json`, which `--run` also runs headless. `tools/mcp/tests/gizmos.json` checks every gizmo through the GUI tools, -`tools/mcp/tests/multicolor.json` object and part filaments and the project scope, `tools/mcp/tests/presets.json` saving, +`tools/mcp/tests/multicolor.json` object and part filaments and the project's settings, `tools/mcp/tests/presets.json` saving, reading and comparing presets, explaining settings, per-variant entries, `changed`, reverting keys, answering the unsaved-changes prompts of a preset switch and a new project, deleting presets, exporting and importing presets with a path, and reading a preference changed in the Preferences dialog, -`tools/mcp/tests/plates.json` the plate scope, `list_plates` and the filament slot commands, +`tools/mcp/tests/plates.json` a plate's settings, name and lock, `plate_list` and the filament slot commands, `tools/mcp/tests/calibration.json` every calibration test and its preset answers, `tools/mcp/tests/dialogs_canvas_input.json` auto-answers that run a button's handler and canvas targets on negative parts and from below the bed, `tools/mcp/tests/slice_stats.json` the slice -reply's statistics on one and two colours, `tools/mcp/tests/preview.json` `get_slice_stats`, -`get_app_state.preview` and `set_view`'s preview arguments, `tools/mcp/tests/context_menus.json` context +reply's statistics on one and two colours, `tools/mcp/tests/preview.json` `plate_slice_stats`, +`app_state.preview` and `view_set`'s preview arguments, `tools/mcp/tests/context_menus.json` context and button menus listed and run without one ever showing, and the Edit menu's Undo and Redo picked by their paths, `tools/mcp/tests/rows.json` object list rows, checklist rows, the object settings table and the print button's popup, `tools/mcp/tests/recording.json` a recording with clicks, a dialog and a slice, stopped and encoded, and one a replay ends, `tools/mcp/tests/plate_icons.json` plate icons (lock, settings, arrange, the plate menu, move to front), `tools/mcp/test_webview_modal.py` JavaScript in modal dialogs' web views, the ones -`run_javascript` is refused in and a page that closes its dialog, `tools/mcp/tests/web_dialogs.json` the preset bundle dialog, the colour picker +`webview_run_javascript` is refused in and a page that closes its dialog, `tools/mcp/tests/web_dialogs.json` the preset bundle dialog, the colour picker (hex field and spectrum) and the setup wizard's first steps through the GUI tools alone, `tools/mcp/test_web_ui.py` every page control kind, action, refusal, locator, timeout and close of the MCP web fixture plugin's dialog, window, dock panel and configuration UI (side-loaded with `--install DATADIR`), `tools/mcp/test_set_view_preview.py` the -legend combo's semantics of `set_view {view_type}`, a canvas screenshot straight after a layer or -view type change, and the preview refusals of `set_view`, `tools/mcp/test_set_window.py` -`set_window` on the main window (sized twice, moved, placed over its display's work area, maximized and, +legend combo's semantics of `view_set {view_type}`, a canvas screenshot straight after a layer or +view type change, and the preview refusals of `view_set`, `tools/mcp/test_set_window.py` +`window_set` on the main window (sized twice, moved, placed over its display's work area, maximized and, on X11, minimized and restored from both, with a window screenshot of the size on Wayland, and the checks a Wayland session can't run reported SKIP), on the Plugins window by its ref and on Preferences by its `{label}` locator (on X11 with the main window kept under it in the X server's stacking order), `tools/mcp/test_speed_dial_open.py` the 3D view's keyboard focus after a switch to Prepare, Preview or the Design tab, Space opening the Speed Dial there, and the dial without KWin's title bar, `tools/mcp/test_set_view_camera.py` -`set_view`'s `look_at` and `zoom` after a queued fit (and its note while no 3D view draws), clamping, +`view_set`'s `look_at` and `zoom` after a queued fit (and its note while no 3D view draws), clamping, an orbit that keeps `look_at`, the camera Preview shares and the Design tab's own, with `camera_state` -and `get_app_state.camera`, and a fit after the window was sized while no 3D view showed, +and `app_state.camera`, and a fit after the window was sized while no 3D view showed, `tools/mcp/test_export_running_job.py` an export during and after a job that outlived its reply, -`tools/mcp/test_send_gcode.py` `send_gcode` and `get_app_state.uploads` against a stub print host that +`tools/mcp/test_send_gcode.py` `printer_send` and `app_state.uploads` against a stub print host that answers 200 or 500, `tools/mcp/test_command_line.py` the command line's options (the refused ones, `--run`'s exit codes, folders and refusals, `--mcp-port`, the two run flags, and a run beside a window already open), @@ -4387,19 +4771,38 @@ instruments going off with the server, `tools/mcp/test_recovery_under_load.py` answering a dialog while stalled clients hold every connection. See `tools/mcp/README.md`. -`test_mcp_scene` covers the scene and layer tools without the app: `transform`'s `size`, the arguments -of the commands that replace a dialog, notifications updated before the first ImGui frame, `arrange`'s option rules, +The commands that do a menu row's job by index, and the gaps they close, have their checks on the app. The +replays `tools/mcp/tests/rows_objects.json`, `rows_structure.json`, `rows_placement.json` and +`rows_plates.json` call the commands made from rows by index and on the selection, and read each back; +`objects_state.json` (printable, Fix Model, Auto Drop), `objects_files.json` (clone, reload, replace), +`objects_order.json` (`object_order {order}`), `filaments_and_files.json` (slots merged and mixed, exports of +some objects, a ZIP's entries), `settings_targets.json` (`settings_list` and the targets of the settings +commands), `presets_and_plate_map.json` (`preset_list`'s filters, a plate's filament map, a nozzle variant), +`view_switches.json` (`view_set`'s switches, the sidebar and the legend, a plate's origin and size) and +`tiles_ask.json` (a call with a tile's arguments, the two tiles that collect a value, and the tiles whose row +is the command's function). The Python tests check what a replay cannot, a refusal: +`tools/mcp/test_rows_refusals.py` and `test_additions_refusals.py` each refusal's reason, +`test_person_forms.py` the person's forms and a pick that runs in place, `test_preferences.py` the +preferences against the dialog, `test_install_printers.py` and `test_install_filaments.py` the installs, also +after a restart, `test_plugin_commands.py` the plugin commands against the Plugins window, +`test_printer_extruders.py` a printer of two extruders, `test_project_open_settings.py` a project opened +with its settings whatever the load-behaviour preference says, and `test_sidebar_floating.py` a floating +sidebar. + +`test_mcp_scene` covers the scene and layer tools without the app: `object_transform`'s `size`, the arguments +of the commands that replace a dialog, notifications updated before the first ImGui frame, `object_arrange`'s option rules, worker-job admission on a stand-in worker (a job past the reply budget, a slow cancel and a timeout, -three ways to start one, recover input and a person's job), `list_objects`' descriptions of a `Model` +three ways to start one, recover input and a person's job), `object_list`' descriptions of a `Model` built in the test (its rows by plate, the plate filter and paging, placement and boxes on the bed, mirrors, filament fallback, precise seam subtypes, height ranges, the summary of a variable layer -height profile), `add_part`'s type names and shape -sizes, the object structure commands' arguments, the height ranges `set_height_ranges` accepts (order, -overlaps, bounds, keys), and `set_custom_gcode_at_layer`'s edits of a layer slider built in the test (by layer +height profile), `part_add`'s type names and shape +sizes, the object structure commands' arguments, the height ranges `object_set_height_ranges` accepts (order, +overlaps, a range that keeps its settings) and the keys and layer heights a range's settings take, and +`plate_set_custom_gcode`'s edits of a layer slider built in the test (by layer and height, in-place edits, refusals that leave the slider as it was, the type names). On the app, `tools/mcp/tests/scene.json` checks object structure and placement (transform on instances, plates and -parts, what `list_objects` reports of them, the selection `select_objects` and `get_app_state` report, shapes at a -size, arrange and Fill bed, `add_part`, the +parts, what `object_list` reports of them, the selection `object_select` and `app_state` report, shapes at a +size, arrange and Fill bed, `part_add`, the object structure commands, then all of them on one scene through to a slice); `tools/mcp/tests/layers.json` height range modifiers and variable layer height profiles (set, read back, undone, sliced, refused, kept by a 3MF) and layer G-codes (placed by layer and height, edited in diff --git a/docs/HLSD/plugin-permissions.md b/docs/HLSD/plugin-permissions.md index c50096c423..1d98097263 100644 --- a/docs/HLSD/plugin-permissions.md +++ b/docs/HLSD/plugin-permissions.md @@ -120,7 +120,7 @@ nested events of the same operation are not asked again. ### Python scripts -A Python script run from the Run Script panel, with `--run` or by an agent's `run_script` +A Python script run from the Run Script panel, with `--run` or by an agent's `script_run` is not a plugin, but its events are judged here under an identity of its own, `(script)` or `(mcp)` (see "Python scripts" in [mcp-server.md](mcp-server.md)). A script has no sidecar, so it holds no grant and is never asked: steps 1 to 3 apply to it, and any other event is denied with a diff --git a/docs/HLSD/preset-cache.md b/docs/HLSD/preset-cache.md index 41a52bd633..4b7a05e8c9 100644 --- a/docs/HLSD/preset-cache.md +++ b/docs/HLSD/preset-cache.md @@ -42,7 +42,7 @@ presets are never serialized — they have their own storage and their own lifec | `resources/profiles/` | `.opc` alone — the profile and its preset JSONs both pruned | What the app ships with and what installing copies from; read directly for vendors not installed | | `/system/` | `.opc` alone, or `.json` + `/` after an update | What the user has installed | | `/system/` (dev build) | `.json` + `/` + `.opc` written at runtime | A developer tree caches as it parses | -| `/cache/wizard_profile_data.json` | The wizard's derived vendor catalog plus the stamps it was built from | Written and read by the setup wizard only; never shipped (see "The wizard's profile-data cache") | +| `/cache/wizard_profile_data.json` | The wizard's derived vendor catalog plus the stamps it was built from | Written and read by the setup wizard and the commands that list and install printer models (`Ops::printer_profile_data()`); never shipped (see "The wizard's profile-data cache") | Two forms of the same vendor therefore exist, and the system's central rule is that **a vendor's cache is the whole of it**. Where a cache ships or is installed, no profile @@ -273,7 +273,9 @@ function of the vendor set: each vendor's name and version, in load order. A pro change requires a version bump, so name and version determine a vendor's content wherever its copy sits; which directory served it is deliberately **not** stamped, and installing or removing a copy at an unchanged version leaves the cache valid. So -the wizard caches the *derived JSON*, not another form of the inputs: +the wizard caches the *derived JSON*, not another form of the inputs +(`Ops::printer_profile_data()`, `GUI/Operations/InstallOps.cpp`, which `printer_list_models`, +`printer_install` and `printer_uninstall` read the catalog through too): `/cache/wizard_profile_data.json` holds the stamp list and the catalog. On open, the wizard computes the current stamps (one version peek per vendor) and, when they match, serves the catalog from the file — no bundle built, no preset installed. diff --git a/docs/HLSD/preset-plugin-api.md b/docs/HLSD/preset-plugin-api.md index 44e1361542..1d665f5a0c 100644 --- a/docs/HLSD/preset-plugin-api.md +++ b/docs/HLSD/preset-plugin-api.md @@ -221,7 +221,7 @@ preserves those side effects and then verifies the resulting edited target. Filament `preset_name` is an additional integration on top of `Tab::select_preset()`: once the filament tab edits the preset, a different name for a slot is assigned to the -slot by `GUI::Ops::assign_filament_preset()`, the operation the MCP `select_preset` tool +slot by `GUI::Ops::assign_filament_preset()`, the operation the MCP `preset_select` command calls too (docs/HLSD/mcp-server.md, "The operations layer"). It does what picking the preset in the slot's sidebar selector does (`Sidebar::select_filament_preset()`): the slot's colour settings follow the preset, the slot-to-preset mapping, the dynamic @@ -233,12 +233,12 @@ slot is not targetable. Process and printer dropdown choices are constrained by visibility and compatibility, and compatibility may depend on the active context. Target resolution -(`GUI::Ops::resolve_preset()`, the rule the `select_preset` tool resolves by, which +(`GUI::Ops::resolve_preset()`, the rule the `preset_select` command resolves by, which words its refusals) checks the tab dropdown's actual items before the selection flow, so a target the user cannot pick fails without raising that flow's unsaved-edit prompt; a name two entries carry is rejected as ambiguous. A hidden preset that suits the printer is shown in the -selectors first, as for the tool, and a process or printer selection that leaves +selectors first, as for the command, and a process or printer selection that leaves another preset edited is refused by `GUI::Ops::select_preset()`. A filament `preset_name` resolves against the requested slot's own sidebar selector rather than the tab's, so that slot's compatibility filter is the one that applies. A name the diff --git a/localization/i18n/list.txt b/localization/i18n/list.txt index f65add9257..7e2851e6dd 100644 --- a/localization/i18n/list.txt +++ b/localization/i18n/list.txt @@ -159,7 +159,10 @@ src/slic3r/GUI/Mcp/McpToolsApi.cpp src/slic3r/GUI/Mcp/McpToolsApp.cpp src/slic3r/GUI/Mcp/McpToolsCad.cpp src/slic3r/GUI/Mcp/McpToolsConfig.cpp +src/slic3r/GUI/Mcp/McpToolsInstall.cpp src/slic3r/GUI/Mcp/McpToolsLayers.cpp +src/slic3r/GUI/Mcp/McpToolsPlugins.cpp +src/slic3r/GUI/Mcp/McpToolsPreferences.cpp src/slic3r/GUI/Mcp/McpToolsProject.cpp src/slic3r/GUI/Mcp/McpToolsPython.cpp src/slic3r/GUI/Mcp/McpToolsRecord.cpp @@ -188,7 +191,11 @@ src/slic3r/GUI/NotificationManager.cpp src/slic3r/GUI/ObjectDataViewModel.cpp src/slic3r/GUI/OpenGLManager.cpp src/slic3r/GUI/Operations/ExportOps.cpp +src/slic3r/GUI/Operations/InstallOps.cpp +src/slic3r/GUI/Operations/ObjectOps.cpp src/slic3r/GUI/Operations/PlateOps.cpp +src/slic3r/GUI/Operations/PluginOps.cpp +src/slic3r/GUI/Operations/PreferenceOps.cpp src/slic3r/GUI/Operations/PresetOps.cpp src/slic3r/GUI/Operations/ProjectOps.cpp src/slic3r/GUI/OptionsGroup.cpp diff --git a/resources/web/dialog/ActionReplay/action_replay.js b/resources/web/dialog/ActionReplay/action_replay.js index a8ea284c02..c91c5ceb4c 100644 --- a/resources/web/dialog/ActionReplay/action_replay.js +++ b/resources/web/dialog/ActionReplay/action_replay.js @@ -82,9 +82,9 @@ function draftReplay() { ' "orca_replay_version": ' + JSON.stringify(REPLAY_VERSION) + ",", ' "name": ' + JSON.stringify(T("untitled_replay", "Untitled replay")) + ",", ' "steps": [', - ' {"tool": "wait", "args": {"for": "ready"}},', - ' {"tool": "slice", "expect": {"/status": {"eq": "done"}}},', - ' {"tool": "screenshot",', + ' {"tool": "app_wait", "args": {"for": "ready"}},', + ' {"tool": "plate_slice", "expect": {"/status": {"eq": "done"}}},', + ' {"tool": "window_screenshot",', ' "args": {"target": "canvas", "save_path": "${out_dir}/preview.png", "overwrite": true}}', " ]", "}", diff --git a/resources/web/dialog/ActionReplay/replay_editor.js b/resources/web/dialog/ActionReplay/replay_editor.js index 138012108e..eed4ffbaaf 100644 --- a/resources/web/dialog/ActionReplay/replay_editor.js +++ b/resources/web/dialog/ActionReplay/replay_editor.js @@ -4,7 +4,7 @@ // The replay format version the draft and the version key's suggestion write: the host's REPLAY_VERSION // (src/slic3r/GUI/Mcp/McpReplay.hpp), which says which versions it reads. -const REPLAY_VERSION = "0.1.0"; +const REPLAY_VERSION = "0.2.0"; // The keys of a replay and of a step, with the JSON type of their values. Accepting a key writes a // value of that type after its colon (an empty string, object or array with the caret inside, or true), diff --git a/resources/web/dialog/ActionReplay/replay_editor.test.js b/resources/web/dialog/ActionReplay/replay_editor.test.js index 8f1bfcd1d1..ce75de905f 100644 --- a/resources/web/dialog/ActionReplay/replay_editor.test.js +++ b/resources/web/dialog/ActionReplay/replay_editor.test.js @@ -5,8 +5,8 @@ const editor = require("./replay_editor.js"); // Two tools, as the host's catalog lists them: one taking a plain number, one an enum and a nullable number. editor.setEditorTools([ - { name: "slice", title: "Slice", args: { plates: { type: "integer" } } }, - { name: "set_view", title: "Set the view", args: { camera: { type: "string", enum: ["top", "front"] }, zoom: { type: ["number", "null"] } } }, + { name: "plate_slice", title: "Slice", args: { plates: { type: "integer" } } }, + { name: "view_set", title: "Set the view", args: { camera: { type: "string", enum: ["top", "front"] }, zoom: { type: ["number", "null"] } } }, ]); // What suggestionsAt() finds with the caret at the end of `text`. @@ -22,25 +22,25 @@ test("a replay's root keys are suggested in a key's string", () => { }); test("a step's keys are suggested inside steps[], leaving out the ones it has", () => { - const found = at('{"steps": [{"tool": "slice", "'); + const found = at('{"steps": [{"tool": "plate_slice", "'); assert.equal(found.kind, "key"); assert.deepEqual(labels(found), ["args", "expect", "optional", "await", "save_as", "timeout_s"]); }); test("a step's tool is suggested from the catalog with its title and arguments", () => { - const text = '{"steps": [{"tool": "sl'; + const text = '{"steps": [{"tool": "pl'; const found = at(text); assert.equal(found.kind, "value"); assert.equal(found.from, text.length - 2); assert.equal(found.to, text.length); assert.deepEqual(found.items, [ - { label: "slice", detail: "Slice", info: "args: plates" }, - { label: "set_view", detail: "Set the view", info: "args: camera, zoom" }, + { label: "plate_slice", detail: "Slice", info: "args: plates" }, + { label: "view_set", detail: "Set the view", info: "args: camera, zoom" }, ]); }); test("a tool's arguments are suggested in its args with their types and allowed values", () => { - const found = at('{"steps": [{"tool": "set_view", "args": {"'); + const found = at('{"steps": [{"tool": "view_set", "args": {"'); assert.equal(found.kind, "key"); assert.deepEqual(found.items, [ { label: "camera", detail: "string", info: "top | front" }, @@ -49,13 +49,13 @@ test("a tool's arguments are suggested in its args with their types and allowed }); test("an argument's allowed values are suggested as its value", () => { - const found = at('{"steps": [{"tool": "set_view", "args": {"camera": "'); + const found = at('{"steps": [{"tool": "view_set", "args": {"camera": "'); assert.equal(found.kind, "value"); assert.deepEqual(labels(found), ["top", "front"]); }); test("a placeholder suggests the folders, the vars and the saved jobs", () => { - const text = '{"vars": {"part": 1}, "steps": [{"tool": "slice", "save_as": "s1"}, {"tool": "set_view", "args": {"camera": "${'; + const text = '{"vars": {"part": 1}, "steps": [{"tool": "plate_slice", "save_as": "s1"}, {"tool": "view_set", "args": {"camera": "${'; const found = at(text); assert.equal(found.kind, "var"); assert.equal(found.from, text.length); @@ -81,7 +81,7 @@ test("an accepted key gets its colon and an empty value with the caret inside", assert.deepEqual(editor.acceptEdit(text, found, name), { from: 2, to: 2, insert: 'name": ""', back: 1, reopen: true }); // The format version is written whole, with the caret after it. const version = found.items.find((item) => item.label === "orca_replay_version"); - assert.deepEqual(editor.acceptEdit(text, found, version), { from: 2, to: 2, insert: 'orca_replay_version": "0.1.0"', back: 0, reopen: false }); + assert.deepEqual(editor.acceptEdit(text, found, version), { from: 2, to: 2, insert: 'orca_replay_version": "0.2.0"', back: 0, reopen: false }); }); test("a key accepted before an existing colon replaces only the key", () => { @@ -92,12 +92,12 @@ test("a key accepted before an existing colon replaces only the key", () => { }); test("a value accepted in a closed string replaces it up to its quote", () => { - const text = '{"steps": [{"tool": "sl"}]}'; - const caret = text.indexOf('sl"') + 2; + const text = '{"steps": [{"tool": "pl"}]}'; + const caret = text.indexOf('pl"') + 2; const found = editor.suggestionsAt(text, caret, false); assert.equal(found.from, caret - 2); assert.equal(found.to, caret + 1); - assert.deepEqual(editor.acceptEdit(text, found, { label: "slice" }), { from: caret - 2, to: caret + 1, insert: 'slice"', back: 0, reopen: false }); + assert.deepEqual(editor.acceptEdit(text, found, { label: "plate_slice" }), { from: caret - 2, to: caret + 1, insert: 'plate_slice"', back: 0, reopen: false }); }); test("an accepted placeholder closes its brace, over one already typed", () => { diff --git a/resources/web/mcp/page_agent.js b/resources/web/mcp/page_agent.js index e99c840dc2..b97f4cf91b 100644 --- a/resources/web/mcp/page_agent.js +++ b/resources/web/mcp/page_agent.js @@ -1,5 +1,5 @@ -// The MCP server's agent inside a web page: lists the page as list_widgets shows it and acts on its -// elements for click, set_widget_value, press_keys, mouse_gesture and answer_dialog. OrcaSlicer injects it on +// The MCP server's agent inside a web page: lists the page as widget_list shows it and acts on its +// elements for widget_click, widget_set_value, keyboard_press, mouse_gesture and dialog_answer. OrcaSlicer injects it on // demand into any of its web views (src/slic3r/GUI/Mcp/WebPages.cpp), so no page or host includes // it. It runs as the body of `function (V, SRC)`, V the version OrcaSlicer stamps it with and SRC // this source, which it hands to the plugin configuration frames it relays to, and installs @@ -175,7 +175,7 @@ function jqueryHandles(el) { function isFrame(el) { return el.localName === 'iframe' || el.localName === 'frame'; } -// The kind list_widgets lists an element as, in the vocabulary of wx widgets, or '' when it is only a +// The kind widget_list lists an element as, in the vocabulary of wx widgets, or '' when it is only a // container. `pointerAbove` says whether its parent already shows the pointer cursor or is a listed // button or link, so a clickable element counts once, not with every child inside it. function kindOf(el, st, pointerAbove) { @@ -483,7 +483,7 @@ function topRect(el) { // ---- the walk ------------------------------------------------------------------------------ -// Visits the page as list_widgets lists it: visit(el, info, depth) for each listed element and +// Visits the page as widget_list lists it: visit(el, info, depth) for each listed element and // text(text, depth, block) for each run of text outside one. Hidden subtrees are left out; open // shadow roots are walked through their slots and same-origin frames entered. function walkPage(visit, text) { @@ -1050,7 +1050,7 @@ function aimAt(el, dx, dy, hitTest) { // What a press lands on must be the element; a move or release may be anywhere (a drag's). if (hitTest && ((dx !== undefined && (dx < 0 || dx > r.width)) || (dy !== undefined && (dy < 0 || dy > r.height)))) fail('point', 'The point x, y is outside the element: they count from its top left, within the width and height ' + - 'list_widgets lists for it'); + 'widget_list lists for it'); var at = {x: dx === undefined ? r.left + r.width / 2 : r.left + dx, y: dy === undefined ? r.top + r.height / 2 : r.top + dy}; if (hitTest) { var root = el.getRootNode ? el.getRootNode() : el.ownerDocument; @@ -1766,7 +1766,7 @@ var CHANGES_MAX = 20; var WATCHES_MAX = 16; var watches = {}; // outlines taken before actions, by the tools' id for the action: {at, lines} -// The page as list_widgets lists it, a line per element (kind, label, value, state and notes) and per +// The page as widget_list lists it, a line per element (kind, label, value, state and notes) and per // run of text, and the configuration frames, whose agents outline their own pages. function outline() { var lines = []; @@ -1885,10 +1885,10 @@ function changes(req) { function element(req) { if (req.doc !== docToken) - fail('stale', 'The page changed (it navigated or reloaded); call list_widgets again'); + fail('stale', 'The page changed (it navigated or reloaded); call widget_list again'); var el = byKey.get(req.k); if (!el || !el.isConnected) - fail('stale', 'The element is gone from the page; call list_widgets again'); + fail('stale', 'The element is gone from the page; call widget_list again'); return el; } @@ -1917,7 +1917,7 @@ function forward(req) { var parts = String(req.k).split('/'); var frame = byKey.get(Number(parts[0])); if (!frame || !frame.isConnected || !relayFrame(frame)) - fail('stale', 'The element\'s frame is gone; call list_widgets again'); + fail('stale', 'The element\'s frame is gone; call widget_list again'); var inner = {}; for (var p in req) inner[p] = req[p]; @@ -1948,7 +1948,7 @@ function release(req) { function act(req) { if (typeof req.k === 'string' && req.k.indexOf('/') > 0) { if (req.doc !== docToken) - fail('stale', 'The page changed (it navigated or reloaded); call list_widgets again'); + fail('stale', 'The page changed (it navigated or reloaded); call widget_list again'); watch(req); return forward(req); } @@ -1956,7 +1956,7 @@ function act(req) { var el = req.k ? element(req) : null; if (req.action === 'key') { if (el && hiddenFromView(el)) - fail('hidden', 'The element is not shown; call list_widgets again'); + fail('hidden', 'The element is not shown; call widget_list again'); // A disabled control (its fieldset's included) takes no focus, so keys would go elsewhere. if (el) { var keyed = infoOf(el); @@ -1993,7 +1993,7 @@ function act(req) { if (!el) fail('target', 'No element'); if (hiddenFromView(el)) - fail('hidden', 'The element is not shown; call list_widgets again'); + fail('hidden', 'The element is not shown; call widget_list again'); var info = infoOf(el); if (disabledOf(info.control || el, info.st)) fail('disabled', 'The ' + info.kind + ' "' + clip(info.label, 40) + '" is disabled'); @@ -2037,7 +2037,7 @@ function press(req) { function evalScript(req) { if (typeof req.k === 'string') - fail('relayed', 'The element is in a plugin configuration frame, which run_javascript does not reach; use click, set_widget_value and press_keys'); + fail('relayed', 'The element is in a plugin configuration frame, which webview_run_javascript does not reach; use widget_click, widget_set_value and keyboard_press'); var el = req.k ? element(req) : undefined; // A page whose Content-Security-Policy forbids eval refuses to build the runner, before any of the // script runs; the agent itself, installed as inline code, still works there. @@ -2045,7 +2045,7 @@ function evalScript(req) { try { run = new Function('el', 'return eval(arguments[1]);'); } catch (e) { - fail('csp', 'This page\'s Content-Security-Policy forbids eval, which run_javascript runs scripts with; click, set_widget_value and press_keys ' + + fail('csp', 'This page\'s Content-Security-Policy forbids eval, which webview_run_javascript runs scripts with; widget_click, widget_set_value and keyboard_press ' + 'still work on it'); } var res = run(el, String(req.script)); diff --git a/scripts/CAD/gen_offer_table.py b/scripts/CAD/gen_offer_table.py index 07b805adae..33adc6f657 100644 --- a/scripts/CAD/gen_offer_table.py +++ b/scripts/CAD/gen_offer_table.py @@ -33,7 +33,7 @@ ENUM = { # a tool block's access -> CadAccess enumerator ACCESS = {"read": "Read", "change": "Change", "sketch": "Sketch", "ui": "Ui"} -# The headings of search_tools' index of the Design commands (Mcp::design_command_index()), in its order: every +# The headings of tool_search's index of the Design commands (Mcp::design_command_index()), in its order: every # command's `section` is one of them. Menu rows holds the commands that take no arguments and only do what their row # does. SECTIONS = ("Document", "Sketch", "Solid", "Surface", "Construct", "Inspect", "Bodies", "History", "Menu rows") @@ -122,7 +122,7 @@ def faults(A): command's own row takes, which a call with none also gives. A command's rows are in one mode. Every command, an entry with an action or a block that is no folded row, has a `section`, its heading in - search_tools' index (SECTIONS); a folded or greyed row, which is no command, has none. + tool_search's index (SECTIONS); a folded or greyed row, which is no command, has none. `feature_row` marks a row whose action acts on the selected row of the Feature list, which a call of its command takes as its target when nothing is picked in the view (Mcp::open_refusal()): only a command with a row @@ -154,7 +154,7 @@ def faults(A): if not command and "section" in v: errs.append(f"{vid}: a folded or greyed row is no command and has no section") elif command and "section" not in v: - errs.append(f"{vid}: a command needs a section, its heading in search_tools' index: one of {list(SECTIONS)}") + errs.append(f"{vid}: a command needs a section, its heading in tool_search's index: one of {list(SECTIONS)}") elif command and v["section"] not in SECTIONS: errs.append(f'{vid}: section {v["section"]!r} is not one of {list(SECTIONS)}') if v.get("feature_row") and (not v.get("action") or "fold" in v): @@ -248,7 +248,7 @@ def main(): "// not apply are shown disabled in place with their reason rather than removed. Row order was", "// ratified 2026-07-31; changing an index is a breaking change to every user's muscle memory.", "// An entry with an action or a tool block, and no fold_into, is a command of the catalog's group Design", - "// (Mcp::register_cad_commands(), Mcp::is_design_command()), under its section in search_tools' index. A", + "// (Mcp::register_cad_commands(), Mcp::is_design_command()), under its section in tool_search's index. A", "// call whose arguments are exactly those that choose one of its rows opens that row's tool for a person", "// (Mcp::opened_row()): none choose the entry's own row where it has an action, else the rows folded into it", "// with {}; a folded row's args, or the entry's own, choose that row. Any other call runs its tool block's", @@ -336,7 +336,7 @@ def main(): " // The arguments that choose this row, as JSON text: a folded row's, or those that choose the own row of", " // an entry with an action and a tool block as a call with none does; nullptr for none.", " const char* args;", - " // The heading its command is listed under in search_tools' index (kDesignSections,", + " // The heading its command is listed under in tool_search's index (kDesignSections,", " // Mcp::design_command_index()); nullptr for an entry that is no command.", " const char* section;", " // Its action acts on the selected row of the Feature list, which a call of its command, not a person's", @@ -344,7 +344,7 @@ def main(): " bool feature_row;", "};", "", - "// The headings of search_tools' index of the Design commands, in its order. Menu rows holds the commands", + "// The headings of tool_search's index of the Design commands, in its order. Menu rows holds the commands", "// that take no arguments and only do what their row does.", "static const char* const kDesignSections[] = {", ] diff --git a/scripts/CAD/tool_atlas.json b/scripts/CAD/tool_atlas.json index 63454d5ad1..b9e70d3f75 100644 --- a/scripts/CAD/tool_atlas.json +++ b/scripts/CAD/tool_atlas.json @@ -4356,10 +4356,10 @@ "access": "change", "ok_false": false, "summary": "Commit to Plate: send the visible bodies to Prepare at their Move-gizmo positions and show Prepare.", - "details": "It is one Prepare undo step. A lone body is sent even when hidden. A body named in the Bodies list or with body_set names its object or part. Reply: objects (list_objects index after replace, name, parts: how many), bodies_sent, bodies_hidden, replaced.", + "details": "It is one Prepare undo step. A lone body is sent even when hidden. A body named in the Bodies list or with body_set names its object or part. Reply: objects (object_list index after replace, name, parts: how many), bodies_sent, bodies_hidden, replaced.", "params": [ {"name": "mode", "type": "string", "default": "", "enum": ["assembly", "bodies"], "description": "assembly: one object with a part per body; bodies: an object per body. Default: the Commit button's mode, which this leaves as it is."}, - {"name": "replace", "type": "array", "default": [], "description": "list_objects indices to delete in the same undo step, such as an earlier commit. Their settings, modifiers and paint go with them."} + {"name": "replace", "type": "array", "default": [], "description": "object_list indices to delete in the same undo step, such as an earlier commit. Their settings, modifiers and paint go with them."} ], "examples": [ { diff --git a/scripts/check_operation_calls.py b/scripts/check_operation_calls.py index 10abc81aab..f578b7611e 100644 --- a/scripts/check_operation_calls.py +++ b/scripts/check_operation_calls.py @@ -35,15 +35,19 @@ NOT_CALLERS = {"src/slic3r/GUI/Mcp/McpToolsCad.cpp"} # Owner methods an operation calls, by the operation that stands for them. BANNED = { "start_gcode_export": ["export_gcode_to"], - "import_models": ["load_files"], + "import_models": ["load_files", "import_zip_archive", "preview_zip_archive"], "open_project": ["load_project"], "new_project": ["new_project"], "save_project_as": ["save_project"], "export_sliced_3mf": ["export_gcode_3mf"], "export_model_3mf": ["export_core_3mf"], "export_stl": ["export_stl"], + "export_toolpaths_obj": ["export_toolpaths_to_obj"], "select_plate": ["select_plate"], "set_plate_locked": ["lock_plate", "set_plate_locked"], + "delete_plate": ["delete_plate"], + "duplicate_plate": ["duplicate_plate"], + "rename_plate": ["rename_plate"], "start_arrange": ["set_prepare_state", "arrange"], "start_slice": ["request_slice"], "show_layer_range": ["SetHigherValue", "SetLowerValue", "show_layer_range"], @@ -51,7 +55,44 @@ BANNED = { "assign_filament_preset": ["set_filament_preset", "select_filament_preset"], "import_presets": ["import_configs"], "set_instance_count": ["set_number_of_copies"], + "delete_objects": ["delete_from_model_and_list", "delete_all_objects_from_model", "remove_selected"], + "rename_object": ["rename_item"], + "separate_instances": ["instances_to_separated_object", "instances_to_separated_objects", "split_instances"], + # assemble_objects calls ObjectList::merge(), a name too common to ban (a bounding box's merge()). + "split_object": ["split_object", "split_volume"], + "change_part_type": ["set_volume_type"], + "order_objects": ["order_objects"], + "mirror_objects": ["mirror"], + "center_objects": ["center_selection", "do_center_plate"], + "scale_to_fit": ["scale_selection_to_fit_print_volume"], + "drop_objects": ["drop_selection"], + "orient_objects": ["orient"], + "add_primitive": ["load_shape_object"], + "set_objects_printable": ["toggle_printable_state", "update_printable_state", "set_printable"], + "set_objects_auto_drop": ["set_auto_drop", "toggle_auto_drop"], + "fix_objects": ["fix_through_cgal", "fix_all_through_cgal"], + # clone_objects calls Selection::clone(), a name too common to ban (ConfigOption::clone()). + "clone_objects": ["clone_selection"], + "reload_parts": ["reload_parts_from_disk", "reload_from_disk", "reload_all_from_disk"], + "replace_part": ["replace_part_with_file", "replace_with_stl"], "send_gcode_to_host": ["send_gcode_legacy"], + "sync_presets": ["restart_sync_user_preset", "start_sync_user_preset"], + "add_filament_slot": ["add_filament"], + "delete_filament_slot": ["delete_filament", "change_filament"], + "add_mixed_filament": ["ensure_mixed_filament", "add_mixed_filament"], + # uninstall_printers, and the Printer Selection dialog's Confirm, apply the set through it too (apply_install_set). + "install_printers": ["apply_vendor_config"], + # uninstall_filaments writes the filaments section through it too. + "install_filaments": ["set_section"], + # The Preferences dialog's controls run these effects through apply_preference(), as set_preferences does. + "set_preferences": ["set_visible_page_count", "set_max_recent_count", "update_filaments_area_height"], + # The Plugins window's switches, Delete and Unsubscribe, and Reload and Reinstall run these through the operations. + "set_plugin_enabled": ["load_plugin", "unload_plugin", "set_capability_enabled"], + "uninstall_plugin": ["delete_plugin", "delete_and_unsubscribe_cloud_plugin"], + "reload_plugin": ["download_and_install_cloud_plugin"], + # The sync dialog's Synchronize now runs the sync through the operation, and a drop in the object list a drag. + "sync_filaments_from_ams": ["sync_ams_list", "apply_ams_sync"], + "reorder_objects": ["move_object"], "the undo snapshot of an operation": ["take_snapshot"], } diff --git a/scripts/operation_calls_baseline.txt b/scripts/operation_calls_baseline.txt index 4747a0b0e5..9640f7c6f1 100644 --- a/scripts/operation_calls_baseline.txt +++ b/scripts/operation_calls_baseline.txt @@ -6,49 +6,53 @@ # Generate candidates with: python3 scripts/check_operation_calls.py --print [src/slic3r/GUI/NativeCommands.cpp] -# The asking path of a command: with no param, and for load_project with or without one, the command -# calls the owner's method, which asks the person what an operation would be told. +# The asking path of a command, its menu row's tile (Rows): the row's function calls the owner's method, which asks +# the person what an operation would be told (project_open {}, project_save {save_as: true}, project_import {archive: +# true}, project_export with a tile's arguments, filament_sync_ams {}). plater->load_project(); -plater->load_project(from_path(*path)); -return project_save_result(plater->save_project(true)); +return NativeCommands::project_save_result(plater->save_project(true)); +plater->import_zip_archive(); plater->export_stl(); plater->export_core_3mf(); -plater->export_gcode_3mf(all); -plater->set_number_of_copies(); -# Another function that uses the same owner method: every object as its own STL, and the Draco exports. +plater->export_gcode_3mf(all_plates); +plater->export_toolpaths_to_obj(); +const std::optional refusal = plater->sidebar().sync_ams_list(); +# Another function that uses the same owner method: every object as its own STL, and the Draco exports, each asking +# for its file or folder. plater->export_stl(false, false, true); -plater->export_stl(false, false, true, FT_STL, from_path(*dir)); plater->export_stl(false, false, false, FT_DRC); plater->export_stl(false, false, true, FT_DRC); -# Another function that uses the same owner method: orient, which leaves a plate-only state behind as arrange does. -plater->set_prepare_state(Job::PREPARE_STATE_DEFAULT); [src/slic3r/GUI/Mcp/McpToolsConfig.cpp] -# The undo step of a tool whose function has one automation entry point (set_settings' object, plate -# and project scopes). +# The undo step of a tool whose function has one automation entry point (settings_set's object and part +# targets, plate_set_settings and project_set_settings). plater.take_snapshot("Move object"); plater.take_snapshot("Plate Settings"); plater.take_snapshot("Change object settings"); # A tool selecting the plate it was given before its own work, as the plate's settings icon does. plater.select_plate(index); -# Another function that uses the same owner method: set_settings makes the filament tab edit a slot's -# preset, and delete_preset selects the preset, deletes it and selects back. +# Another function that uses the same owner method: settings_set makes the filament tab edit a slot's +# preset, and preset_delete selects the preset, deletes it and selects back. if (!tab->select_preset(name)) if (!tab->select_preset(name)) tab->select_preset(selected); [src/slic3r/GUI/Mcp/McpToolsLayers.cpp] -# The undo step of a tool whose function has one automation entry point (set_height_ranges). +# The undo step of a tool whose function has one automation entry point (object_set_height_ranges). plater.take_snapshot("Edit height ranges"); [src/slic3r/GUI/Mcp/McpToolsProject.cpp] -# The asking path of a command, its person's form: new_project and save_project called with no arguments +# The asking path of a command, its person's form: project_new and project_save called with no arguments # call the owner's method, which asks the person what an operation would be told. plater->new_project(); return NativeCommands::project_save_result(plater->save_project(false)); [src/slic3r/GUI/Mcp/McpToolsScene.cpp] -# The undo step of a tool whose function has one automation entry point (transform). +# The asking path of a command, its person's form: object_rename {} and object_set_instances {} call the owner's +# method on the target they resolved from the selection, which asks the person what an operation would be told. +list->rename_item(); +plater.set_number_of_copies(); +# The undo step of a tool whose function has one automation entry point (object_transform). plater.take_snapshot("Transform object"); plater.take_snapshot("Transform part", UndoRedo::SnapshotType::GizmoAction); diff --git a/src/libslic3r/PresetBundle.hpp b/src/libslic3r/PresetBundle.hpp index 5a660e839f..3d5c872226 100644 --- a/src/libslic3r/PresetBundle.hpp +++ b/src/libslic3r/PresetBundle.hpp @@ -679,6 +679,9 @@ public: // based on the user configuration. // If the "vendor" section is missing, enable all models and variants of the particular vendor. void load_installed_printers(const AppConfig &config); + // Set the is_visible flag for filaments from the user configuration's filaments section, + // first adding there the default filaments of each installed printer that no installed filament fits. + void load_installed_filaments(AppConfig &config); const std::string& get_preset_name_by_alias(const Preset::Type& preset_type, const std::string& alias) const; @@ -937,9 +940,8 @@ private: // Update renamed_from and alias maps of system profiles. void update_system_maps(); - // Set the is_visible flag for filaments and sla materials, - // apply defaults based on enabled printers when no filaments/materials are installed. - void load_installed_filaments(AppConfig &config); + // Set the is_visible flag for sla materials, + // apply defaults based on enabled printers when no materials are installed. void load_installed_sla_materials(AppConfig &config); // Load print, filament & printer presets from a config. If it is an external config, then the name is extracted from the external path. diff --git a/src/slic3r/CMakeLists.txt b/src/slic3r/CMakeLists.txt index 18195c8a0e..ca57a41c1c 100644 --- a/src/slic3r/CMakeLists.txt +++ b/src/slic3r/CMakeLists.txt @@ -145,14 +145,23 @@ set(SLIC3R_GUI_SOURCES GUI/ActionRegistry.hpp GUI/ActionReplayDialog.cpp GUI/ActionReplayDialog.hpp + GUI/NativeCommandRows.hpp GUI/NativeCommands.cpp GUI/NativeCommands.hpp GUI/Operations/ExportOps.cpp GUI/Operations/ExportOps.hpp + GUI/Operations/InstallOps.cpp + GUI/Operations/InstallOps.hpp + GUI/Operations/ObjectOps.cpp + GUI/Operations/ObjectOps.hpp GUI/Operations/Outcome.cpp GUI/Operations/Outcome.hpp GUI/Operations/PlateOps.cpp GUI/Operations/PlateOps.hpp + GUI/Operations/PluginOps.cpp + GUI/Operations/PluginOps.hpp + GUI/Operations/PreferenceOps.cpp + GUI/Operations/PreferenceOps.hpp GUI/Operations/PresetOps.cpp GUI/Operations/PresetOps.hpp GUI/Operations/ProjectOps.cpp @@ -176,6 +185,8 @@ set(SLIC3R_GUI_SOURCES GUI/Mcp/McpPersonRun.hpp GUI/Mcp/McpRecorder.cpp GUI/Mcp/McpRecorder.hpp + GUI/Mcp/McpTargets.cpp + GUI/Mcp/McpTargets.hpp GUI/Mcp/McpTools.hpp GUI/Mcp/McpPluginCaller.cpp GUI/Mcp/McpPluginCaller.hpp @@ -184,7 +195,10 @@ set(SLIC3R_GUI_SOURCES GUI/Mcp/McpToolsApp.cpp GUI/Mcp/McpToolsCommon.cpp GUI/Mcp/McpToolsConfig.cpp + GUI/Mcp/McpToolsInstall.cpp GUI/Mcp/McpToolsLayers.cpp + GUI/Mcp/McpToolsPlugins.cpp + GUI/Mcp/McpToolsPreferences.cpp GUI/Mcp/McpToolsProject.cpp GUI/Mcp/McpToolsPython.cpp GUI/Mcp/McpToolsRecord.cpp diff --git a/src/slic3r/GUI/ActionIds.hpp b/src/slic3r/GUI/ActionIds.hpp index 8071b6eca8..0476c1accc 100644 --- a/src/slic3r/GUI/ActionIds.hpp +++ b/src/slic3r/GUI/ActionIds.hpp @@ -1,5 +1,7 @@ #pragma once +#include + // The built-in action source's key and name, and the prefix of a command's tile id. No wx here: this header is part // of the library libslic3r_automation, which is built without wx. namespace Slic3r { namespace GUI { @@ -12,4 +14,17 @@ inline constexpr const char* kOrcaSourceName = "OrcaSlicer"; // The prefix of a catalog command's tile id, "orca_command::orca" (NativeCommands::make_action()). inline constexpr const char* kCommandPrefix = "orca_command"; +// The key inside a command's tile id, "orca_command::orca"; `id` itself when it has no colon, the name inside the +// id, which action_run takes in its place; empty for any other action's id. +inline std::string command_tile_key(const std::string& id) +{ + if (id.find(':') == std::string::npos) + return id; + const std::string prefix = std::string(kCommandPrefix) + ':', suffix = std::string(":") + kOrcaSourceKey; + if (id.size() > prefix.size() + suffix.size() && id.compare(0, prefix.size(), prefix) == 0 && + id.compare(id.size() - suffix.size(), suffix.size(), suffix) == 0) + return id.substr(prefix.size(), id.size() - prefix.size() - suffix.size()); + return {}; +} + }} // namespace Slic3r::GUI diff --git a/src/slic3r/GUI/ActionRegistry.cpp b/src/slic3r/GUI/ActionRegistry.cpp index 233ce2e75d..2b952c8ea5 100644 --- a/src/slic3r/GUI/ActionRegistry.cpp +++ b/src/slic3r/GUI/ActionRegistry.cpp @@ -478,7 +478,7 @@ struct PlateAction : AppAction } AppActionRunResult run(const nlohmann::json& /*args*/) const override - { return NativeCommands::run("plate_goto", {{"plate", plate_index}}); } + { return NativeCommands::run("plate_select", {{"plate", plate_index}}); } }; // A dynamic "Open recent project " action, one per recent project file, rebuilt on every @@ -608,12 +608,12 @@ void ActionRegistry::init() upsert(std::move(action)); } - // Built-in palette commands (Save/Load, Preferences, Mode switch, Slice/Preview, Go to layer): the - // catalog's commands with a tile, and no others. Register after plugins so the plugin ids win on any - // (unlikely) id collision - ids are distinct by prefix, so this is order-independent. The catalog (and + // Built-in palette tiles (Save/Load, Preferences, Mode switch, Slice/Preview, Go to layer): the catalog's + // commands' own tiles and the items of their tiles, and no others. Register after plugins so the plugin ids win + // on any (unlikely) id collision - ids are distinct by prefix, so this is order-independent. The catalog (and // its thin AppAction adapter) lives in NativeCommands; the registry only stores and dispatches the result. - for (const NativeCommand* c : NativeCommands::palette_commands(NativeCommands::instance())) - upsert(NativeCommands::make_action(*c)); + for (const NativeCommands::PaletteTile& t : NativeCommands::palette_tiles(NativeCommands::instance())) + upsert(t.tile != nullptr ? NativeCommands::make_action(*t.command, *t.tile) : NativeCommands::make_action(*t.command)); } void ActionRegistry::relocalize_builtins() @@ -633,8 +633,8 @@ void ActionRegistry::relocalize_builtins() for (const std::string& id : stale) remove(id); - for (const NativeCommand* c : NativeCommands::palette_commands(NativeCommands::instance())) - upsert(NativeCommands::make_action(*c)); + for (const NativeCommands::PaletteTile& t : NativeCommands::palette_tiles(NativeCommands::instance())) + upsert(t.tile != nullptr ? NativeCommands::make_action(*t.command, *t.tile) : NativeCommands::make_action(*t.command)); } void ActionRegistry::refresh_source(const std::string& plugin_key, ActionChange change) diff --git a/src/slic3r/GUI/ActionRegistry.hpp b/src/slic3r/GUI/ActionRegistry.hpp index ff7dab0ab8..bb21c31c98 100644 --- a/src/slic3r/GUI/ActionRegistry.hpp +++ b/src/slic3r/GUI/ActionRegistry.hpp @@ -120,11 +120,13 @@ struct AppAction std::string automation_description; nlohmann::json input_schema; bool completes_in_background = false; - // The catalog key of a command's tile (NativeCommands), whose own function run_action runs; empty for + // The catalog key of a command's tile (NativeCommands), whose own function action_run runs; empty for // every other action. std::string command; - // The arguments the tile of a menu row folded into `command` runs it with, an object that may be empty - // (NativeCommands::make_action()); null for every other action, which runs with the arguments it is given. + // The arguments a tile of `command` runs it with, an object that may be empty: an item of its tiles' args, to which a + // tile that collects a value (input) adds that value (tile_call_args(), CommandCatalog.hpp), or {} for the command's + // own tile outside the Design tab. Null for every other action, a Design command's own tile among them, which runs + // with the arguments it is given. nlohmann::json preset; virtual ~AppAction() = default; @@ -240,7 +242,7 @@ public: const AppAction* by_id(const std::string& id) const; // The action `id` as the app is now: by_id() after the families whose membership follows live state // (plates, recent projects, the Design tab's tiles) are re-materialised, for a caller that may have - // changed that state since the last snapshot() or describe(), such as an automated run_action after a + // changed that state since the last snapshot() or describe(), such as an automated action_run after a // sketch was opened or the tab switched. Settings are not, being thousands: snapshot() and describe() // with include_settings materialise them. UI thread only. const AppAction* find_live(const std::string& id); diff --git a/src/slic3r/GUI/ActionReplayDialog.cpp b/src/slic3r/GUI/ActionReplayDialog.cpp index dc3c0edd48..3ae29a6ba2 100644 --- a/src/slic3r/GUI/ActionReplayDialog.cpp +++ b/src/slic3r/GUI/ActionReplayDialog.cpp @@ -126,17 +126,17 @@ std::pair replay_what_text(const json& what, const Com const std::string key = what.value("key", ""); const auto* command = catalog.find(key); // Titled as its tile is, so a Design command's step reads as the Design tab names its tool; a call that is - // a folded row's tile, as that row. + // a folded row's tile, as that row, with the value a tile that collects one was given. + const std::string args = what.contains("args") ? join(what["args"]) : std::string(); if (what.contains("tile")) { const auto [owner, tile] = find_tile(catalog, what.value("tile", "")); if (tile != nullptr && owner == command) { const std::string title = tile->at("title").get(); const char* context = title_context(*owner); - return {into_u8(context != nullptr ? I18N::translate(title, context) : I18N::translate(title)), {}}; + return {into_u8(context != nullptr ? I18N::translate(title, context) : I18N::translate(title)), args}; } } - return {command != nullptr ? into_u8(NativeCommands::tile_title(*command)) : key, - what.contains("args") ? join(what["args"]) : std::string()}; + return {command != nullptr ? into_u8(NativeCommands::tile_title(*command)) : key, args}; } if (kind == "recent_project" || kind == "preset") return {what.value("name", ""), {}}; @@ -855,7 +855,7 @@ json ActionReplayDialog::step_view(const json& entry) const const json result = entry.value("result", json()); json lines = json::array(); - if (tool == "run_script" && result.is_object()) { + if (tool == "script_run" && result.is_object()) { // What the script printed, then what it returned. std::istringstream output(result.value("output", std::string())); std::string line; @@ -891,7 +891,7 @@ json ActionReplayDialog::step_view(const json& entry) const json files = json::array(); for (const std::string& path : Mcp::result_files(result)) files.push_back({{"path", path}, {"name", Mcp::path_to_utf8(Mcp::path_from_utf8(path).filename())}}); - if (tool == "screenshot" && !files.empty()) + if (tool == "window_screenshot" && !files.empty()) if (const std::string url = thumbnail(files[0]["path"].get()); !url.empty()) view["thumbnail"] = url; view["files"] = std::move(files); diff --git a/src/slic3r/GUI/ActionReplayDialog.hpp b/src/slic3r/GUI/ActionReplayDialog.hpp index b702c96617..6c5be5b1bd 100644 --- a/src/slic3r/GUI/ActionReplayDialog.hpp +++ b/src/slic3r/GUI/ActionReplayDialog.hpp @@ -33,9 +33,9 @@ struct Replay; struct ReplayContext; } // namespace Mcp -// A replay step's main line in the Action Replay window and, for a command given arguments, its second line, from -// describe_step()'s `what`, in the UI's language. A command, found in `catalog`, is titled as its own tile is, and a -// call that is one of its tiles (`what`'s `tile`) as that tile. +// A replay step's main line in the Action Replay window and, for a command given arguments or a tile given the value +// it collects, its second line, from describe_step()'s `what`, in the UI's language. A command, found in `catalog`, is +// titled as its own tile is, and a call that is one of its tiles (`what`'s `tile`) as that tile. std::pair replay_what_text(const nlohmann::json& what, const CommandCatalog& catalog); // The Action Replay window: a person opens or writes a replay file (the JSON list of tool calls an diff --git a/src/slic3r/GUI/AuiMgr.cpp b/src/slic3r/GUI/AuiMgr.cpp index cceb7d0010..ac09753460 100644 --- a/src/slic3r/GUI/AuiMgr.cpp +++ b/src/slic3r/GUI/AuiMgr.cpp @@ -13,6 +13,8 @@ #include #include +#include + namespace Slic3r { namespace GUI { namespace { @@ -66,6 +68,21 @@ void AuiMgr::track_docked_size(wxWindow* window) }); } +void AuiMgr::set_docked_width(wxWindow* window, int width) +{ + wxAuiPaneInfo& pane = GetPane(window); + if (!pane.IsOk()) + return; + pane.BestSize(width, pane.best_size.GetHeight()); + // A dock keeps its size from layout to layout; one of size 0 takes its panes' best size at the next. + for (std::size_t i = 0; i < m_docks.size(); ++i) { + wxAuiDockInfo& dock = m_docks[i]; + if (dock.dock_direction == pane.dock_direction && dock.dock_layer == pane.dock_layer && dock.dock_row == pane.dock_row) + dock.size = 0; + } + Update(); +} + wxAuiPaneInfo AuiMgr::sidebar_pane_info() { return wxAuiPaneInfo() diff --git a/src/slic3r/GUI/AuiMgr.hpp b/src/slic3r/GUI/AuiMgr.hpp index 57b3950b93..a36168dedd 100644 --- a/src/slic3r/GUI/AuiMgr.hpp +++ b/src/slic3r/GUI/AuiMgr.hpp @@ -16,6 +16,9 @@ public: // Keeps the docked size of `window`'s pane in its best_size, which re-docking and a saved layout // use: wxAUI does not record a dragged sash there. void track_docked_size(wxWindow* window); + // Docks the left or right pane of `window` at `width` pixels, as a drag of its sash leaves it: its best_size, which + // its dock takes at once and again when it is docked anew. + void set_docked_width(wxWindow* window, int width); // A tab's sidebar pane: docked left by default, movable to the right or floating, no close button. static wxAuiPaneInfo sidebar_pane_info(); diff --git a/src/slic3r/GUI/CAD/DesignOffer.hpp b/src/slic3r/GUI/CAD/DesignOffer.hpp index d6e9c52a3d..3883531608 100644 --- a/src/slic3r/GUI/CAD/DesignOffer.hpp +++ b/src/slic3r/GUI/CAD/DesignOffer.hpp @@ -6,7 +6,7 @@ // not apply are shown disabled in place with their reason rather than removed. Row order was // ratified 2026-07-31; changing an index is a breaking change to every user's muscle memory. // An entry with an action or a tool block, and no fold_into, is a command of the catalog's group Design -// (Mcp::register_cad_commands(), Mcp::is_design_command()), under its section in search_tools' index. A +// (Mcp::register_cad_commands(), Mcp::is_design_command()), under its section in tool_search's index. A // call whose arguments are exactly those that choose one of its rows opens that row's tool for a person // (Mcp::opened_row()): none choose the entry's own row where it has an action, else the rows folded into it // with {}; a folded row's args, or the entry's own, choose that row. Any other call runs its tool block's @@ -126,7 +126,7 @@ struct DesignTool { // The arguments that choose this row, as JSON text: a folded row's, or those that choose the own row of // an entry with an action and a tool block as a call with none does; nullptr for none. const char* args; - // The heading its command is listed under in search_tools' index (kDesignSections, + // The heading its command is listed under in tool_search's index (kDesignSections, // Mcp::design_command_index()); nullptr for an entry that is no command. const char* section; // Its action acts on the selected row of the Feature list, which a call of its command, not a person's @@ -134,7 +134,7 @@ struct DesignTool { bool feature_row; }; -// The headings of search_tools' index of the Design commands, in its order. Menu rows holds the commands +// The headings of tool_search's index of the Design commands, in its order. Menu rows holds the commands // that take no arguments and only do what their row does. static const char* const kDesignSections[] = { "Document", @@ -1338,18 +1338,18 @@ static const DesignTool kDesignTools[] = { {"commit_to_plate", L_CONTEXT("Commit to plate", "Design"), -1, nullptr, nullptr, nullptr, 0x00000000u, 0, 0, false, false, nullptr, nullptr, nullptr, false, CadAccess::Change, false, "{\"summary\":\"Commit to Plate: send the visible bodies to Prepare at their Move-gizmo positions an" "d show Prepare.\",\"details\":\"It is one Prepare undo step. A lone body is sent even when hidden. A" - " body named in the Bodies list or with body_set names its object or part. Reply: objects (list_o" - "bjects index after replace, name, parts: how many), bodies_sent, bodies_hidden, replaced.\",\"para" - "ms\":[{\"name\":\"mode\",\"type\":\"string\",\"default\":\"\",\"enum\":[\"assembly\",\"bodies\"],\"description\":\"ass" - "embly: one object with a part per body; bodies: an object per body. Default: the Commit button's" - " mode, which this leaves as it is.\"},{\"name\":\"replace\",\"type\":\"array\",\"default\":[],\"description\"" - ":\"list_objects indices to delete in the same undo step, such as an earlier commit. Their setting" - "s, modifiers and paint go with them.\"}],\"examples\":[{\"title\":\"A plate sent to Prepare as one obj" - "ect\",\"calls\":[{\"tool\":\"extrude\",\"args\":{\"distance\":5,\"height\":20,\"width\":20}},{\"tool\":\"commit_to" - "_plate\",\"args\":{}}]},{\"title\":\"Two bodies sent to Prepare as an object each\",\"calls\":[{\"tool\":\"e" - "xtrude\",\"args\":{\"distance\":5,\"height\":20,\"width\":20}},{\"tool\":\"extrude\",\"args\":{\"distance\":10,\"o" - "peration\":\"new_body\",\"profile\":[[20,-5],[30,-5],[30,5],[20,5]]}},{\"tool\":\"commit_to_plate\",\"args" - "\":{\"mode\":\"bodies\"}}]}],\"ids\":false}", nullptr, nullptr, "Document", false}, + " body named in the Bodies list or with body_set names its object or part. Reply: objects (object" + "_list index after replace, name, parts: how many), bodies_sent, bodies_hidden, replaced.\",\"param" + "s\":[{\"name\":\"mode\",\"type\":\"string\",\"default\":\"\",\"enum\":[\"assembly\",\"bodies\"],\"description\":\"asse" + "mbly: one object with a part per body; bodies: an object per body. Default: the Commit button's " + "mode, which this leaves as it is.\"},{\"name\":\"replace\",\"type\":\"array\",\"default\":[],\"description\":" + "\"object_list indices to delete in the same undo step, such as an earlier commit. Their settings," + " modifiers and paint go with them.\"}],\"examples\":[{\"title\":\"A plate sent to Prepare as one objec" + "t\",\"calls\":[{\"tool\":\"extrude\",\"args\":{\"distance\":5,\"height\":20,\"width\":20}},{\"tool\":\"commit_to_p" + "late\",\"args\":{}}]},{\"title\":\"Two bodies sent to Prepare as an object each\",\"calls\":[{\"tool\":\"ext" + "rude\",\"args\":{\"distance\":5,\"height\":20,\"width\":20}},{\"tool\":\"extrude\",\"args\":{\"distance\":10,\"ope" + "ration\":\"new_body\",\"profile\":[[20,-5],[30,-5],[30,5],[20,5]]}},{\"tool\":\"commit_to_plate\",\"args\":" + "{\"mode\":\"bodies\"}}]}],\"ids\":false}", nullptr, nullptr, "Document", false}, {"new_design", L_CONTEXT("New design", "Design"), -1, nullptr, nullptr, nullptr, 0x00000000u, 0, 0, false, false, nullptr, nullptr, nullptr, false, CadAccess::Change, false, "{\"summary\":\"New Design: erase every feature, body and variable and the Design undo history.\",\"de" "tails\":\"Committed objects stay on the plate. Reply: cleared {features, bodies, variables}.\",\"par" diff --git a/src/slic3r/GUI/CAD/DesignPanel.cpp b/src/slic3r/GUI/CAD/DesignPanel.cpp index faec9b58a9..45fa118848 100644 --- a/src/slic3r/GUI/CAD/DesignPanel.cpp +++ b/src/slic3r/GUI/CAD/DesignPanel.cpp @@ -5046,7 +5046,7 @@ bool DesignPanel::mcp_select(const DesignSelection& s, std::string& why) if (s.plane < 0 || s.plane > 2) { why = "plane is XY, XZ or YZ"; return false; } // Where update_reference_planes() puts the planes up for a click (no card is open here). if (!m_show_origin && !m_choosing_sketch_plane) { - why = "no click can pick a plane now: one does while the Origin row shows the planes (set_view {\"tab\": " + why = "no click can pick a plane now: one does while the Origin row shows the planes (view_set {\"tab\": " "\"design\", \"origin\": true}) or while Sketch waits for its plane (sketch_create {})"; return false; } diff --git a/src/slic3r/GUI/CAD/DesignPanel.hpp b/src/slic3r/GUI/CAD/DesignPanel.hpp index 08b0cedef2..032bf8a493 100644 --- a/src/slic3r/GUI/CAD/DesignPanel.hpp +++ b/src/slic3r/GUI/CAD/DesignPanel.hpp @@ -230,7 +230,7 @@ public: // Design commands may be the first thing to touch the Design tab after a project was opened. void hydrate_from_model(); - // The view switches that are not the canvas's, set by value for set_view; the toolbar's and the rows' + // The view switches that are not the canvas's, set by value for view_set; the toolbar's and the rows' // toggles go through these. The section view is one horizontal clip at world height `z` that keeps the // lower half, or the upper one with `keep_upper`; turned on with no z it cuts at the model's middle // height. Turned off, z and keep_upper are left as they were. diff --git a/src/slic3r/GUI/CloneDialog.cpp b/src/slic3r/GUI/CloneDialog.cpp index a00a1ea416..3db2cce173 100644 --- a/src/slic3r/GUI/CloneDialog.cpp +++ b/src/slic3r/GUI/CloneDialog.cpp @@ -16,12 +16,11 @@ #include #include "slic3r/GUI/Widgets/DialogButtons.hpp" #include "slic3r/GUI/Widgets/Button.hpp" -#include "slic3r/GUI/Selection.hpp" #include -#include "slic3r/GUI/Jobs/Job.hpp" #include "libslic3r/AppConfig.hpp" -#include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/I18N.hpp" +#include "slic3r/GUI/Operations/ObjectOps.hpp" +#include "slic3r/GUI/Operations/Outcome.hpp" #include "slic3r/GUI/Plater.hpp" class wxWindow; @@ -98,30 +97,18 @@ CloneDialog::CloneDialog(wxWindow *parent) v_sizer->Fit(this); Refresh(); - Selection& sel = m_plater->canvas3D()->get_selection(); - m_plater->take_snapshot(std::string("Selection-clone")); - m_plater->Freeze(); // Better to stop rendering canvas while processing - sel.copy_to_clipboard(); - for (int i = 0; i < m_count; i++) { // same method with Selection::clone() - m_progress->SetValue(static_cast(static_cast(i) / m_count * 100)); // pass 0 / 100 - sel.paste_from_clipboard(); - - if (m_cancel_process) { - m_plater->undo(); - return; - } - + // The selection's copies, the progress bar showing each; Cancel, which ends the dialog, undoes them. + Ops::CloneObjectsArgs clone; + clone.targets.from_selection = true; + clone.count = m_count; + clone.arrange = m_arrange_cb->GetValue(); + const auto pasted = [this](int done, int count) { + m_progress->SetValue(static_cast(static_cast(done - 1) / count * 100)); // pass 0 / 100 wxYield(); // Allow event loop to process updates - } - - if (!m_cancel_process) { - if (m_arrange_cb->GetValue()) { - m_plater->set_prepare_state(Job::PREPARE_STATE_MENU); - m_plater->arrange(); - } - m_plater->Thaw(); + return !m_cancel_process; + }; + if (Ops::clone_objects(clone, pasted)) EndModal(wxID_OK); - } }); dlg_btns->GetCANCEL()->Bind(wxEVT_BUTTON, [this](wxCommandEvent &) { diff --git a/src/slic3r/GUI/CommandCatalog.cpp b/src/slic3r/GUI/CommandCatalog.cpp index 9154742385..b6a55e7c6f 100644 --- a/src/slic3r/GUI/CommandCatalog.cpp +++ b/src/slic3r/GUI/CommandCatalog.cpp @@ -1,5 +1,6 @@ #include "CommandCatalog.hpp" +#include "ActionIds.hpp" #include "CommandTypes.hpp" #include "Mcp/McpArguments.hpp" @@ -130,12 +131,33 @@ const nlohmann::json* tile_with_args(const NativeCommand& command, const nlohman return nullptr; // A call with no arguments gives none, null as {}, as Mcp::opened_row() reads it. const nlohmann::json given = Mcp::person_form(args) ? nlohmann::json::object() : args; + // A tile that collects a value is called with that value besides its own arguments, never with these alone. for (const nlohmann::json& tile : command.tiles) - if (tile.at("args") == given) + if (tile.value("input", std::string()).empty() && tile.at("args") == given) return &tile; return nullptr; } +nlohmann::json tile_call_args(const nlohmann::json* tile, const nlohmann::json& args) +{ + if (tile == nullptr) + return args; + nlohmann::json out = tile->at("args"); + const std::string input = tile->value("input", std::string()); + // Without the value the tile's args alone are given: action_run refuses such a call first (action_args_error()), + // and the Speed Dial's second phase always collects the value. + if (input.empty() || !args.is_object() || !args.contains(input)) + return out; + nlohmann::json value = args.at(input); + // The Speed Dial's tab picker sends the id of a page, and view_set's tab takes the word of a page that has one. + if (input == "tab") + for (const TabWord& w : kTabWords) + if (value == w.page) + value = w.word; + out[tile->value("input_arg", input)] = std::move(value); + return out; +} + std::string call_title(const NativeCommand& command, const nlohmann::json& args) { const nlohmann::json* tile = tile_with_args(command, args); @@ -154,6 +176,17 @@ std::pair find_tile(const CommandCa return {nullptr, nullptr}; } +std::pair shown_title(const CommandCatalog& catalog, const NativeCommand& command, + const nlohmann::json& args) +{ + if (command.key == "action_run" && args.is_object() && args.value("id", nlohmann::json()).is_string()) { + const auto [owner, tile] = find_tile(catalog, command_tile_key(args.at("id").get())); + if (owner != nullptr) + return {tile != nullptr ? tile->at("title").get() : owner->title, owner}; + } + return {call_title(command, args), &command}; +} + nlohmann::json command_reference(const NativeCommand& command) { nlohmann::json entry{{"key", command.key}, @@ -170,6 +203,11 @@ nlohmann::json command_reference(const NativeCommand& command) {"guard", guard_name(command.guard)}, {"completion", completion_name(command.completion)}, {"operations", command.operations}}; + for (const auto& [name, value] : {std::pair{"icon", &command.icon}, + {"input", &command.input}, + {"tile_group", &command.tile_group}}) + if (!value->empty()) + entry[name] = *value; if (!command.examples.is_null()) entry["examples"] = command.examples; if (!command.tiles.is_null()) diff --git a/src/slic3r/GUI/CommandCatalog.hpp b/src/slic3r/GUI/CommandCatalog.hpp index 2902558fc0..be3f2f8165 100644 --- a/src/slic3r/GUI/CommandCatalog.hpp +++ b/src/slic3r/GUI/CommandCatalog.hpp @@ -37,10 +37,15 @@ struct NativeCommand { std::string key; std::string title; // untranslated English msgid; make_action() translates it for display - // A tile's section, an untranslated msgid as the title is. A typed tool without a tile is in the group of the way it - // acts, which search_tools filters by: core runs the session, recovers from dialogs and runs Python, api acts on - // project data by index and name with JSON in and out, and ui drives the GUI itself. + // What tool_search filters by. Outside the Design tab, the English heading of the command's place + // (NativeCommands::place_heading()): Objects, Plates, The app, the place its name starts with but for the two + // screenshot commands, which are under Recordings, replays and scripts; a plugin's operation is in Plugins. A + // Design command's is kDesignGroup, an untranslated msgid, which is also the Speed Dial section of its own tile and + // of its tiles. std::string group; + // The Speed Dial section of the command's own tile (in_palette), an untranslated msgid; empty where that tile is in + // `group`, as a Design command's is. + std::string tile_group; // "percent"/"tab": the palette's second phase, which collects the value the command needs before it // runs; "" to run at once. std::string input; @@ -53,33 +58,40 @@ struct NativeCommand nlohmann::json input_schema = {{"type", "object"}, {"properties", nlohmann::json::object()}}; // Calls that document the command: [{title, calls: [{tool, args}], needs?}], or null. nlohmann::json examples; - // The tiles of the menu rows folded into a Design command, [{key, title, icon, description, args}], or null: - // each, under the id of its key, runs the command with `args` (NativeCommands::make_action()). Its title is an - // untranslated msgid in title_context(), as the command's is. + // The tiles of the menu rows folded into the command, [{key, title, group?, icon, description, args, input?, + // input_arg?}] (NativeCommands::tile()), or null: each, under the id of its key, runs the command with `args` + // (NativeCommands::make_action()). Its title is an untranslated msgid in title_context(), as the command's is. + // group is its Speed Dial section, an untranslated msgid; a Design tile has none and is in the command's group. + // input is the Speed Dial's token for the value its second phase collects ("percent", "tab"), which the tile + // passes on under input_arg, the command's argument, or under the token where it has no input_arg. nlohmann::json tiles; - bool listed = false; // shown in tools/list: a typed tool + // shown in tools/list: every command outside the Design tab that runs from its arguments, all but three menu rows + bool listed = false; bool in_palette = false; // a person can pick it: it has a tile of its own, under its key // The access labels sent as MCP's annotations. Clients act on them: Codex asks a person before every call // of a destructive command, and Claude Code runs read-only calls in parallel and retries idempotent ones. - // read_only: it changes nothing in the app or the project; screenshot is, since its PNG replaces no file - // without overwrite, and export_replay, which can clear the journal, is not. destructive: every call deletes - // what a person made, with no undo: delete_preset. A command that can lose work only when an argument asks - // for it is not: new_project, generate_calibration_test and open_files drop unsaved changes only with - // discard_changes, and an output replaces a file only with overwrite. Nor is a command that runs what its - // arguments name (click and the other input tools, run_action, call_tool, run_replay, run_script), though + // read_only: it changes nothing in the app or the project; window_screenshot is, since its PNG replaces no file + // without overwrite, and replay_export, which can clear the journal, is not. destructive: every call deletes + // what a person made, with no undo: preset_delete and plugin_uninstall. A command that can lose work only when an + // argument asks for it is not: project_new, calibration_generate_test and project_open drop unsaved changes only + // with discard_changes, and an output replaces a file only with overwrite. Nor is a command that runs what its + // arguments name (widget_click and the other input tools, action_run, tool_call, replay_run, script_run), though // what it runs may be. The client sees both in the arguments, and the label would ask on every call. Nor is - // encode_recording, which deletes only a recording this session made, once its MP4 has replaced it. - // open_world: it can reach outside OrcaSlicer (a - // printer, the cloud account, the network, or anything the computer allows), including through what it runs. + // recording_encode, which deletes only a recording this session made, once its MP4 has replaced it, nor a command + // whose deletion has undo (object_delete, plate_delete). A command made from menu rows is neither read_only nor + // destructive. open_world: it can reach outside OrcaSlicer (a printer, the cloud account, the network, or anything + // the computer allows), including through what it runs: of the commands made from rows, printer_send, preset_sync, + // filament_sync_ams, app_check_for_updates, app_open_web_page and plugin_refresh; and plugin_enable and plugin_reload, + // which run a plugin's code and download a cloud plugin, and plugin_uninstall, whose Unsubscribe reaches the account. bool read_only = false, destructive = false, idempotent = false, open_world = false; GuardClass guard = GuardClass::Mutate; // inline_call: pure observation, which runs on the request thread and is never a job; everything that can // activate UI runs as a job instead, because activating UI can open a modal that blocks the call. journal: - // recorded by the session journal for export_replay; observation commands turn it off, except wait and - // screenshot, which a replay needs. + // recorded by the session journal for replay_export; observation commands turn it off, except app_wait and + // window_screenshot, which a replay needs. bool inline_call = false, journal = true; - // allowed_during_operation: may run while an MCP slice/export operation holds the project (cancel_job). - // cancellable: `cancel_job {job}` stops a running call that is not an operation (encode_recording); the + // allowed_during_operation: may run while an MCP slice/export operation holds the project (job_cancel). + // cancellable: `job_cancel {job}` stops a running call that is not an operation (recording_encode); the // function sees ToolContext::cancelled() and ends. bool allowed_during_operation = false, cancellable = false; // How long a call may run before the reply returns a job envelope and the call continues. @@ -100,17 +112,39 @@ inline const char* title_context(const NativeCommand& command) return command.group == kDesignGroup ? "Design" : nullptr; } -// The first of `command`'s tiles whose args are `args`, compared as JSON values, a null `args` as {}; nullptr when -// none is. +// A word view_set's tab takes for one of the main window's own pages, and the id of that page (MainFrame's TAB_ID_*). +struct TabWord +{ + const char* word; + const char* page; +}; +// The words of the main window's own pages. A word is its page's id, but for the Device tab's: device, whose page is +// monitor. The window's other pages (the web Device page, a plugin's) have no word and are named by their ids. +inline constexpr TabWord kTabWords[] = {{"home", "home"}, {"design", "design"}, + {"prepare", "prepare"}, {"preview", "preview"}, + {"device", "monitor"}, {"multi_device", "multi_device"}, + {"project", "project"}, {"calibration", "calibration"}}; + +// The first of `command`'s tiles that collect no value (no input) whose args are `args`, compared as JSON values, a +// null `args` as {}; nullptr when none is. const nlohmann::json* tile_with_args(const NativeCommand& command, const nlohmann::json& args); +// The arguments a pick of `tile`, an item of a command's tiles, runs its command with, given `args` (what +// action_run or the Speed Dial's second phase gives): the tile's args, and for a tile with an input the value `args` +// holds under that token, put under its input_arg, or under the token where it has none; a tab's page id that a word +// of kTabWords names is given as that word (the Device tab's monitor as device). For a command's own tile +// (`tile` null), `args` as they are, the call's own arguments. A person's pick, action_run and the description of a +// replay's step all run a tile with it. +nlohmann::json tile_call_args(const nlohmann::json* tile, const nlohmann::json& args); + // What a call of `command` with `args` is titled where a person is shown it (a recording's caption): the title of // tile_with_args(), else the command's. Untranslated, in title_context(command). std::string call_title(const NativeCommand& command, const nlohmann::json& args); -// What the reference says of a command: key, title, group, description, input_schema, examples and tiles when it -// has some, listed, in_palette, the four access labels, guard ("inspect", "recover", "mutate"), completion -// ("none", "export") and operations. All of it is the command's English text and constants, never translated. +// What the reference says of a command: key, title, group, description, input_schema, listed, in_palette, the four +// access labels, guard ("inspect", "recover", "mutate"), completion ("immediate", "deferred") and operations; icon, +// input and tile_group when they are not empty, and examples and tiles when it has some. All of it is the command's +// English text and constants, never translated. nlohmann::json command_reference(const NativeCommand& command); // Commands that come and go while the app runs (plugin operations). Any thread. @@ -171,6 +205,13 @@ private: // command added with add() has one. std::pair find_tile(const CommandCatalog& catalog, const std::string& key); +// What a call of `command` with `args` is titled where a person is shown it (a recording's caption), and the command +// whose title_context() that title is translated in: for action_run of a command's tile in `catalog` (args.id, the +// tile's id or the key inside it), the tile's title and that command, the command's own title for its own tile; for any +// other call, call_title() and `command`. Untranslated. +std::pair shown_title(const CommandCatalog& catalog, const NativeCommand& command, + const nlohmann::json& args); + // The reference of `catalog`: {"commands": [command_reference(), ...]} of the commands added with add(), in // the order they were added. Its sources' commands are left out: they are a plugin's, not the build's. // tests/data/command_catalog.json is this reference of the catalog a run with the Design tab holds, and the diff --git a/src/slic3r/GUI/CommandTypes.hpp b/src/slic3r/GUI/CommandTypes.hpp index 5222c3932b..bd90b1c51d 100644 --- a/src/slic3r/GUI/CommandTypes.hpp +++ b/src/slic3r/GUI/CommandTypes.hpp @@ -102,7 +102,7 @@ public: // Calls another tool as a child of this call (replay steps and a script's calls). Returns what a client would get: // the result, or a job envelope when the child outlives its reply budget. virtual ToolResult call_child(const std::string& tool, const nlohmann::json& args) = 0; - // This call's job and its ancestors, which `wait {for:"idle"}` must not wait for. + // This call's job and its ancestors, which `app_wait {for:"idle"}` must not wait for. virtual std::set lineage() const = 0; // Replaces the arguments the session journal records for this call (refs become locators). virtual void set_journal_args(nlohmann::json args) = 0; diff --git a/src/slic3r/GUI/FilamentMapPanel.cpp b/src/slic3r/GUI/FilamentMapPanel.cpp index 578c21c5e2..617598f36a 100644 --- a/src/slic3r/GUI/FilamentMapPanel.cpp +++ b/src/slic3r/GUI/FilamentMapPanel.cpp @@ -6,7 +6,10 @@ #include #include #include "libslic3r/Config.hpp" +#include "libslic3r/PresetBundle.hpp" #include "libslic3r/PrintConfig.hpp" +#include +#include #include #include #include @@ -44,75 +47,84 @@ static const wxColour TextErrorColor = wxColour("#E14747"); wxDEFINE_EVENT(wxEVT_INVALID_MANUAL_MAP, wxCommandEvent); +// The edited printer's extruder_max_nozzle_count, none where it lacks the option. +static std::vector max_nozzle_counts(const PresetBundle &preset_bundle) +{ + const auto *opt = preset_bundle.printers.get_edited_preset().config.option("extruder_max_nozzle_count"); + return opt != nullptr ? opt->values : std::vector(); +} + // Orca: whether the edited printer has an extruder that can physically carry several nozzles // (only such extruders track a per-volume-type nozzle inventory worth validating against). static bool printer_has_multi_nozzle_extruder() { - auto *max_nozzle_counts_opt = wxGetApp().preset_bundle->printers.get_edited_preset().config.option("extruder_max_nozzle_count"); + return has_multi_nozzle_extruder(max_nozzle_counts(*wxGetApp().preset_bundle)); +} + +bool has_multi_nozzle_extruder(const std::vector &max_nozzle_counts) +{ // Skip nil entries: a nullable-int nil is INT_MAX (> 1) and would otherwise falsely pass the gate. - return max_nozzle_counts_opt && - std::any_of(max_nozzle_counts_opt->values.begin(), max_nozzle_counts_opt->values.end(), + return std::any_of(max_nozzle_counts.begin(), max_nozzle_counts.end(), [](int v) { return v > 1 && v != ConfigOptionIntsNullable::nil_value(); }); } +NozzleInventory nozzle_inventory(const PresetBundle &preset_bundle) +{ + NozzleInventory inventory; + inventory.max_nozzle_counts = max_nozzle_counts(preset_bundle); + if (const auto *types = preset_bundle.project_config.option("nozzle_volume_type")) + inventory.volume_types = types->values; + if (const auto *stats = preset_bundle.printers.get_edited_preset().config.option("extruder_nozzle_stats")) + inventory.nozzle_counts = get_extruder_nozzle_stats(stats->values); + return inventory; +} + +std::optional manual_map_nozzle_shortage(const NozzleInventory &inventory, + const std::vector &filaments, + const std::vector &filament_map, + const std::vector &filament_volume_map) +{ + // Orca: only multi-nozzle extruders carry a meaningful nozzle inventory; validating a plain + // dual-extruder printer against it would flag every grouping whenever the stats are stale. + if (!has_multi_nozzle_extruder(inventory.max_nozzle_counts)) + return std::nullopt; + const auto nozzle_count = [&inventory](int eid, NozzleVolumeType volume_type) { + if (eid >= (int) inventory.nozzle_counts.size()) + return 0; + const auto it = inventory.nozzle_counts[eid].find(volume_type); + return it == inventory.nozzle_counts[eid].end() ? 0 : it->second; + }; + // Whether a filament the plate prints goes to extruder `eid`; with `volume_type`, with that nozzle volume type. + const auto prints_on = [&](int eid, std::optional volume_type) { + return std::any_of(filaments.begin(), filaments.end(), [&](int fid) { + return fid >= 1 && fid - 1 < (int) filament_map.size() && (filament_map[fid - 1] - 1) == eid && + (!volume_type || (fid - 1 < (int) filament_volume_map.size() && + filament_volume_map[fid - 1] == static_cast(*volume_type))); + }); + }; + for (int eid = 0; eid < (int) inventory.volume_types.size(); ++eid) { + if (!prints_on(eid, std::nullopt)) + continue; + const NozzleVolumeType extruder_volume_type = NozzleVolumeType(inventory.volume_types[eid]); + if (extruder_volume_type != nvtHybrid) { + if (nozzle_count(eid, extruder_volume_type) == 0) + return NozzleShortage{eid, extruder_volume_type}; + continue; + } + for (const NozzleVolumeType needed : {NozzleVolumeType::nvtStandard, NozzleVolumeType::nvtHighFlow}) + if (prints_on(eid, needed) && nozzle_count(eid, needed) == 0) + return NozzleShortage{eid, needed}; + } + return std::nullopt; +} + void FilamentMapManualPanel::OnTimer(wxTimerEvent &) { - bool valid = true; - int invalid_eid = -1; - NozzleVolumeType invalid_nozzle = NozzleVolumeType::nvtStandard; - auto preset_bundle = wxGetApp().preset_bundle; - auto proj_config = preset_bundle->project_config; - auto nozzle_volume_values = proj_config.option("nozzle_volume_type")->values; - std::vector filament_map = GetFilamentMaps(); - std::vector filament_volume_map = GetFilamentVolumeMaps(); - // Orca: only multi-nozzle extruders carry a meaningful nozzle inventory; validating a plain - // dual-extruder printer against it would flag every grouping whenever the stats are stale. - if (printer_has_multi_nozzle_extruder()) { - for (size_t eid = 0; eid < nozzle_volume_values.size(); ++eid) { - NozzleVolumeType extruder_volume_type = NozzleVolumeType(nozzle_volume_values[eid]); - bool extruder_used = std::find_if(m_filament_list.begin(), m_filament_list.end(), - [&filament_map, eid](int fid) { - return fid - 1 < (int) filament_map.size() && (filament_map[fid - 1] - 1) == (int) eid; - }) != m_filament_list.end(); - - if (!extruder_used) { - continue; - } - - if (extruder_volume_type == nvtHybrid) { - int standard_count = getExtruderNozzleCount(preset_bundle, eid, NozzleVolumeType::nvtStandard); - int highflow_count = getExtruderNozzleCount(preset_bundle, eid, NozzleVolumeType::nvtHighFlow); - - auto has_material_of_type = [this, eid, &filament_map, &filament_volume_map](NozzleVolumeType volume_type) { - return std::find_if(m_filament_list.begin(), m_filament_list.end(), - [eid, &filament_map, &filament_volume_map, volume_type](int fid) { - return fid - 1 < (int) filament_map.size() && (filament_map[fid - 1] - 1) == (int) eid && - fid - 1 < (int) filament_volume_map.size() && - filament_volume_map[fid - 1] == static_cast(volume_type); - }) != m_filament_list.end(); - }; - - bool has_standard = has_material_of_type(NozzleVolumeType::nvtStandard); - bool has_highflow = has_material_of_type(NozzleVolumeType::nvtHighFlow); - - if ((has_standard && standard_count == 0) || - (has_highflow && highflow_count == 0)) { - valid = false; - invalid_eid = eid; - invalid_nozzle = (has_standard && standard_count == 0) ? NozzleVolumeType::nvtStandard : NozzleVolumeType::nvtHighFlow; - break; - } - } else { - int count = getExtruderNozzleCount(preset_bundle, eid, extruder_volume_type); - if (count == 0) { - valid = false; - invalid_eid = eid; - invalid_nozzle = extruder_volume_type; - break; - } - } - } - } + const std::optional shortage = manual_map_nozzle_shortage(nozzle_inventory(*wxGetApp().preset_bundle), m_filament_list, + GetFilamentMaps(), GetFilamentVolumeMaps()); + const bool valid = !shortage; + const int invalid_eid = shortage ? shortage->extruder : -1; + const NozzleVolumeType invalid_nozzle = shortage ? shortage->volume_type : NozzleVolumeType::nvtStandard; bool update_ui = m_invalid_id != invalid_eid; bool send_event = update_ui || m_force_validation; diff --git a/src/slic3r/GUI/FilamentMapPanel.hpp b/src/slic3r/GUI/FilamentMapPanel.hpp index c165c76be6..dd357719a9 100644 --- a/src/slic3r/GUI/FilamentMapPanel.hpp +++ b/src/slic3r/GUI/FilamentMapPanel.hpp @@ -8,13 +8,53 @@ #include "Widgets/Label.hpp" #include #include +#include +#include #include #include #include #include #include "libslic3r/PrintConfig.hpp" -namespace Slic3r { namespace GUI { +namespace Slic3r { +class PresetBundle; + +namespace GUI { + +// The nozzles a printer's extruders carry, per extruder: the most nozzles it can hold (the printer's +// extruder_max_nozzle_count), its nozzle volume type (the project's nozzle_volume_type) and how many nozzles of each +// volume type it has (the printer's extruder_nozzle_stats, none of a type it lacks). +struct NozzleInventory +{ + std::vector max_nozzle_counts; + std::vector volume_types; + std::vector> nozzle_counts; +}; + +// The inventory of the printer being edited and the project. +NozzleInventory nozzle_inventory(const PresetBundle& preset_bundle); + +// Whether one of the extruders can hold several nozzles. Only such an extruder keeps an inventory worth checking: a +// plain multi-extruder printer has none, and checking it would refuse every grouping whenever its counts are stale. +bool has_multi_nozzle_extruder(const std::vector& max_nozzle_counts); + +// An extruder (0-based) that a manual filament grouping gives filaments and that has no nozzle of the volume type +// they need. +struct NozzleShortage +{ + int extruder = -1; + NozzleVolumeType volume_type = nvtStandard; +}; + +// The check the filament grouping dialog's Custom page makes before its OK can be pressed: the first extruder that +// `filament_map` (the 1-based extruder of each filament) gives one of `filaments` (the 1-based filaments the plate +// prints) and that has no nozzle of the volume type it needs. That type is the extruder's own, or on a Hybrid extruder +// each of the types `filament_volume_map` gives its filaments (Standard checked before High Flow). None on a printer +// with no multi-nozzle extruder. +std::optional manual_map_nozzle_shortage(const NozzleInventory& inventory, + const std::vector& filaments, + const std::vector& filament_map, + const std::vector& filament_volume_map); // Fired by the manual panel's validation timer: the event int is 1 when the current manual // grouping is printable with the installed nozzles, 0 when some zone has no matching nozzle. @@ -126,6 +166,7 @@ public: private: Label *m_label; }; -}} // namespace Slic3r::GUI +} // namespace GUI +} // namespace Slic3r #endif \ No newline at end of file diff --git a/src/slic3r/GUI/FileArchiveDialog.cpp b/src/slic3r/GUI/FileArchiveDialog.cpp index db71c2c21f..2d4077800d 100644 --- a/src/slic3r/GUI/FileArchiveDialog.cpp +++ b/src/slic3r/GUI/FileArchiveDialog.cpp @@ -189,6 +189,12 @@ ArchiveViewCtrl::~ArchiveViewCtrl() } } +bool is_archive_model(const boost::filesystem::path& path) +{ + static const std::regex pattern_drop(".*[.](stl|obj|amf|3mf|step|stp)", std::regex::icase); + return !boost::algorithm::starts_with(path.string(), "__MACOSX") && std::regex_match(path.extension().string(), pattern_drop); +} + FileArchiveDialog::FileArchiveDialog(wxWindow* parent_window, mz_zip_archive* archive, std::vector>& selected_paths_w_size) : DPIDialog(parent_window, wxID_ANY, _(L("Archive preview")), wxDefaultPosition, wxSize(45 * wxGetApp().em_unit(), 40 * wxGetApp().em_unit()), @@ -235,7 +241,6 @@ FileArchiveDialog::FileArchiveDialog(wxWindow* parent_window, mz_zip_archive* ar return struct_size + 1; }; - const std::regex pattern_drop(".*[.](stl|obj|amf|3mf|step|stp)", std::regex::icase); mz_uint num_entries = mz_zip_reader_get_num_files(archive); mz_zip_archive_file_stat stat; std::vector> filtered_entries; // second is unzipped size @@ -263,7 +268,7 @@ FileArchiveDialog::FileArchiveDialog(wxWindow* parent_window, mz_zip_archive* ar depth = std::max(depth, adjust_stack(path, stack)); if (!stack.empty()) parent = stack.back(); - if (std::regex_match(path.extension().string(), pattern_drop)) { // this leaves out non-compatible files + if (is_archive_model(path)) { // this leaves out non-compatible files std::shared_ptr new_node = m_avc->get_model()->AddFile(parent, boost::nowide::widen(path.filename().string()), false); new_node->set_fullpath(/*std::move(path)*/path); // filename string to wstring? new_node->set_size(entry.second); diff --git a/src/slic3r/GUI/FileArchiveDialog.hpp b/src/slic3r/GUI/FileArchiveDialog.hpp index 0afac1fd33..aa10c3811b 100644 --- a/src/slic3r/GUI/FileArchiveDialog.hpp +++ b/src/slic3r/GUI/FileArchiveDialog.hpp @@ -111,6 +111,10 @@ protected: }; +// Whether `path`, an entry of a ZIP archive, is a model file the archive's file list offers: a file named .stl, .obj, +// .amf, .3mf, .step or .stp, outside the __MACOSX folder macOS adds to an archive. +bool is_archive_model(const boost::filesystem::path& path); + class FileArchiveDialog : public DPIDialog { public: diff --git a/src/slic3r/GUI/GCodeViewer.cpp b/src/slic3r/GUI/GCodeViewer.cpp index b56bfa1af2..4b45dacb75 100644 --- a/src/slic3r/GUI/GCodeViewer.cpp +++ b/src/slic3r/GUI/GCodeViewer.cpp @@ -141,46 +141,53 @@ static void add_swatch(ImDrawList* draw_list, const ImVec2& min, const ImVec2& m draw_list->AddRectFilled(min, max, ImGuiWrapper::to_ImU32(color)); } -static std::string get_view_type_string(libvgcode::EViewType view_type) +// The English name of a view type, marked for translation; empty for a type the preview does not offer. +static const char* view_type_msgid(libvgcode::EViewType view_type) { if (view_type == libvgcode::EViewType::Summary) - return _u8L("Summary"); + return L("Summary"); else if (view_type == libvgcode::EViewType::FeatureType) - return _u8L("Line Type"); + return L("Line Type"); else if (view_type == libvgcode::EViewType::Height) - return _u8L("Layer Height"); + return L("Layer Height"); else if (view_type == libvgcode::EViewType::Width) - return _u8L("Line Width"); + return L("Line Width"); else if (view_type == libvgcode::EViewType::Speed) - return _u8L("Speed"); + return L("Speed"); else if (view_type == libvgcode::EViewType::ActualSpeed) - return _u8L("Actual Speed"); + return L("Actual Speed"); else if (view_type == libvgcode::EViewType::Acceleration) - return _u8L("Acceleration"); + return L("Acceleration"); else if (view_type == libvgcode::EViewType::Jerk) - return _u8L("Jerk"); + return L("Jerk"); else if (view_type == libvgcode::EViewType::FanSpeed) - return _u8L("Fan Speed"); + return L("Fan Speed"); else if (view_type == libvgcode::EViewType::Temperature) - return _u8L("Temperature"); + return L("Temperature"); else if (view_type == libvgcode::EViewType::VolumetricFlowRate) - return _u8L("Flow"); + return L("Flow"); else if (view_type == libvgcode::EViewType::ActualVolumetricFlowRate) - return _u8L("Actual Flow"); + return L("Actual Flow"); else if (view_type == libvgcode::EViewType::Tool) - return _u8L("Tool"); + return L("Tool"); else if (view_type == libvgcode::EViewType::ColorPrint) - return _u8L("Filament"); + return L("Filament"); else if (view_type == libvgcode::EViewType::LayerTimeLinear) - return _u8L("Layer Time"); + return L("Layer Time"); else if (view_type == libvgcode::EViewType::LayerTimeLogarithmic) - return _u8L("Layer Time (log)"); + return L("Layer Time (log)"); // ORCA: Add Pressure Advance visualization support else if (view_type == libvgcode::EViewType::PressureAdvance) - return _u8L("Pressure Advance"); + return L("Pressure Advance"); return ""; } +static std::string get_view_type_string(libvgcode::EViewType view_type) +{ + const char* msgid = view_type_msgid(view_type); + return *msgid == '\0' ? std::string() : _u8L(msgid); +} + // ORCA: Stable, locale independent names used to persist a view type in the application config. // Keep these in sync with the entries of libvgcode::EViewType exposed in the preview combo box. static const std::vector>& view_type_config_map() @@ -1268,11 +1275,11 @@ bool GCodeViewer::view_type_from_config_name(const std::string& name, libvgcode: std::vector> GCodeViewer::default_view_type_choices() { std::vector> choices = { - { "auto", _u8L("Automatic") }, - { "last", _u8L("Last used") }, + { "auto", L("Automatic") }, + { "last", L("Last used") }, }; for (const auto& [name, type] : view_type_config_map()) - choices.push_back({ name, get_view_type_string(type) }); + choices.push_back({ name, view_type_msgid(type) }); return choices; } diff --git a/src/slic3r/GUI/GCodeViewer.hpp b/src/slic3r/GUI/GCodeViewer.hpp index fc897b91e8..83b3b40f38 100644 --- a/src/slic3r/GUI/GCodeViewer.hpp +++ b/src/slic3r/GUI/GCodeViewer.hpp @@ -553,13 +553,16 @@ public: bool can_switch_time_mode() const; // What the legend's "Show stealth mode" / "Show normal mode" button does. void set_time_mode(libvgcode::ETimeMode mode); + // The legend folded to its title row, as its fold button leaves it; picking a view type unfolds it. + bool is_legend_folded() const { return m_fold; } + void fold_legend(bool fold) { m_fold = fold; } // ORCA: apply the "preview_default_view_type" preference, see the definition for the supported values void apply_default_view_type(); // ORCA: stable, locale independent name of a view type, as stored in the application config static std::string view_type_to_config_name(libvgcode::EViewType type); static bool view_type_from_config_name(const std::string& name, libvgcode::EViewType& type); - // ORCA: (config value, translated label) pairs for the "preview_default_view_type" preference combo box + // ORCA: (config value, English label marked for translation) pairs for the "preview_default_view_type" preference static std::vector> default_view_type_choices(); void reset_visible(libvgcode::EViewType type) { if (type == libvgcode::EViewType::FeatureType) { diff --git a/src/slic3r/GUI/GLCanvas3D.hpp b/src/slic3r/GUI/GLCanvas3D.hpp index 4057864c82..534bc4569b 100644 --- a/src/slic3r/GUI/GLCanvas3D.hpp +++ b/src/slic3r/GUI/GLCanvas3D.hpp @@ -1200,6 +1200,7 @@ public: void share_section_view(const GLCanvas3D& owner) { m_section_view = owner.m_section_view; } void toggle_world_axes_visibility(bool force_show = false); + bool are_world_axes_shown() const { return m_show_world_axes; } void refresh_camera_scene_box(); void set_color_by(const std::string& value); diff --git a/src/slic3r/GUI/GUI_App.cpp b/src/slic3r/GUI/GUI_App.cpp index 38fff5c60e..7c98d383de 100644 --- a/src/slic3r/GUI/GUI_App.cpp +++ b/src/slic3r/GUI/GUI_App.cpp @@ -73,6 +73,8 @@ #include #include "slic3r/GUI/Monitor.hpp" #include "slic3r/GUI/OpenGLManager.hpp" +#include "slic3r/GUI/Operations/PluginOps.hpp" +#include "slic3r/GUI/Operations/PreferenceOps.hpp" #include "slic3r/GUI/DeviceCore/DevDefs.h" #include #include "slic3r/GUI/UserNotification.hpp" @@ -3360,7 +3362,7 @@ bool GUI_App::on_init_inner() // Slic3r::debugf "wxWidgets version %s, Wx version %s\n", wxVERSION_STRING, wxVERSION; // The command catalog, before anything that runs or lists a command: the automation runtime below and the // Speed Dial's action registry. Then the Python scripts setting's value in force, before the endpoint opens and - // the command line's run starts, so that get_app_state and the first script read it. Each value in force is the + // the command line's run starts, so that app_state and the first script read it. Each value in force is the // preference, or the command line's flag (--cad, --unrestricted-scripts). The CAD feature's is read here from the // config and the launch parameters, since is_enable_cad_feature() is in a CAD build only. const bool cad_in_force = app_config->get_bool("enable_cad_feature") || (init_params != nullptr && init_params->cad); @@ -9202,20 +9204,14 @@ void GUI_App::notify_plugin_permissions_changed(const std::string& plugin_key) m_plugins_dlg->refresh_permissions_if_visible(); } -void GUI_App::refresh_plugins() +Ops::RefreshTicket GUI_App::refresh_plugins() { - // The metadata refresh blocks on disc discovery and a cloud round-trip, so run it on a worker - // and report completion through the notification manager -- the speed dial needs no dialog. - std::thread([]() { - wxString error; - bool unknown_error = false; - try { - refresh_plugin_metadata_blocking(/*fetch_cloud=*/true); - } catch (const std::exception& ex) { - error = from_u8(ex.what()); - } catch (...) { - unknown_error = true; // translated in CallAfter: wx translation isn't safe off the UI thread - } + // The metadata refresh blocks on disc discovery and a cloud round-trip, so it runs off the UI thread, after + // the refreshes asked for before it, and the notification manager reports its end -- the speed dial needs no + // dialog. + return Ops::start_plugin_refresh([](const std::string& what, bool unknown_error) { + // An unknown failure's text is translated in CallAfter: wx translation isn't safe off the UI thread. + const wxString error = from_u8(what); if (!wxTheApp) return; wxTheApp->CallAfter([error, unknown_error]() { @@ -9236,7 +9232,7 @@ void GUI_App::refresh_plugins() NotificationManager::NotificationLevel::ErrorNotificationLevel, into_u8(wxString::Format(_L("Failed to refresh plugins: %s"), unknown_error ? _L("Unknown error") : error))); }); - }).detach(); + }); } void GUI_App::update_plugins_dialog() @@ -9311,14 +9307,9 @@ void GUI_App::open_preferences() { open_preferences(PreferencesTab::General); } void GUI_App::open_preferences(PreferencesTab tab, const std::string& highlight_option) { // Render settings the canvas reads every frame; a change needs one redraw to show. - static constexpr const char* opengl_render_setting_keys[] = { - SETTING_OPENGL_FXAA_ENABLED, SETTING_OPENGL_FPS_CAP, SETTING_OPENGL_SHOW_FPS_OVERLAY, SETTING_OPENGL_SHOW_RENDER_TIMINGS, - SETTING_OPENGL_SCENE_CACHE, SETTING_OPENGL_SKIP_IDENTICAL_FRAMES, SETTING_OPENGL_REALISTIC_SHADOWS, - SETTING_OPENGL_REALISTIC_GLOSS, SETTING_OPENGL_OUTLINE_PERSISTENT, SETTING_OPENGL_OUTLINE_COLOR, - SETTING_OPENGL_SELECTION_OUTLINE_COLOR - }; + const std::vector& opengl_render_setting_keys = Ops::canvas_preferences(); std::vector previous_opengl_render_settings; - for (const char* key : opengl_render_setting_keys) + for (const std::string& key : opengl_render_setting_keys) previous_opengl_render_settings.emplace_back(app_config->get(key)); bool need_recreate_gui = false; diff --git a/src/slic3r/GUI/GUI_App.hpp b/src/slic3r/GUI/GUI_App.hpp index 71c2144ac5..6ef3fe0e80 100644 --- a/src/slic3r/GUI/GUI_App.hpp +++ b/src/slic3r/GUI/GUI_App.hpp @@ -107,6 +107,9 @@ class Downloader; struct GUI_InitParams; class ParamsDialog; class HMSQuery; +namespace Ops { +class RefreshTicket; +} class ModelMallDialog; class PingCodeBindDialog; class PresetBundleDialog; @@ -775,8 +778,10 @@ public: // Called on the GUI thread after an audit prompt stores a grant outside the Plugins dialog. // Refreshes an existing dialog instance; never creates or raises it. void notify_plugin_permissions_changed(const std::string& plugin_key); - // Dialog-free plugin action used by the speed dial: it never requires the Plugins dialog to be open. - void refresh_plugins(); + // Refresh Plugins, which needs no Plugins dialog: starts a run of Ops::start_plugin_refresh(), whose end a + // notification reports, and returns its ticket. A refresh asked for while one waits or runs is a run of its own + // after it, with a notification of its own. GUI thread. + Ops::RefreshTicket refresh_plugins(); // Shows the current plugin list in the Plugins dialog when it is open, after a change made outside it // (the speed dial's refresh or install, a plugin loading). GUI thread; never creates or raises it. void update_plugins_dialog(); diff --git a/src/slic3r/GUI/GUI_Factories.cpp b/src/slic3r/GUI/GUI_Factories.cpp index ce2d98aa35..b2e3718a63 100644 --- a/src/slic3r/GUI/GUI_Factories.cpp +++ b/src/slic3r/GUI/GUI_Factories.cpp @@ -210,7 +210,11 @@ std::vector SettingsFactory::get_options(const bool is_part) options.erase(find(options.begin(), options.end(), "layer_height")); return options; } + return get_fff_options(is_part); +} +std::vector SettingsFactory::get_fff_options(const bool is_part) +{ PrintRegionConfig reg_config; auto options = reg_config.keys(); if (!is_part) { diff --git a/src/slic3r/GUI/GUI_Factories.hpp b/src/slic3r/GUI/GUI_Factories.hpp index 16a50f05f3..7cfaa046fb 100644 --- a/src/slic3r/GUI/GUI_Factories.hpp +++ b/src/slic3r/GUI/GUI_Factories.hpp @@ -43,6 +43,9 @@ struct SettingsFactory static wxBitmap get_category_bitmap(const std::string& category_name, bool menu_bmp = true); static Bundle get_bundle(const DynamicPrintConfig* config, bool is_object_settings, bool is_layer_settings = false); static std::vector get_options(bool is_part); + // get_options() for an FFF printer, which reads no printer: the region settings for a part or modifier, and the + // object settings too for an object. + static std::vector get_fff_options(bool is_part); // Options of this category are not offered to objects (is_object_settings) or to parts and // modifiers: internal options without a category, and per-feature filaments with one filament. static bool is_improper_category(const std::string& category, int filaments_cnt, bool is_object_settings = true); diff --git a/src/slic3r/GUI/GUI_ObjectList.cpp b/src/slic3r/GUI/GUI_ObjectList.cpp index 511cdee58c..db61e165d7 100644 --- a/src/slic3r/GUI/GUI_ObjectList.cpp +++ b/src/slic3r/GUI/GUI_ObjectList.cpp @@ -96,7 +96,8 @@ #include #include -#include "slic3r/Utils/FixModelByCgal.hpp" +#include "Operations/ObjectOps.hpp" +#include "Operations/Outcome.hpp" #include "libslic3r/Format/bbs_3mf.hpp" #include "libslic3r/Orient.hpp" #include "libslic3r/PrintConfig.hpp" @@ -965,7 +966,7 @@ void ObjectList::update_name_for_items() wxGetApp().plater()->update(); } -void ObjectList::object_config_options_changed(const ObjectVolumeID& ov_id) +void ObjectList::object_config_options_changed(const ObjectVolumeID& ov_id, const t_layer_height_range* range) { if (ov_id.object == nullptr) return; @@ -974,6 +975,15 @@ void ObjectList::object_config_options_changed(const ObjectVolumeID& ov_id) ModelObject* mo = ov_id.object; ModelVolume* mv = ov_id.volume; + if (range != nullptr) { + // A height range's row, as a change in the range's panel marks it (TabPrintLayer::notify_changed()). + const auto config = mo->layer_config_ranges.find(*range); + const auto obj = std::find(objects.begin(), objects.end(), mo); + if (config != mo->layer_config_ranges.end() && obj != objects.end()) + add_settings_item(m_objects_model->GetItemByLayerRange(int(obj - objects.begin()), *range), &config->second.get()); + return; + } + wxDataViewItem obj_item = m_objects_model->GetObjectItem(mo); if (mv != nullptr) { size_t vol_idx; @@ -2078,33 +2088,7 @@ void ObjectList::OnDrop(wxDataViewEvent &event) take_snapshot(_u8L("Object order changed")); if(m_dragged_data.type() & itObject){ - int delta = dest_obj_id < src_obj_id ? -1 : 1; - PartPlateList& partplate_list = wxGetApp().plater()->get_partplate_list(); - /*int cnt = 0, cur_id = src_obj_id, next_id, total = abs(src_obj_id - dest_obj_id); - //for (cur_id = src_obj_id; cnt < total; id += delta, cnt++) - next_id = src_obj_id + delta; - while (cnt < total) - { - int cur_plate = partplate_list.find_instance(next_id, 0); - if (cur_plate != src_plate) { - cnt ++; - next_id += delta; - continue; - } - std::swap((*m_objects)[cur_id], (*m_objects)[next_id]); - cur_id = next_id; - cnt ++; - next_id += delta; - }*/ - - int cnt = 0; - for (int id = src_obj_id; cnt < abs(src_obj_id - dest_obj_id); id += delta, cnt++) - std::swap((*m_objects)[id], (*m_objects)[id + delta]); - - select_item(m_objects_model->ReorganizeObjects(src_obj_id, dest_obj_id)); - - partplate_list.reload_all_objects(false, src_plate); - changed_object(src_obj_id); + move_object(src_obj_id, dest_obj_id, src_plate); } else if (m_dragged_data.type() & itVolume) { int from_volume_id = m_dragged_data.sub_obj_idx(); @@ -2690,7 +2674,9 @@ void ObjectList::load_generic_subobject(const std::string& type_name, const Mode Plater::SingleSnapshot single(wxGetApp().plater()); if (type == ModelVolumeType::INVALID) { - load_shape_object(type_name, interactive, given_size); + // Add Primitive adds nothing while an object is selected on the 3D scene. + if (can_add_shape_object()) + load_shape_object(type_name, interactive, given_size); return; } @@ -2801,10 +2787,6 @@ bool ObjectList::can_add_shape_object() const void ObjectList::load_shape_object(const std::string &type_name, bool interactive, const std::vector& given_size) { - // Add nothing while an object is selected on the 3D scene. - if (!can_add_shape_object()) - return; - const int obj_idx = m_objects->size(); if (obj_idx < 0) return; @@ -3169,6 +3151,18 @@ void ObjectList::split() if (!item || obj_idx < 0) return; + ModelVolume* volume = nullptr; + if (!(*m_objects)[obj_idx]->hides_imported_parts() && !get_volume_by_item(item, volume)) + return; + // The object's row stands for its one part. + const ModelVolumePtrs& volumes = (*m_objects)[obj_idx]->volumes; + const ItemType type = m_objects_model->GetItemType(item); + split(obj_idx, volume == nullptr || type != itVolume ? -1 : int(std::find(volumes.begin(), volumes.end(), volume) - volumes.begin()), + type == itObject); +} + +void ObjectList::split(int obj_idx, int volume_idx, bool expand) +{ ModelObject* imported = (*m_objects)[obj_idx]; if (imported->hides_imported_parts()) { // Reveal the original CAD bodies, including their names and exact transforms. @@ -3179,8 +3173,9 @@ void ObjectList::split() return; } - ModelVolume* volume; - if (!get_volume_by_item(item, volume)) return; + if (volume_idx < 0 && imported->volumes.size() != 1) + return; + ModelVolume* volume = imported->volumes[volume_idx < 0 ? 0 : std::size_t(volume_idx)]; DynamicPrintConfig& config = printer_config(); // BBS const ConfigOptionStrings* filament_colors = config.option("filament_colour", false); @@ -3198,11 +3193,8 @@ void ObjectList::split() auto model_object = (*m_objects)[obj_idx]; - auto parent = m_objects_model->GetObject(item); - if (parent) - m_objects_model->DeleteVolumeChildren(parent); - else - parent = item; + wxDataViewItem parent = m_objects_model->GetItemById(obj_idx); + m_objects_model->DeleteVolumeChildren(parent); for (const ModelVolume* volume : model_object->volumes) { const wxDataViewItem& vol_item = m_objects_model->AddVolumeChild(parent, from_u8(volume->name), @@ -3218,7 +3210,7 @@ void ObjectList::split() model_object->input_file.clear(); - if (parent == item) + if (expand) Expand(parent); changed_object(obj_idx); @@ -3229,11 +3221,19 @@ void ObjectList::split() update_info_items(obj_idx); } -void ObjectList::merge(bool to_multipart_object) +void ObjectList::merge(bool to_multipart_object, const wxDataViewItemArray& items) { wxBusyCursor wait; // merge selected objects to the multipart object if (to_multipart_object) { + // The rows given are selected first: the instances are split off into objects of their own, and the merged + // objects removed, as the selected rows. + if (!items.IsEmpty()) { + m_prevent_list_events = true; + UnselectAll(); + SetSelections(items); + m_prevent_list_events = false; + } auto get_object_idxs = [this](std::vector& obj_idxs, wxDataViewItemArray& sels) { // check selections and split instances to the separated objects... @@ -6173,14 +6173,15 @@ static void move_volume_to_end(ModelObject* obj, ModelVolume* volume) } } -wxString ObjectList::set_volume_type(ModelVolumeType new_type, bool preserve_ps_subtype, bool show_errors) +wxString ObjectList::set_volume_type(ModelVolumeType new_type, bool preserve_ps_subtype, bool show_errors, + const std::vector>& parts) { struct VolumeSelection { int object_idx; ModelVolume* volume; }; - // --- Collect selected volumes from the object tree, falling back to the 3D canvas --- + // --- Collect the parts given, else the selected volumes from the object tree, falling back to the 3D canvas --- std::vector volumes; auto add_volume = [&volumes](int obj_idx, ModelVolume* volume) { // A painted modifier has no shape of its own to keep as another type. @@ -6191,8 +6192,12 @@ wxString ObjectList::set_volume_type(ModelVolumeType new_type, bool preserve_ps_ volumes.push_back({ obj_idx, volume }); }; + for (const auto& [obj_idx, vol_idx] : parts) + add_volume(obj_idx, (*m_objects)[obj_idx]->volumes[vol_idx]); + wxDataViewItemArray sels; - GetSelections(sels); + if (parts.empty()) + GetSelections(sels); for (auto item : sels) { wxDataViewItem volume_item = item; ItemType type = m_objects_model->GetItemType(item); @@ -6228,6 +6233,9 @@ wxString ObjectList::set_volume_type(ModelVolumeType new_type, bool preserve_ps_ } }; + // Parts given are what changes, painted modifiers aside, and the selection is not read. + if (volumes.empty() && !parts.empty()) + return {}; if (volumes.empty()) { collect_from_canvas(wxGetApp().plater()->canvas3D()); if (volumes.empty()) { @@ -6646,13 +6654,6 @@ void ObjectList::fix_through_cgal(const std::vector &obj_idxs, const std::v if (obj_idxs.empty() || !wxGetApp().plater()->get_view3D_canvas3D()->get_gizmos_manager().check_gizmos_closed_except(GLGizmosManager::Undefined)) return; - // model_name - std::vector succes_models; - // model_name failing reason - std::vector> failed_models; - size_t unchanged_models = 0; - bool painting_removed = false; - std::vector model_names; if (vol_idxs.empty()) { @@ -6669,77 +6670,62 @@ void ObjectList::fix_through_cgal(const std::vector &obj_idxs, const std::v } auto plater = wxGetApp().plater(); - const bool keep_painting = GUI::wxGetApp().app_config->get_bool("keep_painting"); - auto fix_and_update_progress = [&](const int obj_idx, const int vol_idx, int model_idx, ProgressDialog& progress_dlg) - { - ModelObject *mo = object(obj_idx); - if (!mo) - return false; + // The objects whole, or the parts of the first object, as Ops::fix_objects() repairs them in turn. + Ops::FixObjectsArgs repair; + if (vol_idxs.empty()) + repair.targets.objects = obj_idxs; + else + for (int vol_idx : vol_idxs) + repair.targets.parts.emplace_back(obj_idxs.front(), vol_idx); + // Open a progress dialog. + ProgressDialog progress_dlg(_L("Repairing model object"), "", 100, find_toplevel_parent(plater), + wxPD_AUTO_HIDE | wxPD_APP_MODAL | wxPD_CAN_ABORT, true); + const auto shown = [&](std::size_t model_idx, int percent, const std::string& what) { const std::string& model_name = model_names[model_idx]; wxString msg = _L("Repairing model object"); if (model_names.size() == 1) msg += ": " + from_u8(model_name) + "\n"; else if (model_names.size() > 10) - msg += ": " + from_u8(model_name) + wxString::Format(" (%d/%d)", model_idx + 1, int(model_names.size())) + "\n"; + msg += ": " + from_u8(model_name) + wxString::Format(" (%d/%d)", int(model_idx) + 1, int(model_names.size())) + "\n"; else { msg += ":\n"; - for (int i = 0; i < int(model_names.size()); ++i) + for (std::size_t i = 0; i < model_names.size(); ++i) msg += (i == model_idx ? " > " : " ") + from_u8(model_names[i]) + "\n"; msg += "\n"; } - - auto count_painted = [mo]() { return std::count_if(mo->volumes.begin(), mo->volumes.end(), [](const ModelVolume *mv) { return mv->is_any_painted(); }); }; - const auto painted_before = count_painted(); - std::string res; - bool modified = false; - if (!fix_model_with_cgal_gui(*mo, vol_idx, progress_dlg, msg, res, keep_painting, &modified)) + // One percent short of the maximum, so that the dialog does not close itself. + if (!progress_dlg.Update(std::max(0, percent - 1), msg + from_u8(what))) return false; - - if (modified) { - painting_removed = painting_removed || count_painted() < painted_before; - mo->ensure_on_bed(); - plater->changed_mesh(obj_idx); - plater->get_partplate_list().notify_instance_update(obj_idx, 0); - plater->sidebar().obj_list()->update_plate_values_for_items(); - update_item_error_icon(obj_idx, vol_idx); - update_info_items(obj_idx); - } - - if (!res.empty()) - failed_models.push_back({ model_name, res }); - else if (modified) - succes_models.push_back(model_name); - else - ++unchanged_models; + progress_dlg.Fit(); return true; }; - - Plater::TakeSnapshot snapshot(plater, _u8L("Repairing model object")); - - // Open a progress dialog. - ProgressDialog progress_dlg(_L("Repairing model object"), "", 100, find_toplevel_parent(plater), - wxPD_AUTO_HIDE | wxPD_APP_MODAL | wxPD_CAN_ABORT, true); - int model_idx{ 0 }; - if (vol_idxs.empty()) { - int vol_idx{ -1 }; - for (int obj_idx : obj_idxs) { - if (!fix_and_update_progress(obj_idx, vol_idx, model_idx, progress_dlg)) - break; - model_idx++; - } - } - else { - int obj_idx{ obj_idxs.front() }; - for (int vol_idx : vol_idxs) { - if (!fix_and_update_progress(obj_idx, vol_idx, model_idx, progress_dlg)) - break; - model_idx++; - } - } + // The gizmo check above is the operation's only refusal here. + const Ops::Outcome fixed = Ops::fix_objects(repair, shown); // Close the progress dialog progress_dlg.Update(100, ""); + if (!fixed) + return; + + // model_name + std::vector succes_models; + // model_name failing reason + std::vector> failed_models; + size_t unchanged_models = 0; + bool painting_removed = false; + for (const Ops::FixedModel& model : fixed.value().models) { + // The notification tells the models whose repair ended; the one a Cancel stopped is left out of it. + if (model.cancelled) + continue; + painting_removed = painting_removed || model.painting_removed; + if (!model.failed.empty()) + failed_models.push_back({ model.name, model.failed }); + else if (model.changed) + succes_models.push_back(model.name); + else + ++unchanged_models; + } if (painting_removed) plater->notify_painting_removed(); @@ -7325,47 +7311,124 @@ void set_import_volume_order(ModelObject& object, bool sort_names) parts[i]->import_display_order = static_cast(i); } -void ObjectList::order_objects(ObjectOrder order, bool all_plates) +std::vector plate_order(const std::vector& objects, const std::function& plate_of, int plate, + ObjectOrder order, bool descending) +{ + std::map> slots; // each plate's list positions, in order + for (size_t obj_idx = 0; obj_idx < objects.size(); ++obj_idx) + if (const int on = plate_of(obj_idx); on >= 0 && (plate < 0 || on == plate)) + slots[on].push_back(obj_idx); + std::vector out = objects; + for (const auto& [on, positions] : slots) { + std::vector plate_objects; + for (size_t obj_idx : positions) + plate_objects.push_back(objects[obj_idx]); + sort_objects(plate_objects, order, descending); + for (size_t i = 0; i < positions.size(); ++i) + out[positions[i]] = plate_objects[i]; + } + return out; +} + +void move_object_in_list(std::vector& objects, int from, int to) +{ + const int delta = to < from ? -1 : 1; + for (int id = from; id != to; id += delta) + std::swap(objects[id], objects[id + delta]); +} + +Ops::Outcome> object_order_moves(const std::vector& plate_of, int plate, const std::vector& order) +{ + const int count = int(plate_of.size()); + std::set named; + for (const int object : order) { + if (count == 0) + return Ops::Refusal{Ops::RefusalKind::Precondition, "no_such_object", L("The project has no objects.")}; + if (object < 0 || object >= count) + return Ops::Refusal{Ops::RefusalKind::Precondition, "no_such_object", + // TRN %1% is the object index asked for, %2% the last object's. + L("Object %1% does not exist: the project has objects 0 to %2%."), + {std::to_string(object), std::to_string(count - 1)}}; + if (plate_of[std::size_t(object)] != plate) + return Ops::Refusal{Ops::RefusalKind::Precondition, "object_not_on_plate", + // TRN %1% is an object's index, %2% a plate's. + L("Object %1% is not on plate %2%."), {std::to_string(object), std::to_string(plate)}}; + if (!named.insert(object).second) + return Ops::Refusal{Ops::RefusalKind::Precondition, "order_repeats_object", + // TRN %1% is an object's index. + L("The order names object %1% twice."), {std::to_string(object)}}; + } + std::vector missing; + for (int object = 0; object < count; ++object) + if (plate_of[std::size_t(object)] == plate && named.count(object) == 0) + missing.push_back(std::to_string(object)); + if (!missing.empty()) { + std::string list; + for (const std::string& object : missing) + list += (list.empty() ? "" : ", ") + object; + return Ops::Refusal{Ops::RefusalKind::Precondition, "order_misses_object", + // TRN %1% is a plate's index, %2% the indices of the objects left out, separated by commas. + L("The order leaves out objects of plate %1%: %2%. Name each of its objects once."), + {std::to_string(plate), list}, missing}; + } + + // Each object in turn is dropped on the object that holds its place, as the list's positions stand after the drops + // before it. + std::vector listed(plate_of.size()); + std::vector moves; + for (int position = 0; position < count; ++position) + listed[std::size_t(position)] = position; + for (std::size_t k = 0; k < order.size(); ++k) { + int seen = -1, to = -1, from = -1; + for (int position = 0; position < count; ++position) { + const int object = listed[std::size_t(position)]; + if (plate_of[std::size_t(object)] == plate && ++seen == int(k)) + to = position; + if (object == order[k]) + from = position; + } + if (from == to) + continue; + moves.push_back({from, to}); + const int delta = to < from ? -1 : 1; + for (int id = from; id != to; id += delta) + std::swap(listed[std::size_t(id)], listed[std::size_t(id + delta)]); + } + return moves; +} + +void ObjectList::order_objects(ObjectOrder order, bool all_plates, int plate, std::optional descending) { Plater* plater = wxGetApp().plater(); if (!plater->get_view3D_canvas3D()->get_gizmos_manager().check_gizmos_closed_except(GLGizmosManager::Undefined)) return; PartPlateList& plates = plater->get_partplate_list(); - const int curr_plate = plates.get_curr_plate_index(); - auto sorted = [&](bool descending) { - std::vector objects = *m_objects; - for (int plate_idx = 0; plate_idx < plates.get_plate_count(); ++plate_idx) { - if (!all_plates && plate_idx != curr_plate) - continue; - // Sort within the list positions the plate already holds, so other plates keep their order. - std::vector slots; - std::vector plate_objects; - for (size_t obj_idx = 0; obj_idx < objects.size(); ++obj_idx) - if (plates.find_instance(int(obj_idx), 0) == plate_idx) { - slots.push_back(obj_idx); - plate_objects.push_back(objects[obj_idx]); - } - sort_objects(plate_objects, order, descending); - for (size_t i = 0; i < slots.size(); ++i) - objects[slots[i]] = plate_objects[i]; - } - return objects; - }; - // Choosing the order the objects already have reverses it. - std::vector objects = sorted(false); - if (objects == *m_objects) + const int sort_plate = plate >= 0 ? plate : plates.get_curr_plate_index(); + const auto plate_of = [&plates](size_t obj_idx) { return plates.find_instance(int(obj_idx), 0); }; + const auto sorted = [&](bool descending) { return plate_order(*m_objects, plate_of, all_plates ? -1 : sort_plate, order, descending); }; + std::vector objects = sorted(descending.value_or(false)); + // Choosing the order the objects already have reverses it, unless the direction is given. + if (!descending && objects == *m_objects) objects = sorted(true); if (objects != *m_objects) { take_snapshot(_u8L("Object order changed")); *m_objects = std::move(objects); - plates.reload_all_objects(false, all_plates ? -1 : curr_plate); + plates.reload_all_objects(false, all_plates ? -1 : sort_plate); } // Rebuilt even when the order holds: an object moved to another plate is listed last there. reload_all_plates(); } +void ObjectList::move_object(int from, int to, int plate) +{ + move_object_in_list(*m_objects, from, to); + select_item(m_objects_model->ReorganizeObjects(from, to)); + wxGetApp().plater()->get_partplate_list().reload_all_objects(false, plate); + changed_object(from); +} + void ObjectList::on_plate_selected(int plate_index) { wxDataViewItem item = m_objects_model->GetItemByPlateId(plate_index); @@ -7454,6 +7517,8 @@ void ObjectList::toggle_printable_state() // BBS: remove snapshot name "Set Printable group", "Set Unprintable group", "Set Printable"... take_snapshot(""); + // An object row sets every instance of its object, an instance row its instance alone. + Ops::Targets rows; std::vector obj_idxs; for (auto item : sels) { @@ -7462,22 +7527,18 @@ void ObjectList::toggle_printable_state() continue; obj_idx = m_objects_model->GetObjectIdByItem(item); - ModelObject* obj = object(obj_idx); - obj_idxs.emplace_back(static_cast(obj_idx)); - - // set printable value for selected instance/instances in object - if (type == itInstance) { - inst_idx = m_objects_model->GetInstanceIdByItem(item); - obj->instances[m_objects_model->GetInstanceIdByItem(item)]->printable = printable; - } + if (type == itInstance) + rows.instances.emplace_back(obj_idx, m_objects_model->GetInstanceIdByItem(item)); else - for (auto inst : obj->instances) - inst->printable = printable; - - // update printable state in ObjectList - m_objects_model->SetObjectPrintableState(printable ? piPrintable : piUnprintable, item); + rows.objects.push_back(obj_idx); } + Ops::set_printable(wxGetApp().plater()->model(), rows, printable); + + // update printable state in ObjectList + for (auto item : sels) + if (m_objects_model->GetItemType(item) & (itObject | itInstance)) + m_objects_model->SetObjectPrintableState(printable ? piPrintable : piUnprintable, item); sort(obj_idxs.begin(), obj_idxs.end()); obj_idxs.erase(unique(obj_idxs.begin(), obj_idxs.end()), obj_idxs.end()); diff --git a/src/slic3r/GUI/GUI_ObjectList.hpp b/src/slic3r/GUI/GUI_ObjectList.hpp index 80b3c0c682..2f2117b16d 100644 --- a/src/slic3r/GUI/GUI_ObjectList.hpp +++ b/src/slic3r/GUI/GUI_ObjectList.hpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -21,6 +22,7 @@ #include "Event.hpp" #include "ObjectDataViewModel.hpp" +#include "Operations/Outcome.hpp" #include "SyntheticInput.hpp" #include "libslic3r/PrintConfig.hpp" @@ -65,6 +67,29 @@ enum class ObjectOrder { Name, Filament, Height, Size }; // Stable sort by natural name order, filament, top Z, or bounding box volume of the first instance. void sort_objects(std::vector& objects, ObjectOrder order, bool descending = false); +// The order Order By gives `objects`, the project's: the objects of plate `plate`, or of every plate with -1, sorted +// (sort_objects()) within the list positions they hold, so that the objects of the other plates, and those on no plate, +// keep theirs. `plate_of` is the plate an object's first instance is on, -1 for none. +std::vector plate_order(const std::vector& objects, const std::function& plate_of, int plate, + ObjectOrder order, bool descending); + +// A drop of the object at list position `from` onto the one at `to`, as dragging an object in the object list makes it. +struct ObjectMove +{ + int from = 0; + int to = 0; +}; + +// Moves the object at `from` to `to`, those between shifting by one toward `from`, as a drop in the object list does. +void move_object_in_list(std::vector& objects, int from, int to); + +// The drops that put the objects of plate `plate` in `order` (their indices), each dropped in turn on the object in its +// place, as a person drags them in the object list: the plate's objects take their list positions in that order, and +// the objects between them, of other plates or of none, move by one with each drop, keeping their own order. +// `plate_of` is the plate each object's first instance is on, -1 for none. No drop where they are in that order. +// Refuses: no_such_object, object_not_on_plate, order_repeats_object, order_misses_object (with the objects left out). +Ops::Outcome> object_order_moves(const std::vector& plate_of, int plate, const std::vector& order); + // Set import-only presentation ranks without changing part order used by slicing. void set_import_volume_order(ModelObject& object, bool sort_names); @@ -343,8 +368,10 @@ public: // dialog after adding a part. void load_generic_subobject(const std::string& type_name, const ModelVolumeType type, bool interactive = true, const std::vector& size = {}); + // Adds the shape as a new object, whatever is selected. void load_shape_object(const std::string &type_name, bool interactive, const std::vector& size = {}); - // Whether load_shape_object() adds an object now: not while an object is selected, whose Add Part menu adds shapes. + // Whether Add Primitive (load_generic_subobject() of no part type) adds an object now: not while an object is + // selected, whose Add Part menu adds shapes. bool can_add_shape_object() const; void load_mesh_object(const TriangleMesh &mesh, const wxString &name, bool center = true); // One object holding one part per mesh; the parts keep their placement relative to each other. @@ -360,8 +387,16 @@ public: bool del_from_cut_object(bool is_connector, bool is_model_part = false, bool is_negative_volume = false); bool del_subobject_from_object(const int obj_idx, const int idx, const int type); void del_info_item(const int obj_idx, InfoItemType type); + // Split > To Parts on the selected object or part. void split(); - void merge(bool to_multipart_object); + // Splits part `volume_idx` of object `obj_idx` into parts by its shells, or with -1 the object's one part, or shows + // the bodies of an import shown as one part. The caller has checked that the part is of several shells. With + // `expand` the object's row is opened on its parts, as a split from that row opens it. + void split(int obj_idx, int volume_idx, bool expand); + // With `to_multipart_object`, assembles the objects and instances of `items`, rows of the list, else the selected + // ones, into one object of parts added last, as Assemble does: the rows are selected first, and each instance of + // them becomes an object of its own. Without it, merges the selected object's parts into one. + void merge(bool to_multipart_object, const wxDataViewItemArray& items = {}); // void merge_volumes(); // BBS: merge parts to single part void layers_editing(); @@ -484,9 +519,11 @@ public: // generic "Change type → Precise Seam" entry where CENTER is a default fallback. // preserve_ps_subtype = false: no preservation — target type is applied verbatim. Used // by the "Precise Seam Type" subtype picker where the user explicitly wants CENTER. - // Returns why the selected parts kept their type, empty when they changed or already had it. + // The parts changed are `parts`, [object, part] by their index in the model, else the selected ones. + // Returns why the parts kept their type, empty when they changed or already had it. // show_errors shows that reason as the menu always has; automation passes false and reports it. - wxString set_volume_type(ModelVolumeType new_type, bool preserve_ps_subtype = true, bool show_errors = true); + wxString set_volume_type(ModelVolumeType new_type, bool preserve_ps_subtype = true, bool show_errors = true, + const std::vector>& parts = {}); ModelVolumeType get_selected_volume_type(); void last_volume_is_deleted(const int obj_idx); @@ -549,11 +586,17 @@ public: void on_plate_added(PartPlate* part_plate); void on_plate_deleted(int plate_index); void reload_all_plates(bool notify_partplate = false); - // Sorts the selected plate or every plate, which sets the print order; repeating a sort reverses it. - void order_objects(ObjectOrder order, bool all_plates); + // Sorts plate `plate` (-1: the selected one) or every plate, which sets the print order (plate_order()). With + // `descending` none, choosing the order the objects already have reverses it, as the plate menu's Order By does. + void order_objects(ObjectOrder order, bool all_plates, int plate = -1, std::optional descending = std::nullopt); + // Drops the object at list position `from` onto the one at `to`, both on plate `plate`, as a drag in the list does + // (move_object_in_list()), and selects it. The caller takes the undo snapshot. + void move_object(int from, int to, int plate); void on_plate_selected(int plate_index); void notify_instance_updated(int obj_idx); - void object_config_options_changed(const ObjectVolumeID& ov_id); + // Marks the row of the object or part `ov_id` names, or with `range` the row of that height range of the object, + // with the icon of its own settings, or takes the icon away when it has none. + void object_config_options_changed(const ObjectVolumeID& ov_id, const t_layer_height_range* range = nullptr); void printable_state_changed(const std::vector model_objects); void printable_state_changed(const std::vector& ov_ids); diff --git a/src/slic3r/GUI/Jobs/OrientJob.cpp b/src/slic3r/GUI/Jobs/OrientJob.cpp index 084dba8fe3..244d59a834 100644 --- a/src/slic3r/GUI/Jobs/OrientJob.cpp +++ b/src/slic3r/GUI/Jobs/OrientJob.cpp @@ -7,6 +7,7 @@ #include "slic3r/GUI/NotificationManager.hpp" #include "libslic3r/PresetBundle.hpp" #include +#include #include #include #include "slic3r/GUI/PartPlate.hpp" @@ -109,9 +110,15 @@ void OrientJob::prepare_selected() { std::vector obj_sel(model.objects.size(), false); - for (auto &s : m_plater->get_selection().get_content()) - if (s.first < int(obj_sel.size())) - obj_sel[size_t(s.first)] = !s.second.empty(); + if (m_objects) { + for (int object : *m_objects) + if (object >= 0 && size_t(object) < obj_sel.size()) + obj_sel[size_t(object)] = true; + } else { + for (auto &s : m_plater->get_selection().get_content()) + if (s.first < int(obj_sel.size())) + obj_sel[size_t(s.first)] = !s.second.empty(); + } //BBS: add only one plate mode prepare_selection(obj_sel, false); @@ -256,7 +263,7 @@ void OrientJob::process(Ctl &ctl) wxGetApp().plater()->show_status_message(ctl.was_canceled() ? "Orienting canceled." : ss.str()); } -OrientJob::OrientJob() : m_plater{wxGetApp().plater()} {} +OrientJob::OrientJob(std::optional> objects) : m_plater{wxGetApp().plater()}, m_objects{std::move(objects)} {} void OrientJob::finalize(bool canceled, std::exception_ptr &eptr) { diff --git a/src/slic3r/GUI/Jobs/OrientJob.hpp b/src/slic3r/GUI/Jobs/OrientJob.hpp index bf4eddc6e2..32bf709086 100644 --- a/src/slic3r/GUI/Jobs/OrientJob.hpp +++ b/src/slic3r/GUI/Jobs/OrientJob.hpp @@ -3,6 +3,7 @@ #include "Job.hpp" #include "libslic3r/Orient.hpp" +#include #include #include #include "libslic3r/Model.hpp" @@ -22,6 +23,8 @@ class OrientJob : public Job OrientMeshs m_selected, m_unselected, m_unprintable; Plater *m_plater; + // The objects to orient in place of the selection, read when the job starts; none of them: every object. + std::optional> m_objects; // clear m_selected and m_unselected, reserve space for next usage void clear_input(); @@ -29,7 +32,7 @@ class OrientJob : public Job //BBS: add only one plate mode void prepare_selection(std::vector obj_sel, bool only_one_plate); - // Prepare the selected and unselected items separately. If nothing is + // Prepare the selected (or the given) and unselected items separately. If nothing is // selected, behaves as if everything would be selected. void prepare_selected(); @@ -41,7 +44,8 @@ public: void process(Ctl &ctl) override; - OrientJob(); + // `objects`, given, are oriented as if they were the selection. + explicit OrientJob(std::optional> objects = std::nullopt); void finalize(bool canceled, std::exception_ptr &e) override; #if 0 diff --git a/src/slic3r/GUI/MainFrame.cpp b/src/slic3r/GUI/MainFrame.cpp index f1c4dff7c1..46c7c419bb 100644 --- a/src/slic3r/GUI/MainFrame.cpp +++ b/src/slic3r/GUI/MainFrame.cpp @@ -3078,12 +3078,12 @@ wxMenu* MainFrame::generate_help_menu() if (wxGetApp().is_editor()) { helpMenu->AppendSeparator(); append_menu_item(helpMenu, wxID_ANY, _L("Take Screenshot"), _L("Save a picture of the main window"), - [](wxCommandEvent&) { NativeCommands::notify_result(NativeCommands::run("take_screenshot")); }); + [](wxCommandEvent&) { NativeCommands::notify_result(NativeCommands::run("window_save_screenshot")); }); append_menu_item(helpMenu, wxID_ANY, _L("Start Recording") + dots, _L("Record a video of the main window"), - [](wxCommandEvent&) { NativeCommands::notify_result(NativeCommands::run("start_recording")); }, "", nullptr, + [](wxCommandEvent&) { NativeCommands::notify_result(NativeCommands::run("recording_start")); }, "", nullptr, []() { return !NativeCommands::recording_active(); }, this); append_menu_item(helpMenu, wxID_ANY, _L("Stop Recording"), _L("Stop the recording and save it"), - [](wxCommandEvent&) { NativeCommands::notify_result(NativeCommands::run("stop_recording")); }, "", nullptr, + [](wxCommandEvent&) { NativeCommands::notify_result(NativeCommands::run("recording_stop")); }, "", nullptr, []() { return NativeCommands::recording_active(); }, this); } diff --git a/src/slic3r/GUI/Mcp/AutomationRuntime.hpp b/src/slic3r/GUI/Mcp/AutomationRuntime.hpp index 4b1179072e..0eabc7d082 100644 --- a/src/slic3r/GUI/Mcp/AutomationRuntime.hpp +++ b/src/slic3r/GUI/Mcp/AutomationRuntime.hpp @@ -34,7 +34,7 @@ class UiInspector; class WebPresses; struct AutoAnswerRule; -// Whose an auto_answer_dialogs call's rules are ("run", "plugin" or "session"), the tracker layer they went into (0 for +// Whose a dialog_auto_answer call's rules are ("run", "plugin" or "session"), the tracker layer they went into (0 for // none), and whether they start paused: a Run Script session's rules registered between its works answer nothing, an open // dialog included, until its next work. struct AutoAnswerSet @@ -137,21 +137,21 @@ public: UiInvoker& ui() { return *m_invoker; } McpCore& core() { return *m_core; } ModalTracker& modals() { return *m_modals; } - // Refs from list_widgets live here. Turns the GUI instruments on if they are off. UI thread only. + // Refs from widget_list live here. Turns the GUI instruments on if they are off. UI thread only. UiInspector& inspector(); // The presses mouse_gesture downs left on pages, the web counterpart of the inspector's held press. // Any thread. WebPresses& web_presses() { return *m_web_presses; } - // start_recording and its kin; also told about every call, for the captions. + // recording_start and its kin; also told about every call, for the captions. McpRecorder& recorder() { return *m_recorder; } - // Auto-answer rules from auto_answer_dialogs. Rules registered from inside a run (the nearest + // Auto-answer rules from dialog_auto_answer. Rules registered from inside a run (the nearest // running replay or script in `ancestry`, the caller's job chain, nearest first) last until that run // ends; a client's rules replace the ones it registered before, and end when the client scope // closes: with the scope closed (the server turned off meanwhile), a client's rules are refused. // A run scope that is paused (set_run_scope_paused()) gets them paused. Any thread. AutoAnswerSet set_auto_answer(std::vector rules, const std::vector& ancestry); - // run_replay and run_script bracket their runs with these. A mouse press the run left held is released + // replay_run and script_run bracket their runs with these. A mouse press the run left held is released // when it ends, and so is a recording it started; `wait_recording` waits for that recording's file, // unless the run already did. void begin_run_scope(const std::string& job); @@ -162,7 +162,7 @@ public: // Releases the mouse presses `job`'s calls left held, on widgets and pages, as the end of its scope does. Any // thread. void release_run_presses(const std::string& job); - // Cancels the operations whose lineage holds `job`, as cancel_job does: a background job through the worker, + // Cancels the operations whose lineage holds `job`, as job_cancel does: a background job through the worker, // a slice or an export through the plater. UI thread. void cancel_operations_of(const std::string& job); // The job of the nearest running replay or script in `ancestry`, else the scope of the plugin whose call it is, diff --git a/src/slic3r/GUI/Mcp/JobRegistry.cpp b/src/slic3r/GUI/Mcp/JobRegistry.cpp index fdc43b7e1a..73a26b1a19 100644 --- a/src/slic3r/GUI/Mcp/JobRegistry.cpp +++ b/src/slic3r/GUI/Mcp/JobRegistry.cpp @@ -49,7 +49,7 @@ std::string JobRegistry::register_job(const std::string& tool, const std::string std::lock_guard lock(m_mutex); const std::size_t running = std::count_if(m_jobs.begin(), m_jobs.end(), [](const auto& kv) { return !kv.second.finished; }); if (running >= kMaxRunning) - throw ToolFailure("Too many running jobs; wait for some to finish (see get_app_state.jobs)"); + throw ToolFailure("Too many running jobs; wait for some to finish (see app_state.jobs)"); std::string id = "j" + std::to_string(m_next++); Job job; job.tool = tool; diff --git a/src/slic3r/GUI/Mcp/JobRegistry.hpp b/src/slic3r/GUI/Mcp/JobRegistry.hpp index af66e2b9a7..343e16bb03 100644 --- a/src/slic3r/GUI/Mcp/JobRegistry.hpp +++ b/src/slic3r/GUI/Mcp/JobRegistry.hpp @@ -24,7 +24,7 @@ namespace Slic3r { namespace GUI { namespace Mcp { inline constexpr char kPluginUnloaded[] = "The plugin that made this call has been unloaded"; // Bookkeeping for mutate tool calls that run on their own threads. A call that outlives its reply -// budget stays here until it finishes, so a later `wait {for:"job"}` can return its result; the +// budget stays here until it finishes, so a later `app_wait {for:"job"}` can return its result; the // most recent finished jobs are kept for that purpose, and so is a finished job whose parent (a // running replay) may still wait for it, up to kKeepFinishedMax in all. Thread-safe. class JobRegistry @@ -41,7 +41,7 @@ public: // job is registered: a plugin found loaded then was loaded while the job was there for its unload to // find, so every job of the plugin is either refused or one the unload finds running. std::string create(const std::string& tool, const std::string& parent, const std::string& owner = {}, bool person = false); - // True when an unfinished job in `lineage` carries the person mark: a run_script there runs as the person's. + // True when an unfinished job in `lineage` carries the person mark: a script_run there runs as the person's. bool person_in(const std::set& lineage) const; // Lets the unfinished job `id`, and the calls under it, drop the project's unsaved changes: the user chose // not to save before a run that replaces the project. Does nothing for an unknown or finished job. @@ -84,7 +84,7 @@ public: bool stop_requested(const std::string& id) const; // True when a running job exists that is not in `excluded` and isn't set idle. bool any_running_except(const std::set& excluded) const; - // Marks a running job as one that leaves `wait {for: "idle"}` to the calls it makes: a run_script run, which may + // Marks a running job as one that leaves `app_wait {for: "idle"}` to the calls it makes: a script_run run, which may // wait for a person in its window for minutes. list() shows it as idle. void set_idle(const std::string& id); // Operation admission: a job marked as an operation holds the project until it finishes. @@ -92,7 +92,7 @@ public: std::string begin_operation(const std::string& id); std::vector running_operations() const; - // [{id, tool, parent, state, age_ms}] for get_app_state. + // [{id, tool, parent, state, age_ms}] for app_state. nlohmann::json list() const; // The tool of `id` while it runs; empty for an unknown or finished job. std::string running_tool(const std::string& id) const; diff --git a/src/slic3r/GUI/Mcp/LaunchRun.cpp b/src/slic3r/GUI/Mcp/LaunchRun.cpp index 3254e8ce7a..41de523db3 100644 --- a/src/slic3r/GUI/Mcp/LaunchRun.cpp +++ b/src/slic3r/GUI/Mcp/LaunchRun.cpp @@ -87,7 +87,7 @@ void start_launch_run(AutomationRuntime& runtime, const McpLaunchOptions& option set_run_output_dir(path_from_utf8(options.run_out)); FollowedCall call; - call.command = *NativeCommands::instance().find(python ? "run_script" : "run_replay"); + call.command = *NativeCommands::instance().find(python ? "script_run" : "replay_run"); call.person = true; // The file is read off the UI thread. call.ready = [&runtime, file, out = options.run_out, python, replay](json& args) { diff --git a/src/slic3r/GUI/Mcp/McpArguments.cpp b/src/slic3r/GUI/Mcp/McpArguments.cpp index d0da5524c6..28615507c2 100644 --- a/src/slic3r/GUI/Mcp/McpArguments.cpp +++ b/src/slic3r/GUI/Mcp/McpArguments.cpp @@ -50,6 +50,19 @@ bool type_matches(const json& value, const json& type) return json_type_name(value) == t; } +// Whether `value`, a call's arguments, meets `cond`, the "if" of with_silent(): it is no person's form, so what the +// silent form requires applies. {"minProperties": 1} holds for any argument, {"not": {"enum": [...]}} for arguments +// other than those listed; any other "if" is not with_silent()'s, and never holds. +bool silent_form(const json& cond, const json& value) +{ + if (cond == json{{"minProperties", 1}}) + return !value.empty(); + if (const auto no = cond.find("not"); cond.size() == 1 && no != cond.end() && no->is_object() && no->size() == 1) + if (const auto forms = no->find("enum"); forms != no->end() && forms->is_array()) + return std::find(forms->begin(), forms->end(), value) == forms->end(); + return false; +} + std::string validate_value(const json& schema, const json& value, const std::string& path) { if (!schema.is_object()) @@ -70,6 +83,9 @@ std::string validate_value(const json& schema, const json& value, const std::str return path + " must be <= " + it->dump(); } if (value.is_array()) { + if (auto it = schema.find("minItems"); + it != schema.end() && it->is_number_integer() && it->get() > 0 && value.size() < it->get()) + return path + " must hold at least " + it->dump() + " item" + (it->get() == 1 ? "" : "s"); if (auto it = schema.find("items"); it != schema.end()) for (std::size_t i = 0; i < value.size(); ++i) if (std::string err = validate_value(*it, value[i], path + "[" + std::to_string(i) + "]"); !err.empty()) @@ -102,10 +118,10 @@ std::string validate_value(const json& schema, const json& value, const std::str if (auto it = schema.find("required"); it != schema.end()) if (std::string err = missing(*it); !err.empty()) return err; - // with_silent()'s shape, and no other use of if: what the silent form requires, once the call gives any - // argument. + // with_silent()'s shapes, and no other use of if: what the silent form requires, once the call is not one of + // the person's forms. const auto cond = schema.find("if"), then = schema.find("then"); - if (cond != schema.end() && then != schema.end() && *cond == json{{"minProperties", 1}} && then->is_object() && !value.empty()) + if (cond != schema.end() && then != schema.end() && then->is_object() && silent_form(*cond, value)) if (auto it = then->find("required"); it != then->end()) if (std::string err = missing(*it); !err.empty()) return err; @@ -132,6 +148,24 @@ const std::vector>>& argument_al return aliases; } +// The arguments that pick a command's variant where it is not a type, named for what is picked (project_export's +// format, object_add_primitive's shape). A guessed type stands for the one of them a command takes, where it takes +// exactly one and no type of its own; with two, either could be meant. +constexpr const char* kVariantArguments[] = {"format", "shape", "model", "test", "into", "by", "axis", "mode", "window", "page"}; + +// The one argument of kVariantArguments that `props` has, or nullptr where it has none or several. +const char* only_variant_argument(const json& props) +{ + const char* found = nullptr; + for (const char* name : kVariantArguments) + if (props.contains(name)) { + if (found != nullptr) + return nullptr; + found = name; + } + return found; +} + bool type_includes(const json& type, const char* name) { return type.is_array() ? std::find(type.begin(), type.end(), name) != type.end() : type == name; @@ -232,9 +266,9 @@ void normalize_arguments(const json& schema, json& args) if (!args.is_object() || !schema.is_object() || !schema.contains("properties")) return; const json& props = schema["properties"]; - // x and y, and width and height, as list_windows reports them, read as the position and size arrays + // x and y, and width and height, as window_list reports them, read as the position and size arrays // of a tool that takes those as window geometry, arrays of integers, and neither part by its own - // name. The mm arrays of the 3D tools (transform, add_part) hold numbers and never take a pair. Only + // name. The mm arrays of the 3D tools (object_transform, part_add) hold numbers and never take a pair. Only // both parts of a pair fold, and never over an array the call gives. struct Pair { @@ -254,27 +288,34 @@ void normalize_arguments(const json& schema, json& args) args.erase(pair.first); args.erase(pair.second); } + // Moves `alias`'s value to `name` where the schema takes name, the call leaves it out and the value fits: the + // widget_click tool's action "click" is no button, and its error should name action. + const auto read_as = [&props, &args](const std::string& alias, const std::string& name) { + if (!props.contains(name) || args.contains(name)) + return false; + json value = args[alias]; + coerce_value(props[name], value); + if (!validate_value(props[name], value, name).empty()) + return false; + args[name] = std::move(value); + args.erase(alias); + return true; + }; for (const auto& [alias, names] : argument_aliases()) { if (!args.contains(alias) || props.contains(alias)) continue; - // Only where the value fits: the click tool's action "click" is no button, and its error should name action. - for (const std::string& name : names) { - if (!props.contains(name) || args.contains(name)) - continue; - json value = args[alias]; - coerce_value(props[name], value); - if (validate_value(props[name], value, name).empty()) { - args[name] = std::move(value); - args.erase(alias); + for (const std::string& name : names) + if (read_as(alias, name)) break; - } - } } + if (args.contains("type") && !props.contains("type")) + if (const char* variant = only_variant_argument(props)) + read_as("type", variant); for (auto it = args.begin(); it != args.end(); ++it) if (auto p = props.find(it.key()); p != props.end()) coerce_value(*p, it.value()); // A value outside its own enum that the enum of one other argument, which the call leaves out, - // takes: set_view's canvas "front" is its camera. The schema keeps each enum to its own values, + // takes: view_set's canvas "front" is its camera. The schema keeps each enum to its own values, // as listing them under both names would have agents give a value to the wrong one. std::vector> moves; for (const auto& [key, value] : args.items()) { @@ -299,6 +340,25 @@ std::string validate_arguments(const json& schema, const json& args) { return va bool person_form(const json& args) { return args.is_null() || (args.is_object() && args.empty()); } +std::vector person_forms(const NativeCommand& command) +{ + std::vector forms; + if (command.in_palette) + forms.push_back(json::object()); + if (command.tiles.is_array()) + for (const json& tile : command.tiles) + if (tile.value("input", std::string()).empty()) + forms.push_back(tile.at("args")); + return forms; +} + +bool person_form(const NativeCommand& command, const json& args) +{ + const json given = person_form(args) ? json::object() : args; + const std::vector forms = person_forms(command); + return std::find(forms.begin(), forms.end(), given) != forms.end(); +} + json silent_args(json args) { if (args.is_object()) @@ -306,19 +366,29 @@ json silent_args(json args) return args; } -json with_silent(json schema) +json with_silent(json schema, const std::vector& person_args) { - schema["properties"]["silent"] = {{"type", "boolean"}, - {"enum", {true}}, - {"description", "true runs the command without asking, with the defaults of what the call " - "leaves out. A call with no arguments does what a person's pick does."}}; + json required = json::array(); if (auto it = schema.find("required"); it != schema.end()) { - json required = std::move(*it); + required = std::move(*it); schema.erase(it); - if (!required.empty()) { - schema["if"] = {{"minProperties", 1}}; - schema["then"] = {{"required", std::move(required)}}; - } + } + const bool only_none = person_args.size() == 1 && person_form(person_args.front()); + const bool has_none = std::any_of(person_args.begin(), person_args.end(), [](const json& a) { return person_form(a); }); + // What silent says is the command's own: what its silent form still needs, and which calls are its person's forms. + std::string needs; + for (std::size_t i = 0; i < required.size(); ++i) + needs += (i == 0 ? "" : i + 1 == required.size() ? " and " : ", ") + required[i].get(); + std::string text = needs.empty() ? "true runs the command without asking; what the call leaves out takes its default." : + "true runs the command without asking; it then needs " + needs + + ", and what else the call leaves out takes its default."; + text += only_none ? " A call with no arguments does what a person's pick does." : + has_none ? " A call with no arguments, or with exactly a tile's arguments, does what a person's pick of that tile does." : + " A call with exactly a tile's arguments does what a person's pick of that tile does."; + schema["properties"]["silent"] = {{"type", "boolean"}, {"enum", {true}}, {"description", std::move(text)}}; + if (!required.empty()) { + schema["if"] = only_none ? json{{"minProperties", 1}} : json{{"not", {{"enum", person_args}}}}; + schema["then"] = {{"required", std::move(required)}}; } return schema; } diff --git a/src/slic3r/GUI/Mcp/McpArguments.hpp b/src/slic3r/GUI/Mcp/McpArguments.hpp index 3c586133f7..2695b57c64 100644 --- a/src/slic3r/GUI/Mcp/McpArguments.hpp +++ b/src/slic3r/GUI/Mcp/McpArguments.hpp @@ -12,7 +12,7 @@ namespace Slic3r { namespace GUI { namespace Mcp { -// For a call of call_tool ({tool, args}): replaces `command` and `args` with its target's, normalized and +// For a call of tool_call ({tool, args}): replaces `command` and `args` with its target's, normalized and // validated, so the call runs and is journaled as the target's own. Returns an error message, or "" (also // for any other command, which it leaves as it is). std::string resolve_call(const CommandCatalog& catalog, std::shared_ptr& command, nlohmann::json& args); @@ -20,22 +20,28 @@ std::string resolve_call(const CommandCatalog& catalog, std::shared_ptr person_forms(const NativeCommand& command); +// Whether `args`, null as {}, are a person's form of `command`: exactly the arguments of one of person_forms(). Such +// a call does what a person's pick of that tile does, and may ask; any other call is its silent form. +bool person_form(const NativeCommand& command, const nlohmann::json& args); // `args` without `silent`, which only chooses the silent form. nlohmann::json silent_args(nlohmann::json args); // The schema of a two-form command from its silent form's `schema`: it gains the property `silent`, which -// takes only true and asks for the silent form with its defaults, and a top-level `required` list moves to -// "if": {"minProperties": 1}, "then": {"required": [...]}, since the call with no arguments, the person's -// form, needs none of them. -nlohmann::json with_silent(nlohmann::json schema); +// takes only true and asks for the silent form with its defaults, described by what that form still requires and by +// which calls are the person's forms (none, a tile's arguments, or both), and a top-level `required` list moves under +// "then", with an "if" that holds for every call but the person's forms, `person_args` (never empty), so that a +// person's form needs none of them: {"minProperties": 1} where the only one is the call with no arguments, else +// {"not": {"enum": []}}. +nlohmann::json with_silent(nlohmann::json schema, const std::vector& person_args = {nlohmann::json::object()}); // Readies a call's arguments for `command`, as every caller of a command does: normalizes `args` in place // (normalize_arguments()) and returns why validate_arguments() refuses them; empty when they are valid. @@ -45,10 +51,11 @@ std::string argument_error(const NativeCommand& command, nlohmann::json& args); // argument under a name the tool does not take but that stands for one it does, which the call leaves // out and the value fits (ref for target, key for keys, text for value, action for id or button, object for objects, // plate for plates, filter for query, settings for values, path for save_path, index for feature, params or -// values for fields), a value written in +// values for fields, and type for the one argument that picks a command's variant where that has another name, as +// project_export's format, when it takes exactly one such and no type), a value written in // another JSON form (a number, boolean, array or object as a string, a single item for an array), -// a value outside its argument's enum that only one omitted argument's enum takes (set_view's canvas -// "front" as camera), and the x and y, or width and height, that list_windows reports, both given, as +// a value outside its argument's enum that only one omitted argument's enum takes (view_set's canvas +// "front" as camera), and the x and y, or width and height, that window_list reports, both given, as // the position or size array of a tool that takes that array, of integers, and neither part. Anything // that still does not fit is left for validate_arguments to report. void normalize_arguments(const nlohmann::json& schema, nlohmann::json& args); diff --git a/src/slic3r/GUI/Mcp/McpCore.cpp b/src/slic3r/GUI/Mcp/McpCore.cpp index ef803b6a74..963309c4f1 100644 --- a/src/slic3r/GUI/Mcp/McpCore.cpp +++ b/src/slic3r/GUI/Mcp/McpCore.cpp @@ -56,7 +56,7 @@ void deliver(const std::function& done, const ToolResul std::string busy_message(const std::string& op) { return "Busy: job " + op + - " is running an operation (slice, export, arrange or another background job); wait for it or stop it with cancel_job"; + " is running an operation (slice, export, arrange or another background job); wait for it or stop it with job_cancel"; } class CallContext final : public ToolContext @@ -291,7 +291,7 @@ std::string McpCore::start_job(const NativeCommand& def, const nlohmann::json& a ToolResult& refused) { // Operation admission: an MCP operation holds the project until it finishes; only recovery - // input and the commands that may run during an operation (cancel_job) get through. + // input and the commands that may run during an operation (job_cancel) get through. if (def.guard == GuardClass::Mutate && !def.allowed_during_operation) if (const auto busy = m_jobs.running_operations(); !busy.empty()) { refused = ToolResult::error(busy_message(busy.front()) + " before changing the project", {{"job", busy.front()}}); @@ -332,7 +332,7 @@ std::string McpCore::start_job(const NativeCommand& def, const nlohmann::json& a result = await_worker(job, def.key, invoke(def, args, ctx)); notify(m_observer, [&](CallObserver& o) { o.call_ended(call, result); }); } - // Before finish(): an export_replay right after the wait that sees the result must know it. + // Before finish(): a replay_export right after the app_wait that sees the result must know it. if (seq != 0) m_journal->job_ended(seq, result); deliver(done, result); @@ -400,8 +400,8 @@ ToolResult McpCore::run(const NativeCommand& def, const nlohmann::json& args, co return ToolResult::ok(std::move(out)); }; const std::string running_note = "The call is still running and will finish on its own; do not retry it. " - "Use wait {for:\"job\", job:\"" + job + "\"} for its result."; - // answer_dialog presses a native message box by the buttons ModalTracker lists for it, but not a + "Use app_wait {for:\"job\", job:\"" + job + "\"} for its result."; + // dialog_answer presses a native message box by the buttons ModalTracker lists for it, but not a // picker, nor a dialog while it holds the UI thread (macOS), so their note asks for a person. auto blocked = [&](nlohmann::json dialogs, bool ui_held) { std::string note; @@ -409,16 +409,16 @@ ToolResult McpCore::run(const NativeCommand& def, const nlohmann::json& args, co const bool pressable = native && !ui_held && !dialogs.back().value("buttons", nlohmann::json::array()).empty(); if (pressable) { note = "The call is waiting on a native message box and continues after it closes; do not retry it. Answer it " - "with answer_dialog and one of its buttons, then wait {for:\"job\", job:\"" + job + "\"}."; + "with dialog_answer and one of its buttons, then app_wait {for:\"job\", job:\"" + job + "\"}."; } else if (native) { - note = "The call is waiting on a native dialog, which only a person can answer (answer_dialog can't); do not retry it. "; + note = "The call is waiting on a native dialog, which only a person can answer (dialog_answer can't); do not retry it. "; if (ui_held) note += "Until it closes, tools that need the UI thread fail. "; - note += "Once it is answered, wait {for:\"job\", job:\"" + job + - "\"}. Register auto_answer_dialogs before a step that opens a native dialog."; + note += "Once it is answered, app_wait {for:\"job\", job:\"" + job + + "\"}. Register dialog_auto_answer before a step that opens a native dialog."; } else { note = "The call is waiting on a dialog and continues after it closes; do not retry it. " - "Answer the dialog (list_widgets, answer_dialog), then wait {for:\"job\", job:\"" + job + "\"}."; + "Answer the dialog (widget_list, dialog_answer), then app_wait {for:\"job\", job:\"" + job + "\"}."; } return envelope("blocked_by_dialog", {{"dialogs", std::move(dialogs)}, {"note", note}}); }; @@ -481,7 +481,7 @@ void McpCore::admit(const std::string& job) const return; } throw ToolFailure("Busy: a background job (arrange, orient, fill bed, or one a gizmo started, such as Text typing) is " - "running in OrcaSlicer; wait {for:\"idle\"} before changing the project"); + "running in OrcaSlicer; app_wait {for:\"idle\"} before changing the project"); } bool McpCore::worker_busy() const { return m_worker.busy && m_worker.busy(); } diff --git a/src/slic3r/GUI/Mcp/McpCore.hpp b/src/slic3r/GUI/Mcp/McpCore.hpp index ee8c859e2d..f0070d166a 100644 --- a/src/slic3r/GUI/Mcp/McpCore.hpp +++ b/src/slic3r/GUI/Mcp/McpCore.hpp @@ -89,7 +89,7 @@ public: // As call(), with the job marked a person's. ToolResult call_person(const NativeCommand& command, const nlohmann::json& args); // A call made by a running job (a replay step or a script's call). The new job's parent is `parent_job`, so a - // `wait {for:"idle"}` from that job does not wait for it, and the journal leaves it out. + // `app_wait {for:"idle"}` from that job does not wait for it, and the journal leaves it out. ToolResult call_child(const NativeCommand& command, const nlohmann::json& args, const std::string& parent_job, const std::string& plugin = {}); // A child call by the command's key, as ToolContext::call_child() makes one, under any parent: the command is @@ -174,7 +174,7 @@ private: mutable std::mutex m_dialogs_mutex; std::map m_dialogs_of; - // Requests that may block (a job within its reply budget, or wait) hold a slot, so the number of + // Requests that may block (a job within its reply budget, or app_wait) hold a slot, so the number of // blocked request threads stays below the connection limit and recovery calls always get through. bool acquire_slot(); void release_slot(); diff --git a/src/slic3r/GUI/Mcp/McpEndpoint.cpp b/src/slic3r/GUI/Mcp/McpEndpoint.cpp index f334431dca..5760273588 100644 --- a/src/slic3r/GUI/Mcp/McpEndpoint.cpp +++ b/src/slic3r/GUI/Mcp/McpEndpoint.cpp @@ -193,7 +193,7 @@ bool McpEndpoint::listen(int port, std::string& err) {"token", token}}, m_discovery_error)) // Serving anyway: clients configured with the URL and token still connect; the stdio - // bridge and the harness, which need the file, see the reason in get_app_state. + // bridge and the harness, which need the file, see the reason in app_state. BOOST_LOG_TRIVIAL(warning) << "MCP server: " << m_discovery_error; BOOST_LOG_TRIVIAL(info) << "MCP server listening on http://127.0.0.1:" << m_http->port() << "/mcp"; return true; diff --git a/src/slic3r/GUI/Mcp/McpJournal.cpp b/src/slic3r/GUI/Mcp/McpJournal.cpp index b9449575cd..007e276731 100644 --- a/src/slic3r/GUI/Mcp/McpJournal.cpp +++ b/src/slic3r/GUI/Mcp/McpJournal.cpp @@ -29,21 +29,19 @@ namespace { // counted as replacement characters rather than thrown on: the journal only needs the size. std::size_t serialized_size(const json& args) { return args.dump(-1, ' ', false, json::error_handler_t::replace).size(); } -// The command a journaled call of `tool` with `args` runs, and the arguments it runs it with: the call's own, or, -// for run_action of a command's tile, named by the command's key or by the tile's full id, that command and the -// arguments inside the tile's {id, args}. +// The name a journaled call of `tool` with `args` runs under, and the arguments it runs with: the call's own, or, for +// action_run of a command's tile, by its full id or the key inside it, that key and the arguments inside the tile's +// {id, args}. A command's own tile is under its command's key, so a Design command's tile is rewritten as its command +// is; a tile of a row folded into a command is under a key of its own, and its call's arguments, none, the tile's own +// or the value it collects, hold no path to rewrite. std::pair called_command(const std::string& tool, json& args) { - if (tool != "run_action" || !args.is_object() || !args.value("id", json()).is_string() || !args.value("args", json()).is_object()) + if (tool != "action_run" || !args.is_object() || !args.value("id", json()).is_string() || !args.value("args", json()).is_object()) return {tool, &args}; - const std::string id = args["id"]; - const std::string prefix = std::string(kCommandPrefix) + ':', suffix = std::string(":") + kOrcaSourceKey; - if (id.find(':') == std::string::npos) - return {id, &args["args"]}; - if (id.size() > prefix.size() + suffix.size() && id.compare(0, prefix.size(), prefix) == 0 && - id.compare(id.size() - suffix.size(), suffix.size(), suffix) == 0) - return {id.substr(prefix.size(), id.size() - prefix.size() - suffix.size()), &args["args"]}; - return {tool, &args}; + const std::string key = command_tile_key(args["id"].get()); + if (key.empty()) + return {tool, &args}; + return {key, &args["args"]}; } } // namespace @@ -52,12 +50,12 @@ json without_expected_ids(const CommandCatalog& catalog, const std::string& comm { if (!args.is_object()) return args; - if (command == "call_tool") { + if (command == "tool_call") { if (args.contains("args") && args["args"].is_object()) args["args"] = without_expected_ids(catalog, args.value("tool", std::string()), std::move(args["args"])); return args; } - if (command == "run_replay") { + if (command == "replay_run") { // An inline replay given as JSON text is recorded as the object it parses to, so its steps are // stripped too. Text that doesn't parse stays as given: the call fails, and no replay keeps it. if (args.contains("replay") && args["replay"].is_string()) { @@ -106,7 +104,7 @@ void Journal::set_args(uint64_t seq, nlohmann::json args) const std::size_t bytes = serialized_size(args); std::lock_guard lock(m_mutex); - // export_replay {clear:true} may have emptied the journal meanwhile. + // replay_export {clear:true} may have emptied the journal meanwhile. const auto it = std::find_if(m_entries.begin(), m_entries.end(), [seq](const Entry& e) { return e.seq == seq; }); if (it == m_entries.end()) return; @@ -125,7 +123,7 @@ void Journal::end(uint64_t seq, const ToolResult& result) e.finished = true; e.failed = e.failed || result.is_error; e.menu_listed = !result.is_error && result.data.is_object() && result.data.contains("popup_menu"); - // The envelope names the call's own job; a `wait` that timed out names another one. + // The envelope names the call's own job; an `app_wait` that timed out names another one. if (result.is_error || e.job.empty() || !result.data.is_object()) continue; const auto job = result.data.find("job"); @@ -167,7 +165,7 @@ void Journal::clear() void Journal::trim() { // A session kept open for days, or one that sends thousands of large calls (a CAD run's sketch_draw), - // must not grow without bound; a replay is exported from the recent calls anyway (export_replay + // must not grow without bound; a replay is exported from the recent calls anyway (replay_export // {clear:true} starts afresh). The oldest calls whose outcome is known go first; a call still // waiting for its reply or its job keeps its place, even when that holds the journal over a bound // until it finishes. One pass moves the kept calls forward and one erase drops the rest, so a large @@ -220,14 +218,14 @@ nlohmann::json Journal::to_replay(const std::string& name, nlohmann::json* left_ if (e.menu_listed && repeated_with_item(it)) continue; nlohmann::json step{{"tool", e.tool}, {"args", e.args}}; - if (e.tool == "wait" && e.args.value("for", "") == "job") { + if (e.tool == "app_wait" && e.args.value("for", "") == "job") { auto it = job_names.find(e.args.value("job", "")); if (it == job_names.end()) continue; // waits on a job the journal did not see start step["args"]["job"] = "${jobs." + it->second + "}"; } - // The command the step calls and its arguments: run_action of a command's tile calls the tile's command - // with the arguments inside the tile's {id, args}, which the step keeps. + // The name the step runs under and its arguments: action_run of a command's tile runs as the tile's key, with + // the arguments inside the tile's {id, args}, which the step keeps, so that its replay runs the tile again. const auto [tool, called_args] = called_command(e.tool, step["args"]); nlohmann::json& args = *called_args; auto in_out_dir = [&](const char* key) { @@ -235,16 +233,16 @@ nlohmann::json Journal::to_replay(const std::string& name, nlohmann::json* left_ return "${out_dir}/" + file; }; auto has_path = [&](const char* key) { return args.contains(key) && args[key].is_string(); }; - if ((tool == "screenshot" || tool == "encode_recording") && has_path("save_path")) + if ((tool == "window_screenshot" || tool == "recording_encode") && has_path("save_path")) args["save_path"] = in_out_dir("save_path"); - if (tool == "start_recording" && has_path("save_path")) { + if (tool == "recording_start" && has_path("save_path")) { const std::string key = path_compare_key(path_from_utf8(args["save_path"].get())); args["save_path"] = in_out_dir("save_path"); recordings[key] = args["save_path"]; } // An encode of a recording this replay makes reads it where the replay writes it; any other // source stays where it is. - if (tool == "encode_recording" && has_path("path")) + if (tool == "recording_encode" && has_path("path")) if (auto it = recordings.find(path_compare_key(path_from_utf8(args["path"].get()))); it != recordings.end()) args["path"] = it->second; if (e.unawaited()) { @@ -254,7 +252,7 @@ nlohmann::json Journal::to_replay(const std::string& name, nlohmann::json* left_ step["save_as"] = job_name; } if (e.answers_dialog) - steps.push_back({{"tool", "wait"}, {"args", {{"for", "dialog"}, {"timeout_s", 50}}}, {"expect", {{"/satisfied", {{"eq", true}}}}}}); + steps.push_back({{"tool", "app_wait"}, {"args", {{"for", "dialog"}, {"timeout_s", 50}}}, {"expect", {{"/satisfied", {{"eq", true}}}}}}); steps.push_back(std::move(step)); } return {{"orca_replay_version", REPLAY_VERSION}, {"name", name}, {"steps", std::move(steps)}}; diff --git a/src/slic3r/GUI/Mcp/McpJournal.hpp b/src/slic3r/GUI/Mcp/McpJournal.hpp index df3eaf4dd9..0d4e55fec7 100644 --- a/src/slic3r/GUI/Mcp/McpJournal.hpp +++ b/src/slic3r/GUI/Mcp/McpJournal.hpp @@ -14,14 +14,14 @@ namespace Slic3r { namespace GUI { namespace Mcp { // `args` of a call of `command` as the journal records them: without the command's id_args (expected object -// and part ids), as ids are allocated per process and a replay addresses by index. So are a call_tool call's -// arguments for its target and a run_replay's inline steps. The arguments of any other command stay as -// written: a plugin operation's own fields, and a run_script call's code and args, since a script reads the +// and part ids), as ids are allocated per process and a replay addresses by index. So are a tool_call call's +// arguments for its target and a replay_run's inline steps. The arguments of any other command stay as +// written: a plugin operation's own fields, and a script_run call's code and args, since a script reads the // ids it uses. nlohmann::json without_expected_ids(const CommandCatalog& catalog, const std::string& command, nlohmann::json args); -// The session's client calls, in the order they were made, for export_replay. A call that returned -// a job envelope is replayed with `await:false` and a name its later `wait` refers to, so a step +// The session's client calls, in the order they were made, for replay_export. A call that returned +// a job envelope is replayed with `await:false` and a name its later `app_wait` refers to, so a step // that opened a dialog can be followed by the steps that answered it. An input call that only listed // the menu it opened is kept, since it may have changed the selection, unless the next call repeats // it with a popup_item. @@ -32,21 +32,21 @@ nlohmann::json without_expected_ids(const CommandCatalog& catalog, const std::st // in the replay whatever becomes of it, since the steps after it answer that dialog. So does a job // that was running while a later call answered a dialog: the dialog may be one the job opened, after // its reply or before it, and the answer depends on it. Such a job replays with `await:false`, and a -// call that answered a dialog replays after a `wait {for:"dialog"}`, since the dialog may open later +// call that answered a dialog replays after an `app_wait {for:"dialog"}`, since the dialog may open later // than the job's replayed reply. Thread-safe. It records the arguments it is given, which McpCore gives it // through without_expected_ids(). class Journal { public: // Starts an entry; returns its sequence number. Calls made by replays and scripts are not recorded. - // `answers_dialog`: the call acts while a modal dialog is open (answer_dialog, input to it). + // `answers_dialog`: the call acts while a modal dialog is open (dialog_answer, input to it). uint64_t begin(const std::string& tool, const nlohmann::json& args, bool answers_dialog = false); void set_args(uint64_t seq, nlohmann::json args); // The call's reply. void end(uint64_t seq, const ToolResult& result); // The call runs as `job`; its outcome is open until job_ended(). void job_started(uint64_t seq, const std::string& job); - // The job's final result, reported before a `wait` on the job can see it, so an export right + // The job's final result, reported before an `app_wait` on the job can see it, so an export right // after that wait already knows the outcome. void job_ended(uint64_t seq, const ToolResult& result); void clear(); diff --git a/src/slic3r/GUI/Mcp/McpOptions.hpp b/src/slic3r/GUI/Mcp/McpOptions.hpp index 727f602a97..515fa4d25b 100644 --- a/src/slic3r/GUI/Mcp/McpOptions.hpp +++ b/src/slic3r/GUI/Mcp/McpOptions.hpp @@ -9,7 +9,7 @@ inline constexpr int kDefaultPort = 13619; // The app config key of the unrestricted Python scripts setting: one switch, off unless true. While it is on, // or the command line's --unrestricted-scripts is, the scripts a person runs (the Run Script panel, --run) and -// agents send (run_script) skip the plugin permission checks. Only the window show_python_scripts_dialog() opens +// agents send (script_run) skip the plugin permission checks. Only the window show_python_scripts_dialog() opens // writes it; no tool and no command line option does. inline constexpr char kPythonUnrestrictedKey[] = "python_scripts_unrestricted"; diff --git a/src/slic3r/GUI/Mcp/McpPersonContext.hpp b/src/slic3r/GUI/Mcp/McpPersonContext.hpp index fd43f2e5e1..08d55e75c1 100644 --- a/src/slic3r/GUI/Mcp/McpPersonContext.hpp +++ b/src/slic3r/GUI/Mcp/McpPersonContext.hpp @@ -11,7 +11,7 @@ #include // The contexts a command runs with besides the MCP core's own: a person's pick, and a Speed Dial tile that -// run_action runs. No wx here, so that unit tests can include it (the slic3rutils tile case does). +// action_run runs. No wx here, so that unit tests can include it (the slic3rutils tile case does). namespace Slic3r { namespace GUI { namespace Mcp { // A person's pick from the Speed Dial or a menu, on the UI thread and outside the automation runtime's dispatch @@ -41,13 +41,19 @@ public: void begin_operation() override {} }; -// What run_action runs a command's tile with: the context of run_action's own call, except that a command -// that rewrites its journal entry does so inside run_action's, as {"id": , "args": ...}, -// so that a replay runs the tile again through run_action. +// What action_run runs a command's tile with: the context of action_run's own call, except that a command +// that rewrites its journal entry does so inside action_run's, as {"id": , "args": ...}, +// so that a replay runs the tile again through action_run. A tile of fixed arguments (an item of a command's tiles, a +// Design command's folded rows among them, or a command's own tile outside the Design tab) records `tile_args` there in +// place of the command's rewrite: what action_run takes for it (tile_journal_args()). action_run refuses any other +// arguments for such a tile, and so would refuse the replay of a rewrite (object_arrange's adds the settings in +// force). A Design command's own tile, which takes its command's arguments, has none, and the command's rewrite stands. class TileContext final : public ToolContext { public: - TileContext(ToolContext& call, std::string action_id) : m_call(call), m_id(std::move(action_id)) {} + TileContext(ToolContext& call, std::string action_id, nlohmann::json tile_args = nullptr) + : m_call(call), m_id(std::move(action_id)), m_tile_args(std::move(tile_args)) + {} bool person() const override { return m_call.person(); } AutomationRuntime& runtime() override { return m_call.runtime(); } @@ -60,15 +66,16 @@ public: std::set lineage() const override { return m_call.lineage(); } void set_journal_args(nlohmann::json args) override { - m_call.set_journal_args({{"id", m_id}, {"args", std::move(args)}}); + m_call.set_journal_args({{"id", m_id}, {"args", m_tile_args.is_null() ? std::move(args) : m_tile_args}}); } void begin_operation() override { m_call.begin_operation(); } void works_in_dialog(std::uint64_t dialog) override { m_call.works_in_dialog(dialog); } const std::string& caller_plugin() const override { return m_call.caller_plugin(); } private: - ToolContext& m_call; - std::string m_id; + ToolContext& m_call; + std::string m_id; + nlohmann::json m_tile_args; }; }}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpPersonRun.cpp b/src/slic3r/GUI/Mcp/McpPersonRun.cpp index 2dfa915c43..7b6b53b219 100644 --- a/src/slic3r/GUI/Mcp/McpPersonRun.cpp +++ b/src/slic3r/GUI/Mcp/McpPersonRun.cpp @@ -53,7 +53,7 @@ void PersonRun::stop() if (job.empty() || m_runtime.stopping()) return; m_runtime.jobs().request_stop(job); - // The step's own operation stops too, as cancel_job stops it. + // The step's own operation stops too, as job_cancel stops it. m_runtime.cancel_operations_of(job); } @@ -86,14 +86,14 @@ void PersonRun::post_finished(nlohmann::json result, nlohmann::json jobs) std::shared_ptr start_replay_run(AutomationRuntime& runtime, Replay replay, ReplayContext sctx, std::optional only_step, bool discard_authorized, PersonRun::Events events) { - const NativeCommand* run_replay_def = NativeCommands::instance().find("run_replay"); + const NativeCommand* run_replay_def = NativeCommands::instance().find("replay_run"); if (run_replay_def == nullptr || runtime.stopping()) return nullptr; auto run = std::make_shared(runtime, std::move(events)); auto shared = std::make_shared(std::move(replay)); auto ctx_held = std::make_shared(std::move(sctx)); - // run_replay's properties, outside the session journal: a person's run is not an agent's call. + // replay_run's properties, outside the session journal: a person's run is not an agent's call. NativeCommand def = *run_replay_def; def.journal = false; def.run = [&runtime, run, shared, ctx_held, only_step, discard_authorized](const json&, ToolContext& ctx) { diff --git a/src/slic3r/GUI/Mcp/McpPersonRun.hpp b/src/slic3r/GUI/Mcp/McpPersonRun.hpp index e0dafa075e..3a74d1f6be 100644 --- a/src/slic3r/GUI/Mcp/McpPersonRun.hpp +++ b/src/slic3r/GUI/Mcp/McpPersonRun.hpp @@ -28,7 +28,7 @@ public: { std::function step_started; std::function step_finished; - // Exactly once: run_replay's result, or {"error": message} when the run failed as a call (refused, + // Exactly once: replay_run's result, or {"error": message} when the run failed as a call (refused, // or its job ended in an error or was lost); `jobs` are the jobs the run saved, for later steps, // or null when it was refused before it started. std::function finished; @@ -38,7 +38,7 @@ public: // UI thread. Latches the stop, so one asked before the job exists still counts, stops the job's lineage // once it is known (JobRegistry::request_stop), and cancels the run's operation (a slice, an export, a - // background job) as cancel_job does. Does nothing once the runtime is stopping. + // background job) as job_cancel does. Does nothing once the runtime is stopping. void stop(); // UI thread: the events are dropped from now on; the run carries on to its end. void detach(); @@ -63,7 +63,7 @@ private: std::atomic m_running{true}; }; -// Runs a replay for the Action Replay window: an unjournaled mutate job, as run_replay runs one, whose steps +// Runs a replay for the Action Replay window: an unjournaled mutate job, as replay_run runs one, whose steps // report through `events`. `runtime` follows the job to its end, past a running or blocked_by_dialog reply, and // posts `finished`. `only_step` runs one step (no result.json). `discard_authorized`: the user chose not to save // before a run that replaces the project, so the replacing tools may drop unsaved changes while it runs. nullptr diff --git a/src/slic3r/GUI/Mcp/McpProtocol.cpp b/src/slic3r/GUI/Mcp/McpProtocol.cpp index e4f7b62d07..4adf805560 100644 --- a/src/slic3r/GUI/Mcp/McpProtocol.cpp +++ b/src/slic3r/GUI/Mcp/McpProtocol.cpp @@ -66,18 +66,18 @@ int base64_value(char c) } // namespace -// ---- call_tool ---------------------------------------------------------------- +// ---- tool_call ---------------------------------------------------------------- std::string resolve_call(const CommandCatalog& catalog, std::shared_ptr& command, json& args) { - if (!command || command->key != "call_tool") + if (!command || command->key != "tool_call") return {}; const std::string target = args.value("tool", std::string()); std::shared_ptr inner = catalog.lookup(target); if (!inner) return catalog.unknown_command(target, /*suggest=*/true); - if (inner->key == "call_tool") - return "call_tool calls another tool, not itself"; + if (inner->key == "tool_call") + return "tool_call calls another tool, not itself"; json inner_args = args.contains("args") && args["args"].is_object() ? args["args"] : json::object(); if (std::string err = argument_error(*inner, inner_args); !err.empty()) return "Invalid arguments for " + target + ": " + err; diff --git a/src/slic3r/GUI/Mcp/McpRecorder.cpp b/src/slic3r/GUI/Mcp/McpRecorder.cpp index dc57236b8a..128ee47897 100644 --- a/src/slic3r/GUI/Mcp/McpRecorder.cpp +++ b/src/slic3r/GUI/Mcp/McpRecorder.cpp @@ -286,7 +286,7 @@ bool capture_area(ModalTracker& modals, bool suspended, Recording& rec, const Ca if (rec.options.target == "canvas") { GLCanvas3D* canvas = shown_canvas(); if (canvas == nullptr || canvas->get_wxglcanvas() == nullptr) { - err = "No 3D view is shown; switch to one with set_view tab"; + err = "No 3D view is shown; switch to one with view_set tab"; return false; } std::optional cap = capture_canvas(*canvas, err, options); @@ -453,7 +453,7 @@ json McpRecorder::start(const RecordingOptions& options, uint64_t files_owner) { std::lock_guard lock(m_mutex); if (m_rec && !m_rec->sink->finalized()) - throw ToolFailure("A recording is already running (" + path_to_utf8(m_rec->options.path) + "); stop_recording ends it"); + throw ToolFailure("A recording is already running (" + path_to_utf8(m_rec->options.path) + "); recording_stop ends it"); previous = m_rec; } if (previous) { @@ -787,7 +787,7 @@ json McpRecorder::stop_and_report(std::chrono::milliseconds timeout, json& encod } end_recording(rec, "stopped"); if (!rec->sink->wait_finalized(timeout)) - throw ToolFailure("The recording is still being written to " + path_to_utf8(rec->options.path) + "; call stop_recording again"); + throw ToolFailure("The recording is still being written to " + path_to_utf8(rec->options.path) + "; call recording_stop again"); { std::lock_guard lock(m_mutex); rec->reported = true; @@ -828,7 +828,7 @@ bool McpRecorder::wait_closed(const fs::path& path, std::chrono::milliseconds ti bool McpRecorder::encode_when_closed(AutomationRuntime& runtime, json args, std::function done) { - const NativeCommand* encode = NativeCommands::instance().find("encode_recording"); + const NativeCommand* encode = NativeCommands::instance().find("recording_encode"); if (encode == nullptr || runtime.stopping()) return false; FollowedCall call; @@ -901,10 +901,10 @@ void McpRecorder::call_started(uint64_t call, const NativeCommand& def, const js std::lock_guard lock(m_mutex); if (!m_rec || m_rec->ending || !m_rec->options.captions) return; - // A call with a folded row's arguments is captioned as that row's tile. - const char* context = title_context(def); - m_rec->board.call_started(call, call_title(def, args), safe_caption_detail(def.key, args), Clock::now(), - context != nullptr ? context : ""); + // A tile's call is captioned with the tile's title: action_run of it, or its command called with its arguments. + const auto [title, titled] = shown_title(NativeCommands::instance(), def, args); + const char* context = title_context(*titled); + m_rec->board.call_started(call, title, safe_caption_detail(def.key, args), Clock::now(), context != nullptr ? context : ""); m_captioned[call] = {def.key, {args}}; } @@ -1020,7 +1020,7 @@ void McpRecorder::on_event(wxEvent& event) return; } - // A real click sent its press first; a command alone is a click made without the mouse (click). + // A real click sent its press first; a command alone is a click made without the mouse (widget_click). wxWindow* pressed = in.pressed_window.get(); if (pressed != nullptr && now - in.pressed_at < kSemanticClick && (pressed == window || window->IsDescendant(pressed))) return; diff --git a/src/slic3r/GUI/Mcp/McpRecorder.hpp b/src/slic3r/GUI/Mcp/McpRecorder.hpp index 5b582e079c..b291caf26a 100644 --- a/src/slic3r/GUI/Mcp/McpRecorder.hpp +++ b/src/slic3r/GUI/Mcp/McpRecorder.hpp @@ -44,7 +44,7 @@ wxFont font_with_line_height(const wxFont& font, int line_height); // the coverage. Null for no text. UI thread. std::shared_ptr render_text(const std::string& text, const wxFont& font, int max_width); -// start_recording's arguments. +// recording_start's arguments. struct RecordingOptions { std::string target = "main"; // main | canvas @@ -56,7 +56,7 @@ struct RecordingOptions bool pointer = false; // the pointer highlighted, its clicks rippling boost::filesystem::path path; std::string owner; // the job of the run (a replay or a script) that started it, "" for a client, kPersonOwner - // encode_recording's arguments, path included, for the stop_recording that reports this recording to run; + // recording_encode's arguments, path included, for the recording_stop that reports this recording to run; // null for none. nlohmann::json encode; // Runs on the UI thread once the recording ends, while its file is still being closed, with the reason it @@ -104,20 +104,20 @@ public: // Any thread. Ends the recording `owner` started ("" for a client's), and with `wait`, waits up to 30 s // for its file to be closed. Returns the path of a file still being written after that wait. std::optional end_owned_by(const std::string& owner, const std::string& reason, bool wait); - // stop_recording: ends the running recording and waits for its file, or takes the result of the last + // recording_stop: ends the running recording and waits for its file, or takes the result of the last // one that ended on its own, once. Null when there is none. `encode` gets the recording's // RecordingOptions::encode. nlohmann::json stop_and_report(std::chrono::milliseconds timeout, nlohmann::json& encode); - // get_app_state's recording: {path, target, seconds, frames} while one runs, else null. + // app_state's recording: {path, target, seconds, frames} while one runs, else null. nlohmann::json state() const; // A recording is being written or finalized. bool active() const; // Any thread. Waits up to `timeout` for the recording at `path` to have its file closed; true once it has, // or when that recording is not the latest, since another starts only after it is closed. bool wait_closed(const boost::filesystem::path& path, std::chrono::milliseconds timeout) const; - // Any thread. Encodes a recording once its file is closed: encode_recording with `args` as an unjournaled job, + // Any thread. Encodes a recording once its file is closed: recording_encode with `args` as an unjournaled job, // which `runtime` follows to its end before posting `done` its result on the UI thread. The job is cancelled - // like any encode (cancel_job {job}, the runtime's stop), and `done` is not called once the runtime stops. + // like any encode (job_cancel {job}, the runtime's stop), and `done` is not called once the runtime stops. // False when the runtime is not started or is stopping, or when the system cannot start a thread. bool encode_when_closed(AutomationRuntime& runtime, nlohmann::json args, std::function done); // The files recordings and encodes use; shared with the sinks' finalizers. diff --git a/src/slic3r/GUI/Mcp/McpReplay.cpp b/src/slic3r/GUI/Mcp/McpReplay.cpp index 3c6d1005a8..f77b2b4195 100644 --- a/src/slic3r/GUI/Mcp/McpReplay.cpp +++ b/src/slic3r/GUI/Mcp/McpReplay.cpp @@ -75,7 +75,7 @@ std::optional resolve_placeholder(const std::string& key, const Replay& re } // How a substitution went: in lenient mode an unresolvable placeholder is kept as written; otherwise -// the first one fails the substitution and is recorded here, so run_replay can say why. +// the first one fails the substitution and is recorded here, so replay_run can say why. struct Substitution { bool lenient = false; @@ -315,7 +315,7 @@ std::optional parse_replay(const std::string& text, std::string& err) } // A step's arguments with their placeholders filled in, except Python source, which runs as written (D7): -// the code of a run_script call, of one a call_tool makes, and of the Python steps of an inline replay. +// the code of a script_run call, of one a tool_call makes, and of the Python steps of an inline replay. json substitute_args(const std::string& tool, const json& args, const Replay& replay, const ReplayContext& ctx, Substitution& sub) { if (!args.is_object()) @@ -323,12 +323,12 @@ json substitute_args(const std::string& tool, const json& args, const Replay& re json out = json::object(); for (auto it = args.begin(); it != args.end(); ++it) { const std::string& key = it.key(); - if (tool == "run_script" && key == "code") { + if (tool == "script_run" && key == "code") { out[key] = it.value(); - } else if (tool == "call_tool" && key == "args" && it.value().is_object()) { + } else if (tool == "tool_call" && key == "args" && it.value().is_object()) { const json target = substitute_value(args.value("tool", json()), replay, ctx, sub, 0); out[key] = substitute_args(target.is_string() ? target.get() : std::string(), it.value(), replay, ctx, sub); - } else if (tool == "run_replay" && key == "replay" && it.value().is_object() && it.value().contains("steps") && + } else if (tool == "replay_run" && key == "replay" && it.value().is_object() && it.value().contains("steps") && it.value()["steps"].is_array()) { json nested = json::object(); for (auto field = it.value().begin(); field != it.value().end(); ++field) { @@ -472,7 +472,7 @@ json run_replay(const Replay& replay, ReplayContext& ctx, const ReplayHost& host if (const json dialogs = host.open_dialogs ? host.open_dialogs() : json::array(); dialogs.is_array() && !dialogs.empty()) { message += " with the dialog \"" + dialogs.back().value("title", std::string()) + - "\" open: a step can't answer a dialog it opens, so register an auto_answer_dialogs rule for it " + "\" open: a step can't answer a dialog it opens, so register a dialog_auto_answer rule for it " "before the step, or give the step \"await\": false and answer the dialog in the steps after it"; details["dialogs"] = dialogs; } @@ -488,11 +488,11 @@ json run_replay(const Replay& replay, ReplayContext& ctx, const ReplayHost& host bool ok = !result.is_error; if (ok) { entry["result"] = result.data; - // run_script reports a script that raised, was cancelled or ran out of time in a successful - // result, as run_replay reports a failed step; inside a replay that fails the step, also when an - // call_tool made the call. A job left running (await: false) has no outcome yet. - const std::string target = step.tool == "call_tool" ? args.value("tool", std::string()) : step.tool; - if (target == "run_script" && !is_job_envelope(result) && result.data.value("status", "") != "finished") { + // script_run reports a script that raised, was cancelled or ran out of time in a successful + // result, as replay_run reports a failed step; inside a replay that fails the step, also when an + // tool_call made the call. A job left running (await: false) has no outcome yet. + const std::string target = step.tool == "tool_call" ? args.value("tool", std::string()) : step.tool; + if (target == "script_run" && !is_job_envelope(result) && result.data.value("status", "") != "finished") { entry["error"] = result.data.value("message", "the Python script did not finish"); reason = {{"kind", "python"}, {"status", result.data.value("status", "")}}; ok = false; diff --git a/src/slic3r/GUI/Mcp/McpReplay.hpp b/src/slic3r/GUI/Mcp/McpReplay.hpp index a4a62c5f6a..da7a52616b 100644 --- a/src/slic3r/GUI/Mcp/McpReplay.hpp +++ b/src/slic3r/GUI/Mcp/McpReplay.hpp @@ -42,14 +42,15 @@ struct ReplayContext // The version of the replay format this build writes, the semver string a replay gives as "orca_replay_version". // A replay is read when it has this major version and a minor version no newer than this one; while the major -// version is 0, every minor version may break, so only this minor version is read. The editor's draft and key -// suggestions write the same version (REPLAY_VERSION in resources/web/dialog/ActionReplay/replay_editor.js). -inline constexpr const char* REPLAY_VERSION = "0.1.0"; +// version is 0, every minor version may break, so only this minor version is read. A replay of another format, whose +// steps may name commands this build does not have, is refused for its format before any step is read. The editor's +// draft and key suggestions write the same version (REPLAY_VERSION in resources/web/dialog/ActionReplay/replay_editor.js). +inline constexpr const char* REPLAY_VERSION = "0.2.0"; // Parses a replay (JSON with // and /* */ comments). nullopt with `err` set when invalid. std::optional parse_replay(const std::string& text, std::string& err); -// The text of a run_replay inline replay, which is given as the replay object or as its JSON text. +// The text of a replay_run inline replay, which is given as the replay object or as its JSON text. std::string inline_replay_text(const nlohmann::json& replay); // Replaces ${replay_dir}, ${out_dir}, ${env:NAME}, ${vars.NAME} and ${jobs.NAME} in every string of @@ -80,7 +81,7 @@ struct ExpectFailure }; std::optional check_expect_detail(const nlohmann::json& result, const nlohmann::json& expect); -// What run_replay needs from its host: calling a tool as a child of the replay's job, waiting for +// What replay_run needs from its host: calling a tool as a child of the replay's job, waiting for // a job's result, and dropping replay-scoped dialog auto-answer rules when the replay ends. // step_started and step_finished, when set, report each step as it runs: step_started (1-based // index) before its arguments are substituted, step_finished with the entry as it goes into the @@ -93,7 +94,7 @@ struct ReplayHost std::function cancelled; std::function step_started; std::function step_finished; - // The open modal dialogs, topmost last, as get_app_state lists them. Optional. + // The open modal dialogs, topmost last, as app_state lists them. Optional. std::function open_dialogs; }; diff --git a/src/slic3r/GUI/Mcp/McpReplaySummary.cpp b/src/slic3r/GUI/Mcp/McpReplaySummary.cpp index 840f0f3fef..91530bb9fe 100644 --- a/src/slic3r/GUI/Mcp/McpReplaySummary.cpp +++ b/src/slic3r/GUI/Mcp/McpReplaySummary.cpp @@ -116,8 +116,6 @@ std::pair split_action_id(const std::string& id) return {id.substr(0, first), id.substr(first + 1, last - first - 1)}; } -bool starts_with(const std::string& s, const char* prefix) { return s.rfind(prefix, 0) == 0; } - bool one_of(const std::string& s, std::initializer_list names) { for (const char* n : names) @@ -126,8 +124,34 @@ bool one_of(const std::string& s, std::initializer_list names) return false; } +// The effects of command `key` called with `args`, whichever way it is called: the files it writes, the presets it +// changes, what it sends to a printer. +void flag_effects(Builder& b, const std::string& key, const json& args) +{ + if (one_of(key, {"project_save", "project_export", "preset_export"})) + b.flag(StepFlag::WritesFile); + // The preset bundle manager imports and deletes bundles of presets. + const bool preset_bundle = key == "window_open" && args.is_object() && args.value("window", std::string()) == "preset_bundle"; + if (one_of(key, {"preset_import", "preset_sync"}) || preset_bundle) + b.flag(StepFlag::ChangesPresets); + if (key == "printer_send") + b.flag(StepFlag::SendsToPrinter); +} + +// Each argument of `args` as "name: value", the file of a path by its name. +json argument_texts(const json& args) +{ + json texts = json::array(); + for (const auto& [name, value] : args.items()) { + const bool file = name == "path" && value.is_string(); + texts.push_back(name + ": " + (file ? file_name(value.get()) : value.is_string() ? value.get() : value.dump())); + } + return texts; +} + // A call of command `key` with `args`, or of its tile `tile` (one of its tiles, which runs it with `args`): a call -// whose arguments are a tile's is that tile, `tile` or else the first with them (tile_with_args()). +// whose arguments are a tile's is that tile, `tile` or else the first with them (tile_with_args()). A tile that +// collects a value is described with the call's arguments, which hold that value. void describe_command(Builder& b, const CommandCatalog& catalog, const std::string& key, const json& args, const json* tile = nullptr) { @@ -135,48 +159,40 @@ void describe_command(Builder& b, const CommandCatalog& catalog, const std::stri if (tile == nullptr) if (const NativeCommand* command = catalog.find(key)) tile = tile_with_args(*command, args); - if (tile != nullptr) { + if (tile != nullptr) what["tile"] = tile->at("key"); - } else if (args.is_object() && !args.empty()) { - // Each argument as "name: value", the file of a path by its name. - json texts = json::array(); - for (const auto& [name, value] : args.items()) { - const bool file = name == "path" && value.is_string(); - texts.push_back(name + ": " + - (file ? file_name(value.get()) : value.is_string() ? value.get() : value.dump())); - } - what["args"] = std::move(texts); - } + if ((tile == nullptr || !tile->value("input", std::string()).empty()) && args.is_object() && !args.empty()) + what["args"] = argument_texts(args); b.d.what = std::move(what); - if (starts_with(key, "calib_")) { + // What the command's tile does, as a person's pick of it: a calibration test's dialog, which then replaces the + // project and changes the presets, and Load Project and New Project, which ask about unsaved changes. + if (key == "calibration_generate_test") { b.flag(StepFlag::ReplacesProject); b.flag(StepFlag::ChangesPresets); b.replace("app_asked"); } - if (one_of(key, {"load_project", "new_project"})) { + if (one_of(key, {"project_open", "project_new"})) { b.flag(StepFlag::ReplacesProject); b.replace("app_asked"); } - if (one_of(key, {"save_project", "save_project_as", "export_config"}) || starts_with(key, "export_")) - b.flag(StepFlag::WritesFile); - if (one_of(key, {"import_configs", "preset_bundle", "sync_presets"})) - b.flag(StepFlag::ChangesPresets); - if (key == "send_gcode") - b.flag(StepFlag::SendsToPrinter); + flag_effects(b, key, args); } void describe_action(Builder& b, const CommandCatalog& catalog, const json& args) { - const std::string id = args.contains("id") && args["id"].is_string() ? args["id"].get() : std::string(); + const std::string id = args.contains("id") && args["id"].is_string() ? args["id"].get() : std::string(); + const json given = args.contains("args") ? args["args"] : json(); + // A command's tile, by its full id or by the key inside it, as action_run takes either: a folded row's tile runs its + // command with the row's arguments, and the value it collects when it has one, as a person's pick of it does. + if (const auto [command, tile] = find_tile(catalog, command_tile_key(id)); command != nullptr) { + describe_command(b, catalog, command->key, tile_call_args(tile, given), tile); + return; + } const auto [prefix, middle] = split_action_id(id); if (prefix == kCommandPrefix) { - // A folded row's tile runs its command with the row's arguments, whatever run_action was given. - const auto [command, tile] = find_tile(catalog, middle); - if (tile != nullptr) - describe_command(b, catalog, command->key, tile->at("args"), tile); - else - describe_command(b, catalog, middle, args.contains("args") ? args["args"] : json()); + // A tile `catalog` does not hold (a Design tile of a run without the Design tab), by the key in its id. + describe_command(b, catalog, middle, given); } else if (prefix == "orca_recent_project") { b.d.what = {{"kind", "recent_project"}, {"name", file_name(middle)}}; b.flag(StepFlag::ReplacesProject); @@ -192,13 +208,15 @@ void describe_action(Builder& b, const CommandCatalog& catalog, const json& args } } -// A command of `catalog` with no typed tool's place in the tool list called as one of its tiles: with a tile of its -// own (load_project, export_stl), or with the arguments of a tile that runs it with them (a Design command's folded -// row). Called so, it does what run_action of that tile does. +// A command of `catalog` called as one of its tiles: with the arguments of a tile that runs it with them (a menu row +// folded into it), or with none, as its tile of its own (plate_delete). A command with a tile of its own that the tool +// list does not show (a Design command) is its tile's call whatever its arguments. Called so, it does what action_run +// of that tile does. bool tile_command(const CommandCatalog& catalog, const std::string& tool, const json& args) { const NativeCommand* command = catalog.find(tool); - return command != nullptr && !command->listed && (command->in_palette || tile_with_args(*command, args) != nullptr); + return command != nullptr && (tile_with_args(*command, args) != nullptr || + (command->in_palette && (!command->listed || person_form(args)))); } std::optional read_text(const fs::path& path) @@ -211,7 +229,7 @@ std::optional read_text(const fs::path& path) return ss.str(); } -// A run_replay step: the nested replay, read in the context its run will have. +// A replay_run step: the nested replay, read in the context its run will have. void describe_nested(Builder& b, const CommandCatalog& catalog, const json& args, const ReplayContext& outer, int depth) { std::optional nested; @@ -271,13 +289,13 @@ json describe_what(const std::string& tool, const json& args) return {{"kind", "value"}, {"text", args[key].is_string() ? args[key].get() : args[key].dump()}}; return nullptr; }; - if (one_of(tool, {"select_preset", "save_preset", "delete_preset"}) && args.contains("name") && args["name"].is_string()) + if (one_of(tool, {"preset_select", "preset_save", "preset_delete"}) && args.contains("name") && args["name"].is_string()) return {{"kind", "preset"}, {"name", args["name"]}}; - if (one_of(tool, {"slice", "arrange"})) - return {{"kind", "plates"}, {"plates", args.contains("plates") ? args["plates"] : json(tool == "slice" ? "current" : "all")}}; - if (tool == "wait") + if (one_of(tool, {"plate_slice", "object_arrange"})) + return {{"kind", "plates"}, {"plates", args.contains("plates") ? args["plates"] : json(tool == "plate_slice" ? "current" : "all")}}; + if (tool == "app_wait") return text("for"); - if (tool == "answer_dialog") + if (tool == "dialog_answer") return text("button"); if (args.contains("paths") && args["paths"].is_array()) { json names = json::array(); @@ -302,7 +320,7 @@ json describe_what(const std::string& tool, const json& args) json describe_call(const CommandCatalog& catalog, const std::string& tool, const json& args) { - if (tool == "run_action") { + if (tool == "action_run") { Builder b; describe_action(b, catalog, args); return b.d.what; @@ -312,7 +330,7 @@ json describe_call(const CommandCatalog& catalog, const std::string& tool, const describe_command(b, catalog, tool, args); return b.d.what; } - if (tool == "run_replay") + if (tool == "replay_run") return args.contains("path") && args["path"].is_string() ? json{{"kind", "files"}, {"names", {file_name(args["path"].get())}}} : json(); return describe_what(tool, args); @@ -337,11 +355,11 @@ StepDescription describe_step(const CommandCatalog& catalog, const ReplayStep& s Builder b; b.d.checks_result = !step.expect.empty(); - if (tool == "run_action") { + if (tool == "action_run") { describe_action(b, catalog, args); return b.done(); } - if (tool == "run_replay") { + if (tool == "replay_run") { describe_nested(b, catalog, args, ctx, depth); return b.done(); } @@ -356,46 +374,46 @@ StepDescription describe_step(const CommandCatalog& catalog, const ReplayStep& s if (args.contains(key) && args[key].is_string() && !inside(args[key].get(), ctx.out_dir)) b.flag(StepFlag::WritesFile); }; - if (one_of(tool, {"export", "save_project"})) - b.flag(StepFlag::WritesFile); - if (one_of(tool, {"screenshot", "start_recording"})) + flag_effects(b, tool, args); + if (one_of(tool, {"window_screenshot", "recording_start"})) writes_outside("save_path"); - if (tool == "encode_recording") { + if (tool == "recording_encode") { // Without save_path the video goes beside its source, which it deletes unless keep_raw_video_file. writes_outside(args.contains("save_path") ? "save_path" : "path"); if (!(args.contains("keep_raw_video_file") && args["keep_raw_video_file"].is_boolean() && args["keep_raw_video_file"].get())) writes_outside("path"); } - if (tool == "export_replay") + if (tool == "replay_export") writes_outside("path"); - if (tool == "pick_gizmo_file" && args.value("action", std::string()) == "svg_save_as") + if (tool == "gizmo_pick_file" && args.value("action", std::string()) == "svg_save_as") writes_outside("path"); // A rule's path lets a save picker write the file, or with overwrite replace it. Which picker a rule will // answer isn't known here, so every path counts. - if (tool == "auto_answer_dialogs" && args.contains("rules") && args["rules"].is_array()) + if (tool == "dialog_auto_answer" && args.contains("rules") && args["rules"].is_array()) for (const json& rule : args["rules"]) if (rule.is_object() && rule.contains("path") && rule["path"].is_string() && !rule["path"].get().empty() && !inside(rule["path"].get(), ctx.out_dir)) b.flag(StepFlag::WritesFile); - if (one_of(tool, {"save_preset", "delete_preset", "generate_calibration_test"})) + if (one_of(tool, {"preset_save", "preset_delete", "calibration_generate_test"})) b.flag(StepFlag::ChangesPresets); - if (one_of(tool, {"new_project", "generate_calibration_test"})) { + if (one_of(tool, {"project_new", "calibration_generate_test"})) { b.flag(StepFlag::ReplacesProject); - // new_project with no arguments is New Project's: the app asks about the unsaved changes. - b.replace(tool == "new_project" && person_form(args) ? "app_asked" : "checked"); + // project_new with no arguments is New Project's: the app asks about the unsaved changes. + b.replace(tool == "project_new" && person_form(args) ? "app_asked" : "checked"); } - if (tool == "open_files" && args.contains("paths") && args["paths"].is_array() && args["paths"].size() == 1 && - args["paths"][0].is_string()) { - const std::string path = args["paths"][0].get(); + // A project replaces the current one as discard_changes says; a G-code to look at, after the app asks about its + // unsaved changes. project_open refuses any other file, which replaces nothing. + if (tool == "project_open" && args.contains("path") && args["path"].is_string()) { + const std::string path = args["path"].get(); if (has_extension(path, {".gcode", ".bgcode"})) { b.flag(StepFlag::ReplacesProject); b.replace("app_asked"); - } else if (has_extension(path, {".3mf"}) && args.value("as", std::string("auto")) != "geometry") { + } else if (has_extension(path, {".3mf"})) { b.flag(StepFlag::ReplacesProject); b.replace("checked"); } } - b.d.answers_dialogs = one_of(tool, {"auto_answer_dialogs", "answer_dialog", "click", "press_keys"}); + b.d.answers_dialogs = one_of(tool, {"dialog_auto_answer", "dialog_answer", "widget_click", "keyboard_press"}); return b.done(); } @@ -408,22 +426,22 @@ json describe_result(const std::string& tool, const json& result) return {{"kind", "file"}, {"name", file_name(result[key].get())}}; return nullptr; }; - if (tool == "open_files" && result.value("opened", std::string()) == "gcode") + if (tool == "project_open" && result.value("opened", std::string()) == "gcode") return file_of("path"); - if (one_of(tool, {"open_files", "new_project", "generate_calibration_test"}) && result.contains("objects") && + if (one_of(tool, {"project_open", "project_import", "project_new", "calibration_generate_test"}) && result.contains("objects") && result["objects"].is_number_integer()) return {{"kind", "objects"}, {"count", result["objects"]}}; - if (tool == "slice" && result.contains("plates") && result["plates"].is_array()) { + if (tool == "plate_slice" && result.contains("plates") && result["plates"].is_array()) { int ok = 0, other = 0; for (const json& p : result["plates"]) (p.is_object() && p.value("outcome", std::string()) == "ok" ? ok : other)++; return {{"kind", "plates"}, {"ok", ok}, {"other", other}}; } - if (one_of(tool, {"export", "save_project", "screenshot"})) + if (one_of(tool, {"project_export", "project_save", "window_screenshot"})) return file_of("path"); - if (tool == "pick_gizmo_file") + if (tool == "gizmo_pick_file") return file_of("saved"); - if (tool == "run_replay" && result.contains("passed") && result["passed"].is_boolean()) { + if (tool == "replay_run" && result.contains("passed") && result["passed"].is_boolean()) { json out{{"kind", "replay"}, {"passed", result["passed"]}}; if (result.contains("failed_step")) out["failed_step"] = result["failed_step"]; diff --git a/src/slic3r/GUI/Mcp/McpReplaySummary.hpp b/src/slic3r/GUI/Mcp/McpReplaySummary.hpp index 71089873ce..b8211a8cc9 100644 --- a/src/slic3r/GUI/Mcp/McpReplaySummary.hpp +++ b/src/slic3r/GUI/Mcp/McpReplaySummary.hpp @@ -41,9 +41,11 @@ struct StepDescription }; // Describes `step` of `replay`, substituting its arguments leniently over `ctx`; a file counts as -// written inside the output folder when it is inside ctx.out_dir. A step that calls a Speed Dial command -// by its key (one of `catalog` with no place in the tool list, with a tile of its own or called with the -// arguments of one of its tiles) is described as run_action of that tile is. A run_replay step is described by +// written inside the output folder when it is inside ctx.out_dir. A step that calls a command of `catalog` as one +// of its tiles (with exactly a tile's arguments, or with none where it has a tile of its own, or, for one the tool +// list does not show, a Design command, with any) is described as action_run of that tile is. A step's flags come +// from the command it runs and its arguments, whether it calls the command or action_run of its tile (an export flags +// writes_file either way). A replay_run step is described by // the steps of its inline replay, or of its file when `path` reads and parses, each in the nested // run's own context (its vars merged with the step's `vars`, its own replay and output folders); // past `depth` 4, or when the file doesn't read or parse, it gets every flag, "checked" and @@ -52,7 +54,7 @@ StepDescription describe_step(const CommandCatalog& catalog, const ReplayStep& s const ReplayContext& ctx, int depth = 0); // What a call of `tool` with `args` acts on, as describe_step()'s `what` says it over `catalog`, Speed Dial -// ids included, but from the arguments as they are and without reading files: a run_replay call is named +// ids included, but from the arguments as they are and without reading files: a replay_run call is named // by its replay file. For recording captions. nlohmann::json describe_call(const CommandCatalog& catalog, const std::string& tool, const nlohmann::json& args); diff --git a/src/slic3r/GUI/Mcp/McpServerInfo.cpp b/src/slic3r/GUI/Mcp/McpServerInfo.cpp index 3087055a43..9ede287292 100644 --- a/src/slic3r/GUI/Mcp/McpServerInfo.cpp +++ b/src/slic3r/GUI/Mcp/McpServerInfo.cpp @@ -12,51 +12,54 @@ namespace { // Server instructions shown to the model; clients truncate them at 4096 characters. const char* kInstructions = "OrcaSlicer, a 3D-printing slicer, driven through its GUI.\n" - "Workflow: get_app_state (is it ready? which presets, plates, dialogs?) -> act -> check it with the reading " - "tools (list_objects, list_plates, get_settings, slice's reply, get_slice_stats); screenshot only to see what they " - "do not report.\n" + "Workflow: app_state (ready? which presets, plates, dialogs?) -> act -> check with object_list, plate_list, " + "settings_get, plate_slice's reply or plate_slice_stats; window_screenshot only for what they do not report.\n" "Running the session, dialogs, replays and scripts:\n" "- A call that takes long or opens a dialog returns {status:\"running\"|\"blocked_by_dialog\", job}. It keeps " - "running: never retry it. Answer dialogs with answer_dialog (see get_app_state.dialogs), then wait {for:\"job\"}. " - "A native message box (native: true) is answered with answer_dialog by one of the buttons listed for it; a file or " - "folder picker, or a native dialog whose buttons list is empty (any on macOS), can't be: register auto_answer_dialogs " - "before the step that opens one.\n" - "- While an operation (slice, export, arrange or another background job) runs, other changes are refused; use wait " - "or cancel_job.\n" - "- export_replay saves this session's calls as a replay that run_replay runs.\n" - "- run_script runs Python against orca.host, the plugin API (search_python_api searches it), computing over meshes and " - "settings and calling tools through orca.host.tools; its own file, program, thread and network use is restricted " - "unless get_app_state.python.scripts_unrestricted.\n" - "- Not sure what does something? search_tools {query} searches every catalog at once: the commands, with those the " - "tool list does not show (Speed Dial commands, the Design tab's, and operations plugins offer as " - "plugin..; call_tool runs them), the Speed Dial's other actions, settings and the Python API, each " - "match with how to use it.\n" + "running: never retry it. Answer dialogs with dialog_answer (see app_state.dialogs), then app_wait {for:\"job\"}. A " + "native message box (native: true) takes dialog_answer with one of its listed buttons; a file or folder picker, " + "or a native dialog with no buttons listed (any on macOS), can't: register dialog_auto_answer before the step " + "that opens one.\n" + "- During an operation (slicing, exporting, arranging, another job) other changes are refused: app_wait or " + "job_cancel.\n" + "- replay_export saves this session's calls as a replay that replay_run runs.\n" + "- script_run runs Python against orca.host, the plugin API (script_search_api searches it), to compute over " + "meshes and settings and call tools (orca.host.tools); its file, program, thread and network use is restricted " + "unless app_state.python.scripts_unrestricted.\n" + "- tool_search {query} searches every catalog: the commands, those the tool list does not show too (menu rows " + "with no arguments, the Design tab's, plugin operations as plugin..; tool_call runs them), the " + "Speed Dial's other actions, settings and the Python API.\n" "Acting on project data by index and name, JSON in and out; prefer these:\n" - "- Typed tools: open_files, select_preset, set_settings, slice, export and the rest.\n" - "- What a setting does, or which one controls an effect: get_settings with keys, or query with a few words, and no " - "scope, which looks through the process, filament and printer settings; each item names its scope, the one " - "set_settings needs (its default is the process), and its meta has its description and where (its settings page and " - "group).\n" - "- Objects, parts and plates are 0-based indices, as list_objects and list_plates give " - "them; filament slots and Preview layers are 1-based.\n" - "- Lists come in pages: {items, offset, total}, with next_offset while more remain; call again with that offset to " - "read on. list_objects has plates and outside in place of items.\n" - "- Paths are absolute. Outputs never overwrite a file unless overwrite is true.\n" - "Driving the GUI itself, for what those do not reach or to see what a person sees:\n" - "- run_action runs every Speed Dial command (search_actions finds them): prefer it to GUI clicks.\n" - "- list_widgets lists widgets, menus, 3D toolbar items, gizmos, ImGui items and web page elements with refs; click " - "/ set_widget_value / press_keys / mouse_gesture act on its refs, good across later listings, or on locators, which " - "its description lists.\n" - "- list_windows lists the open windows, modal or not, with refs: a window's ref as screenshot's target captures " - "that window, as list_widgets's target lists it alone, and as set_window's target sizes, moves or raises it.\n" - "- Gizmos (Cut, Text, SVG, the painting tools...): click {target: {gizmo: \"Cut\"}} opens one; its panel's " - "fields and buttons are ImGui items for set_widget_value / click, and painting is a mouse_gesture drag starting on the " - "object. Move the camera with set_view, never a drag: what a drag does follows the user's mouse settings. pick_gizmo_file only stands in for a file picker inside an open gizmo.\n" - "- screenshot returns a downscaled image plus the full-size PNG path; target \"canvas\" is the 3D view.\n" - "- start_recording / stop_recording record a video (MJPEG .mkv), optionally with the tool calls as captions and the " - "pointer highlighted; with encode, stop_recording then encodes it to MP4 with the system ffmpeg as a job to wait " - "for, and encode_recording encodes any recording later. An encode deletes the .mkv this session recorded once the " - "MP4 is written, unless keep_raw_video_file."; + "- Commands are named place first, then verb (object_mirror); tool_search {group:\"Objects\"} lists a place's " + "commands.\n" + "- A call with exactly one Speed Dial tile's arguments (project_export {format:\"gcode\"}) may ask in a dialog or " + "act on the selection, as a person's pick of it does. Any other call, with silent: true where a " + "schema takes it, runs from its arguments; a dialog it still opens (preset_export's always) is in its " + "description.\n" + "- Which setting does what: settings_get {query} (a few words, no type) searches the settings being edited; each " + "item names its type, which settings_set needs, and its meta its description and page.\n" + "- Objects, parts and plates are 0-based, as object_list and plate_list number them; filament slots and Preview " + "layers are 1-based.\n" + "- Lists come in pages: {items, offset, total}, next_offset while more remain (call again with it); object_list " + "has plates and outside for items.\n" + "- Paths are absolute; an output replaces a file only with overwrite: true.\n" + "Driving the GUI, for what those do not reach or to see what a person sees:\n" + "- action_run runs a Speed Dial entry by id from action_search: a tile as a call with its arguments does; a plate, " + "a recent project, a plugin's script or page as a person's pick does.\n" + "- widget_list lists widgets, menus, 3D toolbar items, gizmos, ImGui items and web page elements with refs; " + "widget_click / widget_set_value / keyboard_press / mouse_gesture act on its refs (good across later listings) or " + "on the locators its description lists.\n" + "- window_list lists the open windows with refs: a window's ref as the target of window_screenshot captures it, " + "of widget_list lists it alone, and of window_set sizes, moves or raises it.\n" + "- Gizmos (Cut, Text, SVG, painting...): widget_click {target: {gizmo: \"Cut\"}} opens one; its panel's fields and " + "buttons are ImGui items for widget_set_value / widget_click, and painting is a mouse_gesture drag from the " + "object. Move the camera with view_set, never a drag, which follows the user's mouse settings. gizmo_pick_file " + "stands in for a file picker inside an open gizmo.\n" + "- window_screenshot returns a downscaled image plus the full-size PNG path; target \"canvas\" is the 3D view.\n" + "- recording_start / recording_stop record a video (MJPEG .mkv), optionally captioned with the tool calls, the " + "pointer highlighted; with encode, recording_stop encodes it to MP4 (system ffmpeg) as a job, and " + "recording_encode encodes any later; an encode deletes this session's .mkv once the MP4 is written, unless " + "keep_raw_video_file."; } // namespace diff --git a/src/slic3r/GUI/Mcp/McpStdioBridge.cpp b/src/slic3r/GUI/Mcp/McpStdioBridge.cpp index 9bf7d530cd..3ae4517aed 100644 --- a/src/slic3r/GUI/Mcp/McpStdioBridge.cpp +++ b/src/slic3r/GUI/Mcp/McpStdioBridge.cpp @@ -155,7 +155,7 @@ std::optional> post(const Endpoint& e, const std::st if (sent != nullptr) *sent = false; // Deadlines only apply to Beast's asynchronous operations, so each step runs as one on a - // private io_context. A tool replies within its budget (45 s) and `wait` within 50 s. + // private io_context. A tool replies within its budget (45 s) and `app_wait` within 50 s. try { net::io_context ioc; boost::beast::tcp_stream stream(ioc); @@ -482,7 +482,7 @@ int run_stdio_bridge(int argc, char** argv, const std::function + +#include +#include +#include +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +using nlohmann::json; + +namespace { + +// Every argument that names a target, in one form or the other. +constexpr const char* kTargetArgs[] = {"object", "objects", "object_id", "object_ids", "instance", "instances", "instance_object_ids", + "part", "parts", "part_id", "part_ids"}; + +template void add_once(std::vector& list, const T& item) +{ + if (std::find(list.begin(), list.end(), item) == list.end()) + list.push_back(item); +} + +// The checks of a target's indices against the model, with the texts object_select gives. +struct IndexCheck +{ + const Model& model; + + const ModelObject& object(int index) const + { + if (index < 0 || std::size_t(index) >= model.objects.size()) + throw ToolFailure("object index " + std::to_string(index) + " is out of range"); + return *model.objects[std::size_t(index)]; + } + + // An instance, or with !instance a part, of object `owner`; the object is checked first. + void member(int owner, int index, bool instance) const + { + const ModelObject& o = object(owner); + if (index < 0 || std::size_t(index) >= (instance ? o.instances.size() : o.volumes.size())) + throw ToolFailure("object " + std::to_string(owner) + " has no " + (instance ? "instance " : "part ") + std::to_string(index) + + " (object_list lists them)"); + } + + // [object, index] of a pair argument. + std::pair pair(const json& entry, bool instance) const + { + if (!entry.is_array() || entry.size() != 2 || !entry[0].is_number_integer() || !entry[1].is_number_integer()) + throw ToolFailure(std::string("an entry of ") + (instance ? "instances" : "parts") + " is [object, " + + (instance ? "instance" : "part") + "]"); + const std::pair out{entry[0].get(), entry[1].get()}; + member(out.first, out.second, instance); + return out; + } +}; + +// The ids `ids_key` expects for the entries of `list_key`, one each, checked against `expected` (the object or part +// each entry names) as check_expected_ids() checks one. +template void check_ids(const json& args, const char* list_key, const char* ids_key, const char* id_key, std::size_t entries, + const Expected& expected) +{ + if (!args.contains(ids_key)) + return; + const json& ids = args.at(ids_key); + if (!ids.is_array() || ids.size() != entries) + throw ToolFailure(std::string(ids_key) + " takes one id per entry of " + list_key); + for (std::size_t k = 0; k < entries; ++k) + expected(k, json{{id_key, ids[k]}}); +} + +Targets named_targets(const Model& model, const json& args, unsigned kinds) +{ + using Forms = std::pair; + for (const Forms& forms : {Forms{"object", "objects"}, Forms{"instance", "instances"}, Forms{"part", "parts"}}) + if (args.contains(forms.first) && args.contains(forms.second)) + throw ToolFailure(std::string("Give ") + forms.first + " or " + forms.second + ", not both"); + const IndexCheck check{model}; + Targets out; + + // One target: the object, or an instance or a part of it. + if (args.contains("object")) { + const int index = args.at("object").get(); + const ModelObject& object = check.object(index); + check_expected_ids(object, nullptr, args); + if ((kinds & kParts) && args.contains("part")) { + const int part = args.at("part").get(); + check.member(index, part, false); + check_expected_ids(object, object.volumes[std::size_t(part)], args); + out.parts.emplace_back(index, part); + } else if ((kinds & kInstances) && args.contains("instance")) { + const int instance = args.at("instance").get(); + check.member(index, instance, true); + out.instances.emplace_back(index, instance); + } else if (kinds & kObjects) { + if (args.contains("part_id")) + throw ToolFailure("part_id goes with part"); + out.objects.push_back(index); + } else { + throw ToolFailure(std::string("object names the object of a ") + (kinds & kParts ? "part: give part too" : "instance: give instance too")); + } + } else { + for (const char* key : {"instance", "part", "object_id", "part_id"}) + if (args.contains(key)) + throw ToolFailure(std::string(key) + " goes with object"); + } + + // Several targets, each checked with its expected id before any is taken. + const json objects = kinds & kObjects ? args.value("objects", json::array()) : json::array(); + const json instances = kinds & kInstances ? args.value("instances", json::array()) : json::array(); + const json parts = kinds & kParts ? args.value("parts", json::array()) : json::array(); + std::vector object_list; + std::vector> instance_list, part_list; + for (const json& entry : objects) { + if (!entry.is_number_integer()) + throw ToolFailure("an entry of objects is an object index"); + check.object(entry.get()); + object_list.push_back(entry.get()); + } + for (const json& entry : instances) + instance_list.push_back(check.pair(entry, true)); + for (const json& entry : parts) + part_list.push_back(check.pair(entry, false)); + check_ids(args, "objects", "object_ids", "object_id", object_list.size(), [&](std::size_t k, const json& id) { + check_expected_ids(*model.objects[std::size_t(object_list[k])], nullptr, id); + }); + check_ids(args, "instances", "instance_object_ids", "object_id", instance_list.size(), [&](std::size_t k, const json& id) { + check_expected_ids(*model.objects[std::size_t(instance_list[k].first)], nullptr, id); + }); + check_ids(args, "parts", "part_ids", "part_id", part_list.size(), [&](std::size_t k, const json& id) { + const ModelObject& object = *model.objects[std::size_t(part_list[k].first)]; + check_expected_ids(object, object.volumes[std::size_t(part_list[k].second)], id); + }); + for (int index : object_list) + add_once(out.objects, index); + for (const auto& instance : instance_list) + add_once(out.instances, instance); + for (const auto& part : part_list) + add_once(out.parts, part); + if (out.objects.empty() && out.instances.empty() && out.parts.empty()) + throw ToolFailure("The call names no target; give one, or none to act on the selection"); + return out; +} + +// Whether `selection` holds parts rather than whole instances. +bool holds_parts(const Selection& selection) +{ + return selection.get_mode() == Selection::Volume && !selection.is_single_full_instance() && !selection.is_multiple_full_instance() && + !selection.is_single_full_object() && !selection.is_multiple_full_object(); +} + +Ops::Outcome selected_targets(const Model& model, const Selection* selection, unsigned kinds) +{ + if (selection == nullptr || selection->is_empty()) + return Ops::nothing_selected(); + if (selection->is_wipe_tower()) + return Ops::wrong_selection(); + Targets out; + out.from_selection = true; + const auto in_model = [&model](int object) { return object >= 0 && std::size_t(object) < model.objects.size(); }; + const bool as_object = (kinds & kObjects) && (kinds & kObjectOfSelection); + if (holds_parts(*selection)) { + for (unsigned int index : selection->get_volume_idxs()) { + const GLVolume* volume = selection->get_volume(index); + if (volume == nullptr || volume->is_wipe_tower || volume->volume_idx() < 0 || !in_model(volume->object_idx())) + continue; + if (kinds & kParts) + add_once(out.parts, std::make_pair(volume->object_idx(), volume->volume_idx())); + else if ((kinds & kInstances) && (kinds & kInstanceOfSelectedPart)) + add_once(out.instances, std::make_pair(volume->object_idx(), volume->instance_idx())); + else if (as_object) + add_once(out.objects, volume->object_idx()); + else + return Ops::wrong_selection(); + } + } else { + for (const auto& [object, instances] : selection->get_content()) { + if (!in_model(object)) + continue; + const bool whole = instances.size() == model.objects[std::size_t(object)]->instances.size(); + if ((kinds & kObjects) && (whole || (as_object && !(kinds & kInstances)))) + add_once(out.objects, object); + else if (kinds & kInstances) + for (int instance : instances) + add_once(out.instances, std::make_pair(object, instance)); + else + return Ops::wrong_selection(); + } + } + if (out.objects.empty() && out.instances.empty() && out.parts.empty()) + return Ops::nothing_selected(); + return out; +} + +} // namespace + +std::vector 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("instance", json{{"type", "integer"}, {"minimum", 0}, {"description", "An instance of the object (object_list)."}}); + if (kinds & kParts) { + out.emplace_back("part", json{{"type", "integer"}, {"minimum", 0}, {"description", "A part of the object (object_list)."}}); + out.emplace_back("part_id", expected_id_prop("part")); + } + return out; + } + if (kinds & kObjects) { + out.emplace_back("objects", array_prop({{"type", "integer"}}, "Object indices.")); + out.emplace_back("object_ids", array_prop({{"type", "integer"}}, "The ids object_list reports for objects, one per entry: refused " + "when an index names another object now.")); + } + if (kinds & kInstances) { + out.emplace_back("instances", array_prop({{"type", "array"}}, "[[object, instance], ...]")); + out.emplace_back("instance_object_ids", array_prop({{"type", "integer"}}, "The ids object_list reports for the objects of instances, " + "one per entry: refused when a pair names another object now.")); + } + if (kinds & kParts) { + out.emplace_back("parts", array_prop({{"type", "array"}}, "[[object, part], ...]")); + out.emplace_back("part_ids", array_prop({{"type", "integer"}}, "The ids object_list reports for the entries of parts, one per entry: " + "refused when a pair names another part now.")); + } + return out; +} + +json with_targets(json schema, unsigned kinds, bool one) +{ + for (Property& property : target_props(kinds, one)) + schema["properties"][property.first] = std::move(property.second); + return schema; +} + +bool names_targets(const json& args) +{ + return args.is_object() && std::any_of(std::begin(kTargetArgs), std::end(kTargetArgs), [&args](const char* key) { return args.contains(key); }); +} + +bool names_empty_lists(const json& args) +{ + return names_targets(args) && std::all_of(std::begin(kTargetArgs), std::end(kTargetArgs), [&args](const char* key) { + return !args.contains(key) || (args.at(key).is_array() && args.at(key).empty()); + }); +} + +Ops::Outcome resolve_targets(const Model& model, const Selection* selection, const json& args, unsigned kinds, bool one) +{ + Targets targets; + if (names_targets(args)) { + targets = named_targets(model, args, kinds); + } else { + Ops::Outcome selected = selected_targets(model, selection, kinds); + if (!selected) + return selected; + targets = selected.value(); + } + if (one && targets.objects.size() + targets.instances.size() + targets.parts.size() > 1) + return Ops::one_object_only(); + return targets; +} + +json targets_reply(const Model& model, const Targets& targets) +{ + const auto object_at = [&model](int index) -> const ModelObject* { + return index >= 0 && std::size_t(index) < model.objects.size() ? model.objects[std::size_t(index)] : nullptr; + }; + json out = json::object(); + json objects = json::array(), instances = json::array(), parts = json::array(); + for (int index : targets.objects) + if (const ModelObject* object = object_at(index)) + objects.push_back({{"index", index}, {"object_id", object->id().id}, {"name", object->name}}); + for (const auto& [index, instance] : targets.instances) + if (const ModelObject* object = object_at(index)) + instances.push_back({{"object", index}, {"instance", instance}, {"object_id", object->id().id}, {"name", object->name}}); + for (const auto& [index, part] : targets.parts) + if (const ModelObject* object = object_at(index); object != nullptr && part >= 0 && std::size_t(part) < object->volumes.size()) + parts.push_back({{"object", index}, {"part", part}, {"part_id", object->volumes[std::size_t(part)]->id().id}, + {"name", object->volumes[std::size_t(part)]->name}}); + if (!targets.objects.empty()) + out["objects"] = std::move(objects); + if (!targets.instances.empty()) + out["instances"] = std::move(instances); + if (!targets.parts.empty()) + out["parts"] = std::move(parts); + return out; +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpTargets.hpp b/src/slic3r/GUI/Mcp/McpTargets.hpp new file mode 100644 index 0000000000..5aa0e193e4 --- /dev/null +++ b/src/slic3r/GUI/Mcp/McpTargets.hpp @@ -0,0 +1,73 @@ +#pragma once + +#include "McpTools.hpp" + +#include "slic3r/GUI/Operations/ObjectOps.hpp" +#include "slic3r/GUI/Operations/Outcome.hpp" + +#include + +#include + +namespace Slic3r { + +class Model; + +namespace GUI { + +class Selection; + +// What a command acts on, read from its arguments, or from the Prepare view's selection when they name nothing: one +// reading of the target arguments for every command that takes objects, instances or parts. The struct is the +// operations' (Ops::Targets), since the operations take it. +namespace Mcp { + +using Ops::Targets; + +// The kinds of target a command takes, or'ed, with how the selection is read for a command that asks for it. +enum TargetKind : unsigned { + kObjects = 1, + kInstances = 2, + kParts = 4, + // An instance or a part selected stands for its object, for a command that takes objects and not them. Asked for by + // object_set_instances, whose items read the selected object so (Plater::get_selected_object_idx()), and by the + // commands of one object that have no row: part_add, object_set_variable_layer_height and object_set_height_ranges. + kObjectOfSelection = 8, + // A part selected stands for its instance, for a command that takes instances and not parts. Asked for by + // object_separate_instances, as Set as Individual Objects reads it (ObjectList::split_instances()). + kInstanceOfSelectedPart = 16, +}; + +// The schema properties that name a command's targets of `kinds`, worded as object_select and object_transform word +// them: objects, object_ids, instances ([[object, instance], ...]), instance_object_ids, parts ([[object, part], ...]) +// and part_ids; or with `one`, for a command of one target, object and object_id, then instance and part, each of +// the object. +std::vector target_props(unsigned kinds, bool one); +// `schema` (object_schema()) with target_props(kinds, one) among its properties. +nlohmann::json with_targets(nlohmann::json schema, unsigned kinds, bool one); + +// Whether `args` name a target in any of the forms target_props() gives. +bool names_targets(const nlohmann::json& args); +// Whether the target arguments `args` give are all empty lists (objects: [] and the like), which object_select reads +// as naming nothing, where resolve_targets() refuses them. +bool names_empty_lists(const nlohmann::json& args); + +// The targets of `kinds` that `args` name, each once, in the order named. Every index is checked to be in range and +// every expected id to match (check_expected_ids()) before anything is returned, and a miss throws ToolFailure naming +// it, as do both forms of one target at once (object and objects), an instance or a part without its object, and +// arguments that name nothing (empty lists). +// With none named: what `selection` holds, from_selection set. Every instance of an object selected is the object, +// for a command that takes objects; an instance or a part selected stands for its object only with +// kObjectOfSelection, and a part for its instance only with kInstanceOfSelectedPart. The selection is refused with +// Ops::nothing_selected() when it is empty or null, and Ops::wrong_selection() when it holds a kind the command does +// not take. With `one`, more than one target is refused with Ops::one_object_only(). +Ops::Outcome resolve_targets(const Model& model, const Selection* selection, const nlohmann::json& args, unsigned kinds, bool one); + +// What a reply says a command acted on: {"objects": [{index, object_id, name}], "instances": [{object, instance, +// object_id, name}], "parts": [{object, part, part_id, name}]}, each key there when `targets` holds that kind. The +// indices and names are as `model` has them now. +nlohmann::json targets_reply(const Model& model, const Targets& targets); + +} // namespace Mcp +} // namespace GUI +} // namespace Slic3r diff --git a/src/slic3r/GUI/Mcp/McpTools.hpp b/src/slic3r/GUI/Mcp/McpTools.hpp index 8061c91368..324ca333b2 100644 --- a/src/slic3r/GUI/Mcp/McpTools.hpp +++ b/src/slic3r/GUI/Mcp/McpTools.hpp @@ -17,6 +17,8 @@ #include #include #include +#include +#include #include #include #include @@ -42,13 +44,17 @@ namespace CustomGCode { struct Info; } namespace GUI { struct AppAction; +struct AppActionRunResult; class IMSlider; +class PartPlate; class PartPlateList; class Plater; namespace Ops { struct ExportTicket; +struct Preference; struct Refusal; +enum class PresetChanges; } // namespace Ops namespace Mcp { @@ -57,22 +63,43 @@ class AutomationRuntime; struct Replay; struct ReplayContext; -// Each tool family adds its commands to the catalog (NativeCommands::register_all_commands()), and so do the -// Design tab's (register_cad_commands(), McpToolsCad.hpp). A command's function reaches the automation runtime -// through its call's context (ToolContext::runtime()), so the catalog is built without one. -void register_app_tools(CommandCatalog& catalog); +// Each tool family adds its commands to the catalog (NativeCommands::register_all_commands(), which gives each the +// group of its place), and so do the Design tab's (register_cad_commands(), McpToolsCad.hpp). A command's function +// reaches the automation runtime through its call's context (ToolContext::runtime()), so the catalog is built +// without one. +// `cad`: the catalog holds the Design tab's commands, which undo's and redo's examples call. +void register_app_tools(CommandCatalog& catalog, bool cad); void register_action_tools(CommandCatalog& catalog); void register_project_tools(CommandCatalog& catalog); void register_config_tools(CommandCatalog& catalog); +// The printer models and system filaments a person installs (McpToolsInstall.cpp). +void register_install_tools(CommandCatalog& catalog); +// The Preferences dialog's preferences, read and written (McpToolsPreferences.cpp). +void register_preference_tools(CommandCatalog& catalog); void register_scene_tools(CommandCatalog& catalog); void register_view_tools(CommandCatalog& catalog); +void register_plugin_tools(CommandCatalog& catalog); +// The error of a plugin command refused by `refusal` (McpToolsPlugins.cpp), the plugin's row (plugin_list's) being +// `before` the call and `after` it, null where it is not listed. Where the call changed how the plugin stands (installed, +// enabled or its error: a cloud plugin downloaded before the refusal, or its download's error recorded), the error says +// how it is left and carries its row under "plugin"; else it is the refusal alone. +ToolFailure plugin_refusal_after(const Ops::Refusal& refusal, const nlohmann::json& before, const nlohmann::json& after); +// plugin_enable's reply once the call has ended (McpToolsPlugins.cpp), `row` being the plugin's row then, null where it is +// not listed: {plugin, changed}, with a note while the load the call started (`load_started`) goes on (`still_loading`), or +// where the plugin is no longer listed. A load that ended with the plugin not enabled, or no longer listed, is an error +// (not_loaded) that says how the plugin is left and carries its row. +nlohmann::json plugin_enable_reply(const std::string& plugin, bool changed, bool load_started, bool still_loading, + const nlohmann::json& row); void register_ui_tools(CommandCatalog& catalog); void register_replay_tools(CommandCatalog& catalog); void register_record_tools(CommandCatalog& catalog); void register_python_tools(CommandCatalog& catalog); -// `design_index` ends search_tools' description: what it says of the Design commands (design_command_index(), +// `design_index` ends tool_search's description: what it says of the Design commands (design_command_index(), // McpToolsCad.hpp) in a catalog that holds them, and nothing in one that does not. void register_api_tools(CommandCatalog& catalog, const std::string& design_index); +// Adds the source of the operations the loaded plugins offer (plugin..), which come and go with their +// plugins, in group Plugins: tool_call runs one by name and tool_search finds it; tools/list does not show them. +void register_plugin_operations(CommandCatalog& catalog); // How run_replay_job() runs a replay beyond what the replay says. struct ReplayRunOptions @@ -84,11 +111,11 @@ struct ReplayRunOptions std::function step_finished; }; -// Runs a parsed replay as the calling job, as run_replay does: steps are child calls, dialog rules +// Runs a parsed replay as the calling job, as replay_run does: steps are child calls, dialog rules // the replay registers end with it, and result.json goes to sctx.out_dir (created if missing). It // stops before the next step, and stops waiting on a step's job, once the call is cancelled: the // runtime stops, or a stop was asked for any job in the call's lineage (JobRegistry::request_stop), so -// a nested run_replay stops with the run that holds it. Returns run_replay()'s result with out_dir (and result_file). +// a nested replay_run stops with the run that holds it. Returns run_replay()'s result with out_dir (and result_file). nlohmann::json run_replay_job(AutomationRuntime& runtime, ToolContext& ctx, const Replay& replay, ReplayContext& sctx, const ReplayRunOptions& options); @@ -103,23 +130,33 @@ nlohmann::json enum_prop(std::vector values, const std::string& des nlohmann::json array_prop(nlohmann::json items, const std::string& description); // The typed tools are listed commands (tools/list shows them) made with NativeCommands::long_command(), their -// function unchanged, each in its `group`: core, api or ui (NativeCommand::group). +// function unchanged. A command's group is its place's, which the catalog gives it (NativeCommands::place_heading()). // Pure observation: inline, read-only, inspect guard, not journaled. -NativeCommand inspect_tool(std::string group, std::string name, std::string title, std::string description, nlohmann::json schema, - CommandFn handler); +NativeCommand inspect_tool(std::string name, std::string title, std::string description, nlohmann::json schema, CommandFn handler); // `command`, naming the operations (GUI/Operations) its function reaches, by function name. NativeCommand reaching(std::vector operations, NativeCommand command); // Anything that changes the app: a job under the mutate guard, journaled. -NativeCommand mutate_tool(std::string group, std::string name, std::string title, std::string description, nlohmann::json schema, - CommandFn handler, bool destructive = false); +NativeCommand mutate_tool(std::string name, std::string title, std::string description, nlohmann::json schema, CommandFn handler, + bool destructive = false); +// A command made from menu rows (NativeCommandRows.hpp): NativeCommands::ui_command(), listed, with `description` and +// the rows as its `tiles`. `fn` does what the row a call's variant argument names does, as a person's pick of that row +// does: on the targets the call names (McpTargets.hpp) where the command takes them, else on what is selected. A row +// with no argument form is no command of the tool list: its declaration sets listed false. +NativeCommand row_command(std::string name, std::string title, std::string description, nlohmann::json schema, nlohmann::json tiles, + std::function fn); +// What a command made from rows replies to a call, which a pick does not show: `reply`. +AppActionRunResult row_reply(const nlohmann::json& reply); +// What a command made from rows answers for a refusal after a dialog the person answered or read, which told them why: +// a pick shows nothing more, and a call learns the refusal. +AppActionRunResult quiet_refusal(const Ops::Refusal& refusal); // ---- expected object IDs --------------------------------------------------------------------- -// The schema of an expected ID argument: the id list_objects reports for an object or part (`of`), which +// The schema of an expected ID argument: the id object_list reports for an object or part (`of`), which // orca.host shows too, so a script addresses what it read. nlohmann::json expected_id_prop(const char* of); // `command` with its id_args: the expected-id arguments its schema has (object_id and part_id, as -// expected_id_prop() describes them, and select_objects' object_ids, part_ids and instance_object_ids). Ids are +// expected_id_prop() describes them, and object_select's object_ids, part_ids and instance_object_ids). Ids are // allocated per process, so the session journal leaves them out (without_expected_ids()). NativeCommand with_expected_ids(NativeCommand command); // Refuses the call when `args` names an expected object_id, or part_id, that is not the id of `object`, @@ -154,7 +191,7 @@ bool arg_bool(const nlohmann::json& args, const char* key, bool fallback) // ---- search ---------------------------------------------------------------------------------- -// search_tools' answer from `catalog`, every command it holds and those its sources hold now, for `args`: +// tool_search's answer from `catalog`, every command it holds and those its sources hold now, for `args`: // - tool: that command's group, read_only, description and input schema, and its examples when it has some; // ToolFailure, naming the closest keys, for a key lookup() does not resolve. // - query: {total, items, use}, the `limit` (default 5) best matches by match_score(), each {name, group, summary, @@ -168,17 +205,23 @@ nlohmann::json search_commands(const CommandCatalog& catalog, const nlohmann::js // The Speed Dial actions of `listed` (ActionRegistry::describe()'s items: id, title, group, description) // that `words` (of query_words()) describe, best first: those matching more of the words, then those // matching more of them in what the action is called (the name inside its id, its title and its group), -// then the shorter name, which is the plainer command (obj_delete before obj_delete_all). search_actions -// and search_tools both rank with it, so one query finds the same actions through either. +// then the shorter name, which is the plainer tile (obj_delete before obj_delete_all). action_search +// and tool_search both rank with it, so one query finds the same actions through either. nlohmann::json rank_actions(const nlohmann::json& listed, const std::vector& words); -// Why run_action refuses `args` for `action`, or empty when it does not: a command's tile takes its command's -// arguments, which the command checks, a tile with a preset (a folded row's) takes none or exactly its preset, and -// every other action (a plugin's script or page, a plate's, a setting's or a recent project's) takes none. +// Why action_run refuses `args` for `action`, or empty when it does not: a tile that collects a value (input) takes +// exactly that value, a command's own tile takes its command's arguments, which the command checks, an item of a +// command's tiles (a folded row's, with a preset) takes none or exactly its preset, and every other action (a +// plugin's script or page, a plate's, a setting's or a recent project's) takes none. std::string action_args_error(const AppAction& action, const nlohmann::json& args); +// The arguments action_run's journal step keeps for a command's tile of fixed arguments (AppAction::preset), run with +// `args`, which action_run accepted: what it takes for that tile, the tile's own arguments, or for a tile that collects +// a value, `args` (that value alone). Null for an action without a preset, a Design command's own tile among them, +// which takes its command's arguments and keeps the command's rewrite of them (Mcp::TileContext). +nlohmann::json tile_journal_args(const AppAction& action, const nlohmann::json& args); -// What run_action answers for `id`, an action id or the name inside one, that no action of the app's state has: -// for a Design tab tile's, when that tile is there and the call_tool that runs it from any tab (its command, with +// What action_run answers for `id`, an action id or the name inside one, that no action of the app's state has: +// for a Design tab tile's, when that tile is there and the tool_call that runs it from any tab (its command, with // the row's arguments for a folded row's tile), or, when `catalog` leaves the tile's command out // (CommandCatalog::leave_out()), why; for any other, where an action or a command is found. std::string unknown_action(const std::string& id, const CommandCatalog& catalog); @@ -191,7 +234,7 @@ std::string to_config_string(const nlohmann::json& value, const std::string& key // ---- Python (McpToolsPython.cpp) ------------------------------------------------------------- -// search_python_api's reference: every public module, class, function, method, property, named instance (such +// script_search_api's reference: every public module, class, function, method, property, named instance (such // as orca.host.preset.process) and constant (such as orca.host.ui.PD_CAN_ABORT) of the orca package, in // the order the package lists them, each {name, kind, signature, doc}. signature holds the signature lines // pybind11 starts a docstring with (a class's are its constructors, joined with " | "), and doc the rest @@ -209,14 +252,14 @@ nlohmann::json rank_python_api(const nlohmann::json& reference, const std::strin // Takes the GIL, as python_api_reference() does. bool python_has_numpy(); -// The Run Script panel's session as the calling job, a person's run_script job. -// The job is idle for `wait {for: "idle"}`, and owns what the session's tool calls leave behind (auto-answer rules, a +// The Run Script panel's session as the calling job, a person's script_run job. +// The job is idle for `app_wait {for: "idle"}`, and owns what the session's tool calls leave behind (auto-answer rules, a // recording, a held press) until the session ends, with its rules paused between works and its presses released as each // work ends. The calls hang under a lineage node of the job, which a stop cancels, inline calls included, and which the // next work replaces. Hosts `session` (host_python_session()) under `filename` until it ends; a job cancel ends it. ToolResult run_python_session_job(AutomationRuntime& runtime, ToolContext& ctx, PythonSession& session, const std::string& filename); -// Hosts the Run Script panel's `session` as an unjournaled person's run_script job (run_python_session_job()), which +// Hosts the Run Script panel's `session` as an unjournaled person's script_run job (run_python_session_job()), which // `runtime` follows on a thread of its own that its stop() joins and stop_followed() stops. `file` is the session's // file; empty for an unsaved script. `events.finished` is posted only for a job refused before its handler ran or a // handler that refused (Python scripts off), as {"error": message}; the session's end is PythonSession::ended(), @@ -231,39 +274,70 @@ nlohmann::json editor_tool_catalog(const CommandCatalog& catalog); // ---- recording (McpToolsRecord.cpp) ---------------------------------------------------------- -// Starts encode_recording with `args` as an unjournaled job of its own and returns at once: the job's envelope, or -// the error that refused it. For a recording's encode that stop_recording starts, which a replay of the recording +// Starts recording_encode with `args` as an unjournaled job of its own and returns at once: the job's envelope, or +// the error that refused it. For a recording's encode that recording_stop starts, which a replay of the recording // asks for again. Any thread. ToolResult start_encode(AutomationRuntime& runtime, const nlohmann::json& args); -// ---- settings scopes (McpToolsConfig.cpp) ---------------------------------------------------- +// ---- settings (McpToolsConfig.cpp) ----------------------------------------------------------- -// The keys the object scope (or, with `is_part`, the volume scope) takes: those of `offered` +// Why settings_get (or, with `writes`, settings_set) refuses `args` before reading anything, or empty when it does +// not: a target the type has not (an object's, a part's and a height range's settings are the process's), an object, +// part or height range given with a target that does not take it, a target part named by its object alone, a target +// height_range without min_z and max_z, or nothing named, worded for the tool called (settings_get: no keys, query or +// compare with the target global; settings_set: no values or reset_all), and an extruders_count set with anything +// else or on another type than the printer. Any thread. +std::string settings_request_error(const nlohmann::json& args, bool writes = false); + +// The keys the target object (or, with `is_part`, the target part) takes: those of `offered` // (SettingsFactory::get_options()) that the object list offers with `filaments` filament slots, and // extruder, the object's or part's filament. std::vector model_scope_options(const std::vector& offered, bool is_part, int filaments); -// What `key` is for an object (`volume` null) or one of its parts, and where it comes from: -// {"effective", "source"}, the part's override ("part"), else the object's ("object"), else the -// process's ("process"), else the option's default ("default"; extruder 1). An extruder of 0 is no -// override. For an object, "parts" lists [{volume, value}] for the parts and modifiers overriding -// `key`, each applying only inside its own volume. -nlohmann::json effective_setting(const std::string& key, const DynamicPrintConfig& process, const ModelObject& object, - const ModelVolume* volume); +// The process settings a target of the settings tools takes, as its rows in the Process panel's Objects mode offer +// them on an FFF printer with `filaments` filament slots: object, an object or an assembly, and part, a part or a +// modifier (SettingsFactory::get_fff_options(), model_scope_options()); height_range, one of an object's height +// ranges (layer_range_option_keys()). Each with extruder, the filament its row sets. Empty for another target. +std::vector target_options(const std::string& target, int filaments); +// The targets whose target_options() hold `key`, in the order object, part, height_range. +std::vector targets_taking(const std::string& key, int filaments); +// Why `target` does not take the process setting `key`, saying where it is set, from targets_taking(): "layer_height is +// set on an object or a height range, not on a part", or for a key no target takes, that it is set globally only. +// Empty when the target takes it. +std::string untaken_setting_error(const std::string& key, const std::string& target, int filaments); -// Checks save_preset's `name` against `presets` as the Save preset dialog does, and returns whether the +// settings_list's page of `items`: all of them, unless the items carry their meta (include_meta, which where implies), +// which pages them by 100; limit and offset as given. +nlohmann::json settings_list_page(const nlohmann::json& items, const nlohmann::json& args); + +// What `key` is for an object (`volume` and `range` null), one of its parts, or one of its height ranges (`range`, its +// settings), and where it comes from, in the order the slicer applies them: {"effective", "source"}, the height range's +// own value ("height_range"), else the part's ("part"), else the object's ("object"), else the process's, the global +// value ("global"), else the option's default ("default"; extruder 1). An extruder of 0 is no override. For an object +// or a height range, "parts" lists [{part, value}] for the parts and modifiers overriding `key`, each applying only +// inside its own volume (inside a height range that sets the key, its modifiers alone); for an object, one of its parts +// or a region modifier that sets none of `key`, "height_ranges" lists [{min_z, max_z, value}] for the object's height +// ranges overriding it, each applying only between its heights. Inside a region modifier (a mesh or a painted one) that +// sets none of `key`, the value of the region it overlaps applies: a model part's, or that of a region modifier before it +// in the object's list. Where one of those sets the key, which it overlaps is not worked out: "effective" is null, +// "source" "overlapped_part", "object_effective" and "object_source" give what the object's chain resolves to, and +// "parts" lists [{part, value}] for those that set it. +nlohmann::json effective_setting(const std::string& key, const DynamicPrintConfig& process, const ModelObject& object, + const ModelVolume* volume, const DynamicPrintConfig* range = nullptr); + +// Checks preset_save's `name` against `presets` as the Save preset dialog does, and returns whether the // preset is kept inside the project: where an existing preset of that name is, else `inside_project`, // else where the edited preset is. Throws ToolFailure for a name the dialog refuses, for replacing // another existing preset without `overwrite`, and for an `inside_project` that contradicts where the // existing preset is, which the dialog does not let a person change. bool save_preset_inside_project(const PresetCollection& presets, const std::string& name, const nlohmann::json& args); -// get_settings' meta of an option: label, description (its whole tooltip: what it does, when to change +// settings_get's meta of an option: label, description (its whole tooltip: what it does, when to change // it, what it affects), type, mode, category, unit, range, and for an enum its values with their labels // (the untranslated texts the GUI shows), in the same order. nlohmann::json option_meta(const ConfigOptionDef& def); -// get_settings' search: the keys of `within` that `query` describes, best first, at most `limit`. +// settings_get's search: the keys of `within` that `query` describes, best first, at most `limit`. // A query word matches a word of a key (split at _), its label or its tooltip that starts with it, so // "retract" finds "retraction". Settings matching more of the query's words come first, then those // matching more of them in the key or label, so of two that match alike, the one the query names @@ -271,8 +345,8 @@ nlohmann::json option_meta(const ConfigOptionDef& def); // the query has longer ones. std::vector rank_settings(const std::string& query, const std::vector& within, std::size_t limit); -// get_settings' search without a scope, for search_tools: the process, filament and printer settings being -// edited that `query` describes, best first, {total, items: [{key, scope, label, where}]} with at most +// settings_get's search without a type, for tool_search: the process, filament and printer settings being +// edited that `query` describes, best first, {total, items: [{key, type, label, where}]} with at most // `limit` items. UI thread. nlohmann::json search_settings(const std::string& query, std::size_t limit); @@ -283,7 +357,7 @@ nlohmann::json search_settings(const std::string& query, std::size_t limit); nlohmann::json variant_entries(const std::string& key, const DynamicPrintConfig& config, const std::vector& extruder_types, const std::vector& nozzle_volume_types); -// The serialized value set_settings writes for `key` of the preset whose config is `config`: `value` +// The serialized value settings_set writes for `key` of the preset whose config is `config`: `value` // itself, or for {"index": i, "value": v} the whole vector with entry i replaced, as editing one variant // in the tab leaves it. Throws ToolFailure, naming the entries, for a value with another number of // entries than a per-variant or per-extruder vector of several (a scalar would collapse it), and for a @@ -297,7 +371,7 @@ std::string preset_setting_value(const std::string& key, const nlohmann::json& v // are left out. nlohmann::json preset_diff(const Preset& left, const Preset& right, const std::vector& keys); -// set_settings' "changed": {key: value} for every key whose value differs between `before` and `after`, +// settings_set's "changed": {key: value} for every key whose value differs between `before` and `after`, // with null for a key `after` no longer has. nlohmann::json changed_settings(const DynamicPrintConfig& before, const DynamicPrintConfig& after); @@ -305,6 +379,15 @@ nlohmann::json changed_settings(const DynamicPrintConfig& before, const DynamicP // a vector), whose value `config` no longer holds; each key once. nlohmann::json discarded_changes(const nlohmann::json& changes, const DynamicPrintConfig& config); +// What a command that changes presets (preset_select, printer_install, printer_uninstall) replies when an operation +// refuses: the refusal's text with what an agent can do about it, and the names it carries under the key each refusal +// has. +ToolFailure preset_refused(const Ops::Refusal& refusal); + +// The answer a call's preset_changes gives about the presets' unsaved changes, as the preset tools take it: transfer or +// discard them; Ask where the call gives none. +Ops::PresetChanges preset_changes_answer(const nlohmann::json& args); + // The process, filament and printer presets being edited that have unsaved changes: // {type: {name, changes: {key or key#index: value}}}. UI thread. nlohmann::json unsaved_changes(); @@ -314,7 +397,7 @@ nlohmann::json unsaved_changes(); // that have keys, and left out when there are none. UI thread. nlohmann::json unsaved_changes_outcome(const nlohmann::json& before); -// Checks that delete_preset may delete the preset `name` of `presets`, as the GUI offers and checks it, and +// Checks that preset_delete may delete the preset `name` of `presets`, as the GUI offers and checks it, and // returns the presets deleted with it: for a custom printer (a base printer that is not a system one), // {"process": [names], "filament": [names]} of the user presets of `prints` and `filaments` made for it // alone; otherwise an empty object. Throws ToolFailure for an unknown name (with similar names), a system, @@ -323,17 +406,17 @@ nlohmann::json unsaved_changes_outcome(const nlohmann::json& before); nlohmann::json check_preset_deletable(const PresetCollection& presets, const std::string& name, bool delete_attached, const PresetCollection& prints, const PresetCollection& filaments); -// The project scope's filament_colour to write: one colour per slot of `current`, each #RRGGBB (stored in +// project_set_settings' filament_colour to write: one colour per slot of `current`, each #RRGGBB (stored in // upper case, as the colour pickers store it) or the slot's current colour in any case. `mixed` flags the // mixed slots, whose colour comes from their components and cannot change. Throws ToolFailure otherwise. std::vector check_filament_colours(std::vector colours, const std::vector& current, const std::vector& mixed); -// The project scope's flush_multiplier to write: one per nozzle, or one value for all, each within the +// project_set_settings' flush_multiplier to write: one per nozzle, or one value for all, each within the // Flushing volumes dialog's 0..3. Throws ToolFailure otherwise. std::vector check_flush_multipliers(std::vector multipliers, std::size_t nozzles); -// The project scope's flush_volumes_matrix to write: per nozzle, `slots` x `slots` volumes (row = from, +// project_set_settings' flush_volumes_matrix to write: per nozzle, `slots` x `slots` volumes (row = from, // column = to) in config order over every slot, as project_config and the G-code header hold it, limited // as the Flushing volumes dialog limits them (g_max_flush_volume / the nozzle's multiplier). Throws // ToolFailure for another length, a negative volume, a non-zero diagonal, or a changed entry of a mixed @@ -341,6 +424,41 @@ std::vector check_flush_multipliers(std::vector multipliers, std std::vector check_flush_matrix(std::vector matrix, std::size_t slots, const std::vector& multipliers, const std::vector& current, const std::vector& mixed); +// The keys of a plate's own settings, which plate_get_settings reads and plate_set_settings writes: what the Plate +// Settings dialog sets on one plate, and the filament grouping its filament map icon opens (filament_map_mode, +// filament_map). Its name and its lock are set by its icons, as plate_rename and plate_lock set them. +const std::vector& plate_setting_keys(); + +// plate_list's place of a plate on the bed: {origin, size}, the [x, y] of its front left corner and its [width, depth] +// in mm, in the bed coordinates object positions are given in, read from the plate's rectangle on the bed. +nlohmann::json plate_place(PartPlate& plate); + +// Why plate_set_settings refuses `map` as a plate's filament_map (the 1-based extruder of each filament), or empty +// when it does not: the map is the plate's own grouping, "Manual" as its `mode` (filament_map_mode, "" where the plate +// follows the project's grouping), with one extruder per filament of the `filaments` and each of the printer's +// `extruders`. +std::string filament_map_error(const std::string& mode, const std::vector& map, int filaments, int extruders); + +// preset_list's filters over `items`, one per preset as preset_list builds them: query (part of the name or alias), +// vendor and filament_type (in either case), source (system, user or project; a preset kept in the project is no user +// one), and the items marked compatible: false or installed: false only with include_incompatible or +// include_uninstalled. With `printer`, `fits` says whether an item's preset fits that printer preset: it stands for the +// item's compatible flag, which is for the selected printer, and sets it. +nlohmann::json filter_preset_items(nlohmann::json items, const nlohmann::json& args, + const std::function& fits); + +// settings_set's extruders_count for the printer: what the Extruders field of the Printer settings takes, a whole +// number from 1 to MAXIMUM_EXTRUDER_NUMBER (or a string of one), and nothing while single extruder multi-material is +// on, which greys the field out. Throws ToolFailure otherwise. +std::size_t extruders_count_value(const nlohmann::json& value, bool single_extruder_multi_material); + +// The printer variant settings_set's nozzle_diameter switches to, as the sidebar's nozzle diameter does: the plain +// diameter among `variants` (the printer model's, PresetCollection::diameters_of_selected_printer()) that every +// extruder is given, unless it is the `current` variant. Empty when the extruders differ, no variant has the diameter +// or the printer has it already: the value is then typed into the Printer settings. +std::string nozzle_diameter_variant(const std::vector& diameters, const std::vector& variants, + const std::string& current); + // A plate's filament order as the Plate Settings dialog's drag canvas gives it: every slot 1..`slots` once. // Throws ToolFailure otherwise. std::vector filament_order(const nlohmann::json& order, int slots); @@ -359,17 +477,20 @@ nlohmann::json layer_sequences_json(const std::vector gcode_layer_zs(const GCodeProcessorResult& result); -// list_plates' layer_gcode of a plate's codes: [{z, layer, type, filament, color, gcode}] by height, z +// plate_list's layer_gcode of a plate's codes: [{z, layer, type, filament, color, gcode}] by height, z // rounded to the G-code's 0.001 mm; layer (1-based, as the slider numbers it) where `layer_zs` has a layer // at or above z, the slider's rule for a stored height; filament and color for a filament or colour // change, gcode for custom G-code. nlohmann::json layer_gcode_json(const CustomGCode::Info& codes, const std::vector& layer_zs); -// get_settings on the preferences scope: [{key, value}] for the `keys` of `args` that `config`'s app section, -// where the Preferences dialog keeps its settings, holds, paged, and unknown_keys for the others with a note -// that a preference never changed is not stored. Values are as stored. Throws ToolFailure without keys: the -// section also holds account and device state, so nothing is listed unasked. -nlohmann::json preferences_settings(const AppConfig& config, const nlohmann::json& args); +// preferences_get's reply: {total, items}, an item for each preference of `shown` (the rows the Preferences dialog shows, +// Ops::shown_preferences()) that `args`' keys, tab and query leave (query: each of its words in the key, the label or +// the section, in any case), with its value typed by its kind: the text `shown_texts` gives for its key, which is what +// the dialog shows where that is not the stored value (Ops::shown_texts()), else the one in `config`'s app section; then +// {key, value} as stored for each named key outside `shown` that the section holds, and unknown_keys, with a note, for +// the named keys it lacks. The section also holds account and device state, so nothing outside `shown` is listed unasked. +nlohmann::json preferences_settings(const AppConfig& config, const std::vector& shown, const nlohmann::json& args, + const std::map& shown_texts = {}); // Points the filament tab at the preset of filament slot `slot` (1-based, in range), as opening that slot's // settings does, through the tab's switch, which asks about its unsaved changes. Returns the preset the tab @@ -379,14 +500,14 @@ std::string edit_filament_slot(int slot); // ---- calibration (McpToolsProject.cpp) ------------------------------------------------------- -// generate_calibration_test's arguments as the test's dialog takes them on `printer`: its defaults for what is left out (the +// calibration_generate_test's arguments as the test's dialog takes them on `printer`: its defaults for what is left out (the // pressure advance ones by the printer's extruder type, an input shaping Y range or frequency by the X one), // temperatures clamped to the dialog field's 155-500 °C and rounded down to its 5 °C, and the dialog's rules // (check_calib_params()). Adds to `warnings` what the dialog would say without refusing. Throws ToolFailure // for an argument the test does not take, a value the dialog refuses, or a choice the printer does not offer. Calib_Params calib_params_from_args(const nlohmann::json& args, const DynamicPrintConfig& printer, std::vector& warnings); -// The parameters `params` holds for generate_calibration_test's `args`, in its argument names and units: what generate_calibration_test +// The parameters `params` holds for calibration_generate_test's `args`, in its argument names and units: what calibration_generate_test // reports and records in the journal, so a replay does not depend on the dialogs' defaults. nlohmann::json calib_params_json(const nlohmann::json& args, const Calib_Params& params, const DynamicPrintConfig& printer); @@ -419,6 +540,25 @@ nlohmann::json poll_until(ToolContext& ctx, // thread. std::string undrawn_window(ToolContext& ctx); +// ---- app (McpToolsApp.cpp) ------------------------------------------------------------------- + +// app_log's lines of the log read from `in`: the last `lines` of those at or above `min_level` (trace, debug, info, +// warning, error, fatal). +std::vector log_tail(std::istream& in, const std::string& min_level, std::size_t lines); + +// ---- view (McpToolsView.cpp) ----------------------------------------------------------------- + +// What view_set sets outside the Design tab, as app_state's view gives it, under the names of view_set's arguments so +// that it can be passed back: sidebar_collapsed and sidebar_width (pixels), legend_collapsed and gcode_window, the 3D +// camera's projection (perspective or orthographic), the section view of Prepare and the Preview ({on}), and the display +// switches labels, overhangs, outline, wireframe, gridlines, axes and navigator. UI thread. +nlohmann::json view_state(Plater& plater); + +// The page of the main window's notebook that view_set's `tab` names, of `pages`, the notebook's page ids: the page +// of one of the words of kTabWords (CommandCatalog.hpp), device being the page monitor; else the page of that id, +// when no word names that page (a plugin's page, the web Device page); else nothing. +std::optional view_tab_page(const std::string& tab, const std::vector& pages); + // ---- windows (McpToolsUi.cpp) ---------------------------------------------------------------- // What a window's title bar offers and where it runs, for window_request_refusal(). @@ -430,10 +570,10 @@ struct WindowAbilities bool can_minimize = false; // wxMINIMIZE_BOX in its style bool positions_known = true; // false on Wayland (window_positions_known()) }; -// Why set_window can't apply `args` to such a window, or empty when it can. Checks everything +// Why window_set can't apply `args` to such a window, or empty when it can. Checks everything // before anything changes. std::string window_request_refusal(const nlohmann::json& args, const WindowAbilities& window); -// How set_window's wait for a window ended, for add_window_notes(). +// How window_set's wait for a window ended, for add_window_notes(). struct WindowSettling { bool limited = false; // the size was held to the window's minimum or maximum size @@ -443,7 +583,7 @@ struct WindowSettling int seconds = 3; // how long the wait for the window lasted at most std::string undrawn; // undrawn_window()'s reason the 3D view isn't drawn, or empty }; -// Adds to set_window's `reply`, which holds the size, position and state the window reads back, +// Adds to window_set's `reply`, which holds the size, position and state the window reads back, // adjusted, the fields of `args` the window differs from, and a note on why: a size limit, the window // manager, a compositor that refused to activate a minimized window, or a 3D view that didn't draw. void add_window_notes(const nlohmann::json& args, const WindowSettling& settling, nlohmann::json& reply); @@ -452,7 +592,7 @@ void add_window_notes(const nlohmann::json& args, const WindowSettling& settling // view is shown. UI thread. bool view_drawn_at_size(); // {index, x, y, width, height}: the work area of display `index` (the screen less the taskbar or the -// dock and menu bar), in the units list_windows reports. UI thread. +// dock and menu bar), in the units window_list reports. UI thread. nlohmann::json display_area(unsigned index); // ---- scene ----------------------------------------------------------------------------------- @@ -464,26 +604,26 @@ GLCanvas3D& require_prepare_scene(Plater& plater); // it does. UI thread. void select_rows(ModelObject* object, ModelVolume* volume); -// Scale factors that turn `current` (mm per axis) into the sizes of transform's `size` argument, [x, y, z] +// Scale factors that turn `current` (mm per axis) into the sizes of object_transform's `size` argument, [x, y, z] // with null for an axis that keeps its size. With one number and two nulls, every axis scales by that // axis's factor. Throws ToolFailure for another length, no number, or a size that is not positive. Vec3d size_factors(const Vec3d& current, const nlohmann::json& size); -// Applies arrange's spacing, rotate, align_y and multi_material to `settings` by the Arrange options +// Applies object_arrange's spacing, rotate, align_y and multi_material to `settings` by the Arrange options // panel's rules: Align to Y axis stays off while rotation is on. Settings not given keep their values. // Returns why an asked-for value did not apply, or "". std::string apply_arrange_args(GLCanvas3D::ArrangeSettings& settings, const nlohmann::json& args); -// The settings as arrange replies with them and records them for replay. +// The settings as object_arrange replies with them and records them for replay. nlohmann::json arrange_settings_json(const GLCanvas3D::ArrangeSettings& settings); -// An object as list_objects describes it: its filament, auto_drop, overrides, instances (without the +// An object as object_list describes it: its filament, auto_drop, overrides, mesh errors, instances (without the // plate, which the GUI's plate registry knows), parts, and its height ranges and variable layer height // profile when it has them. Bounding boxes, on the bed and of model parts only, are {min, max, size}. nlohmann::json object_info(const ModelObject& object, std::size_t index); -// A part as list_objects describes it: its type, filament, placement on the bed measured on instance 0, +// A part as object_list describes it: its type, filament, placement on the bed measured on instance 0, // rotation and scale in the object's frame, mesh, paint, and what a text or SVG part was made from. nlohmann::json volume_info(const ModelVolume& volume, std::size_t index); -// What list_objects replies with, laid out as the Objects panel is: `plates`, each {index, name, objects} +// What object_list replies with, laid out as the Objects panel is: `plates`, each {index, name, objects} // with the objects that have an instance on it, and `outside`, the objects with an instance on no plate. // An object row lists the instances of its plate only, so an object on two plates has a row under each. // `plate_of(object, instance)` is the plate an instance is on, or -1, and `plate_names` has a name per @@ -498,17 +638,20 @@ nlohmann::json objects_by_plate(const Model& model, const std::vector part_shape_size(const std::string& shape, const nlohmann::json& size); @@ -520,28 +663,34 @@ void register_layer_tools(CommandCatalog& catalog); // The settings a height range modifier takes: layer_height, the per-region process settings the object // list offers a part or a range (with `filaments` filament slots), and extruder, the range's filament. std::vector layer_range_option_keys(int filaments); -// set_height_ranges' ranges as an object's layer_config_ranges. Each starts from `defaults`, what the -// object list gives a new range, and takes its values, parsed strictly. Throws ToolFailure for a range -// that is not 0 <= min_z < max_z or that overlaps another (touching is fine), a key a range does not -// take, an invalid value, an extruder above `filaments`, or a layer_height given outside -// `layer_height_bounds(extruder)`. -t_layer_config_ranges layer_config_ranges_from_json(const nlohmann::json& ranges, const DynamicPrintConfig& defaults, int filaments, - const std::function(int extruder)>& layer_height_bounds); -// An object's height range modifiers as list_objects and set_height_ranges report them: -// [{min_z, max_z, values: {key: value serialized as get_settings returns it}}], lowest first. +// A height range as messages give it: "0-5", "12.5-20". +std::string height_range_text(const Slic3r::t_layer_height_range& range); +// object_set_height_ranges' ranges, each {min_z, max_z}, as an object's layer_config_ranges: a range of `current`, the +// object's, with the same heights keeps its settings, and any other starts from `defaults`, what the object list gives +// a new range. Throws ToolFailure for a range that is not 0 <= min_z < max_z or that overlaps another (touching is +// fine). +t_layer_config_ranges layer_config_ranges_from_json(const nlohmann::json& ranges, const t_layer_config_ranges& current, + const DynamicPrintConfig& defaults); +// settings_set's check of the `values` it writes to a height range whose settings are `range`: a layer_height given is +// within `layer_height_bounds(extruder)` for the range's filament after the call (the one given, else the range's), as the +// range editor checks what a person types. Throws ToolFailure otherwise. +void check_height_range_layer_height(const DynamicPrintConfig& values, const DynamicPrintConfig& range, + const std::function(int extruder)>& layer_height_bounds); +// An object's height range modifiers as object_list and object_set_height_ranges report them: +// [{min_z, max_z, values: {key: value serialized as settings_get returns it}}], lowest first. nlohmann::json layer_config_ranges_json(const t_layer_config_ranges& ranges); -// An object's layer_height_profile ([z0, h0, z1, h1, ...]) as list_objects and set_variable_layer_height +// An object's layer_height_profile ([z0, h0, z1, h1, ...]) as object_list and object_set_variable_layer_height // report it: {points, min_height, max_height}, heights to 0.001 mm; null unless the object list marks the // object's layer height as variable (more than 4 entries). nlohmann::json layer_height_profile_json(const std::vector& profile); -// The names set_custom_gcode_at_layer and list_plates give the types of layer codes: pause, custom, template, +// The names plate_set_custom_gcode and plate_list give the types of layer codes: pause, custom, template, // change_filament, and color_change for an old project's colour change. const char* custom_gcode_type_name(CustomGCode::Type type); -// The type set_custom_gcode_at_layer adds for a name; CustomGCode::Unknown for any other, color_change included, +// The type plate_set_custom_gcode adds for a name; CustomGCode::Unknown for any other, color_change included, // since the layer slider adds none. CustomGCode::Type custom_gcode_type_from_name(const std::string& name); -// set_custom_gcode_at_layer's clear, remove and add, in that order, on a layer slider that holds a plate's layers +// plate_set_custom_gcode's clear, remove and add, in that order, on a layer slider that holds a plate's layers // and codes. Everything is checked against the slider's layers and codes before it changes, with the // rules of its menus: one code per layer, a template only when the printer has one (`has_template`), a // filament change only with two or more filaments, as many as the slider has (`filaments`, the slots now), @@ -571,13 +720,13 @@ class GCodeViewer; namespace Mcp { -// The camera set_view leaves, as its reply's camera_state and get_app_state.camera give it: type ("ortho" +// The camera view_set leaves, as its reply's camera_state and app_state.camera give it: type ("ortho" // or "perspective"), look_at, the point it looks at, and position ([x, y, z] in mm, to 0.001), zoom (viewport // pixels per mm at look_at's depth) and click_px_per_mm (the zoom in the logical pixels the input tools take, the zoom over // `canvas_scale`), both to 0.0001, and the elevation and azimuth orbit uses, in whole degrees. nlohmann::json camera_state(Camera& camera, double canvas_scale); -// What a sliced plate reports in the slice reply: print time, filament totals with the flush, cost, +// What a sliced plate reports in plate_slice's reply: print time, filament totals with the flush, cost, // layer count, max Z, filament changes, and every filament slot of the project (zeros for slots the // plate does not use, so filaments[i] is slot i + 1) split into model, support, flush and prime // tower. Read from `statistics`, the plate's gcode_statistics_json() parsed, so the reply agrees with @@ -585,18 +734,18 @@ nlohmann::json camera_state(Camera& camera, double canvas_scale); // leaves out, come from `result`. nlohmann::json plate_summary(const nlohmann::json& statistics, const GCodeProcessorResult& result); -// get_slice_stats's tables, from the same parsed statistics, which sum the moves as the Preview does. +// plate_slice_stats's tables, from the same parsed statistics, which sum the moves as the Preview does. // Per feature type, keyed by the English names of the G-code's ;FEATURE: tags: seconds, share of // the print time and grams, plus a Travel row with its distance. The shares need not add up to 100: // the print time also counts retractions, wipes, Z moves, tool changes and the prepare time. nlohmann::json preview_features(const nlohmann::json& statistics); -// Every layer, numbered from 1 as the Preview's layer slider and set_view count them, with its Z, +// Every layer, numbered from 1 as the Preview's layer slider and view_set count them, with its Z, // its height above the layer below (a layer lower than that one, the next object of a by-object // print, starts again from the bed), seconds and grams; with `with_features`, the seconds of each // feature type on it. nlohmann::json preview_layers(const nlohmann::json& statistics, bool with_features); // Grams per object instance, model and support. The G-code names an instance by its object's name -// and its index among that object's instances, so an entry gets the list_objects index `object` +// and its index among that object's instances, so an entry gets the object_list index `object` // only when exactly one of `object_names` (the model's objects, in order) has its name. nlohmann::json preview_objects(const nlohmann::json& statistics, const std::vector& object_names); // What the Preview shows: view type, time mode, the layer slider's range (1-based) with the Z of @@ -605,7 +754,7 @@ nlohmann::json preview_state(GCodeViewer& viewer); // Whether the Preview's toolpaths are `result`'s. It loads a plate's only while it is shown, so after // another plate is selected it keeps the last one's. UI thread. bool viewer_holds(const GCodeViewer& viewer, const GCodeProcessorResult* result); -// The names get_slice_stats and set_view give the legend's rows: a feature type by the English name of +// The names plate_slice_stats and view_set give the legend's rows: a feature type by the English name of // its ;FEATURE: tag, an option by a key; null for the options that are markers, not rows. std::string legend_feature_key(libvgcode::EGCodeExtrusionRole role); const char* legend_option_key(libvgcode::EOptionType type); diff --git a/src/slic3r/GUI/Mcp/McpToolsActions.cpp b/src/slic3r/GUI/Mcp/McpToolsActions.cpp index f5333d4701..296ac29a09 100644 --- a/src/slic3r/GUI/Mcp/McpToolsActions.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsActions.cpp @@ -1,4 +1,4 @@ -// search_actions and run_action: every Speed Dial action - built-in commands, plates, recent projects, +// action_search and action_run: every Speed Dial action - built-in commands, plates, recent projects, // plugin scripts and pages, and (on request) settings - is reachable through these two tools. #include "slic3r/GUI/I18N.hpp" @@ -31,7 +31,7 @@ ActionRegistry& registry_or_fail() { ActionRegistry* reg = wxGetApp().m_action_registry.get(); if (reg == nullptr) - throw ToolFailure("The action catalog is not available yet; wait {for:\"ready\"} first"); + throw ToolFailure("The action catalog is not available yet; app_wait {for:\"ready\"} first"); return *reg; } @@ -79,18 +79,38 @@ const AppAction& find_action(ActionRegistry& actions, std::string& id) std::string action_args_error(const AppAction& action, const json& args) { + // A tile that collects a value takes that value alone, as the Speed Dial's second phase gives it. + if (!action.input.empty()) + return args.is_object() && args.size() == 1 && args.contains(action.input) ? + std::string() : + "The action " + action.id() + " takes exactly its " + action.input + ": run it with args {\"" + action.input + + "\": ...} (its input_schema)"; if (person_form(args)) return {}; - // A folded row's tile runs its command with the row's arguments, which it takes as well as none. - if (!action.preset.is_null()) - return args == action.preset ? std::string() : - "The action " + action.id() + " runs " + action.command + " with " + action.preset.dump() + - ": run it without args, or with exactly those"; + // A command's tile runs its command with the tile's arguments, which it takes as well as none; other arguments are + // the command's to take. + if (!action.preset.is_null()) { + if (args == action.preset) + return {}; + if (action.preset.empty()) + return "The action " + action.id() + " takes no arguments: run it without args, or call " + action.command + + " with them"; + return "The action " + action.id() + " runs " + action.command + " with " + action.preset.dump() + + ": run it without args or with exactly those, or call " + action.command + " with other arguments"; + } + // A Design command's own tile takes the command's arguments, which the command checks. if (!action.command.empty()) return {}; return "The action " + action.id() + " takes no arguments: run it without args"; } +json tile_journal_args(const AppAction& action, const json& args) +{ + if (action.preset.is_null()) + return nullptr; + return action.input.empty() ? action.preset : args; +} + std::string unknown_action(const std::string& id, const CommandCatalog& catalog) { // A Design tile is no action while it is not live (ActionRegistry::materialize_design_actions()); its @@ -110,10 +130,10 @@ std::string unknown_action(const std::string& id, const CommandCatalog& catalog) call += ", \"args\": {" + args + "}"; } return id + " is a Design tab tile, there only while the Design tab is shown in its mode (a sketch's or the model's) " - "with the CAD feature on; call_tool " + call + "} runs its command from any tab"; + "with the CAD feature on; tool_call " + call + "} runs its command from any tab"; } - // The name may be a command's that has no tile, which call_tool runs. - return "Unknown action id " + id + "; find an action with search_actions, or a command with search_tools"; + // The name may be a command's that has no tile, which tool_call runs. + return "Unknown action id " + id + "; find an action with action_search, or a command with tool_search"; } json rank_actions(const json& listed, const std::vector& words) @@ -175,13 +195,13 @@ ToolResult await_gcode_export(ToolContext& ctx, const Ops::ExportTicket& ticket) void register_action_tools(CommandCatalog& catalog) { catalog.add(inspect_tool( - "ui", "search_actions", L("Search Speed Dial actions"), + "action_search", L("Search Speed Dial actions"), "Search everything the Speed Dial can run: built-in commands (slice, export, views, object operations, plates, " - "calibration wizards, help), recent projects, plugin scripts and pages. Each entry has an id for run_action, a " + "calibration wizards, help), recent projects, plugin scripts and pages. Each entry has an id for action_run, a " "description, the command's key for a built-in command, and, when it takes arguments, their input_schema. A query " "ranks them, best match first, as " - "search_tools does; without one they are listed by group and title. include_settings also lists settings (each " - "jumps to that setting in the sidebar; use get_settings / set_settings to read or change values).", + "tool_search does; without one they are listed by group and title. include_settings also lists settings (each " + "jumps to that setting in the sidebar; use settings_get / settings_set to read or change values).", object_schema({{"query", prop("string", "A few words, e.g. \"delete object\": each is matched at the start of the words of " "an action's id, title, group and description.")}, {"group", prop("string", "Only this group, e.g. \"Object\", \"View\", \"Slice & Export\".")}, @@ -205,58 +225,61 @@ void register_action_tools(CommandCatalog& catalog) })); NativeCommand run = mutate_tool( - "ui", "run_action", L("Run a Speed Dial action"), - "Run one action by the id search_actions returned (orca_command:view_front:orca, or the name inside it, view_front), " - "with args, the command's arguments, when it takes some (its input_schema). A command that asks in a dialog asks " - "when it is given no args, as a person's pick does, and runs without asking when given them: an absolute path " - "skips a file dialog, and an output needs {\"path\": ..., \"overwrite\": true} to replace a file. Go to layer and " - "Go to tab need their value ({\"percent\": 50}, {\"tab\": \"preview\"}). Actions that open a dialog return " - "blocked_by_dialog; answer it with answer_dialog, or, for a native one it can't press (a file picker), register " - "auto_answer_dialogs before the call. An export_gcode with a path completes when the file is written; an action " - "that starts a background job (obj_arrange, obj_orient) when the job ends. An action that does nothing (no object " - "selected) is an error. Some commands add what they did to the reply (the obj_order_by_* order, the object " - "obj_assemble made). A command's action runs that command, as call_tool {tool: its command} does; the tile of a " - "Design tab menu row folded into a command runs that command with the row's arguments, and takes no others. The " - "other actions (plates, recent projects, plugin scripts and pages, settings) run only here.", - object_schema({{"id", prop("string", "Action id from search_actions, or the name inside it.")}, + "action_run", L("Run a Speed Dial action"), + "Run one action by the id action_search returned (orca_command:view_front:orca, or the name inside it, view_front), " + "with args, the command's arguments, when it takes some (its input_schema). A command's tile (action_search names " + "the command) runs the command as a call with the tile's arguments does: a tile that asks in a dialog asks, and " + "the call returns blocked_by_dialog; answer it with dialog_answer, or, for a native one it can't press (a file " + "picker), register dialog_auto_answer before the call. Such a tile takes no args, or exactly its own; to run a " + "command without asking, call it with its arguments (an absolute path skips a file dialog). Go to layer and Go to " + "tab take their value alone ({\"percent\": 50}, {\"tab\": \"preview\"}), and a Design command's own tile takes the " + "command's arguments. An action that starts a background job (obj_arrange, obj_orient) completes when the job " + "ends. An action that does nothing (no object selected) is an error. Some commands add what they did to the reply " + "(the order object_order leaves, the object object_assemble made). The other actions (plates, recent projects, " + "plugin scripts and pages, settings) run only here.", + object_schema({{"id", prop("string", "Action id from action_search, or the name inside it.")}, {"args", {{"type", "object"}, {"description", "The command's arguments, as its input_schema gives them."}}}}, {"id"}), [](const json& args, ToolContext& ctx) { std::string id = arg_string(args, "id"); json command_args = args.contains("args") ? args["args"] : json::object(); - std::string key; // the command of a command's tile - AppActionRunResult result; // of any other action + std::string key; // the command of a command's tile + json tile_args; // what its journal step keeps for a tile of fixed arguments + AppActionRunResult result; // of any other action ctx.run_ui([&]() -> json { ActionRegistry& actions = registry_or_fail(); const AppAction& action = find_action(actions, id); if (const std::string err = action_args_error(action, command_args); !err.empty()) throw ToolFailure(err); - key = action.command; - if (key.empty()) + key = action.command; + tile_args = tile_journal_args(action, command_args); + if (key.empty()) { result = actions.run(id, command_args, /*record_stats=*/false); - else if (!action.preset.is_null()) - // A folded row's tile runs its command with the row's arguments, which the journal records. - command_args = action.preset; + } else { + // What a person's pick of the tile runs its command with, which the journal records. + const json* tile = find_tile(NativeCommands::instance(), short_id(id)).second; + command_args = tile_call_args(tile, command_args); + } return json(); }); if (key.empty()) { settle(ctx); return NativeCommands::from_run_result(id, result); } - // A command's tile runs the command's own function, as a call of the command does, inside run_action's + // A command's tile runs the command's own function, as a call of the command does, inside action_run's // journal entry. const NativeCommand* command = NativeCommands::find(key); if (command == nullptr) throw ToolFailure("Unknown command " + key); if (const std::string err = argument_error(*command, command_args); !err.empty()) throw ToolFailure("Invalid arguments for " + key + ": " + err); - TileContext tile(ctx, id); + TileContext tile(ctx, id, tile_args); ToolResult reply = command->run(command_args, tile); if (!reply.is_error && reply.data.is_object()) reply.data["ran"] = id; return reply; }); - // Its commands upload G-code to a print host (send_gcode) and sync presets with the cloud account (sync_presets). + // Its tiles upload G-code to a print host (printer_send) and sync presets with the cloud account (preset_sync). run.open_world = true; catalog.add(run); } diff --git a/src/slic3r/GUI/Mcp/McpToolsApi.cpp b/src/slic3r/GUI/Mcp/McpToolsApi.cpp index ff9b440033..248bf5182e 100644 --- a/src/slic3r/GUI/Mcp/McpToolsApi.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsApi.cpp @@ -1,7 +1,7 @@ -// search_tools and call_tool: a generic way to every command of the catalog, those tools/list never shows -// among them: the Speed Dial's commands, the Design tab's and the operations plugins offer (plugin..). -// search_tools's search also reaches the other catalogs an agent calls into: the Speed Dial's other actions, -// settings and the Python API. +// tool_search and tool_call: a generic way to every command of the catalog, those tools/list does not show among +// them: the menu rows that take no arguments, the Design tab's commands and the operations plugins offer +// (plugin..). tool_search's search also reaches the other catalogs an agent calls into: the Speed Dial's +// other actions, settings and the Python API. #include "McpArguments.hpp" #include "McpTools.hpp" @@ -56,11 +56,11 @@ json editor_tool_catalog(const CommandCatalog& catalog) namespace { -// How many of each other catalog's matches search_tools shows beside the commands, and of the commands +// How many of each other catalog's matches tool_search shows beside the commands, and of the commands // without a limit; each catalog's own search lists the rest. constexpr std::size_t kCatalogHits = 5; -// What search_tools looks through: every command of `catalog`, in the order they were added, then what its +// What tool_search looks through: every command of `catalog`, in the order they were added, then what its // sources hold now; with `group`, those of that group, compared in any case. A group none of them has is // refused with the groups there are, in the order they first appear. std::vector> search_inventory(const CommandCatalog& catalog, const std::string& group) @@ -89,7 +89,7 @@ std::vector> search_inventory(const Command return out; } -// A catalog's best matches for search_tools, from `ranked`, its matches best first: {total, items, use} +// A catalog's best matches for tool_search, from `ranked`, its matches best first: {total, items, use} // with the first few, or null when nothing matched. json catalog_hits(const json& ranked, const std::string& use) { @@ -102,7 +102,7 @@ json catalog_hits(const json& ranked, const std::string& use) } // The Speed Dial's actions that are no command (plates, recent projects, plugin scripts and pages) and settings -// matching `words` (of `query`), for search_tools. A command's tile is left out: the command is among the +// matching `words` (of `query`), for tool_search. A command's tile is left out: the command is among the // commands already. A catalog that can't be read yet (startup, before the main window) is left out. UI thread. json ui_catalog_hits(const std::vector& words, const std::string& query) { @@ -115,13 +115,13 @@ json ui_catalog_hits(const std::vector& words, const std::string& q for (json& action : listed["items"]) if (!action.contains("command")) others.push_back(std::move(action)); - // Ranked as search_actions ranks them, so the same query reads on there from these. - out["actions"] = catalog_hits(rank_actions(others, words), "run_action {id, args}; search_actions {query} lists the rest"); + // Ranked as action_search ranks them, so the same query reads on there from these. + out["actions"] = catalog_hits(rank_actions(others, words), "action_run {id, args}; action_search {query} lists the rest"); } try { json settings = search_settings(query, kCatalogHits); if (settings["total"] != 0) { - settings["use"] = "get_settings {scope, keys} reads one with its description; set_settings {scope, values} changes it"; + settings["use"] = "settings_get {type, keys} reads one with its description; settings_set {type, values} changes it"; out["settings"] = std::move(settings); } } catch (const ToolFailure&) { @@ -129,7 +129,7 @@ json ui_catalog_hits(const std::vector& words, const std::string& q return out; } -// The Python API entries matching `query`, for search_tools, or null when Python is not running or none +// The Python API entries matching `query`, for tool_search, or null when Python is not running or none // matches. json python_hits(const std::string& query) { @@ -142,7 +142,7 @@ json python_hits(const std::string& query) try { ranked = rank_python_api(python_api_reference(), query); } catch (const ToolFailure&) { - return nullptr; // search_python_api reports why + return nullptr; // script_search_api reports why } if (ranked.empty()) return nullptr; @@ -152,7 +152,7 @@ json python_hits(const std::string& query) {"summary", first_sentence(ranked[i]["doc"].get())}}); return {{"total", ranked.size()}, {"items", std::move(items)}, - {"use", "run_script {code}; search_python_api {query} gives each entry's whole documentation"}}; + {"use", "script_run {code}; script_search_api {query} gives each entry's whole documentation"}}; } json describe_tool(const NativeCommand& def) @@ -169,14 +169,14 @@ json describe_tool(const NativeCommand& def) } // A plugin's operation as a command: a job (plugin code may take long), under the mutate guard and journaled -// when it changes something, under the inspect guard and unjournaled when it only reads. Not listed; in the api -// group, as it is called by name with JSON in and out. +// when it changes something, under the inspect guard and unjournaled when it only reads. Not listed; in the group +// Plugins, the place of the commands that manage the plugins. std::shared_ptr operation_command(const PluginOperation& op) { auto def = std::make_shared(); def->key = op.full_name(); def->title = op.name; - def->group = "api"; + def->group = "Plugins"; def->description = "Offered by a plugin. " + op.description; def->input_schema = op.schema; def->read_only = !op.changes; @@ -199,7 +199,7 @@ std::shared_ptr operation_command(const PluginOperation& op } // The operations the loaded plugins offer (plugin..), which come and go with their plugins: a -// call finds one by name, and search_tools lists them; tools/list does not. +// call finds one by name, and tool_search lists them; tools/list does not. class PluginOperationSource final : public CommandSource { public: @@ -265,34 +265,40 @@ json search_commands(const CommandCatalog& catalog, const json& args) } return {{"total", scored.size()}, {"items", std::move(items)}, - {"use", "call a listed command by its name; call_tool {tool, args} runs one that is not listed"}}; + {"use", "call a listed command by its name; tool_call {tool, args} runs one that is not listed"}}; +} + +void register_plugin_operations(CommandCatalog& catalog) +{ + // Plugin operations resolve by name, beside the catalog's commands, without being listed. + catalog.add_source(std::make_unique()); } void register_api_tools(CommandCatalog& catalog, const std::string& design_index) { - // Plugin operations resolve by name, beside the catalog's commands, without being listed. - catalog.add_source(std::make_unique()); - // Its description ends with `design_index`: the Design commands' names, in a catalog that holds them. catalog.add(inspect_tool( - "api", "search_tools", L("Find tools, actions, settings and APIs"), + "tool_search", L("Find tools, actions, settings and APIs"), "Find what does something, in one search, or look up one command. With query: the commands that match, best " "first, each with its group, the first sentence of its description and listed, whether the tool list shows it; " - "one that is not listed (a Speed Dial command, a Design tab command, or an operation a plugin offers, " - "plugin..) comes with its input schema, and its description when that says more, which nothing " - "else shows. Beside them, the best few matches of each other catalog, with its total and how to use it: actions " - "(the Speed Dial's plates, recent projects and plugin scripts and pages, for run_action), settings (get_settings " - "/ set_settings) and python (the orca API for run_script). With tool: that command's description and input schema, " - "and its examples when it has some (the Design commands do). With neither: every command's name. group keeps the " - "names and the command matches to one group; the other catalogs' matches stay as they are. call_tool runs any " - "command, listed or not." + design_index, + "one that is not listed (a menu row that takes no arguments, a Design tab command, or an operation a plugin " + "offers, plugin..) comes with its input schema, and its description when that says more, which " + "nothing else shows. Beside them, the best few matches of each other catalog, with its total and how to use it: " + "actions (the Speed Dial's plates, recent projects and plugin scripts and pages), settings, and python (the orca " + "API a script calls). The reply says how to call each kind of match. With tool: that command's description and " + "input schema, and its examples when it has some (the Design commands do). With neither: every command's name. " + "group keeps the names and the command matches to one group; the other catalogs' matches stay as they are." + + design_index, object_schema({{"tool", prop("string", "A command's name: its description and schema.")}, {"query", prop("string", "A few words saying what you want to do or find, e.g. \"brim\" or \"mesh normals\".")}, - {"group", prop("string", "Only the commands of this group, in any case: core (the session, dialogs and " - "Python), api (project data by index and name; plugin operations too), ui (the " - "GUI itself), Design (the Design tab's, with the CAD feature on), or a Speed Dial " - "section such as Commands, Object or View. A group no command has is refused with " - "the groups there are.")}, + {"group", prop("string", "Only the commands of this group, in any case: the heading of a place (Tools " + "and actions; The app; The project; Objects; Parts; Plates; Presets and " + "settings; Filaments; Printers and prints; Plugins, with the operations plugins " + "offer; View and windows; Recordings, replays and scripts; Driving the GUI), the " + "place a command's name starts with, but for window_screenshot and " + "window_save_screenshot, which are under Recordings, replays and scripts; or " + "Design (the Design tab's, with the CAD feature on). A group no command has is " + "refused with the groups there are.")}, {"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 200}, {"description", "At most this many commands (default 5)."}}}}), [](const json& args, ToolContext& ctx) { json out = search_commands(NativeCommands::instance(), args); @@ -316,15 +322,15 @@ void register_api_tools(CommandCatalog& catalog, const std::string& design_index // Dispatched before it runs (resolve_call): the call runs as the target's own, with its guard, // mode, budget and journal flag, and is journaled as the target's call. This handler is never reached. NativeCommand call = mutate_tool( - "api", "call_tool", L("Call a tool or plugin operation"), - "Call any command by name with its arguments: a tool, or one the tool list does not show, a Speed Dial command, a " - "Design tab command or an operation a plugin offers (see search_tools). It runs and is recorded as that command's " - "own call, with its guards and reply budget.", + "tool_call", L("Call a tool or plugin operation"), + "Call any command by name with its arguments: a tool, or one the tool list does not show, a menu row that takes no " + "arguments, a Design tab command or an operation a plugin offers (see tool_search). It runs and is recorded as " + "that command's own call, with its guards and reply budget.", object_schema({{"tool", prop("string", "The command to call.")}, {"args", {{"type", "object"}, {"description", "Its arguments."}}}}, {"tool"}), - [](const json&, ToolContext&) -> ToolResult { throw ToolFailure("call_tool is dispatched to its tool before it runs"); }); - // It calls any tool, run_script included, and plugin code. + [](const json&, ToolContext&) -> ToolResult { throw ToolFailure("tool_call is dispatched to its tool before it runs"); }); + // It calls any tool, script_run included, and plugin code. call.open_world = true; catalog.add(call); } diff --git a/src/slic3r/GUI/Mcp/McpToolsApp.cpp b/src/slic3r/GUI/Mcp/McpToolsApp.cpp index 724c60e9d6..21358028ef 100644 --- a/src/slic3r/GUI/Mcp/McpToolsApp.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsApp.cpp @@ -1,4 +1,5 @@ -// get_app_state, wait and get_log: what an agent reads before and after acting. +// app_state, app_wait and app_log: what an agent reads before and after acting; undo and redo; and the app's +// commands made from the Help menu's rows. #include "JobRegistry.hpp" #include "slic3r/GUI/I18N.hpp" @@ -13,6 +14,8 @@ #include "ScreenCapture.hpp" #include "UiInspector.hpp" #include "WindowControl.hpp" +#include "slic3r/GUI/ActionRegistry.hpp" +#include "slic3r/GUI/CommandCatalog.hpp" #include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/GCodeViewer.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" @@ -21,20 +24,25 @@ #include "slic3r/GUI/Gizmos/GLGizmosManager.hpp" #include "slic3r/GUI/Jobs/Worker.hpp" #include "slic3r/GUI/MainFrame.hpp" +#include "slic3r/GUI/NativeCommandRows.hpp" +#include "slic3r/GUI/NativeCommands.hpp" #include "slic3r/GUI/Notebook.hpp" #include "slic3r/GUI/NotificationManager.hpp" #include "slic3r/GUI/PartPlate.hpp" #include "slic3r/GUI/Plater.hpp" #include "slic3r/GUI/PrintHostDialogs.hpp" +#include "slic3r/Utils/CloudProvider.hpp" +#include "slic3r/Utils/NetworkAgent.hpp" +#include "slic3r/Utils/bambu_networking.hpp" #include "slic3r/plugin/PythonInterpreter.hpp" #ifdef SLIC3R_CAD #include "McpToolsCad.hpp" -#include "slic3r/GUI/NativeCommands.hpp" #endif #if defined(__WXGTK__) #include "slic3r/GUI/LinuxDisplayBackend.hpp" #endif +#include "libslic3r/AppConfig.hpp" #include "libslic3r/Model.hpp" #include "libslic3r/PresetBundle.hpp" #include "libslic3r/Utils.hpp" @@ -53,6 +61,7 @@ #include #include #include +#include #include #include #include @@ -123,7 +132,7 @@ json app_state(AutomationRuntime& runtime) {"jobs", runtime.jobs().list()}}; if (json recording = runtime.recorder().state(); !recording.is_null()) state["recording"] = std::move(recording); - // Each display's work area, where set_window can place a window. + // Each display's work area, where window_set can place a window. json displays = json::array(); for (unsigned i = 0; i < wxDisplay::GetCount(); ++i) { const wxDisplay display(i); @@ -133,12 +142,24 @@ json app_state(AutomationRuntime& runtime) displays.push_back(std::move(area)); } state["displays"] = std::move(displays); + // Whether a person is signed in to the Orca cloud and to Bambu Lab's, and the Bambu network plug-in as the app found + // it: installed (the setting that has the app load it), loaded, its version and why it did not load. + GUI_App& app = wxGetApp(); + state["account"] = {{"signed_in", app.is_user_login(ORCA_CLOUD_PROVIDER)}, {"bambu_signed_in", app.is_user_login(BBL_CLOUD_PROVIDER)}}; + const bool loaded = NetworkAgent::is_network_module_loaded(); + const NetworkLibraryLoadError load_error = NetworkAgent::get_load_error(); + state["network_plugin"] = {{"installed", app.app_config->get_bool("installed_networking")}, + {"loaded", loaded}, + {"version", loaded ? NetworkAgent::get_version() : std::string()}, + {"error", load_error.has_error ? load_error.message : std::string()}}; + // The folder Help > Show Configuration Folder opens: the presets, the app configuration and the logs. + state["config_folder"] = data_dir(); MainFrame* frame = wxGetApp().mainframe; Plater* plater = wxGetApp().plater(); if (frame == nullptr || plater == nullptr) return state; - // The size and state list_windows reports, and the place where the platform knows it. + // The size and state window_list reports, and the place where the platform knows it. const wxSize size = window_size(*frame); const std::string frame_state = window_state(*frame); state["window"] = {{"title", into_u8(frame->GetTitle())}, @@ -188,6 +209,7 @@ json app_state(AutomationRuntime& runtime) // plater's while it is shown. if (GLCanvas3D* canvas = shown_canvas(); canvas != nullptr && canvas->get_wxglcanvas()->IsShownOnScreen()) state["camera"] = camera_state(plater->get_camera(), canvas->get_scale()); + state["view"] = view_state(*plater); // The open gizmo, on the canvas shown first. state["gizmo"] = nullptr; std::vector canvases = live_canvases(); @@ -199,7 +221,7 @@ json app_state(AutomationRuntime& runtime) } state["objects"] = plater->model().objects.size(); state["slicing"] = plater->is_slicing_any(); - // The selection select_objects acts on: the assemble view's while it is shown, else Prepare's. + // The selection object_select acts on: the assemble view's while it is shown, else Prepare's. GLCanvas3D* assemble = plater->get_assmeble_canvas3D(); GLCanvas3D* scene = assemble != nullptr && plater->get_current_canvas3D() == assemble ? assemble : plater->get_view3D_canvas3D(); state["selection"] = scene != nullptr ? selection_state(*scene) : json(); @@ -248,30 +270,79 @@ bool condition_holds(AutomationRuntime& runtime, const std::string& condition, c } // namespace -void register_app_tools(CommandCatalog& catalog) +std::vector log_tail(std::istream& in, const std::string& min_level, std::size_t lines) +{ + // The log file sink starts an entry with its level, "[error]\t" (set_log_path_and_level(), utils.cpp); a line + // without one continues the message of the entry above it. + static const std::vector levels{"trace", "debug", "info", "warning", "error", "fatal"}; + const auto level_of = [](const std::string& line) { + for (std::size_t i = 0; i < levels.size(); ++i) + if (const std::string field = "[" + levels[i] + "]\t"; line.compare(0, field.size(), field) == 0) + return int(i); + return -1; + }; + const int min = int(std::find(levels.begin(), levels.end(), min_level) - levels.begin()); + // The newest entries kept, each its first line and those that continue it, as many as fit in `lines`. + std::deque> entries; + std::size_t held = 0; + // Lines before the file's first entry, which continue an entry of an earlier file, have no level to filter by. + bool keeping = min == 0; + std::string line; + while (std::getline(in, line)) { + if (const int level = level_of(line); level >= 0) { + keeping = level >= min; + if (keeping) + entries.emplace_back(); + } else if (keeping && entries.empty()) { + entries.emplace_back(); + } + if (!keeping) + continue; + entries.back().push_back(std::move(line)); + ++held; + while (held > lines && entries.size() > 1) { + held -= entries.front().size(); + entries.pop_front(); + } + } + // An entry longer than `lines` gives its first lines. + std::vector out; + for (std::vector& entry : entries) + for (std::string& kept : entry) + if (out.size() < lines) + out.push_back(std::move(kept)); + return out; +} + +void register_app_tools(CommandCatalog& catalog, [[maybe_unused]] bool cad) { catalog.add(inspect_tool( - "core", "get_app_state", L("Get app state"), + "app_state", L("Get app state"), "Snapshot of OrcaSlicer. Call it first and whenever you are unsure what the app is doing. The app: version, platform " "and display backend, whether it is ready, the main window, the displays (each one's work area x, y, width and " - "height, as set_window takes positions, its scale and whether it is primary), the MCP endpoint (mcp), python " + "height, as window_set takes positions, its scale and whether it is primary), the MCP endpoint (mcp), python " "(available: Python runs " "in this build; scripts_unrestricted: a script's own file, network, process and thread access is not held to " "OrcaSlicer's folders, which only a person turns on, in Preferences > AI features > Python scripts or for one run " "with --unrestricted-scripts), design_tab " - "(the Design tab is on, and call_tool runs its commands, search_tools' group Design) and, when they do not run, " - "cad_note, how a person turns the CAD feature on. The project: current tab and mode, printer technology, name, path and unsaved changes, " + "(the Design tab is on, and tool_call runs its commands, tool_search's group Design) and, when they do not run, " + "cad_note, how a person turns the CAD feature on; account (signed_in to the Orca cloud, bambu_signed_in to Bambu " + "Lab's), network_plugin (installed, loaded, version, error: the Bambu network plug-in as the app found it) and " + "config_folder (presets, app configuration and logs). The view outside the Design tab (view: sidebar_collapsed, " + "sidebar_width, legend_collapsed, gcode_window, projection, section and the display switches labels, overhangs, " + "outline, wireframe, gridlines, axes and navigator, under the names view_set takes them). " + "The project: current tab and mode, printer technology, name, path and unsaved changes, " "selected printer/process/filament presets, plates (count, current), object count, the selection (objects, the " "instances [[object, instance]] they are selected in and, when parts rather than whole instances are selected, " - "parts [[object, part]], in the indices select_objects takes; wipe_tower when a prime tower is selected; canvas is the 3D " + "parts [[object, part]], in the indices object_select takes; wipe_tower when a prime tower is selected; canvas is the 3D " "view it belongs to), slicing state, " "the Preview's view type, time mode and layer range (1-based, with their Z), and the camera of the 3D view shown " - "(camera: type, look_at, position, zoom, click_px_per_mm, elevation and azimuth, as set_view replies with it). What " + "(camera: type, look_at, position, zoom, click_px_per_mm, elevation and azimuth, as view_set replies with it). What " "is going on: open modal " "dialogs, each with its title, buttons (enabled: false when disabled) and a message that reads it as shown: its " "text and its controls row by row, fields [value], choices [value ▾], checkboxes [x] / [ ] / [-], radio and " "selector options (*) / ( ), list rows \"- row | cells\", secrets [******], \" (disabled)\" after a disabled " - "control; menus closed unseen (a menu a call opened that no reply listed), auto_answer_dialogs rules in force, " + "control; menus closed unseen (a menu a call opened that no reply listed), dialog_auto_answer rules in force, " "notifications, print host uploads (state, progress, error), the open gizmo, running jobs and a running " "recording.", object_schema({}), [](const json&, ToolContext& ctx) { @@ -280,9 +351,9 @@ void register_app_tools(CommandCatalog& catalog) })); NativeCommand wait = inspect_tool( - "core", "wait", L("Wait for a condition"), + "app_wait", L("Wait for a condition"), "Block until a condition holds or timeout_s passes (max 50). for: \"ready\" (startup finished), \"idle\" (no dialog, " - "no running job, nothing slicing or arranging, no gizmo working in the background; a run_script run counts only " + "no running job, nothing slicing or arranging, no gizmo working in the background; a script_run run counts only " "through the calls it makes), \"dialog\" / \"no_dialog\", or \"job\" with a job id an earlier call returned, whose " "result is then the reply. On timeout the reply is {satisfied: false}, or for a job {status: \"running\", job, " "note}: call it again.", @@ -319,34 +390,124 @@ void register_app_tools(CommandCatalog& catalog) catalog.add(wait); catalog.add(inspect_tool( - "core", "get_log", L("Read the log"), - "The last lines of OrcaSlicer's current log file, optionally only those at or above a level.", - object_schema({{"lines", {{"type", "integer"}, {"minimum", 1}, {"maximum", 2000}, {"description", "Default 200."}}}, + "app_log", L("Read the log"), + "The last lines of OrcaSlicer's current log file, optionally only those at or above a level. An entry's level is " + "the one its first line starts with ([error]); the lines of its message after the first come with it, and the " + "reply holds whole entries.", + object_schema({{"lines", {{"type", "integer"}, {"minimum", 1}, {"maximum", 2000}, + {"description", "The most lines, of the newest whole entries; an entry longer than that gives its " + "first lines. Default 200."}}}, {"level", enum_prop({"trace", "debug", "info", "warning", "error", "fatal"}, "Minimum level.")}}), [](const json& args, ToolContext&) { const boost::filesystem::path file = get_log_file_name(); if (file.empty()) throw ToolFailure("No log file is open"); - static const std::vector levels{"trace", "debug", "info", "warning", "error", "fatal"}; - const std::string min_level = arg_string(args, "level", "trace"); - const auto min_it = std::find(levels.begin(), levels.end(), min_level); - const std::size_t lines = std::size_t(arg_int(args, "lines", 200)); flush_logs(); boost::nowide::ifstream in(path_to_utf8(file).c_str()); - std::deque tail; - std::string line; - while (std::getline(in, line)) { - bool keep = min_it == levels.begin(); - for (auto it = min_it; !keep && it != levels.end(); ++it) - keep = line.find("[" + *it + "]") != std::string::npos; - if (!keep) - continue; - tail.push_back(line); - if (tail.size() > lines) - tail.pop_front(); - } - return ToolResult::ok({{"file", path_to_utf8(file)}, {"lines", json(std::vector(tail.begin(), tail.end()))}}); + const std::vector tail = log_tail(in, arg_string(args, "level", "trace"), + std::size_t(arg_int(args, "lines", 200))); + return ToolResult::ok({{"file", path_to_utf8(file)}, {"lines", json(tail)}}); })); + + // Undo and Redo act on the shown tab's history, as the Edit menu's do; history names one for automation, which acts + // whatever tab is shown. Each has a tile of its own, in the Speed Dial's section Commands. + const json history = object_schema( + {{"history", enum_prop({"design", "project"}, "The history: design, the Design tab's (with the CAD feature on), or project. " + "Default: the Design tab's while it is shown, else the project's.")}}); + // A person's pick does what the Edit menu's item does, and shows nothing where it would be greyed. An automated + // call, action_run of the tile included, acts on the history Rows::undo_redo() picks: the Design tab's through its + // gate, whose refusals say why, and the project's as the Edit menu's item does. + const auto history_command = [&history](std::string key, std::string title, std::string icon, std::string description, bool redo) { + NativeCommand command = row_command(std::move(key), std::move(title), std::move(description), history, json(), + [redo](const json& args) { return Rows::undo_redo(args, redo); }); + const CommandFn picked = NativeCommands::ui_command(command.key, command.title, command.group, history, + [redo](const json& args) { return Rows::picked_undo_redo(args, redo); }) + .run; + command.run = [picked, automated = std::move(command.run)](const json& args, ToolContext& ctx) { + return ctx.person() ? picked(args, ctx) : automated(args, ctx); + }; + command.in_palette = true; + command.tile_group = L("Commands"); + command.icon = std::move(icon); + return command; + }; + NativeCommand undo = history_command( + "undo", L("Undo"), "menu_undo", + "Take back the last change of a history, as Edit > Undo does. history design is the Design tab's: the last feature " + "added, edited, deleted, moved, shown or hidden, or renamed, or variable changed, or in a sketch session the last " + "drawn shape; project is the project's. Without history, the Design tab's while it is shown, else the project's. " + "Reply: history and, for the Design tab's, result: scope (design or sketch), undo_depth, redo_depth, features, " + "bodies and generation; entities in a sketch.", + false); + NativeCommand redo = history_command("redo", L("Redo"), "menu_redo", + "Put back what undo took back, until the next change, as Edit > Redo does, in the history " + "undo takes. Reply as undo's.", + true); +#ifdef SLIC3R_CAD + // An example calls Design commands, so only a catalog that holds them documents the Design history. + if (cad) { + undo.examples = json::parse(R"json([ + {"title": "Take back an extrude, its sketch with it", "calls": [ + {"tool": "extrude", "args": {"width": 20, "height": 20, "distance": 5}}, + {"tool": "undo", "args": {"history": "design"}}]}, + {"title": "Take back the last shape drawn in a sketch", "calls": [ + {"tool": "sketch_create", "args": {"plane": "XY"}}, + {"tool": "sketch_draw", "args": {"type": "rectangle_2_point", "p0": [-15, -10], "p1": [15, 10]}}, + {"tool": "sketch_draw", "args": {"entities": [{"type": "circle_center", "center": [0, 0], "radius": 4}]}}, + {"tool": "undo", "args": {"history": "design"}}]}])json"); + redo.examples = json::parse(R"json([ + {"title": "Put back an extrude undo took back", "calls": [ + {"tool": "extrude", "args": {"width": 20, "height": 20, "distance": 5}}, + {"tool": "undo", "args": {"history": "design"}}, + {"tool": "redo", "args": {"history": "design"}}]}, + {"title": "Put back the shape undo took off a sketch", "calls": [ + {"tool": "sketch_create", "args": {"plane": "XY"}}, + {"tool": "sketch_draw", "args": {"type": "rectangle_2_point", "p0": [-15, -10], "p1": [15, 10]}}, + {"tool": "sketch_draw", "args": {"entities": [{"type": "circle_center", "center": [0, 0], "radius": 4}]}}, + {"tool": "undo", "args": {"history": "design"}}, + {"tool": "redo", "args": {"history": "design"}}]}])json"); + } +#endif + catalog.add(std::move(undo)); + catalog.add(std::move(redo)); + + // ---- The app's commands made from the Help and Plugins menus' rows ---- + using NativeCommands::tile; + NativeCommand web_page = row_command( + "app_open_web_page", L("Open a web page"), + "Open one of OrcaSlicer's web pages in the default web browser, as its menu row does: wiki, the OrcaSlicer wiki; " + "youtube, the OrcaSlicer YouTube channel; plugin_hub, the plugin hub's page, where a person picks a plugin to install. " + "Nothing opens in OrcaSlicer.", + object_schema({{"page", enum_prop({"wiki", "youtube", "plugin_hub"}, "The page.")}}, {"page"}), + json::array({tile("open_wiki", L("Open Wiki"), L("Help"), "link_wiki_img", {{"page", "wiki"}}, "Open the OrcaSlicer wiki in the browser."), + tile("open_youtube", L("Open YouTube Channel"), L("Help"), "", {{"page", "youtube"}}, + "Open the OrcaSlicer YouTube channel in the browser."), + tile("install_plugin", L("Install Plugin"), L("Plugins"), "", {{"page", "plugin_hub"}}, + "Open the plugin hub's page in the default web browser, where a person picks a plugin to install; " + "nothing opens in OrcaSlicer.")}), + [](const json& args) { return Rows::open_web_page(arg_string(args, "page")); }); + // The browser it opens reaches the network. + web_page.open_world = true; + catalog.add(std::move(web_page)); + const std::string updates = "Check for a newer OrcaSlicer."; + NativeCommand check_updates = row_command("app_check_for_updates", L("Check for Updates"), updates, object_schema({}), + json::array({tile("help_check_updates", L("Check for Updates"), L("Help"), "refresh", + json::object(), updates)}), + [](const json&) { return Rows::check_for_updates(); }); + // It asks the update server. + check_updates.open_world = true; + catalog.add(std::move(check_updates)); + const std::string folder = "Open the configuration folder in the file manager."; + catalog.add(row_command("app_show_config_folder", L("Show Configuration Folder"), folder, object_schema({}), + json::array({tile("help_open_config_folder", L("Show Configuration Folder"), L("Help"), "open_project", + json::object(), folder)}), + [](const json&) { return Rows::show_config_folder(); })); + const std::string benchmark = "Time the 3D views on a test model. It asks first (Start or Cancel), then replaces the project with " + "the OrcaSliced Combo as New Project does, which may ask about unsaved changes, slices it and shows " + "the results."; + catalog.add(row_command("app_benchmark_3d_scene", L("Benchmark 3D Scene"), benchmark, object_schema({}), + json::array({tile("help_benchmark_3d_scene", L("Benchmark 3D Scene"), L("Help"), "", json::object(), benchmark)}), + [](const json&) { return Rows::benchmark_3d_scene(); })); } }}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpToolsCad.cpp b/src/slic3r/GUI/Mcp/McpToolsCad.cpp index 894288e62f..5942b8a77f 100644 --- a/src/slic3r/GUI/Mcp/McpToolsCad.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsCad.cpp @@ -51,7 +51,7 @@ #include "McpArguments.hpp" #include "McpTools.hpp" #include "McpPaths.hpp" -#include "UiInspector.hpp" // gizmo_name: the name get_app_state reports +#include "UiInspector.hpp" // gizmo_name: the name app_state reports #include "slic3r/GUI/CAD/DesignPanel.hpp" #include "slic3r/GUI/CAD/DesignCanvas.hpp" #include "slic3r/GUI/CAD/DesignSketchTool.hpp" @@ -193,7 +193,7 @@ std::string mode_note(const DesignTool& t, bool no_arguments = false) // catalog holds the Design commands only when the feature was on at startup (the preference, or the command // line's --cad), and the main window creates the Design page only then too (its panel is built on first use), // so turning the feature on takes a restart. -const char* const kCadOffNote = "call_tool runs no Design command now: they need the CAD feature on when OrcaSlicer " +const char* const kCadOffNote = "tool_call runs no Design command now: they need the CAD feature on when OrcaSlicer " "started, in Preferences > Features or with --cad. A person turns it on there if it is " "off and restarts OrcaSlicer, or starts it with --cad."; @@ -2827,7 +2827,7 @@ json action_commit_to_plate(DesignPanel* panel, const json& params) {"tab", "prepare"}}; } -// New Design without its confirmation dialog: discard_changes confirms, as new_project's does. +// New Design without its confirmation dialog: discard_changes confirms, as project_new's does. json action_new_design(DesignPanel* panel, const json& params) { const CadDocument& doc = panel->mcp_doc(); @@ -3469,7 +3469,7 @@ json sketch_transform(DesignSketchTool& t, const json& params, bool pattern) SketchConstraintType constraint_type_arg(const json& v) { if (!v.is_string()) - throw std::runtime_error("type must be a constraint type, such as \"parallel\" (search_tools {tool: \"sketch_constrain\"} lists " + throw std::runtime_error("type must be a constraint type, such as \"parallel\" (tool_search {tool: \"sketch_constrain\"} lists " "them, and {tool: \"sketch_dimension\"} the dimensions)"); const std::string s = v.get(); if (s == "equal") return SketchConstraintType::EqualLength; @@ -3480,7 +3480,7 @@ SketchConstraintType constraint_type_arg(const json& v) if (edit_distance(boost::algorithm::to_lower_copy(s), n) <= 2 + s.size() / 4) close += std::string(close.empty() ? "" : ", ") + "\"" + n + "\""; throw std::runtime_error("unknown constraint type \"" + s + "\"" + (close.empty() ? "" : "; did you mean " + close) + - " (search_tools {tool: \"sketch_constrain\"} lists them, and {tool: \"sketch_dimension\"} the dimensions)"); + " (tool_search {tool: \"sketch_constrain\"} lists them, and {tool: \"sketch_dimension\"} the dimensions)"); } // Why the CONSTRAIN bar refuses a pick, in ConstraintReject order: a code an agent can test and the @@ -4980,11 +4980,11 @@ void cad_apply_feature_refs(CadFeature& f, const json& refs, const CadDocument& std::vector cad_commit_to_plate_replace(const json& replace, const Model& model) { - if (!replace.is_array()) throw std::runtime_error("replace takes a list of object indices (list_objects)"); + if (!replace.is_array()) throw std::runtime_error("replace takes a list of object indices (object_list)"); const int count = int(model.objects.size()); std::vector out; for (const json& v : replace) { - if (!v.is_number_integer()) throw std::runtime_error("replace takes object indices (list_objects), not " + v.dump()); + if (!v.is_number_integer()) throw std::runtime_error("replace takes object indices (object_list), not " + v.dump()); const auto i = v.get(); if (i < 0 || i >= count) throw std::runtime_error("object " + std::to_string(i) + " is out of range; the project has " + std::to_string(count) + @@ -4994,7 +4994,7 @@ std::vector cad_commit_to_plate_replace(const json& replace, const Model& m // Deleting one opens the "part of a cut object" warning, which the person answers. if (model.objects[size_t(i)]->is_cut()) throw std::runtime_error("object " + std::to_string(i) + - " is part of a cut object; delete it with select_objects + run_action obj_delete, which asks first"); + " is part of a cut object; delete it with object_select, then object_delete, which asks first"); out.push_back(int(i)); } std::sort(out.begin(), out.end()); diff --git a/src/slic3r/GUI/Mcp/McpToolsCad.hpp b/src/slic3r/GUI/Mcp/McpToolsCad.hpp index 03ea2d12b3..1350a0bcf9 100644 --- a/src/slic3r/GUI/Mcp/McpToolsCad.hpp +++ b/src/slic3r/GUI/Mcp/McpToolsCad.hpp @@ -2,8 +2,8 @@ // The Design tab's commands, one per entry of its table (kDesignTools, DesignOffer.hpp, generated from // scripts/CAD/tool_atlas.json) that has an action or a tool block and is no folded row (is_design_command()): its -// tools, sketches, features, measurements and edits, which an agent finds with search_tools (group Design) and -// runs with call_tool, and a person picks as Speed Dial tiles while the Design tab is shown, those of the mode it +// tools, sketches, features, measurements and edits, which an agent finds with tool_search (group Design) and +// runs with tool_call, and a person picks as Speed Dial tiles while the Design tab is shown, those of the mode it // is in. A call with exactly the arguments that choose one of the command's rows (opened_row()) does what that // right-click menu row does, in the mode the row belongs to (open_refusal()); any other call, or one with // silent: true, runs the entry's tool block's silent form. They run on the UI thread through the GUI's own @@ -80,7 +80,7 @@ void register_cad_commands(CommandCatalog& catalog); // started and how a person turns it on (CommandCatalog::leave_out()). void leave_out_cad_commands(CommandCatalog& catalog); -// What search_tools' description says of the Design commands, which tools/list does not show, so that an agent +// What tool_search's description says of the Design commands, which tools/list does not show, so that an agent // learns without a search that they exist and are CAD: a lead saying what they cover, that one is looked up with // tool before it is called, and that a command whose schema has silent does what its menu row does when called // with no arguments unless silent is true; then each heading of kDesignSections with the keys of its commands @@ -169,7 +169,7 @@ nlohmann::json run_cad_tool(const std::string& id, const nlohmann::json& args); // generation. Fails (-32000) when there is nothing to take back or put back. UI thread only. nlohmann::json cad_undo_redo(bool redo); -// get_app_state's cad_note: how a person turns the CAD feature on, in the editor while the Design commands +// app_state's cad_note: how a person turns the CAD feature on, in the editor while the Design commands // cannot run, because `catalog` holds none of them (the feature was off at startup) or the feature is off // now; null otherwise. UI thread. nlohmann::json cad_note(const CommandCatalog& catalog); diff --git a/src/slic3r/GUI/Mcp/McpToolsCommon.cpp b/src/slic3r/GUI/Mcp/McpToolsCommon.cpp index b4034869fe..29e6f8ca2d 100644 --- a/src/slic3r/GUI/Mcp/McpToolsCommon.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsCommon.cpp @@ -3,6 +3,7 @@ #include "libslic3r/Model.hpp" #include "UiInspector.hpp" +#include "slic3r/GUI/ActionRegistry.hpp" #include "slic3r/GUI/CommandCatalog.hpp" #include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/NativeCommands.hpp" @@ -24,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -57,10 +59,10 @@ json enum_prop(std::vector values, const std::string& description) json array_prop(json items, const std::string& description) { return {{"type", "array"}, {"items", std::move(items)}, {"description", description}}; } -NativeCommand inspect_tool(std::string group, std::string name, std::string title, std::string description, json schema, CommandFn handler) +NativeCommand inspect_tool(std::string name, std::string title, std::string description, json schema, CommandFn handler) { - NativeCommand d = NativeCommands::long_command(std::move(name), std::move(title), std::move(group), std::move(schema), - std::move(handler), /*inline_call=*/true); + NativeCommand d = NativeCommands::long_command(std::move(name), std::move(title), {}, std::move(schema), std::move(handler), + /*inline_call=*/true); d.description = std::move(description); d.listed = true; d.read_only = true; @@ -76,11 +78,9 @@ NativeCommand reaching(std::vector operations, NativeCommand comman return command; } -NativeCommand mutate_tool(std::string group, std::string name, std::string title, std::string description, json schema, CommandFn handler, - bool destructive) +NativeCommand mutate_tool(std::string name, std::string title, std::string description, json schema, CommandFn handler, bool destructive) { - NativeCommand d = NativeCommands::long_command(std::move(name), std::move(title), std::move(group), std::move(schema), - std::move(handler)); + NativeCommand d = NativeCommands::long_command(std::move(name), std::move(title), {}, std::move(schema), std::move(handler)); d.description = std::move(description); d.listed = true; d.destructive = destructive; @@ -88,6 +88,30 @@ NativeCommand mutate_tool(std::string group, std::string name, std::string title return d; } +NativeCommand row_command(std::string name, std::string title, std::string description, json schema, json tiles, + std::function fn) +{ + NativeCommand d = NativeCommands::ui_command(std::move(name), std::move(title), {}, std::move(schema), std::move(fn)); + d.description = std::move(description); + d.tiles = std::move(tiles); + d.listed = true; + return d; +} + +AppActionRunResult row_reply(const json& reply) +{ + AppActionRunResult result{AppActionRunResult::Level::Succeeded}; + result.reply = reply.dump(); + return result; +} + +AppActionRunResult quiet_refusal(const Ops::Refusal& refusal) +{ + AppActionRunResult kept{AppActionRunResult::Level::Info, {}, false}; + kept.refusal = std::make_shared(refusal); + return kept; +} + namespace { // Whether a 3D view is shown but can't draw yet. On Wayland a canvas gets its GL surface from the @@ -179,7 +203,7 @@ Plater& ui_plater() throw ToolFailure("OrcaSlicer is shutting down"); Plater* plater = wxGetApp().plater(); if (plater == nullptr || wxGetApp().mainframe == nullptr) - throw ToolFailure("OrcaSlicer is still starting; wait {for:\"ready\"} first"); + throw ToolFailure("OrcaSlicer is still starting; app_wait {for:\"ready\"} first"); return *plater; } @@ -246,7 +270,7 @@ json expected_id_prop(const char* of) { return {{"type", "integer"}, {"minimum", 0}, - {"description", std::string("The id list_objects reports for this ") + of + + {"description", std::string("The id object_list reports for this ") + of + ": the call is refused when the index names another one now."}}; } @@ -264,12 +288,12 @@ void check_expected_ids(const ModelObject& object, const ModelVolume* volume, co if (args.contains("object_id") && args["object_id"].get() != object.id().id) throw ToolFailure("The object at this index is now \"" + object.name + "\" (id " + std::to_string(object.id().id) + "), not the expected id " + std::to_string(args["object_id"].get()) + - ": list_objects again", + ": object_list again", {{"id", object.id().id}}); if (volume != nullptr && args.contains("part_id") && args["part_id"].get() != volume->id().id) throw ToolFailure("The part at this index is now \"" + volume->name + "\" (id " + std::to_string(volume->id().id) + "), not the expected id " + std::to_string(args["part_id"].get()) + - ": list_objects again", + ": object_list again", {{"id", volume->id().id}}); } diff --git a/src/slic3r/GUI/Mcp/McpToolsConfig.cpp b/src/slic3r/GUI/Mcp/McpToolsConfig.cpp index aaa1363479..6a2afe9f7e 100644 --- a/src/slic3r/GUI/Mcp/McpToolsConfig.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsConfig.cpp @@ -1,15 +1,22 @@ -// list_presets, select_preset, save_preset, delete_preset, get_settings, set_settings and list_plates: presets -// are selected through the same selectors a person uses, saved and deleted through the tab, and settings change -// through the Tab's own transaction (strict parsing, on_change callbacks, rollback on failure), or for the -// project's and the plates' own settings through the code of their sidebar controls, dialogs and plate icons, -// so the UI and the project stay consistent. Preferences are only read here; they change in the Preferences -// dialog, whose handlers carry their effects. +// preset_list, preset_select, preset_save, preset_delete, settings_list, settings_get, settings_set, +// plate_get_settings, plate_set_settings, project_get_settings, project_set_settings and +// plate_list: presets are selected through the same selectors a person uses, saved and deleted through the tab, and +// settings change through the Tab's own transaction (strict parsing, on_change callbacks, rollback on failure), or +// for the project's and the plates' own settings through the code of their sidebar controls and dialogs, so the UI +// and the project stay consistent. The preferences have commands of their own (McpToolsPreferences.cpp). The plate +// commands made from menu rows act on the plate a call names, else on the +// current plate, through the plate operations (Operations/PlateOps.hpp); plate_add runs its row's function +// (NativeCommandRows.hpp). #include "slic3r/GUI/I18N.hpp" #include "McpArguments.hpp" +#include "McpTargets.hpp" #include "McpTools.hpp" +#include "slic3r/GUI/ActionRegistry.hpp" +#include "slic3r/GUI/CommandCatalog.hpp" #include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/CreatePresetsDialog.hpp" +#include "slic3r/GUI/FilamentMapPanel.hpp" #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/GUI_Factories.hpp" @@ -17,24 +24,30 @@ #include "slic3r/GUI/GUI_ObjectList.hpp" #include "slic3r/GUI/IMSlider.hpp" #include "slic3r/GUI/MainFrame.hpp" +#include "slic3r/GUI/NativeCommandRows.hpp" +#include "slic3r/GUI/NativeCommands.hpp" #include "slic3r/GUI/ObjectDataViewModel.hpp" #include "slic3r/GUI/Operations/Outcome.hpp" #include "slic3r/GUI/Operations/PlateOps.hpp" #include "slic3r/GUI/Operations/PresetOps.hpp" #include "slic3r/GUI/PartPlate.hpp" +#include "slic3r/GUI/PlateSettingsDialog.hpp" #include "slic3r/GUI/Plater.hpp" #include "slic3r/GUI/PresetComboBoxes.hpp" #include "slic3r/GUI/SavePresetDialog.hpp" #include "slic3r/GUI/SettingsIndex.hpp" #include "slic3r/GUI/Tab.hpp" #include "slic3r/GUI/WipeTowerDialog.hpp" +#include "slic3r/GUI/format.hpp" #include "libslic3r/AppConfig.hpp" +#include "libslic3r/BoundingBox.hpp" #include "libslic3r/Config.hpp" #include "libslic3r/CustomGCode.hpp" #include "libslic3r/ExtrusionEntity.hpp" #include "libslic3r/FlushVolCalc.hpp" #include "libslic3r/GCode/GCodeProcessor.hpp" +#include "libslic3r/LocalesUtils.hpp" #include "libslic3r/Model.hpp" #include "libslic3r/ParameterUtils.hpp" #include "libslic3r/Point.hpp" @@ -42,8 +55,10 @@ #include "libslic3r/PresetBundle.hpp" #include "libslic3r/PrintConfig.hpp" #include "libslic3r/Utils.hpp" +#include "libslic3r/libslic3r.h" #include +#include #include #include @@ -55,6 +70,7 @@ #include #include #include +#include #include #include #include @@ -95,7 +111,7 @@ PresetCollection& collection(Preset::Type type) } } -// The settings of a preset type, as its tab and set_settings take them. +// The settings of a preset type, as its tab and settings_set take them. const std::vector& preset_options(Preset::Type type) { return type == Preset::TYPE_PRINT ? Preset::print_options() : type == Preset::TYPE_FILAMENT ? Preset::filament_options() : Preset::printer_options(); @@ -141,7 +157,7 @@ const char* type_name(ConfigOptionType type) } } -// Option keys whose key or label contains `query`, for "did you mean" and for get_settings' query. +// Option keys whose key or label contains `query`, for "did you mean". std::vector search_keys(const std::string& query, const std::vector& within, std::size_t limit) { const std::string q = lower(query); @@ -175,37 +191,26 @@ std::map setting_places(Preset::Type type) // name no preset has. json similar_presets(const PresetCollection& presets, const std::string& name) { return Ops::similar_preset_names(presets, name); } -// What select_preset replies when a preset operation refuses: the hint an agent can act on, and the names -// under the key each refusal has had here. -ToolFailure preset_refused(const Ops::Refusal& refusal) -{ - const std::string code = refusal.code; - if (code == "preset_not_offered") - return refused(refusal, "See list_presets.", "similar"); - if (code == "ambiguous_hidden_preset") - return refused(refusal, "", "presets"); - if (code == "preset_incompatible") - return refused(refusal, "list_presets include_incompatible lists such presets."); - if (code == "transfer_not_offered") - return refused(refusal, "Pass preset_changes: \"discard\", or save_preset first."); - return refused(refusal); -} - +// The settings a call reads or writes: a type's preset (target global), an object's, a part's or a height range's +// overrides, or the project's own settings. struct ConfigTarget { - Preset::Type type = Preset::TYPE_INVALID; // preset scopes + Preset::Type type = Preset::TYPE_INVALID; // a type's preset const Preset* preset = nullptr; // the preset read: the one being edited, or a saved one bool edited = false; // config is the edited preset's, unsaved changes included - ModelObject* object = nullptr; // object/volume scopes + std::string target = "global"; // the targets object, part and height_range + ModelObject* object = nullptr; ModelVolume* volume = nullptr; int object_index = -1; - bool project = false; // the project scope, read from `owned` + std::optional range; // the height range's heights, a key of the object's ranges + Targets named; // what the reply names: the object, or the part + bool project = false; // the project's settings, read from `owned` std::shared_ptr owned; const DynamicPrintConfig* config = nullptr; - std::vector options; // keys valid in this scope + std::vector options; // the keys these settings have }; -// The project scope: the project's own settings (PresetBundle::project_config) that a person sets in the +// The project's settings: the project's own settings (PresetBundle::project_config) that a person sets in the // sidebar, on the canvas or in their dialogs, and the filament slot facts they depend on, which are set // elsewhere and listed for reading only. bool project_key_read_only(const std::string& key) @@ -223,47 +228,55 @@ std::vector project_options() return keys; } -// The scopes get_settings looks through when keys or a query come without one: the process, filament and printer +// The types settings_get looks through when keys or a query come without one: the process, filament and printer // settings being edited, since a question about an effect rarely knows which tab answers it. -const char* const kSearchScopes[]{"process", "filament", "printer"}; +const char* const kSearchTypes[]{"process", "filament", "printer"}; -// The scope `key` is a setting of, for a call that named it where it isn't one: the first of kSearchScopes that has -// it, else the project's; empty when none does. UI thread. -std::string scope_of_key(const std::string& key) +// Where `key` is a setting, for a call that named it where it isn't one: the first of kSearchTypes that has it, else +// "project" for the project's own settings; empty when none does. UI thread, but for a key that names no config option, +// which is no project setting either, and is answered without the app. +std::string type_of_key(const std::string& key) { - for (const char* scope : kSearchScopes) - if (const std::vector& options = preset_options(preset_type(scope)); + for (const char* type : kSearchTypes) + if (const std::vector& options = preset_options(preset_type(type)); std::find(options.begin(), options.end(), key) != options.end()) - return scope; + return type; + // The project's nozzle flow types, read and set with the printer's settings (resolve_target()). + if (key == "nozzle_volume_type") + return "printer"; + if (!print_config_def.has(key)) + return {}; const std::vector project = project_options(); return std::find(project.begin(), project.end(), key) != project.end() ? "project" : ""; } -// Sets unknown_keys to the keys a read named that its scope lacks, and scope_of to the scope that has each of those -// another scope has, so the agent can ask there. UI thread. +// Sets unknown_keys to the keys a read named that its settings lack, and type_of to where each of those is a setting +// elsewhere (type_of_key()), so the agent can ask there. UI thread. void add_unknown_keys(json& out, const json& unknown) { if (unknown.empty()) return; out["unknown_keys"] = unknown; - json scopes = json::object(); + json types = json::object(); for (const json& key : unknown) - if (std::string scope = scope_of_key(key.get()); !scope.empty()) - scopes[key.get()] = std::move(scope); - if (!scopes.empty()) - out["scope_of"] = std::move(scopes); + if (std::string type = type_of_key(key.get()); !type.empty()) + types[key.get()] = std::move(type); + if (!types.empty()) + out["type_of"] = std::move(types); } -// The refusal of a key that `scope` lacks: it names the scope that has the key when another does, since the usual -// cause is a key passed to the wrong scope or to none (the process). UI thread. -ToolFailure unknown_setting(const std::string& key, const std::string& scope, json details) +// The refusal of a key that the settings `where` names (a type, "project" or "plate") lack: it says where the key is a +// setting when it is one elsewhere, since the usual cause is a key passed with the wrong type or to none (the +// process). UI thread. +ToolFailure unknown_setting(const std::string& key, const std::string& where, json details) { - if (const std::string other = scope_of_key(key); !other.empty() && other != scope) - return ToolFailure("\"" + key + "\" is a " + other + " setting: pass scope \"" + other + "\""); - return ToolFailure("Unknown setting \"" + key + "\" for the " + scope + " scope", std::move(details)); + if (const std::string other = type_of_key(key); !other.empty() && other != where) + return ToolFailure(other == "project" ? "\"" + key + "\" is one of the project's own settings: project_set_settings changes it" : + "\"" + key + "\" is a " + other + " setting: settings_set takes it with type \"" + other + "\""); + return ToolFailure("Unknown setting \"" + key + "\" for the " + where + " settings", std::move(details)); } -// The project scope's values: project_config's, with the wipe tower position one entry per plate and a +// The project's settings: project_config's, with the wipe tower position one entry per plate and a // mixed flag per slot, since a project can store fewer of either. UI thread. DynamicPrintConfig project_settings() { @@ -314,20 +327,17 @@ std::vector project_offered(const std::string& key) return out; } -// set_settings on the project scope. Every key is written by the code its control runs: the plate type -// selector, a colour button's picker, the Flushing volumes and Purge mode dialogs' OK, a wipe tower drag. -// Everything is checked before anything changes. Colours go first, in a closure of their own, so the -// flushing volumes their change recalculates ("Auto flush after changing") are in place before a matrix -// given in the same call replaces them. +// project_set_settings. Every key is written by the code its control runs: the plate type selector, a colour +// button's picker, the Flushing volumes and Purge mode dialogs' OK, a wipe tower drag. Everything is checked before +// anything changes. Colours go first, in a closure of their own, so the flushing volumes their change recalculates +// ("Auto flush after changing") are in place before a matrix given in the same call replaces them. ToolResult set_project_settings(const json& args, ToolContext& ctx) { const json values_in = args.value("values", json::object()); if (values_in.empty()) throw ToolFailure("values must be a non-empty object {key: value}"); - if (args.contains("reset_all") || args.contains("reset_to")) - throw ToolFailure("reset_all and reset_to are for preset scopes; project settings always have a value"); DynamicPrintConfig before; - DynamicPrintConfig values; // checked, in the form the scope reads them + DynamicPrintConfig values; // checked, in the form project_get_settings reads them // The matrix to write, given whole or as one entry of `basis`'s matrix. const auto checked_matrix = [&](const DynamicPrintConfig& basis) { const char* const key = "flush_volumes_matrix"; @@ -481,14 +491,25 @@ ToolResult set_project_settings(const json& args, ToolContext& ctx) return ToolResult::ok(reply); } -// The plate scope: what the Plate Settings dialog sets on one plate, and the plate's name and lock, which -// its icons set. -const char* const plate_scope_keys[] = {"curr_bed_type", "print_sequence", "spiral_mode", "first_layer_print_sequence", - "other_layers_print_sequence", "name", "locked"}; +bool is_plate_setting(const std::string& key) +{ + const std::vector& keys = plate_setting_keys(); + return std::find(keys.begin(), keys.end(), key) != keys.end(); +} -bool is_plate_setting(const std::string& key) { return key != "name" && key != "locked"; } +// The plate settings plate_list and an unnamed plate_get_settings show: the filament grouping only on a printer with +// several extruders, whose plates show the filament map icon (a plate keeps a mode of its own on any printer). UI thread. +std::vector listed_plate_keys() +{ + std::vector keys = plate_setting_keys(); + if (wxGetApp().preset_bundle->get_printer_extruder_count() < 2) + keys.erase(std::remove_if(keys.begin(), keys.end(), + [](const std::string& key) { return key == "filament_map_mode" || key == "filament_map"; }), + keys.end()); + return keys; +} -// The plate the scope's `plate` argument names, the current one without it. UI thread. +// The plate the call's `plate` argument names, the current one without it. UI thread. int scope_plate(const json& args) { PartPlateList& plates = ui_plater().get_partplate_list(); @@ -498,14 +519,71 @@ int scope_plate(const json& args) return index; } -// A plate setting in the form set_settings takes: the plate's own value, null where it follows the -// project's plate type, the process or Auto; or with `effective` what the plate prints with. +// How many filaments the filament grouping dialog groups: one per slot of the project. +int grouped_filaments() +{ + const auto* colours = ui_plater().config()->option("filament_colour"); + return colours != nullptr ? int(colours->size()) : 0; +} + +// The extruder of each filament as the plate's filament grouping dialog shows it: the plate's own map, else the +// project's, extruder 1 for a filament it lacks. With `volumes`, the nozzle volume type of each filament the same way, +// Standard for one it lacks. +std::vector shown_filament_map(const PartPlate& plate, bool volumes = false) +{ + const DynamicPrintConfig& project = wxGetApp().preset_bundle->project_config; + std::vector map = volumes ? plate.get_real_filament_volume_maps(project) : plate.get_real_filament_maps(project); + map.resize(std::size_t(grouped_filaments()), volumes ? 0 : 1); + return map; +} + +// The filament_map_mode values the plate's filament grouping dialog offers: none on a printer with one extruder, whose +// plates show no filament map icon, and Auto For Match, which groups by the filaments a printer has loaded, once that +// printer is synced and has no filament track switch ready. UI thread. +std::vector offered_map_modes() +{ + if (wxGetApp().preset_bundle->get_printer_extruder_count() < 2) + return {}; + Plater& plater = ui_plater(); + std::vector modes{"Auto For Flush"}; + if (plater.get_machine_sync_status() && !plater.sidebar().is_fila_switch_ready()) + modes.push_back("Auto For Match"); + modes.push_back("Manual"); + return modes; +} + +// A plate's filament_map_mode as plate_set_settings takes it: an offered mode, or null, no mode of the plate's own, so +// that it follows the project's grouping (PartPlate::set_filament_map_mode() with fmmDefault; the plate's grouping +// dialog offers no page for it). UI thread. +FilamentMapMode filament_map_mode_value(const json& value) +{ + if (value.is_null()) + return fmmDefault; + const std::vector offered = offered_map_modes(); + if (!value.is_string() || std::find(offered.begin(), offered.end(), value.get()) == offered.end()) + throw ToolFailure("filament_map_mode is a mode the plate's filament grouping offers (meta.offered of plate_get_settings), " + "or null for the project's grouping" + + std::string(value == "Auto For Match" ? "; Auto For Match groups by the filaments a printer has " + "loaded, and is offered once that printer is synced" : + ""), + {{"offered", offered}}); + return FilamentMapMode(ConfigOptionEnum::get_enum_values().at(value.get())); +} + +// A plate setting in the form plate_set_settings takes: the plate's own value, null where it follows the +// project's plate type, the process, Auto or the project's filament grouping; or with `effective` what the plate +// prints with. json plate_value(PartPlate& plate, const std::string& key, bool effective) { - if (key == "name") - return plate.get_plate_name(); - if (key == "locked") - return plate.is_locked(); + if (key == "filament_map_mode") { + const FilamentMapMode mode = effective ? plate.get_real_filament_map_mode(wxGetApp().preset_bundle->project_config) : + plate.get_filament_map_mode(); + return mode == fmmDefault ? json() : json(ConfigOptionEnum(mode).serialize()); + } + if (key == "filament_map") { + const std::vector own = plate.get_filament_maps(); + return effective ? json(shown_filament_map(plate)) : own.empty() ? json() : json(own); + } if (key == "curr_bed_type") { const BedType type = plate.get_bed_type(effective); return type == btDefault ? json() : json(ConfigOptionEnum(type).serialize()); @@ -524,30 +602,27 @@ json plate_value(PartPlate& plate, const std::string& key, bool effective) return ranges.empty() ? json() : layer_sequences_json(ranges); } -// Every plate scope value of a plate: its own, or with `effective` what it prints with. +// Every listed setting of a plate (listed_plate_keys()): its own value, or with `effective` what it prints with. json plate_values(PartPlate& plate, bool effective) { json out = json::object(); - for (const char* key : plate_scope_keys) + for (const std::string& key : listed_plate_keys()) out[key] = plate_value(plate, key, effective); return out; } -// get_settings on the plate scope: every key, or those named, with the plate's own value and the one it -// prints with. UI thread. +// plate_get_settings: every key, or those named, with the plate's own value and the one it prints with. UI thread. json plate_settings(const json& args) { - if (args.contains("compare") || args.contains("preset")) - throw ToolFailure("preset and compare are for the process, filament and printer scopes"); - const int index = scope_plate(args); - PartPlate& plate = *ui_plater().get_partplate_list().get_plate(index); - std::vector keys(std::begin(plate_scope_keys), std::end(plate_scope_keys)); + const int index = scope_plate(args); + PartPlate& plate = *ui_plater().get_partplate_list().get_plate(index); + std::vector keys = listed_plate_keys(); json unknown = json::array(); if (args.contains("keys")) { keys.clear(); for (const json& k : args["keys"]) { const std::string key = k.get(); - if (std::find(std::begin(plate_scope_keys), std::end(plate_scope_keys), key) != std::end(plate_scope_keys)) + if (is_plate_setting(key)) keys.push_back(key); else unknown.push_back(key); @@ -555,14 +630,13 @@ json plate_settings(const json& args) } json items = json::array(); for (const std::string& key : keys) { - json item{{"key", key}, {"value", plate_value(plate, key, false)}}; - if (is_plate_setting(key)) { - item["effective"] = plate_value(plate, key, true); - if (arg_bool(args, "include_meta", true)) { - item["meta"] = option_meta(*print_config_def.get(key)); - if (key == "curr_bed_type") - item["meta"]["offered"] = project_offered(key); - } + json item{{"key", key}, {"value", plate_value(plate, key, false)}, {"effective", plate_value(plate, key, true)}}; + if (arg_bool(args, "include_meta", true)) { + item["meta"] = option_meta(*print_config_def.get(key)); + if (key == "curr_bed_type") + item["meta"]["offered"] = project_offered(key); + if (key == "filament_map_mode") + item["meta"]["offered"] = offered_map_modes(); } items.push_back(std::move(item)); } @@ -572,19 +646,21 @@ json plate_settings(const json& args) return out; } -// set_settings on the plate scope. The Plate Settings dialog's values go through its OK -// (Plater::apply_plate_settings()) with the plate's other values as they are, after selecting the plate as -// its settings icon does; the lock and the name as their icons do. Everything is checked before anything -// changes, and the call is one undo step. +// plate_set_settings. The Plate Settings dialog's values go through its OK (Plater::apply_plate_settings()) with the +// plate's other values as they are, after selecting the plate as its settings icon does; the filament grouping's go +// through the OK of the dialog the plate's filament map icon opens (Plater::open_filament_map_setting_dialog()), which +// takes no undo snapshot of its own. Everything is checked before anything changes, a key a plate's settings lack +// before the app is read, and the call is one undo step. ToolResult set_plate_settings(const json& args, ToolContext& ctx) { const json values_in = args.value("values", json::object()); if (values_in.empty()) throw ToolFailure("values must be a non-empty object {key: value}"); - if (args.contains("reset_all") || args.contains("reset_to")) - throw ToolFailure("reset_all and reset_to are for preset scopes; here a null value takes the global setting or Auto"); int index = -1; json reply = ctx.run_ui([&]() -> json { + for (auto it = values_in.begin(); it != values_in.end(); ++it) + if (!is_plate_setting(it.key())) + throw unknown_setting(it.key(), "plate", {{"keys", plate_setting_keys()}}); Plater& plater = ui_plater(); if (plater.printer_technology() != ptFFF || plater.only_gcode_mode()) throw ToolFailure("Plates are a filament (FFF) feature"); @@ -600,16 +676,14 @@ ToolResult set_plate_settings(const json& args, ToolContext& ctx) std::vector first_layer = plate.get_first_layer_print_sequence(); std::vector other_layers = plate.get_other_layers_print_sequence(); const int slots = wxGetApp().filaments_cnt(); + // The filament grouping dialog's choices: its mode, and the map its Custom page sets. + const FilamentMapMode own_mode = plate.get_filament_map_mode(); + FilamentMapMode map_mode = own_mode; + std::optional> map; + const int extruders = wxGetApp().preset_bundle->get_printer_extruder_count(); for (auto it = values_in.begin(); it != values_in.end(); ++it) { const std::string& key = it.key(); const json& value = it.value(); - if (std::find(std::begin(plate_scope_keys), std::end(plate_scope_keys), key) == std::end(plate_scope_keys)) - throw unknown_setting(key, "plate", - {{"keys", std::vector(std::begin(plate_scope_keys), std::end(plate_scope_keys))}}); - if (key == "name" && !value.is_string()) - throw ToolFailure("name takes a string (\"\" for none)"); - if (key == "locked" && !value.is_boolean()) - throw ToolFailure("locked takes true or false"); if (key == "curr_bed_type") { bed_type = btDefault; // "Same as Global Plate Type" if (value.is_null()) @@ -633,51 +707,95 @@ ToolResult set_plate_settings(const json& args, ToolContext& ctx) // The dialog greys the custom orders out while a slot is a mixed filament, which prints a different // physical filament from layer to layer. if (!value.is_null() && wxGetApp().preset_bundle->num_mixed_filaments() > 0) - throw ToolFailure(key + " cannot be set while the project has mixed filaments (see the project scope's " - "filament_is_mixed); null sets Auto"); + throw ToolFailure(key + " cannot be set while the project has mixed filaments (see filament_is_mixed of " + "project_get_settings); null sets Auto"); if (key == "first_layer_print_sequence") first_layer = value.is_null() ? std::vector() : filament_order(value, slots); else other_layers = value.is_null() ? std::vector() : layer_sequences(value, slots); + } else { + // The plate shows its filament map icon on a printer with several extruders alone. + if (extruders < 2) + throw ToolFailure(key + " groups the filaments onto the extruders of a printer that has several; this one has one"); + if (key == "filament_map_mode") { + map_mode = filament_map_mode_value(value); + } else { + if (!value.is_array() || + std::any_of(value.begin(), value.end(), [](const json& extruder) { return !extruder.is_number_integer(); })) + throw ToolFailure("filament_map is the extruder of each filament, 1-based, e.g. [1, 2, 2]"); + map = value.get>(); + } } } + if (map) { + const std::string mode = map_mode == fmmDefault ? std::string() : ConfigOptionEnum(map_mode).serialize(); + if (const std::string err = filament_map_error(mode, *map, grouped_filaments(), extruders); !err.empty()) + throw ToolFailure(err); + } const bool settings = bed_type != plate.get_bed_type() || sequence != plate.get_print_seq() || first_layer != plate.get_first_layer_print_sequence() || other_layers != plate.get_other_layers_print_sequence() || spiral != own_spiral; - const bool rename = values_in.contains("name") && values_in["name"].get() != plate.get_plate_name(); - // The settings and name icons select their plate first; the dialogs work on the current plate. - if ((settings || rename) && index != plates.get_curr_plate_index()) - plater.select_plate(index); - Plater::SingleSnapshot single(&plater); - if (settings) { + // The grouping dialog's OK: in the Manual mode the map and nozzle volume types its Custom page shows become the + // plate's own, and the slice is invalidated when the mode or what the plate prints with changes. + const DynamicPrintConfig& project = wxGetApp().preset_bundle->project_config; + const std::vector old_maps = plate.get_real_filament_maps(project); + const std::vector old_volumes = plate.get_real_filament_volume_maps(project); + const std::vector new_maps = map ? *map : shown_filament_map(plate); + const std::vector new_volumes = shown_filament_map(plate, true); + const bool manual = map_mode == fmmManual; + const bool regrouped = map_mode != own_mode || old_maps != new_maps || old_volumes != new_volumes; + const bool own_map = manual && (plate.get_filament_maps() != new_maps || + plate.get_filament_volume_maps() != new_volumes); + const bool grouping_given = values_in.contains("filament_map_mode") || values_in.contains("filament_map"); + const bool grouping = grouping_given && (regrouped || own_map); + // The Custom page disables the dialog's OK while an extruder its map gives a filament the plate prints has no + // nozzle of the volume type that filament needs. + if (const std::optional shortage = manual && grouping_given ? + manual_map_nozzle_shortage(nozzle_inventory(*wxGetApp().preset_bundle), plate.get_extruders(true), new_maps, + new_volumes) : + std::nullopt) { + const std::string type = ConfigOptionEnum(shortage->volume_type).serialize(); + const char* side = shortage->extruder == 0 ? " (left)" : shortage->extruder == 1 ? " (right)" : ""; + throw ToolFailure("The manual grouping gives extruder " + std::to_string(shortage->extruder + 1) + side + + " a filament that prints with a " + type + " nozzle, and the extruder has no " + type + + " nozzle, so the filament grouping dialog does not take this map: give that filament another " + "extruder, or set the extruder's nozzles first", + {{"code", "no_nozzle_for_grouping"}, {"extruder", shortage->extruder + 1}, {"nozzle_volume_type", type}}); + } + if (settings || grouping) { + // The settings and filament map icons select their plate first; the dialogs work on the current plate. + if (index != plates.get_curr_plate_index()) + plater.select_plate(index); + Plater::SingleSnapshot single(&plater); plater.take_snapshot("Plate Settings"); - plater.apply_plate_settings(index, bed_type, first_layer, other_layers, sequence, spiral); + if (settings) + plater.apply_plate_settings(index, bed_type, first_layer, other_layers, sequence, spiral); + if (grouping) { + if (map_mode != own_mode) + plate.set_filament_map_mode(map_mode); + if (manual) { + plate.set_filament_maps(new_maps); + plate.set_filament_volume_maps(new_volumes); + } + if (regrouped) { + plate.update_slice_result_valid_state(false); + plater.set_plater_dirty(true); + plater.update(); + } + } } - if (values_in.contains("locked")) { - Ops::SetPlateLockedArgs lock; - lock.plate = index; - lock.locked = values_in["locked"].get(); - if (const Ops::Outcome locked = Ops::set_plate_locked(lock); !locked) - throw refused(locked.refusal()); - } - if (rename) - plater.rename_plate(index, values_in["name"].get()); const json after = plate_values(plate, false); json applied = json::object(); json effective = json::object(); json changed = json::object(); for (auto it = values_in.begin(); it != values_in.end(); ++it) { - applied[it.key()] = after[it.key()]; - if (is_plate_setting(it.key())) - effective[it.key()] = plate_value(plate, it.key(), true); + applied[it.key()] = after.value(it.key(), json()); + effective[it.key()] = plate_value(plate, it.key(), true); } - for (const char* key : plate_scope_keys) - if (after[key] != before[key]) - changed[key] = after[key]; - json out{{"plate", index}, {"applied", applied}, {"changed", changed}}; - if (!effective.empty()) - out["effective"] = std::move(effective); - return out; + for (auto it = after.begin(); it != after.end(); ++it) + if (it.value() != before.value(it.key(), json())) + changed[it.key()] = it.value(); + return json{{"plate", index}, {"applied", applied}, {"changed", changed}, {"effective", effective}}; }); // A replay sets the same plate, whichever is current then. if (!args.contains("plate")) { @@ -689,8 +807,22 @@ ToolResult set_plate_settings(const json& args, ToolContext& ctx) return ToolResult::ok(reply); } -// list_plates: every plate's settings as it prints them, what it sets itself, its objects, slice state, -// prime tower position and layer G-codes. UI thread. +// How many objects have an instance on plate `plate`; object_list lists them. +int objects_on_plate(const Model& model, PartPlateList& plates, int plate) +{ + int objects = 0; + for (std::size_t o = 0; o < model.objects.size(); ++o) { + const std::size_t instances = model.objects[o]->instances.size(); + std::size_t j = 0; + while (j < instances && instance_plate(plates, int(o), int(j)) != plate) + ++j; + objects += j < instances; + } + return objects; +} + +// plate_list: every plate's name, lock, settings as it prints them, what it sets itself, its objects, place on the bed, +// slice state, prime tower position and layer G-codes. UI thread. json list_plates(const json& args) { Plater& plater = ui_plater(); @@ -704,23 +836,17 @@ json list_plates(const json& args) PartPlate& plate = *plates.get_plate(i); json entry = plate_values(plate, true); entry["index"] = i; + entry["name"] = plate.get_plate_name(); + entry["locked"] = plate.is_locked(); entry["current"] = i == plates.get_curr_plate_index(); json overrides = json::array(); - for (const char* key : plate_scope_keys) - if (is_plate_setting(key) && !plate_value(plate, key, false).is_null()) + for (const std::string& key : listed_plate_keys()) + if (!plate_value(plate, key, false).is_null()) overrides.push_back(key); entry["overrides"] = std::move(overrides); - // How many objects have an instance on the plate; list_objects lists them. - int objects = 0; - for (std::size_t o = 0; o < model.objects.size(); ++o) { - const std::size_t instances = model.objects[o]->instances.size(); - std::size_t j = 0; - while (j < instances && instance_plate(plates, int(o), int(j)) != i) - ++j; - objects += j < instances; - } - entry["objects"] = objects; - entry["sliced"] = plate.is_slice_result_valid(); + entry["objects"] = objects_on_plate(model, plates, i); + entry.update(plate_place(plate)); + entry["sliced"] = plate.is_slice_result_valid(); if (tower_x != nullptr && tower_y != nullptr && !tower_x->empty() && !tower_y->empty()) entry["wipe_tower"] = {tower_x->get_at(std::size_t(i)), tower_y->get_at(std::size_t(i))}; // Layer numbers only from an up-to-date slice that no slice is rewriting. @@ -735,50 +861,250 @@ json list_plates(const json& args) return page(items, args, 100); } -// Resolves the scope arguments to the config they read and write. UI thread. +// ---- The plate commands made from menu rows ---- + +// What a plate command made from rows answers for a refusal: as information where its row told it so (no plates to +// edit, the only plate, no room for another, a slice running), else as an error. +AppActionRunResult plate_refused(const Ops::Refusal& refusal) +{ + const std::string code = refusal.code; + const bool info = refusal.kind == Ops::RefusalKind::Busy || code == "no_plates" || code == "last_plate" || + code == "too_many_plates"; + return NativeCommands::refused(refusal, info ? AppActionRunResult::Level::Info : AppActionRunResult::Level::Error); +} + +// The plate a call's `plate` argument names; none without it, for the current plate. +std::optional named_plate(const json& args) +{ + return args.contains("plate") ? std::optional(arg_int(args, "plate", 0)) : std::nullopt; +} + +// The plates as a command that adds or removes one replies with them afterwards: each plate's index, name and how many +// objects stand on it, and the current plate. UI thread. +json plates_reply() +{ + Plater& plater = ui_plater(); + PartPlateList& plates = plater.get_partplate_list(); + json items = json::array(); + for (int i = 0; i < plates.get_plate_count(); ++i) + items.push_back( + {{"index", i}, {"name", plates.get_plate(i)->get_plate_name()}, {"objects", objects_on_plate(plater.model(), plates, i)}}); + return {{"plates", std::move(items)}, {"current", plates.get_curr_plate_index()}}; +} + +AppActionRunResult plate_delete_command(const json& args) +{ + const Ops::Outcome deleted = Ops::delete_plate({named_plate(args)}); + if (!deleted) + return plate_refused(deleted.refusal()); + json reply = plates_reply(); + reply["plate"] = deleted.value(); + return row_reply(reply); +} + +AppActionRunResult plate_duplicate_command(const json& args) +{ + const Ops::Outcome made = Ops::duplicate_plate({named_plate(args)}); + if (!made) + return plate_refused(made.refusal()); + json reply = plates_reply(); + reply["plate"] = made.value().plate; + reply["new_plate"] = made.value().copy; + return row_reply(reply); +} + +// plate_rename: a call with no arguments asks for the current plate's name in its name dialog, as the row does; any +// other gives it. +AppActionRunResult plate_rename_command(const json& args) +{ + Ops::RenamePlateArgs op; + op.plate = named_plate(args); + if (person_form(args)) { + if (std::optional refusal = Ops::plates_refusal()) + return plate_refused(*refusal); + PlateNameEditDialog dlg(wxGetApp().mainframe, wxID_ANY, _L("Edit Plate Name")); + dlg.set_plate_name(from_u8(ui_plater().get_partplate_list().get_curr_plate()->get_plate_name())); + // The person called it off, and knows nothing was renamed. + if (dlg.ShowModal() != wxID_YES) + return quiet_refusal(Ops::plate_not_renamed()); + op.name = into_u8(dlg.get_plate_name()); + } else { + op.name = arg_string(args, "name"); + } + const Ops::Outcome renamed = Ops::rename_plate(op); + if (!renamed) + return plate_refused(renamed.refusal()); + const PartPlate& plate = *ui_plater().get_partplate_list().get_plate(renamed.value()); + return row_reply({{"plate", renamed.value()}, {"name", plate.get_plate_name()}}); +} + +AppActionRunResult plate_lock_command(const json& args) +{ + Ops::SetPlateLockedArgs op; + op.plate = named_plate(args); + if (args.contains("locked")) + op.locked = arg_bool(args, "locked", true); + const Ops::Outcome locked = Ops::set_plate_locked(op); + if (!locked) + return plate_refused(locked.refusal()); + return row_reply({{"plate", locked.value().plate}, {"locked", locked.value().locked}, {"changed", locked.value().changed}}); +} + +// plate_select: Ops::select_plate() also serves the commands that select a plate on the way, so the check of the rows, +// that the project has plates to select, is made here. +AppActionRunResult plate_select_command(const json& args) +{ + if (std::optional refusal = Ops::plates_refusal()) + return plate_refused(*refusal); + Ops::SelectPlateArgs op; + op.plate = arg_int(args, "plate", ui_plater().get_partplate_list().get_curr_plate_index()); + if (const Ops::Outcome selected = Ops::select_plate(op); !selected) + return plate_refused(selected.refusal()); + return row_reply({{"plate", op.plate}}); +} + +// ---- The filament slot commands made from menu rows, and Sync Presets ---- + +// What a filament slot command answers for a refusal: as information where its row told it so (no slots to change, no +// + and - buttons for the printer, no room for another slot, the only slot), else as an error. +AppActionRunResult filament_refused(const Ops::Refusal& refusal) +{ + const std::string code = refusal.code; + const bool info = code == "filaments_unavailable" || code == "one_filament_per_extruder" || code == "too_many_filaments" || + code == "last_filament_slot"; + return NativeCommands::refused(refusal, info ? AppActionRunResult::Level::Info : AppActionRunResult::Level::Error); +} + +// What a filament slot command that ran shows a person, `message`, and replies to a call: `reply` with how many slots +// the project has afterwards. +AppActionRunResult filament_reply(const wxString& message, json reply) +{ + reply["filament_slots"] = wxGetApp().preset_bundle->filament_presets.size(); + AppActionRunResult result{AppActionRunResult::Level::Succeeded, message}; + result.reply = reply.dump(); + return result; +} + +AppActionRunResult filament_add_command(const json&) +{ + const Ops::Outcome added = Ops::add_filament_slot(); + if (!added) + return filament_refused(added.refusal()); + // TRN %1% is a filament slot number. + return filament_reply(format_wxstr(_L("Added filament slot %1%."), added.value()), {{"filament_slot", added.value()}}); +} + +AppActionRunResult filament_delete_command(const json& args) +{ + Ops::DeleteFilamentArgs op; + if (args.contains("filament_slot")) + op.filament_slot = arg_int(args, "filament_slot", 1); + if (args.contains("merge_into")) + op.merge_into = arg_int(args, "merge_into", 1); + const Ops::Outcome deleted = Ops::delete_filament_slot(op); + if (!deleted) + return filament_refused(deleted.refusal()); + json reply{{"filament_slot", deleted.value().filament_slot}}; + if (deleted.value().merged_into) + reply["merged_into"] = *deleted.value().merged_into; + // TRN %1% is a filament slot number. + return filament_reply(format_wxstr(_L("Deleted filament slot %1%."), deleted.value().filament_slot), std::move(reply)); +} + +// filament_sync_ams: with no arguments, as its tile, the sync dialog's run, which asks and warns; with mode, the sync +// with that choice of the dialog, which opens nothing. Reply: each slot's preset and colour afterwards. +AppActionRunResult sync_ams_command(const json& args) +{ + if (!args.contains("mode")) + return Rows::sync_ams(); + const Ops::AmsSyncMode mode = arg_string(args, "mode") == "map" ? Ops::AmsSyncMode::Map : Ops::AmsSyncMode::Overwrite; + const Ops::Outcome synced = Ops::sync_filaments_from_ams(mode); + if (!synced) + return NativeCommands::refused(synced.refusal(), AppActionRunResult::Level::Error); + json slots = json::array(); + for (std::size_t slot = 0; slot < synced.value().presets.size(); ++slot) { + json item{{"filament_slot", slot + 1}, {"preset", synced.value().presets[slot]}}; + if (slot < synced.value().colours.size()) + item["colour"] = synced.value().colours[slot]; + slots.push_back(std::move(item)); + } + json reply{{"mode", arg_string(args, "mode")}, {"filaments", std::move(slots)}}; + if (!synced.value().unknowns.empty()) + reply["mapped_to_generic"] = synced.value().unknowns; + return row_reply(reply); +} + +// preset_sync: signed out, a pick says to sign in, as its row did, and a call is refused. +AppActionRunResult preset_sync_command(const json&) +{ + if (const Ops::Outcome synced = Ops::sync_presets(); !synced) + return NativeCommands::refused(synced.refusal(), AppActionRunResult::Level::Info); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; +} + +// Whether settings_list's items carry their meta: as include_meta says, by default with where. +bool listed_with_meta(const json& args) { return arg_bool(args, "include_meta", args.contains("where")); } + +// Resolves a call's type and target (settings_request_error() has checked them) to the config they read and write: +// a type's preset for the target global, the process's overrides of an object, a part or a height range for the +// others, which take what their rows offer (target_options()). The object or the part is the one the call names, else +// the one selected in Prepare, as for every command of one target. UI thread. ConfigTarget resolve_target(const json& args, bool for_write) { - const std::string scope = arg_string(args, "scope", "process"); + const std::string target = arg_string(args, "target", "global"); + const std::string type = arg_string(args, "type", "process"); PresetBundle& bundle = *wxGetApp().preset_bundle; ConfigTarget t; - if (scope == "object" || scope == "part") { - Plater& plater = ui_plater(); - const int idx = arg_int(args, "object", -1); - ModelObjectPtrs& objects = plater.model().objects; - if (idx < 0 || idx >= int(objects.size())) - throw ToolFailure("object must be an index from list_objects (0.." + std::to_string(int(objects.size()) - 1) + ")"); - t.object = objects[size_t(idx)]; - t.object_index = idx; - if (scope == "part") { - const int v = arg_int(args, "part", -1); - if (v < 0 || v >= int(t.object->volumes.size())) - throw ToolFailure("part must be a part index from list_objects"); - t.volume = t.object->volumes[size_t(v)]; - t.config = &t.volume->config.get(); + if (target != "global") { + Plater& plater = ui_plater(); + Model& model = plater.model(); + json names = json::object(); + for (const char* key : {"object", "object_id", "part", "part_id"}) + if (args.contains(key)) + names[key] = args[key]; + // An instance or a part selected stands for its object. + const Ops::Outcome resolved = resolve_targets(model, &plater.get_view3D_canvas3D()->get_selection(), names, + target == "part" ? kParts : kObjects | kObjectOfSelection, true); + if (!resolved) + throw refused(resolved.refusal()); + t.target = target; + t.named = resolved.value(); + if (target == "part") { + const auto [object, part] = t.named.parts.front(); + t.object_index = object; + t.object = model.objects[std::size_t(object)]; + t.volume = t.object->volumes[std::size_t(part)]; + t.config = &t.volume->config.get(); } else { - t.config = &t.object->config.get(); + t.object_index = t.named.objects.front(); + t.object = model.objects[std::size_t(t.object_index)]; + t.config = &t.object->config.get(); } - check_expected_ids(*t.object, t.volume, args); - const bool is_part = t.volume != nullptr; - t.options = model_scope_options(SettingsFactory::get_options(is_part), is_part, wxGetApp().filaments_cnt()); - if (!for_write) { - // Reads take any print setting too: the object prints with every one of them, from its - // override or the process, which `effective` says. Writes keep to what the object list - // offers, so no override is made that the GUI can't show. - for (const std::string& key : preset_options(Preset::TYPE_PRINT)) - if (std::find(t.options.begin(), t.options.end(), key) == t.options.end()) - t.options.push_back(key); + if (target == "height_range") { + // The range of those heights, as object_list gives them, to a tenth of a micron. + const t_layer_height_range heights{arg_double(args, "min_z", -1.), arg_double(args, "max_z", -1.)}; + t_layer_config_ranges& ranges = t.object->layer_config_ranges; + const auto range = std::find_if(ranges.begin(), ranges.end(), [&heights](const auto& entry) { + return std::abs(entry.first.first - heights.first) < EPSILON && std::abs(entry.first.second - heights.second) < EPSILON; + }); + if (range == ranges.end()) { + std::string listed; + json have = json::array(); + for (const auto& entry : ranges) { + listed += (listed.empty() ? "" : ", ") + height_range_text(entry.first); + have.push_back({{"min_z", entry.first.first}, {"max_z", entry.first.second}}); + } + throw ToolFailure("object " + std::to_string(t.object_index) + " has no height range " + height_range_text(heights) + + (listed.empty() ? "; it has none (object_set_height_ranges makes them)" : "; it has " + listed), + {{"height_ranges", std::move(have)}}); + } + t.range = range->first; + t.config = &range->second.get(); } + t.options = target_options(target, wxGetApp().filaments_cnt()); return t; } - if (scope == "project") { - t.project = true; - t.owned = std::make_shared(project_settings()); - t.config = t.owned.get(); - t.options = project_options(); - return t; - } - t.type = preset_type(scope); + t.type = preset_type(type); t.options = preset_options(t.type); if (args.contains("preset")) { // A saved preset, selected or not, read without selecting it. @@ -790,7 +1116,7 @@ ConfigTarget resolve_target(const json& args, bool for_write) // `real`: the saved preset, not the edited copy find_preset() gives for the selected one. t.preset = collection(t.type).find_preset(name, false, true); if (t.preset == nullptr) - throw ToolFailure("No " + scope + " preset \"" + name + "\" (see list_presets)", {{"similar", similar_presets(collection(t.type), name)}}); + throw ToolFailure("No " + type + " preset \"" + name + "\" (see preset_list)", {{"similar", similar_presets(collection(t.type), name)}}); t.config = &t.preset->config; return t; } @@ -811,6 +1137,26 @@ ConfigTarget resolve_target(const json& args, bool for_write) t.edited = true; t.preset = &collection(t.type).get_edited_preset(); t.config = &t.preset->config; + if (t.type == Preset::TYPE_PRINTER) { + // The nozzle flow type of each extruder, which its card in the sidebar picks and the project holds. + auto printer = std::make_shared(t.preset->config); + if (const ConfigOption* volumes = bundle.project_config.option("nozzle_volume_type")) + printer->set_key_value("nozzle_volume_type", volumes->clone()); + t.owned = printer; + t.config = printer.get(); + t.options.push_back("nozzle_volume_type"); + } + return t; +} + +// The project's own settings, which project_get_settings reads. UI thread. +ConfigTarget project_target() +{ + ConfigTarget t; + t.project = true; + t.owned = std::make_shared(project_settings()); + t.config = t.owned.get(); + t.options = project_options(); return t; } @@ -824,7 +1170,198 @@ std::pair, std::vector> printer_extruders() return {types != nullptr ? types->values : std::vector(), volumes != nullptr ? volumes->values : std::vector()}; } -// The preset get_settings' compare names: ":saved" is the read preset as saved (so the difference is +// settings_set's extruders_count, set alone (settings_request_error()): what a change of the Extruders field of the +// Printer settings does (TabPrinter::change_extruders_count()). `before` is the printer's settings before it. UI thread. +json set_extruders_count(const json& args, const DynamicPrintConfig& before) +{ + const std::size_t count = extruders_count_value(args["values"]["extruders_count"], before.opt_bool("single_extruder_multi_material")); + auto* tab = dynamic_cast(wxGetApp().get_tab(Preset::TYPE_PRINTER)); + if (tab == nullptr) + throw ToolFailure("The settings tab is not available"); + tab->change_extruders_count(count); + // The Extruders field shows the count, which was not typed into it. + tab->reload_config(); + const ConfigTarget after = resolve_target(args, false); + return json{{"applied", {{"extruders_count", tab->m_extruders_count}}}, {"changed", changed_settings(before, *after.config)}}; +} + +// What settings_set's printer values set through the sidebar's nozzle cards: the printer variant a nozzle_diameter +// switches to (nozzle_diameter_variant()) and the printer preset that selects, and the nozzle flow type of each +// extruder a nozzle_volume_type gives. +struct NozzlePicks +{ + std::string variant; + std::string preset; + std::optional> flow_types; +}; + +// The nozzle flow types of `types` as nozzle_volume_type names them. +json flow_type_names(const std::vector& types) +{ + json names = json::array(); + for (const NozzleVolumeType type : types) + names.push_back(ConfigOptionEnum(type).serialize()); + return names; +} + +// The nozzle flow type of each extruder once `target`, a printer preset of another variant, is selected, read without +// selecting it: what the printer tab gives the project when it loads a preset of another base preset +// (TabPrinter::on_preset_loaded()), the types the app configuration remembers for that base, else the preset's +// default_nozzle_volume_type; `current`, the types the project has, for a preset of the same base. UI thread. +std::vector flow_types_after_switch(const Preset& target, const std::vector& current) +{ + PresetCollection& printers = wxGetApp().preset_bundle->printers; + const auto base = [&printers](const Preset& preset) { + const Preset* found = printers.get_preset_base(preset); + return (found != nullptr ? found : &preset)->name; + }; + const std::string name = base(target); + if (name == base(printers.get_selected_preset())) + return current; + if (const auto* project = wxGetApp().preset_bundle->project_config.option("nozzle_volume_type")) { + ConfigOptionEnumsGeneric remembered(*project); + if (const std::string saved = wxGetApp().app_config->get_nozzle_volume_types_from_config(name); + !saved.empty() && remembered.deserialize(saved)) + return remembered.values; + } + const auto* defaults = target.config.option("default_nozzle_volume_type"); + return defaults != nullptr ? defaults->values : current; +} + +// Takes the values the nozzle cards set out of `values` (key, serialized value) and checks them, before anything +// changes: a nozzle_diameter no variant has stays, to be typed into the Printer settings. A nozzle_diameter that selects +// another variant's preset goes with nozzle_volume_type alone, since the other values would be read against one preset +// and written to another. A flow type other than the one the extruder has, or with a variant switch will have +// (flow_types_after_switch()), is checked against the Flow combo it is picked in: the one shown, or with a variant +// switch the one the new preset shows. `printer` is the printer's settings, its nozzle_volume_type included +// (resolve_target()). UI thread. +NozzlePicks nozzle_picks(std::vector>& values, const DynamicPrintConfig& printer) +{ + NozzlePicks picks; + std::vector types; + for (auto v = values.begin(); v != values.end();) { + if (v->first != "nozzle_diameter" && v->first != "nozzle_volume_type") { + ++v; + continue; + } + DynamicPrintConfig scratch; + try { + scratch.set_deserialize_strict(v->first, v->second); + } catch (const std::exception& e) { + throw ToolFailure("Invalid value for " + v->first + ": " + e.what()); + } + if (v->first == "nozzle_diameter") { + const auto* variant = printer.option("printer_variant"); + picks.variant = nozzle_diameter_variant(scratch.option(v->first)->values, + wxGetApp().preset_bundle->printers.diameters_of_selected_printer(), + variant != nullptr ? variant->value : std::string()); + v = picks.variant.empty() ? std::next(v) : values.erase(v); + continue; + } + types = scratch.option(v->first)->values; + picks.flow_types = types; + v = values.erase(v); + } + const Preset* target = nullptr; + if (!picks.variant.empty()) { + target = wxGetApp().preset_bundle->get_similar_printer_preset({}, picks.variant); + if (target == nullptr) + throw ToolFailure("The printer has no preset of the nozzle variant " + picks.variant); + picks.preset = target->name; + if (!values.empty()) { + std::string keys; + for (const auto& [key, value] : values) + keys += (keys.empty() ? "" : ", ") + key; + throw ToolFailure("Set " + keys + " in a second call: a nozzle_diameter that selects the printer preset of another " + "variant (" + target->name + ") goes with nozzle_volume_type alone"); + } + } + if (!picks.flow_types) + return picks; + const auto* current = printer.option("nozzle_volume_type"); + const std::size_t count = current != nullptr ? current->size() : 0; + if (types.size() != count) + throw ToolFailure("nozzle_volume_type holds a nozzle flow type per extruder: " + std::to_string(count) + " extruders, " + + std::to_string(types.size()) + " given"); + // The types the extruders have when the picks are made: now, or once the switch has selected the new preset. + const std::vector before = target != nullptr ? flow_types_after_switch(*target, current->values) : current->values; + const auto name = [](int type) { return ConfigOptionEnum(NozzleVolumeType(type)).serialize(); }; + for (std::size_t e = 0; e < count; ++e) { + if (e < before.size() && types[e] == before[e]) + continue; + const std::vector offered = target != nullptr ? Sidebar::nozzle_volume_types(target->config, int(e)) : + ui_plater().sidebar().nozzle_volume_types(int(e)); + if (std::find(offered.begin(), offered.end(), NozzleVolumeType(types[e])) == offered.end()) { + const std::string has = e < before.size() ? ": the extruder has " + name(before[e]) + " there" : std::string(); + const std::string offer = offered.empty() ? "no nozzle flow type to pick" + has : + "the nozzle flow types " + flow_type_names(offered).dump() + ", not " + + name(types[e]); + throw ToolFailure("The nozzle card of extruder " + std::to_string(e + 1) + + (target != nullptr ? " with the printer preset " + target->name : std::string()) + " offers " + offer, + {{"offered", flow_type_names(offered)}}); + } + } + return picks; +} + +// What nozzle_picks() checked, done as a person picks it in the sidebar: the variant, then the flow type of each +// extruder that has another, each read back after the picks. The switch fails only when its question about the +// printer's unsaved changes is cancelled, after `discarded`, reset_all's discarding of those changes, when the call +// asked for it. UI thread. +void pick_nozzles(const NozzlePicks& picks, bool discarded) +{ + Sidebar& sidebar = ui_plater().sidebar(); + if (!picks.variant.empty() && !sidebar.pick_nozzle_variant(picks.variant)) + throw ToolFailure("The printer preset " + picks.preset + " of the nozzle variant " + picks.variant + " was not selected" + + (discarded ? "; reset_all had discarded the printer's unsaved changes" : "")); + if (!picks.flow_types) + return; + const auto flow_types = [] { + return wxGetApp().preset_bundle->project_config.option("nozzle_volume_type")->values; + }; + const std::vector& wanted = *picks.flow_types; + const std::vector current = flow_types(); + for (std::size_t e = 0; e < wanted.size() && e < current.size(); ++e) + if (current[e] != wanted[e]) + sidebar.pick_nozzle_volume_type(int(e), NozzleVolumeType(wanted[e])); + // A guard for what nozzle_picks() rules out: an extruder whose Flow combo, after a variant switch whose flow types + // it predicted wrongly, did not take the type asked for. The call then fails, saying what it changed. + const std::vector after = flow_types(); + const auto name = [](int type) { return ConfigOptionEnum(NozzleVolumeType(type)).serialize(); }; + std::vector wrong, set; + for (std::size_t e = 0; e < wanted.size(); ++e) { + const std::string extruder = "extruder " + std::to_string(e + 1); + if (e < after.size() && e < current.size() && after[e] != current[e]) + set.push_back(extruder + " to " + name(after[e])); + if (e >= after.size()) + wrong.push_back(extruder + " is not there"); + else if (after[e] != wanted[e]) + wrong.push_back(extruder + " has " + name(after[e]) + ", not " + name(wanted[e])); + } + if (wrong.empty()) + return; + const auto listed = [](const std::vector& items) { + std::string text; + for (std::size_t i = 0; i < items.size(); ++i) + text += (i == 0 ? "" : i + 1 == items.size() ? " and " : ", ") + items[i]; + return text; + }; + std::vector changes; + if (!picks.variant.empty()) + changes.push_back("selected the printer preset " + picks.preset); + if (!set.empty()) + changes.push_back("set the nozzle flow type of " + listed(set)); + if (discarded) + changes.push_back("discarded the printer's unsaved changes (reset_all)"); + json types = json::array(); + for (const int type : after) + types.push_back(name(type)); + throw ToolFailure("nozzle_volume_type was not set as asked: " + listed(wrong) + ". The call " + + (changes.empty() ? std::string("changed nothing") : listed(changes)) + ".", + {{"nozzle_volume_type", std::move(types)}}); +} + +// The preset settings_get's compare names: ":saved" is the read preset as saved (so the difference is // its unsaved changes), ":parent" what the tab's lock icons compare against, else a saved preset by name. const Preset& compare_preset(const ConfigTarget& t, const std::string& name) { @@ -843,7 +1380,7 @@ const Preset& compare_preset(const ConfigTarget& t, const std::string& name) } else { other = presets.find_preset(name, false, true); if (other == nullptr) - throw ToolFailure("No preset \"" + name + "\" to compare with (see list_presets)", {{"similar", similar_presets(presets, name)}}); + throw ToolFailure("No preset \"" + name + "\" to compare with (see preset_list)", {{"similar", similar_presets(presets, name)}}); } // The Compare presets dialog compares presets of one printer technology only. if (other->printer_technology() != t.preset->printer_technology()) @@ -881,10 +1418,16 @@ void check_filament_numbers(const DynamicPrintConfig& values) } // The object list row whose Change Filament sets the target's filament: the object's, which is also -// what a single-part object shows for its one part, or the part's or modifier's own row. UI thread. +// what a single-part object shows for its one part, the part's or modifier's own row, or the height range's. UI thread. wxDataViewItem filament_row(const ConfigTarget& t) { ObjectDataViewModel& rows = *wxGetApp().obj_list()->GetModel(); + if (t.range) { + const wxDataViewItem row = rows.GetItemByLayerRange(t.object_index, *t.range); + if (!row.IsOk()) + throw ToolFailure("The height range has no row in the object list"); + return row; + } if (t.volume != nullptr && !t.volume->is_model_part() && !t.volume->is_modifier()) throw ToolFailure("Only parts and modifiers take a filament; this one is a negative part, a support blocker or enforcer, " "or a seam modifier"); @@ -938,24 +1481,39 @@ json filament_slots(const std::string& name) return slots; } +// The first entry of a preset's string vector `key` ("" without one): a filament's vendor or type. +std::string first_value(const Preset& preset, const char* key) +{ + const auto* values = preset.config.option(key); + return values != nullptr && !values->values.empty() ? values->values.front() : std::string(); +} + +// preset_list: an item per preset of the type, the default one only when it is alone, filtered by +// filter_preset_items(). A filament's vendor and type are the ones the filament selection dialogs show; a printer's or +// process's vendor is its vendor bundle (BBL), as the Printer Selection dialog has it. The Template vendor's presets +// are what Create Printer and Create Filament start from, which nothing installs: they are left out. With `printer`, +// a preset fits that printer preset as it would fit the selected one. UI thread. json list_presets(const json& args) { - const Preset::Type type = preset_type(arg_string(args, "type")); - const bool include_incompatible = arg_bool(args, "include_incompatible", false); - const bool include_hidden = arg_bool(args, "include_hidden", false); - const std::string query = lower(arg_string(args, "query")); - PresetCollection& presets = collection(type); - const std::string selected = presets.get_selected_preset_name(); - json items = json::array(); + const Preset::Type type = preset_type(arg_string(args, "type")); + PresetBundle& bundle = *wxGetApp().preset_bundle; + PresetCollection& presets = collection(type); + const std::string selected = presets.get_selected_preset_name(); + const Preset* printer = nullptr; + if (args.contains("printer")) { + const std::string name = arg_string(args, "printer"); + printer = bundle.printers.find_preset(name, false, true); + if (printer == nullptr) + throw ToolFailure("No printer preset \"" + name + "\" (see preset_list {\"type\": \"printer\", \"include_uninstalled\": true})", + {{"similar", similar_presets(bundle.printers, name)}}); + } + json items = json::array(); for (size_t i = 0; i < presets.size(); ++i) { const Preset& p = presets.preset(i); if (p.is_default && presets.size() > 1) continue; - if (!include_incompatible && !p.is_compatible) - continue; - if (!include_hidden && !p.is_visible) - continue; - if (!query.empty() && lower(p.name).find(query) == std::string::npos && lower(p.alias).find(query) == std::string::npos) + const VendorProfile* vendor = presets.get_preset_with_vendor_profile(p).vendor; + if (vendor != nullptr && vendor->id == PRESET_TEMPLATE_DIR) continue; json j{{"name", p.name}, {"system", p.is_system}, {"user", p.is_user()}}; if (!p.alias.empty() && p.alias != p.name) @@ -966,23 +1524,63 @@ json list_presets(const json& args) j["project"] = true; if (!p.is_compatible) j["compatible"] = false; + // Not offered by the selectors: a system printer or filament a person has not installed. if (!p.is_visible) - j["visible"] = false; + j["installed"] = false; if (p.name == selected) { j["selected"] = true; if (presets.current_is_dirty()) j["modified"] = true; } - if (type == Preset::TYPE_FILAMENT) + if (type == Preset::TYPE_FILAMENT) { + for (const auto& [field, key] : {std::pair{"vendor", "filament_vendor"}, std::pair{"filament_type", "filament_type"}}) + if (std::string value = first_value(p, key); !value.empty()) + j[field] = std::move(value); if (json slots = filament_slots(p.name); !slots.empty()) j["filament_slots"] = std::move(slots); + } else if (vendor != nullptr) { + j["vendor"] = vendor->id; + } + if (type == Preset::TYPE_PRINTER) + for (const auto& [field, key] : {std::pair{"printer_model", "printer_model"}, std::pair{"nozzle", "printer_variant"}}) + if (const auto* value = p.config.option(key); value != nullptr && !value->value.empty()) + j[field] = value->value; items.push_back(std::move(j)); } - return page(items, args, 100); + std::function fits; + if (printer != nullptr) + fits = [&](const json& item) { + const Preset* p = presets.find_preset(item["name"].get(), false, true); + return p != nullptr && is_compatible_with_printer(presets.get_preset_with_vendor_profile(*p), + bundle.printers.get_preset_with_vendor_profile(*printer)); + }; + return page(filter_preset_items(std::move(items), args, fits), args, 100); } } // namespace +ToolFailure preset_refused(const Ops::Refusal& refusal) +{ + const std::string code = refusal.code; + if (code == "preset_not_offered") + return refused(refusal, "See preset_list.", "similar"); + if (code == "ambiguous_hidden_preset") + return refused(refusal, "", "presets"); + if (code == "preset_incompatible") + return refused(refusal, "preset_list include_incompatible lists such presets."); + if (code == "transfer_not_offered" || code == "unsaved_preset_changes") + return refused(refusal, "Pass preset_changes: \"discard\", or preset_save first."); + return refused(refusal); +} + +Ops::PresetChanges preset_changes_answer(const json& args) +{ + const std::string changes = arg_string(args, "preset_changes"); + return changes == "transfer" ? Ops::PresetChanges::Transfer : + changes == "discard" ? Ops::PresetChanges::Discard : + Ops::PresetChanges::Ask; +} + std::vector model_scope_options(const std::vector& offered, bool is_part, int filaments) { std::vector keys; @@ -995,38 +1593,118 @@ std::vector model_scope_options(const std::vector& off return keys; } -json effective_setting(const std::string& key, const DynamicPrintConfig& process, const ModelObject& object, const ModelVolume* volume) +std::vector target_options(const std::string& target, int filaments) +{ + if (target == "object" || target == "part") + return model_scope_options(SettingsFactory::get_fff_options(target == "part"), target == "part", filaments); + if (target == "height_range") + return layer_range_option_keys(filaments); + return {}; +} + +std::vector targets_taking(const std::string& key, int filaments) +{ + std::vector targets; + for (const char* target : {"object", "part", "height_range"}) { + const std::vector options = target_options(target, filaments); + if (std::find(options.begin(), options.end(), key) != options.end()) + targets.emplace_back(target); + } + return targets; +} + +std::string untaken_setting_error(const std::string& key, const std::string& target, int filaments) +{ + const std::vector takers = targets_taking(key, filaments); + if (std::find(takers.begin(), takers.end(), target) != takers.end()) + return {}; + const auto row = [](const std::string& name) { + return name == "object" ? std::string("an object") : name == "part" ? std::string("a part") : std::string("a height range"); + }; + if (takers.empty()) + return key + " is set globally only, on the process (target global), not on " + row(target); + std::string where; + for (std::size_t i = 0; i < takers.size(); ++i) + where += (i == 0 ? "" : i + 1 == takers.size() ? " or " : ", ") + row(takers[i]); + return key + " is set on " + where + ", not on " + row(target); +} + +json effective_setting(const std::string& key, const DynamicPrintConfig& process, const ModelObject& object, const ModelVolume* volume, + const DynamicPrintConfig* range) { // An extruder of 0 is the object list's "Default": no filament of its own. - const auto own = [&key](const ModelConfig& config) -> const ConfigOption* { + const auto own = [&key](const DynamicPrintConfig& config) -> const ConfigOption* { const ConfigOption* opt = config.option(key); return opt != nullptr && (key != "extruder" || opt->getInt() != 0) ? opt : nullptr; }; json out; - if (const ConfigOption* opt = volume != nullptr ? own(volume->config) : nullptr) + if (const ConfigOption* opt = range != nullptr ? own(*range) : nullptr) + out = {{"effective", opt->serialize()}, {"source", "height_range"}}; + else if (const ConfigOption* opt = volume != nullptr ? own(volume->config.get()) : nullptr) out = {{"effective", opt->serialize()}, {"source", "part"}}; - else if (const ConfigOption* opt = own(object.config)) + else if (const ConfigOption* opt = own(object.config.get())) out = {{"effective", opt->serialize()}, {"source", "object"}}; else if (process.has(key)) - out = {{"effective", process.opt_serialize(key)}, {"source", "process"}}; + out = {{"effective", process.opt_serialize(key)}, {"source", "global"}}; else if (key == "extruder") out = {{"effective", "1"}, {"source", "default"}}; // the process has no extruder; filament 1 prints else if (const ConfigOptionDef* def = print_config_def.get(key); def != nullptr && def->default_value) out = {{"effective", def->default_value->serialize()}, {"source", "default"}}; if (volume == nullptr) { - json parts = json::array(); + // Inside a height range that sets the key, the range's value replaces its parts' own; a region modifier's, mesh or + // painted, applies still. + const bool range_sets = range != nullptr && own(*range) != nullptr; + json parts = json::array(); for (std::size_t i = 0; i < object.volumes.size(); ++i) { const ModelVolume& v = *object.volumes[i]; - if (v.is_model_part() || v.is_modifier()) - if (const ConfigOption* opt = own(v.config)) + if (v.is_region_modifier() || (v.is_model_part() && !range_sets)) + if (const ConfigOption* opt = own(v.config.get())) parts.push_back({{"part", int(i)}, {"value", opt->serialize()}}); } if (!parts.empty()) out["parts"] = std::move(parts); } + // A region modifier, a mesh or a painted one, that sets none of the key prints, inside it, with the region it overlaps: + // a model part's, or that of a region modifier before it in the object's list over the part (the slicer chains both + // kinds alike, and region_config_from_model_volume() starts from that region's config). Where the modifier sits is not + // worked out here, so where one of those volumes sets the key no value is the one it prints with: the object's chain + // gives one, beside the volumes that set their own. + if (volume != nullptr && volume->is_region_modifier() && range == nullptr && own(volume->config.get()) == nullptr) { + json parts = json::array(); + for (std::size_t i = 0; i < object.volumes.size() && object.volumes[i] != volume; ++i) { + const ModelVolume& v = *object.volumes[i]; + if (v.is_model_part() || v.is_region_modifier()) + if (const ConfigOption* opt = own(v.config.get())) + parts.push_back({{"part", int(i)}, {"value", opt->serialize()}}); + } + if (!parts.empty()) + out = {{"effective", nullptr}, + {"source", "overlapped_part"}, + {"object_effective", out["effective"]}, + {"object_source", out["source"]}, + {"parts", std::move(parts)}}; + } + // A height range applies over the object's parts, after their own values; a region modifier's own value applies over + // it, and inside a region modifier that sets none the range's does, its region inheriting the part's region the range + // is applied to (region_config_from_model_volume()). + const bool ranges_apply = volume == nullptr || volume->is_model_part() || + (volume->is_region_modifier() && own(volume->config.get()) == nullptr); + if (range == nullptr && ranges_apply) { + json ranges = json::array(); + for (const auto& [heights, config] : object.layer_config_ranges) + if (const ConfigOption* opt = own(config.get())) + ranges.push_back({{"min_z", heights.first}, {"max_z", heights.second}, {"value", opt->serialize()}}); + if (!ranges.empty()) + out["height_ranges"] = std::move(ranges); + } return out; } +json settings_list_page(const json& items, const json& args) +{ + return page(items, args, listed_with_meta(args) ? 100 : std::max(items.size(), 1)); +} + bool save_preset_inside_project(const PresetCollection& presets, const std::string& name, const json& args) { wxString info; @@ -1080,7 +1758,7 @@ std::vector rank_settings(const std::string& query, const std::vect const std::vector words = query_words(query); // (query words matched, those matched in the key or label) per key. std::vector, std::string>> scored; - std::set seen; // a scope's options can list a key twice + std::set seen; // a type's options can list a key twice for (const std::string& key : within) { const ConfigOptionDef* def = print_config_def.get(key); if (def == nullptr || !seen.insert(key).second) @@ -1116,7 +1794,8 @@ json variant_entries(const std::string& key, const DynamicPrintConfig& config, c id_key = "printer_extruder_id"; variant_key = "printer_extruder_variant"; stride = printer_options_with_variant_2.count(key) > 0 ? 2 : 1; - } else if (printer_extruder_options.count(key) == 0 && key != "extruder_offset") { + } else if (printer_extruder_options.count(key) == 0 && key != "extruder_offset" && + key != "nozzle_volume_type" /* the project's, read and set with the printer's settings */) { return nullptr; } json names = json::array(); @@ -1268,7 +1947,7 @@ json unsaved_changes() { json out = json::object(); for (const char* type : {"process", "filament", "printer"}) { - // What list_presets calls modified, in the settings the tab shows: the full comparison also lists + // What preset_list calls modified, in the settings the tab shows: the full comparison also lists // bookkeeping keys that only one of the two configs has. const PresetCollection& presets = collection(preset_type(type)); if (!presets.current_is_dirty()) @@ -1311,7 +1990,7 @@ json check_preset_deletable(const PresetCollection& presets, const std::string& const char* const type = presets.type() == Preset::TYPE_PRINT ? "process" : presets.type() == Preset::TYPE_FILAMENT ? "filament" : "printer"; const Preset* preset = presets.find_preset(name, false); if (preset == nullptr) - throw ToolFailure(std::string("No ") + type + " preset \"" + name + "\" (see list_presets)", {{"similar", similar_presets(presets, name)}}); + throw ToolFailure(std::string("No ") + type + " preset \"" + name + "\" (see preset_list)", {{"similar", similar_presets(presets, name)}}); // The tab's own rule (Tab::can_delete_preset()), worded for an agent. std::vector inherited_by; switch (Tab::can_delete_preset(presets, *preset, &inherited_by)) { @@ -1414,6 +2093,118 @@ std::vector check_flush_matrix(std::vector matrix, std::size_t s return matrix; } +json plate_place(PartPlate& plate) +{ + // The plate's shape on the bed, moved to where the plate list places the plate; the extended box holds the grabber + // in front of it too. + const BoundingBoxf3& box = plate.get_bounding_box(); + const auto mm = [](double v) { return std::round(v * 1000.) / 1000. + 0.; }; + return {{"origin", {mm(box.min.x()), mm(box.min.y())}}, {"size", {mm(box.size().x()), mm(box.size().y())}}}; +} + +const std::vector& plate_setting_keys() +{ + static const std::vector keys{"curr_bed_type", + "print_sequence", + "spiral_mode", + "first_layer_print_sequence", + "other_layers_print_sequence", + "filament_map_mode", + "filament_map"}; + return keys; +} + +std::string filament_map_error(const std::string& mode, const std::vector& map, int filaments, int extruders) +{ + if (mode != "Manual") + return "filament_map is a plate's own grouping, which filament_map_mode \"Manual\" takes: the automatic modes group the " + "filaments when the plate slices, and null follows the project's grouping"; + if (int(map.size()) != filaments) + return "filament_map gives one extruder per filament: " + std::to_string(filaments) + " filaments, " + + std::to_string(map.size()) + " given"; + for (const int extruder : map) + if (extruder < 1 || extruder > extruders) + return "filament_map names extruder " + std::to_string(extruder) + "; this printer has extruders 1 to " + + std::to_string(extruders); + return {}; +} + +json filter_preset_items(json items, const json& args, const std::function& fits) +{ + const bool include_incompatible = arg_bool(args, "include_incompatible", false); + const bool include_uninstalled = arg_bool(args, "include_uninstalled", false); + const std::string query = lower(arg_string(args, "query")); + const std::string vendor = lower(arg_string(args, "vendor")); + const std::string filament_type = lower(arg_string(args, "filament_type")); + const std::string source = arg_string(args, "source"); + const bool other_printer = args.contains("printer") && fits; + json out = json::array(); + for (json& item : items) { + if (other_printer) { + if (fits(item)) + item.erase("compatible"); + else + item["compatible"] = false; + } + if ((!include_incompatible && !item.value("compatible", true)) || (!include_uninstalled && !item.value("installed", true))) + continue; + if (!query.empty() && lower(item.value("name", "")).find(query) == std::string::npos && + lower(item.value("alias", "")).find(query) == std::string::npos) + continue; + if ((!vendor.empty() && lower(item.value("vendor", "")) != vendor) || + (!filament_type.empty() && lower(item.value("filament_type", "")) != filament_type)) + continue; + const bool project = item.value("project", false); + if ((source == "system" && !item.value("system", false)) || (source == "user" && (!item.value("user", false) || project)) || + (source == "project" && !project)) + continue; + out.push_back(std::move(item)); + } + return out; +} + +std::size_t extruders_count_value(const json& value, bool single_extruder_multi_material) +{ + if (single_extruder_multi_material) + throw ToolFailure("Extruder count cannot be edited in single extruder multimaterial mode (single_extruder_multi_material)"); + long long count = 0; + if (value.is_number_integer()) { + count = value.get(); + } else if (value.is_string()) { + const std::string text = value.get(); + std::size_t end = 0; + try { + count = std::stoll(text, &end); + } catch (const std::exception&) { + end = 0; + } + if (end == 0 || end != text.size()) + count = 0; + } + if (count < 1 || count > (long long) MAXIMUM_EXTRUDER_NUMBER) + throw ToolFailure("extruders_count is a whole number from 1 to " + std::to_string(MAXIMUM_EXTRUDER_NUMBER) + + ", as the Extruders field of the Printer settings takes; got " + value.dump()); + return std::size_t(count); +} + +std::string nozzle_diameter_variant(const std::vector& diameters, const std::vector& variants, + const std::string& current) +{ + if (diameters.empty()) + return {}; + const double diameter = diameters.front(); + if (std::any_of(diameters.begin(), diameters.end(), [diameter](double d) { return std::abs(d - diameter) > EPSILON; })) + return {}; + for (const std::string& variant : variants) { + // A plain diameter ("0.6"), not a named variant ("0.4 High Flow"), which shares its diameter with the plain one. + std::size_t parsed = 0; + const double value = string_to_double_decimal_point(variant, &parsed); + if (!variant.empty() && parsed == variant.size() && std::abs(value - diameter) <= EPSILON) + return variant == current ? std::string() : variant; + } + return {}; +} + std::vector filament_order(const json& order, int slots) { std::vector out; @@ -1535,29 +2326,6 @@ json changed_settings(const DynamicPrintConfig& before, const DynamicPrintConfig return changed; } -json preferences_settings(const AppConfig& config, const json& args) -{ - if (!args.contains("keys") || args.contains("query") || args.contains("preset") || args.contains("compare")) - throw ToolFailure("The preferences scope reads the keys named in keys, nothing else: it lists no preferences unasked, " - "since the app configuration also holds account and device state"); - json items = json::array(), unknown = json::array(); - for (const json& k : args["keys"]) { - std::string value; - if (config.get("app", k.get(), value)) - items.push_back({{"key", k}, {"value", value}}); - else - unknown.push_back(k); - } - json out = page(items, args, 100); - if (!unknown.empty()) { - out["unknown_keys"] = unknown; - // Many preferences are stored only once they are changed. - out["note"] = "unknown_keys are not stored: a preference never changed shows its default in the dialog (most " - "checkboxes unchecked), or the key is not a preference."; - } - return out; -} - std::string edit_filament_slot(int slot) { PresetBundle& bundle = *wxGetApp().preset_bundle; @@ -1628,27 +2396,39 @@ std::string to_config_string(const json& v, const std::string& key) namespace { -// The keys of kSearchScopes, each once, with the scope that offers it first. UI thread. -std::vector search_scope_options(std::map& scope_of) +// The keys of kSearchTypes, each once, with the type that offers it first. UI thread. +std::vector search_type_options(std::map& type_of) { std::vector options; - for (const char* scope : kSearchScopes) - for (const std::string& key : resolve_target(json{{"scope", scope}}, false).options) - if (scope_of.emplace(key, scope).second) + for (const char* type : kSearchTypes) + for (const std::string& key : resolve_target(json{{"type", type}}, false).options) + if (type_of.emplace(key, type).second) options.push_back(key); return options; } -// get_settings: the settings `args` asks for, read on the UI thread. +json read_target(const json& args, const ConfigTarget& t, bool listing = false); + +// What a call on a target other than global acted on, as every command with a target names it: the object or the part +// (objects, parts) and, for a height range, its heights (height_range). UI thread. +json target_reply(const ConfigTarget& t) +{ + json out = targets_reply(ui_plater().model(), t.named); + if (t.range) + out["height_range"] = {{"min_z", t.range->first}, {"max_z", t.range->second}}; + return out; +} + +// settings_get: the settings `args` asks for, read on the UI thread. json read_settings(const json& args) { if (int(args.contains("keys")) + int(args.contains("query")) + int(args.contains("where")) > 1) throw ToolFailure("Give one of keys, query or where"); - // A search or named keys with no scope look through kSearchScopes; each item names its scope. - if ((args.contains("query") || args.contains("keys")) && !args.contains("scope") && !args.contains("preset") && - !args.contains("compare")) { - std::map scope_of; - const std::vector options = search_scope_options(scope_of); + // A search or named keys with no type look through kSearchTypes; each item names its type. + if ((args.contains("query") || args.contains("keys")) && !args.contains("type") && arg_string(args, "target", "global") == "global" && + !args.contains("preset") && !args.contains("compare")) { + std::map type_of; + const std::vector options = search_type_options(type_of); std::vector wanted; json unknown = json::array(); if (args.contains("query")) @@ -1656,26 +2436,26 @@ json read_settings(const json& args) else for (const json& k : args["keys"]) { const std::string key = k.get(); - if (scope_of.count(key) == 0) + if (type_of.count(key) == 0) unknown.push_back(key); else if (std::find(wanted.begin(), wanted.end(), key) == wanted.end()) wanted.push_back(key); } std::map found; - for (const char* scope : kSearchScopes) { + for (const char* type : kSearchTypes) { json keys = json::array(); for (const std::string& key : wanted) - if (scope_of[key] == scope) + if (type_of[key] == type) keys.push_back(key); if (keys.empty()) continue; - json scoped = args; - scoped.erase("query"); - scoped.erase("offset"); - scoped.update({{"scope", scope}, {"keys", std::move(keys)}, {"limit", 500}}); - json read = read_settings(scoped); + json typed = args; + typed.erase("query"); + typed.erase("offset"); + typed.update({{"type", type}, {"keys", std::move(keys)}, {"limit", 500}}); + json read = read_settings(typed); for (json& item : read["items"]) { - item["scope"] = scope; + item["type"] = type; const std::string key = item["key"]; found[key] = std::move(item); } @@ -1688,18 +2468,21 @@ json read_settings(const json& args) add_unknown_keys(out, unknown); return out; } - if (arg_string(args, "scope") == "plate") - return plate_settings(args); - if (arg_string(args, "scope") == "preferences") - return preferences_settings(*wxGetApp().app_config, args); - const ConfigTarget t = resolve_target(args, false); - const bool compare = args.contains("compare"); + return read_target(args, resolve_target(args, false)); +} + +// The settings of `t` that `args` asks for: its keys, query or where, its whole listing without them (for a target +// other than global, what it overrides), or with compare what differs from another preset. `listing`: settings_list's, +// paged by settings_list_page(). A key a target does not take is refused with where it is set. UI thread. +json read_target(const json& args, const ConfigTarget& t, bool listing) +{ + const bool compare = args.contains("compare"); // A preset's whole listing, hundreds of keys, is for scanning values; what one key takes // comes with it when it is named, searched for or listed with its group. const bool whole = !args.contains("keys") && !args.contains("query") && !args.contains("where") && t.object == nullptr && !t.project; - const bool meta = arg_bool(args, "include_meta", !compare && !whole); - if ((t.object != nullptr || t.project) && (compare || args.contains("preset"))) - throw ToolFailure("preset and compare are for the process, filament and printer scopes"); + const bool meta = listing ? listed_with_meta(args) : arg_bool(args, "include_meta", !compare && !whole); + if (t.object != nullptr && (compare || args.contains("preset"))) + throw ToolFailure("preset and compare read a type's presets, which the targets object, part and height_range are not"); // An object's or part's settings are process settings, on the process tab's pages. const std::map places = t.project ? std::map() : setting_places(t.object != nullptr ? Preset::TYPE_PRINT : t.type); @@ -1719,17 +2502,26 @@ json read_settings(const json& args) groups.insert(place->second); } if (keys.empty()) - throw ToolFailure("No page or group \"" + arg_string(args, "where") + "\" in this scope", {{"groups", groups}}); + throw ToolFailure("No page or group \"" + arg_string(args, "where") + "\" in these settings", {{"groups", groups}}); } else if (t.object != nullptr) { - keys = t.config->keys(); + // What the target overrides: its own keys, a filament of 0 ("Default") being none. + for (const std::string& key : t.config->keys()) + if (key != "extruder" || t.config->opt_int("extruder") != 0) + keys.push_back(key); } else { keys = t.options; } - std::vector known; - json unknown = json::array(); + // A target's overrides are listed whatever they are; a key named for a target is one it takes. + const bool overrides = t.object != nullptr && !args.contains("keys") && !args.contains("query"); + const std::vector& process = preset_options(Preset::TYPE_PRINT); + std::vector known; + json unknown = json::array(); for (const std::string& key : keys) { - if (print_config_def.get(key) != nullptr && std::find(t.options.begin(), t.options.end(), key) != t.options.end()) + const bool defined = print_config_def.get(key) != nullptr; + if (defined && (overrides || std::find(t.options.begin(), t.options.end(), key) != t.options.end())) known.push_back(key); + else if (defined && t.object != nullptr && std::find(process.begin(), process.end(), key) != process.end()) + throw ToolFailure(untaken_setting_error(key, t.target, wxGetApp().filaments_cnt())); else unknown.push_back(key); } @@ -1765,11 +2557,13 @@ json read_settings(const json& args) out["left"] = t.preset->name + (edited ? " (edited)" : ""); out["right"] = other.name; } else { - // What an object or part prints with falls back to the process being edited, as its + // What an object, a part or a height range prints with falls back to the process being edited, as its // settings tab shows it. - const DynamicPrintConfig& process = wxGetApp().preset_bundle->prints.get_edited_preset().config; - bool part_only = false; - json items = json::array(); + const DynamicPrintConfig& global = wxGetApp().preset_bundle->prints.get_edited_preset().config; + bool part_only = false; + bool range_only = false; + bool overlapped = false; + json items = json::array(); for (const std::string& key : known) { json item{{"key", key}}; if (t.config->has(key)) @@ -1777,8 +2571,10 @@ json read_settings(const json& args) else item["value"] = nullptr; // not overridden at this level if (t.object != nullptr) { - item.update(effective_setting(key, process, *t.object, t.volume)); - part_only = part_only || item.contains("parts") || item.value("source", "") == "part"; + item.update(effective_setting(key, global, *t.object, t.volume, t.range ? t.config : nullptr)); + part_only = part_only || item.contains("parts") || item.value("source", "") == "part"; + range_only = range_only || item.contains("height_ranges") || item.value("source", "") == "height_range"; + overlapped = overlapped || item.value("source", "") == "overlapped_part"; } if (meta) add_meta(item, key); @@ -1786,21 +2582,57 @@ json read_settings(const json& args) } // A search's matches carry their descriptions, and those past the best few rarely // fit what was asked. - out = page(items, args, args.contains("query") ? 20 : 100); + out = listing ? settings_list_page(items, args) : page(items, args, args.contains("query") ? 20 : 100); + std::string note; if (part_only) - out["note"] = "A part's value (source \"part\", or in parts) applies only inside that part's volume."; + note = "A part's value (source \"part\", or in parts) applies only inside that part's volume."; + if (range_only) + note += std::string(note.empty() ? "" : " ") + + "A height range's value (source \"height_range\", or in height_ranges) applies only between its min_z and max_z."; + if (overlapped) + note += std::string(note.empty() ? "" : " ") + + "Inside a modifier, mesh or painted, that sets none of a key (source \"overlapped_part\"), the value of the " + "part it overlaps applies: that part's own in parts, else object_effective; which parts it overlaps is not " + "worked out."; + if (!note.empty()) + out["note"] = note; } + if (t.object != nullptr) + out.update(target_reply(t)); add_unknown_keys(out, unknown); return out; } +// settings_list: a type's settings, a preset's or those an object or a region takes, which read the process +// preset's values. UI thread. +json list_settings(const json& args) +{ + const std::string type = arg_string(args, "type"); + if (type != "object" && type != "region") + return read_target(args, resolve_target(args, false), true); + json process = args; + process["type"] = "process"; + ConfigTarget t = resolve_target(process, false); + // A region is a part, a modifier or a height range: what a height range takes, a part's and the layer height. + const std::vector taken = target_options(type == "object" ? "object" : "height_range", wxGetApp().filaments_cnt()); + t.options.erase(std::remove_if(t.options.begin(), t.options.end(), + [&taken](const std::string& key) { return std::find(taken.begin(), taken.end(), key) == taken.end(); }), + t.options.end()); + json out = read_target(process, t, true); + if (type == "region") + for (json& item : out["items"]) + if (item["key"] == "layer_height") + item["targets"] = json::array({"height_range"}); + return out; +} + } // namespace json search_settings(const std::string& query, std::size_t limit) { ui_plater(); // the presets and the settings pages exist once the main window does - std::map scope_of; - const std::vector options = search_scope_options(scope_of); + std::map type_of; + const std::vector options = search_type_options(type_of); const std::vector ranked = rank_settings(query, options, options.size()); const std::map types{{"process", Preset::TYPE_PRINT}, {"filament", Preset::TYPE_FILAMENT}, {"printer", Preset::TYPE_PRINTER}}; @@ -1808,12 +2640,12 @@ json search_settings(const std::string& query, std::size_t limit) json items = json::array(); for (std::size_t i = 0; i < ranked.size() && i < limit; ++i) { const std::string& key = ranked[i]; - const std::string& scope = scope_of[key]; + const std::string& type = type_of[key]; const ConfigOptionDef* def = print_config_def.get(key); - auto place = places.find(scope); + auto place = places.find(type); if (place == places.end()) - place = places.emplace(scope, setting_places(types.at(scope))).first; - json item{{"key", key}, {"scope", scope}, {"label", def->full_label.empty() ? def->label : def->full_label}}; + place = places.emplace(type, setting_places(types.at(type))).first; + json item{{"key", key}, {"type", type}, {"label", def->full_label.empty() ? def->label : def->full_label}}; if (const auto where = place->second.find(key); where != place->second.end()) item["where"] = where->second; items.push_back(std::move(item)); @@ -1821,45 +2653,113 @@ json search_settings(const std::string& query, std::size_t limit) return {{"total", ranked.size()}, {"items", std::move(items)}}; } +std::string settings_request_error(const json& args, bool writes) +{ + const std::string target = arg_string(args, "target", "global"); + const bool names = args.contains("object") || args.contains("object_id") || args.contains("part") || args.contains("part_id"); + const bool range = args.contains("min_z") || args.contains("max_z"); + if (target == "global" && names) + return "object and part name the object or part of a target: give target object, part or height_range"; + if (target != "height_range" && range) + return "min_z and max_z go with target height_range, the range of an object they name"; + if (target != "global") { + // An object's, a part's and a height range's settings are process settings. + if (const std::string type = arg_string(args, "type", "process"); type != "process") + return "The " + type + " settings have no target " + target + ": an object's, a part's or a height range's own " + "settings are process settings (type process, or no type)"; + if (target != "part" && (args.contains("part") || args.contains("part_id"))) + return "part goes with target part: target " + target + " is of an object"; + if (target == "part" && args.contains("object") != args.contains("part")) + return "target part names its part by object and part, or by neither for the part selected in Prepare"; + if (target == "height_range" && !(args.contains("min_z") && args.contains("max_z"))) + return "target height_range needs min_z and max_z, the range's heights as object_list lists them"; + } + // settings_set writes values, or takes a preset back to its saved state; settings_get reads what keys, query or + // compare names, or a target's overrides. + if (writes) { + if (!args.contains("values") && !args.contains("reset_all")) + return "Nothing is named: give values to change settings, or reset_all to discard the unsaved changes of a type's " + "preset"; + // The extruders a count adds or takes away change what the printer's other values hold. + const json values = args.value("values", json::object()); + if (values.is_object() && values.contains("extruders_count") && + (arg_string(args, "type", "process") != "printer" || values.size() > 1 || arg_bool(args, "reset_all", false))) + return "extruders_count is set alone, with type printer: the extruders it adds take their settings in a following " + "call"; + } else if (target == "global" && !args.contains("keys") && !args.contains("query") && !args.contains("compare")) { + return "Nothing is named: give keys, query or compare to read settings, or a target other than global to read what " + "it overrides; settings_list lists a type's settings"; + } + return {}; +} + void register_config_tools(CommandCatalog& catalog) { - const json plate_prop = {{"type", "integer"}, {"minimum", 0}, {"description", "Plate index (plate scope; default: the current plate)."}}; - // get_settings and set_settings take the same scopes and differ in what they do without one. - const std::vector scopes{"process", "filament", "printer", "object", "part", "project", "plate", "preferences"}; - const std::string scope_text = "Which settings: the process, filament or printer preset being edited, an " - "object's / part's own overrides, the project's own settings, a plate's, or the " - "app's preferences (read only)."; - const json read_scope_prop = enum_prop(scopes, scope_text + " Without it, keys and query look through the process, filament " - "and printer settings; anything else reads the process."); - const json write_scope_prop = enum_prop(scopes, scope_text + " Default: the process."); + const json plate_prop = {{"type", "integer"}, {"minimum", 0}, {"description", "Plate index; default: the current plate."}}; + // The settings tools' type and target, as the Process panel's Global and Objects rows choose them. + const json type_prop = enum_prop({"printer", "process", "filament"}, "Which settings: the printer, process or filament " + "preset being edited."); + const json target_prop = enum_prop({"global", "object", "part", "height_range"}, + "Where they apply: global (default), the type's preset; object, part or height_range, " + "the overrides an object, one of its parts or modifiers, or one of its height ranges " + "carries, which are process settings."); + const json object_prop = {{"type", "integer"}, + {"minimum", 0}, + {"description", "Object index from object_list (targets object, part and height_range); without it, " + "the object selected in Prepare."}}; + const json part_prop = {{"type", "integer"}, + {"minimum", 0}, + {"description", "Part index in the object (target part, with object); without both, the part selected " + "in Prepare."}}; + const json min_z_prop = {{"type", "number"}, {"minimum", 0}, {"description", "Target height_range: the range's bottom, mm."}}; + const json max_z_prop = {{"type", "number"}, {"minimum", 0}, {"description", "Target height_range: the range's top, mm."}}; + const json read_preset_prop = prop("string", "Read this saved preset of the type (a name from preset_list) instead of the one " + "being edited."); catalog.add(inspect_tool( - "api", "list_presets", L("List presets"), + "preset_list", L("List presets"), "Printer, process or filament presets, each with its name, alias (the name its selector shows, when another), " "system, user, project (kept inside the project), inherits, selected (and modified), compatible: false or " - "visible: false when so, and for a filament the slots using it (filament_slots). Only compatible, visible presets " - "unless asked: a fresh install hides most system filaments and printers, and select_preset takes a hidden one too.", + "installed: false when so, and vendor; a filament its filament_type and the slots using it (filament_slots), a " + "printer its printer_model and nozzle. Only compatible, installed presets unless asked: a fresh install leaves most " + "system filaments and printers out of the selectors, and preset_select takes such a preset too. printer lists the " + "filaments or processes that fit another printer preset, in place of the selected one.", object_schema({{"type", enum_prop({"printer", "process", "filament"}, "Preset category.")}, {"query", prop("string", "Case-insensitive part of the name or alias.")}, + {"vendor", prop("string", "A vendor, in either case: a filament's maker (\"Bambu Lab\", \"Generic\"), a " + "printer's or process's vendor bundle (\"BBL\").")}, + {"filament_type", prop("string", "Type filament: a filament type, in either case (\"PLA\").")}, + {"printer", prop("string", "Types filament and process: list what fits this printer preset (a name from " + "preset_list type printer) in place of the selected printer.")}, + {"source", enum_prop({"system", "user", "project"}, "Where the presets come from: the system's, a " + "person's own, or kept inside the project.")}, {"include_incompatible", prop("boolean", "Also list presets incompatible with the printer.")}, - {"include_hidden", prop("boolean", "Also list hidden presets.")}, + {"include_uninstalled", prop("boolean", "Also list the system presets the selectors do not offer, which " + "a person has not installed.")}, {"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 500}, {"description", "Default 100."}}}, {"offset", {{"type", "integer"}, {"minimum", 0}}}}, {"type"}), - [](const json& args, ToolContext& ctx) { return ToolResult::ok(ctx.run_ui([&] { return list_presets(args); })); })); + [](const json& args, ToolContext& ctx) { + const std::string type = arg_string(args, "type"); + if (args.contains("printer") && type == "printer") + throw ToolFailure("printer lists the filaments or processes that fit a printer preset, not printers"); + if (args.contains("filament_type") && type != "filament") + throw ToolFailure("filament_type filters filaments (type filament)"); + return ToolResult::ok(ctx.run_ui([&] { return list_presets(args); })); + })); catalog.add(reaching({"resolve_preset", "select_preset", "assign_filament_preset"}, mutate_tool( - "api", "select_preset", L("Select a preset"), + "preset_select", L("Select a preset"), "Select a printer, process or filament preset by the name its selector shows (or its internal name), as a person " - "would. A hidden one (list_presets include_hidden) is shown in the selectors first, until the app restarts; one " - "the selector leaves out as incompatible with the printer is refused. With unsaved changes the Transfer-or-discard prompt opens " + "would. One the selectors do not offer (preset_list include_uninstalled) is shown in them first, until the app " + "restarts; one the selector leaves out as incompatible with the printer is refused. With unsaved changes the Transfer-or-discard prompt opens " "(blocked_by_dialog) unless preset_changes answers it. A filament is assigned to filament_slot (1-based, default " "1); with several slots the filament tab keeps the preset and the changes it has, so nothing is asked. Reply: " - "selected, shown (a hidden preset it showed); " + "selected, shown (a preset it showed in the selectors); " "when presets had or have unsaved changes, discarded and modified list per preset the keys dropped and the keys " "still unsaved.", object_schema({{"type", enum_prop({"printer", "process", "filament"}, "Preset category.")}, - {"name", prop("string", "Preset name as list_presets shows it.")}, + {"name", prop("string", "Preset name as preset_list shows it.")}, {"filament_slot", {{"type", "integer"}, {"minimum", 1}, {"description", "Filament slot, 1-based."}}}, {"preset_changes", enum_prop({"transfer", "discard"}, "Unsaved changes of the presets the switch replaces: move " "them to the new preset or drop them, as the prompt's " @@ -1868,18 +2768,15 @@ void register_config_tools(CommandCatalog& catalog) "another type). Omitted: the prompt opens.")}}, {"type", "name"}), [](const json& args, ToolContext& ctx) { - const Preset::Type type = preset_type(arg_string(args, "type")); - const std::string name = arg_string(args, "name"); - const std::string changes = arg_string(args, "preset_changes"); + const Preset::Type type = preset_type(arg_string(args, "type")); + const std::string name = arg_string(args, "name"); + const Ops::PresetChanges answer = preset_changes_answer(args); json result = ctx.run_ui([&]() -> json { ui_plater(); const int slot = arg_int(args, "filament_slot", 1); const Ops::PresetKind kind = type == Preset::TYPE_PRINTER ? Ops::PresetKind::Printer : type == Preset::TYPE_FILAMENT ? Ops::PresetKind::Filament : Ops::PresetKind::Process; - const Ops::PresetChanges answer = changes == "transfer" ? Ops::PresetChanges::Transfer : - changes == "discard" ? Ops::PresetChanges::Discard : - Ops::PresetChanges::Ask; Ops::ResolvePresetArgs resolve; resolve.kind = kind; resolve.name = name; @@ -1914,13 +2811,13 @@ void register_config_tools(CommandCatalog& catalog) }))); NativeCommand save = mutate_tool( - "api", "save_preset", L("Save a preset"), + "preset_save", L("Save a preset"), "Save the printer, process or filament preset being edited, with its unsaved changes, as a preset called name, " "which is then selected: what the tab's Save button does through its dialog. A filament is filament_slot's " "(default 1), and every slot using the old preset takes the new one. Replacing another existing preset needs " "overwrite (pass it in replays and scripts meant to be rerun). Reply: saved, selected, user, project, inherits, " "filament_slots. A " - "temperature warning or an unsaved-changes prompt makes it blocked_by_dialog. To keep only some edits, set_settings " + "temperature warning or an unsaved-changes prompt makes it blocked_by_dialog. To keep only some edits, settings_set " "{reset_all: true, values} first.", object_schema({{"type", enum_prop({"printer", "process", "filament"}, "Preset category.")}, {"name", prop("string", "Name to save under.")}, @@ -1938,13 +2835,14 @@ void register_config_tools(CommandCatalog& catalog) ui_plater(); // The dialog shows its detach checkbox only in Developer mode. if (detach && wxGetApp().get_mode() != comDevelop) - throw ToolFailure("Detach is offered only in Developer mode; run_action orca_command:toggle_developer_mode:orca first"); + throw ToolFailure("Detach is offered only in Developer mode; turn it on first with tool_call {\"tool\": " + "\"settings_toggle_developer_mode\"}"); Tab* tab = wxGetApp().get_tab(type); if (tab == nullptr) throw ToolFailure("The settings tab is not available"); - // The filament tab edits one slot's preset; edit this slot's, as set_settings does. + // The filament tab edits one slot's preset; edit this slot's, as settings_set does. if (type == Preset::TYPE_FILAMENT) - resolve_target({{"scope", "filament"}, {"filament_slot", arg_int(args, "filament_slot", 1)}}, true); + resolve_target({{"type", "filament"}, {"filament_slot", arg_int(args, "filament_slot", 1)}}, true); PresetCollection& presets = collection(type); const bool inside_project = save_preset_inside_project(presets, name, args); // With the name given, the tab saves without opening the dialog. @@ -1975,7 +2873,7 @@ void register_config_tools(CommandCatalog& catalog) catalog.add(save); NativeCommand remove = mutate_tool( - "api", "delete_preset", L("Delete a preset"), + "preset_delete", L("Delete a preset"), "Delete a user preset or one inside the project, its file and its cloud copy, as the tab's Delete does, without " "asking. A selected preset is replaced as the tab does (its parent or the next preset). Another filament is deleted " "without changing the selection, and slots using it take the selected one; another process is selected, deleted " @@ -1983,9 +2881,9 @@ void register_config_tools(CommandCatalog& catalog) "deleted with it. Refused: system, default and bundle presets, presets others inherit from, another preset while " "the edited one of its type has unsaved changes. Deleting a selected printer or process can " "ask about other presets' unsaved changes (blocked_by_dialog). Reply: deleted, selected, filaments (per slot), " - "attached, and discarded/modified as select_preset's.", + "attached, and discarded/modified as preset_select's.", object_schema({{"type", enum_prop({"printer", "process", "filament"}, "Preset category.")}, - {"name", prop("string", "Preset name as list_presets shows it.")}, + {"name", prop("string", "Preset name as preset_list shows it.")}, {"delete_attached", prop("boolean", "A custom printer with process or filament presets made for it alone is " "refused without this: they are deleted with it, as the GUI " "deletes them.")}}, @@ -2012,10 +2910,10 @@ void register_config_tools(CommandCatalog& catalog) tab->delete_preset(false); } else if (type == Preset::TYPE_PRINTER) { // Switching to another printer and back recomputes the process and the filaments, so it is no round trip. - throw ToolFailure("\"" + name + "\" is not the selected printer; select it first with select_preset"); + throw ToolFailure("\"" + name + "\" is not the selected printer; select it first with preset_select"); } else if (presets.current_is_dirty()) { // Both routes select the edited preset again, which would drop or ask about its changes. - throw ToolFailure("The edited " + type_name + " \"" + selected + "\" has unsaved changes; save_preset or set_settings " + throw ToolFailure("The edited " + type_name + " \"" + selected + "\" has unsaved changes; preset_save or settings_set " "{reset_all: true} first"); } else if (type == Preset::TYPE_FILAMENT) { delete_unselected_filament_preset(name); @@ -2052,105 +2950,142 @@ void register_config_tools(CommandCatalog& catalog) catalog.add(remove); catalog.add(inspect_tool( - "api", "get_settings", L("Read settings"), - "Read settings: 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, range, allowed values and mode. Choose " - "them by keys; by query, a few words matched in keys, labels and descriptions, best matches first; by where, a page " - "or \"Page > Group\" (an unknown one is refused with the list of them); or by none of these, for the whole scope, " - "paged and, in a preset scope, " - "without meta. Keys the scope lacks are listed in unknown_keys, and scope_of gives the scope of those another " - "scope has.\n" - "- No scope: keys and query look through the process, filament and printer settings, and each item names its " - "scope, the one set_settings takes; anything else reads the process.\n" - "- process, filament, printer: the preset being edited, or with preset a saved one; compare lists only " - "the keys that differ from another preset (value and other). A per-variant value lists in meta its variants (what " - "each entry is for) and active (the entry each extruder prints with).\n" - "- object, part: listed whole, the overrides that object or part carries; keys, query and where read any process " - "setting there. Each has effective (the value it prints with) and " - "source (part, object, process or default); an object's item lists in parts the parts and modifiers that override " - "the key inside their own volume.\n" - "- project: the plate type, slot colours, flushing volumes, purge mode, prime tower position per plate, mixed slots " - "and, with several extruders, the filament grouping; meta.offered lists the choices this printer has.\n" - "- plate: a plate's curr_bed_type, print_sequence, spiral_mode, first_layer_print_sequence, " - "other_layers_print_sequence, name and locked, each with value (the plate's own, null where it follows the global " - "setting or Auto) and effective.\n" - "- preferences: the named keys of the app configuration (the Preferences dialog's settings, keys as its controls " - "are named), as stored; it lists none unasked.", - object_schema({{"scope", read_scope_prop}, + "settings_list", L("List settings"), + "All the settings of a type in one reply, each item with its value as OrcaSlicer writes it, and without meta unless " + "include_meta. process, printer and filament: the preset being edited, or with preset a saved one, or with " + "filament_slot a slot's. object: the process settings an object or an assembly takes; region: those a part, a " + "modifier or a height range takes, whose layer_height item has targets [\"height_range\"], a height range alone " + "taking it; in both, each with the process preset's value, which an object or a region prints with unless it " + "sets its own. With where, the settings of one settings page or \"Page > Group\" (an unknown one is refused with " + "the list of them). Items with meta, which where gives them, come 100 a page. settings_get reads the settings " + "named or searched for, and what an object, a part or a height range overrides.", + object_schema({{"type", enum_prop({"process", "printer", "filament", "object", "region"}, + "Which settings: a preset's, or those an object or a region takes.")}, + {"where", prop("string", "A settings page, or \"Page > Group\" as meta.where gives it, e.g. " + "\"Strength > Walls\".")}, + {"preset", prop("string", "Read this saved preset (a name from preset_list) instead of the one being " + "edited: of the type, or for object and region a process preset.")}, + {"filament_slot", {{"type", "integer"}, {"minimum", 1}, + {"description", "Type filament: the slot whose preset is read, 1-based (default 1), with " + "its unsaved changes when the filament tab is editing it."}}}, + {"include_meta", prop("boolean", "Include labels, types and ranges. Default false, true with where.")}, + {"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 500}, + {"description", "Default: all of them, or 100 with meta."}}}, + {"offset", {{"type", "integer"}, {"minimum", 0}}}}, + {"type"}), + [](const json& args, ToolContext& ctx) { + return ToolResult::ok(ctx.run_ui([&] { + ui_plater(); // the presets and the settings pages exist once the main window does + return list_settings(args); + })); + })); + + catalog.add(inspect_tool( + "settings_get", L("Read settings"), + "Read the settings named or searched for: 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, range, " + "allowed values and mode. Choose them by keys, or by query, a few words matched in keys, labels and descriptions, " + "best matches first. Keys the settings lack are listed in unknown_keys, and type_of gives where each of those is a " + "setting elsewhere (a type, or project for the project's own settings). It needs keys, query, compare or a target " + "other than global; settings_list lists all of a type's settings.\n" + "- No type: keys and query look through the process, filament and printer settings, and each item names its " + "type, the one settings_set takes; otherwise the type is the process.\n" + "- type printer, process or filament (target global): the preset being edited, or with preset a saved one; " + "compare lists only the keys that differ from another preset (value and other). A per-variant value lists in meta " + "its variants (what each entry is for) and active (the entry each extruder prints with).\n" + "- target object (object), part (object and part) or height_range (object, min_z and max_z), the object or part " + "selected in Prepare where none is named: without keys, what it overrides; keys and query read the process " + "settings it takes (settings_list type object or region lists them) and extruder, its filament, and a key it does " + "not take is refused with where it is set. Each has value (its own, null where it has none), effective (the " + "value it prints with) and source, in the order the slicer applies them: height_range, part, object, global or " + "default; an object's item lists in parts the parts and modifiers that override the key inside their own volume, " + "and an object's or a part's item lists in height_ranges the ranges whose value applies to it between their " + "heights. Inside a modifier, mesh or painted, that sets none of a key, the value of the part it overlaps applies, " + "which the command does not work out: where a part (or a modifier of either kind before it) sets the key, the " + "modifier's item has effective null, source overlapped_part, object_effective and object_source (the object's " + "value), and in parts those that set it. These settings are process settings. The reply names the target (objects or parts, and " + "height_range).\n" + "preferences_get reads the app's preferences, plate_get_settings a plate's settings and project_get_settings the " + "project's own.", + object_schema({{"type", type_prop}, + {"target", target_prop}, {"keys", array_prop({{"type", "string"}}, "Option keys, e.g. [\"layer_height\", \"wall_loops\"].")}, {"query", prop("string", "A few distinctive words, e.g. \"stringing\" or \"ooze travel\"; the best 20 " "matches unless limit says otherwise.")}, - {"where", prop("string", "A settings page, or \"Page > Group\" as meta.where gives it, e.g. " - "\"Strength > Walls\".")}, - {"object", {{"type", "integer"}, {"minimum", 0}, {"description", "Object index (object/part scope)."}}}, - {"part", {{"type", "integer"}, {"minimum", 0}, {"description", "Part index (part scope)."}}}, - {"plate", plate_prop}, + {"object", object_prop}, + {"part", part_prop}, + {"min_z", min_z_prop}, + {"max_z", max_z_prop}, {"filament_slot", {{"type", "integer"}, {"minimum", 1}, - {"description", "Filament scope: the slot whose preset is read, 1-based (default 1), with " + {"description", "Type filament: the slot whose preset is read, 1-based (default 1), with " "its unsaved changes when the filament tab is editing it."}}}, - {"preset", prop("string", "Preset scopes: read this saved preset (a name from list_presets) instead of the " - "one being edited.")}, - {"compare", prop("string", "Preset scopes: a preset name, \":saved\" (the unsaved changes) or \":parent\" " + {"preset", read_preset_prop}, + {"compare", prop("string", "Target global: a preset name, \":saved\" (the unsaved changes) or \":parent\" " "(the preset it inherits from).")}, - {"include_meta", prop("boolean", "Include labels, types and ranges. Default true, false for a preset " - "scope's whole listing and with compare.")}, + {"include_meta", prop("boolean", "Include labels, types and ranges. Default true, false with compare.")}, {"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 500}, {"description", "Default 100, or 20 with query."}}}, {"offset", {{"type", "integer"}, {"minimum", 0}}}}), [](const json& args, ToolContext& ctx) { + // Refused before the UI is asked for anything: what the arguments alone decide. + if (const std::string err = settings_request_error(args); !err.empty()) + throw ToolFailure(err); return ToolResult::ok(ctx.run_ui([&] { ui_plater(); // the presets and the settings pages exist once the main window does return read_settings(args); })); })); - catalog.add(reaching({"set_plate_locked"}, with_expected_ids(mutate_tool( - "api", "set_settings", L("Change settings"), - "Change settings of one scope (default the process) as typing them into its settings tab would. Values are strings " - "in OrcaSlicer's format (\"15%\", \"0.2\", \"1,2\") or JSON numbers, booleans and arrays (a point as [x, y]). All are " - "parsed strictly first and applied together, so nothing changes if one is invalid, and a key of another scope is " - "refused with that scope named. Reply: applied, and changed, every setting the call changed, including those the " - "app adjusted in turn. An object's, part's or plate's change is one undo step; a preset's is not in the undo " - "history. Spiral vase and a few others confirm their adjustments in a dialog (blocked_by_dialog).\n" - "- process, filament, printer: null takes a key back to its saved value, or with reset_to parent to the " - "parent's; reset_all first discards every unsaved change, as the tab's undo button does (reply: reverted). A " - "per-variant value (get_settings meta.variants) takes one value for the entries in use (meta.active), {index, " - "value} for one entry, or an array of all.\n" - "- object, part: overrides of the keys the object list offers there; null removes one. extruder is the object's " - "or part's filament (1-based; 0 or null for Default), set as the Change Filament menu does.\n" - "- project, as the sidebar's controls write them: curr_bed_type, filament_colour (#RRGGBB per slot), " - "flush_multiplier, flush_volumes_matrix, prime_volume_mode, and wipe_tower_x/y (mm from the plate's origin, one per " - "plate). flush_volumes_matrix is per nozzle, slots x slots from row to column, in config order over every slot, " - "before the multiplier; a mixed slot's entries must be given as they are, and a colour change can recalculate it, " - "so set it last.\n" - "- plate, which it selects and writes as the Plate Settings dialog's OK does: curr_bed_type, print_sequence (\"by " - "layer\", \"by object\"), spiral_mode (true asks for confirmation), first_layer_print_sequence (every slot once, " - "e.g. [2, 1]), other_layers_print_sequence ([{from: layer >= 2, to, order}], to omitted for the last layer), name " - "and locked; null returns a value to the global setting or Auto.", - object_schema({{"scope", write_scope_prop}, + catalog.add(with_expected_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 an object, a part or a height range carries (targets object, part and height_range, whose settings " + "are process settings). Values " + "are strings in OrcaSlicer's format (\"15%\", \"0.2\", \"1,2\") or JSON numbers, booleans and arrays (a point as " + "[x, y]). All are parsed strictly first and applied together, so nothing changes if one is invalid, and a key of " + "another type is refused with that type named. Reply: applied, and changed, every setting the call changed, " + "including those the app adjusted in turn. An object's or part's change is one undo step; a preset's is not in the " + "undo history. Spiral vase and a few others confirm their adjustments in a dialog (blocked_by_dialog).\n" + "- type printer, process (the default) or filament, target global: null takes a key back to its saved value, or " + "with reset_to parent to the parent's; reset_all first discards every unsaved change, as the tab's undo button " + "does (reply: reverted). A per-variant value (settings_get meta.variants) takes one value for the entries in use " + "(meta.active), {index, value} for one entry, or an array of all.\n" + "- type printer: extruders_count, alone, as the Extruders field of the Printer settings sets it; " + "nozzle_volume_type, each extruder's nozzle flow type as its card in the sidebar picks it; a nozzle_diameter that a " + "variant of the printer model has selects that variant's printer preset, as the sidebar's nozzle diameter does, with " + "nozzle_volume_type alone (other keys go in a second call), each flow type checked against what the new preset's " + "nozzle card offers, or gives where it offers none. The switch asks about the printer's unsaved changes " + "(blocked_by_dialog) unless reset_all discards them first; the discard stays if the switch is not made.\n" + "- target object (object), part (object and part) or height_range (object, min_z and max_z), the object or part " + "selected in Prepare where none is named: overrides of the keys its row offers there (settings_list type object or " + "region), and extruder; a key it does not take is refused with where it is set. null removes one; a height range " + "keeps its layer_height, which is checked against the printer's layer heights for the range's filament. extruder, " + "in neither list, is the target's filament (1-based; 0 or null for Default, the object's), set as the Change " + "Filament menu does. The reply names the target (objects or parts, and height_range).\n" + "plate_set_settings changes a plate's settings and project_set_settings the project's own. preferences_set changes " + "the app's preferences; those it refuses (preferences_get marks them refused) change in the Preferences dialog, " + "whose controls carry their effects: window_open {\"window\": \"preferences\", \"tab\": \"\", \"key\": " + "\"\"}, then widget_set_value {\"target\": {\"name\": \"\", \"within\": \"Preferences\"}, \"value\": " + "...}.", + object_schema({{"type", type_prop}, + {"target", target_prop}, {"values", {{"type", "object"}, {"description", "{key: value}, or {key: {index, value}} for one entry"}}}, - {"reset_all", prop("boolean", "Preset scopes: discard the unsaved changes before applying values.")}, - {"reset_to", enum_prop({"saved", "parent"}, "Preset scopes: what a null value takes a key back to: the " + {"reset_all", prop("boolean", "Target global: discard the unsaved changes before applying values.")}, + {"reset_to", enum_prop({"saved", "parent"}, "Target global: what a null value takes a key back to: the " "saved preset (default) or the preset it inherits from.")}, - {"object", {{"type", "integer"}, {"minimum", 0}, {"description", "Object index (object/part scope)."}}}, - {"part", {{"type", "integer"}, {"minimum", 0}, {"description", "Part index (part scope)."}}}, + {"object", object_prop}, + {"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")}, - {"plate", plate_prop}, {"filament_slot", {{"type", "integer"}, {"minimum", 1}, - {"description", "Filament scope: the slot whose preset is changed, 1-based (default 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 " "changes it holds (blocked_by_dialog)."}}}}), [](const json& args, ToolContext& ctx) { - // A preference's control carries its effects (theme, language, network, this server's own port), which - // writing the key would skip. - if (arg_string(args, "scope") == "preferences") - throw ToolFailure("Preferences change in the Preferences dialog: run_action orca_command:open_preferences:orca " - "with args {\"tab\": \"\", \"key\": \"\"}, then set_widget_value {\"target\": {\"name\": \"\", \"within\": " - "\"Preferences\"}, \"value\": ...}"); - if (arg_string(args, "scope") == "project") - return set_project_settings(args, ctx); - if (arg_string(args, "scope") == "plate") - return set_plate_settings(args, ctx); + // Refused before the UI is asked for anything: what the arguments alone decide. + if (const std::string err = settings_request_error(args, /*writes=*/true); !err.empty()) + throw ToolFailure(err); const json values_in = args.value("values", json::object()); const bool reset_all = arg_bool(args, "reset_all", false); if (values_in.empty() && !reset_all) @@ -2161,27 +3096,32 @@ void register_config_tools(CommandCatalog& catalog) ui_plater(); const ConfigTarget t = resolve_target(args, true); if ((reset_all || args.contains("reset_to")) && t.object != nullptr) - throw ToolFailure(std::string(reset_all ? "reset_all" : "reset_to") + " is for preset scopes; here a null value removes an override"); + throw ToolFailure(std::string(reset_all ? "reset_all" : "reset_to") + " is for a type's preset; on a target a null value removes an override"); // What a null value takes a preset's key back to: its saved value, as the key's undo arrow does, // or the parent's, as its lock icon does. const Preset* reference = t.object != nullptr ? nullptr : arg_string(args, "reset_to", "saved") == "parent" ? &compare_preset(t, ":parent") : &collection(t.type).get_selected_preset(); + const DynamicPrintConfig before = *t.config; + if (t.type == Preset::TYPE_PRINTER && t.object == nullptr && values_in.contains("extruders_count")) + return set_extruders_count(args, before); // A preset's value is checked against what it will replace: after reset_all, the saved preset. const DynamicPrintConfig& basis = reset_all ? collection(t.type).get_selected_preset().config : *t.config; const auto extruders = printer_extruders(); - const DynamicPrintConfig before = *t.config; std::vector> values; std::vector removals; + const std::vector& process = preset_options(Preset::TYPE_PRINT); for (auto it = values_in.begin(); it != values_in.end(); ++it) { if (std::find(t.options.begin(), t.options.end(), it.key()) == t.options.end()) { json similar{{"similar", search_keys(it.key().substr(0, std::max(3, it.key().size() / 2)), t.options, 5)}}; - if (t.object != nullptr && print_config_def.get(it.key()) != nullptr) - throw ToolFailure("The object list does not offer \"" + it.key() + "\" for " + - (t.volume != nullptr ? "a part or modifier" : "an object"), - std::move(similar)); - throw unknown_setting(it.key(), arg_string(args, "scope", "process"), std::move(similar)); + // A process setting the target does not take is set where its rows offer it. + if (t.object != nullptr && std::find(process.begin(), process.end(), it.key()) != process.end()) + throw ToolFailure(untaken_setting_error(it.key(), t.target, wxGetApp().filaments_cnt()), std::move(similar)); + throw unknown_setting(it.key(), arg_string(args, "type", "process"), std::move(similar)); } + // A height range's row shows its layer height, which it always has. + if (it.value().is_null() && t.range && it.key() == "layer_height") + throw ToolFailure("A height range keeps its layer_height; give it another value"); if (it.value().is_null() && reference != nullptr) { if (!reference->config.has(it.key())) throw ToolFailure("\"" + reference->name + "\" has no " + it.key()); @@ -2212,19 +3152,28 @@ void register_config_tools(CommandCatalog& catalog) Tab* tab = wxGetApp().get_tab(t.type); if (tab == nullptr) throw ToolFailure("The settings tab is not available"); + // Every value is checked before the first change: the nozzle cards' picks, then the rest parsed. + const NozzlePicks nozzles = t.type == Preset::TYPE_PRINTER ? nozzle_picks(values, *t.config) : NozzlePicks(); + parse_values(); if (reset_all) { - parse_values(); reverted = collection(t.type).current_dirty_options(); tab->on_roll_back_value(); } + if (t.type == Preset::TYPE_PRINTER) + pick_nozzles(nozzles, reset_all && !reverted.empty()); try { - tab->apply_preset_config_values(values); + if (!values.empty()) + tab->apply_preset_config_values(values); } catch (const std::exception& e) { throw ToolFailure(e.what()); } } else { DynamicPrintConfig scratch = parse_values(); check_filament_numbers(scratch); + if (t.range) + check_height_range_layer_height(scratch, *t.config, [](int extruder) { + return std::make_pair(get_min_layer_height(extruder), get_max_layer_height(extruder)); + }); // The filament goes through the object list's Change Filament, as a person sets it; // null is its "Default" (0). const bool set_extruder = scratch.has("extruder") || @@ -2239,12 +3188,16 @@ void register_config_tools(CommandCatalog& catalog) Plater::SingleSnapshot single(&plater); if (!scratch.empty() || !removals.empty()) { plater.take_snapshot("Change object settings"); - ModelConfig& cfg = t.volume != nullptr ? static_cast(t.volume->config) : static_cast(t.object->config); + ModelConfig& cfg = t.range ? t.object->layer_config_ranges.at(*t.range) : + t.volume != nullptr ? static_cast(t.volume->config) : + static_cast(t.object->config); for (const std::string& key : scratch.keys()) cfg.set_key_value(key, scratch.option(key)->clone()); for (const std::string& key : removals) cfg.erase(key); - wxGetApp().obj_list()->object_config_options_changed(ObjectVolumeID{t.object, t.volume}); + // The row of the object, the part or the height range shows whether it has settings of its own. + wxGetApp().obj_list()->object_config_options_changed(ObjectVolumeID{t.object, t.volume}, + t.range ? &*t.range : nullptr); plater.changed_object(t.object_index); } if (set_extruder) { @@ -2253,39 +3206,367 @@ void register_config_tools(CommandCatalog& catalog) wxGetApp().obj_list()->set_extruder_for_items(rows, extruder); } } - const ConfigTarget after = resolve_target(args, false); + // A preset's settings are read again, which a printer's nozzle flow types are copied into; a target's are + // its own, changed in place. + const ConfigTarget reread = t.object == nullptr ? resolve_target(args, false) : ConfigTarget(); + const DynamicPrintConfig& after = t.object == nullptr ? *reread.config : *t.config; json applied = json::object(); - for (const auto& [key, value] : values) - applied[key] = after.config->has(key) ? json(after.config->opt_serialize(key)) : json(); + for (auto it = values_in.begin(); it != values_in.end(); ++it) + applied[it.key()] = after.has(it.key()) ? json(after.opt_serialize(it.key())) : json(); for (const std::string& key : removals) applied[key] = nullptr; - json out{{"applied", applied}, {"changed", changed_settings(before, *after.config)}}; + json out{{"applied", applied}, {"changed", changed_settings(before, after)}}; if (reset_all) out["reverted"] = std::move(reverted); - if (values_in.contains("extruder")) { + if (values_in.contains("extruder") && t.object != nullptr) { // A single-part object shows no part row; its filament is the object's. - const bool on_object = after.volume != nullptr && after.object->volumes.size() == 1; - const DynamicPrintConfig& cfg = on_object ? after.object->config.get() : *after.config; + const bool on_object = t.volume != nullptr && t.object->volumes.size() == 1; + const DynamicPrintConfig& cfg = on_object ? t.object->config.get() : after; out["applied"]["extruder"] = cfg.has("extruder") ? json(cfg.opt_serialize("extruder")) : json(); if (on_object) out["note"] = "A single-part object's filament is the object's; it was set there."; } + if (t.object != nullptr) + out.update(target_reply(t)); return out; }); settle(ctx); return ToolResult::ok(result); - })))); + }))); catalog.add(inspect_tool( - "api", "list_plates", L("List plates"), - "Plates with name, locked, current, objects (how many are on it; list_objects lists them), and the settings they print with: curr_bed_type, " - "print_sequence, spiral_mode, first_layer_print_sequence and other_layers_print_sequence (null: Auto); overrides " - "lists those the plate sets itself (set_settings scope plate). Also sliced (an up-to-date slice), wipe_tower [x, y] " + "plate_get_settings", L("Read a plate's settings"), + "Read a plate's own settings, as the Plate Settings dialog sets them: curr_bed_type, print_sequence, spiral_mode, " + "first_layer_print_sequence and other_layers_print_sequence; and as its filament grouping sets them on a printer " + "with several extruders: filament_map_mode and filament_map (the extruder of each filament, 1-based). Each with " + "value (the plate's own, null where it follows the global setting or Auto), effective (what the plate prints with) " + "and meta (meta.offered lists the plate types or grouping modes this printer has). All of them, or those named in " + "keys. Reply: plate, items; unknown_keys for the keys a plate does not have.", + object_schema({{"plate", plate_prop}, + {"keys", array_prop({{"type", "string"}}, "Setting keys, e.g. [\"curr_bed_type\"].")}, + {"include_meta", prop("boolean", "Include labels, types and ranges. Default true.")}}), + [](const json& args, ToolContext& ctx) { + return ToolResult::ok(ctx.run_ui([&] { + ui_plater(); + return plate_settings(args); + })); + })); + + catalog.add(mutate_tool( + "plate_set_settings", L("Change a plate's settings"), + "Change a plate's own settings, which it selects and writes as the Plate Settings dialog's OK does: curr_bed_type, " + "print_sequence (\"by layer\", \"by object\"), spiral_mode (true asks for confirmation), first_layer_print_sequence " + "(every slot once, e.g. [2, 1]) and other_layers_print_sequence ([{from: layer >= 2, to, order}], to omitted for " + "the last layer); and as the OK of its filament grouping does, with several extruders: filament_map_mode (an " + "offered mode) and, with \"Manual\", filament_map (one extruder per filament, e.g. [1, 2, 2]; on a printer whose " + "extruder holds several nozzles, refused as the dialog refuses it where an extruder it uses has no nozzle of the " + "volume type its filaments print with). null returns a value to the global setting or Auto. Values are checked " + "before anything changes, and the call is one undo step. Reply: plate, applied, changed, and effective for the " + "settings the plate prints with.", + object_schema({{"plate", plate_prop}, + {"values", {{"type", "object"}, {"description", "{key: value}"}}}}, + {"values"}), + [](const json& args, ToolContext& ctx) { return set_plate_settings(args, ctx); })); + + catalog.add(inspect_tool( + "project_get_settings", L("Read the project's settings"), + "Read the settings the project stores outside any preset: the plate type (curr_bed_type), slot colours " + "(filament_colour), flushing volumes (flush_volumes_matrix, flush_multiplier), purge mode (prime_volume_mode), " + "prime tower position per plate (wipe_tower_x, wipe_tower_y), mixed slots (filament_is_mixed) and, with several " + "extruders, the filament grouping (filament_map_mode, filament_map); all of them, or those named in keys. Each item " + "has its value and meta; meta.offered lists the choices this printer has, and meta.read_only marks what is set " + "elsewhere.", + object_schema({{"keys", array_prop({{"type", "string"}}, "Setting keys, e.g. [\"filament_colour\"].")}, + {"include_meta", prop("boolean", "Include labels, types and ranges. Default true.")}}), + [](const json& args, ToolContext& ctx) { + return ToolResult::ok(ctx.run_ui([&] { + ui_plater(); + return read_target(args, project_target()); + })); + })); + + catalog.add(mutate_tool( + "project_set_settings", L("Change the project's settings"), + "Change the project's own settings as the sidebar's controls write them: curr_bed_type, filament_colour (#RRGGBB " + "per slot), flush_multiplier, flush_volumes_matrix, prime_volume_mode, and wipe_tower_x/y (mm from the plate's " + "origin, one per plate). flush_volumes_matrix is per nozzle, slots x slots from row to column, in config order over " + "every slot, before the multiplier; a mixed slot's entries must be given as they are, and a colour change can " + "recalculate it, so set it last. Values are checked before anything changes; a prime tower move is one undo step. " + "Reply: applied, changed, and a note when the app moved a prime tower that did not fit.", + object_schema({{"values", {{"type", "object"}, {"description", "{key: value}, or {key: {index, value}} for one entry"}}}}, + {"values"}), + [](const json& args, ToolContext& ctx) { return set_project_settings(args, ctx); })); + + catalog.add(inspect_tool( + "plate_list", L("List plates"), + "Plates with name, locked, current, objects (how many are on it; object_list lists them), and the settings they print with: curr_bed_type, " + "print_sequence, spiral_mode, first_layer_print_sequence and other_layers_print_sequence (null: Auto), with several " + "extruders filament_map_mode and filament_map; overrides " + "lists those the plate sets itself (plate_set_settings). Also origin and size, the plate's place on the bed in " + "mm: the [x, y] of its front left corner and its [width, depth], in the bed coordinates object positions are " + "given in, so that origin plus half the size is its middle; sliced (an up-to-date slice), wipe_tower [x, y] " "and layer_gcode: the plate's pauses, custom G-code, templates and filament changes, each {z, layer, type, " "filament, color, gcode}; layer is the Preview slider's number, given while the plate's slice is up to date.", object_schema({{"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 500}, {"description", "Default 100."}}}, {"offset", {{"type", "integer"}, {"minimum", 0}}}}), [](const json& args, ToolContext& ctx) { return ToolResult::ok(ctx.run_ui([&] { return list_plates(args); })); })); + + // The plate commands made from menu rows: each acts on the plate the call names, else on the current plate, as its row + // does, and its reply names the plate. A command named as its row is that row's tile, in the Speed Dial's section + // `section`. + const auto own_tile = [](NativeCommand command, std::string section, std::string icon) { + command.in_palette = true; + command.tile_group = std::move(section); + command.icon = std::move(icon); + return command; + }; + const std::string plates_after = "plates (each plate afterwards: index, name and objects, how many stand on it) and current " + "(the current plate)"; + catalog.add(own_tile(row_command("plate_add", L("Add Plate"), "Add a plate.", object_schema({}), json(), + [](const json&) { return Rows::plate_add(); }), + L("Plate"), "toolbar_add_plate")); + catalog.add(reaching({"delete_plate"}, + own_tile(row_command("plate_delete", L("Delete Plate"), + "Delete a plate (plate, else the current one), as Delete Plate does. The objects on it " + "stay in the project, outside the plates, and the plates after it move down one. The " + "only plate is refused. One undo step. Reply: plate (the index it had), " + + plates_after + ".", + object_schema({{"plate", plate_prop}}), json(), plate_delete_command), + L("Plate"), "delete"))); + catalog.add(reaching({"duplicate_plate"}, + own_tile(row_command("plate_duplicate", L("Duplicate Plate"), + "Add a plate with a copy of each object on the plate (plate, else the current one), " + "placed on it as on that plate, as Duplicate Current Plate does. The new " + "plate comes last, and the current plate stays current. Refused when the project " + "holds as many plates as it can, and while slicing. One undo step. Reply: plate (the " + "plate copied), new_plate (the new plate's index), " + + plates_after + ".", + object_schema({{"plate", plate_prop}}), json(), plate_duplicate_command), + L("Plate"), "menu_copy"))); + // The name dialog's name, which every call but the tile's gives. + NativeCommand rename = own_tile(row_command("plate_rename", L("Rename Plate"), + "Name a plate (plate, else the current one), as its name icon does: a plate other " + "than the current one is made current first. name \"\" leaves it unnamed. With no " + "arguments, as its tile, the name dialog asks for the current plate's name " + "(blocked_by_dialog), and a cancelled dialog renames nothing, which the call is " + "told. The name is one undo step; the name the plate has already changes nothing, " + "the current plate included. Reply: plate and name.", + object_schema({{"plate", plate_prop}, + {"name", prop("string", "The plate's name, in place of the name dialog.")}}, + {"name"}), + json(), plate_rename_command), + L("Plate"), "plate_name_edit"); + rename.input_schema = with_silent(std::move(rename.input_schema), person_forms(rename)); + catalog.add(reaching({"rename_plate", "select_plate"}, std::move(rename))); + catalog.add(reaching( + {"set_plate_locked"}, + row_command("plate_lock", L("Toggle Plate Lock"), + "Lock or unlock a plate (plate, else the current one), as its lock icon does: locked true locks it and false " + "unlocks it; without locked it toggles, as its tile does. An arrange of every plate leaves a locked one as " + "it is. One undo step, none when the plate is in that state already. Reply: plate, locked, and changed " + "(false when it was so already).", + object_schema({{"plate", plate_prop}, + {"locked", prop("boolean", "true locks the plate, false unlocks it. Default: the other state.")}}), + json::array({NativeCommands::tile("plate_toggle_lock", L("Toggle Plate Lock"), L("Plate"), "lock_normal", json::object(), + "Lock or unlock the current plate.")}), + plate_lock_command))); + catalog.add(reaching( + {"select_plate"}, + row_command("plate_select", L("Go to Plate"), + "Make a plate the current one, as a click on it does: plate; without it, the current plate stays current. " + "An index the project lacks is an error. Reply: plate.", + object_schema({{"plate", plate_prop}}), + json::array({NativeCommands::tile("plate_goto", L("Go to Plate"), L("Plate"), "go_next_plate", {{"plate", 0}}, + "Make the first plate the current one.")}), + plate_select_command))); + + // ---- The presets and settings commands made from menu rows ---- + using NativeCommands::tile; + const std::string preset_file = "a preset .json, a .zip of them, an .orca_printer, .orca_filament or .orca_bundle, or a .gcode"; + const std::string imported = "and the message names the presets imported, replaced and kept; a .gcode loads the settings it was " + "sliced with."; + NativeCommand import_configs = reaching( + {"import_presets"}, + row_command("preset_import", L("Import Configs"), + "Import presets from " + preset_file + " by absolute path, without a dialog, " + imported + + " Called with no arguments it is Import Configs: the file dialog asks for the file (blocked_by_dialog).", + object_schema({{"path", Rows::input_file(preset_file.c_str())}, + {"on_conflict", enum_prop({"skip", "overwrite"}, "What happens to a preset that exists already. Default skip.")}}, + {"path"}), + json::array({tile("import_configs", L("Import Configs"), L("Import"), "menu_open", json::object(), + "Import presets from the file a dialog asks for. preset_import with a path imports " + preset_file + + " without a dialog, " + imported)}), + [](const json& args) { return Rows::import_configs(args); })); + import_configs.input_schema = with_silent(std::move(import_configs.input_schema), person_forms(import_configs)); + catalog.add(std::move(import_configs)); + + // Ruling 16: the dialog opens on every call, and the caller answers it. + const std::string export_dialog = "Export presets as a bundle or ZIP archives through the Export Preset Bundle dialog: click the " + "label of the kind to export, check its rows (each named after a printer preset or a " + "filament), press OK, then answer the result message."; + catalog.add(row_command( + "preset_export", L("Export Preset Bundle"), + export_dialog + " Every call opens the dialog (blocked_by_dialog). With path, OK writes into that folder instead of " + "asking for one, and a cancelled dialog is an error: nothing was exported.", + object_schema({{"path", prop("string", "Absolute path of an existing folder, which the dialog's OK writes into.")}}), + json::array({tile("export_config", L("Export Preset Bundle"), L("Export"), "save", json::object(), + export_dialog + " preset_export with a folder as path has OK write there instead of asking for one.")}), + [](const json& args) { return Rows::export_config(args); })); + + const std::string sync = "Synchronize user presets with the cloud account."; + NativeCommand preset_sync = reaching({"sync_presets"}, + row_command("preset_sync", L("Sync Presets"), sync + " Refused while no account is signed in.", + object_schema({}), + json::array({tile("sync_presets", L("Sync Presets"), L("Presets"), "printer_sync_ok", + json::object(), sync)}), + preset_sync_command)); + // It reaches the cloud account. + preset_sync.open_world = true; + catalog.add(std::move(preset_sync)); + + const std::string migrate = "Migrate legacy user filament presets."; + catalog.add(row_command("preset_migrate_filaments", L("Migrate Filament Presets"), migrate, object_schema({}), + json::array({tile("help_migrate_filament_presets", L("Migrate Filament Presets"), L("Help"), "", + json::object(), migrate)}), + [](const json&) { return Rows::migrate_filament_presets(); })); + + // The Mode rows; titles are L("...")-marked here so xgettext extracts them. + struct ModeRow + { + const char* key; + const char* title; + const char* mode; + const char* name; + }; + static const ModeRow mode_rows[] = {{"mode_simple", L("Mode: Simple"), "simple", "Simple"}, + {"mode_advanced", L("Mode: Advanced"), "advanced", "Advanced"}, + {"mode_expert", L("Mode: Expert"), "expert", "Expert"}}; + json mode_tiles = json::array(); + for (const ModeRow& row : mode_rows) + mode_tiles.push_back(tile(row.key, row.title, L("Mode"), "advanced", {{"mode", row.mode}}, + std::string("Switch the settings view to ") + row.name + " mode.")); + catalog.add(row_command("settings_set_mode", L("Set the settings mode"), + "Switch the settings view to Simple, Advanced or Expert mode, which decides which settings the settings " + "pages show.", + object_schema({{"mode", enum_prop({"simple", "advanced", "expert"}, "The mode.")}}, {"mode"}), + std::move(mode_tiles), [](const json& args) { return Rows::set_mode(arg_string(args, "mode")); })); + + const std::string developer = "Turn Developer mode on or off."; + NativeCommand developer_mode = row_command("settings_toggle_developer_mode", L("Toggle Developer Mode"), developer, object_schema({}), + json::array({tile("toggle_developer_mode", L("Toggle Developer Mode"), L("Mode"), + "advanced", json::object(), developer)}), + [](const json&) { return Rows::toggle_developer_mode(); }); + // A menu row with no argument form: tool_search finds it and tool_call runs it, the tool list does not show it. + developer_mode.listed = false; + catalog.add(std::move(developer_mode)); + + // ---- The filament slot and printer commands made from menu rows ---- + // The + and - buttons above the filament list and a slot's Delete menu item, each named as its row, in the Speed + // Dial's section Filament. + const std::string slot_buttons = "Refused for a printer that has one filament per extruder, which shows no + and - buttons."; + catalog.add(reaching({"add_filament_slot"}, + own_tile(row_command("filament_add", L("Add Filament Slot"), + "Add a filament slot, as the + button above the filament list does. It takes the next " + "colour and the last slot's preset (change them with preset_select filament_slot and " + "project_set_settings filament_colour). It goes after the physical slots: mixed " + "filaments move up by one, and objects on them follow. " + + slot_buttons + " Reply: filament_slot (the new slot) and filament_slots (how many the " + "project has).", + object_schema({}), json(), filament_add_command), + L("Filament"), "add_filament"))); + catalog.add(reaching( + {"delete_filament_slot"}, + own_tile(row_command("filament_delete", L("Delete Filament Slot"), + "Delete a filament slot, as its Delete menu item does, the objects on it taking the first filament; " + "with merge_into, as its Merge with item does, the objects on it taking that slot. The slots after " + "it move down by one. The only physical slot and a mixed filament (project_get_settings " + "filament_is_mixed) are refused, and so is a merge into a mixed filament that mixes the slot. " + + slot_buttons + " Not in the undo history. Reply: filament_slot (the slot deleted), merged_into " + "(the slot its objects went to, as numbered afterwards) and filament_slots.", + object_schema({{"filament_slot", {{"type", "integer"}, + {"minimum", 1}, + {"description", "The 1-based filament slot. Default: the last " + "physical slot, as the - button."}}}, + {"merge_into", {{"type", "integer"}, + {"minimum", 1}, + {"description", "The 1-based slot the objects on it go to, as Merge " + "with does. Default: they take the first filament."}}}}), + json(), filament_delete_command), + L("Filament"), "delete_filament"))); + + NativeCommand mixed = reaching( + {"add_mixed_filament"}, + mutate_tool( + "filament_add_mixed", L("Add Mixed Filament"), + "Add a mixed filament: a slot that prints its physical filaments in turn, layer by layer, in the ratios given, as " + "the Add Mixed Filament dialog's OK does with no gradient. components are two or more of the physical slots " + "(1-based), each named once, whose filaments are of one type; ratios a whole percentage for each, adding up to " + "100. It goes after every other slot. A mix the " + "project has already is not added again: the reply names its slot. Not in the undo history. Reply: " + "filament_slot (1-based) and added (false for a mix the project had).", + object_schema({{"components", array_prop({{"type", "integer"}, {"minimum", 1}}, + "The physical filament slots to mix, 1-based, two or more, each once, of " + "filaments of one type.")}, + {"ratios", array_prop({{"type", "integer"}, {"exclusiveMinimum", 0}}, + "Each component's share in percent, in the order of components, adding up to " + "100.")}}, + {"components", "ratios"}), + [](const json& args, ToolContext& ctx) { + Ops::AddMixedFilamentArgs op; + for (const json& component : args.at("components")) + op.components.push_back(component.get()); + for (const json& ratio : args.at("ratios")) + op.ratios.push_back(ratio.get()); + json reply = ctx.run_ui([&] { + ui_plater(); + const Ops::Outcome mixed = Ops::add_mixed_filament(op); + if (!mixed) + throw refused(mixed.refusal()); + return json{{"filament_slot", mixed.value().filament_slot}, {"added", mixed.value().added}}; + }); + settle(ctx); + return ToolResult::ok(reply); + })); + mixed.examples = json::parse(R"json([ + {"title": "Mix the first two filaments half and half", "calls": [ + {"tool": "filament_add_mixed", "args": {"components": [1, 2], "ratios": [50, 50]}}]}, + {"title": "Mix three filaments, the third the most", "calls": [ + {"tool": "filament_add_mixed", "args": {"components": [1, 2, 3], "ratios": [25, 25, 50]}}]}])json"); + catalog.add(std::move(mixed)); + + const std::string ams = "Synchronize the filament list from the connected printer's AMS."; + NativeCommand sync_ams = reaching( + {"sync_filaments_from_ams"}, + row_command("filament_sync_ams", L("Synchronize Filament List from AMS"), + ams + " With mode, as the sync dialog's Synchronize now does with that choice, without the dialog: map maps " + "each of the project's filaments to a slot, as the dialog's Mapping first does, which takes a project " + "with objects; overwrite replaces the filament list with the slots' filaments. Called with no arguments, " + "as its tile, it opens the sync dialog where the project has objects (blocked_by_dialog), and a warning " + "where it cannot sync. With no printer connected, no AMS or no filament it is refused, saying so. Not in " + "the undo history. Reply: mode, filaments (each slot's preset and colour afterwards) and " + "mapped_to_generic (slots whose filament is unknown, mapped to a generic preset).", + object_schema({{"mode", enum_prop({"map", "overwrite"}, "The sync dialog's choice: map or overwrite.")}}), + json::array({tile("sync_ams", L("Synchronize Filament List from AMS"), L("Printer"), "ams_fila_sync", json::object(), + ams)}), + sync_ams_command)); + // It reads the connected printer's AMS. + sync_ams.open_world = true; + catalog.add(std::move(sync_ams)); + + const std::string send = + "Open the Send G-code to printer host dialog for the current plate, as the Print button does for a printer with a print " + "host (OctoPrint, Moonraker, PrusaLink, Duet...). Set the file name with widget_set_value and press Upload or Upload and " + "Print with dialog_answer; the plate is sliced if needed, then uploaded in the background: app_state.uploads shows the " + "row's state, and a failed upload also opens an error dialog. A replay uploads again. Fails for a printer without a " + "print host, or one that prints through the Bambu network or printer agents."; + NativeCommand printer_send = reaching({"send_gcode_to_host"}, + row_command("printer_send", L("Send G-code to printer host"), send, object_schema({}), + json::array({tile("send_gcode", L("Send G-code to printer host"), + L("Slice & Export"), "printer", json::object(), send)}), + [](const json&) { return Rows::send_gcode(); })); + // It uploads to the printer's print host. + printer_send.open_world = true; + catalog.add(std::move(printer_send)); } }}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpToolsInstall.cpp b/src/slic3r/GUI/Mcp/McpToolsInstall.cpp new file mode 100644 index 0000000000..381d388dfb --- /dev/null +++ b/src/slic3r/GUI/Mcp/McpToolsInstall.cpp @@ -0,0 +1,337 @@ +// printer_list_models, printer_install and printer_uninstall: what the Printer Selection dialog lists and its Confirm +// installs; filament_install and filament_uninstall: what the System Filaments dialog's Confirm installs. On the +// operations of GUI/Operations/InstallOps.hpp. + +#include "McpTools.hpp" +#include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" +#include "slic3r/GUI/I18N.hpp" +#include "slic3r/GUI/NativeCommands.hpp" +#include "slic3r/GUI/Operations/InstallOps.hpp" +#include "slic3r/GUI/Operations/Outcome.hpp" +#include "slic3r/GUI/Operations/PresetOps.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +using nlohmann::json; + +namespace { + +// Runs `load` on a thread of its own with a flag that turns true once the call is cancelled (job_cancel, a stop of +// the replay or script it runs in, the app closing), which the load of the vendors reads between vendors. +template Result cancellable(ToolContext& ctx, const std::function*)>& load) +{ + std::atomic cancel{false}; + std::future result = std::async(std::launch::async, [&load, &cancel] { return load(&cancel); }); + while (result.wait_for(std::chrono::milliseconds(100)) != std::future_status::ready) + if (ctx.cancelled()) + cancel = true; + return result.get(); +} + +// What the install commands reply when an operation refuses: the names a refusal carries under the key that says +// what they are, and the preset tools' hint where the presets have unsaved changes. +ToolFailure install_refused(const Ops::Refusal& refusal) +{ + const std::string code = refusal.code; + if (code == "no_such_vendor" || code == "no_such_model") + return refused(refusal, "printer_list_models lists them.", "similar"); + if (code == "ambiguous_model" || code == "vendors_not_loaded") + return refused(refusal, "", "vendors"); + if (code == "no_such_nozzle") + return refused(refusal, "", "nozzles"); + return preset_refused(refusal); +} + +// Every printer model the app ships or has installed, which a call's names are checked against. On the call's thread, +// as the first read after a profile update loads every vendor. +std::vector known_models(ToolContext& ctx) +{ + using Known = Ops::Outcome>; + const Known known = cancellable(ctx, [](const std::atomic* cancel) { + Ops::PrinterModelsArgs all; + all.cancel = cancel; + return Ops::printer_models(all); + }); + if (!known) + throw install_refused(known.refusal()); + return known.value(); +} + +json models_json(const std::vector& models) +{ + json out = json::array(); + for (const Ops::ModelNozzles& model : models) + out.push_back({{"vendor", model.vendor}, {"model", model.model}, {"nozzles", model.nozzles}}); + return out; +} + +// printer_install's and printer_uninstall's function: the models a call names, applied on the UI thread. +CommandFn change_printers(bool install) +{ + return [install](const json& args, ToolContext& ctx) { + Ops::InstallPrintersArgs op; + for (const json& item : args.at("models")) { + Ops::ModelNozzles model{arg_string(item, "vendor"), arg_string(item, "model"), {}}; + if (const auto nozzles = item.find("nozzles"); nozzles != item.end()) + for (const json& nozzle : *nozzles) + model.nozzles.push_back(nozzle.get()); + op.models.push_back(std::move(model)); + } + op.changes = preset_changes_answer(args); + op.known = known_models(ctx); + json reply = ctx.run_ui([&] { + ui_plater(); + const json before = unsaved_changes(); + const Ops::Outcome done = install ? Ops::install_printers(op) : Ops::uninstall_printers(op); + if (!done) + throw install_refused(done.refusal()); + const Ops::InstalledPrinters& printers = done.value(); + json out{{"models", models_json(printers.models)}, {"selected", printers.selected}}; + out[install ? "added" : "removed"] = install ? printers.added : printers.removed; + if (!(install ? printers.removed : printers.added).empty()) + out[install ? "removed" : "added"] = install ? printers.removed : printers.added; + if (!printers.missing.empty()) + out[install ? "not_offered" : "still_offered"] = models_json(printers.missing); + if (!printers.filaments_installed.empty()) + out["filaments_installed"] = printers.filaments_installed; + if (!printers.filaments_uninstalled.empty()) + out["filaments_uninstalled"] = printers.filaments_uninstalled; + out.update(unsaved_changes_outcome(before)); + return out; + }); + settle(ctx); + return ToolResult::ok(reply); + }; +} + +// What the filament commands reply when an operation refuses: the names a refusal carries under the key that says +// what they are. +ToolFailure filament_refused(const Ops::Refusal& refusal) +{ + const std::string code = refusal.code; + if (code == "no_such_filament" || code == "no_filament_vendor") + return refused(refusal, "preset_list {type: \"filament\", include_uninstalled: true} lists the system filaments.", "similar"); + if (code == "fits_no_printer") + return refused(refusal, "Name one of its presets.", "presets"); + if (code == "no_matching_filament") + return refused(refusal, "", "filament_types"); + if (code == "filament_in_use") + return refused(refusal, "Select another filament for the slot first (preset_select with filament_slot).", "presets"); + return refused(refusal); +} + +// filament_install's and filament_uninstall's function: the names, or the vendor and filament type, a call gives. +CommandFn change_filaments(bool install) +{ + return [install](const json& args, ToolContext& ctx) { + Ops::InstallFilamentsArgs op; + if (const auto names = args.find("names"); names != args.end()) + for (const json& name : *names) + op.names.push_back(name.get()); + op.vendor = arg_string(args, "vendor"); + op.filament_type = arg_string(args, "filament_type"); + if (op.names.empty() && op.vendor.empty() && op.filament_type.empty()) + throw ToolFailure("Give names, or vendor and filament_type"); + if (!op.names.empty() && (args.contains("vendor") || args.contains("filament_type"))) + throw ToolFailure("Give names, or vendor and filament_type, not both"); + if (op.names.empty() && (op.vendor.empty() || op.filament_type.empty())) + throw ToolFailure("vendor and filament_type go together"); + json reply = ctx.run_ui([&] { + ui_plater(); + const Ops::Outcome done = install ? Ops::install_filaments(op) : Ops::uninstall_filaments(op); + if (!done) + throw filament_refused(done.refusal()); + json out{{install ? "installed" : "uninstalled", done.value().changed}}; + if (!done.value().unchanged.empty()) + out[install ? "installed_already" : "not_installed"] = done.value().unchanged; + if (!done.value().defaults_installed.empty()) + out["filaments_installed"] = done.value().defaults_installed; + return out; + }); + settle(ctx); + return ToolResult::ok(reply); + }; +} + +} // namespace + +void register_install_tools(CommandCatalog& catalog) +{ + const json models_prop = { + {"type", "array"}, + {"minItems", 1}, + {"items", object_schema({{"model", prop("string", "The model, as printer_list_models lists it (\"Bambu Lab X1 Carbon\").")}, + {"vendor", prop("string", "Its vendor (\"BBL\"), needed where several vendors have a model of that " + "name.")}, + {"nozzles", {{"type", "array"}, + {"minItems", 1}, + {"items", {{"type", "string"}}}, + {"description", "Its nozzles, as printer_list_models lists them (\"0.4\"). Default: " + "all of them, as the dialog's tick of a model."}}}}, + {"model"})}, + {"description", "The printer models, each with its nozzles."}}; + const json preset_changes_prop = enum_prop({"transfer", "discard"}, + "The presets' unsaved changes, which reloading the presets drops: move them to the " + "presets selected after it, or drop them, as the Transfer and Discard of the question " + "the dialog's Confirm asks. Needed while presets have unsaved changes; without it the " + "call is refused."); + const std::string reload = "Reloading the presets drops their unsaved changes, so while there are some preset_changes says what " + "becomes of them; without it the call is refused. A call that changes nothing reloads nothing. The " + "reload installs a printer's default filaments where no installed filament fits it, as the dialog " + "does, and where a vendor's profile lists default filaments of its own, which none of the shipped " + "profiles does, swaps a @System filament for the vendor's: those are under filaments_installed and " + "filaments_uninstalled. Two errors come after a change and say what it was: vendors_not_installed, " + "where a vendor's profiles cannot be installed (the installed printers are as they were, the " + "unsaved changes discarded if preset_changes said so, and the profiles copied before it stay in " + "the configuration folder), and presets_not_reloaded (the installed printers were written, the " + "presets not reloaded). Not in the undo history."; + + NativeCommand list = NativeCommands::long_command( + "printer_list_models", L("List printer models"), {}, + object_schema({{"vendor", prop("string", "A vendor's models only (\"BBL\", \"Prusa\"), in any case.")}, + {"query", prop("string", "Models whose name holds this, in any case.")}, + {"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 500}, {"description", "Default 100."}}}, + {"offset", {{"type", "integer"}, {"minimum", 0}}}}), + [](const json& args, ToolContext& ctx) { + Ops::PrinterModelsArgs op; + op.vendor = arg_string(args, "vendor"); + op.query = arg_string(args, "query"); + ctx.run_ui([&op] { + ui_plater(); + op.installed = Ops::installed_set(); + return json(); + }); + using Models = Ops::Outcome>; + const Models models = cancellable(ctx, [&op](const std::atomic* cancel) { + Ops::PrinterModelsArgs run = op; + run.cancel = cancel; + return Ops::printer_models(run); + }); + if (!models) + throw install_refused(models.refusal()); + json items = json::array(); + for (const Ops::PrinterModel& model : models.value()) + items.push_back({{"vendor", model.vendor}, + {"model", model.model}, + {"nozzles", model.nozzles}, + {"installed_nozzles", model.installed_nozzles}}); + return ToolResult::ok(page(items, args, 100)); + }); + list.description = "Every printer model OrcaSlicer ships or has installed, of every vendor, as the Printer Selection dialog " + "lists them: each with its vendor (the vendor's id, \"BBL\"), model, nozzles and installed_nozzles, the " + "nozzles whose printer presets the printer selector offers. vendor keeps one vendor's models, and query " + "those whose name holds it. The first call after the shipped profiles change reads every vendor, which " + "takes a while and can reply with a job to wait for; later calls read the result kept in the configuration " + "folder. printer_install and printer_uninstall change what is installed."; + list.listed = true; + list.read_only = true; + list.idempotent = true; + list.guard = GuardClass::Inspect; + list.journal = false; + list.cancellable = true; + list.operations = {"printer_models"}; + list.examples = json::parse(R"json([ + {"title": "Find a printer model and its nozzles", "calls": [ + {"tool": "printer_list_models", "args": {"query": "X1 Carbon"}}]}, + {"title": "List one vendor's printer models", "calls": [ + {"tool": "printer_list_models", "args": {"vendor": "Prusa"}}]}])json"); + catalog.add(std::move(list)); + + NativeCommand install = reaching( + {"install_printers"}, + mutate_tool("printer_install", L("Install printer models"), + "Install printer models, for good, as ticking them in the Printer Selection dialog and pressing Confirm " + "does: a vendor's profiles are installed from the ones OrcaSlicer ships, the presets reloaded, and a printer " + "newly added selected. The other installed models are kept, and the installed filaments but for what the " + "reload changes. A name no model has, a vendor or a nozzle a model lacks, is refused with the closest " + "names. " + + reload + + " Reply: models (what was named, resolved), added (the printer presets the printer selector offers " + "that it did not before the call), selected, not_offered (named nozzles whose presets it still does " + "not offer), and discarded/modified as preset_select's.", + object_schema({{"models", models_prop}, {"preset_changes", preset_changes_prop}}, {"models"}), + change_printers(true))); + install.examples = json::parse(R"json([ + {"title": "Install a printer model with one of its nozzles", "calls": [ + {"tool": "printer_list_models", "args": {"query": "Velo"}}, + {"tool": "printer_install", "args": {"models": [{"vendor": "Goofoo", "model": "Goofoo Velo+", "nozzles": ["0.4"]}]}}]}, + {"title": "Install every nozzle of a model, dropping the presets' unsaved changes", "calls": [ + {"tool": "printer_install", "args": {"models": [{"model": "Bambu Lab X1 Carbon"}], "preset_changes": "discard"}}]}])json"); + catalog.add(std::move(install)); + + NativeCommand uninstall = reaching( + {"uninstall_printers"}, + mutate_tool("printer_uninstall", L("Uninstall printer models"), + "Uninstall printer models, for good, as unticking them in the Printer Selection dialog and pressing " + "Confirm does: the printer selector no longer offers their printer presets, and the vendor's profiles stay " + "on disk. Without nozzles a model goes whole. A printer removed while selected is replaced by another " + "installed one. Removing the last installed printer model is refused, and so are names as printer_install " + "refuses them. " + + reload + + " Reply: models, removed (the printer presets the printer selector no longer offers), selected, " + "still_offered (named nozzles whose presets it still offers), and discarded/modified as preset_select's.", + object_schema({{"models", models_prop}, {"preset_changes", preset_changes_prop}}, {"models"}), + change_printers(false))); + uninstall.examples = json::parse(R"json([ + {"title": "Uninstall a printer model", "calls": [ + {"tool": "printer_uninstall", "args": {"models": [{"vendor": "Goofoo", "model": "Goofoo Velo+"}]}}]}])json"); + catalog.add(std::move(uninstall)); + + const json names_prop = {{"type", "array"}, + {"minItems", 1}, + {"items", {{"type", "string"}}}, + {"description", "System filaments: a preset's name, or the short name the filament selector " + "shows (\"Bambu PLA Basic\"), which stands for its preset of every installed " + "printer it fits."}}; + const std::string kept = "The app keeps an installed printer's default filaments installed while no other installed filament " + "fits it: where the call leaves one so, they are installed again and listed under " + "filaments_installed, as the next start would. The other filaments, and the presets' unsaved " + "changes, are kept, and the selectors are refreshed. Not in the undo history."; + NativeCommand install_filaments = reaching( + {"install_filaments"}, + mutate_tool("filament_install", L("Install system filaments"), + "Install system filaments, for good, as ticking them in the System Filaments dialog and pressing Confirm " + "does: the filament selectors offer them. Name them by names, or with vendor and filament_type every " + "filament of that vendor and type that an installed printer fits. preset_list {type: \"filament\", " + "include_uninstalled: true} lists the system filaments, those not installed with installed: false. A name " + "no filament has is refused with the closest names. " + + kept + " Reply: installed (the presets installed), installed_already, filaments_installed.", + object_schema({{"names", names_prop}, + {"vendor", prop("string", "With filament_type, in place of names: a filament maker (\"Bambu " + "Lab\", \"Generic\"), in any case.")}, + {"filament_type", prop("string", "With vendor: a filament type (\"PLA\"), in any case.")}}), + change_filaments(true))); + install_filaments.examples = json::parse(R"json([ + {"title": "Install a filament by the name the selector shows", "calls": [ + {"tool": "preset_list", "args": {"type": "filament", "include_uninstalled": true, "query": "PETG HF"}}, + {"tool": "filament_install", "args": {"names": ["Bambu PETG HF"]}}]}, + {"title": "Install every filament of a vendor and type", "calls": [ + {"tool": "filament_install", "args": {"vendor": "Generic", "filament_type": "PETG"}}]}])json"); + catalog.add(std::move(install_filaments)); + + NativeCommand uninstall_filaments = reaching( + {"uninstall_filaments"}, + mutate_tool("filament_uninstall", L("Uninstall system filaments"), + "Uninstall system filaments, for good, as unticking them in the System Filaments dialog and pressing " + "Confirm does: the filament selectors no longer offer them. names as filament_install takes them. A " + "filament a slot of the project uses is refused, naming the slot. " + + kept + " Reply: uninstalled (the presets uninstalled), not_installed, filaments_installed.", + object_schema({{"names", names_prop}}, {"names"}), change_filaments(false))); + uninstall_filaments.examples = json::parse(R"json([ + {"title": "Uninstall a filament", "calls": [ + {"tool": "filament_uninstall", "args": {"names": ["Bambu PETG HF"]}}]}])json"); + catalog.add(std::move(uninstall_filaments)); +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpToolsLayers.cpp b/src/slic3r/GUI/Mcp/McpToolsLayers.cpp index f2090376ab..3ab9b44b5f 100644 --- a/src/slic3r/GUI/Mcp/McpToolsLayers.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsLayers.cpp @@ -1,9 +1,11 @@ -// set_height_ranges: an object's height range modifiers (the object list's Height Range Modifier), -// given as the whole set of ranges. set_variable_layer_height: the Variable layer height panel's -// Adaptive, Smooth and Reset on an object. And how list_objects reports both. set_custom_gcode_at_layer: the -// pauses, custom G-codes and filament changes of a plate's layers, through the Preview's layer slider. +// object_set_height_ranges: an object's height range modifiers (the object list's Height Range Modifier), +// given as the whole set of ranges, whose settings the settings tools set. object_set_variable_layer_height: the +// Variable layer height panel's Adaptive, Smooth and Reset on an object. And how object_list reports both. +// plate_set_custom_gcode: the pauses, custom G-codes and filament changes of a plate's layers, through the Preview's +// layer slider. #include "slic3r/GUI/I18N.hpp" +#include "McpTargets.hpp" #include "McpTools.hpp" #include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/GCodeViewer.hpp" @@ -12,8 +14,11 @@ #include "slic3r/GUI/GUI_ObjectList.hpp" #include "slic3r/GUI/IMSlider.hpp" #include "slic3r/GUI/MainFrame.hpp" +#include "slic3r/GUI/Operations/ObjectOps.hpp" +#include "slic3r/GUI/Operations/Outcome.hpp" #include "slic3r/GUI/PartPlate.hpp" #include "slic3r/GUI/Plater.hpp" +#include "slic3r/GUI/Selection.hpp" #include "slic3r/GUI/TickCode.hpp" #include "libslic3r/Config.hpp" @@ -32,9 +37,7 @@ #include #include #include -#include #include -#include #include #include #include @@ -58,26 +61,12 @@ std::string mm(double z) return out.str(); } -std::string range_text(const Slic3r::t_layer_height_range& range) { return mm(range.first) + "-" + mm(range.second); } - ToolFailure overlap(const Slic3r::t_layer_height_range& lower, const Slic3r::t_layer_height_range& upper) { - return ToolFailure("Ranges " + range_text(lower) + " and " + range_text(upper) + + return ToolFailure("Ranges " + height_range_text(lower) + " and " + height_range_text(upper) + " overlap; ranges may touch, one's max_z being the next one's min_z"); } -// For "did you mean": keys holding the first half of `key`, those that begin as it does first. -json similar_keys(const std::string& key, const std::vector& keys) -{ - const std::string part = key.substr(0, std::max(3, key.size() / 2)); - std::vector hits; - std::copy_if(keys.begin(), keys.end(), std::back_inserter(hits), [&part](const std::string& k) { return k.find(part) != std::string::npos; }); - const auto common = [&key](const std::string& k) { return std::mismatch(k.begin(), k.end(), key.begin(), key.end()).first - k.begin(); }; - std::stable_sort(hits.begin(), hits.end(), [&common](const std::string& a, const std::string& b) { return common(a) > common(b); }); - hits.resize(std::min(hits.size(), 5)); - return hits; -} - bool same_ranges(const t_layer_config_ranges& a, const t_layer_config_ranges& b) { return a.size() == b.size() && @@ -101,38 +90,46 @@ json layer_height_warnings(const ModelObject& object) return warnings; } -// The object a layer call names, on an FFF printer. -ModelObject& layer_object(Plater& plater, const json& args) +// The index of the object a layer call names, else of the one selected in the Prepare view (or of the object of the +// selected instance or part), on an FFF printer. +int layer_object(Plater& plater, const json& args) { - const ModelObjectPtrs& objects = plater.model().objects; - const int oi = arg_int(args, "object", -1); - if (oi < 0 || oi >= int(objects.size())) - throw ToolFailure("object index out of range"); if (plater.printer_technology() != ptFFF) throw ToolFailure("Height range modifiers and variable layer heights are for FFF printers"); - check_expected_ids(*objects[std::size_t(oi)], nullptr, args); - return *objects[std::size_t(oi)]; + const Ops::Outcome target = + resolve_targets(plater.model(), &plater.get_view3D_canvas3D()->get_selection(), args, kObjects | kObjectOfSelection, true); + if (!target) + throw refused(target.refusal()); + return target.value().objects.front(); } -// The object set_variable_layer_height names, after the checks that need no view, such as an argument -// that goes with another action. -ModelObject& profile_object(Plater& plater, const json& args) +// The reply's naming of object `oi`, as every command with a target gives it. +json named_object(const Plater& plater, int oi) { - ModelObject& object = layer_object(plater, args); + Ops::Targets object; + object.objects = {oi}; + return targets_reply(plater.model(), object); +} + +// The object object_set_variable_layer_height names, or the one selected, after the checks that need no view, such as +// an argument that goes with another action. +int profile_object(Plater& plater, const json& args) +{ + const int oi = layer_object(plater, args); const std::string action = arg_string(args, "action"); if (args.contains("quality") && action != "adaptive") throw ToolFailure("quality goes with action adaptive"); if ((args.contains("radius") || args.contains("keep_min")) && action != "smooth") throw ToolFailure("radius and keep_min go with action smooth"); - return object; + return oi; } // What the panel's Adaptive, Smooth and Reset buttons run, on the object selected as the panel's // object is, without opening the panel. Reset of an object without a profile changes nothing. json set_variable_layer_height(Plater& plater, const json& args) { - ModelObject& object = profile_object(plater, args); - const int oi = arg_int(args, "object", -1); + const int oi = profile_object(plater, args); + ModelObject& object = *plater.model().objects[std::size_t(oi)]; const std::string action = arg_string(args, "action"); GLCanvas3D& canvas = require_prepare_scene(plater); @@ -153,7 +150,8 @@ json set_variable_layer_height(Plater& plater, const json& args) canvas.reset_layer_height_profile(); } - json out{{"object", oi}, {"height", object.instance_bounding_box(0).max.z()}}; + json out = named_object(plater, oi); + out.update({{"object", oi}, {"height", object.instance_bounding_box(0).max.z()}}); if (json profile = layer_height_profile_json(object.layer_height_profile.get()); !profile.is_null()) out["layer_height_profile"] = std::move(profile); if (json warnings = layer_height_warnings(object); !warnings.empty()) @@ -161,17 +159,16 @@ json set_variable_layer_height(Plater& plater, const json& args) return out; } -// What the object list does when a person adds, edits and removes ranges, with the whole set given at -// once. Everything the arguments can tell is checked before anything changes. +// What the object list does when a person adds and removes ranges, with the whole set given at once, on the object the +// call names or the one selected. A range's settings are the settings tools' (target height_range). Everything the +// arguments can tell is checked before anything changes. json set_height_ranges(Plater& plater, const json& args) { - ModelObject* object = &layer_object(plater, args); - const int oi = arg_int(args, "object", -1); + const int oi = layer_object(plater, args); + ModelObject* object = plater.model().objects[std::size_t(oi)]; ObjectList* list = wxGetApp().obj_list(); - t_layer_config_ranges ranges = layer_config_ranges_from_json(args.value("ranges", json()), list->get_default_layer_config(oi), - wxGetApp().filaments_cnt(), [](int extruder) { - return std::make_pair(get_min_layer_height(extruder), get_max_layer_height(extruder)); - }); + t_layer_config_ranges ranges = layer_config_ranges_from_json(args.value("ranges", json()), object->layer_config_ranges, + list->get_default_layer_config(oi)); require_prepare_scene(plater); if (!same_ranges(ranges, object->layer_config_ranges)) { @@ -184,15 +181,16 @@ json set_height_ranges(Plater& plater, const json& args) plater.changed_object(oi); } - json out{{"object", oi}, - {"height", object->instance_bounding_box(0).max.z()}, - {"layer_config_ranges", layer_config_ranges_json(object->layer_config_ranges)}}; + json out = named_object(plater, oi); + out.update({{"object", oi}, + {"height", object->instance_bounding_box(0).max.z()}, + {"layer_config_ranges", layer_config_ranges_json(object->layer_config_ranges)}}); if (json warnings = layer_height_warnings(*object); !warnings.empty()) out["warnings"] = std::move(warnings); return out; } -// The plate set_custom_gcode_at_layer names (default: the current one), after the checks that need neither its +// The plate plate_set_custom_gcode names (default: the current one), after the checks that need neither its // layers nor a view. int gcode_plate(Plater& plater, const json& args) { @@ -201,7 +199,7 @@ int gcode_plate(Plater& plater, const json& args) const bool edits = arg_bool(args, "clear", false) || !args.value("add", json::array()).empty() || !args.value("remove", json::array()).empty(); if (!edits) - throw ToolFailure("Give add, remove or clear; list_plates lists each plate's layer_gcode"); + throw ToolFailure("Give add, remove or clear; plate_list lists each plate's layer_gcode"); PartPlateList& plates = plater.get_partplate_list(); const int index = arg_int(args, "plate", plates.get_curr_plate_index()); if (index < 0 || index >= plates.get_plate_count()) @@ -216,7 +214,7 @@ int gcode_plate(Plater& plater, const json& args) throw ToolFailure(name + " prints by object (print_sequence), which takes no layer G-codes"); // A slice would replace the layers under the edit. if (plater.is_slicing_any()) - throw ToolFailure("Slicing is in progress; wait {for: \"idle\"} first"); + throw ToolFailure("Slicing is in progress; app_wait {for: \"idle\"} first"); return index; } @@ -234,7 +232,7 @@ bool preview_shows_plate(Plater& plater, int index) viewer.get_layers_slider()->GetMaxValue() + 1 == int(preview->get_gcode_layers_zs().size()); } -// A plate's codes as list_plates' layer_gcode lists them: by height, z to the G-code's 0.001 mm, layer +// A plate's codes as plate_list's layer_gcode lists them: by height, z to the G-code's 0.001 mm, layer // (1-based) where `zs` has a layer at or above z, the slider's rule for a stored height. json plate_layer_gcode(const CustomGCode::Info& codes, const std::vector& zs) { @@ -258,7 +256,7 @@ json plate_layer_gcode(const CustomGCode::Info& codes, const std::vector return out; } -// set_custom_gcode_at_layer's reply, once the plater has the slider's codes. UI thread. +// plate_set_custom_gcode's reply, once the plater has the slider's codes. UI thread. json layer_gcode_reply(Plater& plater, int index, bool changed, const json& args) { const Model& model = plater.model(); @@ -273,13 +271,13 @@ json layer_gcode_reply(Plater& plater, int index, bool changed, const json& args const PresetBundle& bundle = *wxGetApp().preset_bundle; for (const json& item : args.value("add", json::array())) if (arg_string(item, "type") == "pause" && bundle.printers.get_edited_preset().config.opt_string("machine_pause_gcode").empty()) { - out["warnings"] = json::array({"machine_pause_gcode is empty, so a pause adds no command (set it with set_settings scope printer)"}); + out["warnings"] = json::array({"machine_pause_gcode is empty, so a pause adds no command (set it with settings_set type printer)"}); break; } return out; } -// Selects the plate set_custom_gcode_at_layer names and shows it in the Preview, unless the Preview shows its layers +// Selects the plate plate_set_custom_gcode names and shows it in the Preview, unless the Preview shows its layers // already, and returns its index. Refused calls leave the view alone. Only a plate with an up-to-date slice // is opened: opening the Preview on one that is not starts a slice. int show_plate_layers(Plater& plater, const json& args) @@ -289,7 +287,7 @@ int show_plate_layers(Plater& plater, const json& args) return index; PartPlateList& plates = plater.get_partplate_list(); if (!plates.get_plate(index)->is_slice_result_valid()) - throw ToolFailure("plate " + std::to_string(index) + " has no up-to-date slice to place codes on; slice it first (slice {plates: " + + throw ToolFailure("plate " + std::to_string(index) + " has no up-to-date slice to place codes on; slice it first (plate_slice {plates: " + std::to_string(index) + "})"); plater.select_view_3D("Preview"); // What clicking a sliced plate in the Preview's plate toolbar does: select it and load its result, which @@ -332,6 +330,8 @@ json set_custom_gcode_at_layer(Plater& plater, int index, const json& args, Cust } // namespace +std::string height_range_text(const Slic3r::t_layer_height_range& range) { return mm(range.first) + "-" + mm(range.second); } + std::vector layer_range_option_keys(int filaments) { // A range's page in the sidebar edits layer_height and the per-region settings, of which the object @@ -351,49 +351,28 @@ std::vector layer_range_option_keys(int filaments) return keys; } -t_layer_config_ranges layer_config_ranges_from_json(const json& ranges, const DynamicPrintConfig& defaults, int filaments, - const std::function(int extruder)>& layer_height_bounds) +t_layer_config_ranges layer_config_ranges_from_json(const json& ranges, + const t_layer_config_ranges& current, + const DynamicPrintConfig& defaults) { if (!ranges.is_array()) - throw ToolFailure("layer_config_ranges must be a list of {min_z, max_z, values}"); - const std::vector keys = layer_range_option_keys(filaments); - t_layer_config_ranges out; + throw ToolFailure("ranges must be a list of {min_z, max_z}"); + t_layer_config_ranges out; for (const json& r : ranges) { if (!r.is_object()) - throw ToolFailure("A range is {min_z, max_z, values}"); + throw ToolFailure("A range is {min_z, max_z}"); const Slic3r::t_layer_height_range range{arg_double(r, "min_z", -1.), arg_double(r, "max_z", -1.)}; if (!(range.first >= 0. && range.first < range.second)) - throw ToolFailure("A height range needs 0 <= min_z < max_z, not " + range_text(range)); - const json values = r.value("values", json::object()); - if (!values.is_object()) - throw ToolFailure("A range's values are {key: value}"); - DynamicPrintConfig config = defaults; - for (auto it = values.begin(); it != values.end(); ++it) { - if (std::find(keys.begin(), keys.end(), it.key()) == keys.end()) - throw ToolFailure("\"" + it.key() + - "\" is not a height range setting; a range takes layer_height, extruder and per-region " - "process settings such as sparse_infill_density", - {{"similar", similar_keys(it.key(), keys)}}); - try { - config.set_deserialize_strict(it.key(), to_config_string(it.value(), it.key())); - } catch (const std::exception& e) { - throw ToolFailure("Invalid value for " + it.key() + ": " + e.what()); - } - } - const int extruder = config.opt_int("extruder"); - if (extruder < 0 || extruder > filaments) - throw ToolFailure("extruder " + std::to_string(extruder) + " is not a filament: 0 (the object's) or " + - (filaments > 1 ? "1-" + std::to_string(filaments) : std::string("1"))); - // Only a layer height given is checked, as the range editor checks only what a person types. - if (values.contains("layer_height")) { - const double height = config.opt_float("layer_height"); - const std::pair bounds = layer_height_bounds(extruder); - if (!(height >= bounds.first && height <= bounds.second)) - throw ToolFailure("layer_height " + mm(height) + " is outside this printer's " + mm(bounds.first) + "-" + mm(bounds.second)); - } + throw ToolFailure("A height range needs 0 <= min_z < max_z, not " + height_range_text(range)); if (out.count(range) != 0) throw overlap(range, range); - out[range].assign_config(std::move(config)); + // A range of the object's with these heights keeps its settings, as the object list keeps a range it is not asked + // to change. + const auto kept = current.find(range); + if (kept != current.end()) + out[range].assign_config(kept->second.get()); + else + out[range].assign_config(defaults); } // Sorted by min_z; the slicer would trim an overlap silently, which from an agent is always a mistake. const Slic3r::t_layer_height_range* lower = nullptr; @@ -405,6 +384,20 @@ t_layer_config_ranges layer_config_ranges_from_json(const json& ranges, const Dy return out; } +void check_height_range_layer_height(const DynamicPrintConfig& values, const DynamicPrintConfig& range, + const std::function(int extruder)>& layer_height_bounds) +{ + // Only a layer height given is checked, as the range editor checks only what a person types. + if (!values.has("layer_height")) + return; + const DynamicPrintConfig& source = values.has("extruder") ? values : range; + const int extruder = source.has("extruder") ? source.opt_int("extruder") : 0; + const double height = values.opt_float("layer_height"); + const std::pair bounds = layer_height_bounds(extruder); + if (!(height >= bounds.first && height <= bounds.second)) + throw ToolFailure("layer_height " + mm(height) + " is outside this printer's " + mm(bounds.first) + "-" + mm(bounds.second)); +} + json layer_config_ranges_json(const t_layer_config_ranges& ranges) { json out = json::array(); @@ -513,7 +506,7 @@ bool edit_layer_gcode(IMSlider& slider, const json& args, int filaments, bool ha if (code.extra.empty() || code.extra.size() > 1023) throw ToolFailure("gcode must be 1 to 1023 bytes, as the Custom G-code dialog takes"); } else if (type == CustomGCode::Template && !has_template) { - throw ToolFailure("The printer's template_custom_gcode is empty; set it (set_settings scope printer) or use type custom"); + throw ToolFailure("The printer's template_custom_gcode is empty; set it (settings_set type printer) or use type custom"); } else if (type == CustomGCode::ToolChange) { // The slider colours each filament change from the filaments of the slice. const int slots = int(slider.GetExtruderColors().size()); @@ -563,7 +556,7 @@ bool edit_layer_gcode(IMSlider& slider, const json& args, int filaments, bool ha slider.add_custom_gcode(code.extra, tick); else if (!slider.add_code_as_tick(code.type, code.type == CustomGCode::ToolChange ? code.extruder : -1, tick)) throw ToolFailure(std::string("The layer slider refused the ") + custom_gcode_type_name(code.type) + " on " + layer(tick) + - (changed ? "; the codes before it changed (list_plates lists them)" : "")); + (changed ? "; the codes before it changed (plate_list lists them)" : "")); changed = true; event = code.type; } @@ -574,25 +567,20 @@ bool edit_layer_gcode(IMSlider& slider, const json& args, int filaments, bool ha void register_layer_tools(CommandCatalog& catalog) { - const json range = object_schema( - {{"min_z", {{"type", "number"}, {"minimum", 0}, {"description", "Bottom, mm above the bed."}}}, - {"max_z", {{"type", "number"}, {"minimum", 0}, {"description", "Top, mm above the bed."}}}, - {"values", {{"type", "object"}, - {"description", "{key: value} as set_settings takes them: layer_height, extruder (0 = the object's " - "filament) and per-region process settings such as sparse_infill_density or wall_loops."}}}}, - {"min_z", "max_z"}); + const json range = object_schema({{"min_z", {{"type", "number"}, {"minimum", 0}, {"description", "Bottom, mm above the bed."}}}, + {"max_z", {{"type", "number"}, {"minimum", 0}, {"description", "Top, mm above the bed."}}}}, + {"min_z", "max_z"}); catalog.add(with_expected_ids(mutate_tool( - "api", "set_height_ranges", L("Set height range modifiers"), + "object_set_height_ranges", L("Set height range modifiers"), "Replace an object's height range modifiers (Height Range Modifier in the object list): Z ranges in mm, each printed " - "with its own layer_height, filament and process settings, starting from the object's layer height and filament. " - "Ranges may touch but not overlap; [] removes them all. One undo step; the object is selected. Reply: the " - "object's height and its ranges as list_objects shows them, and warnings, such as a variable layer height profile " - "deciding the layer heights instead.", - object_schema({{"object", {{"type", "integer"}, {"minimum", 0}, {"description", "Object index (list_objects)."}}}, - {"object_id", expected_id_prop("object")}, - {"ranges", array_prop(range, "The object's ranges afterwards, in any order.")}}, - {"object", "ranges"}), + "with its own layer_height, filament and process settings, which settings_get and settings_set read and write with " + "the target height_range. A range given with the min_z and max_z of one the object has keeps its settings; a new " + "one starts from the object's layer height and filament. Ranges may touch but not overlap; [] removes them all. " + "The object is the one named, else the one selected in the Prepare view. One undo step; the object is selected. " + "Reply: the object (objects, object), its height and its ranges as object_list shows them, with their settings, and " + "warnings, such as a variable layer height profile deciding the layer heights instead.", + with_targets(object_schema({{"ranges", array_prop(range, "The object's ranges afterwards, in any order.")}}, {"ranges"}), kObjects, true), [](const json& args, ToolContext& ctx) { json out = ctx.run_ui([&] { return set_height_ranges(ui_plater(), args); }); settle(ctx); @@ -600,26 +588,28 @@ void register_layer_tools(CommandCatalog& catalog) }))); catalog.add(with_expected_ids(mutate_tool( - "api", "set_variable_layer_height", L("Set a variable layer height profile"), + "object_set_variable_layer_height", L("Set a variable layer height profile"), "Run the Variable layer height panel's Adaptive, Smooth or Reset on an object, without opening the panel: adaptive " "computes layer heights from the object's shape (inside a height range, the range's layer_height), smooth smooths " - "its profile (or the one its height ranges give), reset goes back to its layer height and ranges. One undo step; " - "the object is selected. Reply: the object's height, its layer_height_profile {points, min_height, " - "max_height} as list_objects shows it (absent after reset), and warnings.", - object_schema({{"object", {{"type", "integer"}, {"minimum", 0}, {"description", "Object index (list_objects)."}}}, - {"object_id", expected_id_prop("object")}, - {"action", enum_prop({"adaptive", "smooth", "reset"}, "The panel's button.")}, - {"quality", {{"type", "number"}, {"minimum", 0}, {"maximum", 1}, - {"description", "adaptive: 0 = quality .. 1 = speed (default 0.5, as the panel)."}}}, - {"radius", {{"type", "integer"}, {"minimum", 1}, {"maximum", 10}, {"description", "smooth: default 5."}}}, - {"keep_min", prop("boolean", "smooth: keep the minimum layer heights (default false).")}}, - {"object", "action"}), + "its profile (or the one its height ranges give), reset goes back to its layer height and ranges. The object is " + "the one named, else the one selected in the Prepare view. One undo step; the object is selected. Reply: the " + "object (objects, object), its height, its layer_height_profile {points, min_height, max_height} as object_list " + "shows it (absent after reset), and warnings.", + with_targets(object_schema({{"action", enum_prop({"adaptive", "smooth", "reset"}, "The panel's button.")}, + {"quality", {{"type", "number"}, {"minimum", 0}, {"maximum", 1}, + {"description", "adaptive: 0 = quality .. 1 = speed (default 0.5, as the panel)."}}}, + {"radius", {{"type", "integer"}, {"minimum", 1}, {"maximum", 10}, {"description", "smooth: default 5."}}}, + {"keep_min", prop("boolean", "smooth: keep the minimum layer heights (default false).")}}, + {"action"}), + kObjects, true), [](const json& args, ToolContext& ctx) { // Refused calls leave the view alone. The Prepare canvas edits layer heights only once it has drawn: - // GLCanvas3D::init() makes the texture the tool needs, and the app starts on Home. + // GLCanvas3D::init() makes the texture the tool needs, and the app starts on Home. The object is read once, + // before the wait, and named in the call that follows it. + json call = args; ctx.run_ui([&] { Plater& plater = ui_plater(); - profile_object(plater, args); + call["object"] = profile_object(plater, args); require_prepare_scene(plater); return json(); }); @@ -630,7 +620,7 @@ void register_layer_tools(CommandCatalog& catalog) return canvas->is_initialized() && !canvas->is_reload_delayed() ? json(true) : json(); }, std::chrono::seconds(15), "the Prepare view to draw"); - json out = ctx.run_ui([&] { return set_variable_layer_height(ui_plater(), args); }); + json out = ctx.run_ui([&] { return set_variable_layer_height(ui_plater(), call); }); settle(ctx); return ToolResult::ok(out); }))); @@ -638,14 +628,14 @@ void register_layer_tools(CommandCatalog& catalog) const json layer = {{"type", "integer"}, {"minimum", 1}, {"description", "1-based, as the Preview's layer slider numbers layers."}}; const json z = {{"type", "number"}, {"minimum", 0}, {"description", "mm: the layer whose top is at or above it."}}; catalog.add(mutate_tool( - "api", "set_custom_gcode_at_layer", L("Set custom G-code at a layer"), + "plate_set_custom_gcode", L("Set custom G-code at a layer"), "Add or remove pauses, custom G-code, custom templates and filament changes at the start of a layer, as the Preview " "layer slider's menu does; they are saved per plate in the project. They go on the plate's sliced layers, so the " "plate needs an up-to-date slice, or must be the one the Preview still shows after an earlier edit; the call selects " "it and shows the Preview. Applies clear, then remove, then add, all checked first. One code per layer: adding " "where a code of the same type is replaces it, and where another type is, is refused (remove it first). Not " "undoable, as in the slider. A change invalidates the " - "plate's slice: slice again before exporting. Reply: the plate's codes as list_plates' layer_gcode lists them, " + "plate's slice: slice again before exporting. Reply: the plate's codes as plate_list's layer_gcode lists them, " "each with z and layer.", object_schema({{"plate", {{"type", "integer"}, {"minimum", 0}, {"description", "Default: the current plate."}}}, {"add", array_prop(object_schema({{"layer", layer}, diff --git a/src/slic3r/GUI/Mcp/McpToolsPlugins.cpp b/src/slic3r/GUI/Mcp/McpToolsPlugins.cpp new file mode 100644 index 0000000000..41cd2c3f63 --- /dev/null +++ b/src/slic3r/GUI/Mcp/McpToolsPlugins.cpp @@ -0,0 +1,396 @@ +// The plugin commands: what the Plugins window lists and does (plugin_list, plugin_enable, plugin_uninstall, +// plugin_reload) on the operations of GUI/Operations/PluginOps.hpp, and the Plugins menu's rows (plugin_install_local, +// plugin_refresh). + +#include "McpArguments.hpp" +#include "McpTools.hpp" +#include "slic3r/GUI/ActionRegistry.hpp" +#include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" +#include "slic3r/GUI/GUI_App.hpp" +#include "slic3r/GUI/I18N.hpp" +#include "slic3r/GUI/NativeCommandRows.hpp" +#include "slic3r/GUI/NativeCommands.hpp" +#include "slic3r/GUI/Operations/Outcome.hpp" +#include "slic3r/GUI/Operations/PluginOps.hpp" +#include "slic3r/plugin/PluginDescriptor.hpp" +#include "slic3r/plugin/PluginManager.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +using nlohmann::json; + +namespace { + +json row_json(const Ops::PluginRow& row) +{ + json capabilities = json::array(); + for (const Ops::PluginCapabilityRow& capability : row.capabilities) + capabilities.push_back({{"name", capability.name}, {"type", capability.type}, {"enabled", capability.enabled}}); + return {{"key", row.key}, {"name", row.name}, {"version", row.version}, {"installed", row.installed}, + {"enabled", row.enabled}, {"status", row.status}, {"source", row.source}, {"capabilities", std::move(capabilities)}, + {"error", row.error}}; +} + +json rows_json() +{ + json rows = json::array(); + for (const Ops::PluginRow& row : Ops::plugin_rows()) + rows.push_back(row_json(row)); + return rows; +} + +// The row of plugin `key` as the window lists it now, or null where it lists none. UI thread. +json row_of(const std::string& key) +{ + for (const Ops::PluginRow& row : Ops::plugin_rows()) + if (row.key == key) + return row_json(row); + return nullptr; +} + +// How a plugin stands, for an error after a step that changed it: "installed, disabled", or "no longer listed". +std::string state_of(const json& row) +{ + if (row.is_null()) + return "no longer listed"; + std::string state = std::string(row.value("installed", false) ? "installed" : "not installed") + ", " + + (row.value("enabled", false) ? "enabled" : "disabled"); + if (const std::string error = row.value("error", std::string()); !error.empty()) + state += ", with the error \"" + error + "\""; + return state; +} + +// `text`, then how a plugin stands (state_of(`row`)) as a sentence of its own: ". It is installed, disabled.". A +// plugin's own error, which `text` may be, need not end in a full stop. +std::string with_state(std::string text, const json& row) +{ + text.erase(std::min(text.size(), text.find_last_not_of(" \t\r\n") + 1)); + if (!text.empty() && std::string(".!?").find(text.back()) == std::string::npos) + text += '.'; + return (text.empty() ? text : text + " ") + "It is " + state_of(row) + "."; +} + +// A refusal of a plugin command, with the names it carries under the key that says what they are. +ToolFailure plugin_refused(const Ops::Refusal& refusal) +{ + const std::string code = refusal.code; + if (code == "no_such_plugin") + return refused(refusal, "plugin_list lists the plugins by key.", "similar"); + if (code == "ambiguous_plugin") + return refused(refusal, "", "plugins"); + if (code == "no_such_capability") + return refused(refusal, "", "capabilities"); + if (code == "ambiguous_capability") + return refused(refusal, "", "types"); + return refused(refusal); +} + +// The plugin a call names, by its key or its name. UI thread. +PluginDescriptor named_plugin(const json& args) +{ + const Ops::Outcome found = Ops::find_plugin(arg_string(args, "plugin")); + if (!found) + throw plugin_refused(found.refusal()); + return found.value(); +} + +ToolResult enable_plugin(const json& args, ToolContext& ctx) +{ + Ops::SetPluginEnabledArgs op; + op.capability = arg_string(args, "capability"); + op.enabled = args.at("enabled").get(); + // The operation reads no capability as the plugin itself, which enabled false would unload. + if (args.contains("capability") && op.capability.empty()) + throw ToolFailure("capability is empty: name one of the plugin's capabilities, or leave capability out to turn the plugin " + "itself on or off", + {{"code", "empty_capability"}}); + Ops::PluginChange change = Ops::PluginChange::None; + ctx.run_ui([&] { + ui_plater(); + op.plugin = named_plugin(args).plugin_key; + const json before = row_of(op.plugin); + std::optional> done; + std::string thrown; + try { + done.emplace(Ops::set_plugin_enabled(op)); + } catch (const std::exception& ex) { + thrown = ex.what(); + } + // The Plugins window shows the plugin as it stands, whatever came of the call. + wxGetApp().update_plugins_dialog(); + if (!done.has_value()) { + const json after = row_of(op.plugin); + throw ToolFailure(with_state(thrown, after), {{"code", op.enabled ? "not_loaded" : "not_unloaded"}, {"plugin", after}}); + } + if (!*done) + throw plugin_refusal_after(done->refusal(), before, row_of(op.plugin)); + change = done->value().change; + return json(); + }); + bool still_loading = false; + if (change == Ops::PluginChange::LoadStarted) { + // The load runs in the background, and may ask for a permission in its dialog, which the caller answers; the + // call waits for its end on its own thread, as the window's Activating... does. + const std::string key = op.plugin; + const json done = poll_until( + ctx, [&key] { return PluginManager::instance().is_plugin_load_in_progress(key) ? json() : json(true); }, + std::chrono::minutes(5), std::chrono::milliseconds(200)); + still_loading = done.is_null(); + if (still_loading && ctx.cancelled()) + throw ToolFailure("Stopped waiting for " + key + " to load; its load goes on, and plugin_list shows how it ends"); + } + const json row = ctx.run_ui([&] { return row_of(op.plugin); }); + return ToolResult::ok( + plugin_enable_reply(op.plugin, change != Ops::PluginChange::None, change == Ops::PluginChange::LoadStarted, still_loading, row)); +} + +ToolResult uninstall(const json& args, ToolContext& ctx) +{ + std::optional plan; + ctx.run_ui([&] { + ui_plater(); + const Ops::Outcome planned = Ops::plugin_uninstall_plan(named_plugin(args).plugin_key); + if (!planned) + throw plugin_refused(planned.refusal()); + plan = planned.value(); + return json(); + }); + // The window runs this behind its progress dialog; the call runs it here, on its own thread. + std::optional failed; + try { + if (const Ops::Outcome removed = Ops::uninstall_plugin(*plan); !removed) + failed = removed.refusal(); + } catch (const std::exception& ex) { + failed = Ops::Refusal{Ops::RefusalKind::Failed, "not_uninstalled", ex.what()}; + } + // A removal that fails may have unloaded the plugin already, so the window shows it as it stands on every path. + const json row = ctx.run_ui([&] { + if (!failed) + Ops::plugin_uninstalled(); + wxGetApp().update_plugins_dialog(); + return row_of(plan->plugin); + }); + if (failed) + throw ToolFailure(with_state(failed->english(), row), {{"code", failed->code}, {"plugin", row}}); + json reply{{"uninstalled", plan->plugin}, {"name", plan->name}, {"unsubscribed", plan->unsubscribe}}; + // A cloud plugin deleted stays listed, to be installed again. + if (!row.is_null()) + reply["plugin"] = row; + return ToolResult::ok(std::move(reply)); +} + +ToolResult reload(const json& args, ToolContext& ctx) +{ + std::optional plan; + ctx.run_ui([&] { + ui_plater(); + const Ops::Outcome planned = + Ops::plugin_reload_plan(named_plugin(args).plugin_key, arg_bool(args, "clear_cache", false)); + if (!planned) + throw plugin_refused(planned.refusal()); + plan = planned.value(); + return json(); + }); + // The window runs this behind its progress dialog; the call runs it here, on its own thread. + std::optional failed; + try { + if (const Ops::Outcome reloaded = Ops::reload_plugin(*plan); !reloaded) + failed = reloaded.refusal(); + } catch (const std::exception& ex) { + failed = Ops::Refusal{Ops::RefusalKind::Failed, "not_loaded", ex.what()}; + } + const json row = ctx.run_ui([&] { + wxGetApp().update_plugins_dialog(); + return row_of(plan->plugin); + }); + if (failed) + throw ToolFailure(with_state(failed->english(), row), {{"code", failed->code}, {"plugin", row}}); + return ToolResult::ok({{"reloaded", plan->plugin}, {"reinstalled", plan->cloud}, {"plugin", row}}); +} + +ToolResult refresh(const json&, ToolContext& ctx) +{ + // The closure runs while the call waits for it, so it hands the ticket over in place. + Ops::RefreshRun::Ticket ticket; + ctx.run_ui([&ticket] { + ui_plater(); + ticket = wxGetApp().refresh_plugins(); + return json(); + }); + // The refresh runs off the UI thread, after the ones asked for before it; the call waits on its own thread. + const std::optional status = + Ops::wait_for_refresh(Ops::plugin_refresh_run(), ticket, [&ctx] { return ctx.cancelled(); }, std::chrono::milliseconds(200)); + if (!status) + throw ToolFailure("Stopped waiting for the plugin refresh, which goes on; plugin_list shows the plugins as they stand"); + json plugins = ctx.run_ui([] { return rows_json(); }); + if (status->state == Ops::RefreshRun::State::Failed) + throw ToolFailure("The plugin refresh failed: " + status->error, {{"code", "refresh_failed"}, {"plugins", std::move(plugins)}}); + return ToolResult::ok({{"plugins", std::move(plugins)}}); +} + +} // namespace + +json plugin_enable_reply(const std::string& plugin, bool changed, bool load_started, bool still_loading, const json& row) +{ + if (load_started && !still_loading && (row.is_null() || !row.value("enabled", false))) + throw ToolFailure(with_state(plugin + " did not load", row), {{"code", "not_loaded"}, {"plugin", row}}); + json reply{{"plugin", row}, {"changed", changed}}; + if (row.is_null()) + reply["note"] = plugin + " is no longer listed."; + else if (still_loading) + reply["note"] = "The plugin is still loading after five minutes; plugin_list shows how its load ends."; + return reply; +} + +ToolFailure plugin_refusal_after(const Ops::Refusal& refusal, const json& before, const json& after) +{ + ToolFailure bare = plugin_refused(refusal); + const auto stands_as = [](const json& row) { + return row.is_null() ? json() : + json{row.value("installed", false), row.value("enabled", false), row.value("error", std::string())}; + }; + if (stands_as(before) == stands_as(after)) + return bare; + json details = bare.details.is_object() ? bare.details : json::object(); + details["plugin"] = after; + return ToolFailure(with_state(bare.what(), after), std::move(details)); +} + +void register_plugin_tools(CommandCatalog& catalog) +{ + using NativeCommands::tile; + const json plugin_prop = prop("string", "The plugin's key, as plugin_list gives it, or its name where one plugin has it."); + + NativeCommand list = inspect_tool( + "plugin_list", L("List plugins"), + "The plugins, as the Plugins window lists them: each with its key (which the other plugin commands take), name, " + "version (the one installed, else the latest offered), installed (a package is on disk), enabled (loaded: the row's " + "switch), status (Activated, Error, RuntimeError, Inactive or Loading), source (local, subscribed, mine or " + "orphaned), capabilities (a loaded plugin's: name, type, enabled) and error.", + object_schema({}), [](const json&, ToolContext& ctx) { + json plugins = ctx.run_ui([] { return rows_json(); }); + return ToolResult::ok({{"total", plugins.size()}, {"plugins", std::move(plugins)}}); + }); + list.examples = json::parse(R"json([ + {"title": "List the plugins and how each stands", "calls": [{"tool": "plugin_list", "args": {}}]}])json"); + catalog.add(std::move(list)); + + // The file its dialog asks for, which every call but the tile's gives. + const std::string replacing = "A plugin of that name installed already is replaced only with overwrite true; without it the " + "call is refused with the question the dialog asks."; + NativeCommand local = row_command( + "plugin_install_local", L("Install Local Plugin"), + "Install a plugin from a .py or .whl file by absolute path, as the Plugins dialog's Install local plugin does, without its " + "file dialog. " + replacing + " Called with no arguments, the file dialog asks for the file (blocked_by_dialog), and " + "replacing an installed plugin asks first (dialog_answer).", + object_schema({{"path", Rows::input_file("a .py or .whl plugin package")}, + {"overwrite", prop("boolean", "Replace a plugin of that name installed already. Default false.")}}, + {"path"}), + json::array({tile("install_local_plugin", L("Install Local Plugin"), L("Plugins"), "", json::object(), + "Install a plugin from the .py or .whl file a dialog asks for, as the Plugins dialog's Install local " + "plugin does, asking before it replaces one installed; plugin_install_local with a path installs that " + "file without a dialog. " + replacing)}), + [](const json& args) { return Rows::install_local_plugin(args); }); + local.input_schema = with_silent(std::move(local.input_schema), person_forms(local)); + catalog.add(std::move(local)); + + NativeCommand enable = reaching( + {"set_plugin_enabled"}, + mutate_tool("plugin_enable", L("Enable or disable a plugin"), + "Turn a plugin, or with capability one of its capabilities, on or off, as the Plugins window's switches do. " + "A plugin turned on is loaded, and the call waits for its load to end; a cloud plugin not installed is " + "downloaded and installed first. A plugin that needs a permission while it loads asks in its permission " + "dialog (blocked_by_dialog), which the caller answers. A plugin turned off is unloaded and loses its error. " + "A capability is one of a loaded plugin's, by its name; an empty one is refused. Reply: plugin (its row, as " + "plugin_list gives it) and changed; a call that fails once it has changed the plugin, a load that fails " + "among them, is an error naming how the plugin is left.", + object_schema({{"plugin", plugin_prop}, + {"capability", {{"type", "string"}, + {"minLength", 1}, + {"description", "One of the plugin's capabilities, by name, in place of the " + "plugin itself. The plugin must be enabled."}}}, + {"enabled", prop("boolean", "On (true) or off (false).")}}, + {"plugin", "enabled"}), + enable_plugin)); + // A plugin turned on runs its code, and a cloud plugin is downloaded. + enable.open_world = true; + enable.examples = json::parse(R"json([ + {"title": "Turn a plugin on", "calls": [ + {"tool": "plugin_list", "args": {}}, + {"tool": "plugin_enable", "args": {"plugin": "my_plugin", "enabled": true}}]}, + {"title": "Turn one of a plugin's capabilities off", "calls": [ + {"tool": "plugin_enable", "args": {"plugin": "my_plugin", "capability": "Export report", "enabled": false}}]}])json"); + catalog.add(std::move(enable)); + + NativeCommand reload_command = reaching( + {"reload_plugin"}, + mutate_tool("plugin_reload", L("Reload a plugin"), + "Load a plugin again after its files changed, as its row's Reload does: it is unloaded and loaded, and a " + "plugin that was not loaded is unloaded again. clear_cache also removes its extracted wheel cache first, as " + "Delete cache and reload does. A cloud plugin is installed again from the cloud, as its Reinstall does, and " + "takes no clear_cache; one no longer available is refused. Reply: reloaded, reinstalled and plugin (its row); " + "a reload that fails is an error naming how the plugin is left.", + object_schema({{"plugin", plugin_prop}, + {"clear_cache", prop("boolean", "Remove the plugin's extracted wheel cache before loading it. " + "Default false.")}}, + {"plugin"}), + reload)); + // A plugin loaded runs its code, and a cloud plugin is downloaded again. + reload_command.open_world = true; + reload_command.examples = json::parse(R"json([ + {"title": "Reload a plugin after editing its files", "calls": [ + {"tool": "plugin_reload", "args": {"plugin": "my_plugin"}}]}, + {"title": "Reload a plugin with its wheel cache removed", "calls": [ + {"tool": "plugin_reload", "args": {"plugin": "my_plugin", "clear_cache": true}}]}])json"); + catalog.add(std::move(reload_command)); + + NativeCommand uninstall_command = reaching( + {"uninstall_plugin"}, + mutate_tool("plugin_uninstall", L("Uninstall a plugin"), + "Remove a plugin for good, without asking, as its row's Delete does once confirmed: it is unloaded where it " + "runs, and its files are removed. A cloud plugin subscribed to is unsubscribed, as its row's Unsubscribe " + "does, which also ends the subscription in the cloud account; the person's own cloud plugin loses its " + "package alone and stays listed, to be installed again. Reply: uninstalled (the key), name, unsubscribed, " + "and plugin where it stays listed; a removal that fails is an error naming how the plugin is left.", + object_schema({{"plugin", plugin_prop}}, {"plugin"}), uninstall, /*destructive=*/true)); + // Unsubscribe reaches the cloud account. + uninstall_command.open_world = true; + uninstall_command.examples = json::parse(R"json([ + {"title": "Uninstall a plugin", "calls": [ + {"tool": "plugin_list", "args": {}}, + {"tool": "plugin_uninstall", "args": {"plugin": "my_plugin"}}]}])json"); + catalog.add(std::move(uninstall_command)); + + NativeCommand refresh_command = reaching( + {"start_plugin_refresh"}, + NativeCommands::long_command("plugin_refresh", L("Refresh Plugins"), {}, object_schema({}), refresh)); + refresh_command.description = + "Reload the plugins, as Refresh Plugins does: the installed plugins are rescanned and the plugin hub's list fetched " + "again, and a notification says how it went. The call waits for the refresh to end and replies with the plugins, as " + "plugin_list gives them; a refresh already running, or waiting, runs before the call's own, so the reply comes from a " + "rescan that began after the call. job_cancel stops the wait, not the refresh."; + refresh_command.listed = true; + refresh_command.cancellable = true; + // It fetches the plugin hub's list. + refresh_command.open_world = true; + refresh_command.tiles = + json::array({tile("refresh_plugins", L("Refresh Plugins"), L("Plugins"), "", json::object(), "Reload plugins.")}); + // A person's pick starts the refresh and returns, its notification saying how it went; a call waits for it. + catalog.add(NativeCommands::with_row_forms( + std::move(refresh_command), [](const json&) { return Rows::refresh_plugins(); }, /*person_form_behind_dialogs=*/false, + std::vector{json::object()})); +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpToolsPreferences.cpp b/src/slic3r/GUI/Mcp/McpToolsPreferences.cpp new file mode 100644 index 0000000000..6716252b9e --- /dev/null +++ b/src/slic3r/GUI/Mcp/McpToolsPreferences.cpp @@ -0,0 +1,255 @@ +// preferences_get and preferences_set: the app's preferences as the Preferences dialog shows them, read from and +// written through the table of GUI/Operations/PreferenceOps.hpp, which the dialog builds its rows from too. + +#include "McpTools.hpp" +#include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" +#include "slic3r/GUI/GUI_App.hpp" +#include "slic3r/GUI/I18N.hpp" +#include "slic3r/GUI/NativeCommands.hpp" +#include "slic3r/GUI/Operations/Outcome.hpp" +#include "slic3r/GUI/Operations/PreferenceOps.hpp" + +#include "libslic3r/AppConfig.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +using nlohmann::json; + +namespace { + +const char* kind_name(Ops::PreferenceKind kind) +{ + switch (kind) { + case Ops::PreferenceKind::Checkbox: return "checkbox"; + case Ops::PreferenceKind::Choice: return "choice"; + case Ops::PreferenceKind::Number: return "number"; + case Ops::PreferenceKind::Text: return "text"; + } + return "text"; +} + +std::string lower(std::string s) +{ + std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return char(std::tolower(c)); }); + return s; +} + +// A bound of a number's range, whole where the row takes whole numbers. +json bound(const Ops::Preference& p, double value) +{ + if (p.decimals == 0) + return std::int64_t(value); + return value; +} + +// What a call learns of `p`'s refusal to be written: its reason, in English. +std::string refused_reason(const Ops::Preference& p) +{ + return Ops::Refusal{Ops::RefusalKind::Precondition, "preference_refused", p.refused, {p.key}}.english(); +} + +// preferences_get's item for `p`: its row, and the value the dialog shows: `shown` where the dialog shows a value of its +// own (Ops::shown_texts()), else the stored one, else the fallback. +json preference_item(const AppConfig& config, const Ops::Preference& p, const std::map& shown) +{ + std::string stored; + const bool is_stored = config.get("app", p.key, stored); + const auto own = shown.find(p.key); + const std::string text = own != shown.end() ? own->second : is_stored ? stored : p.fallback; + json item{{"key", p.key}, {"tab", p.tab}, {"section", p.section}, + {"label", p.label}, {"kind", kind_name(p.kind)}, + {"value", Ops::preference_value(p, text)}}; + if (!p.choices.empty()) { + json choices = json::array(); + for (const auto& [value, label] : p.choices) + choices.push_back({{"value", value}, {"label", label}}); + item["choices"] = std::move(choices); + } + if (p.min) + item["min"] = bound(p, *p.min); + if (p.max) + item["max"] = bound(p, *p.max); + if (!is_stored) + item["stored"] = false; + if (p.restart_needed) + item["restart_needed"] = true; + if (p.refused != nullptr) + item["refused"] = refused_reason(p); + return item; +} + +// What preferences_set replies when the operation refuses: the names the refusal carries under the key that says what +// they are, and where a refused preference changes instead. +ToolFailure preferences_refused(const Ops::Refusal& refusal, const std::vector& table) +{ + const std::string code = refusal.code; + if (code == "not_a_preference") + return refused(refusal, "preferences_get lists the Preferences dialog's preferences.", "similar"); + if (code == "no_such_choice") + return refused(refusal, "", "choices"); + if (code == "out_of_range") + return refused(refusal, "", "range"); + if (code == "preference_refused" && !refusal.args.empty()) + if (const Ops::Preference* p = Ops::find_preference(table, refusal.args.front())) + return refused(refusal, "It changes in the Preferences dialog: window_open {\"window\": \"preferences\", \"tab\": \"" + p->tab + + "\", \"key\": \"" + p->key + "\"}, then widget_set_value on the control named " + p->key + + " within Preferences.", + "keys"); + return refused(refusal); +} + +// preferences_set's reply: each preference changed, with its value before and after, typed as preferences_get gives it, +// stored_before: false where `before` is the fallback, restart_needed where the value is read at the next start; and +// those already so. +json changes_json(const Ops::PreferenceChanges& changes, const std::vector& table) +{ + json changed = json::array(); + for (const Ops::PreferenceChange& c : changes.changed) { + const Ops::Preference& p = *Ops::find_preference(table, c.key); + json item{{"key", c.key}, {"before", Ops::preference_value(p, c.before)}, {"after", Ops::preference_value(p, c.after)}}; + if (!c.stored_before) + item["stored_before"] = false; + if (p.restart_needed) + item["restart_needed"] = true; + changed.push_back(std::move(item)); + } + return {{"changed", std::move(changed)}, {"unchanged", changes.unchanged}}; +} + +} // namespace + +json preferences_settings(const AppConfig& config, const std::vector& shown, const json& args, + const std::map& shown_texts) +{ + const std::string tab = arg_string(args, "tab"); + std::vector words; + std::istringstream query(lower(arg_string(args, "query"))); + for (std::string word; query >> word;) + words.push_back(word); + std::vector asked; + if (args.contains("keys")) + for (const json& key : args["keys"]) + asked.push_back(key.get()); + const auto named = [&asked](const std::string& key) { return std::find(asked.begin(), asked.end(), key) != asked.end(); }; + const auto matches = [&](const Ops::Preference& p) { + if ((!tab.empty() && p.tab != tab) || (args.contains("keys") && !named(p.key))) + return false; + const std::string text = lower(p.key + " " + p.label + " " + p.section); + return std::all_of(words.begin(), words.end(), [&text](const std::string& word) { return text.find(word) != std::string::npos; }); + }; + + json items = json::array(), unknown = json::array(); + for (const Ops::Preference& p : shown) + if (matches(p)) + items.push_back(preference_item(config, p, shown_texts)); + // A named key the dialog does not show is read as the app configuration stores it. + for (const std::string& key : asked) { + if (Ops::find_preference(shown, key) != nullptr) + continue; + std::string value; + if (config.get("app", key, value)) + items.push_back({{"key", key}, {"value", value}}); + else + unknown.push_back(key); + } + json out{{"total", items.size()}, {"items", std::move(items)}}; + if (!unknown.empty()) { + out["unknown_keys"] = std::move(unknown); + // Some preferences are stored only once they are changed. + out["note"] = "unknown_keys are not stored and are no preference the Preferences dialog shows now."; + } + return out; +} + +void register_preference_tools(CommandCatalog& catalog) +{ + catalog.add(inspect_tool( + "preferences_get", L("Read preferences"), + "Read the app's preferences as the Preferences dialog shows them. With no argument, every preference it shows, " + "tab by tab in its order, each with key (its control is named after it), tab, section and label (the row's title, " + "in English), kind (checkbox, choice, number or text), value (what the dialog shows: true or false for a checkbox, " + "a number for a number field), a choice's choices ({value, label}; preferences_set takes the value), a number's " + "min and max, stored: false where nothing is stored and the value is the one the dialog shows then, " + "restart_needed: true for a preference read at the next start, which a write changes nothing before, and " + "refused, the reason, for a preference preferences_set does not write. The MCP server's switch and port read as " + "the dialog shows them: on while the server runs, and the port it is on, also where this session's launch " + "arguments set them without storing them; their stored says whether a value is stored. keys, query and tab " + "narrow the list together; a " + "named key the dialog does not show is read as the app configuration stores it ({key, value}), and one that is " + "neither is listed under unknown_keys. The app configuration also holds account and device state, which is read " + "only by name.", + object_schema({{"keys", array_prop({{"type", "string"}}, "Preference keys, e.g. [\"project_load_behaviour\"].")}, + {"query", prop("string", "Words to find in the keys, labels and section titles, in any case, e.g. " + "\"auto slice\".")}, + {"tab", enum_prop({"general", "files", "behaviour", "control", "graphics", "online", "developer"}, + "The dialog's tab, as window_open names it.")}}), + [](const json& args, ToolContext& ctx) { + return ToolResult::ok(ctx.run_ui([&] { + ui_plater(); + return preferences_settings(*wxGetApp().app_config, Ops::shown_preferences(), args, Ops::shown_texts()); + })); + })); + + NativeCommand write = reaching( + {"set_preferences"}, + mutate_tool( + "preferences_set", L("Change preferences"), + "Change preferences as their controls in the Preferences dialog do: values {key: value}, a checkbox as true or " + "false, a choice as one of its values, a number within its range, as preferences_get lists them, and the " + "downloads folder (download_path) as the absolute path of an existing folder. All are checked first and written " + "together, so nothing changes if one is refused; then each does what its control does in the app, in the keys' " + "order (the preview redrawn, the sidebar's lists, the settings' mode, the theme, preset sync started or " + "stopped, stealth mode's sign-out of the cloud accounts), and those preferences_get marks restart_needed are " + "stored and take effect at the next start. A key whose value is already the one given is left as it is. " + "Refused, by name and with the reason: a key the dialog does not show, and those preferences_get marks " + "refused, whose control opens a dialog, restarts OrcaSlicer, signs out, or reaches outside it (the language, " + "the login region, the network plug-in, file associations, the mixed-temperature warning, the MCP server's " + "switch and port); those change in the dialog: window_open {\"window\": \"preferences\", \"tab\", " + "\"key\"}, then widget_set_value. Not in the undo history. Reply: changed, [{key, before, after}] typed as " + "preferences_get gives them, with stored_before: false where nothing was stored and before is the value the " + "dialog showed, and restart_needed: true where preferences_get gives it; and unchanged, the keys already so.", + object_schema({{"values", {{"type", "object"}, + {"description", "{key: value}, e.g. {\"auto_arrange\": false, \"auto_calculate_flush\": " + "\"color change\"}."}}}}, + {"values"}), + [](const json& args, ToolContext& ctx) { + const json values = args.value("values", json::object()); + if (values.empty()) + throw ToolFailure("values names no preference: give {key: value}, e.g. {\"auto_arrange\": false}"); + std::map asked; + for (const auto& [key, value] : values.items()) + asked[key] = value; + json result = ctx.run_ui([&]() -> json { + ui_plater(); + const std::vector table = Ops::shown_preferences(); + const Ops::Outcome done = Ops::set_preferences(asked); + if (!done) + throw preferences_refused(done.refusal(), table); + return changes_json(done.value(), table); + }); + settle(ctx); + return ToolResult::ok(result); + })); + write.examples = json::parse(R"json([ + {"title": "Find a preference and turn it off", "calls": [ + {"tool": "preferences_get", "args": {"query": "arrange"}}, + {"tool": "preferences_set", "args": {"values": {"auto_arrange": false}}}]}, + {"title": "Set a choice and a number", "calls": [ + {"tool": "preferences_set", "args": {"values": {"auto_calculate_flush": "color change", "opengl_fps_cap": 60}}}]}])json"); + catalog.add(std::move(write)); +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpToolsProject.cpp b/src/slic3r/GUI/Mcp/McpToolsProject.cpp index 57b7f57b96..5d192b726a 100644 --- a/src/slic3r/GUI/Mcp/McpToolsProject.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsProject.cpp @@ -1,10 +1,12 @@ -// open_files, new_project, save_project and export: files in and out without file dialogs. generate_calibration_test: the -// Calibration menu's tests, which start a new project. +// project_new, project_open, project_import, project_save and project_export: the project's files in and out without +// file dialogs, and called as their menu rows' tiles, with them. calibration_generate_test: the Calibration menu's +// tests, which start a new project. #include "slic3r/GUI/I18N.hpp" #include "JobRegistry.hpp" #include "McpPaths.hpp" #include "AutomationRuntime.hpp" +#include "McpTargets.hpp" #include "McpTools.hpp" #include "slic3r/GUI/ActionRegistry.hpp" #include "slic3r/GUI/CommandCatalog.hpp" @@ -12,8 +14,10 @@ #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/MainFrame.hpp" +#include "slic3r/GUI/NativeCommandRows.hpp" #include "slic3r/GUI/NativeCommands.hpp" #include "slic3r/GUI/Operations/ExportOps.hpp" +#include "slic3r/GUI/Operations/ObjectOps.hpp" #include "slic3r/GUI/Operations/Outcome.hpp" #include "slic3r/GUI/Operations/PlateOps.hpp" #include "slic3r/GUI/Operations/ProjectOps.hpp" @@ -75,7 +79,7 @@ json project_json(const Ops::ProjectSummary& project) Ops::UnsavedChanges unsaved_changes_answer(bool discard) { return discard ? Ops::UnsavedChanges::Discard : Ops::UnsavedChanges::Refuse; } // What a tool that replaces the project adds to the refusal of unsaved changes. -constexpr const char* kUnsavedChangesHint = "save_project first, or pass discard_changes: true."; +constexpr const char* kUnsavedChangesHint = "project_save first, or pass discard_changes: true."; // Fails when the project has unsaved changes the caller did not say to drop. void require_project_discardable(bool discard) @@ -99,7 +103,7 @@ bool is_belt(const DynamicPrintConfig& printer) return belt != nullptr && belt->value; } -// generate_calibration_test's test_model values, as each test's dialog lists its models. +// calibration_generate_test's test_model values, as each test's dialog lists its models. std::vector calib_test_models(CalibMode mode) { switch (mode) { @@ -148,22 +152,22 @@ std::string calib_rule(CalibParamsError error, const Calib_Params& p, const Dyna json calib_result_keys(CalibMode mode, const DynamicPrintConfig& printer) { switch (mode) { - case CalibMode::Calib_Temp_Tower: return {{"scope", "filament"}, {"keys", {"nozzle_temperature", "nozzle_temperature_initial_layer"}}}; - case CalibMode::Calib_Vol_speed_Tower: return {{"scope", "filament"}, {"keys", {"filament_max_volumetric_speed"}}}; + case CalibMode::Calib_Temp_Tower: return {{"type", "filament"}, {"keys", {"nozzle_temperature", "nozzle_temperature_initial_layer"}}}; + case CalibMode::Calib_Vol_speed_Tower: return {{"type", "filament"}, {"keys", {"filament_max_volumetric_speed"}}}; case CalibMode::Calib_PA_Tower: - case CalibMode::Calib_PA_Line: return {{"scope", "filament"}, {"keys", {"enable_pressure_advance", "pressure_advance"}}}; + case CalibMode::Calib_PA_Line: return {{"type", "filament"}, {"keys", {"enable_pressure_advance", "pressure_advance"}}}; case CalibMode::Calib_PA_Pattern: - return {{"scope", "filament"}, + return {{"type", "filament"}, {"keys", {"enable_pressure_advance", "pressure_advance", "adaptive_pressure_advance", "adaptive_pressure_advance_model"}}}; - case CalibMode::Calib_Flow_Rate: return {{"scope", "filament"}, {"keys", {"filament_flow_ratio"}}}; - case CalibMode::Calib_Retraction_tower: return {{"scope", "filament"}, {"keys", {"filament_retraction_length"}}}; + case CalibMode::Calib_Flow_Rate: return {{"type", "filament"}, {"keys", {"filament_flow_ratio"}}}; + case CalibMode::Calib_Retraction_tower: return {{"type", "filament"}, {"keys", {"filament_retraction_length"}}}; case CalibMode::Calib_VFA_Tower: - return {{"scope", "printer"}, {"keys", {"resonance_avoidance", "min_resonance_avoidance_speed", "max_resonance_avoidance_speed"}}}; + return {{"type", "printer"}, {"keys", {"resonance_avoidance", "min_resonance_avoidance_speed", "max_resonance_avoidance_speed"}}}; case CalibMode::Calib_Cornering: - return {{"scope", "printer"}, + return {{"type", "printer"}, {"keys", has_junction_deviation(printer) ? json{"machine_max_junction_deviation"} : json{"machine_max_jerk_x", "machine_max_jerk_y"}}}; default: - return {{"scope", "printer"}, + return {{"type", "printer"}, {"keys", {"input_shaping_emit", "input_shaping_type", "input_shaping_freq_x", "input_shaping_freq_y", "input_shaping_damp_x", "input_shaping_damp_y"}}}; } @@ -199,14 +203,16 @@ json apply_vfa_fit(Calib_Params& params, bool auto_adjust, const PresetBundle& b } } -// export's format for a path given without one, from its extension. +// project_export's format for a path given without one, from its extension. std::string format_of(const std::string& path) { - static const std::pair formats[]{{".gcode.3mf", "sliced_3mf"}, {".gcode", "gcode"}, {".3mf", "3mf"}, {".stl", "stl"}}; + static const std::pair formats[]{{".gcode.3mf", "sliced_3mf"}, {".gcode", "gcode"}, {".3mf", "3mf"}, + {".stl", "stl"}, {".drc", "drc"}, {".obj", "toolpaths_obj"}}; for (const auto& [ext, format] : formats) if (boost::algorithm::iends_with(path, ext)) return format; - throw ToolFailure("Give format (gcode, sliced_3mf, 3mf or stl), or a path ending in .gcode, .gcode.3mf, .3mf or .stl"); + throw ToolFailure("Give format (gcode, sliced_3mf, 3mf, stl, drc or toolpaths_obj), or a path ending in .gcode, .gcode.3mf, " + ".3mf, .stl, .drc or .obj"); } } // namespace @@ -214,7 +220,7 @@ std::string format_of(const std::string& path) Calib_Params calib_params_from_args(const json& args, const DynamicPrintConfig& printer, std::vector& warnings) { const std::string test = arg_string(args, "test"); - // The arguments each test takes, besides test, discard_changes and preset_changes. + // The arguments each test takes, besides test, silent, discard_changes and preset_changes. std::vector takes{"start", "end", "step"}; CalibMode mode = CalibMode::Calib_None; std::string method; @@ -258,7 +264,7 @@ Calib_Params calib_params_from_args(const json& args, const DynamicPrintConfig& throw ToolFailure("Unknown test \"" + test + "\""); } for (auto it = args.begin(); it != args.end(); ++it) - if (it.key() != "test" && it.key() != "discard_changes" && it.key() != "preset_changes" && + if (it.key() != "test" && it.key() != "silent" && it.key() != "discard_changes" && it.key() != "preset_changes" && std::find(takes.begin(), takes.end(), it.key()) == takes.end()) throw ToolFailure(it.key() + " does not apply to " + test + (method.empty() ? "" : " with method " + method), {{"takes", takes}}); @@ -392,72 +398,141 @@ json calib_params_json(const json& args, const Calib_Params& p, const DynamicPri void register_project_tools(CommandCatalog& catalog) { - catalog.add(reaching({"open_project", "import_models"}, mutate_tool( - "api", "open_files", L("Open files"), - "Open model files (STL, 3MF, STEP, OBJ, AMF, SVG...), a project (.3mf) or G-code by absolute path, without a file " - "dialog. Models are added to the current project. A .3mf given alone opens as a project, replacing the current " - "one, unless as is \"geometry\"; when the current project has unsaved changes that fails, changing nothing, unless " - "discard_changes. Given with other paths, a .3mf adds its models only. A G-code given alone replaces the project " - "too, to show its toolpaths: with unsaved changes the app asks first (blocked_by_dialog), whatever discard_changes " - "says. Importing can open a dialog (STEP mesh options, for instance); the reply is then blocked_by_dialog.", - object_schema({{"paths", array_prop({{"type", "string"}}, "Absolute paths.")}, - {"as", enum_prop({"auto", "geometry", "project"}, "How a .3mf given alone opens: as a project (auto, the " - "default, and project) or adding its models only " - "(geometry).")}, - {"discard_changes", prop("boolean", "Drop the project's unsaved changes rather than fail when a .3mf " + NativeCommand open = reaching({"open_project"}, mutate_tool( + "project_open", L("Open a project"), + "Open a project (.3mf) by absolute path, without a file dialog, replacing the current project, with the settings it " + "was saved with whatever the Preferences' Load behavior says; when the current project has unsaved changes that " + "fails, changing nothing, unless discard_changes. A G-code file replaces the project too, to show its toolpaths: " + "with unsaved changes the app asks first (blocked_by_dialog), whatever discard_changes says. project_import adds " + "models, or a project's objects alone, to the current project. Called with no arguments it is Load Project: the " + "Open dialog asks for the file (blocked_by_dialog), after asking about the unsaved changes. Reply: opened (project " + "or gcode), and objects, names and plates for a project, path for a G-code.", + object_schema({{"path", prop("string", "Absolute path of a .3mf project, or of a G-code file (.gcode, .bgcode).")}, + {"discard_changes", prop("boolean", "Drop the project's unsaved changes rather than fail when a project " "replaces it.")}}, - {"paths"}), + {"path"}), [](const json& args, ToolContext& ctx) { AutomationRuntime& runtime = ctx.runtime(); + std::string err; + const auto path = resolve_input_path(arg_string(args, "path"), err); + if (!path) + throw ToolFailure(err); + const bool gcode = has_extension(*path, {".gcode", ".bgcode"}); + if (!gcode && !has_extension(*path, {".3mf"})) + throw ToolFailure("project_open opens a .3mf project or a G-code file; project_import adds models to the project"); + // A run the user let drop unsaved changes (Run Script's "don't save") counts as discard_changes. + const bool discard = arg_bool(args, "discard_changes", false) || runtime.jobs().discard_allowed_in(ctx.lineage()); + json out = ctx.run_ui([&]() -> json { + Plater& plater = ui_plater(); + if (gcode) { + plater.load_gcode(from_path(*path)); + return {{"opened", "gcode"}, {"path", path_to_utf8(*path)}}; + } + Ops::OpenProjectArgs open; + open.path = *path; + open.unsaved = unsaved_changes_answer(discard); + const Ops::Outcome opened = Ops::open_project(open); + if (!opened) + throw refused(opened.refusal(), kUnsavedChangesHint); + json o = project_json(opened.value()); + o["opened"] = "project"; + return o; + }); + settle(ctx); + return ToolResult::ok(out); + })); + open.tiles = json::array({NativeCommands::tile("load_project", L("Load Project"), L("Commands"), "menu_open", json::object(), + "Open a project through the Open dialog (it asks first if the current project " + "has unsaved changes); project_open with a path opens that file without a " + "dialog.")}); + catalog.add(NativeCommands::with_person_form(std::move(open), [](const json&) { return Rows::load_project(); })); + + NativeCommand import_ = reaching({"import_models"}, mutate_tool( + "project_import", L("Import models"), + "Add the models of files (STL, 3MF, STEP, OBJ, AMF, SVG...) to the current project by absolute path, without a file " + "dialog, as one undo step; a .3mf adds its objects only, not its settings (project_open opens it as a project). A " + ".zip archive gives the model files it holds (STL, OBJ, AMF, 3MF, STEP; a .3mf its objects only, as above), as Import " + "ZIP Archive does: those entries names, by their paths in the archive, else all of them, in place of its file list; " + "an entry the archive lacks is refused with the names it has, before anything is imported. Importing can open a " + "dialog (STEP mesh options, for instance); the reply is then blocked_by_dialog. Called with no arguments it is " + "Import 3MF/STL/STEP/SVG/OBJ/AMF, and with archive: true alone Import ZIP Archive: a file dialog asks for the files, " + "or for the archive and then which of its files to import (blocked_by_dialog). Reply: opened (models), added (how " + "many objects), archives (each archive's path and the entries taken) and the project's objects, names and plates.", + object_schema({{"paths", array_prop({{"type", "string"}}, "Absolute paths of model files, or of a .zip archive of them.")}, + {"entries", {{"type", "array"}, + {"items", {{"type", "string"}}}, + {"minItems", 1}, + {"description", "The files to take from the one .zip archive among paths, by their paths " + "in it (\"parts/cube.stl\"). Default: every model file it holds."}}}, + {"archive", prop("boolean", "true, alone: ask for a ZIP archive in a file dialog and import the models " + "it holds, as Import ZIP Archive does.")}}, + {"paths"}), + [](const json& args, ToolContext& ctx) { + if (arg_bool(args, "archive", false)) + throw ToolFailure("archive asks for the archive in a file dialog, so it goes alone; paths imports files without one"); + if (args.contains("entries")) { + const json& given = args["paths"]; + const auto zips = std::count_if(given.begin(), given.end(), [](const json& p) { + return boost::algorithm::iends_with(p.get(), ".zip"); + }); + if (zips == 0) + throw ToolFailure("entries names files of a .zip archive: give the archive in paths"); + if (zips > 1) + throw ToolFailure("entries names the files of one archive: give one .zip in paths"); + } std::vector paths; for (const json& p : args["paths"]) { std::string err; auto resolved = resolve_input_path(p.get(), err); if (!resolved) throw ToolFailure(err); + if (has_extension(*resolved, {".gcode", ".bgcode"})) + throw ToolFailure(p.get() + " is a G-code file, which project_open opens to show its toolpaths"); paths.push_back(*resolved); } if (paths.empty()) throw ToolFailure("paths is empty"); - const std::string as = arg_string(args, "as", "auto"); - // A run the user let drop unsaved changes (Run Script's "don't save") counts as discard_changes. - const bool discard = arg_bool(args, "discard_changes", false) || runtime.jobs().discard_allowed_in(ctx.lineage()); json out = ctx.run_ui([&]() -> json { - Plater& plater = ui_plater(); - if (paths.size() == 1 && has_extension(paths[0], {".gcode", ".bgcode"})) { - plater.load_gcode(from_path(paths[0])); - return {{"opened", "gcode"}, {"path", path_to_utf8(paths[0])}}; - } - if (paths.size() == 1 && as != "geometry" && has_extension(paths[0], {".3mf"})) { - Ops::OpenProjectArgs open; - open.path = paths[0]; - open.unsaved = unsaved_changes_answer(discard); - const Ops::Outcome opened = Ops::open_project(open); - if (!opened) - throw refused(opened.refusal(), kUnsavedChangesHint); - json o = project_json(opened.value()); - o["opened"] = "project"; - return o; - } + Plater& plater = ui_plater(); Ops::ImportModelsArgs models; models.paths = paths; + if (args.contains("entries")) + models.entries = args["entries"].get>(); const Ops::Outcome imported = Ops::import_models(models); - if (!imported) - throw refused(imported.refusal(), "See get_log for the reason."); + if (!imported) { + const bool nothing = std::string(imported.refusal().code) == "nothing_loaded"; + throw refused(imported.refusal(), nothing ? "See app_log for the reason." : "", "entries"); + } json o = objects_summary(plater); o["opened"] = "models"; o["added"] = imported.value().added; + if (!imported.value().archives.empty()) { + json archives = json::array(); + for (const Ops::ImportedArchive& archive : imported.value().archives) + archives.push_back({{"path", path_to_utf8(archive.path)}, {"entries", archive.entries}}); + o["archives"] = std::move(archives); + } return o; }); settle(ctx); return ToolResult::ok(out); - }))); + })); + import_.tiles = json::array( + {NativeCommands::tile("import_file", L("Import 3MF/STL/STEP/SVG/OBJ/AMF"), L("Import"), "menu_open", json::object(), + "Import models (3MF/STL/STEP/SVG/OBJ/AMF) through a file dialog, as one undo step; a project " + "file's settings are not loaded (project_open opens a project). project_import with paths adds " + "files' geometry without a dialog."), + NativeCommands::tile("import_zip_archive", L("Import ZIP Archive"), L("Import"), "menu_open", {{"archive", true}}, + "Import models from a ZIP archive (opens a file dialog).")}); + catalog.add(NativeCommands::with_person_form(std::move(import_), [](const json& tile_args) { + return tile_args.value("archive", false) ? Rows::import_zip_archive() : Rows::import_file(); + })); - // The Speed Dial's New Project too: with no arguments it asks as the tile does. - catalog.add(NativeCommands::with_person_form(reaching({"new_project"}, mutate_tool( - {}, "new_project", {}, + // New Project's row is its tile: with no arguments it asks as the row does. + NativeCommand project_new = reaching({"new_project"}, mutate_tool( + "project_new", L("New Project"), "Start a new, empty project. Called with no arguments, it asks as New Project does, about the unsaved changes " - "if there are any: the reply is then blocked_by_dialog, and answer_dialog answers it. With arguments, or silent: " + "if there are any: the reply is then blocked_by_dialog, and dialog_answer answers it. With arguments, or silent: " "true, it asks nothing: it fails, changing nothing, when the current project has unsaved changes, unless " "discard_changes. The presets' unsaved changes carry over to the new project unless preset_changes is \"discard\", as " "New Project's prompt offers. Reply, with arguments: objects, names, plates; when presets had or have unsaved " @@ -486,28 +561,33 @@ void register_project_tools(CommandCatalog& catalog) }); settle(ctx); return ToolResult::ok(out); - })), - L("New Project"), L("Commands"), "menu_open", [] { - if (Plater* plater = wxGetApp().plater()) - plater->new_project(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; })); + project_new.tiles = json::array({NativeCommands::tile("new_project", L("New Project"), L("Commands"), "menu_open", json::object(), + "Runs project_new with no arguments, as New Project does: a new, empty " + "project, after asking about the unsaved changes if there are any.")}); + catalog.add(NativeCommands::with_person_form(std::move(project_new), [](const json&) { + if (Plater* plater = wxGetApp().plater()) + plater->new_project(); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; + })); - catalog.add(mutate_tool( - "api", "generate_calibration_test", L("Generate a calibration test"), + NativeCommand calibration = mutate_tool( + "calibration_generate_test", L("Generate a calibration test"), "Generate a Calibration menu test as its dialog's OK does: a new project named after the test with the test " "model, and the process, filament and printer presets changed as the test needs (presets_changed). The test prints " "with filament slot 1, so the filament tab is pointed at slot 1's preset. Omitted parameters take the dialog's " "defaults (pressure advance's by the printer's extruder type); temperatures are clamped to 155-500 °C and rounded " "down to 5 °C. Fails, changing nothing, when the project has unsaved changes (pass discard_changes) or presets do " - "(pass preset_changes). Reply: test, project, params (the values used, which the journal records), objects, names, " - "plates, presets_changed, result_keys (where the measured value belongs), warnings, adjusted (vfa), and discarded " - "and modified as new_project. Then slice and export. To save a measured value: new_project {discard_changes, " - "preset_changes: \"discard\"}, set_settings the value, save_preset.", + "(pass preset_changes). Called with test alone it opens that test's dialog, as the Calibration menu does " + "(blocked_by_dialog), and the dialog's OK runs the test; silent: true with test alone runs it with the dialog's " + "defaults. Reply: test, project, params (the values used, which the " + "journal records), objects, names, plates, presets_changed, result_keys (where the measured value belongs), " + "warnings, adjusted (vfa), and discarded and modified as project_new. Then plate_slice and project_export. To save " + "a measured value: project_new {discard_changes, preset_changes: \"discard\"}, settings_set the value, preset_save.", object_schema( {{"test", enum_prop({"temperature", "max_volumetric", "pressure_advance", "flow_ratio", "retraction", "vfa", "cornering", "input_shaping_freq", "input_shaping_damp"}, - "The test, named as the calib_* actions.")}, + "The test, as the Calibration menu names it.")}, {"method", enum_prop({"tower", "line", "pattern", "pass1", "pass2", "yolo", "yolo_perfectionist"}, "pressure_advance: tower (default), line or pattern; flow_ratio: pass1, pass2, yolo (default) or " "yolo_perfectionist.")}, @@ -617,7 +697,7 @@ void register_project_tools(CommandCatalog& catalog) if (!switched_from.empty()) presets_changed["filament"]["tab_switched_from"] = switched_from; if (plater.model().objects.empty()) - throw ToolFailure("The project was replaced but the test model was not added; see get_log", + throw ToolFailure("The project was replaced but the test model was not added; see app_log", {{"presets_changed", presets_changed}}); json reply = calib_params_json(args, params, printer); @@ -641,19 +721,64 @@ void register_project_tools(CommandCatalog& catalog) ctx.set_journal_args(std::move(recorded)); settle(ctx); return ToolResult::ok(out); - })); + }); + // The Calibration menu's rows, each the dialog of its test. The tab strip's calib_sf glyph is drawn white for the dark + // tab bar and vanishes on the palette's light tile, so each row borrows the matching settings-group icon instead. + struct CalibrationRow + { + const char* key; + const char* title; + const char* icon; + const char* test; + CalibKind kind; + }; + // Titles are L("...")-marked here so xgettext extracts them. + static const CalibrationRow calibration_rows[] = { + {"calib_temperature", L("Temperature Calibration"), "param_temperature", "temperature", CalibKind::Temperature}, + {"calib_max_volumetric", L("Max Volumetric Speed Calibration"), "param_volumetric_speed", "max_volumetric", + CalibKind::MaxVolumetric}, + {"calib_pressure_advance", L("Pressure Advance Calibration"), "param_flow_ratio_and_pressure_advance", "pressure_advance", + CalibKind::PressureAdvance}, + {"calib_flow_ratio", L("Flow Ratio Calibration"), "param_flow_ratio_and_pressure_advance", "flow_ratio", CalibKind::FlowRatio}, + {"calib_retraction", L("Retraction Calibration"), "param_retraction", "retraction", CalibKind::Retraction}, + {"calib_cornering", L("Cornering Calibration"), "param_precision", "cornering", CalibKind::Cornering}, + {"calib_input_shaping_freq", L("Input Shaping Frequency Calibration"), "param_resonance_avoidance", "input_shaping_freq", + CalibKind::InputShapingFreq}, + {"calib_input_shaping_damp", L("Input Shaping Damping Calibration"), "param_resonance_avoidance", "input_shaping_damp", + CalibKind::InputShapingDamp}, + {"calib_vfa", L("VFA Calibration"), "param_speed", "vfa", CalibKind::VFA}, + }; + calibration.tiles = json::array(); + for (const CalibrationRow& row : calibration_rows) + calibration.tiles.push_back(NativeCommands::tile(row.key, row.title, L("Calibration"), row.icon, {{"test", row.test}}, + std::string("Open the ") + row.title + + " dialog; calibration_generate_test with the test's parameters, or " + "silent, runs it with no dialog.")); + catalog.add(NativeCommands::with_person_form(std::move(calibration), [](const json& tile_args) { + const std::string test = tile_args.at("test"); + for (const CalibrationRow& row : calibration_rows) + if (test == row.test) + return Rows::calib(row.kind); + return AppActionRunResult{AppActionRunResult::Level::Error, from_u8("Unknown test \"" + test + "\""), false}; + })); - // The Speed Dial's Save Project too: with no arguments it saves as the tile does. - NativeCommand save = NativeCommands::with_person_form(reaching({"save_project_as"}, mutate_tool( - {}, "save_project", {}, + // Save Project's and Save Project As's rows are its tiles: with no arguments, or with save_as alone, it saves as the + // row does. + NativeCommand save = reaching({"save_project_as"}, mutate_tool( + "project_save", L("Save Project"), "Save the project. Called with no arguments, it saves as Save Project does: to the project's file (reply: ran, " - "level), or, when it has none, through a file dialog (blocked_by_dialog; a native picker needs auto_answer_dialogs " - "registered first). With path, it saves a .3mf there without the file dialog, and the file becomes the project's " - "(reply: path, bytes); a name ending in .gcode.3mf is refused (export writes that). Either way the save can still " - "open a dialog (blocked_by_dialog): a warning when settings name a plugin OrcaSlicer cannot identify, or an error " - "when the file cannot be written. A save that writes nothing, its file dialog or that warning cancelled or the " - "write failed, fails with project_not_saved, and a file already there stays as it was.", - object_schema({{"path", prop("string", "Absolute .3mf path.")}, {"overwrite", prop("boolean", "Replace an existing file.")}}, {"path"}), + "level), or, when it has none, through a file dialog (blocked_by_dialog; a native picker needs dialog_auto_answer " + "registered first); with save_as: true alone, as Save Project As does, always through the file dialog. With path, " + "it saves a .3mf there without the file dialog, and the file becomes the project's (reply: path, bytes); a name " + "ending in .gcode.3mf is refused (project_export writes that). Either way the save can still open a dialog " + "(blocked_by_dialog): a warning when settings name a plugin OrcaSlicer cannot identify, or an error when the file " + "cannot be written. A save that writes nothing, its file dialog or that warning cancelled or the write failed, " + "fails with project_not_saved, and a file already there stays as it was.", + object_schema({{"path", prop("string", "Absolute .3mf path.")}, + {"overwrite", prop("boolean", "Replace an existing file.")}, + {"save_as", prop("boolean", "true, alone: ask for the file in the save dialog, as Save Project As does. With " + "path it adds nothing: path is the new file.")}}, + {"path"}), [](const json& args, ToolContext& ctx) { std::string err; auto path = resolve_output_path(arg_string(args, "path"), arg_bool(args, "overwrite", false), err); @@ -665,42 +790,73 @@ void register_project_tools(CommandCatalog& catalog) save.path = *path; if (const Ops::Outcome saved = Ops::save_project_as(save); !saved) throw refused(saved.refusal(), std::string(saved.refusal().code) == "sliced_file_name" ? - "That is export {format: \"sliced_3mf\"} (plates \"all\" for every plate)." : - "See get_log."); + "That is project_export {format: \"sliced_3mf\"} (plates \"all\" for every plate)." : + "See app_log."); return json(); }); settle(ctx); return ToolResult::ok({{"path", path_to_utf8(*path)}, {"bytes", fs::file_size(*path)}}); - })), - L("Save Project"), L("Commands"), "menu_save", [] { - if (Plater* plater = wxGetApp().plater()) - return NativeCommands::project_save_result(plater->save_project(false)); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - // Any argument makes path required, and a call with path skips the file dialog: silent has nothing to add here. + })); + save.tiles = json::array( + {NativeCommands::tile("save_project", L("Save Project"), L("Commands"), "menu_save", json::object(), + "Runs project_save with no arguments, as Save Project does: to the project's file, or through a " + "file dialog when it has none."), + NativeCommands::tile("save_project_as", L("Save Project As"), L("Commands"), "menu_save", {{"save_as", true}}, + "Save the project as a .3mf file through the save dialog. project_save with a path saves there " + "without a dialog; a name ending in .gcode.3mf is refused (project_export {format: \"sliced_3mf\"} " + "writes that).")}); + save = NativeCommands::with_person_form(std::move(save), [](const json& tile_args) { + if (tile_args.value("save_as", false)) + return Rows::save_project_as(); + if (Plater* plater = wxGetApp().plater()) + return NativeCommands::project_save_result(plater->save_project(false)); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; + }); + // Every call but the two tiles' requires path, and a call with path skips the file dialog: silent has nothing to add. save.input_schema["properties"]["silent"]["description"] = - "Goes with path, which any argument makes required, and adds nothing to it: a call with path skips the file dialog already."; + "Goes with path, which every call but {} and {save_as: true} requires, and adds nothing to it: a call with path skips " + "the file dialog already."; catalog.add(save); - catalog.add(reaching({"start_gcode_export", "export_sliced_3mf", "export_model_3mf", "export_stl"}, mutate_tool( - "api", "export", L("Export"), + NativeCommand export_ = reaching( + {"start_gcode_export", "export_sliced_3mf", "export_model_3mf", "export_stl", "export_toolpaths_obj"}, + with_expected_ids(mutate_tool( + "project_export", L("Export"), "Write the project to a file without a dialog. gcode: the plate's G-code (slice first; it is written in the " "background, and the call returns once it is). sliced_3mf: the sliced plate, or all plates, as .gcode.3mf (slice " - "first: a plate that is not sliced is written without G-code). 3mf: the model without slicing data. stl: all " - "objects as one STL. Both hold every plate's objects. Without format, the path's extension (.gcode, .gcode.3mf, " - ".3mf, .stl) says which. Reply: path and bytes; for gcode, path and export (ok, or superseded with a note when the " - "project changed while it was written).", - object_schema({{"format", enum_prop({"gcode", "sliced_3mf", "3mf", "stl"}, "What to write; default from the path's extension.")}, - {"path", prop("string", "Absolute output path.")}, - {"plates", {{"type", {"string", "integer"}}, - {"description", "\"current\" (default), a plate index, which is selected first and is the plate " - "gcode and sliced_3mf write, or \"all\" (sliced_3mf only)."}}}, - {"overwrite", prop("boolean", "Replace an existing file.")}}, - {"path"}), + "first: a plate that is not sliced is written without G-code). 3mf: the model without slicing data. stl and drc " + "(Draco): the objects as one file, or with per_object each in a file of its own, named after it, into the folder " + "path names; every object of every plate, or those objects names. toolpaths_obj: the toolpaths the Preview shows, " + "as an OBJ, refused while it shows none (slice the plate and show the Preview first). Without format, the path's " + "extension (.gcode, .gcode.3mf, .3mf, .stl, .drc, .obj) says which. Called with exactly the arguments of one of the " + "File > Export rows (format alone, sliced_3mf with plates \"all\", stl or drc with per_object), it asks for the file " + "or folder in the dialog that row opens (blocked_by_dialog). A file per object of a project with no objects, and the " + "toolpaths while the Preview shows none, are refused in either form. Reply: path and bytes; for gcode, path and " + "export (ok, or superseded with a note when the project changed while it was written); for per_object, path and " + "files (each file written); for stl and drc, objects (those written).", + with_targets(object_schema({{"format", enum_prop({"gcode", "sliced_3mf", "3mf", "stl", "drc", "toolpaths_obj"}, + "What to write; default from the path's extension.")}, + {"path", prop("string", "Absolute output path: the file, or with per_object an existing folder.")}, + {"plates", {{"type", {"string", "integer"}}, + {"description", "\"current\" (default), a plate index, which is selected first and is " + "the plate gcode and sliced_3mf write, or \"all\" (sliced_3mf only)."}}}, + {"per_object", prop("boolean", "stl and drc: a file per object, into a folder. Default false.")}, + {"overwrite", prop("boolean", "Replace an existing file.")}}, + {"path"}), + kObjects, false), [](const json& args, ToolContext& ctx) { - const std::string format = args.contains("format") ? arg_string(args, "format") : format_of(arg_string(args, "path")); - std::string err; - auto path = resolve_output_path(arg_string(args, "path"), arg_bool(args, "overwrite", false), err); + const std::string format = args.contains("format") ? arg_string(args, "format") : format_of(arg_string(args, "path")); + const bool per_object = arg_bool(args, "per_object", false); + const bool meshes = format == "stl" || format == "drc"; + if (per_object && !meshes) + throw ToolFailure("per_object goes with format stl or drc"); + if (per_object && (args.contains("plates") || args.contains("overwrite"))) + throw ToolFailure("per_object writes every object into the folder path names: plates and overwrite go with one file"); + if (format == "toolpaths_obj" && args.contains("plates")) + throw ToolFailure("toolpaths_obj writes the toolpaths the Preview shows: plates goes with the other formats"); + std::string err; + const auto path = per_object ? resolve_output_dir(arg_string(args, "path"), err) : + resolve_output_path(arg_string(args, "path"), arg_bool(args, "overwrite", false), err); if (!path) throw ToolFailure(err); const json plate = args.value("plates", json("current")); @@ -708,12 +864,53 @@ void register_project_tools(CommandCatalog& catalog) if (all && format != "sliced_3mf") throw ToolFailure("plates \"all\" applies to sliced_3mf only"); std::optional ticket; + json written = json::object(); // what the reply adds for stl and drc ctx.run_ui([&]() -> json { // A G-code export finishes in the background: held from before it starts. if (format == "gcode") ctx.begin_operation(); - ui_plater(); + Plater& plater = ui_plater(); const std::optional index = plate.is_number_integer() ? std::optional(plate.get()) : std::nullopt; + // The objects named, by index or id; none named: every object. + Targets named; + if (names_targets(args)) { + const Ops::Outcome found = resolve_targets(plater.model(), nullptr, args, kObjects, false); + if (!found) + throw refused(found.refusal()); + named = found.value(); + } + if (const std::optional refusal = + Ops::export_objects_refusal(format, named.objects, per_object, plater.model())) + throw refused(*refusal); + if (meshes) { + Ops::ExportStlArgs mesh; + mesh.path = *path; + mesh.plate = index; + mesh.objects = named.objects; + mesh.per_object = per_object; + mesh.draco = format == "drc"; + const Ops::Outcome> files = Ops::export_stl(mesh); + if (!files) + throw refused(files.refusal(), std::string(files.refusal().code) == "file_not_written" ? "See app_log." : ""); + Targets exported = named; + if (exported.objects.empty()) + for (int o = 0; o < int(plater.model().objects.size()); ++o) + exported.objects.push_back(o); + written = targets_reply(plater.model(), exported); + if (per_object) { + written["files"] = json::array(); + for (const fs::path& file : files.value()) + written["files"].push_back(path_to_utf8(file)); + } + return json(); + } + if (format == "toolpaths_obj") { + if (const Ops::Outcome drawn = Ops::export_toolpaths_obj({*path}); !drawn) + throw refused(drawn.refusal(), std::string(drawn.refusal().code) == "no_toolpaths" ? + "plate_slice {preview: true} slices the plate and shows it." : + "See app_log."); + return json(); + } if (format == "gcode") { Ops::ExportGcodeArgs gcode; gcode.path = *path; @@ -721,8 +918,8 @@ void register_project_tools(CommandCatalog& catalog) const Ops::Outcome started = Ops::start_gcode_export(gcode); if (!started) { const std::string code = started.refusal().code; - throw refused(started.refusal(), code == "slicing_in_progress" ? "wait {for:\"idle\"} waits for it." : - code == "export_not_started" ? "Check get_app_state.notifications." : + throw refused(started.refusal(), code == "slicing_in_progress" ? "app_wait {for:\"idle\"} waits for it." : + code == "export_not_started" ? "Check app_state.notifications." : ""); } ticket = started.value(); @@ -735,18 +932,64 @@ void register_project_tools(CommandCatalog& catalog) Ops::ExportFileArgs file; file.path = *path; file.plate = index; - const Ops::Outcome written = format == "sliced_3mf" ? Ops::export_sliced_3mf(sliced) : - format == "3mf" ? Ops::export_model_3mf(file) : - Ops::export_stl(file); - if (!written) - throw refused(written.refusal(), std::string(written.refusal().code) == "file_not_written" ? "See get_log." : ""); + const Ops::Outcome done = format == "sliced_3mf" ? Ops::export_sliced_3mf(sliced) : Ops::export_model_3mf(file); + if (!done) + throw refused(done.refusal(), std::string(done.refusal().code) == "file_not_written" ? "See app_log." : ""); return json(); }); if (ticket) return await_gcode_export(ctx, *ticket); settle(ctx); - return ToolResult::ok({{"path", path_to_utf8(*path)}, {"bytes", fs::file_size(*path)}}); + json reply{{"path", path_to_utf8(*path)}}; + if (!per_object) + reply["bytes"] = fs::file_size(*path); + reply.update(written); + return ToolResult::ok(reply); }))); + // The File > Export rows, each with the dialog it asks for the file or folder in. + export_.tiles = json::array({ + NativeCommands::tile("export_gcode", L("Export G-code"), L("Slice & Export"), "custom-gcode_gcode", {{"format", "gcode"}}, + "Export the current plate's G-code through the export dialog, in the background. project_export " + "with a path exports the sliced plate there without a dialog, and the call returns when the file " + "is written; a plate that is not sliced is refused (slice first)."), + NativeCommands::tile("export_sliced_file", L("Export Sliced File"), L("Slice & Export"), "save", {{"format", "sliced_3mf"}}, + "Export the current plate's sliced file (.gcode.3mf) through a file dialog; project_export with a " + "path writes there without one."), + NativeCommands::tile("export_all_sliced_file", L("Export All Sliced Files"), L("Slice & Export"), "save", + {{"format", "sliced_3mf"}, {"plates", "all"}}, + "Export every plate's sliced file into one .gcode.3mf through a file dialog; project_export with a " + "path writes there without one."), + NativeCommands::tile("export_3mf", L("Export 3MF"), L("Slice & Export"), "menu_save", {{"format", "3mf"}}, + "Export the model as a .3mf without slicing data, through a file dialog; project_export with a path " + "writes there without one."), + NativeCommands::tile("export_stl", L("Export STL"), L("Slice & Export"), "save", {{"format", "stl"}}, + "Export all objects as one STL through a file dialog; project_export with a path writes there " + "without one."), + NativeCommands::tile("export_stl_multi", L("Export All Objects as STLs"), L("Export"), "save", {{"format", "stl"}, {"per_object", true}}, + "Export each object as its own STL into the folder a dialog asks for; project_export with a folder " + "as path writes there without one."), + NativeCommands::tile("export_drc_single", L("Export All Objects as DRC (one file)"), L("Export"), "save", {{"format", "drc"}}, + "Export all objects as one Draco (.drc) file."), + NativeCommands::tile("export_drc_multi", L("Export All Objects as DRCs"), L("Export"), "save", {{"format", "drc"}, {"per_object", true}}, + "Export each object as its own Draco (.drc) file."), + NativeCommands::tile("export_toolpaths_obj", L("Export Toolpaths as OBJ"), L("Export"), "custom-gcode_gcode", + {{"format", "toolpaths_obj"}}, "Export the sliced toolpaths as an OBJ."), + }); + catalog.add(NativeCommands::with_person_form(std::move(export_), [](const json& tile_args) { + const std::string format = tile_args.at("format"); + const bool per_object = tile_args.value("per_object", false); + if (format == "gcode") + return Rows::export_gcode(); + if (format == "sliced_3mf") + return Rows::export_sliced_file(tile_args.value("plates", std::string()) == "all"); + if (format == "3mf") + return Rows::export_3mf(); + if (format == "stl") + return per_object ? Rows::export_stl_multi() : Rows::export_stl(); + if (format == "drc") + return per_object ? Rows::export_drc_multi() : Rows::export_drc_single(); + return Rows::export_toolpaths_obj(); + })); } }}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpToolsPython.cpp b/src/slic3r/GUI/Mcp/McpToolsPython.cpp index 3e4335e448..586d260e98 100644 --- a/src/slic3r/GUI/Mcp/McpToolsPython.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsPython.cpp @@ -1,4 +1,4 @@ -// run_script and search_python_api: Python scripts against orca.host, the plugin API, and the orca package's +// script_run and script_search_api: Python scripts against orca.host, the plugin API, and the orca package's // reference. #include "JobRegistry.hpp" @@ -9,7 +9,9 @@ #include "AutomationRuntime.hpp" #include "McpTools.hpp" +#include "slic3r/GUI/ActionRegistry.hpp" #include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/NativeCommandRows.hpp" #include "slic3r/GUI/NativeCommands.hpp" #include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/GUI_App.hpp" @@ -44,7 +46,7 @@ namespace py = pybind11; namespace { -// A run's orca.host.tools calls, as child calls of the run_script job, so each has its tool's guards, +// A run's orca.host.tools calls, as child calls of the script_run job, so each has its tool's guards, // admission and undo, and a cancel of the run reaches them. class RunBridge final : public ToolBridge { @@ -63,13 +65,13 @@ private: }; // The Run Script panel's session's orca.host.tools calls: child calls under a lineage node of the session's job, so a -// stop cancels every call in flight, inline ones (wait) included, without stopping the session, and the next work's +// stop cancels every call in flight, inline ones (app_wait) included, without stopping the session, and the next work's // calls run under a fresh node. class SessionBridge final : public ToolBridge { public: SessionBridge(AutomationRuntime& runtime, const std::string& session_job) - : m_runtime(runtime), m_node(runtime.jobs(), "run_script", session_job) + : m_runtime(runtime), m_node(runtime.jobs(), "script_run", session_job) {} json call(const std::string& tool, const json& args) override { @@ -79,7 +81,7 @@ public: return r.data; } // A stop or time-out, from the session's watcher: the node's calls are cancelled, and its operations, as the - // cancel_job cancels them. + // job_cancel cancels them. void stop_calls() { const std::string node = m_node.id(); @@ -257,7 +259,7 @@ bool python_has_numpy() ToolResult run_python_session_job(AutomationRuntime& runtime, ToolContext& ctx, PythonSession& session, const std::string& filename) { const std::string job = ctx.job_id(); - // The session waits for the person between works: `wait {for: "idle"}` counts only the calls it makes. + // The session waits for the person between works: `app_wait {for: "idle"}` counts only the calls it makes. runtime.jobs().set_idle(job); // What its calls leave behind is the session's, as a run's is; its rules act only while a work runs. runtime.begin_run_scope(job); @@ -291,14 +293,14 @@ ToolResult run_python_session_job(AutomationRuntime& runtime, ToolContext& ctx, std::shared_ptr start_python_session(AutomationRuntime& runtime, std::shared_ptr session, const boost::filesystem::path& file, PersonRun::Events events) { - const NativeCommand* run_script = NativeCommands::instance().find("run_script"); - if (run_script == nullptr || runtime.stopping() || !session) + const NativeCommand* script_run = NativeCommands::instance().find("script_run"); + if (script_run == nullptr || runtime.stopping() || !session) return nullptr; auto run = std::make_shared(runtime, std::move(events)); auto hosted = std::make_shared>(false); - auto filename = file.empty() ? std::string("") : path_to_utf8(file); - // run_script's properties, outside the session journal, as a person's run. - NativeCommand def = *run_script; + auto filename = file.empty() ? std::string("") : path_to_utf8(file); + // script_run's properties, outside the session journal, as a person's run. + NativeCommand def = *script_run; def.journal = false; def.run = [&runtime, run, session, hosted, filename](const json&, ToolContext& ctx) { run->set_job(ctx.job_id()); @@ -337,12 +339,12 @@ std::shared_ptr start_python_session(AutomationRuntime& runtime, std: void register_python_tools(CommandCatalog& catalog) { NativeCommand run = mutate_tool( - "core", "run_script", L("Run a Python script"), + "script_run", L("Run a Python script"), "Run Python code inside OrcaSlicer as its main program (__name__ == \"__main__\") against orca.host, the whole plugin " - "API (search_python_api searches it): read objects, meshes and settings, compute, use orca.host.ui and the preset " + "API (script_search_api searches it): read objects, meshes and settings, compute, use orca.host.ui and the preset " "API, and call these same tools, with their guards and undo, through orca.host.tools.call(name, args). Mesh and " "matrix arrays need numpy, which " - "search_python_api says is installed or not; a file run's PEP 723 block can install it. The code runs on a worker " + "script_search_api says is installed or not; a file run's PEP 723 block can install it. The code runs on a worker " "thread, where calls documented as UI thread only raise RuntimeError. The run ends once its code and the non-daemon " "threads and pool tasks it started are done; its windows close with it. `args` holds the args you pass; set `result` " "to a JSON value to return it; print() output comes back as output. Reply: {status: finished | raised | cancelled | " @@ -350,14 +352,14 @@ void register_python_tools(CommandCatalog& catalog) "own file access is held to OrcaSlicer's folders (its data folder, and read only its resources folder and, for a " "file run, the file's folder), and it starts no programs or threads and reaches no network: such an access raises " "PermissionError, unless a person has let Python scripts run unrestricted in Preferences " - "(get_app_state.python.scripts_unrestricted), when the threads and pool tasks it starts call the tools too while " + "(app_state.python.scripts_unrestricted), when the threads and pool tasks it starts call the tools too while " "the run lasts; the tools it calls work as they do for you. Recorded " - "by export_replay as one step with its code, which a replay runs again against the project as it is then.", + "by replay_export as one step with its code, which a replay runs again against the project as it is then.", object_schema({{"code", prop("string", "Python source, run as a module body.")}, {"args", {{"type", "object"}, {"description", "Bound to the name `args` in the code."}}}, {"timeout_s", {{"type", "integer"}, {"minimum", 1}, {"maximum", 3600}, {"description", "The run is stopped as timed_out after this many seconds (default 300)."}}}, - {"filename", prop("string", "The name tracebacks show for the code (default ). An existing file's " + {"filename", prop("string", "The name tracebacks show for the code (default ). An existing file's " "path makes it a file run, as `python file.py` runs it: __file__, sys.argv, imports " "from its folder and its PEP 723 dependencies; any other name only names it. " "What runs is still `code`: pass the file's text there.")}}, @@ -373,7 +375,7 @@ void register_python_tools(CommandCatalog& catalog) // A run owns what its calls leave behind (auto-answer rules, a recording, a held press) as a JSON // script does: it all ends with the run. const std::string job = ctx.job_id(); - // A run may wait for a person in its window: `wait {for: "idle"}` counts only the calls it makes. + // A run may wait for a person in its window: `app_wait {for: "idle"}` counts only the calls it makes. runtime.jobs().set_idle(job); runtime.begin_run_scope(job); struct ScopeEnd @@ -389,7 +391,7 @@ void register_python_tools(CommandCatalog& catalog) request.code = arg_string(args, "code"); request.args = args.value("args", json::object()); request.identity = identity; - request.filename = arg_string(args, "filename", ""); + request.filename = arg_string(args, "filename", ""); // 0, below the schema's minimum, is passed only in process, by the Run Script dialog, whose Stop ends a run: // every external path validates the arguments. It means no time limit. request.budget = std::chrono::seconds(arg_int(args, "timeout_s", 300)); @@ -405,19 +407,19 @@ void register_python_tools(CommandCatalog& catalog) data["traceback"] = out.traceback; if (!out.message.empty()) data["message"] = out.message; - // A run that did not finish is reported, not failed, as run_replay reports a failed step: the + // A run that did not finish is reported, not failed, as replay_run reports a failed step: the // journal keeps it, and a replay of it fails again (D7). return ToolResult::ok(std::move(data)); }); - // cancel_job {job} stops a run: its code is interrupted at its next bytecode. + // job_cancel {job} stops a run: its code is interrupted at its next bytecode. run.cancellable = true; // A script reaches outside the app: files, programs and the network. run.open_world = true; catalog.add(run); catalog.add(inspect_tool( - "core", "search_python_api", L("Search the Python API"), - "Search orca, the Python API of run_script scripts and plugins, in the running build: orca.host (the project's " + "script_search_api", L("Search the Python API"), + "Search orca, the Python API of script_run scripts and plugins, in the running build: orca.host (the project's " "model and meshes, presets and their editors, slicing data, orca.host.ui windows and dialogs, orca.host.tools " "calling these tools) and the classes, events and pages plugins build on. Each entry has its kind, signature (a " "class's constructors) and documentation. A query ranks them, best match first; without one, the whole package is " @@ -445,6 +447,17 @@ void register_python_tools(CommandCatalog& catalog) out["numpy"] = python_has_numpy(); return ToolResult::ok(std::move(out)); })); + + // The Run Script panel's menu row, which has no argument form. + const std::string panel = "Show or hide the Run Script panel, where a person writes and runs Python scripts cell by cell. Agents " + "run Python with the script_run tool instead."; + NativeCommand toggle_panel = row_command("script_toggle_panel", L("Run Script"), panel, object_schema({}), + json::array({NativeCommands::tile("toggle_run_script_panel", L("Run Script"), + L("Commands"), "media_play", json::object(), panel)}), + [](const json&) { return Rows::toggle_run_script_panel(); }); + // A menu row with no argument form: tool_search finds it and tool_call runs it, the tool list does not show it. + toggle_panel.listed = false; + catalog.add(std::move(toggle_panel)); } }}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpToolsRecord.cpp b/src/slic3r/GUI/Mcp/McpToolsRecord.cpp index 66e001927d..94e9c23b4e 100644 --- a/src/slic3r/GUI/Mcp/McpToolsRecord.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsRecord.cpp @@ -1,4 +1,4 @@ -// start_recording, stop_recording and encode_recording: a video of what OrcaSlicer shows, optionally captioned +// recording_start, recording_stop and recording_encode: a video of what OrcaSlicer shows, optionally captioned // with the current tool call and its pointer highlighted, and its encode to MP4. #include "McpCore.hpp" @@ -48,10 +48,9 @@ namespace { // The recording tools only read the app, so they run behind dialogs and during operations, but each // is a job: ownership is read from the job's ancestry, and an encode outlives the reply budget. -NativeCommand record_tool(std::string group, std::string name, std::string title, std::string description, json schema, CommandFn handler) +NativeCommand record_tool(std::string name, std::string title, std::string description, json schema, CommandFn handler) { - NativeCommand d = NativeCommands::long_command(std::move(name), std::move(title), std::move(group), std::move(schema), - std::move(handler)); + NativeCommand d = NativeCommands::long_command(std::move(name), std::move(title), {}, std::move(schema), std::move(handler)); d.description = std::move(description); d.listed = true; d.guard = GuardClass::Inspect; @@ -99,30 +98,30 @@ std::vector encode_preset_keys() ToolResult start_encode(AutomationRuntime& runtime, const json& args) { - const NativeCommand* encode = NativeCommands::instance().find("encode_recording"); + const NativeCommand* encode = NativeCommands::instance().find("recording_encode"); if (encode == nullptr || runtime.stopping()) return ToolResult::error("OrcaSlicer is shutting down"); NativeCommand def = *encode; def.journal = false; - def.budget_ms = 0; // the envelope at once; the result comes from wait + def.budget_ms = 0; // the envelope at once; the result comes from app_wait return runtime.core().call(def, args); } void register_record_tools(CommandCatalog& catalog) { - // The Speed Dial's Start Recording too: with no arguments it opens the tile's dialog. - catalog.add(NativeCommands::with_person_form(record_tool( - {}, "start_recording", {}, - "Record a video of OrcaSlicer until stop_recording: the main window with any modal dialog on it (target main), or " + // The Speed Dial's Start Recording is its tile: with no arguments it opens the tile's dialog. + NativeCommand start = record_tool( + "recording_start", L("Start Recording"), + "Record a video of OrcaSlicer until recording_stop: the main window with any modal dialog on it (target main), or " "the 3D view shown (canvas). Frames are MJPEG in a Matroska (.mkv) file with their real timestamps. With captions, " "the tool call acting on the app shows as a caption at the bottom (secret setting values never show); with pointer, " "the pointer is highlighted, its clicks rippling. Capture takes at most about a third of the UI thread, so " "the frame rate drops where capturing is slow. One recording at a time: one a replay or script starts ends with it, a " - "client's when the server is turned off. With encode, the stop_recording that reports it also encodes it to an MP4 " - "beside it, as the Start Recording command does, and the .mkv is deleted once the MP4 is written unless " - "keep_raw_video_file; encode_recording makes an MP4 of any recording later. Called with no " - "arguments, it opens the Start Recording dialog instead, as the Start Recording command does (blocked_by_dialog): " - "its controls are named after their settings for set_widget_value, answer_dialog \"Start recording\" starts the " + "client's when the server is turned off. With encode, the recording_stop that reports it also encodes it to an MP4 " + "beside it, as Start Recording does, and the .mkv is deleted once the MP4 is written unless " + "keep_raw_video_file; recording_encode makes an MP4 of any recording later. Called with no " + "arguments, it opens the Start Recording dialog instead, as Start Recording does (blocked_by_dialog): " + "its controls are named after their settings for widget_set_value, dialog_answer \"Start recording\" starts the " "person's recording, which neither the end of a replay or script nor the server turning off ends, and the dialog " "remembers the settings; silent: true starts one here at once with the defaults.", object_schema({{"target", enum_prop({"main", "canvas"}, "main (default): the main window and its dialogs; canvas: the 3D view shown.")}, @@ -225,23 +224,28 @@ void register_record_tools(CommandCatalog& catalog) recorded["save_path"] = out["path"]; ctx.set_journal_args(std::move(recorded)); return ToolResult::ok(out); - }), - L("Start Recording"), L("Commands"), "recording_start", NativeCommands::start_person_recording)); + }); + start.tiles = json::array({NativeCommands::tile("start_recording", L("Start Recording"), L("Commands"), "recording_start", + json::object(), + "Runs recording_start with no arguments, as Start Recording does: the Start " + "Recording dialog, whose Start recording starts the person's recording, " + "which neither the end of a replay or script nor the server turning off ends.")}); + catalog.add(NativeCommands::with_person_form(std::move(start), [](const json&) { return NativeCommands::start_person_recording(); })); - // The Speed Dial's Stop Recording too: with no arguments it stops as the tile does. - NativeCommand stop = NativeCommands::with_person_form(record_tool({}, "stop_recording", {}, + // The Speed Dial's Stop Recording is its tile: with no arguments it stops as the tile does. + NativeCommand stop = record_tool("recording_stop", L("Stop Recording"), "Stop the running recording. Call it with silent: true for the report: it waits for the file and " "returns it with its seconds, frames captured and " "written, frames dropped when encoding fell behind, failed when they could not be encoded, or " "skipped when the window could not be captured, " "the size, the mean UI-thread time a capture took (capture_ms), and why it ended. A recording that ended on its own (max_seconds, the replay or script that started it ended, a " - "write error) is reported once by the next stop_recording. For a recording started with encode, it then " - "starts the MP4 encode and returns it under encode: a job, whose wait {for: \"job\"} returns " - "encode_recording's result, whose raw_video_file_deleted says whether the .mkv was deleted. " + "write error) is reported once by the next recording_stop. For a recording started with encode, it then " + "starts the MP4 encode and returns it under encode: a job, whose app_wait {for: \"job\"} returns " + "recording_encode's result, whose raw_video_file_deleted says whether the .mkv was deleted. " "Called with no arguments, it stops " - "the recording as the Stop Recording command does, whoever started it: without waiting for its " + "the recording as Stop Recording does, whoever started it: without waiting for its " "file, it shows the person a notification naming it and replies with its path; the next " - "stop_recording with silent: true reports it as ended stopped_in_app.", + "recording_stop with silent: true reports it as ended stopped_in_app.", object_schema({}), [](const json&, ToolContext& ctx) { AutomationRuntime& runtime = ctx.runtime(); // The last state too, even if the timer has not ticked since the last call. Without the @@ -262,20 +266,26 @@ void register_record_tools(CommandCatalog& catalog) report["encode"] = r.is_error ? json{{"error", r.message}} : r.data; } return ToolResult::ok(report); - }), - // The person's stop opens nothing: like the silent one, it stops a recording behind a dialog. - L("Stop Recording"), L("Commands"), "recording_stop", NativeCommands::stop_recording_in_app, /*person_form_behind_dialogs=*/true); + }); + stop.tiles = json::array({NativeCommands::tile("stop_recording", L("Stop Recording"), L("Commands"), "recording_stop", + json::object(), + "Runs recording_stop with no arguments, as Stop Recording does: it stops the " + "recording, whoever started it, and shows the person a notification naming its " + "file.")}); + // The person's stop opens nothing: like the silent one, it stops a recording behind a dialog. + stop = NativeCommands::with_person_form(std::move(stop), [](const json&) { return NativeCommands::stop_recording_in_app(); }, + /*person_form_behind_dialogs=*/true); // It has no other argument, and neither form asks: silent picks the form that waits and reports. stop.input_schema["properties"]["silent"]["description"] = "true waits for the file and returns the report, and the encode job when the recording has one; a call with no " - "arguments stops as the Stop Recording command does."; + "arguments stops as Stop Recording does."; catalog.add(stop); NativeCommand encode = record_tool( - "ui", "encode_recording", L("Encode a recording"), + "recording_encode", L("Encode a recording"), "Encode a recording into an H.265 (or H.264) MP4 with the system ffmpeg (ORCA_FFMPEG, else ffmpeg on PATH; it " "needs libx265 or libx264), keeping its timing. Takes this session's last finished recording unless path names " - "one, and writes beside it unless save_path says where. A long encode returns a job: wait for it, or cancel_job {job} " + "one, and writes beside it unless save_path says where. A long encode returns a job: app_wait waits for it, or job_cancel {job} " "stops it. Once the MP4 is written, it deletes the .mkv if this session recorded it, unless keep_raw_video_file; " "any other .mkv is kept. raw_video_file_deleted in the reply says which.", object_schema({{"path", prop("string", "Absolute .mkv of a finished recording; default this session's last.")}, diff --git a/src/slic3r/GUI/Mcp/McpToolsReplay.cpp b/src/slic3r/GUI/Mcp/McpToolsReplay.cpp index bf654f0508..74a986fdb8 100644 --- a/src/slic3r/GUI/Mcp/McpToolsReplay.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsReplay.cpp @@ -1,4 +1,4 @@ -// run_replay and export_replay: deterministic replays of tool calls, and turning a session into one. +// replay_run and replay_export: deterministic replays of tool calls, and turning a session into one. #include "JobRegistry.hpp" #include "slic3r/GUI/CommandTypes.hpp" @@ -111,7 +111,7 @@ json run_replay_job(AutomationRuntime& runtime, ToolContext& ctx, const Replay& void register_replay_tools(CommandCatalog& catalog) { NativeCommand run = mutate_tool( - "core", "run_replay", L("Run a replay"), + "replay_run", L("Run a replay"), std::string("Replay a list of tool calls in order and report each step: {orca_replay_version:\"") + REPLAY_VERSION + "\", name, vars, steps:[{tool, args, expect, " "optional, await, save_as, timeout_s}]}, JSON with comments. Strings may use ${replay_dir}, ${out_dir}, ${env:NAME}, " @@ -120,7 +120,7 @@ void register_replay_tools(CommandCatalog& catalog) "matchers (eq ne gt ge lt le contains regex exists empty); the first failed step or expectation stops the run unless " "the step is optional. Writes result.json to out_dir (default: the replay file's name with .out, beside it; for an " "inline replay, replay- in the session's output folder). Reply: passed, steps, failed_step, out_dir and " - "result_file. auto_answer_dialogs rules a replay registers end with it. export_replay turns this session into one.", + "result_file. dialog_auto_answer rules a replay registers end with it. replay_export turns this session into one.", object_schema({{"path", prop("string", "Absolute path of a replay file.")}, {"replay", {{"type", json::array({"object", "string"})}, {"description", "The replay itself, as an object or as its JSON text, instead of path."}}}, @@ -171,16 +171,16 @@ void register_replay_tools(CommandCatalog& catalog) json result = run_replay_job(runtime, ctx, *replay, sctx, ReplayRunOptions{}); return ToolResult::ok(std::move(result)); }); - // Its steps call any tool, run_script included. + // Its steps call any tool, script_run included. run.open_world = true; catalog.add(run); NativeCommand exp = inspect_tool( - "core", "export_replay", L("Export this session as a replay"), - "Turn the calls this session made into a replay that run_replay runs: mutating calls, wait, screenshot and the " - "recording tools, in order, with refs replaced by locators, job replies replayed with await:false, and screenshot " + "replay_export", L("Export this session as a replay"), + "Turn the calls this session made into a replay that replay_run runs: mutating calls, app_wait, window_screenshot and the " + "recording tools, in order, with refs replaced by locators, job replies replayed with await:false, and window_screenshot " "and recording paths moved under ${out_dir}. " - "Calls that failed, at once or as a job later, are left out (a run_script that raised or timed out replied, so it " + "Calls that failed, at once or as a job later, are left out (a script_run that raised or timed out replied, so it " "stays); so is a call whose job is still running (unless it " "waits on a dialog), which left_out_running lists as {tool, job}. " "Reply: the replay, which with path is also written there. clear:true then forgets the calls made so far.", @@ -191,7 +191,7 @@ void register_replay_tools(CommandCatalog& catalog) [](const json& args, ToolContext& ctx) { AutomationRuntime& runtime = ctx.runtime(); if (!ctx.caller_plugin().empty()) - throw ToolFailure("export_replay exports the agent's session, which a plugin's calls are not part of"); + throw ToolFailure("replay_export exports the agent's session, which a plugin's calls are not part of"); json running; json replay = runtime.journal().to_replay(arg_string(args, "name", "session " + timestamp()), &running); json out{{"steps", replay["steps"].size()}}; diff --git a/src/slic3r/GUI/Mcp/McpToolsScene.cpp b/src/slic3r/GUI/Mcp/McpToolsScene.cpp index d1c7383530..f03fca9574 100644 --- a/src/slic3r/GUI/Mcp/McpToolsScene.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsScene.cpp @@ -1,6 +1,12 @@ -// list_objects, select_objects, transform, add_part, arrange, slice and cancel_job: the model on the plates, the +// object_list, object_select, object_transform, part_add, object_arrange, plate_slice and job_cancel: the model on the plates, the // arrange and Fill bed jobs, and the slice operation, which reports its own outcome per plate (see -// Operations/RunStatus). +// Operations/RunStatus). The object and part commands made from menu rows: those that add a primitive, delete, rename, +// set the number of instances, make instances separate objects, split, assemble, order, mirror, centre, scale to fit, +// drop and orient objects and change a part's type take their targets (McpTargets.hpp) and run their operations +// (Operations/ObjectOps, ProjectOps); the others run their rows' functions (NativeCommandRows.hpp) on the selection. +// The object and part commands of menu items with no Speed Dial tile, which mark objects printable, turn their Auto Drop +// on or off, repair their meshes, clone them, reload them from their files and replace a part's mesh, take their targets +// and run their operations too. #include "CanvasTarget.hpp" #include "slic3r/GUI/I18N.hpp" @@ -10,23 +16,32 @@ #include "libslic3r/Point.hpp" #include "McpPaths.hpp" #include "AutomationRuntime.hpp" +#include "McpArguments.hpp" +#include "McpTargets.hpp" #include "McpTools.hpp" #include "UiInspector.hpp" #include "slic3r/GUI/3DScene.hpp" +#include "slic3r/GUI/ActionRegistry.hpp" #include "slic3r/GUI/Camera.hpp" +#include "slic3r/GUI/CommandCatalog.hpp" #include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/GUI_App.hpp" +#include "slic3r/GUI/GUI_Factories.hpp" #include "slic3r/GUI/GUI_Geometry.hpp" #include "slic3r/GUI/GUI_ObjectList.hpp" #include "slic3r/GUI/Gizmos/GLGizmosManager.hpp" #include "slic3r/GUI/Jobs/Worker.hpp" #include "slic3r/GUI/MainFrame.hpp" +#include "slic3r/GUI/NativeCommandRows.hpp" #include "slic3r/GUI/NativeCommands.hpp" #include "slic3r/GUI/NotificationManager.hpp" +#include "slic3r/GUI/ObjectDataViewModel.hpp" +#include "slic3r/GUI/Operations/ObjectOps.hpp" #include "slic3r/GUI/Operations/Outcome.hpp" #include "slic3r/GUI/Operations/PlateOps.hpp" +#include "slic3r/GUI/Operations/ProjectOps.hpp" #include "slic3r/GUI/Operations/RunStatus.hpp" #include "slic3r/GUI/PartPlate.hpp" #include "slic3r/GUI/Plater.hpp" @@ -50,6 +65,7 @@ #include #include #include +#include #include #include @@ -60,6 +76,7 @@ #include #include #include +#include #include #include #include @@ -87,30 +104,48 @@ Vec3d to_vec3(const json& v, const char* what) return {v[0].get(), v[1].get(), v[2].get()}; } +// The canvas whose selection the view shown has, switching no view: the assemble view while it is shown, else the +// Prepare view's, whose selection stays while Preview or another tab is shown. +GLCanvas3D& selection_canvas(Plater& plater) +{ + if (GLCanvas3D* assemble = plater.get_assmeble_canvas3D(); assemble != nullptr && plater.get_current_canvas3D() == assemble) + return *assemble; + return *plater.get_view3D_canvas3D(); +} + // The 3D canvas object operations act on: the assemble view while it is shown, else the Prepare // view, switched to when another is shown. GLCanvas3D& object_canvas() { - Plater& plater = ui_plater(); - if (GLCanvas3D* assemble = plater.get_assmeble_canvas3D(); assemble != nullptr && plater.get_current_canvas3D() == assemble) - return *assemble; - if (!plater.is_view3D_shown()) { + Plater& plater = ui_plater(); + GLCanvas3D& canvas = selection_canvas(plater); + if (&canvas != plater.get_assmeble_canvas3D() && !plater.is_view3D_shown()) { plater.select_view_3D("3D"); if (MainFrame* mf = wxGetApp().mainframe) mf->select_tab(TAB_ID_PREPARE); } - return *plater.canvas3D(); + return canvas; } -// The Prepare view's canvas, the view shown first when another is, as Ops::start_arrange() shows it. -GLCanvas3D& shown_prepare_canvas(Plater& plater) +// What Deselect All does, for object_select {none: true} and a pick of its tile: the selection of `canvas` clears +// and its open gizmo closes. UI thread. +void clear_selection(GLCanvas3D& canvas) { - Ops::show_prepare_view(); - GLCanvas3D& canvas = *plater.canvas3D(); - // A canvas hidden while the model changed loads its scene on its next draw; it is loaded now. - if (canvas.is_reload_delayed()) - canvas.reload_scene(true); - return canvas; + canvas.deselect_all(); + canvas.set_as_dirty(); +} + +// What Select All does, for object_select {all: true} and a pick of its tile: every object of `canvas` selected, and the +// object list showing it. Refused while a gizmo of that canvas keeps its selection, where GLCanvas3D::select_all() +// would select nothing. UI thread. +std::optional select_everything(GLCanvas3D& canvas) +{ + if (!canvas.get_gizmos_manager().is_allow_select_all()) + return Ops::gizmo_keeps_selection(); + canvas.select_all(); + wxGetApp().obj_list()->update_selections(); + canvas.set_as_dirty(); + return std::nullopt; } } // namespace @@ -119,10 +154,10 @@ GLCanvas3D& shown_prepare_canvas(Plater& plater) GLCanvas3D& require_prepare_scene(Plater& plater) { if (GLCanvas3D* assemble = plater.get_assmeble_canvas3D(); assemble != nullptr && plater.get_current_canvas3D() == assemble) - throw ToolFailure("Leave the assemble view first (set_view {canvas: \"3d\"})"); + throw ToolFailure("Leave the assemble view first (view_set {canvas: \"3d\"})"); GLCanvas3D& canvas = object_canvas(); if (const auto type = canvas.get_gizmos_manager().get_current_type(); type != GLGizmosManager::Undefined) - throw ToolFailure("Close the " + gizmo_name(type) + " gizmo first (click {target: {gizmo: \"" + gizmo_name(type) + "\"}})"); + throw ToolFailure("Close the " + gizmo_name(type) + " gizmo first (widget_click {target: {gizmo: \"" + gizmo_name(type) + "\"}})"); // A canvas hidden while the model changed loads its scene on its next draw; the selection needs // it now, as when the Prepare tab is requested while shown (Plater::priv::set_current_panel()). if (canvas.is_reload_delayed()) @@ -204,7 +239,16 @@ int volume_filament(const ModelVolume& volume) return volume.is_modifier() ? own : 0; } -// An instance as list_objects describes it, except its plate and canvas rectangle, which the GUI knows. +// An object's mesh errors as object_list and object_fix report them. +json mesh_errors_json(const Ops::MeshErrors& errors) +{ + return {{"open_edges", errors.open_edges}, {"manifold", errors.manifold}, + {"degenerate_facets", errors.degenerate_facets}, {"edges_fixed", errors.edges_fixed}, + {"facets_removed", errors.facets_removed}, {"facets_reversed", errors.facets_reversed}, + {"backwards_edges", errors.backwards_edges}}; +} + +// An instance as object_list describes it, except its plate and canvas rectangle, which the GUI knows. json instance_info(const ModelObject& object, std::size_t index) { const ModelInstance& inst = *object.instances[index]; @@ -249,7 +293,7 @@ json list_objects(const json& args) if (arg_bool(args, "screen", false)) { canvas = plater.get_current_canvas3D(); if (canvas == nullptr || canvas == plater.get_preview_canvas3D()) - throw ToolFailure("screen needs the Prepare view or the assemble view shown (set_view)"); + throw ToolFailure("screen needs the Prepare view or the assemble view shown (view_set)"); } std::vector names; for (int i = 0; i < plates.get_plate_count(); ++i) @@ -271,7 +315,7 @@ json list_objects(const json& args) return out; } -// The slice tool's view of its request: slice_status()'s state, which adds when the tool started +// The plate_slice tool's view of its request: slice_status()'s state, which adds when the tool started // waiting to what the operation's ticket holds. struct SliceTicket { @@ -279,7 +323,7 @@ struct SliceTicket std::vector plates; }; -// transform on an instance: written straight into the ModelInstance, then dropped, registered with +// object_transform on an instance: written straight into the ModelInstance, then dropped, registered with // its plate and reloaded. Arguments are checked before anything changes. json transform_instance(Plater& plater, int oi, const json& args) { @@ -308,7 +352,7 @@ json transform_instance(Plater& plater, int oi, const json& args) if (args.contains("plate")) { const int to = arg_int(args, "plate", 0); if (to >= plates.get_plate_count()) - throw ToolFailure(no_such_plate(to, plates.get_plate_count()) + "; run_action plate_add makes one"); + throw ToolFailure(no_such_plate(to, plates.get_plate_count()) + "; action_run plate_add makes one"); const int from = plates.find_instance(oi, ii); if (from < 0) throw ToolFailure("instance " + std::to_string(ii) + " is off every plate; place it with translate (absolute) first"); @@ -330,15 +374,7 @@ json transform_instance(Plater& plater, int oi, const json& args) inst->set_scaling_factor(*scale); // The plate move is one more relative translate, after the others. inst->set_offset(inst->get_offset() + to_plate); - // The bounding box is cached: ensure_on_bed() must measure the new placement. - object->invalidate_bounding_box(); - if (arg_bool(args, "drop_to_bed", true)) - object->ensure_on_bed(); - // Slicing and the object list read the plate an instance is on from the plate registry, which - // GLCanvas3D::do_move() updates for a person's moves. - plates.notify_instance_update(oi, ii); - wxGetApp().obj_list()->update_plate_values_for_items(); - plater.changed_object(oi); + Ops::placed_instance(oi, ii, arg_bool(args, "drop_to_bed", true)); return {{"object", oi}, {"instance", ii}, {"offset", vec3(inst->get_offset())}, @@ -346,17 +382,14 @@ json transform_instance(Plater& plater, int oi, const json& args) {"plate", plates.find_instance(oi, ii)}}; } -// transform on a part: the Object manipulation panel's path with the part selected, so do_move(), +// object_transform on a part: the Object manipulation panel's path with the part selected, so do_move(), // do_rotate() and do_scale() write the part, drop the object (Auto Drop), register its instances // with their plates and update the object list. Translate and rotate are along the bed's axes on -// instance 0, scale and size along the part's own axes. +// instance 0, scale and size along the part's own axes. The part is one resolve_targets() checked. json transform_part(Plater& plater, int oi, const json& args) { ModelObject* object = plater.model().objects[size_t(oi)]; const int vi = arg_int(args, "part", 0); - if (vi >= int(object->volumes.size())) - throw ToolFailure("part index out of range"); - check_expected_ids(*object, object->volumes[size_t(vi)], args); // A single part has no row of its own in the object list, so the panel can't select it. if (object->volumes.size() == 1) throw ToolFailure("object " + std::to_string(oi) + " has one part; transform the instance"); @@ -429,14 +462,14 @@ std::set> shown_notifications(Plater& plater) return out; } -// Validates arrange's arguments, applies its settings and starts the job the toolbar's Arrange, a +// Validates object_arrange's arguments, applies its settings and starts the job the toolbar's Arrange, a // plate's Arrange icon or Fill bed starts. UI thread. ArrangeStart start_arrange(Plater& plater, const json& args) { const bool fill = args.contains("fill_object"); // Fill bed selects its object first, so it needs what every tool that selects needs. An arrangement // runs from whatever view and with whatever gizmo is open, as the toolbar's Arrange does. - GLCanvas3D& canvas = fill ? require_prepare_scene(plater) : shown_prepare_canvas(plater); + GLCanvas3D& canvas = fill ? require_prepare_scene(plater) : Ops::shown_prepare_canvas(); PartPlateList& plates = plater.get_partplate_list(); const ModelObjectPtrs& objects = plater.model().objects; ArrangeStart start; @@ -467,8 +500,8 @@ ArrangeStart start_arrange(Plater& plater, const json& args) } const std::string plate_name = "Plate " + std::to_string(plate); if (plate >= 0 && plates.get_plate(plate)->is_locked()) - throw ToolFailure(plate_name + " is locked; unlock it first (run_action plate_goto with args {\"plate\": " + std::to_string(plate) + - "}, then plate_toggle_lock)"); + throw ToolFailure(plate_name + " is locked; unlock it first (plate_select {\"plate\": " + std::to_string(plate) + + "}, then plate_lock)"); if (plate >= 0 && plates.get_plate(plate)->empty()) throw ToolFailure(plate_name + " has no objects to arrange"); @@ -514,7 +547,7 @@ ArrangeStart start_arrange(Plater& plater, const json& args) return start; } -// arrange's reply once the worker is idle. UI thread. +// object_arrange's reply once the worker is idle. UI thread. json arrange_reply(Plater& plater, const ArrangeStart& start) { PartPlateList& plates = plater.get_partplate_list(); @@ -556,7 +589,7 @@ json arrange_reply(Plater& plater, const ArrangeStart& start) return out; } -// The object list's name of an add_part shape, which its menus and the Primitive size dialog use; +// The object list's name of a part_add shape, which its menus and the Primitive size dialog use; // nullptr for another shape. const char* shape_type_name(const std::string& shape) { @@ -568,17 +601,13 @@ const char* shape_type_name(const std::string& shape) return nullptr; } -// add_part: what the object's context menu Add items do, with the size or the file given instead -// of asked for, then a move to `position` along the Move panel's path. Everything the arguments -// can tell is checked before anything changes. -json add_part(Plater& plater, const json& args) +// part_add: what the object's context menu Add items do, on object `oi`, which resolve_targets() checked, with the +// size or the file given instead of asked for, then a move to `position` along the Move panel's path. Everything the +// arguments can tell is checked before anything changes. +json add_part(Plater& plater, int oi, const json& args) { const ModelObjectPtrs& objects = plater.model().objects; - const int oi = arg_int(args, "object", -1); - if (oi < 0 || oi >= int(objects.size())) - throw ToolFailure("object index out of range"); - check_expected_ids(*objects[size_t(oi)], nullptr, args); - const ModelVolumeType type = volume_type_from_name(arg_string(args, "type")); + const ModelVolumeType type = volume_type_from_name(arg_string(args, "type")); if (type == ModelVolumeType::INVALID) throw ToolFailure("type must be part, negative, modifier, support_blocker, support_enforcer or precise_seam"); if (args.contains("shape") == args.contains("path")) @@ -597,7 +626,7 @@ json add_part(Plater& plater, const json& args) throw ToolFailure(err); // The SVG gizmo makes SVG parts, placed where the camera looks. if (boost::algorithm::iends_with(path_to_utf8(*file), ".svg")) - throw ToolFailure("SVG parts come from run_action add_primitive_svg (a part of the selected object) or the SVG gizmo"); + throw ToolFailure("SVG parts come from object_add_svg (a part of the selected object) or the SVG gizmo"); files.Add(from_path(*file)); } std::optional position; @@ -708,6 +737,17 @@ ModelVolumeType volume_type_from_name(const std::string& name) return ModelVolumeType::INVALID; } +// The subtype's name is the 3MF type name without its "precise_seam_" prefix, as volume_info() gives it. +ModelVolumeType precise_seam_subtype(const std::string& name) +{ + for (const ModelVolumeType seam : {ModelVolumeType::PRECISE_SEAM_CENTER, ModelVolumeType::PRECISE_SEAM_LEFT, ModelVolumeType::PRECISE_SEAM_RIGHT, + ModelVolumeType::PRECISE_SEAM_ENFORCED, ModelVolumeType::PRECISE_SEAM_BLOCKED, + ModelVolumeType::PRECISE_SEAM_NEUTRAL}) + if ("precise_seam_" + name == ModelVolume::type_to_string(seam)) + return seam; + return ModelVolumeType::INVALID; +} + std::vector part_shape_size(const std::string& shape, const json& size) { const char* type_name = shape_type_name(shape); @@ -748,7 +788,8 @@ json object_info(const ModelObject& object, std::size_t index) {"parts", std::move(volumes)}, {"bbox", object.instances.empty() ? json(nullptr) : box_json(object.instance_bounding_box(0))}, {"brim_ears", object.brim_points.size()}, - {"overrides", std::move(overrides)}}; + {"overrides", std::move(overrides)}, + {"mesh_errors", mesh_errors_json(Ops::mesh_errors(object))}}; if (!object.layer_config_ranges.empty()) out["layer_config_ranges"] = layer_config_ranges_json(object.layer_config_ranges); if (json profile = layer_height_profile_json(object.layer_height_profile.get()); !profile.is_null()) @@ -968,28 +1009,1431 @@ json plate_summary(const json& statistics, const GCodeProcessorResult& result) return out; } +namespace { + +// The Prepare view's selection, the view shown first when another is, as the object rows read it: what a command made +// from rows acts on when it is given no target. Null for a call that names its targets, which leaves the view shown. +const Selection* prepare_selection(const json& args) +{ + return names_targets(args) ? nullptr : &Ops::shown_prepare_canvas().get_selection(); +} + +// What a command made from rows answers for a refusal: as information where the person can select something else or +// wait and pick it again, as the rows told those, else as an error. +AppActionRunResult row_refused(const Ops::Refusal& refusal) +{ + const std::string code = refusal.code; + const bool again = refusal.kind == Ops::RefusalKind::Busy || code == "nothing_selected" || code == "wrong_selection" || + code == "one_object_only"; + return NativeCommands::refused(refusal, again ? AppActionRunResult::Level::Info : AppActionRunResult::Level::Error); +} + +// A refusal a command made from rows answers as information, where its row told that refusal, or the check it stands +// for, as information. +AppActionRunResult row_info(const Ops::Refusal& refusal) { return NativeCommands::refused(refusal, AppActionRunResult::Level::Info); } + +constexpr unsigned kEveryTarget = kObjects | kInstances | kParts; + +// The object list's selected rows as targets, for a command whose row acted on them (Assemble, Change Type), read in +// the Prepare view, shown first, as the row read them: an object row as its object, an instance row as [object, +// instance] and a part row as [object, part], by the part's index in the model. Refuses nothing_selected for no row and +// wrong_selection for a row of none of `types` (ItemType bits). UI thread. +Ops::Outcome listed_rows(int types) +{ + Ops::show_prepare_view(); + ObjectList& list = *wxGetApp().obj_list(); + ObjectDataViewModel& rows = *list.GetModel(); + wxDataViewItemArray selected; + list.GetSelections(selected); + if (selected.IsEmpty()) + return Ops::nothing_selected(); + Targets out; + out.from_selection = true; + for (const wxDataViewItem& row : selected) { + const ItemType type = rows.GetItemType(row); + const int object = rows.GetObjectIdByItem(row); + if ((type & types) == 0 || object < 0) + return Ops::wrong_selection(); + if (type & itObject) + out.objects.push_back(object); + else if (type & itInstance) + out.instances.emplace_back(object, rows.GetInstanceIdByItem(row)); + else if (type & itVolume) + out.parts.emplace_back(object, rows.get_real_volume_index_in_3d(object, rows.GetVolumeIdByItem(row))); + else + return Ops::wrong_selection(); + } + return out; +} + +// What Split takes from the object list, as ObjectList::is_splittable() reads it in the Prepare view, shown first: its +// one selected row. Into objects, the object of its row or of a row of the object's own other than a part's; into +// parts, the part of a part row, else the object of the row. `object_row` says whether the row is the object's. +struct SplitRow +{ + Targets target; + bool object_row = false; +}; +Ops::Outcome split_row(bool to_objects) +{ + Ops::show_prepare_view(); + ObjectList& list = *wxGetApp().obj_list(); + ObjectDataViewModel& rows = *list.GetModel(); + wxDataViewItemArray selected; + list.GetSelections(selected); + if (selected.IsEmpty()) + return Ops::nothing_selected(); + if (selected.size() > 1) + return Ops::one_object_only(); + const wxDataViewItem row = selected.front(); + const ItemType type = rows.GetItemType(row); + const int object = rows.GetObjectIdByItem(row); + if (object < 0 || (to_objects && (type == itVolume || (type != itObject && rows.GetItemType(rows.GetParent(row)) != itObject)))) + return Ops::wrong_selection(); + SplitRow out; + out.target.from_selection = true; + out.object_row = type == itObject; + if (!to_objects && type == itVolume) + out.target.parts.emplace_back(object, rows.GetVolumeIdByItem(row)); + else + out.target.objects.push_back(object); + return out; +} + +// What stands on plate `plate`: the objects whose every instance is on it, and the instances on it of the others. +Targets plate_targets(Plater& plater, int plate) +{ + PartPlateList& plates = plater.get_partplate_list(); + if (plate < 0 || plate >= plates.get_plate_count()) + throw ToolFailure(no_such_plate(plate, plates.get_plate_count())); + const ModelObjectPtrs& objects = plater.model().objects; + Targets out; + for (std::size_t o = 0; o < objects.size(); ++o) { + std::vector on; + for (std::size_t i = 0; i < objects[o]->instances.size(); ++i) + if (instance_plate(plates, int(o), int(i)) == plate) + on.push_back(int(i)); + if (!on.empty() && on.size() == objects[o]->instances.size()) + out.objects.push_back(int(o)); + else + for (int i : on) + out.instances.emplace_back(int(o), i); + } + if (out.objects.empty() && out.instances.empty()) + throw ToolFailure("Plate " + std::to_string(plate) + " has no objects"); + return out; +} + +// The entries of `named` (targets_reply()'s) for the targets `which` names by the same indices, under the same keys. +json entries_of(const json& named, const Targets& which) +{ + const auto has = [](const auto& list, const auto& item) { return std::find(list.begin(), list.end(), item) != list.end(); }; + json out = json::object(); + const auto keep = [&out, &named](const char* key, const std::function& wanted) { + json entries = json::array(); + for (const json& entry : named.value(key, json::array())) + if (wanted(entry)) + entries.push_back(entry); + if (!entries.empty()) + out[key] = std::move(entries); + }; + const auto pair_of = [](const json& e, const char* second) { return std::pair(e.at("object").get(), e.at(second).get()); }; + keep("objects", [&](const json& e) { return has(which.objects, e.at("index").get()); }); + keep("instances", [&](const json& e) { return has(which.instances, pair_of(e, "instance")); }); + keep("parts", [&](const json& e) { return has(which.parts, pair_of(e, "part")); }); + return out; +} + +// object_delete: what the call names, what stands on its plate, every object with all, else the selection. Only its +// person's form, a call with no arguments, leaves a cut object and a last solid part to the object list, which asks +// its question or shows its message, as a person's Delete does; any other call is refused with them. +AppActionRunResult delete_command(const json& args) +{ + const bool all = arg_bool(args, "all", false); + if (all && args.contains("plate")) + throw ToolFailure("Give all or plate, not both"); + if ((all || args.contains("plate")) && names_targets(args)) + throw ToolFailure(all ? "all deletes every object; leave the targets out" : "plate deletes what stands on it; leave the targets out"); + Plater& plater = ui_plater(); + const Model& model = plater.model(); + + Ops::DeleteObjectsArgs op; + op.all = all; + op.checks = person_form(args) ? Ops::DeleteChecks::ObjectList : Ops::DeleteChecks::Refuse; + if (args.contains("plate")) { + op.targets = plate_targets(plater, arg_int(args, "plate", 0)); + } else if (!all) { + const Ops::Outcome found = resolve_targets(model, prepare_selection(args), args, kEveryTarget, false); + if (!found) + return row_refused(found.refusal()); + op.targets = found.value(); + } + // Named before the delete renumbers what follows. + Targets doomed = Ops::deletion(model, op.targets); + if (all) + for (std::size_t i = 0; i < model.objects.size(); ++i) + doomed.objects.push_back(int(i)); + const json named = targets_reply(model, doomed); + const Ops::Outcome deleted = Ops::delete_objects(op); + if (!deleted) { + if (std::string(deleted.refusal().code) != "nothing_deleted") + return row_refused(deleted.refusal()); + // The object list told the person why, or they answered its question themself: the pick shows nothing more, + // and a call learns that nothing was deleted. + AppActionRunResult kept{AppActionRunResult::Level::Info, {}, false}; + kept.refusal = std::make_shared(deleted.refusal()); + return kept; + } + json reply = entries_of(named, deleted.value().deleted); + if (const json kept = targets_reply(model, deleted.value().kept); !kept.empty()) + reply["kept"] = kept; + reply["object_count"] = model.objects.size(); + return row_reply(reply); +} + +// object_rename: the object or part the call names, else the one selected. A call with no arguments asks for the name +// in the Rename dialog, as the row does; any other gives it. +AppActionRunResult rename_command(const json& args) +{ + const bool asks = person_form(args); + const std::string name = arg_string(args, "name"); + // Before anything is read, so a name that cannot be given leaves the view as it is. + if (!asks) + if (const std::optional refusal = Ops::rename_refusal(name)) + return row_refused(*refusal); + Plater& plater = ui_plater(); + const Ops::Outcome found = resolve_targets(plater.model(), prepare_selection(args), args, kObjects | kParts, true); + if (!found) + return row_refused(std::string(found.refusal().code) == "wrong_selection" ? Ops::rename_wrong_selection() : found.refusal()); + const Targets& target = found.value(); + const int object = target.parts.empty() ? target.objects.front() : target.parts.front().first; + const int part = target.parts.empty() ? -1 : target.parts.front().second; + if (asks) { + if (const std::optional refusal = Ops::unlisted_part_refusal(plater.model(), object, part)) + return row_refused(*refusal); + // The dialog renames the object list's selected row, which is the target's once every instance of an object + // selected stands for it. A part's row is by its place among the rows, which leave a cut's connectors out. + ObjectList* list = wxGetApp().obj_list(); + ObjectDataViewModel* rows = list->GetModel(); + ModelObject* owner = plater.model().objects[std::size_t(object)]; + const wxDataViewItem item = part < 0 ? rows->GetItemById(object) : + rows->GetItemByVolumeId(object, rows->get_real_volume_index_in_ui(object, part)); + if (list->GetSelection() != item) + select_rows(owner, part < 0 ? nullptr : owner->volumes[std::size_t(part)]); + list->rename_item(); + } else if (const Ops::Outcome renamed = Ops::rename_object({object, part, name}); !renamed) { + return row_refused(renamed.refusal()); + } + return row_reply(targets_reply(plater.model(), target)); +} + +// object_set_instances: the object the call names, else the one selected, or the object of the selected instance or +// part, as the item reads it. A call with no arguments asks for the count in the item's dialog; delta is the +// toolbar's + and -. +AppActionRunResult instances_command(const json& args) +{ + const bool asks = person_form(args); + if (args.contains("count") && args.contains("delta")) + throw ToolFailure("Give count or delta, not both"); + if (!asks && !args.contains("count") && !args.contains("delta")) + throw ToolFailure("Give count, or delta 1 or -1; with no arguments the dialog asks for the count"); + Plater& plater = ui_plater(); + const Ops::Outcome found = + resolve_targets(plater.model(), prepare_selection(args), args, kObjects | kObjectOfSelection, true); + if (!found) + return row_refused(found.refusal()); + const int object = found.value().objects.front(); + const std::size_t had = plater.model().objects[std::size_t(object)]->instances.size(); + if (asks) { + // The asking path: the item's dialog, on the selected object, enabled as the menu enables it. + if (const std::optional refusal = Ops::add_instances_refusal(plater.model(), object)) + return row_refused(*refusal); + if (const std::optional refusal = Ops::instance_change_blocked()) + return row_refused(*refusal); + plater.set_number_of_copies(); + } else { + const int count = args.contains("count") ? args.at("count").get() : int(had) + args.at("delta").get(); + if (const Ops::Outcome set = Ops::set_instance_count({object, count}); !set) + return row_refused(set.refusal()); + } + json reply = targets_reply(plater.model(), found.value()); + reply["object"] = object; + reply["instances"] = plater.model().objects[std::size_t(object)]->instances.size(); + return row_reply(reply); +} + +// object_separate_instances: the object the call names or the instances of one object, else the selection, where a part +// selected stands for its instance, as Set as Individual Objects reads it. +AppActionRunResult separate_command(const json& args) +{ + Plater& plater = ui_plater(); + const Ops::Outcome found = resolve_targets(plater.model(), prepare_selection(args), args, + kObjects | kInstances | kInstanceOfSelectedPart, false); + if (!found) + return row_refused(found.refusal()); + const Ops::Outcome holders = Ops::separate_instances(found.value()); + if (!holders) + return row_refused(holders.refusal()); + return row_reply(targets_reply(plater.model(), holders.value())); +} + +// object_split: the object the call names, else the object list's one selected row (split_row()), as the Split rows +// read it. A call with a tile's arguments asks what Split asks (the Auto-Drop question, a message for an object of one +// piece); any other answers the question with keep_z, and is refused without it. The rows told every refusal of theirs +// as information. +AppActionRunResult split_command(const json& args) +{ + const std::string into = arg_string(args, "into"); + const bool to_objects = into == "objects"; + const bool asks = args == json{{"into", into}}; + Plater& plater = ui_plater(); + Ops::SplitObjectArgs op; + if (names_targets(args)) { + const Ops::Outcome found = resolve_targets(plater.model(), nullptr, args, kObjects, true); + if (!found) + return row_info(found.refusal()); + op.target = found.value(); + } else { + const Ops::Outcome found = split_row(to_objects); + if (!found) + return row_info(found.refusal()); + op.target = found.value().target; + op.expand = found.value().object_row; + } + op.to_objects = to_objects; + op.ask = asks; + if (args.contains("keep_z")) + op.keep_z = args.at("keep_z").get(); + const Ops::Outcome made = Ops::split_object(op); + if (!made) + return asks && std::string(made.refusal().code) == "one_piece" ? quiet_refusal(made.refusal()) : row_info(made.refusal()); + json reply = targets_reply(plater.model(), made.value()); + reply["object_count"] = plater.model().objects.size(); + return row_reply(reply); +} + +// object_assemble: the objects the call names, else the object and instance rows selected in the object list, which +// the Assemble row merged. The row told a selection of fewer than two, or of parts, as information, and a cut object as +// an error. +AppActionRunResult assemble_command(const json& args) +{ + Plater& plater = ui_plater(); + const Model& model = plater.model(); + const Ops::Outcome found = names_targets(args) ? resolve_targets(model, nullptr, args, kObjects | kInstances, false) : + listed_rows(itObject | itInstance); + if (!found) + return row_info(std::string(found.refusal().code) == "wrong_selection" ? *Ops::assemble_refusal(model, Targets{}) : found.refusal()); + const Ops::Outcome assembled = Ops::assemble_objects(found.value()); + if (!assembled) + return std::string(assembled.refusal().code) == "too_few_objects" ? row_info(assembled.refusal()) : row_refused(assembled.refusal()); + const int index = assembled.value(); + Targets made; + made.objects = {index}; + json reply = targets_reply(model, made); + reply["object"] = index; + reply["name"] = model.objects[std::size_t(index)]->name; + return row_reply(reply); +} + +// part_change_type: the parts the call names, else the part rows selected in the object list, which the Change Type +// rows changed. The row told a selection of anything but parts as information, in its own words, and why a part keeps +// its type as an error. +AppActionRunResult part_type_command(const json& args) +{ + std::optional subtype; + if (args.contains("subtype")) + subtype = precise_seam_subtype(arg_string(args, "subtype")); + Plater& plater = ui_plater(); + const Ops::Outcome found = names_targets(args) ? resolve_targets(plater.model(), nullptr, args, kParts, false) : + listed_rows(itVolume); + if (!found) + return row_info(std::string(found.refusal().code) == "wrong_selection" ? Ops::part_wrong_selection() : found.refusal()); + const Ops::Outcome changed = Ops::change_part_type({found.value(), volume_type_from_name(arg_string(args, "type")), subtype}); + if (!changed) + return row_refused(changed.refusal()); + json reply = targets_reply(plater.model(), changed.value()); + for (json& part : reply["parts"]) { + const ModelVolume& volume = *plater.model().objects[part["object"].get()]->volumes[part["part"].get()]; + part["type"] = volume_type_name(volume.type()); + } + return row_reply(reply); +} + +// object_order's arguments, checked before the call reads the app: by, or the objects in order, which names one plate's. +void check_order_arguments(const json& args) +{ + const bool by = args.contains("by"); + const bool order = args.contains("order"); + if (by && order) + throw ToolFailure("Give by or order, not both"); + if (!by && !order) + throw ToolFailure("Give by, or the objects in order"); + if (order && args.contains("all")) + throw ToolFailure("order names the objects of one plate: leave all out"); + if (order && args.contains("descending")) + throw ToolFailure("descending goes with by: order gives the objects in their order"); + if (arg_bool(args, "all", false) && args.contains("plate")) + throw ToolFailure("Give plate or all, not both"); +} + +// The objects of plate `sorted`, or of every plate with `all`, in their order, as object_order replies them. UI thread. +json plate_objects(int sorted, bool all) +{ + Plater& plater = ui_plater(); + PartPlateList& plates = plater.get_partplate_list(); + const ModelObjectPtrs& objects = plater.model().objects; + json order = json::array(); + for (int plate = 0; plate < plates.get_plate_count(); ++plate) + 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}}); + return order; +} + +// object_order: the current plate, the plate the call names, or every plate with all. Its tile's call ({by}) shows +// the Prepare view and reverses an order the objects already have, as the plate menu's Order By does; any other call +// with by is ascending unless descending says otherwise. With order, the plate's objects go in that order, as drags in +// the object list put them. The row told a plate with no objects as information. +AppActionRunResult order_command(const json& args) +{ + if (const auto order = args.find("order"); order != args.end()) { + Ops::ReorderObjectsArgs op; + op.order = order->get>(); + if (args.contains("plate")) + op.plate = arg_int(args, "plate", 0); + const Ops::Outcome> ordered = Ops::reorder_objects(op); + if (!ordered) + return row_refused(ordered.refusal()); + const int plate = op.plate.value_or(ui_plater().get_partplate_list().get_curr_plate_index()); + return row_reply({{"order", plate_objects(plate, false)}}); + } + const std::string by = arg_string(args, "by"); + const bool all = arg_bool(args, "all", false); + const bool asks = args == json{{"by", by}}; + if (asks) + Ops::show_prepare_view(); + static const std::pair orders[] = { + {"name", ObjectOrder::Name}, {"filament", ObjectOrder::Filament}, {"height", ObjectOrder::Height}, {"size", ObjectOrder::Size}}; + Ops::OrderObjectsArgs op{}; + for (const auto& [name, order] : orders) + if (by == name) + op.order = order; + op.all = all; + if (args.contains("plate")) + op.plate = arg_int(args, "plate", 0); + if (args.contains("descending") || !asks) + op.descending = arg_bool(args, "descending", false); + const Ops::Outcome ordered = Ops::order_objects(op); + if (!ordered) + return std::string(ordered.refusal().code) == "no_objects_to_order" ? row_info(ordered.refusal()) : row_refused(ordered.refusal()); + + // The sorted plates' objects in their new order. + const int sorted = op.plate.value_or(ui_plater().get_partplate_list().get_curr_plate_index()); + return row_reply({{"order", plate_objects(sorted, all)}, {"descending", ordered.value()}}); +} + +// object_mirror: the objects and parts the call names, else the selection, which Mirror takes of one instance or parts +// of one. The row told every refusal as information. +AppActionRunResult mirror_command(const json& args) +{ + const std::string axis = arg_string(args, "axis"); + Plater& plater = ui_plater(); + const Ops::Outcome found = resolve_targets(plater.model(), prepare_selection(args), args, kEveryTarget, false); + if (!found) + return row_info(found.refusal()); + const Ops::Outcome mirrored = Ops::mirror_objects({found.value(), axis == "x" ? Axis::X : axis == "y" ? Axis::Y : Axis::Z}); + if (!mirrored) + return row_info(mirrored.refusal()); + return row_reply(targets_reply(plater.model(), found.value())); +} + +// object_center: the objects the call names, else the selection; on the plate each stands on, or on plate. Its tile's +// call ({}) is Center on the selection. The row told a selection to make as information. +AppActionRunResult center_command(const json& args) +{ + Plater& plater = ui_plater(); + std::optional plate; + if (args.contains("plate")) { + plate = arg_int(args, "plate", 0); + // Before the selection is read, so a plate the project lacks is named whatever is selected. + if (const int count = plater.get_partplate_list().get_plate_count(); *plate >= count) + return row_refused(Ops::no_such_plate(*plate, count)); + } + const Ops::Outcome found = resolve_targets(plater.model(), prepare_selection(args), args, kEveryTarget, false); + if (!found) + return row_info(found.refusal()); + const Ops::Outcome>> centred = Ops::center_objects({found.value(), plate}); + if (!centred) + return row_refused(centred.refusal()); + json reply = targets_reply(plater.model(), found.value()); + json plates = json::array(); + for (const auto& [on, objects] : centred.value()) + plates.push_back({{"plate", on}, {"objects", objects}}); + reply["plates"] = std::move(plates); + return row_reply(reply); +} + +// object_scale_to_fit: the objects the call names, else the objects and instances selected, as Scale to Fit Print Volume +// takes them. The row told every refusal as information. +AppActionRunResult scale_to_fit_command(const json& args) +{ + Plater& plater = ui_plater(); + const Ops::Outcome found = resolve_targets(plater.model(), prepare_selection(args), args, kObjects | kInstances, false); + if (!found) + return row_info(found.refusal()); + if (const Ops::Outcome fitted = Ops::scale_to_fit(found.value()); !fitted) + return row_info(fitted.refusal()); + const Model& model = plater.model(); + std::vector> instances = found.value().instances; + for (int object : found.value().objects) + for (std::size_t i = 0; i < model.objects[std::size_t(object)]->instances.size(); ++i) + instances.emplace_back(object, int(i)); + json scales = json::array(); + for (const auto& [object, instance] : instances) + scales.push_back({{"object", object}, + {"instance", instance}, + {"scale", vec3(model.objects[std::size_t(object)]->instances[std::size_t(instance)]->get_scaling_factor())}}); + json reply = targets_reply(model, found.value()); + reply["scales"] = std::move(scales); + return row_reply(reply); +} + +// object_drop: the objects and parts the call names, else the selection. What already rests on the bed is no error: the +// pick tells it, as information, and the call's reply says that nothing moved. +AppActionRunResult drop_command(const json& args) +{ + Plater& plater = ui_plater(); + const Ops::Outcome found = resolve_targets(plater.model(), prepare_selection(args), args, kEveryTarget, false); + if (!found) + return row_info(found.refusal()); + const Ops::Outcome dropped = Ops::drop_objects(found.value()); + if (!dropped) + return row_info(dropped.refusal()); + json reply = targets_reply(plater.model(), found.value()); + reply["moved"] = dropped.value(); + if (dropped.value()) + return row_reply(reply); + AppActionRunResult resting = row_info(Ops::already_on_bed()); + resting.done = true; + resting.reply = reply.dump(); + return resting; +} + +// object_auto_orient's targets: the objects named, else the selection, an instance or a part standing for its object as +// the job reads it, and with nothing selected (or the prime tower) every object, as Auto-Orient does; plates add theirs. +// Shows the Prepare view where it reads the selection. UI thread. +Ops::Outcome orient_args(Plater& plater, const json& args) +{ + Ops::OrientObjectsArgs op; + for (const json& plate : args.value("plates", json::array())) + op.plates.push_back(plate.get()); + if (op.plates.empty() || names_targets(args)) { + const Ops::Outcome found = + resolve_targets(plater.model(), prepare_selection(args), args, kObjects | kObjectOfSelection, false); + if (found) + op.targets = found.value(); + else if (const std::string code = found.refusal().code; code == "nothing_selected" || code == "wrong_selection") + op.targets.from_selection = true; + else + return found.refusal(); + } + return op; +} + +// What object_auto_orient replies once the job has ended: the rotation of each instance it turned (Ops::orientable()), +// of the objects named or of the plates named, else as the job turns a selection: the instances of the selection it +// can turn, or, with none of those and none of the selection on a locked plate, of every object. +json orient_reply(Plater& plater, const Ops::OrientObjectsArgs& op) +{ + const Model& model = plater.model(); + PartPlateList& plates = plater.get_partplate_list(); + const std::function locked = Ops::on_locked_plate(plates); + std::set objects(op.targets.objects.begin(), op.targets.objects.end()); + for (std::size_t o = 0; o < model.objects.size(); ++o) + for (std::size_t i = 0; i < model.objects[o]->instances.size(); ++i) + if (std::find(op.plates.begin(), op.plates.end(), instance_plate(plates, int(o), int(i))) != op.plates.end()) + objects.insert(int(o)); + std::vector> turned = Ops::orientable(model, objects, locked); + const auto some_locked = [&]() { + for (int object : objects) + for (std::size_t i = 0; i < model.objects[std::size_t(object)]->instances.size(); ++i) + if (locked(object, int(i))) + return true; + return false; + }; + if (turned.empty() && op.targets.from_selection && op.plates.empty() && !some_locked()) { + std::set every; + for (std::size_t o = 0; o < model.objects.size(); ++o) + every.insert(int(o)); + turned = Ops::orientable(model, every, locked); + } + Targets oriented; + json rotations = json::array(); + for (const auto& [object, instance] : turned) { + if (oriented.objects.empty() || oriented.objects.back() != object) + oriented.objects.push_back(object); + const ModelInstance& turned_instance = *model.objects[std::size_t(object)]->instances[std::size_t(instance)]; + rotations.push_back({{"object", object}, {"instance", instance}, {"rotation_deg", degrees(turned_instance.get_rotation())}}); + } + json reply = targets_reply(model, oriented); + reply["rotations"] = std::move(rotations); + return reply; +} + +// object_add_primitive: a call with the tile's arguments ({shape}) is Add Primitive, refused while an object is selected +// and asking for the size; any other adds the shape at its size, or the built-in one, whatever is selected, on plate, at +// position, named name, in one undo step (Ops::add_primitive()). +AppActionRunResult add_primitive_command(const json& args) +{ + const std::string shape = arg_string(args, "shape"); + Ops::AddPrimitiveArgs op; + // The size first: it refuses a shape of another name, which shape_type_name() has none for. + op.size = part_shape_size(shape, args.value("size", json())); + op.shape = shape_type_name(shape); + op.ask = args == json{{"shape", shape}}; + if (args.contains("plate")) + op.plate = arg_int(args, "plate", 0); + if (args.contains("name")) + op.name = arg_string(args, "name"); + if (args.contains("position")) + op.position = to_vec3(args["position"], "position"); + + Plater& plater = ui_plater(); + const Ops::Outcome added = Ops::add_primitive(op); + if (!added) + // The size dialog cancelled told the person nothing more is to come. + return op.ask && std::string(added.refusal().code) == "not_added" ? quiet_refusal(added.refusal()) : row_refused(added.refusal()); + const int index = added.value(); + Targets made; + made.objects = {index}; + json reply = targets_reply(plater.model(), made); + reply["object"] = index; + reply["plate"] = instance_plate(plater.get_partplate_list(), index, 0); + reply["offset"] = vec3(plater.model().objects[std::size_t(index)]->instances.front()->get_offset()); + return row_reply(reply); +} + +// The object and part commands made from menu rows: each acts on the targets it is given or, given none, on what is +// selected in the Prepare view, as a person's pick of the row does. Those of the object's and part's menus read their +// targets through resolve_targets() and run their operations; the handy models, Text and SVG run the row their +// variant argument names. Their tiles are the rows, under the rows' ids, titles, sections and icons. +void register_object_rows(CommandCatalog& catalog) +{ + using NativeCommands::tile; + const char* const object_section = L("Object"); + + // ---- Add Primitive and Add Handy models ---- (the Add menu; each creates a new object) + const json shape_size = array_prop({{"type", "number"}}, "mm, the Primitive size dialog's fields, in place of the dialog: cube " + "[x, y, z]; cylinder, cone, disc [diameter, height]; sphere [diameter]; " + "torus [inner diameter, tube diameter]; each above 0."); + // A shape the plate may then turn toward the part-cooling fan. + const std::string turned = " The shape may then be turned toward the part-cooling fan, so the size is along its own axes before that turn."; + const auto primitive = [&turned](const char* key, const char* title, const char* icon, const char* shape, bool turns) { + return tile(key, title, L("Add Primitive"), icon, {{"shape", shape}}, + std::string("Add a ") + shape + " object to the current plate at the size its dialog asks for; fails while an " + "object is selected. object_add_primitive with a size, or silent, skips the " + "dialog." + + (turns ? turned : std::string())); + }; + // With shape alone the size dialog asks, as the tiles do; a size or silent skips it. + NativeCommand add_primitive = row_command( + "object_add_primitive", L("Add a primitive"), + "Add a primitive shape (cube, cylinder, sphere, cone, disc or torus) as a new object, as Add Primitive does: on the " + "current plate, or on plate, which becomes the current one; at position, in the bed coordinates object_list and " + "object_transform use, else where Add Primitive puts it; named name, else after its shape. With a size, at that " + "size; with silent, at the shape's built-in size. With shape alone, as its tiles, the Primitive size dialog asks " + "for the size (blocked_by_dialog), unless a person turned that dialog off, and the call is refused while an object " + "is selected (part_add adds a shape to an object); any other call adds the object whatever is selected. One undo " + "step; the new object is selected. Reply: the object (objects, object), its plate and offset." + + turned, + object_schema({{"shape", enum_prop({"cube", "cylinder", "sphere", "cone", "disc", "torus"}, "The shape.")}, + {"size", shape_size}, + {"plate", {{"type", "integer"}, {"minimum", 0}, {"description", "The plate to add it on. Default: the current plate."}}}, + {"position", array_prop({{"type", "number"}}, "[x, y, z] mm: where its first instance goes, as object_transform's " + "position; it then rests on the bed.")}, + {"name", prop("string", "The object's name. Default: its shape's.")}}, + {"shape"}), + json::array({primitive("add_primitive_cube", L("Cube"), "menu_obj_cube", "cube", false), + primitive("add_primitive_cylinder", L("Cylinder"), "menu_obj_cylinder", "cylinder", true), + primitive("add_primitive_sphere", L("Sphere"), "menu_obj_sphere", "sphere", false), + primitive("add_primitive_cone", L("Cone"), "menu_obj_cone", "cone", true), + primitive("add_primitive_disc", L("Disc"), "menu_obj_disc", "disc", true), + primitive("add_primitive_torus", L("Torus"), "menu_obj_torus", "torus", true)}), + add_primitive_command); + add_primitive.input_schema = with_silent(std::move(add_primitive.input_schema), person_forms(add_primitive)); + catalog.add(reaching({"add_primitive", "rename_object"}, std::move(add_primitive))); + + // The two handy models of several files, which the menu arranges once they are loaded. + static const std::pair arranged[] = { + {"orca_cube", "Add the Orca Cube and its plug to the current plate, then arrange the objects as the toolbar's Arrange " + "does, which moves the others too."}, + {"orcasliced_combo", "Add the OrcaSliced Combo (the OrcaSliced model, the Orca Cube and its plug) to the current plate, " + "then arrange the objects as the toolbar's Arrange does, which moves the others too."}}; + std::vector models; + json handy_tiles = json::array(); + for (const MenuFactory::HandyModel& model : MenuFactory::handy_models()) { + models.emplace_back(model.key); + std::string description = std::string("Add the ") + model.label + " model to the current plate."; + for (const auto& [key, text] : arranged) + if (models.back() == key) + description = text; + handy_tiles.push_back(tile("add_handy_" + models.back(), model.label, L("Add Handy models"), "", {{"model", model.key}}, + description)); + } + catalog.add(row_command( + "object_add_handy_model", L("Add a handy model"), + "Add one of the test models OrcaSlicer ships to the current plate, as Add Handy models does; orca_cube and " + "orcasliced_combo, of several files, then arrange the objects as the toolbar's Arrange does, which moves the others too.", + object_schema({{"model", enum_prop(models, "The model.")}}, {"model"}), std::move(handy_tiles), [](const json& args) { + const std::string model = arg_string(args, "model"); + const std::vector& all = MenuFactory::handy_models(); + const auto it = std::find_if(all.begin(), all.end(), [&model](const MenuFactory::HandyModel& m) { return model == m.key; }); + return Rows::add_handy(std::size_t(it - all.begin())); + })); + + 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(row_command("object_add_text", L("Text"), text, object_schema({}), + json::array({tile("add_primitive_text", L("Text"), L("Add Primitive"), "menu_obj_text", json::object(), text)}), + [](const json&) { return Rows::add_primitive_text(); })); + + catalog.add(row_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.", + object_schema({{"path", Rows::input_file("an .svg file")}}), + json::array({tile("add_primitive_svg", L("SVG"), L("Add Primitive"), "menu_obj_svg", json::object(), + "Add an SVG as a new object, or as a part of the selected object, from the file a dialog asks for; " + "object_add_svg with a path uses that file without one. The part is created in the background " + "(app_wait {for: \"idle\"} waits for it), and the SVG gizmo opens on it.")}), + [](const json& args) { return Rows::add_primitive_svg(args); })); + + // ---- Object ---- (the object's context menu and the Edit menu) + NativeCommand del = row_command( + "object_delete", L("Delete objects"), + "Delete objects, instances or parts, as Delete does: those named (objects, instances, parts), what stands on a plate " + "(plate: its objects, or the instances on it of an object on two plates), every object (all, as Delete All does), or " + "with none of these what is selected in the Prepare view. An object whose every instance or every part is named goes " + "whole. An object's last solid part alone, and a cut object or a solid or negative part of one, are refused with " + "the message or the question Delete gives; a call with no arguments leaves them to the object list, which shows " + "the message or asks the question (blocked_by_dialog), and all deletes cut objects without asking, as Delete All " + "does. One undo step. Reply: what was deleted (objects, instances, parts, with the indices they had); kept, what " + "was named and stayed, with its indices now (the object list deletes from the last named and stops at what it " + "refuses or asks about); and object_count, the objects left; the objects after a deleted one move down.", + with_targets(object_schema({{"plate", {{"type", "integer"}, {"minimum", 0}, {"description", "Delete what stands on this plate."}}}, + {"all", prop("boolean", "Delete every object. Default false: the targets.")}}), + kEveryTarget, false), + json::array({tile("obj_delete", L("Delete Selected"), object_section, "delete", json::object(), "Delete the selected objects or parts."), + tile("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)))); + + // The Rename dialog's name, which every call but the tile's gives. + NativeCommand rename = row_command( + "object_rename", L("Rename"), + "Rename an object, or a part of it (object and part), or with neither the object or part selected in the Prepare " + "view. With a name, skips the Rename dialog; an empty name, or one with characters a file name cannot hold, is " + "refused. Reply: what was renamed, with its name (objects or parts).", + with_targets(object_schema({{"name", prop("string", "The new name, in place of the Rename dialog.")}}, {"name"}), kObjects | kParts, true), + json::array({tile("obj_rename", L("Rename"), object_section, "", json::object(), + "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)))); + + // The count the dialog asks for, which every call but the tiles' gives; delta is the toolbar's + and -. + NativeCommand instances = row_command( + "object_set_instances", L("Set the number of instances"), + "Give an object this many instances (count), as Set Number of Instances does, or one more or one fewer (delta 1 " + "or -1), as the toolbar's + and - do: the object named, else the one selected in the Prepare view, or the object " + "of the selected instance or part. With no arguments the dialog asks for the count (blocked_by_dialog). New " + "instances overlap; arrange afterwards. One undo step; the object is selected. Reply: the object (objects, " + "object) and instances, how many it has.", + with_targets(object_schema({{"count", {{"type", "integer"}, + {"minimum", 1}, + {"description", "The total number of instances, up to 1000, in place of the dialog."}}}, + {"delta", {{"type", "integer"}, + {"enum", {1, -1}}, + {"description", "1 adds an instance and -1 removes one, as the toolbar's + and - do."}}}}), + kObjects, true), + json::array({tile("obj_set_instances", L("Set Number of Instances"), object_section, "instance_add", json::object(), + "Give the selected object the number of instances the dialog asks for, in one undo step; " + "object_set_instances with a count skips the dialog. New instances overlap; arrange " + "afterwards."), + tile("obj_instances_up", L("Increase Instances"), object_section, "instance_add", {{"delta", 1}}, + "Add an instance of the selected object."), + tile("obj_instances_down", L("Decrease Instances"), object_section, "instance_remove", {{"delta", -1}}, + "Remove an instance of the selected object.")}), + instances_command); + instances.input_schema = with_silent(std::move(instances.input_schema), person_forms(instances)); + // Its silent form needs count or delta, which a schema of this server cannot require as one of two. + 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 a " + "tile's arguments, does what a person's pick of that tile does."; + catalog.add(reaching({"set_instance_count"}, with_expected_ids(std::move(instances)))); + + NativeCommand separate = row_command( + "object_separate_instances", L("Set as Individual Objects"), + "Make each instance of an object a separate object (object), or some instances of one object one new object " + "(instances), as Set as Individual Objects does; with neither, what is selected in the Prepare view: an object, or " + "some of its instances. New objects are added last. Reply: the objects that hold those instances afterwards " + "(objects): the object and its new objects, or the new object.", + with_targets(with_targets(object_schema({}), kObjects, true), kInstances, false), + json::array({tile("obj_instances_to_objects", L("Set as Individual Objects"), object_section, "", json::object(), + "Make each instance of the selected object a separate object (object_select {objects: [n]}); with some " + "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)))); + + // The answer to Split's Auto-Drop question, which every call but the tiles' gives where the split asks it. + NativeCommand split = row_command( + "object_split", L("Split an object"), + "Split an object into separate objects, or into parts of it, as Split > To Objects and To Parts do: the object named, " + "else the one row selected in the object list, as Split reads it: an object's row, into objects also a row of the " + "object's own other than a part's, and into parts a part's row, or another row of the object. A mesh of one shell " + "is refused, and into parts so is an object of several parts, whose part is selected to split it. Into objects, " + "the object is removed and its pieces are added last and selected. Where some of them " + "would float above the bed of an object that drops, keep_z answers the question Split asks (true keeps their " + "height, false lets them drop), and without it the call is refused (auto_drop_question); with only a tile's " + "arguments Split asks it (blocked_by_dialog). One undo step. Reply: the new objects (objects) or the parts the " + "part became (parts), with their indices afterwards, and object_count.", + with_targets(object_schema({{"into", enum_prop({"objects", "parts"}, "Separate objects, or parts of the object.")}, + {"keep_z", prop("boolean", "Into objects, the answer to the question whether pieces that would " + "float above the bed keep their height: true keeps it, false " + "lets them drop.")}}, + {"into"}), + kObjects, true), + json::array({tile("obj_split_objects", L("Split to Objects"), object_section, "menu_split_objects", {{"into", "objects"}}, + "Split the selected object into separate objects."), + tile("obj_split_parts", L("Split to Parts"), object_section, "menu_split_parts", {{"into", "parts"}}, + "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( + {"assemble_objects"}, + with_expected_ids(row_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 " + "are refused. They are removed and the new object is added last and selected, so object indices change. One " + "undo step. Reply: the new object's index (object) and name, and objects.", + with_targets(object_schema({}), kObjects, false), + json::array({tile("obj_assemble", L("Assemble"), object_section, "", json::object(), + "Assemble two or more selected objects into one object of parts named Assembly. They are removed " + "and it is added last, so object indices change; the reply has its index (object) and name.")}), + assemble_command)))); + + // The plate menu's Order By. + struct OrderRow + { + const char* key; + const char* title; + const char* by; + const char* what; + }; + // Titles are L("...")-marked here so xgettext extracts them. + static const OrderRow order_rows[] = { + {"obj_order_by_name", L("Order by Name"), "name", "name"}, + {"obj_order_by_filament", L("Order by Filament"), "filament", "filament"}, + {"obj_order_by_height", L("Order by Height"), "height", "height"}, + {"obj_order_by_size", L("Order by Size"), "size", "size (bounding box volume)"}, + }; + json order_tiles = json::array(); + for (const OrderRow& row : order_rows) + order_tiles.push_back(tile(row.key, row.title, object_section, "", {{"by", row.by}}, + std::string("Order the current plate's objects by ") + row.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.")); + NativeCommand order = reaching( + {"order_objects", "reorder_objects"}, + row_command("object_order", L("Order objects"), + "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 tiles, 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; object indices change. Reply: the new order (order: [{object, 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"}, + {"minItems", 1}, + {"items", {{"type", "integer"}, {"minimum", 0}}}, + {"description", "In place of by: the plate's objects, by index (object_list), each " + "once, in the order wanted."}}}, + {"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_tiles), order_command)); + // The arguments are checked before the call reads the app. + order.run = [run = std::move(order.run)](const json& args, ToolContext& ctx) { + check_order_arguments(args); + return run(args, ctx); + }; + catalog.add(std::move(order)); + + catalog.add(reaching( + {"drop_objects"}, + with_expected_ids(row_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 " + "already rests on the bed is no error: moved false says that nothing moved. One undo step; the targets are left " + "selected. Reply: what it acted on (objects, instances, parts) and moved.", + with_targets(object_schema({}), kObjects | kParts, false), + json::array({tile("obj_drop", L("Drop to Bed"), object_section, "toolbar_flatten", json::object(), "Drop the selection onto the bed.")}), + drop_command)))); + + catalog.add(reaching( + {"mirror_objects"}, + with_expected_ids(row_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 " + "of one instance or parts of one. Cut objects are refused. One undo step; the targets are left selected. Reply: what " + "it mirrored (objects, instances, parts).", + with_targets(object_schema({{"axis", enum_prop({"x", "y", "z"}, "The axis to mirror along.")}}, {"axis"}), kObjects | kParts, false), + json::array({tile("obj_mirror_x", L("Mirror X"), object_section, "menu_mirror_x", {{"axis", "x"}}, "Mirror the selection along X."), + tile("obj_mirror_y", L("Mirror Y"), object_section, "menu_mirror_y", {{"axis", "y"}}, "Mirror the selection along Y."), + tile("obj_mirror_z", L("Mirror Z"), object_section, "menu_mirror_z", {{"axis", "z"}}, "Mirror the selection along Z.")}), + mirror_command)))); + + catalog.add(reaching( + {"center_objects"}, + with_expected_ids(row_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 " + "Prepare view as one group, on plate, or with no arguments, as its tile, on the current plate. A group moves as one, " + "its box to the plate's centre, its objects keeping their places relative to each other, so a group spread over " + "several plates and sent to plate may not fit on its bed. One undo step; the targets are left selected. Reply: " + "what it centred (objects, instances, parts) and the groups (plates: [{plate, objects}]).", + with_targets(object_schema({{"plate", {{"type", "integer"}, {"minimum", 0}, {"description", "Centre them all on this plate."}}}}), + kObjects, false), + json::array({tile("obj_center", L("Center Selected on Plate"), object_section, "", json::object(), "Center the selection on its plate.")}), + center_command)))); + + catalog.add(reaching( + {"scale_to_fit"}, + with_expected_ids(row_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 " + "than a rectangle or a circle are refused. One undo step; the targets are left selected. Reply: what it scaled " + "(objects, instances) and each instance's scale (scales: [{object, instance, scale}]).", + with_targets(object_schema({}), kObjects, false), + json::array({tile("obj_fit_volume", L("Scale to Fit Print Volume"), object_section, "", json::object(), + "Scale the selection to fit the print volume.")}), + scale_to_fit_command)))); + + // Auto-Orient waits for its job; a person's pick starts it in place, as the toolbar does. + const std::string orient_tile = "Auto-orient the selection, or every object when nothing is selected; the call returns when it is done."; + NativeCommand orient = reaching( + {"orient_objects"}, + with_expected_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 " + "nothing is selected. An object on a locked plate, or one that is not printable, keeps its orientation. A call " + "that names objects or plates turns no other object: a plate named that holds no objects, a locked plate named, " + "and objects named none of which can be turned (not printable, or on a locked plate) are refused. A selection of " + "objects that are not printable, none on a locked plate, leaves the job to turn every other object, as the " + "toolbar's does. " + "Waits for the job to end. One undo step; objects named are left selected. Reply: the objects it turned (objects) " + "and the rotation of each instance it turned (rotations: [{object, instance, rotation_deg}]).", + with_targets(object_schema({{"plates", array_prop({{"type", "integer"}}, "Plate indices: orient the objects that stand on them.")}}), + kObjects, false), + [](const json& args, ToolContext& ctx) { + AutomationRuntime& runtime = ctx.runtime(); + Ops::OrientObjectsArgs op; + ctx.run_ui([&] { + Plater& plater = ui_plater(); + const Ops::Outcome found = orient_args(plater, args); + if (!found) + throw refused(found.refusal()); + op = found.value(); + if (const Ops::Outcome started = Ops::orient_objects(op); !started) + throw refused(started.refusal()); + return json(); + }); + const auto timeout = std::chrono::seconds(300); + try { + return ToolResult::ok(poll_ui( + ctx, + [&]() -> json { + Plater& plater = ui_plater(); + return plater.get_ui_job_worker().is_idle() ? orient_reply(plater, op) : json(); + }, + timeout, "the orientation")); + } catch (const ToolFailure&) { + if (ctx.cancelled()) + throw; + // McpCore keeps the call's admission until the cancelled job has really stopped. + ctx.observe_ui([&] { return json(runtime.core().cancel_worker(ctx.job_id())); }); + throw ToolFailure("The orientation did not finish within " + std::to_string(timeout.count()) + " s, so it was cancelled"); + } + }))); + orient.tiles = json::array({tile("obj_orient", L("Auto-Orient"), object_section, "toolbar_orient", json::object(), orient_tile)}); + // A person's pick of the tile starts the orientation in place and returns while it runs; an automated call of the + // tile's arguments is the command's own function, which waits and replies. Both are orient_objects() on the same + // targets. + catalog.add(NativeCommands::with_row_forms( + std::move(orient), + [](const json&) { + Plater* plater = wxGetApp().plater(); + if (plater == nullptr) + return AppActionRunResult{}; + const Ops::Outcome found = orient_args(*plater, json::object()); + if (!found) + return row_info(found.refusal()); + if (const Ops::Outcome started = Ops::orient_objects(found.value()); !started) + return row_info(started.refusal()); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; + }, + /*person_form_behind_dialogs=*/false, std::vector{json::object()})); + + // ---- Parts ---- (Change Type, in the part menus only) + struct TypeRow + { + const char* key; + const char* title; + const char* type; + const char* description; + }; + // Titles are L("...")-marked here so xgettext extracts them. + const TypeRow type_rows[] = { + {"obj_type_part", L("Change Type to Part"), "part", + "Make the selected parts (object_select {parts} first) solid parts, as Change Type does. Parts are listed by type, so " + "part indices change."}, + {"obj_type_negative", L("Change Type to Negative Part"), "negative", + "Make the selected parts negative parts, as Change Type does; not the object's last solid part. Parts are listed by " + "type, so part indices change."}, + {"obj_type_modifier", L("Change Type to Modifier"), "modifier", + "Make the selected parts modifiers, as Change Type does; not the object's last solid part. Parts are listed by type, " + "so part indices change."}, + {"obj_type_support_blocker", L("Change Type to Support Blocker"), "support_blocker", + "Make the selected parts support blockers, as Change Type does; not the object's last solid part, nor a text or SVG " + "part. Parts are listed by type, so part indices change."}, + {"obj_type_support_enforcer", L("Change Type to Support Enforcer"), "support_enforcer", + "Make the selected parts support enforcers, as Change Type does; not the object's last solid part, nor a text or SVG " + "part. Parts are listed by type, so part indices change."}, + {"obj_type_precise_seam", L("Change Type to Precise Seam"), "precise_seam", + "Make the selected parts Center precise seams (seams keep their subtype), as Change Type does; not the object's last " + "solid part, nor a text or SVG part. Parts are listed by type, so part indices change."}, + }; + json type_tiles = json::array(); + for (const TypeRow& row : type_rows) + type_tiles.push_back(tile(row.key, row.title, object_section, "", {{"type", row.type}}, row.description)); + catalog.add(reaching( + {"change_part_type"}, + with_expected_ids(row_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 " + "keeps its subtype; subtype, with precise_seam alone, sets the seam's subtype as the Precise Seam Type menu does. " + "Not an object's last solid part; a text or SVG part does not become a support blocker or enforcer or a precise " + "seam; a painted modifier keeps its type. One undo step. Parts are listed by type, so part indices change. Reply: " + "each part with its index afterwards and its type (parts).", + with_targets(object_schema({{"type", enum_prop({"part", "negative", "modifier", "support_blocker", "support_enforcer", "precise_seam"}, + "What the parts become.")}, + {"subtype", enum_prop({"center", "left", "right", "enforced", "blocked", "neutral"}, + "With type precise_seam: the seam's subtype, which every part named " + "takes. Default: a seam keeps its own, another part becomes center.")}}, + {"type"}), + kParts, false), + std::move(type_tiles), part_type_command)))); +} + +// What object_fix replies: what it repaired (objects whole, parts), and for each object or part in turn whether its mesh +// changed, why it could not be repaired, the object's mesh errors before and after, whether painting was removed, and +// whether it is the one a cancel stopped, listed because its mesh had changed by then. +json fix_reply(const Model& model, const Ops::FixedModels& fixed) +{ + Targets repaired; + json repairs = json::array(); + for (const Ops::FixedModel& m : fixed.models) { + if (m.part < 0) + repaired.objects.push_back(m.object); + else + repaired.parts.emplace_back(m.object, m.part); + json item{{"object", m.object}, + {"name", m.name}, + {"changed", m.changed}, + {"mesh_errors_before", mesh_errors_json(m.before)}, + {"mesh_errors_after", mesh_errors_json(m.after)}, + {"painting_removed", m.painting_removed}}; + if (m.part >= 0) + item["part"] = m.part; + if (!m.failed.empty()) + item["failed"] = m.failed; + if (m.cancelled) + item["cancelled"] = true; + repairs.push_back(std::move(item)); + } + json reply = targets_reply(model, repaired); + reply["repairs"] = std::move(repairs); + return reply; +} + +// The object and part commands of the GUI's menus that have no Speed Dial tile: Printable, Auto Drop, Fix Model, Clone, +// Reload from disk and Replace 3D file. Each reads its targets through resolve_targets() and runs its operation. +void register_object_tools(CommandCatalog& catalog) +{ + NativeCommand printable = reaching( + {"set_objects_printable"}, + with_expected_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 " + "instance that is not printable is greyed in the 3D view and left out of slicing. One undo step. Reply: every " + "instance it set, with printable (instances), and the objects named (objects).", + with_targets(object_schema({{"printable", prop("boolean", "true marks them printable, false not printable.")}}, {"printable"}), + kObjects | kInstances, false), + [](const json& args, ToolContext& ctx) { + json out = ctx.run_ui([&] { + Plater& plater = ui_plater(); + const Ops::Outcome found = + resolve_targets(plater.model(), prepare_selection(args), args, kObjects | kInstances, false); + if (!found) + throw refused(found.refusal()); + const bool printable = arg_bool(args, "printable", true); + const Ops::Outcome>> set = Ops::set_objects_printable({found.value(), printable}); + if (!set) + throw refused(set.refusal()); + Targets acted; + acted.objects = found.value().objects; + acted.instances = set.value(); + json reply = targets_reply(plater.model(), acted); + for (json& instance : reply["instances"]) + instance["printable"] = printable; + return reply; + }); + settle(ctx); + return ToolResult::ok(out); + }))); + printable.examples = json::parse(R"json([ + {"title": "Leave one instance out of the print", "calls": [ + {"tool": "object_set_instances", "args": {"object": 0, "count": 3}}, + {"tool": "object_set_printable", "args": {"instances": [[0, 1]], "printable": false}}]}, + {"title": "Print the selected objects again", "calls": [ + {"tool": "object_set_printable", "args": {"printable": true}}]}])json"); + catalog.add(std::move(printable)); + + NativeCommand auto_drop = reaching( + {"set_objects_auto_drop"}, + with_expected_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 " + "object_transform or the Move gizmo leaves it, above the bed; with it on it drops onto the bed when it is next " + "moved. An object's instances share it. One undo step. Reply: the objects (objects) and auto_drop.", + with_targets(object_schema({{"auto_drop", prop("boolean", "true lets the objects drop onto the bed, false lets them " + "stay above it.")}}, + {"auto_drop"}), + kObjects, false), + [](const json& args, ToolContext& ctx) { + json out = ctx.run_ui([&] { + Plater& plater = ui_plater(); + const Ops::Outcome found = + resolve_targets(plater.model(), prepare_selection(args), args, kObjects | kObjectOfSelection, false); + if (!found) + throw refused(found.refusal()); + const bool auto_drop = arg_bool(args, "auto_drop", true); + const Ops::Outcome> set = Ops::set_objects_auto_drop({found.value(), auto_drop}); + if (!set) + throw refused(set.refusal()); + Targets acted; + acted.objects = set.value(); + json reply = targets_reply(plater.model(), acted); + reply["auto_drop"] = auto_drop; + return reply; + }); + settle(ctx); + return ToolResult::ok(out); + }))); + auto_drop.examples = json::parse(R"json([ + {"title": "Let an object stay above the bed where it is moved to", "calls": [ + {"tool": "object_set_auto_drop", "args": {"objects": [0], "auto_drop": false}}]}, + {"title": "Let the selected objects drop onto the bed again", "calls": [ + {"tool": "object_set_auto_drop", "args": {"auto_drop": true}}]}])json"); + catalog.add(std::move(auto_drop)); + + // The repair runs in one UI closure, which job_cancel {job} stops through the progress it reports. A cancel fails the + // call with the reply in its details: the models repaired before it, and the one it stopped when that one's mesh had + // changed (a part of an object repaired before the cancel keeps its new mesh). + NativeCommand fix = reaching( + {"fix_objects"}, + with_expected_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 " + "standing for its object. A painted modifier is left as it is, and painting is kept only with the keep_painting " + "preference on. It opens no progress dialog and shows no notification; the call waits for the repair, during " + "which the window does not redraw, and job_cancel {job} cancels it: the call fails with the reply in its " + "details, and what was repaired before the cancel, a part of the object it stopped in among them, keeps its new " + "mesh. Refused while a gizmo is open. One undo step. Reply: what it repaired (objects, parts) and repairs, for " + "each in turn: changed, failed (why it could not be repaired), the object's mesh_errors_before and " + "mesh_errors_after (as object_list gives them), painting_removed, and cancelled: true on the one a cancel " + "stopped, listed when its mesh had changed by then.", + with_targets(object_schema({{"plate", {{"type", "integer"}, + {"minimum", 0}, + {"description", "Repair the objects on this plate."}}}, + {"all", prop("boolean", "Repair every object. Default false: the targets.")}}), + kObjects | kParts, false), + [](const json& args, ToolContext& ctx) { + const bool all = arg_bool(args, "all", false); + if (all && args.contains("plate")) + throw ToolFailure("Give all or plate, not both"); + if ((all || args.contains("plate")) && names_targets(args)) + throw ToolFailure(all ? "all repairs every object; leave the targets out" : + "plate repairs the objects on it; leave the targets out"); + json out = ctx.run_ui([&] { + Plater& plater = ui_plater(); + Ops::FixObjectsArgs op; + op.all = all; + if (args.contains("plate")) { + op.plate = arg_int(args, "plate", 0); + } else if (!all) { + const Ops::Outcome found = resolve_targets(plater.model(), prepare_selection(args), args, + kObjects | kParts | kObjectOfSelection, false); + if (!found) + throw refused(found.refusal()); + op.targets = found.value(); + } + const Ops::Outcome fixed = Ops::fix_objects(op, [&ctx](std::size_t, int, const std::string&) { + return !ctx.cancelled(); + }); + if (!fixed) + throw refused(fixed.refusal()); + json reply = fix_reply(plater.model(), fixed.value()); + if (fixed.value().cancelled) + throw ToolFailure("The repair was cancelled; what it repaired before keeps its new mesh (repairs)", reply); + return reply; + }); + settle(ctx); + return ToolResult::ok(out); + }))); + fix.cancellable = true; + fix.examples = json::parse(R"json([ + {"title": "Repair an imported object whose mesh has holes", "calls": [ + {"tool": "object_list", "args": {}}, + {"tool": "object_fix", "args": {"objects": [0]}}]}, + {"title": "Repair the objects on the first plate", "calls": [ + {"tool": "object_fix", "args": {"plate": 0}}]}])json"); + catalog.add(std::move(fix)); + + // Clone waits for the arrangement it starts, as object_arrange does. + NativeCommand clone = reaching( + {"clone_objects"}, + with_expected_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 " + "each (default 1, as the dialog's field starts), added after the other objects, placed near them on the current " + "plate; the last copies are left selected. With arrange true the current plate is then arranged, as the dialog's " + "Auto arrange plate after cloning does; without arrange, the dialog's choice: the auto_arrange preference. The " + "call waits for the arrangement. One undo step for the copies, and one for the arrangement. Reply: the new objects " + "(objects), what was copied (copied: its objects, or its instances where instances were selected), object_count " + "and arranged.", + with_targets(object_schema({{"count", {{"type", "integer"}, + {"minimum", 1}, + {"maximum", 1000}, + {"description", "Copies of each, up to 1000 as the Clone dialog takes. Default 1."}}}, + {"arrange", prop("boolean", "Arrange the current plate afterwards. Default: the Clone dialog's " + "choice, the auto_arrange preference.")}}), + kObjects, false), + [](const json& args, ToolContext& ctx) { + AutomationRuntime& runtime = ctx.runtime(); + bool arranged = false; + json reply = ctx.run_ui([&] { + Plater& plater = ui_plater(); + const Ops::Outcome found = + resolve_targets(plater.model(), prepare_selection(args), args, kObjects | kInstances, false); + if (!found) + throw refused(found.refusal()); + Ops::CloneObjectsArgs op; + op.targets = found.value(); + op.count = arg_int(args, "count", 1); + if (args.contains("arrange")) + op.arrange = arg_bool(args, "arrange", false); + // Read before the copies are added after the other objects, which leaves these indices as they are. + json copied = targets_reply(plater.model(), found.value()); + const Ops::Outcome cloned = Ops::clone_objects(op); + if (!cloned) + throw refused(cloned.refusal()); + arranged = cloned.value().arranged; + json out = targets_reply(plater.model(), cloned.value().objects); + out["copied"] = std::move(copied); + out["object_count"] = plater.model().objects.size(); + out["arranged"] = arranged; + return out; + }); + if (arranged) { + const auto timeout = std::chrono::seconds(300); + try { + poll_ui( + ctx, []() -> json { return ui_plater().get_ui_job_worker().is_idle() ? json(true) : json(); }, timeout, + "the arrangement"); + } catch (const ToolFailure&) { + if (ctx.cancelled()) + throw; + // McpCore keeps the call's admission until the cancelled job has really stopped. + ctx.observe_ui([&] { return json(runtime.core().cancel_worker(ctx.job_id())); }); + throw ToolFailure("The arrangement did not finish within " + std::to_string(timeout.count()) + + " s, so it was cancelled; the copies stay"); + } + } + settle(ctx); + return ToolResult::ok(reply); + }))); + clone.examples = json::parse(R"json([ + {"title": "Make three copies of an object and arrange the plate", "calls": [ + {"tool": "object_clone", "args": {"objects": [0], "count": 3, "arrange": true}}]}, + {"title": "Copy the selected objects once, where they are", "calls": [ + {"tool": "object_clone", "args": {"arrange": false}}]}])json"); + catalog.add(std::move(clone)); + + NativeCommand reload = reaching( + {"reload_parts"}, + with_expected_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 " + "the Prepare view. A part's file is the one it was loaded from, else the file of that name beside its object's " + "file. A part whose file is gone is not asked for: it is listed under missing. A part keeps its settings, type, " + "filament and placement, and its painting when the keep_painting preference is on. Parts loaded from no file " + "(primitives, the built-in models) are left out; cut objects are refused, since a reload would replace a cut part " + "with its whole file, and so is a call while a gizmo is open. One undo step. Reply: reloaded (parts), missing " + "(with each part's path), unmatched (parts their file holds no part to take for) and unreadable (a file that " + "could not be read, after which nothing more was loaded).", + with_targets(object_schema({{"all", prop("boolean", "Reload every object but the cut ones. Default false: the targets.")}}), + kObjects | kParts, false), + [](const json& args, ToolContext& ctx) { + const bool all = arg_bool(args, "all", false); + if (all && names_targets(args)) + throw ToolFailure("all reloads every object; leave the targets out"); + json out = ctx.run_ui([&] { + Plater& plater = ui_plater(); + Ops::ReloadFromDiskArgs op; + op.all = all; + if (!all) { + const Ops::Outcome found = resolve_targets(plater.model(), prepare_selection(args), args, + kObjects | kParts | kObjectOfSelection, false); + if (!found) + throw refused(found.refusal()); + op.targets = found.value(); + } + const Ops::Outcome reloaded = Ops::reload_parts(op); + if (!reloaded) + throw refused(reloaded.refusal()); + const Model& model = plater.model(); + // Each part with the file it was loaded from. + const auto parts = [&model](const std::vector>& list) { + Targets named; + named.parts = list; + json items = targets_reply(model, named).value("parts", json::array()); + for (json& item : items) + item["path"] = model.objects[item["object"].get()] + ->volumes[item["part"].get()] + ->source.input_file; + return items; + }; + json reply{{"reloaded", parts(reloaded.value().reloaded)}, + {"missing", parts(reloaded.value().missing)}, + {"unmatched", parts(reloaded.value().unmatched)}}; + if (!reloaded.value().unreadable.empty()) + reply["unreadable"] = reloaded.value().unreadable; + return reply; + }); + settle(ctx); + return ToolResult::ok(out); + }))); + reload.examples = json::parse(R"json([ + {"title": "Reload an imported object after its file changed", "calls": [ + {"tool": "object_reload_from_disk", "args": {"objects": [0]}}]}, + {"title": "Reload every object", "calls": [ + {"tool": "object_reload_from_disk", "args": {"all": true}}]}])json"); + catalog.add(std::move(reload)); + + NativeCommand replace = reaching( + {"replace_part"}, + with_expected_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 " + "and placement, and its painting when the keep_painting preference is on; with it off the painting is copied as it " + "is, which fits the same mesh alone. A file that loads as more than one object or part is refused, as Replace 3D " + "file refuses it. path names the file, so no file dialog opens; the loader may still ask, a STEP file for its mesh " + "options (blocked_by_dialog). Cut objects are refused, and so is a call while a gizmo is open. One undo step. " + "Reply: the part (parts), with its new part_id and its index, which moves when the object's parts are not in type " + "order (the replacement sorts them), and its object_list entry (part_info).", + with_targets(object_schema({{"path", prop("string", "Absolute path of the model file (STL, OBJ, 3MF, STEP, ...).")}}, {"path"}), + kParts, true), + [](const json& args, ToolContext& ctx) { + json out = ctx.run_ui([&] { + Plater& plater = ui_plater(); + const Ops::Outcome found = resolve_targets(plater.model(), prepare_selection(args), args, + kObjects | kParts | kObjectOfSelection, true); + if (!found) + throw refused(found.refusal()); + const Ops::Outcome> part = Ops::replaced_part(plater.model(), found.value()); + if (!part) + throw refused(part.refusal()); + const int object = part.value().first; + const Ops::Outcome replaced = Ops::replace_part({object, part.value().second, arg_string(args, "path")}); + if (!replaced) + throw refused(replaced.refusal()); + const std::size_t index = std::size_t(replaced.value()); + Targets acted; + acted.parts = {{object, replaced.value()}}; + json reply = targets_reply(plater.model(), acted); + reply["part_info"] = volume_info(*plater.model().objects[std::size_t(object)]->volumes[index], index); + return reply; + }); + settle(ctx); + return ToolResult::ok(out); + }))); + replace.examples = json::parse(R"json([ + {"title": "Replace an object's only part with a new version of its file", "calls": [ + {"tool": "part_replace", "args": {"object": 0, "path": "/models/bracket_v2.stl"}}]}, + {"title": "Replace a modifier with a mesh of another shape", "calls": [ + {"tool": "part_replace", "args": {"object": 0, "part": 1, "path": "/models/modifier.stl"}}]}])json"); + catalog.add(std::move(replace)); +} + +} // namespace + void register_scene_tools(CommandCatalog& catalog) { catalog.add(inspect_tool( - "api", "list_objects", L("List objects"), + "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; outside: the objects with an instance on no plate. An object with instances on two plates is " "listed under both, each time with that plate's instances. An object has its filament, auto_drop, bounding box " - "(instance 0), brim ear count and overrides, the keys of the settings it overrides (get_settings scope object " - "reads them); its instances (offset, rotation in degrees, scale, " + "(instance 0), brim ear count and overrides, the keys of the settings it overrides (settings_get target object " + "reads them); its mesh_errors, as the list's warning icon reads them: open_edges, manifold (no open edge), and the " + "loader's or a repair's counts degenerate_facets, edges_fixed, facets_removed, facets_reversed and " + "backwards_edges (object_fix repairs it); its instances (offset, rotation in degrees, scale, " "mirrored, bbox); its parts, one or more: parts, negative parts, modifiers, support blockers and enforcers and " "precise seams (type, with 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 in mm3 on the bed, measured on instance 0; rotation_deg and scale in the " "object's frame; mirrored; triangle count; mesh_volume, the unscaled mesh's mm3; painted facets: supports and " "seam enforcers/blockers, fuzzy_skin, mmu per filament, texture per layer; a text part's text and font, an SVG " - "part's file); its height range modifiers when it has any (layer_config_ranges: [{min_z, max_z, values}], as " - "set_height_ranges takes them) and its variable layer height profile when it has one (layer_height_profile: " + "part's file); its height range modifiers when it has any (layer_config_ranges: [{min_z, max_z, values}], values " + "being a range's settings, which settings_set changes with target height_range; object_set_height_ranges takes " + "min_z and max_z) and its variable layer height profile when it has one (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: " - "they are what select_objects, transform, mouse_gesture targets and the object/part settings scopes take. " + "they are what object_select, object_transform, mouse_gesture targets and the settings tools' object and part targets take. " "Each object and part also has an id, which stays with it when a delete, split or assemble shifts the indices: pass " - "it as object_id / part_id to transform, add_part, set_settings, set_height_ranges and set_variable_layer_height " - "(object_ids, part_ids and instance_object_ids to select_objects), and a call whose index names another one now is " + "it as object_id / part_id to object_transform, part_add, settings_set, object_set_height_ranges and object_set_variable_layer_height " + "(object_ids, part_ids and instance_object_ids to object_select), and a call whose index names another one now is " "refused instead of acting on it. 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."}}}, {"screen", prop("boolean", "Add each instance's rectangle in the shown 3D view, logical pixels [x, y, w, h].")}, @@ -997,119 +2441,89 @@ 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); })); })); - catalog.add(with_expected_ids(mutate_tool( - "ui", "select_objects", L("Select objects"), + NativeCommand select = with_expected_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 / " - "none select everything or nothing, whatever else is given. The reply is the selection as get_app_state.selection " - "gives it.", - object_schema({{"objects", array_prop({{"type", "integer"}}, "Object indices.")}, - {"instances", array_prop({{"type", "array"}}, "[[object, instance], ...]")}, - {"parts", array_prop({{"type", "array"}}, "[[object, part], ...]")}, - {"object_ids", array_prop({{"type", "integer"}}, "The ids list_objects reports for objects, one per " - "entry: refused when an index names another object now.")}, - {"part_ids", array_prop({{"type", "integer"}}, "The ids list_objects reports for the entries of parts, " - "one per entry: refused when a pair names another part now.")}, - {"instance_object_ids", array_prop({{"type", "integer"}}, "The ids list_objects reports for the objects of " - "instances, one per entry: refused when a pair names " - "another object now.")}, - {"add", prop("boolean", "Add to the selection instead of replacing it.")}, - {"all", prop("boolean", "Select all objects.")}, - {"none", prop("boolean", "Clear the selection.")}}), + "none select everything or nothing, whatever else is given; none also closes the open gizmo, as Deselect All does, " + "and all is refused while a gizmo that keeps its selection is open. The reply is the selection as " + "app_state.selection gives it, for all and none alone (Select All and Deselect All) too.", + with_targets(object_schema({{"add", prop("boolean", "Add to the selection instead of replacing it.")}, + {"all", prop("boolean", "Select all objects.")}, + {"none", prop("boolean", "Clear the selection and close the open gizmo.")}}), + kEveryTarget, false), [](const json& args, ToolContext& ctx) { json out = ctx.run_ui([&] { - Plater& plater = ui_plater(); - GLCanvas3D& canvas = object_canvas(); - Selection& sel = canvas.get_selection(); - const bool assemble = &canvas == plater.get_assmeble_canvas3D(); + Plater& plater = ui_plater(); + GLCanvas3D& canvas = object_canvas(); + Selection& sel = canvas.get_selection(); if (arg_bool(args, "none", false)) { - if (assemble) - sel.remove_all(); - else - plater.deselect_all(); - canvas.set_as_dirty(); + clear_selection(canvas); return selection_state(canvas); } if (arg_bool(args, "all", false)) { - if (assemble) - sel.add_all(); - else - plater.select_all(); - canvas.set_as_dirty(); + if (const std::optional refusal = select_everything(canvas)) + throw refused(*refusal); return selection_state(canvas); } - const size_t count = plater.model().objects.size(); - bool first = !arg_bool(args, "add", false); - auto check_obj = [&](int o) { - if (o < 0 || size_t(o) >= count) - throw ToolFailure("object index " + std::to_string(o) + " is out of range"); - }; - // An instance or part an object no longer has would select nothing, as quietly as a stale - // index from before a merge or a delete. - auto check_in = [&](const json& p, bool instance) { - const int o = p.at(0).get(), i = p.at(1).get(); - check_obj(o); - const ModelObject& object = *plater.model().objects[size_t(o)]; - if (i < 0 || size_t(i) >= (instance ? object.instances.size() : object.volumes.size())) - throw ToolFailure("object " + std::to_string(o) + " has no " + (instance ? "instance " : "part ") + - std::to_string(i) + " (list_objects lists them)"); - }; - // Expected ids are checked for every entry before the selection changes. - const json objects = args.value("objects", json::array()), volumes = args.value("parts", json::array()); - if (args.contains("object_ids")) { - if (args["object_ids"].size() != objects.size()) - throw ToolFailure("object_ids takes one id per entry of objects"); - for (std::size_t k = 0; k < objects.size(); ++k) { - check_obj(objects[k].get()); - check_expected_ids(*plater.model().objects[size_t(objects[k].get())], nullptr, - json{{"object_id", args["object_ids"][k]}}); + // Every index and expected id is checked before the selection changes. A call that names nothing, or + // only empty lists, leaves it as it is. + if (names_targets(args) && !names_empty_lists(args)) { + const Ops::Outcome named = resolve_targets(plater.model(), nullptr, args, kEveryTarget, false); + if (!named) + throw refused(named.refusal()); + bool first = !arg_bool(args, "add", false); + for (int o : named.value().objects) { + sel.add_object(unsigned(o), first); + first = false; } - } - const json instances = args.value("instances", json::array()); - if (args.contains("instance_object_ids")) { - if (args["instance_object_ids"].size() != instances.size()) - throw ToolFailure("instance_object_ids takes one id per entry of instances"); - for (std::size_t k = 0; k < instances.size(); ++k) { - check_in(instances[k], true); - check_expected_ids(*plater.model().objects[size_t(instances[k].at(0).get())], nullptr, - json{{"object_id", args["instance_object_ids"][k]}}); + for (const auto& [o, i] : named.value().instances) { + sel.add_instance(unsigned(o), unsigned(i), first); + first = false; } - } - if (args.contains("part_ids")) { - if (args["part_ids"].size() != volumes.size()) - throw ToolFailure("part_ids takes one id per entry of parts"); - for (std::size_t k = 0; k < volumes.size(); ++k) { - check_in(volumes[k], false); - const ModelObject& object = *plater.model().objects[size_t(volumes[k].at(0).get())]; - check_expected_ids(object, object.volumes[size_t(volumes[k].at(1).get())], - json{{"part_id", args["part_ids"][k]}}); + for (const auto& [o, p] : named.value().parts) { + sel.add_volume(unsigned(o), unsigned(p), 0, first); + first = false; } } - for (const json& o : objects) { - check_obj(o.get()); - sel.add_object(unsigned(o.get()), first); - first = false; - } - for (const json& p : args.value("instances", json::array())) { - check_in(p, true); - sel.add_instance(unsigned(p.at(0).get()), unsigned(p.at(1).get()), first); - first = false; - } - for (const json& p : args.value("parts", json::array())) { - check_in(p, false); - sel.add_volume(unsigned(p.at(0).get()), unsigned(p.at(1).get()), 0, first); - first = false; - } wxGetApp().obj_list()->update_selections(); canvas.set_as_dirty(); return selection_state(canvas); }); settle(ctx); return ToolResult::ok(out); - }))); + })); + select.tiles = json::array({NativeCommands::tile("select_all", L("Select All Objects"), L("Object"), "", {{"all", true}}, + "Select every object in the 3D view (the assemble view while it is shown, " + "else Prepare, switching to it), and reply with the selection; refused " + "while a gizmo that keeps its selection is open. A person's pick shows " + "Prepare and selects there."), + NativeCommands::tile("deselect_all", L("Deselect All"), L("Object"), "", {{"none", true}}, + "Clear the selection in the 3D view (the assemble view while it is shown, " + "else Prepare, switching to it), close the open gizmo, and reply with the " + "selection. A person's pick clears it where it is, switching no tab.")}); + // A person's pick runs in place, as its row did: Select All shows Prepare and select_everything() selects there, + // Deselect All is clear_selection() on the view shown, switching no tab. An automated call of either tile's + // arguments is object_select's own function, which the two functions serve too, on the view shown, and replies + // with the selection. + catalog.add(NativeCommands::with_row_forms( + std::move(select), + [](const json& tile_args) { + Plater* plater = wxGetApp().plater(); + if (arg_bool(tile_args, "all", false)) { + if (plater == nullptr) + return AppActionRunResult{}; + Ops::show_prepare_view(); + if (const std::optional refusal = select_everything(*plater->get_view3D_canvas3D())) + return NativeCommands::refused(*refusal, AppActionRunResult::Level::Info); + } else if (plater != nullptr) + clear_selection(selection_canvas(*plater)); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; + }, + /*person_form_behind_dialogs=*/false, std::vector{json{{"none", true}}, json{{"all", true}}})); catalog.add(with_expected_ids(mutate_tool( - "api", "transform", L("Move, rotate or scale an instance or a part"), + "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, " "scale a factor (one number or [x, y, z]), size [x, y, z] mm along the object's or part's own axes, plate moves " @@ -1118,78 +2532,109 @@ void register_scene_tools(CommandCatalog& catalog) "off; drop_to_bed false lets it sink into the bed, but an object of one part left above the bed still drops. A part " "moves as the " "Object manipulation panel moves it: translate and rotate along the bed's axes, measured on instance 0, scale and " - "size along its own axes; every instance shows the change, and Auto Drop may lower the object afterwards. One " - "undo step. Reply: the instance's offset, scale and plate, or the part's size along its own axes and its " - "list_objects entry (part_info).", - object_schema({{"object", {{"type", "integer"}, {"minimum", 0}, {"description", "Object index (list_objects)."}}}, - {"instance", {{"type", "integer"}, {"minimum", 0}, {"description", "Default 0."}}}, - {"part", {{"type", "integer"}, {"minimum", 0}, {"description", "Transform this part instead of the instance."}}}, - {"object_id", expected_id_prop("object")}, - {"part_id", expected_id_prop("part")}, - {"translate", array_prop({{"type", "number"}}, "[x, y, z] mm")}, - {"position", array_prop({{"type", "number"}}, "[x, y, z] mm: the position to move to. Not with translate.")}, - {"rotate", array_prop({{"type", "number"}}, "[x, y, z] degrees; relative only for a part")}, - {"scale", {{"type", {"number", "array"}}, {"description", "Factor or [x, y, z] factors."}}}, - {"size", array_prop({{"type", {"number", "null"}}}, "[x, y, z] mm, null keeps an axis; one number and two " - "nulls keep the proportions. Not with scale.")}, - {"plate", {{"type", "integer"}, {"minimum", 0}, {"description", "Move the instance to this plate."}}}, - {"mode", enum_prop({"relative", "absolute"}, "Default relative.")}, - {"drop_to_bed", prop("boolean", "Default true; instances only.")}}, - {"object"}), + "size along its own axes; every instance shows the change, and Auto Drop may lower the object afterwards. The " + "instance is the object's instance (default 0) and the part one of its parts; with no object, the instance or part " + "selected in the Prepare view, or instance 0 of the object selected. One undo step. Reply: the instance's offset, " + "scale and plate, or the part's size along its own axes and its object_list entry (part_info), and what it moved " + "(instances or parts).", + with_targets(object_schema({{"translate", array_prop({{"type", "number"}}, "[x, y, z] mm")}, + {"position", array_prop({{"type", "number"}}, "[x, y, z] mm: the position to move to. Not with translate.")}, + {"rotate", array_prop({{"type", "number"}}, "[x, y, z] degrees; relative only for a part")}, + {"scale", {{"type", {"number", "array"}}, {"description", "Factor or [x, y, z] factors."}}}, + {"size", array_prop({{"type", {"number", "null"}}}, "[x, y, z] mm, null keeps an axis; one number " + "and two nulls keep the proportions. Not with scale.")}, + {"plate", {{"type", "integer"}, {"minimum", 0}, {"description", "Move the instance to this plate."}}}, + {"mode", enum_prop({"relative", "absolute"}, "Default relative.")}, + {"drop_to_bed", prop("boolean", "Default true; instances only.")}}), + kEveryTarget, true), [](const json& args, ToolContext& ctx) { json out = ctx.run_ui([&]() -> json { - Plater& plater = ui_plater(); - const int oi = arg_int(args, "object", -1); - if (oi < 0 || oi >= int(plater.model().objects.size())) - throw ToolFailure("object index out of range"); + Plater& plater = ui_plater(); if (args.contains("scale") && args.contains("size")) throw ToolFailure("give scale or size, not both"); if (args.contains("translate") && args.contains("position")) throw ToolFailure("give translate or position, not both"); - check_expected_ids(*plater.model().objects[size_t(oi)], nullptr, args); - return args.contains("part") ? transform_part(plater, oi, args) : transform_instance(plater, oi, args); + const Ops::Outcome found = resolve_targets(plater.model(), &plater.get_view3D_canvas3D()->get_selection(), args, + kEveryTarget, true); + if (!found) + throw refused(found.refusal()); + // The call as the transforms read it: the object, and the instance (a whole object's is instance 0) or + // the part. + const Targets& target = found.value(); + json call = args; + Targets moved; + if (!target.parts.empty()) { + call["object"] = target.parts.front().first; + call["part"] = target.parts.front().second; + moved.parts = target.parts; + } else { + const std::pair instance = target.instances.empty() ? + std::make_pair(target.objects.front(), arg_int(args, "instance", 0)) : + target.instances.front(); + call["object"] = instance.first; + call["instance"] = instance.second; + moved.instances = {instance}; + } + const int oi = call.at("object").get(); + json reply = call.contains("part") ? transform_part(plater, oi, call) : transform_instance(plater, oi, call); + reply.update(targets_reply(plater.model(), moved)); + return reply; }); settle(ctx); return ToolResult::ok(out); }))); catalog.add(with_expected_ids(mutate_tool( - "api", "add_part", L("Add a part or modifier to an object"), + "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 " "menu puts it (a shape beside the object, a file at its coordinates relative to the object's first part) unless " "position is given. Like the menu, adding a shape folds the instance's rotation and scale into the object's parts " "(the instance's scale then reads 1). Refused for an object with several instances: add parts first. A STEP file " - "may ask for mesh options (blocked_by_dialog). The new part is selected; one undo step. Reply: its index, which is " - "not always the last (parts are ordered by type), the object's part count and the part's list_objects entry " - "(part_info).", - object_schema({{"object", {{"type", "integer"}, {"minimum", 0}, {"description", "Object index (list_objects)."}}}, - {"object_id", expected_id_prop("object")}, - {"type", enum_prop({"part", "negative", "modifier", "support_blocker", "support_enforcer", "precise_seam"}, - "What the new part is.")}, - {"shape", enum_prop({"cube", "cylinder", "sphere", "cone", "disc", "torus"}, "A primitive shape.")}, - {"size", array_prop({{"type", "number"}}, "mm, the Primitive size dialog's fields: cube [x, y, z]; cylinder, " - "cone, disc [diameter, height]; sphere [diameter]; torus [inner " - "diameter, tube diameter]. Default: the built-in size.")}, - {"path", prop("string", "Instead of shape: absolute path of a model file (STL, OBJ, 3MF, STEP, ...).")}, - {"position", array_prop({{"type", "number"}}, "[x, y, z] mm on the bed for the part's centre, on " - "instance 0, as the Move panel shows it.")}}, - {"object", "type"}), + "may ask for mesh options (blocked_by_dialog). The object is the one named, else the one selected in the Prepare " + "view, or the object of the selected instance or part. The new part is selected; one undo step. Reply: its index, " + "which is not always the last (parts are ordered by type), the object's part count and the part's object_list entry " + "(part_info), and the object (objects).", + with_targets(object_schema({{"type", enum_prop({"part", "negative", "modifier", "support_blocker", "support_enforcer", "precise_seam"}, + "What the new part is.")}, + {"shape", enum_prop({"cube", "cylinder", "sphere", "cone", "disc", "torus"}, "A primitive shape.")}, + {"size", array_prop({{"type", "number"}}, "mm, the Primitive size dialog's fields: cube [x, y, z]; " + "cylinder, cone, disc [diameter, height]; sphere " + "[diameter]; torus [inner diameter, tube diameter]. " + "Default: the built-in size.")}, + {"path", prop("string", "Instead of shape: absolute path of a model file (STL, OBJ, 3MF, STEP, ...).")}, + {"position", array_prop({{"type", "number"}}, "[x, y, z] mm on the bed for the part's centre, on " + "instance 0, as the Move panel shows it.")}}, + {"type"}), + kObjects, true), [](const json& args, ToolContext& ctx) { - json out = ctx.run_ui([&] { return add_part(ui_plater(), args); }); + json out = ctx.run_ui([&] { + Plater& plater = ui_plater(); + const Ops::Outcome found = resolve_targets(plater.model(), &plater.get_view3D_canvas3D()->get_selection(), args, + kObjects | kObjectOfSelection, true); + if (!found) + throw refused(found.refusal()); + json reply = add_part(plater, found.value().objects.front(), args); + reply.update(targets_reply(plater.model(), found.value())); + return reply; + }); settle(ctx); return ToolResult::ok(out); }))); - catalog.add(reaching({"start_arrange"}, mutate_tool( - "api", "arrange", L("Arrange objects or fill the bed"), + register_object_rows(catalog); + register_object_tools(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 " "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 list_objects again. " - "One undo step.", + "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.", object_schema({{"plates", {{"type", {"string", "integer"}}, {"description", "\"all\" (default), \"current\" or a plate index."}}}, {"spacing", {{"type", "number"}, {"minimum", 0}, {"description", "mm between objects; 0 means auto."}}}, {"rotate", prop("boolean", "Auto rotate for arrangement.")}, @@ -1227,19 +2672,35 @@ void register_scene_tools(CommandCatalog& catalog) ctx.observe_ui([&] { return json(runtime.core().cancel_worker(ctx.job_id())); }); throw ToolFailure("The arrangement did not finish within " + std::to_string(timeout.count()) + " s, so it was cancelled"); } - }))); + })); + arrange.tiles = json::array({NativeCommands::tile("obj_arrange", L("Auto-Arrange"), L("Object"), "toolbar_arrange", json::object(), + "Arrange all objects on the unlocked plates with the saved Arrange options, as " + "the toolbar does; the call waits for the arrangement and replies as " + "object_arrange does: the settings in force, the instances left off every " + "plate and the plates skipped. object_arrange with arguments also takes " + "options, one plate or fill bed.")}); + // A person's pick starts the arrangement in place as the toolbar does, and returns while it runs; an automated call + // of the tile'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_row_forms( + std::move(arrange), [](const json&) { return Rows::obj_arrange(); }, /*person_form_behind_dialogs=*/false, + std::vector{json::object()})); NativeCommand slice = reaching({"start_slice"}, mutate_tool( - "api", "slice", L("Slice"), + "plate_slice", L("Slice"), "Slice the current plate, all plates, or one plate by index, the way the toolbar's Slice button does, and wait for " "the result (or reply with a job id when it takes longer than the reply budget). Each requested plate reports ok, " "error, cancelled, empty or skipped; the whole operation is superseded when someone else started a slice or " "edited the project while it ran. An ok plate has time_s (silent_time_s when the printer estimates it), " "filament_m and filament_g including flush, filament_cost, layers, max_z, filament_changes, and filaments[i] for " "slot i+1 with m, g and the grams of model_g, support_g, flush_g and tower_g. Other changes are refused until it " - "finishes; cancel_job stops it.", + "finishes; job_cancel stops it. The Preview tab shows the result, as after the Slice button; preview: true, alone " + "or with plates \"all\", is the call of Slice and Preview or Slice All Plates, whose pick starts the slice as a job " + "and shows its result as a notification.", object_schema({{"plates", {{"type", {"string", "integer"}}, {"description", "\"current\" (default), \"all\", or a plate index."}}}, - {"timeout_s", {{"type", "integer"}, {"minimum", 10}, {"maximum", 7200}, {"description", "Stop waiting after this long (default 1800): the call fails, and the slice goes on unless cancel_job stops it."}}}}), + {"timeout_s", {{"type", "integer"}, {"minimum", 10}, {"maximum", 7200}, {"description", "Stop waiting after this long (default 1800): the call fails, and the slice goes on unless job_cancel stops it."}}}, + {"preview", prop("boolean", "Show the Preview tab, as every slice does: the argument of the Slice and " + "Preview and Slice All Plates tiles.")}}), [](const json& args, ToolContext& ctx) { const json plates_arg = args.value("plates", json("current")); auto ticket = std::make_shared(); @@ -1249,7 +2710,7 @@ void register_scene_tools(CommandCatalog& catalog) ctx.begin_operation(); return json(ui_plater().slice_cancel_seq()); }).get(); - // A change made just before (set_settings, open_files) is validated by an update + // A change made just before (settings_set, project_open) is validated by an update // scheduled a moment later; a slice requested first would be refused on the old state. poll_ui( ctx, @@ -1352,14 +2813,21 @@ void register_scene_tools(CommandCatalog& catalog) return ToolResult::ok(result); })); slice.budget_ms = 45000; - catalog.add(slice); + slice.tiles = json::array( + {NativeCommands::tile("slice_and_preview", L("Slice and Preview"), L("Slice & Export"), "media_play", {{"preview", true}}, + "Slice the current plate and show the Preview tab; the call waits for the result, and a pick starts " + "the slice as a job."), + NativeCommands::tile("slice_all", L("Slice All Plates"), L("Slice & Export"), "media_play", {{"plates", "all"}, {"preview", true}}, + "Slice every plate and show the Preview tab; the call waits for the results, and a pick starts the " + "slice as a job.")}); + catalog.add(std::move(slice)); NativeCommand cancel = mutate_tool( - "core", "cancel_job", L("Cancel a job"), + "job_cancel", L("Cancel a job"), "Stop the running operation: a slice or G-code export, as the slicing progress's cancel button does, or a " "background job an MCP call started (an arrange, orient or fill bed). Its job then reports cancelled; a background " "job keeps other changes out until it has really stopped. With job, only that job is stopped: the running " - "operation, a run_script run or an encode_recording. Allowed while an operation holds the project. Reply: " + "operation, an object_fix, a script_run run or a recording_encode. Allowed while an operation holds the project. Reply: " "was_running, and job when one was stopped.", object_schema({{"job", prop("string", "The operation's job to cancel, e.g. \"j12\".")}}), [](const json& args, ToolContext& ctx) { diff --git a/src/slic3r/GUI/Mcp/McpToolsUi.cpp b/src/slic3r/GUI/Mcp/McpToolsUi.cpp index bdbec16a23..b2d1da8dee 100644 --- a/src/slic3r/GUI/Mcp/McpToolsUi.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsUi.cpp @@ -68,16 +68,16 @@ using namespace std::chrono_literals; namespace { -// The locator grammar is spelled out once, in list_widgets's description, which hands out the refs. +// The locator grammar is spelled out once, in widget_list's description, which hands out the refs. const json kTargetSchema = {{"type", json::array({"string", "object"})}, - {"description", "A ref list_widgets gave (\"w12\"), which later listings leave good (one refused as stale or " + {"description", "A ref widget_list gave (\"w12\"), which later listings leave good (one refused as stale or " "unknown needs a new listing), or a locator, such as {label: \"OK\", within: " - "\"Preferences\"} or {menu: \"File>Export>Export G-code\"}; list_widgets's description " + "\"Preferences\"} or {menu: \"File>Export>Export G-code\"}; widget_list's description " "lists every kind."}}; -// run_javascript's target: a web view or an element of its page, not a widget. +// webview_run_javascript's target: a web view or an element of its page, not a widget. const json kPageTargetSchema = {{"type", json::array({"string", "object"})}, - {"description", "A web view (its ref; list_widgets lists it as kind webview) or an element of its " + {"description", "A web view (its ref; widget_list lists it as kind webview) or an element of its " "page (its ref or a {web} / {css} locator), which the code gets as `el`. Default: " "the topmost dialog's web view, else the only one shown."}}; @@ -88,7 +88,7 @@ const json kPageTimeoutSchema = {{"type", "integer"}, const json kModifiersSchema = {{"type", "array"}, {"items", {{"type", "string"}, {"enum", {"ctrl", "cmd", "rawctrl", "shift", "alt"}}}}, - {"description", "Modifier keys held during the input, as in press_keys: ctrl and cmd are both Command on macOS " + {"description", "Modifier keys held during the input, as in keyboard_press: ctrl and cmd are both Command on macOS " "and Ctrl elsewhere; rawctrl is the macOS Control key."}}; bool in_top_dialog(AutomationRuntime& runtime, wxWindow* window) @@ -123,11 +123,9 @@ void journal_with_locator(ToolContext& ctx, const json& args, const json& locato ctx.set_journal_args(std::move(recorded)); } -NativeCommand recover_input_tool(std::string group, std::string name, std::string title, std::string description, json schema, - CommandFn handler) +NativeCommand recover_input_tool(std::string name, std::string title, std::string description, json schema, CommandFn handler) { - NativeCommand d = mutate_tool(std::move(group), std::move(name), std::move(title), std::move(description), std::move(schema), - std::move(handler)); + NativeCommand d = mutate_tool(std::move(name), std::move(title), std::move(description), std::move(schema), std::move(handler)); d.guard = GuardClass::Recover; return d; } @@ -237,12 +235,12 @@ wxWebView* default_webview(AutomationRuntime& runtime) } } if (webs.empty()) - throw ToolFailure("No web view is shown (the Home tab has one: set_view tab=home)"); + throw ToolFailure("No web view is shown (the Home tab has one: view_set tab=home)"); if (webs.size() > 1) { json urls = json::array(); for (wxWebView* w : webs) urls.push_back(redact_url(into_u8(w->GetCurrentURL()))); - throw ToolFailure("Several web views are shown" + where + "; pass target (list_widgets query=webview)", {{"web_views", urls}}); + throw ToolFailure("Several web views are shown" + where + "; pass target (widget_list query=webview)", {{"web_views", urls}}); } return webs.front(); } @@ -266,7 +264,7 @@ void guard_page(AutomationRuntime& runtime, ToolContext& ctx, wxWebView* web) // The input tools reach a page element through its page's agent (WebPages.hpp): resolve it, guard // its web view as any widget's window, ask the page to act, and observe what followed. -// A "d" ref from list_widgets, also written {ref: "d12"}, or a {css}/{web} locator. +// A "d" ref from widget_list, also written {ref: "d12"}, or a {css}/{web} locator. bool is_web_target(const json& target) { const json& ref = target.is_object() && target.size() == 1 && target.contains("ref") ? target["ref"] : target; @@ -295,13 +293,13 @@ WebHandle web_view_target(AutomationRuntime& runtime, ToolContext& ctx, const js return out; } -// click and set_widget_value on a web view: the page's elements are the targets. +// widget_click and widget_set_value on a web view: the page's elements are the targets. void refuse_web_view(AutomationRuntime& runtime, ToolContext& ctx, const json& target) { std::string within; if (web_view_target(runtime, ctx, target, within) != 0) throw ToolFailure("That is a web view, whose page wx events don't reach; target one of its page elements: a d ref from " - "list_widgets, or a {web} / {css} locator"); + "widget_list, or a {web} / {css} locator"); } // A page element an input tool acts on. @@ -441,7 +439,7 @@ void check_page_reply(const PageReply& r, std::chrono::seconds timeout, bool act throw ToolFailure("Cancelled: OrcaSlicer is closing or the replay or script was stopped"); throw ToolFailure("The page did not answer within " + std::to_string(timeout.count()) + " s" + (acting ? ", so the outcome is unknown: the action may have run, or may still run once the page is free. Call " - "list_widgets before trying again (timeout_s waits longer)" : + "widget_list before trying again (timeout_s waits longer)" : "; it may be busy")); } if (r.value.contains("error")) { @@ -453,7 +451,7 @@ void check_page_reply(const PageReply& r, std::chrono::seconds timeout, bool act } // The pages a locator looks in: the shown ones within `within`, in snapshot order. Without `within` -// while the topmost modal dialog shows a page, only that dialog's pages, the ones list_widgets reads +// while the topmost modal dialog shows a page, only that dialog's pages, the ones widget_list reads // and the only ones input can reach, so a page behind it never makes a label ambiguous. std::vector locator_pages(AutomationRuntime& runtime, const std::string& within) { @@ -480,7 +478,7 @@ WebTarget resolve_web(AutomationRuntime& runtime, ToolContext& ctx, const json& throw ToolFailure("The ref is not a page element"); auto* web = dynamic_cast(t.window.get()); if (web == nullptr) - throw ToolFailure("The page's web view is gone; call list_widgets again"); + throw ToolFailure("The page's web view is gone; call widget_list again"); out.web = web_handle(web); out.key = t.web_key; out.doc = t.web_doc; @@ -584,10 +582,10 @@ WebTarget resolve_web(AutomationRuntime& runtime, ToolContext& ctx, const json& throw ToolFailure("No page element matches " + target.dump() + " in what answered" + (unknown.empty() ? "" : "; " + unknown + " did not answer or failed the search") + (failed == 0 ? "" : "; " + count(failed, "page", "pages") + " could not run the page agent") + - "; nothing was done. " + (unknown.empty() ? "Call list_widgets" : "Try again once they answer"), + "; nothing was done. " + (unknown.empty() ? "Call widget_list" : "Try again once they answer"), {{"unread_pages", unread}}); if (matches.empty()) - throw ToolFailure("No page element matches " + target.dump() + "; call list_widgets"); + throw ToolFailure("No page element matches " + target.dump() + "; call widget_list"); if (matches.size() > 1 && index < 0) { json listed = json::array(); for (const Match& m : matches) @@ -633,7 +631,7 @@ json web_locator(AutomationRuntime& runtime, ToolContext& ctx, const WebTarget& return loc; } -// Why answer_dialog does not press a button refused_press() refuses. +// Why dialog_answer does not press a button refused_press() refuses. std::string refused_button(const std::string& button, DialogPress refused) { if (refused == DialogPress::Hidden) @@ -676,7 +674,7 @@ std::string watch_id() // document behind the page (a reload, or a form posted to the same URL). Not IsBusy(), which WebView2 // also reports while a page only works. Failing those, for an action the page outlined itself before // (before.watch), `page`: whether what the page lists changed by then (changed), the lines it lists -// that it did not (added) and those it no longer does (removed), as list_widgets writes them, partial +// that it did not (added) and those it no longer does (removed), as widget_list writes them, partial // when a configuration frame could not be compared (then changed only when a line was found), and how // many messages the page itself sent OrcaSlicer during the action (posted). A change after that is the // next snapshot's to show. @@ -789,7 +787,7 @@ WebActed web_act(AutomationRuntime& runtime, ToolContext& ctx, const WebTarget& throw ToolFailure("The MCP server was turned off before this gesture ran; it was not performed"); wxWebView* web = web_view_of(t.web); if (web == nullptr || !web->IsShownOnScreen()) - throw ToolFailure("The page's web view is gone or hidden; call list_widgets again"); + throw ToolFailure("The page's web view is gone or hidden; call widget_list again"); guard_page(runtime, ctx, web); if (in_top_dialog(runtime, web)) before.modal = runtime.modals().serial(runtime.modals().top()); @@ -835,7 +833,7 @@ WebActed web_act(AutomationRuntime& runtime, ToolContext& ctx, const WebTarget& return out; } -// The DOM modifier flags of a click or gesture's `modifiers`, named as press_keys chords name them: ctrl +// The DOM modifier flags of a widget_click's or mouse_gesture's `modifiers`, named as keyboard_press chords name them: ctrl // and cmd are Command on macOS and Ctrl elsewhere, rawctrl the macOS Control key. json web_modifiers(const json& args) { @@ -869,7 +867,7 @@ PressAgent agent_of(const WebTarget& t) { return press_agent(t.web, t.doc, t.key // Ends every press mouse_gesture downs left on pages but `keep`'s, each released where it was pressed, // all asked at once so an agent that doesn't answer holds up none of the others. Every gesture, -// click and answer_dialog does this first, even one the tool then refuses, except that a move or an +// widget_click and dialog_answer does this first, even one the tool then refuses, except that a move or an // up keeps the press of the agent it is on, which it belongs to; keys and input leave the presses, as // a person can type while holding the mouse. One whose agent did not take the release (busy, // failing) stays on record, so the next gesture asks again; a release taken late is past its @@ -913,7 +911,7 @@ void end_web_press(AutomationRuntime& runtime, ToolContext& ctx, const std::opti ToolResult web_click(AutomationRuntime& runtime, ToolContext& ctx, const json& args) { if (args.contains("popup_item")) - throw ToolFailure("popup_item is for the menus OrcaSlicer opens; a page's own menu is part of the page, so call list_widgets after " + throw ToolFailure("popup_item is for the menus OrcaSlicer opens; a page's own menu is part of the page, so call widget_list after " "the click"); const auto timeout = web_timeout(args); WebTarget t = resolve_web(runtime, ctx, args["target"], timeout); @@ -954,7 +952,7 @@ ToolResult web_input(AutomationRuntime& runtime, ToolContext& ctx, const json& a ToolResult web_keys(AutomationRuntime& runtime, ToolContext& ctx, const json& args, WebTarget t) { if (args.contains("popup_item")) - throw ToolFailure("popup_item is for the menus OrcaSlicer opens; a page's own menu is part of the page, so call list_widgets after " + throw ToolFailure("popup_item is for the menus OrcaSlicer opens; a page's own menu is part of the page, so call widget_list after " "the keys"); const std::string keys = arg_string(args, "keys"), text = arg_string(args, "text"); json a{{"text", text}}; @@ -1061,7 +1059,7 @@ wxWebView* key_page(AutomationRuntime& runtime) return webs.size() == 1 && !own_widget ? webs.front() : nullptr; } -// The window set_window's target names: the main window, the topmost modal dialog, or the window a ref or +// The window window_set's target names: the main window, the topmost modal dialog, or the window a ref or // locator is in. Refuses one no tool may size or move. `locator` gets what the journal records for a // ref. UI thread. wxTopLevelWindow& window_target(AutomationRuntime& runtime, const json& target, json& locator) @@ -1080,30 +1078,30 @@ wxTopLevelWindow& window_target(AutomationRuntime& runtime, const json& target, try { t = runtime.inspector().resolve(target); } catch (const ToolFailure& e) { - // A window's ref goes stale once the window is destroyed, and list_windows gives the open ones'. + // A window's ref goes stale once the window is destroyed, and window_list gives the open ones'. if (!target.is_string()) throw; - throw ToolFailure(std::string(e.what()) + ", or list_windows for the open windows", e.details); + throw ToolFailure(std::string(e.what()) + ", or window_list for the open windows", e.details); } locator = runtime.inspector().locator_for(t); window = t.window.get() != nullptr ? wxGetTopLevelParent(t.window.get()) : nullptr; } if (dynamic_cast(window) != nullptr) - throw ToolFailure("The target is in a popup, which the window it opened from places; give that window (list_windows)"); + throw ToolFailure("The target is in a popup, which the window it opened from places; give that window (window_list)"); auto* tlw = dynamic_cast(window); if (tlw == nullptr) throw ToolFailure("The target is in no window"); if (tlw->GetName() == kHiddenFromAutomation) throw ToolFailure("The window is the person's own, which no tool reaches"); if (auto* dlg = dynamic_cast(tlw); dlg != nullptr && is_native_dialog(dlg)) - throw ToolFailure("A native dialog is placed by the system; answer it with answer_dialog"); + throw ToolFailure("A native dialog is placed by the system; answer it with dialog_answer"); // A closed dialog may be hidden rather than destroyed, so its ref still resolves. if (!tlw->IsShown()) - throw ToolFailure("The window is closed; list_windows lists the open windows"); + throw ToolFailure("The window is closed; window_list lists the open windows"); return *tlw; } -// `window` while it is still one of the app's top-level windows, else null: set_window keeps a plain +// `window` while it is still one of the app's top-level windows, else null: window_set keeps a plain // pointer across its UI closures and checks it before following it. UI thread. wxTopLevelWindow* live_window(wxTopLevelWindow* window) { @@ -1113,7 +1111,7 @@ wxTopLevelWindow* live_window(wxTopLevelWindow* window) return nullptr; } -// set_window: checks the request and applies it in one UI closure, waits for the window to take it, +// window_set: checks the request and applies it in one UI closure, waits for the window to take it, // then replies with what the window became. A size or position applies to the normal window, so a // maximized or minimized one is restored first. Where the window system restores it later (GTK), the call // waits for that before sizing, as a size given meanwhile is lost: on Wayland the compositor's answer to @@ -1234,7 +1232,7 @@ ToolResult set_window(AutomationRuntime& runtime, ToolContext& ctx, const json& wxTopLevelWindow* w = live_window(window); if (w == nullptr) throw ToolFailure(closed); - // list_windows's own entry, so the two report a window alike. + // window_list's own entry, so the two report a window alike. const json entry = runtime.inspector().window_entry(*w, modal); json reply{{"title", entry["title"]}, {"kind", entry["kind"]}, {"ref", entry["ref"]}, {"size", {entry["width"], entry["height"]}}}; if (entry.contains("x")) @@ -1301,7 +1299,7 @@ std::string window_request_refusal(const json& args, const WindowAbilities& wind { const bool size = args.contains("size"), position = args.contains("position"); if (!size && !position && !args.contains("state") && !args.contains("raise")) - return "Give at least one of size, position, state or raise; list_windows reads a window's geometry without changing it"; + return "Give at least one of size, position, state or raise; window_list reads a window's geometry without changing it"; // Two whole numbers that fit wx's int coordinates, both positive for a size. Whole floats pass, as // they pass the schema's integer type. const auto is_pair = [](const json& value, bool positive) { @@ -1343,15 +1341,15 @@ json display_area(unsigned index) void register_ui_tools(CommandCatalog& catalog) { catalog.add(inspect_tool( - "ui", "list_windows", L("List the windows"), + "window_list", L("List the windows"), "List OrcaSlicer's open windows: the main window, then the windows that don't block the app (Plugins, an " "object's settings, a dock panel floating on its own), then the modal dialogs in the order they opened, the " - "topmost last. A window's ref goes to screenshot as target to capture that window, to list_widgets as target to " - "list it alone, and to press_keys as target; its title is the within of locators for its widgets.\n" + "topmost last. A window's ref goes to window_screenshot as target to capture that window, to widget_list as target to " + "list it alone, and to keyboard_press as target; its title is the within of locators for its widgets.\n" "Reply: each window's title, kind (main, window, dialog, or panel: a dock panel floating on its own), modal, " "ref, web (it shows a web page), x and y on screen (not on Wayland, which doesn't say), width and height, state " - "(normal, maximized or minimized) and resizable (it has a resize border); set_window changes them.\n" - "A native dialog (a message box, a file picker) has native: true and no ref: answer_dialog answers it. hidden: " + "(normal, maximized or minimized) and resizable (it has a resize border); window_set changes them.\n" + "A native dialog (a message box, a file picker) has native: true and no ref: dialog_answer answers it. hidden: " "true marks the person's own windows (Action Replay, the Run Script panel and their prompts, the Python scripts " "setting), which no tool reaches and screenshots leave out.", object_schema({{"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 200}, {"description", "Default 100."}}}, @@ -1363,11 +1361,11 @@ void register_ui_tools(CommandCatalog& catalog) { NativeCommand def = recover_input_tool( - "ui", "set_window", L("Size, move or raise a window"), + "window_set", L("Size, move or raise a window"), "Size, move, maximize, minimize or raise a window: the main window (default), the topmost modal dialog, or one " - "list_windows lists, also while a modal dialog is open. Size the main window before set_view fits the camera and " - "before start_recording, as a recording keeps its first frame's size. size and position are in the units " - "list_windows reports, whose x/y and width/height are read as position and size too. A size or position restores " + "window_list lists, also while a modal dialog is open. Size the main window before view_set fits the camera and " + "before recording_start, as a recording keeps its first frame's size. size and position are in the units " + "window_list reports, whose x/y and width/height are read as position and size too. A size or position restores " "a maximized or minimized window first. A window takes only the states its title bar offers; a modal dialog " "never minimizes. A refused call changes nothing. Replies once the window holds still and the 3D view has drawn " "at its new size (3 s at most): title, kind, ref, size, position, state, resizable, scale (screenshot pixels per " @@ -1375,7 +1373,7 @@ void register_ui_tools(CommandCatalog& catalog) "changed.", object_schema({{"target", {{"type", json::array({"string", "object"})}, {"description", "main (default), dialog (the topmost modal " - "dialog), or a window's ref or locator from list_windows; a widget's ref or " + "dialog), or a window's ref or locator from window_list; a widget's ref or " "locator picks the window it is in."}}}, {"size", array_prop({{"type", "integer"}}, "[width, height], held to the window's minimum and maximum size.")}, {"position", array_prop({{"type", "integer"}}, "[x, y] of the window's top-left corner on screen; not on Wayland.")}, @@ -1391,15 +1389,15 @@ void register_ui_tools(CommandCatalog& catalog) { NativeCommand def = inspect_tool( - "ui", "list_widgets", L("List the widgets"), - "Describe what is on screen as an indented tree, one element per line with a ref to pass to click, set_widget_value, " - "press_keys and run_javascript (a page element's to mouse_gesture too): the widgets of every shown window, the rows of lists, " + "widget_list", L("List the widgets"), + "Describe what is on screen as an indented tree, one element per line with a ref to pass to widget_click, widget_set_value, " + "keyboard_press and webview_run_javascript (a page element's to mouse_gesture too): the widgets of every shown window, the rows of lists, " "trees and tables, each shown popup after the window it opened from, the main menus, the 3D canvas's toolbar " "items and gizmos, each ImGui panel drawn in the last frame with its items and text, and the elements of each " "shown web page (dialogs, the setup wizard, sign-in, plugin windows) under its web view. With a modal dialog " - "open, only the topmost dialog's pages are read. Refs go stale when their element goes away: call list_widgets " - "again then. Prefer run_action and the typed tools when one fits.\n" - "A locator names an element without a ref, in any session (export_replay records them); index (0-based) picks " + "open, only the topmost dialog's pages are read. Refs go stale when their element goes away: call widget_list " + "again then. Prefer action_run and the typed tools when one fits.\n" + "A locator names an element without a ref, in any session (replay_export records them); index (0-based) picks " "one of several matches:\n" "- a widget: {label, class, name, within, index}, within being its window's title; a notebook page: {tab: " "\"General\", within}\n" @@ -1411,11 +1409,11 @@ void register_ui_tools(CommandCatalog& catalog) "- a plate or one of its icons in the Prepare view: {plate_icon: \"lock\", plate: 0}, the icon being plate, " "delete, orient, arrange, lock, settings, name, move_to_front, filament_map or imex_mode\n" "- a web page's element: {web: \"Next\", kind?: \"button\", css?: \"#AcceptBtn\", within?, index?}, by the label " - "list_widgets lists (exactly, else ignoring case, else a part of it), its kind, a CSS selector (the id a line " + "widget_list lists (exactly, else ignoring case, else a part of it), its kind, a CSS selector (the id a line " "shows as name: name=#save is {css: \"#save\"}), or together. Without within it looks in the topmost dialog's " "pages while one is open, else in every shown page, and an action on it waits for its element up to 2 s short of " "the action's timeout_s (8 s by default), but at least 3 s or the whole of a shorter timeout_s.", - object_schema({{"target", prop("string", "all (default), main, dialog (the topmost modal), popup, or a window's ref (list_windows).")}, + object_schema({{"target", prop("string", "all (default), main, dialog (the topmost modal), popup, or a window's ref (window_list).")}, {"query", prop("string", "Case-insensitive text to look for in labels, values, names and classes.")}, {"max_nodes", {{"type", "integer"}, {"minimum", 1}, {"maximum", 5000}, {"description", "Default 400."}}}, {"include_imgui", prop("boolean", "List ImGui items (default true).")}, @@ -1481,7 +1479,7 @@ void register_ui_tools(CommandCatalog& catalog) } catalog.add(recover_input_tool( - "ui", "click", L("Click an element"), + "widget_click", L("Click an element"), "Click a GUI element as a person would. Menu items, buttons, checkboxes, toggles, radio buttons, toolbar items and " "gizmos are activated the way their owners expect: a gizmo opens and a second click closes it (Text on an object " "without text creates a text part: created). Other widgets and ImGui items get a mouse click once scrolled into " @@ -1500,7 +1498,7 @@ void register_ui_tools(CommandCatalog& catalog) "refused when something else covers that point. The reply reads back checked, and has closed when the click closed " "its dialog (with dialogs, those still open under it, which still need an answer), navigated (with url) when it " "changed the page, or dialogs when it opened another. Otherwise page says what changed on the page within 300 ms: " - "changed (false when its lines are as before), the list_widgets lines added and removed, partial when a plugin " + "changed (false when its lines are as before), the widget_list lines added and removed, partial when a plugin " "configuration frame could not be compared, and posted, how many messages the page sent OrcaSlicer.", object_schema({{"target", kTargetSchema}, {"button", enum_prop({"left", "right", "middle"}, "Default left.")}, @@ -1592,7 +1590,7 @@ void register_ui_tools(CommandCatalog& catalog) })); catalog.add(recover_input_tool( - "ui", "set_widget_value", L("Set a widget's value"), + "widget_set_value", L("Set a widget's value"), "Set a widget's value and send the events a person's edit would. Widgets: text fields (submit, the default, also " "presses Enter and leaves the field, which is when Orca's setting fields commit), spin controls, sliders, choice, " "combo and list boxes (by option text or index), checkboxes, toggles and a row's checkbox (true or false), and a " @@ -1603,9 +1601,9 @@ void register_ui_tools(CommandCatalog& catalog) "beside it, multiline text with \\n), a combo's option is picked by its text or 0-based index, and a checkbox, radio " "or toggle is clicked when it differs. A web page's fields, as typing would leave them: text, number, range, colour " "and date fields and editable text get the value with input and change events (submit then leaves the field; " - "press_keys Return presses Enter), a select its option by text, value or index, and a checkbox or radio is clicked when " - "it differs; the value is read back and page says what changed, as for click. File fields can't be set. For " - "settings, set_settings is more reliable.", + "keyboard_press Return presses Enter), a select its option by text, value or index, and a checkbox or radio is clicked when " + "it differs; the value is read back and page says what changed, as for widget_click. File fields can't be set. For " + "settings, settings_set is more reliable.", object_schema({{"target", kTargetSchema}, {"value", {{"type", json::array({"string", "number", "boolean"})}, {"description", "The new value."}}}, {"submit", prop("boolean", "Press Enter / commit after setting (default true).")}, @@ -1629,15 +1627,15 @@ void register_ui_tools(CommandCatalog& catalog) })); catalog.add(recover_input_tool( - "ui", "press_keys", L("Press keys"), + "keyboard_press", L("Press keys"), "Send a key chord (\"Ctrl+S\", \"Escape\", \"Return\", \"Delete\", \"Shift+Tab\", \"Left\", \"F5\") and/or type text to " "a target or, without one, to the focused window (the topmost dialog while one is open, the shown 3D view when " "nothing has focus). As with a real key press, the shortcut handling of the target's panels and window sees the keys " - "first. Typing reaches ImGui fields and key handlers; fill a widget's text field with set_widget_value. A menu the keys open " + "first. Typing reaches ImGui fields and key handlers; fill a widget's text field with widget_set_value. A menu the keys open " "is listed as popup_menu, or popup_item runs one of its items. Keys for a web page (its element, or without a " "target the focused web view or the topmost dialog's only page) go to the page's focused element with the " "browser's default actions: typing, Backspace/Delete, Enter (submits a form, activates a button), Space, Tab moving " - "the focus, arrows stepping a select, range or radio group; page says what they changed, as for click.", + "the focus, arrows stepping a select, range or radio group; page says what they changed, as for widget_click.", object_schema({{"target", kTargetSchema}, {"keys", prop("string", "One chord: a key, after any modifiers joined by +. Keys: one character, Enter, Esc, " "Tab, Space, Backspace, Delete, Insert, Home, End, PageUp, PageDown, Left, Right, " @@ -1710,22 +1708,22 @@ void register_ui_tools(CommandCatalog& catalog) mouse_canvases.insert(mouse_canvases.end() - 1, "design"); #endif catalog.add(recover_input_tool( - "ui", "mouse_gesture", L("Mouse gesture on a 3D view or page element"), + "mouse_gesture", L("Mouse gesture on a 3D view or page element"), "Make a mouse gesture on a 3D canvas as a person would: move, down, up, click, drag or wheel. It starts at `at`, a " "point of the model, which is projected through the camera and by default checked to land on that part (check " "\"point\" only projects it), or at x/y, logical pixels from the canvas's top left. A drag goes through `waypoints` to " "`to`, `steps` moves per leg: on an object it moves the object, in a painting gizmo it paints from a press on the " "object being painted (waypoints zigzagging over an area paint all of it), and elsewhere it turns or pans the camera " - "as this install's mouse settings say, so turn the camera with set_view camera or orbit instead. A wheel turns delta " + "as this install's mouse settings say, so turn the camera with view_set camera or orbit instead. A wheel turns delta " "notches; positive zooms in (out with the Reverse mouse zoom preference on) or scrolls a panel up. Modifiers are " "held as keys for the gesture (shift picks points in Measure and erases in a painting gizmo). A down keeps its button and modifiers held, so moves drag, until an up or another " - "gesture. Grabbers are set through the gizmo's panel fields or transform, not dragged. A menu a right click opens " + "gesture. Grabbers are set through the gizmo's panel fields or object_transform, not dragged. A menu a right click opens " "is listed as popup_menu, or popup_item (with click or up) runs one of its items. The reply's camera_moved says the " "gesture moved the camera, so earlier screenshots and pixels no longer match the view.\n" "With target, the gesture is on a web page's element instead (a canvas such as the colour picker's spectrum, a " "slider, a sortable or scrolled list): x/y, to and waypoints are logical pixels from its top left, a drag keeps the " "pointer captured where the page asks for it, and a wheel scrolls what is under the pointer unless the page takes " - "it; page says what the gesture changed there, as for click.", + "it; page says what the gesture changed there, as for widget_click.", object_schema({{"action", enum_prop({"move", "down", "up", "click", "drag", "wheel"}, "Default click.")}, {"canvas", enum_prop(mouse_canvases, "Default current, the view shown. design takes x/y only.")}, {"at", target_schema}, @@ -1768,8 +1766,8 @@ void register_ui_tools(CommandCatalog& catalog) const std::string name = arg_string(args, "canvas", "current"); GLCanvas3D* canvas = name == "current" ? shown_canvas() : canvas_by_name(name); if (canvas == nullptr || !canvas->get_wxglcanvas()->IsShownOnScreen()) - throw ToolFailure(name == "design" ? "The Design view is not shown; set_view {\"tab\": \"design\"} first" : - "That 3D view is not shown; switch to it with set_view first"); + throw ToolFailure(name == "design" ? "The Design view is not shown; view_set {\"tab\": \"design\"} first" : + "That 3D view is not shown; switch to it with view_set first"); // The Design view sets up its GL at its first frame, as DesignCanvas guards its own renders. if (canvas == design_canvas() && !canvas->is_initialized()) throw ToolFailure("The Design view has not drawn yet"); @@ -1795,12 +1793,12 @@ void register_ui_tools(CommandCatalog& catalog) })); catalog.add(mutate_tool( - "ui", "pick_gizmo_file", L("Load or save the open gizmo's SVG or texture file"), + "gizmo_pick_file", L("Load or save the open gizmo's SVG or texture file"), "Do what a file picker inside the open gizmo does, with a path instead of its dialog: svg_change loads another SVG " "file into the SVG part being edited, svg_save_as writes that part's SVG to a new file (an existing one only with " "overwrite), texture_import imports a height-map image into the texture library and puts it on Texture " - "Displacement's active layer. To add an SVG part, use run_action add_primitive_svg with a path. Gizmos open with " - "click {target: {gizmo: name}}, and their panels take set_widget_value / click on the ImGui items list_widgets lists.", + "Displacement's active layer. To add an SVG part, use object_add_svg with a path. Gizmos open with " + "widget_click {target: {gizmo: name}}, and their panels take widget_set_value / widget_click on the ImGui items widget_list lists.", object_schema({{"action", enum_prop({"svg_change", "svg_save_as", "texture_import"}, "What to do.")}, {"path", prop("string", "Absolute path of the file to read or write.")}, {"overwrite", prop("boolean", "svg_save_as: replace an existing file.")}}, @@ -1842,21 +1840,21 @@ void register_ui_tools(CommandCatalog& catalog) })); catalog.add(recover_input_tool( - "core", "answer_dialog", L("Answer a dialog"), + "dialog_answer", L("Answer a dialog"), "Press a button of the topmost modal dialog: yes, no, ok, cancel, close, apply, a button's label, or a numeric id. " "A disabled button (enabled: false) is refused, the dialog's message showing what it still needs, and so is one on " "a page the dialog does not show, except a hidden cancel or close, which ends the dialog. On a dialog that is " "neither native nor a web dialog, a standard name or id it has no button for ends it with that answer too, " "without a handler running (pressed: false). The label of an option of a " "selector made of buttons (Orca's radio groups, tab bars and multi-switches, shown as (*) / ( ) in the message) " - "selects that option and leaves the dialog open; set other radio buttons and switches with click or set_widget_value " - "true, and notebook tabs with click. " + "selects that option and leaves the dialog open; set other radio buttons and switches with widget_click or widget_set_value " + "true, and notebook tabs with widget_click. " "dialog.title, text the dialog's title contains, makes sure which dialog that is; it must be the topmost. Reply: " "dialog, button, pressed, and id, the wx id pressed or ended with, or web: true for a button on a web dialog's " - "page, with what the page did as click reports it; closed: true when it closed, and dialogs, those still open. A " + "page, with what the page did as widget_click reports it; closed: true when it closed, and dialogs, those still open. A " "native message box (native: true) is pressed through " - "the OS, by one of the buttons get_app_state.dialogs lists for it; a file or folder picker can't be answered here, nor " - "any native dialog on macOS (its buttons list is empty): register auto_answer_dialogs before opening them. A web " + "the OS, by one of the buttons app_state.dialogs lists for it; a file or folder picker can't be answered here, nor " + "any native dialog on macOS (its buttons list is empty): register dialog_auto_answer before opening them. A web " "dialog's buttons are on its page: a label is pressed there, waiting up to 3 s for it to show, so the page's own " "handler runs. With no such page button, or a page busy for those 3 s, cancel and close end the dialog, and ok, yes, " "no and apply are refused rather than skip the page's commit; page_buttons then lists the page's buttons.", @@ -1894,7 +1892,7 @@ void register_ui_tools(CommandCatalog& catalog) } if (is_native_dialog(dialog) && message_box_buttons(dialog).empty()) throw ToolFailure("This native dialog (a file or folder picker, or a message box on macOS) can't be pressed; " - "register auto_answer_dialogs before the action that opens it", + "register dialog_auto_answer before the action that opens it", {{"dialog", describe_dialog(dialog)}}); return dialog; }; @@ -1925,7 +1923,7 @@ void register_ui_tools(CommandCatalog& catalog) throw ToolFailure(refused_button(button, *refused), {{"dialog", describe_dialog(dialog)}}); const DialogPress press = press_dialog_button(dialog, id); if (press == DialogPress::Failed) - throw ToolFailure("The message box is not shown, so its button could not be pressed; call list_widgets again", + throw ToolFailure("The message box is not shown, so its button could not be pressed; call widget_list again", {{"dialog", describe_dialog(dialog)}}); return {{"dialog", dialog_title}, {"button", button}, {"id", id}, {"pressed", press == DialogPress::Pressed}}; }); @@ -1959,7 +1957,7 @@ void register_ui_tools(CommandCatalog& catalog) wxDialog* dialog = find_dialog(); wxWebView* web = web_view_of(page.web); if (dialog != web_dialog || web == nullptr) - throw ToolFailure("The dialog changed while its page was being asked; call list_widgets again"); + throw ToolFailure("The dialog changed while its page was being asked; call widget_list again"); before.modal = runtime.modals().serial(dialog); before.stack = runtime.modals().stack().size(); before.url = into_u8(web->GetCurrentURL()); @@ -2021,15 +2019,15 @@ void register_ui_tools(CommandCatalog& catalog) { NativeCommand def = recover_input_tool( - "core", "auto_answer_dialogs", L("Answer dialogs automatically"), + "dialog_auto_answer", L("Answer dialogs automatically"), "Answer modal dialogs automatically when their title or message matches a rule's regex (case-insensitive). " - "get_app_state.auto_answer_rules lists the rules in force. Called from a replay or script, the rules join those " + "app_state.auto_answer_rules lists the rules in force. Called from a replay or script, the rules join those " "it set before and last until it ends, and a plugin's likewise until it unloads; an MCP client's replace the " "ones MCP clients set before and last until the MCP server stops, and an empty list clears them. Reply: scope (run, plugin or session), rules (uses counts " "a rule's answers) and answered_open_dialog. A native dialog " "returns the rule's button at once and never shows. A file or folder picker takes button ok with an absolute path " "and returns it without showing (on Linux such a rule cancels it); without a path a picker can only be cancelled, " - "and a multi-select picker takes no path. A wx dialog is answered as answer_dialog does. A matching dialog " + "and a multi-select picker takes no path. A wx dialog is answered as dialog_answer does. A matching dialog " "already open is answered too " "(answered_open_dialog), so a prompt that shows around the same time, such as the restore prompt after startup, " "is caught either way. A web dialog is matched by its title: a button that names one of its shown wx buttons (by " @@ -2056,7 +2054,7 @@ void register_ui_tools(CommandCatalog& catalog) // Paused rules leave the dialog that is open now to the person, as they leave the ones that open later. json answered = set.paused ? json() : ctx.run_ui([&]() -> json { wxDialog* top = runtime.modals().top(); - // A message box is pressed as answer_dialog presses it; a picker can't be. + // A message box is pressed as dialog_answer presses it; a picker can't be. const bool native = top != nullptr && is_native_dialog(top); if (top == nullptr || (native && message_box_buttons(top).empty())) return json(); @@ -2103,15 +2101,15 @@ void register_ui_tools(CommandCatalog& catalog) } NativeCommand eval = recover_input_tool( - "ui", "run_javascript", L("Run JavaScript in a web view"), + "webview_run_javascript", L("Run JavaScript in a web view"), "Evaluate JavaScript in one of OrcaSlicer's web views (Home, the device page, dialogs, plugin windows). Prefer " - "list_widgets and the input tools (click, set_widget_value, press_keys, mouse_gesture), which see and drive pages as they do widgets. The code runs in the target's page: " - "a web view's (kind webview in list_widgets), or a page element's, with the element as `el`; without a target, in " + "widget_list and the input tools (widget_click, widget_set_value, keyboard_press, mouse_gesture), which see and drive pages as they do widgets. The code runs in the target's page: " + "a web view's (kind webview in widget_list), or a page element's, with the element as `el`; without a target, in " "the topmost dialog's web view, else in the only shown one. While a modal dialog is open, only its pages run " "code. Reply: result, the value of the last expression (JSON values come back parsed), and url; closed: true when " "the code closed its dialog, navigated: true when it changed the page, dialogs when it opened another. Messages " "the page posts to OrcaSlicer reach it once the code has returned. It runs through eval, which a page whose " - "Content-Security-Policy forbids it may refuse (list_widgets and the input tools still work there).", + "Content-Security-Policy forbids it may refuse (widget_list and the input tools still work there).", object_schema({{"code", prop("string", "JavaScript statements, run through eval: the last expression's value is the " "result. No top-level return or await; a Promise or a DOM node comes back as {}.")}, {"target", kPageTargetSchema}, @@ -2141,11 +2139,11 @@ void register_ui_tools(CommandCatalog& catalog) locator = runtime.inspector().locator_for(t); web = dynamic_cast(target_window(t)); if (web == nullptr) - throw ToolFailure("The target is not a web view (list_widgets lists them as kind webview)"); + throw ToolFailure("The target is not a web view (widget_list lists them as kind webview)"); } else web = default_webview(runtime); if (web == nullptr) - throw ToolFailure("The page's web view is gone; call list_widgets again"); + throw ToolFailure("The page's web view is gone; call widget_list again"); guard_page(runtime, ctx, web); page.web = web_handle(web); before.modal = in_top_dialog(runtime, web) ? runtime.modals().serial(runtime.modals().top()) : 0; diff --git a/src/slic3r/GUI/Mcp/McpToolsView.cpp b/src/slic3r/GUI/Mcp/McpToolsView.cpp index ed0c440012..248208c838 100644 --- a/src/slic3r/GUI/Mcp/McpToolsView.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsView.cpp @@ -1,5 +1,6 @@ -// screenshot, get_slice_stats and set_view: what the agent looks at and reads off the Preview, and -// pointing the view before looking. +// window_screenshot, plate_slice_stats and view_set: what the agent looks at and reads off the Preview, and +// pointing the view before looking; and the window commands made from menu rows, window_open and +// window_save_screenshot. #include "libvgcode/include/ColorRange.hpp" #include "slic3r/GUI/I18N.hpp" @@ -11,7 +12,9 @@ #include "ModalTracker.hpp" #include "ScreenCapture.hpp" #include "UiInspector.hpp" +#include "slic3r/GUI/ActionRegistry.hpp" #include "slic3r/GUI/Camera.hpp" +#include "slic3r/GUI/CommandCatalog.hpp" #include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/GCodeViewer.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" @@ -20,6 +23,9 @@ #include "slic3r/GUI/IMSlider.hpp" #include "slic3r/GUI/LibVGCode/LibVGCodeWrapper.hpp" #include "slic3r/GUI/MainFrame.hpp" +#include "slic3r/GUI/NativeCommandRows.hpp" +#include "slic3r/GUI/NativeCommands.hpp" +#include "slic3r/GUI/Notebook.hpp" #include "slic3r/GUI/Operations/Outcome.hpp" #include "slic3r/GUI/Operations/PlateOps.hpp" #include "slic3r/GUI/PartPlate.hpp" @@ -29,6 +35,7 @@ #include "slic3r/GUI/CAD/DesignPanel.hpp" #endif +#include "libslic3r/AppConfig.hpp" #include "libslic3r/Config.hpp" #include "libslic3r/ExtrusionEntity.hpp" #include "libslic3r/GCode/GCodeProcessor.hpp" @@ -80,19 +87,13 @@ std::string base64(const std::string& bytes) return out; } -const char* tab_id(const std::string& name) +// The ids of the main window's notebook pages, in the notebook's order. +std::vector notebook_pages(const Notebook& notebook) { - if (name == "home") return TAB_ID_HOME; - if (name == "prepare") return TAB_ID_PREPARE; - if (name == "preview") return TAB_ID_PREVIEW; - if (name == "device" || name == "monitor") return TAB_ID_MONITOR; - if (name == "multi_device") return TAB_ID_MULTI_DEVICE; - if (name == "project") return TAB_ID_PROJECT; - if (name == "calibration") return TAB_ID_CALIBRATION; -#ifdef SLIC3R_CAD - if (name == "design") return TAB_ID_DESIGN; -#endif - return nullptr; + std::vector pages; + for (size_t i = 0; i < notebook.GetPageCount(); ++i) + pages.push_back(into_u8(notebook.GetPageName(i))); + return pages; } // Rounded for a reply, which reads like the legend rather than the raw floats. @@ -158,7 +159,7 @@ bool any_legend_row(const std::string& key) return false; } -// set_view's legend argument: each named row shown or hidden as a click on it does, clicked only when its +// view_set's legend argument: each named row shown or hidden as a click on it does, clicked only when its // state differs. The rows are the feature types and options the print has, whatever the view type: the // viewer keeps one visibility set, though the legend lists feature types only in Line Type. The keys are // checked here, before the Preview changes; the returned function applies them and gives each row's @@ -226,13 +227,13 @@ std::pair camera_angles(Camera& camera) return {std::asin(std::clamp(offset.z() / distance, -1., 1.)), std::atan2(flat.y(), flat.x())}; } -// Angles in radians as set_view replies with them: whole degrees, the azimuth from -180 to 180. +// Angles in radians as view_set replies with them: whole degrees, the azimuth from -180 to 180. json angles_json(double elevation, double azimuth) { return {{"elevation", std::lround(Geometry::rad2deg(elevation))}, {"azimuth", std::lround(std::remainder(Geometry::rad2deg(azimuth), 360.))}}; } -// set_view's orbit: the camera moved around the point it looks at, `yaw` degrees to its right +// view_set's orbit: the camera moved around the point it looks at, `yaw` degrees to its right // (counterclockwise seen from above) and `pitch` degrees up, at the same distance. It is placed from its // position rather than turned as a mouse drag turns it, so the result is the same whatever the user's // mouse settings and free-camera preference. The elevation stops a degree short of straight up or down, @@ -258,15 +259,23 @@ bool fit_pending(const Camera& camera) return camera.requires_zoom_to_bed || camera.requires_zoom_to_volumes || camera.requires_zoom_to_plate != REQUIRES_ZOOM_TO_PLATE_IDLE; } -// set_view's camera: a named direction or a fit of the shown 3D view. On the Design tab it points the Design -// view as its own controls do, `default` being its Home view and `sketch_normal` the sketch's N key. UI thread. -void point_camera(Plater& plater, const std::string& cam) +// Why fit_bed does nothing on the Design tab, which a pick of Fit Bed to View shows there. +Ops::Refusal no_bed_in_design() +{ + return Ops::Refusal{Ops::RefusalKind::Precondition, "no_bed_in_design", L("The Design tab has no bed to fit the view to.")}; +} + +// view_set's camera, and a pick of a camera tile: a named direction or a fit of the shown 3D view. On the Design tab +// it points the Design view as its own controls do, `default` being its Home view and `sketch_normal` the sketch's N +// key. The refusal is the one a tile can reach, fit_bed on the Design tab; fit_selection and sketch_normal, which no +// tile gives, throw. UI thread. +std::optional point_camera(Plater& plater, const std::string& cam) { #ifdef SLIC3R_CAD if (DesignPanel* design = wxGetApp().mainframe->shown_design_panel()) { DesignCanvas* view = design->mcp_viewport(); if (cam == "fit_bed") - throw ToolFailure("fit_bed is not offered in the Design tab"); + return no_bed_in_design(); if (cam == "fit_objects") view->fit_view(); else if (cam == "fit_selection") { @@ -277,7 +286,7 @@ void point_camera(Plater& plater, const std::string& cam) throw ToolFailure("No sketch is open in the Design tab"); } else view->set_view(cam == "default" ? "iso" : cam); - return; + return std::nullopt; } #endif GLCanvas3D* canvas = plater.get_current_canvas3D(); @@ -297,6 +306,7 @@ void point_camera(Plater& plater, const std::string& cam) } else { plater.select_view(cam); } + return std::nullopt; } // Asks the shown 3D view, the Design view on the Design tab, to draw again. UI thread. @@ -309,6 +319,142 @@ void repaint_shown_canvas() } } +// The 3D view of Prepare or the Preview whose axes switch app_state reads: the one shown, else Prepare's. UI thread. +GLCanvas3D* axes_canvas(Plater& plater) +{ + GLCanvas3D* preview = plater.get_preview_canvas3D(); + return plater.is_preview_shown() && preview != nullptr ? preview : plater.get_view3D_canvas3D(); +} + +// view_set's display switches of Prepare and the Preview, under the names it and app_state give them: the switches of +// the View menu and of the 3D view's own menu (the canvas toolbar's), each read as its check mark or eye shows it and set +// as its item sets it, where it differs. labels and overhangs are Prepare's 3D view's, which its items set while it is +// shown, and are set on it from any tab; Prepare's and the Preview's 3D views each draw the axes by a switch of their +// own, which the menu sets on the view shown, and axes sets both. The others are the app's. UI thread. +struct ViewSwitch +{ + const char* name; + bool (*shown)(Plater&); + void (*show)(Plater&, bool); +}; + +const ViewSwitch kViewSwitches[] = { + {"labels", [](Plater& plater) { return plater.get_view3D_canvas3D()->are_labels_shown(); }, + [](Plater& plater, bool on) { + plater.get_view3D_canvas3D()->show_labels(on); + wxGetApp().app_config->set_bool("show_labels", on); + }}, + {"overhangs", [](Plater& plater) { return plater.get_view3D_canvas3D()->is_overhang_shown(); }, + [](Plater& plater, bool on) { + plater.get_view3D_canvas3D()->show_overhang(on); + wxGetApp().app_config->set_bool("show_overhang", on); + }}, + {"outline", [](Plater&) { return wxGetApp().show_outline(); }, + [](Plater&, bool on) { + if (wxGetApp().show_outline() != on) + wxGetApp().toggle_show_outline(); + }}, + {"wireframe", [](Plater& plater) { return plater.is_show_wireframe(); }, + [](Plater& plater, bool on) { + if (plater.is_show_wireframe() != on) + plater.toggle_show_wireframe(); + }}, + {"gridlines", [](Plater&) { return wxGetApp().show_plate_gridlines(); }, + [](Plater&, bool on) { + if (wxGetApp().show_plate_gridlines() != on) + wxGetApp().toggle_show_plate_gridlines(); + }}, + {"axes", [](Plater& plater) { return axes_canvas(plater)->are_world_axes_shown(); }, + [](Plater& plater, bool on) { + for (GLCanvas3D* canvas : {plater.get_view3D_canvas3D(), plater.get_preview_canvas3D()}) + if (canvas != nullptr && canvas->are_world_axes_shown() != on) + canvas->toggle_world_axes_visibility(false); + }}, + {"navigator", [](Plater&) { return wxGetApp().show_3d_navigator(); }, + [](Plater&, bool on) { + if (wxGetApp().show_3d_navigator() != on) + wxGetApp().toggle_show_3d_navigator(); + }}, +}; + +// The section view of Prepare and the Preview, whose 3D views share it: on, as a right click on its toolbar button turns +// it on, at the cut it had or through the middle, and off. UI thread. +bool section_view_on(Plater& plater) { return plater.get_view3D_canvas3D()->is_section_view_active(); } + +void show_section_view(Plater& plater, bool on) +{ + GLCanvas3D* canvas = plater.get_view3D_canvas3D(); + if (canvas->is_section_view_active() != on) + canvas->toggle_section_view(); +} + +// view_set's tab, and a pick of Go to tab: shows the main window's page `tab` names (view_tab_page()). Refused when no +// page has that name, named as given, or when the page refuses to open, named by its id as the Speed Dial lists it. +// UI thread. +std::optional show_tab(MainFrame& frame, const std::string& tab) +{ + const std::optional page = frame.m_tabpanel != nullptr ? view_tab_page(tab, notebook_pages(*frame.m_tabpanel)) : + std::nullopt; + if (!page) + // TRN %1% is the tab id the command was given, such as "preview". + return Ops::Refusal{Ops::RefusalKind::Precondition, "no_such_tab", L("No tab has the id \"%1%\"."), {tab}}; + frame.select_tab(from_u8(*page)); + // The tab can refuse to open: the Device tab of a Bambu Lab printer without its network plugin. + if (frame.m_tabpanel->GetSelectedPageName() != from_u8(*page)) + // TRN %1% is the id of the tab that could not be opened, such as "monitor". + return Ops::Refusal{Ops::RefusalKind::Failed, "tab_not_opened", L("The \"%1%\" tab could not be opened."), {*page}}; + return std::nullopt; +} + +// The Preview tab, which a preview field given without tab or canvas, and a pick of Go to layer, show. UI thread. +void show_preview(Plater& plater, MainFrame& frame) +{ + plater.select_view_3D("Preview", false); + frame.select_tab(wxString(TAB_ID_PREVIEW)); +} + +// view_set's layer_percent, and a pick of Go to layer: the top of the Preview's shown range moves to the layer that +// share of the plate's layers stands for, and its bottom stays. UI thread. +Ops::Outcome show_layer_percent(double percent) +{ + const Ops::Outcome count = Ops::layer_count(); + if (!count) + return count.refusal(); + Ops::ShowLayerRangeArgs range; + range.last = int(std::lround(percent / 100.0 * double(count.value() - 1))) + 1; + return Ops::show_layer_range(range); +} + +// A person's pick of one of view_set's tiles, in place on the UI thread as its row ran: for each argument the function +// a call's UI closure runs, and a refusal in the UI's language, Go to tab's as an error and the others, which say that +// the view has nothing to show it, as information. +AppActionRunResult picked_view(const json& tile_args) +{ + Plater* plater = wxGetApp().plater(); + MainFrame* frame = wxGetApp().mainframe; + if (plater == nullptr || frame == nullptr) + return AppActionRunResult{}; + if (tile_args.contains("layout")) + return Rows::reset_window_layout(); + if (tile_args.contains("projection")) + return Rows::toggle_perspective(); + if (tile_args.contains("tab")) { + if (const std::optional refusal = show_tab(*frame, arg_string(tile_args, "tab"))) + return NativeCommands::refused(*refusal); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; + } + if (tile_args.contains("layer_percent")) { + show_preview(*plater, *frame); + const Ops::Outcome shown = show_layer_percent(tile_args.at("layer_percent").get()); + return shown ? AppActionRunResult{AppActionRunResult::Level::Succeeded} : + NativeCommands::refused(shown.refusal(), AppActionRunResult::Level::Info); + } + if (const std::optional refusal = point_camera(*plater, arg_string(tile_args, "camera"))) + return NativeCommands::refused(*refusal, AppActionRunResult::Level::Info); + repaint_shown_canvas(); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; +} + } // namespace json camera_state(Camera& camera, double canvas_scale) @@ -325,6 +471,33 @@ json camera_state(Camera& camera, double canvas_scale) return state; } +json view_state(Plater& plater) +{ + GLCanvas3D* preview = plater.get_preview_canvas3D(); + json state{{"sidebar_collapsed", plater.is_sidebar_collapsed()}, + {"sidebar_width", plater.sidebar_width()}, + {"legend_collapsed", preview != nullptr && preview->get_gcode_viewer().is_legend_folded()}, + {"gcode_window", wxGetApp().show_gcode_window()}, + {"projection", plater.get_camera().get_type_as_string()}, + {"section", {{"on", section_view_on(plater)}}}}; + for (const ViewSwitch& view_switch : kViewSwitches) + state[view_switch.name] = view_switch.shown(plater); + return state; +} + +std::optional view_tab_page(const std::string& tab, const std::vector& pages) +{ + const auto has = [&pages](const std::string& page) { return std::find(pages.begin(), pages.end(), page) != pages.end(); }; + for (const TabWord& w : kTabWords) { + if (tab == w.word) + return has(w.page) ? std::optional(w.page) : std::nullopt; + // A page a word names is reached by its word: the Device tab is device, never monitor. + if (tab == w.page) + return std::nullopt; + } + return has(tab) ? std::optional(tab) : std::nullopt; +} + std::string legend_feature_key(libvgcode::EGCodeExtrusionRole role) { return ExtrusionEntity::role_to_string(libvgcode::convert(role)); } const char* legend_option_key(libvgcode::EOptionType type) @@ -423,17 +596,17 @@ json preview_state(GCodeViewer& viewer) void register_view_tools(CommandCatalog& catalog) { NativeCommand screenshot = inspect_tool( - "ui", "screenshot", L("Take a screenshot"), + "window_screenshot", L("Take a screenshot"), "Capture what OrcaSlicer shows and return it as an image, downscaled to max_dim on the long edge (default 1280), " "plus the full-size PNG written to save_path (or the session's output folder). target: \"main\" (the main " "window), \"canvas\" (the visible 3D view exactly as rendered: scene, toolpaths, toolbars, ImGui panels; on the " "Design tab its view), " - "\"dialog\" (the topmost modal dialog), or a ref: a window's from list_windows (one that is not modal, say), or a " - "widget's from list_widgets, cropped to that widget (a page element's ref captures its whole web view). The result " + "\"dialog\" (the topmost modal dialog), or a ref: a window's from window_list (one that is not modal, say), or a " + "widget's from widget_list, cropped to that widget (a page element's ref captures its whole web view). The result " "says when parts may differ from the " - "screen (approximate). Point the view first with set_view.", + "screen (approximate). Point the view first with view_set.", object_schema({{"target", {{"type", json::array({"string", "object"})}, - {"description", "main (default), canvas, dialog, or a widget's ref or locator from list_widgets."}}}, + {"description", "main (default), canvas, dialog, or a widget's ref or locator from widget_list."}}}, {"max_dim", {{"type", "integer"}, {"minimum", 256}, {"maximum", 2000}, {"description", "Long edge of the returned image."}}}, {"save_path", prop("string", "Absolute .png path for the full-size image.")}, {"overwrite", prop("boolean", "Replace an existing save_path.")}, @@ -473,7 +646,7 @@ void register_view_tools(CommandCatalog& catalog) ui_plater(); // refuses while OrcaSlicer starts or closes GLCanvas3D* canvas = shown_canvas(); if (canvas == nullptr) - throw ToolFailure("No 3D view is shown; switch to one with set_view tab"); + throw ToolFailure("No 3D view is shown; switch to one with view_set tab"); cap = capture_canvas(*canvas, err); } else if (target == "dialog") { wxDialog* top = runtime.modals().top(); @@ -490,7 +663,7 @@ void register_view_tools(CommandCatalog& catalog) throw ToolFailure("target must be main, canvas, dialog or the ref of a widget"); if (t.kind == UiTarget::Kind::WebElement) { // A replay captures the same web view, by its own locator: a page element's - // has none the screenshot's target takes. + // has none the window_screenshot's target takes. UiTarget view; view.kind = UiTarget::Kind::Window; view.window = w; @@ -503,9 +676,9 @@ void register_view_tools(CommandCatalog& catalog) // A tab: its page, which only the selected tab shows. auto* book = dynamic_cast(w); if (book == nullptr || t.page >= int(book->GetPageCount())) - throw ToolFailure("The tab is gone; call list_widgets again"); + throw ToolFailure("The tab is gone; call widget_list again"); if (book->GetSelection() != t.page) - throw ToolFailure("The tab's page is not shown; click the tab (click) first"); + throw ToolFailure("The tab's page is not shown; click the tab (widget_click) first"); w = book->GetPage(size_t(t.page)); } if (GLCanvas3D* canvas = runtime.inspector().canvas_of(&t); canvas != nullptr && canvas->get_wxglcanvas() == w) { @@ -514,7 +687,7 @@ void register_view_tools(CommandCatalog& catalog) wxWindow* top = wxGetTopLevelParent(w); // A popup is a native window of its own, which its window's capture draws in. if (dynamic_cast(top) != nullptr) - throw ToolFailure("The widget is in a popup; a screenshot of its window shows the popup, and list_widgets " + throw ToolFailure("The widget is in a popup; a screenshot of its window shows the popup, and widget_list " "{target: \"popup\"} lists it"); auto* tlw = dynamic_cast(top); if (tlw == nullptr) @@ -583,11 +756,11 @@ void register_view_tools(CommandCatalog& catalog) catalog.add(screenshot); catalog.add(inspect_tool( - "api", "get_slice_stats", L("Get slice statistics"), - "What the Preview shows for a sliced plate. summary: the slice reply's, plus prepare and travel time and travel " + "plate_slice_stats", L("Get slice statistics"), + "What the Preview shows for a sliced plate. summary: plate_slice's, plus prepare and travel time and travel " "distance. features: seconds, share of the print time and grams per feature type (the Line Type legend), and " - "travel. layers: per layer (1-based, as set_view's layer) Z, height, seconds and grams, paged; layer_features adds " - "each feature type's seconds. objects: grams per object instance, with its list_objects index when its name is " + "travel. layers: per layer (1-based, as view_set's layer) Z, height, seconds and grams, paged; layer_features adds " + "each feature type's seconds. objects: grams per object instance, with its object_list index when its name is " "unique. view, for the plate the Preview shows: view type, time mode, layer range, which legend rows are visible, " "and each view type's colour range for what the legend shows. Times are normal-mode estimates. A G-code file " "opened for viewing reads the same.", @@ -605,7 +778,7 @@ void register_view_tools(CommandCatalog& catalog) throw ToolFailure("The Preview needs an FFF printer"); // The background process may be rewriting a result whatever its valid flag says. if (plater.is_slicing_any()) - throw ToolFailure("Slicing is in progress; wait {\"for\": \"idle\"} first"); + throw ToolFailure("Slicing is in progress; app_wait {\"for\": \"idle\"} first"); PartPlateList& plates = plater.get_partplate_list(); const int current = plates.get_curr_plate_index(); const int index = arg_int(args, "plate", current); @@ -621,7 +794,7 @@ void register_view_tools(CommandCatalog& catalog) // shows, without marking the plate sliced. const bool gcode_file = plater.only_gcode_mode() && shown; const std::string name = "Plate " + std::to_string(index); - const std::string slice_it = "slice {\"plates\": " + std::to_string(index) + "}"; + const std::string slice_it = "plate_slice {\"plates\": " + std::to_string(index) + "}"; if (result == nullptr || !(plate->is_slice_result_valid() || gcode_file)) throw ToolFailure(name + " has no up-to-date slice; " + slice_it + " first"); // Of a project opened from a sliced 3MF, a plate the Preview has not shown keeps only the file's totals. @@ -649,9 +822,9 @@ void register_view_tools(CommandCatalog& catalog) out["view"] = shown ? preview_view(*canvas) : json(); if (index != current) out["note"] = "The Preview shows plate " + std::to_string(current) + "; show plate " + std::to_string(index) + - " there (run_action orca_command:plate_goto:orca, args {\"plate\": " + std::to_string(index) + "}) to read its legend"; + " there (plate_select {\"plate\": " + std::to_string(index) + "}) to read its legend"; else if (!shown) - out["note"] = "The Preview has not loaded this plate's toolpaths; show it with set_view {\"tab\": \"preview\"}"; + out["note"] = "The Preview has not loaded this plate's toolpaths; show it with view_set {\"tab\": \"preview\"}"; } return out; })); @@ -663,13 +836,13 @@ void register_view_tools(CommandCatalog& catalog) if (std::string name = GCodeViewer::view_type_to_config_name(libvgcode::EViewType(i)); !name.empty()) view_types.push_back(std::move(name)); - std::vector tabs{"home", "prepare", "preview", "device", "multi_device", "project", "calibration"}; -#ifdef SLIC3R_CAD - tabs.insert(tabs.begin() + 1, "design"); -#endif + // The words of tab, as the description lists them. + std::string tab_words; + for (const TabWord& w : kTabWords) + tab_words += (tab_words.empty() ? "" : ", ") + std::string(w.word); - catalog.add(reaching({"show_layer_range"}, mutate_tool( - "ui", "set_view", L("Set up the view"), + NativeCommand view = reaching({"show_layer_range"}, mutate_tool( + "view_set", L("Set up the view"), "Set up what the window shows, for screenshots and GUI work: the main tab, the 3D view (canvas: Prepare's, the " "preview or the assemble view, which has its own gizmos), the camera of the 3D view shown (a named direction, the " "default view, or fit to bed / objects / selection, then look_at, the point it looks at, an orbit to look from " @@ -679,9 +852,18 @@ void register_view_tools(CommandCatalog& catalog) "sketch_normal looks straight at the open sketch), and with tab design, section, origin_planes, world_axes, origin and bed " "set the Design view's switches. The reply echoes them; preview layers as [first, last, count] with z, the heights of " "first and last; with tab design, design: the section view and the four switches as they then are; with any camera " - "field, camera_state, the camera it leaves as get_app_state.camera gives it, and adjusted: [\"zoom\"] when the zoom " - "was held to its limits.", - object_schema({{"tab", enum_prop(tabs, "Main window tab.")}, + "field, camera_state, the camera it leaves as app_state.camera gives it, and adjusted: [\"zoom\"] when the zoom " + "was held to its limits. tab takes the id of any other page of the window too, such as a plugin's. projection " + "sets the 3D camera's, layout default restores the default window layout, and layer_percent shows the Preview " + "at that share of the layer range, as Go to layer does. Outside the Design tab, from any tab: section {on} turns " + "the section view of Prepare and the Preview on or off; labels, overhangs, outline, wireframe, gridlines, axes and " + "navigator set the display switches of the View menu and of the 3D view's own menu; sidebar_collapsed and " + "sidebar_width set the sidebar of Prepare and the Preview; in the Preview, legend_collapsed folds the legend and " + "gcode_window shows the G-code window. Each is echoed as the app reads it back, and app_state's view gives them " + "under these names. A pick of a view tile runs the same code in place, so a camera tile turns the Design tab's " + "camera too.", + object_schema({{"tab", prop("string", "Main window tab: " + tab_words + ", or the id of another page of the window " + "(monitor_web, the web Device page where the app shows one, or a plugin's page).")}, {"canvas", enum_prop({"3d", "preview", "assemble"}, "3D view: Prepare's, the preview, or the assemble view (needs an object; leave it with 3d, as its Return button does).")}, {"camera", enum_prop({"iso", "top", "bottom", "front", "rear", "left", "right", "default", "fit_bed", "fit_objects", "fit_selection", "sketch_normal"}, @@ -694,15 +876,18 @@ void register_view_tools(CommandCatalog& catalog) {"keep", enum_prop({"lower", "upper"}, "The half that stays: lower (the default) or upper.")}}}, {"required", {"on"}}, {"additionalProperties", false}, - {"description", "Design tab: the section view, a horizontal cut that hides half of the model to show " - "inside it, as the toolbar's Section View and Flip set it."}}}, + {"description", "The section view, a cut that hides part of the model to show inside it. With tab " + "design, the Design view's horizontal cut, as its toolbar's Section View and " + "Flip set it, at z, keeping one half. Without it, the section view of Prepare " + "and the Preview, on alone, as a right click on its toolbar button turns it on " + "and off."}}}, {"origin_planes", {{"type", "boolean"}, {"description", "Design tab: show the origin helper planes (key P)."}}}, {"world_axes", {{"type", "boolean"}, {"description", "Design tab: show the world axis triad (key A)."}}}, {"origin", {{"type", "boolean"}, {"description", "Design tab: the Origin row's eye, the XY, XZ and YZ planes kept up " "where a click picks one; off lets go of a picked plane."}}}, {"bed", {{"type", "boolean"}, {"description", "Design tab: the Bed row's eye, the printer bed drawn."}}}, {"look_at", array_prop({{"type", "number"}}, "[x, y, z] in mm: the point the camera looks at, in the 3D view's " - "world coordinates, as list_objects gives positions; on the Design tab, " + "world coordinates, as object_list gives positions; on the Design tab, " "the Design view's, which the Design commands' world points use (describe_design's " "modeling_origin is the sketch planes' origin). The camera moves " "parallel, keeping its direction and distance. After camera.")}, @@ -717,21 +902,60 @@ void register_view_tools(CommandCatalog& catalog) {"layer_z", {{"type", "number"}, {"minimum", 0}, {"description", "Preview: show layers up to the first whose top is at or above this height (mm), as the slider places a custom G-code."}}}, {"view_type", enum_prop(view_types, "Preview color scheme.")}, {"legend", {{"type", "object"}, {"additionalProperties", {{"type", "boolean"}}}, - {"description", "Preview: show (true) or hide (false) legend rows: feature types by name as get_slice_stats lists them " + {"description", "Preview: show (true) or hide (false) legend rows: feature types by name as plate_slice_stats lists them " "(\"Sparse infill\"), and travel, wipe, retract, unretract, seams, filament_changes, color_changes, " "pauses, custom_gcode, in any case and with _ or a space between words. Hiding a row this " "print lacks does nothing. Applied after view_type."}}}, - {"time_mode", enum_prop({"normal", "silent"}, "Preview: the time estimate the legend and layer times show; silent only when the print has its own.")}}), + {"time_mode", enum_prop({"normal", "silent"}, "Preview: the time estimate the legend and layer times show; silent only when the print has its own.")}, + {"layer_percent", {{"type", "number"}, {"minimum", 0}, {"maximum", 100}, + {"description", "Preview: show the layers up to this share of the layer range, as Go to " + "layer does; the bottom of the shown range stays."}}}, + {"projection", enum_prop({"perspective", "orthographic", "toggle"}, "The 3D camera's projection; toggle " + "switches between the two.")}, + {"layout", enum_prop({"default"}, "default restores the default window layout, as View > Reset Window " + "Layout does.")}, + {"sidebar_collapsed", prop("boolean", "Collapse (true) or expand (false) the sidebar of Prepare and the " + "Preview, as its collapse button does.")}, + {"sidebar_width", {{"type", {"integer", "string"}}, + {"minimum", 1}, + {"description", "The sidebar's width in pixels, as a drag of its edge sets it, or " + "\"default\", its width in the default window layout. A sidebar " + "floating in a window of its own is sized with window_set."}}}, + {"legend_collapsed", prop("boolean", "Preview: fold the legend to its title row (true) or unfold it (false), " + "as its fold button does.")}, + {"gcode_window", prop("boolean", "Preview: show (true) or hide (false) the G-code window, as View > Show " + "G-code Window does.")}, + {"labels", prop("boolean", "Prepare: the object labels, as View > Show Labels sets them.")}, + {"overhangs", prop("boolean", "Prepare: the overhang highlight, as View > Show Overhang sets it.")}, + {"outline", prop("boolean", "The outline around the selected objects, as View > Show Selected Outline sets " + "it.")}, + {"wireframe", prop("boolean", "The objects' wireframe, as the 3D view's own menu sets it.")}, + {"gridlines", prop("boolean", "The plate's gridlines, as View > Show Gridlines sets them.")}, + {"axes", prop("boolean", "The axes on the bed of Prepare and the Preview, as the 3D view's own menu sets " + "them; with tab design, world_axes is the Design view's.")}, + {"navigator", prop("boolean", "The 3D navigator of Prepare and the Preview, as View > Show 3D Navigator " + "sets it.")}}), [](const json& args, ToolContext& ctx) { const bool preview_args = args.contains("layer") || args.contains("layer_range") || args.contains("layer_z") || - args.contains("view_type") || args.contains("legend") || args.contains("time_mode"); - if (arg_string(args, "tab") == "design" && (args.contains("canvas") || preview_args)) + args.contains("layer_percent") || args.contains("view_type") || args.contains("legend") || + args.contains("time_mode") || args.contains("legend_collapsed") || args.contains("gcode_window"); + const bool design_tab = arg_string(args, "tab") == "design"; + if (design_tab && (args.contains("canvas") || preview_args)) throw ToolFailure("canvas and the Preview fields show Prepare or Preview; give them without tab design"); - const bool design_args = args.contains("section") || args.contains("origin_planes") || args.contains("world_axes") || - args.contains("origin") || args.contains("bed") || arg_string(args, "camera") == "sketch_normal"; - if (design_args && arg_string(args, "tab") != "design") - throw ToolFailure("sketch_normal, section, origin_planes, world_axes, origin and bed are the Design tab's: give them " - "with tab design"); + // The section view is the Design view's with tab design, else Prepare's and the Preview's. + const bool design_args = (args.contains("section") && design_tab) || args.contains("origin_planes") || + args.contains("world_axes") || args.contains("origin") || args.contains("bed") || + arg_string(args, "camera") == "sketch_normal"; + if (design_args && !design_tab) + throw ToolFailure("sketch_normal, origin_planes, world_axes, origin and bed are the Design tab's: give them with " + "tab design"); + const bool view_section = args.contains("section") && !design_tab; + if (view_section && (args["section"].contains("z") || args["section"].contains("keep"))) + throw ToolFailure("z and keep are the Design view's cut: give them with tab design. Without it, section is the " + "section view of Prepare and the Preview, which takes on alone"); + if (args.contains("sidebar_width") && args["sidebar_width"].is_string() && args["sidebar_width"] != "default") + throw ToolFailure("sidebar_width is a width in pixels or \"default\""); + const bool sidebar_args = args.contains("sidebar_collapsed") || args.contains("sidebar_width"); if (args.contains("orbit") && args["orbit"].size() != 2) throw ToolFailure("orbit is [yaw, pitch] in degrees"); if (args.contains("look_at") && args["look_at"].size() != 3) @@ -742,6 +966,11 @@ void register_view_tools(CommandCatalog& catalog) Plater& plater = ui_plater(); MainFrame* frame = wxGetApp().mainframe; json done = json::object(); + // The sidebar's state, refused before anything changes where it takes none. + if (sidebar_args && !plater.is_sidebar_enabled()) + throw ToolFailure("The sidebar is off while a G-code file is shown without its settings"); + if (args.contains("sidebar_width") && plater.is_sidebar_floating()) + throw ToolFailure("The sidebar floats in a window of its own, whose size window_set sets"); #ifdef SLIC3R_CAD // The Design tab's panel, which its options set and the reply reads. They, and the cameras the // Design view refuses (point_camera()), are refused here, before the tab or anything else @@ -760,21 +989,25 @@ void register_view_tools(CommandCatalog& catalog) if (arg_string(args, "camera") == "sketch_normal" && !design->mcp_viewport()->is_sketching()) throw ToolFailure("No sketch is open in the Design tab"); } - if (design != nullptr && arg_string(args, "camera") == "fit_bed") - throw ToolFailure("fit_bed is not offered in the Design tab"); - if (design != nullptr && arg_string(args, "camera") == "fit_selection" && !design->mcp_viewport()->selection_box().defined) + // The Design view the camera points once the tab is handled: the one asked for, or the one shown, which + // a call with no tab, canvas or Preview field leaves shown. Its refusals (point_camera()) come here too. + DesignPanel* aimed = design; + if (aimed == nullptr && !args.contains("tab") && !args.contains("canvas") && !preview_args) + aimed = frame->shown_design_panel(); + if (aimed != nullptr && arg_string(args, "camera") == "fit_bed") + throw refused(no_bed_in_design()); + if (aimed != nullptr && arg_string(args, "camera") == "fit_selection" && !aimed->mcp_viewport()->selection_box().defined) throw ToolFailure("Nothing is selected in the Design tab"); #endif if (args.contains("tab")) { - const char* id = tab_id(arg_string(args, "tab")); - if (id == nullptr) - throw ToolFailure("Unknown tab"); + const std::string tab = arg_string(args, "tab"); #ifdef SLIC3R_CAD - if (id == std::string(TAB_ID_DESIGN) && frame->m_design_page == nullptr) + if (tab == "design" && frame->m_design_page == nullptr) throw ToolFailure("The Design tab is off; enable the CAD feature in Preferences and restart"); #endif - frame->select_tab(wxString(id)); - done["tab"] = arg_string(args, "tab"); + if (const std::optional refusal = show_tab(*frame, tab)) + throw refused(*refusal); + done["tab"] = tab; } #ifdef SLIC3R_CAD if (design != nullptr) { @@ -828,10 +1061,8 @@ void register_view_tools(CommandCatalog& catalog) frame->select_tab(wxString(TAB_ID_PREVIEW)); done["canvas"] = view; } - if (preview_args && !args.contains("tab") && !args.contains("canvas")) { - plater.select_view_3D("Preview", false); - frame->select_tab(wxString(TAB_ID_PREVIEW)); - } + if (preview_args && !args.contains("tab") && !args.contains("canvas")) + show_preview(plater, *frame); if (preview_args) { GLCanvas3D* canvas = plater.get_preview_canvas3D(); if (canvas == nullptr) @@ -839,6 +1070,8 @@ void register_view_tools(CommandCatalog& catalog) GCodeViewer& viewer = canvas->get_gcode_viewer(); if (args.contains("layer_z") && (args.contains("layer") || args.contains("layer_range"))) throw ToolFailure("Give layer_z or layer/layer_range, not both"); + if (args.contains("layer_percent") && (args.contains("layer") || args.contains("layer_range") || args.contains("layer_z"))) + throw ToolFailure("Give layer_percent alone, without layer, layer_range or layer_z"); if ((args.contains("legend") || args.contains("time_mode")) && !viewer.has_data()) throw ToolFailure("legend and time_mode need the Preview's toolpaths; slice first"); const std::function show_legend = args.contains("legend") ? legend_change(viewer, args["legend"]) : nullptr; @@ -865,7 +1098,7 @@ void register_view_tools(CommandCatalog& catalog) viewer.set_time_mode(mode); done["time_mode"] = arg_string(args, "time_mode"); } - if (args.contains("layer") || args.contains("layer_range") || args.contains("layer_z")) { + if (args.contains("layer") || args.contains("layer_range") || args.contains("layer_z") || args.contains("layer_percent")) { const Ops::Outcome count = Ops::layer_count(); if (!count) throw refused(count.refusal()); @@ -886,7 +1119,7 @@ void register_view_tools(CommandCatalog& catalog) range.last = r[1].get(); } if (args.contains("layer_z")) { - // The slider's own rule for a height, which set_custom_gcode_at_layer's z follows too. + // The slider's own rule for a height, which plate_set_custom_gcode's z follows too. const double z = args["layer_z"].get(); const int tick = layers->get_tick_from_value(z, true); if (tick < 0 || tick > max) @@ -894,17 +1127,59 @@ void register_view_tools(CommandCatalog& catalog) json(rounded(layers->GetMaxValueD(), 1000.)).dump() + " mm)"); range.last = tick + 1; } - const Ops::Outcome shown = Ops::show_layer_range(range); + const Ops::Outcome shown = args.contains("layer_percent") ? + show_layer_percent(args["layer_percent"].get()) : + Ops::show_layer_range(range); if (!shown) throw refused(shown.refusal()); // The reply echoes the range asked for; z is of the layers the slider shows. done["layers"] = {shown.value().asked_first, shown.value().asked_last, shown.value().count}; done["z"] = {rounded(shown.value().z_first, 1000.), rounded(shown.value().z_last, 1000.)}; } + // After the layers, which can still refuse the call, and after view_type, whose pick unfolds the + // legend. + if (args.contains("legend_collapsed")) { + viewer.fold_legend(args["legend_collapsed"].get()); + done["legend_collapsed"] = viewer.is_legend_folded(); + } + if (args.contains("gcode_window")) { + if (wxGetApp().show_gcode_window() != args["gcode_window"].get()) + wxGetApp().toggle_show_gcode_window(); + done["gcode_window"] = wxGetApp().show_gcode_window(); + } canvas->set_as_dirty(); } + if (args.contains("projection")) { + Camera& camera = plater.get_camera(); + const std::string projection = arg_string(args, "projection"); + if (projection == "toggle") + camera.select_next_type(); + else + camera.set_type(projection == "perspective" ? Camera::EType::Perspective : Camera::EType::Ortho); + done["projection"] = camera.get_type_as_string(); + } + if (args.contains("layout")) { + plater.reset_window_layout(); + done["layout"] = arg_string(args, "layout"); + } + if (view_section) { + show_section_view(plater, args["section"].at("on").get()); + done["section"] = {{"on", section_view_on(plater)}}; + } + for (const ViewSwitch& view_switch : kViewSwitches) + if (args.contains(view_switch.name)) { + view_switch.show(plater, args[view_switch.name].get()); + done[view_switch.name] = view_switch.shown(plater); + } + // After layout, which expands the sidebar at its default width. + if (args.contains("sidebar_collapsed") && plater.is_sidebar_collapsed() != args["sidebar_collapsed"].get()) + plater.collapse_sidebar(args["sidebar_collapsed"].get()); + if (args.contains("sidebar_width")) + plater.set_sidebar_width(args["sidebar_width"].is_string() ? plater.default_sidebar_width() : + args["sidebar_width"].get()); if (GLCanvas3D* canvas = plater.get_current_canvas3D()) canvas->set_as_dirty(); + repaint_shown_canvas(); return done; }); if (camera_args) { @@ -939,7 +1214,8 @@ void register_view_tools(CommandCatalog& catalog) Camera& camera = plater.get_camera(); json done = json::object(); if (args.contains("camera")) { - point_camera(plater, arg_string(args, "camera")); + if (const std::optional refusal = point_camera(plater, arg_string(args, "camera"))) + throw refused(*refusal); done["camera"] = arg_string(args, "camera"); } if (args.contains("look_at")) { @@ -965,6 +1241,17 @@ void register_view_tools(CommandCatalog& catalog) }, std::chrono::seconds(15), "the assemble view to show its objects"); settle(ctx); + // The sidebar as the window lays it out once the change is handled. + if (sidebar_args) + out.update(ctx.observe_ui([&args] { + Plater& plater = ui_plater(); + json read = json::object(); + if (args.contains("sidebar_collapsed")) + read["sidebar_collapsed"] = plater.is_sidebar_collapsed(); + if (args.contains("sidebar_width")) + read["sidebar_width"] = plater.sidebar_width(); + return read; + })); if (camera_args) out.update(ctx.observe_ui([&args] { const GLCanvas3D* canvas = shown_canvas(); @@ -976,7 +1263,117 @@ void register_view_tools(CommandCatalog& catalog) return read; })); return ToolResult::ok(out); - }))); + })); + // The View menu's rows and the Speed Dial's Go to tab and Go to layer, whose value its second phase collects. Titles + // are L("...")-marked here so xgettext extracts them. + struct CameraRow + { + const char* key; + const char* title; + const char* camera; + }; + static const CameraRow camera_rows[] = {{"view_top", L("View: Top"), "top"}, {"view_bottom", L("View: Bottom"), "bottom"}, + {"view_front", L("View: Front"), "front"}, {"view_rear", L("View: Rear"), "rear"}, + {"view_left", L("View: Left"), "left"}, {"view_right", L("View: Right"), "right"}, + {"view_iso", L("View: Isometric"), "iso"}, {"view_default", L("View: Default"), "default"}, + {"view_fit_bed", L("Fit Bed to View"), "fit_bed"}}; + view.tiles = json::array(); + std::vector camera_forms; + for (const CameraRow& row : camera_rows) { + const std::string camera = row.camera; + std::string does = "Turn the camera of the view shown, the Design tab's too, to the " + camera + " view."; + if (camera == "default") + does = "Turn the camera of the view shown to the default view and fit the plate; on the Design tab, its Home view."; + else if (camera == "fit_bed") + does = "Fit the build plate in the 3D view shown; refused on the Design tab, which has no bed to fit."; + view.tiles.push_back(NativeCommands::tile(row.key, row.title, L("View"), "", {{"camera", camera}}, does)); + camera_forms.push_back({{"camera", camera}}); + } + view.tiles.push_back(NativeCommands::tile("view_toggle_perspective", L("Toggle Perspective"), L("View"), "", {{"projection", "toggle"}}, + "Switch the 3D camera between perspective and orthographic.")); + view.tiles.push_back(NativeCommands::tile("reset_window_layout", L("Reset Window Layout"), L("View"), "toolbar_reset", + {{"layout", "default"}}, "Restore the default window layout.")); + view.tiles.push_back(NativeCommands::tile("go_to_tab", L("Go to tab..."), L("Commands"), "", json::object(), + "Switch to a main window tab.", "tab")); + view.tiles.push_back(NativeCommands::tile("go_to_layer", L("Go to layer (percent)"), L("Commands"), "height_range_layer", + json::object(), + "Show the Preview tab at a layer chosen as a percentage of the layer range; an error " + "while the Preview has no layers (slice first).", + "percent", "layer_percent")); + // A person's pick of any of these tiles runs in place (picked_view()): Toggle Perspective and Reset Window Layout + // their rows, the camera tiles, Go to tab and Go to layer the camera, tab and layer functions view_set's UI closure + // runs for a call, so a camera tile turns the Design tab's camera too. An automated call of a camera tile, Go to tab + // or Go to layer is view_set's own function. + catalog.add(NativeCommands::with_row_forms(std::move(view), picked_view, /*person_form_behind_dialogs=*/false, + std::move(camera_forms))); + + // ---- The window commands made from menu rows ---- + struct WindowRow + { + const char* key; + const char* title; + const char* group; + const char* icon; + const char* window; + const char* description; + }; + // Titles are L("...")-marked here so xgettext extracts them. + static const WindowRow window_rows[] = { + {"open_preferences", L("Preferences"), L("Commands"), "cog", "preferences", + "Open the Preferences dialog. window_open with a tab, and a key on it, opens it on that tab with that preference's " + "control scrolled into view and focused (shown on its own tab)."}, + {"open_plugins", L("Open Plugins"), L("Plugins"), "", "plugins", "Open the plugins dialog."}, + {"open_action_replay", L("Action Replay"), L("Commands"), "loop", "action_replay", + "Open the Action Replay window, where a person opens a replay file, reads its steps and replays them. Agents run " + "replays with the replay_run tool instead."}, + {"preset_bundle", L("Open Preset Bundle"), L("Presets"), "menu_edit_preset", "preset_bundle", "Open the preset bundle manager."}, + {"help_keyboard_shortcuts", L("Keyboard Shortcuts"), L("Help"), "", "keyboard_shortcuts", "Show the keyboard shortcuts dialog."}, + {"help_setup_wizard", L("Setup Wizard"), L("Help"), "", "setup_wizard", "Open the setup wizard."}, + {"help_network_test", L("Open Network Test"), L("Help"), "", "network_test", "Open the network test dialog."}, + {"help_troubleshoot", L("Troubleshoot Center"), L("Help"), "", "troubleshoot", "Open the troubleshooting center."}, + {"help_tip_of_the_day", L("Show Tip of the Day"), L("Help"), "info", "tip_of_the_day", "Show a tip of the day."}, + {"help_about", L("About OrcaSlicer"), L("Help"), "OrcaSlicer_gradient_circle", "about", "Show the About dialog."}, + }; + std::vector windows; + json window_tiles = json::array(); + for (const WindowRow& row : window_rows) { + windows.emplace_back(row.window); + window_tiles.push_back(NativeCommands::tile(row.key, row.title, row.group, row.icon, {{"window", row.window}}, row.description)); + } + catalog.add(row_command( + "window_open", L("Open a window"), + "Open one of OrcaSlicer's windows or dialogs for a person, as its menu row does: preferences, the Preferences dialog, " + "with tab, and key on it, on that tab with that preference's control scrolled into view and focused (its controls are " + "named after their preference keys: preferences_get reads them and preferences_set writes those it does not refuse, " + "and widget_set_value {\"target\": {\"name\": key, \"within\": \"Preferences\"}} changes one through the " + "dialog); plugins, the Plugins window; action_replay, the " + "Action Replay window, where a person replays a replay file (agents run one with replay_run); preset_bundle, the preset " + "bundle manager; keyboard_shortcuts; setup_wizard; network_test; troubleshoot, the troubleshooting center; " + "tip_of_the_day; about. A modal one replies blocked_by_dialog.", + object_schema({{"window", enum_prop(windows, "The window.")}, + {"tab", enum_prop(Rows::preferences_tabs(), "preferences: the tab to show.")}, + {"key", prop("string", "preferences, with tab: a preference on that tab, e.g. auto_arrange on behaviour: " + "its control is scrolled into view and focused.")}}, + {"window"}), + std::move(window_tiles), [](const json& args) { + const std::string window = arg_string(args, "window"); + if (window != "preferences" && (args.contains("tab") || args.contains("key"))) + return AppActionRunResult{AppActionRunResult::Level::Error, from_u8("tab and key go with window preferences"), false}; + json preferences = args; + preferences.erase("window"); + return Rows::open_window(window, preferences); + })); + + const std::string saved = "Save a PNG of the main window in the folder Start Recording saves in (the person's Downloads unless " + "they chose another) and show the person a notification naming it; the reply has its path. Agents use " + "the window_screenshot tool, which returns the image."; + NativeCommand save_screenshot = row_command("window_save_screenshot", L("Take Screenshot"), saved, object_schema({}), + json::array({NativeCommands::tile("take_screenshot", L("Take Screenshot"), + L("Commands"), "screenshot", json::object(), saved)}), + [](const json&) { return Rows::take_screenshot(); }); + // A menu row with no argument form: tool_search finds it and tool_call runs it, the tool list does not show it. + save_screenshot.listed = false; + catalog.add(std::move(save_screenshot)); } }}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/ModalTracker.cpp b/src/slic3r/GUI/Mcp/ModalTracker.cpp index 7487d3f30c..3bb72e2d9e 100644 --- a/src/slic3r/GUI/Mcp/ModalTracker.cpp +++ b/src/slic3r/GUI/Mcp/ModalTracker.cpp @@ -79,7 +79,7 @@ using nlohmann::json; namespace { constexpr std::size_t kMaxMessage = 2000; -// Rows of one list a message shows; list_widgets lists them all. +// Rows of one list a message shows; widget_list lists them all. constexpr std::size_t kMaxListRows = 25; std::string lower(std::string s) @@ -400,7 +400,7 @@ private: text += (text.empty() ? "" : "\n") + line; } if (rows.size() > kMaxListRows) - text += "\n- … more rows (list_widgets lists them)"; + text += "\n- … more rows (widget_list lists them)"; return content(w, text); } @@ -1095,7 +1095,7 @@ int ModalTracker::Enter(wxDialog* dialog) // An exception must never escape into ShowModal(). try { // A window hidden from automation (the Python scripts setting) is the person's alone: no rule - // answers it, and leaving it off the stack keeps it out of the dialog tools and get_app_state. + // answers it, and leaving it off the stack keeps it out of the dialog tools and app_state. if (dialog != nullptr && dialog->GetName() == kHiddenFromAutomation) return wxID_NONE; // A description that fails leaves the dialog matched by its title alone, and tracked all the same. @@ -1170,10 +1170,10 @@ int ModalTracker::Enter(wxDialog* dialog) } // A wx dialog's buttons do its work in their handlers (Transfer, Discard, Clone's Fill), which // a returned id would skip. So it opens, and the button is pressed once its modal loop runs, as - // answer_dialog does; the rule counts as used once that pressed the button or ended the + // dialog_answer does; the rule counts as used once that pressed the button or ended the // dialog. A button disabled by then leaves the dialog open. Queued on the dialog, the press goes // with it if it is destroyed first; a modal opened above it before then leaves it to - // answer_dialog. The tracker lives as long as the app. + // dialog_answer. The tracker lives as long as the app. if (wx_rule) dialog->CallAfter([this, dialog, answer, title, rule = *wx_rule] { const auto& [layer, pattern, button] = rule; diff --git a/src/slic3r/GUI/Mcp/ModalTracker.hpp b/src/slic3r/GUI/Mcp/ModalTracker.hpp index e0d367d120..a0c22a0302 100644 --- a/src/slic3r/GUI/Mcp/ModalTracker.hpp +++ b/src/slic3r/GUI/Mcp/ModalTracker.hpp @@ -116,7 +116,7 @@ private: // {title, message, class, native, buttons:[{id,label,enabled?}], web?} for a dialog. A wx dialog's // message reads it as a person does: its text, and its controls with their values and states, row by // row (DialogReader in the .cpp); `enabled` is false for a disabled button. `web` is true for a dialog -// with a web view, whose page holds its controls (list_widgets with target dialog lists them). `text`, when +// with a web view, whose page holds its controls (widget_list with target dialog lists them). `text`, when // given, receives the dialog's own text: its static text and html, one per line, without its // controls, which auto-answer rules also search (rule_matches()). UI thread only. nlohmann::json describe_dialog(wxDialog* dialog, std::string* text = nullptr); diff --git a/src/slic3r/GUI/Mcp/RecordingSettings.hpp b/src/slic3r/GUI/Mcp/RecordingSettings.hpp index 70052e3970..a7ed7b132e 100644 --- a/src/slic3r/GUI/Mcp/RecordingSettings.hpp +++ b/src/slic3r/GUI/Mcp/RecordingSettings.hpp @@ -17,11 +17,11 @@ namespace Slic3r { namespace GUI { namespace Mcp { // remembers them; the command's parameter overrides them for one recording. struct RecordingSettings { - int quality = 80; // the frames' JPEG quality, 30-95, as start_recording's - bool captions = false; // the overlays, as start_recording's + int quality = 80; // the frames' JPEG quality, 30-95, as recording_start's + bool captions = false; // the overlays, as recording_start's bool pointer = false; bool encode = false; - std::string codec = "h265"; // and the rest as encode_recording takes them + std::string codec = "h265"; // and the rest as recording_encode takes them int crf = 28; std::string speed = "medium"; std::string profile = "main"; @@ -60,13 +60,13 @@ std::string matching_encode_preset(const RecordingSettings& settings); RecordingSettings load_recording_settings(const AppConfig& config); void save_recording_settings(AppConfig& config, const RecordingSettings& settings); -// Applies start_recording's encode arguments, an object with any of encode, encode_preset, codec, crf, speed, +// Applies recording_start's encode arguments, an object with any of encode, encode_preset, codec, crf, speed, // profile and keep_raw_video_file, other keys left alone: encode_preset's fields first, then the fields it // names. A codec named without a profile takes the codec's default profile when the one it had does not fit. // Returns what is wrong, "" when nothing; `settings` is then unchanged. std::string apply_recording_overrides(RecordingSettings& settings, const nlohmann::json& overrides); -// encode_recording's arguments for the recording at `path` (UTF-8). +// recording_encode's arguments for the recording at `path` (UTF-8). nlohmann::json encode_arguments(const RecordingSettings& settings, const std::string& path); }}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/UiInspector.cpp b/src/slic3r/GUI/Mcp/UiInspector.cpp index d00ac3a53f..ed97bf1147 100644 --- a/src/slic3r/GUI/Mcp/UiInspector.cpp +++ b/src/slic3r/GUI/Mcp/UiInspector.cpp @@ -644,9 +644,9 @@ std::string no_modal_dialog(ModalTracker& modals) open += (open.empty() ? "\"" : ", \"") + label_of(tlw) + "\""; if (open.empty()) return "No modal dialog is open"; - return "No modal dialog is open. Open without blocking the app: " + open + ". list_windows lists such a window with its ref: " - "screenshot captures it with the ref as target, list_widgets reads it alone with the ref as target, and the window's own " - "close button or press_keys Escape with its ref as target closes it"; + return "No modal dialog is open. Open without blocking the app: " + open + ". window_list lists such a window with its ref: " + "window_screenshot captures it with the ref as target, widget_list reads it alone with the ref as target, and the window's own " + "close button or keyboard_press Escape with its ref as target closes it"; } // Stable English gizmo names for refs and locators: the names Orca uses for the gizmos it names, @@ -685,7 +685,7 @@ GLGizmosManager::EType gizmo_from_name(const std::string& name) return GLGizmosManager::Undefined; } -// The mouse tools' modifiers, named as in press_keys's chords so both mean the same keys: ctrl (or cmd) is +// The mouse tools' modifiers, named as in keyboard_press's chords so both mean the same keys: ctrl (or cmd) is // the shortcut modifier, Command on macOS, and rawctrl is the macOS Control key. int parse_modifiers(const std::vector& mods) { @@ -1042,7 +1042,7 @@ wxPoint target_pixel(GLCanvas3D& canvas, const json& target, const std::string& // The assemble view shows only the objects selected when it opened, and clears `visible` on the rest. if (shown == nullptr || shown->mesh_raycaster == nullptr || !shown->visible || (!shown->is_active && !own(shown))) throw ToolFailure(what + " is not shown in the " + std::string(canvas_name(&canvas)) + - " view (list_objects lists objects and parts; the assemble view shows the objects selected when it opened)"); + " view (object_list lists objects and parts; the assemble view shows the objects selected when it opened)"); const Transform3d world = shown->world_matrix(); const AABBMesh& mesh = shown->mesh_raycaster->get_aabb_mesh(); @@ -1072,7 +1072,7 @@ wxPoint target_pixel(GLCanvas3D& canvas, const json& target, const std::string& const CanvasView view = canvas_view(canvas); const auto projected = project_point(view, point); if (!projected) - throw ToolFailure("The point of " + what + " is off screen; turn or zoom the camera with set_view"); + throw ToolFailure("The point of " + what + " is off screen; turn or zoom the camera with view_set"); // Events carry whole logical pixels: the click goes through this one, not the projected point. const wxPoint pixel(int(std::lround(projected->x())), int(std::lround(projected->y()))); @@ -1098,7 +1098,7 @@ wxPoint target_pixel(GLCanvas3D& canvas, const json& target, const std::string& const std::string why = check_surface(point, pixel_ray(view, Vec2d(pixel.x, pixel.y)), meshes, clip ? &*clip : nullptr, beds, limit); if (!why.empty()) throw ToolFailure("A click at the point of " + what + " would miss it: " + why + - ". Turn the camera with set_view, or pass check:\"point\" for a point off the surface"); + ". Turn the camera with view_set, or pass check:\"point\" for a point off the surface"); } else if (check != "point") { throw ToolFailure("check is surface or point"); } @@ -1404,7 +1404,7 @@ std::optional cell_text(wxDataViewModel& model, const wxDataViewIte return std::nullopt; } -// What an object list row stands for, by the indices list_objects uses. +// What an object list row stands for, by the indices object_list uses. std::string object_row_note(ObjectDataViewModel& model, const wxDataViewItem& item) { int plate = -1; @@ -1469,8 +1469,15 @@ void data_view_rows(wxDataViewCtrl& ctrl, std::vector& out, std::size_t } if (!labelled) row.path.emplace_back(); - if (objects != nullptr) + if (objects != nullptr) { row.note = object_row_note(*objects, item); + // A plate's, an object's, a part's or a height range's settings of its own show as the icon that + // resets them. + const auto* node = static_cast(item.GetID()); + const bool settable = (objects->GetItemType(item) & (itPlate | itObject | itVolume | itLayer)) != 0; + if (node != nullptr && settable && node->IsActionEnabled()) + row.note += ", has settings"; + } row.selected = ctrl.IsSelected(item); row.shown = shown; row.depth = depth; @@ -1687,7 +1694,7 @@ json click_data_view_row(wxDataViewCtrl& ctrl, const ListRow& row, const std::st // the middle of that rect is a click outside the list, which its owner ignores. const wxRect shown = cell.IsEmpty() ? wxRect() : cell.Intersect(ctrl.GetClientRect()); if (shown.IsEmpty()) - throw ToolFailure("\"" + row.path.back() + "\" can't be scrolled into the list's view; make the window taller with set_window size"); + throw ToolFailure("\"" + row.path.back() + "\" can't be scrolled into the list's view; make the window taller with window_set size"); // The pointer stays on the cell for the click: the object list acts on the cell under it (Printable // toggles printability, Editing resets the row's settings). wxMouseState pointer; @@ -1930,7 +1937,7 @@ std::vector> find_rows(const std::vector(&list) != nullptr) - throw ToolFailure("Table cells are read-only here; edit object settings with set_settings {scope: \"object\"}"); + throw ToolFailure("Table cells are read-only here; edit object settings with settings_set {target: \"object\"}"); const std::string text = value.is_string() ? lower(value.get()) : value.dump(); if (!value.is_boolean() && text != "true" && text != "false" && text != "1" && text != "0") throw ToolFailure("A row takes true or false, for its checkbox"); @@ -2000,7 +2007,7 @@ json input_row(wxWindow& list, const ListRow& row, const std::string& column, co } return {{"row", joined(row.path, ">")}, {"checked", checks->IsChecked(n)}}; } - throw ToolFailure("This row has no checkbox; use click"); + throw ToolFailure("This row has no checkbox; use widget_click"); } // ---- snapshot --------------------------------------------------------------------------------- @@ -2334,7 +2341,7 @@ void UiInspector::add_imgui_items(GLCanvas3D& canvas, int depth, std::vector(); if (find_menu_path(path, id) == nullptr) - throw ToolFailure("No menu item " + path + " (list_widgets lists them)"); + throw ToolFailure("No menu item " + path + " (widget_list lists them)"); t.kind = UiTarget::Kind::MenuItem; t.window = wxGetApp().mainframe; t.menu_id = id; @@ -2783,14 +2790,14 @@ UiTarget UiInspector::resolve(const json& target) names.push_back(gizmo_name(g)); throw ToolFailure("No gizmo " + t.name, {{"gizmos", names}}); } - t.name = gizmo_name(t.gizmo); // replies name it as get_app_state does + t.name = gizmo_name(t.gizmo); // replies name it as app_state does return t; } // ImGui item: search the named canvas, or every canvas when none was named. const auto matches = match_imgui(target); const int index = target.value("index", -1); if (matches.empty()) - throw ToolFailure("No ImGui item matches " + target.dump() + " in the last frame; show its panel first (list_widgets lists them)"); + throw ToolFailure("No ImGui item matches " + target.dump() + " in the last frame; show its panel first (widget_list lists them)"); if (matches.size() > 1 && index < 0) throw ToolFailure(std::to_string(matches.size()) + " ImGui items match " + target.dump() + "; add \"index\" (0-based) or use a ref"); if (index >= int(matches.size())) @@ -2826,8 +2833,8 @@ UiTarget UiInspector::resolve(const json& target) // Global/Objects switch is on Objects. if (any.empty()) throw ToolFailure("No shown list has any rows; the Prepare sidebar's object list shows when its Global/Objects " - "switch, the SwitchButton list_widgets labels \"Process\", is on Objects (click it)"); - throw ToolFailure("No shown list has a row " + target["row"].dump() + "; call list_widgets", {{"rows", similar.empty() ? any : similar}}); + "switch, the SwitchButton widget_list labels \"Process\", is on Objects (click it)"); + throw ToolFailure("No shown list has a row " + target["row"].dump() + "; call widget_list", {{"rows", similar.empty() ? any : similar}}); } if (matches.size() > 1 && index < 0) throw ToolFailure(std::to_string(matches.size()) + " rows match " + target.dump() + "; add \"index\" (0-based) or use a ref"); @@ -2844,7 +2851,7 @@ UiTarget UiInspector::resolve(const json& target) if (target.contains("tab")) { const auto matches = match_tabs(target); if (matches.empty()) - throw ToolFailure("No tab " + target.dump() + "; call list_widgets"); + throw ToolFailure("No tab " + target.dump() + "; call widget_list"); if (matches.size() > 1 && index < 0) throw ToolFailure(std::to_string(matches.size()) + " tabs match " + target.dump() + "; add \"index\" (0-based) or use a ref"); if (index >= int(matches.size())) @@ -2862,7 +2869,7 @@ UiTarget UiInspector::resolve(const json& target) throw ToolFailure("A locator needs option, label, name or class (or menu, tab, row, gltoolbar, gizmo, imgui, imgui_name)"); const std::vector matches = match_windows(target); if (matches.empty()) - throw ToolFailure("Nothing matches " + target.dump() + "; call list_widgets"); + throw ToolFailure("Nothing matches " + target.dump() + "; call widget_list"); if (matches.size() > 1 && index < 0) throw ToolFailure(std::to_string(matches.size()) + " elements match " + target.dump() + "; add \"index\" (0-based) or use a ref"); if (index >= int(matches.size())) @@ -3060,7 +3067,7 @@ void UiInspector::reveal(UiTarget& target) } if (item.clipped) throw ToolFailure("\"" + target.imgui_label + "\" is outside the visible part of its panel, which does not scroll to it; " - "make the window taller with set_window size"); + "make the window taller with window_set size"); target.x = item.x, target.y = item.y, target.w = item.w, target.h = item.h; } @@ -3071,7 +3078,7 @@ ImGuiWrapper::RecordedItem UiInspector::imgui_record(const UiTarget& t) const const auto items = wxGetApp().imgui()->recorded_items(t.canvas); if (const auto at = imgui_find_item(items, t.imgui_id, t.imgui_name, t.imgui_window, t.imgui_twins)) return items[*at]; - throw ToolFailure("\"" + t.imgui_label + "\" is no longer shown; call list_widgets again"); + throw ToolFailure("\"" + t.imgui_label + "\" is no longer shown; call widget_list again"); } GLCanvas3D* UiInspector::canvas_of(const UiTarget* target) const @@ -3107,7 +3114,7 @@ json UiInspector::click(const UiTarget& t, const ClickOptions& o) case UiTarget::Kind::MenuItem: { wxMenuItem* item = find_menu_item(t.menu_id, nullptr); if (item == nullptr || item->GetMenu() == nullptr) - throw ToolFailure("The menu item is gone; call list_widgets again"); + throw ToolFailure("The menu item is gone; call widget_list again"); return run_menu_item(*item, *wxGetApp().mainframe, t.menu_path); } case UiTarget::Kind::ToolbarItem: { @@ -3161,7 +3168,7 @@ json UiInspector::click(const UiTarget& t, const ClickOptions& o) case GLGizmosManager::ToolbarClick::Nothing: break; } if (type == GLGizmosManager::Svg) - throw ToolFailure("The SVG gizmo opens on a selected SVG part: select one, or add one with run_action add_primitive_svg"); + throw ToolFailure("The SVG gizmo opens on a selected SVG part: select one, or add one with object_add_svg"); throw ToolFailure("The " + t.name + " gizmo did not open (select an object first?)"); } case UiTarget::Kind::ImGuiItem: { @@ -3170,7 +3177,7 @@ json UiInspector::click(const UiTarget& t, const ClickOptions& o) const wxPoint pos = imgui_to_canvas(*shown.canvas, shown.x + shown.w / 2.f, shown.y + shown.h / 2.f); if (const std::string cover = covered_by(*shown.canvas, pos, shown.imgui_window); !cover.empty()) throw ToolFailure("\"" + shown.imgui_label + "\" is under " + cover + - ", which would take the click; close it, or enlarge the window with set_window size"); + ", which would take the click; close it, or enlarge the window with window_set size"); canvas_click(*shown.canvas, pos, o); return {{"clicked", shown.imgui_label}, {"at", {pos.x, pos.y}}}; } @@ -3178,7 +3185,7 @@ json UiInspector::click(const UiTarget& t, const ClickOptions& o) wxWindow* list = t.window.get(); const std::optional row = list != nullptr ? find_row(*list, t.row_path, t.row_twin) : std::nullopt; if (!row) - throw ToolFailure("The row is gone; call list_widgets again"); + throw ToolFailure("The row is gone; call widget_list again"); return click_row(*list, *row, t.column, o); } case UiTarget::Kind::PlateIcon: { @@ -3186,12 +3193,12 @@ json UiInspector::click(const UiTarget& t, const ClickOptions& o) // no plate clicks. GLCanvas3D& canvas = *t.canvas; if (!is_live_canvas(t.canvas) || !canvas.get_wxglcanvas()->IsShownOnScreen()) - throw ToolFailure("Plate icons are on the Prepare view; set_view {\"tab\": \"prepare\"} first"); + throw ToolFailure("Plate icons are on the Prepare view; view_set {\"tab\": \"prepare\"} first"); if (o.button == "middle" || o.double_click || o.at_point) throw ToolFailure("A plate icon takes a single left or right click"); if (canvas.is_layers_editing_enabled()) throw ToolFailure("Plate icons take no clicks while variable layer height is being edited; close it with " - "click {\"target\": {\"gltoolbar\": \"layersediting\"}} first"); + "widget_click {\"target\": {\"gltoolbar\": \"layersediting\"}} first"); if (const auto open = canvas.get_gizmos_manager().get_current_type(); open != GLGizmosManager::Undefined) throw ToolFailure("Close the " + gizmo_name(open) + " gizmo first: plate icons take no clicks while it is open"); Plater& plater = *wxGetApp().plater(); @@ -3229,7 +3236,7 @@ json UiInspector::click(const UiTarget& t, const ClickOptions& o) out["started"] = idle && !worker.is_idle(); if (!out["started"].get() && arrange_stuck) out["note"] = "The arrange icon does nothing after an arrange was cancelled or failed, until another arrange " - "finishes; arrange with the arrange tool or run_action obj_arrange"; + "finishes; arrange with object_arrange"; } return out; } @@ -3238,20 +3245,20 @@ json UiInspector::click(const UiTarget& t, const ClickOptions& o) wxWindow* w = t.window.get(); if (w == nullptr) - throw ToolFailure("The element is gone; call list_widgets again"); + throw ToolFailure("The element is gone; call widget_list again"); if (!w->IsEnabled()) throw ToolFailure("The element is disabled"); scroll_into_view(w); if (t.page >= 0) { auto* book = dynamic_cast(w); if (book == nullptr || t.page >= int(book->GetPageCount())) - throw ToolFailure("The tab is gone; call list_widgets again"); + throw ToolFailure("The tab is gone; call widget_list again"); book->SetSelection(size_t(t.page)); // sends the page-changing and page-changed events return {{"clicked", t.name}, {"page", t.page}}; } if (o.at_point && dynamic_cast(w) == nullptr) { if (is_native_control(w)) - throw ToolFailure("x/y clicks a point of a custom-drawn widget; this is a native control, so use click without x/y"); + throw ToolFailure("x/y clicks a point of a custom-drawn widget; this is a native control, so use widget_click without x/y"); click_window(w, o); return {{"clicked", label_of(w)}, {"at", {o.x, o.y}}}; } @@ -3306,11 +3313,11 @@ json UiInspector::input(const UiTarget& t, const json& value, bool submit) wxWindow* list = t.window.get(); const std::optional row = list != nullptr ? find_row(*list, t.row_path, t.row_twin) : std::nullopt; if (!row) - throw ToolFailure("The row is gone; call list_widgets again"); + throw ToolFailure("The row is gone; call widget_list again"); return input_row(*list, *row, t.column, value); } if (t.kind != UiTarget::Kind::Window || t.window.get() == nullptr) - throw ToolFailure("set_widget_value works on controls, list rows and ImGui fields"); + throw ToolFailure("widget_set_value works on controls, list rows and ImGui fields"); wxWindow* w = t.window.get(); if (!w->IsEnabled()) throw ToolFailure("The control is disabled"); @@ -3322,7 +3329,7 @@ json UiInspector::input(const UiTarget& t, const json& value, bool submit) // An option, as a radio button, is unselected by selecting another; a click would only select it again. if (!want && checked_of(w) == 1 && (selector_option(w).selector != nullptr || dynamic_cast(w) != nullptr || dynamic_cast(w) != nullptr)) - throw ToolFailure("An option is unselected by selecting another one; set_widget_value true on that one"); + throw ToolFailure("An option is unselected by selecting another one; widget_set_value true on that one"); if ((checked_of(w) == 1) != want) click(t, ClickOptions{}); return {{"checked", checked_of(w) == 1}}; @@ -3377,7 +3384,7 @@ json UiInspector::input(const UiTarget& t, const json& value, bool submit) } return {{"value", into_u8(te->GetValue())}}; } - throw ToolFailure("This element (" + short_class(w) + ") takes no input; use click"); + throw ToolFailure("This element (" + short_class(w) + ") takes no input; use widget_click"); } // Sets an ImGui control the way a person does, chosen by its kind, and reads the value back. @@ -3478,7 +3485,7 @@ json UiInspector::imgui_input(UiTarget t, const json& value, bool submit) throw ToolFailure("\"" + t.imgui_label + "\" is a slider that takes no typing and has no number field beside it; drag it with mouse_gesture"); } if (field_kind != "input" && field_kind != "multiline" && field_kind != "drag" && field_kind != "slider") - throw ToolFailure("\"" + t.imgui_label + "\" is a " + field_kind + ", which takes no typed value; use click"); + throw ToolFailure("\"" + t.imgui_label + "\" is a " + field_kind + ", which takes no typed value; use widget_click"); // A Ctrl+click turns a slider or drag into a text field; an input field takes a plain click. ClickOptions focus; @@ -3659,7 +3666,7 @@ json UiInspector::mouse(GLCanvas3D& canvas, const json& g, const std::string& ow if (const std::string cover = covered_by(canvas, from); !cover.empty()) throw ToolFailure("The model point at pixel (" + std::to_string(from.x) + ", " + std::to_string(from.y) + ") is under " + cover + ", which would take the " + (action == "move" ? "pointer" : action == "wheel" ? "wheel" : "click") + - "; turn or zoom the camera with set_view, or close it"); + "; turn or zoom the camera with view_set, or close it"); // A painting gizmo takes a press only on the object it paints. One that misses falls through to the // canvas, which turns or pans the camera as the user's mouse settings say, and the stroke paints nothing. if ((action == "down" || action == "drag") && !design && dynamic_cast(canvas.get_gizmos_manager().get_current()) != nullptr && @@ -3669,8 +3676,8 @@ json UiInspector::mouse(GLCanvas3D& canvas, const json& g, const std::string& ow if (const auto hit = first_hit_on_stroke(canvas, from, stops)) throw ToolFailure(missed + "The stroke first reaches the object at pixel (" + std::to_string(hit->x) + ", " + std::to_string(hit->y) + "): start it there"); - throw ToolFailure(missed + "Start the stroke on the object (at a model point, or a pixel inside its list_objects {\"screen\": true} " - "box that shows the object), and turn the camera with set_view camera or orbit"); + throw ToolFailure(missed + "Start the stroke on the object (at a model point, or a pixel inside its object_list {\"screen\": true} " + "box that shows the object), and turn the camera with view_set camera or orbit"); } json out{{"action", action}, {"canvas", canvas_name(&canvas)}, {"pixels", pixels}}; diff --git a/src/slic3r/GUI/Mcp/UiInspector.hpp b/src/slic3r/GUI/Mcp/UiInspector.hpp index 9b1e85570d..36d162d164 100644 --- a/src/slic3r/GUI/Mcp/UiInspector.hpp +++ b/src/slic3r/GUI/Mcp/UiInspector.hpp @@ -81,7 +81,7 @@ struct UiTarget nlohmann::json locator; }; -// A row of a list, tree, table or drop-down list, as list_widgets lists it and row locators find it. +// A row of a list, tree, table or drop-down list, as widget_list lists it and row locators find it. struct ListRow { std::vector path; // labels from the top: the row's own label last @@ -123,7 +123,7 @@ struct ClickOptions int x = 0, y = 0; }; -// Lists and drives the GUI for list_widgets and the input tools: wx widgets of every shown top-level window, the +// Lists and drives the GUI for widget_list and the input tools: wx widgets of every shown top-level window, the // menus, the 3D canvases' toolbar items, gizmos and ImGui items. Input is synthesized as wx // events delivered to the widgets' own handlers (no OS input, focus or pointer needed), with // semantic activation for controls whose handlers listen to command events. UI thread only. @@ -139,14 +139,14 @@ public: // {tree, nodes, omitted} nlohmann::json snapshot(const SnapshotOptions& options); - // The open windows as list_windows lists them, in list_widgets's order: the main window, the windows + // The open windows as window_list lists them, in widget_list's order: the main window, the windows // that don't block, then the modal dialogs in the order they opened, so the topmost is last. Each - // has the ref list_widgets gives it. A native dialog has no ref, and a window hidden from automation + // has the ref widget_list gives it. A native dialog has no ref, and a window hidden from automation // is listed by its title and kind alone, so an agent knows it is there and out of reach. nlohmann::json windows(); // One window of windows(), `modal` saying whether it blocks the app: its title, kind and modal, then // hidden or native for a window no tool reaches, else a new ref, web, x and y where the platform - // knows them, width, height, state and resizable. set_window replies with the same fields. + // knows them, width, height, state and resizable. window_set replies with the same fields. nlohmann::json window_entry(wxTopLevelWindow& window, bool modal); // The web views a snapshot with `options` walks whose pages it lists: shown ones under its // roots, and while a modal dialog is open only those in the topmost one. `behind` gets the @@ -303,10 +303,10 @@ std::string no_modal_dialog(ModalTracker& modals); // What a locator's `within` names `w`'s window by: its top-level window's title, empty for the main // window, whose title follows the project name. std::string within_of(wxWindow* w); -// The shown popups that opened from `top` or from its widgets, which list_widgets lists after it. +// The shown popups that opened from `top` or from its widgets, which widget_list lists after it. std::vector popups_of(wxWindow* top); -// How an agent reads a widget. list_widgets and a modal dialog's description (describe_dialog()) both +// How an agent reads a widget. widget_list and a modal dialog's description (describe_dialog()) both // read controls through these, so they say the same about each one. UI thread only. // The role a window plays for an agent: button, checkbox, toggle, radio, combo, choice, spin, text, @@ -353,7 +353,7 @@ struct SelectorChoices }; std::optional selector_choices(wxWindow* w); -// Rows of the lists list_widgets reads: wxDataViewCtrl (every row, collapsed branches too), wxListBox and +// Rows of the lists widget_list reads: wxDataViewCtrl (every row, collapsed branches too), wxListBox and // wxCheckListBox, wxListCtrl, Orca's DropDown, wxGrid (read-only) and the Design tab's DesignRowList. // Empty for other windows. With a `limit`, only shown rows are read (a tree's collapsed branches are // skipped), and at most `limit` of them: what a summary of the list costs, whatever its size. @@ -378,7 +378,7 @@ nlohmann::json input_row(wxWindow& list, const ListRow& row, const std::string& std::vector live_canvases(); // The Design tab's view once the tab is built, else null. GLCanvas3D* design_canvas(); -// live_canvases() and the Design view: the canvases list_widgets lists and the input tools find items in and send +// live_canvases() and the Design view: the canvases widget_list lists and the input tools find items in and send // input to. The gizmo state and the idle checks read live_canvases(), since the Design view has no // gizmos. std::vector ui_canvases(); @@ -435,7 +435,7 @@ std::vector surface_meshes(const std::vector& // A GL toolbar's items, with the visibility and enabled state the canvas's idle handler gives them // (GLToolbar::update_items_state()) brought up to date first: until that handler runs they keep the -// state of the last idle event, so an item a `select_objects` just enabled would still read disabled. +// state of the last idle event, so an item an `object_select` just enabled would still read disabled. // `changed` tells whether a state changed, which the canvas has yet to draw. const std::vector& toolbar_items(GLToolbar& toolbar, bool* changed = nullptr); diff --git a/src/slic3r/GUI/Mcp/UiInvoker.cpp b/src/slic3r/GUI/Mcp/UiInvoker.cpp index fe51baec74..3e8dc83e6e 100644 --- a/src/slic3r/GUI/Mcp/UiInvoker.cpp +++ b/src/slic3r/GUI/Mcp/UiInvoker.cpp @@ -98,7 +98,7 @@ nlohmann::json UiInvoker::run(GuardClass guard, const std::string& tool, const s else if (shared->generation && shared->generation() != generation) error = "The UI was recreated (language change) before the call ran; it was not run, so it is safe to retry"; else if (guard == GuardClass::Mutate && g.modal) { - error = "A modal dialog is open; answer it first (list_widgets, answer_dialog)"; + error = "A modal dialog is open; answer it first (widget_list, dialog_answer)"; details = {{"dialogs", g.dialogs}}; } else if (guard == GuardClass::Mutate && !shared->running_tools.empty()) error = "Busy: " + shared->running_tools.front() + " is still running; only inspection and dialog tools can run now"; @@ -139,7 +139,7 @@ nlohmann::json UiInvoker::run(GuardClass guard, const std::string& tool, const s throw ToolFailure("OrcaSlicer is shutting down"); if (nlohmann::json dialogs = open_dialogs(); topmost_dialog_is_native(dialogs)) throw ToolFailure("A native dialog holds the UI thread until a person answers it, so the call was not run; register " - "auto_answer_dialogs before the step that opens one", + "dialog_auto_answer before the step that opens one", {{"dialogs", std::move(dialogs)}}); throw ToolFailure("The UI thread is busy and did not run the call; it was not run, so it is safe to retry"); } @@ -190,7 +190,7 @@ void UiInvoker::require_mutate() const if (m_shared->guards_on_ui) { const GuardState g = m_shared->guards_on_ui(); if (g.modal) - throw ToolFailure("A modal dialog is open; answer it first (list_widgets, answer_dialog)", {{"dialogs", g.dialogs}}); + throw ToolFailure("A modal dialog is open; answer it first (widget_list, dialog_answer)", {{"dialogs", g.dialogs}}); } if (m_shared->running_tools.size() > 1) throw ToolFailure("Busy: " + m_shared->running_tools.front() + diff --git a/src/slic3r/GUI/Mcp/UiRefs.hpp b/src/slic3r/GUI/Mcp/UiRefs.hpp index 4044ea09ba..b3cb03adc7 100644 --- a/src/slic3r/GUI/Mcp/UiRefs.hpp +++ b/src/slic3r/GUI/Mcp/UiRefs.hpp @@ -24,7 +24,7 @@ std::string imgui_label_name(const std::string& label); // windows ("Move##gizmo/##body_1A2B3C4D") count as the panel. std::string imgui_window_label(const std::string& window); -// One line of list_widgets' reply. +// One line of widget_list's reply. struct UiNode { std::string ref; // "w12", "m3", "t5", "z2", "g7" @@ -93,7 +93,7 @@ std::string plate_icon_name(int action); // {plate, action} of a bed picking id. std::pair plate_icon_of(int picking_id); -// The refs list_widgets hands out. Ids are never reused, so two clients can't confuse each other's +// The refs widget_list hands out. Ids are never reused, so two clients can't confuse each other's // refs; each stores what it points at and how to tell whether that still exists, plus the UI // generation it was taken in (a rebuilt main window invalidates every ref). template class RefTable @@ -118,11 +118,11 @@ public: { auto it = m_entries.find(ref); if (it == m_entries.end()) { - err = "Unknown ref " + ref + "; call list_widgets again"; + err = "Unknown ref " + ref + "; call widget_list again"; return nullptr; } if (it->second.generation != generation || (it->second.alive && !it->second.alive())) { - err = "Stale ref " + ref + ": the element is gone or the window was rebuilt; call list_widgets again"; + err = "Stale ref " + ref + ": the element is gone or the window was rebuilt; call widget_list again"; return nullptr; } return &it->second.payload; diff --git a/src/slic3r/GUI/Mcp/VideoEncode.hpp b/src/slic3r/GUI/Mcp/VideoEncode.hpp index 1df2552875..54c6c8c58e 100644 --- a/src/slic3r/GUI/Mcp/VideoEncode.hpp +++ b/src/slic3r/GUI/Mcp/VideoEncode.hpp @@ -15,7 +15,7 @@ namespace Slic3r { namespace GUI { namespace Mcp { -// encode_recording's half: finding the system ffmpeg, its command line, running it, and which files +// recording_encode's half: finding the system ffmpeg, its command line, running it, and which files // recordings and encodes are using. The bundled FFmpeg only decodes, so the encode runs the system one. // wx-free. diff --git a/src/slic3r/GUI/Mcp/VideoOverlay.cpp b/src/slic3r/GUI/Mcp/VideoOverlay.cpp index eb063e1338..fa24bb1c30 100644 --- a/src/slic3r/GUI/Mcp/VideoOverlay.cpp +++ b/src/slic3r/GUI/Mcp/VideoOverlay.cpp @@ -566,7 +566,7 @@ void scalars(const json& value, std::vector& out) scalars(v, out); } -// The values of sensitive keys anywhere in `args` (set_settings' values, a per-variant entry's value). +// The values of sensitive keys anywhere in `args` (settings_set's values, a per-variant entry's value). void sensitive_values(const json& args, std::vector& out) { if (args.is_object()) { @@ -589,15 +589,15 @@ std::vector hidden_values(const std::string& tool, const json& args sensitive_values(args, out); if (!args.is_object()) return out; - if (tool == "set_widget_value") { + if (tool == "widget_set_value") { const json& target = args.contains("target") ? args["target"] : json(); const std::string option = target.is_object() ? str(target, "option") : std::string(); if ((option.empty() || is_sensitive_key(option)) && args.contains("value")) scalars(args["value"], out); } - if (tool == "press_keys" && args.contains("text")) + if (tool == "keyboard_press" && args.contains("text")) scalars(args["text"], out); - if (tool == "run_javascript") + if (tool == "webview_run_javascript") scalars(args, out); return out; } @@ -640,7 +640,7 @@ std::string caption_detail(const std::string& tool, const json& args) { if (!args.is_object()) return {}; - if (tool == "set_widget_value") { + if (tool == "widget_set_value") { std::string out = target_text(args.value("target", json())); // Only a setting field's value: a field found by its label, or a ref not yet resolved, may be a // password box. @@ -650,23 +650,23 @@ std::string caption_detail(const std::string& tool, const json& args) out += " = " + scalar_text(args["value"]); return out; } - if (tool == "press_keys") { + if (tool == "keyboard_press") { // Typed text shows as keys in the input caption, masked where it goes into a password field. const std::string keys = str(args, "keys"); const std::string target = target_text(args.value("target", json())); return keys.empty() ? target : (target.empty() ? keys : keys + " - " + target); } - if (tool == "click" || tool == "mouse_gesture" || tool == "answer_dialog") { + if (tool == "widget_click" || tool == "mouse_gesture" || tool == "dialog_answer") { std::string out = target_text(args.value("target", json())); if (tool == "mouse_gesture") out = str(args, "action"); - if (tool == "answer_dialog") + if (tool == "dialog_answer") out = str(args, "button"); if (const std::string item = str(args, "popup_item"); !item.empty()) out += (out.empty() ? "" : " > ") + path_text(item); return out; } - if (tool == "run_javascript") + if (tool == "webview_run_javascript") return {}; // the code may carry anything if (args.contains("values") && args["values"].is_object()) { std::vector pairs; diff --git a/src/slic3r/GUI/Mcp/WebPages.hpp b/src/slic3r/GUI/Mcp/WebPages.hpp index f3127bec12..89b384db99 100644 --- a/src/slic3r/GUI/Mcp/WebPages.hpp +++ b/src/slic3r/GUI/Mcp/WebPages.hpp @@ -91,7 +91,7 @@ const std::string& page_agent_version(); // The script that asks `request` of the agent: when `install`, it installs the agent first. std::string page_script(const nlohmann::json& request, bool install); -// A page snapshot (the agent's reply) as list_widgets lines at `depth`, in the window-client frame +// A page snapshot (the agent's reply) as widget_list lines at `depth`, in the window-client frame // widgets use: CSS pixels times `scale` (logical pixels per CSS pixel), offset by `origin`, the web // view's place in its window. `key` is the element the line stands for (null for none). struct PageNode @@ -121,7 +121,7 @@ std::string redact_url(const std::string& url); std::optional journal_index(const std::vector& webs, const std::vector& replies, WebHandle web, const nlohmann::json& key); -// What a press_keys chord is to the agent: {key: {key, code, keyCode, charCode, text?}, mods: {ctrl, +// What a keyboard_press chord is to the agent: {key: {key, code, keyCode, charCode, text?}, mods: {ctrl, // shift, alt, meta}}, with Ctrl/Cmd the Command key on macOS and RawCtrl its Control key. Throws // ToolFailure for a chord KeyChord::parse() refuses. nlohmann::json web_key(const std::string& chord); diff --git a/src/slic3r/GUI/Mcp/WindowControl.cpp b/src/slic3r/GUI/Mcp/WindowControl.cpp index 74ae2a97bc..6c7259e948 100644 --- a/src/slic3r/GUI/Mcp/WindowControl.cpp +++ b/src/slic3r/GUI/Mcp/WindowControl.cpp @@ -43,7 +43,7 @@ GtkWidget* gtk_window_of(const wxTopLevelWindow& window) // What a Wayland compositor says of a window, which GTK passes on as a visibility notify and wx ignores: // it hides the window (xdg_toplevel's suspended state). KWin hides a minimized window, but also one on // another virtual desktop and every window while the screens are off; Mutter hides any window it has not -// shown for 3 s. So a hidden window reads minimized only while set_window's minimize of it stands, which +// shown for 3 s. So a hidden window reads minimized only while window_set's minimize of it stands, which // ends once the window shows, takes the focus or closes. constexpr const char* kSuspendedKey = "orca-mcp-suspended"; constexpr const char* kMinimizedKey = "orca-mcp-minimized"; @@ -176,7 +176,7 @@ void raise_transients(const wxTopLevelWindow& window) } } -// The window's normal rect, kept on the GtkWindow while set_window keeps it maximized itself. +// The window's normal rect, kept on the GtkWindow while window_set keeps it maximized itself. constexpr const char* kNormalRectKey = "orca-mcp-normal-rect"; // Adds or removes the maximized atoms in the window's _NET_WM_STATE, keeping the others GDK set. With no diff --git a/src/slic3r/GUI/Mcp/WindowControl.hpp b/src/slic3r/GUI/Mcp/WindowControl.hpp index a2a8fe2cfd..db48f83964 100644 --- a/src/slic3r/GUI/Mcp/WindowControl.hpp +++ b/src/slic3r/GUI/Mcp/WindowControl.hpp @@ -18,15 +18,15 @@ namespace Slic3r { namespace GUI { namespace Mcp { // Follows, while `on`, the windows a Wayland compositor hides, which GTK passes on only as a visibility // change, and the focus that ends a minimize: on before the first window_state(). Turning it off forgets -// what was followed, so a window reads minimized again only after a set_window minimizes it with this on. +// what was followed, so a window reads minimized again only after a window_set minimizes it with this on. void track_window_states(bool on); -// "minimized", "maximized" or "normal": a window's state as list_windows reports it and set_window takes +// "minimized", "maximized" or "normal": a window's state as window_list reports it and window_set takes // it. On Wayland, which reports no minimize, a window reads minimized while the compositor hides it after -// set_window minimized it. +// window_set minimized it. const char* window_state(const wxTopLevelWindow& window); -// The window's size as the window system shows it, in the units list_windows reports: wx's size, less +// The window's size as the window system shows it, in the units window_list reports: wx's size, less // the margins GTK draws a client-side decorated window's shadow in on Wayland, which the compositor and a // window screenshot leave out. wxSize window_size(wxTopLevelWindow& window); @@ -55,7 +55,7 @@ void raise_window(wxTopLevelWindow& window); // Whether bringing a minimized window back takes the compositor's leave to activate it, which it may // refuse (Wayland). bool restore_needs_activation(); -// How long set_window waits for a window to report the `state` it was asked for: 3 s, and 5 s for a +// How long window_set waits for a window to report the `state` it was asked for: 3 s, and 5 s for a // minimize on Wayland, where Mutter reports a window hidden once it has not shown it for 3 s. std::chrono::seconds state_change_timeout(const std::string& state); diff --git a/src/slic3r/GUI/Mcp/WindowNames.hpp b/src/slic3r/GUI/Mcp/WindowNames.hpp index f8fa7335be..92126450b6 100644 --- a/src/slic3r/GUI/Mcp/WindowNames.hpp +++ b/src/slic3r/GUI/Mcp/WindowNames.hpp @@ -3,8 +3,8 @@ // The window names the MCP tools read. A header of their own, so that a window that sets one includes nothing more. namespace Slic3r { namespace GUI { namespace Mcp { -// The name of a top-level window the MCP GUI tools never see: list_widgets and locators skip it, -// run_javascript never picks its web views, keys sent without a target never go to it, window screenshots leave it +// The name of a top-level window the MCP GUI tools never see: widget_list and locators skip it, +// webview_run_javascript never picks its web views, keys sent without a target never go to it, window screenshots leave it // out, and as a modal dialog it is not tracked, so the dialog tools and auto-answer rules never reach // it. Action Replay carries it, so a replay it runs can't act on it, and so does the window that // changes the Python scripts setting, so no agent, replay or script can turn it on. diff --git a/src/slic3r/GUI/NativeCommandRows.hpp b/src/slic3r/GUI/NativeCommandRows.hpp new file mode 100644 index 0000000000..53a53a49c7 --- /dev/null +++ b/src/slic3r/GUI/NativeCommandRows.hpp @@ -0,0 +1,107 @@ +#pragma once + +#include "ActionRegistry.hpp" // for AppActionRunResult + +#include + +#include +#include +#include + +namespace Slic3r { +namespace GUI { + +enum class CalibKind : int; + +// The functions of the Speed Dial's menu rows that are tiles of a command: each does what its row does, as a +// person's pick of the row does it: on what is selected in the Prepare view, on the current plate, or on the app and +// its windows. A command made from rows calls the function of the row its variant argument names, and a typed tool +// calls one when a call's arguments are that row's tile's (Mcp::person_form()), or, where the row does what the tool +// does (Auto-Arrange), for a person's pick of the tile alone (NativeCommands::with_row_forms()). They are defined in +// NativeCommands.cpp, beside the helpers the rows share. UI thread. +namespace Rows { + +// ---- The project ---- +AppActionRunResult load_project(); +AppActionRunResult save_project_as(); +AppActionRunResult import_file(); +AppActionRunResult import_zip_archive(); +AppActionRunResult export_gcode(); +AppActionRunResult export_stl(); +AppActionRunResult export_3mf(); +// The current plate's sliced file, or with `all_plates` every plate's in one file. +AppActionRunResult export_sliced_file(bool all_plates); +// Every object as its own STL file, into the folder a dialog asks for; a project with no objects is refused. +AppActionRunResult export_stl_multi(); +AppActionRunResult export_drc_single(); +// Every object as its own Draco file, into the folder a dialog asks for; a project with no objects is refused. +AppActionRunResult export_drc_multi(); +// The toolpaths the Preview shows as an OBJ, into the file a dialog asks for; refused while it shows none. +AppActionRunResult export_toolpaths_obj(); + +// ---- Objects and parts ---- +// Handy model `index` of MenuFactory::handy_models(). +AppActionRunResult add_handy(std::size_t index); +AppActionRunResult add_primitive_text(); +// An SVG as a new object, or a part of the selected object: with no arguments from the file a dialog asks for, +// else from the file `args` names ({"path"}). +AppActionRunResult add_primitive_svg(const nlohmann::json& args); +AppActionRunResult obj_arrange(); + +// ---- Plates ---- +AppActionRunResult plate_add(); +// The calibration test's dialog, as the Calibration menu opens it. +AppActionRunResult calib(CalibKind kind); + +// ---- Presets and settings ---- +// With no arguments the Import Configs file dialog, else the file `args` names ({"path", "on_conflict"?}): a preset +// .json, a .zip of them, an .orca_printer, .orca_filament or .orca_bundle, or a .gcode, whose settings it loads. +AppActionRunResult import_configs(const nlohmann::json& args); +// The Export Preset Bundle dialog, whose OK writes into the existing folder `args` names ({"path"}) when it names one. +AppActionRunResult export_config(const nlohmann::json& args); +AppActionRunResult migrate_filament_presets(); +// The settings mode `mode` names: simple, advanced or expert. +AppActionRunResult set_mode(const std::string& mode); +AppActionRunResult toggle_developer_mode(); + +// ---- The app ---- +// Undo, or with `redo` Redo, of an automated call: on the history `args` names ({"history"?}: design or project), else +// the shown tab's. A refusal is thrown as ToolFailure. +AppActionRunResult undo_redo(const nlohmann::json& args, bool redo); +// A person's pick of Undo, or Redo: what the Edit menu's item does, on the history `args` names or else the shown +// tab's; nothing where the item would be greyed. +AppActionRunResult picked_undo_redo(const nlohmann::json& args, bool redo); +// The web page `page` names in the default browser: wiki, youtube or plugin_hub. +AppActionRunResult open_web_page(const std::string& page); +AppActionRunResult check_for_updates(); +AppActionRunResult show_config_folder(); +AppActionRunResult benchmark_3d_scene(); + +// ---- View and windows ---- +AppActionRunResult toggle_perspective(); +AppActionRunResult reset_window_layout(); +// The window or dialog `window` names: preferences (on the tab and at the key `args` names, {"tab"?, "key"?}), plugins, +// action_replay, preset_bundle, keyboard_shortcuts, setup_wizard, network_test, troubleshoot, tip_of_the_day or about. +AppActionRunResult open_window(const std::string& window, const nlohmann::json& args); +// The names open_window()'s tab gives the Preferences dialog's tabs, in the dialog's order. +std::vector preferences_tabs(); +AppActionRunResult take_screenshot(); + +// ---- Filaments, printers and plugins ---- +AppActionRunResult sync_ams(); +AppActionRunResult send_gcode(); +// With no arguments the plugin file a dialog asks for, else the file `args` names ({"path"}). +AppActionRunResult install_local_plugin(const nlohmann::json& args); +AppActionRunResult refresh_plugins(); + +// ---- Scripts ---- +AppActionRunResult toggle_run_script_panel(); + +// The schema of the argument of a command that opens or imports a file, in place of its file dialog: the absolute path +// of `what`. +nlohmann::json input_file(const char* what); + +} // namespace Rows + +} // namespace GUI +} // namespace Slic3r diff --git a/src/slic3r/GUI/NativeCommands.cpp b/src/slic3r/GUI/NativeCommands.cpp index c65877695c..072bc0acd3 100644 --- a/src/slic3r/GUI/NativeCommands.cpp +++ b/src/slic3r/GUI/NativeCommands.cpp @@ -1,4 +1,5 @@ #include "NativeCommands.hpp" +#include "NativeCommandRows.hpp" #include "ActionIds.hpp" #include "calib_dlg.hpp" @@ -11,27 +12,21 @@ #include "GUI.hpp" #include "GUI_App.hpp" #include "GUI_Factories.hpp" -#include "GUI_ObjectList.hpp" #include "Gizmos/GLGizmoSVG.hpp" #include "Gizmos/GLGizmosManager.hpp" #include "I18N.hpp" #include "Shortcuts.hpp" -#include "Jobs/Job.hpp" -#include "Jobs/Worker.hpp" #include "MainFrame.hpp" #include "RunScriptPanel.hpp" -#include "ObjectDataViewModel.hpp" #include "NetworkTestDialog.hpp" -#include "Notebook.hpp" #include "Operations/ExportOps.hpp" #include "Operations/Outcome.hpp" #include "Operations/PlateOps.hpp" +#include "Operations/PluginOps.hpp" #include "Operations/PresetOps.hpp" #include "Operations/ProjectOps.hpp" #include "Plater.hpp" #include "PluginsDialog.hpp" -#include "PartPlate.hpp" -#include "PlateSettingsDialog.hpp" #include "RecordingDialog.hpp" #include "Preferences.hpp" #include "SceneBenchmark.hpp" @@ -56,7 +51,6 @@ #include "libslic3r/AppConfig.hpp" #include "libslic3r/Config.hpp" #include "libslic3r/Preset.hpp" -#include "libslic3r/PresetBundle.hpp" #include "libslic3r/Utils.hpp" #include #include @@ -77,6 +71,7 @@ #include #include #include "libslic3r/libslic3r.h" +#include #include #include #include "slic3r/GUI/ActionRegistry.hpp" @@ -84,12 +79,10 @@ #include #include #include -#include #include #include #include -#include #include #include #include @@ -97,8 +90,6 @@ #include #include -class wxWindow; - namespace Slic3r { namespace GUI { using nlohmann::json; @@ -122,30 +113,25 @@ void ensure_3d_view(Plater* plater) } } -// Object op guard + run: object ops read the Prepare canvas selection, so ensure that view first so -// a launch from another tab doesn't report a spuriously empty selection. -AppActionRunResult object_op(Plater* plater, bool (*ok)(Plater*), void (*op)(Plater*)) -{ - if (!plater) - return {AppActionRunResult::Level::Info, _L("Open the 3D view first."), false}; - ensure_3d_view(plater); - if (!ok(plater)) - return {AppActionRunResult::Level::Info, _L("Select an object first."), false}; - op(plater); - return {AppActionRunResult::Level::Succeeded}; -} +using NativeCommands::refused; -// What a command answers when its operation refuses: the refusal in the UI's language, shown at -// `level`, as a command that did nothing; automation reads the refusal itself. -AppActionRunResult refused(const Ops::Refusal& refusal, AppActionRunResult::Level level = AppActionRunResult::Level::Error) +// The tile of `command` that collects a value whose call `args` is: the tile's args and the value, under its +// input_arg (or its input where it has none), and nothing else; nullptr when none is. +const json* tile_with_input(const NativeCommand& command, const json& args) { - AppActionRunResult result{level, refusal.translated(), false}; - result.refusal = std::make_shared(refusal); - return result; + if (!command.tiles.is_array() || !args.is_object()) + return nullptr; + for (const json& tile : command.tiles) { + const std::string input = tile.value("input", std::string()); + if (input.empty()) + continue; + json rest = args; + if (rest.erase(tile.value("input_arg", input)) == 1 && rest == tile.at("args")) + return &tile; + } + return nullptr; } -AppActionRunResult worker_busy() { return {AppActionRunResult::Level::Info, _L("Wait for the running background job to finish."), false}; } - // Arrange as the toolbar runs it: on every unlocked plate, in the background. No objects and a running // job each get their own message. AppActionRunResult arrange_all(Plater* plater) @@ -157,22 +143,6 @@ AppActionRunResult arrange_all(Plater* plater) return {AppActionRunResult::Level::Succeeded}; } -// Orient as the toolbar runs it, with the guards arrange has. -AppActionRunResult orient_all(Plater* plater) -{ - if (!plater) - return {AppActionRunResult::Level::Info, _L("Open the 3D view first."), false}; - ensure_3d_view(plater); - if (plater->model().objects.empty()) - return {AppActionRunResult::Level::Info, _L("There are no objects to orient."), false}; - if (!plater->get_ui_job_worker().is_idle()) - return worker_busy(); - // A plate's Auto Rotate icon leaves the plate-only state behind. - plater->set_prepare_state(Job::PREPARE_STATE_DEFAULT); - plater->orient(); - return {AppActionRunResult::Level::Succeeded}; -} - // How many undo and how many redo items the project's active history lists, as the canvas's Undo and Redo lists // show them (Plater::undo_redo_string_getter()). Both are counted from the active snapshot, so they change exactly // when it moves, which is when Plater::undo() or redo() takes back or puts back an entry of the history. @@ -209,134 +179,6 @@ AppActionRunResult project_undo_redo(bool redo, bool agent) return {AppActionRunResult::Level::Succeeded, {}, true, json{{"history", "project"}}.dump()}; } -// An automated call of Undo, or Redo, on the history args.history names: "design", the Design tab's, or -// "project". Without it the history is the shown tab's, as the Edit menu's Undo and Redo choose it. The reply says -// which history it was and, for the Design tab's, what Mcp::cad_undo_redo() replies. A refusal is thrown as ToolFailure. -AppActionRunResult undo_redo(const json& args, bool redo) -{ - std::string history = args.value("history", std::string()); - if (history.empty()) { - history = "project"; -#ifdef SLIC3R_CAD - if (MainFrame* mf = wxGetApp().mainframe; mf != nullptr && mf->shown_design_panel() != nullptr) - history = "design"; -#endif - } - if (history == "design") { -#ifdef SLIC3R_CAD - json reply{{"history", "design"}, {"result", Mcp::cad_undo_redo(redo)}}; - return {AppActionRunResult::Level::Succeeded, {}, true, reply.dump()}; -#else - throw ToolFailure("The CAD feature is off: this build of OrcaSlicer has no Design tab"); -#endif - } - return project_undo_redo(redo, /*agent=*/true); -} - -// A person's pick of Undo, or Redo: what the Edit menu's item does, on the history args.history names or else the -// shown tab's, through the function the menu calls. It shows nothing: where the menu's item would be greyed it does -// nothing, and otherwise the Design tab's status line or the canvas shows what changed, as after the menu's. -AppActionRunResult picked_undo_redo(const json& args, bool redo) -{ - const std::string history = args.value("history", std::string()); - // What a pick that does nothing shows: nothing. - const AppActionRunResult greyed{AppActionRunResult::Level::Info, {}, false}; -#ifdef SLIC3R_CAD - DesignPanel* design = nullptr; - if (history.empty()) { - if (MainFrame* mf = wxGetApp().mainframe) - design = mf->shown_design_panel(); - } else if (history == "design") - design = DesignPanel::if_built(); - if (design != nullptr || history == "design") { - if (design == nullptr || !design->menu_can_undo_redo(redo)) - return greyed; - design->menu_undo_redo(redo); - return {AppActionRunResult::Level::Succeeded, {}, true, json{{"history", "design"}}.dump()}; - } -#else - // A build without CAD has no Design tab, so no history of it to take back. - if (history == "design") - return greyed; -#endif - // Plater::undo() and redo() act wherever they are called from; the menu's item is what keeps them to the 3D - // view with no job running. - const Plater* plater = wxGetApp().plater(); - if (plater == nullptr || !(redo ? plater->can_redo() : plater->can_undo())) - return greyed; - return project_undo_redo(redo, /*agent=*/false); -} - -// The object list, once the Prepare view is shown; the object structure commands act on its selected -// rows, as the context menu items they stand for do. -ObjectList* object_list_in_3d_view() -{ - Plater* plater = wxGetApp().plater(); - ObjectList* list = wxGetApp().obj_list(); - if (plater == nullptr || list == nullptr) - return nullptr; - ensure_3d_view(plater); - return list; -} - -// The object list's selected rows, or none unless every one is of one of `types` (ItemType bits). -wxDataViewItemArray selected_rows(const ObjectList& list, int types) -{ - wxDataViewItemArray rows; - list.GetSelections(rows); - for (const wxDataViewItem& row : rows) - if ((list.GetModel()->GetItemType(row) & types) == 0) - return {}; - return rows; -} - -AppActionRunResult with_reply(const nlohmann::json& reply) -{ - AppActionRunResult r{AppActionRunResult::Level::Succeeded}; - r.reply = reply.dump(); - return r; -} - -// What an Order By left: the sorted plates' objects in their new order, and whether they run -// descending (choosing the order the objects already have reverses it). -AppActionRunResult ordered(Plater& plater, ObjectOrder order, bool all_plates) -{ - PartPlateList& plates = plater.get_partplate_list(); - const ModelObjectPtrs& objects = plater.model().objects; - nlohmann::json list = nlohmann::json::array(); - bool descending = false; - for (int plate = 0; plate < plates.get_plate_count(); ++plate) { - if (!all_plates && plate != plates.get_curr_plate_index()) - continue; - std::vector on_plate; - for (size_t i = 0; i < objects.size(); ++i) - if (plates.find_instance(int(i), 0) == plate) { - on_plate.push_back(objects[i]); - list.push_back({{"object", i}, {"name", objects[i]->name}, {"plate", plate}}); - } - std::vector ascending = on_plate; - sort_objects(ascending, order, false); - descending = descending || ascending != on_plate; - } - return with_reply({{"order", list}, {"descending", descending}}); -} - -// Jumps the Preview to the layer a 0-100 percent of its layers stands for. The percent moves the top -// of the shown range; its bottom stays. The caller has already switched to the Preview. -AppActionRunResult go_to_layer(double pct) -{ - pct = std::clamp(pct, 0.0, 100.0); - - const Ops::Outcome count = Ops::layer_count(); - if (!count) - return refused(count.refusal(), AppActionRunResult::Level::Info); - Ops::ShowLayerRangeArgs range; - range.last = int(std::lround(pct / 100.0 * double(count.value() - 1))) + 1; - if (const Ops::Outcome shown = Ops::show_layer_range(range); !shown) - return refused(shown.refusal(), AppActionRunResult::Level::Info); - return {AppActionRunResult::Level::Succeeded}; -} - // The file `args` names ({"path", "overwrite"?}), checked for reading (`output` false) or for writing, where // a file that exists is replaced only with overwrite. nullopt with an Error in `fail` when the path is // missing or unusable. @@ -382,12 +224,6 @@ const char* level_name(AppActionRunResult::Level level) } } -// What a command that wrote `path` answers, or its operation's refusal. -AppActionRunResult written(const Ops::Outcome& outcome, const boost::filesystem::path& path) -{ - return outcome ? AppActionRunResult{AppActionRunResult::Level::Succeeded, from_u8(path.string())} : refused(outcome.refusal()); -} - // A screenshot or recording saved into the MCP output folder, which a person would not find by themselves: a // notification names the file, with a button that opens its folder. void notify_saved(const wxString& text, const boost::filesystem::path& path) @@ -400,7 +236,7 @@ void notify_saved(const wxString& text, const boost::filesystem::path& path) // For automation: the file a command saved, which its notification shows the person. std::string path_reply(const boost::filesystem::path& path) { return nlohmann::json{{"path", Mcp::path_to_utf8(path)}}.dump(); } -// Why a recording ended when Stop Recording ended it; an agent's stop_recording reports it. +// Why a recording ended when Stop Recording ended it; an agent's recording_stop reports it. constexpr const char* kStoppedInApp = "stopped_in_app"; void notify_error(const wxString& text) @@ -432,7 +268,7 @@ bool encode_when_closed(const boost::filesystem::path& path, const Mcp::Recordin // The dialog shows the remembered settings and remembers what it starts with. Encoding needs an ffmpeg: the // dialog says so, and the recording is then not encoded. Neither a run's end nor the server turning off ends // the recording. Whatever does end it says where it went: Stop Recording itself, or the recording's `ended` for -// an agent's stop_recording, the limit or a write error; with encode, `ended` also encodes it. +// an agent's recording_stop, the limit or a write error; with encode, `ended` also encodes it. AppActionRunResult NativeCommands::start_person_recording() { if (recording_active()) @@ -506,14 +342,6 @@ AppActionRunResult NativeCommands::stop_recording_in_app() namespace { -// Select a named camera view. Plater::select_view dispatches to the current panel. -AppActionRunResult view_command(Plater* plater, const std::string& dir) -{ - if (plater) - plater->select_view(dir); - return {AppActionRunResult::Level::Succeeded}; -} - // Calibration wizards. Routes through MainFrame::run_calibration, the same entry point as the // Calibration menu (which caches most of the wizard dialogs). AppActionRunResult calib_command(CalibKind kind) @@ -551,1262 +379,711 @@ AppActionRunResult import_preset_file(const boost::filesystem::path& path, bool return {AppActionRunResult::Level::Succeeded, message}; } -// Thin AppAction wrapper for one catalog entry, or one of its tiles: identity and presentation come from the -// catalog, run() routes back to it. The id is keyed by the stable catalog key (not the display title), so a -// rename or a UI-language switch never re-keys the action. +// Thin AppAction wrapper for one catalog entry's own tile, or one of its items: identity and presentation come from +// the catalog, run() runs the catalog's command, which outlives the action. The id is keyed by the stable catalog key +// (not the display title), so a rename or a UI-language switch never re-keys the action. struct CommandAction : AppAction { - // A tile with a preset runs its command with it: run_action takes no arguments for it, or exactly those. - AppActionRunResult run(const json& args) const override { return NativeCommands::run(command, preset.is_null() ? args : preset); } + // A Speed Dial pick (ActionRegistry::run()): `args` is empty for a plain pick, or the value a tile with an input + // collects. The tile's own arguments join them (tile_call_args()), and NativeCommands::run() checks the result + // against the command's schema. + AppActionRunResult run(const json& args) const override + { + return NativeCommands::run(m_command, tile_call_args(m_tile.is_null() ? nullptr : &m_tile, args)); + } - // The command's own tile. `title` is the command's title in the UI's language. - CommandAction(const NativeCommand& c, std::string title) : CommandAction(c, c.key, std::move(title), c.title) + // The command's own tile, in its tile_group, else its group. `title` is the command's title in the UI's language. A + // Design command's takes the command's arguments, which its gizmo or dialog would otherwise ask for; any other's + // takes none, as an item of tiles with no arguments does, and runs the command as a person's pick does. + CommandAction(const NativeCommand& c, std::string title) + : CommandAction(c, c.key, std::move(title), c.title, c.tile_group.empty() ? c.group : c.tile_group) { this->input = c.input; this->icon = c.icon; this->automation_description = c.description; this->input_schema = c.input_schema; this->completes_in_background = c.completion == CommandCompletion::Deferred; + if (c.group != kDesignGroup) { + this->input_schema = Mcp::object_schema({}); + this->preset = json::object(); + } } - // The tile `tile` of `c`, which runs `c` with its args. `title` is the tile's title in the UI's language. + // The tile `tile` of `c`, in its group, else the command's. `title` is the tile's title in the UI's language. CommandAction(const NativeCommand& c, const json& tile, std::string title) - : CommandAction(c, tile.at("key").get(), std::move(title), tile.at("title").get()) + : CommandAction(c, tile.at("key").get(), std::move(title), tile.at("title").get(), + tile.value("group", c.group)) { + m_tile = tile; this->icon = tile.at("icon").get(); this->automation_description = tile.at("description").get(); - this->input_schema = Mcp::object_schema({}); this->preset = tile.at("args"); + this->input = tile.value("input", std::string()); + this->input_schema = Mcp::object_schema({}); + // The value the Speed Dial's second phase collects, typed as the command's argument it goes to. + if (!this->input.empty()) { + const std::string to = tile.value("input_arg", this->input); + const json& property = c.input_schema.at("properties").at(to); + this->input_schema = {{"type", "object"}, + {"properties", {{this->input, property}}}, + {"required", json::array({this->input})}, + {"additionalProperties", false}}; + } } private: - // Under id `key`, with the English `title_en`. - CommandAction(const NativeCommand& c, const std::string& key, std::string title, std::string title_en) + // Under id `key`, with the English `title_en`, in the Speed Dial section `group_en`. + CommandAction(const NativeCommand& c, const std::string& key, std::string title, std::string title_en, std::string group_en) : AppAction(AppActionId{AppAction::compose_id(kCommandPrefix, key, kOrcaSourceKey)}, std::move(title), kOrcaSourceKey, kOrcaSourceName) + , m_command(c) { this->kind = AppActionKind::Command; - this->group = I18N::translate_utf8(c.group); + this->group = I18N::translate_utf8(group_en); this->title_en = std::move(title_en); - this->group_en = c.group; + this->group_en = std::move(group_en); this->command = c.key; } + + const NativeCommand& m_command; + json m_tile; // the item of m_command's tiles; null for its own tile }; -// A description of each command for agents (English, never shown in the palette): what it does, what its -// arguments stand for and what it replies. -void describe_commands(std::vector& commands) -{ - struct Detail - { - const char* key; - const char* description; - }; - static const Detail details[] = { - {"slice_and_preview", "Slice the current plate and show the Preview tab. Returns at once; use the slice tool to wait for the result."}, - {"slice_all", "Slice every plate and show the Preview tab. Returns at once; use the slice tool to wait for results."}, - {"go_to_layer", "Show the Preview tab at a layer chosen as a percentage of the layer range; an error while the Preview has no layers (slice first)."}, - {"go_to_tab", "Switch to a main window tab."}, - {"load_project", "Open a project. With a path, opens that file without a dialog (asks first if the current project has unsaved changes)."}, - {"save_project_as", "Save the project as a .3mf file. With a path, saves there without a dialog; a name ending in .gcode.3mf is refused (export_sliced_file writes that)."}, - {"undo", "Take back the last change of a history, as Edit > Undo does. history design is the Design tab's: the last " - "feature added, edited, deleted, moved, shown or hidden, or renamed, or variable changed, or in a sketch session " - "the last drawn shape; project is the project's. Without history, the Design tab's while it is shown, else the " - "project's. Reply: history and, for the Design tab's, result: scope (design or sketch), undo_depth, redo_depth, " - "features, bodies and generation; entities in a sketch."}, - {"redo", "Put back what undo took back, until the next change, as Edit > Redo does, in the history undo takes. Reply " - "as undo's."}, - {"open_action_replay", "Open the Action Replay window, where a person opens a replay file, reads its steps " - "and replays them. Agents run replays with the run_replay tool instead."}, - {"toggle_run_script_panel", "Show or hide the Run Script panel, where a person writes and runs Python scripts cell by cell. " - "Agents run Python with the run_script tool instead."}, - {"take_screenshot", "Save a PNG of the main window in the folder Start Recording saves in (the person's Downloads unless " - "they chose another) and show the person a notification naming it; the reply has its path. Agents use " - "the screenshot tool, which returns the image."}, - {"open_preferences", "Open the Preferences dialog on a tab, scrolled to one preference when given (shown on its own tab). Its " - "controls are named after their preference keys: set_widget_value {\"target\": {\"name\": key, \"within\": " - "\"Preferences\"}} changes one through the dialog; get_settings scope preferences reads them."}, - {"mode_simple", "Switch the settings view to Simple mode."}, - {"mode_advanced", "Switch the settings view to Advanced mode."}, - {"mode_expert", "Switch the settings view to Expert mode."}, - {"toggle_developer_mode", "Turn Developer mode on or off."}, - {"export_gcode", "Export the current plate's G-code. With a path, exports the sliced plate there without a dialog, in the " - "background, and the call returns when the file is written; a plate that is not sliced is refused " - "(slice first). With no arguments, it opens the export dialog."}, - {"export_stl", "Export all objects as one STL. With a path, writes there without a dialog."}, - {"export_3mf", "Export the model as a .3mf without slicing data. With a path, writes there without a dialog."}, - {"export_sliced_file", "Export the current plate's sliced file (.gcode.3mf). With a path, writes there without a dialog."}, - {"export_all_sliced_file", "Export every plate's sliced file into one .gcode.3mf. With a path, writes there without a dialog."}, - {"send_gcode", "Open the Send G-code to printer host dialog for the current plate, as the Print button does for a printer with a print host (OctoPrint, Moonraker, PrusaLink, Duet...). Set the file name with set_widget_value and press Upload or Upload and Print with answer_dialog; the plate is sliced if needed, then uploaded in the background: get_app_state.uploads shows the row's state, and a failed upload also opens an error dialog. A replay uploads again. Fails for a printer without a print host, or one that prints through the Bambu network or printer agents."}, - {"export_stl_multi", "Export each object as its own STL. With a directory, writes there without a dialog."}, - {"export_drc_single", "Export all objects as one Draco (.drc) file."}, - {"export_drc_multi", "Export each object as its own Draco (.drc) file."}, - {"export_toolpaths_obj", "Export the sliced toolpaths as an OBJ."}, - {"export_config", "Export presets as a bundle or ZIP archives. Opens a dialog: click the label of the kind to export, check " - "its rows (each named after a printer preset or a filament), press OK, then answer the result message. " - "With a directory, OK writes there instead of asking for a folder."}, - {"import_file", "Import models (3MF/STL/STEP/SVG/OBJ/AMF). With a path, adds that file's geometry without a dialog, as one undo step; " - "a project file's settings are not loaded (load_project opens a project)."}, - {"import_zip_archive", "Import models from a ZIP archive (opens a file dialog)."}, - {"import_configs", "Import presets. With a path, imports a preset .json, a .zip of them or an .orca_printer, " - ".orca_filament or .orca_bundle without a dialog, and the message names the presets imported, " - "replaced and kept; a .gcode loads the settings it was sliced with."}, - {"view_default", "Reset the 3D camera to the default view and fit the plate."}, - {"view_fit_bed", "Fit the build plate in the 3D view."}, - {"view_toggle_perspective", "Switch the 3D camera between perspective and orthographic."}, - {"reset_window_layout", "Restore the default window layout."}, - {"obj_delete", "Delete the selected objects or parts."}, - {"obj_delete_all", "Delete all objects."}, - {"select_all", "Select all objects in the 3D view."}, - {"deselect_all", "Clear the selection."}, - {"obj_mirror_x", "Mirror the selection along X."}, - {"obj_mirror_y", "Mirror the selection along Y."}, - {"obj_mirror_z", "Mirror the selection along Z."}, - {"obj_split_objects", "Split the selected object into separate objects."}, - {"obj_split_parts", "Split the selected object into parts."}, - {"obj_center", "Center the selection on its plate."}, - {"obj_drop", "Drop the selection onto the bed."}, - {"obj_fit_volume", "Scale the selection to fit the print volume."}, - {"obj_instances_up", "Add an instance of the selected object."}, - {"obj_instances_down", "Remove an instance of the selected object."}, - {"obj_arrange", "Arrange all objects on the unlocked plates with the saved Arrange options, as the toolbar does; the " - "call returns when the arrangement is done. The arrange tool also takes options, one plate or fill bed."}, - {"obj_orient", "Auto-orient the selection, or every object when nothing is selected; the call returns when it is done."}, - // Object structure: the object list's Change Type, Rename, instance and Assemble items, and the plate - // menu's Order By. Arguments stand in for the item's dialog. - {"obj_type_part", "Make the selected parts (select_objects {parts} first) solid parts, as Change Type does. Parts are listed by type, so part indices change."}, - {"obj_type_negative", "Make the selected parts negative parts, as Change Type does; not the object's last solid part. Parts are listed by type, so part indices change."}, - {"obj_type_modifier", "Make the selected parts modifiers, as Change Type does; not the object's last solid part. Parts are listed by type, so part indices change."}, - {"obj_type_support_blocker", "Make the selected parts support blockers, as Change Type does; not the object's last solid part, nor a text or SVG part. Parts are listed by type, so part indices change."}, - {"obj_type_support_enforcer", "Make the selected parts support enforcers, as Change Type does; not the object's last solid part, nor a text or SVG part. Parts are listed by type, so part indices change."}, - {"obj_type_precise_seam", "Make the selected parts Center precise seams (seams keep their subtype), as Change Type does; not the object's last solid part, nor a text or SVG part. Parts are listed by type, so part indices change."}, - {"obj_rename", "Rename the selected object or part (select one). With a name, skips the Rename dialog; an empty name, or one with characters a file name cannot hold, is refused."}, - {"obj_set_instances", "Give the selected object this many instances, in one undo step. With a count, skips the dialog. New instances overlap; arrange afterwards. The reply has object and instances."}, - {"obj_assemble", "Assemble two or more selected objects into one object of parts named Assembly. They are removed and it is added last, so object indices change; the reply has its index (object) and name."}, - {"obj_instances_to_objects", "Make each instance of the selected object a separate object (select_objects {objects: [n]}); with some of its instances selected, only those. New objects are added last; the reply lists the objects the instances are in now (objects)."}, - {"obj_order_by_name", "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."}, - {"obj_order_by_filament", "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."}, - {"obj_order_by_height", "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."}, - {"obj_order_by_size", "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."}, - {"add_primitive_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 (wait for idle), and the SVG gizmo opens on it."}, - {"add_primitive_text", "Add a text: a part on the selected object, or a new object when nothing is selected. It is created " - "in the background (wait for idle), and the Text gizmo opens on it."}, - // Shapes: a size skips the Primitive size dialog. - {"add_primitive_cube", "Add a cube object to the current plate; fails while an object is selected. With a size, skips the size dialog."}, - {"add_primitive_cylinder", "Add a cylinder object to the current plate; fails while an object is selected. With a size, skips the size dialog. The shape may then be turned toward the part-cooling fan, so the size is along its own axes before that turn."}, - {"add_primitive_sphere", "Add a sphere object to the current plate; fails while an object is selected. With a size, skips the size dialog."}, - {"add_primitive_cone", "Add a cone object to the current plate; fails while an object is selected. With a size, skips the size dialog. The shape may then be turned toward the part-cooling fan, so the size is along its own axes before that turn."}, - {"add_primitive_disc", "Add a disc object to the current plate; fails while an object is selected. With a size, skips the size dialog. The shape may then be turned toward the part-cooling fan, so the size is along its own axes before that turn."}, - {"add_primitive_torus", "Add a torus object to the current plate; fails while an object is selected. With a size, skips the size dialog. The shape may then be turned toward the part-cooling fan, so the size is along its own axes before that turn."}, - // The two handy models of several files, which the menu arranges once they are loaded. - {"add_handy_orca_cube", "Add the Orca Cube and its plug to the current plate, then arrange the objects as the toolbar's " - "Arrange does, which moves the others too."}, - {"add_handy_orcasliced_combo", "Add the OrcaSliced Combo (the OrcaSliced model, the Orca Cube and its plug) to the current " - "plate, then arrange the objects as the toolbar's Arrange does, which moves the others too."}, - {"plate_add", "Add a plate."}, - {"plate_duplicate", "Duplicate the current plate."}, - {"plate_delete", "Delete the current plate."}, - {"plate_rename", "Rename the current plate (opens a dialog)."}, - {"plate_toggle_lock", "Lock or unlock the current plate."}, - {"plate_goto", "Make a plate the current one; an index the project lacks is an error."}, - {"sync_ams", "Synchronize the filament list from the connected printer's AMS."}, - {"preset_bundle", "Open the preset bundle manager."}, - {"sync_presets", "Synchronize user presets with the cloud account."}, - {"help_keyboard_shortcuts", "Show the keyboard shortcuts dialog."}, - {"help_setup_wizard", "Open the setup wizard."}, - {"help_open_config_folder", "Open the configuration folder in the file manager."}, - {"help_migrate_filament_presets", "Migrate legacy user filament presets."}, - {"help_troubleshoot", "Open the troubleshooting center."}, - {"help_network_test", "Open the network test dialog."}, - {"help_benchmark_3d_scene", "Time the 3D views on a test model. It asks first (Start or Cancel), then replaces the project " - "with the OrcaSliced Combo as New Project does, which may ask about unsaved changes, slices it " - "and shows the results."}, - {"help_tip_of_the_day", "Show a tip of the day."}, - {"help_check_updates", "Check for a newer OrcaSlicer."}, - {"help_about", "Show the About dialog."}, - {"open_wiki", "Open the OrcaSlicer wiki in the browser."}, - {"open_youtube", "Open the OrcaSlicer YouTube channel in the browser."}, - {"open_plugins", "Open the plugins dialog."}, - {"refresh_plugins", "Reload plugins."}, - {"install_plugin", "Open the plugin hub's page in the default web browser, where a person picks a plugin to install; " - "nothing opens in OrcaSlicer."}, - {"install_local_plugin", "Install a plugin from a .py or .whl file, as the Plugins dialog's Install local plugin does. With a " - "path, installs that file without a dialog. Replacing a plugin installed already asks first " - "(answer with answer_dialog); the message names the plugin installed, or why it was not."}, - // Filament slots - {"filament_add", "Add a filament slot, as the + button above the filament list does; the message names the new slot. It " - "takes the next colour and the last slot's preset (change them with select_preset filament_slot and " - "set_settings scope project filament_colour). It goes after the physical slots: mixed filaments move " - "up by one, and objects on them follow."}, - {"filament_delete", "Delete a filament slot, as its Delete menu item does; objects on it move to another slot. A mixed " - "filament (project scope filament_is_mixed) is refused."}, - }; - // The operations (GUI/Operations) a command reaches once it has what it needs to run without asking. - static const std::pair> reaches[] = { - {"slice_and_preview", {"start_slice"}}, - {"slice_all", {"start_slice"}}, - {"go_to_layer", {"show_layer_range"}}, - {"save_project_as", {"save_project_as"}}, - {"export_gcode", {"start_gcode_export"}}, - {"export_stl", {"export_stl"}}, - {"export_3mf", {"export_model_3mf"}}, - {"export_sliced_file", {"export_sliced_3mf"}}, - {"export_all_sliced_file", {"export_sliced_3mf"}}, - {"send_gcode", {"send_gcode_to_host"}}, - {"import_file", {"import_models"}}, - {"import_configs", {"import_presets"}}, - {"obj_arrange", {"start_arrange"}}, - {"obj_set_instances", {"set_instance_count"}}, - {"plate_toggle_lock", {"set_plate_locked"}}, - {"plate_goto", {"select_plate"}}, - }; - for (NativeCommand& c : commands) { - if (const auto ops = std::find_if(std::begin(reaches), std::end(reaches), [&](const auto& r) { return c.key == r.first; }); - ops != std::end(reaches)) - c.operations = ops->second; - auto it = std::find_if(std::begin(details), std::end(details), [&](const Detail& d) { return c.key == d.key; }); - if (it != std::end(details)) { - c.description = it->description; - } else if (c.key.rfind("calib_", 0) == 0) { - c.description = "Open the " + c.title + - " dialog; the generate_calibration_test tool runs the same test with typed parameters and no dialog."; - } else if (c.key.rfind("view_", 0) == 0) { - // A named direction, which set_view's camera takes by the same name. The command points the view of - // Prepare, Preview or the assemble view; the Design view is set_view's alone. - const std::string direction = c.key.substr(5); - c.description = "Turn the 3D camera of Prepare, Preview or the assemble view to the " + direction + - " view, as set_view {camera: \"" + direction + "\"} does there."; - } else if (c.key.rfind("add_primitive_", 0) == 0 || c.key.rfind("add_handy_", 0) == 0) { - c.description = "Add the " + c.title + " model to the current plate."; - } - } -} +// The Preferences dialog's tabs, by the names window_open's tab gives them. +constexpr std::pair kPreferencesTabs[] = {{"general", PreferencesTab::General}, + {"files", PreferencesTab::Files}, + {"behaviour", PreferencesTab::Behaviour}, + {"control", PreferencesTab::Control}, + {"graphics", PreferencesTab::Graphics}, + {"online", PreferencesTab::Online}, + {"developer", PreferencesTab::Developer}}; } // namespace -void NativeCommands::register_all_commands(CommandCatalog& catalog, [[maybe_unused]] const CatalogOptions& options) +// ---- The rows that are tiles of a command (NativeCommandRows.hpp) ---- + +json Rows::input_file(const char* what) { return Mcp::prop("string", std::string("Absolute path of ") + what + "."); } + +AppActionRunResult Rows::load_project() { - // The Speed Dial's commands: each has a tile. - std::vector out; - // Adds `command` with a tile. The reference is valid until the next command is added: long enough to say - // what arguments the command takes, as in add(...).input_schema = Mcp::object_schema({...}). - const auto tile = [&out](NativeCommand command) -> NativeCommand& { - command.in_palette = true; - out.push_back(std::move(command)); - return out.back(); - }; - // `title` and `group` are the untranslated English msgids, L("...")-marked at each call so xgettext - // extracts them. A command takes no arguments unless its schema is given afterwards; with none, a - // dialog command asks as a person's pick does. - using Body = std::function; - auto add = [&tile](std::string key, std::string title, std::string group, Body fn, std::string input = {}, - std::string icon = {}) -> NativeCommand& { - NativeCommand& c = tile(ui_command(std::move(key), std::move(title), std::move(group), Mcp::object_schema({}), std::move(fn))); - c.input = std::move(input); - c.icon = std::move(icon); - return c; - }; - // Presentation-first overload: keeps the tile icon next to the title/group it belongs to. - auto add_with_icon = [&add](std::string key, std::string title, std::string group, std::string icon, Body fn, - std::string input = {}) -> NativeCommand& { - return add(std::move(key), std::move(title), std::move(group), std::move(fn), std::move(input), std::move(icon)); - }; - // The argument of a command that opens or imports a file, in place of its file dialog. - const auto input_file = [](const char* what) { return Mcp::prop("string", std::string("Absolute path of ") + what + "."); }; - // The arguments of a command that writes a file, in place of its save dialog. - const auto output_file = [](const char* what) { - return Mcp::object_schema({{"path", Mcp::prop("string", std::string("Absolute path of the ") + what + " to write.")}, - {"overwrite", Mcp::prop("boolean", "Replace a file that exists already. Default false.")}}); - }; + Plater* plater = wxGetApp().plater(); + if (plater == nullptr) + return AppActionRunResult{}; + plater->load_project(); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; +} - // ---- Slice & Export ---- - // Slices through the toolbar's path, so it counts as a user slice request (Plater::request_slice). - add_with_icon("slice_and_preview", L("Slice and Preview"), L("Slice & Export"), "media_play", [](const json&) { - if (wxGetApp().plater() != nullptr) - Ops::start_slice({}); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add_with_icon("slice_all", L("Slice All Plates"), L("Slice & Export"), "media_play", [](const json&) { - if (wxGetApp().plater() != nullptr) { - Ops::SliceArgs slice; - slice.all_plates = true; - Ops::start_slice(slice); - } - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); +AppActionRunResult Rows::save_project_as() +{ + Plater* plater = wxGetApp().plater(); + if (plater == nullptr) + return AppActionRunResult{}; + return NativeCommands::project_save_result(plater->save_project(true)); +} - // Go to layer and Go to tab have one form, which needs its value: the palette collects it in its second - // phase (`input`) and passes it as their argument. - add_with_icon( - "go_to_layer", L("Go to layer (percent)"), L("Commands"), "height_range_layer", - [](const json& args) { - Plater* plater = wxGetApp().plater(); - if (plater == nullptr) - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - plater->select_view_3D("Preview", false); - if (MainFrame* mf = wxGetApp().mainframe; mf) - mf->select_tab(TAB_ID_PREVIEW); - return go_to_layer(args.at("percent").get()); - }, - "percent") - .input_schema = Mcp::object_schema({{"percent", {{"type", "number"}, - {"minimum", 0}, - {"maximum", 100}, - {"description", "The layer to show, as a percentage of the layer range."}}}}, - {"percent"}); - add( - "go_to_tab", L("Go to tab..."), L("Commands"), - [](const json& args) { - MainFrame* mf = wxGetApp().mainframe; - if (mf == nullptr) - return AppActionRunResult{}; - const std::string tab = args.at("tab").get(); - // select_tab() shows the last tab for an empty id, and leaves the tab as it is for an id no page has. - if (mf->m_tabpanel == nullptr || mf->m_tabpanel->FindPageByName(from_u8(tab)) == wxNOT_FOUND) - // TRN %1% is the tab id the command was given, such as "preview". - return AppActionRunResult{AppActionRunResult::Level::Error, format_wxstr(_L("No tab has the id \"%1%\"."), tab), false}; - mf->select_tab(from_u8(tab)); - // The tab can refuse to open: the Device tab of a Bambu Lab printer without its network plugin. - if (mf->m_tabpanel->GetSelectedPageName() != from_u8(tab)) - // TRN %1% is the id of the tab that could not be opened, such as "monitor". - return AppActionRunResult{AppActionRunResult::Level::Error, format_wxstr(_L("The \"%1%\" tab could not be opened."), tab), false}; - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }, - "tab") - .input_schema = Mcp::object_schema( - {{"tab", Mcp::prop("string", "The tab's id: home, prepare, preview, monitor (the Device tab, which set_view calls device), " - "monitor_web (the web Device page, where the app shows one), multi_device, project, " - "calibration, design, or a plugin page's id.")}}, - {"tab"}); +AppActionRunResult Rows::export_gcode() +{ + Plater* plater = wxGetApp().plater(); + if (plater == nullptr) + return AppActionRunResult{}; + plater->export_gcode(false); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; +} - add_with_icon("load_project", L("Load Project"), L("Commands"), "menu_open", [](const json& args) { - Plater* plater = wxGetApp().plater(); - if (plater == nullptr) - return AppActionRunResult{}; - if (Mcp::person_form(args)) { - plater->load_project(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - } - AppActionRunResult fail; - const auto path = path_argument(args, false, fail); - if (!path) - return fail; - plater->load_project(from_path(*path)); +AppActionRunResult Rows::export_stl() +{ + Plater* plater = wxGetApp().plater(); + if (plater == nullptr) + return AppActionRunResult{}; + plater->export_stl(); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; +} + +AppActionRunResult Rows::export_3mf() +{ + Plater* plater = wxGetApp().plater(); + if (plater == nullptr) + return AppActionRunResult{}; + plater->export_core_3mf(); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; +} + +AppActionRunResult Rows::export_sliced_file(bool all_plates) +{ + Plater* plater = wxGetApp().plater(); + if (plater == nullptr) + return AppActionRunResult{}; + plater->export_gcode_3mf(all_plates); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; +} + +AppActionRunResult Rows::calib(CalibKind kind) { return calib_command(kind); } + +// ---- Object ---- +AppActionRunResult Rows::obj_arrange() { return arrange_all(wxGetApp().plater()); } + +// ---- Add Primitive ---- (the Add > Add Primitive submenu's Text and SVG) +AppActionRunResult Rows::add_primitive_text() +{ + Plater* plater = wxGetApp().plater(); + if (plater) { + ensure_3d_view(plater); + if (GLCanvas3D* canvas = plater->canvas3D()) + canvas->clear_popup_menu_position(); + MenuFactory::add_text_volume(ModelVolumeType::INVALID); + } + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; +} + +AppActionRunResult Rows::add_primitive_svg(const json& args) +{ + Plater* plater = wxGetApp().plater(); + if (plater == nullptr) + return AppActionRunResult{}; + ensure_3d_view(plater); + GLCanvas3D* canvas = plater->canvas3D(); + if (canvas != nullptr) + canvas->clear_popup_menu_position(); + if (Mcp::person_form(args)) { + MenuFactory::add_svg_volume(ModelVolumeType::INVALID); return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }).input_schema = Mcp::object_schema({{"path", input_file("a .3mf project")}}); - add_with_icon("save_project_as", L("Save Project As"), L("Commands"), "menu_save", [](const json& args) { - Plater* plater = wxGetApp().plater(); - if (plater == nullptr) - return AppActionRunResult{}; - if (Mcp::person_form(args)) - return project_save_result(plater->save_project(true)); - AppActionRunResult fail; - const auto path = path_argument(args, true, fail); - if (!path) - return fail; - return written(Ops::save_project_as({*path}), *path); - }).input_schema = output_file(".3mf project"); - // Undo and Redo act on the shown tab's history, as the Edit menu's do; history names one for automation, - // which acts whatever tab is shown. - const json history = Mcp::object_schema( - {{"history", Mcp::enum_prop({"design", "project"}, "The history: design, the Design tab's (with the CAD feature on), " - "or project. Default: the Design tab's while it is shown, else " - "the project's.")}}); - // A person's pick does what the Edit menu's item does, and shows nothing where it would be greyed. An - // automated call, run_action of the tile included, acts on the history undo_redo() picks: the Design tab's - // through its gate, whose refusals say why, and the project's as the Edit menu's item does. - const auto picked_as_menu = [](NativeCommand& command, bool redo) { - const CommandFn picked = ui_command(command.key, command.title, command.group, command.input_schema, - [redo](const json& args) { return picked_undo_redo(args, redo); }) - .run; - command.run = [picked, automated = std::move(command.run)](const json& args, ToolContext& ctx) { - return ctx.person() ? picked(args, ctx) : automated(args, ctx); - }; - }; - NativeCommand& undo = add_with_icon("undo", L("Undo"), L("Commands"), "menu_undo", [](const json& args) { return undo_redo(args, false); }); - undo.input_schema = history; - picked_as_menu(undo, false); -#ifdef SLIC3R_CAD - // An example calls Design commands, so only a catalog that holds them documents the Design history. - if (options.cad) - undo.examples = json::parse(R"json([ - {"title": "Take back an extrude, its sketch with it", "calls": [ - {"tool": "extrude", "args": {"width": 20, "height": 20, "distance": 5}}, - {"tool": "undo", "args": {"history": "design"}}]}, - {"title": "Take back the last shape drawn in a sketch", "calls": [ - {"tool": "sketch_create", "args": {"plane": "XY"}}, - {"tool": "sketch_draw", "args": {"type": "rectangle_2_point", "p0": [-15, -10], "p1": [15, 10]}}, - {"tool": "sketch_draw", "args": {"entities": [{"type": "circle_center", "center": [0, 0], "radius": 4}]}}, - {"tool": "undo", "args": {"history": "design"}}]}])json"); + } + // What the dialog path does once a file is picked: a new object with nothing selected, else + // a part of the selected object. + AppActionRunResult fail; + const auto path = path_argument(args, false, fail); + if (!path) + return fail; + auto* svg = canvas != nullptr ? dynamic_cast(canvas->get_gizmos_manager().get_gizmo(GLGizmosManager::Svg)) : nullptr; + if (svg == nullptr || !svg->create_volume(into_u8(from_path(*path)), ModelVolumeType::MODEL_PART)) + return AppActionRunResult{AppActionRunResult::Level::Error, _L("The SVG file could not be added.")}; + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; +} + +// ---- Add Handy models ---- (the Add > Add Handy models submenu) +AppActionRunResult Rows::add_handy(std::size_t index) +{ + if (Plater* plater = wxGetApp().plater()) + ensure_3d_view(plater); + MenuFactory::load_handy_model(index); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; +} + +// ---- Plate ---- +AppActionRunResult Rows::plate_add() +{ + Plater* plater = wxGetApp().plater(); + if (!is_fff_plater(plater)) + return plate_unavailable(); + if (!plater->can_add_plate()) + return AppActionRunResult{AppActionRunResult::Level::Info, _L("Cannot add another plate (maximum reached).")}; + plater->add_plate(); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; +} + +// ---- Import ---- +AppActionRunResult Rows::import_file() +{ + Plater* plater = wxGetApp().plater(); + if (plater == nullptr) + return AppActionRunResult{}; +#ifdef __APPLE__ + plater->add_model(); +#else + plater->add_file(); #endif - NativeCommand& redo = add_with_icon("redo", L("Redo"), L("Commands"), "menu_redo", [](const json& args) { return undo_redo(args, true); }); - redo.input_schema = history; - picked_as_menu(redo, true); -#ifdef SLIC3R_CAD - if (options.cad) - redo.examples = json::parse(R"json([ - {"title": "Put back an extrude undo took back", "calls": [ - {"tool": "extrude", "args": {"width": 20, "height": 20, "distance": 5}}, - {"tool": "undo", "args": {"history": "design"}}, - {"tool": "redo", "args": {"history": "design"}}]}, - {"title": "Put back the shape undo took off a sketch", "calls": [ - {"tool": "sketch_create", "args": {"plane": "XY"}}, - {"tool": "sketch_draw", "args": {"type": "rectangle_2_point", "p0": [-15, -10], "p1": [15, 10]}}, - {"tool": "sketch_draw", "args": {"entities": [{"type": "circle_center", "center": [0, 0], "radius": 4}]}}, - {"tool": "undo", "args": {"history": "design"}}, - {"tool": "redo", "args": {"history": "design"}}]}])json"); -#endif - add_with_icon("toggle_run_script_panel", L("Run Script"), L("Commands"), "media_play", [](const json&) { - if (wxGetApp().mainframe != nullptr) - wxGetApp().run_script_panel().toggle(); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; +} + +AppActionRunResult Rows::import_zip_archive() +{ + if (Plater* plater = wxGetApp().plater()) + plater->import_zip_archive(); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; +} + +// ---- Export extras ---- +AppActionRunResult Rows::export_stl_multi() +{ + Plater* plater = wxGetApp().plater(); + if (plater == nullptr) + return AppActionRunResult{}; + if (const std::optional refusal = Ops::export_objects_refusal("stl", {}, true, plater->model())) + return refused(*refusal, AppActionRunResult::Level::Info); + plater->export_stl(false, false, true); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; +} + +AppActionRunResult Rows::export_drc_single() +{ + if (Plater* plater = wxGetApp().plater()) + plater->export_stl(false, false, false, FT_DRC); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; +} + +AppActionRunResult Rows::export_drc_multi() +{ + Plater* plater = wxGetApp().plater(); + if (plater == nullptr) + return AppActionRunResult{}; + if (const std::optional refusal = Ops::export_objects_refusal("drc", {}, true, plater->model())) + return refused(*refusal, AppActionRunResult::Level::Info); + plater->export_stl(false, false, true, FT_DRC); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; +} + +AppActionRunResult Rows::export_toolpaths_obj() +{ + Plater* plater = wxGetApp().plater(); + if (plater == nullptr) + return AppActionRunResult{}; + if (const std::optional refusal = Ops::toolpaths_refusal()) + return refused(*refusal, AppActionRunResult::Level::Info); + plater->export_toolpaths_to_obj(); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; +} + +// ---- Presets and settings ---- +AppActionRunResult Rows::import_configs(const json& args) +{ + MainFrame* mf = wxGetApp().mainframe; + if (mf == nullptr) + return AppActionRunResult{}; + if (Mcp::person_form(args)) { + mf->load_config_file(); return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add_with_icon("open_action_replay", L("Action Replay"), L("Commands"), "loop", [](const json&) { + } + AppActionRunResult fail; + const auto path = path_argument(args, false, fail); + if (!path) + return fail; + const bool overwrite = args.value("on_conflict", std::string("skip")) == "overwrite"; + const std::string file = Mcp::path_to_utf8(*path); + if (is_gcode_file(file)) { + if (!mf->load_config_file(file)) + return AppActionRunResult{AppActionRunResult::Level::Error, _L("The configuration was not loaded.")}; + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; + } + for (const char* ext : {".json", ".zip", ".orca_printer", ".orca_filament", ".orca_bundle"}) + if (boost::iends_with(file, ext)) + return import_preset_file(*path, overwrite); + return AppActionRunResult{AppActionRunResult::Level::Error, + "Not a preset file: give a .json, .zip, .orca_printer, .orca_filament, .orca_bundle or .gcode"}; +} + +AppActionRunResult Rows::export_config(const json& args) +{ + if (Mcp::person_form(args)) { if (MainFrame* mf = wxGetApp().mainframe) - mf->show_action_replay(); + mf->export_config(); return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - // The tabs of the Preferences dialog, by the names open_preferences takes. - static const std::pair preferences_tabs[] = {{"general", PreferencesTab::General}, - {"files", PreferencesTab::Files}, - {"behaviour", PreferencesTab::Behaviour}, - {"control", PreferencesTab::Control}, - {"graphics", PreferencesTab::Graphics}, - {"online", PreferencesTab::Online}, - {"developer", PreferencesTab::Developer}}; - std::vector preferences_tab_names; - for (const auto& [name, tab] : preferences_tabs) - preferences_tab_names.emplace_back(name); - add_with_icon("open_preferences", L("Preferences"), L("Commands"), "cog", [](const json& args) { + } + AppActionRunResult fail; + const auto dir = dir_argument(args, fail); + if (!dir) + return fail; + // The dialog MainFrame::export_config() opens, given the folder its OK writes to. + ExportConfigsDialog dlg(nullptr, from_path(*dir)); + if (dlg.ShowModal() != wxID_OK) + return AppActionRunResult{AppActionRunResult::Level::Error, _L("Nothing was exported.")}; + return AppActionRunResult{AppActionRunResult::Level::Succeeded, from_path(*dir)}; +} + +AppActionRunResult Rows::migrate_filament_presets() +{ + wxGetApp().check_legacy_user_filament_presets(true); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; +} + +AppActionRunResult Rows::set_mode(const std::string& mode) +{ + static const std::pair modes[] = {{"simple", comSimple}, {"advanced", comAdvanced}, {"expert", comExpert}}; + for (const auto& [name, value] : modes) + if (mode == name) { + wxGetApp().set_mode(value); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; + } + return AppActionRunResult{AppActionRunResult::Level::Error, from_u8("mode is simple, advanced or expert"), false}; +} + +// What Preferences > Developer > Developer mode does: flip the flag, keep it, refresh the UI. +AppActionRunResult Rows::toggle_developer_mode() +{ + GUI_App& app = wxGetApp(); + const bool on = !app.app_config->get_bool("developer_mode"); + app.app_config->set_bool("developer_mode", on); + app.app_config->save(); + app.update_mode(); + return AppActionRunResult{AppActionRunResult::Level::Succeeded, on ? _L("Developer mode enabled.") : _L("Developer mode disabled.")}; +} + +// ---- The app ---- +// The Design tab's history is "design", else "project". Without args.history it is the shown tab's, as the Edit menu's +// Undo and Redo choose it. The reply says which history it was and, for the Design tab's, what Mcp::cad_undo_redo() +// replies. +AppActionRunResult Rows::undo_redo(const json& args, bool redo) +{ + std::string history = args.value("history", std::string()); + if (history.empty()) { + history = "project"; +#ifdef SLIC3R_CAD + if (MainFrame* mf = wxGetApp().mainframe; mf != nullptr && mf->shown_design_panel() != nullptr) + history = "design"; +#endif + } + if (history == "design") { +#ifdef SLIC3R_CAD + json reply{{"history", "design"}, {"result", Mcp::cad_undo_redo(redo)}}; + return {AppActionRunResult::Level::Succeeded, {}, true, reply.dump()}; +#else + throw ToolFailure("The CAD feature is off: this build of OrcaSlicer has no Design tab"); +#endif + } + return project_undo_redo(redo, /*agent=*/true); +} + +// Through the function the menu calls. It shows nothing: where the menu's item would be greyed it does nothing, and +// otherwise the Design tab's status line or the canvas shows what changed, as after the menu's. +AppActionRunResult Rows::picked_undo_redo(const json& args, bool redo) +{ + const std::string history = args.value("history", std::string()); + // What a pick that does nothing shows: nothing. + const AppActionRunResult greyed{AppActionRunResult::Level::Info, {}, false}; +#ifdef SLIC3R_CAD + DesignPanel* design = nullptr; + if (history.empty()) { + if (MainFrame* mf = wxGetApp().mainframe) + design = mf->shown_design_panel(); + } else if (history == "design") + design = DesignPanel::if_built(); + if (design != nullptr || history == "design") { + if (design == nullptr || !design->menu_can_undo_redo(redo)) + return greyed; + design->menu_undo_redo(redo); + return {AppActionRunResult::Level::Succeeded, {}, true, json{{"history", "design"}}.dump()}; + } +#else + // A build without CAD has no Design tab, so no history of it to take back. + if (history == "design") + return greyed; +#endif + // Plater::undo() and redo() act wherever they are called from; the menu's item is what keeps them to the 3D + // view with no job running. + const Plater* plater = wxGetApp().plater(); + if (plater == nullptr || !(redo ? plater->can_redo() : plater->can_undo())) + return greyed; + return project_undo_redo(redo, /*agent=*/false); +} + +AppActionRunResult Rows::open_web_page(const std::string& page) +{ + if (page == "wiki") + wxLaunchDefaultBrowser("https://www.orcaslicer.com/wiki/", wxBROWSER_NEW_WINDOW); + else if (page == "youtube") + wxLaunchDefaultBrowser("https://www.youtube.com/@OfficialOrcaSlicer/videos", wxBROWSER_NEW_WINDOW); + else if (page == "plugin_hub") + open_plugin_hub(); + else + return AppActionRunResult{AppActionRunResult::Level::Error, from_u8("page is wiki, youtube or plugin_hub"), false}; + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; +} + +AppActionRunResult Rows::check_for_updates() +{ + wxGetApp().check_new_version_sf(true, 1); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; +} + +AppActionRunResult Rows::show_config_folder() +{ + Slic3r::GUI::desktop_open_datadir_folder(); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; +} + +AppActionRunResult Rows::benchmark_3d_scene() +{ + run_scene_benchmark(); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; +} + +// ---- View and windows ---- +AppActionRunResult Rows::toggle_perspective() +{ + if (Plater* plater = wxGetApp().plater()) + plater->get_camera().select_next_type(); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; +} + +AppActionRunResult Rows::reset_window_layout() +{ + if (Plater* plater = wxGetApp().plater()) + plater->reset_window_layout(); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; +} + +std::vector Rows::preferences_tabs() +{ + std::vector names; + for (const auto& [name, tab] : kPreferencesTabs) + names.emplace_back(name); + return names; +} + +AppActionRunResult Rows::open_window(const std::string& window, const json& args) +{ + GUI_App& app = wxGetApp(); + if (window == "preferences") { if (Mcp::person_form(args)) { - wxGetApp().open_preferences(); + app.open_preferences(); return AppActionRunResult{AppActionRunResult::Level::Succeeded}; } // The tab to show, and the preference whose control is scrolled into view and focused. const std::string tab = args.value("tab", std::string()); - const auto it = std::find_if(std::begin(preferences_tabs), std::end(preferences_tabs), [&](const auto& t) { return tab == t.first; }); - if (it == std::end(preferences_tabs)) + const auto it = std::find_if(std::begin(kPreferencesTabs), std::end(kPreferencesTabs), [&](const auto& t) { return tab == t.first; }); + if (it == std::end(kPreferencesTabs)) return AppActionRunResult{AppActionRunResult::Level::Error, from_u8("tab is required: general, files, behaviour, control, graphics, online or developer")}; - wxGetApp().open_preferences(it->second, args.value("key", std::string())); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }).input_schema = Mcp::object_schema( - {{"tab", Mcp::enum_prop(preferences_tab_names, "The tab to show.")}, - {"key", Mcp::prop("string", "With tab: a preference on that tab, e.g. auto_arrange on behaviour: its control is scrolled into view and focused.")}}); - - // ---- Screenshots and recordings ---- (the MCP screenshot and recording tools' defaults, for the person) - add_with_icon("take_screenshot", L("Take Screenshot"), L("Commands"), "screenshot", [](const json&) { - MainFrame* mf = wxGetApp().mainframe; - if (mf == nullptr) - return AppActionRunResult{}; - std::string err; - const std::optional cap = Mcp::capture_window(*mf, err); - if (!cap) - // TRN %1% is why, in English. - return AppActionRunResult{AppActionRunResult::Level::Error, format_wxstr(_L("The screenshot could not be taken: %1%"), err), false}; - const boost::filesystem::path path = - Mcp::timestamped_path(capture_folder(Mcp::load_recording_settings(*wxGetApp().app_config)), "screenshot", ".png"); - if (!cap->image.SaveFile(from_path(path), wxBITMAP_TYPE_PNG)) - return AppActionRunResult{AppActionRunResult::Level::Error, _L("The screenshot could not be saved."), false}; - notify_saved(_L("Screenshot saved"), path); - return AppActionRunResult{AppActionRunResult::Level::Succeeded, {}, true, path_reply(path)}; - }); - - // ---- Mode ---- - add_with_icon("mode_simple", L("Mode: Simple"), L("Mode"), "advanced", [](const json&) { - wxGetApp().set_mode(comSimple); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add_with_icon("mode_advanced", L("Mode: Advanced"), L("Mode"), "advanced", [](const json&) { - wxGetApp().set_mode(comAdvanced); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add_with_icon("mode_expert", L("Mode: Expert"), L("Mode"), "advanced", [](const json&) { - wxGetApp().set_mode(comExpert); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - // Mirrors Preferences > Developer > Developer mode: flip the flag, persist, refresh the UI. - add_with_icon("toggle_developer_mode", L("Toggle Developer Mode"), L("Mode"), "advanced", [](const json&) { - GUI_App& app = wxGetApp(); - const bool on = !app.app_config->get_bool("developer_mode"); - app.app_config->set_bool("developer_mode", on); - app.app_config->save(); - app.update_mode(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded, on ? _L("Developer mode enabled.") : _L("Developer mode disabled.")}; - }); - - // ---- Export pipeline ---- - // The G-code is written in the background: a call that gives the file waits for it. - tile(ui_command( - "export_gcode", L("Export G-code"), L("Slice & Export"), output_file(".gcode file"), - [](const json& args) { - Plater* plater = wxGetApp().plater(); - if (plater == nullptr) - return AppActionRunResult{}; - if (Mcp::person_form(args)) { - plater->export_gcode(false); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - } - AppActionRunResult fail; - const auto path = path_argument(args, true, fail); - if (!path) - return fail; - Ops::ExportGcodeArgs gcode; - gcode.path = *path; - if (const Ops::Outcome started = Ops::start_gcode_export(gcode); !started) - return refused(started.refusal()); - return AppActionRunResult{AppActionRunResult::Level::Info, from_u8(path->string())}; - }, - CommandCompletion::Deferred)) - .icon = "custom-gcode_gcode"; - add_with_icon("export_stl", L("Export STL"), L("Slice & Export"), "save", [](const json& args) { - Plater* plater = wxGetApp().plater(); - if (plater == nullptr) - return AppActionRunResult{}; - if (Mcp::person_form(args)) { - plater->export_stl(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - } - AppActionRunResult fail; - const auto path = path_argument(args, true, fail); - if (!path) - return fail; - return written(Ops::export_stl({*path}), *path); - }).input_schema = output_file(".stl file"); - add_with_icon("export_3mf", L("Export 3MF"), L("Slice & Export"), "menu_save", [](const json& args) { - Plater* plater = wxGetApp().plater(); - if (plater == nullptr) - return AppActionRunResult{}; - if (Mcp::person_form(args)) { - plater->export_core_3mf(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - } - AppActionRunResult fail; - const auto path = path_argument(args, true, fail); - if (!path) - return fail; - return written(Ops::export_model_3mf({*path}), *path); - }).input_schema = output_file(".3mf file"); - auto export_sliced = [](bool all) { - return [all](const json& args) { - Plater* plater = wxGetApp().plater(); - if (plater == nullptr) - return AppActionRunResult{}; - if (Mcp::person_form(args)) { - plater->export_gcode_3mf(all); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - } - AppActionRunResult fail; - const auto path = path_argument(args, true, fail); - if (!path) - return fail; - Ops::ExportSlicedArgs sliced; - sliced.path = *path; - sliced.all_plates = all; - return written(Ops::export_sliced_3mf(sliced), *path); - }; - }; - add_with_icon("export_sliced_file", L("Export Sliced File"), L("Slice & Export"), "save", export_sliced(false)).input_schema = - output_file(".gcode.3mf file"); - add_with_icon("export_all_sliced_file", L("Export All Sliced Files"), L("Slice & Export"), "save", export_sliced(true)).input_schema = - output_file(".gcode.3mf file"); - - // ---- Send to print host ---- - // The Print button's send for a printer with a print host: the Send G-code dialog, then the upload queue. Where - // the button would not send to a print host, the command says why instead of doing nothing. - add_with_icon("send_gcode", L("Send G-code to printer host"), L("Slice & Export"), "printer", [](const json&) { - if (wxGetApp().plater() == nullptr) - return AppActionRunResult{}; - if (const Ops::Outcome sent = Ops::send_gcode_to_host(); !sent) - return refused(sent.refusal()); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - - // ---- Calibration ---- - // The tab-strip calib_sf glyph is drawn white for the dark tab bar and vanishes on the palette's - // light tile, so each wizard borrows the matching settings-group icon instead (gray + accent green). - add_with_icon("calib_temperature", L("Temperature Calibration"), L("Calibration"), "param_temperature", - [](const json&) { return calib_command(CalibKind::Temperature); }); - add_with_icon("calib_max_volumetric", L("Max Volumetric Speed Calibration"), L("Calibration"), "param_volumetric_speed", - [](const json&) { return calib_command(CalibKind::MaxVolumetric); }); - add_with_icon("calib_pressure_advance", L("Pressure Advance Calibration"), L("Calibration"), "param_flow_ratio_and_pressure_advance", - [](const json&) { return calib_command(CalibKind::PressureAdvance); }); - add_with_icon("calib_flow_ratio", L("Flow Ratio Calibration"), L("Calibration"), "param_flow_ratio_and_pressure_advance", - [](const json&) { return calib_command(CalibKind::FlowRatio); }); - add_with_icon("calib_retraction", L("Retraction Calibration"), L("Calibration"), "param_retraction", - [](const json&) { return calib_command(CalibKind::Retraction); }); - add_with_icon("calib_cornering", L("Cornering Calibration"), L("Calibration"), "param_precision", - [](const json&) { return calib_command(CalibKind::Cornering); }); - add_with_icon("calib_input_shaping_freq", L("Input Shaping Frequency Calibration"), L("Calibration"), "param_resonance_avoidance", - [](const json&) { return calib_command(CalibKind::InputShapingFreq); }); - add_with_icon("calib_input_shaping_damp", L("Input Shaping Damping Calibration"), L("Calibration"), "param_resonance_avoidance", - [](const json&) { return calib_command(CalibKind::InputShapingDamp); }); - add_with_icon("calib_vfa", L("VFA Calibration"), L("Calibration"), "param_speed", [](const json&) { return calib_command(CalibKind::VFA); }); - - // ---- View ---- - // Titles are L("...")-marked here (not via a variable) so xgettext can extract them. - for (auto [key, dir, title] : - std::initializer_list>{{"view_top", "top", L("View: Top")}, - {"view_bottom", "bottom", L("View: Bottom")}, - {"view_front", "front", L("View: Front")}, - {"view_rear", "rear", L("View: Rear")}, - {"view_left", "left", L("View: Left")}, - {"view_right", "right", L("View: Right")}, - {"view_iso", "iso", L("View: Isometric")}}) { - std::string k = key, d = dir; - add(k, title, L("View"), - [d](const json&) { return view_command(wxGetApp().plater(), d); }); - } - add("view_default", L("View: Default"), L("View"), [](const json&) { - Plater* plater = wxGetApp().plater(); - if (plater) { - plater->select_view("plate"); - if (GLCanvas3D* canvas = plater->get_current_canvas3D()) - canvas->zoom_to_bed(); - } - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add("view_fit_bed", L("Fit Bed to View"), L("View"), [](const json&) { - if (Plater* plater = wxGetApp().plater()) - if (GLCanvas3D* canvas = plater->get_current_canvas3D()) - canvas->zoom_to_bed(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add("view_toggle_perspective", L("Toggle Perspective"), L("View"), [](const json&) { - if (Plater* plater = wxGetApp().plater()) - plater->get_camera().select_next_type(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add_with_icon("reset_window_layout", L("Reset Window Layout"), L("View"), "toolbar_reset", [](const json&) { - if (Plater* plater = wxGetApp().plater()) - plater->reset_window_layout(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - - // ---- Object ---- - add_with_icon("obj_delete", L("Delete Selected"), L("Object"), "delete", [](const json&) { - return object_op(wxGetApp().plater(), [](Plater* p) { return !p->is_selection_empty(); }, [](Plater* p) { p->remove_selected(); }); - }); - add_with_icon("obj_delete_all", L("Delete All Objects"), L("Object"), "delete", [](const json&) { - return object_op( - wxGetApp().plater(), [](Plater* p) { return p->can_delete_all(); }, [](Plater* p) { p->delete_all_objects_from_model(); }); - }); - add("select_all", L("Select All Objects"), L("Object"), [](const json&) { - Plater* plater = wxGetApp().plater(); - if (plater == nullptr) - return AppActionRunResult{}; - ensure_3d_view(plater); - plater->select_all(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add("deselect_all", L("Deselect All"), L("Object"), [](const json&) { - if (Plater* plater = wxGetApp().plater()) - plater->deselect_all(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add_with_icon("obj_mirror_x", L("Mirror X"), L("Object"), "menu_mirror_x", [](const json&) { - return object_op(wxGetApp().plater(), [](Plater* p) { return p->can_mirror(); }, [](Plater* p) { p->mirror(Axis::X); }); - }); - add_with_icon("obj_mirror_y", L("Mirror Y"), L("Object"), "menu_mirror_y", [](const json&) { - return object_op(wxGetApp().plater(), [](Plater* p) { return p->can_mirror(); }, [](Plater* p) { p->mirror(Axis::Y); }); - }); - add_with_icon("obj_mirror_z", L("Mirror Z"), L("Object"), "menu_mirror_z", [](const json&) { - return object_op(wxGetApp().plater(), [](Plater* p) { return p->can_mirror(); }, [](Plater* p) { p->mirror(Axis::Z); }); - }); - add_with_icon("obj_split_objects", L("Split to Objects"), L("Object"), "menu_split_objects", [](const json&) { - return object_op(wxGetApp().plater(), [](Plater* p) { return p->can_split_to_objects(); }, [](Plater* p) { p->split_object(true); }); - }); - add_with_icon("obj_split_parts", L("Split to Parts"), L("Object"), "menu_split_parts", [](const json&) { - return object_op(wxGetApp().plater(), [](Plater* p) { return p->can_split_to_volumes(); }, [](Plater* p) { p->split_volume(); }); - }); - add("obj_center", L("Center Selected on Plate"), L("Object"), [](const json&) { - return object_op(wxGetApp().plater(), [](Plater* p) { return !p->is_selection_empty(); }, [](Plater* p) { p->center_selection(); }); - }); - add_with_icon("obj_drop", L("Drop to Bed"), L("Object"), "toolbar_flatten", [](const json&) { - return object_op(wxGetApp().plater(), [](Plater* p) { return p->get_selection().can_drop(); }, [](Plater* p) { p->drop_selection(); }); - }); - add("obj_fit_volume", L("Scale to Fit Print Volume"), L("Object"), [](const json&) { - return object_op( - wxGetApp().plater(), [](Plater* p) { return p->can_scale_to_print_volume(); }, - [](Plater* p) { p->scale_selection_to_fit_print_volume(); }); - }); - add_with_icon("obj_instances_up", L("Increase Instances"), L("Object"), "instance_add", [](const json&) { - return object_op( - wxGetApp().plater(), [](Plater* p) { return p->can_increase_instances(); }, [](Plater* p) { p->increase_instances(); }); - }); - add_with_icon("obj_instances_down", L("Decrease Instances"), L("Object"), "instance_remove", [](const json&) { - return object_op( - wxGetApp().plater(), [](Plater* p) { return p->can_decrease_instances(); }, [](Plater* p) { p->decrease_instances(); }); - }); - add_with_icon("obj_arrange", L("Auto-Arrange"), L("Object"), "toolbar_arrange", [](const json&) { - return arrange_all(wxGetApp().plater()); - }); - add_with_icon("obj_orient", L("Auto-Orient"), L("Object"), "toolbar_orient", [](const json&) { - return orient_all(wxGetApp().plater()); - }); - - // ---- Object structure ---- (the object list's context menus and the plate menu's Order By) - // Change Type is in the part menus only: without part rows, set_volume_type() would change every - // part of a selected object, which no menu offers. - auto add_type = [&](std::string key, std::string title, ModelVolumeType type) { - add(std::move(key), std::move(title), L("Object"), [type](const json&) { - ObjectList* list = object_list_in_3d_view(); - if (list == nullptr) - return AppActionRunResult{}; - if (selected_rows(*list, itVolume).empty()) - return AppActionRunResult{AppActionRunResult::Level::Info, _L("Select a part first."), false}; - const wxString why = list->set_volume_type(type, true, /*show_errors=*/false); - if (!why.empty()) - return AppActionRunResult{AppActionRunResult::Level::Error, why}; - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - }; - add_type("obj_type_part", L("Change Type to Part"), ModelVolumeType::MODEL_PART); - add_type("obj_type_negative", L("Change Type to Negative Part"), ModelVolumeType::NEGATIVE_VOLUME); - add_type("obj_type_modifier", L("Change Type to Modifier"), ModelVolumeType::PARAMETER_MODIFIER); - add_type("obj_type_support_blocker", L("Change Type to Support Blocker"), ModelVolumeType::SUPPORT_BLOCKER); - add_type("obj_type_support_enforcer", L("Change Type to Support Enforcer"), ModelVolumeType::SUPPORT_ENFORCER); - add_type("obj_type_precise_seam", L("Change Type to Precise Seam"), ModelVolumeType::PRECISE_SEAM_CENTER); - add("obj_rename", L("Rename"), L("Object"), [](const json& args) { - // The Rename dialog leaves the name as it is when it is emptied, so a call has to give one. - const std::string name = args.value("name", std::string()); - if (!Mcp::person_form(args) && name.empty()) - return AppActionRunResult{AppActionRunResult::Level::Error, - from_u8("A name is needed: give the new name, or no arguments for the Rename dialog.")}; - ObjectList* list = object_list_in_3d_view(); - if (list == nullptr) - return AppActionRunResult{}; - const wxDataViewItemArray rows = selected_rows(*list, itObject | itVolume); - if (rows.size() != 1) - return AppActionRunResult{AppActionRunResult::Level::Info, _L("Select one object or part first."), false}; - if (Mcp::person_form(args)) - list->rename_item(); - else if (!list->rename_item(rows.front(), from_u8(name))) - return AppActionRunResult{AppActionRunResult::Level::Error, - _L("Invalid name, the following characters are not allowed:") + " <>:/\\|?*\""}; - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }).input_schema = Mcp::object_schema({{"name", Mcp::prop("string", "The new name, in place of the Rename dialog.")}}); - add_with_icon("obj_set_instances", L("Set Number of Instances"), L("Object"), "instance_add", [](const json& args) { - Plater* plater = wxGetApp().plater(); - ObjectList* list = object_list_in_3d_view(); - if (list == nullptr) - return AppActionRunResult{}; - // A selection to make and a job to wait for are told as information, the other reasons as errors. - const auto refused_count = [](const Ops::Refusal& refusal) { - const std::string code = refusal.code; - return refused(refusal, code == "no_object_selected" || code == "job_running" ? AppActionRunResult::Level::Info : - AppActionRunResult::Level::Error); - }; - if (Mcp::person_form(args)) { - // The asking path: the item's dialog, enabled as the menu enables it. - if (const std::optional refusal = Ops::instance_count_refusal()) - return refused_count(*refusal); - plater->set_number_of_copies(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - } - const Ops::Outcome set = Ops::set_instance_count({args.at("count").get()}); - if (!set) - return refused_count(set.refusal()); - return with_reply({{"object", set.value().object}, {"instances", set.value().instances}}); - }).input_schema = Mcp::object_schema({{"count", {{"type", "integer"}, - {"minimum", 1}, - {"description", "The total number of instances, up to 1000, in place of the dialog."}}}}); - add("obj_assemble", L("Assemble"), L("Object"), [](const json&) { - ObjectList* list = object_list_in_3d_view(); - if (list == nullptr) - return AppActionRunResult{}; - // Assemble is in the menu of two or more selected objects only; can_merge_to_multipart_object() - // alone accepts one, which merge() would replace with an "Assembly" of one. - if (selected_rows(*list, itObject | itInstance).size() < 2) - return AppActionRunResult{AppActionRunResult::Level::Info, _L("Select two or more objects first."), false}; - if (!list->can_merge_to_multipart_object()) - return AppActionRunResult{AppActionRunResult::Level::Error, _L("Cut objects can't be assembled.")}; - list->merge(true); - const ModelObjectPtrs& objects = wxGetApp().plater()->model().objects; - return with_reply({{"object", objects.size() - 1}, {"name", objects.back()->name}}); - }); - add("obj_instances_to_objects", L("Set as Individual Objects"), L("Object"), [](const json&) { - Plater* plater = wxGetApp().plater(); - ObjectList* list = object_list_in_3d_view(); - if (list == nullptr) - return AppActionRunResult{}; - if (!plater->can_set_instance_to_object()) - return AppActionRunResult{AppActionRunResult::Level::Info, _L("Select an object with more than one instance first."), false}; - const int obj_idx = plater->get_selected_object_idx(); - const size_t before = plater->model().objects.size(); - list->split_instances(); - nlohmann::json objects = nlohmann::json::array({obj_idx}); - for (size_t i = before; i < plater->model().objects.size(); ++i) - objects.push_back(i); - return with_reply({{"objects", objects}}); - }); - auto add_order = [&](std::string key, std::string title, ObjectOrder order) { - add(std::move(key), std::move(title), L("Object"), [order](const json& args) { - Plater* plater = wxGetApp().plater(); - ObjectList* list = object_list_in_3d_view(); - if (list == nullptr) - return AppActionRunResult{}; - const bool all = args.value("all", false); - if (all ? plater->model().objects.empty() : plater->get_partplate_list().get_selected_plate()->empty()) - return AppActionRunResult{AppActionRunResult::Level::Info, _L("There are no objects to order."), false}; - // order_objects() only shows a notification while a gizmo is open. - if (plater->get_view3D_canvas3D()->get_gizmos_manager().get_current_type() != GLGizmosManager::Undefined) - return AppActionRunResult{AppActionRunResult::Level::Error, _L("Error: Please close all toolbar menus first")}; - list->order_objects(order, all); - return ordered(*plater, order, all); - }).input_schema = Mcp::object_schema({{"all", Mcp::prop("boolean", "Order the objects of every plate. Default false: the current plate's.")}}); - }; - add_order("obj_order_by_name", L("Order by Name"), ObjectOrder::Name); - add_order("obj_order_by_filament", L("Order by Filament"), ObjectOrder::Filament); - add_order("obj_order_by_height", L("Order by Height"), ObjectOrder::Height); - add_order("obj_order_by_size", L("Order by Size"), ObjectOrder::Size); - - // ---- Add Primitive ---- (the Add > Add Primitive submenu; creates a new object) - // A size holds the dimensions the size dialog asks for, in its order, and skips the dialog; `size_help` names - // them. - auto add_primitive = [&](std::string key, std::string title, std::string icon, const char* type_name, const char* size_help) { - add_with_icon(std::move(key), std::move(title), L("Add Primitive"), std::move(icon), [type_name, size_help](const json& args) { - Plater* plater = wxGetApp().plater(); - ObjectList* list = wxGetApp().obj_list(); - if (plater == nullptr || list == nullptr) - return AppActionRunResult{}; - ensure_3d_view(plater); - if (!list->can_add_shape_object()) - return AppActionRunResult{AppActionRunResult::Level::Error, - _L("Deselect all objects to add a primitive object. To add a shape to the selected object, " - "use its Add Part menu.")}; - const std::vector size = args.value("size", std::vector()); - if (!Mcp::person_form(args) && !is_primitive_size(type_name, size)) - return AppActionRunResult{AppActionRunResult::Level::Error, - from_u8(std::string("The size is ") + size_help + ", each above 0.")}; - list->load_generic_subobject(type_name, ModelVolumeType::INVALID, true, size); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }).input_schema = Mcp::object_schema({{"size", Mcp::array_prop({{"type", "number"}}, std::string("The size, ") + size_help + - ", each above 0, in place of the size dialog.")}}); - }; - add_primitive("add_primitive_cube", L("Cube"), "menu_obj_cube", "Cube", "[X, Y, Z] in mm"); - add_primitive("add_primitive_cylinder", L("Cylinder"), "menu_obj_cylinder", "Cylinder", "[diameter, height] in mm"); - add_primitive("add_primitive_sphere", L("Sphere"), "menu_obj_sphere", "Sphere", "[diameter] in mm"); - add_primitive("add_primitive_cone", L("Cone"), "menu_obj_cone", "Cone", "[base diameter, height] in mm"); - add_primitive("add_primitive_disc", L("Disc"), "menu_obj_disc", "Disc", "[diameter, height] in mm"); - add_primitive("add_primitive_torus", L("Torus"), "menu_obj_torus", "Torus", "[inner diameter, tube diameter] in mm"); - add_with_icon("add_primitive_text", L("Text"), L("Add Primitive"), "menu_obj_text", [](const json&) { - Plater* plater = wxGetApp().plater(); - if (plater) { - ensure_3d_view(plater); - if (GLCanvas3D* canvas = plater->canvas3D()) - canvas->clear_popup_menu_position(); - MenuFactory::add_text_volume(ModelVolumeType::INVALID); - } - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add_with_icon("add_primitive_svg", L("SVG"), L("Add Primitive"), "menu_obj_svg", [](const json& args) { - Plater* plater = wxGetApp().plater(); - if (plater == nullptr) - return AppActionRunResult{}; - ensure_3d_view(plater); - GLCanvas3D* canvas = plater->canvas3D(); - if (canvas != nullptr) - canvas->clear_popup_menu_position(); - if (Mcp::person_form(args)) { - MenuFactory::add_svg_volume(ModelVolumeType::INVALID); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - } - // What the dialog path does once a file is picked: a new object with nothing selected, else - // a part of the selected object. - AppActionRunResult fail; - const auto path = path_argument(args, false, fail); - if (!path) - return fail; - auto* svg = canvas != nullptr ? dynamic_cast(canvas->get_gizmos_manager().get_gizmo(GLGizmosManager::Svg)) : nullptr; - if (svg == nullptr || !svg->create_volume(into_u8(from_path(*path)), ModelVolumeType::MODEL_PART)) - return AppActionRunResult{AppActionRunResult::Level::Error, _L("The SVG file could not be added.")}; - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }).input_schema = Mcp::object_schema({{"path", input_file("an .svg file")}}); - - // ---- Add Handy models ---- (the Add > Add Handy models submenu) - const std::vector& handy = MenuFactory::handy_models(); - for (std::size_t i = 0; i < handy.size(); ++i) { - add("add_handy_" + std::string(handy[i].key), handy[i].label, L("Add Handy models"), - [i](const json&) { - if (Plater* plater = wxGetApp().plater()) - ensure_3d_view(plater); - MenuFactory::load_handy_model(i); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - } - - // ---- Plate ---- - add_with_icon("plate_add", L("Add Plate"), L("Plate"), "toolbar_add_plate", [](const json&) { - Plater* plater = wxGetApp().plater(); - if (!is_fff_plater(plater)) - return plate_unavailable(); - if (!plater->can_add_plate()) - return AppActionRunResult{AppActionRunResult::Level::Info, _L("Cannot add another plate (maximum reached).")}; - plater->add_plate(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add_with_icon("plate_duplicate", L("Duplicate Plate"), L("Plate"), "menu_copy", [](const json&) { - Plater* plater = wxGetApp().plater(); - if (!is_fff_plater(plater)) - return plate_unavailable(); - if (!plater->can_add_plate()) - return AppActionRunResult{AppActionRunResult::Level::Info, _L("Cannot duplicate a plate (maximum reached).")}; - plater->duplicate_plate(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add_with_icon("plate_delete", L("Delete Plate"), L("Plate"), "delete", [](const json&) { - Plater* plater = wxGetApp().plater(); - if (!is_fff_plater(plater)) - return plate_unavailable(); - if (!plater->can_delete_plate()) - return AppActionRunResult{AppActionRunResult::Level::Info, _L("Cannot delete the only plate.")}; - plater->delete_plate(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add_with_icon("plate_rename", L("Rename Plate"), L("Plate"), "plate_name_edit", [](const json&) { - Plater* plater = wxGetApp().plater(); - if (!is_fff_plater(plater)) - return plate_unavailable(); - PartPlate* curr = plater->get_partplate_list().get_curr_plate(); - PlateNameEditDialog dlg((wxWindow*) wxGetApp().mainframe, wxID_ANY, _L("Edit Plate Name")); - dlg.set_plate_name(from_u8(curr->get_plate_name())); - if (dlg.ShowModal() == wxID_YES) - plater->rename_plate(plater->get_partplate_list().get_curr_plate_index(), dlg.get_plate_name().ToUTF8().data()); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add_with_icon("plate_toggle_lock", L("Toggle Plate Lock"), L("Plate"), "lock_normal", [](const json&) { - Plater* plater = wxGetApp().plater(); - if (!is_fff_plater(plater)) - return plate_unavailable(); - PartPlateList& plates = plater->get_partplate_list(); - Ops::SetPlateLockedArgs lock; - lock.locked = !plates.is_locked(plates.get_curr_plate_index()); - if (const Ops::Outcome locked = Ops::set_plate_locked(lock); !locked) - return refused(locked.refusal()); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add_with_icon("plate_goto", L("Go to Plate"), L("Plate"), "go_next_plate", [](const json& args) { - Plater* plater = wxGetApp().plater(); - if (!is_fff_plater(plater)) - return plate_unavailable(); - PartPlateList& plates = plater->get_partplate_list(); - const int count = plates.get_plate_count(); - if (count <= 0) - return AppActionRunResult{AppActionRunResult::Level::Info, _L("No plates available.")}; - Ops::SelectPlateArgs plate; - plate.plate = args.value("plate", plate.plate); - if (const Ops::Outcome selected = Ops::select_plate(plate); !selected) - return refused(selected.refusal()); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }).input_schema = Mcp::object_schema({{"plate", Mcp::prop("integer", "The plate's 0-based index. Default 0.")}}); - - // ---- Printer / device connection ---- - add_with_icon("sync_ams", L("Synchronize Filament List from AMS"), L("Printer"), "ams_fila_sync", [](const json&) { - Plater* plater = wxGetApp().plater(); - DeviceManager* dev = wxGetApp().getDeviceManager(); - if (dev && dev->get_selected_machine() && plater) { - plater->sidebar().sync_ams_list(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - } - return AppActionRunResult{AppActionRunResult::Level::Info, _L("Connect a printer to synchronize the AMS filament list.")}; - }); - - // ---- Filament slots ---- - // The + and - buttons above the filament list and a slot's Delete menu item. They show for printers - // that take several filaments through one extruder (Sidebar::show_SEMM_buttons()), and a G-code file - // shown in place of a project has its own filament list. - const auto filament_slots_unavailable = [](Plater* plater) -> std::optional { - if (!is_fff_plater(plater) || plater->using_exported_file()) - return AppActionRunResult{AppActionRunResult::Level::Info, _L("Filament slots belong to a filament (FFF) project, not to a G-code file.")}; - if (!Sidebar::should_show_SEMM_buttons()) - return AppActionRunResult{AppActionRunResult::Level::Info, - _L("This printer has one filament per extruder; change the number of extruders in the printer settings.")}; - return std::nullopt; - }; - add_with_icon("filament_add", L("Add Filament Slot"), L("Filament"), "add_filament", [filament_slots_unavailable](const json&) { - Plater* plater = wxGetApp().plater(); - if (const auto refused = filament_slots_unavailable(plater)) - return *refused; - const PresetBundle& bundle = *wxGetApp().preset_bundle; - if (bundle.filament_presets.size() >= MAXIMUM_EXTRUDER_NUMBER) - return AppActionRunResult{AppActionRunResult::Level::Info, _L("No more filament slots can be added.")}; - // A new physical slot goes after the physical ones; mixed filaments move up by one. - const size_t slot = bundle.num_physical_filaments() + 1; - plater->sidebar().add_filament(); - plater->sidebar().update_filaments_counter(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded, format_wxstr(_L("Added filament slot %1%."), slot)}; - }); - add_with_icon("filament_delete", L("Delete Filament Slot"), L("Filament"), "delete_filament", [filament_slots_unavailable](const json& args) { - Plater* plater = wxGetApp().plater(); - if (const auto refused = filament_slots_unavailable(plater)) - return *refused; - const PresetBundle& bundle = *wxGetApp().preset_bundle; - const size_t physical = bundle.num_physical_filaments(); - if (physical < 2) - return AppActionRunResult{AppActionRunResult::Level::Info, _L("The only filament slot cannot be deleted.")}; - // Without a slot, the last physical one, as the - button. - size_t slot = physical; - if (args.contains("filament_slot")) { - slot = args.at("filament_slot").get(); - if (slot < 1 || slot > bundle.filament_presets.size()) - return AppActionRunResult{AppActionRunResult::Level::Error, - format_wxstr(_L("Filament slot must be 1 to %1%."), bundle.filament_presets.size())}; - if (bundle.is_mixed_filament(slot - 1)) - return AppActionRunResult{AppActionRunResult::Level::Error, - format_wxstr(_L("Filament slot %1% is a mixed filament; delete it from the mixed filament list."), slot)}; - } - plater->sidebar().delete_filament(slot - 1); - plater->sidebar().update_filaments_counter(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded, format_wxstr(_L("Deleted filament slot %1%."), slot)}; - }).input_schema = Mcp::object_schema( - {{"filament_slot", {{"type", "integer"}, - {"minimum", 1}, - {"description", "The 1-based filament slot. Default: the last physical slot, as the - button."}}}}); - - // ---- Presets / cloud ---- - add_with_icon("preset_bundle", L("Open Preset Bundle"), L("Presets"), "menu_edit_preset", [](const json&) { - wxGetApp().open_presetbundledialog(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add_with_icon("sync_presets", L("Sync Presets"), L("Presets"), "printer_sync_ok", [](const json&) { - if (!wxGetApp().is_user_login()) - return AppActionRunResult{AppActionRunResult::Level::Info, _L("Sign in to sync presets.")}; - wxGetApp().restart_sync_user_preset(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - - // ---- Import ---- - add_with_icon("import_file", L("Import 3MF/STL/STEP/SVG/OBJ/AMF"), L("Import"), "menu_open", [](const json& args) { - Plater* plater = wxGetApp().plater(); - if (plater == nullptr) - return AppActionRunResult{}; - if (Mcp::person_form(args)) { -#ifdef __APPLE__ - plater->add_model(); -#else - plater->add_file(); -#endif - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - } - AppActionRunResult fail; - const auto path = path_argument(args, false, fail); - if (!path) - return fail; - Ops::ImportModelsArgs models; - models.paths = {*path}; - if (const Ops::Outcome imported = Ops::import_models(models); !imported) - return refused(imported.refusal()); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }).input_schema = Mcp::object_schema({{"path", input_file("a model file")}}); - add_with_icon("import_zip_archive", L("Import ZIP Archive"), L("Import"), "menu_open", [](const json&) { - if (Plater* plater = wxGetApp().plater()) - plater->import_zip_archive(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add_with_icon("import_configs", L("Import Configs"), L("Import"), "menu_open", [](const json& args) { - MainFrame* mf = wxGetApp().mainframe; - if (mf == nullptr) - return AppActionRunResult{}; - if (Mcp::person_form(args)) { - mf->load_config_file(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - } - AppActionRunResult fail; - const auto path = path_argument(args, false, fail); - if (!path) - return fail; - const bool overwrite = args.value("on_conflict", std::string("skip")) == "overwrite"; - const std::string file = Mcp::path_to_utf8(*path); - if (is_gcode_file(file)) { - if (!mf->load_config_file(file)) - return AppActionRunResult{AppActionRunResult::Level::Error, _L("The configuration was not loaded.")}; - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - } - for (const char* ext : {".json", ".zip", ".orca_printer", ".orca_filament", ".orca_bundle"}) - if (boost::iends_with(file, ext)) - return import_preset_file(*path, overwrite); - return AppActionRunResult{AppActionRunResult::Level::Error, - "Not a preset file: give a .json, .zip, .orca_printer, .orca_filament, .orca_bundle or .gcode"}; - }).input_schema = Mcp::object_schema( - {{"path", input_file("a preset .json, a .zip of them, an .orca_printer, .orca_filament or .orca_bundle, or a .gcode")}, - {"on_conflict", Mcp::enum_prop({"skip", "overwrite"}, "What happens to a preset that exists already. Default skip.")}}); - - // ---- Export extras ---- - // The argument of a command that writes several files, in place of its folder dialog. - const auto output_dir = Mcp::object_schema({{"path", Mcp::prop("string", "Absolute path of an existing directory to write into.")}}); - add_with_icon("export_stl_multi", L("Export All Objects as STLs"), L("Export"), "save", [](const json& args) { - Plater* plater = wxGetApp().plater(); - if (plater == nullptr) - return AppActionRunResult{}; - if (Mcp::person_form(args)) { - plater->export_stl(false, false, true); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - } - AppActionRunResult fail; - const auto dir = dir_argument(args, fail); - if (!dir) - return fail; - plater->export_stl(false, false, true, FT_STL, from_path(*dir)); - return AppActionRunResult{AppActionRunResult::Level::Succeeded, from_u8(dir->string())}; - }).input_schema = output_dir; - add_with_icon("export_drc_single", L("Export All Objects as DRC (one file)"), L("Export"), "save", [](const json&) { - if (Plater* plater = wxGetApp().plater()) - plater->export_stl(false, false, false, FT_DRC); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add_with_icon("export_drc_multi", L("Export All Objects as DRCs"), L("Export"), "save", [](const json&) { - if (Plater* plater = wxGetApp().plater()) - plater->export_stl(false, false, true, FT_DRC); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add_with_icon("export_toolpaths_obj", L("Export Toolpaths as OBJ"), L("Export"), "custom-gcode_gcode", [](const json&) { - if (Plater* plater = wxGetApp().plater()) - plater->export_toolpaths_to_obj(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add_with_icon("export_config", L("Export Preset Bundle"), L("Export"), "save", [](const json& args) { - if (Mcp::person_form(args)) { - if (MainFrame* mf = wxGetApp().mainframe) - mf->export_config(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - } - AppActionRunResult fail; - const auto dir = dir_argument(args, fail); - if (!dir) - return fail; - // The dialog MainFrame::export_config() opens, given the folder its OK writes to. - ExportConfigsDialog dlg(nullptr, from_path(*dir)); - if (dlg.ShowModal() != wxID_OK) - return AppActionRunResult{AppActionRunResult::Level::Error, _L("Nothing was exported.")}; - return AppActionRunResult{AppActionRunResult::Level::Succeeded, from_path(*dir)}; - }).input_schema = output_dir; - - // ---- Help ---- (mirrors the top-bar Help menu, plus the wiki/YouTube links) - add("help_keyboard_shortcuts", L("Keyboard Shortcuts"), L("Help"), [](const json&) { - wxGetApp().keyboard_shortcuts(ShortcutContext::Global); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add("help_setup_wizard", L("Setup Wizard"), L("Help"), [](const json&) { - wxGetApp().ShowUserGuide(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add_with_icon("help_open_config_folder", L("Show Configuration Folder"), L("Help"), "open_project", [](const json&) { - Slic3r::GUI::desktop_open_datadir_folder(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add("help_migrate_filament_presets", L("Migrate Filament Presets"), L("Help"), [](const json&) { - wxGetApp().check_legacy_user_filament_presets(true); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add("help_troubleshoot", L("Troubleshoot Center"), L("Help"), [](const json&) { - wxGetApp().troubleshoot(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add("help_network_test", L("Open Network Test"), L("Help"), [](const json&) { - NetworkTestDialog dlg(wxGetApp().mainframe); + app.open_preferences(it->second, args.value("key", std::string())); + } else if (window == "plugins") { + app.open_plugins_dialog(); + } else if (window == "action_replay") { + if (MainFrame* mf = app.mainframe) + mf->show_action_replay(); + } else if (window == "preset_bundle") { + app.open_presetbundledialog(); + } else if (window == "keyboard_shortcuts") { + app.keyboard_shortcuts(ShortcutContext::Global); + } else if (window == "setup_wizard") { + app.ShowUserGuide(); + } else if (window == "network_test") { + NetworkTestDialog dlg(app.mainframe); dlg.ShowModal(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add("help_benchmark_3d_scene", L("Benchmark 3D Scene"), L("Help"), [](const json&) { - run_scene_benchmark(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add_with_icon("help_tip_of_the_day", L("Show Tip of the Day"), L("Help"), "info", [](const json&) { - if (Plater* plater = wxGetApp().plater()) { + } else if (window == "troubleshoot") { + app.troubleshoot(); + } else if (window == "tip_of_the_day") { + if (Plater* plater = app.plater()) { plater->get_dailytips()->open(); if (GLCanvas3D* canvas = plater->get_current_canvas3D()) canvas->set_as_dirty(); } - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add_with_icon("help_check_updates", L("Check for Updates"), L("Help"), "refresh", [](const json&) { - wxGetApp().check_new_version_sf(true, 1); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add_with_icon("help_about", L("About OrcaSlicer"), L("Help"), "OrcaSlicer_gradient_circle", [](const json&) { + } else if (window == "about") { Slic3r::GUI::about(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add_with_icon("open_wiki", L("Open Wiki"), L("Help"), "link_wiki_img", [](const json&) { - wxLaunchDefaultBrowser("https://www.orcaslicer.com/wiki/", wxBROWSER_NEW_WINDOW); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add("open_youtube", L("Open YouTube Channel"), L("Help"), [](const json&) { - wxLaunchDefaultBrowser("https://www.youtube.com/@OfficialOrcaSlicer/videos", wxBROWSER_NEW_WINDOW); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); + } else { + return AppActionRunResult{AppActionRunResult::Level::Error, from_u8("Unknown window \"" + window + "\""), false}; + } + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; +} - // ---- Plugins ---- - add("open_plugins", L("Open Plugins"), L("Plugins"), [](const json&) { - wxGetApp().open_plugins_dialog(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add("refresh_plugins", L("Refresh Plugins"), L("Plugins"), [](const json&) { - wxGetApp().refresh_plugins(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add("install_plugin", L("Install Plugin"), L("Plugins"), [](const json&) { - open_plugin_hub(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - add("install_local_plugin", L("Install Local Plugin"), L("Plugins"), [](const json& args) { - MainFrame* mf = wxGetApp().mainframe; - if (mf == nullptr) - return AppActionRunResult{}; - boost::filesystem::path package; - if (Mcp::person_form(args)) { - wxFileDialog dialog(mf, _L("Select plugin package"), wxEmptyString, wxEmptyString, _L("Plugin files (*.py;*.whl)|*.py;*.whl"), - wxFD_OPEN | wxFD_FILE_MUST_EXIST); - if (dialog.ShowModal() != wxID_OK) - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - package = into_path(dialog.GetPath()); - } else { - AppActionRunResult fail; - const auto path = path_argument(args, false, fail); - if (!path) - return fail; - package = *path; - } - wxString message; - const bool installed = install_local_plugin_package(package, mf, message); - wxGetApp().update_plugins_dialog(); - if (message.IsEmpty()) // the overwrite prompt was cancelled - return AppActionRunResult{AppActionRunResult::Level::Info, _L("The plugin was not installed."), false}; - return AppActionRunResult{installed ? AppActionRunResult::Level::Succeeded : AppActionRunResult::Level::Error, message}; - }).input_schema = Mcp::object_schema({{"path", input_file("a .py or .whl plugin package")}}); +// A PNG of the main window, saved where the person's recordings go, as the MCP screenshot tool's default. +AppActionRunResult Rows::take_screenshot() +{ + MainFrame* mf = wxGetApp().mainframe; + if (mf == nullptr) + return AppActionRunResult{}; + std::string err; + const std::optional cap = Mcp::capture_window(*mf, err); + if (!cap) + // TRN %1% is why, in English. + return AppActionRunResult{AppActionRunResult::Level::Error, format_wxstr(_L("The screenshot could not be taken: %1%"), err), false}; + const boost::filesystem::path path = + Mcp::timestamped_path(capture_folder(Mcp::load_recording_settings(*wxGetApp().app_config)), "screenshot", ".png"); + if (!cap->image.SaveFile(from_path(path), wxBITMAP_TYPE_PNG)) + return AppActionRunResult{AppActionRunResult::Level::Error, _L("The screenshot could not be saved."), false}; + notify_saved(_L("Screenshot saved"), path); + return AppActionRunResult{AppActionRunResult::Level::Succeeded, {}, true, path_reply(path)}; +} - describe_commands(out); - for (NativeCommand& c : out) - catalog.add(std::move(c)); +// ---- Filaments, printers and plugins ---- +AppActionRunResult Rows::sync_ams() +{ + Plater* plater = wxGetApp().plater(); + if (plater == nullptr) + return AppActionRunResult{}; + const std::optional refusal = plater->sidebar().sync_ams_list(); + if (!refusal) + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; + // With no printer the row says so; otherwise the warning it showed said why. + if (std::string(refusal->code) == "no_printer") + return refused(*refusal, AppActionRunResult::Level::Info); + return Mcp::quiet_refusal(*refusal); +} - // The typed tools, family by family, in the order tools/list shows them: the app's state, the search and the generic - // call first, then the project data, replays, Python and recordings, and the Speed Dial and the GUI-driving tools - // last. Between them the Design tab's commands, which no listing shows, only while the CAD feature is on; the - // search's description names them then. +// The Print button's send for a printer with a print host: the Send G-code dialog, then the upload queue. Where the +// button would not send to a print host, it says why instead of doing nothing. +AppActionRunResult Rows::send_gcode() +{ + if (wxGetApp().plater() == nullptr) + return AppActionRunResult{}; + if (const Ops::Outcome sent = Ops::send_gcode_to_host(); !sent) + return refused(sent.refusal()); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; +} + +AppActionRunResult Rows::install_local_plugin(const json& args) +{ + MainFrame* mf = wxGetApp().mainframe; + if (mf == nullptr) + return AppActionRunResult{}; + boost::filesystem::path package; + // The person's form asks before it replaces a plugin installed already; a call with a path is told by overwrite. + std::optional overwrite; + if (Mcp::person_form(args)) { + wxFileDialog dialog(mf, _L("Select plugin package"), wxEmptyString, wxEmptyString, _L("Plugin files (*.py;*.whl)|*.py;*.whl"), + wxFD_OPEN | wxFD_FILE_MUST_EXIST); + if (dialog.ShowModal() != wxID_OK) + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; + package = into_path(dialog.GetPath()); + } else { + AppActionRunResult fail; + const auto path = path_argument(args, false, fail); + if (!path) + return fail; + package = *path; + overwrite = args.value("overwrite", false); + } + wxString message; + std::optional replace_refused; + const bool installed = install_local_plugin_package(package, mf, message, overwrite, &replace_refused); + wxGetApp().update_plugins_dialog(); + if (replace_refused) + return refused(*replace_refused, AppActionRunResult::Level::Error); + if (message.IsEmpty()) // the overwrite prompt was cancelled + return AppActionRunResult{AppActionRunResult::Level::Info, _L("The plugin was not installed."), false}; + return AppActionRunResult{installed ? AppActionRunResult::Level::Succeeded : AppActionRunResult::Level::Error, message}; +} + +AppActionRunResult Rows::refresh_plugins() +{ + wxGetApp().refresh_plugins(); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; +} + +// ---- Scripts ---- +AppActionRunResult Rows::toggle_run_script_panel() +{ + if (wxGetApp().mainframe != nullptr) + wxGetApp().run_script_panel().toggle(); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; +} + +namespace { + +// The headings of the places, in the order tools/list gives them. +constexpr const char* kToolsAndActions = "Tools and actions"; +constexpr const char* kTheApp = "The app"; +constexpr const char* kTheProject = "The project"; +constexpr const char* kObjects = "Objects"; +constexpr const char* kParts = "Parts"; +constexpr const char* kPlates = "Plates"; +constexpr const char* kPresets = "Presets and settings"; +constexpr const char* kFilaments = "Filaments"; +constexpr const char* kPrinters = "Printers and prints"; +constexpr const char* kPlugins = "Plugins"; +constexpr const char* kViewAndWindows = "View and windows"; +constexpr const char* kRecordings = "Recordings, replays and scripts"; +constexpr const char* kDrivingTheGui = "Driving the GUI"; +constexpr const char* kHeadingOrder[] = {kToolsAndActions, kTheApp, kTheProject, kObjects, kParts, + kPlates, kPresets, kFilaments, kPrinters, kPlugins, + kViewAndWindows, kRecordings, kDrivingTheGui}; + +// The place a command's first word names, by that word: a name is its place, then its verb. undo and redo, shared with +// the Design tab, have no place word: they are the app's. +constexpr std::pair kPlaceWords[] = { + {"tool", kToolsAndActions}, {"action", kToolsAndActions}, {"app", kTheApp}, + {"job", kTheApp}, {"preferences", kTheApp}, {"undo", kTheApp}, + {"redo", kTheApp}, {"project", kTheProject}, {"object", kObjects}, + {"part", kParts}, {"plate", kPlates}, {"calibration", kPlates}, + {"preset", kPresets}, {"settings", kPresets}, {"filament", kFilaments}, + {"printer", kPrinters}, {"print", kPrinters}, {"plugin", kPlugins}, + {"view", kViewAndWindows}, {"window", kViewAndWindows}, {"widget", kDrivingTheGui}, + {"keyboard", kDrivingTheGui}, {"mouse", kDrivingTheGui}, {"dialog", kDrivingTheGui}, + {"webview", kDrivingTheGui}, {"gizmo", kDrivingTheGui}, {"recording", kRecordings}, + {"replay", kRecordings}, {"script", kRecordings}}; + +// The commands grouped apart from their first word, looked up before it: a screenshot is a recording's still, so the +// agent's capture and the person's row are with the recordings, not with the windows. +constexpr std::pair kPlaceExceptions[] = {{"window_screenshot", kRecordings}, + {"window_save_screenshot", kRecordings}}; + +// Where `command`, in its place's group, comes in tools/list: the search, the generic call and the app's state +// first, as what an agent starts with, then the places in kHeadingOrder. +std::ptrdiff_t list_rank(const NativeCommand& command) +{ + static const char* const kFirst[] = {"tool_search", "tool_call", "app_state"}; + if (const auto first = std::find(std::begin(kFirst), std::end(kFirst), command.key); first != std::end(kFirst)) + return first - std::begin(kFirst); + const auto place = std::find_if(std::begin(kHeadingOrder), std::end(kHeadingOrder), + [&command](const char* heading) { return command.group == heading; }); + return std::ptrdiff_t(std::size(kFirst)) + (place - std::begin(kHeadingOrder)); +} + +} // namespace + +const char* NativeCommands::place_heading(const std::string& key) +{ + for (const auto& [name, heading] : kPlaceExceptions) + if (key == name) + return heading; + const std::string word = key.substr(0, key.find('_')); + for (const auto& [first, heading] : kPlaceWords) + if (word == first) + return heading; + return nullptr; +} + +void NativeCommands::register_all_commands(CommandCatalog& catalog, [[maybe_unused]] const CatalogOptions& options) +{ + // The families' commands are gathered first, so that each takes its place's group and its place in the order + // (list_rank()), whichever family declares it; a stable sort keeps a place's commands in their families' order. + // The Design tab's commands, only while the CAD feature is on, go before the GUI-driving ones; the search's + // description names them then, and undo's and redo's examples show the Design tab's history. std::string design_index; #ifdef SLIC3R_CAD if (options.cad) design_index = Mcp::design_command_index(); #endif - Mcp::register_app_tools(catalog); - Mcp::register_api_tools(catalog, design_index); - Mcp::register_project_tools(catalog); - Mcp::register_config_tools(catalog); - Mcp::register_scene_tools(catalog); - Mcp::register_layer_tools(catalog); - Mcp::register_view_tools(catalog); - Mcp::register_replay_tools(catalog); - Mcp::register_python_tools(catalog); - Mcp::register_record_tools(catalog); + // The families register into a catalog of their own, which keeps only their commands for the sort: a source or a + // left-out record added to it would be lost with it. So the plugin operations' source is added to `catalog` apart + // (register_plugin_operations()), as are the Design commands and their left-out records. + CommandCatalog families; + Mcp::register_app_tools(families, options.cad); + Mcp::register_api_tools(families, design_index); + Mcp::register_project_tools(families); + Mcp::register_config_tools(families); + Mcp::register_preference_tools(families); + Mcp::register_install_tools(families); + Mcp::register_scene_tools(families); + Mcp::register_layer_tools(families); + Mcp::register_view_tools(families); + Mcp::register_plugin_tools(families); + Mcp::register_replay_tools(families); + Mcp::register_python_tools(families); + Mcp::register_record_tools(families); + Mcp::register_action_tools(families); + Mcp::register_ui_tools(families); + + std::vector placed(families.commands().begin(), families.commands().end()); + for (NativeCommand& command : placed) { + const char* heading = place_heading(command.key); + if (heading == nullptr) + throw std::logic_error("The command " + command.key + " has no place"); + command.group = heading; + } + std::stable_sort(placed.begin(), placed.end(), + [](const NativeCommand& a, const NativeCommand& b) { return list_rank(a) < list_rank(b); }); + + Mcp::register_plugin_operations(catalog); + const auto gui = std::find_if(placed.begin(), placed.end(), [](const NativeCommand& c) { return c.group == kDrivingTheGui; }); + for (auto it = placed.begin(); it != gui; ++it) + catalog.add(std::move(*it)); #ifdef SLIC3R_CAD if (options.cad) Mcp::register_cad_commands(catalog); else Mcp::leave_out_cad_commands(catalog); #endif - Mcp::register_action_tools(catalog); - Mcp::register_ui_tools(catalog); + for (auto it = gui; it != placed.end(); ++it) + catalog.add(std::move(*it)); } namespace { @@ -1846,13 +1123,34 @@ const CommandCatalog& NativeCommands::instance() return process_catalog != nullptr ? *process_catalog : publish_catalog({}); } -std::vector NativeCommands::palette_commands(const CommandCatalog& catalog) +json NativeCommands::tile(std::string key, std::string title, std::string group, std::string icon, json args, std::string description, + std::string input, std::string input_arg) { - std::vector out; - for (const NativeCommand& c : catalog.commands()) + json item{{"key", std::move(key)}, {"title", std::move(title)}, + {"icon", std::move(icon)}, {"description", std::move(description)}, {"args", std::move(args)}}; + // Without a group of its own the item is in its command's section. + if (!group.empty()) + item["group"] = std::move(group); + if (!input.empty()) + item["input"] = std::move(input); + if (!input_arg.empty()) + item["input_arg"] = std::move(input_arg); + return item; +} + +std::vector NativeCommands::palette_tiles(const CommandCatalog& catalog) +{ + std::vector out; + for (const NativeCommand& c : catalog.commands()) { // The Design tab's tiles are there only while the tab is shown (ActionRegistry::materialize_design_actions()). - if (c.in_palette && c.group != kDesignGroup) - out.push_back(&c); + if (c.group == kDesignGroup) + continue; + if (c.in_palette) + out.push_back({&c, nullptr}); + if (c.tiles.is_array()) + for (const json& item : c.tiles) + out.push_back({&c, &item}); + } return out; } @@ -1948,20 +1246,43 @@ NativeCommand NativeCommands::long_command(std::string key, std::string title, s return c; } -NativeCommand NativeCommands::with_person_form(NativeCommand tool, std::string title, std::string group, std::string icon, - std::function person, bool person_form_behind_dialogs) +AppActionRunResult NativeCommands::refused(const Ops::Refusal& refusal, AppActionRunResult::Level level) { + AppActionRunResult result{level, refusal.translated(), false}; + result.refusal = std::make_shared(refusal); + return result; +} + +NativeCommand NativeCommands::with_person_form(NativeCommand tool, std::function person, + bool person_form_behind_dialogs) +{ + tool.input_schema = Mcp::with_silent(std::move(tool.input_schema), Mcp::person_forms(tool)); + return with_row_forms(std::move(tool), std::move(person), person_form_behind_dialogs); +} + +NativeCommand NativeCommands::with_row_forms(NativeCommand tool, std::function person, + bool person_form_behind_dialogs, std::vector own_forms) +{ + // The tiles a call's arguments are matched against, kept apart from the tool this returns. + NativeCommand forms; + forms.in_palette = tool.in_palette; + forms.tiles = tool.tiles; // The person's form runs as a ui_command() function does: in place for a person's pick, in one UI closure - // for an automated call, whose reply then says what the pick showed. - const CommandFn asks = ui_command(tool.key, title, group, Mcp::object_schema({}), [person](const json&) { return person(); }).run; - const bool checked = !person_form_behind_dialogs && tool.guard != GuardClass::Mutate; - tool.title = std::move(title); - tool.group = std::move(group); - tool.icon = std::move(icon); - tool.in_palette = true; - tool.input_schema = Mcp::with_silent(std::move(tool.input_schema)); - tool.run = [key = tool.key, person = std::move(person), asks, checked, silent = std::move(tool.run)](const json& args, ToolContext& ctx) { - if (!Mcp::person_form(args)) + // for an automated call, whose reply then says what the pick showed. It is given the tile's arguments, {} for + // the tool's own tile. + const auto given = [](const json& args) { return Mcp::person_form(args) ? json::object() : args; }; + const CommandFn asks = ui_command(tool.key, tool.title, tool.group, Mcp::object_schema({}), + [person, given](const json& args) { return person(given(args)); }) + .run; + const bool checked = !person_form_behind_dialogs && tool.guard != GuardClass::Mutate; + tool.run = [key = tool.key, forms = std::move(forms), own_forms = std::move(own_forms), person = std::move(person), given, asks, + checked, silent = std::move(tool.run)](const json& args, ToolContext& ctx) { + const bool own = std::find(own_forms.begin(), own_forms.end(), given(args)) != own_forms.end(); + // A person's pick of a tile whose row is the tool's own function, or of a tile that collects a value, runs that + // function in place, as a row does: no job. + if (ctx.person() && (own || tile_with_input(forms, args) != nullptr)) + return asks(args, ctx); + if (own || !Mcp::person_form(forms, args)) return silent(args, ctx); if (!checked || ctx.person()) return asks(args, ctx); @@ -1969,9 +1290,9 @@ NativeCommand NativeCommands::with_person_form(NativeCommand tool, std::string t // opens, so it is refused while a modal dialog is open or another call's nested loop runs, in the UI // closure that runs it. Mcp::UiInvoker& ui = ctx.runtime().ui(); - return ui_command(key, {}, {}, Mcp::object_schema({}), [&person, &ui](const json&) { + return ui_command(key, {}, {}, Mcp::object_schema({}), [&person, &ui, &given](const json& tile_args) { ui.require_mutate(); - return person(); + return person(given(tile_args)); }).run(args, ctx); }; return tool; diff --git a/src/slic3r/GUI/NativeCommands.hpp b/src/slic3r/GUI/NativeCommands.hpp index 912bf08582..e58c4cb58e 100644 --- a/src/slic3r/GUI/NativeCommands.hpp +++ b/src/slic3r/GUI/NativeCommands.hpp @@ -14,6 +14,10 @@ namespace Slic3r { namespace GUI { +namespace Ops { +struct Refusal; +} + namespace NativeCommands { // Which optional families of commands the process catalog holds. cad: the Design tab is on in this run, so the // catalog holds its commands (in a build with CAD; a build without it has none). @@ -22,16 +26,26 @@ struct CatalogOptions bool cad = false; }; -// Adds the built-in commands to `catalog`: the Speed Dial's, each with in_palette, then the typed tools, each -// listed, family by family (Mcp::register_app_tools() and the others), and with options.cad the Design tab's -// (Mcp::register_cad_commands()), not listed, of which those with an action have a tile the Speed Dial shows -// in the Design tab; without it, in a build with CAD, it records that it leaves them out and why -// (Mcp::leave_out_cad_commands()). new_project, save_project, start_recording and stop_recording are both: -// typed tools with a tile (with_person_form()). undo and redo act on the Design tab's history or the -// project's, a person's pick as the Edit menu's item does; with options.cad their examples show the Design -// tab's. +// Adds the built-in commands to `catalog`, family by family (Mcp::register_app_tools() and the others): the typed +// tools and the commands made from menu rows (Rows, NativeCommandRows.hpp), whose rows are their tiles, eight of them +// with a tile of their own (in_palette). Each is in the group of its place (place_heading()) and is listed, as it runs +// from its arguments, but for the three rows that take none (window_save_screenshot, script_toggle_panel, +// settings_toggle_developer_mode). They come in the order tools/list gives them: tool_search, tool_call and app_state, +// then place by place (Tools and actions, The app, The project, Objects, Parts, Plates and on), each place's commands +// in the order their families declare them, and Driving the GUI last. Before Driving the GUI, with options.cad, the Design tab's commands +// (Mcp::register_cad_commands()), not listed, of which those with an action have a tile the Speed Dial shows in the +// Design tab; without it, in a build with CAD, it records that it leaves them out and why +// (Mcp::leave_out_cad_commands()). undo and redo act on the Design tab's history or the project's, a person's pick +// as the Edit menu's item does; with options.cad their examples show the Design tab's. Also adds the source of the +// operations the loaded plugins offer (Mcp::register_plugin_operations()). void register_all_commands(CommandCatalog& catalog, const CatalogOptions& options); +// The heading of the place a command outside the Design tab is under, its group, an English text tool_search filters +// by: the place its name's first word names (object_mirror: Objects; undo and redo: The app), or for the two +// screenshot commands, which are grouped with the recordings and not with the windows, Recordings, replays and +// scripts. nullptr for a key whose first word is no place. +const char* place_heading(const std::string& key); + // Builds and seals the process catalog. UI thread, once, at startup; a second call, or a call after // instance() built the catalog by itself, throws std::logic_error. void build(const CatalogOptions& options); @@ -42,10 +56,26 @@ void build(const CatalogOptions& options); // switch. Any thread. const CommandCatalog& instance(); -// The commands a person picks from the Speed Dial whatever tab is shown: those with in_palette, in the order -// they were added, but the Design tab's (group kDesignGroup), whose tiles the Speed Dial has only while that tab -// is shown (ActionRegistry::materialize_design_actions()). -std::vector palette_commands(const CommandCatalog& catalog); +// An item of a command's `tiles`: a menu row folded into the command, which runs it with `args`. `title` and `group` +// (its Speed Dial section) are untranslated msgids, L()-marked by the caller. `input` is the Speed Dial's token for +// the value the row's second phase collects ("percent", "tab"), and `input_arg` the command's argument that value +// goes to where it is not named as the token. The item has `group`, `input` and `input_arg` only when they are +// given: without a group it is in its command's section. +nlohmann::json tile(std::string key, std::string title, std::string group, std::string icon, nlohmann::json args, + std::string description, std::string input = {}, std::string input_arg = {}); + +// A tile a person picks from the Speed Dial: `command`'s own (in_palette) when `tile` is null, else the item of its +// tiles `tile` points at. +struct PaletteTile +{ + const NativeCommand* command; + const nlohmann::json* tile; +}; + +// The tiles a person picks from the Speed Dial whatever tab is shown, in the order their commands were added, a +// command's own first and then each item of its tiles: all but the Design tab's (group kDesignGroup), which the +// Speed Dial has only while that tab is shown (ActionRegistry::materialize_design_actions()). +std::vector palette_tiles(const CommandCatalog& catalog); // A command whose function runs on the UI thread and says what a person's pick shows. Its run: for a // person's pick (ToolContext::person()), `fn(args)` in place, its result as the reply's notice. For an @@ -63,28 +93,43 @@ NativeCommand ui_command(std::string key, std::string title, std::string group, NativeCommand long_command(std::string key, std::string title, std::string group, nlohmann::json schema, CommandFn fn, bool inline_call = false); -// A typed tool that a person picks too: `tool` with the tile's `title`, `group` and `icon`, in_palette, and its -// schema through Mcp::with_silent(). Its run, called with no arguments, is the person's form: `person` on the -// UI thread, as ui_command() runs a function. Called with arguments, or silent: true, it is the tool's own -// function, given the arguments as they are, silent included, so that what the function journals keeps it. -// An agent's call of the person's form is refused while a modal dialog is open or another call's nested loop -// runs (Mcp::UiInvoker::require_mutate()), also where the tool's guard lets it run behind dialogs, unless -// `person_form_behind_dialogs` says the form opens nothing and may run where the tool does. -NativeCommand with_person_form(NativeCommand tool, std::string title, std::string group, std::string icon, - std::function person, bool person_form_behind_dialogs = false); +// A typed tool that a person picks too: `tool`, which has its tiles already (its own, in_palette, or items of its +// tiles), with its person's forms (Mcp::person_forms()): {} for its own tile, and the args of each item that collects +// no value. A call that is one of them (Mcp::person_form(tool, args)) is the person's form: `person` given those +// arguments, on the UI thread, as ui_command() runs a function. Any other call is the tool's own function, given the +// arguments as they are. `own_forms` are the tiles whose row does what the tool does (view_set's camera tiles): an +// automated call whose arguments, null as {}, are one of them is the tool's own function, and a person's pick of one +// is `person`, which runs the same function in place; they stay person's forms (Mcp::person_form()) for what reads a +// call as a tile's. A person's pick of a tile that collects a value is `person` too, given the tile's call (its args +// and the value), while an automated call of it is the tool's. An agent's call of the person's form is refused while a +// modal dialog is open or another call's nested loop runs (Mcp::UiInvoker::require_mutate()), also where the tool's +// guard lets it run behind dialogs, unless `person_form_behind_dialogs` says the form opens nothing and may run where +// the tool does. The tool's schema stays as it is: it takes its tiles' arguments, and its own function needs nothing a +// tile leaves out. +NativeCommand with_row_forms(NativeCommand tool, std::function person, + bool person_form_behind_dialogs = false, std::vector own_forms = {}); +// with_row_forms() for a tool whose own function requires what its person's forms leave out (a path a dialog asks +// for): its schema goes through Mcp::with_silent() with them, so it also takes silent: true, and a call with silent is +// the tool's own function, given silent with the other arguments, so that what the function journals keeps it. +NativeCommand with_person_form(NativeCommand tool, std::function person, + bool person_form_behind_dialogs = false); -// The person's forms of start_recording and stop_recording. UI thread. +// The person's forms of recording_start and recording_stop. UI thread. // The Start Recording dialog, with the settings it remembers, and the person's recording it starts: the main // window, with the overlays the settings ask for, for up to an hour, into the folder the settings name. AppActionRunResult start_person_recording(); // Stops the running recording, whoever started it, without waiting for its file, and shows the person a // notification naming it; the reply has its path. AppActionRunResult stop_recording_in_app(); -// What the person's forms of save_project and save_project_as answer for Plater::save_project()'s `answer`. +// What the person's forms of project_save, {} and {"save_as": true}, answer for Plater::save_project()'s `answer`. // A save that wrote nothing (a dialog cancelled, the file not written) did nothing: the person, who answered // or read its dialog, is shown nothing more, and automation gets Ops::project_not_saved(). AppActionRunResult project_save_result(int answer); +// What a command answers when an operation, or the shared function a pick runs, refuses: the refusal in the UI's +// language, shown at `level`, as a command that did nothing; automation reads the refusal itself (from_run_result()). +AppActionRunResult refused(const Ops::Refusal& refusal, AppActionRunResult::Level level = AppActionRunResult::Level::Error); + // What a command's result replies to an automated call: {"ran": key, "level", "message"?} with the fields // of its `reply`. It is an error for a Busy or Error level and for a command that did nothing; an operation's // refusal is worded in English, with {"code", "names"?} as the error's details. @@ -117,13 +162,17 @@ const NativeCommand* find(const std::string& key); // own (title_context()). UI thread only. wxString tile_title(const NativeCommand& command); -// Materialises one catalog entry as a runnable AppAction, titled tile_title() with the English title/group -// kept as search aliases. Keeps the catalog's identity, presentation and behaviour as the single source of -// truth; ActionRegistry only stores and dispatches the result. UI thread only. +// Materialises the own tile of one catalog entry as a runnable AppAction, titled tile_title() with the English title +// and section kept as search aliases; its section is the command's tile_group, or its group where that is empty. A +// Design command's takes the command's arguments; any other's takes none, its preset {}, as an item of tiles with no +// arguments does. Keeps the catalog's identity, presentation and behaviour as the single source of truth; ActionRegistry only stores +// and dispatches the result. The action runs `command`, which outlives it. UI thread only. std::unique_ptr make_action(const NativeCommand& command); // The action of `tile`, one of `command`'s tiles (NativeCommand::tiles): the id of its key, its title translated -// in the command's title_context(), its icon and description, no arguments to show an agent, and its args as the -// preset the action runs the command with, for a person's pick and run_action alike. UI thread only. +// in the command's title_context(), its section (the tile's group, else the command's), its icon and description, +// and its args as the preset. A tile that collects a value takes that value alone, under its input token, typed as +// the command's argument it goes to; any other shows an agent no arguments. Either runs the command with +// tile_call_args() (CommandCatalog.hpp), for a person's pick and action_run alike. UI thread only. std::unique_ptr make_action(const NativeCommand& command, const nlohmann::json& tile); } // namespace NativeCommands diff --git a/src/slic3r/GUI/Operations/ExportOps.cpp b/src/slic3r/GUI/Operations/ExportOps.cpp index a56da4a16a..29d205a335 100644 --- a/src/slic3r/GUI/Operations/ExportOps.cpp +++ b/src/slic3r/GUI/Operations/ExportOps.cpp @@ -23,6 +23,7 @@ #include #include #include +#include #include @@ -30,12 +31,14 @@ namespace Slic3r { namespace GUI { namespace Ops { namespace { +Refusal file_not_written() { return {RefusalKind::Failed, "file_not_written", L("The file was not written.")}; } + // The one success check of an export that writes its file before it returns. Outcome written(const boost::filesystem::path& path) { boost::system::error_code ec; if (!boost::filesystem::exists(path, ec)) - return Refusal{RefusalKind::Failed, "file_not_written", L("The file was not written.")}; + return file_not_written(); return Done{}; } @@ -126,15 +129,60 @@ Outcome export_model_3mf(const ExportFileArgs& args) return written(args.path); } -Outcome export_stl(const ExportFileArgs& args) +std::optional export_objects_refusal(const std::string& format, const std::vector& objects, bool per_object, + const Model& model) +{ + if (!objects.empty() && format != "stl" && format != "drc") + // TRN %1% is a file format, as project_export names it: gcode, sliced_3mf, 3mf or toolpaths_obj. + return Refusal{RefusalKind::Precondition, "objects_not_taken", L("Only an STL or a DRC export takes objects, not %1%."), {format}}; + if ((per_object || !objects.empty()) && model.objects.empty()) + return no_objects(); + for (int object : objects) + if (object < 0 || object >= int(model.objects.size())) + // TRN %1% is the object index asked for, %2% the index of the project's last object. + return Refusal{RefusalKind::Precondition, "no_such_object", L("Object %1% does not exist (the project has objects 0..%2%)"), + {std::to_string(object), std::to_string(model.objects.size() - 1)}}; + return std::nullopt; +} + +Outcome> export_stl(const ExportStlArgs& args) { assert(wxThread::IsMain()); Plater& plater = *wxGetApp().plater(); if (plater.model().objects.empty()) return no_objects(); + if (std::optional refusal = export_objects_refusal(args.draco ? "drc" : "stl", args.objects, args.per_object, plater.model())) + return *refusal; if (std::optional refusal = select_named_plate(args.plate)) return *refusal; - plater.export_stl(false, false, false, FT_STL, from_path(args.path)); + std::vector files; + for (const std::string& file : + plater.export_stl(false, false, args.per_object, args.draco ? FT_DRC : FT_STL, from_path(args.path), args.objects)) { + files.push_back(into_path(from_u8(file))); + if (!written(files.back())) + return file_not_written(); + } + if (files.empty()) + return file_not_written(); + return files; +} + +std::optional toolpaths_refusal() +{ + assert(wxThread::IsMain()); + const Plater& plater = *wxGetApp().plater(); + if (plater.printer_technology() != ptFFF || !plater.is_preview_loaded() || !plater.has_toolpaths_to_export()) + return Refusal{RefusalKind::Precondition, "no_toolpaths", + L("The Preview shows no toolpaths. Slice the plate and show it in the Preview first.")}; + return std::nullopt; +} + +Outcome export_toolpaths_obj(const ExportToolpathsArgs& args) +{ + assert(wxThread::IsMain()); + if (std::optional refusal = toolpaths_refusal()) + return *refusal; + wxGetApp().plater()->export_toolpaths_to_obj(from_path(args.path)); return written(args.path); } diff --git a/src/slic3r/GUI/Operations/ExportOps.hpp b/src/slic3r/GUI/Operations/ExportOps.hpp index 5272e245a4..f32b19a4e9 100644 --- a/src/slic3r/GUI/Operations/ExportOps.hpp +++ b/src/slic3r/GUI/Operations/ExportOps.hpp @@ -8,6 +8,11 @@ #include #include #include +#include + +namespace Slic3r { +class Model; +} // Writing the project or its G-code to a file the caller names, without a file dialog. namespace Slic3r { namespace GUI { namespace Ops { @@ -59,9 +64,40 @@ struct ExportFileArgs // too: one that holds only a Design-tab recipe has none. // Refuses: no_such_plate, plate_not_selected, file_not_written. Outcome export_model_3mf(const ExportFileArgs& args); -// Writes all objects as one STL. -// Refuses: no_objects, no_such_plate, plate_not_selected, file_not_written. -Outcome export_stl(const ExportFileArgs& args); + +// What keeps an export in `format` (gcode, sliced_3mf, 3mf, stl, drc or toolpaths_obj) of `objects` (indices in `model`; +// none: every object), or of a file per object with `per_object`, from being written, or none: objects named for a +// format that writes no objects of its own choosing (objects_not_taken), objects named, or a file per object, in a +// project with none (no_objects), and an index the project lacks (no_such_object). +std::optional export_objects_refusal(const std::string& format, const std::vector& objects, bool per_object, + const Model& model); + +struct ExportStlArgs +{ + boost::filesystem::path path; // the file, or with per_object an existing folder + std::optional plate; // made the current plate first; the files hold objects of every plate + std::vector objects; // their indices; none: every object + bool per_object = false; // a file per object, named after it, into the folder + bool draco = false; // Draco (.drc) files in place of STL +}; +// Writes objects as one STL or Draco file, as File > Export writes every object, or each into a file of its own, as +// Export All Objects as STLs does and the object menu's Export as STLs does for the objects selected +// (Plater::export_stl()). A file per object is named after it, with a number added where the folder has that name. +// Returns the files written. +// Refuses: no_objects, what export_objects_refusal() gives, no_such_plate, plate_not_selected, file_not_written. +Outcome> export_stl(const ExportStlArgs& args); + +// What keeps the toolpaths from being written as an OBJ, or none: none loaded in the Preview (no_toolpaths), which +// shows a plate's toolpaths once the plate is sliced and the Preview has been shown. +std::optional toolpaths_refusal(); + +struct ExportToolpathsArgs +{ + boost::filesystem::path path; +}; +// Writes the toolpaths the Preview shows as an OBJ, as Export Toolpaths as OBJ does. +// Refuses: no_toolpaths, file_not_written. +Outcome export_toolpaths_obj(const ExportToolpathsArgs& args); struct SendGcodeToHostArgs {}; diff --git a/src/slic3r/GUI/Operations/InstallOps.cpp b/src/slic3r/GUI/Operations/InstallOps.cpp new file mode 100644 index 0000000000..6560b9696e --- /dev/null +++ b/src/slic3r/GUI/Operations/InstallOps.cpp @@ -0,0 +1,923 @@ +#include "InstallOps.hpp" + +#include "Outcome.hpp" +#include "PresetOps.hpp" + +#include "slic3r/GUI/GUI.hpp" +#include "slic3r/GUI/GUI_App.hpp" +#include "slic3r/GUI/I18N.hpp" +#include "slic3r/GUI/MainFrame.hpp" +#include "slic3r/GUI/Plater.hpp" +#include "slic3r/GUI/Tab.hpp" +#include "slic3r/GUI/UnsavedChangesDialog.hpp" + +#include "libslic3r/AppConfig.hpp" +#include "libslic3r/Config.hpp" +#include "libslic3r/Preset.hpp" +#include "libslic3r/PresetBundle.hpp" +#include "libslic3r/PresetCacheFormat.hpp" +#include "libslic3r/PrintConfig.hpp" +#include "libslic3r/Semver.hpp" +#include "libslic3r/Utils.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace Slic3r { namespace GUI { namespace Ops { + +using nlohmann::json; + +namespace { + +std::string lower(std::string s) +{ + std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return char(std::tolower(c)); }); + return s; +} + +// A string member of a JSON object, empty where it has none. +std::string text(const json& object, const char* key) +{ + const auto it = object.find(key); + return it != object.end() && it->is_string() ? it->get() : std::string(); +} + +// The nozzles of a model as the dialog's data lists them, "0.4;0.6". +std::vector split_nozzles(const std::string& list) +{ + std::vector nozzles; + std::size_t start = 0; + while (start <= list.size()) { + const std::size_t end = std::min(list.find(';', start), list.size()); + std::string nozzle = boost::algorithm::trim_copy(list.substr(start, end - start)); + if (!nozzle.empty()) + nozzles.push_back(std::move(nozzle)); + start = end + 1; + } + return nozzles; +} + +Refusal no_such_vendor(const std::string& vendor, std::vector vendors) +{ + return {RefusalKind::Precondition, "no_such_vendor", L("No printer vendor is called \"%1%\"."), {vendor}, + closest_names(std::move(vendors), vendor)}; +} + +// The vendors of the models `profile` lists, each once. +std::vector profile_vendors(const json& profile) +{ + std::set vendors; + if (const auto models = profile.find("model"); models != profile.end() && models->is_array()) + for (const json& entry : *models) + if (entry.is_object()) + vendors.insert(text(entry, "vendor")); + vendors.erase(std::string()); + return {vendors.begin(), vendors.end()}; +} + +std::size_t nozzle_count(const InstallSet& set) +{ + std::size_t count = 0; + for (const auto& [vendor, models] : set.printers) + for (const auto& [model, nozzles] : models) + count += nozzles.size(); + return count; +} + +// The Transfer of the prompt about unsaved changes that a Confirm opens (GUI_App::check_and_keep_current_preset_changes()) +// with every change it lists ticked: each tab caches what it lists of its preset's changes, and the printer tab the +// extruder count where that changed, for GUI_App::apply_keeped_preset_modifications() to put on the presets the reload +// selects. +void cache_listed_changes() +{ + GUI_App& app = wxGetApp(); + const PrinterTechnology technology = app.preset_bundle->printers.get_edited_preset().printer_technology(); + for (Tab* tab : app.tabs_list) { + if (!tab->supports_printer_technology(technology) || !tab->current_preset_is_dirty()) + continue; + const PresetCollection& presets = *tab->get_presets(); + std::vector keys; + for (const std::string& option : listed_dirty_options(presets)) + if (std::string key = option.substr(0, option.find('#')); std::find(keys.begin(), keys.end(), key) == keys.end()) + keys.push_back(std::move(key)); + if (tab->type() == Preset::TYPE_PRINTER && technology == ptFFF) { + const auto* saved = presets.get_selected_preset().config.option("nozzle_diameter"); + const auto* edited = presets.get_edited_preset().config.option("nozzle_diameter"); + if (saved != nullptr && edited != nullptr && saved->values.size() != edited->values.size()) + static_cast(tab)->cache_extruder_cnt(); + } + tab->cache_config_diff(keys); + } +} + +// The system presets of `presets` the selectors offer. +std::vector offered(const PresetCollection& presets) +{ + std::vector names; + for (const Preset& preset : presets) + if (preset.is_system && preset.is_visible) + names.push_back(preset.name); + return names; +} + +// Whether the selectors offer a system printer preset of `vendor`'s `model` with `nozzle`. +bool offers_printer(const PresetBundle& bundle, const std::string& vendor, const std::string& model, const std::string& nozzle) +{ + for (const Preset& preset : bundle.printers) + if (preset.is_system && preset.is_visible && preset.vendor != nullptr && preset.vendor->id == vendor && + preset.config.opt_string("printer_model") == model && preset.config.opt_string("printer_variant") == nozzle) + return true; + return false; +} + +// The names of `a` that `b` lacks, in `a`'s order. +std::vector missing_from(const std::vector& a, const std::vector& b) +{ + std::vector out; + for (const std::string& name : a) + if (std::find(b.begin(), b.end(), name) == b.end()) + out.push_back(name); + return out; +} + +Outcome change_printers(const InstallPrintersArgs& args, bool install) +{ + assert(wxThread::IsMain()); + const Outcome> resolved = resolve_models(args.known, args.models); + if (!resolved) + return resolved.refusal(); + const InstallSet installed = installed_set(); + if (!install) + if (std::optional refusal = uninstall_refusal(installed, resolved.value())) + return *refusal; + const InstallSet changed = install ? changed_install_set(installed, resolved.value(), {}) : + changed_install_set(installed, {}, resolved.value()); + + GUI_App& app = wxGetApp(); + PresetBundle& bundle = *app.preset_bundle; + InstalledPrinters out; + out.models = resolved.value(); + if (changed.printers != installed.printers) { + // The reload drops the presets' unsaved changes, which the Confirm asks about; a call says what becomes of them. + if (args.changes == PresetChanges::Ask && app.has_current_preset_changes()) + return Refusal{RefusalKind::Precondition, "unsaved_preset_changes", + L("The presets have unsaved changes, which reloading the presets would drop.")}; + const std::vector before = offered(bundle.printers), filaments_before = offered(bundle.filaments); + const bool discards = args.changes == PresetChanges::Discard && app.has_current_preset_changes(); + try { + const Outcome applied = apply_install_set(changed, args.changes); + if (!applied && applied.refusal().code == std::string("vendors_not_installed")) + // The answer about the unsaved changes and the copies of the bundles came before the failure. + return Refusal{RefusalKind::Failed, "vendors_not_installed", + discards ? L("The printer profiles could not be installed, so the installed printers are as they " + "were, but the presets' unsaved changes were discarded. Vendor profiles copied " + "before the failure stay in the configuration folder.") : + L("The printer profiles could not be installed, so the installed printers are as they " + "were. Vendor profiles copied before the failure stay in the configuration folder.")}; + if (!applied) + return applied.refusal(); + } catch (const std::exception& e) { + BOOST_LOG_TRIVIAL(error) << "install_printers: reloading the presets failed: " << e.what(); + return Refusal{RefusalKind::Failed, "presets_not_reloaded", + // TRN %1% is the error's own text. + L("The installed printers were changed, but reloading the presets failed: %1%"), {e.what()}}; + } + // What a person's Confirm refreshes once the dialog has closed (GUI_App::run_wizard()), and the app configuration + // written, so that the change is kept however the app ends. + app.load_current_presets(); + app.update_publish_status(); + if (app.mainframe != nullptr) + app.mainframe->refresh_plugin_tips(); + app.app_config->save(); + const std::vector after = offered(bundle.printers), filaments_after = offered(bundle.filaments); + out.added = missing_from(after, before); + out.removed = missing_from(before, after); + out.filaments_installed = missing_from(filaments_after, filaments_before); + out.filaments_uninstalled = missing_from(filaments_before, filaments_after); + } + out.selected = bundle.printers.get_selected_preset_name(); + for (const ModelNozzles& model : out.models) { + ModelNozzles left{model.vendor, model.model, {}}; + for (const std::string& nozzle : model.nozzles) + if (offers_printer(bundle, model.vendor, model.model, nozzle) != install) + left.nozzles.push_back(nozzle); + if (!left.nozzles.empty()) + out.missing.push_back(std::move(left)); + } + return out; +} + +// Whether the filaments section `section` installs `preset`: by its name, or by a name it was renamed from, as +// Preset::set_visible_from_appconfig() reads it. +bool installs(const std::map& section, const Preset& preset) +{ + const auto has = [§ion](const std::string& name) { + const auto it = section.find(name); + return it != section.end() && !it->second.empty(); + }; + return has(preset.name) || std::any_of(preset.renamed_from.begin(), preset.renamed_from.end(), has); +} + +Outcome change_filaments(const InstallFilamentsArgs& args, bool install) +{ + assert(wxThread::IsMain()); + GUI_App& app = wxGetApp(); + PresetBundle& bundle = *app.preset_bundle; + AppConfig& config = *app.app_config; + const Outcome> named = filaments_named(loaded_filaments(), args); + if (!named) + return named.refusal(); + if (!install) + if (std::optional refusal = filament_uninstall_refusal(named.value(), bundle.filament_presets)) + return *refusal; + + // Without the section every filament is installed: an install changes nothing, and an uninstall writes the section + // with every system filament the selectors offer, so that the others stay installed. + std::map section = installed_set_from(config, offered(bundle.filaments)).filaments; + + InstalledFilaments out; + std::vector edited; + for (const std::string& name : named.value()) { + const Preset* preset = bundle.filaments.find_preset(name, false); + if (preset == nullptr) + continue; + if (installs(section, *preset) == install) { + out.unchanged.push_back(name); + continue; + } + if (install) { + section[name] = "true"; + } else { + section.erase(name); + for (const std::string& old_name : preset->renamed_from) + section.erase(old_name); + } + edited.push_back(preset); + } + if (edited.empty()) + return out; + + // What is installed then is the app's rule, as the next start applies it: an installed printer that no installed + // filament fits gets its default filaments again, into the section, and every filament is shown as the section says. + // The rule takes the printers shown for installed, as they are at a start, where load_selections() has just shown + // the installed ones (PresetBundle::load_installed_printers()). A running app also shows printers it does not + // install, for this session only: one selected while not installed, a bound one in the sidebar's list. Those are + // hidden while the rule runs and shown again after it, so that the section gets no filament for them. + config.set_section(AppConfig::SECTION_FILAMENTS, section); + { + std::vector shown; + for (const Preset& printer : bundle.printers) + shown.push_back(printer.is_visible); + ScopeGuard show_again([&bundle, &shown] { + size_t i = 0; + for (Preset& printer : bundle.printers) + printer.is_visible = shown[i++]; + }); + // What load_installed_printers() does to the printers, without its rebuild of the alias and rename maps, which + // counts a duplicate rename as a load error again. + for (Preset& printer : bundle.printers) + printer.set_visible_from_appconfig(config); + bundle.load_installed_filaments(config); + } + // A filament a slot holds stays shown, installed or not, as the slot's selector shows it + // (PlaterPresetComboBox::update()); the tabs' selectors are refreshed before the slots' are. + for (const std::string& name : bundle.filament_presets) + if (Preset* preset = bundle.filaments.find_preset(name, false); preset != nullptr) + preset->is_visible = true; + const std::map result = config.get_section(AppConfig::SECTION_FILAMENTS); + for (const Preset* preset : edited) + if (installs(result, *preset) == install) + out.changed.push_back(preset->name); + for (const Preset& preset : bundle.filaments) + if (preset.is_system && !installs(section, preset) && installs(result, preset)) + out.defaults_installed.push_back(preset.name); + config.save(); + if (app.mainframe != nullptr) + app.mainframe->update_side_preset_ui(); + return out; +} + +} // namespace + +// ---- Printer models ---- + +json profile_data_from(const PresetBundle& bundle) +{ + json data{{"model", json::array()}, {"machine", json::object()}, {"filament", json::object()}, {"process", json::array()}}; + + // Models from vendor profiles + for (const auto& [vendor_id, vp] : bundle.vendors) { + for (const auto& model : vp.models) { + std::string nozzle_str; + for (const auto& v : model.variants) { + if (!nozzle_str.empty()) + nozzle_str += ";"; + nozzle_str += v.name; + } + const std::string materials_str = boost::algorithm::join(model.default_materials, ";"); + boost::filesystem::path cover_path = + (boost::filesystem::path(resources_dir()) / "profiles" / vp.id / (model.id + "_cover.png")).make_preferred(); + if (!boost::filesystem::exists(cover_path)) + cover_path = (boost::filesystem::path(resources_dir()) / "web/image/printer" / (model.id + "_cover.png")).make_preferred(); + + json entry; + entry["model"] = model.id; + entry["name"] = model.name; + entry["vendor"] = vp.id; + entry["nozzle_diameter"] = nozzle_str; + entry["materials"] = materials_str; + entry["cover"] = into_u8(file_url_from_path(cover_path)); + entry["nozzle_selected"] = ""; + entry["sub_path"] = ""; + data["model"].push_back(entry); + } + } + + // Machine map: preset name -> {model, nozzle variant} + for (const Preset& p : bundle.printers()) { + if (!p.is_system || !p.vendor) + continue; + const auto* printer_model = p.config.option("printer_model"); + const auto* printer_variant = p.config.option("printer_variant"); + if (!printer_model || printer_model->value.empty() || !printer_variant) + continue; + + json mach; + mach["model"] = printer_model->value; + mach["nozzle"] = printer_variant->value; + data["machine"][p.name] = mach; + } + + // Filament map from system filament presets (vendor/type already resolved in config) + const json& machines = data["machine"]; + for (const Preset& p : bundle.filaments()) { + if (!p.is_system || !p.vendor) + continue; + const auto* fila_vendor = p.config.option("filament_vendor"); + const auto* fila_type = p.config.option("filament_type"); + const auto* compat_printers = p.config.option("compatible_printers"); + + std::string vendor = (fila_vendor && !fila_vendor->values.empty()) ? fila_vendor->values[0] : ""; + std::string type = (fila_type && !fila_type->values.empty()) ? fila_type->values[0] : ""; + + std::string model_list; + if (compat_printers) { + for (const std::string& pname : compat_printers->values) { + auto it = machines.find(pname); + if (it != machines.end()) { + const std::string m = (*it)["model"]; + const std::string n = (*it)["nozzle"]; + model_list += "[" + m + "++" + n + "]"; + } + } + } + + json ff; + ff["name"] = p.name; + ff["sub_path"] = p.file; + ff["vendor"] = vendor; + ff["type"] = type; + ff["models"] = model_list; + ff["selected"] = 0; + data["filament"][p.name] = ff; + } + + // Process list from visible system print presets + for (const Preset& p : bundle.prints()) { + if (!p.is_system || !p.vendor || !p.is_visible) + continue; + json entry; + entry["name"] = p.name; + entry["sub_path"] = p.file; + data["process"].push_back(entry); + } + + BOOST_LOG_TRIVIAL(info) << "printer_profile_data: built profile data (" << data["model"].size() << " models, " + << data["machine"].size() << " machines, " << data["filament"].size() << " filaments)"; + return data; +} + +Outcome printer_profile_data(const std::atomic* cancel) +{ + const boost::filesystem::path vendor_dir = (boost::filesystem::path(data_dir()) / PRESET_SYSTEM_DIR).make_preferred(); + const boost::filesystem::path rsrc_vendor_dir = (boost::filesystem::path(resources_dir()) / "profiles").make_preferred(); + try { + // A vendor in the user's system dir shadows the bundled one of that name. vendor_names_in names a vendor by its + // profile or, where a build ships preset caches instead, by its cache alone. + std::map vendor_sources; + for (const boost::filesystem::path& dir : {vendor_dir, rsrc_vendor_dir}) { + boost::system::error_code ec; + if (boost::filesystem::exists(dir, ec)) + for (const std::string& name : vendor_names_in(dir)) + vendor_sources.emplace(name, dir); // first dir wins + } + + // The load order: the filament library first, because the others' + // filaments inherit from it, then every versioned vendor — each loaded + // from the directory it was found in, so a vendor that is not installed + // is served from the shipped profiles. Each is stamped by name and + // version alone: a profile change requires a version bump, so those two + // determine content wherever the vendor's copy sits. + std::vector ordered; + json stamps = json::array(); + auto add_vendor = [&ordered, &stamps](const std::string& name, const boost::filesystem::path& dir) { + // The version a load from `dir` would serve: the profile's where one + // exists (a cache is only served while it covers the profile beside + // it), the cache's own stamp where the cache is the whole vendor. + // A profile without a version (blacklist.json) carries no presets + // and is passed over. + const boost::filesystem::path profile = dir / (name + ".json"); + std::string version; + if (boost::filesystem::exists(profile)) { + const Semver v = get_version_from_json(profile.string()); + if (!v.valid()) + return; + version = v.to_string(); + } else { + version = VendorCacheFile::peek_version((dir / (name + ".opc")).string(), name); + } + ordered.push_back({name, dir}); + stamps.push_back({name, version}); + }; + const std::string filament_library(PresetBundle::ORCA_FILAMENT_LIBRARY); + if (auto it = vendor_sources.find(filament_library); it != vendor_sources.end()) + add_vendor(filament_library, it->second); + for (const auto& [name, dir] : vendor_sources) + if (name != filament_library) + add_vendor(name, dir); + if (ordered.empty()) + return Refusal{RefusalKind::Failed, "no_vendors", L("No printer profiles were found.")}; + + // What follows is a pure function of that stamped set, so the derived + // JSON is cached whole: a fresh cache makes the data one file read, with + // no bundle built and no preset installed. Stale or absent, the bundle is + // rebuilt below and the result written back. + const boost::filesystem::path cache_file = boost::filesystem::path(data_dir()) / "cache" / "wizard_profile_data.json"; + try { + // Slurped whole and parsed from the buffer — nlohmann's fastest + // input path; a stream adapter costs real time on a multi-MB file. + boost::nowide::ifstream ifs(cache_file.string(), std::ios::binary); + if (ifs.is_open()) { + const std::string text{std::istreambuf_iterator(ifs), std::istreambuf_iterator()}; + json cached = json::parse(text); + if (cached.value("format", 0) == 1 && cached["vendors"] == stamps && !cached["profile"]["machine"].empty()) { + json data = json::object(); + for (const char* key : {"model", "machine", "filament", "process"}) + data[key] = std::move(cached["profile"][key]); + BOOST_LOG_TRIVIAL(info) << "printer_profile_data: served from " << cache_file; + return data; + } + } + } catch (const std::exception& e) { + BOOST_LOG_TRIVIAL(info) << "printer_profile_data: rejecting the cached data: " << e.what(); + } + + // Each vendor comes from its preset cache where one covers it, which is + // what makes this worth doing instead of the dialog's scan of the vendors' JSON files. + PresetBundle bundle; + std::vector failed; + const std::string errors = bundle.load_vendors(ordered, ForwardCompatibilitySubstitutionRule::EnableSilent, + /*allow_cache=*/true, cancel, &failed) + .second; + if (cancel != nullptr && *cancel) + return Refusal{RefusalKind::Failed, "cancelled", L("Reading the printer profiles was cancelled.")}; + if (bundle.vendors.empty()) + return Refusal{RefusalKind::Failed, "no_vendors", L("No printer profiles were found.")}; + if (!errors.empty()) + BOOST_LOG_TRIVIAL(warning) << "printer_profile_data: loading the vendors reported: " << errors; + if (!failed.empty()) + return Refusal{RefusalKind::Failed, "vendors_not_loaded", L("These printer vendors could not be loaded: %1%."), + {boost::algorithm::join(failed, ", ")}, failed}; + json data = profile_data_from(bundle); + if (data["machine"].empty()) + return Refusal{RefusalKind::Failed, "no_vendors", L("No printer profiles were found.")}; + + // Written through a temp file and moved into place, as the preset caches + // are: half a cache must never be readable. + try { + json out; + out["format"] = 1; + out["vendors"] = std::move(stamps); + out["profile"] = data; + boost::filesystem::create_directories(cache_file.parent_path()); + const std::string text = out.dump(-1, ' ', false, json::error_handler_t::ignore); + if (const std::error_code ec = write_file_atomically(cache_file.string(), text, /*binary=*/true)) + throw std::runtime_error(ec.message()); + } catch (const std::exception& e) { + BOOST_LOG_TRIVIAL(warning) << "printer_profile_data: could not write the cache: " << e.what(); + } + return data; + } catch (const std::exception& e) { + BOOST_LOG_TRIVIAL(error) << "printer_profile_data failed: " << e.what(); + // TRN %1% is the error's own text. + return Refusal{RefusalKind::Failed, "profile_data_unreadable", L("The printer profiles could not be read: %1%"), {e.what()}}; + } +} + +InstallSet installed_set_from(const AppConfig& config, const std::vector& offered_filaments) +{ + InstallSet set; + set.printers = config.vendors(); + if (config.has_section(AppConfig::SECTION_FILAMENTS)) + set.filaments = config.get_section(AppConfig::SECTION_FILAMENTS); + else + for (const std::string& name : offered_filaments) + set.filaments[name] = "true"; + return set; +} + +InstallSet installed_set() +{ + assert(wxThread::IsMain()); + return installed_set_from(*wxGetApp().app_config, offered(wxGetApp().preset_bundle->filaments)); +} + +InstallSet changed_install_set(const InstallSet& installed, const std::vector& add, const std::vector& remove) +{ + InstallSet changed = installed; + for (const ModelNozzles& model : add) + if (!model.nozzles.empty()) + changed.printers[model.vendor][model.model].insert(model.nozzles.begin(), model.nozzles.end()); + for (const ModelNozzles& model : remove) { + const auto vendor = changed.printers.find(model.vendor); + if (vendor == changed.printers.end()) + continue; + const auto nozzles = vendor->second.find(model.model); + if (nozzles == vendor->second.end()) + continue; + const std::size_t had = nozzles->second.size(); + for (const std::string& nozzle : model.nozzles) + nozzles->second.erase(nozzle); + if (nozzles->second.size() == had) + continue; + if (nozzles->second.empty()) + vendor->second.erase(nozzles); + if (vendor->second.empty()) + changed.printers.erase(vendor); + } + return changed; +} + +std::optional uninstall_refusal(const InstallSet& installed, const std::vector& remove) +{ + if (nozzle_count(installed) > 0 && nozzle_count(changed_install_set(installed, {}, remove)) == 0) + return Refusal{RefusalKind::Precondition, "last_printer", L("At least one printer model must stay installed.")}; + return std::nullopt; +} + +std::vector printer_models_from(const json& profile, const InstallSet& installed, const std::string& vendor, + const std::string& query) +{ + std::vector models; + const auto entries = profile.find("model"); + if (entries == profile.end() || !entries->is_array()) + return models; + const std::string wanted_vendor = lower(vendor); + const std::string wanted = lower(query); + for (const json& entry : *entries) { + if (!entry.is_object()) + continue; + PrinterModel model; + model.vendor = text(entry, "vendor"); + model.model = text(entry, "model"); + if (!wanted_vendor.empty() && lower(model.vendor) != wanted_vendor) + continue; + if (!wanted.empty() && lower(model.model).find(wanted) == std::string::npos && + lower(text(entry, "name")).find(wanted) == std::string::npos) + continue; + model.nozzles = split_nozzles(text(entry, "nozzle_diameter")); + if (const auto v = installed.printers.find(model.vendor); v != installed.printers.end()) + if (const auto m = v->second.find(model.model); m != v->second.end()) + for (const std::string& nozzle : model.nozzles) + if (m->second.count(nozzle) != 0) + model.installed_nozzles.push_back(nozzle); + models.push_back(std::move(model)); + } + return models; +} + +Outcome> printer_models(const PrinterModelsArgs& args) +{ + const Outcome profile = printer_profile_data(args.cancel); + if (!profile) + return profile.refusal(); + if (!args.vendor.empty()) { + const std::vector vendors = profile_vendors(profile.value()); + if (std::none_of(vendors.begin(), vendors.end(), [&args](const std::string& v) { return lower(v) == lower(args.vendor); })) + return no_such_vendor(args.vendor, vendors); + } + return printer_models_from(profile.value(), args.installed, args.vendor, args.query); +} + +Outcome> resolve_models(const std::vector& known, const std::vector& asked) +{ + std::vector vendors; + for (const PrinterModel& model : known) + vendors.push_back(model.vendor); + std::sort(vendors.begin(), vendors.end()); + vendors.erase(std::unique(vendors.begin(), vendors.end()), vendors.end()); + + std::vector resolved; + for (const ModelNozzles& want : asked) { + std::string vendor; + if (!want.vendor.empty()) { + const auto it = std::find_if(vendors.begin(), vendors.end(), + [&want](const std::string& v) { return lower(v) == lower(want.vendor); }); + if (it == vendors.end()) + return no_such_vendor(want.vendor, vendors); + vendor = *it; + } + // The models of that id, in any case, of the vendor named; one id the same in every case is its own. + std::vector found; + for (const PrinterModel& model : known) + if ((vendor.empty() || model.vendor == vendor) && lower(model.model) == lower(want.model)) + found.push_back(&model); + if (std::any_of(found.begin(), found.end(), [&want](const PrinterModel* m) { return m->model == want.model; })) + found.erase(std::remove_if(found.begin(), found.end(), [&want](const PrinterModel* m) { return m->model != want.model; }), + found.end()); + if (found.empty()) { + std::vector names; + for (const PrinterModel& model : known) + if (vendor.empty() || model.vendor == vendor) + names.push_back(model.model); + if (vendor.empty()) + return Refusal{RefusalKind::Precondition, "no_such_model", L("No printer model is called \"%1%\"."), {want.model}, + closest_names(std::move(names), want.model)}; + // TRN %1% is a printer vendor, %2% the printer model asked for. + return Refusal{RefusalKind::Precondition, "no_such_model", L("%1% has no printer model called \"%2%\"."), + {vendor, want.model}, closest_names(std::move(names), want.model)}; + } + std::vector owners; + for (const PrinterModel* model : found) + if (std::find(owners.begin(), owners.end(), model->vendor) == owners.end()) + owners.push_back(model->vendor); + if (owners.size() > 1) { + std::sort(owners.begin(), owners.end()); + return Refusal{RefusalKind::Precondition, "ambiguous_model", + L("\"%1%\" is a printer model of several vendors: name its vendor."), {want.model}, owners}; + } + const PrinterModel& model = *found.front(); + ModelNozzles named{model.vendor, model.model, {}}; + if (want.nozzles.empty()) + named.nozzles = model.nozzles; + for (const std::string& nozzle : want.nozzles) { + if (std::find(model.nozzles.begin(), model.nozzles.end(), nozzle) == model.nozzles.end()) + // TRN %1% is a printer model, %2% the nozzle asked for ("0.4"). + return Refusal{RefusalKind::Precondition, "no_such_nozzle", L("%1% has no nozzle \"%2%\"."), {model.model, nozzle}, + model.nozzles}; + if (std::find(named.nozzles.begin(), named.nozzles.end(), nozzle) == named.nozzles.end()) + named.nozzles.push_back(nozzle); + } + resolved.push_back(std::move(named)); + } + return resolved; +} + +Outcome apply_install_set(const InstallSet& set, PresetChanges changes) +{ + assert(wxThread::IsMain()); + GUI_App& app = wxGetApp(); + AppConfig* app_config = app.app_config; + PresetBundle* preset_bundle = app.preset_bundle; + + const auto& enabled_vendors = set.printers; + const auto old_enabled_vendors = app_config->vendors(); + const auto& enabled_filaments = set.filaments; + const auto old_enabled_filaments = app_config->has_section(AppConfig::SECTION_FILAMENTS) ? + app_config->get_section(AppConfig::SECTION_FILAMENTS) : + std::map(); + + // The reload drops the presets' unsaved changes: they are asked about, or the caller's answer applies. + bool keep_changes = false; + if (enabled_vendors != old_enabled_vendors || enabled_filaments != old_enabled_filaments) { + if (changes == PresetChanges::Ask) { + const wxString header = _L("The configuration package is changed in previous Config Guide"); + const wxString caption = _L("Configuration package changed"); + if (!app.check_and_keep_current_preset_changes(caption, header, ActionButtons::KEEP | ActionButtons::SAVE, &keep_changes)) + return Refusal{RefusalKind::Precondition, "selection_cancelled", + L("The question about the unsaved changes was cancelled.")}; + } else if (app.has_current_preset_changes()) { + if (changes == PresetChanges::Discard) { + app.discard_current_preset_changes(); + } else { + cache_listed_changes(); + keep_changes = true; + } + } + } + + std::string preferred_model; + std::string preferred_variant; + auto get_preferred_printer_model = [preset_bundle, &enabled_vendors, &old_enabled_vendors](const std::string& bundle_name, + std::string& variant) { + const auto config = enabled_vendors.find(bundle_name); + if (config == enabled_vendors.end()) + return std::string(); + + const VendorProfile& printer_profile = preset_bundle->vendors[bundle_name]; + const std::map>& model_maps = config->second; + for (const auto& model_it : model_maps) { + if (model_it.second.size() > 0) { + variant = *model_it.second.begin(); + if (model_it.second.size() > 1) { + if (printer_profile.models.size() > 0) { + const auto is_model = [id = model_it.first](auto& m) { return m.id == id; }; + const VendorProfile::PrinterModel& printer_model = + *std::find_if(printer_profile.models.begin(), printer_profile.models.end(), is_model); + for (auto& vt : printer_model.variants) { + if (std::find(model_it.second.begin(), model_it.second.end(), vt.name) != model_it.second.end()) { + variant = vt.name; + break; + } + } + } else if (variant != PresetBundle::ORCA_DEFAULT_PRINTER_VARIANT) { + if (std::find(model_it.second.begin(), model_it.second.end(), PresetBundle::ORCA_DEFAULT_PRINTER_VARIANT) != + model_it.second.end()) + variant = PresetBundle::ORCA_DEFAULT_PRINTER_VARIANT; + } + } + + const auto config_old = old_enabled_vendors.find(bundle_name); + if (config_old == old_enabled_vendors.end()) + return model_it.first; + const auto model_it_old = config_old->second.find(model_it.first); + if (model_it_old == config_old->second.end()) + return model_it.first; + else if (model_it_old->second != model_it.second) { + for (const auto& var : model_it.second) + if (model_it_old->second.find(var) == model_it_old->second.end()) { + variant = var; + return model_it.first; + } + } + } + } + if (!variant.empty()) + variant.clear(); + return std::string(); + }; + // Orca "custom" printers are considered first, then 3rd party. + if (preferred_model = get_preferred_printer_model(PresetBundle::ORCA_DEFAULT_BUNDLE, preferred_variant); preferred_model.empty()) { + for (const auto& bundle : enabled_vendors) { + if (bundle.first == PresetBundle::ORCA_DEFAULT_BUNDLE) { + continue; + } + if (preferred_model = get_preferred_printer_model(bundle.first, preferred_variant); !preferred_model.empty()) + break; + } + } + + // Installs the bundles from the shipped profiles, writes both sections and reloads the presets. A @System filament + // is replaced by a vendor's own only where the vendor's profile lists default filaments, which an INI bundle does + // and the shipped JSON profiles do not. + BOOST_LOG_TRIVIAL(info) << "apply_install_set: calling apply_vendor_config"; + if (!preset_bundle->apply_vendor_config(enabled_vendors, enabled_filaments, app_config, true, preferred_model, preferred_variant)) + return Refusal{RefusalKind::Failed, "vendors_not_installed", L("The printer profiles could not be installed.")}; + + if (keep_changes) + app.apply_keeped_preset_modifications(); + app_config->set_legacy_datadir(false); + app.update_mode(); + if (Plater* plater = app.plater()) + plater->normalize_bed_types(false); + return Done{}; +} + +Outcome install_printers(const InstallPrintersArgs& args) { return change_printers(args, true); } + +Outcome uninstall_printers(const InstallPrintersArgs& args) { return change_printers(args, false); } + +// ---- System filaments ---- + +std::vector loaded_filaments() +{ + assert(wxThread::IsMain()); + const PresetBundle& bundle = *wxGetApp().preset_bundle; + const AppConfig& config = *wxGetApp().app_config; + const auto first = [](const Preset& preset, const char* key) { + const auto* values = preset.config.option(key); + return values != nullptr && !values->values.empty() ? values->values.front() : std::string(); + }; + // A printer is installed where the models section names its model and nozzle under its vendor. + const auto installed = [&bundle, &config](const std::string& printer_name) { + const Preset* printer = bundle.printers.find_preset(printer_name, false); + return printer != nullptr && printer->is_system && printer->vendor != nullptr && + config.get_variant(printer->vendor->id, printer->config.opt_string("printer_model"), + printer->config.opt_string("printer_variant")); + }; + std::vector rows; + for (const Preset& preset : bundle.filaments) { + if (!preset.is_system || preset.vendor == nullptr || preset.vendor->id == PRESET_TEMPLATE_DIR) + continue; + FilamentRow row{preset.name, preset.alias.empty() ? preset.name : preset.alias, first(preset, "filament_vendor"), + first(preset, "filament_type")}; + const auto* printers = preset.config.option("compatible_printers"); + row.fits = printers == nullptr || printers->values.empty() || + std::any_of(printers->values.begin(), printers->values.end(), installed); + rows.push_back(std::move(row)); + } + return rows; +} + +std::vector filament_presets_named(const std::vector& loaded, const std::string& name) +{ + if (std::any_of(loaded.begin(), loaded.end(), [&name](const FilamentRow& row) { return row.name == name; })) + return {name}; + std::vector presets; + for (const FilamentRow& row : loaded) + if (row.alias == name && row.fits) + presets.push_back(row.name); + return presets; +} + +Outcome> filaments_named(const std::vector& loaded, const InstallFilamentsArgs& args) +{ + std::vector presets; + const auto add = [&presets](const std::string& name) { + if (std::find(presets.begin(), presets.end(), name) == presets.end()) + presets.push_back(name); + }; + if (args.names.empty()) { + const std::string vendor = lower(args.vendor), type = lower(args.filament_type); + std::vector vendors, types; + for (const FilamentRow& row : loaded) { + vendors.push_back(row.vendor); + if (lower(row.vendor) != vendor || !row.fits) + continue; + if (std::find(types.begin(), types.end(), row.type) == types.end()) + types.push_back(row.type); + if (lower(row.type) == type) + add(row.name); + } + if (!presets.empty()) + return presets; + if (std::none_of(loaded.begin(), loaded.end(), [&vendor](const FilamentRow& row) { return lower(row.vendor) == vendor; })) + return Refusal{RefusalKind::Precondition, "no_filament_vendor", L("No system filament is of the vendor \"%1%\"."), + {args.vendor}, closest_names(std::move(vendors), args.vendor)}; + std::sort(types.begin(), types.end()); + return Refusal{RefusalKind::Precondition, "no_matching_filament", + // TRN %1% is a filament vendor ("Bambu Lab"), %2% a filament type ("PLA"). + L("No system filament of %1% of type %2% fits an installed printer."), {args.vendor, args.filament_type}, types}; + } + for (const std::string& name : args.names) { + const std::vector named = filament_presets_named(loaded, name); + if (named.empty()) { + std::vector unfit, candidates; + for (const FilamentRow& row : loaded) { + if (row.alias == name) + unfit.push_back(row.name); + candidates.push_back(row.alias); + candidates.push_back(row.name); + } + if (!unfit.empty()) + return Refusal{RefusalKind::Precondition, "fits_no_printer", L("No installed printer fits the filament \"%1%\"."), {name}, + unfit}; + return Refusal{RefusalKind::Precondition, "no_such_filament", L("No system filament is called \"%1%\"."), {name}, + closest_names(std::move(candidates), name)}; + } + for (const std::string& preset : named) + add(preset); + } + return presets; +} + +std::optional filament_uninstall_refusal(const std::vector& presets, const std::vector& slot_presets) +{ + for (std::size_t slot = 0; slot < slot_presets.size(); ++slot) + if (std::find(presets.begin(), presets.end(), slot_presets[slot]) != presets.end()) + // TRN %1% is a filament slot's number, %2% the filament preset it uses. + return Refusal{RefusalKind::Precondition, "filament_in_use", L("Filament slot %1% uses %2%."), + {std::to_string(slot + 1), slot_presets[slot]}, {slot_presets[slot]}}; + return std::nullopt; +} + +Outcome install_filaments(const InstallFilamentsArgs& args) { return change_filaments(args, true); } + +Outcome uninstall_filaments(const InstallFilamentsArgs& args) { return change_filaments(args, false); } + +}}} // namespace Slic3r::GUI::Ops diff --git a/src/slic3r/GUI/Operations/InstallOps.hpp b/src/slic3r/GUI/Operations/InstallOps.hpp new file mode 100644 index 0000000000..362e1d1f63 --- /dev/null +++ b/src/slic3r/GUI/Operations/InstallOps.hpp @@ -0,0 +1,203 @@ +#pragma once + +#include "Outcome.hpp" +#include "PresetOps.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +namespace Slic3r { + +class AppConfig; +class PresetBundle; + +// What a person installs: the printer models the Printer Selection dialog lists and the system filaments the System +// Filaments dialog lists (GuideFrame, WebGuideDialog.cpp). Installed is what the app configuration's models and +// filaments sections name, which the presets' visibility follows (Preset::set_visible_from_appconfig()): the selectors +// offer an installed printer or filament, and the others only by name (preset_list include_uninstalled). +namespace GUI { namespace Ops { + +// ---- Printer models ---- + +// The data the Printer Selection dialog lists, of every vendor the app ships or has installed: {model: [{model, name, +// vendor, nozzle_diameter ("0.4;0.6"), materials, cover, ...}], machine: {printer preset: {model, nozzle}}, filament: +// {preset: {name, vendor, type, models, ...}}, process: [{name, sub_path}]}. Read from +// /cache/wizard_profile_data.json while its vendor stamps (each vendor's name and version, in load order) are +// those of the vendors found in /system and the shipped profiles, the installed copy first; else every vendor +// is loaded into a preset bundle of its own, the data built from it and the cache written. It touches no window and +// runs on any thread: the dialog and printer_list_models run it off the UI thread, as the load takes a while. Once +// *cancel is set, no further vendor starts loading. +// Refuses: no_vendors, cancelled, vendors_not_loaded (with the vendors that failed), profile_data_unreadable. +Outcome printer_profile_data(const std::atomic* cancel = nullptr); + +// The data printer_profile_data() lists, built from `bundle`: its vendors' models, its system printers, filaments and +// visible processes. Throws std::exception where a preset's data cannot be read; the data has no machine when the +// bundle holds no system printer. +nlohmann::json profile_data_from(const PresetBundle& bundle); + +// What the two dialogs' Confirm writes: the app configuration's models and filaments sections. +struct InstallSet +{ + std::map>> printers; // vendor -> model -> nozzles (AppConfig::vendors()) + std::map filaments; // preset name -> "true" +}; + +// The installed set `config` holds: its models section, and its filaments section or, where it has none, which installs +// every filament, `offered_filaments` (the system filaments the selectors offer), so that a set written back keeps them +// installed. +InstallSet installed_set_from(const AppConfig& config, const std::vector& offered_filaments); + +// installed_set_from() of the app configuration and the filaments the selectors offer. UI thread. +InstallSet installed_set(); + +// A printer model and nozzles of it that a call names. +struct ModelNozzles +{ + std::string vendor; // the vendor's id ("BBL"); empty: the one vendor that has the model + std::string model; // the model's id, as printer_list_models lists it + std::vector nozzles; // the model's nozzle variants ("0.4"); empty: all of them +}; + +// `installed` with the nozzles of `add` added and those of `remove` removed, each under its vendor and model: a model +// left with no nozzle is removed, and a vendor left with no model. The other models and the filaments are kept. +InstallSet changed_install_set(const InstallSet& installed, const std::vector& add, const std::vector& remove); + +// The refusal of removing `remove` from `installed` where it would leave no printer model installed (last_printer), as +// the Printer Selection dialog requires one; none otherwise. +std::optional uninstall_refusal(const InstallSet& installed, const std::vector& remove); + +// A printer model the app ships or has installed, as the Printer Selection dialog lists it. +struct PrinterModel +{ + std::string vendor, model; + std::vector nozzles, installed_nozzles; +}; + +// The models of `profile` (printer_profile_data()'s), in its order, with the nozzles `installed` holds for each under +// its vendor: those of `vendor` (any case) when one is given, and those whose id or name holds `query` (any case). +std::vector printer_models_from(const nlohmann::json& profile, const InstallSet& installed, const std::string& vendor, + const std::string& query); + +struct PrinterModelsArgs +{ + std::string vendor; // any case; empty: every vendor + std::string query; // a part of a model's id or name, any case + InstallSet installed; // installed_set(), read on the UI thread + const std::atomic* cancel = nullptr; +}; +// Every printer model of printer_profile_data(), as printer_models_from() filters it. Off the UI thread, as +// printer_profile_data(). +// Refuses: what printer_profile_data() refuses, and no_such_vendor (with the closest vendors). +Outcome> printer_models(const PrinterModelsArgs& args); + +// The models `asked` names, each resolved against `known` (every model): its vendor where one vendor has a model of that +// id (in any case), all its nozzles where it names none. Every model and nozzle is checked. +// Refuses: no_such_vendor, no_such_model (each with the closest names), ambiguous_model (with the vendors that have +// it), no_such_nozzle (with the model's nozzles). +Outcome> resolve_models(const std::vector& known, const std::vector& asked); + +// Applies `set` as the dialogs' Confirm does: asks about the presets' unsaved changes where the set differs from the +// installed one (`changes` Ask: the prompt with Transfer, Save and Discard; Transfer and Discard answer it), installs the +// vendor bundles a model of it needs from the shipped profiles, writes both sections, reloads the presets and selects a +// newly added printer (PresetBundle::apply_vendor_config()), puts the changes kept back on the presets selected, and +// brings the mode and the plates' bed types in line. Not in the undo history. UI thread. +// Refuses: selection_cancelled (the prompt's Cancel, before any change), vendors_not_installed (a bundle could not be +// installed: the sections are not written and the presets not reloaded, but the unsaved changes are as the +// answer left them, saved or discarded, and the bundles copied before the failure stay in the configuration +// folder). +Outcome apply_install_set(const InstallSet& set, PresetChanges changes); + +struct InstallPrintersArgs +{ + std::vector models; + std::vector known; // printer_models() of every vendor + PresetChanges changes = PresetChanges::Ask; // Ask: refused while presets have unsaved changes +}; +struct InstalledPrinters +{ + std::vector models; // the models and nozzles the call named, resolved + std::vector added; // printer presets the selectors offer that they did not + std::vector removed; // printer presets the selectors no longer offer + std::string selected; // the printer preset selected afterwards + std::vector missing; // named nozzles the selectors do not offer after an install, or still offer + // System filaments the reload installed or uninstalled: a printer's default filaments where no installed filament + // fits it (PresetBundle::load_installed_filaments()), and, where a vendor's profile lists default filaments of its + // own (an INI bundle; the shipped JSON profiles list none), a @System filament swapped for the vendor's, as the + // dialogs' Confirm swaps it (PresetBundle::apply_vendor_config()). + std::vector filaments_installed, filaments_uninstalled; +}; +// Adds the models' nozzles to the installed printers and applies the set (apply_install_set()) with the installed +// filaments (installed_set()), then refreshes what a person's Confirm refreshes after the dialog closes and saves the +// app configuration. A set that does not change is not applied. Opens nothing: unsaved changes need `changes`. UI +// thread. +// Refuses: what resolve_models() refuses, unsaved_preset_changes, vendors_not_installed (as apply_install_set(): the +// error says that the installed printers are as they were, what became of the unsaved changes and that copied +// bundles stay), presets_not_reloaded (the sections were written, the presets not reloaded: the error says so). +Outcome install_printers(const InstallPrintersArgs& args); +// As install_printers(), removing the models' nozzles. +// Refuses: also what uninstall_refusal() refuses. +Outcome uninstall_printers(const InstallPrintersArgs& args); + +// ---- System filaments ---- + +// A system filament preset the app has loaded, as a row of the System Filaments dialog lists it. +struct FilamentRow +{ + std::string name; // the preset's + std::string alias; // the short name the filament selectors show + std::string vendor, type; + bool fits = false; // an installed printer fits it: its compatible_printers name one, or none at all +}; + +// The system filaments the app has loaded, the Template vendor's left out. UI thread. +std::vector loaded_filaments(); + +// The presets `name` stands for: the preset of that name, else each preset whose short name it is and that an installed +// printer fits, as a row of the System Filaments dialog stands for them; none for a name no row has. +std::vector filament_presets_named(const std::vector& loaded, const std::string& name); + +struct InstallFilamentsArgs +{ + std::vector names; // presets' names or short names + std::string vendor; // with filament_type, in place of names: every filament of them an installed printer fits + std::string filament_type; +}; +// The presets `args` names in `loaded`, each once, in their order: those of each name (filament_presets_named()), or of +// the vendor and the filament type (any case). Every name is checked. +// Refuses: no_such_filament (with the closest names), fits_no_printer (a short name of presets no installed printer fits, +// with them), no_filament_vendor (with the closest vendors), no_matching_filament (with the vendor's types). +Outcome> filaments_named(const std::vector& loaded, const InstallFilamentsArgs& args); + +// The refusal of uninstalling `presets` where a filament slot of the project uses one of them (filament_in_use), naming +// the first such slot (1-based) and its preset; `slot_presets` are the slots' presets, slot 1 first. +std::optional filament_uninstall_refusal(const std::vector& presets, const std::vector& slot_presets); + +struct InstalledFilaments +{ + std::vector changed; // named presets installed (or uninstalled) by the call + std::vector unchanged; // named presets that were installed (or not installed) already + // System filaments installed again as an installed printer's default filaments, which the app keeps installed while + // no other installed filament fits the printer (PresetBundle::load_installed_filaments()); named ones among them. + std::vector defaults_installed; +}; +// Adds the named presets to the app configuration's filaments section, which installs them for good, then applies the +// section as the app's start does (PresetBundle::load_installed_filaments()): the filaments it installs are shown in +// the filament selectors, and an installed printer that no installed filament fits gets its default filaments again; +// a printer shown for this session only, which the app configuration does not install, gets none. +// The app configuration is saved and the selectors refreshed. The presets are not reloaded, so their unsaved changes are +// kept. A configuration with no filaments section, which installs every filament, is left as it is. UI thread. +// Refuses: what filaments_named() refuses. +Outcome install_filaments(const InstallFilamentsArgs& args); +// As install_filaments(), taking the named presets (and the names they were renamed from) out of the section. A +// configuration with no filaments section gets one, of every other system filament the selectors offer. +// Refuses: what filaments_named() refuses, and what filament_uninstall_refusal() refuses for the project's slots. +Outcome uninstall_filaments(const InstallFilamentsArgs& args); + +}} // namespace GUI::Ops +} // namespace Slic3r diff --git a/src/slic3r/GUI/Operations/ObjectOps.cpp b/src/slic3r/GUI/Operations/ObjectOps.cpp new file mode 100644 index 0000000000..06779c5cb8 --- /dev/null +++ b/src/slic3r/GUI/Operations/ObjectOps.cpp @@ -0,0 +1,1244 @@ +#include "ObjectOps.hpp" + +#include "Outcome.hpp" +#include "PlateOps.hpp" + +#include "slic3r/GUI/GLCanvas3D.hpp" +#include "slic3r/GUI/GUI.hpp" +#include "slic3r/GUI/GUI_App.hpp" +#include "slic3r/GUI/GUI_ObjectList.hpp" +#include "slic3r/GUI/Gizmos/GLGizmosManager.hpp" +#include "slic3r/GUI/I18N.hpp" +#include "slic3r/GUI/Jobs/Job.hpp" +#include "slic3r/GUI/Jobs/Worker.hpp" +#include "slic3r/GUI/ObjectDataViewModel.hpp" +#include "slic3r/GUI/PartPlate.hpp" +#include "slic3r/GUI/Plater.hpp" +#include "slic3r/GUI/Selection.hpp" +#include "slic3r/Utils/FixModelByCgal.hpp" + +#include "libslic3r/AppConfig.hpp" +#include "libslic3r/BoundingBox.hpp" +#include "libslic3r/BuildVolume.hpp" +#include "libslic3r/Model.hpp" +#include "libslic3r/ObjectID.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/TriangleMesh.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Ops { + +namespace { + +Plater& the_plater() +{ + assert(wxThread::IsMain()); + return *wxGetApp().plater(); +} + +// The objects `targets` names or names something of, each once, by index. +std::set objects_of(const Targets& targets) +{ + std::set out(targets.objects.begin(), targets.objects.end()); + for (const auto& [object, instance] : targets.instances) + out.insert(object); + for (const auto& [object, part] : targets.parts) + out.insert(object); + return out; +} + +// What ObjectList::del_subobject_from_object() asks before it deletes a solid or negative part of a cut object, and +// Plater's delete_object_from_model() before it deletes a cut object; only `targets` as deletion() gives them. +std::optional cut_refusal(const Model& model, const Targets& doomed) +{ + for (int object : doomed.objects) + if (model.objects[std::size_t(object)]->is_cut()) + return Refusal{RefusalKind::Precondition, "cut_object", + L("You are trying to delete an object which is a part of a cut object.\nThis action will break a cut " + "correspondence.\nAfter that, model consistency can't be guaranteed.")}; + for (const auto& [object, part] : doomed.parts) { + const ModelObject& owner = *model.objects[std::size_t(object)]; + const ModelVolume& volume = *owner.volumes[std::size_t(part)]; + if (owner.is_cut() && (volume.is_model_part() || volume.is_negative_volume())) + return Refusal{RefusalKind::Precondition, "cut_object", + L("This action will break a cut correspondence.\nAfter that, model consistency can't be guaranteed.\n\nTo " + "manipulate with solid parts or negative volumes you have to invalidate cut information first.")}; + } + return std::nullopt; +} + +// An object left without a solid part by the parts of `doomed` (deletion()), which the object list refuses. +std::optional last_solid_part_refusal(const Model& model, const Targets& doomed) +{ + std::map> named; + for (const auto& [object, part] : doomed.parts) + named[object].insert(std::size_t(part)); + for (const auto& [object, parts] : named) { + const ModelObject& owner = *model.objects[std::size_t(object)]; + bool kept = false, deleted = false; + for (std::size_t v = 0; v < owner.volumes.size(); ++v) + if (owner.volumes[v]->is_model_part()) + (parts.count(v) != 0 ? deleted : kept) = true; + if (deleted && !kept) + return Refusal{RefusalKind::Precondition, "last_solid_part", L("Deleting the last solid part is not allowed.")}; + } + return std::nullopt; +} + +Refusal part_not_listed() +{ + return {RefusalKind::Precondition, "part_not_listed", L("The object list does not show this part, so it cannot be renamed.")}; +} + +// Whether `targets` names a cut object or something of one. +bool names_cut_object(const Model& model, const Targets& targets) +{ + const std::set objects = objects_of(targets); + return std::any_of(objects.begin(), objects.end(), [&model](int object) { return model.objects[std::size_t(object)]->is_cut(); }); +} + +// The refusal of a change to the meshes while a gizmo is open, which keeps references to them and undo steps of its own, +// in the words the GUI's check (GLGizmosManager::check_gizmos_closed_except()) shows in a notification; none when no gizmo +// is open. +std::optional gizmo_open(Plater& plater) +{ + if (plater.get_view3D_canvas3D()->get_gizmos_manager().get_current_type() == GLGizmosManager::Undefined) + return std::nullopt; + return Refusal{RefusalKind::Precondition, "gizmo_open", L("Error: Please close all toolbar menus first")}; +} + +// The refusal of a file that loads as more than one object or part, which Replace 3D file tells in a message box. +Refusal several_parts_loaded() +{ + return {RefusalKind::Precondition, "several_parts", L("Unable to replace with more than one volume")}; +} + +// Selects `targets` in the Prepare view and nothing else, as clicking them would: an object whole, an instance, a part +// on instance 0; the object list shows it. +void select_targets(const Targets& targets) +{ + GLCanvas3D& canvas = shown_prepare_canvas(); + Selection& sel = canvas.get_selection(); + bool first = true; + for (int object : targets.objects) { + sel.add_object(unsigned(object), first); + first = false; + } + for (const auto& [object, instance] : targets.instances) { + sel.add_instance(unsigned(object), unsigned(instance), first); + first = false; + } + for (const auto& [object, part] : targets.parts) { + sel.add_volume(unsigned(object), unsigned(part), 0, first); + first = false; + } + wxGetApp().obj_list()->update_selections(); + canvas.set_as_dirty(); +} + +// One instance, or the parts of one object, at a time: what Mirror takes of the targets, for an object every instance +// of it, in the order named. +std::vector mirror_turns(const Model& model, const Targets& targets) +{ + std::vector out; + const auto instance = [&out](int object, int index) { + Targets one; + one.instances = {{object, index}}; + out.push_back(std::move(one)); + }; + for (int object : targets.objects) + for (std::size_t i = 0; i < model.objects[std::size_t(object)]->instances.size(); ++i) + instance(object, int(i)); + for (const auto& [object, index] : targets.instances) + instance(object, index); + std::map parts; + for (const auto& part : targets.parts) + parts[part.first].parts.push_back(part); + for (auto& [object, of_object] : parts) + out.push_back(std::move(of_object)); + return out; +} + +} // namespace + +Refusal nothing_selected() +{ + return {RefusalKind::Precondition, "nothing_selected", L("Nothing is selected: name the objects, or select them first.")}; +} + +Refusal wrong_selection() +{ + return {RefusalKind::Precondition, "wrong_selection", L("This does not act on what is selected: name its targets, or select them first.")}; +} + +Refusal one_object_only() +{ + return {RefusalKind::Precondition, "one_object_only", L("This acts on one object or part at a time: name one, or select only one.")}; +} + +Refusal gizmo_keeps_selection() +{ + return {RefusalKind::Precondition, "gizmo_open", L("Close the open gizmo first: while it is open, Select All selects nothing.")}; +} + +Targets deletion(const Model& model, const Targets& targets) +{ + std::set whole(targets.objects.begin(), targets.objects.end()); + std::map> instances, parts; + for (const auto& [object, instance] : targets.instances) + instances[object].insert(instance); + for (const auto& [object, part] : targets.parts) + parts[object].insert(part); + for (const auto& [object, named] : instances) + if (named.size() == model.objects[std::size_t(object)]->instances.size()) + whole.insert(object); + for (const auto& [object, named] : parts) + if (named.size() == model.objects[std::size_t(object)]->volumes.size()) + whole.insert(object); + + Targets out; + out.from_selection = targets.from_selection; + out.objects.assign(whole.begin(), whole.end()); + for (const auto& instance : targets.instances) + if (whole.count(instance.first) == 0) + out.instances.push_back(instance); + for (const auto& part : targets.parts) + if (whole.count(part.first) == 0) + out.parts.push_back(part); + return out; +} + +std::optional delete_refusal(const Model& model, const Targets& targets) +{ + const Targets doomed = deletion(model, targets); + if (std::optional refusal = cut_refusal(model, doomed)) + return refusal; + return last_solid_part_refusal(model, doomed); +} + +TargetIds target_ids(const Model& model, const Targets& targets) +{ + TargetIds out; + for (int object : targets.objects) + out.objects.push_back(model.objects[std::size_t(object)]->id()); + for (const auto& [object, instance] : targets.instances) + out.instances.push_back(model.objects[std::size_t(object)]->instances[std::size_t(instance)]->id()); + for (const auto& [object, part] : targets.parts) + out.parts.push_back(model.objects[std::size_t(object)]->volumes[std::size_t(part)]->id()); + return out; +} + +DeletedTargets deleted_targets(const Targets& doomed, const TargetIds& before, const Model& after) +{ + // Where `after` holds the object, or the instance or part of `items`, of identity `id`: its index, or [object, index]. + const auto object_at = [&after](ObjectID id) -> std::optional { + for (std::size_t o = 0; o < after.objects.size(); ++o) + if (after.objects[o]->id() == id) + return int(o); + return std::nullopt; + }; + const auto item_at = [&after](ObjectID id, const auto& items) -> std::optional> { + for (std::size_t o = 0; o < after.objects.size(); ++o) { + const auto& of_object = items(*after.objects[o]); + for (std::size_t i = 0; i < of_object.size(); ++i) + if (of_object[i]->id() == id) + return std::pair(int(o), int(i)); + } + return std::nullopt; + }; + const auto instances = [](const ModelObject& object) -> const ModelInstancePtrs& { return object.instances; }; + const auto volumes = [](const ModelObject& object) -> const ModelVolumePtrs& { return object.volumes; }; + + DeletedTargets out; + out.deleted.from_selection = out.kept.from_selection = doomed.from_selection; + for (std::size_t i = 0; i < doomed.objects.size(); ++i) + if (const std::optional now = object_at(before.objects[i])) + out.kept.objects.push_back(*now); + else + out.deleted.objects.push_back(doomed.objects[i]); + for (std::size_t i = 0; i < doomed.instances.size(); ++i) + if (const auto now = item_at(before.instances[i], instances)) + out.kept.instances.push_back(*now); + else + out.deleted.instances.push_back(doomed.instances[i]); + for (std::size_t i = 0; i < doomed.parts.size(); ++i) + if (const auto now = item_at(before.parts[i], volumes)) + out.kept.parts.push_back(*now); + else + out.deleted.parts.push_back(doomed.parts[i]); + return out; +} + +Outcome delete_objects(const DeleteObjectsArgs& args) +{ + Plater& plater = the_plater(); + const Model& model = plater.model(); + if (args.all) { + if (model.objects.empty()) + return Refusal{RefusalKind::Precondition, "no_objects", L("There are no objects to delete.")}; + DeletedTargets every; + for (std::size_t i = 0; i < model.objects.size(); ++i) + every.deleted.objects.push_back(int(i)); + plater.delete_all_objects_from_model(); + return every; + } + + const Targets doomed = deletion(model, args.targets); + if (args.checks == DeleteChecks::Refuse) + if (std::optional refusal = delete_refusal(model, doomed)) + return *refusal; + // In index order: the object list deletes them from the last, so no deletion moves an index still to come. + std::vector items; + for (int object : doomed.objects) + items.emplace_back(itObject, object, 0); + for (const auto& [object, instance] : doomed.instances) + items.emplace_back(itInstance, object, instance); + for (const auto& [object, part] : doomed.parts) + items.emplace_back(itVolume, object, part); + std::sort(items.begin(), items.end()); + + const TargetIds before = target_ids(model, doomed); + Plater::TakeSnapshot snapshot(&plater, "Delete Selected Objects"); + plater.get_ui_job_worker().cancel_all(); + ObjectList& list = *wxGetApp().obj_list(); + // One object or one instance as Selection::erase() deletes a selection of one, the rest as it deletes several. + if (items.size() == 1 && items.front().type != itVolume) + list.delete_from_model_and_list(items.front().type, items.front().obj_idx, items.front().sub_obj_idx); + else + list.delete_from_model_and_list(items); + // The object list stops at an item it refuses (an object's last solid part) or asks about (a cut object, whose + // question cancelled or answered by invalidating the cut deletes nothing), having deleted the items after it. + DeletedTargets done = deleted_targets(doomed, before, model); + if (done.deleted.objects.empty() && done.deleted.instances.empty() && done.deleted.parts.empty()) + return nothing_deleted(); + return done; +} + +Refusal nothing_deleted() { return {RefusalKind::Failed, "nothing_deleted", L("Nothing was deleted.")}; } + +std::optional rename_refusal(const std::string& name) +{ + if (name.empty()) + return Refusal{RefusalKind::Precondition, "empty_name", L("The name cannot be empty.")}; + if (Plater::has_illegal_filename_characters(name)) + // TRN %1% is the characters a name cannot hold. + return Refusal{RefusalKind::Precondition, "invalid_name", L("Invalid name, the following characters are not allowed: %1%"), + {"<>:/\\|?*\""}}; + return std::nullopt; +} + +Refusal rename_wrong_selection() { return {RefusalKind::Precondition, "wrong_selection", L("Select one object or part first.")}; } + +std::optional unlisted_part_refusal(const Model& model, int object, int part) +{ + const ModelObject& owner = *model.objects[std::size_t(object)]; + if (part >= 0 && owner.is_cut() && owner.volumes[std::size_t(part)]->is_cut_connector()) + return part_not_listed(); + return std::nullopt; +} + +Outcome rename_object(const RenameObjectArgs& args) +{ + if (std::optional refusal = rename_refusal(args.name)) + return *refusal; + const Model& model = the_plater().model(); + if (std::optional refusal = unlisted_part_refusal(model, args.object, args.part)) + return *refusal; + const ModelObject& object = *model.objects[std::size_t(args.object)]; + ObjectList& list = *wxGetApp().obj_list(); + // A part's row is by its place among the rows, which leave a cut's connectors out. + const wxDataViewItem item = args.part < 0 ? + list.GetModel()->GetItemById(args.object) : + list.GetModel()->GetItemByVolumeId(args.object, + list.GetModel()->get_real_volume_index_in_ui(args.object, args.part)); + if (!item.IsOk()) + return part_not_listed(); + std::string before = args.part < 0 ? object.name : object.volumes[std::size_t(args.part)]->name; + list.rename_item(item, from_u8(args.name)); + return before; +} + +std::optional separate_refusal(const Model& model, const Targets& targets) +{ + if (!targets.parts.empty()) + return wrong_selection(); + const std::set objects = objects_of(targets); + if (objects.empty()) + return nothing_selected(); + if (objects.size() > 1) + return one_object_only(); + const ModelObject& object = *model.objects[std::size_t(*objects.begin())]; + for (const auto& [owner, instance] : targets.instances) + if (instance < 0 || std::size_t(instance) >= object.instances.size()) + // TRN %1% is an object's name, %2% an instance's index. + return Refusal{RefusalKind::Precondition, "no_such_instance", L("\"%1%\" has no instance %2%."), {object.name, std::to_string(instance)}}; + if (object.instances.size() == 1) + // TRN %1% is an object's name. + return Refusal{RefusalKind::Precondition, "one_instance", L("\"%1%\" has one instance: there are no instances to separate."), {object.name}}; + return std::nullopt; +} + +Outcome separate_instances(const Targets& targets) +{ + Plater& plater = the_plater(); + const Model& model = plater.model(); + if (std::optional refusal = separate_refusal(model, targets)) + return *refusal; + const int object = *objects_of(targets).begin(); + std::set instances; + for (const auto& [owner, instance] : targets.instances) + instances.insert(instance); + const bool every = !targets.objects.empty() || instances.size() == model.objects[std::size_t(object)]->instances.size(); + const std::size_t before = model.objects.size(); + + Plater::TakeSnapshot snapshot(&plater, _u8L("Instances to Separated Objects")); + ObjectList& list = *wxGetApp().obj_list(); + if (every) + list.instances_to_separated_objects(object); + else + list.instances_to_separated_object(object, instances); + + Targets holders; + if (every) + holders.objects.push_back(object); + for (std::size_t i = before; i < model.objects.size(); ++i) + holders.objects.push_back(int(i)); + return holders; +} + +std::optional split_refusal(const Model& model, const Targets& targets) +{ + const auto one_shell = [](const std::string& name, const ModelVolume& mesh) -> std::optional { + if (mesh.is_splittable()) + return std::nullopt; + // TRN %1% is an object's or a part's name. + return Refusal{RefusalKind::Precondition, "one_shell", L("\"%1%\" is one piece: its mesh has one shell, so it cannot be split."), + {name}}; + }; + // An object of several parts splits into objects by its parts. + for (int object : targets.objects) + if (const ModelObject& owner = *model.objects[std::size_t(object)]; owner.volumes.size() == 1) + if (std::optional refusal = one_shell(owner.name, *owner.volumes.front())) + return refusal; + for (const auto& [object, part] : targets.parts) { + const ModelVolume& volume = *model.objects[std::size_t(object)]->volumes[std::size_t(part)]; + if (std::optional refusal = one_shell(volume.name, volume)) + return refusal; + } + return std::nullopt; +} + +Outcome split_object(const SplitObjectArgs& args) +{ + Plater& plater = the_plater(); + const Model& model = plater.model(); + if (std::optional refusal = split_refusal(model, args.target)) + return *refusal; + const int object = args.target.objects.empty() ? args.target.parts.front().first : args.target.objects.front(); + if (args.to_objects) { + const std::size_t before = model.objects.size(); + switch (plater.split_object(object, args.ask, args.keep_z)) { + case Plater::SplitResult::OnePiece: + return Refusal{RefusalKind::Precondition, "one_piece", L("The selected object couldn't be split.")}; + case Plater::SplitResult::Unanswered: + return Refusal{RefusalKind::Precondition, "auto_drop_question", + L("Object with floating parts was detected: disable Auto-Drop to preserve Z positioning?")}; + case Plater::SplitResult::Split: break; + } + // The object is removed, and its pieces are added last. + Targets pieces; + for (std::size_t i = before - 1; i < model.objects.size(); ++i) + pieces.objects.push_back(int(i)); + return pieces; + } + + const ModelObject& owner = *model.objects[std::size_t(object)]; + const int part = args.target.parts.empty() ? -1 : args.target.parts.front().second; + const bool shown = owner.hides_imported_parts(); // the split shows the bodies the import hides + if (part < 0 && owner.volumes.size() > 1 && !shown) + // TRN %1% is an object's name. + return Refusal{RefusalKind::Precondition, "several_parts", L("\"%1%\" has several parts: select the part to split into parts."), + {owner.name}}; + const ModelVolume* split = shown ? nullptr : owner.volumes[std::size_t(std::max(part, 0))]; + const std::set before(owner.volumes.begin(), owner.volumes.end()); + wxGetApp().obj_list()->split(object, part, args.expand); + // The part keeps its place, as the first of its shells, and the others follow it. + Targets parts; + for (std::size_t v = 0; v < owner.volumes.size(); ++v) + if (shown || owner.volumes[v] == split || before.count(owner.volumes[v]) == 0) + parts.parts.emplace_back(object, int(v)); + return parts; +} + +std::optional assemble_refusal(const Model& model, const Targets& targets) +{ + if (targets.objects.size() + targets.instances.size() < 2) + return Refusal{RefusalKind::Precondition, "too_few_objects", L("Select two or more objects first.")}; + for (int object : objects_of(targets)) + if (model.objects[std::size_t(object)]->is_cut()) + return Refusal{RefusalKind::Precondition, "cut_object", L("Cut objects can't be assembled.")}; + return std::nullopt; +} + +Outcome assemble_objects(const Targets& targets) +{ + Plater& plater = the_plater(); + const Model& model = plater.model(); + if (std::optional refusal = assemble_refusal(model, targets)) + return *refusal; + ObjectList& list = *wxGetApp().obj_list(); + // The list's selected rows are merged as they are selected, as Assemble merges them. + if (targets.from_selection) { + list.merge(true); + return int(model.objects.size()) - 1; + } + ObjectDataViewModel& rows = *list.GetModel(); + wxDataViewItemArray items; + for (int object : targets.objects) + items.Add(rows.GetItemById(object)); + for (const auto& [object, instance] : targets.instances) + items.Add(rows.GetItemByInstanceId(object, instance)); + list.merge(true, items); + return int(model.objects.size()) - 1; +} + +std::optional part_type_refusal(const Model& model, const Targets& targets, ModelVolumeType type, + std::optional subtype) +{ + if (subtype && !is_precise_seam(type)) + return Refusal{RefusalKind::Precondition, "subtype_without_seam", + // TRN "precise_seam" is a value of the command's type argument: keep it as it is. + L("A subtype is a precise seam's: give it with the type precise_seam.")}; + // As ObjectList::set_volume_type() reads them: a painted modifier keeps its type, and a seam keeps its subtype unless + // one is given. + const ModelVolumeType to = subtype.value_or(type); + std::vector parts; + for (const auto& [object, part] : targets.parts) + if (const ModelVolume* volume = model.objects[std::size_t(object)]->volumes[std::size_t(part)]; !volume->is_painted_modifier()) + parts.push_back(volume); + const auto becomes = [&](const ModelVolume* volume) { return !subtype && is_precise_seam(to) && volume->is_precise_seam() ? volume->type() : to; }; + + if ((to == ModelVolumeType::SUPPORT_BLOCKER || to == ModelVolumeType::SUPPORT_ENFORCER || is_precise_seam(to)) && + std::any_of(parts.begin(), parts.end(), [](const ModelVolume* volume) { return volume->is_svg() || volume->is_text(); })) + return Refusal{RefusalKind::Precondition, "text_part", L("A text or SVG part can only be a part, a negative part or a modifier.")}; + if (std::none_of(parts.begin(), parts.end(), [&](const ModelVolume* volume) { return volume->type() != becomes(volume); })) + return std::nullopt; + if (to != ModelVolumeType::MODEL_PART) { + std::map named; + for (const ModelVolume* volume : parts) + if (volume->type() == ModelVolumeType::MODEL_PART) + ++named[volume->get_object()]; + for (const auto& [object, count] : named) + if (count == std::count_if(object->volumes.begin(), object->volumes.end(), + [](const ModelVolume* volume) { return volume->type() == ModelVolumeType::MODEL_PART; })) + return Refusal{RefusalKind::Precondition, "last_solid_part", L("The type of the last solid object part cannot be changed.")}; + } + return std::nullopt; +} + +Refusal part_wrong_selection() { return {RefusalKind::Precondition, "wrong_selection", L("Select a part first.")}; } + +Outcome change_part_type(const ChangePartTypeArgs& args) +{ + Plater& plater = the_plater(); + const Model& model = plater.model(); + if (std::optional refusal = part_type_refusal(model, args.targets, args.type, args.subtype)) + return *refusal; + std::vector volumes; + for (const auto& [object, part] : args.targets.parts) + volumes.push_back(model.objects[std::size_t(object)]->volumes[std::size_t(part)]); + // A subtype given is set as the Precise Seam Type menu sets it; without one a seam keeps its own. + if (const wxString kept = wxGetApp().obj_list()->set_volume_type(args.subtype.value_or(args.type), !args.subtype, /*show_errors=*/false, + args.targets.parts); + !kept.empty()) + // A reason of the object list's that part_type_refusal() does not foresee. + return Refusal{RefusalKind::Failed, "type_kept", L("The parts kept their type: the object list refused the change.")}; + Targets moved; + for (std::size_t k = 0; k < volumes.size(); ++k) { + const ModelVolumePtrs& now = model.objects[std::size_t(args.targets.parts[k].first)]->volumes; + moved.parts.emplace_back(args.targets.parts[k].first, int(std::find(now.begin(), now.end(), volumes[k]) - now.begin())); + } + return moved; +} + +Outcome order_objects(const OrderObjectsArgs& args) +{ + Plater& plater = the_plater(); + const Model& model = plater.model(); + PartPlateList& plates = plater.get_partplate_list(); + const int count = plates.get_plate_count(); + const int plate = args.plate.value_or(plates.get_curr_plate_index()); + if (plate < 0 || plate >= count) + return no_such_plate(plate, count); + if (args.all ? model.objects.empty() : plates.get_plate(plate)->empty()) + return Refusal{RefusalKind::Precondition, "no_objects_to_order", L("There are no objects to order.")}; + // order_objects() only shows a notification while a gizmo is open. + if (std::optional refusal = gizmo_open(plater)) + return *refusal; + wxGetApp().obj_list()->order_objects(args.order, args.all, plate, args.descending); + // Descending where sorting them ascending would change their order. + const auto plate_of = [&plates](std::size_t object) { return plates.find_instance(int(object), 0); }; + return plate_order(model.objects, plate_of, args.all ? -1 : plate, args.order, false) != model.objects; +} + +Outcome> reorder_objects(const ReorderObjectsArgs& args) +{ + Plater& plater = the_plater(); + const Model& model = plater.model(); + PartPlateList& plates = plater.get_partplate_list(); + const int count = plates.get_plate_count(); + const int plate = args.plate.value_or(plates.get_curr_plate_index()); + if (plate < 0 || plate >= count) + return no_such_plate(plate, count); + const auto plate_of = [&plates, &model] { + std::vector on(model.objects.size()); + for (std::size_t object = 0; object < on.size(); ++object) + on[object] = plates.find_instance(int(object), 0); + return on; + }; + const Outcome> moves = object_order_moves(plate_of(), plate, args.order); + if (!moves) + return moves.refusal(); + if (!moves.value().empty()) { + plater.take_snapshot(_u8L("Object order changed")); + for (const ObjectMove& move : moves.value()) + wxGetApp().obj_list()->move_object(move.from, move.to, plate); + } + std::vector ordered; + const std::vector now = plate_of(); + for (std::size_t object = 0; object < now.size(); ++object) + if (now[object] == plate) + ordered.push_back(int(object)); + return ordered; +} + +std::optional mirror_refusal(const Model& model, const Targets& targets) +{ + if (names_cut_object(model, targets)) + return Refusal{RefusalKind::Precondition, "cut_object", L("Cut objects can't be mirrored.")}; + return std::nullopt; +} + +Outcome mirror_objects(const MirrorObjectsArgs& args) +{ + Plater& plater = the_plater(); + if (std::optional refusal = mirror_refusal(plater.model(), args.targets)) + return *refusal; + if (args.targets.from_selection) { + if (!plater.get_selection().is_from_single_instance()) + return Refusal{RefusalKind::Precondition, "several_instances", L("Mirror takes one instance, or parts of one: select only one.")}; + plater.mirror(args.axis); + return Done{}; + } + Plater::SingleSnapshot single(&plater); + for (const Targets& turn : mirror_turns(plater.model(), args.targets)) { + select_targets(turn); + plater.mirror(args.axis); + } + select_targets(args.targets); + return Done{}; +} + +std::map> objects_by_plate(const std::vector& objects, const std::function& plate_of, int current_plate) +{ + std::map> out; + for (int object : objects) { + const int plate = plate_of(object); + out[plate < 0 ? current_plate : plate].push_back(object); + } + return out; +} + +Outcome>> center_objects(const CenterObjectsArgs& args) +{ + Plater& plater = the_plater(); + PartPlateList& plates = plater.get_partplate_list(); + if (args.plate && (*args.plate < 0 || *args.plate >= plates.get_plate_count())) + return no_such_plate(*args.plate, plates.get_plate_count()); + GLCanvas3D& canvas = *plater.get_view3D_canvas3D(); + const int current = plates.get_curr_plate_index(); + if (args.targets.from_selection) { + if (args.plate) + canvas.do_center_plate(*args.plate); + else + plater.center_selection(); + const std::set objects = objects_of(args.targets); + return std::map>{{args.plate.value_or(current), std::vector(objects.begin(), objects.end())}}; + } + const auto plate_of = [&](int object) { return args.plate ? *args.plate : plates.find_instance(object, 0); }; + const std::map> groups = objects_by_plate(args.targets.objects, plate_of, current); + Plater::SingleSnapshot single(&plater); + for (const auto& [plate, objects] : groups) { + Targets group; + group.objects = objects; + select_targets(group); + canvas.do_center_plate(plate); + } + select_targets(args.targets); + return groups; +} + +std::optional scale_to_fit_refusal(const Model& model, const Targets& targets) +{ + if (names_cut_object(model, targets)) + return Refusal{RefusalKind::Precondition, "cut_object", L("Cut objects can't be scaled to fit the print volume.")}; + return std::nullopt; +} + +Outcome scale_to_fit(const Targets& targets) +{ + Plater& plater = the_plater(); + if (std::optional refusal = scale_to_fit_refusal(plater.model(), targets)) + return *refusal; + if (const BuildVolume_Type type = plater.build_volume().type(); type != BuildVolume_Type::Rectangle && type != BuildVolume_Type::Circle) + return Refusal{RefusalKind::Precondition, "bed_shape", L("Scale to fit needs a rectangular or circular bed.")}; + if (!targets.from_selection) + select_targets(targets); + plater.scale_selection_to_fit_print_volume(); + return Done{}; +} + +Targets objects_above_bed(const Model& model, const Targets& targets) +{ + // As Selection::can_drop() measures it. + const auto off_bed = [](double min_z) { return std::abs(min_z) > -SINKING_Z_THRESHOLD; }; + Targets out; + for (int object : targets.objects) { + const ModelObject& owner = *model.objects[std::size_t(object)]; + for (std::size_t i = 0; i < owner.instances.size(); ++i) + if (off_bed(owner.get_instance_min_z(i))) { + out.objects.push_back(object); + break; + } + } + for (const auto& [object, instance] : targets.instances) + if (off_bed(model.objects[std::size_t(object)]->get_instance_min_z(std::size_t(instance)))) + out.instances.emplace_back(object, instance); + for (const auto& [object, part] : targets.parts) { + const ModelObject& owner = *model.objects[std::size_t(object)]; + const ModelVolume& volume = *owner.volumes[std::size_t(part)]; + if (owner.instances.empty()) + continue; + const Transform3d placed = owner.instances.front()->get_matrix() * volume.get_matrix(); + if (off_bed(volume.mesh().transformed_bounding_box(placed).min.z())) + out.parts.emplace_back(object, part); + } + return out; +} + +Refusal already_on_bed() { return {RefusalKind::Precondition, "on_bed", L("Nothing to drop: it already rests on the bed.")}; } + +Outcome drop_objects(const Targets& targets) +{ + Plater& plater = the_plater(); + if (targets.from_selection) { + if (!plater.get_selection().can_drop()) + return false; + plater.drop_selection(); + return true; + } + // Each instance and each part that is off the bed, as Drop drops it selected alone: an object's instances one by one. + const Model& model = plater.model(); + std::set> instances; + Targets each; + for (int object : targets.objects) + for (std::size_t i = 0; i < model.objects[std::size_t(object)]->instances.size(); ++i) + instances.emplace(object, int(i)); + instances.insert(targets.instances.begin(), targets.instances.end()); + each.instances.assign(instances.begin(), instances.end()); + each.parts = targets.parts; + each = objects_above_bed(model, each); + std::vector turns; + for (const auto& instance : each.instances) { + Targets one; + one.instances = {instance}; + turns.push_back(std::move(one)); + } + for (const auto& part : each.parts) { + Targets one; + one.parts = {part}; + turns.push_back(std::move(one)); + } + { + Plater::SingleSnapshot single(&plater); + for (const Targets& turn : turns) { + select_targets(turn); + plater.drop_selection(); + } + } + select_targets(targets); + return !turns.empty(); +} + +std::vector> orientable(const Model& model, const std::set& objects, const std::function& locked) +{ + std::vector> out; + for (int object : objects) { + const ModelObject& owner = *model.objects[std::size_t(object)]; + if (!owner.printable) + continue; + for (std::size_t i = 0; i < owner.instances.size(); ++i) + if (!locked(object, int(i))) + out.emplace_back(object, int(i)); + } + return out; +} + +std::function on_locked_plate(PartPlateList& plates) +{ + return [&plates](int object, int instance) { + const int plate = plates.find_instance(object, instance); + return plate >= 0 && plate < plates.get_plate_count() && plates.is_locked(plate); + }; +} + +Outcome orient_objects(const OrientObjectsArgs& args) +{ + Plater& plater = the_plater(); + const Model& model = plater.model(); + PartPlateList& plates = plater.get_partplate_list(); + if (model.objects.empty()) + return Refusal{RefusalKind::Precondition, "no_objects_to_orient", L("There are no objects to orient.")}; + if (!plater.get_ui_job_worker().is_idle()) + return job_running(); + std::set objects(args.targets.objects.begin(), args.targets.objects.end()); + for (int plate : args.plates) { + if (plate < 0 || plate >= plates.get_plate_count()) + return no_such_plate(plate, plates.get_plate_count()); + bool holds = false; + for (std::size_t o = 0; o < model.objects.size(); ++o) + for (std::size_t i = 0; i < model.objects[o]->instances.size(); ++i) + if (plates.find_instance(int(o), int(i)) == plate) { + objects.insert(int(o)); + holds = true; + } + // Before the lock: a plate of no objects would leave none to orient, which the job takes for every object. + if (!holds) + // TRN %1% is a plate index. + return Refusal{RefusalKind::Precondition, "no_objects_to_orient", L("Plate %1% has no objects to orient."), {std::to_string(plate)}}; + if (plates.is_locked(plate)) + return Refusal{RefusalKind::Precondition, "plate_locked", L("This plate is locked.\nCannot auto-orient on this plate.")}; + } + const bool named = !args.targets.from_selection || !args.plates.empty(); + const std::function locked = on_locked_plate(plates); + if (named && orientable(model, objects, locked).empty()) { + // The job turns every other object when it can turn none of those it is given: a call that names its objects + // turns none it did not name. + const bool all_locked = std::all_of(objects.begin(), objects.end(), [&](int object) { + for (std::size_t i = 0; i < model.objects[std::size_t(object)]->instances.size(); ++i) + if (!locked(object, int(i))) + return false; + return true; + }); + if (all_locked) + return Refusal{RefusalKind::Precondition, "plate_locked", + L("All the selected objects are on a locked plate.\nCannot auto-orient these objects.")}; + return Refusal{RefusalKind::Precondition, "not_printable", + L("Auto-Orient can turn none of these objects: they are not printable, or stand on a locked plate.")}; + } + if (named) { + Targets selected; + selected.objects.assign(objects.begin(), objects.end()); + select_targets(selected); + } + // A plate's Auto Rotate icon leaves the plate-only state behind. + plater.set_prepare_state(Job::PREPARE_STATE_DEFAULT); + plater.orient(std::vector(objects.begin(), objects.end())); + return Done{}; +} + +Outcome add_primitive(const AddPrimitiveArgs& args) +{ + if (args.name) + if (std::optional refusal = rename_refusal(*args.name)) + return *refusal; + Plater& plater = the_plater(); + Plater::SingleSnapshot single(&plater); + show_prepare_view(); + if (args.plate) + if (const Outcome selected = select_plate({*args.plate}); !selected) + return selected.refusal(); + ObjectList& list = *wxGetApp().obj_list(); + if (args.ask && !list.can_add_shape_object()) + return Refusal{RefusalKind::Precondition, "object_selected", + L("Deselect all objects to add a primitive object. To add a shape to the selected object, use its Add Part menu.")}; + const std::size_t before = plater.model().objects.size(); + list.load_shape_object(args.shape, args.ask, args.size); + if (plater.model().objects.size() == before) + return Refusal{RefusalKind::Failed, "not_added", L("No object was added.")}; + const int index = int(before); + if (args.name) + if (const Outcome renamed = rename_object({index, -1, *args.name}); !renamed) + return renamed.refusal(); + if (args.position) { + plater.model().objects[std::size_t(index)]->instances.front()->set_offset(*args.position); + placed_instance(index, 0, true); + } + return index; +} + +std::vector> set_printable(Model& model, const Targets& targets, bool printable) +{ + std::vector> out; + const auto set = [&](int object, int instance) { + if (std::find(out.begin(), out.end(), std::make_pair(object, instance)) != out.end()) + return; + model.objects[std::size_t(object)]->instances[std::size_t(instance)]->printable = printable; + out.emplace_back(object, instance); + }; + for (int object : targets.objects) + for (std::size_t i = 0; i < model.objects[std::size_t(object)]->instances.size(); ++i) + set(object, int(i)); + for (const auto& [object, instance] : targets.instances) + set(object, instance); + return out; +} + +Outcome>> set_objects_printable(const SetPrintableArgs& args) +{ + Plater& plater = the_plater(); + // The Printable cell's undo step, which has no name. + Plater::TakeSnapshot snapshot(&plater, ""); + const std::vector> set = set_printable(plater.model(), args.targets, args.printable); + ObjectList& list = *wxGetApp().obj_list(); + std::set objects; + for (const auto& [object, instance] : set) { + list.update_printable_state(object, instance); + objects.insert(std::size_t(object)); + } + plater.get_view3D_canvas3D()->update_instance_printable_state_for_objects(std::vector(objects.begin(), objects.end())); + plater.update(); + plater.reload_paint_after_background_process_apply(); + return set; +} + +std::vector set_auto_drop(Model& model, const Targets& targets, bool auto_drop) +{ + std::vector out; + const auto set = [&](int object) { + if (std::find(out.begin(), out.end(), object) != out.end()) + return; + model.objects[std::size_t(object)]->auto_drop = auto_drop; + out.push_back(object); + }; + for (int object : targets.objects) + set(object); + for (const auto& [object, instance] : targets.instances) + set(object); + for (const auto& [object, part] : targets.parts) + set(object); + return out; +} + +Outcome> set_objects_auto_drop(const SetAutoDropArgs& args) +{ + Plater& plater = the_plater(); + // The 3D view's Auto Drop's undo step. + Plater::TakeSnapshot snapshot(&plater, args.auto_drop ? "Set Selection Auto-Drop Enabled" : "Set Selection Auto-Drop Disabled"); + const std::vector set = set_auto_drop(plater.model(), args.targets, args.auto_drop); + plater.update(); + return set; +} + +MeshErrors mesh_errors(const ModelObject& object) +{ + const TriangleMeshStats stats = object.get_object_stl_stats(); + const RepairedMeshErrors fixed = stats.repaired_errors; + MeshErrors out; + out.open_edges = stats.open_edges; + out.manifold = stats.manifold(); + out.degenerate_facets = fixed.degenerate_facets; + out.edges_fixed = fixed.edges_fixed; + out.facets_removed = fixed.facets_removed; + out.facets_reversed = fixed.facets_reversed; + out.backwards_edges = fixed.backwards_edges; + return out; +} + +Outcome fix_objects(const FixObjectsArgs& args, const FixProgress& progress) +{ + Plater& plater = the_plater(); + Model& model = plater.model(); + if (std::optional refusal = gizmo_open(plater)) + return *refusal; + + // What is repaired, in turn: [object, part], part -1 for a whole object. + std::vector> models; + if (args.all || args.plate) { + std::vector objects; + if (args.all) { + for (std::size_t o = 0; o < model.objects.size(); ++o) + objects.push_back(int(o)); + } else { + PartPlateList& plates = plater.get_partplate_list(); + if (*args.plate < 0 || *args.plate >= plates.get_plate_count()) + return no_such_plate(*args.plate, plates.get_plate_count()); + for (const ModelObject* object : plates.get_plate(*args.plate)->get_objects_on_this_plate()) + objects.push_back(int(std::find(model.objects.begin(), model.objects.end(), object) - model.objects.begin())); + std::sort(objects.begin(), objects.end()); + objects.erase(std::unique(objects.begin(), objects.end()), objects.end()); + } + if (objects.empty()) + return Refusal{RefusalKind::Precondition, "no_objects", L("There are no objects to repair.")}; + for (int object : objects) + models.emplace_back(object, -1); + } else { + // An instance stands for its object, whose meshes its instances share. + std::vector whole = args.targets.objects; + for (const auto& [object, instance] : args.targets.instances) + if (std::find(whole.begin(), whole.end(), object) == whole.end()) + whole.push_back(object); + for (int object : whole) + models.emplace_back(object, -1); + for (const auto& [object, part] : args.targets.parts) + if (std::find(whole.begin(), whole.end(), object) == whole.end()) + models.emplace_back(object, part); + } + + const bool keep_painting = wxGetApp().app_config->get_bool("keep_painting"); + ObjectList& list = *wxGetApp().obj_list(); + Plater::TakeSnapshot snapshot(&plater, _u8L("Repairing model object")); + return repair_models(model, models, progress, keep_painting, [&](int index, int part) { + model.objects[std::size_t(index)]->ensure_on_bed(); + plater.changed_mesh(index); + plater.get_partplate_list().notify_instance_update(index, 0); + list.update_plate_values_for_items(); + list.update_item_error_icon(index, part); + list.update_info_items(std::size_t(index)); + }); +} + +FixedModels repair_models(Model& model, const std::vector>& models, const FixProgress& progress, + bool keep_painting, const std::function& changed) +{ + FixedModels out; + for (std::size_t k = 0; k < models.size(); ++k) { + const auto [index, part] = models[k]; + ModelObject& object = *model.objects[std::size_t(index)]; + FixedModel fixed; + fixed.object = index; + fixed.part = part; + fixed.name = part < 0 ? object.name : object.volumes[std::size_t(part)]->name; + fixed.before = mesh_errors(object); + const auto painted = [&object]() { + return std::count_if(object.volumes.begin(), object.volumes.end(), + [](const ModelVolume* volume) { return volume->is_any_painted(); }); + }; + const auto painted_before = painted(); + const auto report = [&progress, k](int percent, const std::string& what) { return progress(k, percent, what); }; + // A cancel ends the repair. The parts repaired before it keep their new mesh, so a model whose mesh changed before + // the cancel goes to `changed` and is listed as any other. + fixed.cancelled = !fix_model_with_cgal(object, part, report, fixed.failed, keep_painting, &fixed.changed); + if (fixed.changed) { + fixed.painting_removed = painted() < painted_before; + if (changed) + changed(index, part); + } + fixed.after = mesh_errors(object); + out.cancelled = fixed.cancelled; + if (!fixed.cancelled || fixed.changed) + out.models.push_back(std::move(fixed)); + if (out.cancelled) + break; + } + return out; +} + +Outcome clone_objects(const CloneObjectsArgs& args, const std::function& pasted) +{ + Plater& plater = the_plater(); + const Model& model = plater.model(); + if (!args.targets.from_selection) + select_targets(args.targets); + ClonedObjects out; + const std::size_t before = model.objects.size(); + out.arranged = args.arrange.value_or(wxGetApp().app_config->get("auto_arrange") == "true"); + // Better to stop rendering canvas while processing. The Clone dialog's Cancel thaws it as it ends the dialog. + plater.Freeze(); + const bool all_pasted = plater.canvas3D()->get_selection().clone(args.count, [&pasted, &args](int done) { + return !pasted || pasted(done, args.count); + }); + if (!all_pasted) { + plater.undo(); + if (plater.IsFrozen()) + plater.Thaw(); + return Refusal{RefusalKind::Failed, "cancelled", L("Cloning was cancelled: the copies were taken back.")}; + } + if (out.arranged) { + plater.set_prepare_state(Job::PREPARE_STATE_MENU); + plater.arrange(); + } + if (plater.IsFrozen()) + plater.Thaw(); + for (std::size_t o = before; o < model.objects.size(); ++o) + out.objects.objects.push_back(int(o)); + return out; +} + +bool has_reload_source(const ModelVolume& volume) +{ + return !volume.source.is_from_builtin_objects && !volume.source.input_file.empty() && + !boost::filesystem::path(volume.source.input_file).extension().string().empty(); +} + +ReloadSources reload_sources(const Model& model, const Targets& targets, const std::function& exists) +{ + // Every part of an object named, or of the object of an instance named, whose parts its instances share. + std::set whole(targets.objects.begin(), targets.objects.end()); + for (const auto& [object, instance] : targets.instances) + whole.insert(object); + std::vector> parts; + for (int object : whole) + for (std::size_t v = 0; v < model.objects[std::size_t(object)]->volumes.size(); ++v) + parts.emplace_back(object, int(v)); + for (const auto& part : targets.parts) + if (std::find(parts.begin(), parts.end(), part) == parts.end()) + parts.push_back(part); + + ReloadSources out; + for (const auto& [object, part] : parts) { + const ModelObject& owner = *model.objects[std::size_t(object)]; + const ModelVolume& volume = *owner.volumes[std::size_t(part)]; + if (!has_reload_source(volume)) + continue; + std::string found; + if (exists(volume.source.input_file)) { + found = volume.source.input_file; + } else if (!owner.input_file.empty()) { + // A file of its name in the folder of its object's file, where a project moved with its parts finds them. + boost::filesystem::path beside = boost::filesystem::path(owner.input_file).remove_filename(); + if (!beside.empty()) { + beside /= boost::filesystem::path(volume.source.input_file).filename(); + if (exists(beside.string())) + found = beside.string(); + } + } + if (found.empty()) { + out.missing.emplace_back(object, part); + continue; + } + out.parts.emplace_back(object, part); + if (std::find(out.paths.begin(), out.paths.end(), found) == out.paths.end()) + out.paths.push_back(found); + } + std::sort(out.paths.begin(), out.paths.end()); + return out; +} + +Outcome reload_parts(const ReloadFromDiskArgs& args) +{ + Plater& plater = the_plater(); + const Model& model = plater.model(); + if (std::optional refusal = gizmo_open(plater)) + return *refusal; + Targets targets = args.targets; + if (args.all) { + // As Reload All does, but for the cut objects, which Reload from disk refuses. + targets = Targets{}; + for (std::size_t o = 0; o < model.objects.size(); ++o) + if (!model.objects[o]->is_cut()) + targets.objects.push_back(int(o)); + if (targets.objects.empty()) + return Refusal{RefusalKind::Precondition, "no_objects", L("There are no objects to reload.")}; + } else if (names_cut_object(model, targets)) { + return Refusal{RefusalKind::Precondition, "cut_object", L("Cut objects can't be reloaded from disk.")}; + } + const ReloadSources sources = reload_sources(model, targets, [](const std::string& path) { + boost::system::error_code ec; + return boost::filesystem::exists(path, ec); + }); + if (sources.parts.empty() && sources.missing.empty()) + return Refusal{RefusalKind::Precondition, "no_source", L("None of these parts was loaded from a file, so none can be reloaded.")}; + ReloadedParts out; + out.missing = sources.missing; + if (!sources.parts.empty()) { + const Plater::ReloadResult reloaded = plater.reload_parts_from_disk(sources.parts); + out.reloaded = reloaded.reloaded; + out.unmatched = reloaded.unmatched; + out.unreadable = reloaded.unreadable; + } + return out; +} + +std::optional replacement_refusal(const Model& loaded) +{ + if (loaded.objects.size() > 1 || (loaded.objects.size() == 1 && loaded.objects.front()->volumes.size() > 1)) + return several_parts_loaded(); + return std::nullopt; +} + +Outcome> replaced_part(const Model& model, const Targets& targets) +{ + if (!targets.parts.empty()) + return targets.parts.front(); + const int index = targets.objects.empty() ? targets.instances.front().first : targets.objects.front(); + const ModelObject& object = *model.objects[std::size_t(index)]; + if (object.volumes.size() != 1) + return Refusal{RefusalKind::Precondition, "several_parts", + // TRN %1% is an object's name. + L("\"%1%\" has several parts: name the part to replace."), {object.name}}; + return std::make_pair(index, 0); +} + +Outcome replace_part(const ReplacePartArgs& args) +{ + Plater& plater = the_plater(); + if (std::optional refusal = gizmo_open(plater)) + return *refusal; + const ModelObject& object = *plater.model().objects[std::size_t(args.object)]; + if (object.is_cut()) + return Refusal{RefusalKind::Precondition, "cut_object", L("A part of a cut object can't be replaced.")}; + // The replacement sorts the object's parts by type, which can move the new part: it is the one whose id is not kept. + std::vector kept; + for (std::size_t v = 0; v < object.volumes.size(); ++v) + if (int(v) != args.part) + kept.push_back(object.volumes[v]->id()); + switch (plater.replace_part_with_file(args.object, args.part, args.path)) { + case Plater::ReplaceResult::Replaced: break; + case Plater::ReplaceResult::Unreadable: + // TRN %1% is a file's path. + return Refusal{RefusalKind::Failed, "not_loaded", L("%1% could not be loaded."), {args.path}}; + case Plater::ReplaceResult::Cancelled: + return Refusal{RefusalKind::Failed, "cancelled", L("The STEP file's mesh options were cancelled, so nothing was replaced.")}; + case Plater::ReplaceResult::SeveralParts: return several_parts_loaded(); + } + for (std::size_t v = 0; v < object.volumes.size(); ++v) + if (std::find(kept.begin(), kept.end(), object.volumes[v]->id()) == kept.end()) + return int(v); + return args.part; +} + +void placed_instance(int object, int instance, bool drop) +{ + Plater& plater = the_plater(); + ModelObject& owner = *plater.model().objects[std::size_t(object)]; + // The bounding box is cached: ensure_on_bed() must measure the new placement. + owner.invalidate_bounding_box(); + if (drop) + owner.ensure_on_bed(); + plater.get_partplate_list().notify_instance_update(object, instance); + wxGetApp().obj_list()->update_plate_values_for_items(); + plater.changed_object(object); +} + +}}} // namespace Slic3r::GUI::Ops diff --git a/src/slic3r/GUI/Operations/ObjectOps.hpp b/src/slic3r/GUI/Operations/ObjectOps.hpp new file mode 100644 index 0000000000..4144796119 --- /dev/null +++ b/src/slic3r/GUI/Operations/ObjectOps.hpp @@ -0,0 +1,508 @@ +#pragma once + +#include "Outcome.hpp" + +#include "libslic3r/ObjectID.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/libslic3r.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Slic3r { +class Model; +class ModelObject; +class ModelVolume; +enum class ModelVolumeType : int; +namespace GUI { +class PartPlateList; +enum class ObjectOrder; +} +} // namespace Slic3r + +// The objects of the project, their instances and their parts: what a command acts on, and the operations that add, +// delete, rename, separate, split, assemble, order, mirror, centre, scale, drop and orient them, change what a part +// is, mark them printable, turn their Auto Drop on or off, repair their meshes, clone them, reload them from their files +// and replace a part's mesh with a file's. An operation takes indices into Model::objects, which its caller has checked +// (Mcp::resolve_targets() does). +namespace Slic3r { namespace GUI { namespace Ops { + +// What a command acts on: whole objects by index, then [object, instance] and [object, part] pairs, in the order +// named, each once. +struct Targets +{ + std::vector objects; + std::vector> instances; + std::vector> parts; + bool from_selection = false; // none was named, so these are the Prepare view's selection +}; + +// The refusal of a command given no target while nothing is selected (nothing_selected). +Refusal nothing_selected(); +// The refusal of a command given no target while the selection holds what it does not act on (wrong_selection). +Refusal wrong_selection(); +// The refusal of a command of one target given several, or several selected (one_object_only). +Refusal one_object_only(); +// The refusal of Select All while a gizmo that keeps its selection is open (gizmo_open), which lets Select All +// select nothing. +Refusal gizmo_keeps_selection(); + +// ---- Delete ---- + +// What deleting `targets` deletes, as the object list deletes a selection: an object every instance or every part +// of which is named goes whole, and what a whole object holds is not named again. +Targets deletion(const Model& model, const Targets& targets); + +// What keeps `targets` from being deleted without a question, or none: a cut object or a solid or negative part of +// one (cut_object, with the question the object list asks before it breaks the cut), and an object's last solid part +// without the object (last_solid_part). +std::optional delete_refusal(const Model& model, const Targets& targets); + +// Whether what delete_refusal() gives is refused before anything is deleted, or left to the object list, which asks +// its question about a cut object and shows its message about a last solid part, as for a person's Delete. +enum class DeleteChecks { Refuse, ObjectList }; + +// The identities (ObjectBase::id()) of what `targets` names in `model`, in the order named: its objects', its instances' +// and its parts'. Unlike an index, an identity stays with its object, instance or part when a delete moves what follows. +struct TargetIds +{ + std::vector objects; + std::vector instances; + std::vector parts; +}; +TargetIds target_ids(const Model& model, const Targets& targets); + +// What a delete asked for went, and what stayed. +struct DeletedTargets +{ + Targets deleted; // with the indices it had + Targets kept; // with its indices afterwards +}; +// What of `doomed`, named in the model before a delete, `before` being their identities there (target_ids()), the model +// afterwards, `after`, no longer holds: found by identity, since the delete moved the indices. +DeletedTargets deleted_targets(const Targets& doomed, const TargetIds& before, const Model& after); + +struct DeleteObjectsArgs +{ + Targets targets; + bool all = false; // every object, as Delete All does, in place of the targets + DeleteChecks checks = DeleteChecks::Refuse; +}; +// Deletes the targets, as Delete does with them selected, in one "Delete Selected Objects" undo step, or every +// object, as Delete All does, cut objects too without a question. Returns what it deleted of what deletion() gives, and +// what of that it kept (deleted_targets()): with DeleteChecks::ObjectList the object list deletes from the last item and +// stops at one it refuses or asks about, after deleting those after it. +// Refuses: no_objects (all, with none), what delete_refusal() gives (with DeleteChecks::Refuse), and nothing_deleted +// (nothing_deleted()). +Outcome delete_objects(const DeleteObjectsArgs& args); +// The refusal of a delete the object list did not make (nothing_deleted): it refused the last solid part, or the +// question it asked about a cut object was cancelled or answered by invalidating the cut. +Refusal nothing_deleted(); + +// ---- Rename ---- + +// What keeps `name` from being an object's or a part's name, or none: an empty name (empty_name), which the Rename +// dialog leaves unchanged, and a character a file name cannot hold (invalid_name), which the object list refuses. +std::optional rename_refusal(const std::string& name); + +// The refusal of Rename with a selection it does not rename, such as an instance, in the object menu row's words +// (wrong_selection). +Refusal rename_wrong_selection(); + +// What keeps part `part` of object `object` (-1 for the object itself) from being renamed, or none: a part the object +// list does not show (part_not_listed), a cut's connector. +std::optional unlisted_part_refusal(const Model& model, int object, int part); + +struct RenameObjectArgs +{ + int object = 0; + int part = -1; // a part of the object, or -1 for the object itself + std::string name; +}; +// Renames the object or the part as the Rename dialog does, in one "Rename Object" or "Rename Part" undo step. A part +// of an object of one part has no row of its own in the object list, which names the two alike, so the object is +// renamed with it. Returns the name it had. +// Refuses: what rename_refusal() and unlisted_part_refusal() give. +Outcome rename_object(const RenameObjectArgs& args); + +// ---- Set as Individual Objects ---- + +// What keeps `targets`, an object or instances of one object, from being made separate objects, or none: an object +// of one instance (one_instance), an instance the object lacks (no_such_instance), parts (wrong_selection), and +// instances of several objects (one_object_only). +std::optional separate_refusal(const Model& model, const Targets& targets); + +// Makes the targets' instances separate objects, added after the others, as Set as Individual Objects does, in one +// undo step: with the whole object (or every instance) each instance but the first becomes an object of its own, and +// with some of its instances those become one new object. Returns the objects that hold the instances afterwards: +// the object and its new objects, or the new object. +// Refuses: what separate_refusal() gives. +Outcome separate_instances(const Targets& targets); + +// ---- Split ---- + +// What keeps `targets` from being split, or none: a mesh of one shell (one_shell), an object of one part or a part. +std::optional split_refusal(const Model& model, const Targets& targets); + +struct SplitObjectArgs +{ + Targets target; // one object, or for parts one part of it + bool to_objects = true; // into objects, else into parts + std::optional keep_z; // the answer to Split's Auto-Drop question: true keeps the height of what floats + bool ask = false; // with keep_z none, the question is asked, and a message tells an object of one + // piece, as Split does; else the split is refused for them + bool expand = false; // into parts, the object's row is opened on its parts, as a split from that row + // opens it +}; +// Splits the target as Split > To Objects or To Parts does, in one undo step. Into objects, the object's pieces are +// added last as objects, which are selected, and the object is removed; into parts, its part, or its one part, becomes +// one part per shell, after it among its parts (an import shown as one part shows its bodies). Returns the new objects, +// or the parts the part became, with their indices afterwards. +// Refuses: what split_refusal() gives; several_parts (into parts, an object of several parts: its part splits); +// one_piece (into objects, an object whose solid parts are one piece; with ask, after the message); auto_drop_question +// (with neither keep_z nor ask, a split that would ask it). +Outcome split_object(const SplitObjectArgs& args); + +// ---- Assemble ---- + +// What keeps `targets` from being assembled into one object, or none: fewer than two objects or instances, as the +// object list counts its rows (too_few_objects), and a cut object (cut_object). +std::optional assemble_refusal(const Model& model, const Targets& targets); + +// Assembles the targets into one object of parts named Assembly, as Assemble does with them selected, in one undo step: +// an instance named becomes an object of its own first, the objects are removed, and the new object is added last and +// selected. Targets read from the selection are the object list's selected rows, which it assembles as they are. +// Returns its index. +// Refuses: what assemble_refusal() gives. +Outcome assemble_objects(const Targets& targets); + +// ---- Change Type ---- + +// What keeps the parts of `targets` from becoming `type`, or with a precise seam's `subtype` that one, or none: what +// ObjectList::set_volume_type() refuses, a text or SVG part made a support blocker or enforcer or a precise seam +// (text_part) and an object's last solid part made something else (last_solid_part); and a subtype with a type other +// than a precise seam (subtype_without_seam). +std::optional part_type_refusal(const Model& model, const Targets& targets, ModelVolumeType type, + std::optional subtype); + +// The refusal of Change Type with a selection of anything but parts, in the row's words (wrong_selection). +Refusal part_wrong_selection(); + +struct ChangePartTypeArgs +{ + Targets targets; // parts + ModelVolumeType type; + std::optional subtype; // a precise seam's; none keeps a seam's own, as Change Type does +}; +// Changes what the parts are, as Change Type does, in one undo step; a painted modifier keeps its type. Parts are +// listed by type, so their indices change. Returns the parts with their indices afterwards. +// Refuses: what part_type_refusal() gives. +Outcome change_part_type(const ChangePartTypeArgs& args); + +// ---- Order ---- + +struct OrderObjectsArgs +{ + ObjectOrder order; + std::optional plate; // none: the current plate + bool all = false; // every plate, in place of one + std::optional descending; // none: descending when the order they have is ascending already, as Order By does +}; +// Orders a plate's objects, or every plate's, as the plate menu's Order By does (ObjectList::order_objects()), which +// sets the object list and print order, in one undo step. Returns whether they are in descending order. +// Refuses: no_such_plate, no_objects_to_order, gizmo_open. +Outcome order_objects(const OrderObjectsArgs& args); + +struct ReorderObjectsArgs +{ + std::optional plate; // none: the current plate + std::vector order; // the plate's objects, each once, in the order wanted +}; +// Puts a plate's objects in `order`, which sets the object list and print order, as dragging each in the object list +// onto the one in its place does (ObjectList::OnDrop(), the drops object_order_moves() gives), in one undo step. The +// objects of other plates keep their order. Returns the plate's objects, by their indices afterwards, in that order. +// Refuses: no_such_plate, and what object_order_moves() refuses. +Outcome> reorder_objects(const ReorderObjectsArgs& args); + +// ---- Mirror, centre, scale to fit, drop, orient ---- +// Each runs the function of its row on the targets selected in the Prepare view, the view shown first, and leaves them +// selected. Targets read from the selection are the selection, which it acts on as it is, as the row does. + +// What keeps `targets` from being mirrored, or none: a cut object (cut_object). +std::optional mirror_refusal(const Model& model, const Targets& targets); + +struct MirrorObjectsArgs +{ + Targets targets; + Axis axis = Axis::X; +}; +// Mirrors the targets along `axis`, as Mirror does (Plater::mirror()), in one undo step: each instance of an object +// named, each instance named, and the parts of each object named, in turn, since Mirror takes one instance or parts of +// one. The selection is mirrored as it is. +// Refuses: what mirror_refusal() gives; several_instances (a selection of more than one instance). +Outcome mirror_objects(const MirrorObjectsArgs& args); + +// `objects` grouped by the plate each stands on, `plate_of` (-1: none), an object on no plate going with +// `current_plate`'s group; each group in the order of `objects`. +std::map> objects_by_plate(const std::vector& objects, const std::function& plate_of, int current_plate); + +struct CenterObjectsArgs +{ + Targets targets; + std::optional plate; // every target centred on this plate, in place of the one each stands on +}; +// Centres the targets on their plate, as Center does, in one undo step. The selection with no plate moves as one to the +// centre of the current plate (Selection::center()), and with a plate to that plate's. Objects named are grouped by the +// plate the first instance of each stands on, or all on `plate` (objects_by_plate(), with the current plate for none), +// and each group moves as one to its plate's centre (Selection::center_plate()). Returns the objects centred on each +// plate. +// Refuses: no_such_plate. +Outcome>> center_objects(const CenterObjectsArgs& args); + +// What keeps `targets` from being scaled to fit the print volume, or none: a cut object (cut_object). +std::optional scale_to_fit_refusal(const Model& model, const Targets& targets); + +// Scales the targets as one to fit the current plate's print volume and moves them into it, as Scale to Fit Print Volume +// does (Plater::scale_selection_to_fit_print_volume()), in one undo step. +// Refuses: what scale_to_fit_refusal() gives; bed_shape (a bed neither rectangular nor circular). +Outcome scale_to_fit(const Targets& targets); + +// What of `targets` does not rest on the bed, as Drop measures it: an object one of whose instances, an instance, or a +// part whose lowest point on instance 0, is above the bed or below it. +Targets objects_above_bed(const Model& model, const Targets& targets); + +// The answer of a drop whose targets rest on the bed already: nothing moved (on_bed). A call that gets it did not fail. +Refusal already_on_bed(); + +// Drops the targets onto the bed, as Drop does (Plater::drop_selection()), in one undo step: each instance and each part +// named that objects_above_bed() gives, in turn, and the selection as one, by its lowest point. Returns whether anything +// moved. +Outcome drop_objects(const Targets& targets); + +// The instances of `objects` Auto-Orient turns, as OrientJob::prepare_selection() takes them: each instance of a printable +// object (ModelObject::printable) that `locked` (object, instance) does not put on a locked plate. +std::vector> orientable(const Model& model, const std::set& objects, const std::function& locked); +// Whether an instance stands on a locked plate of `plates`, as the job reads it, for orientable(). +std::function on_locked_plate(PartPlateList& plates); + +struct OrientObjectsArgs +{ + Targets targets; // objects; none read from the selection: every object, as Auto-Orient with nothing selected + std::vector plates; // the objects that stand on these plates too +}; +// Starts Auto-Orient of the targets, as the toolbar's Auto-Orient does with them selected, in the background (OrientJob) +// as one undo step; the UI job worker is busy until it ends. An object on a locked plate, or one that is not printable, +// keeps its orientation. Objects named, or of the plates named, are the only ones turned; targets read from the +// selection are turned as the job turns a selection: every other object when it can turn none of them and none of them +// stands on a locked plate, and nothing, with the job's warning, when it can turn none and one stands on a locked plate. +// Refuses: no_objects_to_orient (no objects, or a plate named that holds none), job_running, no_such_plate, +// plate_locked (a plate named is locked, or every object named is on a locked plate), not_printable (nothing named that +// the job can turn: each is not printable, or stands on a locked plate). +Outcome orient_objects(const OrientObjectsArgs& args); + +// ---- Add Primitive ---- + +struct AddPrimitiveArgs +{ + std::string shape; // the object list's name of the shape: Cube, Cylinder, Sphere, Cone, Disc, Torus + std::vector size; // the Primitive size dialog's fields; none: the built-in size, or with ask the + // dialog's + std::optional plate; // the plate it is added on, which becomes the current one; none: the current plate + std::optional name; // its name (rename_object()); none: its shape's + std::optional position; // where its first instance goes, in bed coordinates, as object_transform's + // position, after which it rests on the bed; none: where Add Primitive puts it + bool ask = false; // as Add Primitive: refused while an object is selected, and the size dialog asks +}; +// Adds the shape as a new object, as Add Primitive does in the Prepare view, the view shown first, named and placed, in +// one undo step, and selects it. Returns its index. +// Refuses: what rename_refusal() gives for the name, before anything is added; no_such_plate; object_selected (with +// ask, while an object is selected); not_added (the size dialog cancelled); what rename_object() refuses. +Outcome add_primitive(const AddPrimitiveArgs& args); + +// ---- Printable ---- + +// Sets ModelInstance::printable of each instance `targets` names and of every instance of each object it names, as the +// object list's Printable cell does for an instance row and an object row. Returns those instances, each once, the +// objects' first, in the order named. +std::vector> set_printable(Model& model, const Targets& targets, bool printable); + +struct SetPrintableArgs +{ + Targets targets; // objects and instances + bool printable = true; +}; +// Marks the targets printable or not (set_printable()), as the Printable cell does, in one undo step; the object list, +// the 3D view and the slicing take the change. Returns the instances set. +Outcome>> set_objects_printable(const SetPrintableArgs& args); + +// ---- Auto Drop ---- + +// Sets ModelObject::auto_drop of each object `targets` names or names an instance or a part of, which all its instances +// share. Returns those objects, each once, in the order named. +std::vector set_auto_drop(Model& model, const Targets& targets, bool auto_drop); + +struct SetAutoDropArgs +{ + Targets targets; + bool auto_drop = true; +}; +// Turns Auto Drop on or off for the targets' objects (set_auto_drop()), as the 3D view's Auto Drop does +// (Selection::set_auto_drop()), in one undo step. An object it is turned on for drops at its next move. Returns the +// objects set. +Outcome> set_objects_auto_drop(const SetAutoDropArgs& args); + +// ---- Fix Model ---- + +// The mesh errors of an object's parts, as the object list's warning icon reads them +// (ModelObject::get_object_stl_stats()): the open edges left, and what the loader or a repair fixed. +struct MeshErrors +{ + int open_edges = 0; + bool manifold = true; // no open edge + int degenerate_facets = 0; + int edges_fixed = 0; + int facets_removed = 0; + int facets_reversed = 0; + int backwards_edges = 0; +}; +MeshErrors mesh_errors(const ModelObject& object); + +struct FixObjectsArgs +{ + Targets targets; // whole objects, and parts of objects + std::optional plate; // in place of the targets, the objects on this plate, as Fix All on the current plate + bool all = false; // in place of the targets, every object +}; +// One object, or one part of an object, as Fix Model repaired it. +struct FixedModel +{ + int object = 0; + int part = -1; // -1: the whole object + std::string name; // the object's, or the part's + bool changed = false; + std::string failed; // why its meshes, or some of them, could not be repaired; empty when they could + MeshErrors before, after; // the object's + bool painting_removed = false; + bool cancelled = false; // the repair was cancelled during this model, after its mesh had changed +}; +struct FixedModels +{ + // In the order repaired. A cancel ends the repair: the model it stopped is listed, cancelled set, when its mesh had + // changed by then (a part of an object repaired before the cancel keeps its new mesh); the models after it are as + // they were. + std::vector models; + bool cancelled = false; // the repair was cancelled +}; +// The progress of fix_objects(): model `model` of those it repairs, in their order, is `percent` done, the name of the +// part being repaired in `what` when it repairs several. Returning false cancels. +using FixProgress = std::function; + +// Repairs `models` of `model` in turn, [object, part] with part -1 for an object whole, with fix_model_with_cgal(), +// keeping painting with `keep_painting`. `changed(object, part)` is called on each model whose mesh changed, the one a +// cancel stopped among them, before its errors after are read. It needs no app: fix_objects() is this with the app's +// updates in `changed`. +FixedModels repair_models(Model& model, const std::vector>& models, const FixProgress& progress, + bool keep_painting, const std::function& changed); + +// Repairs the targets' meshes, as Fix Model does (repair_models()), in one "Repairing model object" undo step: each +// object whole, or each part named, in turn, keeping painting with the keep_painting preference on. A model whose mesh +// changed, the one a cancel stopped too, is put back on the bed and the object list, the plates and the slicing take it. +// Opens no dialog and pushes no notification: `progress` is told how it goes, from the UI thread, while the repair runs +// on a worker thread. +// Refuses: gizmo_open (a gizmo is open), no_such_plate, no_objects (a plate or a project with none). +Outcome fix_objects(const FixObjectsArgs& args, const FixProgress& progress); + +// ---- Clone ---- + +struct CloneObjectsArgs +{ + Targets targets; // objects, and instances of one; read from the selection, the selection as it is + int count = 1; // copies of each + std::optional arrange; // arrange the current plate afterwards; none: the Clone dialog's choice, the auto_arrange + // preference +}; +struct ClonedObjects +{ + Targets objects; // the new objects + bool arranged = false; // the current plate's arrangement was started +}; +// Pastes `count` copies of the targets as new objects, added after the others near the originals, as the Clone dialog does +// (Selection::clone()), in one "Selection-clone" undo step, the last copies left selected; then with arrange starts the +// arrangement of the current plate, as the dialog does, in the background (the UI job worker is busy until it ends). The +// 3D view does not redraw while it pastes. `pasted(done, count)` is called after each copy, and returning false undoes them. +// Refuses: cancelled (pasted returned false). +Outcome clone_objects(const CloneObjectsArgs& args, const std::function& pasted = {}); + +// ---- Reload from disk ---- + +// Whether Reload from disk reloads `volume`: it was loaded from a file that has an extension, and is no built-in model. +bool has_reload_source(const ModelVolume& volume); + +// The files the parts of `targets` (an object's every part, or the parts named) are reloaded from, as Reload from disk +// finds them, `exists` saying whether a file is there: a part's source file, else the file of that name beside its +// object's file. A part has_reload_source() is false for is left out. +struct ReloadSources +{ + std::vector> parts; // [object, part] of the parts whose file is there + std::vector paths; // the files they load from, each once, sorted + std::vector> missing; // [object, part] of the parts whose file is not there +}; +ReloadSources reload_sources(const Model& model, const Targets& targets, const std::function& exists); + +struct ReloadFromDiskArgs +{ + Targets targets; // objects and parts + bool all = false; // in place of the targets, every object but the cut ones, as Reload All does +}; +struct ReloadedParts +{ + std::vector> reloaded; // the parts whose mesh the file replaced + std::vector> missing; // the parts whose file is not there, which no file dialog asks for + std::vector> unmatched; // the parts their file holds no part to take for + std::string unreadable; // a file that could not be read, after which nothing more was loaded +}; +// Reloads the targets' parts from their files (reload_sources()), as Reload from disk does +// (Plater::reload_parts_from_disk()), in one "Reload from disk" undo step: each keeps its settings, type, filament and +// placement, and its painting with the keep_painting preference on. A part whose file is gone is listed as missing; no +// dialog opens. +// Refuses: gizmo_open (a gizmo is open), cut_object (a cut object named: a reload would replace a cut part with its whole +// file), no_objects (all, with none that is not cut), no_source (none of the parts was loaded from a file). +Outcome reload_parts(const ReloadFromDiskArgs& args); + +// ---- Replace 3D file ---- + +// What keeps the model loaded from a file from replacing a part, or none: more than one object, or one object of more than +// one part (several_parts), as Replace 3D file refuses it. +std::optional replacement_refusal(const Model& loaded); + +// The part `targets` names, [object, part]: the part named, or the one part of the object named, as Replace 3D file takes a +// selected object of one part. Refuses several_parts for an object of several parts. +Outcome> replaced_part(const Model& model, const Targets& targets); + +struct ReplacePartArgs +{ + int object = 0; + int part = 0; + std::string path; +}; +// Replaces the part's mesh with the mesh of the file at `path`, as Replace 3D file does once its file is picked +// (Plater::replace_part_with_file()), in one "Replace with 3D file" undo step: the part keeps its settings, type, filament +// and placement, and its painting with the keep_painting preference on, else the painting as it is. The loader asks a STEP +// file's mesh options as it does for an import. No message box tells a file of several parts. Gives the new part's index: +// the replacement sorts the object's parts by type, which can move it. +// Refuses: gizmo_open, cut_object, not_loaded (the file could not be read), cancelled (the STEP mesh options were +// cancelled), several_parts (replacement_refusal()). +Outcome replace_part(const ReplacePartArgs& args); + +// Brings the app up to date with instance `instance` of object `object`, placed anew in the model: dropped onto the bed +// with `drop`, its plate registered (slicing and the object list read the plate from the registry, which a move on the +// canvas updates) and the object reloaded. UI thread. +void placed_instance(int object, int instance, bool drop); + +}}} // namespace Slic3r::GUI::Ops diff --git a/src/slic3r/GUI/Operations/Outcome.cpp b/src/slic3r/GUI/Operations/Outcome.cpp index 96f89ab0b1..ae0a55da78 100644 --- a/src/slic3r/GUI/Operations/Outcome.cpp +++ b/src/slic3r/GUI/Operations/Outcome.cpp @@ -4,7 +4,12 @@ #include +#include +#include +#include #include +#include +#include #include #include @@ -26,10 +31,61 @@ std::string filled(const std::string& text, const std::vector& args return format.str(); } +std::string lower(std::string s) +{ + std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return char(std::tolower(c)); }); + return s; +} + +// The fewest insertions, deletions and substitutions of one character that turn `a` into `b`. +std::size_t edit_distance(const std::string& a, const std::string& b) +{ + std::vector row(b.size() + 1); + for (std::size_t j = 0; j <= b.size(); ++j) + row[j] = j; + for (std::size_t i = 1; i <= a.size(); ++i) { + std::size_t diagonal = row[0]; + row[0] = i; + for (std::size_t j = 1; j <= b.size(); ++j) { + const std::size_t above = row[j]; + row[j] = std::min({row[j] + 1, row[j - 1] + 1, diagonal + (a[i - 1] == b[j - 1] ? 0 : 1)}); + diagonal = above; + } + } + return row[b.size()]; +} + } // namespace wxString Refusal::translated() const { return wxString::FromUTF8(filled(I18N::translate_utf8(msgid), args)); } std::string Refusal::english() const { return filled(msgid, args); } +std::vector closest_names(std::vector candidates, const std::string& name) +{ + std::sort(candidates.begin(), candidates.end()); + candidates.erase(std::unique(candidates.begin(), candidates.end()), candidates.end()); + const std::string wanted = lower(name); + std::vector words; + for (std::size_t start = 0; start < wanted.size();) { + const std::size_t end = std::min(wanted.find(' ', start), wanted.size()); + if (end > start) + words.push_back(wanted.substr(start, end - start)); + start = end + 1; + } + std::vector> ranked; + for (std::string& candidate : candidates) { + const std::string low = lower(candidate); + const auto holds = [&low](const std::string& word) { return low.find(word) != std::string::npos; }; + const int found = int(std::count_if(words.begin(), words.end(), holds)); + ranked.emplace_back(-found, edit_distance(wanted, low), std::move(candidate)); + } + std::sort(ranked.begin(), ranked.end()); + std::vector names; + for (auto& [found, distance, candidate] : ranked) + if (names.size() < 8) + names.push_back(std::move(candidate)); + return names; +} + }}} // namespace Slic3r::GUI::Ops diff --git a/src/slic3r/GUI/Operations/Outcome.hpp b/src/slic3r/GUI/Operations/Outcome.hpp index 30c216dc6e..261662c8af 100644 --- a/src/slic3r/GUI/Operations/Outcome.hpp +++ b/src/slic3r/GUI/Operations/Outcome.hpp @@ -55,4 +55,8 @@ private: struct Done {}; +// The names of `candidates` closest to `name`, for a refusal of a name none has: those holding more of its words +// first, then those fewer edits away, at most eight. Any case. +std::vector closest_names(std::vector candidates, const std::string& name); + }}} // namespace Slic3r::GUI::Ops diff --git a/src/slic3r/GUI/Operations/PlateOps.cpp b/src/slic3r/GUI/Operations/PlateOps.cpp index b36f7f3060..c1ef242a2b 100644 --- a/src/slic3r/GUI/Operations/PlateOps.cpp +++ b/src/slic3r/GUI/Operations/PlateOps.cpp @@ -12,6 +12,7 @@ #include "slic3r/GUI/PartPlate.hpp" #include "slic3r/GUI/Plater.hpp" +#include "libslic3r/Config.hpp" #include "libslic3r/Model.hpp" #include @@ -53,6 +54,21 @@ Refusal no_such_plate(int plate, int count) {std::to_string(plate), std::to_string(count - 1)}}; } +std::optional plate_index_refusal(int plate, int count) +{ + if (plate < 0 || plate >= count) + return no_such_plate(plate, count); + return std::nullopt; +} + +std::optional plates_refusal() +{ + Plater& plater = the_plater(); + if (plater.printer_technology() != ptFFF || plater.only_gcode_mode()) + return Refusal{RefusalKind::Precondition, "no_plates", L("Plates are a filament (FFF) feature.")}; + return std::nullopt; +} + Refusal job_running() { return {RefusalKind::Busy, "job_running", L("Wait for the running background job to finish.")}; } void show_prepare_view() @@ -65,12 +81,20 @@ void show_prepare_view() frame->select_tab(wxString(TAB_ID_PREPARE)); } +GLCanvas3D& shown_prepare_canvas() +{ + show_prepare_view(); + GLCanvas3D& canvas = *the_plater().get_view3D_canvas3D(); + if (canvas.is_reload_delayed()) + canvas.reload_scene(true); + return canvas; +} + Outcome select_plate(const SelectPlateArgs& args) { - Plater& plater = the_plater(); - const int count = plater.get_partplate_list().get_plate_count(); - if (args.plate < 0 || args.plate >= count) - return no_such_plate(args.plate, count); + Plater& plater = the_plater(); + if (std::optional refusal = plate_index_refusal(args.plate, plater.get_partplate_list().get_plate_count())) + return *refusal; if (plater.select_plate(args.plate) != 0) return plate_not_selected(args.plate); return Done{}; @@ -78,17 +102,87 @@ Outcome select_plate(const SelectPlateArgs& args) Outcome set_plate_locked(const SetPlateLockedArgs& args) { + if (std::optional refusal = plates_refusal()) + return *refusal; Plater& plater = the_plater(); PartPlateList& plates = plater.get_partplate_list(); - const int index = args.plate ? *args.plate : plates.get_curr_plate_index(); - if (index < 0 || index >= plates.get_plate_count()) - return no_such_plate(index, plates.get_plate_count()); - if (plates.is_locked(index) == args.locked) - return PlateLocked{index, false}; - plater.set_plate_locked(index, args.locked); - return PlateLocked{index, true}; + const int index = args.plate.value_or(plates.get_curr_plate_index()); + if (std::optional refusal = plate_index_refusal(index, plates.get_plate_count())) + return *refusal; + const bool locked = args.locked.value_or(!plates.is_locked(index)); + if (plates.is_locked(index) == locked) + return PlateLocked{index, locked, false}; + plater.set_plate_locked(index, locked); + return PlateLocked{index, locked, true}; } +std::optional delete_plate_refusal(int plate, int count) +{ + if (std::optional refusal = plate_index_refusal(plate, count)) + return refusal; + if (count <= 1) + return Refusal{RefusalKind::Precondition, "last_plate", L("Cannot delete the only plate.")}; + return std::nullopt; +} + +Outcome delete_plate(const PlateArgs& args) +{ + if (std::optional refusal = plates_refusal()) + return *refusal; + Plater& plater = the_plater(); + PartPlateList& plates = plater.get_partplate_list(); + const int index = args.plate.value_or(plates.get_curr_plate_index()); + if (std::optional refusal = delete_plate_refusal(index, plates.get_plate_count())) + return *refusal; + plater.delete_plate(index); + return index; +} + +std::optional duplicate_plate_refusal(int plate, int count, bool slicing) +{ + if (std::optional refusal = plate_index_refusal(plate, count)) + return refusal; + if (count >= int(PartPlateList::MAX_PLATES_COUNT)) + return Refusal{RefusalKind::Precondition, "too_many_plates", L("Cannot duplicate a plate (maximum reached).")}; + if (slicing) + return Refusal{RefusalKind::Busy, "slicing_in_progress", L("Wait for the slicing to finish.")}; + return std::nullopt; +} + +Outcome duplicate_plate(const PlateArgs& args) +{ + if (std::optional refusal = plates_refusal()) + return *refusal; + Plater& plater = the_plater(); + PartPlateList& plates = plater.get_partplate_list(); + const int index = args.plate.value_or(plates.get_curr_plate_index()); + if (std::optional refusal = duplicate_plate_refusal(index, plates.get_plate_count(), plater.is_background_process_slicing())) + return *refusal; + return PlateCopy{index, plater.duplicate_plate(index)}; +} + +Outcome rename_plate(const RenamePlateArgs& args) +{ + if (std::optional refusal = plates_refusal()) + return *refusal; + Plater& plater = the_plater(); + PartPlateList& plates = plater.get_partplate_list(); + const int index = args.plate.value_or(plates.get_curr_plate_index()); + if (std::optional refusal = plate_index_refusal(index, plates.get_plate_count())) + return *refusal; + // The name the plate has already changes nothing: neither the current plate nor the undo history. + if (plates.get_plate(index)->get_plate_name() == args.name) + return index; + // The name icon makes its plate the current one before its dialog names it. + if (index != plates.get_curr_plate_index()) + if (const Outcome selected = select_plate({index}); !selected) + return selected.refusal(); + plater.rename_plate(index, args.name); + return index; +} + +Refusal plate_not_renamed() { return {RefusalKind::Failed, "not_renamed", L("The plate was not renamed.")}; } + std::optional arrange_refusal(const ArrangeArgs& args) { Plater& plater = the_plater(); diff --git a/src/slic3r/GUI/Operations/PlateOps.hpp b/src/slic3r/GUI/Operations/PlateOps.hpp index cbafce6bba..e1ab8fb997 100644 --- a/src/slic3r/GUI/Operations/PlateOps.hpp +++ b/src/slic3r/GUI/Operations/PlateOps.hpp @@ -4,13 +4,24 @@ #include #include +#include #include +namespace Slic3r { namespace GUI { +class GLCanvas3D; +}} // namespace Slic3r::GUI + // Plates, what is arranged and sliced on them, and the sliced plate's layers in the Preview. namespace Slic3r { namespace GUI { namespace Ops { // The refusal for a plate index the project lacks (no_such_plate), `count` being how many it has. Refusal no_such_plate(int plate, int count); +// What every plate operation checks of the plate it is given, of a project of `count` plates: no_such_plate for an +// index the project lacks, or none. +std::optional plate_index_refusal(int plate, int count); +// What keeps the plates from being changed, or none: a printer of another technology, or a G-code file opened for +// viewing, has no plates to edit (no_plates). UI thread. +std::optional plates_refusal(); struct SelectPlateArgs { @@ -22,24 +33,69 @@ Outcome select_plate(const SelectPlateArgs& args); struct SetPlateLockedArgs { - std::optional plate; // none: the current plate - bool locked = true; + std::optional plate; // none: the current plate + std::optional locked; // none: the other state, as the lock icon toggles it }; struct PlateLocked { int plate = 0; + bool locked = false; // the plate's lock afterwards bool changed = false; // false: the plate was in that state already, and no undo step was taken }; -// Locks or unlocks the plate, as one undo step. -// Refuses: no_such_plate. +// Locks or unlocks the plate, as its lock icon does, as one undo step. +// Refuses: no_plates, no_such_plate. Outcome set_plate_locked(const SetPlateLockedArgs& args); +struct PlateArgs +{ + std::optional plate; // none: the current plate +}; + +// What keeps plate `plate` of a project of `count` plates from being deleted, or none: an index the project lacks +// (no_such_plate), or its only plate (last_plate). +std::optional delete_plate_refusal(int plate, int count); +// Deletes the plate, as Delete Plate does, as one undo step: the objects on it stay in the project, outside the plates, +// and the plates after it move down one. The current plate stays current; when it is the one deleted, the plate before +// it is current, or the first plate when there is none before it. Returns the index the plate had. +// Refuses: no_plates, what delete_plate_refusal() gives. +Outcome delete_plate(const PlateArgs& args); + +// What keeps plate `plate` of a project of `count` plates from being duplicated, or none: an index the project lacks +// (no_such_plate), as many plates as a project holds (too_many_plates), or, with `slicing`, a slice running, during +// which no plate is added (slicing_in_progress). +std::optional duplicate_plate_refusal(int plate, int count, bool slicing); +struct PlateCopy +{ + int plate = 0; // the plate copied + int copy = 0; // the new plate's index +}; +// Adds a plate after the last with a copy of each object that stands on the plate, placed on it as on the plate, as +// Duplicate Current Plate does, as one undo step. The current plate stays current. +// Refuses: no_plates, what duplicate_plate_refusal() gives. +Outcome duplicate_plate(const PlateArgs& args); + +struct RenamePlateArgs +{ + std::optional plate; // none: the current plate + std::string name; // "" for none +}; +// Names the plate, as the name dialog of its name icon does: a plate other than the current one is made current first, +// as the icon does, and the name is one undo step. The name the plate has already changes nothing, the current plate +// included. Returns the plate's index. +// Refuses: no_plates, no_such_plate, plate_not_selected. +Outcome rename_plate(const RenamePlateArgs& args); +// The refusal of a rename the person called off: the name dialog cancelled (not_renamed). +Refusal plate_not_renamed(); + // The refusal while the UI job worker runs a job, such as an arrangement or an orientation (job_running). Refusal job_running(); // Shows the Prepare view when another view is shown. start_arrange() does it first; a caller with // work of its own in that view before the start calls it earlier. void show_prepare_view(); +// Shows the Prepare view (show_prepare_view()) and returns its canvas with its scene loaded: a canvas hidden while the +// model changed loads it on its next draw, and a selection made or read there needs it now. +GLCanvas3D& shown_prepare_canvas(); struct ArrangeArgs { diff --git a/src/slic3r/GUI/Operations/PluginOps.cpp b/src/slic3r/GUI/Operations/PluginOps.cpp new file mode 100644 index 0000000000..daaf01d37a --- /dev/null +++ b/src/slic3r/GUI/Operations/PluginOps.cpp @@ -0,0 +1,618 @@ +#include "PluginOps.hpp" + +#include "Outcome.hpp" + +#include "slic3r/GUI/GUI_App.hpp" +#include "slic3r/GUI/I18N.hpp" +#include "slic3r/GUI/Plater.hpp" +#include "slic3r/GUI/PluginSource.hpp" +#include "slic3r/GUI/PluginStatus.hpp" +#include "slic3r/GUI/PluginsDialog.hpp" +#include "slic3r/plugin/PluginDescriptor.hpp" +#include "slic3r/plugin/PluginFsUtils.hpp" +#include "slic3r/plugin/PluginManager.hpp" +#include "slic3r/plugin/PythonPluginInterface.hpp" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Ops { + +namespace { + +Refusal no_such_plugin(const std::string& plugin, std::vector keys) +{ + return Refusal{RefusalKind::Precondition, "no_such_plugin", + // TRN %1% is what a call named a plugin by. + L("No plugin is named \"%1%\"."), {plugin}, closest_names(std::move(keys), plugin)}; +} + +Refusal plugin_loading(const std::string& name) +{ + // TRN %1% is a plugin's name. + return Refusal{RefusalKind::Busy, "plugin_loading", L("\"%1%\" is loading; try again when its load has ended."), {name}}; +} + +// A cloud plugin that is no longer available, with its package removed so that it is listed to be installed again. +PluginDescriptor as_cloud_only_descriptor(PluginDescriptor descriptor) +{ + descriptor.plugin_root.clear(); + descriptor.entry_path.clear(); + descriptor.installed_version.clear(); + // No local package is left behind, so the package verdict and any load error it produced go with it. + descriptor.metadata_valid = false; + descriptor.clear_error(); + if (descriptor.cloud.has_value()) { + descriptor.cloud->installed = false; + descriptor.cloud->update_available = false; + } + return descriptor; +} + +} // namespace + +// ---- The list ---- + +PluginSource plugin_source(const PluginDescriptor& plugin) +{ + const bool has_cloud_meta = plugin.cloud.has_value(); + const bool is_cloud = plugin.is_cloud_plugin(); + const bool is_mine = is_cloud && has_cloud_meta && plugin.cloud->is_mine; + + if (is_cloud && has_cloud_meta && plugin.cloud->orphaned) + return PluginSource::Orphaned; + if (is_mine) + return PluginSource::Mine; + if (is_cloud) + return PluginSource::Subscribed; + return PluginSource::Local; +} + +std::string installed_plugin_version(const PluginDescriptor& plugin) +{ + // The cloud merge overwrites `version` with the latest cloud version, so the preserved local one comes first, + // `version` serving local-only and pre-merge descriptors. + if (!plugin.has_local_package()) + return {}; + return plugin.installed_version.empty() ? plugin.version : plugin.installed_version; +} + +PluginActions plugin_actions(const PluginDescriptor& plugin, bool loading) +{ + PluginActions actions; + const bool is_cloud = plugin.is_cloud_plugin(); + const bool is_orphaned = plugin.cloud.has_value() && plugin.cloud->orphaned; + const bool is_mine = plugin_source(plugin) == PluginSource::Mine; + const bool has_local = plugin.has_local_package(); + + actions.toggle_installs_cloud_plugin = is_cloud && !is_orphaned && !has_local && !plugin.is_unauthorized(); + actions.can_toggle = !loading && (has_local || actions.toggle_installs_cloud_plugin); + // The person's own cloud plugin falls through to the local delete: it removes the installed package only. Deleting + // a plugin from the cloud is a plugin hub operation and is never offered. + actions.unsubscribe = is_cloud && !is_orphaned && !is_mine; + actions.remove = !actions.unsubscribe && has_local; + actions.open_folder = has_local; + actions.reinstall = !is_orphaned && is_cloud; + actions.reload = !is_orphaned && !is_cloud; + return actions; +} + +std::vector plugin_rows_from(const std::vector& plugins, const std::map& runtime) +{ + std::vector rows; + rows.reserve(plugins.size()); + for (const PluginDescriptor& plugin : plugins) { + const auto found = runtime.find(plugin.plugin_key); + const PluginRuntime state = found != runtime.end() ? found->second : PluginRuntime{}; + const std::string installed = installed_plugin_version(plugin); + PluginRow row; + row.key = plugin.plugin_key; + row.name = plugin.name; + row.version = installed.empty() ? plugin.latest_available_version() : installed; + row.installed = plugin.has_local_package(); + row.enabled = state.loaded; + row.status = to_string(resolve_plugin_status(state.loading, plugin.has_error(), state.loaded)); + row.source = to_string(plugin_source(plugin)); + row.capabilities = state.capabilities; + row.error = plugin.normalized_error(); + rows.push_back(std::move(row)); + } + return rows; +} + +std::vector plugin_rows() +{ + PluginManager& manager = PluginManager::instance(); + const std::vector plugins = manager.get_plugin_descriptors(/*include_invalid=*/true); + std::map runtime; + for (const PluginDescriptor& plugin : plugins) { + PluginRuntime& state = runtime[plugin.plugin_key]; + state.loaded = manager.is_plugin_loaded(plugin.plugin_key); + state.loading = manager.is_plugin_load_in_progress(plugin.plugin_key); + // A package that is not loaded has no capabilities. + for (const auto& capability : manager.get_plugin_capabilities(plugin.plugin_key, PluginCapabilityType::Unknown, + /*only_enabled=*/false)) + state.capabilities.push_back( + {capability->identity().name, plugin_capability_type_to_string(capability->type()), capability->is_enabled()}); + } + return plugin_rows_from(plugins, runtime); +} + +bool plugin_descriptor(const std::string& plugin, PluginDescriptor& descriptor) +{ + PluginManager& manager = PluginManager::instance(); + if (manager.try_get_valid_plugin_descriptor(plugin, descriptor)) + return true; + return manager.try_get_plugin_descriptor(plugin, descriptor) && descriptor.is_invalid_package(); +} + +Outcome find_plugin(const std::string& plugin) +{ + PluginDescriptor descriptor; + if (plugin_descriptor(plugin, descriptor)) + return descriptor; + std::vector keys; + std::vector named; + for (const PluginDescriptor& listed : PluginManager::instance().get_plugin_descriptors(/*include_invalid=*/true)) { + keys.push_back(listed.plugin_key); + if (listed.name == plugin && plugin_descriptor(listed.plugin_key, descriptor)) + named.push_back(descriptor); + } + if (named.size() == 1) + return named.front(); + if (named.size() > 1) { + std::vector named_keys; + for (const PluginDescriptor& one : named) + named_keys.push_back(one.plugin_key); + return Refusal{RefusalKind::Precondition, "ambiguous_plugin", + // TRN %1% is a plugin's name. + L("Several plugins are named \"%1%\": name one by its key."), {plugin}, named_keys}; + } + return no_such_plugin(plugin, std::move(keys)); +} + +// ---- Turning a plugin or a capability on or off ---- + +Outcome set_plugin_enabled(const SetPluginEnabledArgs& args) +{ + assert(wxThread::IsMain()); + const std::string& key = args.plugin; + PluginDescriptor row; + if (!plugin_descriptor(key, row)) + return no_such_plugin(key, {}); + PluginManager& manager = PluginManager::instance(); + PluginEnabled done{key, args.capability, PluginChange::None}; + + if (!args.capability.empty()) { + const auto capabilities = manager.get_plugin_capabilities(key, PluginCapabilityType::Unknown, /*only_enabled=*/false); + if (capabilities.empty() && !manager.is_plugin_loaded(key)) + return Refusal{RefusalKind::Precondition, "plugin_not_enabled", + // TRN %1% is a plugin's name. + L("\"%1%\" is not enabled, so its capabilities are not loaded: enable it first."), {row.name}}; + std::vector names; + std::vector> matching; + for (const auto& capability : capabilities) { + const PluginCapabilityId id = capability->identity(); + names.push_back(id.name); + if (id.name == args.capability && (args.capability_type == PluginCapabilityType::Unknown || id.type == args.capability_type)) + matching.push_back(capability); + } + if (matching.empty()) { + BOOST_LOG_TRIVIAL(warning) << "Cannot toggle missing plugin capability: " << key << " | " << args.capability; + return Refusal{RefusalKind::Precondition, "no_such_capability", + // TRN %1% is a capability's name, %2% a plugin's. + L("\"%2%\" has no capability named \"%1%\"."), {args.capability, row.name}, names}; + } + if (matching.size() > 1) { + std::vector types; + for (const auto& capability : matching) + types.push_back(plugin_capability_type_to_string(capability->type())); + return Refusal{RefusalKind::Precondition, "ambiguous_capability", + // TRN %1% is a capability's name. + L("Several capabilities are named \"%1%\"."), {args.capability}, types}; + } + const bool was_enabled = matching.front()->is_enabled(); + BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": " << (args.enabled ? "Enabling" : "Disabling") << " plugin capability: " << key + << " | " << args.capability; + manager.set_capability_enabled(matching.front()->identity(), args.enabled); + if (was_enabled != args.enabled) + done.change = args.enabled ? PluginChange::CapabilityEnabled : PluginChange::CapabilityDisabled; + return done; + } + + BOOST_LOG_TRIVIAL(info) << "Toggle plugin request. plugin_key=" << key << " enabled=" << args.enabled; + if (!args.enabled) { + const bool was_loaded = manager.is_plugin_loaded(key); + if (!manager.unload_plugin(key)) { + BOOST_LOG_TRIVIAL(error) << "Failed to unload plugin: " << key; + return Refusal{RefusalKind::Failed, "not_unloaded", L("Failed to unload plugin.")}; + } + BOOST_LOG_TRIVIAL(info) << "Plugin unloaded: " << key; + // A plugin switched off has no meaningful error state. + if (!manager.clear_plugin_error(key)) + BOOST_LOG_TRIVIAL(warning) << "Failed to clear plugin error for " << key << " (failed to find)"; + if (was_loaded) + done.change = PluginChange::Unloaded; + return done; + } + + const bool loading = manager.is_plugin_load_in_progress(key); + const PluginActions actions = plugin_actions(row, loading); + if (!actions.can_toggle) { + if (row.is_unauthorized() && !actions.toggle_installs_cloud_plugin && !row.has_local_package()) + return Refusal{RefusalKind::Precondition, "unauthorized_plugin", L("Unauthorized cloud plugins cannot be installed.")}; + if (loading) + return plugin_loading(row.name); + return Refusal{RefusalKind::Precondition, "not_installable", + // TRN %1% is a plugin's name. + L("\"%1%\" is no longer available from the cloud, and it is not installed."), {row.name}}; + } + + if (actions.toggle_installs_cloud_plugin) { + const std::function()> work = [key, version = row.version] { return download_cloud_plugin(key, version); }; + const Outcome downloaded = args.run_download ? args.run_download(work) : wait_off_ui_thread(work); + if (!downloaded) + return downloaded.refusal(); + BOOST_LOG_TRIVIAL(info) << "Cloud plugin installed locally: " << key; + // The download updated the descriptor already, so no rescan is needed here. + if (!plugin_descriptor(key, row)) + return no_such_plugin(key, {}); + if (row.has_error()) + return Refusal{RefusalKind::Failed, "plugin_error", row.normalized_error()}; + } + + if (manager.is_plugin_loaded(key)) + return done; + PluginDescriptor valid_descriptor; + if (!manager.try_get_valid_plugin_descriptor(key, valid_descriptor)) + return Refusal{RefusalKind::Precondition, "manifest_not_found", L("Plugin manifest was not found.")}; + if (manager.is_plugin_load_in_progress(key)) + return plugin_loading(row.name); + + BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": Starting plugin load: " << key; + manager.load_plugin(key); + done.change = PluginChange::LoadStarted; + return done; +} + +Outcome download_cloud_plugin(const std::string& plugin, const std::string& version) +{ + BOOST_LOG_TRIVIAL(info) << "Downloading cloud plugin. plugin_key=" << plugin; + std::string error; + bool downloaded = false; + try { + downloaded = PluginManager::instance().download_and_install_cloud_plugin(plugin, version, error); + } catch (const std::exception& ex) { + error = ex.what(); + } catch (...) { + error = L("Unknown error"); + } + if (downloaded) { + BOOST_LOG_TRIVIAL(info) << "Cloud plugin downloaded successfully. plugin_key=" << plugin; + return Done{}; + } + BOOST_LOG_TRIVIAL(error) << "Cloud plugin download failed. plugin_key=" << plugin << " error=" << error; + PluginManager::instance().set_plugin_error(plugin, error); + return Refusal{RefusalKind::Failed, "download_failed", error.empty() ? std::string(L("Plugin download failed.")) : error}; +} + +Outcome wait_off_ui_thread(const std::function()>& work) +{ + assert(wxThread::IsMain()); + struct State + { + std::mutex mutex; + std::optional> result; + }; + auto state = std::make_shared(); + bool finished = false; + wxEventLoop loop; + // The completion runs on the UI thread, which is in the loop below until it has run, so the loop outlives it. + std::function on_finish = [&finished, &loop] { + finished = true; + if (loop.IsRunning()) + loop.Exit(); + }; + std::thread([state, work, on_finish] { + Outcome result = Refusal{RefusalKind::Failed, "failed", L("Unknown error")}; + try { + result = work(); + } catch (const std::exception& ex) { + result = Refusal{RefusalKind::Failed, "failed", ex.what()}; + } catch (...) { + } + { + std::lock_guard lock(state->mutex); + state->result.emplace(std::move(result)); + } + if (wxTheApp != nullptr) + wxTheApp->CallAfter(on_finish); + }).detach(); + if (!finished) + loop.Run(); + std::lock_guard lock(state->mutex); + return state->result ? *state->result : Outcome(Refusal{RefusalKind::Failed, "failed", L("Unknown error")}); +} + +// ---- Delete and Unsubscribe ---- + +Outcome plugin_uninstall_plan(const std::string& plugin) +{ + const Outcome found = find_plugin(plugin); + if (!found) + return found.refusal(); + const PluginDescriptor& descriptor = found.value(); + const PluginActions actions = + plugin_actions(descriptor, PluginManager::instance().is_plugin_load_in_progress(descriptor.plugin_key)); + if (!actions.unsubscribe && !actions.remove) + return Refusal{RefusalKind::Precondition, "nothing_to_uninstall", + // TRN %1% is a plugin's name. + L("\"%1%\" is not installed, and no subscription keeps it listed."), {descriptor.name}}; + return PluginUninstall{descriptor.plugin_key, descriptor.name, actions.unsubscribe, descriptor}; +} + +Outcome uninstall_plugin(const PluginUninstall& plan) +{ + PluginManager& manager = PluginManager::instance(); + std::string error; + bool succeeded = false; + if (plan.unsubscribe) { + succeeded = manager.delete_and_unsubscribe_cloud_plugin(plan.plugin, error); + } else { + succeeded = manager.delete_plugin(plan.plugin, error); + // Keep the cloud row listed so the plugin stays installable without waiting on a cloud fetch. + if (succeeded && plan.descriptor.is_cloud_plugin()) + manager.update_cloud_metadata(std::vector{as_cloud_only_descriptor(plan.descriptor)}); + } + if (succeeded) + return Done{}; + if (!error.empty()) + return Refusal{RefusalKind::Failed, "not_uninstalled", error}; + return Refusal{RefusalKind::Failed, "not_uninstalled", + plan.unsubscribe ? L("Failed to unsubscribe plugin.") : L("Failed to delete plugin.")}; +} + +void plugin_uninstalled() +{ + // The package is gone only now; the unload callback rechecked the notices too early. + if (Plater* plater = wxGetApp().plater()) + plater->refresh_missing_plugin_notifications(); +} + +// ---- Reload, Delete cache and reload, and Reinstall ---- + +Outcome plugin_reload_plan(const std::string& plugin, bool clear_cache) +{ + const Outcome found = find_plugin(plugin); + if (!found) + return found.refusal(); + const PluginDescriptor& descriptor = found.value(); + PluginManager& manager = PluginManager::instance(); + const PluginActions actions = plugin_actions(descriptor, manager.is_plugin_load_in_progress(descriptor.plugin_key)); + PluginReload plan{descriptor.plugin_key, descriptor.name, clear_cache, manager.is_plugin_loaded(descriptor.plugin_key), + actions.reinstall, descriptor}; + if (actions.reinstall) { + if (clear_cache) + return Refusal{RefusalKind::Precondition, "no_cache_to_clear", + // TRN %1% is a plugin's name. + L("\"%1%\" is a cloud plugin, which is installed again with its cache; leave clear_cache out."), + {descriptor.name}}; + return plan; + } + if (!actions.reload) + return Refusal{RefusalKind::Precondition, "no_reload", + // TRN %1% is a plugin's name. + L("\"%1%\" is no longer available from the cloud, so it cannot be installed or loaded again."), {descriptor.name}}; + return plan; +} + +Outcome remove_plugin_package_for_reinstall(const PluginDescriptor& plugin) +{ + PluginManager& manager = PluginManager::instance(); + std::string error; + if (!manager.delete_plugin(plugin.plugin_key, error)) + return Refusal{RefusalKind::Failed, "not_uninstalled", error.empty() ? std::string(L("Failed to delete plugin.")) : error}; + manager.update_cloud_metadata(std::vector{as_cloud_only_descriptor(plugin)}); + return Done{}; +} + +Outcome load_plugin_and_wait(const std::string& plugin) +{ + PluginManager& manager = PluginManager::instance(); + manager.load_plugin(plugin); + std::string error; + if (!manager.wait_for_plugin_load(plugin, std::chrono::minutes(5), error) || !manager.is_plugin_loaded(plugin)) + return Refusal{RefusalKind::Failed, "not_loaded", error.empty() ? std::string(L("Plugin failed to load.")) : error}; + return Done{}; +} + +Outcome reload_plugin(const PluginReload& plan) +{ + const std::string& key = plan.plugin; + if (plan.cloud) { + if (plan.descriptor.has_local_package()) + if (const Outcome removed = remove_plugin_package_for_reinstall(plan.descriptor); !removed) + return removed; + if (const Outcome downloaded = download_cloud_plugin(key, plan.descriptor.version); !downloaded) + return downloaded; + return plan.was_loaded ? load_plugin_and_wait(key) : Outcome(Done{}); + } + + PluginManager& manager = PluginManager::instance(); + boost::filesystem::path cache_dir; + if (plan.clear_cache) { + PluginDescriptor descriptor; + if (!manager.try_get_plugin_descriptor(key, descriptor)) + return Refusal{RefusalKind::Precondition, "no_such_plugin", L("Plugin not found.")}; + boost::filesystem::path resolved_root; + std::string resolve_error; + if (!resolve_allowed_plugin_root(descriptor, {get_orca_plugins_dir()}, + L("Refusing to clear a plugin cache outside the local plugin directory."), resolved_root, + resolve_error)) + return Refusal{RefusalKind::Precondition, "outside_plugins_folder", resolve_error}; + cache_dir = resolved_root / "__whl_extracted__"; + } + if (!manager.unload_plugin(key)) + return Refusal{RefusalKind::Failed, "not_unloaded", L("Failed to unload plugin.")}; + if (plan.clear_cache) { + boost::system::error_code ec; + boost::filesystem::remove_all(cache_dir, ec); + if (ec) + return Refusal{RefusalKind::Failed, "cache_not_cleared", L("Failed to clear plugin cache: %1%"), {ec.message()}}; + } + if (const Outcome loaded = load_plugin_and_wait(key); !loaded) + return loaded; + if (!plan.was_loaded && !manager.unload_plugin(key)) + return Refusal{RefusalKind::Failed, "not_restored", L("Plugin reloaded, but failed to restore the inactive state.")}; + return Done{}; +} + +// ---- Refresh Plugins ---- + +// A run's own lock: the queue's thread writes how the run ended, and the threads that hold its ticket read it, with no +// need of the queue. +struct RefreshRunState +{ + std::mutex mutex; + RefreshRun::Status status; +}; + +namespace { + +void set_status(RefreshRunState& run, RefreshRun::Status status) +{ + std::lock_guard lock(run.mutex); + run.status = std::move(status); +} + +} // namespace + +RefreshRun::Ticket RefreshRun::start(std::function work) +{ + const std::shared_ptr runs = m_runs; + const auto run = std::make_shared(); + std::thread queue; + { + std::lock_guard lock(runs->mutex); + runs->waiting.emplace_back(run, std::move(work)); + if (runs->running) + return Ticket(run); + // The thread starts under the lock, which it takes first in run_queue(), so no other call queues a work before it + // is known whether a thread runs the queue. + try { + queue = std::thread([runs] { run_queue(runs); }); + runs->running = true; + } catch (const std::exception& ex) { + // No thread runs the queue, so it holds only this work. + runs->waiting.clear(); + set_status(*run, Status{State::Failed, ex.what()}); + return Ticket(run); + } + } + try { + queue.detach(); + } catch (const std::system_error&) { + // The thread goes on running the queue. A joinable thread can be neither destroyed nor, without holding the caller + // until every queued refresh has ended, waited for, so its handle is kept for the process's life. + new std::thread(std::move(queue)); + } + return Ticket(run); +} + +void RefreshRun::run_queue(const std::shared_ptr& runs) +{ + for (;;) { + std::pair, std::function> next; + { + std::lock_guard lock(runs->mutex); + if (runs->waiting.empty()) { + runs->running = false; + return; + } + next = std::move(runs->waiting.front()); + runs->waiting.pop_front(); + } + Status status{State::Done, {}}; + try { + next.second(); + } catch (const std::exception& ex) { + status = Status{State::Failed, ex.what()}; + } catch (...) { + status = Status{State::Failed, "Unknown error"}; + } + set_status(*next.first, std::move(status)); + } +} + +RefreshRun::Status RefreshRun::status(Ticket ticket) const +{ + if (ticket.m_run == nullptr) + return Status{State::Failed, "This ticket is of no refresh."}; + std::lock_guard lock(ticket.m_run->mutex); + return ticket.m_run->status; +} + +std::optional wait_for_refresh(const RefreshRun& run, RefreshRun::Ticket ticket, const std::function& cancelled, + std::chrono::milliseconds poll) +{ + for (RefreshRun::Status status = run.status(ticket);; status = run.status(ticket)) { + if (status.state != RefreshRun::State::Pending) + return status; + if (cancelled && cancelled()) + return std::nullopt; + std::this_thread::sleep_for(poll); + } +} + +RefreshRun& plugin_refresh_run() +{ + static RefreshRun run; + return run; +} + +RefreshRun::Ticket start_plugin_refresh(std::function finished) +{ + assert(wxThread::IsMain()); + return plugin_refresh_run().start([finished = std::move(finished)] { + try { + // A run that waited for others must not begin on an app that is closing, whose plugins are being unloaded. + if (wxTheApp == nullptr || wxGetApp().is_closing()) + throw std::runtime_error("OrcaSlicer is closing."); + refresh_plugin_metadata_blocking(/*fetch_cloud=*/true); + } catch (const std::exception& ex) { + if (finished) + finished(ex.what(), false); + throw; + } catch (...) { + if (finished) + finished({}, true); + throw; + } + if (finished) + finished({}, false); + }); +} + +}}} // namespace Slic3r::GUI::Ops diff --git a/src/slic3r/GUI/Operations/PluginOps.hpp b/src/slic3r/GUI/Operations/PluginOps.hpp new file mode 100644 index 0000000000..e16686d333 --- /dev/null +++ b/src/slic3r/GUI/Operations/PluginOps.hpp @@ -0,0 +1,260 @@ +#pragma once + +#include "Outcome.hpp" + +#include "slic3r/GUI/PluginSource.hpp" +#include "slic3r/plugin/PluginDescriptor.hpp" +#include "slic3r/plugin/PythonPluginInterface.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// The plugins, as the Plugins window lists them and as its switches and row menus change them: the list, a plugin's or a +// capability's switch, Delete and Unsubscribe, Reload and Reinstall, and Refresh Plugins. +// +// What the window does behind a progress dialog runs off the UI thread. Those steps are functions of their own here, +// which the window runs behind its progress dialog and a command on its own thread, with no dialog: plan on the UI +// thread, do the work, finish on the UI thread. +namespace Slic3r { namespace GUI { namespace Ops { + +// ---- The list ---- + +struct PluginCapabilityRow +{ + std::string name; + std::string type; // plugin_capability_type_to_string(): "script", "importer", ... + bool enabled = false; +}; + +// One row of the Plugins window, as data. +struct PluginRow +{ + std::string key; // the plugin manager's key, which every plugin command takes + std::string name; + std::string version; // the version installed, else the latest one offered: what the row shows + bool installed = false; // a package is on disk + bool enabled = false; // loaded: the row's switch is on + std::string status; // Activated, Error, RuntimeError, Inactive or Loading, as the row shows it + std::string source; // local, subscribed, mine or orphaned + // A loaded plugin's capabilities, in the order it registered them; a plugin that is not loaded has none. + std::vector capabilities; + std::string error; // the blocking error the row shows, or "" +}; + +// What the plugin manager holds of a plugin besides its descriptor. +struct PluginRuntime +{ + bool loaded = false; + bool loading = false; + std::vector capabilities; +}; + +// Where a row says a plugin comes from: the person's own upload, a subscription, one no longer available, or a local +// package. +PluginSource plugin_source(const PluginDescriptor& plugin); +// The version of the package on disk: `installed_version`, which a merge of the cloud's list leaves as it is, else +// `version`; "" where no package is installed. +std::string installed_plugin_version(const PluginDescriptor& plugin); + +// What a row offers: its switch, and the items of its menu that act on the plugin. +struct PluginActions +{ + bool can_toggle = false; // the switch can be used + bool toggle_installs_cloud_plugin = false; // switching it on downloads and installs the cloud plugin first + bool unsubscribe = false; // Unsubscribe: a cloud plugin subscribed to, not the person's own + bool remove = false; // Delete: where a package is installed and no Unsubscribe is offered + bool open_folder = false; // Show in folder: where a package is installed + bool reinstall = false; // Reinstall: a cloud plugin still available + bool reload = false; // Reload and Delete cache and reload: a local plugin +}; +// What the row of `plugin` offers, `loading` while its load runs. +PluginActions plugin_actions(const PluginDescriptor& plugin, bool loading); + +// The rows of `plugins`, in their order, with what `runtime` holds for each key (nothing: not loaded). +std::vector plugin_rows_from(const std::vector& plugins, const std::map& runtime); +// The rows of every plugin the plugin manager knows, those with an invalid package among them, as the window lists them. +std::vector plugin_rows(); + +// The descriptor of the plugin of key `plugin`, as the window reads a row's: a valid package, or an invalid one that is +// installed. False where there is none. +bool plugin_descriptor(const std::string& plugin, PluginDescriptor& descriptor); +// The plugin a call names: by its key, else by its name where one plugin has it. +// Refuses: no_such_plugin (with the closest keys). +Outcome find_plugin(const std::string& plugin); + +// ---- Turning a plugin or a capability on or off: the row's switch and a capability's ---- + +enum class PluginChange +{ + None, // it was so already + Unloaded, + LoadStarted, // the load goes on in the background (PluginManager::load_plugin()) + CapabilityEnabled, + CapabilityDisabled, +}; + +// Runs `work` off the UI thread and returns what it returned, keeping the UI going meanwhile. +using RunOffUiThread = std::function(const std::function()>& work)>; + +struct SetPluginEnabledArgs +{ + std::string plugin; // key + std::string capability; // a capability's name; "": the plugin itself + PluginCapabilityType capability_type = PluginCapabilityType::Unknown; // Unknown: the capability of that name, of any type + bool enabled = true; + // How the download of a cloud plugin that is not installed, which switching it on starts, is waited for: the + // window's behind its progress dialog. None: in a nested event loop, with no dialog (wait_off_ui_thread()). + RunOffUiThread run_download; +}; +struct PluginEnabled +{ + std::string plugin; // key + std::string capability; // the capability's name, or "" + PluginChange change = PluginChange::None; +}; +// Does what the row's switch, or a capability's switch, does (PluginsDialog::toggle_plugin(), +// toggle_plugin_capability()). Switching on a plugin starts its load, after downloading and installing a cloud plugin +// that is not installed. A plugin switched off loses its error, as one a person switched off has none. UI thread. +// Refuses: no_such_plugin; for the plugin: not_unloaded, plugin_loading (Busy), unauthorized_plugin (a cloud plugin +// not authorized for install and not installed), not_installable (a cloud plugin no longer available, not +// installed), download_failed (its error recorded on the plugin, as the window records it), plugin_error (the +// package downloaded has an error), manifest_not_found; for a capability: plugin_not_enabled (a plugin not +// loaded shows no capabilities), no_such_capability (with the plugin's), ambiguous_capability (a name two of +// its capabilities have, with their types). +Outcome set_plugin_enabled(const SetPluginEnabledArgs& args); + +// Downloads and installs the cloud plugin's package of `version`; on failure records the error on the plugin, as the +// window does. Blocking: off the UI thread. +// Refuses: download_failed, with the plugin manager's error, which may be "". +Outcome download_cloud_plugin(const std::string& plugin, const std::string& version); +// Runs `work` on a thread of its own and waits in a nested event loop until it returns, with no dialog. UI thread. +Outcome wait_off_ui_thread(const std::function()>& work); + +// ---- Delete and Unsubscribe: the row menu's ---- + +struct PluginUninstall +{ + std::string plugin; // key + std::string name; + bool unsubscribe = false; // Unsubscribe, which also ends the subscription in the cloud account; else Delete + PluginDescriptor descriptor; // as it was planned +}; +// What the row's menu offers to remove the plugin: Unsubscribe for a cloud plugin the person subscribed to, else +// Delete where a package is installed (a local plugin, or the person's own cloud one, whose package alone goes). UI +// thread. +// Refuses: no_such_plugin, nothing_to_uninstall (no package installed and no subscription: the menu offers neither). +Outcome plugin_uninstall_plan(const std::string& plugin); +// The work of the row's Delete or Unsubscribe: the plugin is unloaded where it is loaded, its package removed, and an +// Unsubscribe ends the subscription; a cloud plugin deleted stays listed, to be installed again. Blocking: off the UI +// thread. +// Refuses: not_uninstalled, with the plugin manager's error, which may be "". +Outcome uninstall_plugin(const PluginUninstall& plan); +// What follows an uninstall on the UI thread: the notices of plugins a project needs are checked again, now that the +// package is gone. +void plugin_uninstalled(); + +// ---- Reload, Delete cache and reload, and Reinstall: the row menu's ---- + +struct PluginReload +{ + std::string plugin; // key + std::string name; + bool clear_cache = false; + bool was_loaded = false; // a plugin that was not loaded is left so + bool cloud = false; // Reinstall: the package is downloaded again + PluginDescriptor descriptor; // as it was planned +}; +// What the row's menu offers to load the plugin again: Reload, or with `clear_cache` Delete cache and reload, for a +// local plugin; Reinstall for a cloud plugin still available. UI thread. +// Refuses: no_such_plugin, no_reload (a cloud plugin no longer available: its menu offers neither), no_cache_to_clear +// (clear_cache for a cloud plugin, whose menu offers no Delete cache and reload). +Outcome plugin_reload_plan(const std::string& plugin, bool clear_cache); +// Loads a local plugin again: unloaded, its extracted wheel cache removed with `clear_cache`, loaded, and unloaded +// again where it was not loaded. A cloud plugin is reinstalled: remove_plugin_package_for_reinstall(), +// download_cloud_plugin(), and load_plugin_and_wait() where it was loaded. Blocking: off the UI thread. +// Refuses: no_such_plugin, outside_plugins_folder, not_unloaded, cache_not_cleared, not_loaded (with the load's error), +// not_restored (reloaded, and left loaded), and what the reinstall's steps refuse. +Outcome reload_plugin(const PluginReload& plan); +// Removes the installed package of a cloud plugin and keeps it listed, as Reinstall does first. Any thread. +// Refuses: not_uninstalled. +Outcome remove_plugin_package_for_reinstall(const PluginDescriptor& plugin); +// Loads the plugin and waits up to five minutes for its load to end. Blocking: off the UI thread. +// Refuses: not_loaded, with the load's error. +Outcome load_plugin_and_wait(const std::string& plugin); + +// ---- Refresh Plugins ---- + +// The state of one run of RefreshRun, which its ticket and the queue share (PluginOps.cpp). +struct RefreshRunState; + +// One run of RefreshRun, as start() gives it. It shares its run's state with the queue, so it reads how its own run +// ended for as long as it, or a copy, is kept. A default ticket is of no run. +class RefreshTicket +{ +public: + RefreshTicket() = default; + friend bool operator==(const RefreshTicket& a, const RefreshTicket& b) { return a.m_run == b.m_run; } + friend bool operator!=(const RefreshTicket& a, const RefreshTicket& b) { return a.m_run != b.m_run; } + +private: + friend class RefreshRun; + explicit RefreshTicket(std::shared_ptr run) : m_run(std::move(run)) {} + std::shared_ptr m_run; +}; + +// Refreshes that take turns: each is a run of its own, off the caller's thread, one at a time, in the order they were +// asked for. Free of wx, so it is unit-tested. +class RefreshRun +{ +public: + using Ticket = RefreshTicket; + enum class State { Pending, Done, Failed }; + struct Status + { + State state = State::Pending; + std::string error; // what the work threw, for Failed + }; + + // Queues `work` and returns its ticket. A work asked for while another waits or runs begins once those before it + // have returned; one that throws does not stop the ones after it. The works run on a detached thread that holds + // what it needs, so they run, in turn, also after this object is gone. + Ticket start(std::function work); + // How the run of `ticket` stands: Pending while it waits or runs. A ticket start() did not give is Failed, with a + // text that says so. + Status status(Ticket ticket) const; + +private: + struct Runs + { + std::mutex mutex; + bool running = false; // a thread runs the queue + std::deque, std::function>> waiting; + }; + // Runs the queue's works, one after another, until it is empty. + static void run_queue(const std::shared_ptr& runs); + std::shared_ptr m_runs = std::make_shared(); +}; + +// Starts a run of Refresh Plugins, the installed plugins rescanned and the cloud's list of plugins fetched again +// (refresh_plugin_metadata_blocking()), after the runs already asked for, a person's and a command's alike. A run that +// would begin while OrcaSlicer closes does not scan and fails. `finished` is called on the run's thread when the run +// ends: with "" when it succeeded, else with what failed, `unknown` where that has no text. UI thread. +RefreshRun::Ticket start_plugin_refresh(std::function finished); +// The app's one queue of refreshes, which start_plugin_refresh() starts its runs on. Any thread. +RefreshRun& plugin_refresh_run(); + +// Waits for the run of `ticket` to end and returns how it ended, looking at its status every `poll`. Before each wait +// it asks `cancelled`, and returns nullopt once that says yes: the wait stops and the run goes on. Free of wx, so it is +// unit-tested. Blocking: off the UI thread. +std::optional wait_for_refresh(const RefreshRun& run, RefreshRun::Ticket ticket, const std::function& cancelled, + std::chrono::milliseconds poll); + +}}} // namespace Slic3r::GUI::Ops diff --git a/src/slic3r/GUI/Operations/PreferenceOps.cpp b/src/slic3r/GUI/Operations/PreferenceOps.cpp new file mode 100644 index 0000000000..ffc147cec4 --- /dev/null +++ b/src/slic3r/GUI/Operations/PreferenceOps.cpp @@ -0,0 +1,943 @@ +#include "PreferenceOps.hpp" + +#include "Outcome.hpp" + +#include "slic3r/GUI/Event.hpp" +#include "slic3r/GUI/GCodeViewer.hpp" +#include "slic3r/GUI/GLCanvas3D.hpp" +#include "slic3r/GUI/GUI_App.hpp" +#include "slic3r/GUI/GUI_Init.hpp" +#include "slic3r/GUI/GUI_Utils.hpp" +#include "slic3r/GUI/I18N.hpp" +#include "slic3r/GUI/MainFrame.hpp" +#include "slic3r/GUI/Mcp/McpEndpoint.hpp" +#include "slic3r/GUI/Mcp/McpOptions.hpp" +#include "slic3r/GUI/Plater.hpp" +#include "slic3r/GUI/Preferences.hpp" +#include "slic3r/GUI/WebViewDialog.hpp" +#include "slic3r/plugin/host/PluginPages.hpp" + +#include "libslic3r/AppConfig.hpp" +#include "libslic3r/Format/DRC.hpp" +#include "libslic3r/Format/bbs_3mf.hpp" +#include "libslic3r/Preset.hpp" +#include "libslic3r/Utils.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Ops { + +using nlohmann::json; + +namespace { + +constexpr const char* kGeneral = "general"; +constexpr const char* kFiles = "files"; +constexpr const char* kBehaviour = "behaviour"; +constexpr const char* kControl = "control"; +constexpr const char* kGraphics = "graphics"; +constexpr const char* kOnline = "online"; +constexpr const char* kDeveloper = "developer"; + +using Lines = std::vector; +using Choices = std::vector>; + +// Adds the table's rows, each under the tab and section named last. +class TableWriter +{ +public: + explicit TableWriter(std::vector& table) : m_table(table) {} + + void section(const char* tab, const char* title) + { + m_tab = tab; + m_section = title; + } + Preference& checkbox(const char* key, const char* label, Lines tooltip = {}) + { + Preference& p = add(key, label, PreferenceKind::Checkbox, std::move(tooltip)); + p.fallback = "false"; // AppConfig::get_bool() of nothing stored + return p; + } + // The dialog shows the first entry where nothing is stored. + Preference& choice(const char* key, const char* label, Choices choices, Lines tooltip = {}) + { + Preference& p = add(key, label, PreferenceKind::Choice, std::move(tooltip)); + p.fallback = choices.empty() ? std::string() : choices.front().first; + p.choices = std::move(choices); + return p; + } + Preference& number(const char* key, const char* label, std::optional min, std::optional max, Lines tooltip = {}) + { + Preference& p = add(key, label, PreferenceKind::Number, std::move(tooltip)); + p.min = min; + p.max = max; + return p; + } + Preference& text(const char* key, const char* label, Lines tooltip = {}) + { + return add(key, label, PreferenceKind::Text, std::move(tooltip)); + } + +private: + Preference& add(const char* key, const char* label, PreferenceKind kind, Lines tooltip) + { + Preference p; + p.key = key; + p.tab = m_tab; + p.section = m_section; + p.label = label; + p.kind = kind; + p.tooltip = std::move(tooltip); + m_table.push_back(std::move(p)); + return m_table.back(); + } + + std::vector& m_table; + std::string m_tab, m_section; +}; + +bool cad_feature_on() { return wxGetApp().is_enable_cad_feature(); } + +#ifdef _WIN32 +// The Microsoft Store package declares its file associations in its manifest, so the dialog shows a link to Windows' +// settings in place of the checkboxes. +bool not_in_store_package() { return !is_running_in_msix(); } +#endif + +std::vector build_table() +{ + std::vector table; + TableWriter t(table); + + //// GENERAL > Settings + t.section(kGeneral, L("Settings")); + Preference& language = t.choice("language", L("Language"), {}); + // TRN %1% is the key of a setting of the Preferences dialog; the sentence says why a script may not change it. + language.refused = L("%1%: changing the language restarts OrcaSlicer."); + language.own_row = true; // the languages are the translations installed + // The dialog's labels add the units to the translated names. + t.choice("use_inches", L("Units"), {{"0", "Metric (mm, g)"}, {"1", "Imperial (in, oz)"}}).own_row = true; + t.choice("default_page", L("Default page"), {{"0", L("Home")}, {"1", L("Prepare")}}, {L("Set the page opened on startup.")}); +#ifdef _WIN32 + Preference& dark_mode = t.checkbox("dark_color_mode", L("Enable dark Mode")); + dark_mode.fallback = "0"; // stored as 1 or 0 + dark_mode.own_row = true; +#endif + t.checkbox("single_instance", L("Allow only one OrcaSlicer instance"), +#if __APPLE__ + {L("On OSX there is always only one instance of app running by default. However it is allowed to run multiple instances " + "of same app from the command line. In such case this settings will allow only one instance.")}); +#else + {L("If this is enabled, when starting OrcaSlicer and another instance of the same OrcaSlicer is already running, that " + "instance will be reactivated instead.")}); +#endif + t.checkbox("show_splash_screen", L("Show splash screen"), {L("Show the splash screen during startup.")}); +#ifdef __linux__ + t.checkbox("window_buttons_on_left", L("Use window buttons on left side")).note = L("(Requires restart)"); + table.back().restart_needed = true; + t.checkbox("prefer_discrete_gpu", + // TRN "GPU" is the graphics card; the option only matters on computers that have two of them. + L("Render on the discrete GPU"), + // TRN DRI_PRIME is an environment variable name and must stay as it is. + {L("On a computer with two GPUs, run OrcaSlicer on the discrete GPU instead of the one that drives the display. " + "Some Wayland systems cannot show frames rendered on the other GPU, or fail to open the window at all. " + "Turn this off if the 3D view stays empty; if OrcaSlicer no longer starts, start it once with DRI_PRIME=0 " + "in the environment to get back here.")}) + .note = L("(Requires restart)"); + table.back().restart_needed = true; +#endif + + //// GENERAL > Features + t.section(kGeneral, L("Features")); + t.checkbox("enable_multi_machine", L("Multi device management"), + {L("With this option enabled, you can send a task to multiple devices at the same time and manage multiple devices.")}) + .note = L("(Requires restart)"); + table.back().restart_needed = true; +#ifdef SLIC3R_CAD + t.checkbox("enable_cad_feature", L("CAD feature (experimental)"), + {L("With this option enabled, the Design tab is shown, where models can be built and edited " + "parametrically. This feature is experimental and still under development.")}) + .note = L("(Requires restart)"); + table.back().restart_needed = true; +#endif + + //// GENERAL > AI features + t.section(kGeneral, L("AI features")); + Preference& mcp = t.checkbox("mcp_enabled", L("MCP server"), + {L("Run a local server that AI agents connect to through the Model Context Protocol (MCP).")}); + mcp.own_row = true; // checked while the server runs, and it turns the server on and off + // TRN %1% is the key of a setting of the Preferences dialog; the sentence says why a script may not change it. + mcp.refused = L("%1%: turning the MCP server off ends the connection of the agents that use it."); + Preference& port = t.number("mcp_port", L("Server port"), 1024, 65535, {L("Local port of the MCP server.")}); + port.own_row = true; // it shows the port the server is on, and moves the server + // TRN %1% is the key of a setting of the Preferences dialog; the sentence says why a script may not change it. + port.refused = L("%1%: changing the port moves the MCP server the agents connect to."); + // The switch that lets Python scripts run unrestricted is changed only in its own window, hidden from automation, so + // its row has no control named after a key and is not in this table. + + //// FILES > Project + t.section(kFiles, L("Project")); + t.choice(SETTING_PROJECT_LOAD_BEHAVIOUR, L("Load behavior"), + {{OPTION_PROJECT_LOAD_BEHAVIOUR_LOAD_ALL, L("Load All")}, + {OPTION_PROJECT_LOAD_BEHAVIOUR_ASK_WHEN_RELEVANT, L("Ask When Relevant")}, + {OPTION_PROJECT_LOAD_BEHAVIOUR_ALWAYS_ASK, L("Always Ask")}, + {OPTION_PROJECT_LOAD_BEHAVIOUR_LOAD_GEOMETRY, L("Load Geometry Only")}}, + {L("Should printer/filament/process settings be loaded when opening a 3MF file?")}); + // The checkbox and the period's field share a row. + t.checkbox("backup_switch", L("Auto backup"), {L("Backup your project periodically to help with restoring from an occasional crash.")}) + .own_row = true; + Preference& backup_interval = t.number("backup_interval", L("Auto backup"), 0, std::nullopt, {L("The period of backup in seconds.")}); + backup_interval.unit = L("sec"); + backup_interval.own_row = true; + t.checkbox("export_sources_full_pathnames", L("Store full source file paths in projects"), + {L("If enabled, saved projects store the absolute path to imported source files (STEP/STL/...), so " + "\"Reload from disk\" still works when the source file is kept in a different folder than the project. " + "If disabled, only the filename is stored, which keeps projects portable and avoids embedding absolute paths.")}); + + //// FILES > Recent files + t.section(kFiles, L("Recent files")); + t.number("max_recent_count", L("Maximum recent files"), 0, std::nullopt, {L("Maximum count of recent files")}).own_row = true; + t.checkbox("recent_models", L("Add STL/STEP files to recent files list")); + + //// FILES > Folder paths + t.section(kFiles, L("Folder paths")); + Preference& downloads = t.text("download_path", L("Downloads folder"), {L("Target folder for downloaded items")}); + downloads.own_row = true; // a folder picker + downloads.folder = true; + + //// FILES > File import + t.section(kFiles, L("File import")); + t.checkbox("import_names_cleanup_show_dialog", L("Ask how to handle unsupported characters in imported names"), + {L("Show the removal or replacement choices when original names contain unsupported characters.")}); + + //// FILES > 3MF import + t.section(kFiles, L("3MF import")); + t.checkbox("import_names_3mf_show_dialog", L("Show options when importing"), + {L("Show original-name and sorting options when importing a 3MF without project settings into the current project.")}); + t.checkbox("import_names_3mf_keep", L("Keep original names"), + {L("Use the body names stored in the imported file when it contains them.")}); + t.checkbox("no_warn_when_modified_gcodes", L("Don't warn when loading 3MF with modified G-code")); + + //// FILES > STEP import + t.section(kFiles, L("STEP import")); + t.checkbox("enable_step_mesh_setting", L("Show options when importing"), + {L("If enabled, a parameter settings dialog will appear during STEP file import.")}) + .wiki = "import_export#dont-show-again"; + Preference& linear = t.number("linear_deflection", L("Linear deflection"), 0.001, 0.1, + {L("Linear deflection used when meshing imported STEP files.\nSmaller values produce higher-quality " + "meshes but increase processing time.\nUsed as the default in the import dialog, or directly when " + "the import dialog is disabled.\nDefault: 0.003 mm.")}); + linear.unit = "mm"; + linear.decimals = 3; + t.number("angle_deflection", L("Angle deflection"), 0.01, 1.0, + {L("Angle deflection used when meshing imported STEP files.\nSmaller values produce higher-quality meshes but increase " + "processing time.\nUsed as the default in the import dialog, or directly when the import dialog is disabled.\nDefault: " + "0.5.")}) + .decimals = 2; + t.checkbox("is_split_compound", L("Split into multiple objects"), + {L("If enabled, compound and compsolid shapes in imported STEP files are split into multiple objects.\nUsed as the default " + "in the import dialog, or directly when the import dialog is disabled.\nDefault: enabled.")}); + t.checkbox("import_names_step_keep", L("Keep original names"), + {L("Use the body names stored in the imported file when it contains them.")}); + + //// FILES > AMF import + t.section(kFiles, L("AMF import")); + t.checkbox("import_names_amf_show_dialog", L("Show options when importing"), + {L("Show body grouping, original-name and sorting options when importing geometry into the current project.")}); + t.checkbox("import_names_amf_keep", L("Keep original names"), + {L("Use the body names stored in the imported file when it contains them.")}); + + //// FILES > DRC export + t.section(kFiles, L("DRC export")); + Preference& drc = t.number("drc_bits", L("Quality level for Draco export"), DRC_BITS_MIN, DRC_BITS_MAX, + {L("Controls the quantization bit depth used when compressing the mesh to Draco format.\n" + "0 = lossless compression (geometry is preserved at full precision). " + "Valid lossy values range from 8 to 30.\n" + "Lower values produce smaller files but lose more geometric detail; " + "higher values preserve more detail at the cost of larger files.")}); + drc.unit = L("bits"); + drc.wiki = "import_export#drc"; + +#ifdef _WIN32 + //// FILES > Extensions + t.section(kFiles, L("Associate files to OrcaSlicer")); + const auto association = [&t](const char* key, const char* label, const char* tooltip) { + Preference& p = t.checkbox(key, label, {tooltip}); + // TRN %1% is the key of a setting of the Preferences dialog; the sentence says why a script may not change it. + p.refused = L("%1%: a file association is a setting of Windows."); + p.shown = not_in_store_package; + }; + association("associate_3mf", L("Associate 3MF files to OrcaSlicer"), + L("If enabled, this sets OrcaSlicer as the default application to open 3MF files.")); + association("associate_drc", L("Associate DRC files to OrcaSlicer"), + L("If enabled, sets OrcaSlicer as default application to open DRC files.")); + association("associate_stl", L("Associate STL files to OrcaSlicer"), + L("If enabled, this sets OrcaSlicer as the default application to open STL files.")); + association("associate_step", L("Associate STEP files to OrcaSlicer"), + L("If enabled, this sets OrcaSlicer as the default application to open STEP files.")); +#endif + + //// BEHAVIOUR > Prepare + t.section(kBehaviour, L("Prepare")); + t.choice("auto_calculate_flush", L("Auto flush after changing..."), + {{"all", L("All")}, {"color change", L("Color")}, {"disabled", L("None")}}, + {L("Auto calculate flushing volumes when selected values changed")}); + t.checkbox("auto_arrange", L("Auto arrange plate after cloning")); + // The checkbox and the delay's field share a row. + t.checkbox("auto_slice_after_change", L("Auto slice after changes"), + {L("If enabled, OrcaSlicer will re-slice automatically whenever slicing-related settings change.")}) + .own_row = true; + Preference& delay = t.number("auto_slice_change_delay_seconds", L("Auto slice after changes"), 0, std::nullopt, + {L("Delay in seconds before auto slicing starts, allowing multiple edits to be grouped. Use 0 to slice " + "immediately.")}); + delay.unit = L("sec"); + delay.own_row = true; + t.checkbox("enable_primitive_size_dialog", L("Show options when adding a primitive"), + {L("If enabled, a dialog asks for the dimensions of a primitive shape before it is added.")}); + t.checkbox("enable_high_low_temp_mixed_printing", L("Remove mixed temperature restriction"), + {L("With this option enabled, you can print materials with a large temperature difference together.")}) + // TRN %1% is the key of a setting of the Preferences dialog; the sentence says why a script may not change it. + .refused = L("%1%: turning it on asks to confirm a warning first."); + t.checkbox("remember_print_action", L("Remember last print action"), + {L("If enabled, OrcaSlicer will remember the last selected option in the print button's dropdown (e.g. Print, Export plate " + "sliced file, Export G-code file) and use it as the default on next startup.")}); + + //// BEHAVIOUR > Preview + t.section(kBehaviour, L("Preview")); + // ORCA: view type the preview opens with + t.choice("preview_default_view_type", L("Default view type"), GCodeViewer::default_view_type_choices(), + {L("The color scheme the sliced preview opens with.\n" + "Automatic: Filament for multi material prints, Line Type for single material ones.\n" + "Last used: the view type you selected last.\n" + "Any other value always opens that view type.\n" + "You can still switch the view type in the preview afterwards.")}); + t.choice("preview_reduced_detail_mode", L("Simplify preview while dragging"), + {{"off", L("Off")}, {"solid", L("Solid model")}, {"shell", L("Shell only")}}, + {L("What the sliced preview draws while you drag the camera or a preview slider, or zoom with the mouse wheel, so that large " + "prints stay responsive. " + "The full toolpaths are restored as soon as you let go.\n" + "Off: the full toolpaths.\n" + "Solid model: the sliced objects and the prime tower as solid shapes in the colors of the current view, cut to the visible " + "layer range, " + "with its bottom and top layers and the supports drawn as toolpaths. Negative volumes are not cut out. " + "A print made object by object, or one on a belt printer, keeps its full toolpaths.\n" + "Shell only: every layer without its sparse infill, internal solid infill, internal bridges and gap fill, which lie under " + "the walls and skins. " + "Walls, top and bottom surfaces, bridges, supports and the prime tower are drawn whole, so the print looks the same from " + "outside.\n" + "The bottom and top layers of the visible range are always drawn whole; a layer with no infill of its own, as with infill " + "combination, takes the layers down to the nearest one with infill along.")}); + t.checkbox("preview_dim_previous_layers", L("Dim lower layers"), + {L("When scrubbing the layer slider in the sliced preview, render the layers below the current one darkened so that only " + "the layer being viewed is shown at full brightness.")}); + t.number("preview_dim_previous_layers_brightness", L("Dimmed layer brightness"), 0, 99, + {L("How brightly the dimmed layers are rendered when \"Dim lower layers\" is enabled.\n" + "99% is barely darkened, 0% renders them black. Capped at 99% because 100% would be the same as disabling the option.")}) + .unit = L("%"); + + //// BEHAVIOUR > Preset + t.section(kBehaviour, L("Preset")); + t.checkbox("remember_printer_config", L("Remember printer configuration"), + {L("If enabled, Orca will remember and switch filament/process configuration for each printer automatically.")}); + t.choice("group_filament_presets", L("Group user filament presets"), + {{"0", L("All")}, {"1", L("None")}, {"2", L("By type")}, {"3", L("By vendor")}}, + {L("Group user filament presets based on selection")}); + t.number("filaments_area_preferred_count", L("Optimize filaments area height for..."), 8, 99, + {L("Optimizes filament area maximum height by chosen filament count.")}) + .unit = L("filaments"); + t.checkbox("show_shared_profiles_notification", L("Show shared profiles notification"), + {L("Show a notification with a link to browse shared profiles when the selected printer is changed.")}); + + //// BEHAVIOUR > Plugins + t.section(kBehaviour, L("Plugins")); + t.number(SETTING_PLUGIN_PAGES_VISIBLE_COUNT, L("Visible plugin pages"), PLUGIN_PAGES_VISIBLE_COUNT_MIN, PLUGIN_PAGES_VISIBLE_COUNT_MAX, + {L("Number of plugin pages shown as fixed tabs before the remaining pages collapse into a dropdown on the last tab.")}) + .unit = L("pages"); + +#ifdef SLIC3R_CAD + //// BEHAVIOUR > Design + // Design-tab only, so it stays out of the way while the CAD feature is switched off. + t.section(kBehaviour, L("Design")); + t.checkbox("design_connector_face_glyph", L("Draw mate connectors as a face"), + {L("In the Design tab, draw a mate connector as a small face instead of the conventional " + "disc with a roll quadrant. A face shows its orientation at a glance, without learning the disc convention. " + "Turn this off for the conventional CAD representation.")}) + .shown = cad_feature_on; + // Saved WITH each design (it decides which loops are closed, i.e. what solid a project + // rebuilds into), so it applies to designs started from now on; an open design keeps + // the rule it was made with. + t.checkbox("auto_close_sketch_loops", L("Auto-close sketch loops"), + {L("Treat sketch endpoints within 0.001 mm as one joint and weld the loop shut. " + "Off: only exactly coincident endpoints join, so a loop with a tiny gap is " + "shown as open instead of being closed for you. Saved with each design; " + "applies to designs started after the change.")}) + .shown = cad_feature_on; +#endif + + //// BEHAVIOUR > Speed dial + t.section(kBehaviour, L("Speed dial")); + t.checkbox("enable_speed_dial", L("Open the Speed Dial from the keyboard"), + {L("When enabled, the Speed Dial keyboard shortcut (Space by default) opens the action search from any page.")}); + t.number(SETTING_SPEED_DIAL_RECENT_COUNT, L("Recent actions"), SPEED_DIAL_RECENT_COUNT_MIN, SPEED_DIAL_RECENT_COUNT_MAX, + {L("How many recently launched actions to show at the top of the Speed Dial. Set to 0 to hide recent actions.")}) + .unit = + // TRN Unit shown after the number of recent actions, as in "5 actions". + L("actions"); + + //// CONTROL > Camera + t.section(kControl, L("Camera")); + t.choice("camera_navigation_style", L("Camera style"), {{"0", L("Default")}, {"1", L("Touchpad")}}, + {L("Select camera navigation style.\nDefault: LMB+move for rotation, RMB/MMB+move for panning.\nTouchpad: Alt+move for " + "rotation, Shift+move for panning.")}); + Preference& orbit = t.number("camera_orbit_mult", L("Orbit speed multiplier"), 0.05, 2.0, + {L("Multiplies the orbit speed for finer or coarser camera movement.")}); + orbit.decimals = 2; + orbit.own_row = true; + t.checkbox("zoom_to_mouse", L("Zoom to mouse position"), + {L("Zoom in towards the mouse pointer's position in the 3D view, rather than the 2D window center.")}); + t.checkbox("use_free_camera", L("Use free camera"), {L("If enabled, use free camera. If not enabled, use constrained camera.")}); + t.checkbox("reverse_mouse_wheel_zoom", L("Reverse mouse zoom"), {L("If enabled, reverses the direction of zoom with mouse wheel.")}); + const Choices drag_actions = {{"0", L("None")}, {"1", L("Pan")}, {"2", L("Rotate")}}; + t.choice("left_mouse_drag_action", L("Left Mouse Drag"), drag_actions, + {L("Set the action that dragging the left mouse button should perform.")}); + t.choice("middle_mouse_drag_action", L("Middle Mouse Drag"), drag_actions, + {L("Set the action that dragging the middle mouse button should perform.")}); + t.choice("right_mouse_drag_action", L("Right Mouse Drag"), drag_actions, + {L("Set the action that dragging the right mouse button should perform.")}); + + //// GRAPHICS > General + t.section(kGraphics, L("General")); + t.checkbox(SETTING_OPENGL_PHONG_SMOOTH_NORMALS, L("Smooth normals"), + {L("Applies smooth normals to the model.\n\nRequires manual scene reload to take effect " + "(right-click on 3D view → \"Reload All\").")}); + t.checkbox("preview_translucent_filaments", L("Translucent filaments"), + {L("Draw the toolpaths of filaments whose color is partly transparent as see-through, as the 3D view draws their objects. " + "Turn it off to draw every filament opaque.")}); + + //// GRAPHICS > Realistic view + t.section(kGraphics, L("Realistic View")); + t.checkbox(SETTING_OPENGL_REALISTIC_PHONG, L("Phong shading"), {L("Uses Phong shading inside realistic view.")}); + t.checkbox(SETTING_OPENGL_REALISTIC_PREVIEW, L("Enable in Preview"), + {L("Also applies realistic view to the Preview canvas, not just Prepare.\n" + "Preview draws the full toolpath geometry, so shadows and SSAO cost considerably" + " more there than on a plain model.")}); + t.checkbox(SETTING_OPENGL_PHONG_SSAO, L("SSAO ambient occlusion"), {L("Applies SSAO in realistic view.")}); + t.choice(SETTING_OPENGL_REALISTIC_SHADOWS, L("Shadows"), + {{"off", L("Off")}, + // TRN Realistic-view shadow mode: the light stays fixed in the scene. + {"static", L("Static")}, + // TRN Realistic-view shadow mode: the light turns with the camera. + {"orbit", L("Orbit")}}, + {L("Renders cast shadows on the plate, other objects, and each object onto itself in realistic view.\n" + "Static: the light stays fixed in the world, so the shadows are only recomputed when the scene changes.\n" + "Orbit: the light turns with the camera, recomputing the shadows every frame the camera moves.")}); + t.checkbox(SETTING_OPENGL_REALISTIC_GLOSS, L("Glossy toolpaths"), + {L("Highlights the toolpaths in Preview as glossy plastic in realistic view.\n" + "Off, a translucent filament is matte and an opaque one keeps the highlight of the plain view.")}); + + //// GRAPHICS > Outline + t.section(kGraphics, L("Outline")); + t.checkbox(SETTING_OPENGL_OUTLINE_PERSISTENT, L("Persistent"), + {L("When Outline is enabled in the 3D canvas menu, outlines visible objects even when they are not selected.")}); + + //// GRAPHICS > Anti-aliasing + t.section(kGraphics, L("Anti-aliasing")); + // Its tooltip ends saying that it requires a restart. + t.choice(SETTING_OPENGL_AA_SAMPLES, L("MSAA Multiplier"), {{"0", L("Disabled")}, {"2", "2x"}, {"4", "4x"}, {"8", "8x"}, {"16", "16x"}}, + {L("Set the Multi-Sample Anti-Aliasing level.\n" + "Higher values result in smoother edges, but the impact on performance is exponential.\n" + "Lower values improve performance, at the cost of jagged edges.\n" + "If disabled, its recommended to enable FXAA to reduce jagged edges with minimal performance impact.\n\n" + "Requires application restart.")}) + .restart_needed = true; + t.checkbox(SETTING_OPENGL_FXAA_ENABLED, L("FXAA post-processing"), + {L("Applies Fast Approximate Anti-Aliasing as a screen-space pass.\n" + "Useful for disabling or reducing the MSAA setting to improve performance.\n\n" + "Takes effect immediately.")}); + + //// GRAPHICS > FPS + t.section(kGraphics, L("FPS")); + Preference& fps_cap = t.number(SETTING_OPENGL_FPS_CAP, L("FPS cap"), 0, 240, + {L("Limits viewport frame rate to reduce GPU load and power usage.\n" + "Set to 0 for unlimited frame rate.")}); + fps_cap.note = L("(0 = unlimited)"); + fps_cap.unit = L("FPS"); + t.checkbox(SETTING_OPENGL_SCENE_CACHE, L("Reuse the 3D scene while idle"), + {L("Skips redrawing the 3D scene when only the mouse cursor moves over the viewport, " + "and reuses the previous frame's scene instead. Reduces GPU load.\n" + "Disable it if the viewport shows stale or missing contents.\n\n" + "Takes effect immediately.")}); + t.checkbox(SETTING_OPENGL_SKIP_IDENTICAL_FRAMES, L("Skip unchanged frames"), + {L("Skips drawing a frame altogether when it would be identical to the one already on screen.\n" + "Only applies to frames that reuse the 3D scene, so it needs Reuse the 3D scene while idle.\n" + "Disable it if a hover highlight, tooltip or animation stops updating.\n\n" + "Takes effect immediately.")}); + t.checkbox(SETTING_OPENGL_SHOW_FPS_OVERLAY, L("Show FPS overlay"), + {L("Displays rendering counts in the top-right corner of the viewport."), + L("FPS: frames presented to the screen per second."), + L("3D: frames per second that redrew the 3D scene.")}); + t.checkbox(SETTING_OPENGL_SHOW_RENDER_TIMINGS, L("Show render timings"), + {L("Displays how many milliseconds each part of a frame that redraws the 3D scene takes, in the top-right corner of the " + "viewport."), + L("CPU: time spent issuing the drawing commands."), L("GPU: time the graphics card spent running them."), + L("Adds a small overhead to each frame while enabled.")}); + + //// ONLINE > Connection + t.section(kOnline, L("Connection")); + Preference& region = t.choice("region", L("Login region"), + {{"Asia-Pacific", "Asia-Pacific"}, + {"China", "China"}, + {"Europe", "Europe"}, + {"North America", "North America"}, + {"Others", "Others"}}); + region.fallback = ""; // no region is shown where none is stored + region.own_row = true; + // TRN %1% is the key of a setting of the Preferences dialog; the sentence says why a script may not change it. + region.refused = L("%1%: changing the login region signs out of the cloud account."); + t.checkbox("stealth_mode", L("Stealth mode"), + {L("This disables all cloud features, including Orca Cloud profile syncing. Users who prefer to work entirely offline can " + "enable this option.\n\nNote: When Stealth Mode is enabled, your user profiles will not be backed up to Orca Cloud.")}); + t.checkbox("hide_login_side_panel", L("Hide login side panel"), {L("Hide the login side panel on the home page.")}); + + //// ONLINE > Update & sync + t.section(kOnline, L("Update & sync")); + t.checkbox("check_stable_update_only", L("Check for stable updates only")); + t.checkbox("sync_user_preset", L("Auto sync user presets (Printer/Filament/Process)")); + t.choice("sync_ams_filament_mode", L("Filament sync mode"), {{"0", L("Filament & Color")}, {"1", L("Color only")}}, + {L("Choose whether sync updates both filament preset and color, or only color.")}); + t.checkbox("sync_system_preset", L("Update built-in presets automatically.")); + t.checkbox(SETTING_USE_ENCRYPTED_TOKEN_FILE, L("Use encrypted file for token storage"), + {L("Store authentication tokens in an encrypted file instead of the system keychain. (Requires restart)")}) + .restart_needed = true; + + //// ONLINE > Network plugin + t.section(kOnline, L("Bambu network plug-in")); + t.checkbox("installed_networking", L("Enable Bambu network plug-in")).refused = + // TRN %1% is the key of a setting of the Preferences dialog; the sentence says why a script may not change it. + L("%1%: enabling the Bambu network plug-in downloads and installs it."); + Preference& plugin_version = t.choice(SETTING_NETWORK_PLUGIN_VERSION, L("Network plug-in version"), {}, + {L("Select the network plug-in version to use")}); + plugin_version.own_row = true; // the versions are those the app can load + // TRN %1% is the key of a setting of the Preferences dialog; the sentence says why a script may not change it. + plugin_version.refused = L("%1%: switching the version downloads or reloads the network plug-in."); + + //// DEVELOPER > Settings + t.section(kDeveloper, L("Settings")); + t.checkbox("developer_mode", L("Developer mode")).wiki = "option_mode#developer+mode"; + t.checkbox("skip_ams_blacklist_check", L("Skip AMS blacklist check")); + t.checkbox("show_unsupported_presets", L("Show unsupported presets"), + {L("Show incompatible/unsupported presets in the printer and filament dropdown lists. These presets cannot be selected.")}); + t.checkbox("export_statistics", L("Export statistics with G-code"), + {L("If enabled, exporting a G-code file also writes its statistics as JSON next to it, as .statistics.json, " + "and an exported sliced 3MF file holds them inside: print time, filament and feature totals, " + "and the same per layer and per object.")}); + + //// DEVELOPER > Experimental Features + t.section(kDeveloper, L("Experimental Features")); + t.checkbox("keep_painting", L("Keep painted feature after mesh change"), + {L("Attempt to keep painted features (color/seam/support/fuzzy etc.) after changing the object mesh (such as cut/reload " + "from disk/simplify/fix etc.)\nHighly experimental! Slow and may create artifact.")}); + t.checkbox("use_printer_agents", L("Use printer agents instead of print hosts"), + {L("Route print jobs for non-Bambu printers through printer plug-in agents instead of the classic print-host upload " + "flow.\nWhen disabled, OrcaSlicer uses the legacy print-host behavior.")}); + + //// DEVELOPER > Storage + t.section(kDeveloper, L("Storage")); + t.checkbox("allow_abnormal_storage", L("Allow Abnormal Storage"), + {L("This allows the use of Storage that is marked as abnormal by the Printer.\nUse at your own risk, can cause issues!")}); + + //// DEVELOPER > Log Level + t.section(kDeveloper, L("Log Level")); + // The values are get_string_logging_level()'s, in the order of their levels. + Preference& log_level = t.choice("log_severity_level", L("Log Level"), + {{"fatal", L("fatal")}, + {"error", L("error")}, + {"warning", L("warning")}, + {"info", L("info")}, + {"debug", L("debug")}, + {"trace", L("trace")}}, + {L("Log Level")}); + log_level.fallback = ""; // the row shows no level where none is stored + log_level.own_row = true; + + return table; +} + +// A number as a person writes it: no trailing zeros, no exponent for the ranges of the table. +std::string number_text(double value) +{ + std::ostringstream out; + out.imbue(std::locale::classic()); + out << value; + return out.str(); +} + +Refusal refusal(const char* code, const char* msgid, std::vector args, std::vector names = {}) +{ + return {RefusalKind::Precondition, code, msgid, std::move(args), std::move(names)}; +} + +// Why `value` is not one `p` takes, or none. +std::optional value_refusal(const Preference& p, const json& value) +{ + switch (p.kind) { + case PreferenceKind::Checkbox: + if (!value.is_boolean()) + // TRN %1% is a preference's key. + return refusal("not_a_boolean", L("%1% is a checkbox: give true or false."), {p.key}); + return std::nullopt; + case PreferenceKind::Choice: { + const std::string given = value.is_string() ? value.get() : value.dump(); + const bool known = (value.is_string() || value.is_number_integer()) && + std::any_of(p.choices.begin(), p.choices.end(), [&given](const auto& c) { return c.first == given; }); + if (known) + return std::nullopt; + std::vector values; + for (const auto& [stored, label] : p.choices) + values.push_back(stored); + // TRN %1% is a preference's key, %2% the value a call gave it. + return refusal("no_such_choice", L("%1% has no choice \"%2%\"."), {p.key, given}, std::move(values)); + } + case PreferenceKind::Number: { + if (!value.is_number()) + // TRN %1% is a preference's key. + return refusal("not_a_number", L("%1% takes a number."), {p.key}); + const double number = value.get(); + if (p.decimals == 0 && std::floor(number) != number) + // TRN %1% is a preference's key. + return refusal("not_a_whole_number", L("%1% takes a whole number."), {p.key}); + if ((p.min && number < *p.min) || (p.max && number > *p.max)) { + const std::string low = p.min ? number_text(*p.min) : std::string(), high = p.max ? number_text(*p.max) : std::string(); + if (p.min && p.max) + // TRN %1% is a preference's key, %2% and %3% the lowest and highest numbers it takes. + return refusal("out_of_range", L("%1% takes a number from %2% to %3%."), {p.key, low, high}, {low, high}); + if (p.min) + // TRN %1% is a preference's key, %2% the lowest number it takes. + return refusal("out_of_range", L("%1% takes a number of at least %2%."), {p.key, low}, {low}); + // TRN %1% is a preference's key, %2% the highest number it takes. + return refusal("out_of_range", L("%1% takes a number of at most %2%."), {p.key, high}, {high}); + } + return std::nullopt; + } + case PreferenceKind::Text: { + if (!value.is_string()) + // TRN %1% is a preference's key. + return refusal("not_a_text", L("%1% takes a text."), {p.key}); + const wxString path = wxString::FromUTF8(value.get()); + if (p.folder && (path.empty() || !wxFileName(path).IsAbsolute() || !wxDirExists(path))) + // TRN %1% is a preference's key, %2% the text a call gave it. + return refusal("not_a_folder", L("%1% takes the absolute path of an existing folder, which \"%2%\" is not."), + {p.key, value.get()}); + return std::nullopt; + } + } + return std::nullopt; +} + +// The Preview tab's canvas, where the main window is up. +GLCanvas3D* preview_canvas() +{ + Plater* plater = wxGetApp().plater(); + return plater != nullptr ? plater->get_preview_canvas3D() : nullptr; +} + +// Draws the loaded preview again with the change just made to its viewer. +void redraw_preview(GLCanvas3D& canvas) +{ + canvas.set_as_dirty(); + canvas.request_extra_frame(); +} + +} // namespace + +const std::vector& preferences() +{ + static const std::vector table = build_table(); + return table; +} + +std::vector shown_preferences() +{ + std::vector shown; + for (const Preference& p : preferences()) + if (p.shown == nullptr || p.shown()) + shown.push_back(p); + return shown; +} + +const Preference* find_preference(const std::vector& table, const std::string& key) +{ + const auto it = std::find_if(table.begin(), table.end(), [&key](const Preference& p) { return p.key == key; }); + return it != table.end() ? &*it : nullptr; +} + +std::string preference_text(const Preference& p, const json& value) +{ + switch (p.kind) { + case PreferenceKind::Checkbox: { + const bool on = value.get(); + if (p.fallback == "0") + return on ? "1" : "0"; + return on ? "true" : "false"; + } + case PreferenceKind::Choice: return value.is_string() ? value.get() : value.dump(); + case PreferenceKind::Number: { + const double number = value.get(); + if (p.decimals == 0) + return std::to_string(std::llround(number)); + // As the dialog's field writes it: wxString::FromCDouble() with the row's decimals. + std::ostringstream out; + out.imbue(std::locale::classic()); + out << std::fixed << std::setprecision(p.decimals) << number; + return out.str(); + } + case PreferenceKind::Text: return value.get(); + } + return {}; +} + +json preference_value(const Preference& p, const std::string& stored) +{ + switch (p.kind) { + case PreferenceKind::Checkbox: return AppConfig::is_true(stored); + case PreferenceKind::Number: { + std::istringstream in(stored); + in.imbue(std::locale::classic()); + double number = 0; + if (stored.empty() || !(in >> number) || !in.eof()) + return stored; + if (p.decimals == 0 && std::floor(number) == number) + return std::int64_t(number); + return number; + } + case PreferenceKind::Choice: + case PreferenceKind::Text: return stored; + } + return stored; +} + +std::optional check_preferences(const std::vector& table, const std::map& values) +{ + for (const auto& [key, value] : values) { + const Preference* p = find_preference(table, key); + if (p == nullptr) { + std::vector keys; + for (const Preference& known : table) + keys.push_back(known.key); + // TRN %1% is the name of a setting a call asked for. + return refusal("not_a_preference", L("%1% is not a setting of the Preferences dialog."), {key}, + closest_names(std::move(keys), key)); + } + if (p->refused != nullptr) + return refusal("preference_refused", p->refused, {key}, {key}); + if (std::optional why = value_refusal(*p, value)) + return why; + } + return std::nullopt; +} + +Outcome set_preferences(const std::map& values) +{ + const std::vector table = shown_preferences(); + for (const auto& [key, value] : values) + if (find_preference(table, key) == nullptr && find_preference(preferences(), key) != nullptr) + // TRN %1% is the name of a setting that the Preferences dialog shows only in some cases. + return refusal("preference_not_shown", L("The Preferences dialog does not show %1% now."), {key}); + if (std::optional why = check_preferences(table, values)) + return *why; + + AppConfig& config = *wxGetApp().app_config; + PreferenceChanges changes; + for (const auto& [key, value] : values) { + const Preference& p = *find_preference(table, key); + const std::string after = preference_text(p, value); + std::string before; + const bool stored = config.get("app", key, before); + if (stored && preference_value(p, before) == preference_value(p, after)) { + changes.unchanged.push_back(key); + continue; + } + config.set(key, after); + changes.changed.push_back({key, stored ? before : p.fallback, after, stored}); + } + if (changes.changed.empty()) + return changes; + config.save(); + + bool redraw = false; + for (const PreferenceChange& change : changes.changed) { + apply_preference(change.key); + const std::vector& drawn = canvas_preferences(); + redraw |= std::find(drawn.begin(), drawn.end(), change.key) != drawn.end(); + } + if (Plater* plater = wxGetApp().plater(); redraw && plater != nullptr) + plater->set_current_canvas_as_dirty(); + return changes; +} + +void apply_preference(const std::string& key) +{ + GUI_App& app = wxGetApp(); + AppConfig& config = *app.app_config; + if (key == "sync_user_preset") { + const bool sync = config.get("sync_user_preset") == "true"; + if (sync) + app.start_sync_user_preset(); + else + app.stop_sync_user_preset(); + BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << " sync_user_preset: " << (sync ? "true" : "false"); + } else if (key == "stealth_mode") { + if (config.get_stealth_mode()) + app.on_stealth_mode_enter(); + } else if (key == "hide_login_side_panel") { + if (WebViewPanel* home = WebViewPanel::if_built()) + home->SendCloudProvidersInfo(); + } else if (key == "preview_translucent_filaments") { + // ORCA: apply the filament translucency change immediately to the currently loaded preview + if (GLCanvas3D* canvas = preview_canvas()) { + canvas->get_gcode_viewer().set_translucent_filaments(config.get_bool(key)); + redraw_preview(*canvas); + } + } else if (key == "preview_dim_previous_layers") { + // ORCA: apply the preview dimming change immediately to the currently loaded preview + if (GLCanvas3D* canvas = preview_canvas()) { + canvas->get_gcode_viewer().set_dim_previous_layers(config.get_bool(key)); + redraw_preview(*canvas); + } + } else if (key == "preview_dim_previous_layers_brightness") { + // ORCA: apply the new brightness immediately to the currently loaded preview + if (GLCanvas3D* canvas = preview_canvas()) { + canvas->get_gcode_viewer().set_dim_previous_layers_brightness(0.01f * std::atoi(config.get(key).c_str())); + redraw_preview(*canvas); + } + } else if (key == "preview_reduced_detail_mode") { + // apply the new mode immediately to the currently loaded preview + if (GLCanvas3D* canvas = preview_canvas()) { + canvas->get_gcode_viewer().set_reduced_detail_mode(config.get(key)); + redraw_preview(*canvas); + } +#ifdef __WXMSW__ + } else if (key == "associate_3mf" || key == "associate_drc" || key == "associate_stl" || key == "associate_step") { + const std::wstring extension = wxString::FromUTF8(key.substr(std::string("associate_").size())).ToStdWstring(); + if (config.get(key) == "true") + app.associate_files(extension); + else + app.disassociate_files(extension); + } else if (key == "installed_networking") { + if (config.get_bool("installed_networking")) + app.CallAfter([] { wxGetApp().ShowDownNetPluginDlg(); }); +#endif // __WXMSW__ + } else if (key == "developer_mode") { + app.update_mode(); + } else if (key == "internal_developer_mode") { + // webview dump_vedio + app.update_internal_development(); + if (config.get("internal_developer_mode") == "true") + app.mainframe->show_log_window(); + } else if (key == "show_unsupported_presets" || key == "group_filament_presets") { + app.plater()->sidebar().update_presets(Preset::TYPE_FILAMENT); + } else if (key == "use_printer_agents") { + // Rebuild the Device tab so the native/web-UI choice reflects the new flag + // immediately, instead of only on the next printer-preset change or restart. + if (app.plater()) + app.plater()->sidebar().update_all_preset_comboboxes(); + } else if (key == "filaments_area_preferred_count") { + if (Plater* plater = app.plater()) { + Sidebar& sidebar = plater->sidebar(); + sidebar.update_filaments_area_height(); + sidebar.Freeze(); + sidebar.Layout(); + sidebar.Thaw(); + plater->PostSizeEvent(); + } + } else if (key == SETTING_PLUGIN_PAGES_VISIBLE_COUNT) { + app.mainframe->plugin_pages().set_visible_page_count(std::atoi(config.get(key).c_str())); + } else if (key == "max_recent_count") { + long max = 0; + if (wxString::FromUTF8(config.get(key)).ToLong(&max)) + app.mainframe->set_max_recent_count(max); + } else if (key == "log_severity_level") { + Slic3r::set_logging_level(Slic3r::level_string_to_boost(config.get(key))); + } else if (key == "backup_switch") { + const bool on = config.get("backup_switch") == "true"; + std::string backup_interval = "10"; + config.get("backup_interval", backup_interval); + Slic3r::set_backup_interval(on ? boost::lexical_cast(backup_interval) : 0); + } else if (key == "backup_interval") { + // The period runs the timer only while Auto backup is on, as the app's start sets it; the dialog's field is + // disabled while it is off. + long interval = 0; + wxString::FromUTF8(config.get(key)).ToLong(&interval); + Slic3r::set_backup_interval(config.get_bool("backup_switch") ? interval : 0); + } else if (key == "download_path") { + // The open Preferences dialog shows the folder in its row. Its Browse button is what reaches it: a call that + // writes the folder cannot run while the dialog, which is modal, is open. + for (wxWindow* window : wxTopLevelWindows) + if (auto* dialog = dynamic_cast(window)) + dialog->show_download_path(); + } else if (key == "dark_color_mode") { + app.Update_dark_mode_flag(); +#ifdef _MSW_DARK_MODE + app.force_colors_update(); + app.update_ui_from_settings(); +#endif + SimpleEvent evt = SimpleEvent(EVT_GLCANVAS_COLOR_MODE_CHANGED); + wxPostEvent(app.plater(), evt); + } +} + +const std::vector& canvas_preferences() +{ + static const std::vector keys = { + SETTING_OPENGL_FXAA_ENABLED, SETTING_OPENGL_FPS_CAP, SETTING_OPENGL_SHOW_FPS_OVERLAY, + SETTING_OPENGL_SHOW_RENDER_TIMINGS, SETTING_OPENGL_SCENE_CACHE, SETTING_OPENGL_SKIP_IDENTICAL_FRAMES, + SETTING_OPENGL_REALISTIC_SHADOWS, SETTING_OPENGL_REALISTIC_GLOSS, SETTING_OPENGL_OUTLINE_PERSISTENT, + SETTING_OPENGL_OUTLINE_COLOR, SETTING_OPENGL_SELECTION_OUTLINE_COLOR}; + return keys; +} + +bool mcp_switch_shown() +{ + const Mcp::McpEndpoint* endpoint = wxGetApp().mcp_endpoint(); + return wxGetApp().app_config->get_bool("mcp_enabled") || (endpoint != nullptr && endpoint->serving()); +} + +int mcp_port_shown() +{ + GUI_App& app = wxGetApp(); + const Mcp::McpEndpoint* endpoint = app.mcp_endpoint(); + if (endpoint != nullptr && endpoint->serving()) + return endpoint->port(); + const GUI_InitParams* params = app.init_params; + return Mcp::endpoint_port(params != nullptr ? params->mcp.port : 0, app.app_config->get("mcp_port")); +} + +std::map shown_texts() +{ + return {{"mcp_enabled", mcp_switch_shown() ? "true" : "false"}, {"mcp_port", std::to_string(mcp_port_shown())}}; +} + +}}} // namespace Slic3r::GUI::Ops diff --git a/src/slic3r/GUI/Operations/PreferenceOps.hpp b/src/slic3r/GUI/Operations/PreferenceOps.hpp new file mode 100644 index 0000000000..d021095597 --- /dev/null +++ b/src/slic3r/GUI/Operations/PreferenceOps.hpp @@ -0,0 +1,124 @@ +#pragma once + +#include "Outcome.hpp" + +#include + +#include +#include +#include +#include +#include + +// The app's preferences as the Preferences dialog shows them: one table of the rows whose control is named after the +// key it stores in the app configuration's `app` section. The dialog builds those rows from it, preferences_get lists +// it and preferences_set writes through it, so the three cannot differ. +namespace Slic3r { namespace GUI { namespace Ops { + +enum class PreferenceKind { Checkbox, Choice, Number, Text }; + +struct Preference +{ + std::string key; + std::string tab; // general, files, behaviour, control, graphics, online or developer + std::string section; // the title of the row's group, an English msgid + std::string label; // the row's title, an English msgid + PreferenceKind kind = PreferenceKind::Checkbox; + // A choice's entries in the dialog's order: the value stored for it and its label, an English msgid, a symbol such as + // "4x" that is shown as it is, or for a row of its own the English of what its function shows. Empty for a choice + // whose entries the running app lists. + std::vector> choices; + std::optional min, max; // a number's range; a bound the dialog does not set is left out + std::string fallback; // what the dialog shows where nothing is stored + bool folder = false; // a text that is the absolute path of an existing folder, which the dialog picks in a folder dialog + const char* refused = nullptr; // why a call may not write it, an English msgid whose %1% is the key; null: it may + // The value is read at the next start, so a write is stored at once and changes nothing before then: the rows the + // dialog marks "(Requires restart)", in their note or their tooltip. + bool restart_needed = false; + + // How the dialog builds the row. + std::vector tooltip; // English msgids, shown one per line; none: the label + std::string note; // a msgid shown after the control, "(Requires restart)" + std::string unit; // a number's unit: a msgid after a spin control, or a symbol in a decimal field, shown as it is + std::string wiki; // the label's link into the wiki, under https://www.orcaslicer.com/wiki/ + int decimals = 0; // a number's decimals; 0: a whole number, in a spin control unless the row is its own + // The dialog builds the row with a function of its own, by its key, as its control has handlers or labels the + // plain rows do not; a row that function builds with another key's (a checkbox and its field) has one too. + bool own_row = false; + // Whether the dialog shows the row in this run, where that depends on the app (the CAD feature, the Microsoft Store + // package); null: always. Called on the UI thread. + bool (*shown)() = nullptr; +}; + +// Every preference the Preferences dialog can show, in its order, tab by tab. +const std::vector& preferences(); + +// The preferences the dialog shows in this run: preferences() less the rows whose `shown` says no. UI thread. +std::vector shown_preferences(); + +// `key`'s entry in `table`, or null. +const Preference* find_preference(const std::vector& table, const std::string& key); + +// What `p` stores for `value` as its control stores it: "true" or "false" for a checkbox ("1" or "0" where its fallback +// is "0"), a choice's value, a whole number, or a number with the row's decimals. `value` is one check_preferences() +// takes. +std::string preference_text(const Preference& p, const nlohmann::json& value); + +// The value `stored` stands for in `p`'s kind: true or false for a checkbox, a number for a number field (the text as it +// is where it is no number), the text for the others. +nlohmann::json preference_value(const Preference& p, const std::string& stored); + +// Why `values` ({key: value}) cannot be written to `table`'s preferences, checked key by key in the keys' order (the +// map's), the first refusal winning, or none: +// not_a_preference (a key `table` lacks, with the closest keys), preference_refused (the reason the table gives, +// with the key), not_a_boolean, no_such_choice (with the choice's values), not_a_number, not_a_whole_number, +// out_of_range (with the range), not_a_text and not_a_folder (a folder's text that is no existing folder's absolute path). +std::optional check_preferences(const std::vector& table, const std::map& values); + +// A preference a call wrote: its text before and after, as stored. Where nothing was stored before, `before` is the +// fallback the dialog showed and `stored_before` is false. +struct PreferenceChange +{ + std::string key, before, after; + bool stored_before = true; +}; +struct PreferenceChanges +{ + std::vector changed; // in the keys' order + std::vector unchanged; // keys whose stored value was already the one asked for +}; + +// Writes `values` ({key: value}) to the preferences the dialog shows, as their controls do: every key and value is +// checked first (check_preferences() over shown_preferences()), so a refused call changes nothing; then the changed +// ones are written together, the app configuration is saved, and each changed key's effect runs through +// apply_preference(), in the keys' order, followed by one redraw of the 3D view where a key it draws with changed. A +// key whose stored value is already the one asked for is left as it is and runs nothing. Not in the undo history. UI +// thread. +// Refuses: what check_preferences() refuses. +Outcome set_preferences(const std::map& values); + +// What changing `key` does in the app beyond storing it, as its control in the Preferences dialog does it, with the new +// value read from the app configuration: the preview's look, the sidebar's preset lists and height, the mode the +// settings show, the backup timer, the log level, the theme, the preset sync started or stopped, stealth mode's sign-out +// of the cloud accounts, the downloads folder an open Preferences dialog shows. The +// dialog's controls and set_preferences() both call it once the value is stored; the dialog's own controls that follow a +// value (a field enabled with its checkbox) stay the dialog's. A key with no effect does nothing. UI thread. +void apply_preference(const std::string& key); + +// The preferences the 3D view reads every frame: a change takes one redraw to show, which the Preferences dialog's +// closing and set_preferences() ask for. +const std::vector& canvas_preferences(); + +// The MCP server's switch as the Preferences dialog shows it: on while the server runs, also where --mcp started it for +// this session only, else as stored. UI thread. +bool mcp_switch_shown(); + +// The MCP server's port as the dialog shows it: the running server's, otherwise the one turning it on opens +// (GUI_App::open_mcp_endpoint()): --mcp-port until a port is set in Preferences, then the saved one. UI thread. +int mcp_port_shown(); + +// What the dialog shows, as preference_text() writes it, for each preference whose control does not show the stored +// value: mcp_enabled (mcp_switch_shown()) and mcp_port (mcp_port_shown()). preferences_get reads these. UI thread. +std::map shown_texts(); + +}}} // namespace Slic3r::GUI::Ops diff --git a/src/slic3r/GUI/Operations/PresetOps.cpp b/src/slic3r/GUI/Operations/PresetOps.cpp index fd5cbd5aaa..7da2ede25f 100644 --- a/src/slic3r/GUI/Operations/PresetOps.cpp +++ b/src/slic3r/GUI/Operations/PresetOps.cpp @@ -7,19 +7,29 @@ #include "slic3r/GUI/I18N.hpp" #include "slic3r/GUI/MainFrame.hpp" #include "slic3r/GUI/Plater.hpp" +#include "slic3r/GUI/DeviceCore/DevManager.h" +#include "slic3r/GUI/DeviceManager.hpp" +#include "slic3r/GUI/PartPlate.hpp" #include "slic3r/GUI/PresetComboBoxes.hpp" +#include "slic3r/GUI/SyncAmsInfoDialog.hpp" #include "slic3r/GUI/Tab.hpp" +#include "libslic3r/Config.hpp" #include "libslic3r/Preset.hpp" #include "libslic3r/PresetBundle.hpp" +#include "libslic3r/ProjectTask.hpp" +#include "libslic3r/TriangleSelector.hpp" +#include "libslic3r/libslic3r.h" #include #include #include #include +#include #include #include +#include #include #include #include @@ -368,4 +378,295 @@ Outcome import_presets(const ImportPresetsArgs& args) return result; } +Outcome sync_presets() +{ + assert(wxThread::IsMain()); + if (!wxGetApp().is_user_login()) + return Refusal{RefusalKind::Precondition, "not_signed_in", L("Sign in to sync presets.")}; + wxGetApp().restart_sync_user_preset(); + return Done{}; +} + +// ---- Filament slots ---- + +namespace { + +// Why the filament list cannot change, or none: a printer of another technology has none, and a G-code file shown in +// place of a project has its own. +std::optional filament_list_refusal(Plater& plater) +{ + if (plater.printer_technology() != ptFFF || plater.only_gcode_mode() || plater.using_exported_file()) + return Refusal{RefusalKind::Precondition, "filaments_unavailable", + L("Filament slots belong to a filament (FFF) project, not to a G-code file.")}; + return std::nullopt; +} + +// Why the + and - buttons and a slot's Delete do not show, or none: they are for a printer that takes several +// filaments through one extruder (Sidebar::should_show_SEMM_buttons()). +std::optional slot_buttons_refusal(Plater& plater) +{ + if (std::optional refusal = filament_list_refusal(plater)) + return refusal; + if (!Sidebar::should_show_SEMM_buttons()) + return Refusal{RefusalKind::Precondition, "one_filament_per_extruder", + L("This printer has one filament per extruder; change the number of extruders in the printer settings.")}; + return std::nullopt; +} + +Refusal too_many_filaments() { return {RefusalKind::Precondition, "too_many_filaments", L("No more filament slots can be added.")}; } + +Refusal last_filament_slot() { return {RefusalKind::Precondition, "last_filament_slot", L("The only filament slot cannot be deleted.")}; } + +} // namespace + +Outcome add_filament_slot() +{ + assert(wxThread::IsMain()); + Plater& plater = *wxGetApp().plater(); + if (std::optional refusal = slot_buttons_refusal(plater)) + return *refusal; + const PresetBundle& bundle = *wxGetApp().preset_bundle; + const std::size_t before = bundle.filament_presets.size(); + if (before >= MAXIMUM_EXTRUDER_NUMBER) + return too_many_filaments(); + // A new physical slot goes after the physical ones; mixed filaments move up by one. + const int slot = int(bundle.num_physical_filaments()) + 1; + plater.sidebar().add_filament(); + plater.sidebar().update_filaments_counter(); + if (bundle.filament_presets.size() == before) + return Refusal{RefusalKind::Failed, "not_added", L("No filament slot was added.")}; + return slot; +} + +std::optional filament_delete_refusal(int slots, int slot, std::optional merge_into) +{ + if (slots < 2) + return last_filament_slot(); + if (slot < 1 || slot > slots) + // TRN %1% is the number of the last filament slot. + return Refusal{RefusalKind::Precondition, "no_such_slot", L("Filament slot must be 1 to %1%."), {std::to_string(slots)}}; + if (merge_into && (*merge_into < 1 || *merge_into > slots)) + // TRN %1% is the number of the last filament slot. + return Refusal{RefusalKind::Precondition, "no_such_slot", L("The slot to merge into must be 1 to %1%."), {std::to_string(slots)}}; + if (merge_into == slot) + return Refusal{RefusalKind::Precondition, "merge_into_itself", L("A filament slot cannot be merged into itself.")}; + return std::nullopt; +} + +Outcome delete_filament_slot(const DeleteFilamentArgs& args) +{ + assert(wxThread::IsMain()); + Plater& plater = *wxGetApp().plater(); + if (std::optional refusal = slot_buttons_refusal(plater)) + return *refusal; + const PresetBundle& bundle = *wxGetApp().preset_bundle; + const int slots = int(bundle.filament_presets.size()); + const int physical = int(bundle.num_physical_filaments()); + // One physical slot stays, whatever mixed slots there are. + if (physical < 2) + return last_filament_slot(); + const int slot = args.filament_slot.value_or(physical); + if (std::optional refusal = filament_delete_refusal(slots, slot, args.merge_into)) + return *refusal; + if (bundle.is_mixed_filament(std::size_t(slot) - 1)) + return Refusal{RefusalKind::Precondition, "mixed_filament_slot", + // TRN %1% is a filament slot number. + L("Filament slot %1% is a mixed filament; delete it from the mixed filament list."), {std::to_string(slot)}}; + Sidebar& sidebar = plater.sidebar(); + if (args.merge_into) { + if (sidebar.merge_removes_component(std::size_t(slot) - 1, std::size_t(*args.merge_into) - 1)) + return Refusal{RefusalKind::Precondition, "mixed_uses_slot", + L("The target mixed filament uses this physical filament as a component. " + "Merging will remove this physical filament and may invalidate the mixed filament. Continue?")}; + sidebar.change_filament(std::size_t(slot) - 1, std::size_t(*args.merge_into) - 1); + } else { + sidebar.delete_filament(std::size_t(slot) - 1); + } + sidebar.update_filaments_counter(); + if (int(bundle.filament_presets.size()) == slots) + return Refusal{RefusalKind::Failed, "not_deleted", L("The filament slot was not deleted.")}; + DeletedFilament deleted; + deleted.filament_slot = slot; + // The slots after the deleted one move down by one. + if (args.merge_into) + deleted.merged_into = *args.merge_into > slot ? *args.merge_into - 1 : *args.merge_into; + return deleted; +} + +std::optional mixed_filament_refusal(const std::vector& types, const std::vector& components, + const std::vector& ratios) +{ + const int slots = int(types.size()); + for (auto it = components.begin(); it != components.end(); ++it) + if (std::find(components.begin(), it, *it) != it) + return Refusal{RefusalKind::Precondition, "duplicate_component", + // TRN %1% is a filament slot number. + L("Filament %1% is named twice: a mixed filament mixes each filament once."), + {std::to_string(*it)}}; + if (components.size() < 2) + return Refusal{RefusalKind::Precondition, "too_few_components", L("A mixed filament mixes two filaments or more.")}; + for (int component : components) + if (component < 1 || component > slots) + return Refusal{RefusalKind::Precondition, "no_such_slot", + // TRN %1% is the filament slot asked for, %2% the number of the last filament that can be mixed. + L("Filament %1% does not exist: the filaments that mix are 1 to %2%."), + {std::to_string(component), std::to_string(slots)}}; + // The dialog's OK takes filaments of one type; check_mixed_filament_type_consistency() marks another mix broken. + std::vector mixed_types; + for (int component : components) + mixed_types.push_back(std::to_string(component) + ": " + types[std::size_t(component - 1)]); + for (int component : components) + if (types[std::size_t(component - 1)] != types[std::size_t(components.front() - 1)]) + return Refusal{RefusalKind::Precondition, "mixed_types", L("Cannot mix different filament types"), {}, mixed_types}; + const bool shares = ratios.size() == components.size() && + std::all_of(ratios.begin(), ratios.end(), [](double ratio) { return ratio > 0.; }) && + std::abs(std::accumulate(ratios.begin(), ratios.end(), 0.) - 100.) < 1e-6; + if (!shares) + return Refusal{RefusalKind::Precondition, "bad_ratios", L("Give one ratio per filament, as percentages that add up to 100.")}; + return std::nullopt; +} + +Outcome add_mixed_filament(const AddMixedFilamentArgs& args) +{ + assert(wxThread::IsMain()); + Plater& plater = *wxGetApp().plater(); + if (std::optional refusal = filament_list_refusal(plater)) + return *refusal; + Sidebar& sidebar = plater.sidebar(); + // The filaments that mix are the physical ones, a selector each, each of the type the sidebar reads for them. + PresetBundle& presets = *wxGetApp().preset_bundle; + std::vector types; + for (std::size_t slot = 0; slot < sidebar.combos_filament().size(); ++slot) { + Preset* preset = slot < presets.filament_presets.size() ? presets.filaments.find_preset(presets.filament_presets[slot]) : + nullptr; + std::string display; + std::string type = preset != nullptr ? preset->config.get_filament_type(display) : std::string(); + types.push_back(type.empty() ? "PLA" : type); + } + if (std::optional refusal = mixed_filament_refusal(types, args.components, args.ratios)) + return *refusal; + const std::vector components(args.components.begin(), args.components.end()); + std::vector ratios; + for (double ratio : args.ratios) + ratios.push_back(int(std::lround(ratio))); + const PresetBundle& bundle = *wxGetApp().preset_bundle; + const std::size_t before = bundle.filament_presets.size(); + const int index = sidebar.ensure_mixed_filament(components, ratios); + if (index < 0 && before >= std::size_t(EnforcerBlockerType::ExtruderMax)) + return too_many_filaments(); + if (index < 0) + return Refusal{RefusalKind::Failed, "not_mixed", L("No mixed filament was added.")}; + MixedFilament mixed; + mixed.filament_slot = index + 1; + mixed.added = bundle.filament_presets.size() > before; + return mixed; +} + +// ---- Syncing the filament list from the AMS ---- + +AmsSyncState ams_sync_state() +{ + assert(wxThread::IsMain()); + AmsSyncState state; + DeviceManager* devices = wxGetApp().getDeviceManager(); + MachineObject* printer = devices != nullptr ? devices->get_selected_machine() : nullptr; + Plater* plater = wxGetApp().plater(); + if (printer == nullptr || plater == nullptr) + return state; + state.printer = true; + state.printer_name = printer->get_dev_name(); + state.selected_printer = into_u8(plater->get_selected_printer_name_in_combox()); + const auto& slots = wxGetApp().preset_bundle->filament_ams_list; + state.slots_listed = !slots.empty(); + state.printer_answered = printer->is_connected() && printer->m_push_count > 0; + for (const auto& slot : slots) + if (!slot.second.opt_string("filament_type", 0u).empty() || slot.second.opt_bool("filament_exist", 0u)) + state.filament_loaded = true; + state.filament_installed = printer->is_filament_installed(); + state.same_printer = plater->is_same_printer_for_connected_and_selected(/*popup_warning=*/false); + PartPlateList& plates = plater->get_partplate_list(); + for (int plate = 0; plate < plates.get_plate_count(); ++plate) + if (!plates.get_plate(plate)->get_objects_on_this_plate().empty()) + state.project_has_objects = true; + return state; +} + +std::optional ams_sync_refusal(const AmsSyncState& state, std::optional mode) +{ + if (!state.printer) + return Refusal{RefusalKind::Precondition, "no_printer", L("Connect a printer to synchronize the AMS filament list.")}; + if (!state.slots_listed) { + // Only an unreachable printer is not connected: one that has sent its status listed no slot. + if (state.printer_answered) + return Refusal{RefusalKind::Precondition, "no_filament_system", + // TRN %s is the connected printer's name. + L("%s is connected, but no filament system (AMS, CFS or other multi-material unit) was found on it, so " + "there are no filaments to synchronize."), + {state.printer_name}}; + return Refusal{RefusalKind::Precondition, "not_connected", + // TRN %s is the printer's name. + L("OrcaSlicer can't connect to %s. Please check if the printer is powered on and connected to the network."), + {state.selected_printer}}; + } + if (!state.filament_loaded) { + if (!state.filament_installed) + return Refusal{RefusalKind::Precondition, "no_filament", + L("There are no filaments on the printer. Please load the filaments on the printer first.")}; + return Refusal{RefusalKind::Precondition, "unknown_filaments", + L("The filaments on the printer are all unknown types. Please go to the printer screen or software device page " + "to set the filament type.")}; + } + if (!state.same_printer) + return Refusal{RefusalKind::Precondition, "other_printer", + // TRN Both %s are the printer selected in the printer selector. + L("The currently connected printer on the device page is not %s. Please switch to %s before syncing."), + {state.selected_printer, state.selected_printer}}; + if (mode == AmsSyncMode::Map && !state.project_has_objects) + return Refusal{RefusalKind::Precondition, "nothing_to_map", + L("Map takes a project with objects on a plate; with none, the filament list is overwritten.")}; + return std::nullopt; +} + +Outcome apply_ams_sync(const AmsSyncChoice& choice) +{ + assert(wxThread::IsMain()); + Plater& plater = *wxGetApp().plater(); + const Sidebar::AmsSyncApplied applied = plater.sidebar().apply_ams_sync(choice.direct_sync, choice.sync_maps, + choice.every_slot_changed, choice.unknowns_found); + if (applied.filaments == 0) { + if (choice.none_compatible) + choice.none_compatible(applied.detail); + return Refusal{RefusalKind::Failed, "no_compatible_filaments", L("There are no compatible filaments, and sync is not performed."), + {}, applied.unknowns}; + } + AmsSynced synced; + const PresetBundle& bundle = *wxGetApp().preset_bundle; + synced.presets = bundle.filament_presets; + if (const auto* colours = bundle.project_config.option("filament_colour")) + synced.colours = colours->values; + synced.unknowns = applied.unknowns; + return synced; +} + +Outcome sync_filaments_from_ams(AmsSyncMode mode) +{ + assert(wxThread::IsMain()); + DeviceManager* devices = wxGetApp().getDeviceManager(); + MachineObject* printer = devices != nullptr ? devices->get_selected_machine() : nullptr; + // The printer's slots, read again, as the sync reads them first. + if (printer != nullptr) + wxGetApp().plater()->sidebar().load_ams_list(printer); + if (std::optional refusal = ams_sync_refusal(ams_sync_state(), mode)) + return *refusal; + // Synchronize now, which the dialog answers wxID_YES: every slot counts as changed. + AmsSyncChoice choice; + if (mode == AmsSyncMode::Map) { + std::vector mapped; + map_filaments_to_ams(printer, ams_sync_filaments(), mapped); + choice.direct_sync = false; + choice.sync_maps = ams_sync_maps(mapped); + } + return apply_ams_sync(choice); +} + }}} // namespace Slic3r::GUI::Ops diff --git a/src/slic3r/GUI/Operations/PresetOps.hpp b/src/slic3r/GUI/Operations/PresetOps.hpp index 4a4408a336..fe3e487ce4 100644 --- a/src/slic3r/GUI/Operations/PresetOps.hpp +++ b/src/slic3r/GUI/Operations/PresetOps.hpp @@ -2,12 +2,18 @@ #include "Outcome.hpp" +#include "libslic3r/PresetBundle.hpp" + #include +#include +#include #include #include #include +#include + namespace Slic3r { class PresetCollection; @@ -95,5 +101,123 @@ Outcome import_presets(const ImportPresetsArgs& args); // of an unknown preset name carries, for a caller that refuses one itself. std::vector similar_preset_names(const PresetCollection& presets, const std::string& name); +// Starts the sync of the user presets with the cloud account, as Sync Presets does; the sync goes on in the +// background. +// Refuses: not_signed_in. +Outcome sync_presets(); + +// ---- Filament slots: the + and - buttons above the filament list, a slot's Delete and Merge with, Add Mixed Filament ---- + +// Adds a physical filament slot after the physical ones, as the + button does: it takes the next colour and the last +// slot's preset, and the mixed filaments, with the objects on them, move up by one. Returns the new slot's number +// (1-based). +// Refuses: filaments_unavailable (a printer of another technology, or a G-code file shown in place of a project, which +// has a filament list of its own), one_filament_per_extruder (a printer whose filaments are its extruders, +// which shows no + button), too_many_filaments. +Outcome add_filament_slot(); + +// What keeps filament slot `slot` (1-based) of a project of `slots` slots, mixed ones among them, from being deleted, or +// merged into slot `merge_into`, or none: the only slot (last_filament_slot), a slot the project lacks (no_such_slot), +// and a merge into the slot itself (merge_into_itself). +std::optional filament_delete_refusal(int slots, int slot, std::optional merge_into); + +struct DeleteFilamentArgs +{ + std::optional filament_slot; // 1-based; none: the last physical slot, as the - button + std::optional merge_into; // 1-based; none: the objects on the slot take the first filament, as its Delete does +}; +struct DeletedFilament +{ + int filament_slot = 0; // the slot deleted, by its number before the delete + std::optional merged_into; // the slot its objects went to, by its number afterwards +}; +// Deletes a filament slot as its Delete menu item does, or, with merge_into, as its Merge with item does +// (Sidebar::change_filament()): the objects on it go to that slot. Not in the undo history, as neither item is. +// Refuses: filaments_unavailable, one_filament_per_extruder, the only physical slot (last_filament_slot), what +// filament_delete_refusal() gives, a mixed filament (mixed_filament_slot, which the mixed filament list +// deletes), a merge into a mixed filament that mixes the slot (mixed_uses_slot, with the question Merge with +// asks there), and a delete the sidebar did not make (not_deleted). +Outcome delete_filament_slot(const DeleteFilamentArgs& args); + +// What keeps a mixed filament of `components` (1-based filament slots) in `ratios` (percentages, one per component) +// from being made in a project whose filaments that mix, its physical ones, have the filament types `types` (slot 1 +// first), or none: a filament named twice (duplicate_component), which the Add Mixed Filament dialog's selectors +// never offer, fewer than two filaments (too_few_components), a slot that is not one of them (no_such_slot), +// filaments of different types (mixed_types), which the dialog does not take and the sidebar marks broken, and ratios +// that are not one per component, each above 0, adding up to 100 (bad_ratios). +std::optional mixed_filament_refusal(const std::vector& types, const std::vector& components, + const std::vector& ratios); + +struct AddMixedFilamentArgs +{ + std::vector components; // 1-based physical filament slots + std::vector ratios; // whole percentages, one per component, as the dialog sets them +}; +struct MixedFilament +{ + int filament_slot = 0; // 1-based + bool added = false; // false: the project mixes these filaments in these ratios already, in that slot +}; +// Adds a mixed filament as the Add Mixed Filament dialog's OK does for these filaments and ratios with no gradient +// (Sidebar::ensure_mixed_filament()), in a slot after every other; a mix the project has already is that slot. +// Refuses: filaments_unavailable, what mixed_filament_refusal() gives, too_many_filaments, and not_mixed where the +// sidebar made none. +Outcome add_mixed_filament(const AddMixedFilamentArgs& args); + +// ---- Syncing the filament list from the AMS: Synchronize Filament List from AMS and its dialog ---- + +// The sync dialog's two choices: map each of the project's filaments to a slot of the printer, or overwrite the filament +// list with the slots' filaments. +enum class AmsSyncMode { Map, Overwrite }; + +// What the sync reads of the printer selected on the Device tab and of the project. +struct AmsSyncState +{ + bool printer = false; // a printer is selected on the Device tab + std::string printer_name; // its name + std::string selected_printer; // the printer the printer selector shows + bool slots_listed = false; // the printer listed AMS or external spool slots + bool printer_answered = false; // it is online and has sent its status + bool filament_loaded = false; // a slot holds a filament of a known type + bool filament_installed = false; // the printer reports filament installed + bool same_printer = false; // it is of the selected printer's model, ready to sync + bool project_has_objects = false; // a plate has objects: the dialog then asks how to sync +}; +// The state of the printer selected on the Device tab, once Sidebar::load_ams_list() has read its slots. UI thread. +AmsSyncState ams_sync_state(); +// Why the filament list cannot be synced from the AMS, or none; `mode` none for the sync dialog's own run. +// Refuses: no_printer, no_filament_system (the printer answered with no slot), not_connected, no_filament, +// unknown_filaments (every filament of an unknown type), other_printer (not the selected printer's model), and +// nothing_to_map (Map for a project with no objects, where the dialog does not ask and overwrites the list). +std::optional ams_sync_refusal(const AmsSyncState& state, std::optional mode); + +// What the sync dialog's Synchronize now takes, as the sync applies it. +struct AmsSyncChoice +{ + bool direct_sync = true; // overwrite the list; else map by sync_maps + std::map sync_maps; // each project filament's slot, by its 0-based index + bool every_slot_changed = true; // each slot's filament counts as changed since the last sync + // Told, in the UI's language, the slots whose filament is unknown or incompatible and was mapped to a generic preset, + // before the list changes; none tells no one. + std::function unknowns_found; + // Told the slots' detail where no filament is compatible and nothing is synced; none tells no one. + std::function none_compatible; +}; +struct AmsSynced +{ + std::vector presets; // each filament slot's preset afterwards, slot 1 first + std::vector colours; // each slot's colour afterwards + std::vector unknowns; // the slots mapped to a generic preset: "tray(type) reason" +}; +// Syncs the filament list from the AMS list read last (Sidebar::apply_ams_sync()), as the sync dialog's Synchronize now +// does with `choice`. Not in the undo history. +// Refuses: no_compatible_filaments (with the slots), where nothing is synced. +Outcome apply_ams_sync(const AmsSyncChoice& choice); +// Syncs the filament list from the AMS of the printer selected on the Device tab with the dialog's choice `mode`, as +// Synchronize now does on what the dialog first shows: Map maps the project's filaments to the slots as the dialog's +// Mapping first does. Opens nothing. +// Refuses: what ams_sync_refusal() gives, and what apply_ams_sync() refuses. +Outcome sync_filaments_from_ams(AmsSyncMode mode); + }} // namespace GUI::Ops } // namespace Slic3r diff --git a/src/slic3r/GUI/Operations/ProjectOps.cpp b/src/slic3r/GUI/Operations/ProjectOps.cpp index 90b06f9acf..add68088bb 100644 --- a/src/slic3r/GUI/Operations/ProjectOps.cpp +++ b/src/slic3r/GUI/Operations/ProjectOps.cpp @@ -3,19 +3,26 @@ #include "Outcome.hpp" #include "PlateOps.hpp" +#include "slic3r/GUI/FileArchiveDialog.hpp" +#include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/GUI_ObjectList.hpp" +#include "slic3r/GUI/Gizmos/GLGizmosManager.hpp" #include "slic3r/GUI/I18N.hpp" +#include "slic3r/GUI/Jobs/Worker.hpp" #include "slic3r/GUI/PartPlate.hpp" #include "slic3r/GUI/Plater.hpp" +#include "slic3r/GUI/Selection.hpp" #include "libslic3r/Format/ProjectStrategy.hpp" #include "libslic3r/Model.hpp" #include "libslic3r/Utils.hpp" +#include "libslic3r/miniz_extension.hpp" #include #include +#include #include #include @@ -47,6 +54,8 @@ ProjectSummary summary(Plater& plater) return out; } +Refusal cut_keeps_instances() { return {RefusalKind::Precondition, "cut_object", L("A cut object keeps its number of instances.")}; } + } // namespace std::optional unsaved_changes_refusal(UnsavedChanges unsaved) @@ -56,20 +65,68 @@ std::optional unsaved_changes_refusal(UnsavedChanges unsaved) return Refusal{RefusalKind::Precondition, "unsaved_changes", L("The project has unsaved changes.")}; } +std::optional> zip_model_entries(const boost::filesystem::path& archive) +{ + mz_zip_archive zip; + mz_zip_zero_struct(&zip); + if (!open_zip_reader(&zip, archive.string())) + return std::nullopt; + std::vector names; + for (mz_uint i = 0, count = mz_zip_reader_get_num_files(&zip); i < count; ++i) { + mz_zip_archive_file_stat stat; + if (mz_zip_reader_file_stat(&zip, i, &stat)) + if (const boost::filesystem::path path(decode_archive_entry_path(&zip, stat)); is_archive_model(path)) + names.push_back(path.generic_string()); + } + close_zip_reader(&zip); + return names; +} + +std::optional zip_entries_refusal(const std::vector& in_archive, const std::vector& asked) +{ + for (const std::string& name : asked) + if (std::find(in_archive.begin(), in_archive.end(), name) == in_archive.end()) + // TRN %1% is a file's path inside a ZIP archive. + return Refusal{RefusalKind::Precondition, "no_such_entry", L("The archive holds no model file %1%."), {name}, in_archive}; + return std::nullopt; +} + Outcome import_models(const ImportModelsArgs& args) { Plater& plater = the_plater(); + // The files each archive gives, checked before anything is imported. + std::vector files; + ImportModelsResult result; + for (const boost::filesystem::path& path : args.paths) { + if (!boost::algorithm::iends_with(path.string(), ".zip")) { + files.push_back(path); + continue; + } + const std::optional> in_archive = zip_model_entries(path); + if (!in_archive) + // TRN %1% is a file's path. + return Refusal{RefusalKind::Failed, "unreadable_archive", L("%1% could not be read as a ZIP archive."), + {into_u8(from_path(path))}}; + if (args.entries) + if (std::optional refusal = zip_entries_refusal(*in_archive, *args.entries)) + return *refusal; + result.archives.push_back({path, args.entries ? *args.entries : *in_archive}); + } // The label File > Import gives its own undo step (Plater::add_file()). std::string label = "Import Objects"; for (size_t i = 0; i < args.paths.size(); ++i) label += (i == 0 ? ": " : ", ") + encode_path(args.paths[i].filename().string().c_str()); - const size_t before = plater.model().objects.size(); - Plater::TakeSnapshot snapshot(&plater, label); - const std::vector loaded = plater.load_files(args.paths, LoadStrategy::LoadModel); - if (loaded.empty() && plater.model().objects.size() == before) + const size_t before = plater.model().objects.size(); + Plater::TakeSnapshot snapshot(&plater, label); + if (!files.empty()) + plater.load_files(files, LoadStrategy::LoadModel); + for (const ImportedArchive& archive : result.archives) + plater.import_zip_archive(archive.path, &archive.entries); + if (plater.model().objects.size() == before) return Refusal{RefusalKind::Failed, "nothing_loaded", L("Nothing was imported.")}; - return ImportModelsResult{plater.model().objects.size() - before}; + result.added = plater.model().objects.size() - before; + return result; } Outcome open_project(const OpenProjectArgs& args) @@ -81,7 +138,9 @@ Outcome open_project(const OpenProjectArgs& args) // and switches no tab, since the project that counts is the one about to load. if (plater.is_project_dirty()) plater.new_project(/*skip_confirm=*/true, /*silent=*/true); - plater.load_project(from_path(args.path)); + // The project with its settings, as opening one is asked for: the load-behaviour preference, which can load the + // geometry alone or ask how to open it, is a person's choice for the files they open themselves. + plater.load_project(from_path(args.path), ""); return summary(plater); } @@ -110,19 +169,29 @@ Outcome save_project_as(const SaveProjectAsArgs& args) Refusal project_not_saved() { return Refusal{RefusalKind::Failed, "project_not_saved", L("The project was not saved.")}; } -std::optional instance_count_refusal() +std::optional add_instances_refusal(const Model& model, int object) { - Plater& plater = the_plater(); - const int obj_idx = plater.get_selected_object_idx(); - if (obj_idx < 0) - return Refusal{RefusalKind::Precondition, "no_object_selected", L("Select an object first.")}; - const ModelObject* object = plater.model().objects[size_t(obj_idx)]; - if (const ObjectList* list = wxGetApp().obj_list(); list != nullptr && list->has_selected_cut_object()) - return Refusal{RefusalKind::Precondition, "cut_object", L("A cut object keeps its number of instances.")}; - if (std::any_of(object->instances.begin(), object->instances.end(), [](const ModelInstance* i) { return !i->printable; })) + const ModelObject& target = *model.objects[size_t(object)]; + if (target.is_cut()) + return cut_keeps_instances(); + if (std::any_of(target.instances.begin(), target.instances.end(), [](const ModelInstance* i) { return !i->printable; })) return Refusal{RefusalKind::Precondition, "unprintable_instance", L("Make every instance of the object printable first.")}; - if (!plater.can_increase_instances()) - return job_running(); + return std::nullopt; +} + +std::optional instance_count_refusal(const Model& model, int object, int count) +{ + const ModelObject& target = *model.objects[size_t(object)]; + const int had = int(target.instances.size()); + if (count < 1 && had == 1) + // TRN %1% is an object's name. + return Refusal{RefusalKind::Precondition, "last_instance", L("\"%1%\" has one instance, and an object keeps at least one."), {target.name}}; + if (count < 1 || count > 1000) + return bad_instance_count(); + if (count > had) + return add_instances_refusal(model, object); + if (count < had && target.is_cut()) + return cut_keeps_instances(); return std::nullopt; } @@ -131,16 +200,31 @@ Refusal bad_instance_count() return {RefusalKind::Precondition, "bad_instance_count", L("The number of instances is a whole number from 1 to 1000.")}; } +std::optional instance_change_blocked() +{ + Plater& plater = the_plater(); + if (!plater.get_ui_job_worker().is_idle()) + return job_running(); + if (plater.get_view3D_canvas3D()->get_gizmos_manager().is_in_editing_mode()) + return Refusal{RefusalKind::Precondition, "gizmo_editing", L("Close the gizmo that is editing the object first.")}; + return std::nullopt; +} + Outcome set_instance_count(const SetInstanceCountArgs& args) { Plater& plater = the_plater(); - if (args.count < 1 || args.count > 1000) - return bad_instance_count(); - if (std::optional refusal = instance_count_refusal()) + if (std::optional refusal = instance_count_refusal(plater.model(), args.object, args.count)) return *refusal; - const int obj_idx = plater.get_selected_object_idx(); + if (std::optional refusal = instance_change_blocked()) + return *refusal; + // The item reads the object selected in the Prepare view, an instance or a part of it as well. + Selection& selection = plater.get_view3D_canvas3D()->get_selection(); + if (selection.get_object_idx() != args.object) { + selection.add_object(unsigned(args.object), true); + wxGetApp().obj_list()->update_selections(); + } plater.set_number_of_copies(args.count); - return InstanceCount{obj_idx, plater.model().objects[size_t(obj_idx)]->instances.size()}; + return InstanceCount{args.object, plater.model().objects[size_t(args.object)]->instances.size()}; } }}} // namespace Slic3r::GUI::Ops diff --git a/src/slic3r/GUI/Operations/ProjectOps.hpp b/src/slic3r/GUI/Operations/ProjectOps.hpp index a16c2e51fd..647c355561 100644 --- a/src/slic3r/GUI/Operations/ProjectOps.hpp +++ b/src/slic3r/GUI/Operations/ProjectOps.hpp @@ -9,6 +9,10 @@ #include #include +namespace Slic3r { +class Model; +} + // The project as a whole: models imported into it, a project file opened, saved or started anew, and // its objects' instance counts. namespace Slic3r { namespace GUI { namespace Ops { @@ -28,19 +32,37 @@ struct ProjectSummary int plates = 0; }; +// The model files of the ZIP archive at `archive` that Import ZIP Archive's file list offers, each by its path in the +// archive with / between folders ("parts/cube.stl"); none when the file cannot be read as a ZIP archive. +std::optional> zip_model_entries(const boost::filesystem::path& archive); +// What keeps the files `asked` names from being taken from an archive whose model files are `in_archive`, or none: a +// name the archive has no model file of (no_such_entry), with the names it has. +std::optional zip_entries_refusal(const std::vector& in_archive, const std::vector& asked); + struct ImportModelsArgs { - std::vector paths; + std::vector paths; + std::optional> entries; // the files to take from the .zip among paths; none: each one's every model file +}; +// A ZIP archive an import took files from. +struct ImportedArchive +{ + boost::filesystem::path path; + std::vector entries; // the files taken, as zip_model_entries() names them }; struct ImportModelsResult { - size_t added = 0; // objects the import added + size_t added = 0; // objects the import added + std::vector archives; }; // Adds the files' geometry to the open project (LoadStrategy::LoadModel: a project file's settings -// are not loaded), as one "Import Objects: " undo step. The owner's import can open a dialog -// of its own (a STEP file's mesh options). -// Refuses: nothing_loaded. The undo step stays in the history then, as after an import from the -// File menu whose load fails. +// are not loaded), as one "Import Objects: " undo step. A .zip archive is taken apart as Import +// ZIP Archive does (Plater::import_zip_archive()): the files `entries` names, or every model file it +// holds, in place of its file list. The owner's import can open a dialog of its own (a STEP file's +// mesh options). +// Refuses: unreadable_archive and what zip_entries_refusal() gives, before anything is imported; +// nothing_loaded. The undo step stays in the history then, as after an import from the File menu +// whose load fails. Outcome import_models(const ImportModelsArgs& args); struct OpenProjectArgs @@ -48,9 +70,10 @@ struct OpenProjectArgs boost::filesystem::path path; UnsavedChanges unsaved = UnsavedChanges::Refuse; }; -// Replaces the open project with the file. Unsaved changes of the open project are dropped without a -// question when the caller says so; what Plater::load_project() asks beyond that (modified presets, -// how to open the 3mf) it still asks. +// Replaces the open project with the file, with the settings it was saved with: a project opens as File > Open +// Project with Load behavior set to load all, whatever the Preferences say. Unsaved changes of the open project are +// dropped without a question when the caller says so; what Plater::load_project() asks beyond that (modified +// presets) it still asks. // Refuses: unsaved_changes. Outcome open_project(const OpenProjectArgs& args); @@ -77,25 +100,34 @@ Outcome save_project_as(const SaveProjectAsArgs& args); // held before stays. Refusal project_not_saved(); -// What keeps the number of instances of the object selected in the Prepare view from being set -// (no_object_selected, cut_object, unprintable_instance, job_running), or none: the reasons the -// object menu's item is disabled, each with its own message. -std::optional instance_count_refusal(); +// What keeps instances from being added to object `object` of `model`, or none: the reasons of the object itself that +// disable Increase Instances and Set Number of Instances, each with its own message: a cut object (cut_object) and an +// instance that is not printable (unprintable_instance). +std::optional add_instances_refusal(const Model& model, int object); +// What keeps object `object` of `model` from having `count` instances, or none: no instance left for an object of one +// (last_instance), a count outside 1..1000 (bad_instance_count), what add_instances_refusal() gives for more instances +// than it has, and a cut object for fewer (cut_object). Fewer instances have no printable rule, as Decrease Instances +// has none. +std::optional instance_count_refusal(const Model& model, int object, int count); // The refusal for a number of instances outside 1..1000 (bad_instance_count). Refusal bad_instance_count(); +// What keeps any object's number of instances from changing now, or none: a running job (job_running) or a gizmo +// editing an object (gizmo_editing), which disable the instance items of the object menu and the toolbar. +std::optional instance_change_blocked(); struct SetInstanceCountArgs { - int count = 1; + int object = 0; // its index in the project + int count = 1; }; struct InstanceCount { - int object = 0; // the selected object's index + int object = 0; // the object's index size_t instances = 0; // the instances it has now }; -// Sets how many instances the object selected in the Prepare view has, as the object menu's item does -// once its dialog is answered. -// Refuses: bad_instance_count, and what instance_count_refusal() gives. +// Sets how many instances the object has, as the object menu's item does once its dialog is answered, with the +// object selected in the Prepare view, as the item reads it. +// Refuses: what instance_count_refusal() and instance_change_blocked() give, before the selection changes. Outcome set_instance_count(const SetInstanceCountArgs& args); }}} // namespace Slic3r::GUI::Ops diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index 3e6244a6d6..4eb6a7ee55 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -310,6 +310,9 @@ #include "FilamentMapDialog.hpp" #include "CloneDialog.hpp" #include "PurgeModeDialog.hpp" +#include "Operations/ObjectOps.hpp" +#include "Operations/Outcome.hpp" +#include "Operations/PresetOps.hpp" #include "DeviceCore/DevFilaSystem.h" #include "DeviceCore/DevManager.h" @@ -1948,6 +1951,42 @@ static bool is_skip_high_flow_printer(const std::string& printer) return invalidate_list.count(printer); }; +// The Flow combo's choices for extruder `index` of the printer `printer`: the nozzle flow types its variants name, and +// Hybrid where the extruder holds several nozzles, each with its position among nozzle_volume_type's labels. E3D High +// Flow is offered at 0.4 and 0.6 mm alone, High Flow neither at 0.2 mm nor on a printer that skips it. +static std::vector> flow_choices(const DynamicPrintConfig &printer, int index) +{ + std::vector> choices; + const auto *extruders = printer.option("extruder_type"); + const auto *extruder_variants = printer.option("extruder_variant_list"); + const auto *extruder_max_nozzle_count = printer.option("extruder_max_nozzle_count"); + if (extruders == nullptr || extruder_variants == nullptr || index < 0 || index >= int(extruder_variants->values.size()) || + index >= int(extruders->values.size())) + return choices; + const ConfigOptionDef *extruders_def = printer.def()->get("extruder_type"); + const ConfigOptionDef *nozzle_volumes_def = printer.def()->get("nozzle_volume_type"); + const std::string diameter = printer.opt_string("printer_variant"); + const std::string printer_model = printer.opt_string("printer_model"); + const std::string type = extruders_def->enum_labels[extruders->values[index]]; + for (size_t i = 0; i < nozzle_volumes_def->enum_labels.size(); ++i) { + const auto cur_volume_type = NozzleVolumeType(nozzle_volumes_def->enum_keys_map->at(nozzle_volumes_def->enum_values[i])); + // get_at falls back to the first entry when a profile defines no per-extruder value, + // so extruders without an explicit sub-nozzle count never offer Hybrid. A nullable-int + // nil is INT_MAX (> 1) and would otherwise falsely pass the gate, so exclude it too. + if (boost::algorithm::contains(extruder_variants->values[index], type + " " + nozzle_volumes_def->enum_labels[i]) || + (extruder_max_nozzle_count != nullptr && extruder_max_nozzle_count->get_at(index) > 1 && + extruder_max_nozzle_count->get_at(index) != ConfigOptionIntsNullable::nil_value() && cur_volume_type == nvtHybrid)) { + // Defensive: profiles restrict E3D to 0.4 / 0.6; keep it out elsewhere. + if (cur_volume_type == NozzleVolumeType::nvtE3DHighFlow && diameter != "0.4" && diameter != "0.6") + continue; + if (cur_volume_type == NozzleVolumeType::nvtHighFlow && (diameter == "0.2" || is_skip_high_flow_printer(printer_model))) + continue; + choices.emplace_back(cur_volume_type, i); + } + } + return choices; +} + // ---- Multi-nozzle sync helpers ---------------------------- // Serialize/deserialize the machine nozzle config + chosen NozzleOption for the app_config // "sync_extruder" reuse cache, and Sidebar::priv::get_nozzle_options (the nozzle picker). @@ -4006,7 +4045,6 @@ void Sidebar::update_presets(Preset::Type preset_type) // Update dual extrudes auto* nozzle_diameter = dynamic_cast(printer_preset.config.option("nozzle_diameter")); auto extruder_variants = printer_preset.config.option("extruder_variant_list"); - std::string printer_model = printer_preset.config.option("printer_model")->value; bool isBBL = preset_bundle.is_bbl_vendor(); bool is_dual_extruder = extruder_variants->size() == 2; @@ -4025,15 +4063,14 @@ void Sidebar::update_presets(Preset::Type preset_type) p->right_extruder->SetTitle(_L(right_title)); } - auto extruders_def = printer_preset.config.def()->get("extruder_type"); auto extruders = printer_preset.config.option("extruder_type"); auto nozzle_volumes_def = wxGetApp().preset_bundle->project_config.def()->get("nozzle_volume_type"); auto nozzle_volumes = wxGetApp().preset_bundle->project_config.option("nozzle_volume_type"); auto diameters = wxGetApp().preset_bundle->printers.diameters_of_selected_printer(); auto diameter = printer_preset.config.opt_string("printer_variant"); - auto extruder_max_nozzle_count = printer_preset.config.option("extruder_max_nozzle_count"); const bool has_flow_variant = preset_bundle.support_different_extruders(); - auto update_extruder_variant = [printer_model, extruders_def, extruders, nozzle_volumes_def, nozzle_volumes, extruder_variants,diameter,extruder_max_nozzle_count,has_flow_variant](ExtruderGroup & extruder, size_t row, int index) { + auto update_extruder_variant = [&printer_preset, extruders, nozzle_volumes_def, nozzle_volumes, extruder_variants, + has_flow_variant](ExtruderGroup &extruder, size_t row, int index) { ComboBox *combo_flow = extruder.rows[row].flow; combo_flow->Clear(); // A profile may leave the per-extruder lists shorter than the nozzle count (they are @@ -4043,28 +4080,13 @@ void Sidebar::update_presets(Preset::Type preset_type) combo_flow->Hide(); return; } - auto type = extruders_def->enum_labels[extruders->values[index]]; int select = -1; - for (size_t i = 0; i < nozzle_volumes_def->enum_labels.size(); ++i) { - // get_at falls back to the first entry when a profile defines no per-extruder value, - // so extruders without an explicit sub-nozzle count never offer Hybrid. A nullable-int - // nil is INT_MAX (> 1) and would otherwise falsely pass the gate, so exclude it too. - if (boost::algorithm::contains(extruder_variants->values[index], type + " " + nozzle_volumes_def->enum_labels[i]) || - (extruder_max_nozzle_count->get_at(index) > 1 && extruder_max_nozzle_count->get_at(index) != ConfigOptionIntsNullable::nil_value() && - nozzle_volumes_def->enum_keys_map->at(nozzle_volumes_def->enum_values[i]) == nvtHybrid)) { - auto cur_volume_type = nozzle_volumes_def->enum_keys_map->at(nozzle_volumes_def->enum_values[i]); - // Defensive: profiles restrict E3D to 0.4 / 0.6; keep it out elsewhere. - if (cur_volume_type == NozzleVolumeType::nvtE3DHighFlow && diameter != "0.4" && diameter != "0.6") - continue; - if (cur_volume_type == NozzleVolumeType::nvtHighFlow && (diameter == "0.2" || - is_skip_high_flow_printer(printer_model))) - continue; - // The client data is the enum value, not the label position: E3D High Flow is 5 - // but sits at position 4, and a position would write an invalid type. - if (nozzle_volumes->values[index] == cur_volume_type) - select = combo_flow->GetCount(); - combo_flow->Append(_L(nozzle_volumes_def->enum_labels[i]), {}, (void*)(intptr_t)cur_volume_type); - } + for (const auto &[cur_volume_type, label] : flow_choices(printer_preset.config, index)) { + // The client data is the enum value, not the label position: E3D High Flow is 5 + // but sits at position 4, and a position would write an invalid type. + if (nozzle_volumes->values[index] == cur_volume_type) + select = combo_flow->GetCount(); + combo_flow->Append(_L(nozzle_volumes_def->enum_labels[label]), {}, (void*)(intptr_t)cur_volume_type); } if (select == -1) select = combo_flow->GetCount() - 1; @@ -5904,36 +5926,30 @@ void Sidebar::delete_filament(size_t filament_id, int replace_filament_id) { filament_list->Scroll(-1, INT_MAX); // ORCA scroll to end of list on changes to inform user about filament count } +bool Sidebar::merge_removes_component(size_t from_id, size_t to_id) const +{ + const auto& pb = *wxGetApp().preset_bundle; + if (pb.is_mixed_filament(from_id) || !pb.is_mixed_filament(to_id)) + return false; + const auto* comp_opt = pb.project_config.option("filament_mixed_components"); + if (!comp_opt || to_id >= comp_opt->values.size()) + return false; + const std::vector comps = Slic3r::parse_mixed_components(comp_opt->values[to_id]); + return std::find(comps.begin(), comps.end(), (unsigned int) from_id + 1) != comps.end(); +} + void Sidebar::change_filament(size_t from_id, size_t to_id) { // Merging a physical filament into a mixed one that lists it as a component would delete // the very filament the mix depends on, leaving it broken. Warn before doing so. - auto& pb = *wxGetApp().preset_bundle; - bool from_is_physical = !pb.is_mixed_filament(from_id); - bool to_is_mixed = pb.is_mixed_filament(to_id); - - if (from_is_physical && to_is_mixed) { - auto* comp_opt = pb.project_config.option("filament_mixed_components"); - if (comp_opt && to_id < comp_opt->values.size()) { - auto comps = Slic3r::parse_mixed_components(comp_opt->values[to_id]); - unsigned int from_1based = (unsigned int)from_id + 1; - bool target_uses_source = false; - for (unsigned int c : comps) { - if (c == from_1based) { - target_uses_source = true; - break; - } - } - if (target_uses_source) { - int ret = wxMessageBox( - _L("The target mixed filament uses this physical filament as a component. " - "Merging will remove this physical filament and may invalidate the mixed filament. Continue?"), - _L("Warning"), - wxOK | wxCANCEL | wxICON_WARNING); - if (ret != wxOK) - return; - } - } + if (merge_removes_component(from_id, to_id)) { + int ret = wxMessageBox( + _L("The target mixed filament uses this physical filament as a component. " + "Merging will remove this physical filament and may invalidate the mixed filament. Continue?"), + _L("Warning"), + wxOK | wxCANCEL | wxICON_WARNING); + if (ret != wxOK) + return; } delete_filament(from_id, int(to_id)); @@ -6192,6 +6208,69 @@ void Sidebar::reset_fila_switch() p->update_extruder_separator_icon(false, false); } +// The Flow combo of extruder `extruder` (0 base), as Sidebar::update_presets() fills them: a row per extruder of a card +// with several rows, the left and right cards of a printer with two extruder variants, else the one card's row. +static ComboBox *flow_combo(const ExtruderGroup &single, const ExtruderGroup &left, const ExtruderGroup &right, int extruder) +{ + if (extruder < 0) + return nullptr; + if (single.NozzleRowCount() > 1) + return size_t(extruder) < single.NozzleRowCount() ? single.rows[extruder].flow : nullptr; + const DynamicPrintConfig &printer = wxGetApp().preset_bundle->printers.get_edited_preset().config; + const auto *variants = printer.option("extruder_variant_list"); + if (variants != nullptr && variants->size() == 2) + return extruder == 0 ? left.rows[0].flow : extruder == 1 ? right.rows[0].flow : nullptr; + return extruder == 0 ? single.rows[0].flow : nullptr; +} + +std::vector Sidebar::nozzle_volume_types(int extruder) const +{ + std::vector types; + ComboBox *combo = flow_combo(*p->single_extruder, *p->left_extruder, *p->right_extruder, extruder); + // A person picks from the combo while it and the card it is on are shown. + if (combo != nullptr && combo->IsShown() && combo->GetParent()->IsShown()) + for (unsigned int i = 0; i < combo->GetCount(); ++i) + types.push_back(NozzleVolumeType(intptr_t(combo->GetClientData(i)))); + return types; +} + +std::vector Sidebar::nozzle_volume_types(const DynamicPrintConfig &printer, int extruder) +{ + // The combo is shown for a printer with flow variants (PresetBundle::support_different_extruders()). + std::vector types; + int extruders = 0; + if (printer.support_different_extruders(extruders)) + for (const auto &choice : flow_choices(printer, extruder)) + types.push_back(choice.first); + return types; +} + +void Sidebar::pick_nozzle_volume_type(int extruder, NozzleVolumeType type) +{ + ComboBox *combo = flow_combo(*p->single_extruder, *p->left_extruder, *p->right_extruder, extruder); + if (combo == nullptr) + return; + for (unsigned int i = 0; i < combo->GetCount(); ++i) + if (NozzleVolumeType(intptr_t(combo->GetClientData(i))) == type) { + // What the combo's drop-down does with a pick. + combo->SetSelection(int(i)); + wxCommandEvent evt(wxEVT_COMBOBOX, combo->GetId()); + evt.SetEventObject(combo); + evt.SetInt(int(i)); + combo->GetEventHandler()->ProcessEvent(evt); + return; + } +} + +bool Sidebar::pick_nozzle_variant(const std::string &variant) +{ + // As the variant combo's pick does, without its deferral: the combo is rebuilt by the preset switch. + p->is_switching_diameter = true; + const bool switched = p->switch_diameter_to(from_u8(variant)); + p->is_switching_diameter = false; + return switched; +} + bool Sidebar::need_auto_sync_extruder_list_after_connect_priner(const MachineObject *obj) { if(!obj) @@ -6316,54 +6395,30 @@ void Sidebar::load_ams_list(MachineObject* obj) p->combo_printer->update(); } -void Sidebar::sync_ams_list(bool is_from_big_sync_btn) +std::optional Sidebar::sync_ams_list(bool is_from_big_sync_btn) { wxBusyCursor cursor; // Force load ams list - auto obj = wxGetApp().getDeviceManager()->get_selected_machine(); - if (!obj) - return; - GUI::wxGetApp().sidebar().load_ams_list(obj); - - auto & list = wxGetApp().preset_bundle->filament_ams_list; - if (list.empty()) { - // Only an unreachable printer is "not connected". One that is online and has - // delivered at least one status push answered the request without listing any - // filament slot, and the message then names the machine that answered. - if (obj->is_connected() && obj->m_push_count > 0) { + DeviceManager* devices = wxGetApp().getDeviceManager(); + auto obj = devices != nullptr ? devices->get_selected_machine() : nullptr; + if (obj) + GUI::wxGetApp().sidebar().load_ams_list(obj); + if (std::optional refusal = Ops::ams_sync_refusal(Ops::ams_sync_state(), std::nullopt)) { + // The warning that says why, with its way to the Device page. With no printer there is none. + const std::string code = refusal->code; + if (code == "no_filament_system") p->plater->pop_warning_and_go_to_device_page(from_u8(obj->get_dev_name()), Plater::PrinterWarningType::NO_FILAMENT_SYSTEM, _L("Sync printer information")); - return; - } - auto printer_name = p->plater->get_selected_printer_name_in_combox(); - p->plater->pop_warning_and_go_to_device_page(printer_name, Plater::PrinterWarningType::NOT_CONNECTED, _L("Sync printer information")); - return; - } - bool exist_at_list_one_filament =false; - for (auto &cur : list) { - auto temp_config = cur.second; - auto filament_type = temp_config.opt_string("filament_type", 0u); - auto filament_color = temp_config.opt_string("filament_colour", 0u); - if (!filament_type.empty() || temp_config.opt_bool("filament_exist", 0u)) { - exist_at_list_one_filament = true; - break; - } - } - if (!exist_at_list_one_filament) { - if (!obj->is_filament_installed()) { + else if (code == "not_connected") + p->plater->pop_warning_and_go_to_device_page(p->plater->get_selected_printer_name_in_combox(), + Plater::PrinterWarningType::NOT_CONNECTED, _L("Sync printer information")); + else if (code == "no_filament") p->plater->pop_warning_and_go_to_device_page("", Plater::PrinterWarningType::UNINSTALL_FILAMENT, _L("Sync printer information")); - return; - } - p->plater->pop_warning_and_go_to_device_page("", Plater::PrinterWarningType::EMPTY_FILAMENT, _L("Sync printer information")); - return; - } - if (!wxGetApp().plater()->is_same_printer_for_connected_and_selected()) { - return; - } - std::string ams_filament_ids = wxGetApp().app_config->get("ams_filament_ids", p->ams_list_device); - std::vector list2; - if (!ams_filament_ids.empty()) { - boost::algorithm::split(list2, ams_filament_ids, boost::algorithm::is_any_of(",")); + else if (code == "unknown_filaments") + p->plater->pop_warning_and_go_to_device_page("", Plater::PrinterWarningType::EMPTY_FILAMENT, _L("Sync printer information")); + else if (code == "other_printer") + wxGetApp().plater()->is_same_printer_for_connected_and_selected(/*popup_warning=*/true); + return refusal; } wxGetApp().plater()->update_all_plate_thumbnails(true);//preview thumbnail for sync_dlg SyncAmsInfoDialog::SyncInfo temp_info; @@ -6388,18 +6443,53 @@ void Sidebar::sync_ams_list(bool is_from_big_sync_btn) dlg_res =(int) wxID_YES; } if (dlg_res == wxID_CANCEL) - return; + return std::nullopt; auto sync_result = m_sync_dlg->get_result(); if (!sync_result.is_same_printer) { BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << "check error: sync_result.is_same_printer value is false"; - return; + return std::nullopt; + } + Ops::AmsSyncChoice choice; + choice.direct_sync = sync_result.direct_sync; + choice.sync_maps = sync_result.sync_maps; + choice.every_slot_changed = dlg_res == wxID_YES; + choice.unknowns_found = [this](const wxString &detail) { + MessageDialog dlg(this, + _L("There are some unknown or incompatible filaments mapped to generic preset.\nPlease update Orca Slicer or restart " + "Orca Slicer to check if there is an update to system presets.") + detail, + _L("Sync filaments with AMS"), wxOK); + dlg.ShowModal(); + }; + choice.none_compatible = [this](const wxString &detail) { + MessageDialog dlg(this, + _L("There are no compatible filaments, and sync is not performed.") + detail, + _L("Sync filaments with AMS"), wxOK); + dlg.ShowModal(); + }; + if (const Ops::Outcome synced = Ops::apply_ams_sync(choice); !synced) + return synced.refusal(); + BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << "begin pop_finsish_sync_ams_dialog"; + pop_finsish_sync_ams_dialog(); + BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << "finish pop_finsish_sync_ams_dialog"; + return std::nullopt; +} + +Sidebar::AmsSyncApplied Sidebar::apply_ams_sync(bool direct_sync, std::map sync_maps, bool every_slot_changed, + const std::function &unknowns_found) +{ + AmsSyncApplied applied; + auto & list = wxGetApp().preset_bundle->filament_ams_list; + std::string ams_filament_ids = wxGetApp().app_config->get("ams_filament_ids", p->ams_list_device); + std::vector list2; + if (!ams_filament_ids.empty()) { + boost::algorithm::split(list2, ams_filament_ids, boost::algorithm::is_any_of(",")); } list2.resize(list.size()); auto iter = list.begin(); for (int i = 0; i < list.size(); ++i, ++iter) { auto & ams = iter->second; auto filament_id = ams.opt_string("filament_id", 0u); - ams.set_key_value("filament_changed", new ConfigOptionBool{dlg_res == wxID_YES || list2[i] != filament_id}); + ams.set_key_value("filament_changed", new ConfigOptionBool{every_slot_changed || list2[i] != filament_id}); list2[i] = filament_id; } @@ -6416,20 +6506,17 @@ void Sidebar::sync_ams_list(bool is_from_big_sync_btn) std::vector> unknowns; auto enable_append = wxGetApp().app_config->get_bool("enable_append_color_by_sync_ams"); auto sync_color_only = wxGetApp().app_config->get("sync_ams_filament_mode") == "1"; - auto n = wxGetApp().preset_bundle->sync_ams_list(unknowns, !sync_result.direct_sync, sync_result.sync_maps, enable_append, merge_info, sync_color_only); - wxString detail; + auto n = wxGetApp().preset_bundle->sync_ams_list(unknowns, !direct_sync, sync_maps, enable_append, merge_info, + sync_color_only); for (auto & uk : unknowns) { auto tray_name = uk.first->opt_string("tray_name", 0u); auto filament_type = uk.first->opt_string("filament_type", 0u); - detail += from_u8("\n- " + tray_name + "(" + filament_type + ") ") + _L(uk.second); - } - if (n == 0) { - MessageDialog dlg(this, - _L("There are no compatible filaments, and sync is not performed.") + detail, - _L("Sync filaments with AMS"), wxOK); - dlg.ShowModal(); - return; + applied.detail += from_u8("\n- " + tray_name + "(" + filament_type + ") ") + _L(uk.second); + applied.unknowns.push_back(tray_name + "(" + filament_type + ") " + uk.second); } + applied.filaments = n; + if (n == 0) + return applied; // Replace unknown filament IDs with the resolved preset's filament_id auto &filaments = wxGetApp().preset_bundle->filaments; auto &filament_presets = wxGetApp().preset_bundle->filament_presets; @@ -6442,12 +6529,8 @@ void Sidebar::sync_ams_list(bool is_from_big_sync_btn) } ams_filament_ids = boost::algorithm::join(list2, ","); wxGetApp().app_config ->set("ams_filament_ids", p->ams_list_device, ams_filament_ids); - if (!unknowns.empty()) { - MessageDialog dlg(this, - _L("There are some unknown or incompatible filaments mapped to generic preset.\nPlease update Orca Slicer or restart Orca Slicer to check if there is an update to system presets.") + detail, - _L("Sync filaments with AMS"), wxOK); - dlg.ShowModal(); - } + if (!unknowns.empty() && unknowns_found) + unknowns_found(applied.detail); if (!sync_color_only) { BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << "on_filament_count_change"; wxGetApp().plater()->on_filament_count_change(n); @@ -6497,7 +6580,7 @@ void Sidebar::sync_ams_list(bool is_from_big_sync_btn) }; { // badge ams filament clear_combos_filament_badge(); - if (sync_result.direct_sync) { + if (direct_sync) { // A placeholder contributes a preserved project filament to the // overwrite result, but it is not AMS-sourced and must not get a // sync badge. Non-placeholder empty trays are omitted entirely. @@ -6535,7 +6618,7 @@ void Sidebar::sync_ams_list(bool is_from_big_sync_btn) } }; std::vector sync_ams_badges; - for (auto iter : sync_result.sync_maps) { + for (auto iter : sync_maps) { sync_ams_badges.push_back(false); if (iter.second.ams_id == "" || iter.second.slot_id == "") { continue; @@ -6564,7 +6647,7 @@ void Sidebar::sync_ams_list(bool is_from_big_sync_btn) } } } else { - for (auto iter : sync_result.sync_maps) { + for (auto iter : sync_maps) { if (iter.second.ams_id == "" || iter.second.slot_id == "") { continue; } @@ -6575,9 +6658,7 @@ void Sidebar::sync_ams_list(bool is_from_big_sync_btn) } } } - BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << "begin pop_finsish_sync_ams_dialog"; - pop_finsish_sync_ams_dialog(); - BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << "finish pop_finsish_sync_ams_dialog"; + return applied; } @@ -7568,7 +7649,9 @@ struct Plater::priv void drop_selection(); void mirror(Axis axis); void split_object(bool auto_drop = true); - void split_object(int obj_idx, bool auto_drop = true); + // Plater::split_object(obj_idx, ask, keep_z), whose split loads the objects with `auto_drop` unless the question + // answers otherwise. + SplitResult split_object(int obj_idx, bool auto_drop = true, bool ask = true, std::optional keep_z = std::nullopt); void split_volume(); void scale_selection_to_fit_print_volume(); @@ -7654,8 +7737,15 @@ struct Plater::priv bool export_gcode(fs::path output_path, bool output_path_on_removable_media, bool tracked = false); void export_gcode(fs::path output_path, bool output_path_on_removable_media, PrintHostJob upload_job); - void reload_from_disk(); - bool replace_volume_with_stl(int object_idx, int volume_idx, const fs::path& new_path, const std::string& snapshot = ""); + // Reload from disk of `parts`, else of the selection's parts. With `ask`, a file that is gone is asked for, a part its + // file has none for is told in a message box, and a file that cannot be read ends the reload where it is; without it + // nothing is asked or told, and the reload goes on to update the scene. + ReloadResult reload_from_disk(const std::vector>* parts = nullptr, bool ask = true); + // With `tell`, a file of several parts is told in a message box. + ReplaceResult replace_volume_with_stl(int object_idx, int volume_idx, const fs::path& new_path, const std::string& snapshot = "", + bool tell = true); + // replace_volume_with_stl() in its own "Replace with 3D file" undo step, then the 3D scene and its printable states. + ReplaceResult replace_part(int object_idx, int volume_idx, const fs::path& new_path, bool tell); void replace_with_stl(); void replace_all_with_stl(); void reload_all_from_disk(); @@ -11329,10 +11419,11 @@ void Plater::priv::split_object(bool auto_drop /* = true */) } // split provided object into multiple objects by its volumes -void Plater::priv::split_object(int obj_idx, bool auto_drop /* = true */) +Plater::SplitResult Plater::priv::split_object(int obj_idx, bool auto_drop /* = true */, bool ask /* = true */, + std::optional keep_z /* = std::nullopt */) { if (obj_idx == -1) - return; + return SplitResult::OnePiece; // we clone model object because split_object() adds the split volumes // into the same model object, thus causing duplicates when we call load_model_objects() @@ -11342,9 +11433,12 @@ void Plater::priv::split_object(int obj_idx, bool auto_drop /* = true */) wxBusyCursor wait; ModelObjectPtrs new_objects; current_model_object->split(&new_objects, wxGetApp().app_config->get_bool("keep_painting")); - if (new_objects.size() == 1) + if (new_objects.size() == 1) { // #ysFIXME use notification - Slic3r::GUI::warning_catcher(q, _L("The selected object couldn't be split.")); + if (ask) + Slic3r::GUI::warning_catcher(q, _L("The selected object couldn't be split.")); + return SplitResult::OnePiece; + } else { // BBS no solid parts removed @@ -11354,8 +11448,6 @@ void Plater::priv::split_object(int obj_idx, bool auto_drop /* = true */) // NotificationManager::NotificationLevel::PrintInfoNotificationLevel, // _u8L("All non-solid parts (modifiers) were deleted")); - Plater::TakeSnapshot snapshot(q, _u8L("Split to Objects")); - auto is_atleast_one_floating = [new_objects]() { for (ModelObject* new_object : new_objects) { if (new_object->get_instance_min_z(0) >= SINKING_MIN_Z_THRESHOLD) @@ -11363,15 +11455,25 @@ void Plater::priv::split_object(int obj_idx, bool auto_drop /* = true */) } return false; }; + // The question is answered, or asked, before anything changes. bool split_auto_drop = auto_drop; if (current_model_object->auto_drop && is_atleast_one_floating()) { - MessageDialog dlg(q, _L("Disable Auto-Drop to preserve Z positioning?\n"), - _L("Object with floating parts was detected"), wxICON_QUESTION | wxYES_NO); + if (keep_z) { + if (*keep_z) + split_auto_drop = false; + } else if (!ask) { + return SplitResult::Unanswered; + } else { + MessageDialog dlg(q, _L("Disable Auto-Drop to preserve Z positioning?\n"), + _L("Object with floating parts was detected"), wxICON_QUESTION | wxYES_NO); - if (dlg.ShowModal() == wxID_YES) - split_auto_drop = false; + if (dlg.ShowModal() == wxID_YES) + split_auto_drop = false; + } } + Plater::TakeSnapshot snapshot(q, _u8L("Split to Objects")); + remove(obj_idx); // load all model objects at once, otherwise the plate would be rearranged after each one @@ -11386,6 +11488,7 @@ void Plater::priv::split_object(int obj_idx, bool auto_drop /* = true */) { get_selection().add_object((unsigned int)idx, false); } + return SplitResult::Split; } } @@ -12165,7 +12268,8 @@ void Plater::priv::update_sla_scene() this->update_restart_background_process(true, true); } -bool Plater::priv::replace_volume_with_stl(int object_idx, int volume_idx, const fs::path& new_path, const std::string& snapshot) +Plater::ReplaceResult Plater::priv::replace_volume_with_stl(int object_idx, int volume_idx, const fs::path& new_path, + const std::string& snapshot, bool tell) { const std::string path = new_path.string(); wxBusyCursor wait; @@ -12200,7 +12304,7 @@ bool Plater::priv::replace_volume_with_stl(int object_idx, int volume_idx, const }; new_model = Model::read_from_step(path, LoadStrategy::AddDefaultInstances | LoadStrategy::LoadModel, nullptr, nullptr, callback, linear, angle, split_compound); - if (is_user_cancel) return false; + if (is_user_cancel) return ReplaceResult::Cancelled; } else { new_model = Model::read_from_file(path, nullptr, nullptr, LoadStrategy::AddDefaultInstances | LoadStrategy::LoadModel); } @@ -12211,13 +12315,18 @@ bool Plater::priv::replace_volume_with_stl(int object_idx, int volume_idx, const } catch (std::exception&) { // error while loading - return false; + return ReplaceResult::Unreadable; } - if (new_model.objects.size() > 1 || new_model.objects.front()->volumes.size() > 1) { - MessageDialog dlg(q, _L("Unable to replace with more than one volume"), _L("Error during replacement"), wxOK | wxOK_DEFAULT | wxICON_WARNING); - dlg.ShowModal(); - return false; + // A file that loaded no object has no mesh to replace the part with. + if (new_model.objects.empty()) + return ReplaceResult::Unreadable; + if (const std::optional refusal = Ops::replacement_refusal(new_model)) { + if (tell) { + MessageDialog dlg(q, refusal->translated(), _L("Error during replacement"), wxOK | wxOK_DEFAULT | wxICON_WARNING); + dlg.ShowModal(); + } + return ReplaceResult::SeveralParts; } wxBusyInfo info(_L("Replace from:") + " " + from_u8(path), q->get_current_canvas3D()->get_wxglcanvas()); @@ -12273,7 +12382,23 @@ bool Plater::priv::replace_volume_with_stl(int object_idx, int volume_idx, const sla::reproject_points_and_holes(old_model_object); - return true; + return ReplaceResult::Replaced; +} + +Plater::ReplaceResult Plater::priv::replace_part(int object_idx, int volume_idx, const fs::path& new_path, bool tell) +{ + const ReplaceResult result = replace_volume_with_stl(object_idx, volume_idx, new_path, _u8L("Replace with 3D file"), tell); + if (result != ReplaceResult::Replaced) + return result; + + // update 3D scene + update(); + + // new GLVolumes have been created at this point, so update their printable state + for (size_t i = 0; i < model.objects.size(); ++i) { + view3D->get_canvas3d()->update_instance_printable_state_for_object(i); + } + return result; } void Plater::priv::replace_with_stl() @@ -12312,16 +12437,7 @@ void Plater::priv::replace_with_stl() return; } - if (!replace_volume_with_stl(object_idx, volume_idx, out_path, _u8L("Replace with 3D file"))) - return; - - // update 3D scene - update(); - - // new GLVolumes have been created at this point, so update their printable state - for (size_t i = 0; i < model.objects.size(); ++i) { - view3D->get_canvas3d()->update_instance_printable_state_for_object(i); - } + replace_part(object_idx, volume_idx, out_path, true); } void Plater::priv::replace_all_with_stl() @@ -12429,7 +12545,7 @@ void Plater::priv::replace_all_with_stl() BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << " replacing volume : " << input_path << " with " << new_path; - if (!replace_volume_with_stl(object_idx, volume_idx, new_path, _u8L("Replace with 3D file"))) { + if (replace_volume_with_stl(object_idx, volume_idx, new_path, _u8L("Replace with 3D file")) != ReplaceResult::Replaced) { status += wxString::Format(_L("✖ Skipped %s: failed to replace.\n"), from_u8(volume_name)); BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << " cannot replace volume : failed to replace with " << new_path; continue; @@ -12462,8 +12578,7 @@ static std::vector> reloadable_volumes(const Model &model, c const ModelObject *obj = model.objects[o_idx]; const int v_idx = v.volume_idx(); if (0 <= v_idx && v_idx < int(obj->volumes.size())) { - const ModelVolume *vol = obj->volumes[v_idx]; - if (!vol->source.is_from_builtin_objects && !vol->source.input_file.empty() && !fs::path(vol->source.input_file).extension().string().empty()) + if (Ops::has_reload_source(*obj->volumes[v_idx])) ret.push_back({o_idx, v_idx}); } } @@ -12472,15 +12587,16 @@ static std::vector> reloadable_volumes(const Model &model, c } #endif // ENABLE_RELOAD_FROM_DISK_REWORK -void Plater::priv::reload_from_disk() +Plater::ReloadResult Plater::priv::reload_from_disk(const std::vector>* parts, bool ask) { + ReloadResult result; #if ENABLE_RELOAD_FROM_DISK_REWORK // collect selected reloadable ModelVolumes - std::vector> selected_volumes = reloadable_volumes(model, get_selection()); + std::vector> selected_volumes = parts != nullptr ? *parts : reloadable_volumes(model, get_selection()); BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << " entry, and reloadable volumes number is: " << selected_volumes.size(); // nothing to reload, return if (selected_volumes.empty()) - return; + return result; std::sort(selected_volumes.begin(), selected_volumes.end(), [](const std::pair &v1, const std::pair &v2) { return (v1.first < v2.first) || (v1.first == v2.first && v1.second < v2.second); @@ -12494,7 +12610,7 @@ void Plater::priv::reload_from_disk() const Selection& selection = get_selection(); if (selection.is_wipe_tower()) - return; + return result; // struct to hold selected ModelVolumes by their indices struct SelectedVolume @@ -12528,28 +12644,13 @@ void Plater::priv::reload_from_disk() std::vector missing_input_paths; #if ENABLE_RELOAD_FROM_DISK_REWORK std::vector> replace_paths; - for (auto [obj_idx, vol_idx] : selected_volumes) { - const ModelObject *object = model.objects[obj_idx]; - const ModelVolume *volume = object->volumes[vol_idx]; - if (fs::exists(volume->source.input_file)) - input_paths.push_back(volume->source.input_file); - else { - // searches the source in the same folder containing the object - bool found = false; - if (!object->input_file.empty()) { - fs::path object_path = fs::path(object->input_file).remove_filename(); - if (!object_path.empty()) { - object_path /= fs::path(volume->source.input_file).filename(); - if (fs::exists(object_path)) { - input_paths.push_back(object_path); - found = true; - } - } - } - if (!found) - missing_input_paths.push_back(volume->source.input_file); - } - } + // A part's source, else the file of its name in the folder of its object's file. + Ops::Targets selected; + selected.parts = selected_volumes; + const Ops::ReloadSources sources = Ops::reload_sources(model, selected, [](const std::string& path) { return fs::exists(path); }); + input_paths.assign(sources.paths.begin(), sources.paths.end()); + for (const auto& [obj_idx, vol_idx] : sources.missing) + missing_input_paths.push_back(model.objects[obj_idx]->volumes[vol_idx]->source.input_file); #else std::vector replace_paths; for (const SelectedVolume& v : selected_volumes) { @@ -12585,7 +12686,7 @@ void Plater::priv::reload_from_disk() std::sort(missing_input_paths.begin(), missing_input_paths.end()); missing_input_paths.erase(std::unique(missing_input_paths.begin(), missing_input_paths.end()), missing_input_paths.end()); - while (!missing_input_paths.empty()) { + while (ask && !missing_input_paths.empty()) { // ask user to select the missing file fs::path search = missing_input_paths.back(); wxString title = _L("Please select a file"); @@ -12595,7 +12696,7 @@ void Plater::priv::reload_from_disk() title += ":"; wxFileDialog dialog(q, title, "", from_u8(search.filename().string()), file_wildcards(FT_MODEL), wxFD_OPEN | wxFD_FILE_MUST_EXIST); if (dialog.ShowModal() != wxID_OK) - return; + return result; std::string sel_filename_path = dialog.GetPath().ToUTF8().data(); std::string sel_filename = fs::path(sel_filename_path).filename().string(); @@ -12686,8 +12787,12 @@ void Plater::priv::reload_from_disk() } catch (std::exception&) { - // error while loading - return; + // A file that cannot be read ends a person's reload here; a call's stops loading and brings the scene up to + // date with the parts it reloaded. + result.unreadable = path; + if (ask) + return result; + break; } #if ENABLE_RELOAD_FROM_DISK_REWORK @@ -12747,11 +12852,13 @@ void Plater::priv::reload_from_disk() if (new_object_idx < 0 || int(new_model.objects.size()) <= new_object_idx) { fail_list.push_back(from_u8(has_source ? old_volume->source.input_file : old_volume->name)); + result.unmatched.emplace_back(obj_idx, vol_idx); continue; } ModelObject *new_model_object = new_model.objects[new_object_idx]; if (int(new_model_object->volumes.size()) <= new_volume_idx) { fail_list.push_back(from_u8(has_source ? old_volume->source.input_file : old_volume->name)); + result.unmatched.emplace_back(obj_idx, vol_idx); continue; } @@ -12801,6 +12908,7 @@ void Plater::priv::reload_from_disk() // Fix warning icon in object list wxGetApp().obj_list()->update_item_error_icon(obj_idx, vol_idx); + result.reloaded.emplace_back(obj_idx, vol_idx); } } #else @@ -12881,7 +12989,7 @@ void Plater::priv::reload_from_disk() for (auto [obj_idx, vol_idx] : selected_volumes) { if (boost::algorithm::iequals(model.objects[obj_idx]->volumes[vol_idx]->source.input_file, src.string())) // When an error occurs, either the dest parsing error occurs, or the number of objects in the dest is greater than 1 and cannot be replaced, and cannot be replaced in this loop. - if (!replace_volume_with_stl(obj_idx, vol_idx, dest, "")) break; + if (replace_volume_with_stl(obj_idx, vol_idx, dest, "") != ReplaceResult::Replaced) break; } } #else @@ -12891,14 +12999,14 @@ void Plater::priv::reload_from_disk() ModelObject* old_model_object = model.objects[sel_v.object_idx]; ModelVolume* old_volume = old_model_object->volumes[sel_v.volume_idx]; bool has_source = !old_volume->source.input_file.empty() && boost::algorithm::iequals(fs::path(old_volume->source.input_file).filename().string(), fs::path(path).filename().string()); - if (!replace_volume_with_stl(sel_v.object_idx, sel_v.volume_idx, path, "")) { + if (replace_volume_with_stl(sel_v.object_idx, sel_v.volume_idx, path, "") != ReplaceResult::Replaced) { fail_list.push_back(from_u8(has_source ? old_volume->source.input_file : old_volume->name)); } } } #endif // ENABLE_RELOAD_FROM_DISK_REWORK - if (!fail_list.empty()) { + if (ask && !fail_list.empty()) { wxString message = _L("Unable to reload:") + "\n"; for (const wxString& s : fail_list) { message += s + "\n"; @@ -12916,6 +13024,14 @@ void Plater::priv::reload_from_disk() } BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << " finish."; + // A part that a later file of its name reloaded is not one its file had none for. + result.unmatched.erase(std::remove_if(result.unmatched.begin(), result.unmatched.end(), + [&result](const std::pair& part) { + return std::find(result.reloaded.begin(), result.reloaded.end(), part) != + result.reloaded.end(); + }), + result.unmatched.end()); + return result; } void Plater::priv::reload_all_from_disk() @@ -15016,12 +15132,12 @@ void Plater::priv::update_objects_position_when_select_preset(const std::functio update(); } -void Plater::orient() +void Plater::orient(std::optional> objects) { auto &w = get_ui_job_worker(); if (w.is_idle()) { p->take_snapshot(_u8L("Orient")); - replace_job(w, std::make_unique()); + replace_job(w, std::make_unique(std::move(objects))); } } @@ -18617,8 +18733,12 @@ void Plater::Calib_Cornering(const Calib_Params& params, bool skip_confirm) BuildVolume_Type Plater::get_build_volume_type() const { return p->bed.get_build_volume_type(); } -void Plater::import_zip_archive() +void Plater::import_zip_archive(const boost::filesystem::path& archive, const std::vector* entries) { + if (!archive.empty()) { + preview_zip_archive(archive, entries); + return; + } wxString input_file; wxGetApp().import_zip(this, input_file); if (input_file.empty()) @@ -18939,7 +19059,7 @@ std::vector Plater::load_files(const std::vector& input_files, return result; } -bool Plater::preview_zip_archive(const boost::filesystem::path& archive_path) +bool Plater::preview_zip_archive(const boost::filesystem::path& archive_path, const std::vector* entries) { //std::vector unzipped_paths; std::vector non_project_paths; @@ -18958,8 +19078,19 @@ bool Plater::preview_zip_archive(const boost::filesystem::path& archive_path) mz_zip_archive_file_stat stat; // selected_paths contains paths and its uncompressed size. The size is used to distinguish between files with same path. std::vector> selected_paths; - FileArchiveDialog dlg(static_cast(wxGetApp().mainframe), &archive, selected_paths); - if (dlg.ShowModal() == wxID_OK) + bool chosen = entries != nullptr; + if (chosen) { + // The files named take the place of the person's choice in the file list. + for (mz_uint i = 0; i < num_entries; ++i) + if (mz_zip_reader_file_stat(&archive, i, &stat)) + if (const fs::path path(Slic3r::decode_archive_entry_path(&archive, stat)); + std::find(entries->begin(), entries->end(), path.generic_string()) != entries->end()) + selected_paths.emplace_back(path, size_t(stat.m_uncomp_size)); + } else { + FileArchiveDialog dlg(static_cast(wxGetApp().mainframe), &archive, selected_paths); + chosen = dlg.ShowModal() == wxID_OK; + } + if (chosen) { std::string archive_path_string = archive_path.string(); archive_path_string = archive_path_string.substr(0, archive_path_string.size() - 4); @@ -19065,8 +19196,9 @@ bool Plater::preview_zip_archive(const boost::filesystem::path& archive_path) return false; } - // 1 project file and some models - behave like drag n drop of 3mf and then load models - if (project_paths.size() == 1) + // 1 project file and some models - behave like drag n drop of 3mf and then load models. Files named by `entries` are + // an import's: a project file among them gives its geometry, as the next branch loads it. + if (project_paths.size() == 1 && entries == nullptr) { wxArrayString aux; aux.Add(from_u8(project_paths.front().string())); @@ -19719,6 +19851,24 @@ bool Plater::is_sidebar_collapsed() const { return p->sidebar_layout.is_collapse void Plater::collapse_sidebar(bool collapse) { p->collapse_sidebar(collapse); } Sidebar::DockingState Plater::get_sidebar_docking_state() const { return p->get_sidebar_docking_state(); } +bool Plater::is_sidebar_floating() const { return p->m_aui_mgr.GetPane(p->sidebar).IsFloating(); } + +int Plater::sidebar_width() const +{ + // track_docked_size() keeps the docked width in best_size, which the pane docks at when it shows again. + const wxAuiPaneInfo& pane = p->m_aui_mgr.GetPane(p->sidebar); + return pane.IsShown() && pane.IsDocked() && pane.rect.GetWidth() > 0 ? pane.rect.GetWidth() : pane.best_size.GetWidth(); +} + +void Plater::set_sidebar_width(int width) { p->m_aui_mgr.set_docked_width(p->sidebar, width); } + +int Plater::default_sidebar_width() const +{ + wxAuiPaneInfo pane = p->m_aui_mgr.GetPane(p->sidebar); + p->m_aui_mgr.LoadPaneInfo(wxString::FromUTF8(aui_pane_layout_entry(p->m_default_window_layout.utf8_string(), "sidebar")), pane); + return pane.best_size.GetWidth(); +} + void Plater::reset_window_layout() { p->reset_window_layout(); @@ -20667,9 +20817,10 @@ TriangleMesh Plater::combine_mesh_fff(const ModelObject& mo, int instance_id, st // BBS export with/without boolean, however, stil merge mesh #define EXPORT_WITH_BOOLEAN 0 -void Plater::export_stl(bool extended, bool selection_only, bool multi_stls, FileType file_type, const wxString& output_path) +std::vector Plater::export_stl(bool extended, bool selection_only, bool multi_stls, FileType file_type, + const wxString& output_path, const std::vector& objects) { - if (p->model.objects.empty()) { return; } + if (p->model.objects.empty()) { return {}; } int quality = 0; @@ -20697,7 +20848,7 @@ void Plater::export_stl(bool extended, bool selection_only, bool multi_stls, Fil } else { path = p->get_export_file(file_type); } - if (path.empty()) { return; } + if (path.empty()) { return {}; } const std::string path_u8 = into_u8(path); wxBusyCursor wait; @@ -20706,15 +20857,15 @@ void Plater::export_stl(bool extended, bool selection_only, bool multi_stls, Fil #if EXPORT_WITH_BOOLEAN if (selection_only && (obj_idx == -1 || selection.is_wipe_tower())) - return; + return {}; #else // BBS support selecting multiple objects - if (selection_only && selection.is_wipe_tower()) return; + if (selection_only && selection.is_wipe_tower()) return {}; // BBS if (selection_only) { // only support selection single full object and mulitiple full object - if (!selection.is_single_full_object() && !selection.is_multiple_full_object()) return; + if (!selection.is_single_full_object() && !selection.is_multiple_full_object()) return {}; } // Following lambda generates a combined mesh for export with normals pointing outwards. @@ -20874,6 +21025,14 @@ void Plater::export_stl(bool extended, bool selection_only, bool multi_stls, Fil return path; }; + // The objects written when no selection decides: those named, else every one. + std::vector exported; + if (objects.empty()) + exported.assign(p->model.objects.begin(), p->model.objects.end()); + for (int object : objects) + exported.push_back(p->model.objects[size_t(object)]); + + std::vector written; TriangleMesh mesh; if (selection_only) { if (selection.is_single_full_object()) { @@ -20903,35 +21062,41 @@ void Plater::export_stl(bool extended, bool selection_only, bool multi_stls, Fil auto mesh = mesh_to_export(*object, i.second); mesh.translate(-object->origin_translation.cast()); + const std::string file = get_save_file(path_u8, object->name); switch (file_type) { - case FT_STL: Slic3r::store_stl(get_save_file(path_u8, object->name).c_str(), &mesh, true); break; - case FT_DRC: Slic3r::store_drc(get_save_file(path_u8, object->name).c_str(), &mesh, quality); break; + case FT_STL: Slic3r::store_stl(file.c_str(), &mesh, true); break; + case FT_DRC: Slic3r::store_drc(file.c_str(), &mesh, quality); break; } + written.push_back(file); } - return; + return written; } } else if (!multi_stls) { - for (const ModelObject* o : p->model.objects) { + for (const ModelObject* o : exported) { mesh.merge(mesh_to_export(*o, -1)); } } else { - for (const ModelObject* o : p->model.objects) { + for (const ModelObject* o : exported) { auto mesh = mesh_to_export(*o, -1); mesh.translate(-o->origin_translation.cast()); + const std::string file = get_save_file(path_u8, o->name); switch (file_type) { - case FT_STL: Slic3r::store_stl(get_save_file(path_u8, o->name).c_str(), &mesh, true); break; - case FT_DRC: Slic3r::store_drc(get_save_file(path_u8, o->name).c_str(), &mesh, quality); break; + case FT_STL: Slic3r::store_stl(file.c_str(), &mesh, true); break; + case FT_DRC: Slic3r::store_drc(file.c_str(), &mesh, quality); break; } + written.push_back(file); } - return; + return written; } switch (file_type) { case FT_STL: Slic3r::store_stl(path_u8.c_str(), &mesh, true); break; case FT_DRC: Slic3r::store_drc(path_u8.c_str(), &mesh, quality); break; } + written.push_back(path_u8); + return written; } //BBS: remove amf export @@ -21340,11 +21505,21 @@ void Plater::reload_from_disk() p->reload_from_disk(); } +Plater::ReloadResult Plater::reload_parts_from_disk(const std::vector>& parts) +{ + return p->reload_from_disk(&parts, false); +} + void Plater::replace_with_stl() { p->replace_with_stl(); } +Plater::ReplaceResult Plater::replace_part_with_file(int object_idx, int volume_idx, const std::string& path) +{ + return p->replace_part(object_idx, volume_idx, fs::path(path), false); +} + void Plater::replace_all_with_stl() { p->replace_all_with_stl(); @@ -21360,12 +21535,12 @@ bool Plater::has_toolpaths_to_export() const return p->preview->get_canvas3d()->has_toolpaths_to_export(); } -void Plater::export_toolpaths_to_obj() const +void Plater::export_toolpaths_to_obj(const wxString& output_path) const { if ((printer_technology() != ptFFF) || !is_preview_loaded()) return; - wxString path = p->get_export_file(FT_OBJ); + wxString path = output_path.empty() ? p->get_export_file(FT_OBJ) : output_path; if (path.empty()) return; @@ -23018,6 +23193,7 @@ void Plater::center_selection() { p->center_selection(); } void Plater::drop_selection() { p->drop_selection(); } void Plater::mirror(Axis axis) { p->mirror(axis); } void Plater::split_object(bool auto_drop) { p->split_object(auto_drop); } +Plater::SplitResult Plater::split_object(int obj_idx, bool ask, std::optional keep_z) { return p->split_object(obj_idx, true, ask, keep_z); } void Plater::split_volume() { p->split_volume(); } void Plater::optimize_rotation() { @@ -24235,13 +24411,16 @@ int Plater::add_plate() return new_plate; } +// Adds a plate with a copy of the objects on plate `plate_index` (-1: the current plate), as one undo step; -1 when no +// plate can be added or the project has no such plate. int Plater::duplicate_plate(int plate_index) { - int index = plate_index, ret; - if (plate_index == -1) - index = p->partplate_list.get_curr_plate_index(); + const int index = plate_index == -1 ? p->partplate_list.get_curr_plate_index() : plate_index; + if (!p->can_add_plate() || p->partplate_list.get_plate(index) == nullptr) + return -1; - ret = p->partplate_list.duplicate_plate(index); + take_snapshot("duplicate partplate"); + const int ret = p->partplate_list.duplicate_plate(index); //need to call update update(); diff --git a/src/slic3r/GUI/Plater.hpp b/src/slic3r/GUI/Plater.hpp index e1a6e489d8..af74087d18 100644 --- a/src/slic3r/GUI/Plater.hpp +++ b/src/slic3r/GUI/Plater.hpp @@ -19,7 +19,10 @@ #include #include "slic3r/GUI/Event.hpp" #include "slic3r/GUI/I18N.hpp" +#include "slic3r/GUI/Operations/Outcome.hpp" +#include "libslic3r/PresetBundle.hpp" #include +#include #include #include @@ -222,6 +225,9 @@ public: void add_filament(); void delete_filament(size_t filament_id = size_t(-1), int replace_filament_id = -1); // 0 base, -1 means default void change_filament(size_t from_id, size_t to_id); // 0 base + // Whether merging filament `from_id` into `to_id` (0 base) deletes a physical filament that the mixed filament `to_id` + // mixes, which change_filament() asks about first. + bool merge_removes_component(size_t from_id, size_t to_id) const; void edit_filament(); void add_custom_filament(wxColour new_col, const std::string& preset_name = std::string(), bool skip_preset_validation = false); bool is_new_project_in_gcode3mf(); @@ -229,10 +235,39 @@ public: void on_bed_type_change(BedType bed_type); void load_ams_list(MachineObject* obj); std::map build_filament_ams_list(MachineObject* obj); - void sync_ams_list(bool is_from_big_sync_btn = false); + // Synchronize Filament List from AMS: the printer's slots read again, the sync dialog where it asks, and the sync + // with its choice (Ops::apply_ams_sync()). Returns why it did not sync, after the warning it showed the person, or + // none where it synced or the person cancelled. + std::optional sync_ams_list(bool is_from_big_sync_btn = false); + // What apply_ams_sync() did. + struct AmsSyncApplied + { + unsigned int filaments = 0; // the filament list's length afterwards; 0: nothing compatible, nothing synced + std::vector unknowns; // the slots mapped to a generic preset, "tray(type) reason", in English + wxString detail; // the same, a line each, in the UI's language, as the sync's messages list them + }; + // Syncs the filament list from the slots load_ams_list() read, as the sync dialog's Synchronize now does with its + // choice: `direct_sync` overwrites the list, else `sync_maps` maps each project filament (by its 0-based index) to a + // slot; `every_slot_changed` counts each slot's filament as changed. `unknowns_found`, when given, is told the slots + // mapped to a generic preset before the list changes. + AmsSyncApplied apply_ams_sync(bool direct_sync, + std::map sync_maps, + bool every_slot_changed, + const std::function& unknowns_found); bool sync_extruder_list(); bool is_fila_switch_ready(); void reset_fila_switch(); + // The nozzle flow types the Flow combo of extruder `extruder` (0 base) lists on its nozzle card, empty while the card + // shows none. + std::vector nozzle_volume_types(int extruder) const; + // The nozzle flow types that Flow combo lists with the printer preset whose settings are `printer` selected: what + // nozzle_volume_types() gives once it is, read before it is. + static std::vector nozzle_volume_types(const DynamicPrintConfig& printer, int extruder); + // Picks `type`, one nozzle_volume_types() lists, in that Flow combo, as a person does. + void pick_nozzle_volume_type(int extruder, NozzleVolumeType type); + // Picks the printer variant `variant` (PresetCollection::diameters_of_selected_printer()) as the nozzle diameter + // combos do: the printer preset of that variant is selected. False when it was not. + bool pick_nozzle_variant(const std::string& variant); bool need_auto_sync_extruder_list_after_connect_priner(const MachineObject* obj); void update_sync_status(const MachineObject* obj); int get_sidebar_pos_right_x(); @@ -409,7 +444,10 @@ public: // Returns false when no object was added (e.g. the user cancelled the load dialog). Without fname the // person picks the files; fname names one of Orca's own models, which loads as LoadStrategy::BundledModel. bool add_model(bool imperial_units = false, std::string fname = ""); - void import_zip_archive(); + // Without `archive`, the archive a file dialog asks for, then the files of it the archive's file list picks; with it, + // the files `entries` names (as the archive's own paths give them) in place of the file list, which shows where + // `entries` is null. + void import_zip_archive(const boost::filesystem::path& archive = {}, const std::vector* entries = nullptr); void import_sl1_archive(); void extract_config_from_project(); void load_gcode(); @@ -469,7 +507,9 @@ public: static wxColour get_next_color_for_filament(); static wxString get_slice_warning_string(GCodeProcessorResult::SliceWarning& warning); - bool preview_zip_archive(const boost::filesystem::path& archive_path); + // Loads files of the archive: those its file list picks, or those `entries` names (as the archive's own paths give + // them) in place of it. False when it loaded none. + bool preview_zip_archive(const boost::filesystem::path& archive_path, const std::vector* entries = nullptr); // BBS: restore std::vector load_files(const std::vector& input_files, LoadStrategy strategy = LoadStrategy::LoadModel | LoadStrategy::LoadConfig, bool ask_multi = false, bool* published_out = nullptr, @@ -540,6 +580,14 @@ public: bool is_sidebar_collapsed() const; void collapse_sidebar(bool collapse); Sidebar::DockingState get_sidebar_docking_state() const; + // The sidebar's width in pixels: the docked pane's while it shows, else the width it docks at when it shows + // again. A drag of its edge sets it, and so does set_sidebar_width(), which a floating sidebar does not take: its + // window's size is its own. + bool is_sidebar_floating() const; + int sidebar_width() const; + void set_sidebar_width(int width); + // The sidebar's width in the default window layout, which reset_window_layout() restores. + int default_sidebar_width() const; void reset_window_layout(); @@ -614,9 +662,11 @@ public: bool get_pending_published(std::vector& out_keys, std::vector& out_material, bool& out_legacy_process) const; void set_pending_published(const std::vector& published_keys, const std::vector& material_keys); static TriangleMesh combine_mesh_fff(const ModelObject& mo, int instance_id, std::function notify_func = {}); - // `output_path` (a directory for multi_stls) skips the file dialog. - void export_stl(bool extended = false, bool selection_only = false, bool multi_stls = false, FileType file_type = FT_STL, - const wxString& output_path = {}); + // `output_path` (a directory for multi_stls) skips the file dialog. Without selection_only it writes `objects` (their + // indices), or every object where none is named. Returns the files it wrote. + std::vector export_stl(bool extended = false, bool selection_only = false, bool multi_stls = false, + FileType file_type = FT_STL, const wxString& output_path = {}, + const std::vector& objects = {}); //BBS: remove amf //void export_amf(); //BBS add extra param for exporting 3mf silence @@ -626,11 +676,29 @@ public: //BBS void reload_from_disk(); + // What reload_parts_from_disk() did: the parts [object, part] whose mesh it replaced, those whose file holds no part to + // take for them, and a file that could not be read, after which it loaded nothing more. + struct ReloadResult + { + std::vector> reloaded; + std::vector> unmatched; + std::string unreadable; + }; + // Reloads `parts`, whose files are there, as Reload from disk does with them selected, but asking for nothing: no file + // dialog for a file that is gone and no message box for a part its file has none for. One undo step; the 3D view is + // brought up to date with what it reloaded. + ReloadResult reload_parts_from_disk(const std::vector>& parts); void replace_with_stl(); + // How a part's replacement with a file ended. + enum class ReplaceResult { Replaced, Unreadable, Cancelled, SeveralParts }; + // Replaces part `volume_idx` of object `object_idx` with the mesh of the file at `path`, as Replace 3D file does once its + // file is picked, but with no message box for a file of several parts. One undo step; then the 3D view. + ReplaceResult replace_part_with_file(int object_idx, int volume_idx, const std::string& path); void replace_all_with_stl(); void reload_all_from_disk(); bool has_toolpaths_to_export() const; - void export_toolpaths_to_obj() const; + // `output_path` skips the file dialog. + void export_toolpaths_to_obj(const wxString& output_path = {}) const; void reslice(); void reslice_SLA_supports(const ModelObject &object, bool postpone_error_messages = false); void reslice_SLA_hollowing(const ModelObject &object, bool postpone_error_messages = false); @@ -768,7 +836,8 @@ public: // Arranges every unlocked plate as the toolbar's Arrange does, or the current plate alone as its // Arrange icon does. void arrange(bool current_plate_only); - void orient(); + // Auto-Orient in the background: `objects` when given, an empty list standing for every object, else the selection. + void orient(std::optional> objects = std::nullopt); void find_new_position(const ModelInstancePtrs &instances); //BBS: add job state related functions void set_prepare_state(int state); @@ -813,7 +882,14 @@ public: void search(bool plater_is_active, Preset::Type type, wxWindow *tag, TextInput *etag, wxWindow *stag); void mirror(Axis axis); void split_object(bool auto_drop = true); - void split_object(int obj_idx, bool auto_drop = true); + // What split_object(obj_idx, ...) did: split the object, found it of one piece, or met the Auto-Drop question it was + // not to ask. + enum class SplitResult { Split, OnePiece, Unanswered }; + // Splits object `obj_idx` into objects, as Split > To Objects does on the selected object, and selects them. Where + // some of them would float above the bed of an object that drops, `keep_z` answers the question the split asks + // (true keeps their height, as its Yes); with none it is asked when `ask`, and otherwise nothing is split. An object + // of one piece is told in a message box when `ask`. + SplitResult split_object(int obj_idx, bool ask, std::optional keep_z = std::nullopt); void split_volume(); void optimize_rotation(); // find all empty cells on the plate and won't overlap with exclusion areas diff --git a/src/slic3r/GUI/PluginsDialog.cpp b/src/slic3r/GUI/PluginsDialog.cpp index 2b8fc57372..00f972c87f 100644 --- a/src/slic3r/GUI/PluginsDialog.cpp +++ b/src/slic3r/GUI/PluginsDialog.cpp @@ -20,6 +20,8 @@ #include #include +#include "slic3r/GUI/Operations/Outcome.hpp" +#include "slic3r/GUI/Operations/PluginOps.hpp" #include "slic3r/GUI/PluginPermissionValidation.hpp" #include "slic3r/GUI/PluginSource.hpp" #include "slic3r/GUI/PluginStatus.hpp" @@ -34,8 +36,10 @@ #include #include +#include #include #include +#include #include #include #include @@ -149,21 +153,6 @@ PluginCapabilityType primary_capability_type_of(PluginManager& manager, const st return capabilities.empty() ? PluginCapabilityType::Unknown : capabilities.front()->type(); } -PluginDescriptor as_cloud_only_descriptor(PluginDescriptor descriptor) -{ - descriptor.plugin_root.clear(); - descriptor.entry_path.clear(); - descriptor.installed_version.clear(); - // No local package is left behind, so the package verdict and any load error it produced go with it. - descriptor.metadata_valid = false; - descriptor.clear_error(); - if (descriptor.cloud.has_value()) { - descriptor.cloud->installed = false; - descriptor.cloud->update_available = false; - } - return descriptor; -} - std::string to_string(PluginUpdateStatus status); nlohmann::json build_context_actions_payload(const PluginAvailableActions& available_actions); @@ -265,55 +254,30 @@ std::string to_string(PluginUpdateStatus status) return "normal"; } -PluginSource derive_plugin_source(const PluginDescriptor& descriptor) -{ - const bool has_cloud_meta = descriptor.cloud.has_value(); - const bool is_cloud = descriptor.is_cloud_plugin(); - const bool is_mine = is_cloud && has_cloud_meta && descriptor.cloud->is_mine; - - if (is_cloud && has_cloud_meta && descriptor.cloud->orphaned) - return PluginSource::Orphaned; - if (is_mine) - return PluginSource::Mine; - if (is_cloud) - return PluginSource::Subscribed; - return PluginSource::Local; -} - -PluginAvailableActions evaluate_action_policy(const PluginDialogItem& item) +// The row's switch and menu items, from what Ops::plugin_actions() says the row offers. +PluginAvailableActions evaluate_action_policy(const PluginDescriptor& descriptor, bool loading) { PluginAvailableActions available_actions; - const bool is_loading = item.status == PluginStatus::Loading; - const bool is_cloud = item.is_cloud_plugin; - const bool is_orphaned = item.orphaned; - const bool is_mine = item.source == PluginSource::Mine; - const bool has_local = item.has_local_package; - const bool authorized_for_install = !item.unauthorized; - - available_actions.toggle_installs_cloud_plugin = is_cloud && !is_orphaned && !has_local && authorized_for_install; - available_actions.can_toggle = !is_loading && (has_local || available_actions.toggle_installs_cloud_plugin); + const Ops::PluginActions offered = Ops::plugin_actions(descriptor, loading); + available_actions.toggle_installs_cloud_plugin = offered.toggle_installs_cloud_plugin; + available_actions.can_toggle = offered.can_toggle; auto add_action = [&available_actions](const char* id, const char* label, bool enabled = true, bool danger = false) { available_actions.context_actions.push_back(PluginContextAction{id, _u8L(label), enabled, danger}); }; - // Owned cloud plugins fall through to the local delete: it removes the installed package only. - // Deleting a plugin from the cloud is a plugin hub operation and is never offered here. - if (is_cloud && !is_orphaned && !is_mine) { + if (offered.unsubscribe) add_action("unsubscribe_plugin", L("Unsubscribe"), true, true); - } else if (has_local) { + else if (offered.remove) add_action("delete_plugin", L("Delete"), true, true); - } - add_action("open_folder", L("Show in folder"), has_local); + add_action("open_folder", L("Show in folder"), offered.open_folder); - if (!is_orphaned) { - if (is_cloud) { - add_action("reinstall_plugin", L("Reinstall")); - } else { - add_action("reload_plugin", L("Reload")); - add_action("clear_cache_reload_plugin", L("Delete cache and reload")); - } + if (offered.reinstall) + add_action("reinstall_plugin", L("Reinstall")); + if (offered.reload) { + add_action("reload_plugin", L("Reload")); + add_action("clear_cache_reload_plugin", L("Delete cache and reload")); } return available_actions; @@ -331,11 +295,7 @@ PluginDialogItem build_plugin_dialog_item(const PluginDescriptor& descriptor) (descriptor.description.empty() ? _u8L("No description.") : descriptor.description); item.author = descriptor.author; item.version = descriptor.version; - // The cloud merge overwrites `version` with the latest cloud version, so prefer the preserved local - // one, falling back to `version` for local-only / pre-merge descriptors. - item.installed_version = descriptor.has_local_package() ? - (descriptor.installed_version.empty() ? descriptor.version : descriptor.installed_version) : - std::string{}; + item.installed_version = Ops::installed_plugin_version(descriptor); item.latest_version = descriptor.latest_available_version(); item.sort_version = item.installed_version.empty() ? item.latest_version : item.installed_version; // A package that is not loaded has no capabilities, so its row contributes none and does not @@ -362,7 +322,7 @@ PluginDialogItem build_plugin_dialog_item(const PluginDescriptor& descriptor) } for (const PluginChangelog& entry : descriptor.changelog) item.changelog.push_back({entry.version, entry.changelog, entry.created_time}); - item.source = derive_plugin_source(descriptor); + item.source = Ops::plugin_source(descriptor); item.update_status = descriptor.get_update_status(); item.error_text = descriptor.normalized_error(); item.has_error = descriptor.has_error(); @@ -389,7 +349,7 @@ PluginDialogItem build_plugin_dialog_item(const PluginDescriptor& descriptor) item.status = resolve_plugin_status(item.loading, item.has_error, item.is_loaded); - item.available_actions = evaluate_action_policy(item); + item.available_actions = evaluate_action_policy(descriptor, item.loading); const bool has_enabled_script = std::any_of(item.capabilities.begin(), item.capabilities.end(), [](const PluginCapabilityView& capability) { return capability.id.type == PluginCapabilityType::Script && capability.enabled; @@ -425,25 +385,24 @@ nlohmann::json build_context_actions_payload(const PluginAvailableActions& avail return payload; } +// The outcome of an operation run behind a progress dialog, handed from its worker to its completion. struct PluginOperationState { - std::mutex mutex; - bool succeeded = false; - std::string error; + std::mutex mutex; + std::optional> outcome; }; -void store_plugin_operation_result(const std::shared_ptr& state, bool succeeded, std::string error) +void store_plugin_operation_result(const std::shared_ptr& state, Ops::Outcome outcome) { std::lock_guard lock(state->mutex); - state->succeeded = succeeded; - state->error = std::move(error); + state->outcome.emplace(std::move(outcome)); } -bool take_plugin_operation_result(const std::shared_ptr& state, std::string& error) +// The worker's outcome; none where it ended without one (it threw). +std::optional> take_plugin_operation_result(const std::shared_ptr& state) { std::lock_guard lock(state->mutex); - error = std::move(state->error); - return state->succeeded; + return state->outcome; } // A full-access or permission-save request carries an opaque correlation token that the webview @@ -545,7 +504,11 @@ void open_plugin_hub() wxLaunchDefaultBrowser(wxString::FromUTF8(cloud_base_url + "/app/plugins/plugin-hub")); } -bool install_local_plugin_package(const boost::filesystem::path& package_file, wxWindow* parent, wxString& message) +bool install_local_plugin_package(const boost::filesystem::path& package_file, + wxWindow* parent, + wxString& message, + std::optional overwrite, + std::optional* refused) { message.clear(); if (package_file.empty()) @@ -582,9 +545,22 @@ bool install_local_plugin_package(const boost::filesystem::path& package_file, w return failed({}); } - if (existing_installation) { + if (existing_installation && overwrite == false) { + const std::string plugin_name = plugin_descriptor.name.empty() ? package_file.filename().string() : plugin_descriptor.name; + // The overwrite prompt's question is the reason. + const Ops::Refusal installed{Ops::RefusalKind::Precondition, "plugin_installed", + // TRN %s is a plugin's name. + L("Plugin \"%s\" is already installed.\n\n" + "Installing this package will overwrite the existing plugin."), + {plugin_name}}; + message = installed.translated(); + if (refused != nullptr) + *refused = installed; + return false; + } + if (existing_installation && !overwrite) { const wxString plugin_name = from_u8(plugin_descriptor.name.empty() ? package_file.filename().string() : plugin_descriptor.name); - // Orca's own message dialog rather than a native box, which answer_dialog can't press on every platform. + // Orca's own message dialog rather than a native box, which dialog_answer can't press on every platform. MessageDialog dialog(parent, wxString::Format(_L("Plugin \"%s\" is already installed.\n\nInstalling this package will overwrite the existing plugin."), plugin_name), @@ -944,10 +920,7 @@ nlohmann::json PluginsDialog::build_plugins_payload() const bool PluginsDialog::get_descriptor(const std::string& plugin_key, PluginDescriptor& descriptor) const { - PluginManager& manager = PluginManager::instance(); - if (manager.try_get_valid_plugin_descriptor(plugin_key, descriptor)) - return true; - return manager.try_get_plugin_descriptor(plugin_key, descriptor) && descriptor.is_invalid_package(); + return Ops::plugin_descriptor(plugin_key, descriptor); } void PluginsDialog::refresh_plugin_metadata_async(const wxString& title, const wxString& message, bool fetch_cloud) @@ -1131,30 +1104,34 @@ void PluginsDialog::toggle_plugin(const std::string& plugin_key, bool enabled) if (plugin_key.empty()) return; - BOOST_LOG_TRIVIAL(info) << "Toggle plugin request. plugin_key=" << plugin_key << " enabled=" << enabled; - - PluginDescriptor row_data; - if (!get_descriptor(plugin_key, row_data)) { + Ops::SetPluginEnabledArgs args; + args.plugin = plugin_key; + args.enabled = enabled; + // Switching on a cloud plugin that is not installed downloads it behind this dialog's progress dialog. + args.run_download = [this, plugin_key](const std::function()>& download) { + PluginDescriptor descriptor; + const wxString name = get_descriptor(plugin_key, descriptor) ? from_u8(descriptor.name) : from_u8(plugin_key); + return run_with_dialog_wait(download, _L("Downloading plugin"), _L("Downloading") + ": " + name); + }; + const Ops::Outcome done = Ops::set_plugin_enabled(args); + if (!done) { + const Ops::Refusal& refusal = done.refusal(); + const std::string code = refusal.code; + if (code == "unauthorized_plugin") { + // The row shows why it stays off. + PluginManager::instance().set_plugin_error(plugin_key, into_u8(refusal.translated())); + show_status(refusal.translated(), "warn"); + } else if (code == "not_unloaded" || code == "manifest_not_found") { + show_status(refusal.translated(), "warn"); + } else if (code == "download_failed") { + show_status(refusal.translated(), "error"); + } + // Otherwise the row shows how the plugin stands: gone, loading, or with its error. send_plugins(); return; } - PluginDialogItem dialog_item = build_plugin_dialog_item(row_data); - PluginAvailableActions available_actions = dialog_item.available_actions; - - PluginManager& manager = PluginManager::instance(); if (!enabled) { - if (!manager.unload_plugin(plugin_key)) { - BOOST_LOG_TRIVIAL(error) << "Failed to unload plugin from Plugins dialog: " << plugin_key; - show_status(_L("Failed to unload plugin."), "warn"); - send_plugins(); - return; - } - - BOOST_LOG_TRIVIAL(info) << "Plugin unloaded from Plugins dialog: " << plugin_key; - // A user-disabled plugin has no meaningful error state. - if (!manager.clear_plugin_error(plugin_key)) - BOOST_LOG_TRIVIAL(warning) << "Failed to clear plugin error for " << plugin_key << " (failed to find)"; // A prior activation of this plugin is moot now; drop it so no stale "Activated" arrives later. if (m_activating_plugin_key == plugin_key) m_activating_plugin_key.clear(); @@ -1163,56 +1140,9 @@ void PluginsDialog::toggle_plugin(const std::string& plugin_key, bool enabled) return; } - if (!available_actions.can_toggle) { - if (dialog_item.unauthorized && available_actions.toggle_installs_cloud_plugin == false && row_data.has_local_package() == false) { - const std::string install_error = _u8L("Unauthorized cloud plugins cannot be installed."); - manager.set_plugin_error(plugin_key, install_error); - show_status(from_u8(install_error), "warn"); - } - send_plugins(); - return; - } - - if (available_actions.toggle_installs_cloud_plugin) { - if (!install_cloud_plugin(row_data.plugin_key, row_data.version, from_u8(row_data.name))) { - BOOST_LOG_TRIVIAL(warning) << "Cloud plugin install was not completed for " << plugin_key; - send_plugins(); - return; - } - - BOOST_LOG_TRIVIAL(info) << "Cloud plugin installed locally from Plugins dialog: " << plugin_key; - // download_and_install_cloud_plugin already updated the descriptor, so no rescan is needed here. - if (!get_descriptor(plugin_key, row_data)) { - send_plugins(); - return; - } - dialog_item = build_plugin_dialog_item(row_data); - if (dialog_item.has_error) { - send_plugins(); - return; - } - } - - if (manager.is_plugin_loaded(plugin_key)) { - send_plugins(); - return; - } - - PluginDescriptor valid_descriptor; - if (!manager.try_get_valid_plugin_descriptor(plugin_key, valid_descriptor)) { - show_status(_L("Plugin manifest was not found."), "warn"); - send_plugins(); - return; - } - - if (manager.is_plugin_load_in_progress(plugin_key)) { - send_plugins(); - return; - } - - BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": Starting plugin load from web dialog: " << plugin_key; - manager.load_plugin(plugin_key); send_plugins(); + if (done.value().change != Ops::PluginChange::LoadStarted) + return; // Loading is asynchronous: show a pending message now; resolve_pending_activation() turns it into // Activated/Failed once the loader's completion callback runs update_plugin_dialog_ui(). m_activating_plugin_key = plugin_key; @@ -1227,30 +1157,16 @@ void PluginsDialog::toggle_plugin_capability(const std::string& plugin_key, if (plugin_key.empty() || capability_name.empty() || type == PluginCapabilityType::Unknown) return; - PluginDescriptor row_data; - if (!get_descriptor(plugin_key, row_data)) { - send_plugins(); - return; - } - - if (!PluginManager::instance().get_plugin_capability({type, capability_name, plugin_key}, /*only_enabled=*/false)) { - BOOST_LOG_TRIVIAL(warning) << "Cannot toggle missing plugin capability: " << plugin_key << " | " << capability_name; - send_plugins(); - return; - } - - PluginManager& manager = PluginManager::instance(); - if (enabled) { - BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": Enabling plugin capability: " << plugin_key << " | " << capability_name; - manager.set_capability_enabled({type, capability_name, plugin_key}, true); - } else { - // check if the capability is currently in use here. - BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": Disabling plugin capability: " << plugin_key << " | " << capability_name; - manager.set_capability_enabled({type, capability_name, plugin_key}, false); - } - + Ops::SetPluginEnabledArgs args; + args.plugin = plugin_key; + args.capability = capability_name; + args.capability_type = type; + args.enabled = enabled; + const Ops::Outcome done = Ops::set_plugin_enabled(args); send_plugins(); - show_status(wxString::Format(enabled ? _L("Enabled \"%s\".") : _L("Disabled \"%s\"."), from_u8(capability_name)), "success"); + // A plugin or capability that is gone leaves the rows to show it. + if (done) + show_status(wxString::Format(enabled ? _L("Enabled \"%s\".") : _L("Disabled \"%s\"."), from_u8(capability_name)), "success"); } void PluginsDialog::handle_plugin_menu_action(const std::string& plugin_key, const std::string& action) @@ -1333,31 +1249,13 @@ bool PluginsDialog::install_cloud_plugin(const std::string& plugin_key, const st if (plugin_key.empty()) return false; - BOOST_LOG_TRIVIAL(info) << "Downloading cloud plugin. plugin_key=" << plugin_key << " name=" << into_u8(name); - - std::string error; - - bool downloaded = false; - try { - downloaded = run_with_dialog_wait( - [plugin_key, &error, version]() { - return PluginManager::instance().download_and_install_cloud_plugin(plugin_key, version, error); - }, - _L("Downloading plugin"), _L("Downloading") + ": " + name); - } catch (const std::exception& ex) { - error = ex.what(); - } catch (...) { - error = _u8L("Unknown error"); - } - + const Ops::Outcome downloaded = run_with_dialog_wait( + [plugin_key, version]() { return Ops::download_cloud_plugin(plugin_key, version); }, _L("Downloading plugin"), + _L("Downloading") + ": " + name); if (!downloaded) { - BOOST_LOG_TRIVIAL(error) << "Cloud plugin download failed. plugin_key=" << plugin_key << " error=" << error; - PluginManager::instance().set_plugin_error(plugin_key, error); - show_status(error.empty() ? _L("Plugin download failed.") : from_u8(error), "error"); + show_status(downloaded.refusal().translated(), "error"); return false; } - - BOOST_LOG_TRIVIAL(info) << "Cloud plugin downloaded successfully. plugin_key=" << plugin_key; return true; } @@ -1554,30 +1452,21 @@ void PluginsDialog::delete_local_plugin(const PluginDescriptor& plugin) if (rc != wxYES) return; - auto state = std::make_shared(); - run_with_dialog( - [plugin_key = plugin.plugin_key, cloud_row = as_cloud_only_descriptor(plugin), state]() { - std::string error; - const bool succeeded = PluginManager::instance().delete_plugin(plugin_key, error); - // Keep the cloud row listed so the plugin stays reinstallable without waiting on a cloud fetch. - if (succeeded && cloud_row.is_cloud_plugin()) - PluginManager::instance().update_cloud_metadata(std::vector{cloud_row}); - store_plugin_operation_result(state, succeeded, std::move(error)); - }, - [this, state, plugin_name]() { - std::string error; - if (!take_plugin_operation_result(state, error)) { - show_status(error.empty() ? _L("Failed to delete plugin.") : from_u8(error), "error"); - return; - } + const Ops::PluginUninstall plan{plugin.plugin_key, plugin.name, /*unsubscribe=*/false, plugin}; + auto state = std::make_shared(); + run_with_dialog([plan, state]() { store_plugin_operation_result(state, Ops::uninstall_plugin(plan)); }, + [this, state, plugin_name]() { + const std::optional> deleted = take_plugin_operation_result(state); + if (!deleted || !*deleted) { + show_status(deleted ? deleted->refusal().translated() : _L("Failed to delete plugin."), "error"); + return; + } - send_plugins(); - // The package is gone only now; the unload callback rechecked the notices too early. - if (Plater* plater = wxGetApp().plater()) - plater->refresh_missing_plugin_notifications(); - show_status(wxString::Format(_L("Deleted \"%s\"."), plugin_name), "success"); - }, - _L("Deleting plugin"), _L("Deleting plugin...")); + send_plugins(); + Ops::plugin_uninstalled(); + show_status(wxString::Format(_L("Deleted \"%s\"."), plugin_name), "success"); + }, + _L("Deleting plugin"), _L("Deleting plugin...")); } void PluginsDialog::unsubscribe_cloud_plugin(const PluginDescriptor& plugin) @@ -1591,27 +1480,22 @@ void PluginsDialog::unsubscribe_cloud_plugin(const PluginDescriptor& plugin) if (rc != wxYES) return; - auto state = std::make_shared(); - run_with_dialog( - [plugin_key = plugin.plugin_key, state]() { - std::string error; - const bool succeeded = PluginManager::instance().delete_and_unsubscribe_cloud_plugin(plugin_key, error); - store_plugin_operation_result(state, succeeded, std::move(error)); - }, - [this, state, plugin_name]() { - std::string error; - if (!take_plugin_operation_result(state, error)) { - show_status(error.empty() ? _L("Failed to unsubscribe plugin.") : from_u8(error), "error"); - return; - } + const Ops::PluginUninstall plan{plugin.plugin_key, plugin.name, /*unsubscribe=*/true, plugin}; + auto state = std::make_shared(); + run_with_dialog([plan, state]() { store_plugin_operation_result(state, Ops::uninstall_plugin(plan)); }, + [this, state, plugin_name]() { + const std::optional> unsubscribed = take_plugin_operation_result(state); + if (!unsubscribed || !*unsubscribed) { + show_status(unsubscribed ? unsubscribed->refusal().translated() : _L("Failed to unsubscribe plugin."), + "error"); + return; + } - send_plugins(); - // The package is gone only now; the unload callback rechecked the notices too early. - if (Plater* plater = wxGetApp().plater()) - plater->refresh_missing_plugin_notifications(); - show_status(wxString::Format(_L("Unsubscribed \"%s\"."), plugin_name), "success"); - }, - _L("Unsubscribing plugin"), _L("Deleting local files and unsubscribing plugin...")); + send_plugins(); + Ops::plugin_uninstalled(); + show_status(wxString::Format(_L("Unsubscribed \"%s\"."), plugin_name), "success"); + }, + _L("Unsubscribing plugin"), _L("Deleting local files and unsubscribing plugin...")); } void PluginsDialog::reload_local_plugin(const std::string& plugin_key, bool clear_cache) @@ -1619,57 +1503,14 @@ void PluginsDialog::reload_local_plugin(const std::string& plugin_key, bool clea if (plugin_key.empty()) return; - const bool was_loaded = PluginManager::instance().is_plugin_loaded(plugin_key); - std::pair reload_result{false, ""}; - try { - reload_result = run_with_dialog_wait( - [plugin_key, was_loaded, clear_cache]() -> std::pair { - PluginManager& manager = PluginManager::instance(); - - boost::filesystem::path cache_dir; - if (clear_cache) { - PluginDescriptor descriptor; - if (!manager.try_get_plugin_descriptor(plugin_key, descriptor)) - return {false, _u8L("Plugin not found.")}; - - boost::filesystem::path resolved_root; - std::string resolve_error; - if (!resolve_allowed_plugin_root(descriptor, {get_orca_plugins_dir()}, - _u8L("Refusing to clear a plugin cache outside the local plugin directory."), - resolved_root, resolve_error)) - return {false, resolve_error}; - cache_dir = resolved_root / "__whl_extracted__"; - } - - if (!manager.unload_plugin(plugin_key)) - return {false, _u8L("Failed to unload plugin.")}; - - if (clear_cache) { - boost::system::error_code ec; - boost::filesystem::remove_all(cache_dir, ec); - if (ec) - return {false, GUI::format(_u8L("Failed to clear plugin cache: %1%"), ec.message())}; - } - - manager.load_plugin(plugin_key, false); - std::string error; - if (!manager.wait_for_plugin_load(plugin_key, std::chrono::minutes(5), error) || !manager.is_plugin_loaded(plugin_key)) - return {false, error.empty() ? _u8L("Plugin failed to load.") : error}; - - if (!was_loaded && !manager.unload_plugin(plugin_key)) - return {false, _u8L("Plugin reloaded, but failed to restore the inactive state.")}; - - return {true, {}}; - }, - _L("Reloading plugin"), _L("Reloading plugin")); - } catch (const std::exception& ex) { - reload_result = {false, ex.what()}; - } catch (...) { - reload_result = {false, _u8L("Unknown plugin reload error.")}; + const Ops::Outcome plan = Ops::plugin_reload_plan(plugin_key, clear_cache); + if (!plan) { + show_status(plan.refusal().translated(), "warn"); + send_plugins(); + return; } - - if (!reload_result.first) { - show_status(reload_result.second.empty() ? _L("Failed to reload plugin.") : from_u8(reload_result.second), "warn"); + if (const Ops::Outcome reloaded = run_reload([plan = plan.value()]() { return Ops::reload_plugin(plan); }); !reloaded) { + show_status(reloaded.refusal().translated(), "warn"); send_plugins(); return; } @@ -1678,24 +1519,36 @@ void PluginsDialog::reload_local_plugin(const std::string& plugin_key, bool clea show_status(wxString::Format(_L("Reloaded \"%s\"."), plugin_display_name(plugin_key)), "success"); } +Ops::Outcome PluginsDialog::run_reload(const std::function()>& work) +{ + Ops::Outcome reloaded = Ops::Done{}; + try { + reloaded = run_with_dialog_wait(work, _L("Reloading plugin"), _L("Reloading plugin")); + } catch (const std::exception& ex) { + reloaded = Ops::Refusal{Ops::RefusalKind::Failed, "not_loaded", ex.what()}; + } catch (...) { + reloaded = Ops::Refusal{Ops::RefusalKind::Failed, "not_loaded", L("Unknown plugin reload error.")}; + } + // A failure with no text of its own. + if (!reloaded && reloaded.refusal().msgid.empty()) + return Ops::Refusal{Ops::RefusalKind::Failed, reloaded.refusal().code, L("Failed to reload plugin.")}; + return reloaded; +} + void PluginsDialog::reinstall_cloud_plugin(const PluginDescriptor& plugin) { const std::string plugin_key = plugin.plugin_key; if (plugin_key.empty()) return; - PluginManager& manager = PluginManager::instance(); - const bool was_loaded = PluginManager::instance().is_plugin_loaded(plugin_key); + const bool was_loaded = PluginManager::instance().is_plugin_loaded(plugin_key); - std::string error; if (plugin.has_local_package()) { - if (!manager.delete_plugin(plugin_key, error)) { - show_status(error.empty() ? _L("Failed to delete plugin.") : from_u8(error), "error"); + if (const Ops::Outcome removed = Ops::remove_plugin_package_for_reinstall(plugin); !removed) { + show_status(removed.refusal().translated(), "error"); send_plugins(); return; } - - manager.update_cloud_metadata(std::vector{as_cloud_only_descriptor(plugin)}); } if (!install_cloud_plugin(plugin_key, plugin.version, from_u8(plugin.name))) { @@ -1704,26 +1557,9 @@ void PluginsDialog::reinstall_cloud_plugin(const PluginDescriptor& plugin) } if (was_loaded) { - std::pair reload_result{false, ""}; - try { - reload_result = run_with_dialog_wait( - [plugin_key]() -> std::pair { - PluginManager& manager = PluginManager::instance(); - manager.load_plugin(plugin_key); - std::string error; - if (!manager.wait_for_plugin_load(plugin_key, std::chrono::minutes(5), error) || !manager.is_plugin_loaded(plugin_key)) - return {false, error.empty() ? _u8L("Plugin failed to load.") : error}; - return {true, {}}; - }, - _L("Reloading plugin"), _L("Reloading plugin")); - } catch (const std::exception& ex) { - reload_result = {false, ex.what()}; - } catch (...) { - reload_result = {false, _u8L("Unknown plugin reload error.")}; - } - - if (!reload_result.first) { - show_status(reload_result.second.empty() ? _L("Failed to reload plugin.") : from_u8(reload_result.second), "warn"); + if (const Ops::Outcome reloaded = run_reload([plugin_key]() { return Ops::load_plugin_and_wait(plugin_key); }); + !reloaded) { + show_status(reloaded.refusal().translated(), "warn"); send_plugins(); return; } diff --git a/src/slic3r/GUI/PluginsDialog.hpp b/src/slic3r/GUI/PluginsDialog.hpp index a95a6ec170..09e7d7acc0 100644 --- a/src/slic3r/GUI/PluginsDialog.hpp +++ b/src/slic3r/GUI/PluginsDialog.hpp @@ -2,6 +2,7 @@ #define slic3r_PluginsDialog_hpp_ #include "Widgets/WebViewHostDialog.hpp" +#include "Operations/Outcome.hpp" #include "PluginSort.hpp" #include @@ -55,7 +56,14 @@ void open_plugin_hub(); // responsive by performing the install on a worker behind a modal progress dialog. `parent` owns // the overwrite prompt and the progress dialog. On success `message` carries the localized // confirmation; on a user-cancelled overwrite it is empty; on failure it carries the reason. -bool install_local_plugin_package(const boost::filesystem::path& package_file, wxWindow* parent, wxString& message); +// `overwrite` answers the overwrite prompt for a plugin installed already: none asks the person; +// false installs nothing, with the prompt's question as the reason, in `message` and in `refused` +// where it is given; true replaces the plugin. +bool install_local_plugin_package(const boost::filesystem::path& package_file, + wxWindow* parent, + wxString& message, + std::optional overwrite = std::nullopt, + std::optional* refused = nullptr); namespace detail { @@ -287,6 +295,8 @@ private: void unsubscribe_cloud_plugin(const Slic3r::PluginDescriptor& plugin); void reload_local_plugin(const std::string& plugin_key, bool clear_cache); void reinstall_cloud_plugin(const Slic3r::PluginDescriptor& plugin); + // Runs a reload's `work` behind the Reloading plugin progress dialog; what it throws is its refusal. + Ops::Outcome run_reload(const std::function()>& work); // In the future, we can allow users to choose which plugin version they want to install. template diff --git a/src/slic3r/GUI/Preferences.cpp b/src/slic3r/GUI/Preferences.cpp index 5b18743cd4..3af9f5bec4 100644 --- a/src/slic3r/GUI/Preferences.cpp +++ b/src/slic3r/GUI/Preferences.cpp @@ -6,12 +6,12 @@ #include "MainFrame.hpp" #include "WebViewDialog.hpp" #include "Plater.hpp" -#include "GLCanvas3D.hpp" // ORCA: for live preview refresh when toggling "Dim lower layers" #include "MsgDialog.hpp" #include "I18N.hpp" #include "libslic3r/AppConfig.hpp" #include "libslic3r/Color.hpp" #include "libslic3r/Format/DRC.hpp" +#include "Operations/PreferenceOps.hpp" #include #include #include @@ -362,6 +362,30 @@ private: } }; +// A string of the preferences table in the UI's language: its msgid's translation, or the text itself where the +// catalog has none (a symbol such as "4x"). +static wxString translated(const std::string& msgid) +{ + return msgid.empty() ? wxString() : I18N::translate(msgid); +} + +// A row's tooltip: its lines, each translated; empty where the row has none, which the builders fill with the title. +static wxString tooltip_of(const Ops::Preference& p) +{ + wxString tooltip; + for (const std::string& line : p.tooltip) + tooltip += (tooltip.empty() ? wxString() : wxString("\n")) + translated(line); + return tooltip; +} + +// The table's entry for `key`: a row with a field of another key's reads that field's texts from it. +static const Ops::Preference& preference(const std::string& key) +{ + const Ops::Preference* p = Ops::find_preference(Ops::preferences(), key); + assert(p != nullptr); + return *p; +} + wxBoxSizer *PreferencesDialog::create_item_title(wxString title) { wxBoxSizer *m_sizer_title = new wxBoxSizer(wxHORIZONTAL); @@ -418,28 +442,6 @@ std::tuple PreferencesDialog::create_item_combobox_base( return {m_sizer, combobox}; } -wxBoxSizer* PreferencesDialog::create_item_combobox(wxString title, wxString tooltip, std::string param, std::vector vlist, std::function onchange, const wxString wiki_url) -{ - unsigned int current_index = 0; - - auto current_setting = app_config->get(param); - if (!current_setting.empty()) { - current_index = atoi(current_setting.c_str()); - } - - auto [sizer, combobox] = create_item_combobox_base(title, tooltip, param, vlist, current_index, wiki_url); - - //// save config - combobox->GetDropDown().Bind(wxEVT_COMBOBOX, [this, param, onchange](wxCommandEvent& e) { - app_config->set(param, std::to_string(e.GetSelection())); - if (onchange) - onchange(std::to_string(e.GetSelection())); - e.Skip(); - }); - - return sizer; -} - wxBoxSizer *PreferencesDialog::create_item_combobox(wxString title, wxString tooltip, std::string param, std::vector vlist, std::vector config_name_index, std::function onchange, const wxString wiki_url) { assert(vlist.size() == config_name_index.size()); @@ -771,8 +773,8 @@ wxBoxSizer *PreferencesDialog::create_item_loglevel_combobox(wxString title, wxS //// save config combobox->GetDropDown().Bind(wxEVT_COMBOBOX, [this](wxCommandEvent &e) { auto level = Slic3r::get_string_logging_level(e.GetSelection()); - Slic3r::set_logging_level(Slic3r::level_string_to_boost(level)); app_config->set("log_severity_level",level); + Ops::apply_preference("log_severity_level"); e.Skip(); }); return m_sizer; @@ -978,22 +980,22 @@ wxBoxSizer *PreferencesDialog::create_item_backup(wxString title, wxString toolt checkbox->Bind(wxEVT_TOGGLEBUTTON, [this, checkbox](wxCommandEvent &e) { app_config->set_bool("backup_switch", checkbox->GetValue()); app_config->save(); + Ops::apply_preference("backup_switch"); bool pbool = app_config->get("backup_switch") == "true" ? true : false; - std::string backup_interval = "10"; - app_config->get("backup_interval", backup_interval); - Slic3r::set_backup_interval(pbool ? boost::lexical_cast(backup_interval) : 0); if (m_backup_interval_textinput != nullptr) { m_backup_interval_textinput->Enable(pbool); } e.Skip(); }); m_backup_interval_time = app_config->get("backup_interval"); - auto input = new ::TextInput(m_parent, wxEmptyString, _L("sec"), "loop", wxDefaultPosition, wxSize(FromDIP(97), -1), wxTE_PROCESS_ENTER); + const Ops::Preference& interval = preference("backup_interval"); + auto input = new ::TextInput(m_parent, wxEmptyString, translated(interval.unit), "loop", wxDefaultPosition, wxSize(FromDIP(97), -1), + wxTE_PROCESS_ENTER); StateColor input_bg(std::pair(wxColour("#F0F0F1"), StateColor::Disabled), std::pair(*wxWHITE, StateColor::Enabled)); input->SetBackgroundColor(input_bg); input->GetTextCtrl()->SetValue(m_backup_interval_time); wxTextValidator validator(wxFILTER_DIGITS); - input->SetToolTip(_L("The period of backup in seconds.")); + input->SetToolTip(tooltip_of(interval)); input->GetTextCtrl()->SetValidator(validator); input->SetName("backup_interval"); @@ -1009,9 +1011,7 @@ wxBoxSizer *PreferencesDialog::create_item_backup(wxString title, wxString toolt m_backup_interval_time = input->GetTextCtrl()->GetValue(); app_config->set("backup_interval", std::string(m_backup_interval_time.mb_str())); app_config->save(); - long backup_interval = 0; - m_backup_interval_time.ToLong(&backup_interval); - Slic3r::set_backup_interval(backup_interval); + Ops::apply_preference("backup_interval"); }; input->GetTextCtrl()->Bind(wxEVT_TEXT_ENTER, [backup_interval](wxCommandEvent &e) { @@ -1044,7 +1044,8 @@ wxBoxSizer *PreferencesDialog::create_item_auto_reslice(wxString title, wxString if (delay_value.empty()) delay_value = "0"; - auto input = new ::TextInput(m_parent, wxEmptyString, _L("sec"), wxEmptyString, wxDefaultPosition, wxSize(FromDIP(97), -1), wxTE_PROCESS_ENTER); + auto input = new ::TextInput(m_parent, wxEmptyString, translated(preference("auto_slice_change_delay_seconds").unit), wxEmptyString, + wxDefaultPosition, wxSize(FromDIP(97), -1), wxTE_PROCESS_ENTER); StateColor input_bg(std::pair(wxColour("#F0F0F1"), StateColor::Disabled), std::pair(*wxWHITE, StateColor::Enabled)); input->SetBackgroundColor(input_bg); input->GetTextCtrl()->SetValue(delay_value); @@ -1110,16 +1111,12 @@ wxBoxSizer* PreferencesDialog::create_item_darkmode(wxString title,wxString tool checkbox->Bind(wxEVT_TOGGLEBUTTON, [this, checkbox, param](wxCommandEvent& e) { app_config->set(param, checkbox->GetValue() ? "1" : "0"); app_config->save(); - wxGetApp().Update_dark_mode_flag(); + Ops::apply_preference(param); //dark mode #ifdef _MSW_DARK_MODE - wxGetApp().force_colors_update(); - wxGetApp().update_ui_from_settings(); set_dark_mode(); #endif - SimpleEvent evt = SimpleEvent(EVT_GLCANVAS_COLOR_MODE_CHANGED); - wxPostEvent(wxGetApp().plater(), evt); e.Skip(); }); @@ -1170,16 +1167,8 @@ wxBoxSizer *PreferencesDialog::create_item_checkbox(wxString title, wxString too app_config->set_bool(param, checkbox->GetValue()); app_config->save(); - if (param == "sync_user_preset") { - bool sync = app_config->get("sync_user_preset") == "true" ? true : false; - if (sync) { - wxGetApp().start_sync_user_preset(); - } else { - wxGetApp().stop_sync_user_preset(); - } - BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << " sync_user_preset: " << (sync ? "true" : "false"); - } - else if (param == SETTING_OPENGL_SCENE_CACHE) { + // The dialog's controls that follow this one. + if (param == SETTING_OPENGL_SCENE_CACHE) { if (m_skip_identical_frames_checkbox) m_skip_identical_frames_checkbox->Enable(checkbox->GetValue()); } else if (param == SETTING_OPENGL_OUTLINE_PERSISTENT) { @@ -1187,111 +1176,22 @@ wxBoxSizer *PreferencesDialog::create_item_checkbox(wxString title, wxString too } else if (param == "stealth_mode") { bool enabled = app_config->get_stealth_mode(); - if (enabled) wxGetApp().on_stealth_mode_enter(); if (m_sync_user_preset_checkbox) m_sync_user_preset_checkbox->Enable(!enabled); if (m_bambu_cloud_checkbox) m_bambu_cloud_checkbox->Enable(!enabled); } - else if (param == "hide_login_side_panel") { - if (WebViewPanel* home = WebViewPanel::if_built()) { - home->SendCloudProvidersInfo(); - } - } - // ORCA: apply the filament translucency change immediately to the currently loaded preview - else if (param == "preview_translucent_filaments") { - if (Plater* plater = wxGetApp().plater()) { - if (GLCanvas3D* canvas = plater->get_preview_canvas3D()) { - canvas->get_gcode_viewer().set_translucent_filaments(app_config->get_bool(param)); - canvas->set_as_dirty(); - canvas->request_extra_frame(); - } - } - } - // ORCA: apply the preview dimming change immediately to the currently loaded preview else if (param == "preview_dim_previous_layers") { if (m_dim_previous_layers_brightness_input) m_dim_previous_layers_brightness_input->Enable(app_config->get_bool(param)); - if (Plater* plater = wxGetApp().plater()) { - if (GLCanvas3D* canvas = plater->get_preview_canvas3D()) { - canvas->get_gcode_viewer().set_dim_previous_layers(app_config->get_bool(param)); - canvas->set_as_dirty(); - canvas->request_extra_frame(); - } - } } - -#ifdef __WXMSW__ - if (param == "associate_3mf") { - bool pbool = app_config->get("associate_3mf") == "true" ? true : false; - if (pbool) { - wxGetApp().associate_files(L"3mf"); - } else { - wxGetApp().disassociate_files(L"3mf"); - } - } - - if (param == "associate_drc") { - bool pbool = app_config->get("associate_drc") == "true" ? true : false; - if (pbool) { - wxGetApp().associate_files(L"drc"); - } else { - wxGetApp().disassociate_files(L"drc"); - } - } - - if (param == "associate_stl") { - bool pbool = app_config->get("associate_stl") == "true" ? true : false; - if (pbool) { - wxGetApp().associate_files(L"stl"); - } else { - wxGetApp().disassociate_files(L"stl"); - } - } - - if (param == "associate_step") { - bool pbool = app_config->get("associate_step") == "true" ? true : false; - if (pbool) { - wxGetApp().associate_files(L"step"); - } else { - wxGetApp().disassociate_files(L"step"); - } - } - - if (param == "installed_networking") { - bool pbool = app_config->get_bool("installed_networking"); - if (pbool) { - GUI::wxGetApp().CallAfter([] { GUI::wxGetApp().ShowDownNetPluginDlg(); }); - } - } - -#endif // __WXMSW__ - - if (param == "developer_mode") { + else if (param == "developer_mode") { m_developer_mode_def = app_config->get("developer_mode"); - Slic3r::GUI::wxGetApp().update_mode(); } - - // webview dump_vedio - if (param == "internal_developer_mode") { + else if (param == "internal_developer_mode") { m_internal_developer_mode_def = app_config->get("internal_developer_mode"); - if (m_internal_developer_mode_def == "true") { - Slic3r::GUI::wxGetApp().update_internal_development(); - Slic3r::GUI::wxGetApp().mainframe->show_log_window(); - } else { - Slic3r::GUI::wxGetApp().update_internal_development(); - } } - if (param == "show_unsupported_presets") { - wxGetApp().plater()->sidebar().update_presets(Preset::TYPE_FILAMENT); - } - - if (param == "use_printer_agents") - { - // Rebuild the Device tab so the native/web-UI choice reflects the new flag - // immediately, instead of only on the next printer-preset change or restart. - if (wxGetApp().plater()) - wxGetApp().plater()->sidebar().update_all_preset_comboboxes(); - } + // What the change does in the app, which preferences_set does through the same function. + Ops::apply_preference(param); if (param == "enable_high_low_temp_mixed_printing") { if (checkbox->GetValue()) { @@ -1372,8 +1272,9 @@ wxBoxSizer* PreferencesDialog::create_item_downloads(wxString title, wxString to auto m_button_download = new Button(m_parent, _L("Browse") + dots); m_button_download->SetStyle(ButtonStyle::Regular, ButtonType::Parameter); m_button_download->SetToolTip(_L("Choose folder for downloaded items")); + m_button_download->SetName("download_path"); // select_tab() and automation find the row by its AppConfig key - m_button_download->Bind(wxEVT_BUTTON, [this, m_staticTextPath, m_sizer](auto& e) { + m_button_download->Bind(wxEVT_BUTTON, [this](auto& e) { wxString defaultPath = wxT("/"); wxDirDialog dialog(this, _L("Choose Download Directory"), defaultPath, wxDD_NEW_DIR_BUTTON); @@ -1381,18 +1282,28 @@ wxBoxSizer* PreferencesDialog::create_item_downloads(wxString title, wxString to wxString download_path = dialog.GetPath(); std::string download_path_str = download_path.ToUTF8().data(); app_config->set("download_path", download_path_str); - m_staticTextPath->SetLabelText(download_path); - m_staticTextPath->SetToolTip(download_path); - m_sizer->Layout(); + Ops::apply_preference("download_path"); } }); m_sizer->Add(m_button_download, 0, wxALIGN_CENTER_VERTICAL); m_sizer->Add(m_staticTextPath , 0, wxALIGN_CENTER_VERTICAL | wxLEFT, FromDIP(10)); + m_download_path_text = m_staticTextPath; + m_download_path_row = m_sizer; return m_sizer; } +void PreferencesDialog::show_download_path() +{ + if (m_download_path_text == nullptr) + return; + const wxString path = wxString::FromUTF8(app_config->get("download_path")); + m_download_path_text->SetLabelText(path); + m_download_path_text->SetToolTip(path); + m_download_path_row->Layout(); +} + // Wrap widths of the AI features texts, in DIP: the introduction spans the page, the server status // what the control column leaves beside the checkbox and the status dot, and the setup hint the // control column. @@ -1402,20 +1313,10 @@ static constexpr int MCP_HINT_WIDTH = 270; // The setup row's Copy button, in DIP: ButtonType::Parameter's height, narrower to leave the picker room. static const wxSize MCP_COPY_BUTTON_SIZE(100, 26); -// The running server's port, otherwise the one turning it on here opens (GUI_App::open_mcp_endpoint()): -// --mcp-port until a port is set in Preferences, then the saved one. -static int mcp_port(const Mcp::McpEndpoint *endpoint, AppConfig *config) +// Where agents connect over HTTP: the port the port field shows (Ops::mcp_port_shown()). +static std::string mcp_url() { - if (endpoint != nullptr && endpoint->serving()) - return endpoint->port(); - const GUI_InitParams *params = wxGetApp().init_params; - return Mcp::endpoint_port(params != nullptr ? params->mcp.port : 0, config->get("mcp_port")); -} - -// Where agents connect over HTTP. -static std::string mcp_url(const Mcp::McpEndpoint *endpoint, AppConfig *config) -{ - return "http://127.0.0.1:" + std::to_string(mcp_port(endpoint, config)) + "/mcp"; + return "http://127.0.0.1:" + std::to_string(Ops::mcp_port_shown()) + "/mcp"; } // The program a stdio setup runs. Inside an AppImage the executable path is a temporary mount. @@ -1460,9 +1361,8 @@ wxBoxSizer *PreferencesDialog::create_item_mcp_server(wxString title, wxString t wxBoxSizer *m_sizer = create_item_label(title, tooltip); // Checked while the server runs, also when --mcp started it for this session only. - const Mcp::McpEndpoint *endpoint = wxGetApp().mcp_endpoint(); auto checkbox = new ::CheckBox(m_parent); - checkbox->SetValue(app_config->get_bool("mcp_enabled") || (endpoint != nullptr && endpoint->serving())); + checkbox->SetValue(Ops::mcp_switch_shown()); checkbox->SetToolTip(tooltip); checkbox->SetName("mcp_enabled"); @@ -1547,7 +1447,7 @@ void PreferencesDialog::update_mcp_status(const std::string ¬e) m_mcp_status->Wrap(FromDIP(MCP_STATUS_WIDTH)); // While the server is off, the address it will listen on, dimmed. m_mcp_address->SetForegroundColour(serving ? primary : secondary); - m_mcp_address->SetLabel(from_u8(mcp_url(endpoint, app_config))); + m_mcp_address->SetLabel(from_u8(mcp_url())); m_mcp_status_dot->Refresh(); m_mcp_status->Refresh(); m_mcp_address->Refresh(); @@ -1563,7 +1463,7 @@ void PreferencesDialog::update_mcp_status(const std::string ¬e) wxBoxSizer *PreferencesDialog::create_item_mcp_port(wxString title, wxString tooltip) { wxBoxSizer *m_sizer = create_item_label(title, tooltip); - auto shown = std::make_shared(mcp_port(wxGetApp().mcp_endpoint(), app_config)); + auto shown = std::make_shared(Ops::mcp_port_shown()); auto input = new ::TextInput(m_parent, wxEmptyString, wxEmptyString, wxEmptyString, wxDefaultPosition, DESIGN_INPUT_SIZE, wxTE_PROCESS_ENTER); StateColor input_bg(std::pair(wxColour("#F0F0F1"), StateColor::Disabled), @@ -1706,7 +1606,7 @@ wxBoxSizer *PreferencesDialog::create_item_mcp_connect(wxString title, wxString } } if (wxTheClipboard->Open()) { - const std::string setup = Mcp::agent_setup(agent, transport, mcp_url(endpoint, app_config), token, mcp_executable()); + const std::string setup = Mcp::agent_setup(agent, transport, mcp_url(), token, mcp_executable()); wxTheClipboard->SetData(new wxTextDataObject(from_u8(setup))); wxTheClipboard->Close(); confirm(); @@ -2140,124 +2040,30 @@ void PreferencesDialog::create_items() // Window focus follows item creation order. so below code has to be in same order with UI // Create functions for custom controls to keep list clean // Tooltips added automatically from related title if its empty + // The rows of preferences come from the table of Operations/PreferenceOps.hpp, in its order and under its section + // titles (add_preference_rows()); the rows that store no preference of it are added here and in add_rows_after(). wxBoxSizer*sizer_page = new wxBoxSizer(wxVERTICAL); wxFlexGridSizer* g_sizer; // use same name on all sizers to make easier to ordering without renaming auto v_gap = FromDIP(4); + const auto add_tab = [&](PreferencesTab tab, const wxString& title) { + m_tab_index[tab] = m_pref_tabs->AppendItem(title); + f_sizers.push_back(new wxFlexGridSizer(1, 1, v_gap, 0)); + f_sizers.back()->AddGrowableCol(0, 1); + return f_sizers.back(); + }; + const auto end_tab = [&]() { + g_sizer->AddSpacer(FromDIP(10)); + sizer_page->Add(g_sizer, 0, wxEXPAND); + }; ////////////////////////// - //// GENERAL TAB + //// GENERAL TAB ///////////////////////////////////// - m_tab_index[PreferencesTab::General] = m_pref_tabs->AppendItem(_L("General")); - f_sizers.push_back(new wxFlexGridSizer(1, 1, v_gap, 0)); - g_sizer = f_sizers.back(); - g_sizer->AddGrowableCol(0, 1); + g_sizer = add_tab(PreferencesTab::General, _L("General")); - //// GENERAL > Settings - g_sizer->Add(create_item_title(_L("Settings")), 1, wxEXPAND); - - auto item_language = create_item_language_combobox(_L("Language"), ""); - g_sizer->Add(item_language); - - std::vectorUnits = {_L("Metric") + " (mm, g)", _L("Imperial") + " (in, oz)"}; - auto item_currency = create_item_combobox(_L("Units"), "", "use_inches", Units); - g_sizer->Add(item_currency); - - std::vector DefaultPage = {_L("Home"), _L("Prepare")}; - auto item_default_page = create_item_combobox(_L("Default page"), _L("Set the page opened on startup."), "default_page", DefaultPage); - g_sizer->Add(item_default_page); - -#ifdef _WIN32 - auto item_darkmode = create_item_darkmode(_L("Enable dark Mode"), "", "dark_color_mode"); - g_sizer->Add(item_darkmode); -#endif - - auto item_single_instance = create_item_checkbox(_L("Allow only one OrcaSlicer instance"), - #if __APPLE__ - _L("On OSX there is always only one instance of app running by default. However it is allowed to run multiple instances " - "of same app from the command line. In such case this settings will allow only one instance."), - #else - _L("If this is enabled, when starting OrcaSlicer and another instance of the same OrcaSlicer is already running, that instance will be reactivated instead."), - #endif - "single_instance"); - g_sizer->Add(item_single_instance); - - auto item_show_splash_scr = create_item_checkbox(_L("Show splash screen"), _L("Show the splash screen during startup."), "show_splash_screen"); - g_sizer->Add(item_show_splash_scr); - -#ifdef __linux__ - auto item_window_button_pos = create_item_checkbox(_L("Use window buttons on left side"), "", "window_buttons_on_left", _L("(Requires restart)")); - g_sizer->Add(item_window_button_pos); - - // TRN "GPU" is the graphics card; the option only matters on computers that have two of them. - auto item_discrete_gpu = create_item_checkbox(_L("Render on the discrete GPU"), - // TRN DRI_PRIME is an environment variable name and must stay as it is. - _L("On a computer with two GPUs, run OrcaSlicer on the discrete GPU instead of the one that drives the display. " - "Some Wayland systems cannot show frames rendered on the other GPU, or fail to open the window at all. " - "Turn this off if the 3D view stays empty; if OrcaSlicer no longer starts, start it once with DRI_PRIME=0 " - "in the environment to get back here."), - "prefer_discrete_gpu", _L("(Requires restart)")); - g_sizer->Add(item_discrete_gpu); -#endif - - //auto item_hints = create_item_checkbox(_L("Show \"Daily Tips\" after start"), page, _L("If enabled, useful hints are displayed at startup."), "show_daily_tips"); - //g_sizer->Add(item_hints); - - //// GENERAL > Features - g_sizer->Add(create_item_title(_L("Features")), 1, wxEXPAND); - - auto item_multi_machine = create_item_checkbox(_L("Multi device management"), _L("With this option enabled, you can send a task to multiple devices at the same time and manage multiple devices."), "enable_multi_machine", _L("(Requires restart)")); - g_sizer->Add(item_multi_machine); - -#ifdef SLIC3R_CAD - auto item_cad_feature = create_item_checkbox(_L("CAD feature (experimental)"), - _L("With this option enabled, the Design tab is shown, where models can be built and edited " - "parametrically. This feature is experimental and still under development."), - "enable_cad_feature", _L("(Requires restart)")); - // The checkbox is the saved preference; --cad turns the feature on for this run without changing it. - if (wxGetApp().cad_feature_set_for_run()) - item_cad_feature->Add(run_override_label(m_parent), 0, wxALIGN_CENTER | wxLEFT, FromDIP(5)); - g_sizer->Add(item_cad_feature); -#endif - - //// GENERAL > AI features - g_sizer->Add(create_item_title(_L("AI features")), 1, wxEXPAND); - - // The rows name the MCP server, a term most people don't know, so the group opens by saying what - // agents can do and who can connect. - m_mcp_intro = new ::Label(m_parent, ::Label::Body_13, - _L("Let AI agents such as Claude Code and Codex open and slice models, change settings and take screenshots " - "while OrcaSlicer is open. Only programs on this computer can connect.")); - m_mcp_intro->SetForegroundColour(wxColour("#6B6B6B")); - m_mcp_intro->Wrap(FromDIP(MCP_INTRO_WIDTH)); - auto item_mcp_intro = new wxBoxSizer(wxHORIZONTAL); - item_mcp_intro->AddSpacer(FromDIP(DESIGN_LEFT_MARGIN)); - item_mcp_intro->Add(m_mcp_intro, 0, wxBOTTOM, FromDIP(4)); - g_sizer->Add(item_mcp_intro); - - auto item_mcp_server = create_item_mcp_server(_L("MCP server"), - _L("Run a local server that AI agents connect to through the Model Context Protocol (MCP).")); - g_sizer->Add(item_mcp_server); - - auto item_mcp_port = create_item_mcp_port(_L("Server port"), _L("Local port of the MCP server.")); - g_sizer->Add(item_mcp_port); - - auto item_mcp_address = create_item_mcp_address(_L("Server address"), - _L("The address agents connect to over HTTP, with the access token.")); - g_sizer->Add(item_mcp_address); - - auto item_mcp_transport = create_item_mcp_transport(_L("Connection type"), - _L("How the agent you set up below connects to OrcaSlicer.")); - g_sizer->Add(item_mcp_transport); - - auto item_mcp_connect = create_item_mcp_connect(_L("Add to an agent"), - _L("Copy the setup that connects the chosen agent to OrcaSlicer.")); - g_sizer->Add(item_mcp_connect); - - auto item_mcp_python = create_item_mcp_python(_L("Python scripts"), - _L("Whether Python scripts are subject to the same permission checks as plugins, or bypass them.")); - g_sizer->Add(item_mcp_python); - update_mcp_status(); + //// GENERAL > Settings, Features, AI features + add_preference_rows(g_sizer, "general"); #if 0 g_sizer->Add(create_item_title(_L("Filament Grouping")), 1, wxEXPAND); @@ -2267,7 +2073,6 @@ void PreferencesDialog::create_items() g_sizer->Add(item_pop_up_filament_map_dialog); #endif - //// GENERAL > Clear my choice on ... g_sizer->Add(create_item_title(_L("Clear my choice on...")), 1, wxEXPAND); @@ -2286,379 +2091,37 @@ void PreferencesDialog::create_items() }); g_sizer->Add(item_restore_hide_pop_ups); - g_sizer->AddSpacer(FromDIP(10)); - sizer_page->Add(g_sizer, 0, wxEXPAND); + end_tab(); ////////////////////////// - //// FILES TAB + //// FILES TAB ///////////////////////////////////// - m_tab_index[PreferencesTab::Files] = m_pref_tabs->AppendItem(_L("Files")); - f_sizers.push_back(new wxFlexGridSizer(1, 1, v_gap, 0)); - g_sizer = f_sizers.back(); - g_sizer->AddGrowableCol(0, 1); + g_sizer = add_tab(PreferencesTab::Files, _L("Files")); - //// FILES > Project - g_sizer->Add(create_item_title(_L("Project")), 1, wxEXPAND); - std::vector projectLoadSettingsBehaviourOptions = {_L("Load All"), _L("Ask When Relevant"), _L("Always Ask"), _L("Load Geometry Only")}; - std::vector projectLoadSettingsConfigOptions = { OPTION_PROJECT_LOAD_BEHAVIOUR_LOAD_ALL, OPTION_PROJECT_LOAD_BEHAVIOUR_ASK_WHEN_RELEVANT, OPTION_PROJECT_LOAD_BEHAVIOUR_ALWAYS_ASK, OPTION_PROJECT_LOAD_BEHAVIOUR_LOAD_GEOMETRY }; - auto item_project_load = create_item_combobox(_L("Load behavior"), _L("Should printer/filament/process settings be loaded when opening a 3MF file?"), SETTING_PROJECT_LOAD_BEHAVIOUR, projectLoadSettingsBehaviourOptions, projectLoadSettingsConfigOptions); - g_sizer->Add(item_project_load); - - auto item_backup = create_item_backup(_L("Auto backup"), _L("Backup your project periodically to help with restoring from an occasional crash.")); - g_sizer->Add(item_backup); - - auto item_full_source_paths = create_item_checkbox(_L("Store full source file paths in projects"), - _L("If enabled, saved projects store the absolute path to imported source files (STEP/STL/...), so " - "\"Reload from disk\" still works when the source file is kept in a different folder than the project. " - "If disabled, only the filename is stored, which keeps projects portable and avoids embedding absolute paths."), - "export_sources_full_pathnames"); - g_sizer->Add(item_full_source_paths); - - //// FILES > Recent files - g_sizer->Add(create_item_title(_L("Recent files")), 1, wxEXPAND); - auto item_max_recent_count = create_item_input(_L("Maximum recent files"), "", _L("Maximum count of recent files"), "max_recent_count", [](wxString value) { - long max = 0; - if (value.ToLong(&max)) - wxGetApp().mainframe->set_max_recent_count(max); - }); - g_sizer->Add(item_max_recent_count); - - auto item_recent_models = create_item_checkbox(_L("Add STL/STEP files to recent files list"), "", "recent_models"); - g_sizer->Add(item_recent_models); - - //// FILES > Folder paths - g_sizer->Add(create_item_title(_L("Folder paths")), 1, wxEXPAND); - auto item_downloads = create_item_downloads(_L("Downloads folder"), _L("Target folder for downloaded items")); - g_sizer->Add(item_downloads); - - //// FILES > File import - g_sizer->Add(create_item_title(_L("File import")), 1, wxEXPAND); - g_sizer->Add(create_item_checkbox(_L("Ask how to handle unsupported characters in imported names"), - _L("Show the removal or replacement choices when original names contain unsupported characters."), - "import_names_cleanup_show_dialog")); - - //// FILES > 3MF import - g_sizer->Add(create_item_title(_L("3MF import")), 1, wxEXPAND); - g_sizer->Add(create_item_checkbox(_L("Show options when importing"), - _L("Show original-name and sorting options when importing a 3MF without project settings into the current project."), - "import_names_3mf_show_dialog")); - g_sizer->Add(create_item_checkbox(_L("Keep original names"), - _L("Use the body names stored in the imported file when it contains them."), "import_names_3mf_keep")); - auto item_gcodes_warning = create_item_checkbox(_L("Don't warn when loading 3MF with modified G-code"), "", "no_warn_when_modified_gcodes"); - g_sizer->Add(item_gcodes_warning); - - //// FILES > STEP import - g_sizer->Add(create_item_title(_L("STEP import")), 1, wxEXPAND); - auto item_step_dialog = create_item_checkbox( - _L("Show options when importing"), _L("If enabled, a parameter settings dialog will appear during STEP file import."), - "enable_step_mesh_setting", wxEmptyString, "import_export#dont-show-again" - ); - g_sizer->Add(item_step_dialog); - - auto item_step_linear = create_item_decimal_input(_L("Linear deflection"), "mm", _L("Linear deflection used when meshing imported STEP files.\nSmaller values produce higher-quality meshes but increase processing time.\nUsed as the default in the import dialog, or directly when the import dialog is disabled.\nDefault: 0.003 mm."), "linear_deflection", 0.001, 0.1, 3); - g_sizer->Add(item_step_linear); - - auto item_step_angle = create_item_decimal_input(_L("Angle deflection"), "", _L("Angle deflection used when meshing imported STEP files.\nSmaller values produce higher-quality meshes but increase processing time.\nUsed as the default in the import dialog, or directly when the import dialog is disabled.\nDefault: 0.5."), "angle_deflection", 0.01, 1.0, 2); - g_sizer->Add(item_step_angle); - - auto item_step_split = create_item_checkbox(_L("Split into multiple objects"), _L("If enabled, compound and compsolid shapes in imported STEP files are split into multiple objects.\nUsed as the default in the import dialog, or directly when the import dialog is disabled.\nDefault: enabled."), "is_split_compound"); - g_sizer->Add(item_step_split); - - g_sizer->Add(create_item_checkbox(_L("Keep original names"), - _L("Use the body names stored in the imported file when it contains them."), "import_names_step_keep")); - - //// FILES > AMF import - g_sizer->Add(create_item_title(_L("AMF import")), 1, wxEXPAND); - g_sizer->Add(create_item_checkbox(_L("Show options when importing"), - _L("Show body grouping, original-name and sorting options when importing geometry into the current project."), - "import_names_amf_show_dialog")); - g_sizer->Add(create_item_checkbox(_L("Keep original names"), - _L("Use the body names stored in the imported file when it contains them."), "import_names_amf_keep")); - - //// FILES > DRC export - g_sizer->Add(create_item_title(_L("DRC export")), 1, wxEXPAND); - auto item_draco_bits = create_item_spinctrl(_L("Quality level for Draco export"), "", - _L("bits"), - _L("Controls the quantization bit depth used when compressing the mesh to Draco format.\n" - "0 = lossless compression (geometry is preserved at full precision). Valid lossy values range from 8 to 30.\n" - "Lower values produce smaller files but lose more geometric detail; higher values preserve more detail at the cost of larger files."), - "drc_bits", DRC_BITS_MIN, DRC_BITS_MAX, nullptr, "import_export#drc" - ); - g_sizer->Add(item_draco_bits); - -#ifdef _WIN32 - // MSIX: associations are declared in the package manifest and defaults are - // managed by Windows Settings; the runtime registry toggles below cannot work. - // Show a minimal page that sends the user to Windows' Default Apps settings instead. - if (is_running_in_msix()) { - g_sizer->Add(create_item_title(_L("Associate files to OrcaSlicer")), 1, wxEXPAND); - - auto item_open_default_apps = create_item_button( - _L("File associations for the Microsoft Store version are managed by Windows Settings."), - _L("Open Windows Default Apps Settings"), "", "", - []() { wxLaunchDefaultBrowser("ms-settings:defaultapps"); }); - g_sizer->Add(item_open_default_apps); - } else { - //// FILES > Extensions - g_sizer->Add(create_item_title(_L("Associate files to OrcaSlicer")), 1, wxEXPAND); - - auto item_associate_3mf = create_item_checkbox(_L("Associate 3MF files to OrcaSlicer"), _L("If enabled, this sets OrcaSlicer as the default application to open 3MF files.") , "associate_3mf"); - g_sizer->Add(item_associate_3mf); - - auto item_associate_drc = create_item_checkbox(_L("Associate DRC files to OrcaSlicer"), _L("If enabled, sets OrcaSlicer as default application to open DRC files."), "associate_drc"); - g_sizer->Add(item_associate_drc); - - auto item_associate_stl = create_item_checkbox(_L("Associate STL files to OrcaSlicer"), _L("If enabled, this sets OrcaSlicer as the default application to open STL files.") , "associate_stl"); - g_sizer->Add(item_associate_stl); - - auto item_associate_step = create_item_checkbox(_L("Associate STEP files to OrcaSlicer"), _L("If enabled, this sets OrcaSlicer as the default application to open STEP files."), "associate_step"); - g_sizer->Add(item_associate_step); - - //// FILES > WebLinks - g_sizer->Add(create_item_title(_L("Associate web links to OrcaSlicer")), 1, wxEXPAND); - - auto associate_url_prusa = create_item_link_association(L"prusaslicer", "Printables.com"); - g_sizer->Add(associate_url_prusa); - - auto associate_url_bambu = create_item_link_association(L"bambustudio", "Makerworld.com"); - g_sizer->Add(associate_url_bambu); - - auto associate_url_cura = create_item_link_association(L"cura", "Thingiverse.com"); - g_sizer->Add(associate_url_cura); - } -#endif // _WIN32 - - g_sizer->AddSpacer(FromDIP(10)); - sizer_page->Add(g_sizer, 0, wxEXPAND); + //// FILES > Project, Recent files, Folder paths, File import, 3MF import, STEP import, AMF import, DRC export, + //// Extensions and WebLinks + add_preference_rows(g_sizer, "files"); + end_tab(); ////////////////////////// //// BEHAVIOUR TAB ///////////////////////////////////// - m_tab_index[PreferencesTab::Behaviour] = m_pref_tabs->AppendItem(_L("Behaviour")); - f_sizers.push_back(new wxFlexGridSizer(1, 1, v_gap, 0)); - g_sizer = f_sizers.back(); - g_sizer->AddGrowableCol(0, 1); - - //// BEHAVIOUR > Prepare - g_sizer->Add(create_item_title(_L("Prepare")), 1, wxEXPAND); - - std::vector FlushOptionLabels = {_L("All"),_L("Color"),_L("None")}; - std::vector FlushOptionValues = { "all","color change","disabled" }; - auto item_auto_flush = create_item_combobox(_L("Auto flush after changing..."), _L("Auto calculate flushing volumes when selected values changed"), "auto_calculate_flush", FlushOptionLabels, FlushOptionValues); - g_sizer->Add(item_auto_flush); - - auto item_auto_arrange = create_item_checkbox(_L("Auto arrange plate after cloning"), "", "auto_arrange"); - g_sizer->Add(item_auto_arrange); - - auto item_auto_reslice = create_item_auto_reslice( - _L("Auto slice after changes"), - _L("If enabled, OrcaSlicer will re-slice automatically whenever slicing-related settings change."), - _L("Delay in seconds before auto slicing starts, allowing multiple edits to be grouped. Use 0 to slice immediately.")); - g_sizer->Add(item_auto_reslice); - - auto item_primitive_dialog = create_item_checkbox(_L("Show options when adding a primitive"), - _L("If enabled, a dialog asks for the dimensions of a primitive shape before it is added."), "enable_primitive_size_dialog"); - g_sizer->Add(item_primitive_dialog); - - auto item_mix_print_high_low_temperature = create_item_checkbox(_L("Remove mixed temperature restriction"), _L("With this option enabled, you can print materials with a large temperature difference together."), "enable_high_low_temp_mixed_printing"); - g_sizer->Add(item_mix_print_high_low_temperature); - - auto item_remember_print_action = create_item_checkbox(_L("Remember last print action"), _L("If enabled, OrcaSlicer will remember the last selected option in the print button's dropdown (e.g. Print, Export plate sliced file, Export G-code file) and use it as the default on next startup."), "remember_print_action"); - g_sizer->Add(item_remember_print_action); - - //// BEHAVIOUR > Preview - g_sizer->Add(create_item_title(_L("Preview")), 1, wxEXPAND); - - // ORCA: view type the preview opens with - std::vector PreviewViewTypeLabels; - std::vector PreviewViewTypeValues; - for (const auto& [value, label] : GCodeViewer::default_view_type_choices()) { - PreviewViewTypeValues.push_back(value); - PreviewViewTypeLabels.push_back(from_u8(label)); - } - auto item_preview_view_type = create_item_combobox( - _L("Default view type"), - _L("The color scheme the sliced preview opens with.\n" - "Automatic: Filament for multi material prints, Line Type for single material ones.\n" - "Last used: the view type you selected last.\n" - "Any other value always opens that view type.\n" - "You can still switch the view type in the preview afterwards."), - "preview_default_view_type", PreviewViewTypeLabels, PreviewViewTypeValues); - g_sizer->Add(item_preview_view_type); - - auto item_reduced_detail_mode = create_item_combobox( - _L("Simplify preview while dragging"), - _L("What the sliced preview draws while you drag the camera or a preview slider, or zoom with the mouse wheel, so that large prints stay responsive. " - "The full toolpaths are restored as soon as you let go.\n" - "Off: the full toolpaths.\n" - "Solid model: the sliced objects and the prime tower as solid shapes in the colors of the current view, cut to the visible layer range, " - "with its bottom and top layers and the supports drawn as toolpaths. Negative volumes are not cut out. " - "A print made object by object, or one on a belt printer, keeps its full toolpaths.\n" - "Shell only: every layer without its sparse infill, internal solid infill, internal bridges and gap fill, which lie under the walls and skins. " - "Walls, top and bottom surfaces, bridges, supports and the prime tower are drawn whole, so the print looks the same from outside.\n" - "The bottom and top layers of the visible range are always drawn whole; a layer with no infill of its own, as with infill combination, takes the layers down to the nearest one with infill along."), - "preview_reduced_detail_mode", - {_L("Off"), _L("Solid model"), _L("Shell only")}, - {"off", "solid", "shell"}, - // apply the new mode immediately to the currently loaded preview - [](std::string value) { - if (Plater* plater = wxGetApp().plater()) { - if (GLCanvas3D* canvas = plater->get_preview_canvas3D()) { - canvas->get_gcode_viewer().set_reduced_detail_mode(value); - canvas->set_as_dirty(); - canvas->request_extra_frame(); - } - } - } - ); - g_sizer->Add(item_reduced_detail_mode); - - auto item_dim_previous_layers = create_item_checkbox( - _L("Dim lower layers"), - _L("When scrubbing the layer slider in the sliced preview, render the layers below the current one darkened so that only the layer being viewed is shown at full brightness."), - "preview_dim_previous_layers" - ); - g_sizer->Add(item_dim_previous_layers); - - auto item_dim_previous_layers_brightness = create_item_spinctrl( - _L("Dimmed layer brightness"), - "", - _L("%"), - _L("How brightly the dimmed layers are rendered when \"Dim lower layers\" is enabled.\n" - "99% is barely darkened, 0% renders them black. Capped at 99% because 100% would be the same as disabling the option."), - "preview_dim_previous_layers_brightness", - 0, - 99, - // ORCA: apply the new brightness immediately to the currently loaded preview - [](int value) { - if (Plater* plater = wxGetApp().plater()) { - if (GLCanvas3D* canvas = plater->get_preview_canvas3D()) { - canvas->get_gcode_viewer().set_dim_previous_layers_brightness(0.01f * value); - canvas->set_as_dirty(); - canvas->request_extra_frame(); - } - } - } - ); - g_sizer->Add(item_dim_previous_layers_brightness); - - //// BEHAVIOUR > Preset - g_sizer->Add(create_item_title(_L("Preset")), 1, wxEXPAND); - - auto item_remember_printer = create_item_checkbox(_L("Remember printer configuration"), _L("If enabled, Orca will remember and switch filament/process configuration for each printer automatically."), "remember_printer_config"); - g_sizer->Add(item_remember_printer); - - auto item_filament_preset_grouping = create_item_combobox(_L("Group user filament presets"), _L("Group user filament presets based on selection"), - "group_filament_presets", {_L("All"), _L("None"), _L("By type"), _L("By vendor")}, [](wxString value) {wxGetApp().plater()->sidebar().update_presets(Preset::TYPE_FILAMENT);}); - g_sizer->Add(item_filament_preset_grouping); + g_sizer = add_tab(PreferencesTab::Behaviour, _L("Behaviour")); // prevent burst calling on keyboard / spin events - m_filament_height_timer.Bind(wxEVT_TIMER, [this](wxTimerEvent&) { - wxGetApp().plater()->sidebar().update_filaments_area_height(); - UpdateSidebarLayout(); - }); - auto item_filament_area_height = create_item_spinctrl(_L("Optimize filaments area height for..."), "", _L("filaments"), _L("Optimizes filament area maximum height by chosen filament count."), - "filaments_area_preferred_count", 8, 99, [this](int value) {m_filament_height_timer.StartOnce(500);}); - g_sizer->Add(item_filament_area_height); + m_filament_height_timer.Bind(wxEVT_TIMER, [](wxTimerEvent&) { Ops::apply_preference("filaments_area_preferred_count"); }); - auto item_shared_profiles = create_item_checkbox(_L("Show shared profiles notification"), _L("Show a notification with a link to browse shared profiles when the selected printer is changed."), "show_shared_profiles_notification"); - g_sizer->Add(item_shared_profiles); - - //// BEHAVIOUR > Plugins - g_sizer->Add(create_item_title(_L("Plugins")), 1, wxEXPAND); - - auto item_plugin_pages_visible_count = create_item_spinctrl( - _L("Visible plugin pages"), - "", - _L("pages"), - _L("Number of plugin pages shown as fixed tabs before the remaining pages collapse into a dropdown on the last tab."), - SETTING_PLUGIN_PAGES_VISIBLE_COUNT, - PLUGIN_PAGES_VISIBLE_COUNT_MIN, - PLUGIN_PAGES_VISIBLE_COUNT_MAX, - [](int value) { wxGetApp().mainframe->plugin_pages().set_visible_page_count(value); } - ); - g_sizer->Add(item_plugin_pages_visible_count); - - //// BEHAVIOUR > Design -#ifdef SLIC3R_CAD - // Design-tab only, so it stays out of the way while the CAD feature is switched off. - if (wxGetApp().is_enable_cad_feature()) { - g_sizer->Add(create_item_title(_L("Design")), 1, wxEXPAND); - auto item_connector_face_glyph = create_item_checkbox(_L("Draw mate connectors as a face"), - _L("In the Design tab, draw a mate connector as a small face instead of the conventional " - "disc with a roll quadrant. A face shows its orientation at a glance, without learning the disc convention. " - "Turn this off for the conventional CAD representation."), "design_connector_face_glyph"); - g_sizer->Add(item_connector_face_glyph); - - // Saved WITH each design (it decides which loops are closed, i.e. what solid a project - // rebuilds into), so it applies to designs started from now on; an open design keeps - // the rule it was made with. - auto item_auto_close_sketch_loops = create_item_checkbox(_L("Auto-close sketch loops"), - _L("Treat sketch endpoints within 0.001 mm as one joint and weld the loop shut. " - "Off: only exactly coincident endpoints join, so a loop with a tiny gap is " - "shown as open instead of being closed for you. Saved with each design; " - "applies to designs started after the change."), - "auto_close_sketch_loops"); - g_sizer->Add(item_auto_close_sketch_loops); - } -#endif - - //// BEHAVIOUR > Speed dial - g_sizer->Add(create_item_title(_L("Speed dial")), 1, wxEXPAND); - - auto item_speed_dial = create_item_checkbox(_L("Open the Speed Dial from the keyboard"), - _L("When enabled, the Speed Dial keyboard shortcut (Space by default) opens the action search from any page."), - "enable_speed_dial"); - g_sizer->Add(item_speed_dial); - - auto item_speed_dial_recents = create_item_spinctrl( - _L("Recent actions"), - "", - // TRN Unit shown after the number of recent actions, as in "5 actions". - _L("actions"), - _L("How many recently launched actions to show at the top of the Speed Dial. Set to 0 to hide recent actions."), - SETTING_SPEED_DIAL_RECENT_COUNT, - SPEED_DIAL_RECENT_COUNT_MIN, - SPEED_DIAL_RECENT_COUNT_MAX); - g_sizer->Add(item_speed_dial_recents); - - g_sizer->AddSpacer(FromDIP(10)); - sizer_page->Add(g_sizer, 0, wxEXPAND); + //// BEHAVIOUR > Prepare, Preview, Preset, Plugins, Design, Speed dial + add_preference_rows(g_sizer, "behaviour"); + end_tab(); ////////////////////////// //// CONTROL TAB ///////////////////////////////////// - m_tab_index[PreferencesTab::Control] = m_pref_tabs->AppendItem(_L("Control")); - f_sizers.push_back(new wxFlexGridSizer(1, 1, v_gap, 0)); - g_sizer = f_sizers.back(); - g_sizer->AddGrowableCol(0, 1); + g_sizer = add_tab(PreferencesTab::Control, _L("Control")); //// CONTROL > Camera - g_sizer->Add(create_item_title(_L("Camera")), 1, wxEXPAND); - - std::vector CameraNavStyle = {_L("Default"), _L("Touchpad")}; - auto item_camera_nav_style = create_item_combobox(_L("Camera style"), _L("Select camera navigation style.\nDefault: LMB+move for rotation, RMB/MMB+move for panning.\nTouchpad: Alt+move for rotation, Shift+move for panning."), "camera_navigation_style", CameraNavStyle); - g_sizer->Add(item_camera_nav_style); - - auto camera_orbit_mult = create_camera_orbit_mult_input(_L("Orbit speed multiplier"), _L("Multiplies the orbit speed for finer or coarser camera movement.")); - g_sizer->Add(camera_orbit_mult); - - auto item_zoom_to_mouse = create_item_checkbox(_L("Zoom to mouse position"), _L("Zoom in towards the mouse pointer's position in the 3D view, rather than the 2D window center."), "zoom_to_mouse"); - g_sizer->Add(item_zoom_to_mouse); - - auto item_use_free_camera = create_item_checkbox(_L("Use free camera"), _L("If enabled, use free camera. If not enabled, use constrained camera."), "use_free_camera"); - g_sizer->Add(item_use_free_camera); - - auto reverse_mouse_zoom = create_item_checkbox(_L("Reverse mouse zoom"), _L("If enabled, reverses the direction of zoom with mouse wheel."), "reverse_mouse_wheel_zoom"); - g_sizer->Add(reverse_mouse_zoom); - - std::vector ButtonDragActions = {_L("None"), _L("Pan"), _L("Rotate")}; - auto item_left_mouse_drag = create_item_combobox(_L("Left Mouse Drag"), _L("Set the action that dragging the left mouse button should perform."), "left_mouse_drag_action", ButtonDragActions); - g_sizer->Add(item_left_mouse_drag); - auto item_middle_mouse_drag = create_item_combobox(_L("Middle Mouse Drag"), _L("Set the action that dragging the middle mouse button should perform."), "middle_mouse_drag_action", ButtonDragActions); - g_sizer->Add(item_middle_mouse_drag); - auto item_right_mouse_drag = create_item_combobox(_L("Right Mouse Drag"), _L("Set the action that dragging the right mouse button should perform."), "right_mouse_drag_action", ButtonDragActions); - g_sizer->Add(item_right_mouse_drag); + add_preference_rows(g_sizer, "control"); //// CONTROL > Keyboard g_sizer->Add(create_item_title(_L("Keyboard")), 1, wxEXPAND); @@ -2668,341 +2131,33 @@ void PreferencesDialog::create_items() }); g_sizer->Add(item_shortcuts); - g_sizer->AddSpacer(FromDIP(10)); - sizer_page->Add(g_sizer, 0, wxEXPAND); + end_tab(); ////////////////////////// //// GRAPHICS TAB ///////////////////////////////////// - m_tab_index[PreferencesTab::Graphics] = m_pref_tabs->AppendItem(_L("Graphics")); - f_sizers.push_back(new wxFlexGridSizer(1, 1, v_gap, 0)); - g_sizer = f_sizers.back(); - g_sizer->AddGrowableCol(0, 1); + g_sizer = add_tab(PreferencesTab::Graphics, _L("Graphics")); - //// GRAPHICS > General - g_sizer->Add(create_item_title(_L("General")), 1, wxEXPAND); - - auto smooth_normals = create_item_checkbox( - _L("Smooth normals"), - _L("Applies smooth normals to the model.\n\nRequires manual scene reload to take effect " - "(right-click on 3D view → \"Reload All\")."), - SETTING_OPENGL_PHONG_SMOOTH_NORMALS - ); - g_sizer->Add(smooth_normals); - - auto item_translucent_filaments = create_item_checkbox( - _L("Translucent filaments"), - _L("Draw the toolpaths of filaments whose color is partly transparent as see-through, as the 3D view draws their objects. Turn it off to draw every filament opaque."), - "preview_translucent_filaments" - ); - g_sizer->Add(item_translucent_filaments); - - //// GRAPHICS > Realistic view - g_sizer->Add(create_item_title(_L("Realistic View")), 1, wxEXPAND); - - auto item_realistic_phong = create_item_checkbox( - _L("Phong shading"), - _L("Uses Phong shading inside realistic view.") - , SETTING_OPENGL_REALISTIC_PHONG - ); - g_sizer->Add(item_realistic_phong); - - auto item_realistic_preview = create_item_checkbox( - _L("Enable in Preview"), - _L("Also applies realistic view to the Preview canvas, not just Prepare.\n" - "Preview draws the full toolpath geometry, so shadows and SSAO cost considerably" - " more there than on a plain model."), - SETTING_OPENGL_REALISTIC_PREVIEW - ); - g_sizer->Add(item_realistic_preview); - - auto item_realistic_ssao = create_item_checkbox( - _L("SSAO ambient occlusion"), - _L("Applies SSAO in realistic view."), - SETTING_OPENGL_PHONG_SSAO - ); - g_sizer->Add(item_realistic_ssao); - - std::vector ShadowsLabels = { _L("Off"), - // TRN Realistic-view shadow mode: the light stays fixed in the scene. - _L("Static"), - // TRN Realistic-view shadow mode: the light turns with the camera. - _L("Orbit") }; - std::vector ShadowsValues = { "off", "static", "orbit" }; - auto item_realistic_shadows = create_item_combobox( - _L("Shadows"), - _L("Renders cast shadows on the plate, other objects, and each object onto itself in realistic view.\n" - "Static: the light stays fixed in the world, so the shadows are only recomputed when the scene changes.\n" - "Orbit: the light turns with the camera, recomputing the shadows every frame the camera moves."), - SETTING_OPENGL_REALISTIC_SHADOWS, ShadowsLabels, ShadowsValues); - g_sizer->Add(item_realistic_shadows); - - auto item_realistic_gloss = create_item_checkbox( - _L("Glossy toolpaths"), - _L("Highlights the toolpaths in Preview as glossy plastic in realistic view.\n" - "Off, a translucent filament is matte and an opaque one keeps the highlight of the plain view."), - SETTING_OPENGL_REALISTIC_GLOSS - ); - g_sizer->Add(item_realistic_gloss); - - //// GRAPHICS > Outline - g_sizer->Add(create_item_title(_L("Outline")), 1, wxEXPAND); - - g_sizer->Add(create_item_checkbox( - _L("Persistent"), - _L("When Outline is enabled in the 3D canvas menu, outlines visible objects even when they are not selected."), - SETTING_OPENGL_OUTLINE_PERSISTENT)); - - auto add_outline_color_item = [this, g_sizer](const wxString& label, const wxString& tooltip, const std::string& key) { - auto sizer = create_item_label(label, tooltip); - auto button = new ColorSwatchButton(m_parent, from_u8(app_config->get(key))); - button->SetToolTip(tooltip); - button->Bind(wxEVT_BUTTON, [this, button, key](wxCommandEvent& event) { - event.Skip(); - ColorRGBA initial; - if (!decode_color(app_config->get(key), initial)) { - show_error(this, _L("The configured outline color is invalid.")); - return; - } - ColorPickerDialog dialog(this, initial, {}, false, button); - if (dialog.ShowModal() == wxID_OK && dialog.selection()) { - const ColorRGBA& color = std::get(*dialog.selection()); - const std::string value = encode_color(ColorRGB(color.r(), color.g(), color.b())); - app_config->set(key, value); - app_config->save(); - button->set_color(from_u8(value)); - // The scrolled window applies the scroll offset to the entire layout. - m_parent->Layout(); - m_parent->FitInside(); - } - }); - sizer->Add(button, 0, wxALIGN_CENTER_VERTICAL); - g_sizer->Add(sizer); - return button; - }; - m_persistent_outline_color_button = add_outline_color_item( - _L("Persistent color"), _L("Choose the color of the persistent outlines of unselected objects."), - SETTING_OPENGL_OUTLINE_COLOR); - m_persistent_outline_color_button->Enable(app_config->get_bool(SETTING_OPENGL_OUTLINE_PERSISTENT)); - add_outline_color_item(_L("Selection color"), _L("Choose the color of the outlines of selected objects."), - SETTING_OPENGL_SELECTION_OUTLINE_COLOR); - - //// GRAPHICS > Anti-aliasing - g_sizer->Add(create_item_title(_L("Anti-aliasing")), 1, wxEXPAND); - - auto item_antialiasing = create_item_combobox( - _L("MSAA Multiplier"), - _L("Set the Multi-Sample Anti-Aliasing level.\n" - "Higher values result in smoother edges, but the impact on performance is exponential.\n" - "Lower values improve performance, at the cost of jagged edges.\n" - "If disabled, its recommended to enable FXAA to reduce jagged edges with minimal performance impact.\n\n" - "Requires application restart."), - SETTING_OPENGL_AA_SAMPLES, - {_L("Disabled"), "2x", "4x", "8x", "16x"}, - {"0", "2", "4", "8", "16"} - ); - g_sizer->Add(item_antialiasing); - - auto item_fxaa = create_item_checkbox( - _L("FXAA post-processing"), - _L("Applies Fast Approximate Anti-Aliasing as a screen-space pass.\n" - "Useful for disabling or reducing the MSAA setting to improve performance.\n\n" - "Takes effect immediately."), - SETTING_OPENGL_FXAA_ENABLED - ); - g_sizer->Add(item_fxaa); - - //// GRAPHICS > FPS - g_sizer->Add(create_item_title(_L("FPS")), 1, wxEXPAND); - - auto item_fps_cap = create_item_spinctrl( - _L("FPS cap"), - _L("(0 = unlimited)"), - _L("FPS"), - _L("Limits viewport frame rate to reduce GPU load and power usage.\n" - "Set to 0 for unlimited frame rate."), - SETTING_OPENGL_FPS_CAP, - 0, - 240 - ); - g_sizer->Add(item_fps_cap); - - auto item_scene_cache = create_item_checkbox( - _L("Reuse the 3D scene while idle"), - _L("Skips redrawing the 3D scene when only the mouse cursor moves over the viewport, " - "and reuses the previous frame's scene instead. Reduces GPU load.\n" - "Disable it if the viewport shows stale or missing contents.\n\n" - "Takes effect immediately."), - SETTING_OPENGL_SCENE_CACHE - ); - g_sizer->Add(item_scene_cache); - - auto item_skip_identical_frames = create_item_checkbox( - _L("Skip unchanged frames"), - _L("Skips drawing a frame altogether when it would be identical to the one already on screen.\n" - "Only applies to frames that reuse the 3D scene, so it needs Reuse the 3D scene while idle.\n" - "Disable it if a hover highlight, tooltip or animation stops updating.\n\n" - "Takes effect immediately."), - SETTING_OPENGL_SKIP_IDENTICAL_FRAMES - ); - g_sizer->Add(item_skip_identical_frames); - if (m_skip_identical_frames_checkbox) m_skip_identical_frames_checkbox->Enable(app_config->get_bool(SETTING_OPENGL_SCENE_CACHE)); - - auto item_fps_overlay = create_item_checkbox( - _L("Show FPS overlay"), - _L("Displays rendering counts in the top-right corner of the viewport.") + "\n" + - _L("FPS: frames presented to the screen per second.") + "\n" + - _L("3D: frames per second that redrew the 3D scene."), - SETTING_OPENGL_SHOW_FPS_OVERLAY - ); - g_sizer->Add(item_fps_overlay); - - auto item_render_timings = create_item_checkbox( - _L("Show render timings"), - _L("Displays how many milliseconds each part of a frame that redraws the 3D scene takes, in the top-right corner of the viewport.") + "\n" + - _L("CPU: time spent issuing the drawing commands.") + "\n" + - _L("GPU: time the graphics card spent running them.") + "\n" + - _L("Adds a small overhead to each frame while enabled."), - SETTING_OPENGL_SHOW_RENDER_TIMINGS - ); - g_sizer->Add(item_render_timings); - - if (wxGetApp().is_editor()) { - auto item_benchmark = create_item_button(_L("3D scene benchmark"), _L("Run") + " " + dots, "", - _L("Replaces the current project with the OrcaSliced Combo, then measures the frame rate and render timings while the camera turns around it in Prepare and Preview, and while the layer slider moves through the sliced layers."), - [this]() { - EndModal(wxID_OK); - wxGetApp().CallAfter([] { run_scene_benchmark(); }); - }); - g_sizer->Add(item_benchmark); - } - - g_sizer->AddSpacer(FromDIP(10)); - sizer_page->Add(g_sizer, 0, wxEXPAND); + //// GRAPHICS > General, Realistic view, Outline, Anti-aliasing, FPS + add_preference_rows(g_sizer, "graphics"); + end_tab(); ////////////////////////// //// ONLINE TAB ///////////////////////////////////// - m_tab_index[PreferencesTab::Online] = m_pref_tabs->AppendItem(_L("Online")); - f_sizers.push_back(new wxFlexGridSizer(1, 1, v_gap, 0)); - g_sizer = f_sizers.back(); - g_sizer->AddGrowableCol(0, 1); + g_sizer = add_tab(PreferencesTab::Online, _L("Online")); - //// ONLINE > Connection - g_sizer->Add(create_item_title(_L("Connection")), 1, wxEXPAND); - - auto item_region = create_item_region_combobox(_L("Login region"), ""); - g_sizer->Add(item_region); - - auto item_stealth_mode = create_item_checkbox(_L("Stealth mode"), _L("This disables all cloud features, including Orca Cloud profile syncing. Users who prefer to work entirely offline can enable this option.\n\nNote: When Stealth Mode is enabled, your user profiles will not be backed up to Orca Cloud."), "stealth_mode"); - g_sizer->Add(item_stealth_mode); - - auto item_hide_login_side_panel = create_item_checkbox(_L("Hide login side panel"), _L("Hide the login side panel on the home page."), "hide_login_side_panel"); - g_sizer->Add(item_hide_login_side_panel); - - auto item_network_test = create_item_button(_L("Network test"), _L("Test") + " " + dots, "", _L("Open Network Test"), []() { - NetworkTestDialog dlg(wxGetApp().mainframe); - dlg.ShowModal(); - }); - g_sizer->Add(item_network_test); - - //// ONLINE > Cloud Providers - g_sizer->Add(create_item_title(_L("Cloud Providers")), 1, wxEXPAND); - - auto item_bambu_cloud = create_item_bambu_cloud(_L("Enable Bambu Cloud"), _L("Allow logging into Bambu Cloud alongside Orca Cloud. When enabled, a Bambu login section appears on the homepage.")); - g_sizer->Add(item_bambu_cloud); - - //// ONLINE > Update & sync - g_sizer->Add(create_item_title(_L("Update & sync")), 1, wxEXPAND); - - auto item_stable_updates = create_item_checkbox(_L("Check for stable updates only"), "", "check_stable_update_only"); - g_sizer->Add(item_stable_updates); - - auto item_user_sync = create_item_checkbox(_L("Auto sync user presets (Printer/Filament/Process)"), "", "sync_user_preset"); - g_sizer->Add(item_user_sync); - - if (app_config->get_stealth_mode()) { - if (m_bambu_cloud_checkbox) m_bambu_cloud_checkbox->Enable(false); - if (m_sync_user_preset_checkbox) m_sync_user_preset_checkbox->Enable(false); - } - - auto item_filament_sync_mode = create_item_combobox( - _L("Filament sync mode"), - _L("Choose whether sync updates both filament preset and color, or only color."), - "sync_ams_filament_mode", - {_L("Filament & Color"), _L("Color only")}); - g_sizer->Add(item_filament_sync_mode); - - auto item_system_sync = create_item_checkbox(_L("Update built-in presets automatically."), "", "sync_system_preset"); - g_sizer->Add(item_system_sync); - - auto item_token_storage = create_item_checkbox(_L("Use encrypted file for token storage"), - _L("Store authentication tokens in an encrypted file instead of the system keychain. (Requires restart)"), - SETTING_USE_ENCRYPTED_TOKEN_FILE); - g_sizer->Add(item_token_storage); - - //// ONLINE > Network plugin - g_sizer->Add(create_item_title(_L("Bambu network plug-in")), 1, wxEXPAND); - - auto item_enable_plugin = create_item_checkbox(_L("Enable Bambu network plug-in"), "", "installed_networking"); - g_sizer->Add(item_enable_plugin); - - auto item_plugin_version = create_item_network_plugin_version(_L("Network plug-in version"), _L("Select the network plug-in version to use")); - g_sizer->Add(item_plugin_version); - - g_sizer->AddSpacer(FromDIP(10)); - sizer_page->Add(g_sizer, 0, wxEXPAND); + //// ONLINE > Connection, Cloud Providers, Update & sync, Network plugin + add_preference_rows(g_sizer, "online"); + end_tab(); ////////////////////////// //// DEVELOPER TAB ///////////////////////////////////// - m_tab_index[PreferencesTab::Developer] = m_pref_tabs->AppendItem(_L("Developer")); - f_sizers.push_back(new wxFlexGridSizer(1, 1, v_gap, 0)); - g_sizer = f_sizers.back(); - g_sizer->AddGrowableCol(0, 1); + g_sizer = add_tab(PreferencesTab::Developer, _L("Developer")); - //// DEVELOPER > Settings - g_sizer->Add(create_item_title(_L("Settings")), 1, wxEXPAND); - - auto item_develop_mode = create_item_checkbox(_L("Developer mode"), "", "developer_mode", wxEmptyString, "option_mode#developer+mode"); - g_sizer->Add(item_develop_mode); - - auto item_ams_blacklist = create_item_checkbox(_L("Skip AMS blacklist check"), "", "skip_ams_blacklist_check"); - g_sizer->Add(item_ams_blacklist); - - auto item_show_unsupported = create_item_checkbox(_L("Show unsupported presets"), _L("Show incompatible/unsupported presets in the printer and filament dropdown lists. These presets cannot be selected."), "show_unsupported_presets"); - g_sizer->Add(item_show_unsupported); - - auto item_export_statistics = create_item_checkbox(_L("Export statistics with G-code"), - _L("If enabled, exporting a G-code file also writes its statistics as JSON next to it, as .statistics.json, " - "and an exported sliced 3MF file holds them inside: print time, filament and feature totals, " - "and the same per layer and per object."), - "export_statistics"); - g_sizer->Add(item_export_statistics); - - //// DEVELOPER > Experimental Features - g_sizer->Add(create_item_title(_L("Experimental Features")), 1, wxEXPAND); - - auto item_keep_painting = create_item_checkbox(_L("Keep painted feature after mesh change"), _L("Attempt to keep painted features (color/seam/support/fuzzy etc.) after changing the object mesh (such as cut/reload from disk/simplify/fix etc.)\nHighly experimental! Slow and may create artifact."), "keep_painting"); - g_sizer->Add(item_keep_painting); - - auto item_plugin_printer_agents = create_item_checkbox( - _L("Use printer agents instead of print hosts"), _L( - "Route print jobs for non-Bambu printers through printer plug-in agents instead of the classic print-host upload flow.\nWhen disabled, OrcaSlicer uses the legacy print-host behavior."), - "use_printer_agents"); - g_sizer->Add(item_plugin_printer_agents); - - //// DEVELOPER > Storage - - g_sizer->Add(create_item_title(_L("Storage")), 1, wxEXPAND); - auto item_allow_abnormal_storage = create_item_checkbox(_L("Allow Abnormal Storage"), _L("This allows the use of Storage that is marked as abnormal by the Printer.\nUse at your own risk, can cause issues!"), "allow_abnormal_storage"); - g_sizer->Add(item_allow_abnormal_storage); - - //// DEVELOPER > Log Level - g_sizer->Add(create_item_title(_L("Log Level")), 1, wxEXPAND); - auto log_level_list = std::vector{_L("fatal"), _L("error"), _L("warning"), _L("info"), _L("debug"), _L("trace")}; - auto loglevel_combox = create_item_loglevel_combobox(_L("Log Level"), _L("Log Level"), log_level_list); - g_sizer->Add(loglevel_combox); + //// DEVELOPER > Settings, Experimental Features, Storage, Log Level + add_preference_rows(g_sizer, "developer"); //// DEVELOPER > Debug #if !BBL_RELEASE_TO_PUBLIC @@ -3011,8 +2166,7 @@ void PreferencesDialog::create_items() g_sizer->Add(debug_page, 1, wxEXPAND); #endif - g_sizer->AddSpacer(FromDIP(10)); - sizer_page->Add(g_sizer, 0, wxEXPAND); + end_tab(); ///////////////////////////////////// ////////////////////////// @@ -3031,6 +2185,234 @@ void PreferencesDialog::create_items() sizer_page->Fit(m_parent); } +void PreferencesDialog::add_preference_rows(wxFlexGridSizer* g_sizer, const std::string& tab) +{ + std::string section; + for (const Ops::Preference& p : Ops::preferences()) { + if (p.tab != tab || (p.shown != nullptr && !p.shown())) + continue; + if (p.section != section) { + section = p.section; + g_sizer->Add(create_item_title(translated(section)), 1, wxEXPAND); + } + wxBoxSizer* row = p.own_row ? create_own_row(g_sizer, p) : create_preference_row(p); + if (row != nullptr) + g_sizer->Add(row); + add_rows_after(g_sizer, p, row); + } +} + +wxBoxSizer* PreferencesDialog::create_preference_row(const Ops::Preference& p) +{ + const wxString label = translated(p.label), tooltip = tooltip_of(p); + switch (p.kind) { + case Ops::PreferenceKind::Checkbox: return create_item_checkbox(label, tooltip, p.key, translated(p.note), from_u8(p.wiki)); + case Ops::PreferenceKind::Choice: { + std::vector labels; + std::vector values; + for (const auto& [value, choice] : p.choices) { + values.push_back(value); + labels.push_back(translated(choice)); + } + return create_item_combobox(label, tooltip, p.key, labels, values, [key = p.key](std::string) { Ops::apply_preference(key); }); + } + case Ops::PreferenceKind::Number: + // A decimal field's unit is a symbol, shown inside the field as it is. + if (p.decimals > 0) + return create_item_decimal_input(label, from_u8(p.unit), tooltip, p.key, *p.min, *p.max, p.decimals, from_u8(p.wiki)); + return create_item_spinctrl(label, translated(p.note), translated(p.unit), tooltip, p.key, int(*p.min), int(*p.max), + [this, key = p.key](int) { preference_changed(key); }, from_u8(p.wiki)); + case Ops::PreferenceKind::Text: break; + } + BOOST_LOG_TRIVIAL(error) << "Preferences: no row is built for " << p.key; + return nullptr; +} + +wxBoxSizer* PreferencesDialog::create_own_row(wxFlexGridSizer* g_sizer, const Ops::Preference& p) +{ + const wxString label = translated(p.label), tooltip = tooltip_of(p); + if (p.key == "language") + return create_item_language_combobox(label, tooltip); + if (p.key == "use_inches") { + std::vector units = {_L("Metric") + " (mm, g)", _L("Imperial") + " (in, oz)"}; + std::vector values; + for (const auto& choice : p.choices) + values.push_back(choice.first); + return create_item_combobox(label, tooltip, p.key, units, values); + } +#ifdef _WIN32 + if (p.key == "dark_color_mode") + return create_item_darkmode(label, tooltip, p.key); +#endif + if (p.key == "mcp_enabled") { + // The rows name the MCP server, a term most people don't know, so the group opens by saying what + // agents can do and who can connect. + m_mcp_intro = new ::Label(m_parent, ::Label::Body_13, + _L("Let AI agents such as Claude Code and Codex open and slice models, change settings and take screenshots " + "while OrcaSlicer is open. Only programs on this computer can connect.")); + m_mcp_intro->SetForegroundColour(wxColour("#6B6B6B")); + m_mcp_intro->Wrap(FromDIP(MCP_INTRO_WIDTH)); + auto item_mcp_intro = new wxBoxSizer(wxHORIZONTAL); + item_mcp_intro->AddSpacer(FromDIP(DESIGN_LEFT_MARGIN)); + item_mcp_intro->Add(m_mcp_intro, 0, wxBOTTOM, FromDIP(4)); + g_sizer->Add(item_mcp_intro); + return create_item_mcp_server(label, tooltip); + } + if (p.key == "mcp_port") + return create_item_mcp_port(label, tooltip); + if (p.key == "backup_switch") + return create_item_backup(label, tooltip); + if (p.key == "max_recent_count") + return create_item_input(label, "", tooltip, p.key, [key = p.key](wxString) { Ops::apply_preference(key); }); + if (p.key == "download_path") + return create_item_downloads(label, tooltip); + if (p.key == "auto_slice_after_change") + return create_item_auto_reslice(label, tooltip, tooltip_of(preference("auto_slice_change_delay_seconds"))); + if (p.key == "camera_orbit_mult") + return create_camera_orbit_mult_input(label, tooltip); + if (p.key == "region") + return create_item_region_combobox(label, tooltip); + if (p.key == SETTING_NETWORK_PLUGIN_VERSION) + return create_item_network_plugin_version(label, tooltip); + if (p.key == "log_severity_level") { + std::vector levels; + for (const auto& choice : p.choices) + levels.push_back(translated(choice.second)); + return create_item_loglevel_combobox(label, tooltip, levels); + } + // backup_interval and auto_slice_change_delay_seconds have their fields in their checkboxes' rows. + return nullptr; +} + +void PreferencesDialog::add_rows_after(wxFlexGridSizer* g_sizer, const Ops::Preference& p, wxBoxSizer* row) +{ + if (p.key == "enable_cad_feature") { + // The checkbox is the saved preference; --cad turns the feature on for this run without changing it. + if (wxGetApp().cad_feature_set_for_run()) + row->Add(run_override_label(m_parent), 0, wxALIGN_CENTER | wxLEFT, FromDIP(5)); + } else if (p.key == "mcp_port") { + auto item_mcp_address = create_item_mcp_address(_L("Server address"), + _L("The address agents connect to over HTTP, with the access token.")); + g_sizer->Add(item_mcp_address); + + auto item_mcp_transport = create_item_mcp_transport(_L("Connection type"), + _L("How the agent you set up below connects to OrcaSlicer.")); + g_sizer->Add(item_mcp_transport); + + auto item_mcp_connect = create_item_mcp_connect(_L("Add to an agent"), + _L("Copy the setup that connects the chosen agent to OrcaSlicer.")); + g_sizer->Add(item_mcp_connect); + + auto item_mcp_python = create_item_mcp_python(_L("Python scripts"), + _L("Whether Python scripts are subject to the same permission checks as plugins, or bypass them.")); + g_sizer->Add(item_mcp_python); + update_mcp_status(); + } else if (p.key == "drc_bits") { +#ifdef _WIN32 + // MSIX: associations are declared in the package manifest and defaults are + // managed by Windows Settings; the runtime registry toggles cannot work. + // Show a minimal page that sends the user to Windows' Default Apps settings instead. + if (is_running_in_msix()) { + g_sizer->Add(create_item_title(_L("Associate files to OrcaSlicer")), 1, wxEXPAND); + + auto item_open_default_apps = create_item_button( + _L("File associations for the Microsoft Store version are managed by Windows Settings."), + _L("Open Windows Default Apps Settings"), "", "", + []() { wxLaunchDefaultBrowser("ms-settings:defaultapps"); }); + g_sizer->Add(item_open_default_apps); + } +#endif // _WIN32 + } else if (p.key == "associate_step") { +#ifdef _WIN32 + //// FILES > WebLinks + g_sizer->Add(create_item_title(_L("Associate web links to OrcaSlicer")), 1, wxEXPAND); + + auto associate_url_prusa = create_item_link_association(L"prusaslicer", "Printables.com"); + g_sizer->Add(associate_url_prusa); + + auto associate_url_bambu = create_item_link_association(L"bambustudio", "Makerworld.com"); + g_sizer->Add(associate_url_bambu); + + auto associate_url_cura = create_item_link_association(L"cura", "Thingiverse.com"); + g_sizer->Add(associate_url_cura); +#endif // _WIN32 + } else if (p.key == SETTING_OPENGL_OUTLINE_PERSISTENT) { + auto add_outline_color_item = [this, g_sizer](const wxString& label, const wxString& tooltip, const std::string& key) { + auto sizer = create_item_label(label, tooltip); + auto button = new ColorSwatchButton(m_parent, from_u8(app_config->get(key))); + button->SetToolTip(tooltip); + button->Bind(wxEVT_BUTTON, [this, button, key](wxCommandEvent& event) { + event.Skip(); + ColorRGBA initial; + if (!decode_color(app_config->get(key), initial)) { + show_error(this, _L("The configured outline color is invalid.")); + return; + } + ColorPickerDialog dialog(this, initial, {}, false, button); + if (dialog.ShowModal() == wxID_OK && dialog.selection()) { + const ColorRGBA& color = std::get(*dialog.selection()); + const std::string value = encode_color(ColorRGB(color.r(), color.g(), color.b())); + app_config->set(key, value); + app_config->save(); + button->set_color(from_u8(value)); + // The scrolled window applies the scroll offset to the entire layout. + m_parent->Layout(); + m_parent->FitInside(); + } + }); + sizer->Add(button, 0, wxALIGN_CENTER_VERTICAL); + g_sizer->Add(sizer); + return button; + }; + m_persistent_outline_color_button = add_outline_color_item( + _L("Persistent color"), _L("Choose the color of the persistent outlines of unselected objects."), + SETTING_OPENGL_OUTLINE_COLOR); + m_persistent_outline_color_button->Enable(app_config->get_bool(SETTING_OPENGL_OUTLINE_PERSISTENT)); + add_outline_color_item(_L("Selection color"), _L("Choose the color of the outlines of selected objects."), + SETTING_OPENGL_SELECTION_OUTLINE_COLOR); + } else if (p.key == SETTING_OPENGL_SKIP_IDENTICAL_FRAMES) { + if (m_skip_identical_frames_checkbox) m_skip_identical_frames_checkbox->Enable(app_config->get_bool(SETTING_OPENGL_SCENE_CACHE)); + } else if (p.key == SETTING_OPENGL_SHOW_RENDER_TIMINGS) { + if (wxGetApp().is_editor()) { + auto item_benchmark = create_item_button(_L("3D scene benchmark"), _L("Run") + " " + dots, "", + _L("Replaces the current project with the OrcaSliced Combo, then measures the frame rate and render timings while the " + "camera turns around it in Prepare and Preview, and while the layer slider moves through the sliced layers."), + [this]() { + EndModal(wxID_OK); + wxGetApp().CallAfter([] { run_scene_benchmark(); }); + }); + g_sizer->Add(item_benchmark); + } + } else if (p.key == "hide_login_side_panel") { + auto item_network_test = create_item_button(_L("Network test"), _L("Test") + " " + dots, "", _L("Open Network Test"), []() { + NetworkTestDialog dlg(wxGetApp().mainframe); + dlg.ShowModal(); + }); + g_sizer->Add(item_network_test); + + //// ONLINE > Cloud Providers + g_sizer->Add(create_item_title(_L("Cloud Providers")), 1, wxEXPAND); + + auto item_bambu_cloud = create_item_bambu_cloud(_L("Enable Bambu Cloud"), + _L("Allow logging into Bambu Cloud alongside Orca Cloud. When enabled, a Bambu login section appears on the homepage.")); + g_sizer->Add(item_bambu_cloud); + } else if (p.key == "sync_user_preset") { + if (app_config->get_stealth_mode()) { + if (m_bambu_cloud_checkbox) m_bambu_cloud_checkbox->Enable(false); + if (m_sync_user_preset_checkbox) m_sync_user_preset_checkbox->Enable(false); + } + } +} + +void PreferencesDialog::preference_changed(const std::string& key) +{ + // prevent burst calling on keyboard / spin events + if (key == "filaments_area_preferred_count") + m_filament_height_timer.StartOnce(500); + else + Ops::apply_preference(key); +} + void PreferencesDialog::create_sync_page() { auto page = new wxWindow(this, wxID_ANY); @@ -3178,22 +2560,4 @@ wxBoxSizer* PreferencesDialog::create_debug_page() return bSizer; } -void PreferencesDialog::UpdateSidebarLayout() -{ - Plater* plater = wxGetApp().plater(); - if (!plater) return; - - Sidebar& sidebar = plater->sidebar(); - - sidebar.Freeze(); - - sidebar.Layout(); - //plater->Layout(); - //wxGetApp().mainframe->Layout(); - - sidebar.Thaw(); - - plater->PostSizeEvent(); -} - }} // namespace Slic3r::GUI diff --git a/src/slic3r/GUI/Preferences.hpp b/src/slic3r/GUI/Preferences.hpp index c241ad5f18..06c3b55ace 100644 --- a/src/slic3r/GUI/Preferences.hpp +++ b/src/slic3r/GUI/Preferences.hpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -29,6 +30,8 @@ namespace Slic3r { namespace GUI { +namespace Ops { struct Preference; } + #define DESIGN_GRAY900_COLOR wxColour("#363636") // Label color #define DESIGN_GRAY600_COLOR wxColour("#ACACAC") // Dimmed text color @@ -39,7 +42,7 @@ namespace Slic3r { namespace GUI { #define DESIGN_INPUT_SIZE wxSize(FromDIP(120), -1) #define DESIGN_LEFT_MARGIN 25 -// The tabs other dialogs and the Speed Dial's open_preferences open Preferences on. +// The tabs other dialogs and window_open {window: "preferences"} open Preferences on. enum class PreferencesTab { General, Files, Behaviour, Control, Graphics, Online, Developer }; class PreferencesDialog : public DPIDialog @@ -102,6 +105,8 @@ public: ::SpinInput *m_dim_previous_layers_brightness_input = {nullptr}; // Disabled while persistent outlines are off. wxWindow * m_persistent_outline_color_button = {nullptr}; + wxStaticText *m_download_path_text = {nullptr}; // the downloads folder, in its row + wxBoxSizer * m_download_path_row = {nullptr}; ::ComboBox * m_network_version_combo = {nullptr}; std::vector m_available_versions; @@ -114,7 +119,6 @@ public: wxBoxSizer *create_item_title(wxString title); wxBoxSizer *create_item_label(wxString label, const wxString tooltip = "", const wxString wiki_url = ""); - wxBoxSizer *create_item_combobox(wxString title, wxString tooltip, std::string param, std::vector vlist, std::function onchange = {}, const wxString wiki_url = ""); wxBoxSizer *create_item_combobox(wxString title, wxString tooltip, std::string param, std::vector vlist, std::vector config_name_index, std::function onchange = {}, const wxString wiki_url = ""); wxBoxSizer *create_item_region_combobox(wxString title, wxString tooltip); wxBoxSizer *create_item_language_combobox(wxString title, wxString tooltip); @@ -124,6 +128,8 @@ public: void set_dark_mode(); wxBoxSizer *create_item_button(wxString title, wxString title2, wxString tooltip, wxString tooltip2, std::function onclick, const wxString wiki_url = ""); wxBoxSizer *create_item_downloads(wxString title, wxString tooltip); + // Shows the downloads folder the app configuration holds in its row. Ops::apply_preference() calls it. + void show_download_path(); wxBoxSizer *create_item_input(wxString title, wxString title2, wxString tooltip, std::string param, std::function onchange = {}, const wxString wiki_url = ""); wxBoxSizer *create_item_spinctrl(wxString title, wxString title2, wxString side_label, wxString tooltip, std::string param, int min, int max, std::function onchange = nullptr, const wxString wiki_url = ""); wxBoxSizer *create_camera_orbit_mult_input(wxString title, wxString tooltip); @@ -145,11 +151,22 @@ public: #endif // WIN32 void create_items(); + // The rows of `tab`'s preferences (Ops::preferences()), in the table's order under their sections' titles, with + // the rows that go with them. + void add_preference_rows(wxFlexGridSizer *g_sizer, const std::string &tab); + // The row of a preference of the table's kinds, built from its entry. + wxBoxSizer *create_preference_row(const Ops::Preference &p); + // The row of a preference whose control is built by a function of its own (Ops::Preference::own_row); none for a + // preference whose control is in another's row. + wxBoxSizer *create_own_row(wxFlexGridSizer *g_sizer, const Ops::Preference &p); + // What the dialog adds after preference `p`'s row `row`: the rows of its section that store no preference of the + // table, and the state of controls that follow the rows built so far. + void add_rows_after(wxFlexGridSizer *g_sizer, const Ops::Preference &p, wxBoxSizer *row); + // What a number field's change of `key` does: Ops::apply_preference(), or later for the filament area's height. + void preference_changed(const std::string &key); void create_sync_page(); wxBoxSizer* create_debug_page(); - void UpdateSidebarLayout(); - // BBS void create_select_domain_widget(); diff --git a/src/slic3r/GUI/RecordingDialog.hpp b/src/slic3r/GUI/RecordingDialog.hpp index b41880e1e6..b198459216 100644 --- a/src/slic3r/GUI/RecordingDialog.hpp +++ b/src/slic3r/GUI/RecordingDialog.hpp @@ -34,7 +34,7 @@ boost::filesystem::path capture_folder(const Mcp::RecordingSettings& settings); // runs once the recording ends, from a built-in preset or field by field, and whether the .mkv stays beside // the MP4 it makes. A rail joins them, showing whether the second runs; it can't without an ffmpeg, and the // stage then says how to get one. Below them is the folder both files go in. Each control is named after the -// key of the command's parameter it sets, so an agent can set it with set_widget_value. +// key of the command's parameter it sets, so an agent can set it with widget_set_value. class RecordingDialog : public DPIDialog { public: diff --git a/src/slic3r/GUI/RecordingIndicator.cpp b/src/slic3r/GUI/RecordingIndicator.cpp index 177775ecef..3799090cb1 100644 --- a/src/slic3r/GUI/RecordingIndicator.cpp +++ b/src/slic3r/GUI/RecordingIndicator.cpp @@ -41,7 +41,7 @@ double pulse(double seconds) } // Runs Stop Recording once the mouse handler that calls this has returned: it hides the pill. -void stop_recording() { wxGetApp().CallAfter([] { NativeCommands::notify_result(NativeCommands::run("stop_recording")); }); } +void stop_recording() { wxGetApp().CallAfter([] { NativeCommands::notify_result(NativeCommands::run("recording_stop")); }); } } // namespace diff --git a/src/slic3r/GUI/RunScriptPanel.cpp b/src/slic3r/GUI/RunScriptPanel.cpp index 74e58522fd..700076f1b4 100644 --- a/src/slic3r/GUI/RunScriptPanel.cpp +++ b/src/slic3r/GUI/RunScriptPanel.cpp @@ -95,7 +95,7 @@ std::string starter_script() // Shift+Enter and Ctrl+Enter. format(_u8L("A line that starts with %1% starts a cell. %2% runs the cell at the cursor, %3% all of them."), "# %%", run_cell_key(), run_all_key()) + - "\nfrom orca.host import tools\ntools.call(\"list_objects\")\n"; + "\nfrom orca.host import tools\ntools.call(\"object_list\")\n"; } // The page's text: its own and the code editor's. @@ -914,7 +914,7 @@ bool RunScriptPanel::start_session() return false; } m_session = std::move(session); - m_session_file = m_file.empty() ? std::string("") : Mcp::path_to_utf8(m_file); + m_session_file = m_file.empty() ? std::string("") : Mcp::path_to_utf8(m_file); m_session_ending = false; m_timer.Start(100); send_session_state(); diff --git a/src/slic3r/GUI/RunScriptPanel.hpp b/src/slic3r/GUI/RunScriptPanel.hpp index 2a82908134..c94014494a 100644 --- a/src/slic3r/GUI/RunScriptPanel.hpp +++ b/src/slic3r/GUI/RunScriptPanel.hpp @@ -30,7 +30,7 @@ class RunScriptPane; // The Run Script panel: a dock pane under the 3D view (it can float) whose page (resources/web/dialog/RunScript) edits a // Python script in `# %%` cells and runs them, one at a time or the whole file, in a live session (PythonSession) hosted -// by the automation runtime as a person's run_script job. One per app, owned by GUI_App: the script's text, file and +// by the automation runtime as a person's script_run job. One per app, owned by GUI_App: the script's text, file and // unsaved state, the session and the recent scripts live here, so they survive the pane, which a main-window rebuild (a // language change) destroys and the panel builds again. The pane and everything in it are hidden from the automation // tools. UI thread. diff --git a/src/slic3r/GUI/Selection.cpp b/src/slic3r/GUI/Selection.cpp index 7209de73a0..05d37e5990 100644 --- a/src/slic3r/GUI/Selection.cpp +++ b/src/slic3r/GUI/Selection.cpp @@ -8,6 +8,7 @@ #include "Gizmos/GLGizmoBase.hpp" #include "Camera.hpp" #include "Plater.hpp" +#include "Operations/ObjectOps.hpp" #include "slic3r/Utils/UndoRedo.hpp" #include "libslic3r/LocalesUtils.hpp" @@ -36,6 +37,7 @@ #include "libslic3r/GCode/WipeTower.hpp" #include "libslic3r/Geometry/Circle.hpp" #include "slic3r/GUI/ObjectDataViewModel.hpp" +#include #include #include "slic3r/GUI/OpenGLManager.hpp" #include @@ -530,16 +532,19 @@ void Selection::remove_curr_plate() erase(); } -void Selection::clone(int numbers) +bool Selection::clone(int numbers, const std::function& pasted) { if (numbers <= 0) - return; + return true; wxGetApp().plater()->take_snapshot(std::string("Selection-clone")); copy_to_clipboard(); for (int i = 0; i < numbers; i++) { paste_from_clipboard(); + if (pasted && !pasted(i + 1)) + return false; } + return true; } void Selection::center() @@ -666,22 +671,12 @@ void Selection::set_auto_drop(bool enabled) if (!m_valid) return; - std::set object_idxs; - for (const auto& [obj_idx, inst_list] : m_cache.content) { - object_idxs.insert(obj_idx); - } - - std::string snapshot_text = (boost::format("%1%") % (enabled ? "Set Selection Auto-Drop Enabled" : "Set Selection Auto-Drop Disabled")).str(); - wxGetApp().plater()->take_snapshot(snapshot_text); - // auto_drop is shared by all instances of an object. - for (int obj_idx : object_idxs) { - ModelObject* object = m_model->objects[obj_idx]; - object->auto_drop = enabled; - } - - // update scene - wxGetApp().plater()->update(); + Ops::SetAutoDropArgs args; + for (const auto& [obj_idx, inst_list] : m_cache.content) + args.targets.objects.push_back(obj_idx); + args.auto_drop = enabled; + Ops::set_objects_auto_drop(args); } void Selection::add_all() diff --git a/src/slic3r/GUI/Selection.hpp b/src/slic3r/GUI/Selection.hpp index e35b71677f..1c36e5a989 100644 --- a/src/slic3r/GUI/Selection.hpp +++ b/src/slic3r/GUI/Selection.hpp @@ -7,6 +7,7 @@ #include "libslic3r/Technologies.hpp" #include "libslic3r/Point.hpp" +#include #include #include #include "libslic3r/BoundingBox.hpp" @@ -245,7 +246,9 @@ public: void add_curr_plate(); void add_object_from_idx(std::vector& object_idxs); void remove_curr_plate(); - void clone(int numbers = 1); + // Pastes `numbers` copies of the selection, in one "Selection-clone" undo step. `pasted(done)` is called after each + // copy; returning false stops there, and clone() returns false. + bool clone(int numbers = 1, const std::function& pasted = {}); void center(); void drop(); bool can_drop() const; diff --git a/src/slic3r/GUI/SyncAmsInfoDialog.cpp b/src/slic3r/GUI/SyncAmsInfoDialog.cpp index a007513766..a63c1d289f 100644 --- a/src/slic3r/GUI/SyncAmsInfoDialog.cpp +++ b/src/slic3r/GUI/SyncAmsInfoDialog.cpp @@ -259,22 +259,30 @@ void SyncAmsInfoDialog::deal_ok() return; } m_result.direct_sync = false; - m_result.sync_maps.clear(); - for (size_t i = 0; i < m_ams_mapping_result.size(); i++) { - auto temp_idx = m_ams_mapping_result[i].id; - if (temp_idx >= 0) { - auto &temp = m_result.sync_maps[temp_idx]; - temp.ams_id = m_ams_mapping_result[i].ams_id; - temp.slot_id = m_ams_mapping_result[i].slot_id; - } - else{ - BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << "check error: m_result.sync_maps:" << temp_idx; - } - } + m_result.sync_maps = ams_sync_maps(m_ams_mapping_result); } } -bool SyncAmsInfoDialog::get_is_double_extruder() +std::map ams_sync_maps(const std::vector &result) +{ + std::map sync_maps; + for (size_t i = 0; i < result.size(); i++) { + auto temp_idx = result[i].id; + if (temp_idx >= 0) { + auto &temp = sync_maps[temp_idx]; + temp.ams_id = result[i].ams_id; + temp.slot_id = result[i].slot_id; + } + else{ + BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << "check error: m_result.sync_maps:" << temp_idx; + } + } + return sync_maps; +} + +bool SyncAmsInfoDialog::get_is_double_extruder() { return ams_sync_double_extruder(); } + +bool ams_sync_double_extruder() { const auto &full_config = wxGetApp().preset_bundle->full_config(); size_t nozzle_nums = full_config.option("nozzle_diameter")->values.size(); @@ -1284,7 +1292,7 @@ void SyncAmsInfoDialog::sync_ams_mapping_result(std::vector &resul // A Filament Track Switch, once installed and ready, feeds both nozzles from one AMS set, // so the mapping collapses to a single dynamic panel and skips ext spools. -bool SyncAmsInfoDialog::has_selector(MachineObject *obj_) const +bool SyncAmsInfoDialog::has_selector(MachineObject *obj_) { if (!obj_) { DeviceManager *dev_manager = Slic3r::GUI::wxGetApp().getDeviceManager(); @@ -1302,29 +1310,10 @@ bool SyncAmsInfoDialog::do_ams_mapping(MachineObject *obj_) obj_->get_ams_colors(m_cur_colors_in_thumbnail); // try color and type mapping - const auto &full_config = wxGetApp().preset_bundle->full_config(); const auto &project_config = wxGetApp().preset_bundle->project_config; - size_t nozzle_nums = full_config.option("nozzle_diameter")->values.size(); m_filaments_map = wxGetApp().plater()->get_partplate_list().get_curr_plate()->get_real_filament_maps(project_config); - int filament_result = 0; - std::vector map_opt; // four values: use_left_ams, use_right_ams, use_left_ext, use_right_ext - if (nozzle_nums > 1) { - map_opt = {true, true, true, true}; // four values: use_left_ams, use_right_ams, use_left_ext, use_right_ext - if (has_selector(obj_)) { // Orca: with a Filament Track Switch the ext spools route through the switch — don't map them - map_opt[2] = false; - map_opt[3] = false; - } - filament_result = DevMappingUtil::ams_filament_mapping(obj_, m_filaments, m_ams_mapping_result, map_opt, std::vector(), - wxGetApp().app_config->get_bool("ams_sync_match_full_use_color_dist") ? false : true); - } - // single nozzle - else { - map_opt = {false, true, false, true}; // four values: use_left_ams, use_right_ams, use_left_ext, use_right_ext - filament_result = DevMappingUtil::ams_filament_mapping(obj_, m_filaments, m_ams_mapping_result, map_opt, std::vector(), - wxGetApp().app_config->get_bool("ams_sync_match_full_use_color_dist") ? false : true); - // auto_supply_with_ext(obj_->vt_slot); - } + const int filament_result = map_filaments_to_ams(obj_, m_filaments, m_ams_mapping_result); if (filament_result == 0) { print_ams_mapping_result(m_ams_mapping_result); @@ -1364,6 +1353,29 @@ bool SyncAmsInfoDialog::do_ams_mapping(MachineObject *obj_) return true; } +int map_filaments_to_ams(MachineObject *printer, const std::vector &filaments, std::vector &result) +{ + const auto &full_config = wxGetApp().preset_bundle->full_config(); + size_t nozzle_nums = full_config.option("nozzle_diameter")->values.size(); + + std::vector map_opt; // four values: use_left_ams, use_right_ams, use_left_ext, use_right_ext + if (nozzle_nums > 1) { + map_opt = {true, true, true, true}; // four values: use_left_ams, use_right_ams, use_left_ext, use_right_ext + // Orca: with a Filament Track Switch the ext spools route through the switch — don't map them + if (SyncAmsInfoDialog::has_selector(printer)) { + map_opt[2] = false; + map_opt[3] = false; + } + return DevMappingUtil::ams_filament_mapping(printer, filaments, result, map_opt, std::vector(), + wxGetApp().app_config->get_bool("ams_sync_match_full_use_color_dist") ? false : true); + } + // single nozzle + map_opt = {false, true, false, true}; // four values: use_left_ams, use_right_ams, use_left_ext, use_right_ext + return DevMappingUtil::ams_filament_mapping(printer, filaments, result, map_opt, std::vector(), + wxGetApp().app_config->get_bool("ams_sync_match_full_use_color_dist") ? false : true); + // auto_supply_with_ext(obj_->vt_slot); +} + void SyncAmsInfoDialog::deal_only_exist_ext_spool(MachineObject *obj_) { if (!obj_) return; @@ -2592,28 +2604,32 @@ void SyncAmsInfoDialog::set_default(bool hide_some) Fit(); } -void SyncAmsInfoDialog::reset_and_sync_ams_list() +namespace { + +// The type, the type shown, the vendor and the filament id of each filament slot's preset, as the sync dialog lists them. +struct SyncFilamentTypes { - BOOST_LOG_TRIVIAL(info) <<__FUNCTION__; - // for black list std::vector materials; std::vector brands; std::vector display_materials; - std::vector m_filaments_id; - auto preset_bundle = wxGetApp().preset_bundle; + std::vector filament_ids; +}; + +SyncFilamentTypes sync_filament_types() +{ + SyncFilamentTypes types; + auto preset_bundle = wxGetApp().preset_bundle; for (auto filament_name : preset_bundle->filament_presets) { for (int f_index = 0; f_index < preset_bundle->filaments.size(); f_index++) { PresetCollection *filament_presets = &wxGetApp().preset_bundle->filaments; Preset * preset = &filament_presets->preset(f_index); - int size = preset_bundle->filaments.size(); if (preset && filament_name.compare(preset->name) == 0) { std::string display_filament_type; std::string filament_type = preset->config.get_filament_type(display_filament_type); - std::string m_filament_id = preset->filament_id; - display_materials.push_back(display_filament_type); - materials.push_back(filament_type); - m_filaments_id.push_back(m_filament_id); + types.display_materials.push_back(display_filament_type); + types.materials.push_back(filament_type); + types.filament_ids.push_back(preset->filament_id); std::string m_vendor_name = ""; auto vendor = dynamic_cast(preset->config.option("filament_vendor")); @@ -2621,10 +2637,61 @@ void SyncAmsInfoDialog::reset_and_sync_ams_list() std::string vendor_name = vendor->values[0]; m_vendor_name = vendor_name; } - brands.push_back(m_vendor_name); + types.brands.push_back(m_vendor_name); } } } + return types; +} + +} // namespace + +std::vector ams_sync_filaments() +{ + const SyncFilamentTypes types = sync_filament_types(); + const auto &project_config = wxGetApp().preset_bundle->project_config; + // Mixed-color slots are virtual: they never occupy a tray, so they must not appear as AMS sync targets. + auto *is_mixed_opt = project_config.option("filament_is_mixed"); + std::vector filaments_map; + const bool use_double_extruder = ams_sync_double_extruder(); + if (use_double_extruder) + filaments_map = wxGetApp().plater()->get_partplate_list().get_curr_plate()->get_real_filament_maps(project_config); + BitmapCache bmcache; + std::vector filaments; + const int count = int(wxGetApp().plater()->get_extruders_colors().size()); + for (int extruder = 0; extruder < count; extruder++) { + if (extruder >= types.materials.size() || extruder >= types.display_materials.size()) + continue; + if (is_mixed_opt && extruder < (int) is_mixed_opt->values.size() && is_mixed_opt->values[extruder]) + continue; + if (use_double_extruder && filaments_map[extruder] != 1 && filaments_map[extruder] != 2) + continue; + auto colour = project_config.opt_string("filament_colour", (unsigned int) extruder); + unsigned char rgb[4]; + bmcache.parse_color4(colour, rgb); + auto colour_rgb = wxColour((int) rgb[0], (int) rgb[1], (int) rgb[2], (int) rgb[3]); + + FilamentInfo info; + info.id = extruder; + info.type = types.materials[extruder]; + info.brand = types.brands[extruder]; + info.filament_id = types.filament_ids[extruder]; + info.color = wxString::Format("#%02X%02X%02X%02X", colour_rgb.Red(), colour_rgb.Green(), colour_rgb.Blue(), + colour_rgb.Alpha()) + .ToStdString(); + filaments.push_back(info); + } + return filaments; +} + +void SyncAmsInfoDialog::reset_and_sync_ams_list() +{ + BOOST_LOG_TRIVIAL(info) <<__FUNCTION__; + // for black list + const SyncFilamentTypes types = sync_filament_types(); + const std::vector &materials = types.materials; + const std::vector &display_materials = types.display_materials; + auto preset_bundle = wxGetApp().preset_bundle; /*std::vector extruders; if (m_specify_plate_idx == -1) { extruders = wxGetApp().plater()->get_partplate_list().get_curr_plate()->get_used_extruders(); @@ -2645,7 +2712,7 @@ void SyncAmsInfoDialog::reset_and_sync_ams_list() m_sizer_ams_mapping->Clear(); m_materialList.clear(); - m_filaments.clear(); + m_filaments = ams_sync_filaments(); // Mixed-color slots are virtual: they never occupy a tray, so they must not appear as // AMS sync targets. @@ -2780,17 +2847,6 @@ void SyncAmsInfoDialog::reset_and_sync_ams_list() material_item->id = extruder; material_item->item = item; m_materialList[i] = material_item; - - // build for ams mapping - if (extruder < materials.size() && extruder >= 0) { - FilamentInfo info; - info.id = extruder; - info.type = materials[extruder]; - info.brand = brands[extruder]; - info.filament_id = m_filaments_id[extruder]; - info.color = wxString::Format("#%02X%02X%02X%02X", colour_rgb.Red(), colour_rgb.Green(), colour_rgb.Blue(), colour_rgb.Alpha()).ToStdString(); - m_filaments.push_back(info); - } } if (use_double_extruder) { //m_filament_left_panel->Show();//SyncAmsInfoDialog::reset_and_sync_ams_list() diff --git a/src/slic3r/GUI/SyncAmsInfoDialog.hpp b/src/slic3r/GUI/SyncAmsInfoDialog.hpp index 96afb7d714..b130cd32e2 100644 --- a/src/slic3r/GUI/SyncAmsInfoDialog.hpp +++ b/src/slic3r/GUI/SyncAmsInfoDialog.hpp @@ -231,7 +231,7 @@ public: void set_print_type(PrintFromType type) { m_print_type = type; }; bool do_ams_mapping(MachineObject *obj_); // Orca: true when a Filament Track Switch is installed and ready (drives the combined dynamic mapping view). - bool has_selector(MachineObject *obj_) const; + static bool has_selector(MachineObject *obj_); void deal_only_exist_ext_spool(MachineObject *obj_); void show_thumbnail_page(); bool get_ams_mapping_result(std::string &mapping_array_str, std::string &mapping_array_str2, std::string &ams_mapping_info); @@ -397,5 +397,17 @@ public: private: InputInfo m_input_info; }; +// The project's filaments as the sync dialog maps them to the printer's slots: each physical filament it lists, in its +// order, with its type, vendor, filament id and colour. UI thread. +std::vector ams_sync_filaments(); +// Maps `filaments` to the slots of `printer`'s AMS and external spools as the sync dialog first does, into `result`: +// DevMappingUtil::ams_filament_mapping()'s result code. UI thread. +int map_filaments_to_ams(MachineObject *printer, const std::vector &filaments, std::vector &result); +// The slot each filament of `result` maps to, by its index, as the dialog's Synchronize now takes them in Mapping. +std::map ams_sync_maps(const std::vector &result); +// Whether the dialog lays out the filaments of two nozzles: a printer of two nozzles whose current plate maps each +// filament to one of them. +bool ams_sync_double_extruder(); + }} // namespace Slic3r::GUI #endif // _STEP_MESH_DIALOG_H_ diff --git a/src/slic3r/GUI/Tab.cpp b/src/slic3r/GUI/Tab.cpp index 41c57e550e..13ec4716ea 100644 --- a/src/slic3r/GUI/Tab.cpp +++ b/src/slic3r/GUI/Tab.cpp @@ -5916,6 +5916,17 @@ void TabPrinter::extruders_count_changed(size_t extruders_count) } } +void TabPrinter::change_extruders_count(size_t extruders_count) +{ + const size_t old_extruders_count = m_extruders_count; + extruders_count_changed(extruders_count); + init_options_list(); // m_options_list should be updated before UI updating + update_dirty(); + // Orca: the variant switches (here, Process in the sidebar, ...) list one option per extruder. + if (m_extruders_count != old_extruders_count) + update_all_extruder_variants(); +} + void TabPrinter::append_option_line(ConfigOptionsGroupShp optgroup, const std::string opt_key, const std::string& label_path) { auto option = optgroup->get_option(opt_key, 0); @@ -6075,13 +6086,7 @@ if (is_marlin_flavor) size_t extruders_count = size_t(boost::any_cast(v)); wxTheApp->CallAfter([this, opt_key, value, extruders_count]() { if (opt_key == "extruders_count" || opt_key == "single_extruder_multi_material") { - const size_t old_extruders_count = m_extruders_count; - extruders_count_changed(extruders_count); - init_options_list(); // m_options_list should be updated before UI updating - update_dirty(); - // Orca: the variant switches (here, Process in the sidebar, ...) list one option per extruder. - if (m_extruders_count != old_extruders_count) - update_all_extruder_variants(); + change_extruders_count(extruders_count); if (opt_key == "single_extruder_multi_material") { // the single_extruder_multimaterial was added to force pages on_value_change(opt_key, value); // rebuild - let's make sure the on_value_change is not skipped @@ -7833,9 +7838,7 @@ bool Tab::can_transfer_changes_to(const std::string& preset_name) const return first_type(m_presets->get_edited_preset()) == first_type(*to_be_selected); } -// The unsaved changes UnsavedChangesDialog lists for a preset switch, all of which its Transfer moves: -// the changed options (key#index for one entry of a vector) that a settings page shows in the current mode. -static std::vector listed_dirty_options(const PresetCollection& presets) +std::vector listed_dirty_options(const PresetCollection& presets) { Search::SettingsIndex& index = wxGetApp().sidebar().settings_index(); index.sort_options_by_key(); diff --git a/src/slic3r/GUI/Tab.hpp b/src/slic3r/GUI/Tab.hpp index e21794652d..7dd95be15a 100644 --- a/src/slic3r/GUI/Tab.hpp +++ b/src/slic3r/GUI/Tab.hpp @@ -374,7 +374,7 @@ public: // How this tab's preset switches answer their unsaved-changes prompts: by a person in // UnsavedChangesDialog (Ask), or with the dialog's Transfer or Discard without showing it, for a - // caller that already has the answer (MCP's select_preset). A caller sets it around one switch. + // caller that already has the answer (MCP's preset_select). A caller sets it around one switch. enum class DirtyPresetAnswer { Ask, Transfer, Discard }; DirtyPresetAnswer m_dirty_preset_answer = DirtyPresetAnswer::Ask; @@ -602,6 +602,10 @@ protected: // Resolves the same object/global settings owner for navigation and availability descriptions. Tab* get_tab_for_option(const std::string& opt_key, Preset::Type type); +// The unsaved changes of `presets`' edited preset that UnsavedChangesDialog lists, all of which its Transfer moves: +// the changed options (key#index for one entry of a vector) that a settings page shows in the current mode. +std::vector listed_dirty_options(const PresetCollection& presets); + class TabPrint : public Tab { public: @@ -801,6 +805,9 @@ public: void update_pages(); // update m_pages according to printer technology void on_gcode_flavor_changed(); void extruders_count_changed(size_t extruders_count); + // What a change of the Extruders field (Multimaterial page) does: the count, then the options list, the dirty + // marks and the variant switches that follow it. + void change_extruders_count(size_t extruders_count); PageShp build_kinematics_page(); void build_unregular_pages(bool from_initial_build = false); void on_preset_loaded() override; diff --git a/src/slic3r/GUI/WebGuideDialog.cpp b/src/slic3r/GUI/WebGuideDialog.cpp index 033292c28d..aaa7ed7f74 100644 --- a/src/slic3r/GUI/WebGuideDialog.cpp +++ b/src/slic3r/GUI/WebGuideDialog.cpp @@ -23,9 +23,7 @@ #include #include #include -#include "slic3r/GUI/UnsavedChangesDialog.hpp" #include "slic3r/GUI/ParamsDialog.hpp" -#include "libslic3r/Semver.hpp" #include #include #include @@ -35,8 +33,10 @@ #include "libslic3r/Config.hpp" #include "libslic3r/Preset.hpp" #include "libslic3r/PresetBundle.hpp" -#include "libslic3r/PresetCacheFormat.hpp" #include "slic3r/GUI/GUI_App.hpp" +#include "slic3r/GUI/Operations/InstallOps.hpp" +#include "slic3r/GUI/Operations/Outcome.hpp" +#include "slic3r/GUI/Operations/PresetOps.hpp" #include #include "libslic3r_version.h" @@ -974,243 +974,15 @@ int GuideFrame::SaveProfile() return 0; } -static std::set get_new_added_presets(const std::map& old_data, const std::map& new_data) +// Applies the whole set the pages collected (SaveProfile()) as a Confirm does: Ops::apply_install_set() asks about +// the presets' unsaved changes, installs the vendor bundles, reloads the presets and selects a newly added printer. +bool GuideFrame::apply_config() { - auto get_aliases = [](const std::map& data) { - std::set old_aliases; - for (auto item : data) { - const std::string& name = item.first; - size_t pos = name.find("@"); - old_aliases.emplace(pos == std::string::npos ? name : name.substr(0, pos-1)); - } - return old_aliases; - }; - - std::set old_aliases = get_aliases(old_data); - std::set new_aliases = get_aliases(new_data); - std::set diff; - std::set_difference(new_aliases.begin(), new_aliases.end(), old_aliases.begin(), old_aliases.end(), std::inserter(diff, diff.begin())); - - return diff; -} - -static std::string get_first_added_preset(const std::map& old_data, const std::map& new_data) -{ - std::set diff = get_new_added_presets(old_data, new_data); - if (diff.empty()) - return std::string(); - return *diff.begin(); -} - -bool GuideFrame::apply_config(AppConfig *app_config, PresetBundle *preset_bundle, const PresetUpdater *updater, bool& apply_keeped_changes) -{ - const auto enabled_vendors = m_appconfig_new.vendors(); - const auto old_enabled_vendors = app_config->vendors(); - - const auto enabled_filaments = m_appconfig_new.has_section(AppConfig::SECTION_FILAMENTS) ? m_appconfig_new.get_section(AppConfig::SECTION_FILAMENTS) : std::map(); - const auto old_enabled_filaments = app_config->has_section(AppConfig::SECTION_FILAMENTS) ? app_config->get_section(AppConfig::SECTION_FILAMENTS) : std::map(); - - bool check_unsaved_preset_changes = false; - std::vector install_bundles; - std::vector remove_bundles; - for (const auto &it : enabled_vendors) { - if (it.second.size() > 0) { - if (!is_vendor_installed(it.first)) { - install_bundles.emplace_back(it.first); - } - } - } - - //add the removed vendor bundles - for (const auto &it : old_enabled_vendors) { - if (it.second.size() > 0) { - if (enabled_vendors.find(it.first) != enabled_vendors.end()) - continue; - if (is_vendor_installed(it.first)) { - remove_bundles.emplace_back(it.first); - } - } - } - - check_unsaved_preset_changes = (enabled_vendors != old_enabled_vendors) || (enabled_filaments != old_enabled_filaments); - wxString header = _L("The configuration package is changed in previous Config Guide"); - wxString caption = _L("Configuration package changed"); - int act_btns = ActionButtons::KEEP|ActionButtons::SAVE; - - if (check_unsaved_preset_changes && - !wxGetApp().check_and_keep_current_preset_changes(caption, header, act_btns, &apply_keeped_changes)) - return false; - - // If there are bundles to install, they will be installed by apply_vendor_config - if (!install_bundles.empty()) { - BOOST_LOG_TRIVIAL(info) << "Will install " << install_bundles.size() << " vendor bundles from resources"; - } else { - BOOST_LOG_TRIVIAL(info) << "No bundles need to be installed from resource directory"; - } - - // Not remove, because these bundles may be updated - //if (remove_bundles.size() > 0) { - // //remove unused bundles - // for (const auto &it : remove_bundles) { - // auto vendor_file = vendor_dir/(it + ".json"); - // auto sub_dir = vendor_dir/(it); - // if (fs::exists(vendor_file)) - // fs::remove(vendor_file); - // if (fs::exists(sub_dir)) - // fs::remove_all(sub_dir); - // } - //} else { - // BOOST_LOG_TRIVIAL(info) << "No bundles need to be removed"; - //} - - std::string preferred_model; - std::string preferred_variant; - PrinterTechnology preferred_pt = ptFFF; - auto get_preferred_printer_model = [preset_bundle, enabled_vendors, old_enabled_vendors](const std::string& bundle_name, std::string& variant) { - const auto config = enabled_vendors.find(bundle_name); - if (config == enabled_vendors.end()) - return std::string(); - - const VendorProfile & printer_profile = preset_bundle->vendors[bundle_name]; - const std::map>& model_maps = config->second; - //for (const auto& vendor_profile : preset_bundle->vendors) { - for (const auto& model_it: model_maps) { - if (model_it.second.size() > 0) { - variant = *model_it.second.begin(); - if (model_it.second.size() > 1) { - if (printer_profile.models.size() > 0) { - const VendorProfile::PrinterModel& printer_model = *std::find_if(printer_profile.models.begin(), printer_profile.models.end(), - [id = model_it.first](auto& m) { return m.id == id; }); - for (auto& vt : printer_model.variants) { - if (std::find(model_it.second.begin(), model_it.second.end(), vt.name) != model_it.second.end()) { variant = vt.name; break; } - } - } - else if (variant != PresetBundle::ORCA_DEFAULT_PRINTER_VARIANT){ - if (std::find(model_it.second.begin(), model_it.second.end(), PresetBundle::ORCA_DEFAULT_PRINTER_VARIANT) != model_it.second.end()) - variant = PresetBundle::ORCA_DEFAULT_PRINTER_VARIANT; - } - } - - const auto config_old = old_enabled_vendors.find(bundle_name); - if (config_old == old_enabled_vendors.end()) - return model_it.first; - const auto model_it_old = config_old->second.find(model_it.first); - if (model_it_old == config_old->second.end()) - return model_it.first; - else if (model_it_old->second != model_it.second) { - for (const auto& var : model_it.second) - if (model_it_old->second.find(var) == model_it_old->second.end()) { - variant = var; - return model_it.first; - } - } - } - } - //} - if (!variant.empty()) - variant.clear(); - return std::string(); - }; - // Orca "custom" printers are considered first, then 3rd party. - if (preferred_model = get_preferred_printer_model(PresetBundle::ORCA_DEFAULT_BUNDLE, preferred_variant); - preferred_model.empty()) { - for (const auto& bundle : enabled_vendors) { - if (bundle.first == PresetBundle::ORCA_DEFAULT_BUNDLE) { continue; } - if (preferred_model = get_preferred_printer_model(bundle.first, preferred_variant); - !preferred_model.empty()) - break; - } - } - - std::string first_added_filament; - auto get_first_added_material_preset = [this, app_config](const std::string& section_name, std::string& first_added_preset) { - if (m_appconfig_new.has_section(section_name)) { - // get first of new added preset names - const std::map& old_presets = app_config->has_section(section_name) ? app_config->get_section(section_name) : std::map(); - first_added_preset = get_first_added_preset(old_presets, m_appconfig_new.get_section(section_name)); - } - }; - // Not switch filament - //get_first_added_material_preset(AppConfig::SECTION_FILAMENTS, first_added_filament); - - // ORCA: functionality moved to PresetBundle::apply_vendor_config; keeping for future reference - // // For each @System filament, check if a vendor-specific override exists - // // in the loaded profiles. If so, replace the @System variant with the - // // override (e.g. replace "Generic ABS @System" with BBL "Generic ABS"). - // // When printers from the default bundle are also selected, keep @System - // // too since those printers need it. - // static const std::string system_suffix = " @System"; - // auto it_default = enabled_vendors.find(PresetBundle::ORCA_DEFAULT_BUNDLE); - // bool has_default_bundle_printer = it_default != enabled_vendors.end() && !it_default->second.empty(); - // bool has_filament_profiles = m_ProfileJson.contains("filament"); - - // // Check if any non-default vendor has selected printers - // bool has_vendor_printer = false; - // for (const auto& [vendor, models] : enabled_vendors) { - // if (vendor != PresetBundle::ORCA_DEFAULT_BUNDLE && !models.empty()) { - // has_vendor_printer = true; - // break; - // } - // } - - // std::map supplemented_filaments; - // for (const auto& [name, value] : enabled_filaments) { - // if (name.size() > system_suffix.size() && - // name.compare(name.size() - system_suffix.size(), system_suffix.size(), system_suffix) == 0) { - // std::string short_name = name.substr(0, name.size() - system_suffix.size()); - // if (has_vendor_printer && has_filament_profiles && m_ProfileJson["filament"].contains(short_name)) { - // supplemented_filaments[short_name] = value; - // BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << " Replacing @System filament: '" << name << "' -> '" << short_name << "'"; - // if (has_default_bundle_printer) { - // supplemented_filaments[name] = value; - // BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << " Also keeping '" << name << "' for default bundle printers"; - // } - // continue; - // } - // } - // supplemented_filaments[name] = value; - // } - - // //update the app_config - // app_config->set_section(AppConfig::SECTION_FILAMENTS, supplemented_filaments); - // app_config->set_vendors(m_appconfig_new); - - // if (check_unsaved_preset_changes) - // preset_bundle->load_presets(*app_config, ForwardCompatibilitySubstitutionRule::Enable, - // {preferred_model, preferred_variant, first_added_filament, std::string()}); - - // // If the active filament is not in the wizard-selected filaments, switch to the first - // // compatible wizard-selected filament. This handles the first-run case where load_presets - // // falls back to "Generic PLA" even though the user selected a different filament. - // bool active_filament_selected = supplemented_filaments.empty() - // || supplemented_filaments.count(preset_bundle->filament_presets.front()) > 0; - // if (!active_filament_selected) { - // for (const auto& [filament_name, _] : supplemented_filaments) { - // const Preset* preset = preset_bundle->filaments.find_preset(filament_name); - // if (preset && preset->is_visible && preset->is_compatible) { - // preset_bundle->filaments.select_preset_by_name(filament_name, true); - // preset_bundle->filament_presets.front() = preset_bundle->filaments.get_selected_preset_name(); - // break; - // } - // } - // } - - // // Update the selections from the compatibilty. - // preset_bundle->export_selections(*app_config); - - BOOST_LOG_TRIVIAL(info) << "calling apply_vendor_config from WebGuideDialog"; - // Call the Core library function to apply vendor configuration - // This handles bundle installation, filament @System substitution, AppConfig updates, and preset loading - if (!preset_bundle->apply_vendor_config( - enabled_vendors, - enabled_filaments, - app_config, - true, - preferred_model, - preferred_variant)) - return false; - - return true; + Ops::InstallSet set; + set.printers = m_appconfig_new.vendors(); + if (m_appconfig_new.has_section(AppConfig::SECTION_FILAMENTS)) + set.filaments = m_appconfig_new.get_section(AppConfig::SECTION_FILAMENTS); + return bool(Ops::apply_install_set(set, Ops::PresetChanges::Ask)); } bool GuideFrame::run() @@ -1237,20 +1009,9 @@ bool GuideFrame::run() int result = this->ShowModal(); if (result == wxID_OK) { - bool apply_keeped_changes = false; BOOST_LOG_TRIVIAL(info) << "GuideFrame returned ok"; - if (! this->apply_config(app.app_config, app.preset_bundle, app.preset_updater, apply_keeped_changes)) + if (! this->apply_config()) return false; - - if (apply_keeped_changes) - app.apply_keeped_preset_modifications(); - - app.app_config->set_legacy_datadir(false); - app.update_mode(); - if (Plater *plater = app.plater()) - plater->normalize_bed_types(false); - // BBS - //app.obj_manipul()->update_ui_from_settings(); BOOST_LOG_TRIVIAL(info) << "GuideFrame applied"; this->Close(); return true; @@ -1382,246 +1143,50 @@ int GuideFrame::GetFilamentInfo(const std::string& VendorDirectory, json& pFilaL return status; } -bool GuideFrame::BuildProfileJson(const PresetBundle& bundle, bool require_all_resource_vendors) +bool GuideFrame::BuildProfileDataFromPresetBundle() { + PresetBundle* pb = wxGetApp().preset_bundle; + if (!pb || pb->vendors.empty()) + return false; + // If rsrc_vendor_dir has vendors (profile JSONs, or the preset caches a + // packaged build ships instead) not covered by the app's bundle, the + // bundle is incomplete (e.g. dev env where data_dir/system only has + // OrcaFilamentLibrary+Custom). Fall back so the slow path reads both dirs. try { - // Models from vendor profiles - for (const auto& [vendor_id, vp] : bundle.vendors) { - for (const auto& model : vp.models) { - std::string nozzle_str; - for (const auto& v : model.variants) { - if (!nozzle_str.empty()) nozzle_str += ";"; - nozzle_str += v.name; - } - const std::string materials_str = boost::algorithm::join(model.default_materials, ";"); - boost::filesystem::path cover_path = - (boost::filesystem::path(resources_dir()) / "profiles" / vp.id / (model.id + "_cover.png")) - .make_preferred(); - if (!boost::filesystem::exists(cover_path)) - cover_path = - (boost::filesystem::path(resources_dir()) / "web/image/printer" / (model.id + "_cover.png")) - .make_preferred(); - - json entry; - entry["model"] = model.id; - entry["name"] = model.name; - entry["vendor"] = vp.id; - entry["nozzle_diameter"] = nozzle_str; - entry["materials"] = materials_str; - entry["cover"] = into_u8(file_url_from_path(cover_path)); - entry["nozzle_selected"] = ""; - entry["sub_path"] = ""; - m_ProfileJson["model"].push_back(entry); + for (const std::string& name : vendor_names_in(rsrc_vendor_dir)) { + if (pb->vendors.find(name) == pb->vendors.end()) { + BOOST_LOG_TRIVIAL(info) << "GuideFrame: vendor '" << name + << "' in resources but not in preset_bundle — falling back to JSON loading"; + return false; } } - - // Machine map: preset name -> {model, nozzle variant} - for (const Preset& p : bundle.printers()) { - if (!p.is_system || !p.vendor) continue; - const auto* printer_model = p.config.option("printer_model"); - const auto* printer_variant = p.config.option("printer_variant"); - if (!printer_model || printer_model->value.empty() || !printer_variant) continue; - - json mach; - mach["model"] = printer_model->value; - mach["nozzle"] = printer_variant->value; - m_ProfileJson["machine"][p.name] = mach; - } - - // Filament map from system filament presets (vendor/type already resolved in config) - const json& machines = m_ProfileJson["machine"]; - for (const Preset& p : bundle.filaments()) { - if (!p.is_system || !p.vendor) continue; - const auto* fila_vendor = p.config.option("filament_vendor"); - const auto* fila_type = p.config.option("filament_type"); - const auto* compat_printers = p.config.option("compatible_printers"); - - std::string vendor = (fila_vendor && !fila_vendor->values.empty()) ? fila_vendor->values[0] : ""; - std::string type = (fila_type && !fila_type->values.empty()) ? fila_type->values[0] : ""; - - std::string model_list; - if (compat_printers) { - for (const std::string& pname : compat_printers->values) { - auto it = machines.find(pname); - if (it != machines.end()) { - const std::string m = (*it)["model"]; - const std::string n = (*it)["nozzle"]; - model_list += "[" + m + "++" + n + "]"; - } - } - } - - json ff; - ff["name"] = p.name; - ff["sub_path"] = p.file; - ff["vendor"] = vendor; - ff["type"] = type; - ff["models"] = model_list; - ff["selected"] = 0; - m_ProfileJson["filament"][p.name] = ff; - } - - // Process list from visible system print presets - for (const Preset& p : bundle.prints()) { - if (!p.is_system || !p.vendor || !p.is_visible) continue; - json entry; - entry["name"] = p.name; - entry["sub_path"] = p.file; - m_ProfileJson["process"].push_back(entry); - } - - if (require_all_resource_vendors) { - // If rsrc_vendor_dir has vendors (profile JSONs, or the preset caches a - // packaged build ships instead) not covered by the current bundle, the - // bundle is incomplete (e.g. dev env where data_dir/system only has - // OrcaFilamentLibrary+Custom). Fall back so the slow path reads both dirs. - try { - for (const std::string& name : vendor_names_in(rsrc_vendor_dir)) { - if (bundle.vendors.find(name) == bundle.vendors.end()) { - BOOST_LOG_TRIVIAL(info) << "GuideFrame: vendor '" << name - << "' in resources but not in preset_bundle — falling back to JSON loading"; - reset_profile_json(); - return false; - } - } - } catch (const std::exception&) {} - } - - BOOST_LOG_TRIVIAL(info) << "GuideFrame: built profile data (" - << m_ProfileJson["model"].size() << " models, " - << m_ProfileJson["machine"].size() << " machines, " - << m_ProfileJson["filament"].size() << " filaments)"; - return !m_ProfileJson["machine"].empty(); + } catch (const std::exception&) {} + try { + json data = Ops::profile_data_from(*pb); + if (data["machine"].empty()) + return false; + for (const char* key : { "model", "machine", "filament", "process" }) + m_ProfileJson[key] = std::move(data[key]); + return true; } catch (const std::exception& e) { - BOOST_LOG_TRIVIAL(warning) << "GuideFrame::BuildProfileJson failed: " << e.what() + BOOST_LOG_TRIVIAL(warning) << "GuideFrame::BuildProfileDataFromPresetBundle failed: " << e.what() << " — falling back to JSON loading"; reset_profile_json(); return false; } } -bool GuideFrame::BuildProfileDataFromPresetBundle() -{ - PresetBundle* pb = wxGetApp().preset_bundle; - if (!pb || pb->vendors.empty()) - return false; - return BuildProfileJson(*pb, /*require_all_resource_vendors=*/true); -} - bool GuideFrame::BuildProfileDataFromVendors() { - try { - // Same vendor set and precedence as the JSON scan in LoadProfileData: a - // vendor in the user's system dir shadows the bundled one of that name. - // vendor_names_in names a vendor by its profile or, where a build ships - // preset caches instead, by its cache alone. - std::map vendor_sources; - for (const boost::filesystem::path& dir : { vendor_dir, rsrc_vendor_dir }) { - boost::system::error_code ec; - if (boost::filesystem::exists(dir, ec)) - for (const std::string& name : vendor_names_in(dir)) - vendor_sources.emplace(name, dir); // first dir wins - } - - // The load order: the filament library first, because the others' - // filaments inherit from it, then every versioned vendor — each loaded - // from the directory it was found in, so a vendor that is not installed - // is served from the shipped profiles. Each is stamped by name and - // version alone: a profile change requires a version bump, so those two - // determine content wherever the vendor's copy sits. - std::vector ordered; - json stamps = json::array(); - auto add_vendor = [&ordered, &stamps](const std::string& name, const boost::filesystem::path& dir) { - // The version a load from `dir` would serve: the profile's where one - // exists (a cache is only served while it covers the profile beside - // it), the cache's own stamp where the cache is the whole vendor. - // A profile without a version (blacklist.json) carries no presets - // and is passed over. - const boost::filesystem::path profile = dir / (name + ".json"); - std::string version; - if (boost::filesystem::exists(profile)) { - const Semver v = get_version_from_json(profile.string()); - if (! v.valid()) - return; - version = v.to_string(); - } else { - version = VendorCacheFile::peek_version((dir / (name + ".opc")).string(), name); - } - ordered.push_back({name, dir}); - stamps.push_back({name, version}); - }; - const std::string filament_library(PresetBundle::ORCA_FILAMENT_LIBRARY); - if (auto it = vendor_sources.find(filament_library); it != vendor_sources.end()) - add_vendor(filament_library, it->second); - for (const auto& [name, dir] : vendor_sources) - if (name != filament_library) - add_vendor(name, dir); - if (ordered.empty()) - return false; - - // What this function derives is a pure function of that stamped set, so - // the derived JSON is cached whole: a fresh cache makes an open one - // file read, with no bundle built and no preset installed. Stale or - // absent, the bundle is rebuilt below and the result written back. - const boost::filesystem::path cache_file = - boost::filesystem::path(Slic3r::data_dir()) / "cache" / "wizard_profile_data.json"; - try { - // Slurped whole and parsed from the buffer — nlohmann's fastest - // input path; a stream adapter costs real time on a multi-MB file. - boost::nowide::ifstream ifs(cache_file.string(), std::ios::binary); - if (ifs.is_open()) { - const std::string text{std::istreambuf_iterator(ifs), std::istreambuf_iterator()}; - json cached = json::parse(text); - if (cached.value("format", 0) == 1 && cached["vendors"] == stamps && - ! cached["profile"]["machine"].empty()) { - for (const char* key : { "model", "machine", "filament", "process" }) - m_ProfileJson[key] = std::move(cached["profile"][key]); - BOOST_LOG_TRIVIAL(info) << "GuideFrame: profile data served from " << cache_file; - return true; - } - } - } catch (const std::exception& e) { - BOOST_LOG_TRIVIAL(info) << "GuideFrame: rejecting cached profile data: " << e.what(); - } - - // Each vendor comes from its preset cache where one covers it, which is - // what makes this worth doing instead of the scan below. - PresetBundle bundle; - std::vector failed; - const std::string errors = bundle.load_vendors(ordered, ForwardCompatibilitySubstitutionRule::EnableSilent, - /*allow_cache=*/true, m_cancel_token.get(), &failed).second; - if (*m_cancel_token || bundle.vendors.empty()) - return false; - if (! errors.empty()) - BOOST_LOG_TRIVIAL(warning) << "GuideFrame: loading the vendors reported: " << errors; - // A vendor that failed to load sends this open to the scan below, which lists - // what it can read of every vendor. - if (! failed.empty()) - return false; - if (! BuildProfileJson(bundle, /*require_all_resource_vendors=*/false)) - return false; - - // Written through a temp file and moved into place, as the preset caches - // are: half a cache must never be readable. - try { - json out; - out["format"] = 1; - out["vendors"] = std::move(stamps); - json& profile = out["profile"]; - for (const char* key : { "model", "machine", "filament", "process" }) - profile[key] = m_ProfileJson[key]; - boost::filesystem::create_directories(cache_file.parent_path()); - if (const std::error_code ec = write_file_atomically(cache_file.string(), out.dump(-1, ' ', false, json::error_handler_t::ignore), /*binary=*/true)) - throw std::runtime_error(ec.message()); - } catch (const std::exception& e) { - BOOST_LOG_TRIVIAL(warning) << "GuideFrame: could not write the profile data cache: " << e.what(); - } - return true; - } catch (const std::exception& e) { - BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << " failed: " << e.what(); - reset_profile_json(); + // A refusal sends this open to the scan of the vendors' JSON files, which lists what it can read of every vendor. + Ops::Outcome data = Ops::printer_profile_data(m_cancel_token.get()); + if (!data) { + BOOST_LOG_TRIVIAL(info) << "GuideFrame: " << data.refusal().english(); return false; } + for (const char* key : { "model", "machine", "filament", "process" }) + m_ProfileJson[key] = data.value().at(key); + return true; } int GuideFrame::LoadProfileData() diff --git a/src/slic3r/GUI/WebGuideDialog.hpp b/src/slic3r/GUI/WebGuideDialog.hpp index 8853ee2661..6f8e369f64 100644 --- a/src/slic3r/GUI/WebGuideDialog.hpp +++ b/src/slic3r/GUI/WebGuideDialog.hpp @@ -103,7 +103,6 @@ public: void init_guide_paths(); void on_profile_loaded(); void notify_profile_loaded(); - bool BuildProfileJson(const PresetBundle& bundle, bool require_all_resource_vendors); bool BuildProfileDataFromPresetBundle(); bool BuildProfileDataFromVendors(); void reset_profile_json(); @@ -111,7 +110,7 @@ public: int GetFilamentInfo( std::string VendorDirectory,json & pFilaList, std::string filepath, std::string &sVendor, std::string &sType); - bool apply_config(AppConfig *app_config, PresetBundle *preset_bundle, const PresetUpdater *updater, bool& apply_keeped_changes); + bool apply_config(); bool run(); void StrReplace(std::string &strBase, std::string strSrc, std::string strDes); diff --git a/src/slic3r/Utils/FixModelByCgal.cpp b/src/slic3r/Utils/FixModelByCgal.cpp index 4f801ba8c1..54455f640a 100644 --- a/src/slic3r/Utils/FixModelByCgal.cpp +++ b/src/slic3r/Utils/FixModelByCgal.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -33,9 +34,18 @@ public: } // namespace -bool fix_model_with_cgal_gui(ModelObject &model_object, int volume_idx, GUI::ProgressDialog &progress_dialog, const wxString &msg_header, std::string &fix_result, bool keep_painting, - bool *modified) +bool fix_model_with_cgal(ModelObject &model_object, int volume_idx, + const std::function &report_progress, std::string &fix_result, + bool keep_painting, bool *modified) { + if (modified) + *modified = false; + // Asked once before the worker starts, so that a cancel given at once leaves every mesh as it is. + if (!report_progress(0, std::string())) { + fix_result.clear(); + return false; + } + // Keeps the backup manager from reading a mesh while the worker replaces it. SaveObjectGaurd backup_gaurd(model_object); @@ -99,14 +109,15 @@ bool fix_model_with_cgal_gui(ModelObject &model_object, int volume_idx, GUI::Pro }); while (!finished) { - std::unique_lock lock(mtx); - condition.wait_for(lock, std::chrono::milliseconds(250), [&progress] { return progress.updated; }); - // One percent short of the maximum, so that the dialog does not close itself. - if (!progress_dialog.Update(std::max(0, progress.percent - 1), msg_header + wxString::FromUTF8(progress.message))) + Progress shown; + { + std::unique_lock lock(mtx); + condition.wait_for(lock, std::chrono::milliseconds(250), [&progress] { return progress.updated; }); + shown = progress; + progress.updated = false; + } + if (!report_progress(shown.percent, shown.message)) canceled = true; - else - progress_dialog.Fit(); - progress.updated = false; } if (worker_thread.joinable()) @@ -118,4 +129,17 @@ bool fix_model_with_cgal_gui(ModelObject &model_object, int volume_idx, GUI::Pro return !canceled; } +bool fix_model_with_cgal_gui(ModelObject &model_object, int volume_idx, GUI::ProgressDialog &progress_dialog, + const wxString &msg_header, std::string &fix_result, bool keep_painting, bool *modified) +{ + const auto shown = [&progress_dialog, &msg_header](int percent, const std::string &what) { + // One percent short of the maximum, so that the dialog does not close itself. + if (!progress_dialog.Update(std::max(0, percent - 1), msg_header + wxString::FromUTF8(what))) + return false; + progress_dialog.Fit(); + return true; + }; + return fix_model_with_cgal(model_object, volume_idx, shown, fix_result, keep_painting, modified); +} + } // namespace Slic3r diff --git a/src/slic3r/Utils/FixModelByCgal.hpp b/src/slic3r/Utils/FixModelByCgal.hpp index e59e767223..b01d82c10e 100644 --- a/src/slic3r/Utils/FixModelByCgal.hpp +++ b/src/slic3r/Utils/FixModelByCgal.hpp @@ -1,6 +1,7 @@ #ifndef slic3r_GUI_Utils_FixModelByCgal_hpp_ #define slic3r_GUI_Utils_FixModelByCgal_hpp_ +#include #include #include @@ -12,7 +13,17 @@ class Model; class ModelObject; class Print; -// Return false if fixing was canceled. fix_result is empty on success; modified tells whether any mesh changed. +// Repairs the meshes of `model_object`'s parts, or of part `volume_idx` alone, on a worker thread while the calling +// thread waits. A painted modifier, which follows the mesh of its host, is left as it is. `progress` is called from the +// calling thread before the repair starts, then on every update of the repair's progress and at most 250 ms apart, with +// the percent done and the name of the part being repaired when there are several; returning false cancels. Parts +// repaired before a cancel or an error keep their new mesh. Returns false if the repair was cancelled. fix_result is +// empty on success, else why parts could not be repaired; modified tells whether any mesh changed. +bool fix_model_with_cgal(ModelObject &model_object, int volume_idx, + const std::function &progress, std::string &fix_result, + bool keep_painting, bool *modified = nullptr); + +// fix_model_with_cgal() shown in `progress_dlg`, whose message is `msg_header` followed by the part being repaired. extern bool fix_model_with_cgal_gui(ModelObject &model_object, int volume_idx, GUI::ProgressDialog &progress_dlg, const wxString &msg_header, std::string &fix_result, bool keep_painting, bool *modified = nullptr); diff --git a/src/slic3r/plugin/PluginAuditManager.hpp b/src/slic3r/plugin/PluginAuditManager.hpp index 3a1e09db2c..fa34be9040 100644 --- a/src/slic3r/plugin/PluginAuditManager.hpp +++ b/src/slic3r/plugin/PluginAuditManager.hpp @@ -22,7 +22,7 @@ struct PluginPermissions; inline constexpr const char* kThreadPermissionTarget = "thread"; // The audit identities of a Python script a person (the Run Script panel, --run) or an agent -// (run_script) starts. A script is judged as a plugin is, but has no install state to hold a grant: what +// (script_run) starts. A script is judged as a plugin is, but has no install state to hold a grant: what // the implicit rules don't allow is denied without a prompt, unless scripts run unrestricted // (set_scripts_unrestricted). No plugin has one of them as its key, so a plugin is never taken for a // script: a local plugin's key keeps only the letters, digits, '_', '-' and '.' of its file name diff --git a/src/slic3r/plugin/PluginOperations.hpp b/src/slic3r/plugin/PluginOperations.hpp index 20de4f943d..60ef9b138a 100644 --- a/src/slic3r/plugin/PluginOperations.hpp +++ b/src/slic3r/plugin/PluginOperations.hpp @@ -14,7 +14,7 @@ namespace Slic3r { // An operation a plugin offers to agents and scripts (D4): declared with orca.register_operation() while // the plugin loads, offered once the plugin has loaded, and gone when the plugin unloads. Agents -// reach it through search_tools and call_tool, scripts through orca.host.tools.call, as +// reach it through tool_search and tool_call, scripts through orca.host.tools.call, as // "plugin.."; it is never in tools/list. struct PluginOperation { diff --git a/src/slic3r/plugin/PythonPluginBridge.cpp b/src/slic3r/plugin/PythonPluginBridge.cpp index 93bda77cdb..f872efad62 100644 --- a/src/slic3r/plugin/PythonPluginBridge.cpp +++ b/src/slic3r/plugin/PythonPluginBridge.cpp @@ -740,7 +740,7 @@ not a capability.)pbdoc"); py::arg("changes") = true, R"pbdoc(Offer an operation to AI agents and scripts while OrcaSlicer loads your module. -It is reached as "plugin.." through call_tool and orca.host.tools.call once the plugin +It is reached as "plugin.." through tool_call and orca.host.tools.call once the plugin has loaded. handler, which is required, is called as handler(args) with the arguments as a dict, validated against schema (a JSON Schema object, or None for an operation that takes no arguments); it runs under the plugin's identity and permissions and returns a JSON value. Pass handler by position diff --git a/src/slic3r/plugin/PythonRunScope.hpp b/src/slic3r/plugin/PythonRunScope.hpp index 9d21a36009..cdb2ce1be4 100644 --- a/src/slic3r/plugin/PythonRunScope.hpp +++ b/src/slic3r/plugin/PythonRunScope.hpp @@ -25,7 +25,7 @@ enum class PythonRunThread { Callback, // a window callback of the run, on the UI thread }; -// One run_script run, shared by the thread that runs its code, the threads it starts, the pool tasks it submits and +// One script_run run, shared by the thread that runs its code, the threads it starts, the pool tasks it submits and // its window callbacks: who it runs as, its file, its tool bridge, the work it waits for before it ends, and whether // it still takes new work and opens UI. Runs can overlap, so everything a run changes is keyed by it. // @@ -42,7 +42,7 @@ public: // The file the code was read from; empty for code sent as text. const boost::filesystem::path& file() const { return m_file; } // A script's windows belong to its run ("script/"; '/' never occurs in a plugin key) and close when it ends; - // a plugin's run_script leaves them to the plugin, which closes them when it unloads. + // a plugin's script_run leaves them to the plugin, which closes them when it unloads. bool owns_ui() const; std::string ui_owner() const; // Lets the calling thread's audit scope read the folder of a script's file, which its imports come from, as a diff --git a/src/slic3r/plugin/PythonScriptRunner.cpp b/src/slic3r/plugin/PythonScriptRunner.cpp index 46eb252c56..b08d75cf9c 100644 --- a/src/slic3r/plugin/PythonScriptRunner.cpp +++ b/src/slic3r/plugin/PythonScriptRunner.cpp @@ -851,7 +851,7 @@ boost::filesystem::path utf8_path(const std::string& utf8) #endif } -// A file run names an existing file; any other name (, a bare traceback name) is code sent as text. +// A file run names an existing file; any other name (, a bare traceback name) is code sent as text. boost::filesystem::path run_file(const std::string& filename) { if (filename.empty() || filename.front() == '<') diff --git a/src/slic3r/plugin/PythonScriptRunner.hpp b/src/slic3r/plugin/PythonScriptRunner.hpp index 43955d8e99..c43c98c841 100644 --- a/src/slic3r/plugin/PythonScriptRunner.hpp +++ b/src/slic3r/plugin/PythonScriptRunner.hpp @@ -17,8 +17,8 @@ namespace Slic3r { class PythonRunScope; class PythonSession; -// A Python script a person or an agent starts (run_script, a .py in the Run Script dialog or -// --run), or a plugin's run_script: code run on the plugin interpreter without being packaged +// A Python script a person or an agent starts (script_run, a .py in the Run Script dialog or +// --run), or a plugin's script_run: code run on the plugin interpreter without being packaged // as a plugin. struct PythonRunRequest { @@ -33,8 +33,8 @@ struct PythonRunRequest std::string identity; // Shown in tracebacks. An existing file's path makes it a file run, which runs as `python file.py` would run // it: `__file__` and `sys.argv` name it, and its folder serves its imports. Any other name, such as the default - // , is code sent as text. - std::string filename = ""; + // , is code sent as text. + std::string filename = ""; // The run is interrupted as timed_out once it has run this long. std::chrono::milliseconds budget{std::chrono::minutes(5)}; // Polled while the code runs, from another thread; true interrupts it as cancelled. @@ -75,7 +75,7 @@ struct PythonSessionRequest std::string identity; // As PythonRunRequest::filename, fixed for the session: an existing file makes it a file session, whose works // run with `__file__`, `sys.argv` and its folder's imports, and whose first work installs its PEP 723 dependencies. - std::string filename = ""; + std::string filename = ""; // Bound to the module-level name `args`. nlohmann::json args = nlohmann::json::object(); // The session is stopped and ended as timed_out once it has run this long, measured from its start; 0 is none. diff --git a/src/slic3r/plugin/host/PluginHostApp.cpp b/src/slic3r/plugin/host/PluginHostApp.cpp index cacbdcd467..04c1025851 100644 --- a/src/slic3r/plugin/host/PluginHostApp.cpp +++ b/src/slic3r/plugin/host/PluginHostApp.cpp @@ -174,13 +174,13 @@ void host_bindings::register_app(py::module_& host) require_main_thread("project_path"); return GUI::into_u8(plater.get_project_filename(".3mf")); }, "Path of the project's .3mf file, where it was last opened from or saved to; empty while it has never been " - "saved. UI thread only: from a worker thread, where run_script scripts run, it raises RuntimeError.") + "saved. UI thread only: from a worker thread, where script_run scripts run, it raises RuntimeError.") .def("export_3mf_copy", &export_3mf_copy, py::arg("path"), "Write the current project, unsaved changes included, to path as a 3MF copy. The project's " "file name and saved state are not changed, and the signed-in account is not written as the designer. " "The path must end in .3mf (ValueError otherwise), and writing it goes through the same permission check " "as open(path, \"w\"). Raises RuntimeError while the 3D view is not ready yet. UI thread only: from a " - "worker thread, where run_script scripts run, it raises RuntimeError."); + "worker thread, where script_run scripts run, it raises RuntimeError."); host.def("plater", ¤t_plater, py::return_value_policy::reference, "The app's Plater, which holds the live project. Raises RuntimeError before the app's main window is up."); @@ -197,14 +197,14 @@ void host_bindings::register_app(py::module_& host) "The running app: version, build, mode, language, app_config_version (the version that wrote the app config " "before this run, empty when there was none), stealth_mode, is_signed_in (Orca Cloud), is_bambu_signed_in (Bambu Cloud), network_plugin_version (empty " "when the Bambu network plugin is not loaded) and network_plugin_error (empty unless it failed to load). " - "UI thread only: from a worker thread, where run_script scripts run, it raises RuntimeError."); + "UI thread only: from a worker thread, where script_run scripts run, it raises RuntimeError."); host.def("gl_info", &gl_info, "OpenGL vendor, renderer, version, glsl_version and core_profile of the 3D view; None before it has been created."); host.def("selected_printer", &selected_printer, "Agent, model_id, connection ('lan' or 'cloud'), online, connected and firmware of the printer selected in the " "device list; model_id and firmware are empty for non-Bambu agents. None when none is selected. Print hosts " "configured in the printer preset (OctoPrint and the like) are not in the device list. UI thread only: from " - "a worker thread, where run_script scripts run, it raises RuntimeError."); + "a worker thread, where script_run scripts run, it raises RuntimeError."); } } // namespace Slic3r diff --git a/src/slic3r/plugin/host/PluginHostTools.cpp b/src/slic3r/plugin/host/PluginHostTools.cpp index 610d8d78e3..b450b08a13 100644 --- a/src/slic3r/plugin/host/PluginHostTools.cpp +++ b/src/slic3r/plugin/host/PluginHostTools.cpp @@ -159,16 +159,16 @@ void register_tools(py::module_& host) py::arg("name"), py::arg("args") = py::none(), "Call the MCP tool `name` with `args` (a dict) and return its result as a dict. A call that outlives its " "reply budget returns {status: \"running\" | \"blocked_by_dialog\", job}, as it does for an agent; follow it " - "with call(\"wait\", {\"for\": \"job\", \"job\": ...}). An error result raises ToolError, whose details " + "with call(\"app_wait\", {\"for\": \"job\", \"job\": ...}). An error result raises ToolError, whose details " "hold the result's data. A person's or an agent's script calls tools from its own code and from the threads and " "pool tasks it starts, while its run lasts, but not from its window callbacks; a plugin calls from a " "Script worker, never the UI thread."); // Static, as pybind keeps a docstring by its pointer; it names the format version this build reads. static const std::string run_replay_doc = std::string("Run a replay ({\"orca_replay_version\": \"") + GUI::Mcp::REPLAY_VERSION + - "\", \"steps\": [...]}) as the run_replay tool does, and return its result. " + "\", \"steps\": [...]}) as the replay_run tool does, and return its result. " "`replay` is the replay as a dict or as its JSON text, which may hold comments as a replay file does; " - "`vars` override the replay's vars. For a replay file, call(\"run_replay\", {\"path\": ...})."; + "`vars` override the replay's vars. For a replay file, call(\"replay_run\", {\"path\": ...})."; tools.def( "run_replay", [tools](const py::object& replay, const py::object& vars) mutable { @@ -176,7 +176,7 @@ void register_tools(py::module_& host) args["replay"] = replay; if (!vars.is_none()) args["vars"] = vars; - return json_to_py(call_tool(tools, "run_replay", args)); + return json_to_py(call_tool(tools, "replay_run", args)); }, py::arg("replay"), py::arg("vars") = py::none(), run_replay_doc.c_str()); @@ -192,10 +192,13 @@ void register_tools(py::module_& host) } return json_to_py(commands); }, - "Every command call() reaches, as a list of {name, title, group, description, read_only, listed}: the tools, the " - "Speed Dial's commands and the Design tab's (with the CAD feature on), in the order the app adds them, then the " - "operations the loaded plugins offer (plugin..). title and description are in English; listed says " - "whether an agent's tool list shows it, read_only that it changes nothing. Any thread."); + "Every command call() reaches, as a list of {name, title, group, description, read_only, listed}: the app's " + "commands and the Design tab's (with the CAD feature on), in the order the app adds them, then the operations the " + "loaded plugins offer (plugin..). group is the heading of the command's place, the one its name " + "starts with (Objects for object_mirror, Plates for plate_slice) but for window_screenshot and " + "window_save_screenshot, which are under Recordings, replays and scripts; Design for a Design tab command and " + "Plugins for an operation. title and description are in English; listed says whether an agent's tool list shows " + "it, read_only that it changes nothing. Any thread."); tools.def( "describe", [tools](const std::string& name) mutable { @@ -217,9 +220,10 @@ void register_tools(py::module_& host) return json_to_py(entry); }, py::arg("name"), - "The command `name` as a dict: key, title, group, description, input_schema (the JSON Schema of its " - "arguments), examples when it has some ([{title, calls: [{tool, args}]}]), listed, in_palette (a person can " - "pick it in the Speed Dial), the access labels read_only, destructive, idempotent and open_world, guard " + "The command `name` as a dict: key, title, group (as list() gives it), description, input_schema (the JSON " + "Schema of its arguments), examples when it has some ([{title, calls: [{tool, args}]}]), listed, in_palette (it " + "has a tile of its own in the Speed Dial), tiles when it has some (the Speed Dial's tiles that run it with their " + "args), the access labels read_only, destructive, idempotent and open_world, guard " "(inspect, recover or mutate: what it may do behind a dialog), completion and operations. An unknown name " "raises ToolError, whose details hold did_you_mean, the closest names. Any thread."); } diff --git a/src/slic3r/plugin/host/PluginHostUi.cpp b/src/slic3r/plugin/host/PluginHostUi.cpp index bf55a64935..5570d720ff 100644 --- a/src/slic3r/plugin/host/PluginHostUi.cpp +++ b/src/slic3r/plugin/host/PluginHostUi.cpp @@ -90,7 +90,7 @@ CallablePtr make_holder(py::object obj) } // The script run the calling code's UI belongs to: the run bound to the thread when it owns its UI (a person's or an -// agent's script). None for a plugin's code, a plugin's run_script included, whose UI belongs to the plugin as always. +// agent's script). None for a plugin's code, a plugin's script_run included, whose UI belongs to the plugin as always. std::shared_ptr owning_run() { const PythonRunBinding& binding = current_python_run(); @@ -118,7 +118,7 @@ void ensure_ui_open(const std::shared_ptr& run) // Calls `call` under the GIL. A script run's callback runs inside that run (its identity, its UI owner, its thread // attribution), counted as one of its active callbacks so the run waits for it, and does nothing once the run's UI has -// closed. A callback runs on the UI thread, so it calls no tools (call_tool refuses a Callback binding). +// closed. A callback runs on the UI thread, so it calls no tools (call_tool() refuses a Callback binding). template void call_in_run(const std::shared_ptr& run, Call&& call) { diff --git a/tests/automation/test_command_catalog.cpp b/tests/automation/test_command_catalog.cpp index 98503dc2af..f5575eaa44 100644 --- a/tests/automation/test_command_catalog.cpp +++ b/tests/automation/test_command_catalog.cpp @@ -63,7 +63,7 @@ TEST_CASE("a sealed catalog refuses additions", "[CommandCatalog]") TEST_CASE("find sees added commands, lookup also a source's", "[CommandCatalog]") { CommandCatalog catalog; - catalog.add(command("slice")); + catalog.add(command("plate_slice")); catalog.add_source(std::make_unique("plugin.x.y")); catalog.seal(); @@ -72,9 +72,9 @@ TEST_CASE("find sees added commands, lookup also a source's", "[CommandCatalog]" REQUIRE(from_source != nullptr); CHECK(from_source->key == "plugin.x.y"); - const NativeCommand* added = catalog.find("slice"); + const NativeCommand* added = catalog.find("plate_slice"); REQUIRE(added != nullptr); - CHECK(catalog.lookup("slice").get() == added); + CHECK(catalog.lookup("plate_slice").get() == added); CHECK(catalog.lookup("plugin.x.z") == nullptr); REQUIRE(catalog.source_commands().size() == 1); @@ -99,9 +99,9 @@ TEST_CASE("a Design command's title is translated in the Design context, any oth REQUIRE(Slic3r::GUI::title_context(design) != nullptr); CHECK(std::string(Slic3r::GUI::title_context(design)) == "Design"); NativeCommand other; - other.key = "save_project"; + other.key = "project_save"; other.title = "Save project"; - other.group = "Commands"; + other.group = "The project"; CHECK(Slic3r::GUI::title_context(other) == nullptr); } @@ -119,6 +119,50 @@ TEST_CASE("the person's form is the call with no arguments", "[CommandCatalog]") CHECK(Mcp::silent_args({{"silent", true}, {"path", "a"}}) == json{{"path", "a"}}); } +TEST_CASE("a call with exactly a tile's arguments is the person's form", "[CommandCatalog]") +{ + // A command with a tile of its own, a tile that mirrors along X and one that collects a tab in the Speed Dial. + NativeCommand c = command("view_it", /*in_palette=*/true); + c.tiles = json::array({json{{"key", "view_x"}, {"title", "X"}, {"group", "View"}, {"icon", ""}, {"description", ""}, + {"args", {{"axis", "x"}}}}, + json{{"key", "view_tab"}, {"title", "Tab"}, {"group", "Commands"}, {"icon", ""}, + {"description", ""}, {"args", json::object()}, {"input", "tab"}}}); + CHECK(Mcp::person_form(c, json())); + CHECK(Mcp::person_form(c, json::object())); + CHECK(Mcp::person_form(c, {{"axis", "x"}})); + CHECK_FALSE(Mcp::person_form(c, {{"axis", "y"}})); + CHECK_FALSE(Mcp::person_form(c, {{"axis", "x"}, {"silent", true}})); + CHECK_FALSE(Mcp::person_form(c, {{"silent", true}})); + + // A tile that collects a value is no person's form: its value comes from the Speed Dial's second phase. + NativeCommand collects = command("go_to"); + collects.tiles = json::array({json{{"key", "go_to_tab"}, {"title", "Tab"}, {"group", "Commands"}, {"icon", ""}, + {"description", ""}, {"args", json::object()}, {"input", "tab"}}}); + CHECK_FALSE(Mcp::person_form(collects, json::object())); +} + +TEST_CASE("what the silent form requires is not asked of a person's form", "[CommandCatalog]") +{ + const json schema{{"type", "object"}, + {"properties", {{"path", {{"type", "string"}}}, {"save_as", {{"type", "boolean"}}}, {"overwrite", {{"type", "boolean"}}}}}, + {"required", {"path"}}}; + const json s = Mcp::with_silent(schema, {json::object(), {{"save_as", true}}}); + CHECK(s["if"] == json{{"not", {{"enum", json::array({json::object(), {{"save_as", true}}})}}}}); + CHECK(s["then"]["required"] == json::array({"path"})); + // The two person's forms and a silent one with what it requires. + CHECK(Mcp::validate_arguments(s, json::object()).empty()); + CHECK(Mcp::validate_arguments(s, {{"save_as", true}}).empty()); + CHECK(Mcp::validate_arguments(s, {{"path", "a.3mf"}}).empty()); + // Silent forms without it. + CHECK_THAT(Mcp::validate_arguments(s, {{"overwrite", true}}), ContainsSubstring("path")); + CHECK_THAT(Mcp::validate_arguments(s, {{"save_as", true}, {"overwrite", true}}), ContainsSubstring("path")); + CHECK_THAT(Mcp::validate_arguments(s, {{"silent", true}}), ContainsSubstring("path")); + + // The person's form with no arguments alone is written as a client's validator reads it most simply. + CHECK(Mcp::with_silent(schema)["if"] == json{{"minProperties", 1}}); + CHECK(Mcp::with_silent(schema, {json::object()})["if"] == json{{"minProperties", 1}}); +} + TEST_CASE("a two-form schema requires its arguments only when some are given", "[CommandCatalog]") { const json s = Mcp::with_silent({{"type", "object"}, @@ -139,17 +183,17 @@ TEST_CASE("a reference entry has the command's fields, and its examples and tile { NativeCommand c = command("export_it", true); c.title = "Export It"; - c.group = "Commands"; + c.group = "The project"; c.description = "Exports it."; c.input_schema = {{"type", "object"}, {"properties", {{"path", {{"type", "string"}}}}}}; c.guard = GuardClass::Recover; c.completion = CommandCompletion::Deferred; - c.operations = {"export_gcode"}; + c.operations = {"start_gcode_export"}; c.open_world = true; const json entry = Slic3r::GUI::command_reference(c); CHECK(entry == json{{"key", "export_it"}, {"title", "Export It"}, - {"group", "Commands"}, + {"group", "The project"}, {"description", "Exports it."}, {"input_schema", c.input_schema}, {"listed", false}, @@ -160,7 +204,7 @@ TEST_CASE("a reference entry has the command's fields, and its examples and tile {"open_world", true}, {"guard", "recover"}, {"completion", "deferred"}, - {"operations", json::array({"export_gcode"})}}); + {"operations", json::array({"start_gcode_export"})}}); const json call{{"tool", "export_it"}, {"args", {{"path", "a"}}}}; c.guard = GuardClass::Inspect; @@ -176,4 +220,16 @@ TEST_CASE("a reference entry has the command's fields, and its examples and tile c.tiles = json::array({json{{"key", "export_it_pdf"}, {"title", "Export as PDF"}, {"icon", ""}, {"description", ""}, {"args", {{"format", "pdf"}}}}}); CHECK(Slic3r::GUI::command_reference(c)["tiles"] == c.tiles); + + // What a person sees of its own tile, once it has any. + CHECK_FALSE(entry.contains("icon")); + CHECK_FALSE(entry.contains("input")); + CHECK_FALSE(entry.contains("tile_group")); + c.icon = "menu_save"; + c.input = "tab"; + c.tile_group = "Commands"; + const json shown = Slic3r::GUI::command_reference(c); + CHECK(shown["icon"] == "menu_save"); + CHECK(shown["input"] == "tab"); + CHECK(shown["tile_group"] == "Commands"); } diff --git a/tests/automation/test_mcp_core.cpp b/tests/automation/test_mcp_core.cpp index 45b663e8ec..f62e11e56b 100644 --- a/tests/automation/test_mcp_core.cpp +++ b/tests/automation/test_mcp_core.cpp @@ -139,7 +139,7 @@ TEST_CASE("a UI call that times out behind a native dialog names the dialog", "[ std::string error; json details; try { - invoker.run(GuardClass::Inspect, "get_app_state", [&] { ran = true; return json(); }, 100ms); + invoker.run(GuardClass::Inspect, "app_state", [&] { ran = true; return json(); }, 100ms); } catch (const ToolFailure& f) { error = f.what(); details = f.details; @@ -158,7 +158,7 @@ TEST_CASE("a UI call that times out behind a wx dialog keeps the busy message", UiInvoker invoker(ui, [] { return GuardState{}; }, {}, [&] { return dialogs; }); std::string error; try { - invoker.run(GuardClass::Inspect, "get_app_state", [] { return json(); }, 100ms); + invoker.run(GuardClass::Inspect, "app_state", [] { return json(); }, 100ms); } catch (const ToolFailure& f) { error = f.what(); } @@ -263,7 +263,7 @@ TEST_CASE("a recover call that targets outside the dialog applies the mutate gua auto attempt = [&]() -> std::string { auto fut = std::async(std::launch::async, [&]() -> std::string { try { - invoker.run(GuardClass::Recover, "click", [&] { + invoker.run(GuardClass::Recover, "widget_click", [&] { invoker.require_mutate(); return json(); }); @@ -286,7 +286,7 @@ TEST_CASE("a recover call that targets outside the dialog applies the mutate gua return invoker.run(GuardClass::Mutate, "outer", [&] { auto m = std::async(std::launch::async, [&]() -> std::string { try { - invoker.run(GuardClass::Recover, "click", [&] { + invoker.run(GuardClass::Recover, "widget_click", [&] { invoker.require_mutate(); return json(); }); @@ -516,7 +516,7 @@ TEST_CASE("a native dialog that the probe sees gets the native note", "[Mcp]") CHECK(h.jobs.wait(envelope.data["job"], 3000ms).has_value()); } -TEST_CASE("a native message box with buttons gets the answer_dialog note", "[Mcp]") +TEST_CASE("a native message box with buttons gets the dialog_answer note", "[Mcp]") { // As ModalTracker describes a message box whose buttons can be pressed (Windows, Linux). const json box = json::array({{{"title", "Plugin permission request"}, @@ -540,7 +540,7 @@ TEST_CASE("a native message box with buttons gets the answer_dialog note", "[Mcp REQUIRE(envelope.data["status"] == "blocked_by_dialog"); CHECK(envelope.data["dialogs"] == box); const std::string note = envelope.data.value("note", ""); - CHECK(note.find("answer_dialog") != std::string::npos); + CHECK(note.find("dialog_answer") != std::string::npos); CHECK(note.find("only a person") == std::string::npos); CHECK(h.jobs.wait(envelope.data["job"], 3000ms).has_value()); } @@ -596,11 +596,11 @@ TEST_CASE("a recover call that opens another modal returns blocked_by_dialog", " CHECK(h.jobs.wait(r.data["job"], 3000ms).has_value()); } -TEST_CASE("every mutate call is refused while a slice job runs, but cancel_job and recover tools run", "[Mcp]") +TEST_CASE("every mutate call is refused while a slice job runs, but job_cancel and recover tools run", "[Mcp]") { Harness h; std::atomic release{false}; - NativeCommand slice = tool("slice", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { + NativeCommand slice = tool("plate_slice", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { ctx.begin_operation(); while (!release) std::this_thread::sleep_for(10ms); @@ -608,8 +608,8 @@ TEST_CASE("every mutate call is refused while a slice job runs, but cancel_job a }); slice.budget_ms = 100; h.registry.add(slice); - h.registry.add(tool("new_project", GuardClass::Mutate, [](const json&, ToolContext&) { return ToolResult::ok(); })); - NativeCommand cancel = tool("cancel_job", GuardClass::Mutate, [&](const json&, ToolContext&) { + h.registry.add(tool("project_new", GuardClass::Mutate, [](const json&, ToolContext&) { return ToolResult::ok(); })); + NativeCommand cancel = tool("job_cancel", GuardClass::Mutate, [&](const json&, ToolContext&) { release = true; return ToolResult::ok(); }); @@ -618,15 +618,15 @@ TEST_CASE("every mutate call is refused while a slice job runs, but cancel_job a h.registry.add(tool("answer", GuardClass::Recover, [](const json&, ToolContext&) { return ToolResult::ok(); })); h.start(); - const ToolResult running = h.call("slice"); + const ToolResult running = h.call("plate_slice"); REQUIRE(running.data["status"] == "running"); - const ToolResult refused = h.call("new_project"); + const ToolResult refused = h.call("project_new"); CHECK(refused.is_error); - CHECK(refused.message.find("wait for it or stop it with cancel_job") != std::string::npos); + CHECK(refused.message.find("wait for it or stop it with job_cancel") != std::string::npos); CHECK_FALSE(h.call("answer").is_error); - CHECK_FALSE(h.call("cancel_job").is_error); + CHECK_FALSE(h.call("job_cancel").is_error); CHECK(h.jobs.wait(running.data["job"], 3000ms).has_value()); - CHECK_FALSE(h.call("new_project").is_error); + CHECK_FALSE(h.call("project_new").is_error); } TEST_CASE("a submitted call returns its job at once and runs on a job's thread", "[Mcp]") @@ -673,7 +673,7 @@ TEST_CASE("a submitted change is refused as a client's is while an operation run std::atomic release{false}; Harness h; SetOnExit let_go{release}; - NativeCommand slice = tool("slice", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { + NativeCommand slice = tool("plate_slice", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { ctx.begin_operation(); while (!release) std::this_thread::sleep_for(10ms); @@ -681,16 +681,16 @@ TEST_CASE("a submitted change is refused as a client's is while an operation run }); slice.budget_ms = 100; h.registry.add(slice); - h.registry.add(tool("new_project", GuardClass::Mutate, [](const json&, ToolContext&) { return ToolResult::ok(); })); + h.registry.add(tool("project_new", GuardClass::Mutate, [](const json&, ToolContext&) { return ToolResult::ok(); })); h.start(); - const ToolResult running = h.call("slice"); + const ToolResult running = h.call("plate_slice"); REQUIRE(running.data["status"] == "running"); - const ToolResult client = h.call("new_project"); + const ToolResult client = h.call("project_new"); REQUIRE(client.is_error); // No job starts, and the refusal comes at once, on the calling thread. std::optional refusal; - CHECK(h.core->submit(*h.registry.find("new_project"), json::object(), [&refusal](const ToolResult& r) { refusal = r; }).empty()); + CHECK(h.core->submit(*h.registry.find("project_new"), json::object(), [&refusal](const ToolResult& r) { refusal = r; }).empty()); REQUIRE(refusal.has_value()); CHECK(refusal->is_error); CHECK(refusal->message == client.message); @@ -699,7 +699,7 @@ TEST_CASE("a submitted change is refused as a client's is while an operation run CHECK(h.jobs.wait(running.data["job"], 3000ms).has_value()); h.core->shutdown(); bool called = false; - CHECK(h.core->submit(*h.registry.find("new_project"), json::object(), [&called](const ToolResult&) { called = true; }).empty()); + CHECK(h.core->submit(*h.registry.find("project_new"), json::object(), [&called](const ToolResult&) { called = true; }).empty()); CHECK_FALSE(called); } @@ -813,14 +813,14 @@ TEST_CASE("the call observer hears inline, job and child calls, and not calls re NativeCommand look = tool("look", GuardClass::Inspect, [](const json&, ToolContext&) { return ToolResult::ok(); }); look.inline_call = true; h.registry.add(look); - h.registry.add(tool("click", GuardClass::Recover, [](const json&, ToolContext& ctx) { + h.registry.add(tool("widget_click", GuardClass::Recover, [](const json&, ToolContext& ctx) { // A ref resolved to its locator, as the GUI tools record it. ctx.set_journal_args({{"target", {{"label", "Slice"}}}}); return ToolResult::error("gone"); })); - h.registry.add(tool("replay", GuardClass::Mutate, [](const json&, ToolContext& ctx) { return ctx.call_child("click", json::object()); })); + h.registry.add(tool("replay", GuardClass::Mutate, [](const json&, ToolContext& ctx) { return ctx.call_child("widget_click", json::object()); })); std::atomic release{false}; - NativeCommand slice = tool("slice", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { + NativeCommand slice = tool("plate_slice", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { ctx.begin_operation(); while (!release) std::this_thread::sleep_for(10ms); @@ -832,15 +832,15 @@ TEST_CASE("the call observer hears inline, job and child calls, and not calls re CHECK_FALSE(h.call("look").is_error); CHECK(heard.take() == std::vector{"start look", "end ok"}); - CHECK(h.call("click").is_error); - CHECK(heard.take() == std::vector{"start click", R"(args {"target":{"label":"Slice"}})", "end error"}); + CHECK(h.call("widget_click").is_error); + CHECK(heard.take() == std::vector{"start widget_click", R"(args {"target":{"label":"Slice"}})", "end error"}); h.call("replay"); CHECK(heard.take() == - std::vector{"start replay", "start click in a job", R"(args {"target":{"label":"Slice"}})", "end error", "end error"}); + std::vector{"start replay", "start widget_click in a job", R"(args {"target":{"label":"Slice"}})", "end error", "end error"}); - const ToolResult running = h.call("slice"); + const ToolResult running = h.call("plate_slice"); REQUIRE(running.data["status"] == "running"); - CHECK(heard.take() == std::vector{"start slice"}); + CHECK(heard.take() == std::vector{"start plate_slice"}); CHECK(h.call("replay").is_error); // refused by admission: it never ran CHECK(heard.take().empty()); release = true; @@ -932,9 +932,9 @@ TEST_CASE("without a blocking slot a job call returns its envelope at once and a TEST_CASE("idle ignores the caller and its ancestors", "[Mcp]") { JobRegistry jobs; - const std::string replay_job = jobs.create("run_replay", ""); - const std::string step = jobs.create("slice", replay_job); - const std::string other = jobs.create("open_files", ""); + const std::string replay_job = jobs.create("replay_run", ""); + const std::string step = jobs.create("plate_slice", replay_job); + const std::string other = jobs.create("project_import", ""); CHECK(jobs.lineage(step) == std::set{step, replay_job}); CHECK(jobs.any_running_except(jobs.lineage(step))); jobs.finish(other, ToolResult::ok()); @@ -946,9 +946,9 @@ TEST_CASE("idle ignores the caller and its ancestors", "[Mcp]") TEST_CASE("idle skips a job set idle, but not the calls it makes", "[Mcp]") { JobRegistry jobs; - const std::string run = jobs.create("run_script", ""); + const std::string run = jobs.create("script_run", ""); jobs.set_idle(run); - const std::string child = jobs.create("slice", run); + const std::string child = jobs.create("plate_slice", run); CHECK(jobs.any_running_except({})); bool listed_idle = false; for (const nlohmann::json& job : jobs.list()) @@ -1010,7 +1010,7 @@ TEST_CASE("a closure queued before a UI rebuild does not run after it", "[Mcp]") std::atomic ran{false}; auto caller = std::async(std::launch::async, [&]() -> std::string { try { - invoker.run(GuardClass::Mutate, "click", [&] { + invoker.run(GuardClass::Mutate, "widget_click", [&] { ran = true; return json(); }); @@ -1033,7 +1033,7 @@ TEST_CASE("operation admission is checked again when a mutate call reaches the U h.registry.add(tool("edit", GuardClass::Mutate, [](const json&, ToolContext& ctx) { return ToolResult::ok(ctx.run_ui([] { return json("edited"); })); })); - NativeCommand slice = tool("slice", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { + NativeCommand slice = tool("plate_slice", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { ctx.run_ui([&] { ctx.begin_operation(); return json(); @@ -1050,7 +1050,7 @@ TEST_CASE("operation admission is checked again when a mutate call reaches the U while (hold) std::this_thread::sleep_for(5ms); }); - auto s = std::async(std::launch::async, [&] { return h.call("slice"); }); + auto s = std::async(std::launch::async, [&] { return h.call("plate_slice"); }); std::this_thread::sleep_for(100ms); auto e = std::async(std::launch::async, [&] { return h.call("edit"); }); std::this_thread::sleep_for(100ms); @@ -1065,8 +1065,8 @@ TEST_CASE("operation admission is checked again when a mutate call reaches the U TEST_CASE("only one operation runs at a time", "[Mcp]") { JobRegistry jobs; - const std::string a = jobs.create("slice", ""); - const std::string b = jobs.create("export", ""); + const std::string a = jobs.create("plate_slice", ""); + const std::string b = jobs.create("project_export", ""); CHECK(jobs.begin_operation(a).empty()); CHECK(jobs.begin_operation(b) == a); jobs.finish(a, ToolResult::ok()); @@ -1076,18 +1076,18 @@ TEST_CASE("only one operation runs at a time", "[Mcp]") TEST_CASE("ancestry lists the job chain nearest first", "[Mcp]") { JobRegistry jobs; - const std::string outer = jobs.create("run_replay", ""); - const std::string inner = jobs.create("run_replay", outer); - const std::string step = jobs.create("auto_answer_dialogs", inner); + const std::string outer = jobs.create("replay_run", ""); + const std::string inner = jobs.create("replay_run", outer); + const std::string step = jobs.create("dialog_auto_answer", inner); CHECK(jobs.ancestry(step) == std::vector{step, inner, outer}); } TEST_CASE("a stop asked for a job reaches its descendants and no other job", "[Mcp]") { JobRegistry jobs; - const std::string replay_job = jobs.create("run_replay", ""); - const std::string step = jobs.create("slice", replay_job); - const std::string other = jobs.create("open_files", ""); + const std::string replay_job = jobs.create("replay_run", ""); + const std::string step = jobs.create("plate_slice", replay_job); + const std::string other = jobs.create("project_import", ""); CHECK_FALSE(jobs.stop_requested(step)); jobs.request_stop(replay_job); CHECK(jobs.stop_requested(replay_job)); @@ -1115,7 +1115,7 @@ TEST_CASE("a job created as a person's is a person's until it finishes", "[Mcp]" TEST_CASE("a job allowed to discard is so until it finishes", "[Mcp]") { JobRegistry jobs; - const std::string run = jobs.create("run_replay", ""); + const std::string run = jobs.create("replay_run", ""); const std::string step = jobs.create("open_project", run); const std::string other = jobs.create("open_project", ""); CHECK_FALSE(jobs.discard_allowed_in({run})); @@ -1137,9 +1137,9 @@ TEST_CASE("a job allowed to discard is so until it finishes", "[Mcp]") TEST_CASE("a job wait with a stop check looks once at zero timeout and ends when stopped", "[Mcp]") { JobRegistry jobs; - const std::string done = jobs.create("slice", ""); + const std::string done = jobs.create("plate_slice", ""); jobs.finish(done, ToolResult::ok({{"done", true}})); - const std::string running = jobs.create("slice", ""); + const std::string running = jobs.create("plate_slice", ""); const auto never = [] { return false; }; const auto finished = jobs.wait(done, 0ms, never); @@ -1156,7 +1156,7 @@ TEST_CASE("a job wait with a stop check looks once at zero timeout and ends when TEST_CASE("a call made by a stopped job sees itself cancelled", "[Mcp]") { Harness h; - // An inline call that polls for cancellation, as wait does. + // An inline call that polls for cancellation, as app_wait does. NativeCommand spin = tool("spin", GuardClass::Inspect, [](const json&, ToolContext& ctx) { const auto end = std::chrono::steady_clock::now() + 5s; while (!ctx.cancelled() && std::chrono::steady_clock::now() < end) @@ -1183,9 +1183,9 @@ TEST_CASE("a call made by a stopped job sees itself cancelled", "[Mcp]") TEST_CASE("a live descendant keeps its lineage after its ancestors are evicted", "[Mcp]") { JobRegistry jobs; - const std::string root = jobs.create("run_replay", ""); - const std::string inner = jobs.create("run_replay", root); - const std::string leaf = jobs.create("wait", inner); + const std::string root = jobs.create("replay_run", ""); + const std::string inner = jobs.create("replay_run", root); + const std::string leaf = jobs.create("app_wait", inner); jobs.finish(inner, ToolResult::ok()); jobs.finish(root, ToolResult::ok()); for (int i = 0; i < 70; ++i) @@ -1200,8 +1200,8 @@ TEST_CASE("a live descendant keeps its lineage after its ancestors are evicted", TEST_CASE("a finished job stays while its parent replay runs", "[Mcp]") { JobRegistry jobs; - const std::string replay_job = jobs.create("run_replay", ""); - const std::string saved = jobs.create("run_action", replay_job); + const std::string replay_job = jobs.create("replay_run", ""); + const std::string saved = jobs.create("action_run", replay_job); jobs.finish(saved, ToolResult::ok({{"x", 1}})); for (std::size_t i = 0; i < JobRegistry::kKeepFinished + 5; ++i) jobs.finish(jobs.create("t", ""), ToolResult::ok()); @@ -1215,7 +1215,7 @@ TEST_CASE("a finished job stays while its parent replay runs", "[Mcp]") TEST_CASE("finished jobs stay bounded while their parent replay runs", "[Mcp]") { JobRegistry jobs; - const std::string replay_job = jobs.create("run_replay", ""); + const std::string replay_job = jobs.create("replay_run", ""); const std::string first = jobs.create("t", replay_job); jobs.finish(first, ToolResult::ok()); for (std::size_t i = 0; i < JobRegistry::kKeepFinishedMax; ++i) @@ -1229,13 +1229,13 @@ TEST_CASE("finished jobs stay bounded while their parent replay runs", "[Mcp]") TEST_CASE("the journal keeps a call waiting for its reply when it drops old calls", "[Mcp]") { Journal journal; - const uint64_t waiting = journal.begin("slice", json::object()); + const uint64_t waiting = journal.begin("plate_slice", json::object()); for (int i = 0; i < 6000; ++i) - journal.end(journal.begin("set_settings", {{"values", {{"wall_loops", i}}}}), ToolResult::ok()); + journal.end(journal.begin("settings_set", {{"values", {{"wall_loops", i}}}}), ToolResult::ok()); journal.end(waiting, ToolResult::ok()); const json steps = journal.to_replay("s")["steps"]; REQUIRE_FALSE(steps.empty()); - CHECK(steps[0]["tool"] == "slice"); + CHECK(steps[0]["tool"] == "plate_slice"); CHECK(steps.size() == 5000); } @@ -1244,7 +1244,7 @@ TEST_CASE("the journal keeps at most 64 MiB of arguments", "[Mcp]") Journal journal; const json big = args_of_mib(1); for (int i = 0; i < 100; ++i) - journal.end(journal.begin("set_settings", big), ToolResult::ok()); + journal.end(journal.begin("settings_set", big), ToolResult::ok()); const json steps = journal.to_replay("s")["steps"]; CHECK(steps.size() < 64); CHECK(steps.size() > 56); @@ -1256,7 +1256,7 @@ TEST_CASE("calls waiting for their reply outlast the byte cap and go once they f const json big = args_of_mib(1); std::vector waiting; for (int i = 0; i < 70; ++i) - waiting.push_back(journal.begin("set_settings", big)); + waiting.push_back(journal.begin("settings_set", big)); json left; CHECK(journal.to_replay("s", &left)["steps"].empty()); CHECK(left.size() == 70); @@ -1301,10 +1301,10 @@ TEST_CASE("replacing a call's arguments moves the journal's byte total", "[Mcp]" const json fifteen = args_of_mib(15); json left; for (int i = 0; i < 4; ++i) - journal.end(journal.begin("set_settings", fifteen), ToolResult::ok()); + journal.end(journal.begin("settings_set", fifteen), ToolResult::ok()); // 60 MiB, then 70 MiB once the small call's arguments grow: the first 15 MiB call goes at once, // while the grown call still waits for its reply. - const uint64_t b = journal.begin("set_settings", {{"values", {{"wall_loops", 3}}}}); + const uint64_t b = journal.begin("settings_set", {{"values", {{"wall_loops", 3}}}}); journal.set_args(b, args_of_mib(10)); CHECK(journal.to_replay("s", &left)["steps"].size() == 3); CHECK(left.size() == 1); @@ -1312,7 +1312,7 @@ TEST_CASE("replacing a call's arguments moves the journal's byte total", "[Mcp]" CHECK(journal.to_replay("s")["steps"].size() == 4); // Shrinking them back leaves 45 MiB, room for one more 15 MiB call. journal.set_args(b, {{"values", {{"wall_loops", 3}}}}); - journal.end(journal.begin("set_settings", fifteen), ToolResult::ok()); + journal.end(journal.begin("settings_set", fifteen), ToolResult::ok()); CHECK(journal.to_replay("s")["steps"].size() == 5); } @@ -1321,11 +1321,11 @@ TEST_CASE("clearing the journal resets its byte total", "[Mcp]") Journal journal; const json fifteen = args_of_mib(15); for (int i = 0; i < 4; ++i) - journal.end(journal.begin("set_settings", fifteen), ToolResult::ok()); + journal.end(journal.begin("settings_set", fifteen), ToolResult::ok()); journal.clear(); // Were the cleared calls' 60 MiB still counted, this 15 MiB call would go once it replied. - journal.end(journal.begin("set_settings", fifteen), ToolResult::ok()); - journal.end(journal.begin("set_settings", {{"values", {{"wall_loops", 3}}}}), ToolResult::ok()); + journal.end(journal.begin("settings_set", fifteen), ToolResult::ok()); + journal.end(journal.begin("settings_set", {{"values", {{"wall_loops", 3}}}}), ToolResult::ok()); CHECK(journal.to_replay("s")["steps"].size() == 2); } @@ -1341,7 +1341,7 @@ TEST_CASE("one call bigger than the cap is dropped once it has replied", "[Mcp]" CHECK(journal.to_replay("s", &left)["steps"].empty()); CHECK(left.empty()); // The total is back to what the remaining calls hold, so a small call stays. - journal.end(journal.begin("set_settings", {{"values", {{"wall_loops", 3}}}}), ToolResult::ok()); + journal.end(journal.begin("settings_set", {{"values", {{"wall_loops", 3}}}}), ToolResult::ok()); CHECK(journal.to_replay("s")["steps"].size() == 1); } @@ -1358,15 +1358,15 @@ TEST_CASE("a job refused at shutdown after it registered ends its journal entry" JobRegistry jobs; Journal journal; CommandCatalog registry; - registry.add(tool("answer_dialog", GuardClass::Recover, [](const json&, ToolContext&) { return ToolResult::ok(); })); + registry.add(tool("dialog_answer", GuardClass::Recover, [](const json&, ToolContext&) { return ToolResult::ok(); })); McpCore core(registry, invoker, jobs, &journal, CoreTiming{}); core_ptr = &core; - const ToolResult r = core.call(*registry.find("answer_dialog"), args_of_mib(65)); + const ToolResult r = core.call(*registry.find("dialog_answer"), args_of_mib(65)); REQUIRE(r.is_error); CHECK(r.message == "OrcaSlicer is shutting down"); // An entry left running would hold its 65 MiB against the cap, so the next call, not it, would go. - journal.end(journal.begin("set_settings", {{"values", {{"wall_loops", 3}}}}), ToolResult::ok()); + journal.end(journal.begin("settings_set", {{"values", {{"wall_loops", 3}}}}), ToolResult::ok()); CHECK(journal.to_replay("s")["steps"].size() == 1); } @@ -1418,23 +1418,23 @@ TEST_CASE("destroying a core waits for a job thread still inside it", "[Mcp]") TEST_CASE("the journal records client calls in order and replays jobs with await false", "[Mcp]") { Journal journal; - const uint64_t a = journal.begin("run_action", {{"id", "orca_command:open_preferences:orca"}}); + const uint64_t a = journal.begin("action_run", {{"id", "orca_command:open_preferences:orca"}}); journal.job_started(a, "j7"); journal.end(a, ToolResult::ok({{"status", "blocked_by_dialog"}, {"job", "j7"}})); - const uint64_t b = journal.begin("answer_dialog", {{"button", "close"}}); + const uint64_t b = journal.begin("dialog_answer", {{"button", "close"}}); journal.end(b, ToolResult::ok()); - const uint64_t c = journal.begin("wait", {{"for", "job"}, {"job", "j7"}}); + const uint64_t c = journal.begin("app_wait", {{"for", "job"}, {"job", "j7"}}); journal.end(c, ToolResult::ok()); - const uint64_t d = journal.begin("screenshot", {{"target", "canvas"}, {"save_path", "/tmp/x/after.png"}}); + const uint64_t d = journal.begin("window_screenshot", {{"target", "canvas"}, {"save_path", "/tmp/x/after.png"}}); journal.end(d, ToolResult::ok()); - const uint64_t e = journal.begin("set_settings", {{"values", {{"wall_loops", 3}}}}); + const uint64_t e = journal.begin("settings_set", {{"values", {{"wall_loops", 3}}}}); journal.end(e, ToolResult::error("no")); const json exported = journal.to_replay("repro"); REQUIRE(exported["steps"].size() == 4); CHECK(exported["steps"][0]["await"] == false); CHECK(exported["steps"][0]["save_as"] == "job1"); - CHECK(exported["steps"][1]["tool"] == "answer_dialog"); + CHECK(exported["steps"][1]["tool"] == "dialog_answer"); CHECK(exported["steps"][2]["args"]["job"] == "${jobs.job1}"); CHECK(exported["steps"][3]["args"]["save_path"] == "${out_dir}/after.png"); } @@ -1442,43 +1442,43 @@ TEST_CASE("the journal records client calls in order and replays jobs with await TEST_CASE("only client calls of journaled tools reach the journal", "[Mcp]") { Harness h; - NativeCommand look = tool("get_app_state", GuardClass::Inspect, [](const json&, ToolContext&) { return ToolResult::ok(); }); + NativeCommand look = tool("app_state", GuardClass::Inspect, [](const json&, ToolContext&) { return ToolResult::ok(); }); look.inline_call = true; look.journal = false; h.registry.add(look); - NativeCommand wait = tool("wait", GuardClass::Inspect, [](const json&, ToolContext&) { return ToolResult::ok(); }); + NativeCommand wait = tool("app_wait", GuardClass::Inspect, [](const json&, ToolContext&) { return ToolResult::ok(); }); wait.inline_call = true; h.registry.add(wait); - h.registry.add(tool("set_settings", GuardClass::Mutate, [](const json&, ToolContext& ctx) { - ctx.set_journal_args({{"values", {{"wall_loops", 3}}}, {"scope", "process"}}); + h.registry.add(tool("settings_set", GuardClass::Mutate, [](const json&, ToolContext& ctx) { + ctx.set_journal_args({{"values", {{"wall_loops", 3}}}, {"type", "process"}}); return ToolResult::ok(); })); h.start(); - h.call("get_app_state"); - h.call("wait", {{"for", "idle"}}); - h.call("set_settings", {{"values", {{"wall_loops", 3}}}}); + h.call("app_state"); + h.call("app_wait", {{"for", "idle"}}); + h.call("settings_set", {{"values", {{"wall_loops", 3}}}}); const json steps = h.journal.to_replay("x")["steps"]; REQUIRE(steps.size() == 2); - CHECK(steps[0]["tool"] == "wait"); - CHECK(steps[1]["args"]["scope"] == "process"); + CHECK(steps[0]["tool"] == "app_wait"); + CHECK(steps[1]["args"]["type"] == "process"); } TEST_CASE("a plugin's call runs as the plugin's own job and never reaches the journal", "[Mcp]") { Harness h; std::string seen, child_seen; - h.registry.add(tool("get_app_state", GuardClass::Inspect, [&child_seen](const json&, ToolContext& ctx) { + h.registry.add(tool("app_state", GuardClass::Inspect, [&child_seen](const json&, ToolContext& ctx) { child_seen = ctx.caller_plugin(); return ToolResult::ok(); })); - h.registry.add(tool("set_settings", GuardClass::Mutate, [&seen](const json&, ToolContext& ctx) { + h.registry.add(tool("settings_set", GuardClass::Mutate, [&seen](const json&, ToolContext& ctx) { seen = ctx.caller_plugin(); // A call it makes, as a replay step does, is the plugin's too. - ctx.call_child("get_app_state", json::object()); + ctx.call_child("app_state", json::object()); return ToolResult::ok({{"job", ctx.job_id()}}); })); h.start(); - const ToolResult r = h.core->call_plugin(*h.registry.find("set_settings"), json::object(), "measure-plugin"); + const ToolResult r = h.core->call_plugin(*h.registry.find("settings_set"), json::object(), "measure-plugin"); REQUIRE_FALSE(r.is_error); CHECK(seen == "measure-plugin"); CHECK(child_seen == "measure-plugin"); @@ -1486,26 +1486,26 @@ TEST_CASE("a plugin's call runs as the plugin's own job and never reaches the jo CHECK(h.journal.to_replay("x")["steps"].empty()); // A client's call has no plugin. - h.call("set_settings"); + h.call("settings_set"); CHECK(seen.empty()); CHECK(h.journal.to_replay("x")["steps"].size() == 1); } -TEST_CASE("call_tool is journaled as the tool it calls", "[Mcp]") +TEST_CASE("tool_call is journaled as the tool it calls", "[Mcp]") { Harness h; - h.registry.add(tool("set_settings", GuardClass::Mutate, [](const json&, ToolContext&) { return ToolResult::ok(); })); - NativeCommand api = tool("call_tool", GuardClass::Mutate, [](const json&, ToolContext&) -> ToolResult { throw ToolFailure("not dispatched"); }); + h.registry.add(tool("settings_set", GuardClass::Mutate, [](const json&, ToolContext&) { return ToolResult::ok(); })); + NativeCommand api = tool("tool_call", GuardClass::Mutate, [](const json&, ToolContext&) -> ToolResult { throw ToolFailure("not dispatched"); }); api.input_schema = {{"type", "object"}, {"properties", {{"tool", {{"type", "string"}}}, {"args", {{"type", "object"}}}}}}; h.registry.add(api); h.start(); McpProtocol protocol(h.registry, *h.core, ServerInfo{"orcaslicer", "OrcaSlicer", "9.9.9", ""}); const PostReply reply = protocol.handle_post(PostRequest{json{{"jsonrpc", "2.0"}, {"id", 1}, {"method", "tools/call"}, - {"params", {{"name", "call_tool"}, {"arguments", {{"tool", "set_settings"}, {"args", {{"values", {{"wall_loops", 3}}}}}}}}}}.dump()}); + {"params", {{"name", "tool_call"}, {"arguments", {{"tool", "settings_set"}, {"args", {{"values", {{"wall_loops", 3}}}}}}}}}}.dump()}); CHECK(json::parse(reply.body)["result"].value("isError", false) == false); const json steps = h.journal.to_replay("x")["steps"]; REQUIRE(steps.size() == 1); - CHECK(steps[0]["tool"] == "set_settings"); + CHECK(steps[0]["tool"] == "settings_set"); CHECK(steps[0]["args"]["values"]["wall_loops"] == 3); } @@ -1663,7 +1663,7 @@ TEST_CASE("a plugin's running call is cancelled the moment the plugin unloads", TEST_CASE("a call under a lineage node sees a stop asked for the node, inline calls included, and a renewed node's calls run", "[Mcp]") { Harness h; - // Polls for cancellation for up to `for_ms`, as wait does. + // Polls for cancellation for up to `for_ms`, as app_wait does. const auto poll = [](const json& args, ToolContext& ctx) { const auto end = std::chrono::steady_clock::now() + std::chrono::milliseconds(args.value("for_ms", 5000)); while (!ctx.cancelled() && std::chrono::steady_clock::now() < end) @@ -1677,9 +1677,9 @@ TEST_CASE("a call under a lineage node sees a stop asked for the node, inline ca h.timing.soft_budget = 10000ms; h.start(); - const std::string session = h.jobs.create("run_script", ""); + const std::string session = h.jobs.create("script_run", ""); h.jobs.set_idle(session); - LineageNode node(h.jobs, "run_script", session); + LineageNode node(h.jobs, "script_run", session); const auto call = [&](const char* tool, int for_ms) { return std::async(std::launch::async, [&h, &node, tool, for_ms] { return h.core->call_child_named(tool, {{"for_ms", for_ms}}, node.id()); @@ -1708,20 +1708,20 @@ TEST_CASE("a call under a lineage node sees a stop asked for the node, inline ca TEST_CASE("lineage nodes leave no running job behind", "[Mcp]") { JobRegistry jobs; - const std::string session = jobs.create("run_script", ""); + const std::string session = jobs.create("script_run", ""); const auto running_nodes = [&] { int count = 0; for (const json& job : jobs.list()) - if (job["tool"] == "run_script" && job.value("parent", std::string()) == session && job["state"] == "running") + if (job["tool"] == "script_run" && job.value("parent", std::string()) == session && job["state"] == "running") ++count; return count; }; { - LineageNode node(jobs, "run_script", session); + LineageNode node(jobs, "script_run", session); CHECK(running_nodes() == 1); } for (int round = 0; round < 10; ++round) { - LineageNode node(jobs, "run_script", session); + LineageNode node(jobs, "script_run", session); for (int renewal = 0; renewal < 3; ++renewal) node.renew(); CHECK(running_nodes() == 1); diff --git a/tests/automation/test_mcp_protocol.cpp b/tests/automation/test_mcp_protocol.cpp index b32298f33e..660c1f4c90 100644 --- a/tests/automation/test_mcp_protocol.cpp +++ b/tests/automation/test_mcp_protocol.cpp @@ -29,7 +29,7 @@ struct Fixture { CommandCatalog registry; DirectCaller caller; - McpProtocol protocol{registry, caller, ServerInfo{"orcaslicer", "OrcaSlicer", "9.9.9", "Use get_app_state first."}}; + McpProtocol protocol{registry, caller, ServerInfo{"orcaslicer", "OrcaSlicer", "9.9.9", "Use app_state first."}}; Fixture() { @@ -80,7 +80,7 @@ TEST_CASE("initialize echoes a supported client version", "[Mcp]") CHECK(result["protocolVersion"] == "2025-06-18"); CHECK(result["serverInfo"]["name"] == "orcaslicer"); CHECK(result["capabilities"].contains("tools")); - CHECK(result["instructions"] == "Use get_app_state first."); + CHECK(result["instructions"] == "Use app_state first."); } TEST_CASE("initialize answers an unsupported version with the latest supported one", "[Mcp]") @@ -199,7 +199,7 @@ TEST_CASE("the stdio bridge derives no headers from a line that is not a message { CHECK(bridge_headers(json::array({{{"method", "ping"}}}), "2025-06-18").empty()); CHECK(bridge_headers(json(42), {}).empty()); - CHECK(bridge_headers({{"jsonrpc", "2.0"}, {"id", 1}, {"method", "tools/call"}, {"params", {{"name", "get_app_state"}}}}, "2025-06-18") + CHECK(bridge_headers({{"jsonrpc", "2.0"}, {"id", 1}, {"method", "tools/call"}, {"params", {{"name", "app_state"}}}}, "2025-06-18") .count("MCP-Protocol-Version") == 1); // Members of the wrong type are left out rather than thrown on. CHECK(bridge_headers({{"jsonrpc", "2.0"}, {"id", 1}, {"method", 5}}, "").empty()); @@ -295,7 +295,8 @@ TEST_CASE("argument validation covers types, enums, ranges and arrays", "[Mcp]") {{"n", {{"type", "integer"}, {"minimum", 1}, {"maximum", 5}}}, {"zoom", {{"type", "number"}, {"exclusiveMinimum", 0}}}, {"mode", {{"type", "string"}, {"enum", {"a", "b"}}}}, - {"paths", {{"type", "array"}, {"items", {{"type", "string"}}}}}}}, + {"paths", {{"type", "array"}, {"items", {{"type", "string"}}}}}, + {"entries", {{"type", "array"}, {"items", {{"type", "string"}}}, {"minItems", 1}}}}}, {"additionalProperties", false}}; CHECK(validate_arguments(schema, {{"n", 3}, {"mode", "a"}, {"paths", {"x"}}}).empty()); CHECK(validate_arguments(schema, {{"n", 0}}).find("n must be >= 1") != std::string::npos); @@ -304,6 +305,9 @@ TEST_CASE("argument validation covers types, enums, ranges and arrays", "[Mcp]") CHECK(validate_arguments(schema, {{"n", 2.5}}).find("integer") != std::string::npos); CHECK(validate_arguments(schema, {{"mode", "c"}}).find("one of") != std::string::npos); CHECK(validate_arguments(schema, {{"paths", {1}}}).find("paths[0]") != std::string::npos); + CHECK(validate_arguments(schema, {{"paths", json::array()}}).empty()); + CHECK(validate_arguments(schema, {{"entries", json::array()}}).find("entries must hold at least 1 item") != std::string::npos); + CHECK(validate_arguments(schema, {{"entries", {"a.stl"}}}).empty()); CHECK(validate_arguments(schema, {{"extra", 1}}).find("unknown argument extra") != std::string::npos); // An argument the tool does not take is named before one the call leaves out: a call that gives an old name for @@ -406,7 +410,7 @@ TEST_CASE("argument normalization leaves a value its enum lacks, and a 3D view u CHECK(normalized({{"scope", "print"}}) == json{{"scope", "print"}}); CHECK(normalized({{"target", "window"}}) == json{{"target", "window"}}); CHECK_FALSE(validate_arguments(schema, normalized({{"scope", "print"}})).empty()); - // set_view's 3D view is its canvas. + // view_set's 3D view is its canvas. const json view = normalized({{"view", "preview"}}); CHECK(view == json{{"view", "preview"}}); CHECK(validate_arguments(schema, view).find("unknown argument view") != std::string::npos); @@ -469,7 +473,7 @@ TEST_CASE("argument normalization moves a value outside its enum to the argument CHECK(unknown == json{{"view", "sideways"}}); } -TEST_CASE("pairs list_windows reports are read as position and size", "[Mcp]") +TEST_CASE("pairs window_list reports are read as position and size", "[Mcp]") { const json schema = {{"type", "object"}, {"properties", {{"position", {{"type", "array"}, {"items", {{"type", "integer"}}}}}, @@ -490,9 +494,9 @@ TEST_CASE("pairs list_windows reports are read as position and size", "[Mcp]") CHECK(kept == json{{"x", 1}, {"y", 2}}); // a tool that takes x and y keeps them } -TEST_CASE("a position or size in mm, an array of numbers, takes no pair list_windows reports", "[Mcp]") +TEST_CASE("a position or size in mm, an array of numbers, takes no pair window_list reports", "[Mcp]") { - // add_part's position and size, and transform's position. + // part_add's position and size, and object_transform's position. const json schema = {{"type", "object"}, {"properties", {{"position", {{"type", "array"}, {"items", {{"type", "number"}}}}}, {"size", {{"type", "array"}, {"items", {{"type", "number"}}}}}}}, @@ -502,7 +506,7 @@ TEST_CASE("a position or size in mm, an array of numbers, takes no pair list_win normalize_arguments(schema, args); CHECK(args == flat); CHECK(validate_arguments(schema, args).find("unknown argument") != std::string::npos); - // transform's size, whose null keeps an axis. + // object_transform's size, whose null keeps an axis. const json nullable = {{"type", "object"}, {"properties", {{"size", {{"type", "array"}, {"items", {{"type", {"number", "null"}}}}}}}}, {"additionalProperties", false}}; @@ -518,15 +522,15 @@ TEST_CASE("an unknown tool is answered with the closest names", "[Mcp]") CHECK(direct["error"]["message"] == "Unknown tool: no_such_tool"); NativeCommand api; - api.key = "call_tool"; + api.key = "tool_call"; api.input_schema = {{"type", "object"}, {"properties", {{"tool", {{"type", "string"}}}, {"args", {{"type", "object"}}}}}, {"required", {"tool"}}}; api.run = [](const json&, ToolContext&) -> ToolResult { throw ToolFailure("not dispatched"); }; f.registry.add(api); - // call_tool's target names the closest command, and nothing else. + // tool_call's target names the closest command, and nothing else. const json typo = body(f.post({{"jsonrpc", "2.0"}, {"id", 9}, {"method", "tools/call"}, - {"params", {{"name", "call_tool"}, {"arguments", {{"tool", "ech"}}}}}}))["result"]; + {"params", {{"name", "tool_call"}, {"arguments", {{"tool", "ech"}}}}}}))["result"]; CHECK(typo["isError"] == true); CHECK(typo["content"][0]["text"] == "Unknown tool: ech (did you mean echo?)"); } @@ -534,7 +538,7 @@ TEST_CASE("an unknown tool is answered with the closest names", "[Mcp]") TEST_CASE("a call's arguments are normalized, then validated", "[Mcp]") { NativeCommand capture; - capture.key = "screenshot"; + capture.key = "window_screenshot"; capture.input_schema = {{"type", "object"}, {"properties", {{"target", {{"type", "string"}}}, {"save_path", {{"type", "string"}}}}}, {"additionalProperties", false}}; @@ -549,11 +553,11 @@ TEST_CASE("a call's arguments are normalized, then validated", "[Mcp]") CHECK(refused.find("save_path") != std::string::npos); } -TEST_CASE("call_tool runs and is journaled as the tool it names", "[Mcp]") +TEST_CASE("tool_call runs and is journaled as the tool it names", "[Mcp]") { Fixture f; NativeCommand api; - api.key = "call_tool"; + api.key = "tool_call"; api.input_schema = {{"type", "object"}, {"properties", {{"tool", {{"type", "string"}}}, {"args", {{"type", "object"}}}}}, {"required", {"tool"}}}; @@ -561,17 +565,17 @@ TEST_CASE("call_tool runs and is journaled as the tool it names", "[Mcp]") f.registry.add(api); const json result = body(f.post({{"jsonrpc", "2.0"}, {"id", 4}, {"method", "tools/call"}, - {"params", {{"name", "call_tool"}, {"arguments", {{"tool", "echo"}, {"args", {{"text", "hi"}}}}}}}}))["result"]; + {"params", {{"name", "tool_call"}, {"arguments", {{"tool", "echo"}, {"args", {{"text", "hi"}}}}}}}}))["result"]; CHECK(json::parse(result["content"][0]["text"].get()) == json{{"echo", "hi"}}); REQUIRE(f.caller.called.size() == 1); CHECK(f.caller.called.back() == "echo"); // The target's arguments are checked against its schema, and an unknown tool is named. const json invalid = body(f.post({{"jsonrpc", "2.0"}, {"id", 5}, {"method", "tools/call"}, - {"params", {{"name", "call_tool"}, {"arguments", {{"tool", "echo"}, {"args", json::object()}}}}}}))["result"]; + {"params", {{"name", "tool_call"}, {"arguments", {{"tool", "echo"}, {"args", json::object()}}}}}}))["result"]; CHECK(invalid["isError"] == true); const json unknown = body(f.post({{"jsonrpc", "2.0"}, {"id", 6}, {"method", "tools/call"}, - {"params", {{"name", "call_tool"}, {"arguments", {{"tool", "ech"}}}}}}))["result"]; + {"params", {{"name", "tool_call"}, {"arguments", {{"tool", "ech"}}}}}}))["result"]; CHECK(unknown["isError"] == true); CHECK(unknown["content"][0]["text"].get().find("did you mean echo") != std::string::npos); } diff --git a/tests/automation/test_mcp_replay.cpp b/tests/automation/test_mcp_replay.cpp index e0589b1e41..40afa7b54d 100644 --- a/tests/automation/test_mcp_replay.cpp +++ b/tests/automation/test_mcp_replay.cpp @@ -1,6 +1,8 @@ #include #include #include +#include +#include #include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/Mcp/McpReplay.hpp" @@ -23,6 +25,7 @@ using namespace Slic3r::GUI; using namespace Slic3r::GUI::Mcp; +using Catch::Matchers::ContainsSubstring; using nlohmann::json; namespace { @@ -71,9 +74,9 @@ TEST_CASE("replays allow comments and read their fields", "[Mcp]") { const Replay s = parse_ok(R"({ // a comment - "orca_replay_version": "0.1.0", "name": "repro", /* block */ "vars": {"n": 3}, - "steps": [{"tool": "slice", "expect": {"/ok": {"eq": true}}, "optional": true, "timeout_s": 5}, - {"tool": "run_action", "await": false, "save_as": "prefs"}] + "orca_replay_version": "0.2.0", "name": "repro", /* block */ "vars": {"n": 3}, + "steps": [{"tool": "plate_slice", "expect": {"/ok": {"eq": true}}, "optional": true, "timeout_s": 5}, + {"tool": "action_run", "await": false, "save_as": "prefs"}] })"); CHECK(s.name == "repro"); REQUIRE(s.steps.size() == 2); @@ -88,10 +91,10 @@ TEST_CASE("invalid replays are rejected with a reason", "[Mcp]") const auto [text, reason] = GENERATE(table({ {"{", "not valid JSON"}, {R"({"steps": []})", "orca_replay_version"}, - {R"({"orca_replay_version": "0.1.0"})", "steps"}, - {R"({"orca_replay_version": "0.1.0", "steps": [{"args": {}}]})", "step 1"}, - {R"({"orca_replay_version": "0.1.0", "steps": [{"tool": "x", "await": false}]})", "save_as"}, - {R"({"orca_replay_version": "0.1.0", "steps": [{"tool": "x", "args": []}]})", "args"}, + {R"({"orca_replay_version": "0.2.0"})", "steps"}, + {R"({"orca_replay_version": "0.2.0", "steps": [{"args": {}}]})", "step 1"}, + {R"({"orca_replay_version": "0.2.0", "steps": [{"tool": "x", "await": false}]})", "save_as"}, + {R"({"orca_replay_version": "0.2.0", "steps": [{"tool": "x", "args": []}]})", "args"}, })); std::string err; CHECK_FALSE(parse_replay(text, err).has_value()); @@ -100,15 +103,16 @@ TEST_CASE("invalid replays are rejected with a reason", "[Mcp]") TEST_CASE("a replay is read only in a format version this build reads", "[Mcp]") { - // This build reads format 0.1.0 (REPLAY_VERSION): while the major version is 0, only its own minor version. + // This build reads format 0.2.0 (REPLAY_VERSION): while the major version is 0, only its own minor version. const auto [version, reason] = GENERATE(table({ - {"0.1.0", ""}, - {"0.1.7", ""}, - {"0.1.0-beta", ""}, - {"0.2.0", "written for a newer OrcaSlicer"}, + {"0.2.0", ""}, + {"0.2.7", ""}, + {"0.2.0-beta", ""}, + {"0.3.0", "written for a newer OrcaSlicer"}, {"1.0.0", "written for a newer OrcaSlicer"}, + {"0.1.0", "no longer reads"}, {"0.0.9", "no longer reads"}, - {"v0.1.0", "must be a version"}, + {"v0.2.0", "must be a version"}, {"0.x.0", "must be a version"}, })); CAPTURE(version); @@ -118,9 +122,26 @@ TEST_CASE("a replay is read only in a format version this build reads", "[Mcp]") CHECK(err.find(reason) != std::string::npos); } +TEST_CASE("a replay of an older format is refused for its format", "[Mcp]") +{ + // A replay written before the commands were named by place calls tools this build does not have: it is refused for + // its format before any step is read, not for its first step's tool. + std::string err; + CHECK_FALSE(parse_replay(R"({"orca_replay_version": "0.1.0", "name": "old", "steps": [{"tool": "list_objects", "args": {}}]})", err) + .has_value()); + CHECK_THAT(err, ContainsSubstring("format 0.1.0")); + CHECK_THAT(err, ContainsSubstring("this one reads format 0.2.0")); + CHECK_THAT(err, !ContainsSubstring("Unknown tool")); + // The same replay in this format, on the command's name, is read. + const Replay now = parse_ok(R"({"orca_replay_version": "0.2.0", "name": "old", "steps": [{"tool": "object_list", "args": {}}]})"); + CHECK(now.name == "old"); + REQUIRE(now.steps.size() == 1); + CHECK(now.steps[0].tool == "object_list"); +} + TEST_CASE("vars, env and jobs substitute recursively", "[Mcp]") { - const Replay s = parse_ok(R"({"orca_replay_version": "0.1.0", "vars": {"model": "${replay_dir}/part.stl", "count": 3}, "steps": []})"); + const Replay s = parse_ok(R"({"orca_replay_version": "0.2.0", "vars": {"model": "${replay_dir}/part.stl", "count": 3}, "steps": []})"); ReplayContext ctx; ctx.replay_dir = "/replays"; ctx.out_dir = "/out"; @@ -177,9 +198,9 @@ TEST_CASE("each matcher passes and fails with a message naming the pointer", "[M TEST_CASE("a job-returning step is awaited before its expect is checked", "[Mcp]") { FakeHost f; - f.tools["slice"] = [](const json&) { return ToolResult::ok({{"status", "running"}, {"job", "j3"}}); }; + f.tools["plate_slice"] = [](const json&) { return ToolResult::ok({{"status", "running"}, {"job", "j3"}}); }; f.job_results["j3"] = ToolResult::ok({{"plates", {{{"outcome", "ok"}}}}}); - const Replay s = parse_ok(R"({"orca_replay_version": "0.1.0", "steps": [{"tool": "slice", "expect": {"/plates/0/outcome": {"eq": "ok"}}}]})"); + const Replay s = parse_ok(R"({"orca_replay_version": "0.2.0", "steps": [{"tool": "plate_slice", "expect": {"/plates/0/outcome": {"eq": "ok"}}}]})"); ReplayContext ctx; const json out = run_replay(s, ctx, f.host()); CHECK(out["passed"] == true); @@ -189,13 +210,13 @@ TEST_CASE("a job-returning step is awaited before its expect is checked", "[Mcp] TEST_CASE("await false stores the job under save_as for later steps", "[Mcp]") { FakeHost f; - f.tools["run_action"] = [](const json&) { return ToolResult::ok({{"status", "blocked_by_dialog"}, {"job", "j5"}}); }; - f.tools["answer_dialog"] = [](const json&) { return ToolResult::ok(); }; - f.tools["wait"] = [](const json& a) { return ToolResult::ok({{"job", a["job"]}}); }; - const Replay s = parse_ok(R"({"orca_replay_version": "0.1.0", "steps": [ - {"tool": "run_action", "await": false, "save_as": "prefs"}, - {"tool": "answer_dialog", "args": {"button": "close"}}, - {"tool": "wait", "args": {"for": "job", "job": "${jobs.prefs}"}, "expect": {"/job": {"eq": "j5"}}}]})"); + f.tools["action_run"] = [](const json&) { return ToolResult::ok({{"status", "blocked_by_dialog"}, {"job", "j5"}}); }; + f.tools["dialog_answer"] = [](const json&) { return ToolResult::ok(); }; + f.tools["app_wait"] = [](const json& a) { return ToolResult::ok({{"job", a["job"]}}); }; + const Replay s = parse_ok(R"({"orca_replay_version": "0.2.0", "steps": [ + {"tool": "action_run", "await": false, "save_as": "prefs"}, + {"tool": "dialog_answer", "args": {"button": "close"}}, + {"tool": "app_wait", "args": {"for": "job", "job": "${jobs.prefs}"}, "expect": {"/job": {"eq": "j5"}}}]})"); ReplayContext ctx; const json out = run_replay(s, ctx, f.host()); CHECK(out["passed"] == true); @@ -208,7 +229,7 @@ TEST_CASE("a run stops at the first failed step unless it is optional", "[Mcp]") FakeHost f; f.tools["ok"] = [](const json&) { return ToolResult::ok({{"v", 1}}); }; f.tools["fail"] = [](const json&) { return ToolResult::error("nope"); }; - const Replay s = parse_ok(R"({"orca_replay_version": "0.1.0", "steps": [ + const Replay s = parse_ok(R"({"orca_replay_version": "0.2.0", "steps": [ {"tool": "fail", "optional": true}, {"tool": "ok", "expect": {"/v": {"eq": 2}}}, {"tool": "ok"}]})"); ReplayContext ctx; const json out = run_replay(s, ctx, f.host()); @@ -224,7 +245,7 @@ TEST_CASE("a run reports each step as it starts and ends", "[Mcp]") FakeHost f; f.tools["a"] = [](const json&) { return ToolResult::ok(); }; f.tools["b"] = [](const json&) { return ToolResult::ok(); }; - const Replay s = parse_ok(R"({"orca_replay_version": "0.1.0", "steps": [{"tool": "a"}, {"tool": "b"}]})"); + const Replay s = parse_ok(R"({"orca_replay_version": "0.2.0", "steps": [{"tool": "a"}, {"tool": "b"}]})"); std::vector events; ReplayHost h = f.host(); h.step_started = [&](std::size_t index) { events.push_back("started " + std::to_string(index)); }; @@ -243,7 +264,7 @@ TEST_CASE("only_step runs one step and reports its own index", "[Mcp]") FakeHost f; for (const char* name : {"a", "b", "c"}) f.tools[name] = [](const json&) { return ToolResult::ok(); }; - const Replay s = parse_ok(R"({"orca_replay_version": "0.1.0", "steps": [{"tool": "a"}, {"tool": "b"}, {"tool": "c"}]})"); + const Replay s = parse_ok(R"({"orca_replay_version": "0.2.0", "steps": [{"tool": "a"}, {"tool": "b"}, {"tool": "c"}]})"); ReplayContext ctx; const json out = run_replay(s, ctx, f.host(), 2); REQUIRE(f.calls.size() == 1); @@ -258,11 +279,11 @@ TEST_CASE("jobs saved by an earlier run resolve in a later single step", "[Mcp]" { FakeHost f; f.tools["x"] = [](const json&) { return ToolResult::ok({{"status", "running"}, {"job", "j7"}}); }; - f.tools["wait"] = [](const json& a) { return ToolResult::ok({{"job", a["job"]}}); }; - const Replay s = parse_ok(R"({"orca_replay_version": "0.1.0", "steps": [ + f.tools["app_wait"] = [](const json& a) { return ToolResult::ok({{"job", a["job"]}}); }; + const Replay s = parse_ok(R"({"orca_replay_version": "0.2.0", "steps": [ {"tool": "x", "await": false, "save_as": "prefs"}, - {"tool": "wait", "args": {"job": "${jobs.prefs}"}}, - {"tool": "wait", "args": {"job": "${jobs.none}"}}]})"); + {"tool": "app_wait", "args": {"job": "${jobs.prefs}"}}, + {"tool": "app_wait", "args": {"job": "${jobs.none}"}}]})"); ReplayContext fresh; const json alone = run_replay(s, fresh, f.host(), 2); @@ -282,8 +303,8 @@ TEST_CASE("jobs saved by an earlier run resolve in a later single step", "[Mcp]" TEST_CASE("a stop during a step marks that step, even the last one", "[Mcp]") { - const std::string text = GENERATE(as{}, R"({"orca_replay_version": "0.1.0", "steps": [{"tool": "stopper"}]})", - R"({"orca_replay_version": "0.1.0", "steps": [{"tool": "stopper", "optional": true}]})"); + const std::string text = GENERATE(as{}, R"({"orca_replay_version": "0.2.0", "steps": [{"tool": "stopper"}]})", + R"({"orca_replay_version": "0.2.0", "steps": [{"tool": "stopper", "optional": true}]})"); const bool single = GENERATE(false, true); FakeHost f; f.tools["stopper"] = [&f](const json&) { @@ -309,7 +330,7 @@ TEST_CASE("a stop during a job wait is a cancel, not a timeout", "[Mcp]") { FakeHost f; f.tools["slow"] = [](const json&) { return ToolResult::ok({{"status", "running"}, {"job", "j1"}}); }; - const Replay s = parse_ok(R"({"orca_replay_version": "0.1.0", "steps": [{"tool": "slow"}]})"); + const Replay s = parse_ok(R"({"orca_replay_version": "0.2.0", "steps": [{"tool": "slow"}]})"); ReplayHost stopping = f.host(); stopping.wait_job = [&f](const std::string&, int) -> std::optional { @@ -331,7 +352,7 @@ TEST_CASE("a job wait that times out names the dialog left open", "[Mcp]") { FakeHost f; f.tools["opens"] = [](const json&) { return ToolResult::ok({{"status", "blocked_by_dialog"}, {"job", "j1"}}); }; - const Replay s = parse_ok(R"({"orca_replay_version": "0.1.0", "steps": [{"tool": "opens"}]})"); + const Replay s = parse_ok(R"({"orca_replay_version": "0.2.0", "steps": [{"tool": "opens"}]})"); const json dialogs = json::array({{{"title", "Uniform scale"}, {"native", false}}, {{"title", "Preferences"}, {"native", false}}}); ReplayHost host = f.host(); @@ -343,15 +364,15 @@ TEST_CASE("a job wait that times out names the dialog left open", "[Mcp]") CHECK(step["reason"]["kind"] == "timeout"); // The topmost dialog, the last one listed, is the one named. CHECK(error.find("\"Preferences\"") != std::string::npos); - CHECK(error.find("auto_answer_dialogs") != std::string::npos); + CHECK(error.find("dialog_auto_answer") != std::string::npos); CHECK(step["details"]["dialogs"] == dialogs); } TEST_CASE("a failed expectation carries its parts", "[Mcp]") { FakeHost f; - f.tools["slice"] = [](const json&) { return ToolResult::ok({{"plates", {{{"outcome", "error"}}}}}); }; - const Replay s = parse_ok(R"({"orca_replay_version": "0.1.0", "steps": [{"tool": "slice", "expect": {"/plates/0/outcome": {"eq": "ok"}}}]})"); + f.tools["plate_slice"] = [](const json&) { return ToolResult::ok({{"plates", {{{"outcome", "error"}}}}}); }; + const Replay s = parse_ok(R"({"orca_replay_version": "0.2.0", "steps": [{"tool": "plate_slice", "expect": {"/plates/0/outcome": {"eq": "ok"}}}]})"); ReplayContext ctx; const json entry = run_replay(s, ctx, f.host())["steps"][0]; CHECK(entry["reason"] == json{{"kind", "expect"}, {"pointer", "/plates/0/outcome"}, {"op", "eq"}, @@ -362,8 +383,8 @@ TEST_CASE("a failed expectation carries its parts", "[Mcp]") TEST_CASE("a matcher that is not an object is a malformed expectation", "[Mcp]") { FakeHost f; - f.tools["slice"] = [](const json&) { return ToolResult::ok({{"outcome", "ok"}}); }; - const Replay s = parse_ok(R"({"orca_replay_version": "0.1.0", "steps": [{"tool": "slice", "expect": {"/outcome": "ok"}}]})"); + f.tools["plate_slice"] = [](const json&) { return ToolResult::ok({{"outcome", "ok"}}); }; + const Replay s = parse_ok(R"({"orca_replay_version": "0.2.0", "steps": [{"tool": "plate_slice", "expect": {"/outcome": "ok"}}]})"); ReplayContext ctx; const json entry = run_replay(s, ctx, f.host())["steps"][0]; CHECK(entry["ok"] == false); @@ -376,17 +397,17 @@ TEST_CASE("a matcher that is not an object is a malformed expectation", "[Mcp]") TEST_CASE("an inline nested replay's placeholders are the outer replay's", "[Mcp]") { FakeHost f; - f.tools["run_replay"] = [](const json&) { return ToolResult::ok({{"passed", true}}); }; - const Replay with_outer = parse_ok(R"({"orca_replay_version": "0.1.0", "vars": {"p": "outer.stl"}, "steps": [{"tool": "run_replay", - "args": {"vars": {"p": "step.stl"}, "replay": {"orca_replay_version": "0.1.0", "steps": [{"tool": "open_files", "args": {"paths": ["${vars.p}"]}}]}}}]})"); + f.tools["replay_run"] = [](const json&) { return ToolResult::ok({{"passed", true}}); }; + const Replay with_outer = parse_ok(R"({"orca_replay_version": "0.2.0", "vars": {"p": "outer.stl"}, "steps": [{"tool": "replay_run", + "args": {"vars": {"p": "step.stl"}, "replay": {"orca_replay_version": "0.2.0", "steps": [{"tool": "project_import", "args": {"paths": ["${vars.p}"]}}]}}}]})"); ReplayContext ctx; CHECK(run_replay(with_outer, ctx, f.host())["passed"] == true); REQUIRE(f.calls.size() == 1); CHECK(f.calls[0].second["replay"]["steps"][0]["args"]["paths"][0] == "outer.stl"); FakeHost g; - const Replay step_only = parse_ok(R"({"orca_replay_version": "0.1.0", "steps": [{"tool": "run_replay", - "args": {"vars": {"p": "step.stl"}, "replay": {"orca_replay_version": "0.1.0", "steps": [{"tool": "open_files", "args": {"paths": ["${vars.p}"]}}]}}}]})"); + const Replay step_only = parse_ok(R"({"orca_replay_version": "0.2.0", "steps": [{"tool": "replay_run", + "args": {"vars": {"p": "step.stl"}, "replay": {"orca_replay_version": "0.2.0", "steps": [{"tool": "project_import", "args": {"paths": ["${vars.p}"]}}]}}}]})"); const json out = run_replay(step_only, ctx, g.host()); CHECK(out["passed"] == false); CHECK(out["steps"][0]["reason"] == json{{"kind", "placeholder"}, {"text", "${vars.p}"}}); @@ -395,7 +416,7 @@ TEST_CASE("an inline nested replay's placeholders are the outer replay's", "[Mcp TEST_CASE("lenient substitution keeps what it cannot resolve", "[Mcp]") { - const Replay s = parse_ok(R"({"orca_replay_version": "0.1.0", "vars": {"model": "C:/m/part.stl"}, "steps": []})"); + const Replay s = parse_ok(R"({"orca_replay_version": "0.2.0", "vars": {"model": "C:/m/part.stl"}, "steps": []})"); ReplayContext ctx; CHECK(substitute_lenient("${vars.model}", s, ctx) == "C:/m/part.stl"); CHECK(substitute_lenient("${jobs.none}/x", s, ctx) == "${jobs.none}/x"); @@ -406,10 +427,10 @@ TEST_CASE("malformed replays are errors, not exceptions", "[Mcp]") { const auto [text, field] = GENERATE(table({ {R"({"orca_replay_version": 1, "steps": []})", "orca_replay_version"}, - {R"({"orca_replay_version": "0.1.0", "name": 5, "steps": []})", "name"}, - {R"({"orca_replay_version": "0.1.0", "steps": [{"tool": 3}]})", "step 1: \"tool\""}, - {R"({"orca_replay_version": "0.1.0", "steps": [{"tool": "a", "timeout_s": "9"}]})", "step 1: \"timeout_s\""}, - {R"({"orca_replay_version": "0.1.0", "steps": [{"tool": "a", "optional": "yes"}]})", "step 1: \"optional\""}, + {R"({"orca_replay_version": "0.2.0", "name": 5, "steps": []})", "name"}, + {R"({"orca_replay_version": "0.2.0", "steps": [{"tool": 3}]})", "step 1: \"tool\""}, + {R"({"orca_replay_version": "0.2.0", "steps": [{"tool": "a", "timeout_s": "9"}]})", "step 1: \"timeout_s\""}, + {R"({"orca_replay_version": "0.2.0", "steps": [{"tool": "a", "optional": "yes"}]})", "step 1: \"optional\""}, {R"([])", "orca_replay_version"}, {R"({})", "orca_replay_version"}, })); @@ -423,16 +444,16 @@ TEST_CASE("malformed replays are errors, not exceptions", "[Mcp]") TEST_CASE("broken JSON says where", "[Mcp]") { std::string err; - CHECK_FALSE(parse_replay("{\n \"orca_replay_version\": \"0.1.0\",\n \"steps\": [ {\"tool\": \"a\",, } ]\n}", err).has_value()); + CHECK_FALSE(parse_replay("{\n \"orca_replay_version\": \"0.2.0\",\n \"steps\": [ {\"tool\": \"a\",, } ]\n}", err).has_value()); CHECK(err.find("line 3, column") != std::string::npos); } TEST_CASE("a Python step's code runs as written while its other arguments substitute", "[Mcp]") { - const Replay s = parse_ok(R"({"orca_replay_version": "0.1.0", "vars": {"a": "seven"}, "steps": [ - {"tool": "run_script", "args": {"code": "label = '${vars.a}'", "args": {"label": "${vars.a}"}}}]})"); + const Replay s = parse_ok(R"({"orca_replay_version": "0.2.0", "vars": {"a": "seven"}, "steps": [ + {"tool": "script_run", "args": {"code": "label = '${vars.a}'", "args": {"label": "${vars.a}"}}}]})"); FakeHost fake; - fake.tools["run_script"] = [](const json&) { return ToolResult::ok({{"status", "finished"}, {"result", nullptr}, {"output", ""}}); }; + fake.tools["script_run"] = [](const json&) { return ToolResult::ok({{"status", "finished"}, {"result", nullptr}, {"output", ""}}); }; ReplayContext ctx; const json out = run_replay(s, ctx, fake.host(), std::nullopt); CHECK(out["passed"] == true); @@ -443,14 +464,14 @@ TEST_CASE("a Python step's code runs as written while its other arguments substi TEST_CASE("a Python step that did not finish fails its replay", "[Mcp]") { - const Replay s = parse_ok(R"S({"orca_replay_version": "0.1.0", "steps": [ - {"tool": "run_script", "args": {"code": "raise ValueError('x')"}}, - {"tool": "get_app_state"}]})S"); + const Replay s = parse_ok(R"S({"orca_replay_version": "0.2.0", "steps": [ + {"tool": "script_run", "args": {"code": "raise ValueError('x')"}}, + {"tool": "app_state"}]})S"); FakeHost fake; - fake.tools["run_script"] = [](const json&) { + fake.tools["script_run"] = [](const json&) { return ToolResult::ok({{"status", "raised"}, {"message", "ValueError: x"}, {"traceback", "..."}, {"output", ""}}); }; - fake.tools["get_app_state"] = [](const json&) { return ToolResult::ok(); }; + fake.tools["app_state"] = [](const json&) { return ToolResult::ok(); }; ReplayContext ctx; const json out = run_replay(s, ctx, fake.host(), std::nullopt); CHECK(out["passed"] == false); @@ -463,29 +484,29 @@ TEST_CASE("a Python step that did not finish fails its replay", "[Mcp]") TEST_CASE("a Python step left running with await false keeps its job for later steps", "[Mcp]") { - const Replay s = parse_ok(R"({"orca_replay_version": "0.1.0", "steps": [ - {"tool": "run_script", "args": {"code": "x = 1"}, "await": false, "save_as": "py"}, - {"tool": "get_app_state"}]})"); + const Replay s = parse_ok(R"({"orca_replay_version": "0.2.0", "steps": [ + {"tool": "script_run", "args": {"code": "x = 1"}, "await": false, "save_as": "py"}, + {"tool": "app_state"}]})"); FakeHost fake; - fake.tools["run_script"] = [](const json&) { return ToolResult::ok({{"status", "running"}, {"job", "j5"}}); }; - fake.tools["get_app_state"] = [](const json&) { return ToolResult::ok(); }; + fake.tools["script_run"] = [](const json&) { return ToolResult::ok({{"status", "running"}, {"job", "j5"}}); }; + fake.tools["app_state"] = [](const json&) { return ToolResult::ok(); }; ReplayContext ctx; const json out = run_replay(s, ctx, fake.host(), std::nullopt); CHECK(out["passed"] == true); CHECK(ctx.jobs["py"] == "j5"); } -TEST_CASE("Python reached through call_tool or a nested replay follows the Python step rules", "[Mcp]") +TEST_CASE("Python reached through tool_call or a nested replay follows the Python step rules", "[Mcp]") { // Its code runs as written however the step reaches it. - const Replay s = parse_ok(R"S({"orca_replay_version": "0.1.0", "vars": {"a": "seven"}, "steps": [ - {"tool": "call_tool", "args": {"tool": "run_script", "args": {"code": "x = '${vars.a}'", "args": {"v": "${vars.a}"}}}}, - {"tool": "run_replay", "args": {"replay": {"orca_replay_version": "0.1.0", "steps": [ - {"tool": "run_script", "args": {"code": "y = '${vars.a}'"}}, - {"tool": "set_settings", "args": {"note": "${vars.a}"}}]}}}]})S"); + const Replay s = parse_ok(R"S({"orca_replay_version": "0.2.0", "vars": {"a": "seven"}, "steps": [ + {"tool": "tool_call", "args": {"tool": "script_run", "args": {"code": "x = '${vars.a}'", "args": {"v": "${vars.a}"}}}}, + {"tool": "replay_run", "args": {"replay": {"orca_replay_version": "0.2.0", "steps": [ + {"tool": "script_run", "args": {"code": "y = '${vars.a}'"}}, + {"tool": "settings_set", "args": {"note": "${vars.a}"}}]}}}]})S"); FakeHost fake; - fake.tools["call_tool"] = [](const json&) { return ToolResult::ok({{"status", "finished"}, {"result", nullptr}, {"output", ""}}); }; - fake.tools["run_replay"] = [](const json&) { return ToolResult::ok({{"passed", true}}); }; + fake.tools["tool_call"] = [](const json&) { return ToolResult::ok({{"status", "finished"}, {"result", nullptr}, {"output", ""}}); }; + fake.tools["replay_run"] = [](const json&) { return ToolResult::ok({{"passed", true}}); }; ReplayContext ctx; const json out = run_replay(s, ctx, fake.host(), std::nullopt); CHECK(out["passed"] == true); @@ -496,11 +517,11 @@ TEST_CASE("Python reached through call_tool or a nested replay follows the Pytho CHECK(nested[0]["args"]["code"] == "y = '${vars.a}'"); CHECK(nested[1]["args"]["note"] == "seven"); - // A run that raised through call_tool fails its step. - const Replay failing = parse_ok(R"({"orca_replay_version": "0.1.0", "steps": [ - {"tool": "call_tool", "args": {"tool": "run_script", "args": {"code": "x"}}}]})"); + // A run that raised through tool_call fails its step. + const Replay failing = parse_ok(R"({"orca_replay_version": "0.2.0", "steps": [ + {"tool": "tool_call", "args": {"tool": "script_run", "args": {"code": "x"}}}]})"); FakeHost raising; - raising.tools["call_tool"] = [](const json&) { return ToolResult::ok({{"status", "raised"}, {"message", "NameError: x"}}); }; + raising.tools["tool_call"] = [](const json&) { return ToolResult::ok({{"status", "raised"}, {"message", "NameError: x"}}); }; ReplayContext ctx2; const json failed = run_replay(failing, ctx2, raising.host(), std::nullopt); CHECK(failed["passed"] == false); diff --git a/tests/automation/test_mcp_replay_summary.cpp b/tests/automation/test_mcp_replay_summary.cpp index 43934517aa..921ea80011 100644 --- a/tests/automation/test_mcp_replay_summary.cpp +++ b/tests/automation/test_mcp_replay_summary.cpp @@ -24,32 +24,58 @@ using Flags = std::vector; const Flags kEveryFlag{"writes_file", "changes_presets", "replaces_project", "sends_to_printer"}; -// The commands the cases call by their key, each with a tile and no place in the tool list, as the app's catalog -// has them: three with a tile of their own; export_drawing with one of its own and one that runs it with -// {"format": "pdf"}; and calib_sample, whose only tile runs it with no arguments, as a Design command's folded rows -// do. Every other tool the cases name is a typed tool, which the summary describes by its name. +// The commands the cases call by their key, with tiles and places in the tool list as the app's catalog has them: +// commands whose menu rows are items of their tiles, view_set's two among them collecting a value, and object_mirror's +// two, one of which has a Speed Dial section of its own; plate_delete, with a tile of its own; all of them listed, as +// they run from their arguments. And export_drawing, made up, with a tile of its own and one that runs it with +// {"format": "pdf"}, which the tool list does not show, as a Design command. Every other tool the cases name is a +// typed tool, which the summary describes by its name. CommandCatalog tile_catalog() { CommandCatalog catalog; - for (const char* key : {"load_project", "export_stl", "sync_presets"}) { - NativeCommand command; - command.key = key; - command.in_palette = true; - command.listed = false; - catalog.add(std::move(command)); - } - const auto tile = [](const char* key, const char* title, json args) { + const auto tile = [](const char* key, const char* title, json args) { return json{{"key", key}, {"title", title}, {"icon", ""}, {"description", ""}, {"args", std::move(args)}}; }; - NativeCommand drawing; - drawing.key = "export_drawing"; - drawing.in_palette = true; - drawing.tiles = json::array({tile("export_drawing_pdf", "Export as PDF", {{"format", "pdf"}})}); - catalog.add(std::move(drawing)); - NativeCommand sample; - sample.key = "calib_sample"; - sample.tiles = json::array({tile("calib_sample_cube", "Sample cube", json::object())}); - catalog.add(std::move(sample)); + // A tile whose second phase collects a value under `input`, which goes to the command's `input_arg`. + const auto collects = [&tile](const char* key, const char* title, const char* input, const char* input_arg) { + json item = tile(key, title, json::object()); + item["input"] = input; + item["input_arg"] = input_arg; + return item; + }; + const auto add = [&catalog](const char* key, bool listed, bool in_palette, json tiles) { + NativeCommand command; + command.key = key; + command.listed = listed; + command.in_palette = in_palette; + command.tiles = std::move(tiles); + catalog.add(std::move(command)); + }; + add("project_new", true, false, json::array({tile("new_project", "New Project", json::object())})); + add("project_open", true, false, json::array({tile("load_project", "Load Project", json::object())})); + add("project_import", true, false, json::array({tile("import_file", "Import 3MF/STL/STEP/SVG/OBJ/AMF", json::object())})); + add("project_save", true, false, + json::array({tile("save_project", "Save Project", json::object()), tile("save_project_as", "Save Project As", {{"save_as", true}})})); + add("project_export", true, false, json::array({tile("export_gcode", "Export G-code", {{"format", "gcode"}})})); + add("calibration_generate_test", true, false, + json::array({tile("calib_flow_ratio", "Flow Ratio Calibration", {{"test", "flow_ratio"}})})); + add("plate_slice", true, false, json::array({tile("slice_all", "Slice All Plates", {{"plates", "all"}, {"preview", true}})})); + add("view_set", true, false, + json::array({tile("view_top", "View: Top", {{"camera", "top"}}), collects("go_to_tab", "Go to tab...", "tab", "tab"), + collects("go_to_layer", "Go to layer (percent)", "percent", "layer_percent")})); + add("object_add_primitive", true, false, json::array({tile("add_primitive_cube", "Cube", {{"shape", "cube"}})})); + add("object_set_instances", true, false, json::array({tile("obj_set_instances", "Set Number of Instances", json::object())})); + json mirror_x = tile("obj_mirror_x", "Mirror X", {{"axis", "x"}}); + mirror_x["group"] = "Object"; + add("object_mirror", true, false, json::array({std::move(mirror_x), tile("obj_mirror_y", "Mirror Y", {{"axis", "y"}})})); + add("preset_export", true, false, json::array({tile("export_config", "Export Preset Bundle", json::object())})); + add("preset_sync", true, false, json::array({tile("sync_presets", "Sync Presets", json::object())})); + add("printer_send", true, false, json::array({tile("send_gcode", "Send G-code to printer host", json::object())})); + add("window_open", true, false, + json::array({tile("open_preferences", "Preferences", {{"window", "preferences"}}), + tile("preset_bundle", "Open Preset Bundle", {{"window", "preset_bundle"}})})); + add("plate_delete", true, true, json()); + add("export_drawing", false, true, json::array({tile("export_drawing_pdf", "Export as PDF", {{"format", "pdf"}})})); catalog.seal(); return catalog; } @@ -58,7 +84,7 @@ CommandCatalog tile_catalog() StepDescription describe(const std::string& step, const std::string& vars = "{}") { std::string err; - const auto replay = parse_replay(R"({"orca_replay_version": "0.1.0", "vars": )" + vars + R"(, "steps": [)" + step + "]}", err); + const auto replay = parse_replay(R"({"orca_replay_version": "0.2.0", "vars": )" + vars + R"(, "steps": [)" + step + "]}", err); INFO(err); REQUIRE(replay.has_value()); ReplayContext ctx; @@ -91,12 +117,12 @@ std::string action(const std::string& id, const json& command_args = json::objec json args{{"id", id}}; if (!command_args.empty()) args["args"] = command_args; - return json{{"tool", "run_action"}, {"args", args}}.dump(); + return json{{"tool", "action_run"}, {"args", args}}.dump(); } } // namespace -TEST_CASE("open_files is flagged by what it opens", "[Mcp]") +TEST_CASE("project_open replaces the project and project_import adds to it", "[Mcp]") { struct Case { @@ -106,14 +132,14 @@ TEST_CASE("open_files is flagged by what it opens", "[Mcp]") std::string replace; }; const Case c = GENERATE(values({ - {R"({"tool": "open_files", "args": {"paths": ["C:/a/p.3mf"]}})", "{}", {"replaces_project"}, "checked"}, - {R"({"tool": "open_files", "args": {"paths": ["C:/a/p.3mf"], "as": "geometry"}})", "{}", {}, ""}, - {R"({"tool": "open_files", "args": {"paths": ["C:/a/p.3mf", "C:/a/b.stl"]}})", "{}", {}, ""}, - {R"({"tool": "open_files", "args": {"paths": ["C:/a/b.stl"]}})", "{}", {}, ""}, - {R"({"tool": "open_files", "args": {"paths": ["C:/a/m.step"]}})", "{}", {}, ""}, - {R"({"tool": "open_files", "args": {"paths": ["C:/a/x.gcode"]}})", "{}", {"replaces_project"}, "app_asked"}, - {R"({"tool": "open_files", "args": {"paths": ["${vars.project}"]}})", R"({"project": "C:/a/p.3mf"})", + {R"({"tool": "project_open", "args": {"path": "C:/a/p.3mf"}})", "{}", {"replaces_project"}, "checked"}, + {R"({"tool": "project_open", "args": {"path": "C:/a/x.gcode"}})", "{}", {"replaces_project"}, "app_asked"}, + {R"({"tool": "project_open", "args": {"path": "C:/a/b.stl"}})", "{}", {}, ""}, + {R"({"tool": "project_open", "args": {"path": "${vars.project}"}})", R"({"project": "C:/a/p.3mf"})", {"replaces_project"}, "checked"}, + {R"({"tool": "project_import", "args": {"paths": ["C:/a/p.3mf"]}})", "{}", {}, ""}, + {R"({"tool": "project_import", "args": {"paths": ["C:/a/p.3mf", "C:/a/b.stl"]}})", "{}", {}, ""}, + {R"({"tool": "project_import", "args": {"paths": ["C:/a/m.step"]}})", "{}", {}, ""}, })); INFO(c.step); const StepDescription d = describe(c.step, c.vars); @@ -123,31 +149,37 @@ TEST_CASE("open_files is flagged by what it opens", "[Mcp]") TEST_CASE("project tools replace the project after checking for unsaved changes", "[Mcp]") { - const StepDescription fresh = describe(R"({"tool": "new_project", "args": {"discard_changes": true}})"); + const StepDescription fresh = describe(R"({"tool": "project_new", "args": {"discard_changes": true}})"); CHECK(flags_of(fresh) == Flags{"replaces_project"}); CHECK(fresh.replace == "checked"); - const StepDescription calib = describe(R"({"tool": "generate_calibration_test", "args": {"test": "temperature"}})"); + const StepDescription calib = describe(R"({"tool": "calibration_generate_test", "args": {"test": "temperature", "start": 230}})"); CHECK(flags_of(calib) == Flags{"changes_presets", "replaces_project"}); CHECK(calib.replace == "checked"); // Silent with its defaults, it checks as with arguments; with none, it asks as New Project does. - CHECK(describe(R"({"tool": "new_project", "args": {"silent": true}})").replace == "checked"); - const StepDescription asked = describe(R"({"tool": "new_project", "args": {}})"); + CHECK(describe(R"({"tool": "project_new", "args": {"silent": true}})").replace == "checked"); + const StepDescription asked = describe(R"({"tool": "project_new", "args": {}})"); CHECK(flags_of(asked) == Flags{"replaces_project"}); CHECK(asked.replace == "app_asked"); + // A test called with its tile's arguments opens its dialog, as the Calibration menu does. + const StepDescription dialog = describe(R"({"tool": "calibration_generate_test", "args": {"test": "flow_ratio"}})"); + CHECK(flags_of(dialog) == Flags{"changes_presets", "replaces_project"}); + CHECK(dialog.replace == "app_asked"); } TEST_CASE("a command called by name is described as its tile is", "[Mcp]") { - const auto [key, args, flags] = GENERATE_COPY(table({ - {"load_project", {{"path", abs_path("p.3mf")}}, {"replaces_project"}}, - {"export_stl", {{"path", abs_path("a.stl")}}, {"writes_file"}}, - {"sync_presets", json::object(), {"changes_presets"}}, + const auto [key, tile_key, args, flags] = GENERATE_COPY(table({ + {"preset_export", "export_config", json::object(), {"writes_file"}}, + {"preset_sync", "sync_presets", json::object(), {"changes_presets"}}, + {"window_open", "preset_bundle", {{"window", "preset_bundle"}}, {"changes_presets"}}, + {"printer_send", "send_gcode", json::object(), {"sends_to_printer"}}, + {"plate_delete", "plate_delete", json::object(), {}}, })); INFO(key << " " << args.dump()); const StepDescription by_name = describe(json{{"tool", key}, {"args", args}}.dump()); - const StepDescription tile = describe(action("orca_command:" + key + ":orca", args)); + const StepDescription tile = describe(action("orca_command:" + tile_key + ":orca")); CHECK(flags_of(by_name) == flags); CHECK(flags_of(by_name) == flags_of(tile)); CHECK(by_name.replace == tile.replace); @@ -158,8 +190,10 @@ TEST_CASE("a command called by name is described as its tile is", "[Mcp]") TEST_CASE("a tile that runs its command with arguments is described as that call is", "[Mcp]") { const auto [key, tile, args, flags] = GENERATE_COPY(table({ - {"export_drawing", "export_drawing_pdf", {{"format", "pdf"}}, {"writes_file"}}, - {"calib_sample", "calib_sample_cube", json::object(), {"changes_presets", "replaces_project"}}, + {"project_export", "export_gcode", {{"format", "gcode"}}, {"writes_file"}}, + {"calibration_generate_test", "calib_flow_ratio", {{"test", "flow_ratio"}}, {"changes_presets", "replaces_project"}}, + {"object_set_instances", "obj_set_instances", json::object(), {}}, + {"object_mirror", "obj_mirror_y", {{"axis", "y"}}, {}}, })); INFO(key << " " << args.dump()); const json what{{"kind", "command"}, {"key", key}, {"tile", tile}}; @@ -174,7 +208,8 @@ TEST_CASE("a tile that runs its command with arguments is described as that call CHECK(d->replace == picked.replace); } CHECK(describe_call(tile_catalog(), key, args) == what); - CHECK(describe_call(tile_catalog(), "run_action", {{"id", id}}) == what); + CHECK(describe_call(tile_catalog(), "action_run", {{"id", id}}) == what); + CHECK(describe_call(tile_catalog(), "action_run", {{"id", tile}}) == what); } TEST_CASE("a call with other arguments than a tile's is described by its arguments", "[Mcp]") @@ -185,28 +220,53 @@ TEST_CASE("a call with other arguments than a tile's is described by its argumen // The command's own tile with the other tile's arguments is that tile. CHECK(describe(action("orca_command:export_drawing:orca", {{"format", "pdf"}})).what == json{{"kind", "command"}, {"key", "export_drawing"}, {"tile", "export_drawing_pdf"}}); + // A command made from rows called with arguments no tile has is described as a typed tool's call, with what it + // does whichever way it is called. + const StepDescription exported = describe(json{{"tool", "preset_export"}, {"args", {{"path", abs_path("presets")}}}}.dump()); + CHECK(exported.what == json{{"kind", "files"}, {"names", {"presets"}}}); + CHECK(flags_of(exported) == Flags{"writes_file"}); + CHECK(flags_of(describe(json{{"tool", "preset_import"}, {"args", {{"path", abs_path("a.json")}}}}.dump())) == Flags{"changes_presets"}); +} + +TEST_CASE("a tile that collects a value is described with it, and a call without it is no tile", "[Mcp]") +{ + // Go to layer's percent reaches view_set as layer_percent, which the description shows with the tile. + CHECK(describe(action("orca_command:go_to_layer:orca", {{"percent", 50}})).what == + json{{"kind", "command"}, {"key", "view_set"}, {"tile", "go_to_layer"}, {"args", {"layer_percent: 50"}}}); + CHECK(describe(action("orca_command:go_to_tab:orca", {{"tab", "preview"}})).what == + json{{"kind", "command"}, {"key", "view_set"}, {"tile", "go_to_tab"}, {"args", {"tab: preview"}}}); + // view_set called with no arguments is no tile's call: the two tiles with nothing of their own collect a value. + CHECK(describe_call(tile_catalog(), "view_set", json::object()).is_null()); + CHECK(describe_call(tile_catalog(), "view_set", {{"camera", "top"}}) == + json{{"kind", "command"}, {"key", "view_set"}, {"tile", "view_top"}}); } TEST_CASE("a step that calls a tile's command by its key is described from the catalog it is given", "[Mcp]") { std::string err; - const auto replay = parse_replay(R"({"orca_replay_version": "0.1.0", "steps": [{"tool": "export_stl", "args": {"path": "C:/a.stl"}}]})", err); + const auto replay = parse_replay(R"({"orca_replay_version": "0.2.0", "steps": [ + {"tool": "filament_delete", "args": {}}, + {"tool": "filament_delete", "args": {"filament_slot": 2}}]})", + err); INFO(err); REQUIRE(replay.has_value()); ReplayContext ctx; ctx.out_dir = "C:/out"; + // filament_delete as the app's catalog has it: listed, with a tile of its own. CommandCatalog catalog; - NativeCommand export_stl; - export_stl.key = "export_stl"; - export_stl.in_palette = true; - export_stl.listed = false; - catalog.add(std::move(export_stl)); + NativeCommand filament_delete; + filament_delete.key = "filament_delete"; + filament_delete.in_palette = true; + filament_delete.listed = true; + catalog.add(std::move(filament_delete)); catalog.seal(); const StepDescription tile = describe_step(catalog, replay->steps[0], *replay, ctx); REQUIRE(tile.what.is_object()); CHECK(tile.what.value("kind", "") == "command"); - CHECK(tile.what.value("key", "") == "export_stl"); + CHECK(tile.what.value("key", "") == "filament_delete"); + // With arguments of its own it is its silent form, described from them as a typed tool's call is. + CHECK(describe_step(catalog, replay->steps[1], *replay, ctx).what == json{{"kind", "value"}, {"text", "filament_slot: 2"}}); // Without the command in the catalog, the step is described from its arguments, as a typed tool's call is. const StepDescription unknown = describe_step(CommandCatalog(), replay->steps[0], *replay, ctx); @@ -216,36 +276,46 @@ TEST_CASE("a step that calls a tile's command by its key is described from the c TEST_CASE("speed dial actions are flagged by their id", "[Mcp]") { + // A tile's id reaches its command through find_tile(), and the command and its arguments decide the flags: a tile's + // call and a call of its command with those arguments, or with a path beside them, are flagged alike. struct Case { - std::string id; - json args; + std::string step; Flags flags; std::string replace; }; - const json none = json::object(); - const Case c = GENERATE_COPY(values({ - {"orca_command:calib_flow_ratio:orca", none, {"changes_presets", "replaces_project"}, "app_asked"}, - {"orca_command:send_gcode:orca", none, {"sends_to_printer"}, ""}, - {"orca_command:open_preferences:orca", none, {}, ""}, - {"orca_command:slice_all:orca", none, {}, ""}, - {"orca_command:export_gcode:orca", {{"path", "C:/x/a.gcode"}}, {"writes_file"}, ""}, - {"orca_command:export_gcode:orca", none, {"writes_file"}, ""}, - {"orca_command:export_config:orca", {{"path", "C:/x"}}, {"writes_file"}, ""}, - {"orca_command:obj_set_instances:orca", {{"count", 3}}, {}, ""}, - {"orca_command:save_project_as:orca", {{"path", "C:/x/a.3mf"}, {"overwrite", true}}, {"writes_file"}, ""}, - {"orca_command:new_project:orca", none, {"replaces_project"}, "app_asked"}, - {"orca_command:import_file:orca", {{"path", abs_path("p.3mf")}}, {}, ""}, - {"orca_command:import_file:orca", {{"path", abs_path("x.gcode")}}, {}, ""}, - {"orca_command:import_file:orca", {{"path", abs_path("b.stl")}}, {}, ""}, - {"orca_recent_project:C:/p/a.3mf:orca", none, {"replaces_project"}, "app_asked"}, - {"orca_plate_goto:1:orca", none, {}, ""}, - {"orca_setting:layer_height:1", none, {}, ""}, - {"plugin_replay_action:tool:plugin", none, kEveryFlag, "app_asked"}, - {"plugin_page_action:page:plugin", none, kEveryFlag, "app_asked"}, + const Case c = GENERATE_COPY(values({ + {action("orca_command:calib_flow_ratio:orca"), {"changes_presets", "replaces_project"}, "app_asked"}, + {action("orca_command:send_gcode:orca"), {"sends_to_printer"}, ""}, + {action("orca_command:open_preferences:orca"), {}, ""}, + {action("orca_command:slice_all:orca"), {}, ""}, + {action("orca_command:export_gcode:orca"), {"writes_file"}, ""}, + {action("orca_command:export_config:orca"), {"writes_file"}, ""}, + {action("orca_command:sync_presets:orca"), {"changes_presets"}, ""}, + {action("orca_command:preset_bundle:orca"), {"changes_presets"}, ""}, + {action("orca_command:obj_set_instances:orca"), {}, ""}, + {action("orca_command:save_project_as:orca"), {"writes_file"}, ""}, + {action("orca_command:new_project:orca"), {"replaces_project"}, "app_asked"}, + {action("orca_command:load_project:orca"), {"replaces_project"}, "app_asked"}, + {action("orca_command:import_file:orca"), {}, ""}, + // A tile by the key inside its id, as action_run takes it. + {action("export_gcode"), {"writes_file"}, ""}, + {action("new_project"), {"replaces_project"}, "app_asked"}, + {action("send_gcode"), {"sends_to_printer"}, ""}, + {action("plate_delete"), {}, ""}, + {action("go_to_layer", {{"percent", 50}}), {}, ""}, + {json{{"tool", "project_export"}, {"args", {{"format", "gcode"}}}}.dump(), {"writes_file"}, ""}, + {json{{"tool", "project_export"}, {"args", {{"format", "gcode"}, {"path", abs_path("a.gcode")}}}}.dump(), {"writes_file"}, ""}, + {action("orca_recent_project:C:/p/a.3mf:orca"), {"replaces_project"}, "app_asked"}, + {action("orca_plate_goto:1:orca"), {}, ""}, + {action("orca_setting:layer_height:1"), {}, ""}, + {action("plugin_replay_action:tool:plugin"), kEveryFlag, "app_asked"}, + {action("plugin_page_action:page:plugin"), kEveryFlag, "app_asked"}, + // A name inside an id that is no tile may be another action's, whose effect can't be read. + {action("page"), kEveryFlag, "app_asked"}, })); - INFO(c.id << " " << c.args.dump()); - const StepDescription d = describe(action(c.id, c.args)); + INFO(c.step); + const StepDescription d = describe(c.step); CHECK(flags_of(d) == c.flags); CHECK(d.replace == c.replace); } @@ -260,14 +330,21 @@ TEST_CASE("speed dial actions describe their command and file", "[Mcp]") { const json none = json::object(); const auto [id, args, what] = GENERATE_COPY(table({ - {"orca_command:import_file:orca", {{"path", abs_path("p.3mf")}}, {{"kind", "command"}, {"key", "import_file"}, {"args", {"path: p.3mf"}}}}, - {"orca_command:save_project_as:orca", {{"path", abs_path("p.3mf")}, {"overwrite", true}}, - {{"kind", "command"}, {"key", "save_project_as"}, {"args", {"overwrite: true", "path: p.3mf"}}}}, - {"orca_command:import_file:orca", {{"path", "models/x.gcode"}}, {{"kind", "command"}, {"key", "import_file"}, {"args", {"path: x.gcode"}}}}, - {"orca_command:go_to_layer:orca", {{"percent", 50}}, {{"kind", "command"}, {"key", "go_to_layer"}, {"args", {"percent: 50"}}}}, - {"orca_command:add_primitive_cube:orca", {{"size", {20, 20, 20}}}, - {{"kind", "command"}, {"key", "add_primitive_cube"}, {"args", {"size: [20,20,20]"}}}}, - {"orca_command:slice_all:orca", none, {{"kind", "command"}, {"key", "slice_all"}}}, + {"orca_command:import_file:orca", none, {{"kind", "command"}, {"key", "project_import"}, {"tile", "import_file"}}}, + {"orca_command:save_project_as:orca", none, {{"kind", "command"}, {"key", "project_save"}, {"tile", "save_project_as"}}}, + {"orca_command:export_config:orca", none, {{"kind", "command"}, {"key", "preset_export"}, {"tile", "export_config"}}}, + {"orca_command:go_to_layer:orca", {{"percent", 50}}, + {{"kind", "command"}, {"key", "view_set"}, {"tile", "go_to_layer"}, {"args", {"layer_percent: 50"}}}}, + {"orca_command:add_primitive_cube:orca", none, {{"kind", "command"}, {"key", "object_add_primitive"}, {"tile", "add_primitive_cube"}}}, + {"orca_command:slice_all:orca", none, {{"kind", "command"}, {"key", "plate_slice"}, {"tile", "slice_all"}}}, + // A tile with a Speed Dial section of its own is described as any other. + {"orca_command:obj_mirror_x:orca", none, {{"kind", "command"}, {"key", "object_mirror"}, {"tile", "obj_mirror_x"}}}, + {"orca_command:obj_mirror_y:orca", none, {{"kind", "command"}, {"key", "object_mirror"}, {"tile", "obj_mirror_y"}}}, + // A tile by the key inside its id, as action_run takes it, a command's own tile among them. + {"export_gcode", none, {{"kind", "command"}, {"key", "project_export"}, {"tile", "export_gcode"}}}, + {"go_to_layer", {{"percent", 50}}, + {{"kind", "command"}, {"key", "view_set"}, {"tile", "go_to_layer"}, {"args", {"layer_percent: 50"}}}}, + {"plate_delete", none, {{"kind", "command"}, {"key", "plate_delete"}}}, {"orca_recent_project:C:/p/a.3mf:orca", none, {{"kind", "recent_project"}, {"name", "a.3mf"}}}, {"orca_setting:layer_height:1", none, {{"kind", "value"}, {"text", "layer_height"}}}, {"plugin_replay_action:tool:plugin", none, {{"kind", "value"}, {"text", "plugin_replay_action:tool:plugin"}}}, @@ -279,27 +356,27 @@ TEST_CASE("speed dial actions describe their command and file", "[Mcp]") TEST_CASE("files written inside the output folder are not flagged", "[Mcp]") { const auto [step, flags] = GENERATE(table({ - {R"({"tool": "screenshot", "args": {"save_path": "C:/out/a.png"}})", {}}, - {R"({"tool": "screenshot", "args": {"save_path": "${out_dir}/a.png"}})", {}}, - {R"({"tool": "screenshot", "args": {"save_path": "C:/x/a.png"}})", {"writes_file"}}, - {R"({"tool": "screenshot", "args": {"target": "canvas"}})", {}}, - {R"({"tool": "export_replay", "args": {"path": "${out_dir}/s.json"}})", {}}, - {R"({"tool": "export_replay", "args": {"path": "C:/x/s.json"}})", {"writes_file"}}, - {R"({"tool": "pick_gizmo_file", "args": {"action": "svg_save_as", "path": "C:/x/a.svg"}})", {"writes_file"}}, - {R"({"tool": "pick_gizmo_file", "args": {"action": "svg_change", "path": "C:/x/a.svg"}})", {}}, + {R"({"tool": "window_screenshot", "args": {"save_path": "C:/out/a.png"}})", {}}, + {R"({"tool": "window_screenshot", "args": {"save_path": "${out_dir}/a.png"}})", {}}, + {R"({"tool": "window_screenshot", "args": {"save_path": "C:/x/a.png"}})", {"writes_file"}}, + {R"({"tool": "window_screenshot", "args": {"target": "canvas"}})", {}}, + {R"({"tool": "replay_export", "args": {"path": "${out_dir}/s.json"}})", {}}, + {R"({"tool": "replay_export", "args": {"path": "C:/x/s.json"}})", {"writes_file"}}, + {R"({"tool": "gizmo_pick_file", "args": {"action": "svg_save_as", "path": "C:/x/a.svg"}})", {"writes_file"}}, + {R"({"tool": "gizmo_pick_file", "args": {"action": "svg_change", "path": "C:/x/a.svg"}})", {}}, // A path rule may answer a save picker, so its path is a file the step may write. - {R"({"tool": "auto_answer_dialogs", "args": {"rules": [{"match": "Save", "button": "ok", "path": "C:/x/a.3mf"}]}})", {"writes_file"}}, - {R"({"tool": "auto_answer_dialogs", "args": {"rules": [{"match": "Save", "button": "ok", "path": "${out_dir}/a.3mf"}]}})", {}}, - {R"({"tool": "auto_answer_dialogs", "args": {"rules": [{"match": "Save", "button": "cancel"}]}})", {}}, - {R"({"tool": "auto_answer_dialogs", "args": {"rules": [{"match": "Discard", "button": "no"}, {"match": "Save", "button": "ok", "path": "C:/x/a.3mf", "overwrite": true}]}})", + {R"({"tool": "dialog_auto_answer", "args": {"rules": [{"match": "Save", "button": "ok", "path": "C:/x/a.3mf"}]}})", {"writes_file"}}, + {R"({"tool": "dialog_auto_answer", "args": {"rules": [{"match": "Save", "button": "ok", "path": "${out_dir}/a.3mf"}]}})", {}}, + {R"({"tool": "dialog_auto_answer", "args": {"rules": [{"match": "Save", "button": "cancel"}]}})", {}}, + {R"({"tool": "dialog_auto_answer", "args": {"rules": [{"match": "Discard", "button": "no"}, {"match": "Save", "button": "ok", "path": "C:/x/a.3mf", "overwrite": true}]}})", {"writes_file"}}, // An encode deletes its source unless it keeps the raw video file. - {R"({"tool": "encode_recording", "args": {"path": "C:/x/a.mkv", "save_path": "${out_dir}/a.mp4"}})", {"writes_file"}}, - {R"({"tool": "encode_recording", "args": {"path": "C:/x/a.mkv", "save_path": "${out_dir}/a.mp4", "keep_raw_video_file": true}})", {}}, - {R"({"tool": "encode_recording", "args": {"path": "${out_dir}/a.mkv"}})", {}}, - {R"({"tool": "export", "args": {"path": "${out_dir}/a.gcode"}})", {"writes_file"}}, - {R"({"tool": "save_preset", "args": {"type": "filament", "name": "Mine"}})", {"changes_presets"}}, - {R"({"tool": "delete_preset", "args": {"type": "filament", "name": "Mine"}})", {"changes_presets"}}, + {R"({"tool": "recording_encode", "args": {"path": "C:/x/a.mkv", "save_path": "${out_dir}/a.mp4"}})", {"writes_file"}}, + {R"({"tool": "recording_encode", "args": {"path": "C:/x/a.mkv", "save_path": "${out_dir}/a.mp4", "keep_raw_video_file": true}})", {}}, + {R"({"tool": "recording_encode", "args": {"path": "${out_dir}/a.mkv"}})", {}}, + {R"({"tool": "project_export", "args": {"path": "${out_dir}/a.gcode"}})", {"writes_file"}}, + {R"({"tool": "preset_save", "args": {"type": "filament", "name": "Mine"}})", {"changes_presets"}}, + {R"({"tool": "preset_delete", "args": {"type": "filament", "name": "Mine"}})", {"changes_presets"}}, })); INFO(step); CHECK(flags_of(describe(step)) == flags); @@ -308,13 +385,13 @@ TEST_CASE("files written inside the output folder are not flagged", "[Mcp]") TEST_CASE("steps that can answer a dialog are told apart", "[Mcp]") { const auto [tool, answers] = GENERATE(table({ - {"auto_answer_dialogs", true}, - {"answer_dialog", true}, - {"click", true}, - {"press_keys", true}, - {"set_widget_value", false}, + {"dialog_auto_answer", true}, + {"dialog_answer", true}, + {"widget_click", true}, + {"keyboard_press", true}, + {"widget_set_value", false}, {"mouse_gesture", false}, - {"run_javascript", false}, + {"webview_run_javascript", false}, })); INFO(tool); const StepDescription d = describe(json{{"tool", tool}}.dump()); @@ -325,67 +402,67 @@ TEST_CASE("steps that can answer a dialog are told apart", "[Mcp]") TEST_CASE("nested replays join their steps' descriptions", "[Mcp]") { const StepDescription replacing = describe( - R"({"tool": "run_replay", "args": {"replay": {"orca_replay_version": "0.1.0", "steps": [{"tool": "new_project", "args": {"discard_changes": true}}]}}})"); + R"({"tool": "replay_run", "args": {"replay": {"orca_replay_version": "0.2.0", "steps": [{"tool": "project_new", "args": {"discard_changes": true}}]}}})"); CHECK(flags_of(replacing) == Flags{"replaces_project"}); CHECK(replacing.replace == "checked"); CHECK(replacing.what == json{{"kind", "replay"}, {"steps", 1}}); // An inline replay given as JSON text, comments included, reads as its object does. - const std::string text = "// starts over\n" R"({"orca_replay_version": "0.1.0", "steps": [{"tool": "new_project", "args": {"discard_changes": true}}]})"; - const StepDescription as_text = describe(json{{"tool", "run_replay"}, {"args", {{"replay", text}}}}.dump()); + const std::string text = "// starts over\n" R"({"orca_replay_version": "0.2.0", "steps": [{"tool": "project_new", "args": {"discard_changes": true}}]})"; + const StepDescription as_text = describe(json{{"tool", "replay_run"}, {"args", {{"replay", text}}}}.dump()); CHECK(flags_of(as_text) == Flags{"replaces_project"}); CHECK(as_text.what == json{{"kind", "replay"}, {"steps", 1}}); const StepDescription own_output = describe( - R"({"tool": "run_replay", "args": {"replay": {"orca_replay_version": "0.1.0", "steps": [{"tool": "screenshot", "args": {"save_path": "${out_dir}/n.png"}}]}}})"); + R"({"tool": "replay_run", "args": {"replay": {"orca_replay_version": "0.2.0", "steps": [{"tool": "window_screenshot", "args": {"save_path": "${out_dir}/n.png"}}]}}})"); CHECK(flags_of(own_output).empty()); // The outer replay substitutes an inline replay's placeholders before the nested run starts, as - // run_replay does: the step's own vars come too late, and its out_dir doesn't move ${out_dir}. + // replay_run does: the step's own vars come too late, and its out_dir doesn't move ${out_dir}. const StepDescription outer_vars = describe( - R"({"tool": "run_replay", "args": {"replay": {"orca_replay_version": "0.1.0", "steps": [{"tool": "open_files", "args": {"paths": ["${vars.p}"]}}]}}})", + R"({"tool": "replay_run", "args": {"replay": {"orca_replay_version": "0.2.0", "steps": [{"tool": "project_open", "args": {"path": "${vars.p}"}}]}}})", R"({"p": "C:/a/p.3mf"})"); CHECK(flags_of(outer_vars) == Flags{"replaces_project"}); CHECK(outer_vars.replace == "checked"); const StepDescription step_vars = describe( - R"({"tool": "run_replay", "args": {"vars": {"p": "C:/a/p.3mf"}, "replay": {"orca_replay_version": "0.1.0", "vars": {"p": "C:/a/q.3mf"}, "steps": [{"tool": "open_files", "args": {"paths": ["${vars.p}"]}}]}}})"); + R"({"tool": "replay_run", "args": {"vars": {"p": "C:/a/p.3mf"}, "replay": {"orca_replay_version": "0.2.0", "vars": {"p": "C:/a/q.3mf"}, "steps": [{"tool": "project_open", "args": {"path": "${vars.p}"}}]}}})"); CHECK(flags_of(step_vars).empty()); CHECK(step_vars.replace == ""); const StepDescription own_folder = describe( - R"({"tool": "run_replay", "args": {"out_dir": "C:/elsewhere", "replay": {"orca_replay_version": "0.1.0", "steps": [{"tool": "screenshot", "args": {"save_path": "${out_dir}/n.png"}}]}}})"); + R"({"tool": "replay_run", "args": {"out_dir": "C:/elsewhere", "replay": {"orca_replay_version": "0.2.0", "steps": [{"tool": "window_screenshot", "args": {"save_path": "${out_dir}/n.png"}}]}}})"); CHECK(flags_of(own_folder).empty()); const StepDescription mixed = describe( - R"({"tool": "run_replay", "args": {"replay": {"orca_replay_version": "0.1.0", "steps": [{"tool": "run_action", "args": {"id": "orca_command:new_project:orca"}}, {"tool": "new_project", "args": {"silent": true}}]}}})"); + R"({"tool": "replay_run", "args": {"replay": {"orca_replay_version": "0.2.0", "steps": [{"tool": "action_run", "args": {"id": "orca_command:new_project:orca"}}, {"tool": "project_new", "args": {"silent": true}}]}}})"); CHECK(mixed.replace == "checked"); const StepDescription clicking = describe( - R"({"tool": "run_replay", "args": {"replay": {"orca_replay_version": "0.1.0", "steps": [{"tool": "click", "args": {"target": {"label": "No"}}}]}}})"); + R"({"tool": "replay_run", "args": {"replay": {"orca_replay_version": "0.2.0", "steps": [{"tool": "widget_click", "args": {"target": {"label": "No"}}}]}}})"); CHECK(clicking.answers_dialogs); // Five levels of nesting: past the inspection depth, so the effect can't be read. - std::string deep = R"({"orca_replay_version": "0.1.0", "steps": [{"tool": "new_project"}]})"; + std::string deep = R"({"orca_replay_version": "0.2.0", "steps": [{"tool": "project_new"}]})"; for (int i = 0; i < 5; ++i) - deep = R"({"orca_replay_version": "0.1.0", "steps": [{"tool": "run_replay", "args": {"replay": )" + deep + "}}]}"; - const StepDescription too_deep = describe(R"({"tool": "run_replay", "args": {"replay": )" + deep + "}}"); + deep = R"({"orca_replay_version": "0.2.0", "steps": [{"tool": "replay_run", "args": {"replay": )" + deep + "}}]}"; + const StepDescription too_deep = describe(R"({"tool": "replay_run", "args": {"replay": )" + deep + "}}"); CHECK(flags_of(too_deep) == kEveryFlag); CHECK(too_deep.replace == "checked"); CHECK(too_deep.answers_dialogs); CHECK(too_deep.what == json{{"kind", "replay"}, {"steps", 1}}); - const StepDescription invalid = describe(R"({"tool": "run_replay", "args": {"replay": {"orca_replay_version": "0.1.0", "steps": [{"tool": 3}]}}})"); + const StepDescription invalid = describe(R"({"tool": "replay_run", "args": {"replay": {"orca_replay_version": "0.2.0", "steps": [{"tool": 3}]}}})"); CHECK(flags_of(invalid) == kEveryFlag); REQUIRE(invalid.what.value("kind", "") == "value"); CHECK(invalid.what.value("text", "").find("step 1") != std::string::npos); - const StepDescription broken_text = describe(json{{"tool", "run_replay"}, {"args", {{"replay", "{\"orca_replay_version\": \"0.1.0\",\n \"steps\": ["}}}}.dump()); + const StepDescription broken_text = describe(json{{"tool", "replay_run"}, {"args", {{"replay", "{\"orca_replay_version\": \"0.2.0\",\n \"steps\": ["}}}}.dump()); CHECK(flags_of(broken_text) == kEveryFlag); REQUIRE(broken_text.what.value("kind", "") == "value"); CHECK(broken_text.what.value("text", "").find("line 2") != std::string::npos); - const StepDescription missing = describe(R"({"tool": "run_replay", "args": {"path": "C:/no/such/replay.json"}})"); + const StepDescription missing = describe(R"({"tool": "replay_run", "args": {"path": "C:/no/such/replay.json"}})"); CHECK(flags_of(missing) == kEveryFlag); CHECK(missing.replace == "checked"); CHECK(missing.answers_dialogs); @@ -396,12 +473,12 @@ TEST_CASE("nested replays join their steps' descriptions", "[Mcp]") // to a job id such as "j12", never a path, so the effects read the same either way. TEST_CASE("saved jobs don't change a step's flags", "[Mcp]") { - const std::string step = GENERATE(as{}, R"({"tool": "open_files", "args": {"paths": ["${jobs.p}"]}})", - R"({"tool": "screenshot", "args": {"save_path": "${jobs.p}/a.png"}})", - R"({"tool": "run_action", "args": {"id": "orca_command:import_file:orca", "args": {"path": "${jobs.p}"}}})"); + const std::string step = GENERATE(as{}, R"({"tool": "project_open", "args": {"path": "${jobs.p}"}})", + R"({"tool": "window_screenshot", "args": {"save_path": "${jobs.p}/a.png"}})", + R"({"tool": "preset_export", "args": {"path": "${jobs.p}"}})"); INFO(step); std::string err; - const auto replay = parse_replay(R"({"orca_replay_version": "0.1.0", "steps": [)" + step + "]}", err); + const auto replay = parse_replay(R"({"orca_replay_version": "0.2.0", "steps": [)" + step + "]}", err); REQUIRE(replay.has_value()); ReplayContext without; without.out_dir = "C:/out"; @@ -417,19 +494,19 @@ TEST_CASE("saved jobs don't change a step's flags", "[Mcp]") TEST_CASE("a step's what names what it acts on", "[Mcp]") { const auto [step, what] = GENERATE(table({ - {R"({"tool": "set_settings", "args": {"values": {"layer_height": 0.12, "wall_loops": "3"}}})", + {R"({"tool": "settings_set", "args": {"values": {"layer_height": 0.12, "wall_loops": "3"}}})", {{"kind", "settings"}, {"pairs", {"layer_height = 0.12", "wall_loops = 3"}}}}, - {R"({"tool": "open_files", "args": {"paths": ["C:/m/3DBenchy.stl", "C:/m/cube.stl"]}})", + {R"({"tool": "project_import", "args": {"paths": ["C:/m/3DBenchy.stl", "C:/m/cube.stl"]}})", {{"kind", "files"}, {"names", {"3DBenchy.stl", "cube.stl"}}}}, - {R"({"tool": "screenshot", "args": {"save_path": "${out_dir}/preview.png"}})", {{"kind", "files"}, {"names", {"preview.png"}}}}, - {R"({"tool": "slice"})", {{"kind", "plates"}, {"plates", "current"}}}, - {R"({"tool": "slice", "args": {"plates": 2}})", {{"kind", "plates"}, {"plates", 2}}}, - {R"({"tool": "arrange"})", {{"kind", "plates"}, {"plates", "all"}}}, - {R"({"tool": "select_preset", "args": {"type": "filament", "name": "Generic PLA"}})", {{"kind", "preset"}, {"name", "Generic PLA"}}}, - {R"({"tool": "wait", "args": {"for": "idle"}})", {{"kind", "value"}, {"text", "idle"}}}, - {R"({"tool": "answer_dialog", "args": {"button": "no"}})", {{"kind", "value"}, {"text", "no"}}}, - {R"({"tool": "transform", "args": {"object": 1}})", {{"kind", "value"}, {"text", "object: 1"}}}, - {R"({"tool": "get_app_state"})", nullptr}, + {R"({"tool": "window_screenshot", "args": {"save_path": "${out_dir}/preview.png"}})", {{"kind", "files"}, {"names", {"preview.png"}}}}, + {R"({"tool": "plate_slice"})", {{"kind", "plates"}, {"plates", "current"}}}, + {R"({"tool": "plate_slice", "args": {"plates": 2}})", {{"kind", "plates"}, {"plates", 2}}}, + {R"({"tool": "object_arrange"})", {{"kind", "plates"}, {"plates", "all"}}}, + {R"({"tool": "preset_select", "args": {"type": "filament", "name": "Generic PLA"}})", {{"kind", "preset"}, {"name", "Generic PLA"}}}, + {R"({"tool": "app_wait", "args": {"for": "idle"}})", {{"kind", "value"}, {"text", "idle"}}}, + {R"({"tool": "dialog_answer", "args": {"button": "no"}})", {{"kind", "value"}, {"text", "no"}}}, + {R"({"tool": "object_transform", "args": {"object": 1}})", {{"kind", "value"}, {"text", "object: 1"}}}, + {R"({"tool": "app_state"})", nullptr}, })); INFO(step); CHECK(describe(step).what == what); @@ -437,23 +514,23 @@ TEST_CASE("a step's what names what it acts on", "[Mcp]") TEST_CASE("a step with an expect checks its result", "[Mcp]") { - CHECK(describe(R"({"tool": "slice", "expect": {"/plates/0/outcome": {"eq": "ok"}}})").checks_result); - CHECK_FALSE(describe(R"({"tool": "slice"})").checks_result); + CHECK(describe(R"({"tool": "plate_slice", "expect": {"/plates/0/outcome": {"eq": "ok"}}})").checks_result); + CHECK_FALSE(describe(R"({"tool": "plate_slice"})").checks_result); } TEST_CASE("results are described from the tools' real replies", "[Mcp]") { - CHECK(describe_result("open_files", {{"objects", 1}, {"names", {"Benchy"}}, {"plates", 1}}) == json{{"kind", "objects"}, {"count", 1}}); - CHECK(describe_result("generate_calibration_test", {{"objects", 3}, {"plates", 1}}) == json{{"kind", "objects"}, {"count", 3}}); - CHECK(describe_result("open_files", {{"opened", "gcode"}, {"path", "C:/a/x.gcode"}}) == json{{"kind", "file"}, {"name", "x.gcode"}}); - CHECK(describe_result("slice", {{"plates", {{{"index", 0}, {"outcome", "ok"}}, {{"index", 1}, {"outcome", "error"}}}}}) == + CHECK(describe_result("project_import", {{"objects", 1}, {"names", {"Benchy"}}, {"plates", 1}}) == json{{"kind", "objects"}, {"count", 1}}); + CHECK(describe_result("calibration_generate_test", {{"objects", 3}, {"plates", 1}}) == json{{"kind", "objects"}, {"count", 3}}); + CHECK(describe_result("project_open", {{"opened", "gcode"}, {"path", "C:/a/x.gcode"}}) == json{{"kind", "file"}, {"name", "x.gcode"}}); + CHECK(describe_result("plate_slice", {{"plates", {{{"index", 0}, {"outcome", "ok"}}, {{"index", 1}, {"outcome", "error"}}}}}) == json{{"kind", "plates"}, {"ok", 1}, {"other", 1}}); - CHECK(describe_result("screenshot", {{"path", "C:/out/a.png"}}) == json{{"kind", "file"}, {"name", "a.png"}}); - CHECK(describe_result("pick_gizmo_file", {{"saved", "C:/x/a.svg"}}) == json{{"kind", "file"}, {"name", "a.svg"}}); - CHECK(describe_result("run_replay", {{"passed", false}, {"failed_step", 2}, {"steps", json::array()}}) == + CHECK(describe_result("window_screenshot", {{"path", "C:/out/a.png"}}) == json{{"kind", "file"}, {"name", "a.png"}}); + CHECK(describe_result("gizmo_pick_file", {{"saved", "C:/x/a.svg"}}) == json{{"kind", "file"}, {"name", "a.svg"}}); + CHECK(describe_result("replay_run", {{"passed", false}, {"failed_step", 2}, {"steps", json::array()}}) == json{{"kind", "replay"}, {"passed", false}, {"failed_step", 2}}); - CHECK(describe_result("run_replay", {{"passed", true}, {"steps", json::array()}}) == json{{"kind", "replay"}, {"passed", true}}); - CHECK(describe_result("get_app_state", {{"ready", true}}).is_null()); + CHECK(describe_result("replay_run", {{"passed", true}, {"steps", json::array()}}) == json{{"kind", "replay"}, {"passed", true}}); + CHECK(describe_result("app_state", {{"ready", true}}).is_null()); CHECK(result_files({{"saved", "C:/x/a.svg"}}) == std::vector{"C:/x/a.svg"}); CHECK(result_files({{"path", "C:/out/a.png"}}) == std::vector{"C:/out/a.png"}); diff --git a/tests/data/command_catalog.json b/tests/data/command_catalog.json index bf7350dd9f..563a8f9104 100644 --- a/tests/data/command_catalog.json +++ b/tests/data/command_catalog.json @@ -2,163 +2,250 @@ "commands": [ { "completion": "immediate", - "description": "Slice the current plate and show the Preview tab. Returns at once; use the slice tool to wait for the result.", + "description": "Find what does something, in one search, or look up one command. With query: the commands that match, best first, each with its group, the first sentence of its description and listed, whether the tool list shows it; one that is not listed (a menu row that takes no arguments, a Design tab command, or an operation a plugin offers, plugin..) comes with its input schema, and its description when that says more, which nothing else shows. Beside them, the best few matches of each other catalog, with its total and how to use it: actions (the Speed Dial's plates, recent projects and plugin scripts and pages), settings, and python (the orca API a script calls). The reply says how to call each kind of match. With tool: that command's description and input schema, and its examples when it has some (the Design commands do). With neither: every command's name. group keeps the names and the command matches to one group; the other catalogs' matches stay as they are. The Design tab's CAD commands follow by heading (sketches, solid and surface features, bodies, measurements); look one up with tool before calling it. A command whose schema has silent does what its menu row does when called with no arguments, unless silent is true. Document: describe_design, import_step, import_mesh, set_variable, commit_to_plate, new_design, export_step, select_geometry, confirm_tool, cancel_tool. Sketch: sketch_create, sketch_project, sketch_text, sketch_insert_svg, sketch_offset, sketch_trim, sketch_fillet, sketch_chamfer, sketch_mirror, sketch_dimension, sketch_constrain, sketch_toggle_construction, sketch_extend, sketch_delete, sketch_describe, sketch_validate, sketch_list_constraints, sketch_blend_curve, sketch_finish, sketch_cancel, sketch_edit, sketch_draw, sketch_select, sketch_repair, sketch_set_value, sketch_transform, sketch_pattern, sketch_delete_constraint. Solid: extrude, revolve, sweep, loft, thicken, rib, boolean, hole, thread, shell, split, fillet, chamfer, draft, pattern, mirror, align, delete_face, list_align_types. Surface: surface_extrude, surface_revolve, surface_loft, surface_patch, surface_offset. Construct: construct_plane, construct_axis, construct_coordinate_system, helix. Inspect: measure, body_mass_properties, interference, body_describe, body_section, body_compare. Bodies: body_transform, body_delete, body_set, body_place. History: feature_edit, feature_delete, feature_describe, feature_set_expression, feature_move, feature_suppress, feature_rename. Menu rows, which take no arguments and do what their row of the right-click menu does: rename_selected, zoom_to_selection, sketch_polygon_inscribed, sketch_polygon_circumscribed, sketch_constrain_selected.", "destructive": false, - "group": "Slice & Export", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "slice_and_preview", - "listed": false, - "open_world": false, - "operations": [ - "start_slice" - ], - "read_only": false, - "title": "Slice and Preview" - }, - { - "completion": "immediate", - "description": "Slice every plate and show the Preview tab. Returns at once; use the slice tool to wait for results.", - "destructive": false, - "group": "Slice & Export", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "slice_all", - "listed": false, - "open_world": false, - "operations": [ - "start_slice" - ], - "read_only": false, - "title": "Slice All Plates" - }, - { - "completion": "immediate", - "description": "Show the Preview tab at a layer chosen as a percentage of the layer range; an error while the Preview has no layers (slice first).", - "destructive": false, - "group": "Commands", - "guard": "mutate", - "idempotent": false, - "in_palette": true, + "group": "Tools and actions", + "guard": "inspect", + "idempotent": true, + "in_palette": false, "input_schema": { "additionalProperties": false, "properties": { - "percent": { - "description": "The layer to show, as a percentage of the layer range.", - "maximum": 100, + "group": { + "description": "Only the commands of this group, in any case: the heading of a place (Tools and actions; The app; The project; Objects; Parts; Plates; Presets and settings; Filaments; Printers and prints; Plugins, with the operations plugins offer; View and windows; Recordings, replays and scripts; Driving the GUI), the place a command's name starts with, but for window_screenshot and window_save_screenshot, which are under Recordings, replays and scripts; or Design (the Design tab's, with the CAD feature on). A group no command has is refused with the groups there are.", + "type": "string" + }, + "limit": { + "description": "At most this many commands (default 5).", + "maximum": 200, + "minimum": 1, + "type": "integer" + }, + "query": { + "description": "A few words saying what you want to do or find, e.g. \"brim\" or \"mesh normals\".", + "type": "string" + }, + "tool": { + "description": "A command's name: its description and schema.", + "type": "string" + } + }, + "type": "object" + }, + "key": "tool_search", + "listed": true, + "open_world": false, + "operations": [], + "read_only": true, + "title": "Find tools, actions, settings and APIs" + }, + { + "completion": "immediate", + "description": "Call any command by name with its arguments: a tool, or one the tool list does not show, a menu row that takes no arguments, a Design tab command or an operation a plugin offers (see tool_search). It runs and is recorded as that command's own call, with its guards and reply budget.", + "destructive": false, + "group": "Tools and actions", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "args": { + "description": "Its arguments.", + "type": "object" + }, + "tool": { + "description": "The command to call.", + "type": "string" + } + }, + "required": [ + "tool" + ], + "type": "object" + }, + "key": "tool_call", + "listed": true, + "open_world": true, + "operations": [], + "read_only": false, + "title": "Call a tool or plugin operation" + }, + { + "completion": "immediate", + "description": "Snapshot of OrcaSlicer. Call it first and whenever you are unsure what the app is doing. The app: version, platform and display backend, whether it is ready, the main window, the displays (each one's work area x, y, width and height, as window_set takes positions, its scale and whether it is primary), the MCP endpoint (mcp), python (available: Python runs in this build; scripts_unrestricted: a script's own file, network, process and thread access is not held to OrcaSlicer's folders, which only a person turns on, in Preferences > AI features > Python scripts or for one run with --unrestricted-scripts), design_tab (the Design tab is on, and tool_call runs its commands, tool_search's group Design) and, when they do not run, cad_note, how a person turns the CAD feature on; account (signed_in to the Orca cloud, bambu_signed_in to Bambu Lab's), network_plugin (installed, loaded, version, error: the Bambu network plug-in as the app found it) and config_folder (presets, app configuration and logs). The view outside the Design tab (view: sidebar_collapsed, sidebar_width, legend_collapsed, gcode_window, projection, section and the display switches labels, overhangs, outline, wireframe, gridlines, axes and navigator, under the names view_set takes them). The project: current tab and mode, printer technology, name, path and unsaved changes, selected printer/process/filament presets, plates (count, current), object count, the selection (objects, the instances [[object, instance]] they are selected in and, when parts rather than whole instances are selected, parts [[object, part]], in the indices object_select takes; wipe_tower when a prime tower is selected; canvas is the 3D view it belongs to), slicing state, the Preview's view type, time mode and layer range (1-based, with their Z), and the camera of the 3D view shown (camera: type, look_at, position, zoom, click_px_per_mm, elevation and azimuth, as view_set replies with it). What is going on: open modal dialogs, each with its title, buttons (enabled: false when disabled) and a message that reads it as shown: its text and its controls row by row, fields [value], choices [value â–¾], checkboxes [x] / [ ] / [-], radio and selector options (*) / ( ), list rows \"- row | cells\", secrets [******], \" (disabled)\" after a disabled control; menus closed unseen (a menu a call opened that no reply listed), dialog_auto_answer rules in force, notifications, print host uploads (state, progress, error), the open gizmo, running jobs and a running recording.", + "destructive": false, + "group": "The app", + "guard": "inspect", + "idempotent": true, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": {}, + "type": "object" + }, + "key": "app_state", + "listed": true, + "open_world": false, + "operations": [], + "read_only": true, + "title": "Get app state" + }, + { + "completion": "immediate", + "description": "Search everything the Speed Dial can run: built-in commands (slice, export, views, object operations, plates, calibration wizards, help), recent projects, plugin scripts and pages. Each entry has an id for action_run, a description, the command's key for a built-in command, and, when it takes arguments, their input_schema. A query ranks them, best match first, as tool_search does; without one they are listed by group and title. include_settings also lists settings (each jumps to that setting in the sidebar; use settings_get / settings_set to read or change values).", + "destructive": false, + "group": "Tools and actions", + "guard": "inspect", + "idempotent": true, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "group": { + "description": "Only this group, e.g. \"Object\", \"View\", \"Slice & Export\".", + "type": "string" + }, + "include_settings": { + "description": "Also list settings (thousands). Default false.", + "type": "boolean" + }, + "limit": { + "description": "Default 50.", + "maximum": 200, + "minimum": 1, + "type": "integer" + }, + "offset": { + "minimum": 0, + "type": "integer" + }, + "query": { + "description": "A few words, e.g. \"delete object\": each is matched at the start of the words of an action's id, title, group and description.", + "type": "string" + } + }, + "type": "object" + }, + "key": "action_search", + "listed": true, + "open_world": false, + "operations": [], + "read_only": true, + "title": "Search Speed Dial actions" + }, + { + "completion": "immediate", + "description": "Run one action by the id action_search returned (orca_command:view_front:orca, or the name inside it, view_front), with args, the command's arguments, when it takes some (its input_schema). A command's tile (action_search names the command) runs the command as a call with the tile's arguments does: a tile that asks in a dialog asks, and the call returns blocked_by_dialog; answer it with dialog_answer, or, for a native one it can't press (a file picker), register dialog_auto_answer before the call. Such a tile takes no args, or exactly its own; to run a command without asking, call it with its arguments (an absolute path skips a file dialog). Go to layer and Go to tab take their value alone ({\"percent\": 50}, {\"tab\": \"preview\"}), and a Design command's own tile takes the command's arguments. An action that starts a background job (obj_arrange, obj_orient) completes when the job ends. An action that does nothing (no object selected) is an error. Some commands add what they did to the reply (the order object_order leaves, the object object_assemble made). The other actions (plates, recent projects, plugin scripts and pages, settings) run only here.", + "destructive": false, + "group": "Tools and actions", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "args": { + "description": "The command's arguments, as its input_schema gives them.", + "type": "object" + }, + "id": { + "description": "Action id from action_search, or the name inside it.", + "type": "string" + } + }, + "required": [ + "id" + ], + "type": "object" + }, + "key": "action_run", + "listed": true, + "open_world": true, + "operations": [], + "read_only": false, + "title": "Run a Speed Dial action" + }, + { + "completion": "immediate", + "description": "Block until a condition holds or timeout_s passes (max 50). for: \"ready\" (startup finished), \"idle\" (no dialog, no running job, nothing slicing or arranging, no gizmo working in the background; a script_run run counts only through the calls it makes), \"dialog\" / \"no_dialog\", or \"job\" with a job id an earlier call returned, whose result is then the reply. On timeout the reply is {satisfied: false}, or for a job {status: \"running\", job, note}: call it again.", + "destructive": false, + "group": "The app", + "guard": "inspect", + "idempotent": true, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "for": { + "description": "What to wait for; default job when job is given, else idle.", + "enum": [ + "ready", + "idle", + "dialog", + "no_dialog", + "job" + ], + "type": "string" + }, + "job": { + "description": "Job id, for \"job\".", + "type": "string" + }, + "timeout_s": { + "description": "Default 30.", + "maximum": 50, "minimum": 0, "type": "number" } }, - "required": [ - "percent" - ], "type": "object" }, - "key": "go_to_layer", - "listed": false, - "open_world": false, - "operations": [ - "show_layer_range" - ], - "read_only": false, - "title": "Go to layer (percent)" - }, - { - "completion": "immediate", - "description": "Switch to a main window tab.", - "destructive": false, - "group": "Commands", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": { - "tab": { - "description": "The tab's id: home, prepare, preview, monitor (the Device tab, which set_view calls device), monitor_web (the web Device page, where the app shows one), multi_device, project, calibration, design, or a plugin page's id.", - "type": "string" - } - }, - "required": [ - "tab" - ], - "type": "object" - }, - "key": "go_to_tab", - "listed": false, + "key": "app_wait", + "listed": true, "open_world": false, "operations": [], - "read_only": false, - "title": "Go to tab..." + "read_only": true, + "title": "Wait for a condition" }, { "completion": "immediate", - "description": "Open a project. With a path, opens that file without a dialog (asks first if the current project has unsaved changes).", + "description": "The last lines of OrcaSlicer's current log file, optionally only those at or above a level. An entry's level is the one its first line starts with ([error]); the lines of its message after the first come with it, and the reply holds whole entries.", "destructive": false, - "group": "Commands", - "guard": "mutate", - "idempotent": false, - "in_palette": true, + "group": "The app", + "guard": "inspect", + "idempotent": true, + "in_palette": false, "input_schema": { "additionalProperties": false, "properties": { - "path": { - "description": "Absolute path of a .3mf project.", + "level": { + "description": "Minimum level.", + "enum": [ + "trace", + "debug", + "info", + "warning", + "error", + "fatal" + ], "type": "string" - } - }, - "type": "object" - }, - "key": "load_project", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Load Project" - }, - { - "completion": "immediate", - "description": "Save the project as a .3mf file. With a path, saves there without a dialog; a name ending in .gcode.3mf is refused (export_sliced_file writes that).", - "destructive": false, - "group": "Commands", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": { - "overwrite": { - "description": "Replace a file that exists already. Default false.", - "type": "boolean" }, - "path": { - "description": "Absolute path of the .3mf project to write.", - "type": "string" + "lines": { + "description": "The most lines, of the newest whole entries; an entry longer than that gives its first lines. Default 200.", + "maximum": 2000, + "minimum": 1, + "type": "integer" } }, "type": "object" }, - "key": "save_project_as", - "listed": false, + "key": "app_log", + "listed": true, "open_world": false, - "operations": [ - "save_project_as" - ], - "read_only": false, - "title": "Save Project As" + "operations": [], + "read_only": true, + "title": "Read the log" }, { "completion": "immediate", @@ -231,8 +318,9 @@ "title": "Take back the last shape drawn in a sketch" } ], - "group": "Commands", + "group": "The app", "guard": "mutate", + "icon": "menu_undo", "idempotent": false, "in_palette": true, "input_schema": { @@ -250,10 +338,11 @@ "type": "object" }, "key": "undo", - "listed": false, + "listed": true, "open_world": false, "operations": [], "read_only": false, + "tile_group": "Commands", "title": "Undo" }, { @@ -339,8 +428,9 @@ "title": "Put back the shape undo took off a sketch" } ], - "group": "Commands", + "group": "The app", "guard": "mutate", + "icon": "menu_redo", "idempotent": false, "in_palette": true, "input_schema": { @@ -358,69 +448,192 @@ "type": "object" }, "key": "redo", - "listed": false, + "listed": true, "open_world": false, "operations": [], "read_only": false, + "tile_group": "Commands", "title": "Redo" }, { "completion": "immediate", - "description": "Show or hide the Run Script panel, where a person writes and runs Python scripts cell by cell. Agents run Python with the run_script tool instead.", + "description": "Open one of OrcaSlicer's web pages in the default web browser, as its menu row does: wiki, the OrcaSlicer wiki; youtube, the OrcaSlicer YouTube channel; plugin_hub, the plugin hub's page, where a person picks a plugin to install. Nothing opens in OrcaSlicer.", "destructive": false, - "group": "Commands", + "group": "The app", "guard": "mutate", "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "toggle_run_script_panel", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Run Script" - }, - { - "completion": "immediate", - "description": "Open the Action Replay window, where a person opens a replay file, reads its steps and replays them. Agents run replays with the run_replay tool instead.", - "destructive": false, - "group": "Commands", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "open_action_replay", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Action Replay" - }, - { - "completion": "immediate", - "description": "Open the Preferences dialog on a tab, scrolled to one preference when given (shown on its own tab). Its controls are named after their preference keys: set_widget_value {\"target\": {\"name\": key, \"within\": \"Preferences\"}} changes one through the dialog; get_settings scope preferences reads them.", - "destructive": false, - "group": "Commands", - "guard": "mutate", - "idempotent": false, - "in_palette": true, + "in_palette": false, "input_schema": { "additionalProperties": false, "properties": { - "key": { - "description": "With tab: a preference on that tab, e.g. auto_arrange on behaviour: its control is scrolled into view and focused.", + "page": { + "description": "The page.", + "enum": [ + "wiki", + "youtube", + "plugin_hub" + ], + "type": "string" + } + }, + "required": [ + "page" + ], + "type": "object" + }, + "key": "app_open_web_page", + "listed": true, + "open_world": true, + "operations": [], + "read_only": false, + "tiles": [ + { + "args": { + "page": "wiki" + }, + "description": "Open the OrcaSlicer wiki in the browser.", + "group": "Help", + "icon": "link_wiki_img", + "key": "open_wiki", + "title": "Open Wiki" + }, + { + "args": { + "page": "youtube" + }, + "description": "Open the OrcaSlicer YouTube channel in the browser.", + "group": "Help", + "icon": "", + "key": "open_youtube", + "title": "Open YouTube Channel" + }, + { + "args": { + "page": "plugin_hub" + }, + "description": "Open the plugin hub's page in the default web browser, where a person picks a plugin to install; nothing opens in OrcaSlicer.", + "group": "Plugins", + "icon": "", + "key": "install_plugin", + "title": "Install Plugin" + } + ], + "title": "Open a web page" + }, + { + "completion": "immediate", + "description": "Check for a newer OrcaSlicer.", + "destructive": false, + "group": "The app", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": {}, + "type": "object" + }, + "key": "app_check_for_updates", + "listed": true, + "open_world": true, + "operations": [], + "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Check for a newer OrcaSlicer.", + "group": "Help", + "icon": "refresh", + "key": "help_check_updates", + "title": "Check for Updates" + } + ], + "title": "Check for Updates" + }, + { + "completion": "immediate", + "description": "Open the configuration folder in the file manager.", + "destructive": false, + "group": "The app", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": {}, + "type": "object" + }, + "key": "app_show_config_folder", + "listed": true, + "open_world": false, + "operations": [], + "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Open the configuration folder in the file manager.", + "group": "Help", + "icon": "open_project", + "key": "help_open_config_folder", + "title": "Show Configuration Folder" + } + ], + "title": "Show Configuration Folder" + }, + { + "completion": "immediate", + "description": "Time the 3D views on a test model. It asks first (Start or Cancel), then replaces the project with the OrcaSliced Combo as New Project does, which may ask about unsaved changes, slices it and shows the results.", + "destructive": false, + "group": "The app", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": {}, + "type": "object" + }, + "key": "app_benchmark_3d_scene", + "listed": true, + "open_world": false, + "operations": [], + "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Time the 3D views on a test model. It asks first (Start or Cancel), then replaces the project with the OrcaSliced Combo as New Project does, which may ask about unsaved changes, slices it and shows the results.", + "group": "Help", + "icon": "", + "key": "help_benchmark_3d_scene", + "title": "Benchmark 3D Scene" + } + ], + "title": "Benchmark 3D Scene" + }, + { + "completion": "immediate", + "description": "Read the app's preferences as the Preferences dialog shows them. With no argument, every preference it shows, tab by tab in its order, each with key (its control is named after it), tab, section and label (the row's title, in English), kind (checkbox, choice, number or text), value (what the dialog shows: true or false for a checkbox, a number for a number field), a choice's choices ({value, label}; preferences_set takes the value), a number's min and max, stored: false where nothing is stored and the value is the one the dialog shows then, restart_needed: true for a preference read at the next start, which a write changes nothing before, and refused, the reason, for a preference preferences_set does not write. The MCP server's switch and port read as the dialog shows them: on while the server runs, and the port it is on, also where this session's launch arguments set them without storing them; their stored says whether a value is stored. keys, query and tab narrow the list together; a named key the dialog does not show is read as the app configuration stores it ({key, value}), and one that is neither is listed under unknown_keys. The app configuration also holds account and device state, which is read only by name.", + "destructive": false, + "group": "The app", + "guard": "inspect", + "idempotent": true, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "keys": { + "description": "Preference keys, e.g. [\"project_load_behaviour\"].", + "items": { + "type": "string" + }, + "type": "array" + }, + "query": { + "description": "Words to find in the keys, labels and section titles, in any case, e.g. \"auto slice\".", "type": "string" }, "tab": { - "description": "The tab to show.", + "description": "The dialog's tab, as window_open names it.", "enum": [ "general", "files", @@ -435,2717 +648,251 @@ }, "type": "object" }, - "key": "open_preferences", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Preferences" - }, - { - "completion": "immediate", - "description": "Save a PNG of the main window in the folder Start Recording saves in (the person's Downloads unless they chose another) and show the person a notification naming it; the reply has its path. Agents use the screenshot tool, which returns the image.", - "destructive": false, - "group": "Commands", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "take_screenshot", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Take Screenshot" - }, - { - "completion": "immediate", - "description": "Switch the settings view to Simple mode.", - "destructive": false, - "group": "Mode", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "mode_simple", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Mode: Simple" - }, - { - "completion": "immediate", - "description": "Switch the settings view to Advanced mode.", - "destructive": false, - "group": "Mode", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "mode_advanced", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Mode: Advanced" - }, - { - "completion": "immediate", - "description": "Switch the settings view to Expert mode.", - "destructive": false, - "group": "Mode", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "mode_expert", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Mode: Expert" - }, - { - "completion": "immediate", - "description": "Turn Developer mode on or off.", - "destructive": false, - "group": "Mode", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "toggle_developer_mode", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Toggle Developer Mode" - }, - { - "completion": "deferred", - "description": "Export the current plate's G-code. With a path, exports the sliced plate there without a dialog, in the background, and the call returns when the file is written; a plate that is not sliced is refused (slice first). With no arguments, it opens the export dialog.", - "destructive": false, - "group": "Slice & Export", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": { - "overwrite": { - "description": "Replace a file that exists already. Default false.", - "type": "boolean" - }, - "path": { - "description": "Absolute path of the .gcode file to write.", - "type": "string" - } - }, - "type": "object" - }, - "key": "export_gcode", - "listed": false, - "open_world": false, - "operations": [ - "start_gcode_export" - ], - "read_only": false, - "title": "Export G-code" - }, - { - "completion": "immediate", - "description": "Export all objects as one STL. With a path, writes there without a dialog.", - "destructive": false, - "group": "Slice & Export", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": { - "overwrite": { - "description": "Replace a file that exists already. Default false.", - "type": "boolean" - }, - "path": { - "description": "Absolute path of the .stl file to write.", - "type": "string" - } - }, - "type": "object" - }, - "key": "export_stl", - "listed": false, - "open_world": false, - "operations": [ - "export_stl" - ], - "read_only": false, - "title": "Export STL" - }, - { - "completion": "immediate", - "description": "Export the model as a .3mf without slicing data. With a path, writes there without a dialog.", - "destructive": false, - "group": "Slice & Export", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": { - "overwrite": { - "description": "Replace a file that exists already. Default false.", - "type": "boolean" - }, - "path": { - "description": "Absolute path of the .3mf file to write.", - "type": "string" - } - }, - "type": "object" - }, - "key": "export_3mf", - "listed": false, - "open_world": false, - "operations": [ - "export_model_3mf" - ], - "read_only": false, - "title": "Export 3MF" - }, - { - "completion": "immediate", - "description": "Export the current plate's sliced file (.gcode.3mf). With a path, writes there without a dialog.", - "destructive": false, - "group": "Slice & Export", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": { - "overwrite": { - "description": "Replace a file that exists already. Default false.", - "type": "boolean" - }, - "path": { - "description": "Absolute path of the .gcode.3mf file to write.", - "type": "string" - } - }, - "type": "object" - }, - "key": "export_sliced_file", - "listed": false, - "open_world": false, - "operations": [ - "export_sliced_3mf" - ], - "read_only": false, - "title": "Export Sliced File" - }, - { - "completion": "immediate", - "description": "Export every plate's sliced file into one .gcode.3mf. With a path, writes there without a dialog.", - "destructive": false, - "group": "Slice & Export", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": { - "overwrite": { - "description": "Replace a file that exists already. Default false.", - "type": "boolean" - }, - "path": { - "description": "Absolute path of the .gcode.3mf file to write.", - "type": "string" - } - }, - "type": "object" - }, - "key": "export_all_sliced_file", - "listed": false, - "open_world": false, - "operations": [ - "export_sliced_3mf" - ], - "read_only": false, - "title": "Export All Sliced Files" - }, - { - "completion": "immediate", - "description": "Open the Send G-code to printer host dialog for the current plate, as the Print button does for a printer with a print host (OctoPrint, Moonraker, PrusaLink, Duet...). Set the file name with set_widget_value and press Upload or Upload and Print with answer_dialog; the plate is sliced if needed, then uploaded in the background: get_app_state.uploads shows the row's state, and a failed upload also opens an error dialog. A replay uploads again. Fails for a printer without a print host, or one that prints through the Bambu network or printer agents.", - "destructive": false, - "group": "Slice & Export", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "send_gcode", - "listed": false, - "open_world": false, - "operations": [ - "send_gcode_to_host" - ], - "read_only": false, - "title": "Send G-code to printer host" - }, - { - "completion": "immediate", - "description": "Open the Temperature Calibration dialog; the generate_calibration_test tool runs the same test with typed parameters and no dialog.", - "destructive": false, - "group": "Calibration", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "calib_temperature", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Temperature Calibration" - }, - { - "completion": "immediate", - "description": "Open the Max Volumetric Speed Calibration dialog; the generate_calibration_test tool runs the same test with typed parameters and no dialog.", - "destructive": false, - "group": "Calibration", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "calib_max_volumetric", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Max Volumetric Speed Calibration" - }, - { - "completion": "immediate", - "description": "Open the Pressure Advance Calibration dialog; the generate_calibration_test tool runs the same test with typed parameters and no dialog.", - "destructive": false, - "group": "Calibration", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "calib_pressure_advance", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Pressure Advance Calibration" - }, - { - "completion": "immediate", - "description": "Open the Flow Ratio Calibration dialog; the generate_calibration_test tool runs the same test with typed parameters and no dialog.", - "destructive": false, - "group": "Calibration", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "calib_flow_ratio", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Flow Ratio Calibration" - }, - { - "completion": "immediate", - "description": "Open the Retraction Calibration dialog; the generate_calibration_test tool runs the same test with typed parameters and no dialog.", - "destructive": false, - "group": "Calibration", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "calib_retraction", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Retraction Calibration" - }, - { - "completion": "immediate", - "description": "Open the Cornering Calibration dialog; the generate_calibration_test tool runs the same test with typed parameters and no dialog.", - "destructive": false, - "group": "Calibration", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "calib_cornering", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Cornering Calibration" - }, - { - "completion": "immediate", - "description": "Open the Input Shaping Frequency Calibration dialog; the generate_calibration_test tool runs the same test with typed parameters and no dialog.", - "destructive": false, - "group": "Calibration", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "calib_input_shaping_freq", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Input Shaping Frequency Calibration" - }, - { - "completion": "immediate", - "description": "Open the Input Shaping Damping Calibration dialog; the generate_calibration_test tool runs the same test with typed parameters and no dialog.", - "destructive": false, - "group": "Calibration", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "calib_input_shaping_damp", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Input Shaping Damping Calibration" - }, - { - "completion": "immediate", - "description": "Open the VFA Calibration dialog; the generate_calibration_test tool runs the same test with typed parameters and no dialog.", - "destructive": false, - "group": "Calibration", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "calib_vfa", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "VFA Calibration" - }, - { - "completion": "immediate", - "description": "Turn the 3D camera of Prepare, Preview or the assemble view to the top view, as set_view {camera: \"top\"} does there.", - "destructive": false, - "group": "View", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "view_top", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "View: Top" - }, - { - "completion": "immediate", - "description": "Turn the 3D camera of Prepare, Preview or the assemble view to the bottom view, as set_view {camera: \"bottom\"} does there.", - "destructive": false, - "group": "View", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "view_bottom", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "View: Bottom" - }, - { - "completion": "immediate", - "description": "Turn the 3D camera of Prepare, Preview or the assemble view to the front view, as set_view {camera: \"front\"} does there.", - "destructive": false, - "group": "View", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "view_front", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "View: Front" - }, - { - "completion": "immediate", - "description": "Turn the 3D camera of Prepare, Preview or the assemble view to the rear view, as set_view {camera: \"rear\"} does there.", - "destructive": false, - "group": "View", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "view_rear", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "View: Rear" - }, - { - "completion": "immediate", - "description": "Turn the 3D camera of Prepare, Preview or the assemble view to the left view, as set_view {camera: \"left\"} does there.", - "destructive": false, - "group": "View", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "view_left", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "View: Left" - }, - { - "completion": "immediate", - "description": "Turn the 3D camera of Prepare, Preview or the assemble view to the right view, as set_view {camera: \"right\"} does there.", - "destructive": false, - "group": "View", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "view_right", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "View: Right" - }, - { - "completion": "immediate", - "description": "Turn the 3D camera of Prepare, Preview or the assemble view to the iso view, as set_view {camera: \"iso\"} does there.", - "destructive": false, - "group": "View", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "view_iso", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "View: Isometric" - }, - { - "completion": "immediate", - "description": "Reset the 3D camera to the default view and fit the plate.", - "destructive": false, - "group": "View", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "view_default", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "View: Default" - }, - { - "completion": "immediate", - "description": "Fit the build plate in the 3D view.", - "destructive": false, - "group": "View", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "view_fit_bed", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Fit Bed to View" - }, - { - "completion": "immediate", - "description": "Switch the 3D camera between perspective and orthographic.", - "destructive": false, - "group": "View", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "view_toggle_perspective", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Toggle Perspective" - }, - { - "completion": "immediate", - "description": "Restore the default window layout.", - "destructive": false, - "group": "View", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "reset_window_layout", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Reset Window Layout" - }, - { - "completion": "immediate", - "description": "Delete the selected objects or parts.", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "obj_delete", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Delete Selected" - }, - { - "completion": "immediate", - "description": "Delete all objects.", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "obj_delete_all", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Delete All Objects" - }, - { - "completion": "immediate", - "description": "Select all objects in the 3D view.", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "select_all", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Select All Objects" - }, - { - "completion": "immediate", - "description": "Clear the selection.", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "deselect_all", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Deselect All" - }, - { - "completion": "immediate", - "description": "Mirror the selection along X.", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "obj_mirror_x", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Mirror X" - }, - { - "completion": "immediate", - "description": "Mirror the selection along Y.", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "obj_mirror_y", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Mirror Y" - }, - { - "completion": "immediate", - "description": "Mirror the selection along Z.", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "obj_mirror_z", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Mirror Z" - }, - { - "completion": "immediate", - "description": "Split the selected object into separate objects.", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "obj_split_objects", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Split to Objects" - }, - { - "completion": "immediate", - "description": "Split the selected object into parts.", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "obj_split_parts", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Split to Parts" - }, - { - "completion": "immediate", - "description": "Center the selection on its plate.", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "obj_center", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Center Selected on Plate" - }, - { - "completion": "immediate", - "description": "Drop the selection onto the bed.", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "obj_drop", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Drop to Bed" - }, - { - "completion": "immediate", - "description": "Scale the selection to fit the print volume.", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "obj_fit_volume", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Scale to Fit Print Volume" - }, - { - "completion": "immediate", - "description": "Add an instance of the selected object.", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "obj_instances_up", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Increase Instances" - }, - { - "completion": "immediate", - "description": "Remove an instance of the selected object.", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "obj_instances_down", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Decrease Instances" - }, - { - "completion": "immediate", - "description": "Arrange all objects on the unlocked plates with the saved Arrange options, as the toolbar does; the call returns when the arrangement is done. The arrange tool also takes options, one plate or fill bed.", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "obj_arrange", - "listed": false, - "open_world": false, - "operations": [ - "start_arrange" - ], - "read_only": false, - "title": "Auto-Arrange" - }, - { - "completion": "immediate", - "description": "Auto-orient the selection, or every object when nothing is selected; the call returns when it is done.", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "obj_orient", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Auto-Orient" - }, - { - "completion": "immediate", - "description": "Make the selected parts (select_objects {parts} first) solid parts, as Change Type does. Parts are listed by type, so part indices change.", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "obj_type_part", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Change Type to Part" - }, - { - "completion": "immediate", - "description": "Make the selected parts negative parts, as Change Type does; not the object's last solid part. Parts are listed by type, so part indices change.", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "obj_type_negative", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Change Type to Negative Part" - }, - { - "completion": "immediate", - "description": "Make the selected parts modifiers, as Change Type does; not the object's last solid part. Parts are listed by type, so part indices change.", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "obj_type_modifier", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Change Type to Modifier" - }, - { - "completion": "immediate", - "description": "Make the selected parts support blockers, as Change Type does; not the object's last solid part, nor a text or SVG part. Parts are listed by type, so part indices change.", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "obj_type_support_blocker", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Change Type to Support Blocker" - }, - { - "completion": "immediate", - "description": "Make the selected parts support enforcers, as Change Type does; not the object's last solid part, nor a text or SVG part. Parts are listed by type, so part indices change.", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "obj_type_support_enforcer", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Change Type to Support Enforcer" - }, - { - "completion": "immediate", - "description": "Make the selected parts Center precise seams (seams keep their subtype), as Change Type does; not the object's last solid part, nor a text or SVG part. Parts are listed by type, so part indices change.", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "obj_type_precise_seam", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Change Type to Precise Seam" - }, - { - "completion": "immediate", - "description": "Rename the selected object or part (select one). With a name, skips the Rename dialog; an empty name, or one with characters a file name cannot hold, is refused.", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": { - "name": { - "description": "The new name, in place of the Rename dialog.", - "type": "string" - } - }, - "type": "object" - }, - "key": "obj_rename", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Rename" - }, - { - "completion": "immediate", - "description": "Give the selected object this many instances, in one undo step. With a count, skips the dialog. New instances overlap; arrange afterwards. The reply has object and instances.", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": { - "count": { - "description": "The total number of instances, up to 1000, in place of the dialog.", - "minimum": 1, - "type": "integer" - } - }, - "type": "object" - }, - "key": "obj_set_instances", - "listed": false, - "open_world": false, - "operations": [ - "set_instance_count" - ], - "read_only": false, - "title": "Set Number of Instances" - }, - { - "completion": "immediate", - "description": "Assemble two or more selected objects into one object of parts named Assembly. They are removed and it is added last, so object indices change; the reply has its index (object) and name.", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "obj_assemble", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Assemble" - }, - { - "completion": "immediate", - "description": "Make each instance of the selected object a separate object (select_objects {objects: [n]}); with some of its instances selected, only those. New objects are added last; the reply lists the objects the instances are in now (objects).", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "obj_instances_to_objects", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Set as Individual Objects" - }, - { - "completion": "immediate", - "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.", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": { - "all": { - "description": "Order the objects of every plate. Default false: the current plate's.", - "type": "boolean" - } - }, - "type": "object" - }, - "key": "obj_order_by_name", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Order by Name" - }, - { - "completion": "immediate", - "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.", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": { - "all": { - "description": "Order the objects of every plate. Default false: the current plate's.", - "type": "boolean" - } - }, - "type": "object" - }, - "key": "obj_order_by_filament", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Order by Filament" - }, - { - "completion": "immediate", - "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.", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": { - "all": { - "description": "Order the objects of every plate. Default false: the current plate's.", - "type": "boolean" - } - }, - "type": "object" - }, - "key": "obj_order_by_height", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Order by Height" - }, - { - "completion": "immediate", - "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.", - "destructive": false, - "group": "Object", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": { - "all": { - "description": "Order the objects of every plate. Default false: the current plate's.", - "type": "boolean" - } - }, - "type": "object" - }, - "key": "obj_order_by_size", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Order by Size" - }, - { - "completion": "immediate", - "description": "Add a cube object to the current plate; fails while an object is selected. With a size, skips the size dialog.", - "destructive": false, - "group": "Add Primitive", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": { - "size": { - "description": "The size, [X, Y, Z] in mm, each above 0, in place of the size dialog.", - "items": { - "type": "number" - }, - "type": "array" - } - }, - "type": "object" - }, - "key": "add_primitive_cube", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Cube" - }, - { - "completion": "immediate", - "description": "Add a cylinder object to the current plate; fails while an object is selected. With a size, skips the size dialog. The shape may then be turned toward the part-cooling fan, so the size is along its own axes before that turn.", - "destructive": false, - "group": "Add Primitive", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": { - "size": { - "description": "The size, [diameter, height] in mm, each above 0, in place of the size dialog.", - "items": { - "type": "number" - }, - "type": "array" - } - }, - "type": "object" - }, - "key": "add_primitive_cylinder", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Cylinder" - }, - { - "completion": "immediate", - "description": "Add a sphere object to the current plate; fails while an object is selected. With a size, skips the size dialog.", - "destructive": false, - "group": "Add Primitive", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": { - "size": { - "description": "The size, [diameter] in mm, each above 0, in place of the size dialog.", - "items": { - "type": "number" - }, - "type": "array" - } - }, - "type": "object" - }, - "key": "add_primitive_sphere", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Sphere" - }, - { - "completion": "immediate", - "description": "Add a cone object to the current plate; fails while an object is selected. With a size, skips the size dialog. The shape may then be turned toward the part-cooling fan, so the size is along its own axes before that turn.", - "destructive": false, - "group": "Add Primitive", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": { - "size": { - "description": "The size, [base diameter, height] in mm, each above 0, in place of the size dialog.", - "items": { - "type": "number" - }, - "type": "array" - } - }, - "type": "object" - }, - "key": "add_primitive_cone", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Cone" - }, - { - "completion": "immediate", - "description": "Add a disc object to the current plate; fails while an object is selected. With a size, skips the size dialog. The shape may then be turned toward the part-cooling fan, so the size is along its own axes before that turn.", - "destructive": false, - "group": "Add Primitive", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": { - "size": { - "description": "The size, [diameter, height] in mm, each above 0, in place of the size dialog.", - "items": { - "type": "number" - }, - "type": "array" - } - }, - "type": "object" - }, - "key": "add_primitive_disc", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Disc" - }, - { - "completion": "immediate", - "description": "Add a torus object to the current plate; fails while an object is selected. With a size, skips the size dialog. The shape may then be turned toward the part-cooling fan, so the size is along its own axes before that turn.", - "destructive": false, - "group": "Add Primitive", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": { - "size": { - "description": "The size, [inner diameter, tube diameter] in mm, each above 0, in place of the size dialog.", - "items": { - "type": "number" - }, - "type": "array" - } - }, - "type": "object" - }, - "key": "add_primitive_torus", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Torus" - }, - { - "completion": "immediate", - "description": "Add a text: a part on the selected object, or a new object when nothing is selected. It is created in the background (wait for idle), and the Text gizmo opens on it.", - "destructive": false, - "group": "Add Primitive", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "add_primitive_text", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Text" - }, - { - "completion": "immediate", - "description": "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 (wait for idle), and the SVG gizmo opens on it.", - "destructive": false, - "group": "Add Primitive", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": { - "path": { - "description": "Absolute path of an .svg file.", - "type": "string" - } - }, - "type": "object" - }, - "key": "add_primitive_svg", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "SVG" - }, - { - "completion": "immediate", - "description": "Add the Orca Cube and its plug to the current plate, then arrange the objects as the toolbar's Arrange does, which moves the others too.", - "destructive": false, - "group": "Add Handy models", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "add_handy_orca_cube", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Orca Cube" - }, - { - "completion": "immediate", - "description": "Add the OrcaSliced Combo (the OrcaSliced model, the Orca Cube and its plug) to the current plate, then arrange the objects as the toolbar's Arrange does, which moves the others too.", - "destructive": false, - "group": "Add Handy models", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "add_handy_orcasliced_combo", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "OrcaSliced Combo" - }, - { - "completion": "immediate", - "description": "Add the Orca Badge model to the current plate.", - "destructive": false, - "group": "Add Handy models", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "add_handy_orca_badge", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Orca Badge" - }, - { - "completion": "immediate", - "description": "Add the Orca Tolerance Test model to the current plate.", - "destructive": false, - "group": "Add Handy models", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "add_handy_orca_tolerance_test", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Orca Tolerance Test" - }, - { - "completion": "immediate", - "description": "Add the 3DBenchy model to the current plate.", - "destructive": false, - "group": "Add Handy models", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "add_handy_3dbenchy", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "3DBenchy" - }, - { - "completion": "immediate", - "description": "Add the Cali Cat model to the current plate.", - "destructive": false, - "group": "Add Handy models", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "add_handy_cali_cat", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Cali Cat" - }, - { - "completion": "immediate", - "description": "Add the Autodesk FDM Test model to the current plate.", - "destructive": false, - "group": "Add Handy models", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "add_handy_autodesk_fdm_test", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Autodesk FDM Test" - }, - { - "completion": "immediate", - "description": "Add the Voron Cube model to the current plate.", - "destructive": false, - "group": "Add Handy models", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "add_handy_voron_cube", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Voron Cube" - }, - { - "completion": "immediate", - "description": "Add the Stanford Bunny model to the current plate.", - "destructive": false, - "group": "Add Handy models", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "add_handy_stanford_bunny", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Stanford Bunny" - }, - { - "completion": "immediate", - "description": "Add the Orca String Hell model to the current plate.", - "destructive": false, - "group": "Add Handy models", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "add_handy_orca_string_hell", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Orca String Hell" - }, - { - "completion": "immediate", - "description": "Add a plate.", - "destructive": false, - "group": "Plate", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "plate_add", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Add Plate" - }, - { - "completion": "immediate", - "description": "Duplicate the current plate.", - "destructive": false, - "group": "Plate", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "plate_duplicate", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Duplicate Plate" - }, - { - "completion": "immediate", - "description": "Delete the current plate.", - "destructive": false, - "group": "Plate", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "plate_delete", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Delete Plate" - }, - { - "completion": "immediate", - "description": "Rename the current plate (opens a dialog).", - "destructive": false, - "group": "Plate", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "plate_rename", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Rename Plate" - }, - { - "completion": "immediate", - "description": "Lock or unlock the current plate.", - "destructive": false, - "group": "Plate", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "plate_toggle_lock", - "listed": false, - "open_world": false, - "operations": [ - "set_plate_locked" - ], - "read_only": false, - "title": "Toggle Plate Lock" - }, - { - "completion": "immediate", - "description": "Make a plate the current one; an index the project lacks is an error.", - "destructive": false, - "group": "Plate", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": { - "plate": { - "description": "The plate's 0-based index. Default 0.", - "type": "integer" - } - }, - "type": "object" - }, - "key": "plate_goto", - "listed": false, - "open_world": false, - "operations": [ - "select_plate" - ], - "read_only": false, - "title": "Go to Plate" - }, - { - "completion": "immediate", - "description": "Synchronize the filament list from the connected printer's AMS.", - "destructive": false, - "group": "Printer", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "sync_ams", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Synchronize Filament List from AMS" - }, - { - "completion": "immediate", - "description": "Add a filament slot, as the + button above the filament list does; the message names the new slot. It takes the next colour and the last slot's preset (change them with select_preset filament_slot and set_settings scope project filament_colour). It goes after the physical slots: mixed filaments move up by one, and objects on them follow.", - "destructive": false, - "group": "Filament", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "filament_add", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Add Filament Slot" - }, - { - "completion": "immediate", - "description": "Delete a filament slot, as its Delete menu item does; objects on it move to another slot. A mixed filament (project scope filament_is_mixed) is refused.", - "destructive": false, - "group": "Filament", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": { - "filament_slot": { - "description": "The 1-based filament slot. Default: the last physical slot, as the - button.", - "minimum": 1, - "type": "integer" - } - }, - "type": "object" - }, - "key": "filament_delete", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Delete Filament Slot" - }, - { - "completion": "immediate", - "description": "Open the preset bundle manager.", - "destructive": false, - "group": "Presets", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "preset_bundle", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Open Preset Bundle" - }, - { - "completion": "immediate", - "description": "Synchronize user presets with the cloud account.", - "destructive": false, - "group": "Presets", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "sync_presets", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Sync Presets" - }, - { - "completion": "immediate", - "description": "Import models (3MF/STL/STEP/SVG/OBJ/AMF). With a path, adds that file's geometry without a dialog, as one undo step; a project file's settings are not loaded (load_project opens a project).", - "destructive": false, - "group": "Import", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": { - "path": { - "description": "Absolute path of a model file.", - "type": "string" - } - }, - "type": "object" - }, - "key": "import_file", - "listed": false, - "open_world": false, - "operations": [ - "import_models" - ], - "read_only": false, - "title": "Import 3MF/STL/STEP/SVG/OBJ/AMF" - }, - { - "completion": "immediate", - "description": "Import models from a ZIP archive (opens a file dialog).", - "destructive": false, - "group": "Import", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "import_zip_archive", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Import ZIP Archive" - }, - { - "completion": "immediate", - "description": "Import presets. With a path, imports a preset .json, a .zip of them or an .orca_printer, .orca_filament or .orca_bundle without a dialog, and the message names the presets imported, replaced and kept; a .gcode loads the settings it was sliced with.", - "destructive": false, - "group": "Import", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": { - "on_conflict": { - "description": "What happens to a preset that exists already. Default skip.", - "enum": [ - "skip", - "overwrite" - ], - "type": "string" - }, - "path": { - "description": "Absolute path of a preset .json, a .zip of them, an .orca_printer, .orca_filament or .orca_bundle, or a .gcode.", - "type": "string" - } - }, - "type": "object" - }, - "key": "import_configs", - "listed": false, - "open_world": false, - "operations": [ - "import_presets" - ], - "read_only": false, - "title": "Import Configs" - }, - { - "completion": "immediate", - "description": "Export each object as its own STL. With a directory, writes there without a dialog.", - "destructive": false, - "group": "Export", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": { - "path": { - "description": "Absolute path of an existing directory to write into.", - "type": "string" - } - }, - "type": "object" - }, - "key": "export_stl_multi", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Export All Objects as STLs" - }, - { - "completion": "immediate", - "description": "Export all objects as one Draco (.drc) file.", - "destructive": false, - "group": "Export", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "export_drc_single", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Export All Objects as DRC (one file)" - }, - { - "completion": "immediate", - "description": "Export each object as its own Draco (.drc) file.", - "destructive": false, - "group": "Export", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "export_drc_multi", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Export All Objects as DRCs" - }, - { - "completion": "immediate", - "description": "Export the sliced toolpaths as an OBJ.", - "destructive": false, - "group": "Export", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "export_toolpaths_obj", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Export Toolpaths as OBJ" - }, - { - "completion": "immediate", - "description": "Export presets as a bundle or ZIP archives. Opens a dialog: click the label of the kind to export, check its rows (each named after a printer preset or a filament), press OK, then answer the result message. With a directory, OK writes there instead of asking for a folder.", - "destructive": false, - "group": "Export", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": { - "path": { - "description": "Absolute path of an existing directory to write into.", - "type": "string" - } - }, - "type": "object" - }, - "key": "export_config", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Export Preset Bundle" - }, - { - "completion": "immediate", - "description": "Show the keyboard shortcuts dialog.", - "destructive": false, - "group": "Help", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "help_keyboard_shortcuts", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Keyboard Shortcuts" - }, - { - "completion": "immediate", - "description": "Open the setup wizard.", - "destructive": false, - "group": "Help", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "help_setup_wizard", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Setup Wizard" - }, - { - "completion": "immediate", - "description": "Open the configuration folder in the file manager.", - "destructive": false, - "group": "Help", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "help_open_config_folder", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Show Configuration Folder" - }, - { - "completion": "immediate", - "description": "Migrate legacy user filament presets.", - "destructive": false, - "group": "Help", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "help_migrate_filament_presets", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Migrate Filament Presets" - }, - { - "completion": "immediate", - "description": "Open the troubleshooting center.", - "destructive": false, - "group": "Help", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "help_troubleshoot", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Troubleshoot Center" - }, - { - "completion": "immediate", - "description": "Open the network test dialog.", - "destructive": false, - "group": "Help", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "help_network_test", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Open Network Test" - }, - { - "completion": "immediate", - "description": "Time the 3D views on a test model. It asks first (Start or Cancel), then replaces the project with the OrcaSliced Combo as New Project does, which may ask about unsaved changes, slices it and shows the results.", - "destructive": false, - "group": "Help", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "help_benchmark_3d_scene", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Benchmark 3D Scene" - }, - { - "completion": "immediate", - "description": "Show a tip of the day.", - "destructive": false, - "group": "Help", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "help_tip_of_the_day", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Show Tip of the Day" - }, - { - "completion": "immediate", - "description": "Check for a newer OrcaSlicer.", - "destructive": false, - "group": "Help", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "help_check_updates", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Check for Updates" - }, - { - "completion": "immediate", - "description": "Show the About dialog.", - "destructive": false, - "group": "Help", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "help_about", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "About OrcaSlicer" - }, - { - "completion": "immediate", - "description": "Open the OrcaSlicer wiki in the browser.", - "destructive": false, - "group": "Help", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "open_wiki", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Open Wiki" - }, - { - "completion": "immediate", - "description": "Open the OrcaSlicer YouTube channel in the browser.", - "destructive": false, - "group": "Help", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "open_youtube", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Open YouTube Channel" - }, - { - "completion": "immediate", - "description": "Open the plugins dialog.", - "destructive": false, - "group": "Plugins", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "open_plugins", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Open Plugins" - }, - { - "completion": "immediate", - "description": "Reload plugins.", - "destructive": false, - "group": "Plugins", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "refresh_plugins", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Refresh Plugins" - }, - { - "completion": "immediate", - "description": "Open the plugin hub's page in the default web browser, where a person picks a plugin to install; nothing opens in OrcaSlicer.", - "destructive": false, - "group": "Plugins", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "install_plugin", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Install Plugin" - }, - { - "completion": "immediate", - "description": "Install a plugin from a .py or .whl file, as the Plugins dialog's Install local plugin does. With a path, installs that file without a dialog. Replacing a plugin installed already asks first (answer with answer_dialog); the message names the plugin installed, or why it was not.", - "destructive": false, - "group": "Plugins", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "properties": { - "path": { - "description": "Absolute path of a .py or .whl plugin package.", - "type": "string" - } - }, - "type": "object" - }, - "key": "install_local_plugin", - "listed": false, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Install Local Plugin" - }, - { - "completion": "immediate", - "description": "Snapshot of OrcaSlicer. Call it first and whenever you are unsure what the app is doing. The app: version, platform and display backend, whether it is ready, the main window, the displays (each one's work area x, y, width and height, as set_window takes positions, its scale and whether it is primary), the MCP endpoint (mcp), python (available: Python runs in this build; scripts_unrestricted: a script's own file, network, process and thread access is not held to OrcaSlicer's folders, which only a person turns on, in Preferences > AI features > Python scripts or for one run with --unrestricted-scripts), design_tab (the Design tab is on, and call_tool runs its commands, search_tools' group Design) and, when they do not run, cad_note, how a person turns the CAD feature on. The project: current tab and mode, printer technology, name, path and unsaved changes, selected printer/process/filament presets, plates (count, current), object count, the selection (objects, the instances [[object, instance]] they are selected in and, when parts rather than whole instances are selected, parts [[object, part]], in the indices select_objects takes; wipe_tower when a prime tower is selected; canvas is the 3D view it belongs to), slicing state, the Preview's view type, time mode and layer range (1-based, with their Z), and the camera of the 3D view shown (camera: type, look_at, position, zoom, click_px_per_mm, elevation and azimuth, as set_view replies with it). What is going on: open modal dialogs, each with its title, buttons (enabled: false when disabled) and a message that reads it as shown: its text and its controls row by row, fields [value], choices [value ▾], checkboxes [x] / [ ] / [-], radio and selector options (*) / ( ), list rows \"- row | cells\", secrets [******], \" (disabled)\" after a disabled control; menus closed unseen (a menu a call opened that no reply listed), auto_answer_dialogs rules in force, notifications, print host uploads (state, progress, error), the open gizmo, running jobs and a running recording.", - "destructive": false, - "group": "core", - "guard": "inspect", - "idempotent": true, - "in_palette": false, - "input_schema": { - "additionalProperties": false, - "properties": {}, - "type": "object" - }, - "key": "get_app_state", + "key": "preferences_get", "listed": true, "open_world": false, "operations": [], "read_only": true, - "title": "Get app state" + "title": "Read preferences" }, { "completion": "immediate", - "description": "Block until a condition holds or timeout_s passes (max 50). for: \"ready\" (startup finished), \"idle\" (no dialog, no running job, nothing slicing or arranging, no gizmo working in the background; a run_script run counts only through the calls it makes), \"dialog\" / \"no_dialog\", or \"job\" with a job id an earlier call returned, whose result is then the reply. On timeout the reply is {satisfied: false}, or for a job {status: \"running\", job, note}: call it again.", + "description": "Change preferences as their controls in the Preferences dialog do: values {key: value}, a checkbox as true or false, a choice as one of its values, a number within its range, as preferences_get lists them, and the downloads folder (download_path) as the absolute path of an existing folder. All are checked first and written together, so nothing changes if one is refused; then each does what its control does in the app, in the keys' order (the preview redrawn, the sidebar's lists, the settings' mode, the theme, preset sync started or stopped, stealth mode's sign-out of the cloud accounts), and those preferences_get marks restart_needed are stored and take effect at the next start. A key whose value is already the one given is left as it is. Refused, by name and with the reason: a key the dialog does not show, and those preferences_get marks refused, whose control opens a dialog, restarts OrcaSlicer, signs out, or reaches outside it (the language, the login region, the network plug-in, file associations, the mixed-temperature warning, the MCP server's switch and port); those change in the dialog: window_open {\"window\": \"preferences\", \"tab\", \"key\"}, then widget_set_value. Not in the undo history. Reply: changed, [{key, before, after}] typed as preferences_get gives them, with stored_before: false where nothing was stored and before is the value the dialog showed, and restart_needed: true where preferences_get gives it; and unchanged, the keys already so.", "destructive": false, - "group": "core", - "guard": "inspect", - "idempotent": true, - "in_palette": false, - "input_schema": { - "additionalProperties": false, - "properties": { - "for": { - "description": "What to wait for; default job when job is given, else idle.", - "enum": [ - "ready", - "idle", - "dialog", - "no_dialog", - "job" - ], - "type": "string" - }, - "job": { - "description": "Job id, for \"job\".", - "type": "string" - }, - "timeout_s": { - "description": "Default 30.", - "maximum": 50, - "minimum": 0, - "type": "number" - } + "examples": [ + { + "calls": [ + { + "args": { + "query": "arrange" + }, + "tool": "preferences_get" + }, + { + "args": { + "values": { + "auto_arrange": false + } + }, + "tool": "preferences_set" + } + ], + "title": "Find a preference and turn it off" }, - "type": "object" - }, - "key": "wait", - "listed": true, - "open_world": false, - "operations": [], - "read_only": true, - "title": "Wait for a condition" - }, - { - "completion": "immediate", - "description": "The last lines of OrcaSlicer's current log file, optionally only those at or above a level.", - "destructive": false, - "group": "core", - "guard": "inspect", - "idempotent": true, - "in_palette": false, - "input_schema": { - "additionalProperties": false, - "properties": { - "level": { - "description": "Minimum level.", - "enum": [ - "trace", - "debug", - "info", - "warning", - "error", - "fatal" - ], - "type": "string" - }, - "lines": { - "description": "Default 200.", - "maximum": 2000, - "minimum": 1, - "type": "integer" - } - }, - "type": "object" - }, - "key": "get_log", - "listed": true, - "open_world": false, - "operations": [], - "read_only": true, - "title": "Read the log" - }, - { - "completion": "immediate", - "description": "Find what does something, in one search, or look up one command. With query: the commands that match, best first, each with its group, the first sentence of its description and listed, whether the tool list shows it; one that is not listed (a Speed Dial command, a Design tab command, or an operation a plugin offers, plugin..) comes with its input schema, and its description when that says more, which nothing else shows. Beside them, the best few matches of each other catalog, with its total and how to use it: actions (the Speed Dial's plates, recent projects and plugin scripts and pages, for run_action), settings (get_settings / set_settings) and python (the orca API for run_script). With tool: that command's description and input schema, and its examples when it has some (the Design commands do). With neither: every command's name. group keeps the names and the command matches to one group; the other catalogs' matches stay as they are. call_tool runs any command, listed or not. The Design tab's CAD commands follow by heading (sketches, solid and surface features, bodies, measurements); look one up with tool before calling it. A command whose schema has silent does what its menu row does when called with no arguments, unless silent is true. Document: describe_design, import_step, import_mesh, set_variable, commit_to_plate, new_design, export_step, select_geometry, confirm_tool, cancel_tool. Sketch: sketch_create, sketch_project, sketch_text, sketch_insert_svg, sketch_offset, sketch_trim, sketch_fillet, sketch_chamfer, sketch_mirror, sketch_dimension, sketch_constrain, sketch_toggle_construction, sketch_extend, sketch_delete, sketch_describe, sketch_validate, sketch_list_constraints, sketch_blend_curve, sketch_finish, sketch_cancel, sketch_edit, sketch_draw, sketch_select, sketch_repair, sketch_set_value, sketch_transform, sketch_pattern, sketch_delete_constraint. Solid: extrude, revolve, sweep, loft, thicken, rib, boolean, hole, thread, shell, split, fillet, chamfer, draft, pattern, mirror, align, delete_face, list_align_types. Surface: surface_extrude, surface_revolve, surface_loft, surface_patch, surface_offset. Construct: construct_plane, construct_axis, construct_coordinate_system, helix. Inspect: measure, body_mass_properties, interference, body_describe, body_section, body_compare. Bodies: body_transform, body_delete, body_set, body_place. History: feature_edit, feature_delete, feature_describe, feature_set_expression, feature_move, feature_suppress, feature_rename. Menu rows, which take no arguments and do what their row of the right-click menu does: rename_selected, zoom_to_selection, sketch_polygon_inscribed, sketch_polygon_circumscribed, sketch_constrain_selected.", - "destructive": false, - "group": "api", - "guard": "inspect", - "idempotent": true, - "in_palette": false, - "input_schema": { - "additionalProperties": false, - "properties": { - "group": { - "description": "Only the commands of this group, in any case: core (the session, dialogs and Python), api (project data by index and name; plugin operations too), ui (the GUI itself), Design (the Design tab's, with the CAD feature on), or a Speed Dial section such as Commands, Object or View. A group no command has is refused with the groups there are.", - "type": "string" - }, - "limit": { - "description": "At most this many commands (default 5).", - "maximum": 200, - "minimum": 1, - "type": "integer" - }, - "query": { - "description": "A few words saying what you want to do or find, e.g. \"brim\" or \"mesh normals\".", - "type": "string" - }, - "tool": { - "description": "A command's name: its description and schema.", - "type": "string" - } - }, - "type": "object" - }, - "key": "search_tools", - "listed": true, - "open_world": false, - "operations": [], - "read_only": true, - "title": "Find tools, actions, settings and APIs" - }, - { - "completion": "immediate", - "description": "Call any command by name with its arguments: a tool, or one the tool list does not show, a Speed Dial command, a Design tab command or an operation a plugin offers (see search_tools). It runs and is recorded as that command's own call, with its guards and reply budget.", - "destructive": false, - "group": "api", + { + "calls": [ + { + "args": { + "values": { + "auto_calculate_flush": "color change", + "opengl_fps_cap": 60 + } + }, + "tool": "preferences_set" + } + ], + "title": "Set a choice and a number" + } + ], + "group": "The app", "guard": "mutate", "idempotent": false, "in_palette": false, "input_schema": { "additionalProperties": false, "properties": { - "args": { - "description": "Its arguments.", + "values": { + "description": "{key: value}, e.g. {\"auto_arrange\": false, \"auto_calculate_flush\": \"color change\"}.", "type": "object" - }, - "tool": { - "description": "The command to call.", - "type": "string" } }, "required": [ - "tool" + "values" ], "type": "object" }, - "key": "call_tool", + "key": "preferences_set", "listed": true, - "open_world": true, - "operations": [], + "open_world": false, + "operations": [ + "set_preferences" + ], "read_only": false, - "title": "Call a tool or plugin operation" + "title": "Change preferences" }, { "completion": "immediate", - "description": "Open model files (STL, 3MF, STEP, OBJ, AMF, SVG...), a project (.3mf) or G-code by absolute path, without a file dialog. Models are added to the current project. A .3mf given alone opens as a project, replacing the current one, unless as is \"geometry\"; when the current project has unsaved changes that fails, changing nothing, unless discard_changes. Given with other paths, a .3mf adds its models only. A G-code given alone replaces the project too, to show its toolpaths: with unsaved changes the app asks first (blocked_by_dialog), whatever discard_changes says. Importing can open a dialog (STEP mesh options, for instance); the reply is then blocked_by_dialog.", + "description": "Stop the running operation: a slice or G-code export, as the slicing progress's cancel button does, or a background job an MCP call started (an arrange, orient or fill bed). Its job then reports cancelled; a background job keeps other changes out until it has really stopped. With job, only that job is stopped: the running operation, an object_fix, a script_run run or a recording_encode. Allowed while an operation holds the project. Reply: was_running, and job when one was stopped.", "destructive": false, - "group": "api", - "guard": "mutate", + "group": "The app", + "guard": "recover", "idempotent": false, "in_palette": false, "input_schema": { "additionalProperties": false, "properties": { - "as": { - "description": "How a .3mf given alone opens: as a project (auto, the default, and project) or adding its models only (geometry).", - "enum": [ - "auto", - "geometry", - "project" - ], + "job": { + "description": "The operation's job to cancel, e.g. \"j12\".", "type": "string" - }, + } + }, + "type": "object" + }, + "key": "job_cancel", + "listed": true, + "open_world": false, + "operations": [], + "read_only": false, + "title": "Cancel a job" + }, + { + "completion": "immediate", + "description": "Open a project (.3mf) by absolute path, without a file dialog, replacing the current project, with the settings it was saved with whatever the Preferences' Load behavior says; when the current project has unsaved changes that fails, changing nothing, unless discard_changes. A G-code file replaces the project too, to show its toolpaths: with unsaved changes the app asks first (blocked_by_dialog), whatever discard_changes says. project_import adds models, or a project's objects alone, to the current project. Called with no arguments it is Load Project: the Open dialog asks for the file (blocked_by_dialog), after asking about the unsaved changes. Reply: opened (project or gcode), and objects, names and plates for a project, path for a G-code.", + "destructive": false, + "group": "The project", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "if": { + "minProperties": 1 + }, + "properties": { "discard_changes": { - "description": "Drop the project's unsaved changes rather than fail when a .3mf replaces it.", + "description": "Drop the project's unsaved changes rather than fail when a project replaces it.", "type": "boolean" }, + "path": { + "description": "Absolute path of a .3mf project, or of a G-code file (.gcode, .bgcode).", + "type": "string" + }, + "silent": { + "description": "true runs the command without asking; it then needs path, and what else the call leaves out takes its default. A call with no arguments does what a person's pick does.", + "enum": [ + true + ], + "type": "boolean" + } + }, + "then": { + "required": [ + "path" + ] + }, + "type": "object" + }, + "key": "project_open", + "listed": true, + "open_world": false, + "operations": [ + "open_project" + ], + "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Open a project through the Open dialog (it asks first if the current project has unsaved changes); project_open with a path opens that file without a dialog.", + "group": "Commands", + "icon": "menu_open", + "key": "load_project", + "title": "Load Project" + } + ], + "title": "Open a project" + }, + { + "completion": "immediate", + "description": "Add the models of files (STL, 3MF, STEP, OBJ, AMF, SVG...) to the current project by absolute path, without a file dialog, as one undo step; a .3mf adds its objects only, not its settings (project_open opens it as a project). A .zip archive gives the model files it holds (STL, OBJ, AMF, 3MF, STEP; a .3mf its objects only, as above), as Import ZIP Archive does: those entries names, by their paths in the archive, else all of them, in place of its file list; an entry the archive lacks is refused with the names it has, before anything is imported. Importing can open a dialog (STEP mesh options, for instance); the reply is then blocked_by_dialog. Called with no arguments it is Import 3MF/STL/STEP/SVG/OBJ/AMF, and with archive: true alone Import ZIP Archive: a file dialog asks for the files, or for the archive and then which of its files to import (blocked_by_dialog). Reply: opened (models), added (how many objects), archives (each archive's path and the entries taken) and the project's objects, names and plates.", + "destructive": false, + "group": "The project", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "if": { + "not": { + "enum": [ + {}, + { + "archive": true + } + ] + } + }, + "properties": { + "archive": { + "description": "true, alone: ask for a ZIP archive in a file dialog and import the models it holds, as Import ZIP Archive does.", + "type": "boolean" + }, + "entries": { + "description": "The files to take from the one .zip archive among paths, by their paths in it (\"parts/cube.stl\"). Default: every model file it holds.", + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, "paths": { - "description": "Absolute paths.", + "description": "Absolute paths of model files, or of a .zip archive of them.", "items": { "type": "string" }, "type": "array" + }, + "silent": { + "description": "true runs the command without asking; it then needs paths, and what else the call leaves out takes its default. A call with no arguments, or with exactly a tile's arguments, does what a person's pick of that tile does.", + "enum": [ + true + ], + "type": "boolean" } }, - "required": [ - "paths" - ], + "then": { + "required": [ + "paths" + ] + }, "type": "object" }, - "key": "open_files", + "key": "project_import", "listed": true, "open_world": false, "operations": [ - "open_project", "import_models" ], "read_only": false, - "title": "Open files" + "tiles": [ + { + "args": {}, + "description": "Import models (3MF/STL/STEP/SVG/OBJ/AMF) through a file dialog, as one undo step; a project file's settings are not loaded (project_open opens a project). project_import with paths adds files' geometry without a dialog.", + "group": "Import", + "icon": "menu_open", + "key": "import_file", + "title": "Import 3MF/STL/STEP/SVG/OBJ/AMF" + }, + { + "args": { + "archive": true + }, + "description": "Import models from a ZIP archive (opens a file dialog).", + "group": "Import", + "icon": "menu_open", + "key": "import_zip_archive", + "title": "Import ZIP Archive" + } + ], + "title": "Import models" }, { "completion": "immediate", - "description": "Start a new, empty project. Called with no arguments, it asks as New Project does, about the unsaved changes if there are any: the reply is then blocked_by_dialog, and answer_dialog answers it. With arguments, or silent: true, it asks nothing: it fails, changing nothing, when the current project has unsaved changes, unless discard_changes. The presets' unsaved changes carry over to the new project unless preset_changes is \"discard\", as New Project's prompt offers. Reply, with arguments: objects, names, plates; when presets had or have unsaved changes, discarded and modified list per preset the keys dropped and the keys still unsaved. With no arguments the reply is ran and level, also once a prompt is answered, whatever the answer: Cancel keeps the project.", + "description": "Start a new, empty project. Called with no arguments, it asks as New Project does, about the unsaved changes if there are any: the reply is then blocked_by_dialog, and dialog_answer answers it. With arguments, or silent: true, it asks nothing: it fails, changing nothing, when the current project has unsaved changes, unless discard_changes. The presets' unsaved changes carry over to the new project unless preset_changes is \"discard\", as New Project's prompt offers. Reply, with arguments: objects, names, plates; when presets had or have unsaved changes, discarded and modified list per preset the keys dropped and the keys still unsaved. With no arguments the reply is ran and level, also once a prompt is answered, whatever the answer: Cancel keeps the project.", "destructive": false, - "group": "Commands", + "group": "The project", "guard": "mutate", "idempotent": false, - "in_palette": true, + "in_palette": false, "input_schema": { "additionalProperties": false, "properties": { @@ -3162,7 +909,7 @@ "type": "string" }, "silent": { - "description": "true runs the command without asking, with the defaults of what the call leaves out. A call with no arguments does what a person's pick does.", + "description": "true runs the command without asking; what the call leaves out takes its default. A call with no arguments does what a person's pick does.", "enum": [ true ], @@ -3171,25 +918,2764 @@ }, "type": "object" }, - "key": "new_project", + "key": "project_new", "listed": true, "open_world": false, "operations": [ "new_project" ], "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Runs project_new with no arguments, as New Project does: a new, empty project, after asking about the unsaved changes if there are any.", + "group": "Commands", + "icon": "menu_open", + "key": "new_project", + "title": "New Project" + } + ], "title": "New Project" }, { "completion": "immediate", - "description": "Generate a Calibration menu test as its dialog's OK does: a new project named after the test with the test model, and the process, filament and printer presets changed as the test needs (presets_changed). The test prints with filament slot 1, so the filament tab is pointed at slot 1's preset. Omitted parameters take the dialog's defaults (pressure advance's by the printer's extruder type); temperatures are clamped to 155-500 °C and rounded down to 5 °C. Fails, changing nothing, when the project has unsaved changes (pass discard_changes) or presets do (pass preset_changes). Reply: test, project, params (the values used, which the journal records), objects, names, plates, presets_changed, result_keys (where the measured value belongs), warnings, adjusted (vfa), and discarded and modified as new_project. Then slice and export. To save a measured value: new_project {discard_changes, preset_changes: \"discard\"}, set_settings the value, save_preset.", + "description": "Save the project. Called with no arguments, it saves as Save Project does: to the project's file (reply: ran, level), or, when it has none, through a file dialog (blocked_by_dialog; a native picker needs dialog_auto_answer registered first); with save_as: true alone, as Save Project As does, always through the file dialog. With path, it saves a .3mf there without the file dialog, and the file becomes the project's (reply: path, bytes); a name ending in .gcode.3mf is refused (project_export writes that). Either way the save can still open a dialog (blocked_by_dialog): a warning when settings name a plugin OrcaSlicer cannot identify, or an error when the file cannot be written. A save that writes nothing, its file dialog or that warning cancelled or the write failed, fails with project_not_saved, and a file already there stays as it was.", "destructive": false, - "group": "api", + "group": "The project", "guard": "mutate", "idempotent": false, "in_palette": false, "input_schema": { "additionalProperties": false, + "if": { + "not": { + "enum": [ + {}, + { + "save_as": true + } + ] + } + }, + "properties": { + "overwrite": { + "description": "Replace an existing file.", + "type": "boolean" + }, + "path": { + "description": "Absolute .3mf path.", + "type": "string" + }, + "save_as": { + "description": "true, alone: ask for the file in the save dialog, as Save Project As does. With path it adds nothing: path is the new file.", + "type": "boolean" + }, + "silent": { + "description": "Goes with path, which every call but {} and {save_as: true} requires, and adds nothing to it: a call with path skips the file dialog already.", + "enum": [ + true + ], + "type": "boolean" + } + }, + "then": { + "required": [ + "path" + ] + }, + "type": "object" + }, + "key": "project_save", + "listed": true, + "open_world": false, + "operations": [ + "save_project_as" + ], + "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Runs project_save with no arguments, as Save Project does: to the project's file, or through a file dialog when it has none.", + "group": "Commands", + "icon": "menu_save", + "key": "save_project", + "title": "Save Project" + }, + { + "args": { + "save_as": true + }, + "description": "Save the project as a .3mf file through the save dialog. project_save with a path saves there without a dialog; a name ending in .gcode.3mf is refused (project_export {format: \"sliced_3mf\"} writes that).", + "group": "Commands", + "icon": "menu_save", + "key": "save_project_as", + "title": "Save Project As" + } + ], + "title": "Save Project" + }, + { + "completion": "immediate", + "description": "Write the project to a file without a dialog. gcode: the plate's G-code (slice first; it is written in the background, and the call returns once it is). sliced_3mf: the sliced plate, or all plates, as .gcode.3mf (slice first: a plate that is not sliced is written without G-code). 3mf: the model without slicing data. stl and drc (Draco): the objects as one file, or with per_object each in a file of its own, named after it, into the folder path names; every object of every plate, or those objects names. toolpaths_obj: the toolpaths the Preview shows, as an OBJ, refused while it shows none (slice the plate and show the Preview first). Without format, the path's extension (.gcode, .gcode.3mf, .3mf, .stl, .drc, .obj) says which. Called with exactly the arguments of one of the File > Export rows (format alone, sliced_3mf with plates \"all\", stl or drc with per_object), it asks for the file or folder in the dialog that row opens (blocked_by_dialog). A file per object of a project with no objects, and the toolpaths while the Preview shows none, are refused in either form. Reply: path and bytes; for gcode, path and export (ok, or superseded with a note when the project changed while it was written); for per_object, path and files (each file written); for stl and drc, objects (those written).", + "destructive": false, + "group": "The project", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "if": { + "not": { + "enum": [ + { + "format": "gcode" + }, + { + "format": "sliced_3mf" + }, + { + "format": "sliced_3mf", + "plates": "all" + }, + { + "format": "3mf" + }, + { + "format": "stl" + }, + { + "format": "stl", + "per_object": true + }, + { + "format": "drc" + }, + { + "format": "drc", + "per_object": true + }, + { + "format": "toolpaths_obj" + } + ] + } + }, + "properties": { + "format": { + "description": "What to write; default from the path's extension.", + "enum": [ + "gcode", + "sliced_3mf", + "3mf", + "stl", + "drc", + "toolpaths_obj" + ], + "type": "string" + }, + "object_ids": { + "description": "The ids object_list reports for objects, one per entry: refused when an index names another object now.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "objects": { + "description": "Object indices.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "overwrite": { + "description": "Replace an existing file.", + "type": "boolean" + }, + "path": { + "description": "Absolute output path: the file, or with per_object an existing folder.", + "type": "string" + }, + "per_object": { + "description": "stl and drc: a file per object, into a folder. Default false.", + "type": "boolean" + }, + "plates": { + "description": "\"current\" (default), a plate index, which is selected first and is the plate gcode and sliced_3mf write, or \"all\" (sliced_3mf only).", + "type": [ + "string", + "integer" + ] + }, + "silent": { + "description": "true runs the command without asking; it then needs path, and what else the call leaves out takes its default. A call with exactly a tile's arguments does what a person's pick of that tile does.", + "enum": [ + true + ], + "type": "boolean" + } + }, + "then": { + "required": [ + "path" + ] + }, + "type": "object" + }, + "key": "project_export", + "listed": true, + "open_world": false, + "operations": [ + "start_gcode_export", + "export_sliced_3mf", + "export_model_3mf", + "export_stl", + "export_toolpaths_obj" + ], + "read_only": false, + "tiles": [ + { + "args": { + "format": "gcode" + }, + "description": "Export the current plate's G-code through the export dialog, in the background. project_export with a path exports the sliced plate there without a dialog, and the call returns when the file is written; a plate that is not sliced is refused (slice first).", + "group": "Slice & Export", + "icon": "custom-gcode_gcode", + "key": "export_gcode", + "title": "Export G-code" + }, + { + "args": { + "format": "sliced_3mf" + }, + "description": "Export the current plate's sliced file (.gcode.3mf) through a file dialog; project_export with a path writes there without one.", + "group": "Slice & Export", + "icon": "save", + "key": "export_sliced_file", + "title": "Export Sliced File" + }, + { + "args": { + "format": "sliced_3mf", + "plates": "all" + }, + "description": "Export every plate's sliced file into one .gcode.3mf through a file dialog; project_export with a path writes there without one.", + "group": "Slice & Export", + "icon": "save", + "key": "export_all_sliced_file", + "title": "Export All Sliced Files" + }, + { + "args": { + "format": "3mf" + }, + "description": "Export the model as a .3mf without slicing data, through a file dialog; project_export with a path writes there without one.", + "group": "Slice & Export", + "icon": "menu_save", + "key": "export_3mf", + "title": "Export 3MF" + }, + { + "args": { + "format": "stl" + }, + "description": "Export all objects as one STL through a file dialog; project_export with a path writes there without one.", + "group": "Slice & Export", + "icon": "save", + "key": "export_stl", + "title": "Export STL" + }, + { + "args": { + "format": "stl", + "per_object": true + }, + "description": "Export each object as its own STL into the folder a dialog asks for; project_export with a folder as path writes there without one.", + "group": "Export", + "icon": "save", + "key": "export_stl_multi", + "title": "Export All Objects as STLs" + }, + { + "args": { + "format": "drc" + }, + "description": "Export all objects as one Draco (.drc) file.", + "group": "Export", + "icon": "save", + "key": "export_drc_single", + "title": "Export All Objects as DRC (one file)" + }, + { + "args": { + "format": "drc", + "per_object": true + }, + "description": "Export each object as its own Draco (.drc) file.", + "group": "Export", + "icon": "save", + "key": "export_drc_multi", + "title": "Export All Objects as DRCs" + }, + { + "args": { + "format": "toolpaths_obj" + }, + "description": "Export the sliced toolpaths as an OBJ.", + "group": "Export", + "icon": "custom-gcode_gcode", + "key": "export_toolpaths_obj", + "title": "Export Toolpaths as OBJ" + } + ], + "title": "Export" + }, + { + "completion": "immediate", + "description": "Read the settings the project stores outside any preset: the plate type (curr_bed_type), slot colours (filament_colour), flushing volumes (flush_volumes_matrix, flush_multiplier), purge mode (prime_volume_mode), prime tower position per plate (wipe_tower_x, wipe_tower_y), mixed slots (filament_is_mixed) and, with several extruders, the filament grouping (filament_map_mode, filament_map); all of them, or those named in keys. Each item has its value and meta; meta.offered lists the choices this printer has, and meta.read_only marks what is set elsewhere.", + "destructive": false, + "group": "The project", + "guard": "inspect", + "idempotent": true, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "include_meta": { + "description": "Include labels, types and ranges. Default true.", + "type": "boolean" + }, + "keys": { + "description": "Setting keys, e.g. [\"filament_colour\"].", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "type": "object" + }, + "key": "project_get_settings", + "listed": true, + "open_world": false, + "operations": [], + "read_only": true, + "title": "Read the project's settings" + }, + { + "completion": "immediate", + "description": "Change the project's own settings as the sidebar's controls write them: curr_bed_type, filament_colour (#RRGGBB per slot), flush_multiplier, flush_volumes_matrix, prime_volume_mode, and wipe_tower_x/y (mm from the plate's origin, one per plate). flush_volumes_matrix is per nozzle, slots x slots from row to column, in config order over every slot, before the multiplier; a mixed slot's entries must be given as they are, and a colour change can recalculate it, so set it last. Values are checked before anything changes; a prime tower move is one undo step. Reply: applied, changed, and a note when the app moved a prime tower that did not fit.", + "destructive": false, + "group": "The project", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "values": { + "description": "{key: value}, or {key: {index, value}} for one entry", + "type": "object" + } + }, + "required": [ + "values" + ], + "type": "object" + }, + "key": "project_set_settings", + "listed": true, + "open_world": false, + "operations": [], + "read_only": false, + "title": "Change the project's settings" + }, + { + "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; outside: the objects with an instance on no plate. An object with instances on two plates is listed under both, each time with that plate's instances. An object has its filament, auto_drop, bounding box (instance 0), brim ear count and overrides, the keys of the settings it overrides (settings_get target object reads them); its mesh_errors, as the list's warning icon reads them: open_edges, manifold (no open edge), and the loader's or a repair's counts degenerate_facets, edges_fixed, facets_removed, facets_reversed and backwards_edges (object_fix repairs it); its instances (offset, rotation in degrees, scale, mirrored, bbox); its parts, one or more: parts, negative parts, modifiers, support blockers and enforcers and precise seams (type, with 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 in mm3 on the bed, measured on instance 0; rotation_deg and scale in the object's frame; mirrored; triangle count; mesh_volume, the unscaled mesh's mm3; painted facets: supports and seam enforcers/blockers, fuzzy_skin, mmu per filament, texture per layer; a text part's text and font, an SVG part's file); its height range modifiers when it has any (layer_config_ranges: [{min_z, max_z, values}], values being a range's settings, which settings_set changes with target height_range; object_set_height_ranges takes min_z and max_z) and its variable layer height profile when it has one (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: they are what object_select, object_transform, mouse_gesture targets and the settings tools' object and part targets take. Each object and part also has an id, which stays with it when a delete, split or assemble shifts the indices: pass it as object_id / part_id to object_transform, part_add, settings_set, object_set_height_ranges and object_set_variable_layer_height (object_ids, part_ids and instance_object_ids to object_select), and a call whose index names another one now is refused instead of acting on it. limit and offset page the objects and total counts them, each once.", + "destructive": false, + "group": "Objects", + "guard": "inspect", + "idempotent": true, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "limit": { + "description": "Objects, default 200.", + "maximum": 500, + "minimum": 1, + "type": "integer" + }, + "offset": { + "minimum": 0, + "type": "integer" + }, + "plate": { + "description": "List this plate alone, without outside.", + "minimum": 0, + "type": "integer" + }, + "screen": { + "description": "Add each instance's rectangle in the shown 3D view, logical pixels [x, y, w, h].", + "type": "boolean" + } + }, + "type": "object" + }, + "key": "object_list", + "listed": true, + "open_world": false, + "operations": [], + "read_only": true, + "title": "List objects" + }, + { + "completion": "immediate", + "description": "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 / none select everything or nothing, whatever else is given; none also closes the open gizmo, as Deselect All does, and all is refused while a gizmo that keeps its selection is open. The reply is the selection as app_state.selection gives it, for all and none alone (Select All and Deselect All) too.", + "destructive": false, + "group": "Objects", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "add": { + "description": "Add to the selection instead of replacing it.", + "type": "boolean" + }, + "all": { + "description": "Select all objects.", + "type": "boolean" + }, + "instance_object_ids": { + "description": "The ids object_list reports for the objects of instances, one per entry: refused when a pair names another object now.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "instances": { + "description": "[[object, instance], ...]", + "items": { + "type": "array" + }, + "type": "array" + }, + "none": { + "description": "Clear the selection and close the open gizmo.", + "type": "boolean" + }, + "object_ids": { + "description": "The ids object_list reports for objects, one per entry: refused when an index names another object now.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "objects": { + "description": "Object indices.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "part_ids": { + "description": "The ids object_list reports for the entries of parts, one per entry: refused when a pair names another part now.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "parts": { + "description": "[[object, part], ...]", + "items": { + "type": "array" + }, + "type": "array" + } + }, + "type": "object" + }, + "key": "object_select", + "listed": true, + "open_world": false, + "operations": [], + "read_only": false, + "tiles": [ + { + "args": { + "all": true + }, + "description": "Select every object in the 3D view (the assemble view while it is shown, else Prepare, switching to it), and reply with the selection; refused while a gizmo that keeps its selection is open. A person's pick shows Prepare and selects there.", + "group": "Object", + "icon": "", + "key": "select_all", + "title": "Select All Objects" + }, + { + "args": { + "none": true + }, + "description": "Clear the selection in the 3D view (the assemble view while it is shown, else Prepare, switching to it), close the open gizmo, and reply with the selection. A person's pick clears it where it is, switching no tab.", + "group": "Object", + "icon": "", + "key": "deselect_all", + "title": "Deselect All" + } + ], + "title": "Select objects" + }, + { + "completion": "immediate", + "description": "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, scale a factor (one number or [x, y, z]), size [x, y, z] mm along the object's or part's own axes, plate moves the instance onto that plate at the same place. mode \"relative\" (default) adds to the current placement (a scale multiplies it), \"absolute\" sets it. An instance is dropped back onto the bed, unless its object's auto_drop is off; drop_to_bed false lets it sink into the bed, but an object of one part left above the bed still drops. A part moves as the Object manipulation panel moves it: translate and rotate along the bed's axes, measured on instance 0, scale and size along its own axes; every instance shows the change, and Auto Drop may lower the object afterwards. The instance is the object's instance (default 0) and the part one of its parts; with no object, the instance or part selected in the Prepare view, or instance 0 of the object selected. One undo step. Reply: the instance's offset, scale and plate, or the part's size along its own axes and its object_list entry (part_info), and what it moved (instances or parts).", + "destructive": false, + "group": "Objects", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "drop_to_bed": { + "description": "Default true; instances only.", + "type": "boolean" + }, + "instance": { + "description": "An instance of the object (object_list).", + "minimum": 0, + "type": "integer" + }, + "mode": { + "description": "Default relative.", + "enum": [ + "relative", + "absolute" + ], + "type": "string" + }, + "object": { + "description": "Object index (object_list).", + "minimum": 0, + "type": "integer" + }, + "object_id": { + "description": "The id object_list reports for this object: the call is refused when the index names another one now.", + "minimum": 0, + "type": "integer" + }, + "part": { + "description": "A part of the object (object_list).", + "minimum": 0, + "type": "integer" + }, + "part_id": { + "description": "The id object_list reports for this part: the call is refused when the index names another one now.", + "minimum": 0, + "type": "integer" + }, + "plate": { + "description": "Move the instance to this plate.", + "minimum": 0, + "type": "integer" + }, + "position": { + "description": "[x, y, z] mm: the position to move to. Not with translate.", + "items": { + "type": "number" + }, + "type": "array" + }, + "rotate": { + "description": "[x, y, z] degrees; relative only for a part", + "items": { + "type": "number" + }, + "type": "array" + }, + "scale": { + "description": "Factor or [x, y, z] factors.", + "type": [ + "number", + "array" + ] + }, + "size": { + "description": "[x, y, z] mm, null keeps an axis; one number and two nulls keep the proportions. Not with scale.", + "items": { + "type": [ + "number", + "null" + ] + }, + "type": "array" + }, + "translate": { + "description": "[x, y, z] mm", + "items": { + "type": "number" + }, + "type": "array" + } + }, + "type": "object" + }, + "key": "object_transform", + "listed": true, + "open_world": false, + "operations": [], + "read_only": false, + "title": "Move, rotate or scale an instance or a part" + }, + { + "completion": "immediate", + "description": "Add a primitive shape (cube, cylinder, sphere, cone, disc or torus) as a new object, as Add Primitive does: on the current plate, or on plate, which becomes the current one; at position, in the bed coordinates object_list and object_transform use, else where Add Primitive puts it; named name, else after its shape. With a size, at that size; with silent, at the shape's built-in size. With shape alone, as its tiles, the Primitive size dialog asks for the size (blocked_by_dialog), unless a person turned that dialog off, and the call is refused while an object is selected (part_add adds a shape to an object); any other call adds the object whatever is selected. One undo step; the new object is selected. Reply: the object (objects, object), its plate and offset. The shape may then be turned toward the part-cooling fan, so the size is along its own axes before that turn.", + "destructive": false, + "group": "Objects", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "if": { + "not": { + "enum": [ + { + "shape": "cube" + }, + { + "shape": "cylinder" + }, + { + "shape": "sphere" + }, + { + "shape": "cone" + }, + { + "shape": "disc" + }, + { + "shape": "torus" + } + ] + } + }, + "properties": { + "name": { + "description": "The object's name. Default: its shape's.", + "type": "string" + }, + "plate": { + "description": "The plate to add it on. Default: the current plate.", + "minimum": 0, + "type": "integer" + }, + "position": { + "description": "[x, y, z] mm: where its first instance goes, as object_transform's position; it then rests on the bed.", + "items": { + "type": "number" + }, + "type": "array" + }, + "shape": { + "description": "The shape.", + "enum": [ + "cube", + "cylinder", + "sphere", + "cone", + "disc", + "torus" + ], + "type": "string" + }, + "silent": { + "description": "true runs the command without asking; it then needs shape, and what else the call leaves out takes its default. A call with exactly a tile's arguments does what a person's pick of that tile does.", + "enum": [ + true + ], + "type": "boolean" + }, + "size": { + "description": "mm, the Primitive size dialog's fields, in place of the dialog: cube [x, y, z]; cylinder, cone, disc [diameter, height]; sphere [diameter]; torus [inner diameter, tube diameter]; each above 0.", + "items": { + "type": "number" + }, + "type": "array" + } + }, + "then": { + "required": [ + "shape" + ] + }, + "type": "object" + }, + "key": "object_add_primitive", + "listed": true, + "open_world": false, + "operations": [ + "add_primitive", + "rename_object" + ], + "read_only": false, + "tiles": [ + { + "args": { + "shape": "cube" + }, + "description": "Add a cube object to the current plate at the size its dialog asks for; fails while an object is selected. object_add_primitive with a size, or silent, skips the dialog.", + "group": "Add Primitive", + "icon": "menu_obj_cube", + "key": "add_primitive_cube", + "title": "Cube" + }, + { + "args": { + "shape": "cylinder" + }, + "description": "Add a cylinder object to the current plate at the size its dialog asks for; fails while an object is selected. object_add_primitive with a size, or silent, skips the dialog. The shape may then be turned toward the part-cooling fan, so the size is along its own axes before that turn.", + "group": "Add Primitive", + "icon": "menu_obj_cylinder", + "key": "add_primitive_cylinder", + "title": "Cylinder" + }, + { + "args": { + "shape": "sphere" + }, + "description": "Add a sphere object to the current plate at the size its dialog asks for; fails while an object is selected. object_add_primitive with a size, or silent, skips the dialog.", + "group": "Add Primitive", + "icon": "menu_obj_sphere", + "key": "add_primitive_sphere", + "title": "Sphere" + }, + { + "args": { + "shape": "cone" + }, + "description": "Add a cone object to the current plate at the size its dialog asks for; fails while an object is selected. object_add_primitive with a size, or silent, skips the dialog. The shape may then be turned toward the part-cooling fan, so the size is along its own axes before that turn.", + "group": "Add Primitive", + "icon": "menu_obj_cone", + "key": "add_primitive_cone", + "title": "Cone" + }, + { + "args": { + "shape": "disc" + }, + "description": "Add a disc object to the current plate at the size its dialog asks for; fails while an object is selected. object_add_primitive with a size, or silent, skips the dialog. The shape may then be turned toward the part-cooling fan, so the size is along its own axes before that turn.", + "group": "Add Primitive", + "icon": "menu_obj_disc", + "key": "add_primitive_disc", + "title": "Disc" + }, + { + "args": { + "shape": "torus" + }, + "description": "Add a torus object to the current plate at the size its dialog asks for; fails while an object is selected. object_add_primitive with a size, or silent, skips the dialog. The shape may then be turned toward the part-cooling fan, so the size is along its own axes before that turn.", + "group": "Add Primitive", + "icon": "menu_obj_torus", + "key": "add_primitive_torus", + "title": "Torus" + } + ], + "title": "Add a primitive" + }, + { + "completion": "immediate", + "description": "Add one of the test models OrcaSlicer ships to the current plate, as Add Handy models does; orca_cube and orcasliced_combo, of several files, then arrange the objects as the toolbar's Arrange does, which moves the others too.", + "destructive": false, + "group": "Objects", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "model": { + "description": "The model.", + "enum": [ + "orca_cube", + "orcasliced_combo", + "orca_badge", + "orca_tolerance_test", + "3dbenchy", + "cali_cat", + "autodesk_fdm_test", + "voron_cube", + "stanford_bunny", + "orca_string_hell" + ], + "type": "string" + } + }, + "required": [ + "model" + ], + "type": "object" + }, + "key": "object_add_handy_model", + "listed": true, + "open_world": false, + "operations": [], + "read_only": false, + "tiles": [ + { + "args": { + "model": "orca_cube" + }, + "description": "Add the Orca Cube and its plug to the current plate, then arrange the objects as the toolbar's Arrange does, which moves the others too.", + "group": "Add Handy models", + "icon": "", + "key": "add_handy_orca_cube", + "title": "Orca Cube" + }, + { + "args": { + "model": "orcasliced_combo" + }, + "description": "Add the OrcaSliced Combo (the OrcaSliced model, the Orca Cube and its plug) to the current plate, then arrange the objects as the toolbar's Arrange does, which moves the others too.", + "group": "Add Handy models", + "icon": "", + "key": "add_handy_orcasliced_combo", + "title": "OrcaSliced Combo" + }, + { + "args": { + "model": "orca_badge" + }, + "description": "Add the Orca Badge model to the current plate.", + "group": "Add Handy models", + "icon": "", + "key": "add_handy_orca_badge", + "title": "Orca Badge" + }, + { + "args": { + "model": "orca_tolerance_test" + }, + "description": "Add the Orca Tolerance Test model to the current plate.", + "group": "Add Handy models", + "icon": "", + "key": "add_handy_orca_tolerance_test", + "title": "Orca Tolerance Test" + }, + { + "args": { + "model": "3dbenchy" + }, + "description": "Add the 3DBenchy model to the current plate.", + "group": "Add Handy models", + "icon": "", + "key": "add_handy_3dbenchy", + "title": "3DBenchy" + }, + { + "args": { + "model": "cali_cat" + }, + "description": "Add the Cali Cat model to the current plate.", + "group": "Add Handy models", + "icon": "", + "key": "add_handy_cali_cat", + "title": "Cali Cat" + }, + { + "args": { + "model": "autodesk_fdm_test" + }, + "description": "Add the Autodesk FDM Test model to the current plate.", + "group": "Add Handy models", + "icon": "", + "key": "add_handy_autodesk_fdm_test", + "title": "Autodesk FDM Test" + }, + { + "args": { + "model": "voron_cube" + }, + "description": "Add the Voron Cube model to the current plate.", + "group": "Add Handy models", + "icon": "", + "key": "add_handy_voron_cube", + "title": "Voron Cube" + }, + { + "args": { + "model": "stanford_bunny" + }, + "description": "Add the Stanford Bunny model to the current plate.", + "group": "Add Handy models", + "icon": "", + "key": "add_handy_stanford_bunny", + "title": "Stanford Bunny" + }, + { + "args": { + "model": "orca_string_hell" + }, + "description": "Add the Orca String Hell model to the current plate.", + "group": "Add Handy models", + "icon": "", + "key": "add_handy_orca_string_hell", + "title": "Orca String Hell" + } + ], + "title": "Add a handy model" + }, + { + "completion": "immediate", + "description": "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.", + "destructive": false, + "group": "Objects", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": {}, + "type": "object" + }, + "key": "object_add_text", + "listed": true, + "open_world": false, + "operations": [], + "read_only": false, + "tiles": [ + { + "args": {}, + "description": "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.", + "group": "Add Primitive", + "icon": "menu_obj_text", + "key": "add_primitive_text", + "title": "Text" + } + ], + "title": "Text" + }, + { + "completion": "immediate", + "description": "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.", + "destructive": false, + "group": "Objects", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "path": { + "description": "Absolute path of an .svg file.", + "type": "string" + } + }, + "type": "object" + }, + "key": "object_add_svg", + "listed": true, + "open_world": false, + "operations": [], + "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Add an SVG as a new object, or as a part of the selected object, from the file a dialog asks for; object_add_svg with a path uses that file without one. The part is created in the background (app_wait {for: \"idle\"} waits for it), and the SVG gizmo opens on it.", + "group": "Add Primitive", + "icon": "menu_obj_svg", + "key": "add_primitive_svg", + "title": "SVG" + } + ], + "title": "SVG" + }, + { + "completion": "immediate", + "description": "Delete objects, instances or parts, as Delete does: those named (objects, instances, parts), what stands on a plate (plate: its objects, or the instances on it of an object on two plates), every object (all, as Delete All does), or with none of these what is selected in the Prepare view. An object whose every instance or every part is named goes whole. An object's last solid part alone, and a cut object or a solid or negative part of one, are refused with the message or the question Delete gives; a call with no arguments leaves them to the object list, which shows the message or asks the question (blocked_by_dialog), and all deletes cut objects without asking, as Delete All does. One undo step. Reply: what was deleted (objects, instances, parts, with the indices they had); kept, what was named and stayed, with its indices now (the object list deletes from the last named and stops at what it refuses or asks about); and object_count, the objects left; the objects after a deleted one move down.", + "destructive": false, + "group": "Objects", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "all": { + "description": "Delete every object. Default false: the targets.", + "type": "boolean" + }, + "instance_object_ids": { + "description": "The ids object_list reports for the objects of instances, one per entry: refused when a pair names another object now.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "instances": { + "description": "[[object, instance], ...]", + "items": { + "type": "array" + }, + "type": "array" + }, + "object_ids": { + "description": "The ids object_list reports for objects, one per entry: refused when an index names another object now.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "objects": { + "description": "Object indices.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "part_ids": { + "description": "The ids object_list reports for the entries of parts, one per entry: refused when a pair names another part now.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "parts": { + "description": "[[object, part], ...]", + "items": { + "type": "array" + }, + "type": "array" + }, + "plate": { + "description": "Delete what stands on this plate.", + "minimum": 0, + "type": "integer" + }, + "silent": { + "description": "true runs the command without asking; what the call leaves out takes its default. A call with no arguments, or with exactly a tile's arguments, does what a person's pick of that tile does.", + "enum": [ + true + ], + "type": "boolean" + } + }, + "type": "object" + }, + "key": "object_delete", + "listed": true, + "open_world": false, + "operations": [ + "delete_objects" + ], + "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Delete the selected objects or parts.", + "group": "Object", + "icon": "delete", + "key": "obj_delete", + "title": "Delete Selected" + }, + { + "args": { + "all": true + }, + "description": "Delete all objects.", + "group": "Object", + "icon": "delete", + "key": "obj_delete_all", + "title": "Delete All Objects" + } + ], + "title": "Delete objects" + }, + { + "completion": "immediate", + "description": "Rename an object, or a part of it (object and part), or with neither the object or part selected in the Prepare view. With a name, skips the Rename dialog; an empty name, or one with characters a file name cannot hold, is refused. Reply: what was renamed, with its name (objects or parts).", + "destructive": false, + "group": "Objects", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "if": { + "minProperties": 1 + }, + "properties": { + "name": { + "description": "The new name, in place of the Rename dialog.", + "type": "string" + }, + "object": { + "description": "Object index (object_list).", + "minimum": 0, + "type": "integer" + }, + "object_id": { + "description": "The id object_list reports for this object: the call is refused when the index names another one now.", + "minimum": 0, + "type": "integer" + }, + "part": { + "description": "A part of the object (object_list).", + "minimum": 0, + "type": "integer" + }, + "part_id": { + "description": "The id object_list reports for this part: the call is refused when the index names another one now.", + "minimum": 0, + "type": "integer" + }, + "silent": { + "description": "true runs the command without asking; it then needs name, and what else the call leaves out takes its default. A call with no arguments does what a person's pick does.", + "enum": [ + true + ], + "type": "boolean" + } + }, + "then": { + "required": [ + "name" + ] + }, + "type": "object" + }, + "key": "object_rename", + "listed": true, + "open_world": false, + "operations": [ + "rename_object" + ], + "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Rename the selected object or part (select one) in the Rename dialog; object_rename with a name skips it.", + "group": "Object", + "icon": "", + "key": "obj_rename", + "title": "Rename" + } + ], + "title": "Rename" + }, + { + "completion": "immediate", + "description": "Give an object this many instances (count), as Set Number of Instances does, or one more or one fewer (delta 1 or -1), as the toolbar's + and - do: the object named, else the one selected in the Prepare view, or the object of the selected instance or part. With no arguments the dialog asks for the count (blocked_by_dialog). New instances overlap; arrange afterwards. One undo step; the object is selected. Reply: the object (objects, object) and instances, how many it has.", + "destructive": false, + "group": "Objects", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "count": { + "description": "The total number of instances, up to 1000, in place of the dialog.", + "minimum": 1, + "type": "integer" + }, + "delta": { + "description": "1 adds an instance and -1 removes one, as the toolbar's + and - do.", + "enum": [ + 1, + -1 + ], + "type": "integer" + }, + "object": { + "description": "Object index (object_list).", + "minimum": 0, + "type": "integer" + }, + "object_id": { + "description": "The id object_list reports for this object: the call is refused when the index names another one now.", + "minimum": 0, + "type": "integer" + }, + "silent": { + "description": "true runs the command without asking; it then needs count or delta. A call with no arguments, or with exactly a tile's arguments, does what a person's pick of that tile does.", + "enum": [ + true + ], + "type": "boolean" + } + }, + "type": "object" + }, + "key": "object_set_instances", + "listed": true, + "open_world": false, + "operations": [ + "set_instance_count" + ], + "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Give the selected object the number of instances the dialog asks for, in one undo step; object_set_instances with a count skips the dialog. New instances overlap; arrange afterwards.", + "group": "Object", + "icon": "instance_add", + "key": "obj_set_instances", + "title": "Set Number of Instances" + }, + { + "args": { + "delta": 1 + }, + "description": "Add an instance of the selected object.", + "group": "Object", + "icon": "instance_add", + "key": "obj_instances_up", + "title": "Increase Instances" + }, + { + "args": { + "delta": -1 + }, + "description": "Remove an instance of the selected object.", + "group": "Object", + "icon": "instance_remove", + "key": "obj_instances_down", + "title": "Decrease Instances" + } + ], + "title": "Set the number of instances" + }, + { + "completion": "immediate", + "description": "Make each instance of an object a separate object (object), or some instances of one object one new object (instances), as Set as Individual Objects does; with neither, what is selected in the Prepare view: an object, or some of its instances. New objects are added last. Reply: the objects that hold those instances afterwards (objects): the object and its new objects, or the new object.", + "destructive": false, + "group": "Objects", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "instance_object_ids": { + "description": "The ids object_list reports for the objects of instances, one per entry: refused when a pair names another object now.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "instances": { + "description": "[[object, instance], ...]", + "items": { + "type": "array" + }, + "type": "array" + }, + "object": { + "description": "Object index (object_list).", + "minimum": 0, + "type": "integer" + }, + "object_id": { + "description": "The id object_list reports for this object: the call is refused when the index names another one now.", + "minimum": 0, + "type": "integer" + } + }, + "type": "object" + }, + "key": "object_separate_instances", + "listed": true, + "open_world": false, + "operations": [ + "separate_instances" + ], + "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Make each instance of the selected object a separate object (object_select {objects: [n]}); with some of its instances selected, only those. New objects are added last; the reply lists the objects that hold those instances (objects).", + "group": "Object", + "icon": "", + "key": "obj_instances_to_objects", + "title": "Set as Individual Objects" + } + ], + "title": "Set as Individual Objects" + }, + { + "completion": "immediate", + "description": "Split an object into separate objects, or into parts of it, as Split > To Objects and To Parts do: the object named, else the one row selected in the object list, as Split reads it: an object's row, into objects also a row of the object's own other than a part's, and into parts a part's row, or another row of the object. A mesh of one shell is refused, and into parts so is an object of several parts, whose part is selected to split it. Into objects, the object is removed and its pieces are added last and selected. Where some of them would float above the bed of an object that drops, keep_z answers the question Split asks (true keeps their height, false lets them drop), and without it the call is refused (auto_drop_question); with only a tile's arguments Split asks it (blocked_by_dialog). One undo step. Reply: the new objects (objects) or the parts the part became (parts), with their indices afterwards, and object_count.", + "destructive": false, + "group": "Objects", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "if": { + "not": { + "enum": [ + { + "into": "objects" + }, + { + "into": "parts" + } + ] + } + }, + "properties": { + "into": { + "description": "Separate objects, or parts of the object.", + "enum": [ + "objects", + "parts" + ], + "type": "string" + }, + "keep_z": { + "description": "Into objects, the answer to the question whether pieces that would float above the bed keep their height: true keeps it, false lets them drop.", + "type": "boolean" + }, + "object": { + "description": "Object index (object_list).", + "minimum": 0, + "type": "integer" + }, + "object_id": { + "description": "The id object_list reports for this object: the call is refused when the index names another one now.", + "minimum": 0, + "type": "integer" + }, + "silent": { + "description": "true runs the command without asking; it then needs into, and what else the call leaves out takes its default. A call with exactly a tile's arguments does what a person's pick of that tile does.", + "enum": [ + true + ], + "type": "boolean" + } + }, + "then": { + "required": [ + "into" + ] + }, + "type": "object" + }, + "key": "object_split", + "listed": true, + "open_world": false, + "operations": [ + "split_object" + ], + "read_only": false, + "tiles": [ + { + "args": { + "into": "objects" + }, + "description": "Split the selected object into separate objects.", + "group": "Object", + "icon": "menu_split_objects", + "key": "obj_split_objects", + "title": "Split to Objects" + }, + { + "args": { + "into": "parts" + }, + "description": "Split the selected object into parts.", + "group": "Object", + "icon": "menu_split_parts", + "key": "obj_split_parts", + "title": "Split to Parts" + } + ], + "title": "Split an object" + }, + { + "completion": "immediate", + "description": "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 are refused. They are removed and the new object is added last and selected, so object indices change. One undo step. Reply: the new object's index (object) and name, and objects.", + "destructive": false, + "group": "Objects", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "object_ids": { + "description": "The ids object_list reports for objects, one per entry: refused when an index names another object now.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "objects": { + "description": "Object indices.", + "items": { + "type": "integer" + }, + "type": "array" + } + }, + "type": "object" + }, + "key": "object_assemble", + "listed": true, + "open_world": false, + "operations": [ + "assemble_objects" + ], + "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Assemble two or more selected objects into one object of parts named Assembly. They are removed and it is added last, so object indices change; the reply has its index (object) and name.", + "group": "Object", + "icon": "", + "key": "obj_assemble", + "title": "Assemble" + } + ], + "title": "Assemble" + }, + { + "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 tiles, 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; object indices change. Reply: the new order (order: [{object, name, plate}]), and descending with by.", + "destructive": false, + "group": "Objects", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "all": { + "description": "With by: order the objects of every plate. Default false: one plate's.", + "type": "boolean" + }, + "by": { + "description": "What to order by.", + "enum": [ + "name", + "filament", + "height", + "size" + ], + "type": "string" + }, + "descending": { + "description": "With by: descending order. Default false.", + "type": "boolean" + }, + "order": { + "description": "In place of by: the plate's objects, by index (object_list), each once, in the order wanted.", + "items": { + "minimum": 0, + "type": "integer" + }, + "minItems": 1, + "type": "array" + }, + "plate": { + "description": "Order this plate's objects. Default: the current plate.", + "minimum": 0, + "type": "integer" + } + }, + "type": "object" + }, + "key": "object_order", + "listed": true, + "open_world": false, + "operations": [ + "order_objects", + "reorder_objects" + ], + "read_only": false, + "tiles": [ + { + "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.", + "group": "Object", + "icon": "", + "key": "obj_order_by_name", + "title": "Order by Name" + }, + { + "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.", + "group": "Object", + "icon": "", + "key": "obj_order_by_filament", + "title": "Order by Filament" + }, + { + "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.", + "group": "Object", + "icon": "", + "key": "obj_order_by_height", + "title": "Order by Height" + }, + { + "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.", + "group": "Object", + "icon": "", + "key": "obj_order_by_size", + "title": "Order by Size" + } + ], + "title": "Order objects" + }, + { + "completion": "immediate", + "description": "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 already rests on the bed is no error: moved false says that nothing moved. One undo step; the targets are left selected. Reply: what it acted on (objects, instances, parts) and moved.", + "destructive": false, + "group": "Objects", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "object_ids": { + "description": "The ids object_list reports for objects, one per entry: refused when an index names another object now.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "objects": { + "description": "Object indices.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "part_ids": { + "description": "The ids object_list reports for the entries of parts, one per entry: refused when a pair names another part now.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "parts": { + "description": "[[object, part], ...]", + "items": { + "type": "array" + }, + "type": "array" + } + }, + "type": "object" + }, + "key": "object_drop", + "listed": true, + "open_world": false, + "operations": [ + "drop_objects" + ], + "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Drop the selection onto the bed.", + "group": "Object", + "icon": "toolbar_flatten", + "key": "obj_drop", + "title": "Drop to Bed" + } + ], + "title": "Drop to Bed" + }, + { + "completion": "immediate", + "description": "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 of one instance or parts of one. Cut objects are refused. One undo step; the targets are left selected. Reply: what it mirrored (objects, instances, parts).", + "destructive": false, + "group": "Objects", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "axis": { + "description": "The axis to mirror along.", + "enum": [ + "x", + "y", + "z" + ], + "type": "string" + }, + "object_ids": { + "description": "The ids object_list reports for objects, one per entry: refused when an index names another object now.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "objects": { + "description": "Object indices.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "part_ids": { + "description": "The ids object_list reports for the entries of parts, one per entry: refused when a pair names another part now.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "parts": { + "description": "[[object, part], ...]", + "items": { + "type": "array" + }, + "type": "array" + } + }, + "required": [ + "axis" + ], + "type": "object" + }, + "key": "object_mirror", + "listed": true, + "open_world": false, + "operations": [ + "mirror_objects" + ], + "read_only": false, + "tiles": [ + { + "args": { + "axis": "x" + }, + "description": "Mirror the selection along X.", + "group": "Object", + "icon": "menu_mirror_x", + "key": "obj_mirror_x", + "title": "Mirror X" + }, + { + "args": { + "axis": "y" + }, + "description": "Mirror the selection along Y.", + "group": "Object", + "icon": "menu_mirror_y", + "key": "obj_mirror_y", + "title": "Mirror Y" + }, + { + "args": { + "axis": "z" + }, + "description": "Mirror the selection along Z.", + "group": "Object", + "icon": "menu_mirror_z", + "key": "obj_mirror_z", + "title": "Mirror Z" + } + ], + "title": "Mirror objects" + }, + { + "completion": "immediate", + "description": "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 Prepare view as one group, on plate, or with no arguments, as its tile, on the current plate. A group moves as one, its box to the plate's centre, its objects keeping their places relative to each other, so a group spread over several plates and sent to plate may not fit on its bed. One undo step; the targets are left selected. Reply: what it centred (objects, instances, parts) and the groups (plates: [{plate, objects}]).", + "destructive": false, + "group": "Objects", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "object_ids": { + "description": "The ids object_list reports for objects, one per entry: refused when an index names another object now.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "objects": { + "description": "Object indices.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "plate": { + "description": "Centre them all on this plate.", + "minimum": 0, + "type": "integer" + } + }, + "type": "object" + }, + "key": "object_center", + "listed": true, + "open_world": false, + "operations": [ + "center_objects" + ], + "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Center the selection on its plate.", + "group": "Object", + "icon": "", + "key": "obj_center", + "title": "Center Selected on Plate" + } + ], + "title": "Center Selected on Plate" + }, + { + "completion": "immediate", + "description": "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 than a rectangle or a circle are refused. One undo step; the targets are left selected. Reply: what it scaled (objects, instances) and each instance's scale (scales: [{object, instance, scale}]).", + "destructive": false, + "group": "Objects", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "object_ids": { + "description": "The ids object_list reports for objects, one per entry: refused when an index names another object now.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "objects": { + "description": "Object indices.", + "items": { + "type": "integer" + }, + "type": "array" + } + }, + "type": "object" + }, + "key": "object_scale_to_fit", + "listed": true, + "open_world": false, + "operations": [ + "scale_to_fit" + ], + "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Scale the selection to fit the print volume.", + "group": "Object", + "icon": "", + "key": "obj_fit_volume", + "title": "Scale to Fit Print Volume" + } + ], + "title": "Scale to Fit Print Volume" + }, + { + "completion": "immediate", + "description": "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 nothing is selected. An object on a locked plate, or one that is not printable, keeps its orientation. A call that names objects or plates turns no other object: a plate named that holds no objects, a locked plate named, and objects named none of which can be turned (not printable, or on a locked plate) are refused. A selection of objects that are not printable, none on a locked plate, leaves the job to turn every other object, as the toolbar's does. Waits for the job to end. One undo step; objects named are left selected. Reply: the objects it turned (objects) and the rotation of each instance it turned (rotations: [{object, instance, rotation_deg}]).", + "destructive": false, + "group": "Objects", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "object_ids": { + "description": "The ids object_list reports for objects, one per entry: refused when an index names another object now.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "objects": { + "description": "Object indices.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "plates": { + "description": "Plate indices: orient the objects that stand on them.", + "items": { + "type": "integer" + }, + "type": "array" + } + }, + "type": "object" + }, + "key": "object_auto_orient", + "listed": true, + "open_world": false, + "operations": [ + "orient_objects" + ], + "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Auto-orient the selection, or every object when nothing is selected; the call returns when it is done.", + "group": "Object", + "icon": "toolbar_orient", + "key": "obj_orient", + "title": "Auto-Orient" + } + ], + "title": "Auto-Orient" + }, + { + "completion": "immediate", + "description": "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 instance that is not printable is greyed in the 3D view and left out of slicing. One undo step. Reply: every instance it set, with printable (instances), and the objects named (objects).", + "destructive": false, + "examples": [ + { + "calls": [ + { + "args": { + "count": 3, + "object": 0 + }, + "tool": "object_set_instances" + }, + { + "args": { + "instances": [ + [ + 0, + 1 + ] + ], + "printable": false + }, + "tool": "object_set_printable" + } + ], + "title": "Leave one instance out of the print" + }, + { + "calls": [ + { + "args": { + "printable": true + }, + "tool": "object_set_printable" + } + ], + "title": "Print the selected objects again" + } + ], + "group": "Objects", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "instance_object_ids": { + "description": "The ids object_list reports for the objects of instances, one per entry: refused when a pair names another object now.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "instances": { + "description": "[[object, instance], ...]", + "items": { + "type": "array" + }, + "type": "array" + }, + "object_ids": { + "description": "The ids object_list reports for objects, one per entry: refused when an index names another object now.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "objects": { + "description": "Object indices.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "printable": { + "description": "true marks them printable, false not printable.", + "type": "boolean" + } + }, + "required": [ + "printable" + ], + "type": "object" + }, + "key": "object_set_printable", + "listed": true, + "open_world": false, + "operations": [ + "set_objects_printable" + ], + "read_only": false, + "title": "Set printable" + }, + { + "completion": "immediate", + "description": "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 object_transform or the Move gizmo leaves it, above the bed; with it on it drops onto the bed when it is next moved. An object's instances share it. One undo step. Reply: the objects (objects) and auto_drop.", + "destructive": false, + "examples": [ + { + "calls": [ + { + "args": { + "auto_drop": false, + "objects": [ + 0 + ] + }, + "tool": "object_set_auto_drop" + } + ], + "title": "Let an object stay above the bed where it is moved to" + }, + { + "calls": [ + { + "args": { + "auto_drop": true + }, + "tool": "object_set_auto_drop" + } + ], + "title": "Let the selected objects drop onto the bed again" + } + ], + "group": "Objects", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "auto_drop": { + "description": "true lets the objects drop onto the bed, false lets them stay above it.", + "type": "boolean" + }, + "object_ids": { + "description": "The ids object_list reports for objects, one per entry: refused when an index names another object now.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "objects": { + "description": "Object indices.", + "items": { + "type": "integer" + }, + "type": "array" + } + }, + "required": [ + "auto_drop" + ], + "type": "object" + }, + "key": "object_set_auto_drop", + "listed": true, + "open_world": false, + "operations": [ + "set_objects_auto_drop" + ], + "read_only": false, + "title": "Set Auto Drop" + }, + { + "completion": "immediate", + "description": "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 standing for its object. A painted modifier is left as it is, and painting is kept only with the keep_painting preference on. It opens no progress dialog and shows no notification; the call waits for the repair, during which the window does not redraw, and job_cancel {job} cancels it: the call fails with the reply in its details, and what was repaired before the cancel, a part of the object it stopped in among them, keeps its new mesh. Refused while a gizmo is open. One undo step. Reply: what it repaired (objects, parts) and repairs, for each in turn: changed, failed (why it could not be repaired), the object's mesh_errors_before and mesh_errors_after (as object_list gives them), painting_removed, and cancelled: true on the one a cancel stopped, listed when its mesh had changed by then.", + "destructive": false, + "examples": [ + { + "calls": [ + { + "args": {}, + "tool": "object_list" + }, + { + "args": { + "objects": [ + 0 + ] + }, + "tool": "object_fix" + } + ], + "title": "Repair an imported object whose mesh has holes" + }, + { + "calls": [ + { + "args": { + "plate": 0 + }, + "tool": "object_fix" + } + ], + "title": "Repair the objects on the first plate" + } + ], + "group": "Objects", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "all": { + "description": "Repair every object. Default false: the targets.", + "type": "boolean" + }, + "object_ids": { + "description": "The ids object_list reports for objects, one per entry: refused when an index names another object now.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "objects": { + "description": "Object indices.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "part_ids": { + "description": "The ids object_list reports for the entries of parts, one per entry: refused when a pair names another part now.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "parts": { + "description": "[[object, part], ...]", + "items": { + "type": "array" + }, + "type": "array" + }, + "plate": { + "description": "Repair the objects on this plate.", + "minimum": 0, + "type": "integer" + } + }, + "type": "object" + }, + "key": "object_fix", + "listed": true, + "open_world": false, + "operations": [ + "fix_objects" + ], + "read_only": false, + "title": "Fix Model" + }, + { + "completion": "immediate", + "description": "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 each (default 1, as the dialog's field starts), added after the other objects, placed near them on the current plate; the last copies are left selected. With arrange true the current plate is then arranged, as the dialog's Auto arrange plate after cloning does; without arrange, the dialog's choice: the auto_arrange preference. The call waits for the arrangement. One undo step for the copies, and one for the arrangement. Reply: the new objects (objects), what was copied (copied: its objects, or its instances where instances were selected), object_count and arranged.", + "destructive": false, + "examples": [ + { + "calls": [ + { + "args": { + "arrange": true, + "count": 3, + "objects": [ + 0 + ] + }, + "tool": "object_clone" + } + ], + "title": "Make three copies of an object and arrange the plate" + }, + { + "calls": [ + { + "args": { + "arrange": false + }, + "tool": "object_clone" + } + ], + "title": "Copy the selected objects once, where they are" + } + ], + "group": "Objects", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "arrange": { + "description": "Arrange the current plate afterwards. Default: the Clone dialog's choice, the auto_arrange preference.", + "type": "boolean" + }, + "count": { + "description": "Copies of each, up to 1000 as the Clone dialog takes. Default 1.", + "maximum": 1000, + "minimum": 1, + "type": "integer" + }, + "object_ids": { + "description": "The ids object_list reports for objects, one per entry: refused when an index names another object now.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "objects": { + "description": "Object indices.", + "items": { + "type": "integer" + }, + "type": "array" + } + }, + "type": "object" + }, + "key": "object_clone", + "listed": true, + "open_world": false, + "operations": [ + "clone_objects" + ], + "read_only": false, + "title": "Clone" + }, + { + "completion": "immediate", + "description": "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 the Prepare view. A part's file is the one it was loaded from, else the file of that name beside its object's file. A part whose file is gone is not asked for: it is listed under missing. A part keeps its settings, type, filament and placement, and its painting when the keep_painting preference is on. Parts loaded from no file (primitives, the built-in models) are left out; cut objects are refused, since a reload would replace a cut part with its whole file, and so is a call while a gizmo is open. One undo step. Reply: reloaded (parts), missing (with each part's path), unmatched (parts their file holds no part to take for) and unreadable (a file that could not be read, after which nothing more was loaded).", + "destructive": false, + "examples": [ + { + "calls": [ + { + "args": { + "objects": [ + 0 + ] + }, + "tool": "object_reload_from_disk" + } + ], + "title": "Reload an imported object after its file changed" + }, + { + "calls": [ + { + "args": { + "all": true + }, + "tool": "object_reload_from_disk" + } + ], + "title": "Reload every object" + } + ], + "group": "Objects", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "all": { + "description": "Reload every object but the cut ones. Default false: the targets.", + "type": "boolean" + }, + "object_ids": { + "description": "The ids object_list reports for objects, one per entry: refused when an index names another object now.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "objects": { + "description": "Object indices.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "part_ids": { + "description": "The ids object_list reports for the entries of parts, one per entry: refused when a pair names another part now.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "parts": { + "description": "[[object, part], ...]", + "items": { + "type": "array" + }, + "type": "array" + } + }, + "type": "object" + }, + "key": "object_reload_from_disk", + "listed": true, + "open_world": false, + "operations": [ + "reload_parts" + ], + "read_only": false, + "title": "Reload from disk" + }, + { + "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.", + "destructive": false, + "group": "Objects", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "align_y": { + "description": "Align to Y axis (off while rotate is on).", + "type": "boolean" + }, + "fill_object": { + "description": "An object index: instead of arranging, fill that object's plate with more of it.", + "minimum": 0, + "type": "integer" + }, + "fill_with": { + "description": "Default instances.", + "enum": [ + "instances", + "copies" + ], + "type": "string" + }, + "multi_material": { + "description": "Allow multiple materials on same plate.", + "type": "boolean" + }, + "plates": { + "description": "\"all\" (default), \"current\" or a plate index.", + "type": [ + "string", + "integer" + ] + }, + "rotate": { + "description": "Auto rotate for arrangement.", + "type": "boolean" + }, + "spacing": { + "description": "mm between objects; 0 means auto.", + "minimum": 0, + "type": "number" + }, + "timeout_s": { + "description": "Cancel it after this long (default 300).", + "maximum": 1800, + "minimum": 10, + "type": "integer" + } + }, + "type": "object" + }, + "key": "object_arrange", + "listed": true, + "open_world": false, + "operations": [ + "start_arrange" + ], + "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Arrange all objects on the unlocked plates with the saved Arrange options, as the toolbar does; the call waits for the arrangement and replies as object_arrange does: the settings in force, the instances left off every plate and the plates skipped. object_arrange with arguments also takes options, one plate or fill bed.", + "group": "Object", + "icon": "toolbar_arrange", + "key": "obj_arrange", + "title": "Auto-Arrange" + } + ], + "title": "Arrange objects or fill the bed" + }, + { + "completion": "immediate", + "description": "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 the target height_range. A range given with the min_z and max_z of one the object has keeps its settings; a new one starts from the object's layer height and filament. Ranges may touch but not overlap; [] removes them all. The object is the one named, else the one selected in the Prepare view. One undo step; the object is selected. Reply: the object (objects, object), its height and its ranges as object_list shows them, with their settings, and warnings, such as a variable layer height profile deciding the layer heights instead.", + "destructive": false, + "group": "Objects", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "object": { + "description": "Object index (object_list).", + "minimum": 0, + "type": "integer" + }, + "object_id": { + "description": "The id object_list reports for this object: the call is refused when the index names another one now.", + "minimum": 0, + "type": "integer" + }, + "ranges": { + "description": "The object's ranges afterwards, in any order.", + "items": { + "additionalProperties": false, + "properties": { + "max_z": { + "description": "Top, mm above the bed.", + "minimum": 0, + "type": "number" + }, + "min_z": { + "description": "Bottom, mm above the bed.", + "minimum": 0, + "type": "number" + } + }, + "required": [ + "min_z", + "max_z" + ], + "type": "object" + }, + "type": "array" + } + }, + "required": [ + "ranges" + ], + "type": "object" + }, + "key": "object_set_height_ranges", + "listed": true, + "open_world": false, + "operations": [], + "read_only": false, + "title": "Set height range modifiers" + }, + { + "completion": "immediate", + "description": "Run the Variable layer height panel's Adaptive, Smooth or Reset on an object, without opening the panel: adaptive computes layer heights from the object's shape (inside a height range, the range's layer_height), smooth smooths its profile (or the one its height ranges give), reset goes back to its layer height and ranges. The object is the one named, else the one selected in the Prepare view. One undo step; the object is selected. Reply: the object (objects, object), its height, its layer_height_profile {points, min_height, max_height} as object_list shows it (absent after reset), and warnings.", + "destructive": false, + "group": "Objects", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "action": { + "description": "The panel's button.", + "enum": [ + "adaptive", + "smooth", + "reset" + ], + "type": "string" + }, + "keep_min": { + "description": "smooth: keep the minimum layer heights (default false).", + "type": "boolean" + }, + "object": { + "description": "Object index (object_list).", + "minimum": 0, + "type": "integer" + }, + "object_id": { + "description": "The id object_list reports for this object: the call is refused when the index names another one now.", + "minimum": 0, + "type": "integer" + }, + "quality": { + "description": "adaptive: 0 = quality .. 1 = speed (default 0.5, as the panel).", + "maximum": 1, + "minimum": 0, + "type": "number" + }, + "radius": { + "description": "smooth: default 5.", + "maximum": 10, + "minimum": 1, + "type": "integer" + } + }, + "required": [ + "action" + ], + "type": "object" + }, + "key": "object_set_variable_layer_height", + "listed": true, + "open_world": false, + "operations": [], + "read_only": false, + "title": "Set a variable layer height profile" + }, + { + "completion": "immediate", + "description": "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 menu puts it (a shape beside the object, a file at its coordinates relative to the object's first part) unless position is given. Like the menu, adding a shape folds the instance's rotation and scale into the object's parts (the instance's scale then reads 1). Refused for an object with several instances: add parts first. A STEP file may ask for mesh options (blocked_by_dialog). The object is the one named, else the one selected in the Prepare view, or the object of the selected instance or part. The new part is selected; one undo step. Reply: its index, which is not always the last (parts are ordered by type), the object's part count and the part's object_list entry (part_info), and the object (objects).", + "destructive": false, + "group": "Parts", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "object": { + "description": "Object index (object_list).", + "minimum": 0, + "type": "integer" + }, + "object_id": { + "description": "The id object_list reports for this object: the call is refused when the index names another one now.", + "minimum": 0, + "type": "integer" + }, + "path": { + "description": "Instead of shape: absolute path of a model file (STL, OBJ, 3MF, STEP, ...).", + "type": "string" + }, + "position": { + "description": "[x, y, z] mm on the bed for the part's centre, on instance 0, as the Move panel shows it.", + "items": { + "type": "number" + }, + "type": "array" + }, + "shape": { + "description": "A primitive shape.", + "enum": [ + "cube", + "cylinder", + "sphere", + "cone", + "disc", + "torus" + ], + "type": "string" + }, + "size": { + "description": "mm, the Primitive size dialog's fields: cube [x, y, z]; cylinder, cone, disc [diameter, height]; sphere [diameter]; torus [inner diameter, tube diameter]. Default: the built-in size.", + "items": { + "type": "number" + }, + "type": "array" + }, + "type": { + "description": "What the new part is.", + "enum": [ + "part", + "negative", + "modifier", + "support_blocker", + "support_enforcer", + "precise_seam" + ], + "type": "string" + } + }, + "required": [ + "type" + ], + "type": "object" + }, + "key": "part_add", + "listed": true, + "open_world": false, + "operations": [], + "read_only": false, + "title": "Add a part or modifier to an object" + }, + { + "completion": "immediate", + "description": "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 keeps its subtype; subtype, with precise_seam alone, sets the seam's subtype as the Precise Seam Type menu does. Not an object's last solid part; a text or SVG part does not become a support blocker or enforcer or a precise seam; a painted modifier keeps its type. One undo step. Parts are listed by type, so part indices change. Reply: each part with its index afterwards and its type (parts).", + "destructive": false, + "group": "Parts", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "part_ids": { + "description": "The ids object_list reports for the entries of parts, one per entry: refused when a pair names another part now.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "parts": { + "description": "[[object, part], ...]", + "items": { + "type": "array" + }, + "type": "array" + }, + "subtype": { + "description": "With type precise_seam: the seam's subtype, which every part named takes. Default: a seam keeps its own, another part becomes center.", + "enum": [ + "center", + "left", + "right", + "enforced", + "blocked", + "neutral" + ], + "type": "string" + }, + "type": { + "description": "What the parts become.", + "enum": [ + "part", + "negative", + "modifier", + "support_blocker", + "support_enforcer", + "precise_seam" + ], + "type": "string" + } + }, + "required": [ + "type" + ], + "type": "object" + }, + "key": "part_change_type", + "listed": true, + "open_world": false, + "operations": [ + "change_part_type" + ], + "read_only": false, + "tiles": [ + { + "args": { + "type": "part" + }, + "description": "Make the selected parts (object_select {parts} first) solid parts, as Change Type does. Parts are listed by type, so part indices change.", + "group": "Object", + "icon": "", + "key": "obj_type_part", + "title": "Change Type to Part" + }, + { + "args": { + "type": "negative" + }, + "description": "Make the selected parts negative parts, as Change Type does; not the object's last solid part. Parts are listed by type, so part indices change.", + "group": "Object", + "icon": "", + "key": "obj_type_negative", + "title": "Change Type to Negative Part" + }, + { + "args": { + "type": "modifier" + }, + "description": "Make the selected parts modifiers, as Change Type does; not the object's last solid part. Parts are listed by type, so part indices change.", + "group": "Object", + "icon": "", + "key": "obj_type_modifier", + "title": "Change Type to Modifier" + }, + { + "args": { + "type": "support_blocker" + }, + "description": "Make the selected parts support blockers, as Change Type does; not the object's last solid part, nor a text or SVG part. Parts are listed by type, so part indices change.", + "group": "Object", + "icon": "", + "key": "obj_type_support_blocker", + "title": "Change Type to Support Blocker" + }, + { + "args": { + "type": "support_enforcer" + }, + "description": "Make the selected parts support enforcers, as Change Type does; not the object's last solid part, nor a text or SVG part. Parts are listed by type, so part indices change.", + "group": "Object", + "icon": "", + "key": "obj_type_support_enforcer", + "title": "Change Type to Support Enforcer" + }, + { + "args": { + "type": "precise_seam" + }, + "description": "Make the selected parts Center precise seams (seams keep their subtype), as Change Type does; not the object's last solid part, nor a text or SVG part. Parts are listed by type, so part indices change.", + "group": "Object", + "icon": "", + "key": "obj_type_precise_seam", + "title": "Change Type to Precise Seam" + } + ], + "title": "Change a part's type" + }, + { + "completion": "immediate", + "description": "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 and placement, and its painting when the keep_painting preference is on; with it off the painting is copied as it is, which fits the same mesh alone. A file that loads as more than one object or part is refused, as Replace 3D file refuses it. path names the file, so no file dialog opens; the loader may still ask, a STEP file for its mesh options (blocked_by_dialog). Cut objects are refused, and so is a call while a gizmo is open. One undo step. Reply: the part (parts), with its new part_id and its index, which moves when the object's parts are not in type order (the replacement sorts them), and its object_list entry (part_info).", + "destructive": false, + "examples": [ + { + "calls": [ + { + "args": { + "object": 0, + "path": "/models/bracket_v2.stl" + }, + "tool": "part_replace" + } + ], + "title": "Replace an object's only part with a new version of its file" + }, + { + "calls": [ + { + "args": { + "object": 0, + "part": 1, + "path": "/models/modifier.stl" + }, + "tool": "part_replace" + } + ], + "title": "Replace a modifier with a mesh of another shape" + } + ], + "group": "Parts", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "object": { + "description": "Object index (object_list).", + "minimum": 0, + "type": "integer" + }, + "object_id": { + "description": "The id object_list reports for this object: the call is refused when the index names another one now.", + "minimum": 0, + "type": "integer" + }, + "part": { + "description": "A part of the object (object_list).", + "minimum": 0, + "type": "integer" + }, + "part_id": { + "description": "The id object_list reports for this part: the call is refused when the index names another one now.", + "minimum": 0, + "type": "integer" + }, + "path": { + "description": "Absolute path of the model file (STL, OBJ, 3MF, STEP, ...).", + "type": "string" + } + }, + "required": [ + "path" + ], + "type": "object" + }, + "key": "part_replace", + "listed": true, + "open_world": false, + "operations": [ + "replace_part" + ], + "read_only": false, + "title": "Replace 3D file" + }, + { + "completion": "immediate", + "description": "Generate a Calibration menu test as its dialog's OK does: a new project named after the test with the test model, and the process, filament and printer presets changed as the test needs (presets_changed). The test prints with filament slot 1, so the filament tab is pointed at slot 1's preset. Omitted parameters take the dialog's defaults (pressure advance's by the printer's extruder type); temperatures are clamped to 155-500 °C and rounded down to 5 °C. Fails, changing nothing, when the project has unsaved changes (pass discard_changes) or presets do (pass preset_changes). Called with test alone it opens that test's dialog, as the Calibration menu does (blocked_by_dialog), and the dialog's OK runs the test; silent: true with test alone runs it with the dialog's defaults. Reply: test, project, params (the values used, which the journal records), objects, names, plates, presets_changed, result_keys (where the measured value belongs), warnings, adjusted (vfa), and discarded and modified as project_new. Then plate_slice and project_export. To save a measured value: project_new {discard_changes, preset_changes: \"discard\"}, settings_set the value, preset_save.", + "destructive": false, + "group": "Plates", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "if": { + "not": { + "enum": [ + { + "test": "temperature" + }, + { + "test": "max_volumetric" + }, + { + "test": "pressure_advance" + }, + { + "test": "flow_ratio" + }, + { + "test": "retraction" + }, + { + "test": "cornering" + }, + { + "test": "input_shaping_freq" + }, + { + "test": "input_shaping_damp" + }, + { + "test": "vfa" + } + ] + } + }, "properties": { "accelerations": { "description": "pressure_advance pattern: one test per acceleration and speed; default the process's.", @@ -3260,6 +3746,13 @@ "description": "Input shaping: an input_shaping_type the printer's firmware offers; default the first.", "type": "string" }, + "silent": { + "description": "true runs the command without asking; it then needs test, and what else the call leaves out takes its default. A call with exactly a tile's arguments does what a person's pick of that tile does.", + "enum": [ + true + ], + "type": "boolean" + }, "speeds": { "description": "pressure_advance pattern: default an optimal speed.", "items": { @@ -3281,7 +3774,7 @@ "type": "number" }, "test": { - "description": "The test, named as the calib_* actions.", + "description": "The test, as the Calibration menu names it.", "enum": [ "temperature", "max_volumetric", @@ -3315,505 +3808,187 @@ "type": "string" } }, - "required": [ - "test" - ], - "type": "object" - }, - "key": "generate_calibration_test", - "listed": true, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Generate a calibration test" - }, - { - "completion": "immediate", - "description": "Save the project. Called with no arguments, it saves as Save Project does: to the project's file (reply: ran, level), or, when it has none, through a file dialog (blocked_by_dialog; a native picker needs auto_answer_dialogs registered first). With path, it saves a .3mf there without the file dialog, and the file becomes the project's (reply: path, bytes); a name ending in .gcode.3mf is refused (export writes that). Either way the save can still open a dialog (blocked_by_dialog): a warning when settings name a plugin OrcaSlicer cannot identify, or an error when the file cannot be written. A save that writes nothing, its file dialog or that warning cancelled or the write failed, fails with project_not_saved, and a file already there stays as it was.", - "destructive": false, - "group": "Commands", - "guard": "mutate", - "idempotent": false, - "in_palette": true, - "input_schema": { - "additionalProperties": false, - "if": { - "minProperties": 1 - }, - "properties": { - "overwrite": { - "description": "Replace an existing file.", - "type": "boolean" - }, - "path": { - "description": "Absolute .3mf path.", - "type": "string" - }, - "silent": { - "description": "Goes with path, which any argument makes required, and adds nothing to it: a call with path skips the file dialog already.", - "enum": [ - true - ], - "type": "boolean" - } - }, "then": { "required": [ - "path" + "test" ] }, "type": "object" }, - "key": "save_project", + "key": "calibration_generate_test", "listed": true, "open_world": false, - "operations": [ - "save_project_as" - ], + "operations": [], "read_only": false, - "title": "Save Project" - }, - { - "completion": "immediate", - "description": "Write the project to a file without a dialog. gcode: the plate's G-code (slice first; it is written in the background, and the call returns once it is). sliced_3mf: the sliced plate, or all plates, as .gcode.3mf (slice first: a plate that is not sliced is written without G-code). 3mf: the model without slicing data. stl: all objects as one STL. Both hold every plate's objects. Without format, the path's extension (.gcode, .gcode.3mf, .3mf, .stl) says which. Reply: path and bytes; for gcode, path and export (ok, or superseded with a note when the project changed while it was written).", - "destructive": false, - "group": "api", - "guard": "mutate", - "idempotent": false, - "in_palette": false, - "input_schema": { - "additionalProperties": false, - "properties": { - "format": { - "description": "What to write; default from the path's extension.", - "enum": [ - "gcode", - "sliced_3mf", - "3mf", - "stl" - ], - "type": "string" + "tiles": [ + { + "args": { + "test": "temperature" }, - "overwrite": { - "description": "Replace an existing file.", - "type": "boolean" - }, - "path": { - "description": "Absolute output path.", - "type": "string" - }, - "plates": { - "description": "\"current\" (default), a plate index, which is selected first and is the plate gcode and sliced_3mf write, or \"all\" (sliced_3mf only).", - "type": [ - "string", - "integer" - ] - } + "description": "Open the Temperature Calibration dialog; calibration_generate_test with the test's parameters, or silent, runs it with no dialog.", + "group": "Calibration", + "icon": "param_temperature", + "key": "calib_temperature", + "title": "Temperature Calibration" }, - "required": [ - "path" - ], - "type": "object" - }, - "key": "export", - "listed": true, - "open_world": false, - "operations": [ - "start_gcode_export", - "export_sliced_3mf", - "export_model_3mf", - "export_stl" + { + "args": { + "test": "max_volumetric" + }, + "description": "Open the Max Volumetric Speed Calibration dialog; calibration_generate_test with the test's parameters, or silent, runs it with no dialog.", + "group": "Calibration", + "icon": "param_volumetric_speed", + "key": "calib_max_volumetric", + "title": "Max Volumetric Speed Calibration" + }, + { + "args": { + "test": "pressure_advance" + }, + "description": "Open the Pressure Advance Calibration dialog; calibration_generate_test with the test's parameters, or silent, runs it with no dialog.", + "group": "Calibration", + "icon": "param_flow_ratio_and_pressure_advance", + "key": "calib_pressure_advance", + "title": "Pressure Advance Calibration" + }, + { + "args": { + "test": "flow_ratio" + }, + "description": "Open the Flow Ratio Calibration dialog; calibration_generate_test with the test's parameters, or silent, runs it with no dialog.", + "group": "Calibration", + "icon": "param_flow_ratio_and_pressure_advance", + "key": "calib_flow_ratio", + "title": "Flow Ratio Calibration" + }, + { + "args": { + "test": "retraction" + }, + "description": "Open the Retraction Calibration dialog; calibration_generate_test with the test's parameters, or silent, runs it with no dialog.", + "group": "Calibration", + "icon": "param_retraction", + "key": "calib_retraction", + "title": "Retraction Calibration" + }, + { + "args": { + "test": "cornering" + }, + "description": "Open the Cornering Calibration dialog; calibration_generate_test with the test's parameters, or silent, runs it with no dialog.", + "group": "Calibration", + "icon": "param_precision", + "key": "calib_cornering", + "title": "Cornering Calibration" + }, + { + "args": { + "test": "input_shaping_freq" + }, + "description": "Open the Input Shaping Frequency Calibration dialog; calibration_generate_test with the test's parameters, or silent, runs it with no dialog.", + "group": "Calibration", + "icon": "param_resonance_avoidance", + "key": "calib_input_shaping_freq", + "title": "Input Shaping Frequency Calibration" + }, + { + "args": { + "test": "input_shaping_damp" + }, + "description": "Open the Input Shaping Damping Calibration dialog; calibration_generate_test with the test's parameters, or silent, runs it with no dialog.", + "group": "Calibration", + "icon": "param_resonance_avoidance", + "key": "calib_input_shaping_damp", + "title": "Input Shaping Damping Calibration" + }, + { + "args": { + "test": "vfa" + }, + "description": "Open the VFA Calibration dialog; calibration_generate_test with the test's parameters, or silent, runs it with no dialog.", + "group": "Calibration", + "icon": "param_speed", + "key": "calib_vfa", + "title": "VFA Calibration" + } ], - "read_only": false, - "title": "Export" + "title": "Generate a calibration test" }, { "completion": "immediate", - "description": "Printer, process or filament presets, each with its name, alias (the name its selector shows, when another), system, user, project (kept inside the project), inherits, selected (and modified), compatible: false or visible: false when so, and for a filament the slots using it (filament_slots). Only compatible, visible presets unless asked: a fresh install hides most system filaments and printers, and select_preset takes a hidden one too.", + "description": "Read a plate's own settings, as the Plate Settings dialog sets them: curr_bed_type, print_sequence, spiral_mode, first_layer_print_sequence and other_layers_print_sequence; and as its filament grouping sets them on a printer with several extruders: filament_map_mode and filament_map (the extruder of each filament, 1-based). Each with value (the plate's own, null where it follows the global setting or Auto), effective (what the plate prints with) and meta (meta.offered lists the plate types or grouping modes this printer has). All of them, or those named in keys. Reply: plate, items; unknown_keys for the keys a plate does not have.", "destructive": false, - "group": "api", + "group": "Plates", "guard": "inspect", "idempotent": true, "in_palette": false, "input_schema": { "additionalProperties": false, "properties": { - "include_hidden": { - "description": "Also list hidden presets.", - "type": "boolean" - }, - "include_incompatible": { - "description": "Also list presets incompatible with the printer.", - "type": "boolean" - }, - "limit": { - "description": "Default 100.", - "maximum": 500, - "minimum": 1, - "type": "integer" - }, - "offset": { - "minimum": 0, - "type": "integer" - }, - "query": { - "description": "Case-insensitive part of the name or alias.", - "type": "string" - }, - "type": { - "description": "Preset category.", - "enum": [ - "printer", - "process", - "filament" - ], - "type": "string" - } - }, - "required": [ - "type" - ], - "type": "object" - }, - "key": "list_presets", - "listed": true, - "open_world": false, - "operations": [], - "read_only": true, - "title": "List presets" - }, - { - "completion": "immediate", - "description": "Select a printer, process or filament preset by the name its selector shows (or its internal name), as a person would. A hidden one (list_presets include_hidden) is shown in the selectors first, until the app restarts; one the selector leaves out as incompatible with the printer is refused. With unsaved changes the Transfer-or-discard prompt opens (blocked_by_dialog) unless preset_changes answers it. A filament is assigned to filament_slot (1-based, default 1); with several slots the filament tab keeps the preset and the changes it has, so nothing is asked. Reply: selected, shown (a hidden preset it showed); when presets had or have unsaved changes, discarded and modified list per preset the keys dropped and the keys still unsaved.", - "destructive": false, - "group": "api", - "guard": "mutate", - "idempotent": false, - "in_palette": false, - "input_schema": { - "additionalProperties": false, - "properties": { - "filament_slot": { - "description": "Filament slot, 1-based.", - "minimum": 1, - "type": "integer" - }, - "name": { - "description": "Preset name as list_presets shows it.", - "type": "string" - }, - "preset_changes": { - "description": "Unsaved changes of the presets the switch replaces: move them to the new preset or drop them, as the prompt's buttons do; transfer is refused where the prompt does not offer it (a printer's changes, a filament of another type). Omitted: the prompt opens.", - "enum": [ - "transfer", - "discard" - ], - "type": "string" - }, - "type": { - "description": "Preset category.", - "enum": [ - "printer", - "process", - "filament" - ], - "type": "string" - } - }, - "required": [ - "type", - "name" - ], - "type": "object" - }, - "key": "select_preset", - "listed": true, - "open_world": false, - "operations": [ - "resolve_preset", - "select_preset", - "assign_filament_preset" - ], - "read_only": false, - "title": "Select a preset" - }, - { - "completion": "immediate", - "description": "Save the printer, process or filament preset being edited, with its unsaved changes, as a preset called name, which is then selected: what the tab's Save button does through its dialog. A filament is filament_slot's (default 1), and every slot using the old preset takes the new one. Replacing another existing preset needs overwrite (pass it in replays and scripts meant to be rerun). Reply: saved, selected, user, project, inherits, filament_slots. A temperature warning or an unsaved-changes prompt makes it blocked_by_dialog. To keep only some edits, set_settings {reset_all: true, values} first.", - "destructive": false, - "group": "api", - "guard": "mutate", - "idempotent": false, - "in_palette": false, - "input_schema": { - "additionalProperties": false, - "properties": { - "detach": { - "description": "Copy inherited values and drop the parent (Developer mode).", - "type": "boolean" - }, - "filament_slot": { - "description": "Filament slot, 1-based.", - "minimum": 1, - "type": "integer" - }, - "inside_project": { - "description": "Keep it inside the project, not as a user preset. Default: where the edited preset is. A preset of that name stays where it is.", - "type": "boolean" - }, - "name": { - "description": "Name to save under.", - "type": "string" - }, - "overwrite": { - "description": "Replace another preset of that name.", - "type": "boolean" - }, - "type": { - "description": "Preset category.", - "enum": [ - "printer", - "process", - "filament" - ], - "type": "string" - } - }, - "required": [ - "type", - "name" - ], - "type": "object" - }, - "key": "save_preset", - "listed": true, - "open_world": true, - "operations": [], - "read_only": false, - "title": "Save a preset" - }, - { - "completion": "immediate", - "description": "Delete a user preset or one inside the project, its file and its cloud copy, as the tab's Delete does, without asking. A selected preset is replaced as the tab does (its parent or the next preset). Another filament is deleted without changing the selection, and slots using it take the selected one; another process is selected, deleted and the selection restored; a printer must be selected first, and the physical printers that use only it are deleted with it. Refused: system, default and bundle presets, presets others inherit from, another preset while the edited one of its type has unsaved changes. Deleting a selected printer or process can ask about other presets' unsaved changes (blocked_by_dialog). Reply: deleted, selected, filaments (per slot), attached, and discarded/modified as select_preset's.", - "destructive": true, - "group": "api", - "guard": "mutate", - "idempotent": false, - "in_palette": false, - "input_schema": { - "additionalProperties": false, - "properties": { - "delete_attached": { - "description": "A custom printer with process or filament presets made for it alone is refused without this: they are deleted with it, as the GUI deletes them.", - "type": "boolean" - }, - "name": { - "description": "Preset name as list_presets shows it.", - "type": "string" - }, - "type": { - "description": "Preset category.", - "enum": [ - "printer", - "process", - "filament" - ], - "type": "string" - } - }, - "required": [ - "type", - "name" - ], - "type": "object" - }, - "key": "delete_preset", - "listed": true, - "open_world": true, - "operations": [], - "read_only": false, - "title": "Delete a preset" - }, - { - "completion": "immediate", - "description": "Read settings: 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, range, allowed values and mode. Choose them by keys; by query, a few words matched in keys, labels and descriptions, best matches first; by where, a page or \"Page > Group\" (an unknown one is refused with the list of them); or by none of these, for the whole scope, paged and, in a preset scope, without meta. Keys the scope lacks are listed in unknown_keys, and scope_of gives the scope of those another scope has.\n- No scope: keys and query look through the process, filament and printer settings, and each item names its scope, the one set_settings takes; anything else reads the process.\n- process, filament, printer: the preset being edited, or with preset a saved one; compare lists only the keys that differ from another preset (value and other). A per-variant value lists in meta its variants (what each entry is for) and active (the entry each extruder prints with).\n- object, part: listed whole, the overrides that object or part carries; keys, query and where read any process setting there. Each has effective (the value it prints with) and source (part, object, process or default); an object's item lists in parts the parts and modifiers that override the key inside their own volume.\n- project: the plate type, slot colours, flushing volumes, purge mode, prime tower position per plate, mixed slots and, with several extruders, the filament grouping; meta.offered lists the choices this printer has.\n- plate: a plate's curr_bed_type, print_sequence, spiral_mode, first_layer_print_sequence, other_layers_print_sequence, name and locked, each with value (the plate's own, null where it follows the global setting or Auto) and effective.\n- preferences: the named keys of the app configuration (the Preferences dialog's settings, keys as its controls are named), as stored; it lists none unasked.", - "destructive": false, - "group": "api", - "guard": "inspect", - "idempotent": true, - "in_palette": false, - "input_schema": { - "additionalProperties": false, - "properties": { - "compare": { - "description": "Preset scopes: a preset name, \":saved\" (the unsaved changes) or \":parent\" (the preset it inherits from).", - "type": "string" - }, - "filament_slot": { - "description": "Filament scope: the slot whose preset is read, 1-based (default 1), with its unsaved changes when the filament tab is editing it.", - "minimum": 1, - "type": "integer" - }, "include_meta": { - "description": "Include labels, types and ranges. Default true, false for a preset scope's whole listing and with compare.", + "description": "Include labels, types and ranges. Default true.", "type": "boolean" }, "keys": { - "description": "Option keys, e.g. [\"layer_height\", \"wall_loops\"].", + "description": "Setting keys, e.g. [\"curr_bed_type\"].", "items": { "type": "string" }, "type": "array" }, - "limit": { - "description": "Default 100, or 20 with query.", - "maximum": 500, - "minimum": 1, - "type": "integer" - }, - "object": { - "description": "Object index (object/part scope).", - "minimum": 0, - "type": "integer" - }, - "offset": { - "minimum": 0, - "type": "integer" - }, - "part": { - "description": "Part index (part scope).", - "minimum": 0, - "type": "integer" - }, "plate": { - "description": "Plate index (plate scope; default: the current plate).", + "description": "Plate index; default: the current plate.", "minimum": 0, "type": "integer" - }, - "preset": { - "description": "Preset scopes: read this saved preset (a name from list_presets) instead of the one being edited.", - "type": "string" - }, - "query": { - "description": "A few distinctive words, e.g. \"stringing\" or \"ooze travel\"; the best 20 matches unless limit says otherwise.", - "type": "string" - }, - "scope": { - "description": "Which settings: the process, filament or printer preset being edited, an object's / part's own overrides, the project's own settings, a plate's, or the app's preferences (read only). Without it, keys and query look through the process, filament and printer settings; anything else reads the process.", - "enum": [ - "process", - "filament", - "printer", - "object", - "part", - "project", - "plate", - "preferences" - ], - "type": "string" - }, - "where": { - "description": "A settings page, or \"Page > Group\" as meta.where gives it, e.g. \"Strength > Walls\".", - "type": "string" } }, "type": "object" }, - "key": "get_settings", + "key": "plate_get_settings", "listed": true, "open_world": false, "operations": [], "read_only": true, - "title": "Read settings" + "title": "Read a plate's settings" }, { "completion": "immediate", - "description": "Change settings of one scope (default the process) as typing them into its settings tab would. Values are strings in OrcaSlicer's format (\"15%\", \"0.2\", \"1,2\") or JSON numbers, booleans and arrays (a point as [x, y]). All are parsed strictly first and applied together, so nothing changes if one is invalid, and a key of another scope is refused with that scope named. Reply: applied, and changed, every setting the call changed, including those the app adjusted in turn. An object's, part's or plate's change is one undo step; a preset's is not in the undo history. Spiral vase and a few others confirm their adjustments in a dialog (blocked_by_dialog).\n- process, filament, printer: null takes a key back to its saved value, or with reset_to parent to the parent's; reset_all first discards every unsaved change, as the tab's undo button does (reply: reverted). A per-variant value (get_settings meta.variants) takes one value for the entries in use (meta.active), {index, value} for one entry, or an array of all.\n- object, part: overrides of the keys the object list offers there; null removes one. extruder is the object's or part's filament (1-based; 0 or null for Default), set as the Change Filament menu does.\n- project, as the sidebar's controls write them: curr_bed_type, filament_colour (#RRGGBB per slot), flush_multiplier, flush_volumes_matrix, prime_volume_mode, and wipe_tower_x/y (mm from the plate's origin, one per plate). flush_volumes_matrix is per nozzle, slots x slots from row to column, in config order over every slot, before the multiplier; a mixed slot's entries must be given as they are, and a colour change can recalculate it, so set it last.\n- plate, which it selects and writes as the Plate Settings dialog's OK does: curr_bed_type, print_sequence (\"by layer\", \"by object\"), spiral_mode (true asks for confirmation), first_layer_print_sequence (every slot once, e.g. [2, 1]), other_layers_print_sequence ([{from: layer >= 2, to, order}], to omitted for the last layer), name and locked; null returns a value to the global setting or Auto.", + "description": "Change a plate's own settings, which it selects and writes as the Plate Settings dialog's OK does: curr_bed_type, print_sequence (\"by layer\", \"by object\"), spiral_mode (true asks for confirmation), first_layer_print_sequence (every slot once, e.g. [2, 1]) and other_layers_print_sequence ([{from: layer >= 2, to, order}], to omitted for the last layer); and as the OK of its filament grouping does, with several extruders: filament_map_mode (an offered mode) and, with \"Manual\", filament_map (one extruder per filament, e.g. [1, 2, 2]; on a printer whose extruder holds several nozzles, refused as the dialog refuses it where an extruder it uses has no nozzle of the volume type its filaments print with). null returns a value to the global setting or Auto. Values are checked before anything changes, and the call is one undo step. Reply: plate, applied, changed, and effective for the settings the plate prints with.", "destructive": false, - "group": "api", + "group": "Plates", "guard": "mutate", "idempotent": false, "in_palette": false, "input_schema": { "additionalProperties": false, "properties": { - "filament_slot": { - "description": "Filament scope: the slot whose preset is changed, 1-based (default 1). The filament tab switches to it, which can ask about the unsaved changes it holds (blocked_by_dialog).", - "minimum": 1, - "type": "integer" - }, - "object": { - "description": "Object index (object/part scope).", - "minimum": 0, - "type": "integer" - }, - "object_id": { - "description": "The id list_objects reports for this object: the call is refused when the index names another one now.", - "minimum": 0, - "type": "integer" - }, - "part": { - "description": "Part index (part scope).", - "minimum": 0, - "type": "integer" - }, - "part_id": { - "description": "The id list_objects reports for this part: the call is refused when the index names another one now.", - "minimum": 0, - "type": "integer" - }, "plate": { - "description": "Plate index (plate scope; default: the current plate).", + "description": "Plate index; default: the current plate.", "minimum": 0, "type": "integer" }, - "reset_all": { - "description": "Preset scopes: discard the unsaved changes before applying values.", - "type": "boolean" - }, - "reset_to": { - "description": "Preset scopes: what a null value takes a key back to: the saved preset (default) or the preset it inherits from.", - "enum": [ - "saved", - "parent" - ], - "type": "string" - }, - "scope": { - "description": "Which settings: the process, filament or printer preset being edited, an object's / part's own overrides, the project's own settings, a plate's, or the app's preferences (read only). Default: the process.", - "enum": [ - "process", - "filament", - "printer", - "object", - "part", - "project", - "plate", - "preferences" - ], - "type": "string" - }, "values": { - "description": "{key: value}, or {key: {index, value}} for one entry", + "description": "{key: value}", "type": "object" } }, + "required": [ + "values" + ], "type": "object" }, - "key": "set_settings", + "key": "plate_set_settings", "listed": true, "open_world": false, - "operations": [ - "set_plate_locked" - ], + "operations": [], "read_only": false, - "title": "Change settings" + "title": "Change a plate's settings" }, { "completion": "immediate", - "description": "Plates with name, locked, current, objects (how many are on it; list_objects lists them), and the settings they print with: curr_bed_type, print_sequence, spiral_mode, first_layer_print_sequence and other_layers_print_sequence (null: Auto); overrides lists those the plate sets itself (set_settings scope plate). Also sliced (an up-to-date slice), wipe_tower [x, y] and layer_gcode: the plate's pauses, custom G-code, templates and filament changes, each {z, layer, type, filament, color, gcode}; layer is the Preview slider's number, given while the plate's slice is up to date.", + "description": "Plates with name, locked, current, objects (how many are on it; object_list lists them), and the settings they print with: curr_bed_type, print_sequence, spiral_mode, first_layer_print_sequence and other_layers_print_sequence (null: Auto), with several extruders filament_map_mode and filament_map; overrides lists those the plate sets itself (plate_set_settings). Also origin and size, the plate's place on the bed in mm: the [x, y] of its front left corner and its [width, depth], in the bed coordinates object positions are given in, so that origin plus half the size is its middle; sliced (an up-to-date slice), wipe_tower [x, y] and layer_gcode: the plate's pauses, custom G-code, templates and filament changes, each {z, layer, type, filament, color, gcode}; layer is the Preview slider's number, given while the plate's slice is up to date.", "destructive": false, - "group": "api", + "group": "Plates", "guard": "inspect", "idempotent": true, "in_palette": false, @@ -3833,7 +4008,7 @@ }, "type": "object" }, - "key": "list_plates", + "key": "plate_list", "listed": true, "open_world": false, "operations": [], @@ -3842,371 +4017,223 @@ }, { "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; outside: the objects with an instance on no plate. An object with instances on two plates is listed under both, each time with that plate's instances. An object has its filament, auto_drop, bounding box (instance 0), brim ear count and overrides, the keys of the settings it overrides (get_settings scope object reads them); its instances (offset, rotation in degrees, scale, mirrored, bbox); its parts, one or more: parts, negative parts, modifiers, support blockers and enforcers and precise seams (type, with 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 in mm3 on the bed, measured on instance 0; rotation_deg and scale in the object's frame; mirrored; triangle count; mesh_volume, the unscaled mesh's mm3; painted facets: supports and seam enforcers/blockers, fuzzy_skin, mmu per filament, texture per layer; a text part's text and font, an SVG part's file); its height range modifiers when it has any (layer_config_ranges: [{min_z, max_z, values}], as set_height_ranges takes them) and its variable layer height profile when it has one (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: they are what select_objects, transform, mouse_gesture targets and the object/part settings scopes take. Each object and part also has an id, which stays with it when a delete, split or assemble shifts the indices: pass it as object_id / part_id to transform, add_part, set_settings, set_height_ranges and set_variable_layer_height (object_ids, part_ids and instance_object_ids to select_objects), and a call whose index names another one now is refused instead of acting on it. limit and offset page the objects and total counts them, each once.", + "description": "Add a plate.", "destructive": false, - "group": "api", - "guard": "inspect", - "idempotent": true, - "in_palette": false, + "group": "Plates", + "guard": "mutate", + "icon": "toolbar_add_plate", + "idempotent": false, + "in_palette": true, + "input_schema": { + "additionalProperties": false, + "properties": {}, + "type": "object" + }, + "key": "plate_add", + "listed": true, + "open_world": false, + "operations": [], + "read_only": false, + "tile_group": "Plate", + "title": "Add Plate" + }, + { + "completion": "immediate", + "description": "Delete a plate (plate, else the current one), as Delete Plate does. The objects on it stay in the project, outside the plates, and the plates after it move down one. The only plate is refused. One undo step. Reply: plate (the index it had), plates (each plate afterwards: index, name and objects, how many stand on it) and current (the current plate).", + "destructive": false, + "group": "Plates", + "guard": "mutate", + "icon": "delete", + "idempotent": false, + "in_palette": true, "input_schema": { "additionalProperties": false, "properties": { - "limit": { - "description": "Objects, default 200.", - "maximum": 500, - "minimum": 1, - "type": "integer" - }, - "offset": { - "minimum": 0, - "type": "integer" - }, "plate": { - "description": "List this plate alone, without outside.", + "description": "Plate index; default: the current plate.", "minimum": 0, "type": "integer" - }, - "screen": { - "description": "Add each instance's rectangle in the shown 3D view, logical pixels [x, y, w, h].", - "type": "boolean" - } - }, - "type": "object" - }, - "key": "list_objects", - "listed": true, - "open_world": false, - "operations": [], - "read_only": true, - "title": "List objects" - }, - { - "completion": "immediate", - "description": "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 / none select everything or nothing, whatever else is given. The reply is the selection as get_app_state.selection gives it.", - "destructive": false, - "group": "ui", - "guard": "mutate", - "idempotent": false, - "in_palette": false, - "input_schema": { - "additionalProperties": false, - "properties": { - "add": { - "description": "Add to the selection instead of replacing it.", - "type": "boolean" - }, - "all": { - "description": "Select all objects.", - "type": "boolean" - }, - "instance_object_ids": { - "description": "The ids list_objects reports for the objects of instances, one per entry: refused when a pair names another object now.", - "items": { - "type": "integer" - }, - "type": "array" - }, - "instances": { - "description": "[[object, instance], ...]", - "items": { - "type": "array" - }, - "type": "array" - }, - "none": { - "description": "Clear the selection.", - "type": "boolean" - }, - "object_ids": { - "description": "The ids list_objects reports for objects, one per entry: refused when an index names another object now.", - "items": { - "type": "integer" - }, - "type": "array" - }, - "objects": { - "description": "Object indices.", - "items": { - "type": "integer" - }, - "type": "array" - }, - "part_ids": { - "description": "The ids list_objects reports for the entries of parts, one per entry: refused when a pair names another part now.", - "items": { - "type": "integer" - }, - "type": "array" - }, - "parts": { - "description": "[[object, part], ...]", - "items": { - "type": "array" - }, - "type": "array" - } - }, - "type": "object" - }, - "key": "select_objects", - "listed": true, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Select objects" - }, - { - "completion": "immediate", - "description": "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, scale a factor (one number or [x, y, z]), size [x, y, z] mm along the object's or part's own axes, plate moves the instance onto that plate at the same place. mode \"relative\" (default) adds to the current placement (a scale multiplies it), \"absolute\" sets it. An instance is dropped back onto the bed, unless its object's auto_drop is off; drop_to_bed false lets it sink into the bed, but an object of one part left above the bed still drops. A part moves as the Object manipulation panel moves it: translate and rotate along the bed's axes, measured on instance 0, scale and size along its own axes; every instance shows the change, and Auto Drop may lower the object afterwards. One undo step. Reply: the instance's offset, scale and plate, or the part's size along its own axes and its list_objects entry (part_info).", - "destructive": false, - "group": "api", - "guard": "mutate", - "idempotent": false, - "in_palette": false, - "input_schema": { - "additionalProperties": false, - "properties": { - "drop_to_bed": { - "description": "Default true; instances only.", - "type": "boolean" - }, - "instance": { - "description": "Default 0.", - "minimum": 0, - "type": "integer" - }, - "mode": { - "description": "Default relative.", - "enum": [ - "relative", - "absolute" - ], - "type": "string" - }, - "object": { - "description": "Object index (list_objects).", - "minimum": 0, - "type": "integer" - }, - "object_id": { - "description": "The id list_objects reports for this object: the call is refused when the index names another one now.", - "minimum": 0, - "type": "integer" - }, - "part": { - "description": "Transform this part instead of the instance.", - "minimum": 0, - "type": "integer" - }, - "part_id": { - "description": "The id list_objects reports for this part: the call is refused when the index names another one now.", - "minimum": 0, - "type": "integer" - }, - "plate": { - "description": "Move the instance to this plate.", - "minimum": 0, - "type": "integer" - }, - "position": { - "description": "[x, y, z] mm: the position to move to. Not with translate.", - "items": { - "type": "number" - }, - "type": "array" - }, - "rotate": { - "description": "[x, y, z] degrees; relative only for a part", - "items": { - "type": "number" - }, - "type": "array" - }, - "scale": { - "description": "Factor or [x, y, z] factors.", - "type": [ - "number", - "array" - ] - }, - "size": { - "description": "[x, y, z] mm, null keeps an axis; one number and two nulls keep the proportions. Not with scale.", - "items": { - "type": [ - "number", - "null" - ] - }, - "type": "array" - }, - "translate": { - "description": "[x, y, z] mm", - "items": { - "type": "number" - }, - "type": "array" - } - }, - "required": [ - "object" - ], - "type": "object" - }, - "key": "transform", - "listed": true, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Move, rotate or scale an instance or a part" - }, - { - "completion": "immediate", - "description": "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 menu puts it (a shape beside the object, a file at its coordinates relative to the object's first part) unless position is given. Like the menu, adding a shape folds the instance's rotation and scale into the object's parts (the instance's scale then reads 1). Refused for an object with several instances: add parts first. A STEP file may ask for mesh options (blocked_by_dialog). The new part is selected; one undo step. Reply: its index, which is not always the last (parts are ordered by type), the object's part count and the part's list_objects entry (part_info).", - "destructive": false, - "group": "api", - "guard": "mutate", - "idempotent": false, - "in_palette": false, - "input_schema": { - "additionalProperties": false, - "properties": { - "object": { - "description": "Object index (list_objects).", - "minimum": 0, - "type": "integer" - }, - "object_id": { - "description": "The id list_objects reports for this object: the call is refused when the index names another one now.", - "minimum": 0, - "type": "integer" - }, - "path": { - "description": "Instead of shape: absolute path of a model file (STL, OBJ, 3MF, STEP, ...).", - "type": "string" - }, - "position": { - "description": "[x, y, z] mm on the bed for the part's centre, on instance 0, as the Move panel shows it.", - "items": { - "type": "number" - }, - "type": "array" - }, - "shape": { - "description": "A primitive shape.", - "enum": [ - "cube", - "cylinder", - "sphere", - "cone", - "disc", - "torus" - ], - "type": "string" - }, - "size": { - "description": "mm, the Primitive size dialog's fields: cube [x, y, z]; cylinder, cone, disc [diameter, height]; sphere [diameter]; torus [inner diameter, tube diameter]. Default: the built-in size.", - "items": { - "type": "number" - }, - "type": "array" - }, - "type": { - "description": "What the new part is.", - "enum": [ - "part", - "negative", - "modifier", - "support_blocker", - "support_enforcer", - "precise_seam" - ], - "type": "string" - } - }, - "required": [ - "object", - "type" - ], - "type": "object" - }, - "key": "add_part", - "listed": true, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Add a part or modifier to an object" - }, - { - "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 list_objects again. One undo step.", - "destructive": false, - "group": "api", - "guard": "mutate", - "idempotent": false, - "in_palette": false, - "input_schema": { - "additionalProperties": false, - "properties": { - "align_y": { - "description": "Align to Y axis (off while rotate is on).", - "type": "boolean" - }, - "fill_object": { - "description": "An object index: instead of arranging, fill that object's plate with more of it.", - "minimum": 0, - "type": "integer" - }, - "fill_with": { - "description": "Default instances.", - "enum": [ - "instances", - "copies" - ], - "type": "string" - }, - "multi_material": { - "description": "Allow multiple materials on same plate.", - "type": "boolean" - }, - "plates": { - "description": "\"all\" (default), \"current\" or a plate index.", - "type": [ - "string", - "integer" - ] - }, - "rotate": { - "description": "Auto rotate for arrangement.", - "type": "boolean" - }, - "spacing": { - "description": "mm between objects; 0 means auto.", - "minimum": 0, - "type": "number" - }, - "timeout_s": { - "description": "Cancel it after this long (default 300).", - "maximum": 1800, - "minimum": 10, - "type": "integer" } }, "type": "object" }, - "key": "arrange", + "key": "plate_delete", "listed": true, "open_world": false, "operations": [ - "start_arrange" + "delete_plate" ], "read_only": false, - "title": "Arrange objects or fill the bed" + "tile_group": "Plate", + "title": "Delete Plate" }, { "completion": "immediate", - "description": "Slice the current plate, all plates, or one plate by index, the way the toolbar's Slice button does, and wait for the result (or reply with a job id when it takes longer than the reply budget). Each requested plate reports ok, error, cancelled, empty or skipped; the whole operation is superseded when someone else started a slice or edited the project while it ran. An ok plate has time_s (silent_time_s when the printer estimates it), filament_m and filament_g including flush, filament_cost, layers, max_z, filament_changes, and filaments[i] for slot i+1 with m, g and the grams of model_g, support_g, flush_g and tower_g. Other changes are refused until it finishes; cancel_job stops it.", + "description": "Add a plate with a copy of each object on the plate (plate, else the current one), placed on it as on that plate, as Duplicate Current Plate does. The new plate comes last, and the current plate stays current. Refused when the project holds as many plates as it can, and while slicing. One undo step. Reply: plate (the plate copied), new_plate (the new plate's index), plates (each plate afterwards: index, name and objects, how many stand on it) and current (the current plate).", "destructive": false, - "group": "api", + "group": "Plates", + "guard": "mutate", + "icon": "menu_copy", + "idempotent": false, + "in_palette": true, + "input_schema": { + "additionalProperties": false, + "properties": { + "plate": { + "description": "Plate index; default: the current plate.", + "minimum": 0, + "type": "integer" + } + }, + "type": "object" + }, + "key": "plate_duplicate", + "listed": true, + "open_world": false, + "operations": [ + "duplicate_plate" + ], + "read_only": false, + "tile_group": "Plate", + "title": "Duplicate Plate" + }, + { + "completion": "immediate", + "description": "Name a plate (plate, else the current one), as its name icon does: a plate other than the current one is made current first. name \"\" leaves it unnamed. With no arguments, as its tile, the name dialog asks for the current plate's name (blocked_by_dialog), and a cancelled dialog renames nothing, which the call is told. The name is one undo step; the name the plate has already changes nothing, the current plate included. Reply: plate and name.", + "destructive": false, + "group": "Plates", + "guard": "mutate", + "icon": "plate_name_edit", + "idempotent": false, + "in_palette": true, + "input_schema": { + "additionalProperties": false, + "if": { + "minProperties": 1 + }, + "properties": { + "name": { + "description": "The plate's name, in place of the name dialog.", + "type": "string" + }, + "plate": { + "description": "Plate index; default: the current plate.", + "minimum": 0, + "type": "integer" + }, + "silent": { + "description": "true runs the command without asking; it then needs name, and what else the call leaves out takes its default. A call with no arguments does what a person's pick does.", + "enum": [ + true + ], + "type": "boolean" + } + }, + "then": { + "required": [ + "name" + ] + }, + "type": "object" + }, + "key": "plate_rename", + "listed": true, + "open_world": false, + "operations": [ + "rename_plate", + "select_plate" + ], + "read_only": false, + "tile_group": "Plate", + "title": "Rename Plate" + }, + { + "completion": "immediate", + "description": "Lock or unlock a plate (plate, else the current one), as its lock icon does: locked true locks it and false unlocks it; without locked it toggles, as its tile does. An arrange of every plate leaves a locked one as it is. One undo step, none when the plate is in that state already. Reply: plate, locked, and changed (false when it was so already).", + "destructive": false, + "group": "Plates", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "locked": { + "description": "true locks the plate, false unlocks it. Default: the other state.", + "type": "boolean" + }, + "plate": { + "description": "Plate index; default: the current plate.", + "minimum": 0, + "type": "integer" + } + }, + "type": "object" + }, + "key": "plate_lock", + "listed": true, + "open_world": false, + "operations": [ + "set_plate_locked" + ], + "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Lock or unlock the current plate.", + "group": "Plate", + "icon": "lock_normal", + "key": "plate_toggle_lock", + "title": "Toggle Plate Lock" + } + ], + "title": "Toggle Plate Lock" + }, + { + "completion": "immediate", + "description": "Make a plate the current one, as a click on it does: plate; without it, the current plate stays current. An index the project lacks is an error. Reply: plate.", + "destructive": false, + "group": "Plates", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "plate": { + "description": "Plate index; default: the current plate.", + "minimum": 0, + "type": "integer" + } + }, + "type": "object" + }, + "key": "plate_select", + "listed": true, + "open_world": false, + "operations": [ + "select_plate" + ], + "read_only": false, + "tiles": [ + { + "args": { + "plate": 0 + }, + "description": "Make the first plate the current one.", + "group": "Plate", + "icon": "go_next_plate", + "key": "plate_goto", + "title": "Go to Plate" + } + ], + "title": "Go to Plate" + }, + { + "completion": "immediate", + "description": "Slice the current plate, all plates, or one plate by index, the way the toolbar's Slice button does, and wait for the result (or reply with a job id when it takes longer than the reply budget). Each requested plate reports ok, error, cancelled, empty or skipped; the whole operation is superseded when someone else started a slice or edited the project while it ran. An ok plate has time_s (silent_time_s when the printer estimates it), filament_m and filament_g including flush, filament_cost, layers, max_z, filament_changes, and filaments[i] for slot i+1 with m, g and the grams of model_g, support_g, flush_g and tower_g. Other changes are refused until it finishes; job_cancel stops it. The Preview tab shows the result, as after the Slice button; preview: true, alone or with plates \"all\", is the call of Slice and Preview or Slice All Plates, whose pick starts the slice as a job and shows its result as a notification.", + "destructive": false, + "group": "Plates", "guard": "mutate", "idempotent": false, "in_palette": false, @@ -4220,8 +4247,12 @@ "integer" ] }, + "preview": { + "description": "Show the Preview tab, as every slice does: the argument of the Slice and Preview and Slice All Plates tiles.", + "type": "boolean" + }, "timeout_s": { - "description": "Stop waiting after this long (default 1800): the call fails, and the slice goes on unless cancel_job stops it.", + "description": "Stop waiting after this long (default 1800): the call fails, and the slice goes on unless job_cancel stops it.", "maximum": 7200, "minimum": 10, "type": "integer" @@ -4229,168 +4260,43 @@ }, "type": "object" }, - "key": "slice", + "key": "plate_slice", "listed": true, "open_world": false, "operations": [ "start_slice" ], "read_only": false, + "tiles": [ + { + "args": { + "preview": true + }, + "description": "Slice the current plate and show the Preview tab; the call waits for the result, and a pick starts the slice as a job.", + "group": "Slice & Export", + "icon": "media_play", + "key": "slice_and_preview", + "title": "Slice and Preview" + }, + { + "args": { + "plates": "all", + "preview": true + }, + "description": "Slice every plate and show the Preview tab; the call waits for the results, and a pick starts the slice as a job.", + "group": "Slice & Export", + "icon": "media_play", + "key": "slice_all", + "title": "Slice All Plates" + } + ], "title": "Slice" }, { "completion": "immediate", - "description": "Stop the running operation: a slice or G-code export, as the slicing progress's cancel button does, or a background job an MCP call started (an arrange, orient or fill bed). Its job then reports cancelled; a background job keeps other changes out until it has really stopped. With job, only that job is stopped: the running operation, a run_script run or an encode_recording. Allowed while an operation holds the project. Reply: was_running, and job when one was stopped.", + "description": "Add or remove pauses, custom G-code, custom templates and filament changes at the start of a layer, as the Preview layer slider's menu does; they are saved per plate in the project. They go on the plate's sliced layers, so the plate needs an up-to-date slice, or must be the one the Preview still shows after an earlier edit; the call selects it and shows the Preview. Applies clear, then remove, then add, all checked first. One code per layer: adding where a code of the same type is replaces it, and where another type is, is refused (remove it first). Not undoable, as in the slider. A change invalidates the plate's slice: slice again before exporting. Reply: the plate's codes as plate_list's layer_gcode lists them, each with z and layer.", "destructive": false, - "group": "core", - "guard": "recover", - "idempotent": false, - "in_palette": false, - "input_schema": { - "additionalProperties": false, - "properties": { - "job": { - "description": "The operation's job to cancel, e.g. \"j12\".", - "type": "string" - } - }, - "type": "object" - }, - "key": "cancel_job", - "listed": true, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Cancel a job" - }, - { - "completion": "immediate", - "description": "Replace an object's height range modifiers (Height Range Modifier in the object list): Z ranges in mm, each printed with its own layer_height, filament and process settings, starting from the object's layer height and filament. Ranges may touch but not overlap; [] removes them all. One undo step; the object is selected. Reply: the object's height and its ranges as list_objects shows them, and warnings, such as a variable layer height profile deciding the layer heights instead.", - "destructive": false, - "group": "api", - "guard": "mutate", - "idempotent": false, - "in_palette": false, - "input_schema": { - "additionalProperties": false, - "properties": { - "object": { - "description": "Object index (list_objects).", - "minimum": 0, - "type": "integer" - }, - "object_id": { - "description": "The id list_objects reports for this object: the call is refused when the index names another one now.", - "minimum": 0, - "type": "integer" - }, - "ranges": { - "description": "The object's ranges afterwards, in any order.", - "items": { - "additionalProperties": false, - "properties": { - "max_z": { - "description": "Top, mm above the bed.", - "minimum": 0, - "type": "number" - }, - "min_z": { - "description": "Bottom, mm above the bed.", - "minimum": 0, - "type": "number" - }, - "values": { - "description": "{key: value} as set_settings takes them: layer_height, extruder (0 = the object's filament) and per-region process settings such as sparse_infill_density or wall_loops.", - "type": "object" - } - }, - "required": [ - "min_z", - "max_z" - ], - "type": "object" - }, - "type": "array" - } - }, - "required": [ - "object", - "ranges" - ], - "type": "object" - }, - "key": "set_height_ranges", - "listed": true, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Set height range modifiers" - }, - { - "completion": "immediate", - "description": "Run the Variable layer height panel's Adaptive, Smooth or Reset on an object, without opening the panel: adaptive computes layer heights from the object's shape (inside a height range, the range's layer_height), smooth smooths its profile (or the one its height ranges give), reset goes back to its layer height and ranges. One undo step; the object is selected. Reply: the object's height, its layer_height_profile {points, min_height, max_height} as list_objects shows it (absent after reset), and warnings.", - "destructive": false, - "group": "api", - "guard": "mutate", - "idempotent": false, - "in_palette": false, - "input_schema": { - "additionalProperties": false, - "properties": { - "action": { - "description": "The panel's button.", - "enum": [ - "adaptive", - "smooth", - "reset" - ], - "type": "string" - }, - "keep_min": { - "description": "smooth: keep the minimum layer heights (default false).", - "type": "boolean" - }, - "object": { - "description": "Object index (list_objects).", - "minimum": 0, - "type": "integer" - }, - "object_id": { - "description": "The id list_objects reports for this object: the call is refused when the index names another one now.", - "minimum": 0, - "type": "integer" - }, - "quality": { - "description": "adaptive: 0 = quality .. 1 = speed (default 0.5, as the panel).", - "maximum": 1, - "minimum": 0, - "type": "number" - }, - "radius": { - "description": "smooth: default 5.", - "maximum": 10, - "minimum": 1, - "type": "integer" - } - }, - "required": [ - "object", - "action" - ], - "type": "object" - }, - "key": "set_variable_layer_height", - "listed": true, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Set a variable layer height profile" - }, - { - "completion": "immediate", - "description": "Add or remove pauses, custom G-code, custom templates and filament changes at the start of a layer, as the Preview layer slider's menu does; they are saved per plate in the project. They go on the plate's sliced layers, so the plate needs an up-to-date slice, or must be the one the Preview still shows after an earlier edit; the call selects it and shows the Preview. Applies clear, then remove, then add, all checked first. One code per layer: adding where a code of the same type is replaces it, and where another type is, is refused (remove it first). Not undoable, as in the slider. A change invalidates the plate's slice: slice again before exporting. Reply: the plate's codes as list_plates' layer_gcode lists them, each with z and layer.", - "destructive": false, - "group": "api", + "group": "Plates", "guard": "mutate", "idempotent": false, "in_palette": false, @@ -4471,7 +4377,7 @@ }, "type": "object" }, - "key": "set_custom_gcode_at_layer", + "key": "plate_set_custom_gcode", "listed": true, "open_world": false, "operations": [], @@ -4480,55 +4386,9 @@ }, { "completion": "immediate", - "description": "Capture what OrcaSlicer shows and return it as an image, downscaled to max_dim on the long edge (default 1280), plus the full-size PNG written to save_path (or the session's output folder). target: \"main\" (the main window), \"canvas\" (the visible 3D view exactly as rendered: scene, toolpaths, toolbars, ImGui panels; on the Design tab its view), \"dialog\" (the topmost modal dialog), or a ref: a window's from list_windows (one that is not modal, say), or a widget's from list_widgets, cropped to that widget (a page element's ref captures its whole web view). The result says when parts may differ from the screen (approximate). Point the view first with set_view.", + "description": "What the Preview shows for a sliced plate. summary: plate_slice's, plus prepare and travel time and travel distance. features: seconds, share of the print time and grams per feature type (the Line Type legend), and travel. layers: per layer (1-based, as view_set's layer) Z, height, seconds and grams, paged; layer_features adds each feature type's seconds. objects: grams per object instance, with its object_list index when its name is unique. view, for the plate the Preview shows: view type, time mode, layer range, which legend rows are visible, and each view type's colour range for what the legend shows. Times are normal-mode estimates. A G-code file opened for viewing reads the same.", "destructive": false, - "group": "ui", - "guard": "inspect", - "idempotent": true, - "in_palette": false, - "input_schema": { - "additionalProperties": false, - "properties": { - "include_image": { - "description": "Return the image itself (default true); false returns only the path.", - "type": "boolean" - }, - "max_dim": { - "description": "Long edge of the returned image.", - "maximum": 2000, - "minimum": 256, - "type": "integer" - }, - "overwrite": { - "description": "Replace an existing save_path.", - "type": "boolean" - }, - "save_path": { - "description": "Absolute .png path for the full-size image.", - "type": "string" - }, - "target": { - "description": "main (default), canvas, dialog, or a widget's ref or locator from list_widgets.", - "type": [ - "string", - "object" - ] - } - }, - "type": "object" - }, - "key": "screenshot", - "listed": true, - "open_world": false, - "operations": [], - "read_only": true, - "title": "Take a screenshot" - }, - { - "completion": "immediate", - "description": "What the Preview shows for a sliced plate. summary: the slice reply's, plus prepare and travel time and travel distance. features: seconds, share of the print time and grams per feature type (the Line Type legend), and travel. layers: per layer (1-based, as set_view's layer) Z, height, seconds and grams, paged; layer_features adds each feature type's seconds. objects: grams per object instance, with its list_objects index when its name is unique. view, for the plate the Preview shows: view type, time mode, layer range, which legend rows are visible, and each view type's colour range for what the legend shows. Times are normal-mode estimates. A G-code file opened for viewing reads the same.", - "destructive": false, - "group": "api", + "group": "Plates", "guard": "inspect", "idempotent": true, "in_palette": false, @@ -4567,7 +4427,7 @@ }, "type": "object" }, - "key": "get_slice_stats", + "key": "plate_slice_stats", "listed": true, "open_world": false, "operations": [], @@ -4576,15 +4436,1636 @@ }, { "completion": "immediate", - "description": "Set up what the window shows, for screenshots and GUI work: the main tab, the 3D view (canvas: Prepare's, the preview or the assemble view, which has its own gizmos), the camera of the 3D view shown (a named direction, the default view, or fit to bed / objects / selection, then look_at, the point it looks at, an orbit to look from between the named directions, and the zoom), the preview's color scheme (picked as in the legend's combo, which shows every feature type again), legend rows, time estimate and layers (1-based, or up to a height). Only the given fields change, but a preview field given without tab or canvas shows the Preview tab. On the Design tab the camera points its view (default is its Home view; no fit_bed; sketch_normal looks straight at the open sketch), and with tab design, section, origin_planes, world_axes, origin and bed set the Design view's switches. The reply echoes them; preview layers as [first, last, count] with z, the heights of first and last; with tab design, design: the section view and the four switches as they then are; with any camera field, camera_state, the camera it leaves as get_app_state.camera gives it, and adjusted: [\"zoom\"] when the zoom was held to its limits.", + "description": "Printer, process or filament presets, each with its name, alias (the name its selector shows, when another), system, user, project (kept inside the project), inherits, selected (and modified), compatible: false or installed: false when so, and vendor; a filament its filament_type and the slots using it (filament_slots), a printer its printer_model and nozzle. Only compatible, installed presets unless asked: a fresh install leaves most system filaments and printers out of the selectors, and preset_select takes such a preset too. printer lists the filaments or processes that fit another printer preset, in place of the selected one.", "destructive": false, - "group": "ui", + "group": "Presets and settings", + "guard": "inspect", + "idempotent": true, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "filament_type": { + "description": "Type filament: a filament type, in either case (\"PLA\").", + "type": "string" + }, + "include_incompatible": { + "description": "Also list presets incompatible with the printer.", + "type": "boolean" + }, + "include_uninstalled": { + "description": "Also list the system presets the selectors do not offer, which a person has not installed.", + "type": "boolean" + }, + "limit": { + "description": "Default 100.", + "maximum": 500, + "minimum": 1, + "type": "integer" + }, + "offset": { + "minimum": 0, + "type": "integer" + }, + "printer": { + "description": "Types filament and process: list what fits this printer preset (a name from preset_list type printer) in place of the selected printer.", + "type": "string" + }, + "query": { + "description": "Case-insensitive part of the name or alias.", + "type": "string" + }, + "source": { + "description": "Where the presets come from: the system's, a person's own, or kept inside the project.", + "enum": [ + "system", + "user", + "project" + ], + "type": "string" + }, + "type": { + "description": "Preset category.", + "enum": [ + "printer", + "process", + "filament" + ], + "type": "string" + }, + "vendor": { + "description": "A vendor, in either case: a filament's maker (\"Bambu Lab\", \"Generic\"), a printer's or process's vendor bundle (\"BBL\").", + "type": "string" + } + }, + "required": [ + "type" + ], + "type": "object" + }, + "key": "preset_list", + "listed": true, + "open_world": false, + "operations": [], + "read_only": true, + "title": "List presets" + }, + { + "completion": "immediate", + "description": "Select a printer, process or filament preset by the name its selector shows (or its internal name), as a person would. One the selectors do not offer (preset_list include_uninstalled) is shown in them first, until the app restarts; one the selector leaves out as incompatible with the printer is refused. With unsaved changes the Transfer-or-discard prompt opens (blocked_by_dialog) unless preset_changes answers it. A filament is assigned to filament_slot (1-based, default 1); with several slots the filament tab keeps the preset and the changes it has, so nothing is asked. Reply: selected, shown (a preset it showed in the selectors); when presets had or have unsaved changes, discarded and modified list per preset the keys dropped and the keys still unsaved.", + "destructive": false, + "group": "Presets and settings", "guard": "mutate", "idempotent": false, "in_palette": false, "input_schema": { "additionalProperties": false, "properties": { + "filament_slot": { + "description": "Filament slot, 1-based.", + "minimum": 1, + "type": "integer" + }, + "name": { + "description": "Preset name as preset_list shows it.", + "type": "string" + }, + "preset_changes": { + "description": "Unsaved changes of the presets the switch replaces: move them to the new preset or drop them, as the prompt's buttons do; transfer is refused where the prompt does not offer it (a printer's changes, a filament of another type). Omitted: the prompt opens.", + "enum": [ + "transfer", + "discard" + ], + "type": "string" + }, + "type": { + "description": "Preset category.", + "enum": [ + "printer", + "process", + "filament" + ], + "type": "string" + } + }, + "required": [ + "type", + "name" + ], + "type": "object" + }, + "key": "preset_select", + "listed": true, + "open_world": false, + "operations": [ + "resolve_preset", + "select_preset", + "assign_filament_preset" + ], + "read_only": false, + "title": "Select a preset" + }, + { + "completion": "immediate", + "description": "Save the printer, process or filament preset being edited, with its unsaved changes, as a preset called name, which is then selected: what the tab's Save button does through its dialog. A filament is filament_slot's (default 1), and every slot using the old preset takes the new one. Replacing another existing preset needs overwrite (pass it in replays and scripts meant to be rerun). Reply: saved, selected, user, project, inherits, filament_slots. A temperature warning or an unsaved-changes prompt makes it blocked_by_dialog. To keep only some edits, settings_set {reset_all: true, values} first.", + "destructive": false, + "group": "Presets and settings", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "detach": { + "description": "Copy inherited values and drop the parent (Developer mode).", + "type": "boolean" + }, + "filament_slot": { + "description": "Filament slot, 1-based.", + "minimum": 1, + "type": "integer" + }, + "inside_project": { + "description": "Keep it inside the project, not as a user preset. Default: where the edited preset is. A preset of that name stays where it is.", + "type": "boolean" + }, + "name": { + "description": "Name to save under.", + "type": "string" + }, + "overwrite": { + "description": "Replace another preset of that name.", + "type": "boolean" + }, + "type": { + "description": "Preset category.", + "enum": [ + "printer", + "process", + "filament" + ], + "type": "string" + } + }, + "required": [ + "type", + "name" + ], + "type": "object" + }, + "key": "preset_save", + "listed": true, + "open_world": true, + "operations": [], + "read_only": false, + "title": "Save a preset" + }, + { + "completion": "immediate", + "description": "Delete a user preset or one inside the project, its file and its cloud copy, as the tab's Delete does, without asking. A selected preset is replaced as the tab does (its parent or the next preset). Another filament is deleted without changing the selection, and slots using it take the selected one; another process is selected, deleted and the selection restored; a printer must be selected first, and the physical printers that use only it are deleted with it. Refused: system, default and bundle presets, presets others inherit from, another preset while the edited one of its type has unsaved changes. Deleting a selected printer or process can ask about other presets' unsaved changes (blocked_by_dialog). Reply: deleted, selected, filaments (per slot), attached, and discarded/modified as preset_select's.", + "destructive": true, + "group": "Presets and settings", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "delete_attached": { + "description": "A custom printer with process or filament presets made for it alone is refused without this: they are deleted with it, as the GUI deletes them.", + "type": "boolean" + }, + "name": { + "description": "Preset name as preset_list shows it.", + "type": "string" + }, + "type": { + "description": "Preset category.", + "enum": [ + "printer", + "process", + "filament" + ], + "type": "string" + } + }, + "required": [ + "type", + "name" + ], + "type": "object" + }, + "key": "preset_delete", + "listed": true, + "open_world": true, + "operations": [], + "read_only": false, + "title": "Delete a preset" + }, + { + "completion": "immediate", + "description": "All the settings of a type in one reply, each item with its value as OrcaSlicer writes it, and without meta unless include_meta. process, printer and filament: the preset being edited, or with preset a saved one, or with filament_slot a slot's. object: the process settings an object or an assembly takes; region: those a part, a modifier or a height range takes, whose layer_height item has targets [\"height_range\"], a height range alone taking it; in both, each with the process preset's value, which an object or a region prints with unless it sets its own. With where, the settings of one settings page or \"Page > Group\" (an unknown one is refused with the list of them). Items with meta, which where gives them, come 100 a page. settings_get reads the settings named or searched for, and what an object, a part or a height range overrides.", + "destructive": false, + "group": "Presets and settings", + "guard": "inspect", + "idempotent": true, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "filament_slot": { + "description": "Type filament: the slot whose preset is read, 1-based (default 1), with its unsaved changes when the filament tab is editing it.", + "minimum": 1, + "type": "integer" + }, + "include_meta": { + "description": "Include labels, types and ranges. Default false, true with where.", + "type": "boolean" + }, + "limit": { + "description": "Default: all of them, or 100 with meta.", + "maximum": 500, + "minimum": 1, + "type": "integer" + }, + "offset": { + "minimum": 0, + "type": "integer" + }, + "preset": { + "description": "Read this saved preset (a name from preset_list) instead of the one being edited: of the type, or for object and region a process preset.", + "type": "string" + }, + "type": { + "description": "Which settings: a preset's, or those an object or a region takes.", + "enum": [ + "process", + "printer", + "filament", + "object", + "region" + ], + "type": "string" + }, + "where": { + "description": "A settings page, or \"Page > Group\" as meta.where gives it, e.g. \"Strength > Walls\".", + "type": "string" + } + }, + "required": [ + "type" + ], + "type": "object" + }, + "key": "settings_list", + "listed": true, + "open_world": false, + "operations": [], + "read_only": true, + "title": "List settings" + }, + { + "completion": "immediate", + "description": "Read the settings named or searched for: 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, range, allowed values and mode. Choose them by keys, or by query, a few words matched in keys, labels and descriptions, best matches first. Keys the settings lack are listed in unknown_keys, and type_of gives where each of those is a setting elsewhere (a type, or project for the project's own settings). It needs keys, query, compare or a target other than global; settings_list lists all of a type's settings.\n- No type: keys and query look through the process, filament and printer settings, and each item names its type, the one settings_set takes; otherwise the type is the process.\n- type printer, process or filament (target global): the preset being edited, or with preset a saved one; compare lists only the keys that differ from another preset (value and other). A per-variant value lists in meta its variants (what each entry is for) and active (the entry each extruder prints with).\n- target object (object), part (object and part) or height_range (object, min_z and max_z), the object or part selected in Prepare where none is named: without keys, what it overrides; keys and query read the process settings it takes (settings_list type object or region lists them) and extruder, its filament, and a key it does not take is refused with where it is set. Each has value (its own, null where it has none), effective (the value it prints with) and source, in the order the slicer applies them: height_range, part, object, global or default; an object's item lists in parts the parts and modifiers that override the key inside their own volume, and an object's or a part's item lists in height_ranges the ranges whose value applies to it between their heights. Inside a modifier, mesh or painted, that sets none of a key, the value of the part it overlaps applies, which the command does not work out: where a part (or a modifier of either kind before it) sets the key, the modifier's item has effective null, source overlapped_part, object_effective and object_source (the object's value), and in parts those that set it. These settings are process settings. The reply names the target (objects or parts, and height_range).\npreferences_get reads the app's preferences, plate_get_settings a plate's settings and project_get_settings the project's own.", + "destructive": false, + "group": "Presets and settings", + "guard": "inspect", + "idempotent": true, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "compare": { + "description": "Target global: a preset name, \":saved\" (the unsaved changes) or \":parent\" (the preset it inherits from).", + "type": "string" + }, + "filament_slot": { + "description": "Type filament: the slot whose preset is read, 1-based (default 1), with its unsaved changes when the filament tab is editing it.", + "minimum": 1, + "type": "integer" + }, + "include_meta": { + "description": "Include labels, types and ranges. Default true, false with compare.", + "type": "boolean" + }, + "keys": { + "description": "Option keys, e.g. [\"layer_height\", \"wall_loops\"].", + "items": { + "type": "string" + }, + "type": "array" + }, + "limit": { + "description": "Default 100, or 20 with query.", + "maximum": 500, + "minimum": 1, + "type": "integer" + }, + "max_z": { + "description": "Target height_range: the range's top, mm.", + "minimum": 0, + "type": "number" + }, + "min_z": { + "description": "Target height_range: the range's bottom, mm.", + "minimum": 0, + "type": "number" + }, + "object": { + "description": "Object index from object_list (targets object, part and height_range); without it, the object selected in Prepare.", + "minimum": 0, + "type": "integer" + }, + "offset": { + "minimum": 0, + "type": "integer" + }, + "part": { + "description": "Part index in the object (target part, with object); without both, the part selected in Prepare.", + "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" + }, + "query": { + "description": "A few distinctive words, e.g. \"stringing\" or \"ooze travel\"; the best 20 matches unless limit says otherwise.", + "type": "string" + }, + "target": { + "description": "Where they apply: global (default), the type's preset; object, part or height_range, the overrides an object, one of its parts or modifiers, or one of its height ranges carries, which are process settings.", + "enum": [ + "global", + "object", + "part", + "height_range" + ], + "type": "string" + }, + "type": { + "description": "Which settings: the printer, process or filament preset being edited.", + "enum": [ + "printer", + "process", + "filament" + ], + "type": "string" + } + }, + "type": "object" + }, + "key": "settings_get", + "listed": true, + "open_world": false, + "operations": [], + "read_only": true, + "title": "Read settings" + }, + { + "completion": "immediate", + "description": "Change settings as typing them into their settings tab would: a type's preset (target global, the default), or the overrides an object, a part or a height range carries (targets object, part and height_range, whose settings are process settings). Values are strings in OrcaSlicer's format (\"15%\", \"0.2\", \"1,2\") or JSON numbers, booleans and arrays (a point as [x, y]). All are parsed strictly first and applied together, so nothing changes if one is invalid, and a key of another type is refused with that type named. Reply: applied, and changed, every setting the call changed, including those the app adjusted in turn. An object's or part's change is one undo step; a preset's is not in the undo history. Spiral vase and a few others confirm their adjustments in a dialog (blocked_by_dialog).\n- type printer, process (the default) or filament, target global: null takes a key back to its saved value, or with reset_to parent to the parent's; reset_all first discards every unsaved change, as the tab's undo button does (reply: reverted). A per-variant value (settings_get meta.variants) takes one value for the entries in use (meta.active), {index, value} for one entry, or an array of all.\n- type printer: extruders_count, alone, as the Extruders field of the Printer settings sets it; nozzle_volume_type, each extruder's nozzle flow type as its card in the sidebar picks it; a nozzle_diameter that a variant of the printer model has selects that variant's printer preset, as the sidebar's nozzle diameter does, with nozzle_volume_type alone (other keys go in a second call), each flow type checked against what the new preset's nozzle card offers, or gives where it offers none. The switch asks about the printer's unsaved changes (blocked_by_dialog) unless reset_all discards them first; the discard stays if the switch is not made.\n- target object (object), part (object and part) or height_range (object, min_z and max_z), the object or part selected in Prepare where none is named: overrides of the keys its row offers there (settings_list type object or region), and extruder; a key it does not take is refused with where it is set. null removes one; a height range keeps its layer_height, which is checked against the printer's layer heights for the range's filament. extruder, in neither list, is the target's filament (1-based; 0 or null for Default, the object's), set as the Change Filament menu does. The reply names the target (objects or parts, and height_range).\nplate_set_settings changes a plate's settings and project_set_settings the project's own. preferences_set changes the app's preferences; those it refuses (preferences_get marks them refused) change in the Preferences dialog, whose controls carry their effects: window_open {\"window\": \"preferences\", \"tab\": \"\", \"key\": \"\"}, then widget_set_value {\"target\": {\"name\": \"\", \"within\": \"Preferences\"}, \"value\": ...}.", + "destructive": false, + "group": "Presets and settings", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "filament_slot": { + "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 changes it holds (blocked_by_dialog).", + "minimum": 1, + "type": "integer" + }, + "max_z": { + "description": "Target height_range: the range's top, mm.", + "minimum": 0, + "type": "number" + }, + "min_z": { + "description": "Target height_range: the range's bottom, mm.", + "minimum": 0, + "type": "number" + }, + "object": { + "description": "Object index from object_list (targets object, part and height_range); without it, the object selected in Prepare.", + "minimum": 0, + "type": "integer" + }, + "object_id": { + "description": "The id object_list reports for this object: the call is refused when the index names another one now.", + "minimum": 0, + "type": "integer" + }, + "part": { + "description": "Part index in the object (target part, with object); without both, the part selected in Prepare.", + "minimum": 0, + "type": "integer" + }, + "part_id": { + "description": "The id object_list reports for this part: the call is refused when the index names another one now.", + "minimum": 0, + "type": "integer" + }, + "reset_all": { + "description": "Target global: discard the unsaved changes before applying values.", + "type": "boolean" + }, + "reset_to": { + "description": "Target global: what a null value takes a key back to: the saved preset (default) or the preset it inherits from.", + "enum": [ + "saved", + "parent" + ], + "type": "string" + }, + "target": { + "description": "Where they apply: global (default), the type's preset; object, part or height_range, the overrides an object, one of its parts or modifiers, or one of its height ranges carries, which are process settings.", + "enum": [ + "global", + "object", + "part", + "height_range" + ], + "type": "string" + }, + "type": { + "description": "Which settings: the printer, process or filament preset being edited.", + "enum": [ + "printer", + "process", + "filament" + ], + "type": "string" + }, + "values": { + "description": "{key: value}, or {key: {index, value}} for one entry", + "type": "object" + } + }, + "type": "object" + }, + "key": "settings_set", + "listed": true, + "open_world": false, + "operations": [], + "read_only": false, + "title": "Change settings" + }, + { + "completion": "immediate", + "description": "Import presets from a preset .json, a .zip of them, an .orca_printer, .orca_filament or .orca_bundle, or a .gcode by absolute path, without a dialog, and the message names the presets imported, replaced and kept; a .gcode loads the settings it was sliced with. Called with no arguments it is Import Configs: the file dialog asks for the file (blocked_by_dialog).", + "destructive": false, + "group": "Presets and settings", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "if": { + "minProperties": 1 + }, + "properties": { + "on_conflict": { + "description": "What happens to a preset that exists already. Default skip.", + "enum": [ + "skip", + "overwrite" + ], + "type": "string" + }, + "path": { + "description": "Absolute path of a preset .json, a .zip of them, an .orca_printer, .orca_filament or .orca_bundle, or a .gcode.", + "type": "string" + }, + "silent": { + "description": "true runs the command without asking; it then needs path, and what else the call leaves out takes its default. A call with no arguments does what a person's pick does.", + "enum": [ + true + ], + "type": "boolean" + } + }, + "then": { + "required": [ + "path" + ] + }, + "type": "object" + }, + "key": "preset_import", + "listed": true, + "open_world": false, + "operations": [ + "import_presets" + ], + "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Import presets from the file a dialog asks for. preset_import with a path imports a preset .json, a .zip of them, an .orca_printer, .orca_filament or .orca_bundle, or a .gcode without a dialog, and the message names the presets imported, replaced and kept; a .gcode loads the settings it was sliced with.", + "group": "Import", + "icon": "menu_open", + "key": "import_configs", + "title": "Import Configs" + } + ], + "title": "Import Configs" + }, + { + "completion": "immediate", + "description": "Export presets as a bundle or ZIP archives through the Export Preset Bundle dialog: click the label of the kind to export, check its rows (each named after a printer preset or a filament), press OK, then answer the result message. Every call opens the dialog (blocked_by_dialog). With path, OK writes into that folder instead of asking for one, and a cancelled dialog is an error: nothing was exported.", + "destructive": false, + "group": "Presets and settings", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "path": { + "description": "Absolute path of an existing folder, which the dialog's OK writes into.", + "type": "string" + } + }, + "type": "object" + }, + "key": "preset_export", + "listed": true, + "open_world": false, + "operations": [], + "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Export presets as a bundle or ZIP archives through the Export Preset Bundle dialog: click the label of the kind to export, check its rows (each named after a printer preset or a filament), press OK, then answer the result message. preset_export with a folder as path has OK write there instead of asking for one.", + "group": "Export", + "icon": "save", + "key": "export_config", + "title": "Export Preset Bundle" + } + ], + "title": "Export Preset Bundle" + }, + { + "completion": "immediate", + "description": "Synchronize user presets with the cloud account. Refused while no account is signed in.", + "destructive": false, + "group": "Presets and settings", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": {}, + "type": "object" + }, + "key": "preset_sync", + "listed": true, + "open_world": true, + "operations": [ + "sync_presets" + ], + "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Synchronize user presets with the cloud account.", + "group": "Presets", + "icon": "printer_sync_ok", + "key": "sync_presets", + "title": "Sync Presets" + } + ], + "title": "Sync Presets" + }, + { + "completion": "immediate", + "description": "Migrate legacy user filament presets.", + "destructive": false, + "group": "Presets and settings", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": {}, + "type": "object" + }, + "key": "preset_migrate_filaments", + "listed": true, + "open_world": false, + "operations": [], + "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Migrate legacy user filament presets.", + "group": "Help", + "icon": "", + "key": "help_migrate_filament_presets", + "title": "Migrate Filament Presets" + } + ], + "title": "Migrate Filament Presets" + }, + { + "completion": "immediate", + "description": "Switch the settings view to Simple, Advanced or Expert mode, which decides which settings the settings pages show.", + "destructive": false, + "group": "Presets and settings", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "mode": { + "description": "The mode.", + "enum": [ + "simple", + "advanced", + "expert" + ], + "type": "string" + } + }, + "required": [ + "mode" + ], + "type": "object" + }, + "key": "settings_set_mode", + "listed": true, + "open_world": false, + "operations": [], + "read_only": false, + "tiles": [ + { + "args": { + "mode": "simple" + }, + "description": "Switch the settings view to Simple mode.", + "group": "Mode", + "icon": "advanced", + "key": "mode_simple", + "title": "Mode: Simple" + }, + { + "args": { + "mode": "advanced" + }, + "description": "Switch the settings view to Advanced mode.", + "group": "Mode", + "icon": "advanced", + "key": "mode_advanced", + "title": "Mode: Advanced" + }, + { + "args": { + "mode": "expert" + }, + "description": "Switch the settings view to Expert mode.", + "group": "Mode", + "icon": "advanced", + "key": "mode_expert", + "title": "Mode: Expert" + } + ], + "title": "Set the settings mode" + }, + { + "completion": "immediate", + "description": "Turn Developer mode on or off.", + "destructive": false, + "group": "Presets and settings", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": {}, + "type": "object" + }, + "key": "settings_toggle_developer_mode", + "listed": false, + "open_world": false, + "operations": [], + "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Turn Developer mode on or off.", + "group": "Mode", + "icon": "advanced", + "key": "toggle_developer_mode", + "title": "Toggle Developer Mode" + } + ], + "title": "Toggle Developer Mode" + }, + { + "completion": "immediate", + "description": "Add a filament slot, as the + button above the filament list does. It takes the next colour and the last slot's preset (change them with preset_select filament_slot and project_set_settings filament_colour). It goes after the physical slots: mixed filaments move up by one, and objects on them follow. Refused for a printer that has one filament per extruder, which shows no + and - buttons. Reply: filament_slot (the new slot) and filament_slots (how many the project has).", + "destructive": false, + "group": "Filaments", + "guard": "mutate", + "icon": "add_filament", + "idempotent": false, + "in_palette": true, + "input_schema": { + "additionalProperties": false, + "properties": {}, + "type": "object" + }, + "key": "filament_add", + "listed": true, + "open_world": false, + "operations": [ + "add_filament_slot" + ], + "read_only": false, + "tile_group": "Filament", + "title": "Add Filament Slot" + }, + { + "completion": "immediate", + "description": "Delete a filament slot, as its Delete menu item does, the objects on it taking the first filament; with merge_into, as its Merge with item does, the objects on it taking that slot. The slots after it move down by one. The only physical slot and a mixed filament (project_get_settings filament_is_mixed) are refused, and so is a merge into a mixed filament that mixes the slot. Refused for a printer that has one filament per extruder, which shows no + and - buttons. Not in the undo history. Reply: filament_slot (the slot deleted), merged_into (the slot its objects went to, as numbered afterwards) and filament_slots.", + "destructive": false, + "group": "Filaments", + "guard": "mutate", + "icon": "delete_filament", + "idempotent": false, + "in_palette": true, + "input_schema": { + "additionalProperties": false, + "properties": { + "filament_slot": { + "description": "The 1-based filament slot. Default: the last physical slot, as the - button.", + "minimum": 1, + "type": "integer" + }, + "merge_into": { + "description": "The 1-based slot the objects on it go to, as Merge with does. Default: they take the first filament.", + "minimum": 1, + "type": "integer" + } + }, + "type": "object" + }, + "key": "filament_delete", + "listed": true, + "open_world": false, + "operations": [ + "delete_filament_slot" + ], + "read_only": false, + "tile_group": "Filament", + "title": "Delete Filament Slot" + }, + { + "completion": "immediate", + "description": "Add a mixed filament: a slot that prints its physical filaments in turn, layer by layer, in the ratios given, as the Add Mixed Filament dialog's OK does with no gradient. components are two or more of the physical slots (1-based), each named once, whose filaments are of one type; ratios a whole percentage for each, adding up to 100. It goes after every other slot. A mix the project has already is not added again: the reply names its slot. Not in the undo history. Reply: filament_slot (1-based) and added (false for a mix the project had).", + "destructive": false, + "examples": [ + { + "calls": [ + { + "args": { + "components": [ + 1, + 2 + ], + "ratios": [ + 50, + 50 + ] + }, + "tool": "filament_add_mixed" + } + ], + "title": "Mix the first two filaments half and half" + }, + { + "calls": [ + { + "args": { + "components": [ + 1, + 2, + 3 + ], + "ratios": [ + 25, + 25, + 50 + ] + }, + "tool": "filament_add_mixed" + } + ], + "title": "Mix three filaments, the third the most" + } + ], + "group": "Filaments", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "components": { + "description": "The physical filament slots to mix, 1-based, two or more, each once, of filaments of one type.", + "items": { + "minimum": 1, + "type": "integer" + }, + "type": "array" + }, + "ratios": { + "description": "Each component's share in percent, in the order of components, adding up to 100.", + "items": { + "exclusiveMinimum": 0, + "type": "integer" + }, + "type": "array" + } + }, + "required": [ + "components", + "ratios" + ], + "type": "object" + }, + "key": "filament_add_mixed", + "listed": true, + "open_world": false, + "operations": [ + "add_mixed_filament" + ], + "read_only": false, + "title": "Add Mixed Filament" + }, + { + "completion": "immediate", + "description": "Synchronize the filament list from the connected printer's AMS. With mode, as the sync dialog's Synchronize now does with that choice, without the dialog: map maps each of the project's filaments to a slot, as the dialog's Mapping first does, which takes a project with objects; overwrite replaces the filament list with the slots' filaments. Called with no arguments, as its tile, it opens the sync dialog where the project has objects (blocked_by_dialog), and a warning where it cannot sync. With no printer connected, no AMS or no filament it is refused, saying so. Not in the undo history. Reply: mode, filaments (each slot's preset and colour afterwards) and mapped_to_generic (slots whose filament is unknown, mapped to a generic preset).", + "destructive": false, + "group": "Filaments", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "mode": { + "description": "The sync dialog's choice: map or overwrite.", + "enum": [ + "map", + "overwrite" + ], + "type": "string" + } + }, + "type": "object" + }, + "key": "filament_sync_ams", + "listed": true, + "open_world": true, + "operations": [ + "sync_filaments_from_ams" + ], + "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Synchronize the filament list from the connected printer's AMS.", + "group": "Printer", + "icon": "ams_fila_sync", + "key": "sync_ams", + "title": "Synchronize Filament List from AMS" + } + ], + "title": "Synchronize Filament List from AMS" + }, + { + "completion": "immediate", + "description": "Install system filaments, for good, as ticking them in the System Filaments dialog and pressing Confirm does: the filament selectors offer them. Name them by names, or with vendor and filament_type every filament of that vendor and type that an installed printer fits. preset_list {type: \"filament\", include_uninstalled: true} lists the system filaments, those not installed with installed: false. A name no filament has is refused with the closest names. The app keeps an installed printer's default filaments installed while no other installed filament fits it: where the call leaves one so, they are installed again and listed under filaments_installed, as the next start would. The other filaments, and the presets' unsaved changes, are kept, and the selectors are refreshed. Not in the undo history. Reply: installed (the presets installed), installed_already, filaments_installed.", + "destructive": false, + "examples": [ + { + "calls": [ + { + "args": { + "include_uninstalled": true, + "query": "PETG HF", + "type": "filament" + }, + "tool": "preset_list" + }, + { + "args": { + "names": [ + "Bambu PETG HF" + ] + }, + "tool": "filament_install" + } + ], + "title": "Install a filament by the name the selector shows" + }, + { + "calls": [ + { + "args": { + "filament_type": "PETG", + "vendor": "Generic" + }, + "tool": "filament_install" + } + ], + "title": "Install every filament of a vendor and type" + } + ], + "group": "Filaments", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "filament_type": { + "description": "With vendor: a filament type (\"PLA\"), in any case.", + "type": "string" + }, + "names": { + "description": "System filaments: a preset's name, or the short name the filament selector shows (\"Bambu PLA Basic\"), which stands for its preset of every installed printer it fits.", + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + "vendor": { + "description": "With filament_type, in place of names: a filament maker (\"Bambu Lab\", \"Generic\"), in any case.", + "type": "string" + } + }, + "type": "object" + }, + "key": "filament_install", + "listed": true, + "open_world": false, + "operations": [ + "install_filaments" + ], + "read_only": false, + "title": "Install system filaments" + }, + { + "completion": "immediate", + "description": "Uninstall system filaments, for good, as unticking them in the System Filaments dialog and pressing Confirm does: the filament selectors no longer offer them. names as filament_install takes them. A filament a slot of the project uses is refused, naming the slot. The app keeps an installed printer's default filaments installed while no other installed filament fits it: where the call leaves one so, they are installed again and listed under filaments_installed, as the next start would. The other filaments, and the presets' unsaved changes, are kept, and the selectors are refreshed. Not in the undo history. Reply: uninstalled (the presets uninstalled), not_installed, filaments_installed.", + "destructive": false, + "examples": [ + { + "calls": [ + { + "args": { + "names": [ + "Bambu PETG HF" + ] + }, + "tool": "filament_uninstall" + } + ], + "title": "Uninstall a filament" + } + ], + "group": "Filaments", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "names": { + "description": "System filaments: a preset's name, or the short name the filament selector shows (\"Bambu PLA Basic\"), which stands for its preset of every installed printer it fits.", + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + } + }, + "required": [ + "names" + ], + "type": "object" + }, + "key": "filament_uninstall", + "listed": true, + "open_world": false, + "operations": [ + "uninstall_filaments" + ], + "read_only": false, + "title": "Uninstall system filaments" + }, + { + "completion": "immediate", + "description": "Open the Send G-code to printer host dialog for the current plate, as the Print button does for a printer with a print host (OctoPrint, Moonraker, PrusaLink, Duet...). Set the file name with widget_set_value and press Upload or Upload and Print with dialog_answer; the plate is sliced if needed, then uploaded in the background: app_state.uploads shows the row's state, and a failed upload also opens an error dialog. A replay uploads again. Fails for a printer without a print host, or one that prints through the Bambu network or printer agents.", + "destructive": false, + "group": "Printers and prints", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": {}, + "type": "object" + }, + "key": "printer_send", + "listed": true, + "open_world": true, + "operations": [ + "send_gcode_to_host" + ], + "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Open the Send G-code to printer host dialog for the current plate, as the Print button does for a printer with a print host (OctoPrint, Moonraker, PrusaLink, Duet...). Set the file name with widget_set_value and press Upload or Upload and Print with dialog_answer; the plate is sliced if needed, then uploaded in the background: app_state.uploads shows the row's state, and a failed upload also opens an error dialog. A replay uploads again. Fails for a printer without a print host, or one that prints through the Bambu network or printer agents.", + "group": "Slice & Export", + "icon": "printer", + "key": "send_gcode", + "title": "Send G-code to printer host" + } + ], + "title": "Send G-code to printer host" + }, + { + "completion": "immediate", + "description": "Every printer model OrcaSlicer ships or has installed, of every vendor, as the Printer Selection dialog lists them: each with its vendor (the vendor's id, \"BBL\"), model, nozzles and installed_nozzles, the nozzles whose printer presets the printer selector offers. vendor keeps one vendor's models, and query those whose name holds it. The first call after the shipped profiles change reads every vendor, which takes a while and can reply with a job to wait for; later calls read the result kept in the configuration folder. printer_install and printer_uninstall change what is installed.", + "destructive": false, + "examples": [ + { + "calls": [ + { + "args": { + "query": "X1 Carbon" + }, + "tool": "printer_list_models" + } + ], + "title": "Find a printer model and its nozzles" + }, + { + "calls": [ + { + "args": { + "vendor": "Prusa" + }, + "tool": "printer_list_models" + } + ], + "title": "List one vendor's printer models" + } + ], + "group": "Printers and prints", + "guard": "inspect", + "idempotent": true, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "limit": { + "description": "Default 100.", + "maximum": 500, + "minimum": 1, + "type": "integer" + }, + "offset": { + "minimum": 0, + "type": "integer" + }, + "query": { + "description": "Models whose name holds this, in any case.", + "type": "string" + }, + "vendor": { + "description": "A vendor's models only (\"BBL\", \"Prusa\"), in any case.", + "type": "string" + } + }, + "type": "object" + }, + "key": "printer_list_models", + "listed": true, + "open_world": false, + "operations": [ + "printer_models" + ], + "read_only": true, + "title": "List printer models" + }, + { + "completion": "immediate", + "description": "Install printer models, for good, as ticking them in the Printer Selection dialog and pressing Confirm does: a vendor's profiles are installed from the ones OrcaSlicer ships, the presets reloaded, and a printer newly added selected. The other installed models are kept, and the installed filaments but for what the reload changes. A name no model has, a vendor or a nozzle a model lacks, is refused with the closest names. Reloading the presets drops their unsaved changes, so while there are some preset_changes says what becomes of them; without it the call is refused. A call that changes nothing reloads nothing. The reload installs a printer's default filaments where no installed filament fits it, as the dialog does, and where a vendor's profile lists default filaments of its own, which none of the shipped profiles does, swaps a @System filament for the vendor's: those are under filaments_installed and filaments_uninstalled. Two errors come after a change and say what it was: vendors_not_installed, where a vendor's profiles cannot be installed (the installed printers are as they were, the unsaved changes discarded if preset_changes said so, and the profiles copied before it stay in the configuration folder), and presets_not_reloaded (the installed printers were written, the presets not reloaded). Not in the undo history. Reply: models (what was named, resolved), added (the printer presets the printer selector offers that it did not before the call), selected, not_offered (named nozzles whose presets it still does not offer), and discarded/modified as preset_select's.", + "destructive": false, + "examples": [ + { + "calls": [ + { + "args": { + "query": "Velo" + }, + "tool": "printer_list_models" + }, + { + "args": { + "models": [ + { + "model": "Goofoo Velo+", + "nozzles": [ + "0.4" + ], + "vendor": "Goofoo" + } + ] + }, + "tool": "printer_install" + } + ], + "title": "Install a printer model with one of its nozzles" + }, + { + "calls": [ + { + "args": { + "models": [ + { + "model": "Bambu Lab X1 Carbon" + } + ], + "preset_changes": "discard" + }, + "tool": "printer_install" + } + ], + "title": "Install every nozzle of a model, dropping the presets' unsaved changes" + } + ], + "group": "Printers and prints", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "models": { + "description": "The printer models, each with its nozzles.", + "items": { + "additionalProperties": false, + "properties": { + "model": { + "description": "The model, as printer_list_models lists it (\"Bambu Lab X1 Carbon\").", + "type": "string" + }, + "nozzles": { + "description": "Its nozzles, as printer_list_models lists them (\"0.4\"). Default: all of them, as the dialog's tick of a model.", + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + "vendor": { + "description": "Its vendor (\"BBL\"), needed where several vendors have a model of that name.", + "type": "string" + } + }, + "required": [ + "model" + ], + "type": "object" + }, + "minItems": 1, + "type": "array" + }, + "preset_changes": { + "description": "The presets' unsaved changes, which reloading the presets drops: move them to the presets selected after it, or drop them, as the Transfer and Discard of the question the dialog's Confirm asks. Needed while presets have unsaved changes; without it the call is refused.", + "enum": [ + "transfer", + "discard" + ], + "type": "string" + } + }, + "required": [ + "models" + ], + "type": "object" + }, + "key": "printer_install", + "listed": true, + "open_world": false, + "operations": [ + "install_printers" + ], + "read_only": false, + "title": "Install printer models" + }, + { + "completion": "immediate", + "description": "Uninstall printer models, for good, as unticking them in the Printer Selection dialog and pressing Confirm does: the printer selector no longer offers their printer presets, and the vendor's profiles stay on disk. Without nozzles a model goes whole. A printer removed while selected is replaced by another installed one. Removing the last installed printer model is refused, and so are names as printer_install refuses them. Reloading the presets drops their unsaved changes, so while there are some preset_changes says what becomes of them; without it the call is refused. A call that changes nothing reloads nothing. The reload installs a printer's default filaments where no installed filament fits it, as the dialog does, and where a vendor's profile lists default filaments of its own, which none of the shipped profiles does, swaps a @System filament for the vendor's: those are under filaments_installed and filaments_uninstalled. Two errors come after a change and say what it was: vendors_not_installed, where a vendor's profiles cannot be installed (the installed printers are as they were, the unsaved changes discarded if preset_changes said so, and the profiles copied before it stay in the configuration folder), and presets_not_reloaded (the installed printers were written, the presets not reloaded). Not in the undo history. Reply: models, removed (the printer presets the printer selector no longer offers), selected, still_offered (named nozzles whose presets it still offers), and discarded/modified as preset_select's.", + "destructive": false, + "examples": [ + { + "calls": [ + { + "args": { + "models": [ + { + "model": "Goofoo Velo+", + "vendor": "Goofoo" + } + ] + }, + "tool": "printer_uninstall" + } + ], + "title": "Uninstall a printer model" + } + ], + "group": "Printers and prints", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "models": { + "description": "The printer models, each with its nozzles.", + "items": { + "additionalProperties": false, + "properties": { + "model": { + "description": "The model, as printer_list_models lists it (\"Bambu Lab X1 Carbon\").", + "type": "string" + }, + "nozzles": { + "description": "Its nozzles, as printer_list_models lists them (\"0.4\"). Default: all of them, as the dialog's tick of a model.", + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + "vendor": { + "description": "Its vendor (\"BBL\"), needed where several vendors have a model of that name.", + "type": "string" + } + }, + "required": [ + "model" + ], + "type": "object" + }, + "minItems": 1, + "type": "array" + }, + "preset_changes": { + "description": "The presets' unsaved changes, which reloading the presets drops: move them to the presets selected after it, or drop them, as the Transfer and Discard of the question the dialog's Confirm asks. Needed while presets have unsaved changes; without it the call is refused.", + "enum": [ + "transfer", + "discard" + ], + "type": "string" + } + }, + "required": [ + "models" + ], + "type": "object" + }, + "key": "printer_uninstall", + "listed": true, + "open_world": false, + "operations": [ + "uninstall_printers" + ], + "read_only": false, + "title": "Uninstall printer models" + }, + { + "completion": "immediate", + "description": "The plugins, as the Plugins window lists them: each with its key (which the other plugin commands take), name, version (the one installed, else the latest offered), installed (a package is on disk), enabled (loaded: the row's switch), status (Activated, Error, RuntimeError, Inactive or Loading), source (local, subscribed, mine or orphaned), capabilities (a loaded plugin's: name, type, enabled) and error.", + "destructive": false, + "examples": [ + { + "calls": [ + { + "args": {}, + "tool": "plugin_list" + } + ], + "title": "List the plugins and how each stands" + } + ], + "group": "Plugins", + "guard": "inspect", + "idempotent": true, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": {}, + "type": "object" + }, + "key": "plugin_list", + "listed": true, + "open_world": false, + "operations": [], + "read_only": true, + "title": "List plugins" + }, + { + "completion": "immediate", + "description": "Install a plugin from a .py or .whl file by absolute path, as the Plugins dialog's Install local plugin does, without its file dialog. A plugin of that name installed already is replaced only with overwrite true; without it the call is refused with the question the dialog asks. Called with no arguments, the file dialog asks for the file (blocked_by_dialog), and replacing an installed plugin asks first (dialog_answer).", + "destructive": false, + "group": "Plugins", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "if": { + "minProperties": 1 + }, + "properties": { + "overwrite": { + "description": "Replace a plugin of that name installed already. Default false.", + "type": "boolean" + }, + "path": { + "description": "Absolute path of a .py or .whl plugin package.", + "type": "string" + }, + "silent": { + "description": "true runs the command without asking; it then needs path, and what else the call leaves out takes its default. A call with no arguments does what a person's pick does.", + "enum": [ + true + ], + "type": "boolean" + } + }, + "then": { + "required": [ + "path" + ] + }, + "type": "object" + }, + "key": "plugin_install_local", + "listed": true, + "open_world": false, + "operations": [], + "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Install a plugin from the .py or .whl file a dialog asks for, as the Plugins dialog's Install local plugin does, asking before it replaces one installed; plugin_install_local with a path installs that file without a dialog. A plugin of that name installed already is replaced only with overwrite true; without it the call is refused with the question the dialog asks.", + "group": "Plugins", + "icon": "", + "key": "install_local_plugin", + "title": "Install Local Plugin" + } + ], + "title": "Install Local Plugin" + }, + { + "completion": "immediate", + "description": "Turn a plugin, or with capability one of its capabilities, on or off, as the Plugins window's switches do. A plugin turned on is loaded, and the call waits for its load to end; a cloud plugin not installed is downloaded and installed first. A plugin that needs a permission while it loads asks in its permission dialog (blocked_by_dialog), which the caller answers. A plugin turned off is unloaded and loses its error. A capability is one of a loaded plugin's, by its name; an empty one is refused. Reply: plugin (its row, as plugin_list gives it) and changed; a call that fails once it has changed the plugin, a load that fails among them, is an error naming how the plugin is left.", + "destructive": false, + "examples": [ + { + "calls": [ + { + "args": {}, + "tool": "plugin_list" + }, + { + "args": { + "enabled": true, + "plugin": "my_plugin" + }, + "tool": "plugin_enable" + } + ], + "title": "Turn a plugin on" + }, + { + "calls": [ + { + "args": { + "capability": "Export report", + "enabled": false, + "plugin": "my_plugin" + }, + "tool": "plugin_enable" + } + ], + "title": "Turn one of a plugin's capabilities off" + } + ], + "group": "Plugins", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "capability": { + "description": "One of the plugin's capabilities, by name, in place of the plugin itself. The plugin must be enabled.", + "minLength": 1, + "type": "string" + }, + "enabled": { + "description": "On (true) or off (false).", + "type": "boolean" + }, + "plugin": { + "description": "The plugin's key, as plugin_list gives it, or its name where one plugin has it.", + "type": "string" + } + }, + "required": [ + "plugin", + "enabled" + ], + "type": "object" + }, + "key": "plugin_enable", + "listed": true, + "open_world": true, + "operations": [ + "set_plugin_enabled" + ], + "read_only": false, + "title": "Enable or disable a plugin" + }, + { + "completion": "immediate", + "description": "Load a plugin again after its files changed, as its row's Reload does: it is unloaded and loaded, and a plugin that was not loaded is unloaded again. clear_cache also removes its extracted wheel cache first, as Delete cache and reload does. A cloud plugin is installed again from the cloud, as its Reinstall does, and takes no clear_cache; one no longer available is refused. Reply: reloaded, reinstalled and plugin (its row); a reload that fails is an error naming how the plugin is left.", + "destructive": false, + "examples": [ + { + "calls": [ + { + "args": { + "plugin": "my_plugin" + }, + "tool": "plugin_reload" + } + ], + "title": "Reload a plugin after editing its files" + }, + { + "calls": [ + { + "args": { + "clear_cache": true, + "plugin": "my_plugin" + }, + "tool": "plugin_reload" + } + ], + "title": "Reload a plugin with its wheel cache removed" + } + ], + "group": "Plugins", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "clear_cache": { + "description": "Remove the plugin's extracted wheel cache before loading it. Default false.", + "type": "boolean" + }, + "plugin": { + "description": "The plugin's key, as plugin_list gives it, or its name where one plugin has it.", + "type": "string" + } + }, + "required": [ + "plugin" + ], + "type": "object" + }, + "key": "plugin_reload", + "listed": true, + "open_world": true, + "operations": [ + "reload_plugin" + ], + "read_only": false, + "title": "Reload a plugin" + }, + { + "completion": "immediate", + "description": "Remove a plugin for good, without asking, as its row's Delete does once confirmed: it is unloaded where it runs, and its files are removed. A cloud plugin subscribed to is unsubscribed, as its row's Unsubscribe does, which also ends the subscription in the cloud account; the person's own cloud plugin loses its package alone and stays listed, to be installed again. Reply: uninstalled (the key), name, unsubscribed, and plugin where it stays listed; a removal that fails is an error naming how the plugin is left.", + "destructive": true, + "examples": [ + { + "calls": [ + { + "args": {}, + "tool": "plugin_list" + }, + { + "args": { + "plugin": "my_plugin" + }, + "tool": "plugin_uninstall" + } + ], + "title": "Uninstall a plugin" + } + ], + "group": "Plugins", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "plugin": { + "description": "The plugin's key, as plugin_list gives it, or its name where one plugin has it.", + "type": "string" + } + }, + "required": [ + "plugin" + ], + "type": "object" + }, + "key": "plugin_uninstall", + "listed": true, + "open_world": true, + "operations": [ + "uninstall_plugin" + ], + "read_only": false, + "title": "Uninstall a plugin" + }, + { + "completion": "immediate", + "description": "Reload the plugins, as Refresh Plugins does: the installed plugins are rescanned and the plugin hub's list fetched again, and a notification says how it went. The call waits for the refresh to end and replies with the plugins, as plugin_list gives them; a refresh already running, or waiting, runs before the call's own, so the reply comes from a rescan that began after the call. job_cancel stops the wait, not the refresh.", + "destructive": false, + "group": "Plugins", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": {}, + "type": "object" + }, + "key": "plugin_refresh", + "listed": true, + "open_world": true, + "operations": [ + "start_plugin_refresh" + ], + "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Reload plugins.", + "group": "Plugins", + "icon": "", + "key": "refresh_plugins", + "title": "Refresh Plugins" + } + ], + "title": "Refresh Plugins" + }, + { + "completion": "immediate", + "description": "Set up what the window shows, for screenshots and GUI work: the main tab, the 3D view (canvas: Prepare's, the preview or the assemble view, which has its own gizmos), the camera of the 3D view shown (a named direction, the default view, or fit to bed / objects / selection, then look_at, the point it looks at, an orbit to look from between the named directions, and the zoom), the preview's color scheme (picked as in the legend's combo, which shows every feature type again), legend rows, time estimate and layers (1-based, or up to a height). Only the given fields change, but a preview field given without tab or canvas shows the Preview tab. On the Design tab the camera points its view (default is its Home view; no fit_bed; sketch_normal looks straight at the open sketch), and with tab design, section, origin_planes, world_axes, origin and bed set the Design view's switches. The reply echoes them; preview layers as [first, last, count] with z, the heights of first and last; with tab design, design: the section view and the four switches as they then are; with any camera field, camera_state, the camera it leaves as app_state.camera gives it, and adjusted: [\"zoom\"] when the zoom was held to its limits. tab takes the id of any other page of the window too, such as a plugin's. projection sets the 3D camera's, layout default restores the default window layout, and layer_percent shows the Preview at that share of the layer range, as Go to layer does. Outside the Design tab, from any tab: section {on} turns the section view of Prepare and the Preview on or off; labels, overhangs, outline, wireframe, gridlines, axes and navigator set the display switches of the View menu and of the 3D view's own menu; sidebar_collapsed and sidebar_width set the sidebar of Prepare and the Preview; in the Preview, legend_collapsed folds the legend and gcode_window shows the G-code window. Each is echoed as the app reads it back, and app_state's view gives them under these names. A pick of a view tile runs the same code in place, so a camera tile turns the Design tab's camera too.", + "destructive": false, + "group": "View and windows", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "axes": { + "description": "The axes on the bed of Prepare and the Preview, as the 3D view's own menu sets them; with tab design, world_axes is the Design view's.", + "type": "boolean" + }, "bed": { "description": "Design tab: the Bed row's eye, the printer bed drawn.", "type": "boolean" @@ -4616,11 +6097,29 @@ ], "type": "string" }, + "gcode_window": { + "description": "Preview: show (true) or hide (false) the G-code window, as View > Show G-code Window does.", + "type": "boolean" + }, + "gridlines": { + "description": "The plate's gridlines, as View > Show Gridlines sets them.", + "type": "boolean" + }, + "labels": { + "description": "Prepare: the object labels, as View > Show Labels sets them.", + "type": "boolean" + }, "layer": { "description": "Preview: show layers up to this one (1-based).", "minimum": 1, "type": "integer" }, + "layer_percent": { + "description": "Preview: show the layers up to this share of the layer range, as Go to layer does; the bottom of the shown range stays.", + "maximum": 100, + "minimum": 0, + "type": "number" + }, "layer_range": { "description": "Preview: [first, last] layers, 1-based.", "items": { @@ -4633,20 +6132,35 @@ "minimum": 0, "type": "number" }, + "layout": { + "description": "default restores the default window layout, as View > Reset Window Layout does.", + "enum": [ + "default" + ], + "type": "string" + }, "legend": { "additionalProperties": { "type": "boolean" }, - "description": "Preview: show (true) or hide (false) legend rows: feature types by name as get_slice_stats lists them (\"Sparse infill\"), and travel, wipe, retract, unretract, seams, filament_changes, color_changes, pauses, custom_gcode, in any case and with _ or a space between words. Hiding a row this print lacks does nothing. Applied after view_type.", + "description": "Preview: show (true) or hide (false) legend rows: feature types by name as plate_slice_stats lists them (\"Sparse infill\"), and travel, wipe, retract, unretract, seams, filament_changes, color_changes, pauses, custom_gcode, in any case and with _ or a space between words. Hiding a row this print lacks does nothing. Applied after view_type.", "type": "object" }, + "legend_collapsed": { + "description": "Preview: fold the legend to its title row (true) or unfold it (false), as its fold button does.", + "type": "boolean" + }, "look_at": { - "description": "[x, y, z] in mm: the point the camera looks at, in the 3D view's world coordinates, as list_objects gives positions; on the Design tab, the Design view's, which the Design commands' world points use (describe_design's modeling_origin is the sketch planes' origin). The camera moves parallel, keeping its direction and distance. After camera.", + "description": "[x, y, z] in mm: the point the camera looks at, in the 3D view's world coordinates, as object_list gives positions; on the Design tab, the Design view's, which the Design commands' world points use (describe_design's modeling_origin is the sketch planes' origin). The camera moves parallel, keeping its direction and distance. After camera.", "items": { "type": "number" }, "type": "array" }, + "navigator": { + "description": "The 3D navigator of Prepare and the Preview, as View > Show 3D Navigator sets it.", + "type": "boolean" + }, "orbit": { "description": "[yaw, pitch] in degrees: move the camera around what it looks at, yaw to its right and pitch up (negative looks from lower), after camera and look_at. The same on every install, unlike a mouse drag.", "items": { @@ -4662,9 +6176,26 @@ "description": "Design tab: show the origin helper planes (key P).", "type": "boolean" }, + "outline": { + "description": "The outline around the selected objects, as View > Show Selected Outline sets it.", + "type": "boolean" + }, + "overhangs": { + "description": "Prepare: the overhang highlight, as View > Show Overhang sets it.", + "type": "boolean" + }, + "projection": { + "description": "The 3D camera's projection; toggle switches between the two.", + "enum": [ + "perspective", + "orthographic", + "toggle" + ], + "type": "string" + }, "section": { "additionalProperties": false, - "description": "Design tab: the section view, a horizontal cut that hides half of the model to show inside it, as the toolbar's Section View and Flip set it.", + "description": "The section view, a cut that hides part of the model to show inside it. With tab design, the Design view's horizontal cut, as its toolbar's Section View and Flip set it, at z, keeping one half. Without it, the section view of Prepare and the Preview, on alone, as a right click on its toolbar button turns it on and off.", "properties": { "keep": { "description": "The half that stays: lower (the default) or upper.", @@ -4688,18 +6219,20 @@ ], "type": "object" }, + "sidebar_collapsed": { + "description": "Collapse (true) or expand (false) the sidebar of Prepare and the Preview, as its collapse button does.", + "type": "boolean" + }, + "sidebar_width": { + "description": "The sidebar's width in pixels, as a drag of its edge sets it, or \"default\", its width in the default window layout. A sidebar floating in a window of its own is sized with window_set.", + "minimum": 1, + "type": [ + "integer", + "string" + ] + }, "tab": { - "description": "Main window tab.", - "enum": [ - "home", - "design", - "prepare", - "preview", - "device", - "multi_device", - "project", - "calibration" - ], + "description": "Main window tab: home, design, prepare, preview, device, multi_device, project, calibration, or the id of another page of the window (monitor_web, the web Device page where the app shows one, or a plugin's page).", "type": "string" }, "time_mode": { @@ -4732,6 +6265,10 @@ ], "type": "string" }, + "wireframe": { + "description": "The objects' wireframe, as the 3D view's own menu sets it.", + "type": "boolean" + }, "world_axes": { "description": "Design tab: show the world axis triad (key A).", "type": "boolean" @@ -4744,20 +6281,472 @@ }, "type": "object" }, - "key": "set_view", + "key": "view_set", "listed": true, "open_world": false, "operations": [ "show_layer_range" ], "read_only": false, + "tiles": [ + { + "args": { + "camera": "top" + }, + "description": "Turn the camera of the view shown, the Design tab's too, to the top view.", + "group": "View", + "icon": "", + "key": "view_top", + "title": "View: Top" + }, + { + "args": { + "camera": "bottom" + }, + "description": "Turn the camera of the view shown, the Design tab's too, to the bottom view.", + "group": "View", + "icon": "", + "key": "view_bottom", + "title": "View: Bottom" + }, + { + "args": { + "camera": "front" + }, + "description": "Turn the camera of the view shown, the Design tab's too, to the front view.", + "group": "View", + "icon": "", + "key": "view_front", + "title": "View: Front" + }, + { + "args": { + "camera": "rear" + }, + "description": "Turn the camera of the view shown, the Design tab's too, to the rear view.", + "group": "View", + "icon": "", + "key": "view_rear", + "title": "View: Rear" + }, + { + "args": { + "camera": "left" + }, + "description": "Turn the camera of the view shown, the Design tab's too, to the left view.", + "group": "View", + "icon": "", + "key": "view_left", + "title": "View: Left" + }, + { + "args": { + "camera": "right" + }, + "description": "Turn the camera of the view shown, the Design tab's too, to the right view.", + "group": "View", + "icon": "", + "key": "view_right", + "title": "View: Right" + }, + { + "args": { + "camera": "iso" + }, + "description": "Turn the camera of the view shown, the Design tab's too, to the iso view.", + "group": "View", + "icon": "", + "key": "view_iso", + "title": "View: Isometric" + }, + { + "args": { + "camera": "default" + }, + "description": "Turn the camera of the view shown to the default view and fit the plate; on the Design tab, its Home view.", + "group": "View", + "icon": "", + "key": "view_default", + "title": "View: Default" + }, + { + "args": { + "camera": "fit_bed" + }, + "description": "Fit the build plate in the 3D view shown; refused on the Design tab, which has no bed to fit.", + "group": "View", + "icon": "", + "key": "view_fit_bed", + "title": "Fit Bed to View" + }, + { + "args": { + "projection": "toggle" + }, + "description": "Switch the 3D camera between perspective and orthographic.", + "group": "View", + "icon": "", + "key": "view_toggle_perspective", + "title": "Toggle Perspective" + }, + { + "args": { + "layout": "default" + }, + "description": "Restore the default window layout.", + "group": "View", + "icon": "toolbar_reset", + "key": "reset_window_layout", + "title": "Reset Window Layout" + }, + { + "args": {}, + "description": "Switch to a main window tab.", + "group": "Commands", + "icon": "", + "input": "tab", + "key": "go_to_tab", + "title": "Go to tab..." + }, + { + "args": {}, + "description": "Show the Preview tab at a layer chosen as a percentage of the layer range; an error while the Preview has no layers (slice first).", + "group": "Commands", + "icon": "height_range_layer", + "input": "percent", + "input_arg": "layer_percent", + "key": "go_to_layer", + "title": "Go to layer (percent)" + } + ], "title": "Set up the view" }, { "completion": "immediate", - "description": "Replay a list of tool calls in order and report each step: {orca_replay_version:\"0.1.0\", name, vars, steps:[{tool, args, expect, optional, await, save_as, timeout_s}]}, JSON with comments. Strings may use ${replay_dir}, ${out_dir}, ${env:NAME}, ${vars.NAME} and ${jobs.NAME}. A step that returns a job is awaited unless await:false, which stores the job under save_as so later steps can answer the dialog it opened. expect maps a JSON pointer into the step's result to matchers (eq ne gt ge lt le contains regex exists empty); the first failed step or expectation stops the run unless the step is optional. Writes result.json to out_dir (default: the replay file's name with .out, beside it; for an inline replay, replay- in the session's output folder). Reply: passed, steps, failed_step, out_dir and result_file. auto_answer_dialogs rules a replay registers end with it. export_replay turns this session into one.", + "description": "Open one of OrcaSlicer's windows or dialogs for a person, as its menu row does: preferences, the Preferences dialog, with tab, and key on it, on that tab with that preference's control scrolled into view and focused (its controls are named after their preference keys: preferences_get reads them and preferences_set writes those it does not refuse, and widget_set_value {\"target\": {\"name\": key, \"within\": \"Preferences\"}} changes one through the dialog); plugins, the Plugins window; action_replay, the Action Replay window, where a person replays a replay file (agents run one with replay_run); preset_bundle, the preset bundle manager; keyboard_shortcuts; setup_wizard; network_test; troubleshoot, the troubleshooting center; tip_of_the_day; about. A modal one replies blocked_by_dialog.", "destructive": false, - "group": "core", + "group": "View and windows", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "key": { + "description": "preferences, with tab: a preference on that tab, e.g. auto_arrange on behaviour: its control is scrolled into view and focused.", + "type": "string" + }, + "tab": { + "description": "preferences: the tab to show.", + "enum": [ + "general", + "files", + "behaviour", + "control", + "graphics", + "online", + "developer" + ], + "type": "string" + }, + "window": { + "description": "The window.", + "enum": [ + "preferences", + "plugins", + "action_replay", + "preset_bundle", + "keyboard_shortcuts", + "setup_wizard", + "network_test", + "troubleshoot", + "tip_of_the_day", + "about" + ], + "type": "string" + } + }, + "required": [ + "window" + ], + "type": "object" + }, + "key": "window_open", + "listed": true, + "open_world": false, + "operations": [], + "read_only": false, + "tiles": [ + { + "args": { + "window": "preferences" + }, + "description": "Open the Preferences dialog. window_open with a tab, and a key on it, opens it on that tab with that preference's control scrolled into view and focused (shown on its own tab).", + "group": "Commands", + "icon": "cog", + "key": "open_preferences", + "title": "Preferences" + }, + { + "args": { + "window": "plugins" + }, + "description": "Open the plugins dialog.", + "group": "Plugins", + "icon": "", + "key": "open_plugins", + "title": "Open Plugins" + }, + { + "args": { + "window": "action_replay" + }, + "description": "Open the Action Replay window, where a person opens a replay file, reads its steps and replays them. Agents run replays with the replay_run tool instead.", + "group": "Commands", + "icon": "loop", + "key": "open_action_replay", + "title": "Action Replay" + }, + { + "args": { + "window": "preset_bundle" + }, + "description": "Open the preset bundle manager.", + "group": "Presets", + "icon": "menu_edit_preset", + "key": "preset_bundle", + "title": "Open Preset Bundle" + }, + { + "args": { + "window": "keyboard_shortcuts" + }, + "description": "Show the keyboard shortcuts dialog.", + "group": "Help", + "icon": "", + "key": "help_keyboard_shortcuts", + "title": "Keyboard Shortcuts" + }, + { + "args": { + "window": "setup_wizard" + }, + "description": "Open the setup wizard.", + "group": "Help", + "icon": "", + "key": "help_setup_wizard", + "title": "Setup Wizard" + }, + { + "args": { + "window": "network_test" + }, + "description": "Open the network test dialog.", + "group": "Help", + "icon": "", + "key": "help_network_test", + "title": "Open Network Test" + }, + { + "args": { + "window": "troubleshoot" + }, + "description": "Open the troubleshooting center.", + "group": "Help", + "icon": "", + "key": "help_troubleshoot", + "title": "Troubleshoot Center" + }, + { + "args": { + "window": "tip_of_the_day" + }, + "description": "Show a tip of the day.", + "group": "Help", + "icon": "info", + "key": "help_tip_of_the_day", + "title": "Show Tip of the Day" + }, + { + "args": { + "window": "about" + }, + "description": "Show the About dialog.", + "group": "Help", + "icon": "OrcaSlicer_gradient_circle", + "key": "help_about", + "title": "About OrcaSlicer" + } + ], + "title": "Open a window" + }, + { + "completion": "immediate", + "description": "List OrcaSlicer's open windows: the main window, then the windows that don't block the app (Plugins, an object's settings, a dock panel floating on its own), then the modal dialogs in the order they opened, the topmost last. A window's ref goes to window_screenshot as target to capture that window, to widget_list as target to list it alone, and to keyboard_press as target; its title is the within of locators for its widgets.\nReply: each window's title, kind (main, window, dialog, or panel: a dock panel floating on its own), modal, ref, web (it shows a web page), x and y on screen (not on Wayland, which doesn't say), width and height, state (normal, maximized or minimized) and resizable (it has a resize border); window_set changes them.\nA native dialog (a message box, a file picker) has native: true and no ref: dialog_answer answers it. hidden: true marks the person's own windows (Action Replay, the Run Script panel and their prompts, the Python scripts setting), which no tool reaches and screenshots leave out.", + "destructive": false, + "group": "View and windows", + "guard": "inspect", + "idempotent": true, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "limit": { + "description": "Default 100.", + "maximum": 200, + "minimum": 1, + "type": "integer" + }, + "offset": { + "minimum": 0, + "type": "integer" + } + }, + "type": "object" + }, + "key": "window_list", + "listed": true, + "open_world": false, + "operations": [], + "read_only": true, + "title": "List the windows" + }, + { + "completion": "immediate", + "description": "Size, move, maximize, minimize or raise a window: the main window (default), the topmost modal dialog, or one window_list lists, also while a modal dialog is open. Size the main window before view_set fits the camera and before recording_start, as a recording keeps its first frame's size. size and position are in the units window_list reports, whose x/y and width/height are read as position and size too. A size or position restores a maximized or minimized window first. A window takes only the states its title bar offers; a modal dialog never minimizes. A refused call changes nothing. Replies once the window holds still and the 3D view has drawn at its new size (3 s at most): title, kind, ref, size, position, state, resizable, scale (screenshot pixels per window unit), display (its work area), active with raise, and adjusted with a note: what the OS or a size limit changed.", + "destructive": false, + "group": "View and windows", + "guard": "recover", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "position": { + "description": "[x, y] of the window's top-left corner on screen; not on Wayland.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "raise": { + "description": "Bring the window in front of the app's other windows; active in the reply says whether it became the active one.", + "type": "boolean" + }, + "size": { + "description": "[width, height], held to the window's minimum and maximum size.", + "items": { + "type": "integer" + }, + "type": "array" + }, + "state": { + "description": "normal restores a maximized or minimized window; maximized and minimized take no size or position.", + "enum": [ + "normal", + "maximized", + "minimized" + ], + "type": "string" + }, + "target": { + "description": "main (default), dialog (the topmost modal dialog), or a window's ref or locator from window_list; a widget's ref or locator picks the window it is in.", + "type": [ + "string", + "object" + ] + } + }, + "type": "object" + }, + "key": "window_set", + "listed": true, + "open_world": false, + "operations": [], + "read_only": false, + "title": "Size, move or raise a window" + }, + { + "completion": "immediate", + "description": "Capture what OrcaSlicer shows and return it as an image, downscaled to max_dim on the long edge (default 1280), plus the full-size PNG written to save_path (or the session's output folder). target: \"main\" (the main window), \"canvas\" (the visible 3D view exactly as rendered: scene, toolpaths, toolbars, ImGui panels; on the Design tab its view), \"dialog\" (the topmost modal dialog), or a ref: a window's from window_list (one that is not modal, say), or a widget's from widget_list, cropped to that widget (a page element's ref captures its whole web view). The result says when parts may differ from the screen (approximate). Point the view first with view_set.", + "destructive": false, + "group": "Recordings, replays and scripts", + "guard": "inspect", + "idempotent": true, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "include_image": { + "description": "Return the image itself (default true); false returns only the path.", + "type": "boolean" + }, + "max_dim": { + "description": "Long edge of the returned image.", + "maximum": 2000, + "minimum": 256, + "type": "integer" + }, + "overwrite": { + "description": "Replace an existing save_path.", + "type": "boolean" + }, + "save_path": { + "description": "Absolute .png path for the full-size image.", + "type": "string" + }, + "target": { + "description": "main (default), canvas, dialog, or a widget's ref or locator from widget_list.", + "type": [ + "string", + "object" + ] + } + }, + "type": "object" + }, + "key": "window_screenshot", + "listed": true, + "open_world": false, + "operations": [], + "read_only": true, + "title": "Take a screenshot" + }, + { + "completion": "immediate", + "description": "Save a PNG of the main window in the folder Start Recording saves in (the person's Downloads unless they chose another) and show the person a notification naming it; the reply has its path. Agents use the window_screenshot tool, which returns the image.", + "destructive": false, + "group": "Recordings, replays and scripts", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": {}, + "type": "object" + }, + "key": "window_save_screenshot", + "listed": false, + "open_world": false, + "operations": [], + "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Save a PNG of the main window in the folder Start Recording saves in (the person's Downloads unless they chose another) and show the person a notification naming it; the reply has its path. Agents use the window_screenshot tool, which returns the image.", + "group": "Commands", + "icon": "screenshot", + "key": "take_screenshot", + "title": "Take Screenshot" + } + ], + "title": "Take Screenshot" + }, + { + "completion": "immediate", + "description": "Replay a list of tool calls in order and report each step: {orca_replay_version:\"0.2.0\", name, vars, steps:[{tool, args, expect, optional, await, save_as, timeout_s}]}, JSON with comments. Strings may use ${replay_dir}, ${out_dir}, ${env:NAME}, ${vars.NAME} and ${jobs.NAME}. A step that returns a job is awaited unless await:false, which stores the job under save_as so later steps can answer the dialog it opened. expect maps a JSON pointer into the step's result to matchers (eq ne gt ge lt le contains regex exists empty); the first failed step or expectation stops the run unless the step is optional. Writes result.json to out_dir (default: the replay file's name with .out, beside it; for an inline replay, replay- in the session's output folder). Reply: passed, steps, failed_step, out_dir and result_file. dialog_auto_answer rules a replay registers end with it. replay_export turns this session into one.", + "destructive": false, + "group": "Recordings, replays and scripts", "guard": "mutate", "idempotent": false, "in_palette": false, @@ -4786,7 +6775,7 @@ }, "type": "object" }, - "key": "run_replay", + "key": "replay_run", "listed": true, "open_world": true, "operations": [], @@ -4795,9 +6784,9 @@ }, { "completion": "immediate", - "description": "Turn the calls this session made into a replay that run_replay runs: mutating calls, wait, screenshot and the recording tools, in order, with refs replaced by locators, job replies replayed with await:false, and screenshot and recording paths moved under ${out_dir}. Calls that failed, at once or as a job later, are left out (a run_script that raised or timed out replied, so it stays); so is a call whose job is still running (unless it waits on a dialog), which left_out_running lists as {tool, job}. Reply: the replay, which with path is also written there. clear:true then forgets the calls made so far.", + "description": "Turn the calls this session made into a replay that replay_run runs: mutating calls, app_wait, window_screenshot and the recording tools, in order, with refs replaced by locators, job replies replayed with await:false, and window_screenshot and recording paths moved under ${out_dir}. Calls that failed, at once or as a job later, are left out (a script_run that raised or timed out replied, so it stays); so is a call whose job is still running (unless it waits on a dialog), which left_out_running lists as {tool, job}. Reply: the replay, which with path is also written there. clear:true then forgets the calls made so far.", "destructive": false, - "group": "core", + "group": "Recordings, replays and scripts", "guard": "inspect", "idempotent": false, "in_palette": false, @@ -4823,7 +6812,7 @@ }, "type": "object" }, - "key": "export_replay", + "key": "replay_export", "listed": true, "open_world": false, "operations": [], @@ -4832,9 +6821,9 @@ }, { "completion": "immediate", - "description": "Run Python code inside OrcaSlicer as its main program (__name__ == \"__main__\") against orca.host, the whole plugin API (search_python_api searches it): read objects, meshes and settings, compute, use orca.host.ui and the preset API, and call these same tools, with their guards and undo, through orca.host.tools.call(name, args). Mesh and matrix arrays need numpy, which search_python_api says is installed or not; a file run's PEP 723 block can install it. The code runs on a worker thread, where calls documented as UI thread only raise RuntimeError. The run ends once its code and the non-daemon threads and pool tasks it started are done; its windows close with it. `args` holds the args you pass; set `result` to a JSON value to return it; print() output comes back as output. Reply: {status: finished | raised | cancelled | timed_out, result, output, traceback?, message?}; a script that raised changed what it changed before. The code's own file access is held to OrcaSlicer's folders (its data folder, and read only its resources folder and, for a file run, the file's folder), and it starts no programs or threads and reaches no network: such an access raises PermissionError, unless a person has let Python scripts run unrestricted in Preferences (get_app_state.python.scripts_unrestricted), when the threads and pool tasks it starts call the tools too while the run lasts; the tools it calls work as they do for you. Recorded by export_replay as one step with its code, which a replay runs again against the project as it is then.", + "description": "Run Python code inside OrcaSlicer as its main program (__name__ == \"__main__\") against orca.host, the whole plugin API (script_search_api searches it): read objects, meshes and settings, compute, use orca.host.ui and the preset API, and call these same tools, with their guards and undo, through orca.host.tools.call(name, args). Mesh and matrix arrays need numpy, which script_search_api says is installed or not; a file run's PEP 723 block can install it. The code runs on a worker thread, where calls documented as UI thread only raise RuntimeError. The run ends once its code and the non-daemon threads and pool tasks it started are done; its windows close with it. `args` holds the args you pass; set `result` to a JSON value to return it; print() output comes back as output. Reply: {status: finished | raised | cancelled | timed_out, result, output, traceback?, message?}; a script that raised changed what it changed before. The code's own file access is held to OrcaSlicer's folders (its data folder, and read only its resources folder and, for a file run, the file's folder), and it starts no programs or threads and reaches no network: such an access raises PermissionError, unless a person has let Python scripts run unrestricted in Preferences (app_state.python.scripts_unrestricted), when the threads and pool tasks it starts call the tools too while the run lasts; the tools it calls work as they do for you. Recorded by replay_export as one step with its code, which a replay runs again against the project as it is then.", "destructive": false, - "group": "core", + "group": "Recordings, replays and scripts", "guard": "mutate", "idempotent": false, "in_palette": false, @@ -4850,7 +6839,7 @@ "type": "string" }, "filename": { - "description": "The name tracebacks show for the code (default ). An existing file's path makes it a file run, as `python file.py` runs it: __file__, sys.argv, imports from its folder and its PEP 723 dependencies; any other name only names it. What runs is still `code`: pass the file's text there.", + "description": "The name tracebacks show for the code (default ). An existing file's path makes it a file run, as `python file.py` runs it: __file__, sys.argv, imports from its folder and its PEP 723 dependencies; any other name only names it. What runs is still `code`: pass the file's text there.", "type": "string" }, "timeout_s": { @@ -4865,7 +6854,7 @@ ], "type": "object" }, - "key": "run_script", + "key": "script_run", "listed": true, "open_world": true, "operations": [], @@ -4874,9 +6863,9 @@ }, { "completion": "immediate", - "description": "Search orca, the Python API of run_script scripts and plugins, in the running build: orca.host (the project's model and meshes, presets and their editors, slicing data, orca.host.ui windows and dialogs, orca.host.tools calling these tools) and the classes, events and pages plugins build on. Each entry has its kind, signature (a class's constructors) and documentation. A query ranks them, best match first; without one, the whole package is listed with each entry's first sentence. Page with offset. numpy says whether numpy is installed, which mesh and matrix arrays need.", + "description": "Search orca, the Python API of script_run scripts and plugins, in the running build: orca.host (the project's model and meshes, presets and their editors, slicing data, orca.host.ui windows and dialogs, orca.host.tools calling these tools) and the classes, events and pages plugins build on. Each entry has its kind, signature (a class's constructors) and documentation. A query ranks them, best match first; without one, the whole package is listed with each entry's first sentence. Page with offset. numpy says whether numpy is installed, which mesh and matrix arrays need.", "destructive": false, - "group": "core", + "group": "Recordings, replays and scripts", "guard": "inspect", "idempotent": true, "in_palette": false, @@ -4900,7 +6889,7 @@ }, "type": "object" }, - "key": "search_python_api", + "key": "script_search_api", "listed": true, "open_world": false, "operations": [], @@ -4909,12 +6898,42 @@ }, { "completion": "immediate", - "description": "Record a video of OrcaSlicer until stop_recording: the main window with any modal dialog on it (target main), or the 3D view shown (canvas). Frames are MJPEG in a Matroska (.mkv) file with their real timestamps. With captions, the tool call acting on the app shows as a caption at the bottom (secret setting values never show); with pointer, the pointer is highlighted, its clicks rippling. Capture takes at most about a third of the UI thread, so the frame rate drops where capturing is slow. One recording at a time: one a replay or script starts ends with it, a client's when the server is turned off. With encode, the stop_recording that reports it also encodes it to an MP4 beside it, as the Start Recording command does, and the .mkv is deleted once the MP4 is written unless keep_raw_video_file; encode_recording makes an MP4 of any recording later. Called with no arguments, it opens the Start Recording dialog instead, as the Start Recording command does (blocked_by_dialog): its controls are named after their settings for set_widget_value, answer_dialog \"Start recording\" starts the person's recording, which neither the end of a replay or script nor the server turning off ends, and the dialog remembers the settings; silent: true starts one here at once with the defaults.", + "description": "Show or hide the Run Script panel, where a person writes and runs Python scripts cell by cell. Agents run Python with the script_run tool instead.", "destructive": false, - "group": "Commands", + "group": "Recordings, replays and scripts", + "guard": "mutate", + "idempotent": false, + "in_palette": false, + "input_schema": { + "additionalProperties": false, + "properties": {}, + "type": "object" + }, + "key": "script_toggle_panel", + "listed": false, + "open_world": false, + "operations": [], + "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Show or hide the Run Script panel, where a person writes and runs Python scripts cell by cell. Agents run Python with the script_run tool instead.", + "group": "Commands", + "icon": "media_play", + "key": "toggle_run_script_panel", + "title": "Run Script" + } + ], + "title": "Run Script" + }, + { + "completion": "immediate", + "description": "Record a video of OrcaSlicer until recording_stop: the main window with any modal dialog on it (target main), or the 3D view shown (canvas). Frames are MJPEG in a Matroska (.mkv) file with their real timestamps. With captions, the tool call acting on the app shows as a caption at the bottom (secret setting values never show); with pointer, the pointer is highlighted, its clicks rippling. Capture takes at most about a third of the UI thread, so the frame rate drops where capturing is slow. One recording at a time: one a replay or script starts ends with it, a client's when the server is turned off. With encode, the recording_stop that reports it also encodes it to an MP4 beside it, as Start Recording does, and the .mkv is deleted once the MP4 is written unless keep_raw_video_file; recording_encode makes an MP4 of any recording later. Called with no arguments, it opens the Start Recording dialog instead, as Start Recording does (blocked_by_dialog): its controls are named after their settings for widget_set_value, dialog_answer \"Start recording\" starts the person's recording, which neither the end of a replay or script nor the server turning off ends, and the dialog remembers the settings; silent: true starts one here at once with the defaults.", + "destructive": false, + "group": "Recordings, replays and scripts", "guard": "inspect", "idempotent": false, - "in_palette": true, + "in_palette": false, "input_schema": { "additionalProperties": false, "properties": { @@ -5001,7 +7020,7 @@ "type": "string" }, "silent": { - "description": "true runs the command without asking, with the defaults of what the call leaves out. A call with no arguments does what a person's pick does.", + "description": "true runs the command without asking; what the call leaves out takes its default. A call with no arguments does what a person's pick does.", "enum": [ true ], @@ -5033,26 +7052,36 @@ }, "type": "object" }, - "key": "start_recording", + "key": "recording_start", "listed": true, "open_world": false, "operations": [], "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Runs recording_start with no arguments, as Start Recording does: the Start Recording dialog, whose Start recording starts the person's recording, which neither the end of a replay or script nor the server turning off ends.", + "group": "Commands", + "icon": "recording_start", + "key": "start_recording", + "title": "Start Recording" + } + ], "title": "Start Recording" }, { "completion": "immediate", - "description": "Stop the running recording. Call it with silent: true for the report: it waits for the file and returns it with its seconds, frames captured and written, frames dropped when encoding fell behind, failed when they could not be encoded, or skipped when the window could not be captured, the size, the mean UI-thread time a capture took (capture_ms), and why it ended. A recording that ended on its own (max_seconds, the replay or script that started it ended, a write error) is reported once by the next stop_recording. For a recording started with encode, it then starts the MP4 encode and returns it under encode: a job, whose wait {for: \"job\"} returns encode_recording's result, whose raw_video_file_deleted says whether the .mkv was deleted. Called with no arguments, it stops the recording as the Stop Recording command does, whoever started it: without waiting for its file, it shows the person a notification naming it and replies with its path; the next stop_recording with silent: true reports it as ended stopped_in_app.", + "description": "Stop the running recording. Call it with silent: true for the report: it waits for the file and returns it with its seconds, frames captured and written, frames dropped when encoding fell behind, failed when they could not be encoded, or skipped when the window could not be captured, the size, the mean UI-thread time a capture took (capture_ms), and why it ended. A recording that ended on its own (max_seconds, the replay or script that started it ended, a write error) is reported once by the next recording_stop. For a recording started with encode, it then starts the MP4 encode and returns it under encode: a job, whose app_wait {for: \"job\"} returns recording_encode's result, whose raw_video_file_deleted says whether the .mkv was deleted. Called with no arguments, it stops the recording as Stop Recording does, whoever started it: without waiting for its file, it shows the person a notification naming it and replies with its path; the next recording_stop with silent: true reports it as ended stopped_in_app.", "destructive": false, - "group": "Commands", + "group": "Recordings, replays and scripts", "guard": "inspect", "idempotent": false, - "in_palette": true, + "in_palette": false, "input_schema": { "additionalProperties": false, "properties": { "silent": { - "description": "true waits for the file and returns the report, and the encode job when the recording has one; a call with no arguments stops as the Stop Recording command does.", + "description": "true waits for the file and returns the report, and the encode job when the recording has one; a call with no arguments stops as Stop Recording does.", "enum": [ true ], @@ -5061,18 +7090,28 @@ }, "type": "object" }, - "key": "stop_recording", + "key": "recording_stop", "listed": true, "open_world": false, "operations": [], "read_only": false, + "tiles": [ + { + "args": {}, + "description": "Runs recording_stop with no arguments, as Stop Recording does: it stops the recording, whoever started it, and shows the person a notification naming its file.", + "group": "Commands", + "icon": "recording_stop", + "key": "stop_recording", + "title": "Stop Recording" + } + ], "title": "Stop Recording" }, { "completion": "immediate", - "description": "Encode a recording into an H.265 (or H.264) MP4 with the system ffmpeg (ORCA_FFMPEG, else ffmpeg on PATH; it needs libx265 or libx264), keeping its timing. Takes this session's last finished recording unless path names one, and writes beside it unless save_path says where. A long encode returns a job: wait for it, or cancel_job {job} stops it. Once the MP4 is written, it deletes the .mkv if this session recorded it, unless keep_raw_video_file; any other .mkv is kept. raw_video_file_deleted in the reply says which.", + "description": "Encode a recording into an H.265 (or H.264) MP4 with the system ffmpeg (ORCA_FFMPEG, else ffmpeg on PATH; it needs libx265 or libx264), keeping its timing. Takes this session's last finished recording unless path names one, and writes beside it unless save_path says where. A long encode returns a job: app_wait waits for it, or job_cancel {job} stops it. Once the MP4 is written, it deletes the .mkv if this session recorded it, unless keep_raw_video_file; any other .mkv is kept. raw_video_file_deleted in the reply says which.", "destructive": false, - "group": "ui", + "group": "Recordings, replays and scripts", "guard": "inspect", "idempotent": false, "in_palette": false, @@ -5137,7 +7176,7 @@ }, "type": "object" }, - "key": "encode_recording", + "key": "recording_encode", "listed": true, "open_world": false, "operations": [], @@ -5217,6 +7256,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_sketch", "idempotent": false, "in_palette": true, "input_schema": { @@ -5355,6 +7395,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_extrude", "idempotent": false, "in_palette": true, "input_schema": { @@ -5578,6 +7619,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_revolve", "idempotent": false, "in_palette": true, "input_schema": { @@ -5796,6 +7838,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_sweep", "idempotent": false, "in_palette": true, "input_schema": { @@ -5937,6 +7980,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_loft", "idempotent": false, "in_palette": true, "input_schema": { @@ -6125,6 +8169,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_thicken", "idempotent": false, "in_palette": true, "input_schema": { @@ -6270,6 +8315,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_rib", "idempotent": false, "in_palette": true, "input_schema": { @@ -6412,6 +8458,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_boolean", "idempotent": false, "in_palette": true, "input_schema": { @@ -6578,6 +8625,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_extrude", "idempotent": false, "in_palette": true, "input_schema": { @@ -6710,6 +8758,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_revolve", "idempotent": false, "in_palette": true, "input_schema": { @@ -6857,6 +8906,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_loft", "idempotent": false, "in_palette": true, "input_schema": { @@ -6978,6 +9028,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_surface", "idempotent": false, "in_palette": true, "input_schema": { @@ -7118,6 +9169,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_hole", "idempotent": false, "in_palette": true, "input_schema": { @@ -7355,6 +9407,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_thread", "idempotent": false, "in_palette": true, "input_schema": { @@ -7536,6 +9589,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_shell", "idempotent": false, "in_palette": true, "input_schema": { @@ -7668,6 +9722,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_cut", "idempotent": false, "in_palette": true, "input_schema": { @@ -7825,6 +9880,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_filletedge", "idempotent": false, "in_palette": true, "input_schema": { @@ -7925,6 +9981,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_chamfer", "idempotent": false, "in_palette": true, "input_schema": { @@ -8023,6 +10080,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_draft", "idempotent": false, "in_palette": true, "input_schema": { @@ -8164,6 +10222,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_offset", "idempotent": false, "in_palette": true, "input_schema": { @@ -8329,6 +10388,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_array", "idempotent": false, "in_palette": true, "input_schema": { @@ -8509,6 +10569,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_mirror", "idempotent": false, "in_palette": true, "input_schema": { @@ -8610,6 +10671,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_move", "idempotent": false, "in_palette": true, "input_schema": { @@ -8785,6 +10847,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_c_coincident", "idempotent": false, "in_palette": true, "input_schema": { @@ -8956,6 +11019,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_plane", "idempotent": false, "in_palette": true, "input_schema": { @@ -9171,6 +11235,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_line", "idempotent": false, "in_palette": true, "input_schema": { @@ -9293,6 +11358,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_point", "idempotent": false, "in_palette": true, "input_schema": { @@ -9396,6 +11462,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_thread", "idempotent": false, "in_palette": true, "input_schema": { @@ -9570,6 +11637,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_sketch", "idempotent": false, "in_palette": true, "input_schema": { @@ -9806,6 +11874,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "info", "idempotent": true, "in_palette": true, "input_schema": { @@ -9872,6 +11941,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_boolean", "idempotent": true, "in_palette": true, "input_schema": { @@ -9962,6 +12032,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_edit", "idempotent": false, "in_palette": true, "input_schema": { @@ -10016,6 +12087,7 @@ "destructive": false, "group": "Design", "guard": "mutate", + "icon": "rename_edit", "idempotent": false, "in_palette": true, "input_schema": { @@ -10080,6 +12152,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_delete", "idempotent": false, "in_palette": true, "input_schema": { @@ -10129,6 +12202,7 @@ "destructive": false, "group": "Design", "guard": "mutate", + "icon": "design_zoom", "idempotent": false, "in_palette": true, "input_schema": { @@ -10219,6 +12293,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_delete", "idempotent": false, "in_palette": true, "input_schema": { @@ -10309,6 +12384,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_delete", "idempotent": false, "in_palette": true, "input_schema": { @@ -10353,6 +12429,7 @@ "destructive": false, "group": "Design", "guard": "mutate", + "icon": "design_polygon", "idempotent": false, "in_palette": true, "input_schema": { @@ -10373,6 +12450,7 @@ "destructive": false, "group": "Design", "guard": "mutate", + "icon": "design_polygon", "idempotent": false, "in_palette": true, "input_schema": { @@ -10442,6 +12520,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_text", "idempotent": false, "in_palette": true, "input_schema": { @@ -10565,6 +12644,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_svg", "idempotent": false, "in_palette": true, "input_schema": { @@ -10701,6 +12781,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_offset", "idempotent": false, "in_palette": true, "input_schema": { @@ -10801,6 +12882,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_trim", "idempotent": false, "in_palette": true, "input_schema": { @@ -10888,6 +12970,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_filletedge", "idempotent": false, "in_palette": true, "input_schema": { @@ -10974,6 +13057,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_chamfer", "idempotent": false, "in_palette": true, "input_schema": { @@ -11146,6 +13230,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_mirror", "idempotent": false, "in_palette": true, "input_schema": { @@ -11292,6 +13377,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_dimension", "idempotent": false, "in_palette": true, "input_schema": { @@ -11488,6 +13574,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_constrain", "idempotent": false, "in_palette": true, "input_schema": { @@ -11573,6 +13660,7 @@ "destructive": false, "group": "Design", "guard": "mutate", + "icon": "design_constrain", "idempotent": false, "in_palette": true, "input_schema": { @@ -11646,6 +13734,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_construction", "idempotent": false, "in_palette": true, "input_schema": { @@ -11734,6 +13823,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_extend", "idempotent": false, "in_palette": true, "input_schema": { @@ -11859,6 +13949,7 @@ ], "group": "Design", "guard": "mutate", + "icon": "design_delete", "idempotent": false, "in_palette": true, "input_schema": { @@ -13515,7 +15606,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 (list_objects 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, name, parts: how many), bodies_sent, bodies_hidden, replaced.", "destructive": false, "examples": [ { @@ -13602,7 +15693,7 @@ }, "replace": { "default": [], - "description": "list_objects indices to delete in the same undo step, such as an earlier commit. Their settings, modifiers and paint go with them.", + "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" } }, @@ -15905,170 +17996,9 @@ }, { "completion": "immediate", - "description": "Search everything the Speed Dial can run: built-in commands (slice, export, views, object operations, plates, calibration wizards, help), recent projects, plugin scripts and pages. Each entry has an id for run_action, a description, the command's key for a built-in command, and, when it takes arguments, their input_schema. A query ranks them, best match first, as search_tools does; without one they are listed by group and title. include_settings also lists settings (each jumps to that setting in the sidebar; use get_settings / set_settings to read or change values).", + "description": "Describe what is on screen as an indented tree, one element per line with a ref to pass to widget_click, widget_set_value, keyboard_press and webview_run_javascript (a page element's to mouse_gesture too): the widgets of every shown window, the rows of lists, trees and tables, each shown popup after the window it opened from, the main menus, the 3D canvas's toolbar items and gizmos, each ImGui panel drawn in the last frame with its items and text, and the elements of each shown web page (dialogs, the setup wizard, sign-in, plugin windows) under its web view. With a modal dialog open, only the topmost dialog's pages are read. Refs go stale when their element goes away: call widget_list again then. Prefer action_run and the typed tools when one fits.\nA locator names an element without a ref, in any session (replay_export records them); index (0-based) picks one of several matches:\n- a widget: {label, class, name, within, index}, within being its window's title; a notebook page: {tab: \"General\", within}\n- a setting's field: {option: \"layer_height\"}\n- {menu: \"File>Export>Export G-code\"}, {gltoolbar: \"arrange\"}, {gizmo: \"Move\"}\n- an ImGui item: {imgui: \"label\", imgui_name?: \"name\", window?, canvas?, index?}, by its label, its name or both\n- a row of a list, tree, table or drop-down list: {row: \"Plate 1>Cube>Cylinder\", column?, within?, index?}, by its last labels; column names the cell to act on\n- a plate or one of its icons in the Prepare view: {plate_icon: \"lock\", plate: 0}, the icon being plate, delete, orient, arrange, lock, settings, name, move_to_front, filament_map or imex_mode\n- a web page's element: {web: \"Next\", kind?: \"button\", css?: \"#AcceptBtn\", within?, index?}, by the label widget_list lists (exactly, else ignoring case, else a part of it), its kind, a CSS selector (the id a line shows as name: name=#save is {css: \"#save\"}), or together. Without within it looks in the topmost dialog's pages while one is open, else in every shown page, and an action on it waits for its element up to 2 s short of the action's timeout_s (8 s by default), but at least 3 s or the whole of a shorter timeout_s.", "destructive": false, - "group": "ui", - "guard": "inspect", - "idempotent": true, - "in_palette": false, - "input_schema": { - "additionalProperties": false, - "properties": { - "group": { - "description": "Only this group, e.g. \"Object\", \"View\", \"Slice & Export\".", - "type": "string" - }, - "include_settings": { - "description": "Also list settings (thousands). Default false.", - "type": "boolean" - }, - "limit": { - "description": "Default 50.", - "maximum": 200, - "minimum": 1, - "type": "integer" - }, - "offset": { - "minimum": 0, - "type": "integer" - }, - "query": { - "description": "A few words, e.g. \"delete object\": each is matched at the start of the words of an action's id, title, group and description.", - "type": "string" - } - }, - "type": "object" - }, - "key": "search_actions", - "listed": true, - "open_world": false, - "operations": [], - "read_only": true, - "title": "Search Speed Dial actions" - }, - { - "completion": "immediate", - "description": "Run one action by the id search_actions returned (orca_command:view_front:orca, or the name inside it, view_front), with args, the command's arguments, when it takes some (its input_schema). A command that asks in a dialog asks when it is given no args, as a person's pick does, and runs without asking when given them: an absolute path skips a file dialog, and an output needs {\"path\": ..., \"overwrite\": true} to replace a file. Go to layer and Go to tab need their value ({\"percent\": 50}, {\"tab\": \"preview\"}). Actions that open a dialog return blocked_by_dialog; answer it with answer_dialog, or, for a native one it can't press (a file picker), register auto_answer_dialogs before the call. An export_gcode with a path completes when the file is written; an action that starts a background job (obj_arrange, obj_orient) when the job ends. An action that does nothing (no object selected) is an error. Some commands add what they did to the reply (the obj_order_by_* order, the object obj_assemble made). A command's action runs that command, as call_tool {tool: its command} does; the tile of a Design tab menu row folded into a command runs that command with the row's arguments, and takes no others. The other actions (plates, recent projects, plugin scripts and pages, settings) run only here.", - "destructive": false, - "group": "ui", - "guard": "mutate", - "idempotent": false, - "in_palette": false, - "input_schema": { - "additionalProperties": false, - "properties": { - "args": { - "description": "The command's arguments, as its input_schema gives them.", - "type": "object" - }, - "id": { - "description": "Action id from search_actions, or the name inside it.", - "type": "string" - } - }, - "required": [ - "id" - ], - "type": "object" - }, - "key": "run_action", - "listed": true, - "open_world": true, - "operations": [], - "read_only": false, - "title": "Run a Speed Dial action" - }, - { - "completion": "immediate", - "description": "List OrcaSlicer's open windows: the main window, then the windows that don't block the app (Plugins, an object's settings, a dock panel floating on its own), then the modal dialogs in the order they opened, the topmost last. A window's ref goes to screenshot as target to capture that window, to list_widgets as target to list it alone, and to press_keys as target; its title is the within of locators for its widgets.\nReply: each window's title, kind (main, window, dialog, or panel: a dock panel floating on its own), modal, ref, web (it shows a web page), x and y on screen (not on Wayland, which doesn't say), width and height, state (normal, maximized or minimized) and resizable (it has a resize border); set_window changes them.\nA native dialog (a message box, a file picker) has native: true and no ref: answer_dialog answers it. hidden: true marks the person's own windows (Action Replay, the Run Script panel and their prompts, the Python scripts setting), which no tool reaches and screenshots leave out.", - "destructive": false, - "group": "ui", - "guard": "inspect", - "idempotent": true, - "in_palette": false, - "input_schema": { - "additionalProperties": false, - "properties": { - "limit": { - "description": "Default 100.", - "maximum": 200, - "minimum": 1, - "type": "integer" - }, - "offset": { - "minimum": 0, - "type": "integer" - } - }, - "type": "object" - }, - "key": "list_windows", - "listed": true, - "open_world": false, - "operations": [], - "read_only": true, - "title": "List the windows" - }, - { - "completion": "immediate", - "description": "Size, move, maximize, minimize or raise a window: the main window (default), the topmost modal dialog, or one list_windows lists, also while a modal dialog is open. Size the main window before set_view fits the camera and before start_recording, as a recording keeps its first frame's size. size and position are in the units list_windows reports, whose x/y and width/height are read as position and size too. A size or position restores a maximized or minimized window first. A window takes only the states its title bar offers; a modal dialog never minimizes. A refused call changes nothing. Replies once the window holds still and the 3D view has drawn at its new size (3 s at most): title, kind, ref, size, position, state, resizable, scale (screenshot pixels per window unit), display (its work area), active with raise, and adjusted with a note: what the OS or a size limit changed.", - "destructive": false, - "group": "ui", - "guard": "recover", - "idempotent": false, - "in_palette": false, - "input_schema": { - "additionalProperties": false, - "properties": { - "position": { - "description": "[x, y] of the window's top-left corner on screen; not on Wayland.", - "items": { - "type": "integer" - }, - "type": "array" - }, - "raise": { - "description": "Bring the window in front of the app's other windows; active in the reply says whether it became the active one.", - "type": "boolean" - }, - "size": { - "description": "[width, height], held to the window's minimum and maximum size.", - "items": { - "type": "integer" - }, - "type": "array" - }, - "state": { - "description": "normal restores a maximized or minimized window; maximized and minimized take no size or position.", - "enum": [ - "normal", - "maximized", - "minimized" - ], - "type": "string" - }, - "target": { - "description": "main (default), dialog (the topmost modal dialog), or a window's ref or locator from list_windows; a widget's ref or locator picks the window it is in.", - "type": [ - "string", - "object" - ] - } - }, - "type": "object" - }, - "key": "set_window", - "listed": true, - "open_world": false, - "operations": [], - "read_only": false, - "title": "Size, move or raise a window" - }, - { - "completion": "immediate", - "description": "Describe what is on screen as an indented tree, one element per line with a ref to pass to click, set_widget_value, press_keys and run_javascript (a page element's to mouse_gesture too): the widgets of every shown window, the rows of lists, trees and tables, each shown popup after the window it opened from, the main menus, the 3D canvas's toolbar items and gizmos, each ImGui panel drawn in the last frame with its items and text, and the elements of each shown web page (dialogs, the setup wizard, sign-in, plugin windows) under its web view. With a modal dialog open, only the topmost dialog's pages are read. Refs go stale when their element goes away: call list_widgets again then. Prefer run_action and the typed tools when one fits.\nA locator names an element without a ref, in any session (export_replay records them); index (0-based) picks one of several matches:\n- a widget: {label, class, name, within, index}, within being its window's title; a notebook page: {tab: \"General\", within}\n- a setting's field: {option: \"layer_height\"}\n- {menu: \"File>Export>Export G-code\"}, {gltoolbar: \"arrange\"}, {gizmo: \"Move\"}\n- an ImGui item: {imgui: \"label\", imgui_name?: \"name\", window?, canvas?, index?}, by its label, its name or both\n- a row of a list, tree, table or drop-down list: {row: \"Plate 1>Cube>Cylinder\", column?, within?, index?}, by its last labels; column names the cell to act on\n- a plate or one of its icons in the Prepare view: {plate_icon: \"lock\", plate: 0}, the icon being plate, delete, orient, arrange, lock, settings, name, move_to_front, filament_map or imex_mode\n- a web page's element: {web: \"Next\", kind?: \"button\", css?: \"#AcceptBtn\", within?, index?}, by the label list_widgets lists (exactly, else ignoring case, else a part of it), its kind, a CSS selector (the id a line shows as name: name=#save is {css: \"#save\"}), or together. Without within it looks in the topmost dialog's pages while one is open, else in every shown page, and an action on it waits for its element up to 2 s short of the action's timeout_s (8 s by default), but at least 3 s or the whole of a shorter timeout_s.", - "destructive": false, - "group": "ui", + "group": "Driving the GUI", "guard": "inspect", "idempotent": true, "in_palette": false, @@ -16104,13 +18034,13 @@ "type": "string" }, "target": { - "description": "all (default), main, dialog (the topmost modal), popup, or a window's ref (list_windows).", + "description": "all (default), main, dialog (the topmost modal), popup, or a window's ref (window_list).", "type": "string" } }, "type": "object" }, - "key": "list_widgets", + "key": "widget_list", "listed": true, "open_world": false, "operations": [], @@ -16119,9 +18049,9 @@ }, { "completion": "immediate", - "description": "Click a GUI element as a person would. Menu items, buttons, checkboxes, toggles, radio buttons, toolbar items and gizmos are activated the way their owners expect: a gizmo opens and a second click closes it (Text on an object without text creates a text part: created). Other widgets and ImGui items get a mouse click once scrolled into view; with x/y, at that point of a 3D canvas or custom-drawn widget, in logical pixels from its top left. A row is selected as a click on its cell selects it (ctrl adds, shift extends; in the object list the named column acts, as Printable toggles), double activates it and a right click opens its menu; a drop-down list's row is picked. A plate icon does what it does in the Prepare view: lock replies locked, arrange and orient reply done once their job ends, settings and filament_map list the dialog they open (dialogs). A button, checkbox, toggle or radio button is activated so by a plain left click only: with modifiers, double or another button it gets a mouse click, which a native control ignores. A menu item runs whatever those options are, a toolbar item takes a left or a right click, and a gizmo a single left one. Modifiers reach the 3D canvas, the object list and handlers that read them. To click a point of the model, drag, scroll or hold a press, use mouse_gesture. A menu the click opens is never shown: the reply lists it as popup_menu, or popup_item runs one of its items (ran). A click that opens a dialog replies blocked_by_dialog.\nA web page's element gets the pointer and mouse events of a click at its centre (or x/y) once scrolled into view, refused when something else covers that point. The reply reads back checked, and has closed when the click closed its dialog (with dialogs, those still open under it, which still need an answer), navigated (with url) when it changed the page, or dialogs when it opened another. Otherwise page says what changed on the page within 300 ms: changed (false when its lines are as before), the list_widgets lines added and removed, partial when a plugin configuration frame could not be compared, and posted, how many messages the page sent OrcaSlicer.", + "description": "Click a GUI element as a person would. Menu items, buttons, checkboxes, toggles, radio buttons, toolbar items and gizmos are activated the way their owners expect: a gizmo opens and a second click closes it (Text on an object without text creates a text part: created). Other widgets and ImGui items get a mouse click once scrolled into view; with x/y, at that point of a 3D canvas or custom-drawn widget, in logical pixels from its top left. A row is selected as a click on its cell selects it (ctrl adds, shift extends; in the object list the named column acts, as Printable toggles), double activates it and a right click opens its menu; a drop-down list's row is picked. A plate icon does what it does in the Prepare view: lock replies locked, arrange and orient reply done once their job ends, settings and filament_map list the dialog they open (dialogs). A button, checkbox, toggle or radio button is activated so by a plain left click only: with modifiers, double or another button it gets a mouse click, which a native control ignores. A menu item runs whatever those options are, a toolbar item takes a left or a right click, and a gizmo a single left one. Modifiers reach the 3D canvas, the object list and handlers that read them. To click a point of the model, drag, scroll or hold a press, use mouse_gesture. A menu the click opens is never shown: the reply lists it as popup_menu, or popup_item runs one of its items (ran). A click that opens a dialog replies blocked_by_dialog.\nA web page's element gets the pointer and mouse events of a click at its centre (or x/y) once scrolled into view, refused when something else covers that point. The reply reads back checked, and has closed when the click closed its dialog (with dialogs, those still open under it, which still need an answer), navigated (with url) when it changed the page, or dialogs when it opened another. Otherwise page says what changed on the page within 300 ms: changed (false when its lines are as before), the widget_list lines added and removed, partial when a plugin configuration frame could not be compared, and posted, how many messages the page sent OrcaSlicer.", "destructive": false, - "group": "ui", + "group": "Driving the GUI", "guard": "recover", "idempotent": false, "in_palette": false, @@ -16142,7 +18072,7 @@ "type": "boolean" }, "modifiers": { - "description": "Modifier keys held during the input, as in press_keys: ctrl and cmd are both Command on macOS and Ctrl elsewhere; rawctrl is the macOS Control key.", + "description": "Modifier keys held during the input, as in keyboard_press: ctrl and cmd are both Command on macOS and Ctrl elsewhere; rawctrl is the macOS Control key.", "items": { "enum": [ "ctrl", @@ -16160,7 +18090,7 @@ "type": "string" }, "target": { - "description": "A ref list_widgets gave (\"w12\"), which later listings leave good (one refused as stale or unknown needs a new listing), or a locator, such as {label: \"OK\", within: \"Preferences\"} or {menu: \"File>Export>Export G-code\"}; list_widgets's description lists every kind.", + "description": "A ref widget_list gave (\"w12\"), which later listings leave good (one refused as stale or unknown needs a new listing), or a locator, such as {label: \"OK\", within: \"Preferences\"} or {menu: \"File>Export>Export G-code\"}; widget_list's description lists every kind.", "type": [ "string", "object" @@ -16186,7 +18116,7 @@ ], "type": "object" }, - "key": "click", + "key": "widget_click", "listed": true, "open_world": false, "operations": [], @@ -16195,9 +18125,9 @@ }, { "completion": "immediate", - "description": "Set a widget's value and send the events a person's edit would. Widgets: text fields (submit, the default, also presses Enter and leaves the field, which is when Orca's setting fields commit), spin controls, sliders, choice, combo and list boxes (by option text or index), checkboxes, toggles and a row's checkbox (true or false), and a radio button (an Orca radio box too) or a selector's option, as the dialog message shows them (*) / ( ) (true selects it; false on the selected one is refused, as only selecting another unselects it). ImGui items, by their kind, with the value read back: a field is typed into (a slider through the number field beside it, multiline text with \\n), a combo's option is picked by its text or 0-based index, and a checkbox, radio or toggle is clicked when it differs. A web page's fields, as typing would leave them: text, number, range, colour and date fields and editable text get the value with input and change events (submit then leaves the field; press_keys Return presses Enter), a select its option by text, value or index, and a checkbox or radio is clicked when it differs; the value is read back and page says what changed, as for click. File fields can't be set. For settings, set_settings is more reliable.", + "description": "Set a widget's value and send the events a person's edit would. Widgets: text fields (submit, the default, also presses Enter and leaves the field, which is when Orca's setting fields commit), spin controls, sliders, choice, combo and list boxes (by option text or index), checkboxes, toggles and a row's checkbox (true or false), and a radio button (an Orca radio box too) or a selector's option, as the dialog message shows them (*) / ( ) (true selects it; false on the selected one is refused, as only selecting another unselects it). ImGui items, by their kind, with the value read back: a field is typed into (a slider through the number field beside it, multiline text with \\n), a combo's option is picked by its text or 0-based index, and a checkbox, radio or toggle is clicked when it differs. A web page's fields, as typing would leave them: text, number, range, colour and date fields and editable text get the value with input and change events (submit then leaves the field; keyboard_press Return presses Enter), a select its option by text, value or index, and a checkbox or radio is clicked when it differs; the value is read back and page says what changed, as for widget_click. File fields can't be set. For settings, settings_set is more reliable.", "destructive": false, - "group": "ui", + "group": "Driving the GUI", "guard": "recover", "idempotent": false, "in_palette": false, @@ -16209,7 +18139,7 @@ "type": "boolean" }, "target": { - "description": "A ref list_widgets gave (\"w12\"), which later listings leave good (one refused as stale or unknown needs a new listing), or a locator, such as {label: \"OK\", within: \"Preferences\"} or {menu: \"File>Export>Export G-code\"}; list_widgets's description lists every kind.", + "description": "A ref widget_list gave (\"w12\"), which later listings leave good (one refused as stale or unknown needs a new listing), or a locator, such as {label: \"OK\", within: \"Preferences\"} or {menu: \"File>Export>Export G-code\"}; widget_list's description lists every kind.", "type": [ "string", "object" @@ -16236,7 +18166,7 @@ ], "type": "object" }, - "key": "set_widget_value", + "key": "widget_set_value", "listed": true, "open_world": false, "operations": [], @@ -16245,9 +18175,9 @@ }, { "completion": "immediate", - "description": "Send a key chord (\"Ctrl+S\", \"Escape\", \"Return\", \"Delete\", \"Shift+Tab\", \"Left\", \"F5\") and/or type text to a target or, without one, to the focused window (the topmost dialog while one is open, the shown 3D view when nothing has focus). As with a real key press, the shortcut handling of the target's panels and window sees the keys first. Typing reaches ImGui fields and key handlers; fill a widget's text field with set_widget_value. A menu the keys open is listed as popup_menu, or popup_item runs one of its items. Keys for a web page (its element, or without a target the focused web view or the topmost dialog's only page) go to the page's focused element with the browser's default actions: typing, Backspace/Delete, Enter (submits a form, activates a button), Space, Tab moving the focus, arrows stepping a select, range or radio group; page says what they changed, as for click.", + "description": "Send a key chord (\"Ctrl+S\", \"Escape\", \"Return\", \"Delete\", \"Shift+Tab\", \"Left\", \"F5\") and/or type text to a target or, without one, to the focused window (the topmost dialog while one is open, the shown 3D view when nothing has focus). As with a real key press, the shortcut handling of the target's panels and window sees the keys first. Typing reaches ImGui fields and key handlers; fill a widget's text field with widget_set_value. A menu the keys open is listed as popup_menu, or popup_item runs one of its items. Keys for a web page (its element, or without a target the focused web view or the topmost dialog's only page) go to the page's focused element with the browser's default actions: typing, Backspace/Delete, Enter (submits a form, activates a button), Space, Tab moving the focus, arrows stepping a select, range or radio group; page says what they changed, as for widget_click.", "destructive": false, - "group": "ui", + "group": "Driving the GUI", "guard": "recover", "idempotent": false, "in_palette": false, @@ -16263,7 +18193,7 @@ "type": "string" }, "target": { - "description": "A ref list_widgets gave (\"w12\"), which later listings leave good (one refused as stale or unknown needs a new listing), or a locator, such as {label: \"OK\", within: \"Preferences\"} or {menu: \"File>Export>Export G-code\"}; list_widgets's description lists every kind.", + "description": "A ref widget_list gave (\"w12\"), which later listings leave good (one refused as stale or unknown needs a new listing), or a locator, such as {label: \"OK\", within: \"Preferences\"} or {menu: \"File>Export>Export G-code\"}; widget_list's description lists every kind.", "type": [ "string", "object" @@ -16282,7 +18212,7 @@ }, "type": "object" }, - "key": "press_keys", + "key": "keyboard_press", "listed": true, "open_world": false, "operations": [], @@ -16291,9 +18221,9 @@ }, { "completion": "immediate", - "description": "Make a mouse gesture on a 3D canvas as a person would: move, down, up, click, drag or wheel. It starts at `at`, a point of the model, which is projected through the camera and by default checked to land on that part (check \"point\" only projects it), or at x/y, logical pixels from the canvas's top left. A drag goes through `waypoints` to `to`, `steps` moves per leg: on an object it moves the object, in a painting gizmo it paints from a press on the object being painted (waypoints zigzagging over an area paint all of it), and elsewhere it turns or pans the camera as this install's mouse settings say, so turn the camera with set_view camera or orbit instead. A wheel turns delta notches; positive zooms in (out with the Reverse mouse zoom preference on) or scrolls a panel up. Modifiers are held as keys for the gesture (shift picks points in Measure and erases in a painting gizmo). A down keeps its button and modifiers held, so moves drag, until an up or another gesture. Grabbers are set through the gizmo's panel fields or transform, not dragged. A menu a right click opens is listed as popup_menu, or popup_item (with click or up) runs one of its items. The reply's camera_moved says the gesture moved the camera, so earlier screenshots and pixels no longer match the view.\nWith target, the gesture is on a web page's element instead (a canvas such as the colour picker's spectrum, a slider, a sortable or scrolled list): x/y, to and waypoints are logical pixels from its top left, a drag keeps the pointer captured where the page asks for it, and a wheel scrolls what is under the pointer unless the page takes it; page says what the gesture changed there, as for click.", + "description": "Make a mouse gesture on a 3D canvas as a person would: move, down, up, click, drag or wheel. It starts at `at`, a point of the model, which is projected through the camera and by default checked to land on that part (check \"point\" only projects it), or at x/y, logical pixels from the canvas's top left. A drag goes through `waypoints` to `to`, `steps` moves per leg: on an object it moves the object, in a painting gizmo it paints from a press on the object being painted (waypoints zigzagging over an area paint all of it), and elsewhere it turns or pans the camera as this install's mouse settings say, so turn the camera with view_set camera or orbit instead. A wheel turns delta notches; positive zooms in (out with the Reverse mouse zoom preference on) or scrolls a panel up. Modifiers are held as keys for the gesture (shift picks points in Measure and erases in a painting gizmo). A down keeps its button and modifiers held, so moves drag, until an up or another gesture. Grabbers are set through the gizmo's panel fields or object_transform, not dragged. A menu a right click opens is listed as popup_menu, or popup_item (with click or up) runs one of its items. The reply's camera_moved says the gesture moved the camera, so earlier screenshots and pixels no longer match the view.\nWith target, the gesture is on a web page's element instead (a canvas such as the colour picker's spectrum, a slider, a sortable or scrolled list): x/y, to and waypoints are logical pixels from its top left, a drag keeps the pointer captured where the page asks for it, and a wheel scrolls what is under the pointer unless the page takes it; page says what the gesture changed there, as for widget_click.", "destructive": false, - "group": "ui", + "group": "Driving the GUI", "guard": "recover", "idempotent": false, "in_palette": false, @@ -16398,7 +18328,7 @@ "type": "boolean" }, "modifiers": { - "description": "Modifier keys held during the input, as in press_keys: ctrl and cmd are both Command on macOS and Ctrl elsewhere; rawctrl is the macOS Control key.", + "description": "Modifier keys held during the input, as in keyboard_press: ctrl and cmd are both Command on macOS and Ctrl elsewhere; rawctrl is the macOS Control key.", "items": { "enum": [ "ctrl", @@ -16477,9 +18407,9 @@ }, { "completion": "immediate", - "description": "Do what a file picker inside the open gizmo does, with a path instead of its dialog: svg_change loads another SVG file into the SVG part being edited, svg_save_as writes that part's SVG to a new file (an existing one only with overwrite), texture_import imports a height-map image into the texture library and puts it on Texture Displacement's active layer. To add an SVG part, use run_action add_primitive_svg with a path. Gizmos open with click {target: {gizmo: name}}, and their panels take set_widget_value / click on the ImGui items list_widgets lists.", + "description": "Do what a file picker inside the open gizmo does, with a path instead of its dialog: svg_change loads another SVG file into the SVG part being edited, svg_save_as writes that part's SVG to a new file (an existing one only with overwrite), texture_import imports a height-map image into the texture library and puts it on Texture Displacement's active layer. To add an SVG part, use object_add_svg with a path. Gizmos open with widget_click {target: {gizmo: name}}, and their panels take widget_set_value / widget_click on the ImGui items widget_list lists.", "destructive": false, - "group": "ui", + "group": "Driving the GUI", "guard": "mutate", "idempotent": false, "in_palette": false, @@ -16510,7 +18440,7 @@ ], "type": "object" }, - "key": "pick_gizmo_file", + "key": "gizmo_pick_file", "listed": true, "open_world": false, "operations": [], @@ -16519,9 +18449,9 @@ }, { "completion": "immediate", - "description": "Press a button of the topmost modal dialog: yes, no, ok, cancel, close, apply, a button's label, or a numeric id. A disabled button (enabled: false) is refused, the dialog's message showing what it still needs, and so is one on a page the dialog does not show, except a hidden cancel or close, which ends the dialog. On a dialog that is neither native nor a web dialog, a standard name or id it has no button for ends it with that answer too, without a handler running (pressed: false). The label of an option of a selector made of buttons (Orca's radio groups, tab bars and multi-switches, shown as (*) / ( ) in the message) selects that option and leaves the dialog open; set other radio buttons and switches with click or set_widget_value true, and notebook tabs with click. dialog.title, text the dialog's title contains, makes sure which dialog that is; it must be the topmost. Reply: dialog, button, pressed, and id, the wx id pressed or ended with, or web: true for a button on a web dialog's page, with what the page did as click reports it; closed: true when it closed, and dialogs, those still open. A native message box (native: true) is pressed through the OS, by one of the buttons get_app_state.dialogs lists for it; a file or folder picker can't be answered here, nor any native dialog on macOS (its buttons list is empty): register auto_answer_dialogs before opening them. A web dialog's buttons are on its page: a label is pressed there, waiting up to 3 s for it to show, so the page's own handler runs. With no such page button, or a page busy for those 3 s, cancel and close end the dialog, and ok, yes, no and apply are refused rather than skip the page's commit; page_buttons then lists the page's buttons.", + "description": "Press a button of the topmost modal dialog: yes, no, ok, cancel, close, apply, a button's label, or a numeric id. A disabled button (enabled: false) is refused, the dialog's message showing what it still needs, and so is one on a page the dialog does not show, except a hidden cancel or close, which ends the dialog. On a dialog that is neither native nor a web dialog, a standard name or id it has no button for ends it with that answer too, without a handler running (pressed: false). The label of an option of a selector made of buttons (Orca's radio groups, tab bars and multi-switches, shown as (*) / ( ) in the message) selects that option and leaves the dialog open; set other radio buttons and switches with widget_click or widget_set_value true, and notebook tabs with widget_click. dialog.title, text the dialog's title contains, makes sure which dialog that is; it must be the topmost. Reply: dialog, button, pressed, and id, the wx id pressed or ended with, or web: true for a button on a web dialog's page, with what the page did as widget_click reports it; closed: true when it closed, and dialogs, those still open. A native message box (native: true) is pressed through the OS, by one of the buttons app_state.dialogs lists for it; a file or folder picker can't be answered here, nor any native dialog on macOS (its buttons list is empty): register dialog_auto_answer before opening them. A web dialog's buttons are on its page: a label is pressed there, waiting up to 3 s for it to show, so the page's own handler runs. With no such page button, or a page busy for those 3 s, cancel and close end the dialog, and ok, yes, no and apply are refused rather than skip the page's commit; page_buttons then lists the page's buttons.", "destructive": false, - "group": "core", + "group": "Driving the GUI", "guard": "recover", "idempotent": false, "in_palette": false, @@ -16549,7 +18479,7 @@ ], "type": "object" }, - "key": "answer_dialog", + "key": "dialog_answer", "listed": true, "open_world": false, "operations": [], @@ -16558,9 +18488,9 @@ }, { "completion": "immediate", - "description": "Answer modal dialogs automatically when their title or message matches a rule's regex (case-insensitive). get_app_state.auto_answer_rules lists the rules in force. Called from a replay or script, the rules join those it set before and last until it ends, and a plugin's likewise until it unloads; an MCP client's replace the ones MCP clients set before and last until the MCP server stops, and an empty list clears them. Reply: scope (run, plugin or session), rules (uses counts a rule's answers) and answered_open_dialog. A native dialog returns the rule's button at once and never shows. A file or folder picker takes button ok with an absolute path and returns it without showing (on Linux such a rule cancels it); without a path a picker can only be cancelled, and a multi-select picker takes no path. A wx dialog is answered as answer_dialog does. A matching dialog already open is answered too (answered_open_dialog), so a prompt that shows around the same time, such as the restore prompt after startup, is caught either way. A web dialog is matched by its title: a button that names one of its shown wx buttons (by label, standard name or id) is pressed as for a wx dialog, any other on its page once it shows there, for up to 10 s after the page loads; past that, cancel and close end the dialog and any other button gives up.", + "description": "Answer modal dialogs automatically when their title or message matches a rule's regex (case-insensitive). app_state.auto_answer_rules lists the rules in force. Called from a replay or script, the rules join those it set before and last until it ends, and a plugin's likewise until it unloads; an MCP client's replace the ones MCP clients set before and last until the MCP server stops, and an empty list clears them. Reply: scope (run, plugin or session), rules (uses counts a rule's answers) and answered_open_dialog. A native dialog returns the rule's button at once and never shows. A file or folder picker takes button ok with an absolute path and returns it without showing (on Linux such a rule cancels it); without a path a picker can only be cancelled, and a multi-select picker takes no path. A wx dialog is answered as dialog_answer does. A matching dialog already open is answered too (answered_open_dialog), so a prompt that shows around the same time, such as the restore prompt after startup, is caught either way. A web dialog is matched by its title: a button that names one of its shown wx buttons (by label, standard name or id) is pressed as for a wx dialog, any other on its page once it shows there, for up to 10 s after the page loads; past that, cancel and close end the dialog and any other button gives up.", "destructive": false, - "group": "core", + "group": "Driving the GUI", "guard": "recover", "idempotent": true, "in_palette": false, @@ -16603,7 +18533,7 @@ ], "type": "object" }, - "key": "auto_answer_dialogs", + "key": "dialog_auto_answer", "listed": true, "open_world": false, "operations": [], @@ -16612,9 +18542,9 @@ }, { "completion": "immediate", - "description": "Evaluate JavaScript in one of OrcaSlicer's web views (Home, the device page, dialogs, plugin windows). Prefer list_widgets and the input tools (click, set_widget_value, press_keys, mouse_gesture), which see and drive pages as they do widgets. The code runs in the target's page: a web view's (kind webview in list_widgets), or a page element's, with the element as `el`; without a target, in the topmost dialog's web view, else in the only shown one. While a modal dialog is open, only its pages run code. Reply: result, the value of the last expression (JSON values come back parsed), and url; closed: true when the code closed its dialog, navigated: true when it changed the page, dialogs when it opened another. Messages the page posts to OrcaSlicer reach it once the code has returned. It runs through eval, which a page whose Content-Security-Policy forbids it may refuse (list_widgets and the input tools still work there).", + "description": "Evaluate JavaScript in one of OrcaSlicer's web views (Home, the device page, dialogs, plugin windows). Prefer widget_list and the input tools (widget_click, widget_set_value, keyboard_press, mouse_gesture), which see and drive pages as they do widgets. The code runs in the target's page: a web view's (kind webview in widget_list), or a page element's, with the element as `el`; without a target, in the topmost dialog's web view, else in the only shown one. While a modal dialog is open, only its pages run code. Reply: result, the value of the last expression (JSON values come back parsed), and url; closed: true when the code closed its dialog, navigated: true when it changed the page, dialogs when it opened another. Messages the page posts to OrcaSlicer reach it once the code has returned. It runs through eval, which a page whose Content-Security-Policy forbids it may refuse (widget_list and the input tools still work there).", "destructive": false, - "group": "ui", + "group": "Driving the GUI", "guard": "recover", "idempotent": false, "in_palette": false, @@ -16626,7 +18556,7 @@ "type": "string" }, "target": { - "description": "A web view (its ref; list_widgets lists it as kind webview) or an element of its page (its ref or a {web} / {css} locator), which the code gets as `el`. Default: the topmost dialog's web view, else the only one shown.", + "description": "A web view (its ref; widget_list lists it as kind webview) or an element of its page (its ref or a {web} / {css} locator), which the code gets as `el`. Default: the topmost dialog's web view, else the only one shown.", "type": [ "string", "object" @@ -16644,7 +18574,7 @@ ], "type": "object" }, - "key": "run_javascript", + "key": "webview_run_javascript", "listed": true, "open_world": true, "operations": [], diff --git a/tests/data/speed_dial_tile_calls.json b/tests/data/speed_dial_tile_calls.json new file mode 100644 index 0000000000..dde1674547 --- /dev/null +++ b/tests/data/speed_dial_tile_calls.json @@ -0,0 +1,826 @@ +[ + { + "key": "undo", + "command": "undo", + "args": {} + }, + { + "key": "redo", + "command": "redo", + "args": {} + }, + { + "key": "new_project", + "command": "project_new", + "args": {} + }, + { + "key": "load_project", + "command": "project_open", + "args": {} + }, + { + "key": "import_file", + "command": "project_import", + "args": {} + }, + { + "key": "import_zip_archive", + "command": "project_import", + "args": { + "archive": true + } + }, + { + "key": "save_project", + "command": "project_save", + "args": {} + }, + { + "key": "save_project_as", + "command": "project_save", + "args": { + "save_as": true + } + }, + { + "key": "export_gcode", + "command": "project_export", + "args": { + "format": "gcode" + } + }, + { + "key": "export_sliced_file", + "command": "project_export", + "args": { + "format": "sliced_3mf" + } + }, + { + "key": "export_all_sliced_file", + "command": "project_export", + "args": { + "format": "sliced_3mf", + "plates": "all" + } + }, + { + "key": "export_3mf", + "command": "project_export", + "args": { + "format": "3mf" + } + }, + { + "key": "export_stl", + "command": "project_export", + "args": { + "format": "stl" + } + }, + { + "key": "export_stl_multi", + "command": "project_export", + "args": { + "format": "stl", + "per_object": true + } + }, + { + "key": "export_drc_single", + "command": "project_export", + "args": { + "format": "drc" + } + }, + { + "key": "export_drc_multi", + "command": "project_export", + "args": { + "format": "drc", + "per_object": true + } + }, + { + "key": "export_toolpaths_obj", + "command": "project_export", + "args": { + "format": "toolpaths_obj" + } + }, + { + "key": "select_all", + "command": "object_select", + "args": { + "all": true + } + }, + { + "key": "deselect_all", + "command": "object_select", + "args": { + "none": true + } + }, + { + "key": "add_primitive_cube", + "command": "object_add_primitive", + "args": { + "shape": "cube" + } + }, + { + "key": "add_primitive_cylinder", + "command": "object_add_primitive", + "args": { + "shape": "cylinder" + } + }, + { + "key": "add_primitive_sphere", + "command": "object_add_primitive", + "args": { + "shape": "sphere" + } + }, + { + "key": "add_primitive_cone", + "command": "object_add_primitive", + "args": { + "shape": "cone" + } + }, + { + "key": "add_primitive_disc", + "command": "object_add_primitive", + "args": { + "shape": "disc" + } + }, + { + "key": "add_primitive_torus", + "command": "object_add_primitive", + "args": { + "shape": "torus" + } + }, + { + "key": "add_handy_orca_cube", + "command": "object_add_handy_model", + "args": { + "model": "orca_cube" + } + }, + { + "key": "add_handy_orcasliced_combo", + "command": "object_add_handy_model", + "args": { + "model": "orcasliced_combo" + } + }, + { + "key": "add_handy_orca_badge", + "command": "object_add_handy_model", + "args": { + "model": "orca_badge" + } + }, + { + "key": "add_handy_orca_tolerance_test", + "command": "object_add_handy_model", + "args": { + "model": "orca_tolerance_test" + } + }, + { + "key": "add_handy_3dbenchy", + "command": "object_add_handy_model", + "args": { + "model": "3dbenchy" + } + }, + { + "key": "add_handy_cali_cat", + "command": "object_add_handy_model", + "args": { + "model": "cali_cat" + } + }, + { + "key": "add_handy_autodesk_fdm_test", + "command": "object_add_handy_model", + "args": { + "model": "autodesk_fdm_test" + } + }, + { + "key": "add_handy_voron_cube", + "command": "object_add_handy_model", + "args": { + "model": "voron_cube" + } + }, + { + "key": "add_handy_stanford_bunny", + "command": "object_add_handy_model", + "args": { + "model": "stanford_bunny" + } + }, + { + "key": "add_handy_orca_string_hell", + "command": "object_add_handy_model", + "args": { + "model": "orca_string_hell" + } + }, + { + "key": "add_primitive_text", + "command": "object_add_text", + "args": {} + }, + { + "key": "add_primitive_svg", + "command": "object_add_svg", + "args": {} + }, + { + "key": "obj_delete", + "command": "object_delete", + "args": {} + }, + { + "key": "obj_delete_all", + "command": "object_delete", + "args": { + "all": true + } + }, + { + "key": "obj_rename", + "command": "object_rename", + "args": {} + }, + { + "key": "obj_set_instances", + "command": "object_set_instances", + "args": {} + }, + { + "key": "obj_instances_up", + "command": "object_set_instances", + "args": { + "delta": 1 + } + }, + { + "key": "obj_instances_down", + "command": "object_set_instances", + "args": { + "delta": -1 + } + }, + { + "key": "obj_instances_to_objects", + "command": "object_separate_instances", + "args": {} + }, + { + "key": "obj_split_objects", + "command": "object_split", + "args": { + "into": "objects" + } + }, + { + "key": "obj_split_parts", + "command": "object_split", + "args": { + "into": "parts" + } + }, + { + "key": "obj_assemble", + "command": "object_assemble", + "args": {} + }, + { + "key": "obj_type_part", + "command": "part_change_type", + "args": { + "type": "part" + } + }, + { + "key": "obj_type_negative", + "command": "part_change_type", + "args": { + "type": "negative" + } + }, + { + "key": "obj_type_modifier", + "command": "part_change_type", + "args": { + "type": "modifier" + } + }, + { + "key": "obj_type_support_blocker", + "command": "part_change_type", + "args": { + "type": "support_blocker" + } + }, + { + "key": "obj_type_support_enforcer", + "command": "part_change_type", + "args": { + "type": "support_enforcer" + } + }, + { + "key": "obj_type_precise_seam", + "command": "part_change_type", + "args": { + "type": "precise_seam" + } + }, + { + "key": "obj_order_by_name", + "command": "object_order", + "args": { + "by": "name" + } + }, + { + "key": "obj_order_by_filament", + "command": "object_order", + "args": { + "by": "filament" + } + }, + { + "key": "obj_order_by_height", + "command": "object_order", + "args": { + "by": "height" + } + }, + { + "key": "obj_order_by_size", + "command": "object_order", + "args": { + "by": "size" + } + }, + { + "key": "obj_drop", + "command": "object_drop", + "args": {} + }, + { + "key": "obj_mirror_x", + "command": "object_mirror", + "args": { + "axis": "x" + } + }, + { + "key": "obj_mirror_y", + "command": "object_mirror", + "args": { + "axis": "y" + } + }, + { + "key": "obj_mirror_z", + "command": "object_mirror", + "args": { + "axis": "z" + } + }, + { + "key": "obj_center", + "command": "object_center", + "args": {} + }, + { + "key": "obj_fit_volume", + "command": "object_scale_to_fit", + "args": {} + }, + { + "key": "obj_arrange", + "command": "object_arrange", + "args": {} + }, + { + "key": "obj_orient", + "command": "object_auto_orient", + "args": {} + }, + { + "key": "plate_add", + "command": "plate_add", + "args": {} + }, + { + "key": "plate_delete", + "command": "plate_delete", + "args": {} + }, + { + "key": "plate_duplicate", + "command": "plate_duplicate", + "args": {} + }, + { + "key": "plate_rename", + "command": "plate_rename", + "args": {} + }, + { + "key": "plate_toggle_lock", + "command": "plate_lock", + "args": {} + }, + { + "key": "plate_goto", + "command": "plate_select", + "args": { + "plate": 0 + } + }, + { + "key": "import_configs", + "command": "preset_import", + "args": {} + }, + { + "key": "export_config", + "command": "preset_export", + "args": {} + }, + { + "key": "sync_presets", + "command": "preset_sync", + "args": {} + }, + { + "key": "mode_simple", + "command": "settings_set_mode", + "args": { + "mode": "simple" + } + }, + { + "key": "mode_advanced", + "command": "settings_set_mode", + "args": { + "mode": "advanced" + } + }, + { + "key": "mode_expert", + "command": "settings_set_mode", + "args": { + "mode": "expert" + } + }, + { + "key": "filament_add", + "command": "filament_add", + "args": {} + }, + { + "key": "filament_delete", + "command": "filament_delete", + "args": {} + }, + { + "key": "sync_ams", + "command": "filament_sync_ams", + "args": {} + }, + { + "key": "slice_and_preview", + "command": "plate_slice", + "args": { + "preview": true + } + }, + { + "key": "slice_all", + "command": "plate_slice", + "args": { + "plates": "all", + "preview": true + } + }, + { + "key": "calib_temperature", + "command": "calibration_generate_test", + "args": { + "test": "temperature" + } + }, + { + "key": "calib_flow_ratio", + "command": "calibration_generate_test", + "args": { + "test": "flow_ratio" + } + }, + { + "key": "calib_pressure_advance", + "command": "calibration_generate_test", + "args": { + "test": "pressure_advance" + } + }, + { + "key": "calib_retraction", + "command": "calibration_generate_test", + "args": { + "test": "retraction" + } + }, + { + "key": "calib_max_volumetric", + "command": "calibration_generate_test", + "args": { + "test": "max_volumetric" + } + }, + { + "key": "calib_vfa", + "command": "calibration_generate_test", + "args": { + "test": "vfa" + } + }, + { + "key": "calib_cornering", + "command": "calibration_generate_test", + "args": { + "test": "cornering" + } + }, + { + "key": "calib_input_shaping_freq", + "command": "calibration_generate_test", + "args": { + "test": "input_shaping_freq" + } + }, + { + "key": "calib_input_shaping_damp", + "command": "calibration_generate_test", + "args": { + "test": "input_shaping_damp" + } + }, + { + "key": "send_gcode", + "command": "printer_send", + "args": {} + }, + { + "key": "view_top", + "command": "view_set", + "args": { + "camera": "top" + } + }, + { + "key": "view_bottom", + "command": "view_set", + "args": { + "camera": "bottom" + } + }, + { + "key": "view_front", + "command": "view_set", + "args": { + "camera": "front" + } + }, + { + "key": "view_rear", + "command": "view_set", + "args": { + "camera": "rear" + } + }, + { + "key": "view_left", + "command": "view_set", + "args": { + "camera": "left" + } + }, + { + "key": "view_right", + "command": "view_set", + "args": { + "camera": "right" + } + }, + { + "key": "view_iso", + "command": "view_set", + "args": { + "camera": "iso" + } + }, + { + "key": "view_default", + "command": "view_set", + "args": { + "camera": "default" + } + }, + { + "key": "view_fit_bed", + "command": "view_set", + "args": { + "camera": "fit_bed" + } + }, + { + "key": "view_toggle_perspective", + "command": "view_set", + "args": { + "projection": "toggle" + } + }, + { + "key": "go_to_tab", + "command": "view_set", + "args": {}, + "input": "tab" + }, + { + "key": "go_to_layer", + "command": "view_set", + "args": {}, + "input": "percent", + "input_arg": "layer_percent" + }, + { + "key": "reset_window_layout", + "command": "view_set", + "args": { + "layout": "default" + } + }, + { + "key": "open_preferences", + "command": "window_open", + "args": { + "window": "preferences" + } + }, + { + "key": "open_plugins", + "command": "window_open", + "args": { + "window": "plugins" + } + }, + { + "key": "open_action_replay", + "command": "window_open", + "args": { + "window": "action_replay" + } + }, + { + "key": "preset_bundle", + "command": "window_open", + "args": { + "window": "preset_bundle" + } + }, + { + "key": "help_keyboard_shortcuts", + "command": "window_open", + "args": { + "window": "keyboard_shortcuts" + } + }, + { + "key": "help_setup_wizard", + "command": "window_open", + "args": { + "window": "setup_wizard" + } + }, + { + "key": "help_network_test", + "command": "window_open", + "args": { + "window": "network_test" + } + }, + { + "key": "help_troubleshoot", + "command": "window_open", + "args": { + "window": "troubleshoot" + } + }, + { + "key": "help_tip_of_the_day", + "command": "window_open", + "args": { + "window": "tip_of_the_day" + } + }, + { + "key": "help_about", + "command": "window_open", + "args": { + "window": "about" + } + }, + { + "key": "open_wiki", + "command": "app_open_web_page", + "args": { + "page": "wiki" + } + }, + { + "key": "open_youtube", + "command": "app_open_web_page", + "args": { + "page": "youtube" + } + }, + { + "key": "install_plugin", + "command": "app_open_web_page", + "args": { + "page": "plugin_hub" + } + }, + { + "key": "start_recording", + "command": "recording_start", + "args": {} + }, + { + "key": "stop_recording", + "command": "recording_stop", + "args": {} + }, + { + "key": "install_local_plugin", + "command": "plugin_install_local", + "args": {} + }, + { + "key": "refresh_plugins", + "command": "plugin_refresh", + "args": {} + }, + { + "key": "help_check_updates", + "command": "app_check_for_updates", + "args": {} + }, + { + "key": "help_open_config_folder", + "command": "app_show_config_folder", + "args": {} + }, + { + "key": "help_migrate_filament_presets", + "command": "preset_migrate_filaments", + "args": {} + }, + { + "key": "help_benchmark_3d_scene", + "command": "app_benchmark_3d_scene", + "args": {} + }, + { + "key": "take_screenshot", + "command": "window_save_screenshot", + "args": {} + }, + { + "key": "toggle_run_script_panel", + "command": "script_toggle_panel", + "args": {} + }, + { + "key": "toggle_developer_mode", + "command": "settings_toggle_developer_mode", + "args": {} + } +] \ No newline at end of file diff --git a/tests/data/speed_dial_tiles.json b/tests/data/speed_dial_tiles.json new file mode 100644 index 0000000000..a3f3897f91 --- /dev/null +++ b/tests/data/speed_dial_tiles.json @@ -0,0 +1,905 @@ +[ + { + "key": "slice_and_preview", + "title": "Slice and Preview", + "group": "Slice & Export", + "icon": "media_play", + "input": "" + }, + { + "key": "slice_all", + "title": "Slice All Plates", + "group": "Slice & Export", + "icon": "media_play", + "input": "" + }, + { + "key": "go_to_layer", + "title": "Go to layer (percent)", + "group": "Commands", + "icon": "height_range_layer", + "input": "percent" + }, + { + "key": "go_to_tab", + "title": "Go to tab...", + "group": "Commands", + "icon": "", + "input": "tab" + }, + { + "key": "load_project", + "title": "Load Project", + "group": "Commands", + "icon": "menu_open", + "input": "" + }, + { + "key": "save_project_as", + "title": "Save Project As", + "group": "Commands", + "icon": "menu_save", + "input": "" + }, + { + "key": "undo", + "title": "Undo", + "group": "Commands", + "icon": "menu_undo", + "input": "" + }, + { + "key": "redo", + "title": "Redo", + "group": "Commands", + "icon": "menu_redo", + "input": "" + }, + { + "key": "toggle_run_script_panel", + "title": "Run Script", + "group": "Commands", + "icon": "media_play", + "input": "" + }, + { + "key": "open_action_replay", + "title": "Action Replay", + "group": "Commands", + "icon": "loop", + "input": "" + }, + { + "key": "open_preferences", + "title": "Preferences", + "group": "Commands", + "icon": "cog", + "input": "" + }, + { + "key": "take_screenshot", + "title": "Take Screenshot", + "group": "Commands", + "icon": "screenshot", + "input": "" + }, + { + "key": "mode_simple", + "title": "Mode: Simple", + "group": "Mode", + "icon": "advanced", + "input": "" + }, + { + "key": "mode_advanced", + "title": "Mode: Advanced", + "group": "Mode", + "icon": "advanced", + "input": "" + }, + { + "key": "mode_expert", + "title": "Mode: Expert", + "group": "Mode", + "icon": "advanced", + "input": "" + }, + { + "key": "toggle_developer_mode", + "title": "Toggle Developer Mode", + "group": "Mode", + "icon": "advanced", + "input": "" + }, + { + "key": "export_gcode", + "title": "Export G-code", + "group": "Slice & Export", + "icon": "custom-gcode_gcode", + "input": "" + }, + { + "key": "export_stl", + "title": "Export STL", + "group": "Slice & Export", + "icon": "save", + "input": "" + }, + { + "key": "export_3mf", + "title": "Export 3MF", + "group": "Slice & Export", + "icon": "menu_save", + "input": "" + }, + { + "key": "export_sliced_file", + "title": "Export Sliced File", + "group": "Slice & Export", + "icon": "save", + "input": "" + }, + { + "key": "export_all_sliced_file", + "title": "Export All Sliced Files", + "group": "Slice & Export", + "icon": "save", + "input": "" + }, + { + "key": "send_gcode", + "title": "Send G-code to printer host", + "group": "Slice & Export", + "icon": "printer", + "input": "" + }, + { + "key": "calib_temperature", + "title": "Temperature Calibration", + "group": "Calibration", + "icon": "param_temperature", + "input": "" + }, + { + "key": "calib_max_volumetric", + "title": "Max Volumetric Speed Calibration", + "group": "Calibration", + "icon": "param_volumetric_speed", + "input": "" + }, + { + "key": "calib_pressure_advance", + "title": "Pressure Advance Calibration", + "group": "Calibration", + "icon": "param_flow_ratio_and_pressure_advance", + "input": "" + }, + { + "key": "calib_flow_ratio", + "title": "Flow Ratio Calibration", + "group": "Calibration", + "icon": "param_flow_ratio_and_pressure_advance", + "input": "" + }, + { + "key": "calib_retraction", + "title": "Retraction Calibration", + "group": "Calibration", + "icon": "param_retraction", + "input": "" + }, + { + "key": "calib_cornering", + "title": "Cornering Calibration", + "group": "Calibration", + "icon": "param_precision", + "input": "" + }, + { + "key": "calib_input_shaping_freq", + "title": "Input Shaping Frequency Calibration", + "group": "Calibration", + "icon": "param_resonance_avoidance", + "input": "" + }, + { + "key": "calib_input_shaping_damp", + "title": "Input Shaping Damping Calibration", + "group": "Calibration", + "icon": "param_resonance_avoidance", + "input": "" + }, + { + "key": "calib_vfa", + "title": "VFA Calibration", + "group": "Calibration", + "icon": "param_speed", + "input": "" + }, + { + "key": "view_top", + "title": "View: Top", + "group": "View", + "icon": "", + "input": "" + }, + { + "key": "view_bottom", + "title": "View: Bottom", + "group": "View", + "icon": "", + "input": "" + }, + { + "key": "view_front", + "title": "View: Front", + "group": "View", + "icon": "", + "input": "" + }, + { + "key": "view_rear", + "title": "View: Rear", + "group": "View", + "icon": "", + "input": "" + }, + { + "key": "view_left", + "title": "View: Left", + "group": "View", + "icon": "", + "input": "" + }, + { + "key": "view_right", + "title": "View: Right", + "group": "View", + "icon": "", + "input": "" + }, + { + "key": "view_iso", + "title": "View: Isometric", + "group": "View", + "icon": "", + "input": "" + }, + { + "key": "view_default", + "title": "View: Default", + "group": "View", + "icon": "", + "input": "" + }, + { + "key": "view_fit_bed", + "title": "Fit Bed to View", + "group": "View", + "icon": "", + "input": "" + }, + { + "key": "view_toggle_perspective", + "title": "Toggle Perspective", + "group": "View", + "icon": "", + "input": "" + }, + { + "key": "reset_window_layout", + "title": "Reset Window Layout", + "group": "View", + "icon": "toolbar_reset", + "input": "" + }, + { + "key": "obj_delete", + "title": "Delete Selected", + "group": "Object", + "icon": "delete", + "input": "" + }, + { + "key": "obj_delete_all", + "title": "Delete All Objects", + "group": "Object", + "icon": "delete", + "input": "" + }, + { + "key": "select_all", + "title": "Select All Objects", + "group": "Object", + "icon": "", + "input": "" + }, + { + "key": "deselect_all", + "title": "Deselect All", + "group": "Object", + "icon": "", + "input": "" + }, + { + "key": "obj_mirror_x", + "title": "Mirror X", + "group": "Object", + "icon": "menu_mirror_x", + "input": "" + }, + { + "key": "obj_mirror_y", + "title": "Mirror Y", + "group": "Object", + "icon": "menu_mirror_y", + "input": "" + }, + { + "key": "obj_mirror_z", + "title": "Mirror Z", + "group": "Object", + "icon": "menu_mirror_z", + "input": "" + }, + { + "key": "obj_split_objects", + "title": "Split to Objects", + "group": "Object", + "icon": "menu_split_objects", + "input": "" + }, + { + "key": "obj_split_parts", + "title": "Split to Parts", + "group": "Object", + "icon": "menu_split_parts", + "input": "" + }, + { + "key": "obj_center", + "title": "Center Selected on Plate", + "group": "Object", + "icon": "", + "input": "" + }, + { + "key": "obj_drop", + "title": "Drop to Bed", + "group": "Object", + "icon": "toolbar_flatten", + "input": "" + }, + { + "key": "obj_fit_volume", + "title": "Scale to Fit Print Volume", + "group": "Object", + "icon": "", + "input": "" + }, + { + "key": "obj_instances_up", + "title": "Increase Instances", + "group": "Object", + "icon": "instance_add", + "input": "" + }, + { + "key": "obj_instances_down", + "title": "Decrease Instances", + "group": "Object", + "icon": "instance_remove", + "input": "" + }, + { + "key": "obj_arrange", + "title": "Auto-Arrange", + "group": "Object", + "icon": "toolbar_arrange", + "input": "" + }, + { + "key": "obj_orient", + "title": "Auto-Orient", + "group": "Object", + "icon": "toolbar_orient", + "input": "" + }, + { + "key": "obj_type_part", + "title": "Change Type to Part", + "group": "Object", + "icon": "", + "input": "" + }, + { + "key": "obj_type_negative", + "title": "Change Type to Negative Part", + "group": "Object", + "icon": "", + "input": "" + }, + { + "key": "obj_type_modifier", + "title": "Change Type to Modifier", + "group": "Object", + "icon": "", + "input": "" + }, + { + "key": "obj_type_support_blocker", + "title": "Change Type to Support Blocker", + "group": "Object", + "icon": "", + "input": "" + }, + { + "key": "obj_type_support_enforcer", + "title": "Change Type to Support Enforcer", + "group": "Object", + "icon": "", + "input": "" + }, + { + "key": "obj_type_precise_seam", + "title": "Change Type to Precise Seam", + "group": "Object", + "icon": "", + "input": "" + }, + { + "key": "obj_rename", + "title": "Rename", + "group": "Object", + "icon": "", + "input": "" + }, + { + "key": "obj_set_instances", + "title": "Set Number of Instances", + "group": "Object", + "icon": "instance_add", + "input": "" + }, + { + "key": "obj_assemble", + "title": "Assemble", + "group": "Object", + "icon": "", + "input": "" + }, + { + "key": "obj_instances_to_objects", + "title": "Set as Individual Objects", + "group": "Object", + "icon": "", + "input": "" + }, + { + "key": "obj_order_by_name", + "title": "Order by Name", + "group": "Object", + "icon": "", + "input": "" + }, + { + "key": "obj_order_by_filament", + "title": "Order by Filament", + "group": "Object", + "icon": "", + "input": "" + }, + { + "key": "obj_order_by_height", + "title": "Order by Height", + "group": "Object", + "icon": "", + "input": "" + }, + { + "key": "obj_order_by_size", + "title": "Order by Size", + "group": "Object", + "icon": "", + "input": "" + }, + { + "key": "add_primitive_cube", + "title": "Cube", + "group": "Add Primitive", + "icon": "menu_obj_cube", + "input": "" + }, + { + "key": "add_primitive_cylinder", + "title": "Cylinder", + "group": "Add Primitive", + "icon": "menu_obj_cylinder", + "input": "" + }, + { + "key": "add_primitive_sphere", + "title": "Sphere", + "group": "Add Primitive", + "icon": "menu_obj_sphere", + "input": "" + }, + { + "key": "add_primitive_cone", + "title": "Cone", + "group": "Add Primitive", + "icon": "menu_obj_cone", + "input": "" + }, + { + "key": "add_primitive_disc", + "title": "Disc", + "group": "Add Primitive", + "icon": "menu_obj_disc", + "input": "" + }, + { + "key": "add_primitive_torus", + "title": "Torus", + "group": "Add Primitive", + "icon": "menu_obj_torus", + "input": "" + }, + { + "key": "add_primitive_text", + "title": "Text", + "group": "Add Primitive", + "icon": "menu_obj_text", + "input": "" + }, + { + "key": "add_primitive_svg", + "title": "SVG", + "group": "Add Primitive", + "icon": "menu_obj_svg", + "input": "" + }, + { + "key": "add_handy_orca_cube", + "title": "Orca Cube", + "group": "Add Handy models", + "icon": "", + "input": "" + }, + { + "key": "add_handy_orcasliced_combo", + "title": "OrcaSliced Combo", + "group": "Add Handy models", + "icon": "", + "input": "" + }, + { + "key": "add_handy_orca_badge", + "title": "Orca Badge", + "group": "Add Handy models", + "icon": "", + "input": "" + }, + { + "key": "add_handy_orca_tolerance_test", + "title": "Orca Tolerance Test", + "group": "Add Handy models", + "icon": "", + "input": "" + }, + { + "key": "add_handy_3dbenchy", + "title": "3DBenchy", + "group": "Add Handy models", + "icon": "", + "input": "" + }, + { + "key": "add_handy_cali_cat", + "title": "Cali Cat", + "group": "Add Handy models", + "icon": "", + "input": "" + }, + { + "key": "add_handy_autodesk_fdm_test", + "title": "Autodesk FDM Test", + "group": "Add Handy models", + "icon": "", + "input": "" + }, + { + "key": "add_handy_voron_cube", + "title": "Voron Cube", + "group": "Add Handy models", + "icon": "", + "input": "" + }, + { + "key": "add_handy_stanford_bunny", + "title": "Stanford Bunny", + "group": "Add Handy models", + "icon": "", + "input": "" + }, + { + "key": "add_handy_orca_string_hell", + "title": "Orca String Hell", + "group": "Add Handy models", + "icon": "", + "input": "" + }, + { + "key": "plate_add", + "title": "Add Plate", + "group": "Plate", + "icon": "toolbar_add_plate", + "input": "" + }, + { + "key": "plate_duplicate", + "title": "Duplicate Plate", + "group": "Plate", + "icon": "menu_copy", + "input": "" + }, + { + "key": "plate_delete", + "title": "Delete Plate", + "group": "Plate", + "icon": "delete", + "input": "" + }, + { + "key": "plate_rename", + "title": "Rename Plate", + "group": "Plate", + "icon": "plate_name_edit", + "input": "" + }, + { + "key": "plate_toggle_lock", + "title": "Toggle Plate Lock", + "group": "Plate", + "icon": "lock_normal", + "input": "" + }, + { + "key": "plate_goto", + "title": "Go to Plate", + "group": "Plate", + "icon": "go_next_plate", + "input": "" + }, + { + "key": "sync_ams", + "title": "Synchronize Filament List from AMS", + "group": "Printer", + "icon": "ams_fila_sync", + "input": "" + }, + { + "key": "filament_add", + "title": "Add Filament Slot", + "group": "Filament", + "icon": "add_filament", + "input": "" + }, + { + "key": "filament_delete", + "title": "Delete Filament Slot", + "group": "Filament", + "icon": "delete_filament", + "input": "" + }, + { + "key": "preset_bundle", + "title": "Open Preset Bundle", + "group": "Presets", + "icon": "menu_edit_preset", + "input": "" + }, + { + "key": "sync_presets", + "title": "Sync Presets", + "group": "Presets", + "icon": "printer_sync_ok", + "input": "" + }, + { + "key": "import_file", + "title": "Import 3MF/STL/STEP/SVG/OBJ/AMF", + "group": "Import", + "icon": "menu_open", + "input": "" + }, + { + "key": "import_zip_archive", + "title": "Import ZIP Archive", + "group": "Import", + "icon": "menu_open", + "input": "" + }, + { + "key": "import_configs", + "title": "Import Configs", + "group": "Import", + "icon": "menu_open", + "input": "" + }, + { + "key": "export_stl_multi", + "title": "Export All Objects as STLs", + "group": "Export", + "icon": "save", + "input": "" + }, + { + "key": "export_drc_single", + "title": "Export All Objects as DRC (one file)", + "group": "Export", + "icon": "save", + "input": "" + }, + { + "key": "export_drc_multi", + "title": "Export All Objects as DRCs", + "group": "Export", + "icon": "save", + "input": "" + }, + { + "key": "export_toolpaths_obj", + "title": "Export Toolpaths as OBJ", + "group": "Export", + "icon": "custom-gcode_gcode", + "input": "" + }, + { + "key": "export_config", + "title": "Export Preset Bundle", + "group": "Export", + "icon": "save", + "input": "" + }, + { + "key": "help_keyboard_shortcuts", + "title": "Keyboard Shortcuts", + "group": "Help", + "icon": "", + "input": "" + }, + { + "key": "help_setup_wizard", + "title": "Setup Wizard", + "group": "Help", + "icon": "", + "input": "" + }, + { + "key": "help_open_config_folder", + "title": "Show Configuration Folder", + "group": "Help", + "icon": "open_project", + "input": "" + }, + { + "key": "help_migrate_filament_presets", + "title": "Migrate Filament Presets", + "group": "Help", + "icon": "", + "input": "" + }, + { + "key": "help_troubleshoot", + "title": "Troubleshoot Center", + "group": "Help", + "icon": "", + "input": "" + }, + { + "key": "help_network_test", + "title": "Open Network Test", + "group": "Help", + "icon": "", + "input": "" + }, + { + "key": "help_benchmark_3d_scene", + "title": "Benchmark 3D Scene", + "group": "Help", + "icon": "", + "input": "" + }, + { + "key": "help_tip_of_the_day", + "title": "Show Tip of the Day", + "group": "Help", + "icon": "info", + "input": "" + }, + { + "key": "help_check_updates", + "title": "Check for Updates", + "group": "Help", + "icon": "refresh", + "input": "" + }, + { + "key": "help_about", + "title": "About OrcaSlicer", + "group": "Help", + "icon": "OrcaSlicer_gradient_circle", + "input": "" + }, + { + "key": "open_wiki", + "title": "Open Wiki", + "group": "Help", + "icon": "link_wiki_img", + "input": "" + }, + { + "key": "open_youtube", + "title": "Open YouTube Channel", + "group": "Help", + "icon": "", + "input": "" + }, + { + "key": "open_plugins", + "title": "Open Plugins", + "group": "Plugins", + "icon": "", + "input": "" + }, + { + "key": "refresh_plugins", + "title": "Refresh Plugins", + "group": "Plugins", + "icon": "", + "input": "" + }, + { + "key": "install_plugin", + "title": "Install Plugin", + "group": "Plugins", + "icon": "", + "input": "" + }, + { + "key": "install_local_plugin", + "title": "Install Local Plugin", + "group": "Plugins", + "icon": "", + "input": "" + }, + { + "key": "new_project", + "title": "New Project", + "group": "Commands", + "icon": "menu_open", + "input": "" + }, + { + "key": "save_project", + "title": "Save Project", + "group": "Commands", + "icon": "menu_save", + "input": "" + }, + { + "key": "start_recording", + "title": "Start Recording", + "group": "Commands", + "icon": "recording_start", + "input": "" + }, + { + "key": "stop_recording", + "title": "Stop Recording", + "group": "Commands", + "icon": "recording_stop", + "input": "" + } +] \ No newline at end of file diff --git a/tests/slic3rutils/retired_names.hpp b/tests/slic3rutils/retired_names.hpp new file mode 100644 index 0000000000..ede7d224c1 --- /dev/null +++ b/tests/slic3rutils/retired_names.hpp @@ -0,0 +1,88 @@ +#pragma once + +#include +#include +#include +#include +#include + +// Names of the retired vocabulary of the commands outside the Design tab, which the catalog's cases check are no +// command: a retired name has no alias. + +// The old names of the 42 tools that are named place first, then verb (the design's Mapping), and of the three that +// are split: open_files into project_open and project_import, get_settings and set_settings into the settings, +// preferences, plate and project commands. +inline const std::vector kRetiredTools{ + "search_tools", "call_tool", "generate_calibration_test", "export", + "list_presets", "select_preset", "save_preset", "delete_preset", + "list_plates", "list_objects", "transform", "add_part", + "arrange", "slice", "set_height_ranges", "set_variable_layer_height", + "set_custom_gcode_at_layer", "get_slice_stats", "get_app_state", "wait", + "get_log", "cancel_job", "run_replay", "export_replay", + "run_script", "search_python_api", "answer_dialog", "auto_answer_dialogs", + "select_objects", "screenshot", "set_view", "encode_recording", + "search_actions", "run_action", "list_windows", "set_window", + "list_widgets", "click", "set_widget_value", "press_keys", + "pick_gizmo_file", "run_javascript", "open_files", "get_settings", + "set_settings"}; + +// The ids of the menu rows that are a tile of a command of another name (the design's Mapping), each the key of +// its tile: those of the project, the objects, the parts and the plates, then those of the presets, the app, the view +// and the rest. +inline const std::vector kRetiredRows{ + "new_project", "load_project", "import_file", "import_zip_archive", + "save_project", "save_project_as", "export_gcode", "export_sliced_file", + "export_all_sliced_file", "export_3mf", "export_stl", "export_stl_multi", + "export_drc_single", "export_drc_multi", "export_toolpaths_obj", "select_all", + "deselect_all", "add_primitive_cube", "add_primitive_cylinder", "add_primitive_sphere", + "add_primitive_cone", "add_primitive_disc", "add_primitive_torus", "add_handy_orca_cube", + "add_handy_orcasliced_combo", "add_handy_orca_badge", "add_handy_orca_tolerance_test", "add_handy_3dbenchy", + "add_handy_cali_cat", "add_handy_autodesk_fdm_test", "add_handy_voron_cube", "add_handy_stanford_bunny", + "add_handy_orca_string_hell", "add_primitive_text", "add_primitive_svg", "obj_delete", + "obj_delete_all", "obj_rename", "obj_set_instances", "obj_instances_up", + "obj_instances_down", "obj_instances_to_objects", "obj_split_objects", "obj_split_parts", + "obj_assemble", "obj_type_part", "obj_type_negative", "obj_type_modifier", + "obj_type_support_blocker", "obj_type_support_enforcer", "obj_type_precise_seam", "obj_order_by_name", + "obj_order_by_filament", "obj_order_by_height", "obj_order_by_size", "obj_drop", + "obj_mirror_x", "obj_mirror_y", "obj_mirror_z", "obj_center", + "obj_fit_volume", "obj_arrange", "obj_orient", "plate_toggle_lock", + "plate_goto", "slice_and_preview", "slice_all", "calib_temperature", + "calib_flow_ratio", "calib_pressure_advance", "calib_retraction", "calib_max_volumetric", + "calib_vfa", "calib_cornering", "calib_input_shaping_freq", "calib_input_shaping_damp", + "import_configs", "export_config", "sync_presets", "help_migrate_filament_presets", + "mode_simple", "mode_advanced", "mode_expert", "toggle_developer_mode", + "open_wiki", "open_youtube", "install_plugin", "help_check_updates", + "help_open_config_folder", "help_benchmark_3d_scene", "view_top", "view_bottom", + "view_front", "view_rear", "view_left", "view_right", + "view_iso", "view_default", "view_fit_bed", "view_toggle_perspective", + "go_to_tab", "go_to_layer", "reset_window_layout", "open_preferences", + "open_plugins", "open_action_replay", "preset_bundle", "help_keyboard_shortcuts", + "help_setup_wizard", "help_network_test", "help_troubleshoot", "help_tip_of_the_day", + "help_about", "take_screenshot", "sync_ams", "send_gcode", + "install_local_plugin", "refresh_plugins", "start_recording", "stop_recording", + "toggle_run_script_panel"}; + +// The names of kRetiredTools and kRetiredRows that are words of `text`, as a text an agent reads would name a command: +// a word is a run of letters, digits, underscores and hyphens, compared in its case, so project_export holds no export +// and a right-click menu no click. +inline std::set retired_names_in(const std::string& text) +{ + std::set found; + std::string word; + const auto flush = [&found, &word] { + const auto named = [&word](const std::vector& names) { + return std::find(names.begin(), names.end(), word) != names.end(); + }; + if (named(kRetiredTools) || named(kRetiredRows)) + found.insert(word); + word.clear(); + }; + for (const char ch : text) { + if (std::isalnum(static_cast(ch)) || ch == '_' || ch == '-') + word += ch; + else + flush(); + } + flush(); + return found; +} diff --git a/tests/slic3rutils/test_action_source.cpp b/tests/slic3rutils/test_action_source.cpp index c242dcbaff..04ec30ac74 100644 --- a/tests/slic3rutils/test_action_source.cpp +++ b/tests/slic3rutils/test_action_source.cpp @@ -42,6 +42,16 @@ public: AppActionRunResult run(const nlohmann::json& /*args*/) const override { return {}; } }; +// The action the registry makes of the Speed Dial's tile `key`, a command's own or an item of its tiles; null when no +// command of the process catalog has that tile. +std::unique_ptr tile_action(const std::string& key) +{ + const auto [command, tile] = Slic3r::GUI::find_tile(Slic3r::GUI::NativeCommands::instance(), key); + if (command == nullptr) + return nullptr; + return tile != nullptr ? Slic3r::GUI::NativeCommands::make_action(*command, *tile) : Slic3r::GUI::NativeCommands::make_action(*command); +} + } // namespace TEST_CASE("AppAction composes a stable id from prefix:title:source_key", "[ActionSource][SpeedDial]") @@ -140,26 +150,26 @@ TEST_CASE("Actions default to no description or wiki link", "[ActionSource][Spee CHECK(command->help_url.empty()); } -// Two-phase commands declare the input the palette must collect before they can run. +// Two-phase tiles declare the input the palette must collect before they can run. TEST_CASE("Two-phase commands declare their input phase", "[ActionSource][SpeedDial]") { - auto input_of = [](const std::string& key) -> std::string { - for (const auto& c : Slic3r::GUI::NativeCommands::instance().commands()) - if (c.key == key) - return c.input; - return {}; - }; - CHECK(input_of("go_to_layer") == "percent"); - CHECK(input_of("go_to_tab") == "tab"); + const std::unique_ptr layer = tile_action("go_to_layer"); + const std::unique_ptr tab = tile_action("go_to_tab"); + REQUIRE(layer != nullptr); + REQUIRE(tab != nullptr); + CHECK(layer->input == "percent"); + CHECK(tab->input == "tab"); } // The input token vocabulary is a JS<->C++ contract (speeddial.js dispatches "percent"/"tab"). -// A typo here would leave a command that never enters its second phase, so pin the allowed set. +// A typo here would leave a tile that never enters its second phase, so pin the allowed set. TEST_CASE("Command input tokens stay in the known vocabulary", "[ActionSource][SpeedDial]") { - for (const auto& c : Slic3r::GUI::NativeCommands::instance().commands()) { - INFO(c.key << " input=" << c.input); - CHECK((c.input.empty() || c.input == "percent" || c.input == "tab")); + for (const Slic3r::GUI::NativeCommands::PaletteTile& t : Slic3r::GUI::NativeCommands::palette_tiles(Slic3r::GUI::NativeCommands::instance())) { + const std::string key = t.tile != nullptr ? t.tile->at("key").get() : t.command->key; + const std::string input = t.tile != nullptr ? t.tile->value("input", std::string()) : t.command->input; + INFO(key << " input=" << input); + CHECK((input.empty() || input == "percent" || input == "tab")); } } @@ -190,6 +200,23 @@ TEST_CASE("A pin with no live action is dropped, the others keep their order", " #endif } +TEST_CASE("A pin under a row's id is kept, as its tile's", "[ActionSource][SpeedDial]") +{ + // The ids the registry holds of the palette's tiles, which it makes as the Speed Dial starts. + std::set held; + for (const Slic3r::GUI::NativeCommands::PaletteTile& t : Slic3r::GUI::NativeCommands::palette_tiles(Slic3r::GUI::NativeCommands::instance())) + held.insert((t.tile != nullptr ? Slic3r::GUI::NativeCommands::make_action(*t.command, *t.tile) : + Slic3r::GUI::NativeCommands::make_action(*t.command)) + ->id()); + const auto live = [&held](const std::string& id) { return held.count(id) != 0; }; + // Delete Selected and New Project, whose rows are tiles of object_delete and project_new. + const std::vector pinned{"orca_command:obj_delete:orca", "orca_command:new_project:orca"}; + std::vector stored, shown; + Slic3r::GUI::prune_favourites(pinned, live, stored, shown); + CHECK(stored == pinned); + CHECK(shown == pinned); +} + namespace { // `n` pins, pin1 to pin. @@ -265,7 +292,7 @@ TEST_CASE("Native command catalog has unique keys and present titles", "[ActionS INFO(c.key); CHECK_FALSE(c.key.empty()); CHECK_FALSE(c.title.empty()); - // A tile shows under its group; a typed tool's group is what search_tools filters by. + // A command's group is what tool_search filters by: its place's heading, or Design. CHECK_FALSE(c.group.empty()); // A duplicated key would silently shadow the earlier command in the palette. CHECK(seen.insert(c.key).second); @@ -278,14 +305,6 @@ TEST_CASE("Native command catalog has unique keys and present titles", "[ActionS // cannot leave broken images in the palette. TEST_CASE("Native command icons resolve to shipped SVGs", "[ActionSource][SpeedDial]") { - const std::vector& commands = Slic3r::GUI::NativeCommands::instance().commands(); - auto icon_of = [&commands](const std::string& key) -> const std::string* { - for (const auto& c : commands) - if (c.key == key) - return &c.icon; - return nullptr; - }; - struct Expected { const char* key; @@ -307,143 +326,146 @@ TEST_CASE("Native command icons resolve to shipped SVGs", "[ActionSource][SpeedD Expected{"help_check_updates", "refresh"}, Expected{"help_about", "OrcaSlicer_gradient_circle"}, Expected{"go_to_tab", ""}}) { - const std::string* icon = icon_of(e.key); INFO(e.key); - REQUIRE(icon != nullptr); - CHECK(*icon == e.icon); + const std::unique_ptr action = tile_action(e.key); + REQUIRE(action != nullptr); + CHECK(action->icon == e.icon); } + // Every tile's icon, a command's own or an item's. const boost::filesystem::path images = boost::filesystem::path(PROFILES_DIR).parent_path() / "images"; - for (const auto& c : commands) { - if (c.icon.empty()) + for (const Slic3r::GUI::NativeCommands::PaletteTile& t : Slic3r::GUI::NativeCommands::palette_tiles(Slic3r::GUI::NativeCommands::instance())) { + const std::string key = t.tile != nullptr ? t.tile->at("key").get() : t.command->key; + const std::string icon = t.tile != nullptr ? t.tile->at("icon").get() : t.command->icon; + if (icon.empty()) continue; - INFO(c.key << " -> " << c.icon); - CHECK(boost::filesystem::exists(images / (c.icon + ".svg"))); + INFO(key << " -> " << icon); + CHECK(boost::filesystem::exists(images / (icon + ".svg"))); } } // The Design tab's tiles are the registry's to show while the tab is shown (materialize_design_actions()), -// so the palette's own commands, which it holds whatever tab is shown, leave the Design group out. -TEST_CASE("the palette's own commands leave the Design group out", "[ActionSource][SpeedDial]") +// so the palette's own tiles, which it holds whatever tab is shown, leave the Design group out. A command of any other +// group, listed as one that runs from its arguments, has its tiles there. +TEST_CASE("the palette's own tiles leave the Design group out", "[ActionSource][SpeedDial]") { Slic3r::GUI::CommandCatalog catalog; - for (const char* group : {"Design", "Commands"}) { + for (const char* group : {"Design", "Objects"}) { Slic3r::GUI::NativeCommand c; c.key = std::string(group) + "_tile"; c.title = group; c.group = group; + c.listed = c.group != Slic3r::GUI::kDesignGroup; c.in_palette = true; + c.tiles = nlohmann::json::array({nlohmann::json{{"key", std::string(group) + "_row"}, {"title", group}, {"icon", ""}, + {"description", ""}, {"args", {{"row", true}}}}}); catalog.add(std::move(c)); } catalog.seal(); - const std::vector palette = Slic3r::GUI::NativeCommands::palette_commands(catalog); - REQUIRE(palette.size() == 1); - CHECK(palette.front()->key == "Commands_tile"); + const std::vector palette = Slic3r::GUI::NativeCommands::palette_tiles(catalog); + REQUIRE(palette.size() == 2); + CHECK(palette[0].command->key == "Objects_tile"); + CHECK(palette[0].tile == nullptr); + REQUIRE(palette[1].tile != nullptr); + CHECK(palette[1].tile->at("key") == "Objects_row"); } -// The Help-menu commands, wiki/YouTube links and the developer-mode toggle are part of the palette. +// The Help-menu tiles, wiki/YouTube links and the developer-mode toggle are part of the palette. // Guard their presence and that they stay grouped with their peers, so a catalog edit cannot drop // or scatter them. Groups are compared to the peer's own group to stay independent of translation. TEST_CASE("Native command catalog includes the Help and developer-mode commands", "[ActionSource][SpeedDial]") { - const std::vector& commands = Slic3r::GUI::NativeCommands::instance().commands(); - auto find = [&commands](const std::string& key) -> const Slic3r::GUI::NativeCommand* { - for (const auto& c : commands) - if (c.key == key) - return &c; - return nullptr; - }; - - const Slic3r::GUI::NativeCommand* first = find("help_keyboard_shortcuts"); + const std::unique_ptr first = tile_action("help_keyboard_shortcuts"); REQUIRE(first != nullptr); for (const char* key : {"help_setup_wizard", "help_open_config_folder", "help_migrate_filament_presets", "help_troubleshoot", "help_network_test", "help_benchmark_3d_scene", "help_tip_of_the_day", "help_check_updates", "help_about", "open_wiki", "open_youtube"}) { - const Slic3r::GUI::NativeCommand* c = find(key); - REQUIRE(c != nullptr); - CHECK(c->group == first->group); + INFO(key); + const std::unique_ptr action = tile_action(key); + REQUIRE(action != nullptr); + CHECK(action->group_en == first->group_en); } - const Slic3r::GUI::NativeCommand* mode_simple = find("mode_simple"); - const Slic3r::GUI::NativeCommand* dev_mode = find("toggle_developer_mode"); + const std::unique_ptr mode_simple = tile_action("mode_simple"); + const std::unique_ptr dev_mode = tile_action("toggle_developer_mode"); REQUIRE(mode_simple != nullptr); REQUIRE(dev_mode != nullptr); - CHECK(dev_mode->group == mode_simple->group); + CHECK(dev_mode->group_en == mode_simple->group_en); } // A person takes screenshots and records from the palette, beside Run Script, with no agent involved. Start and -// Stop Recording are the typed tools too, whose arguments skip what the tile does. +// Stop Recording are tiles of the typed tools, whose arguments skip what the tile does; Take Screenshot's command has +// no argument form. TEST_CASE("Native command catalog has the screenshot and recording commands", "[ActionSource][SpeedDial]") { - const Slic3r::GUI::NativeCommand* runner = Slic3r::GUI::NativeCommands::find("open_action_replay"); + const std::unique_ptr runner = tile_action("open_action_replay"); REQUIRE(runner != nullptr); - for (const char* key : {"take_screenshot", "start_recording", "stop_recording"}) { + for (const auto& [key, name] : {std::make_pair("take_screenshot", "window_save_screenshot"), + std::make_pair("start_recording", "recording_start"), std::make_pair("stop_recording", "recording_stop")}) { INFO(key); - const Slic3r::GUI::NativeCommand* c = Slic3r::GUI::NativeCommands::find(key); + const std::unique_ptr action = tile_action(key); + REQUIRE(action != nullptr); + CHECK(action->group_en == runner->group_en); + CHECK(action->input.empty()); + CHECK(action->command == name); + const Slic3r::GUI::NativeCommand* c = Slic3r::GUI::NativeCommands::find(name); REQUIRE(c != nullptr); - CHECK(c->group == runner->group); - CHECK(c->input.empty()); CHECK(c->input_schema.at("properties").empty() == (std::string(key) == "take_screenshot")); CHECK_FALSE(c->description.empty()); } } -// The Run Script panel's command sits beside Action Replay's, which keeps its id so existing replays and agent sessions +// The Run Script panel's tile sits beside Action Replay's, which keeps its id so existing replays and agent sessions // that open it still do. TEST_CASE("Native command catalog has the Run Script panel and Action Replay commands", "[ActionSource][SpeedDial]") { - const Slic3r::GUI::NativeCommand* replay = Slic3r::GUI::NativeCommands::find("open_action_replay"); + const std::unique_ptr replay = tile_action("open_action_replay"); REQUIRE(replay != nullptr); - CHECK(std::string(replay->title) == "Action Replay"); - const Slic3r::GUI::NativeCommand* panel = Slic3r::GUI::NativeCommands::find("toggle_run_script_panel"); + CHECK(replay->title_en == "Action Replay"); + const std::unique_ptr panel = tile_action("toggle_run_script_panel"); REQUIRE(panel != nullptr); - CHECK(panel->group == replay->group); + CHECK(panel->group_en == replay->group_en); CHECK(panel->input.empty()); - CHECK(panel->input_schema.at("properties").empty()); - CHECK_FALSE(panel->description.empty()); + const Slic3r::GUI::NativeCommand* command = Slic3r::GUI::NativeCommands::find(panel->command); + REQUIRE(command != nullptr); + CHECK(command->key == "script_toggle_panel"); + CHECK(command->input_schema.at("properties").empty()); + CHECK_FALSE(command->description.empty()); } -// Every "Add Primitive" item and shipped handy model has a palette command, grouped as in the Add +// Every "Add Primitive" item and shipped handy model has a palette tile, grouped as in the Add // menu. Groups are compared to a peer's own group to stay independent of translation. TEST_CASE("Native command catalog covers the Add menus", "[ActionSource][SpeedDial]") { - const std::vector& commands = Slic3r::GUI::NativeCommands::instance().commands(); - auto group_of = [&commands](const std::string& key) -> const std::string* { - for (const auto& c : commands) - if (c.key == key) - return &c.group; - return nullptr; - }; - - const std::string* primitive_group = group_of("add_primitive_cube"); - REQUIRE(primitive_group != nullptr); + const std::unique_ptr primitive = tile_action("add_primitive_cube"); + REQUIRE(primitive != nullptr); for (const char* key : {"add_primitive_cylinder", "add_primitive_sphere", "add_primitive_cone", "add_primitive_disc", "add_primitive_torus", "add_primitive_text", "add_primitive_svg"}) { - const std::string* group = group_of(key); INFO(key); - REQUIRE(group != nullptr); - CHECK(*group == *primitive_group); + const std::unique_ptr action = tile_action(key); + REQUIRE(action != nullptr); + CHECK(action->group_en == primitive->group_en); } - const std::string* handy_group = group_of("add_handy_orca_cube"); - REQUIRE(handy_group != nullptr); + const std::unique_ptr handy = tile_action("add_handy_orca_cube"); + REQUIRE(handy != nullptr); for (const char* key : {"add_handy_orcasliced_combo", "add_handy_orca_badge", "add_handy_orca_tolerance_test", "add_handy_3dbenchy", "add_handy_cali_cat", "add_handy_autodesk_fdm_test", "add_handy_voron_cube", "add_handy_stanford_bunny", "add_handy_orca_string_hell"}) { - const std::string* group = group_of(key); INFO(key); - REQUIRE(group != nullptr); - CHECK(*group == *handy_group); + const std::unique_ptr action = tile_action(key); + REQUIRE(action != nullptr); + CHECK(action->group_en == handy->group_en); } - // A handy model's command is titled by the English label its Add-menu entry is built from, so it is + // A handy model's tile is titled by the English label its Add-menu entry is built from, so it is // searchable in English in any UI language. for (const auto& model : Slic3r::GUI::MenuFactory::handy_models()) { const std::string key = "add_handy_" + std::string(model.key); INFO(key); - const auto it = std::find_if(commands.begin(), commands.end(), [&key](const auto& c) { return c.key == key; }); - REQUIRE(it != commands.end()); - CHECK(it->title == model.label); + const std::unique_ptr action = tile_action(key); + REQUIRE(action != nullptr); + CHECK(action->title_en == model.label); } } diff --git a/tests/slic3rutils/test_command_catalog.cpp b/tests/slic3rutils/test_command_catalog.cpp index 59c4ac1935..d6345002bc 100644 --- a/tests/slic3rutils/test_command_catalog.cpp +++ b/tests/slic3rutils/test_command_catalog.cpp @@ -4,6 +4,7 @@ #include #include "automation/automation_test_utils.hpp" +#include "retired_names.hpp" #include "slic3r/GUI/ActionRegistry.hpp" #include "slic3r/GUI/CommandCatalog.hpp" @@ -23,12 +24,14 @@ #include #include #include +#include #include #include #include #include #include #include +#include #include #include @@ -139,20 +142,501 @@ std::string first_difference(const std::string& actual, const std::string& expec return "the file has " + std::to_string(a.size()) + " lines where the catalog has " + std::to_string(e.size()); } +// The design's command set outside the Design tab, heading by heading in the order tools/list gives them, Driving the +// GUI last, after the Design tab's commands: the 118 commands of the catalog, its typed tools, the commands made from +// menu rows, the seven Parts 4a to 4c add (Printable, Fix Model, Auto Drop, Clone, Reload from disk, Replace 3D file, +// Add Mixed Filament), the three of Part 5a (the Printer Selection dialog's list, install and uninstall), the two of +// Part 5b (the System Filaments dialog's install and uninstall), Part 5c's write of the Preferences dialog's preferences +// and the four of Part 5d (the Plugins window's list, a switch, Delete or Unsubscribe, and Reload). +// A part that adds a command adds it here. +const std::vector>> kPlaces{ + {"Tools and actions", {"tool_search", "tool_call", "action_search", "action_run"}}, + {"The app", + {"app_state", "app_log", "app_wait", "job_cancel", "undo", "redo", "app_open_web_page", "app_check_for_updates", + "app_show_config_folder", "app_benchmark_3d_scene", "preferences_get", "preferences_set"}}, + {"The project", + {"project_new", "project_open", "project_import", "project_save", "project_get_settings", "project_set_settings", "project_export"}}, + {"Objects", + {"object_list", "object_select", "object_add_primitive", "object_add_handy_model", "object_add_text", "object_add_svg", + "object_delete", "object_rename", "object_set_instances", "object_separate_instances", "object_split", "object_assemble", + "object_order", "object_transform", "object_drop", "object_mirror", "object_center", "object_scale_to_fit", "object_arrange", + "object_auto_orient", "object_set_variable_layer_height", "object_set_height_ranges", "object_set_printable", "object_fix", + "object_set_auto_drop", "object_clone", "object_reload_from_disk"}}, + {"Parts", {"part_add", "part_change_type", "part_replace"}}, + {"Plates", + {"plate_list", "plate_get_settings", "plate_set_settings", "plate_add", "plate_delete", "plate_duplicate", "plate_rename", + "plate_lock", "plate_select", "plate_slice", "plate_slice_stats", "plate_set_custom_gcode", "calibration_generate_test"}}, + {"Presets and settings", + {"preset_list", "preset_select", "preset_save", "preset_delete", "settings_list", "settings_get", "settings_set", "preset_import", + "preset_export", "preset_sync", "settings_set_mode", "preset_migrate_filaments", "settings_toggle_developer_mode"}}, + {"Filaments", + {"filament_add", "filament_delete", "filament_sync_ams", "filament_add_mixed", "filament_install", "filament_uninstall"}}, + {"Printers and prints", {"printer_send", "printer_list_models", "printer_install", "printer_uninstall"}}, + {"Plugins", {"plugin_list", "plugin_install_local", "plugin_enable", "plugin_reload", "plugin_uninstall", "plugin_refresh"}}, + {"View and windows", {"view_set", "window_list", "window_set", "window_open"}}, + {"Recordings, replays and scripts", + {"script_search_api", "window_screenshot", "recording_start", "recording_stop", "recording_encode", "replay_run", "replay_export", + "script_run", "window_save_screenshot", "script_toggle_panel"}}, + {"Driving the GUI", + {"widget_list", "widget_click", "widget_set_value", "keyboard_press", "mouse_gesture", "webview_run_javascript", "dialog_answer", + "dialog_auto_answer", "gizmo_pick_file"}}, +}; + +// The groups of `keys`' commands in `catalog`, each run of one group once, in their order. +std::vector group_runs(const CommandCatalog& catalog, const std::vector& keys) +{ + std::vector runs; + for (const std::string& key : keys) + if (const NativeCommand* c = catalog.find(key); c != nullptr && (runs.empty() || runs.back() != c->group)) + runs.push_back(c->group); + return runs; +} + } // namespace -TEST_CASE("the process catalog's palette is the Speed Dial's commands", "[CommandCatalog]") +TEST_CASE("the process catalog's palette is the Speed Dial's tiles", "[CommandCatalog]") { const CommandCatalog& catalog = NativeCommands::instance(); CHECK(catalog.sealed()); - const std::vector palette = NativeCommands::palette_commands(catalog); + const std::vector palette = NativeCommands::palette_tiles(catalog); CHECK(palette.size() == 129); - for (const NativeCommand* c : palette) { - INFO(c->key); - CHECK(c->in_palette); + for (const NativeCommands::PaletteTile& t : palette) { + REQUIRE(t.command != nullptr); + INFO(t.command->key); + // A command's own tile, or an item of its tiles. + if (t.tile == nullptr) + CHECK(t.command->in_palette); + else + CHECK(t.command->tiles.is_array()); } // The Speed Dial's own lookup reads the same catalog. - CHECK(NativeCommands::find("slice_all") == catalog.find("slice_all")); + CHECK(NativeCommands::find("plate_slice") == catalog.find("plate_slice")); +} + +TEST_CASE("every Speed Dial tile of today is still a tile", "[CommandCatalog][SpeedDial]") +{ + // The 129 tiles of the Speed Dial, each with its id, title, section, icon and input: each is a tile of + // the palette with that presentation, and the palette has no other. + std::ifstream in(std::string(TEST_DATA_DIR) + "/speed_dial_tiles.json", std::ios::binary); + REQUIRE(in.is_open()); + const json fixture = json::parse(in); + REQUIRE(fixture.size() == 129); + + const CommandCatalog& catalog = NativeCommands::instance(); + std::vector expected; + for (const json& item : fixture) { + const std::string key = item.at("key"); + INFO(key); + expected.push_back(key); + const auto [command, tile] = Slic3r::GUI::find_tile(catalog, key); + REQUIRE(command != nullptr); + const std::unique_ptr action = tile != nullptr ? NativeCommands::make_action(*command, *tile) : + NativeCommands::make_action(*command); + REQUIRE(action != nullptr); + CHECK(action->id() == "orca_command:" + key + ":orca"); + CHECK(action->title_en == item.at("title").get()); + CHECK(action->group_en == item.at("group").get()); + CHECK(action->icon == item.at("icon").get()); + CHECK(action->input == item.at("input").get()); + } + + std::vector tiles; + for (const NativeCommands::PaletteTile& t : NativeCommands::palette_tiles(catalog)) + tiles.push_back(t.tile != nullptr ? t.tile->at("key").get() : t.command->key); + std::sort(expected.begin(), expected.end()); + std::sort(tiles.begin(), tiles.end()); + CHECK(tiles == expected); +} + +TEST_CASE("a row's id is a tile's key, not a command", "[CommandCatalog][SpeedDial]") +{ + const CommandCatalog& catalog = NativeCommands::instance(); + REQUIRE(kRetiredRows.size() == 121); + for (const std::string& row : kRetiredRows) { + INFO(row); + CHECK(catalog.find(row) == nullptr); + const auto [command, tile] = Slic3r::GUI::find_tile(catalog, row); + CHECK(command != nullptr); + CHECK(tile != nullptr); + } +} + +TEST_CASE("every tile is its command's, with the design's arguments, and they fit its schema", "[CommandCatalog][SpeedDial]") +{ + // Each of the 129 tiles with the command the design folds its row into and the arguments it runs it with. + std::ifstream in(std::string(TEST_DATA_DIR) + "/speed_dial_tile_calls.json", std::ios::binary); + REQUIRE(in.is_open()); + const json fixture = json::parse(in); + REQUIRE(fixture.size() == 129); + + const CommandCatalog& catalog = NativeCommands::instance(); + std::size_t folded = 0; + for (const json& item : fixture) { + const std::string key = item.at("key"); + const std::string name = item.at("command"); + INFO(key << " -> " << name); + const auto [command, tile] = Slic3r::GUI::find_tile(catalog, key); + REQUIRE(command != nullptr); + REQUIRE(command->key == name); + ++folded; + if (key == name) { + // The command's own tile, a person's form of it. + CHECK(command->in_palette); + CHECK(tile == nullptr); + CHECK(item.at("args") == json::object()); + CHECK(Mcp::person_form(*command, json::object())); + json none = Slic3r::GUI::tile_call_args(nullptr, json::object()); + CHECK(Mcp::argument_error(*command, none).empty()); + continue; + } + REQUIRE(tile != nullptr); + CHECK(tile->at("args") == item.at("args")); + const std::string input = item.value("input", std::string()); + CHECK(tile->value("input", std::string()) == input); + CHECK(tile->value("input_arg", std::string()) == item.value("input_arg", std::string())); + // A tile that collects nothing is a person's form of its command; one that collects a value is not, as its + // value comes from the Speed Dial's second phase. + CHECK(Mcp::person_form(*command, tile->at("args")) == input.empty()); + // What a pick runs the command with: the tile's arguments, and the value its second phase collects. + json value = json::object(); + if (!input.empty()) + value[input] = input == "percent" ? json(50) : json("preview"); + json call = Slic3r::GUI::tile_call_args(tile, value); + CHECK(Mcp::argument_error(*command, call).empty()); + } + // Every tile of today, under the command the design folds its row into. + CHECK(folded == 129); + + // The tiles that ask need none of what the silent form requires; one more argument is the silent form. + const NativeCommand* save = catalog.find("project_save"); + const NativeCommand* export_ = catalog.find("project_export"); + const NativeCommand* import_ = catalog.find("project_import"); + REQUIRE(save != nullptr); + REQUIRE(export_ != nullptr); + REQUIRE(import_ != nullptr); + json save_as{{"save_as", true}}; + CHECK(Mcp::argument_error(*save, save_as).empty()); + json gcode{{"format", "gcode"}}; + CHECK(Mcp::argument_error(*export_, gcode).empty()); + json archive{{"archive", true}}; + CHECK(Mcp::argument_error(*import_, archive).empty()); + json overwrite{{"overwrite", true}}; + CHECK_THAT(Mcp::argument_error(*save, overwrite), ContainsSubstring("path")); + json gcode_overwrite{{"format", "gcode"}, {"overwrite", true}}; + CHECK_THAT(Mcp::argument_error(*export_, gcode_overwrite), ContainsSubstring("path")); +} + +TEST_CASE("a row's tile runs its command with the row's arguments", "[SpeedDial]") +{ + // One tile of each command that has tiles, and each of view_set's kinds of tile: a tile's key, its command, the + // arguments it runs it with, and the Speed Dial's token for the value it collects with the argument that takes it. + struct Pair + { + const char* tile; + const char* command; + json args; + const char* input = ""; + const char* input_arg = ""; + }; + const std::vector pairs{ + {"new_project", "project_new", json::object()}, + {"load_project", "project_open", json::object()}, + {"import_zip_archive", "project_import", {{"archive", true}}}, + {"save_project_as", "project_save", {{"save_as", true}}}, + {"export_stl_multi", "project_export", {{"format", "stl"}, {"per_object", true}}}, + {"select_all", "object_select", {{"all", true}}}, + {"add_primitive_torus", "object_add_primitive", {{"shape", "torus"}}}, + {"add_handy_orca_cube", "object_add_handy_model", {{"model", "orca_cube"}}}, + {"add_primitive_text", "object_add_text", json::object()}, + {"add_primitive_svg", "object_add_svg", json::object()}, + {"obj_delete_all", "object_delete", {{"all", true}}}, + {"obj_rename", "object_rename", json::object()}, + {"obj_instances_down", "object_set_instances", {{"delta", -1}}}, + {"obj_instances_to_objects", "object_separate_instances", json::object()}, + {"obj_split_parts", "object_split", {{"into", "parts"}}}, + {"obj_assemble", "object_assemble", json::object()}, + {"obj_order_by_height", "object_order", {{"by", "height"}}}, + {"obj_drop", "object_drop", json::object()}, + {"obj_mirror_y", "object_mirror", {{"axis", "y"}}}, + {"obj_center", "object_center", json::object()}, + {"obj_fit_volume", "object_scale_to_fit", json::object()}, + {"obj_arrange", "object_arrange", json::object()}, + {"obj_orient", "object_auto_orient", json::object()}, + {"obj_type_support_enforcer", "part_change_type", {{"type", "support_enforcer"}}}, + {"plate_add", "plate_add", json::object()}, + {"plate_delete", "plate_delete", json::object()}, + {"plate_duplicate", "plate_duplicate", json::object()}, + {"plate_rename", "plate_rename", json::object()}, + {"plate_toggle_lock", "plate_lock", json::object()}, + {"plate_goto", "plate_select", {{"plate", 0}}}, + {"slice_all", "plate_slice", {{"plates", "all"}, {"preview", true}}}, + {"calib_pressure_advance", "calibration_generate_test", {{"test", "pressure_advance"}}}, + {"import_configs", "preset_import", json::object()}, + {"export_config", "preset_export", json::object()}, + {"sync_presets", "preset_sync", json::object()}, + {"help_migrate_filament_presets", "preset_migrate_filaments", json::object()}, + {"mode_expert", "settings_set_mode", {{"mode", "expert"}}}, + {"toggle_developer_mode", "settings_toggle_developer_mode", json::object()}, + {"undo", "undo", json::object()}, + {"redo", "redo", json::object()}, + {"install_plugin", "app_open_web_page", {{"page", "plugin_hub"}}}, + {"help_check_updates", "app_check_for_updates", json::object()}, + {"help_open_config_folder", "app_show_config_folder", json::object()}, + {"help_benchmark_3d_scene", "app_benchmark_3d_scene", json::object()}, + {"view_top", "view_set", {{"camera", "top"}}}, + {"view_toggle_perspective", "view_set", {{"projection", "toggle"}}}, + {"reset_window_layout", "view_set", {{"layout", "default"}}}, + {"go_to_tab", "view_set", json::object(), "tab"}, + {"go_to_layer", "view_set", json::object(), "percent", "layer_percent"}, + {"open_preferences", "window_open", {{"window", "preferences"}}}, + {"take_screenshot", "window_save_screenshot", json::object()}, + {"filament_add", "filament_add", json::object()}, + {"filament_delete", "filament_delete", json::object()}, + {"sync_ams", "filament_sync_ams", json::object()}, + {"send_gcode", "printer_send", json::object()}, + {"install_local_plugin", "plugin_install_local", json::object()}, + {"refresh_plugins", "plugin_refresh", json::object()}, + {"start_recording", "recording_start", json::object()}, + {"stop_recording", "recording_stop", json::object()}, + {"toggle_run_script_panel", "script_toggle_panel", json::object()}, + }; + REQUIRE(pairs.size() == 60); + const CommandCatalog& catalog = NativeCommands::instance(); + for (const Pair& p : pairs) { + INFO(p.tile << " -> " << p.command << " " << p.args.dump()); + const auto [command, tile] = Slic3r::GUI::find_tile(catalog, p.tile); + REQUIRE(command != nullptr); + CHECK(command->key == p.command); + // The tile's action runs its command, with what tile_call_args() makes of a pick that collects nothing. + const std::unique_ptr action = tile != nullptr ? NativeCommands::make_action(*command, *tile) : + NativeCommands::make_action(*command); + CHECK(action->command == p.command); + CHECK(Slic3r::GUI::tile_call_args(tile, json::object()) == p.args); + CHECK(action->input == p.input); + if (tile != nullptr) + CHECK(tile->value("input_arg", std::string()) == p.input_arg); + // The command's own tile is the one whose key is the command's name. + CHECK((tile == nullptr) == (std::string(p.tile) == p.command)); + } +} + +TEST_CASE("outside the Design tab the catalog has its commands and 129 tiles", "[CommandCatalog]") +{ + // The section the Speed Dial shows each tile in, by its key. + std::ifstream in(std::string(TEST_DATA_DIR) + "/speed_dial_tiles.json", std::ios::binary); + REQUIRE(in.is_open()); + std::map section; + for (const json& item : json::parse(in)) + section[item.at("key").get()] = item.at("group").get(); + + std::size_t commands = 0, items = 0; + std::set own; + for (const NativeCommand& c : NativeCommands::instance().commands()) { + if (c.group == Slic3r::GUI::kDesignGroup) + continue; + ++commands; + if (c.tiles.is_array()) + items += c.tiles.size(); + if (!c.in_palette) + continue; + INFO(c.key); + own.insert(c.key); + // An own tile is in the section the Speed Dial shows its key in. + CHECK(c.tile_group == section.at(c.key)); + } + // The commands outside the Design tab: the typed tools, the commands made from menu rows, the seven Parts 4a to 4c + // add, Part 5a's three, Part 5b's two, Part 5c's one and Part 5d's four. + CHECK(commands == 118); + // The eight commands named as their rows keep a tile of their own; the other 121 tiles are items. + CHECK(own == std::set{"plate_add", "plate_delete", "plate_duplicate", "plate_rename", "filament_add", "filament_delete", + "undo", "redo"}); + CHECK(items == 121); +} + +TEST_CASE("the commands outside the Design tab are the design's, under its headings", "[CommandCatalog]") +{ + std::map> by_heading; + for (const NativeCommand& c : NativeCommands::instance().commands()) { + if (c.group == Slic3r::GUI::kDesignGroup) + continue; + INFO(c.key); + // A command whose name starts with no place has no heading. + const char* heading = NativeCommands::place_heading(c.key); + REQUIRE(heading != nullptr); + CHECK(c.group == heading); + by_heading[c.group].insert(c.key); + } + std::size_t commands = 0; + for (const auto& [heading, keys] : kPlaces) { + INFO(heading); + CHECK(by_heading[heading] == keys); + commands += keys.size(); + } + CHECK(by_heading.size() == kPlaces.size()); + CHECK(commands == 118); + + // tool_search's group says which there are. + const NativeCommand* search = NativeCommands::find("tool_search"); + REQUIRE(search != nullptr); + const std::string group = search->input_schema.at("properties").at("group").at("description").get(); + for (const auto& place : kPlaces) + CHECK_THAT(group, ContainsSubstring(place.first)); + CHECK_THAT(group, ContainsSubstring(Slic3r::GUI::kDesignGroup)); + + // The screenshot commands are under Recordings, replays and scripts, apart from the other window commands. + const auto heading_of = [](const char* key) { + const char* heading = NativeCommands::place_heading(key); + return heading != nullptr ? std::string(heading) : std::string("(none)"); + }; + CHECK(heading_of("window_screenshot") == "Recordings, replays and scripts"); + CHECK(heading_of("window_save_screenshot") == "Recordings, replays and scripts"); + CHECK(heading_of("window_list") == "View and windows"); + // undo and redo are a place's word of their own; a row's id and a word that is no place have none. + CHECK(heading_of("undo") == "The app"); + CHECK(heading_of("obj_mirror_x") == "(none)"); + CHECK(heading_of("objects_list") == "(none)"); + CHECK(heading_of("") == "(none)"); +} + +TEST_CASE("every command that runs from arguments is in the tool list, by place", "[CommandCatalog]") +{ + const CommandCatalog& catalog = NativeCommands::instance(); + std::vector listed; + std::set unlisted; + for (const NativeCommand& c : catalog.commands()) { + if (c.group == Slic3r::GUI::kDesignGroup) + continue; + if (c.listed) + listed.push_back(c.key); + else + unlisted.insert(c.key); + } + // The three menu rows with no argument form, which tool_search finds and tool_call runs. + CHECK(unlisted == std::set{"window_save_screenshot", "script_toggle_panel", "settings_toggle_developer_mode"}); + // Task 3's 98, the seven Parts 4a to 4c add, Part 5a's three, Part 5b's two, Part 5c's one and Part 5d's four. + CHECK(listed.size() == 115); + + // The search, the generic call and the app's state first; then each heading's commands together, in the + // design's order, Driving the GUI last. + REQUIRE(listed.size() > 3); + const std::vector first{"tool_search", "tool_call", "app_state"}; + CHECK(std::vector(listed.begin(), listed.begin() + 3) == first); + std::vector headings; + for (const auto& place : kPlaces) + headings.push_back(place.first); + CHECK(group_runs(catalog, std::vector(listed.begin() + 3, listed.end())) == headings); + + // With the Design tab, its commands sit between the last of the places and Driving the GUI. + CommandCatalog with_design = catalog_with_design(); + with_design.seal(); + const std::vector keys = keys_of(with_design.commands()); + REQUIRE(keys.size() > 3); + std::vector with_design_headings = headings; + with_design_headings.insert(with_design_headings.end() - 1, Slic3r::GUI::kDesignGroup); + CHECK(group_runs(with_design, std::vector(keys.begin() + 3, keys.end())) == with_design_headings); +} + +TEST_CASE("only deleting a preset and uninstalling a plugin are labelled destructive", "[CommandCatalog]") +{ + // The reads: they change nothing in the app or the project. + const std::set reads{"app_state", "app_wait", "app_log", "tool_search", + "preset_list", "settings_list", "settings_get", "preferences_get", + "plate_get_settings", "project_get_settings", "plate_list", "object_list", + "window_screenshot", "plate_slice_stats", "script_search_api", "action_search", + "window_list", "widget_list", "printer_list_models", "plugin_list"}; + // The commands made from menu rows whose row reaches a printer, the cloud account or the network. + const std::set rows_reaching_out{"printer_send", "preset_sync", "filament_sync_ams", + "app_check_for_updates", "app_open_web_page", "plugin_refresh"}; + // The plugin commands that run a plugin's code or reach the cloud account: a plugin switched on or loaded again + // runs its code, a cloud plugin is downloaded, and Unsubscribe ends a subscription. + const std::set plugins_reaching_out{"plugin_enable", "plugin_reload", "plugin_uninstall"}; + std::set destructive, read_only; + for (const NativeCommand& c : NativeCommands::instance().commands()) { + if (c.group == Slic3r::GUI::kDesignGroup) + continue; + INFO(c.key); + if (c.destructive) + destructive.insert(c.key); + if (c.read_only) + read_only.insert(c.key); + if (c.listed) { + CHECK_FALSE(c.description.empty()); + CHECK(c.input_schema.value("type", std::string()) == "object"); + } + } + CHECK(destructive == std::set{"preset_delete", "plugin_uninstall"}); + CHECK(read_only == reads); + std::set reaching_out = rows_reaching_out; + reaching_out.insert(plugins_reaching_out.begin(), plugins_reaching_out.end()); + for (const std::string& key : reaching_out) { + INFO(key); + const NativeCommand* c = NativeCommands::find(key); + REQUIRE(c != nullptr); + CHECK(c->open_world); + } +} + +TEST_CASE("the plugin commands name the plugin they act on, and an install replaces one only when told to", "[CommandCatalog]") +{ + const auto required = [](const char* key) { + const NativeCommand* c = NativeCommands::find(key); + REQUIRE(c != nullptr); + std::set names; + for (const json& name : c->input_schema.value("required", json::array())) + names.insert(name.get()); + return names; + }; + CHECK(required("plugin_enable") == std::set{"plugin", "enabled"}); + CHECK(required("plugin_uninstall") == std::set{"plugin"}); + CHECK(required("plugin_reload") == std::set{"plugin"}); + CHECK(required("plugin_list").empty()); + CHECK(required("plugin_refresh").empty()); + const NativeCommand* enable = NativeCommands::find("plugin_enable"); + REQUIRE(enable != nullptr); + CHECK(enable->input_schema.at("properties").contains("capability")); + const NativeCommand* reload = NativeCommands::find("plugin_reload"); + REQUIRE(reload != nullptr); + CHECK(reload->input_schema.at("properties").contains("clear_cache")); + const NativeCommand* install = NativeCommands::find("plugin_install_local"); + REQUIRE(install != nullptr); + CHECK(install->input_schema.at("properties").at("overwrite").at("type") == "boolean"); +} + +TEST_CASE("a call with no arguments is not titled as a tile that collects a value", "[CommandCatalog]") +{ + // view_set's Go to tab and Go to layer have no arguments of their own: their call takes its value from the Speed + // Dial's second phase, so a call with none is view_set's, and a call with the value is the tile's command with it. + const NativeCommand* view = NativeCommands::find("view_set"); + REQUIRE(view != nullptr); + CHECK(Slic3r::GUI::tile_with_args(*view, json::object()) == nullptr); + CHECK(Slic3r::GUI::call_title(*view, json::object()) == view->title); + // A tile that collects nothing titles its call. + CHECK(Slic3r::GUI::call_title(*view, {{"camera", "top"}}) == "View: Top"); +} + +TEST_CASE("the four commands with a person's form take it with no arguments", "[CommandCatalog]") +{ + for (const char* key : {"project_new", "project_save", "recording_start", "recording_stop"}) { + INFO(key); + const NativeCommand* c = NativeCommands::find(key); + REQUIRE(c != nullptr); + CHECK(Mcp::person_form(*c, json::object())); + } + const NativeCommand* fresh = NativeCommands::find("project_new"); + REQUIRE(fresh != nullptr); + json silent{{"silent", true}}; + CHECK(Mcp::argument_error(*fresh, silent).empty()); + CHECK_FALSE(Mcp::person_form(*fresh, silent)); + + // Its silent form requires path, which its person's form does not. + const NativeCommand* save = NativeCommands::find("project_save"); + REQUIRE(save != nullptr); + json none = json::object(); + CHECK(Mcp::argument_error(*save, none).empty()); + json path{{"path", "a.3mf"}}; + CHECK(Mcp::argument_error(*save, path).empty()); + json only_silent{{"silent", true}}; + CHECK_THAT(Mcp::argument_error(*save, only_silent), ContainsSubstring("path")); } TEST_CASE("every key of the process catalog is unique, tools and commands together", "[CommandCatalog]") @@ -162,39 +646,47 @@ TEST_CASE("every key of the process catalog is unique, tools and commands togeth INFO(c.key); CHECK(keys.insert(c.key).second); } - // The Speed Dial's commands and the typed tools are both there. - CHECK(keys.count("obj_arrange") == 1); - CHECK(keys.count("get_app_state") == 1); + // The commands made from menu rows and the typed tools are both there. + CHECK(keys.count("object_mirror") == 1); + CHECK(keys.count("app_state") == 1); } -TEST_CASE("the typed tools are listed and the four merged commands are both", "[CommandCatalog]") +TEST_CASE("the typed tools are listed and the merged commands are both", "[CommandCatalog]") { - for (const char* key : {"new_project", "save_project", "start_recording", "stop_recording"}) { + // A tool whose row is an item of its tiles, with the row's title, section and icon. + for (const auto& [key, tile_key, title] : {std::make_tuple("project_new", "new_project", "New Project"), + std::make_tuple("project_save", "save_project", "Save Project"), + std::make_tuple("recording_start", "start_recording", "Start Recording"), + std::make_tuple("recording_stop", "stop_recording", "Stop Recording")}) { INFO(key); const NativeCommand* merged = NativeCommands::find(key); REQUIRE(merged != nullptr); CHECK(merged->listed); - CHECK(merged->in_palette); - // The Speed Dial's title and section. - CHECK(merged->group == "Commands"); - CHECK_FALSE(merged->icon.empty()); + CHECK_FALSE(merged->in_palette); + const auto [command, tile] = Slic3r::GUI::find_tile(NativeCommands::instance(), tile_key); + CHECK(command == merged); + REQUIRE(tile != nullptr); + CHECK(tile->at("title") == title); + CHECK(tile->at("group") == "Commands"); + CHECK_FALSE(tile->at("icon").get().empty()); } - CHECK(NativeCommands::find("new_project")->title == "New Project"); - const NativeCommand* tool = NativeCommands::find("get_app_state"); + const NativeCommand* tool = NativeCommands::find("app_state"); REQUIRE(tool != nullptr); CHECK(tool->listed); CHECK_FALSE(tool->in_palette); - const NativeCommand* tile = NativeCommands::find("obj_arrange"); - REQUIRE(tile != nullptr); - CHECK_FALSE(tile->listed); - CHECK(tile->in_palette); + // A command made from menu rows is listed too, as it runs from its arguments: its rows are its tiles. + const NativeCommand* rows = NativeCommands::find("object_mirror"); + REQUIRE(rows != nullptr); + CHECK(rows->listed); + CHECK_FALSE(rows->in_palette); + CHECK(rows->tiles.size() == 3); } -TEST_CASE("no typed tool is in the palette", "[CommandCatalog]") +TEST_CASE("the palette's tiles are under the rows' keys, not the tools' names", "[CommandCatalog]") { - // Every tile of the Speed Dial: its own commands, the four merged ones among them, and no other typed tool. + // Every tile of the Speed Dial by its key: a typed tool is there only through its rows' tiles. const std::set tiles{ "add_handy_3dbenchy", "add_handy_autodesk_fdm_test", "add_handy_cali_cat", "add_handy_orca_badge", "add_handy_orca_cube", "add_handy_orca_string_hell", "add_handy_orca_tolerance_test", "add_handy_orcasliced_combo", @@ -222,17 +714,19 @@ TEST_CASE("no typed tool is in the palette", "[CommandCatalog]") REQUIRE(tiles.size() == 129); std::set palette; - for (const NativeCommand* c : NativeCommands::palette_commands(NativeCommands::instance())) - palette.insert(c->key); + for (const NativeCommands::PaletteTile& t : NativeCommands::palette_tiles(NativeCommands::instance())) + palette.insert(t.tile != nullptr ? t.tile->at("key").get() : t.command->key); CHECK(palette == tiles); CHECK(palette.count("new_project") == 1); - CHECK(palette.count("get_app_state") == 0); - CHECK(palette.count("slice") == 0); + CHECK(palette.count("project_new") == 0); + CHECK(palette.count("app_state") == 0); + // plate_slice's tiles are slice_and_preview and slice_all. + CHECK(palette.count("plate_slice") == 0); } TEST_CASE("a merged command accepts silent and publishes its form", "[CommandCatalog]") { - const NativeCommand* save = NativeCommands::find("save_project"); + const NativeCommand* save = NativeCommands::find("project_save"); REQUIRE(save != nullptr); CHECK_FALSE(save->input_schema.contains("required")); CHECK(save->input_schema["then"]["required"] == json::array({"path"})); @@ -243,7 +737,7 @@ TEST_CASE("a merged command accepts silent and publishes its form", "[CommandCat json silent{{"silent", true}}; CHECK_THAT(Mcp::argument_error(*save, silent), ContainsSubstring("path")); - const NativeCommand* fresh = NativeCommands::find("new_project"); + const NativeCommand* fresh = NativeCommands::find("project_new"); REQUIRE(fresh != nullptr); const json& properties = fresh->input_schema["properties"]; for (const char* name : {"silent", "discard_changes", "preset_changes"}) { @@ -252,35 +746,88 @@ TEST_CASE("a merged command accepts silent and publishes its form", "[CommandCat } } -TEST_CASE("a merged command's call with no arguments is the person's form", "[CommandCatalog]") +TEST_CASE("a merged command's call with a tile's arguments is the person's form", "[CommandCatalog]") { - int tool_calls = 0, person_calls = 0; - const json schema{{"type", "object"}, {"properties", {{"path", {{"type", "string"}}}}}, {"required", {"path"}}}; - const auto tool = NativeCommands::long_command("k", "K", "", schema, [&tool_calls](const json&, ToolContext&) { + int tool_calls = 0; + json person_args; // what each run of the person's form was given + const json schema{{"type", "object"}, + {"properties", {{"path", {{"type", "string"}}}, {"save_as", {{"type", "boolean"}}}}}, + {"required", {"path"}}}; + auto tool = NativeCommands::long_command("k", "K", "", schema, [&tool_calls](const json&, ToolContext&) { ++tool_calls; return ToolResult::ok({{"tool", true}}); }); - const NativeCommand merged = NativeCommands::with_person_form(tool, "K", "Commands", "menu_save", [&person_calls] { - ++person_calls; + tool.in_palette = true; + tool.tiles = json::array({NativeCommands::tile("k_as", "K as", "Commands", "", {{"save_as", true}}, "Saves as.")}); + const NativeCommand merged = NativeCommands::with_person_form(tool, [&person_args](const json& tile_args) { + person_args.push_back(tile_args); return AppActionRunResult{AppActionRunResult::Level::Succeeded, "Asked"}; }); - CHECK(merged.in_palette); - CHECK(merged.title == "K"); - CHECK(merged.group == "Commands"); - CHECK(merged.icon == "menu_save"); CHECK(merged.input_schema["properties"].contains("silent")); + // Neither person's form needs what the silent one requires. + CHECK(merged.input_schema["if"] == json{{"not", {{"enum", json::array({json::object(), {{"save_as", true}}})}}}}); - TestContext agent; - const ToolResult asked = merged.run(json::object(), agent); - CHECK(person_calls == 1); - CHECK(tool_calls == 0); + TestContext agent; + const ToolResult asked = merged.run(json::object(), agent); CHECK(asked.data["ran"] == "k"); + merged.run({{"save_as", true}}, agent); + CHECK(person_args == json::array({json::object(), {{"save_as", true}}})); + CHECK(tool_calls == 0); const ToolResult given = merged.run({{"path", "a"}}, agent); - CHECK(person_calls == 1); + CHECK(person_args.size() == 2); CHECK(tool_calls == 1); CHECK(given.data["tool"] == true); } +TEST_CASE("a pick of a tile whose row and tool are one function runs it in place, and a call runs the tool", "[CommandCatalog]") +{ + int tool_calls = 0; + json person_args = json::array(); // what each run of the shared function for a pick was given + auto tool = NativeCommands::long_command("k", "K", "", no_arguments(), [&tool_calls](const json&, ToolContext&) { + ++tool_calls; + return ToolResult::ok({{"tool", true}}); + }); + tool.tiles = json::array({NativeCommands::tile("k_row", "Row", "View", "", {{"row", true}}, "The row's function."), + NativeCommands::tile("k_tool", "Tool", "View", "", {{"camera", "top"}}, "The tool's function."), + NativeCommands::tile("k_input", "Input", "View", "", json::object(), "A value it collects.", "percent", + "level")}); + const NativeCommand merged = NativeCommands::with_row_forms( + tool, + [&person_args](const json& tile_args) { + person_args.push_back(tile_args); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; + }, + /*person_form_behind_dialogs=*/false, std::vector{json{{"camera", "top"}}}); + // The row's tile and the tool's are person's forms of the command; the tile that collects a value is not. + CHECK(Mcp::person_form(merged, {{"row", true}})); + CHECK(Mcp::person_form(merged, {{"camera", "top"}})); + CHECK_FALSE(Mcp::person_form(merged, {{"level", 50}})); + + // An automated call: the row's tile runs the row, the tool's own form and the input tile's call run the tool. + TestContext agent; + merged.run({{"row", true}}, agent); + CHECK(person_args == json::array({{{"row", true}}})); + CHECK(merged.run({{"camera", "top"}}, agent).data["tool"] == true); + CHECK(merged.run({{"level", 50}}, agent).data["tool"] == true); + CHECK(tool_calls == 2); + CHECK(agent.submitted.empty()); + + // A person's pick of the tool's own form, and of the input tile with its value, runs the shared function in place: + // nothing is submitted as a job, and the tool's function does not run. + TestContext person(/*person=*/true); + const ToolResult picked = merged.run({{"camera", "top"}}, person); + CHECK_FALSE(picked.is_error); + REQUIRE(picked.notice != nullptr); + CHECK(picked.notice->level == AppActionRunResult::Level::Succeeded); + merged.run({{"level", 50}}, person); + CHECK(person_args == json::array({{{"row", true}}, {{"camera", "top"}}, {{"level", 50}}})); + CHECK(person.submitted.empty()); + CHECK(tool_calls == 2); + // Any other call of a person is the tool's, which a long command starts as a job. + merged.run({{"camera", "front"}}, person); + CHECK(person.submitted == std::vector{"k"}); +} + TEST_CASE("an agent's call of a person's form is checked as a mutate call, a person's is not", "[CommandCatalog]") { int person_calls = 0; @@ -288,12 +835,13 @@ TEST_CASE("an agent's call of a person's form is checked as a mutate call, a per return ToolResult::ok(); }); tool.guard = GuardClass::Inspect; // as the recording tools run, behind dialogs - const auto person = [&person_calls] { + tool.in_palette = true; + const auto person = [&person_calls](const json&) { ++person_calls; return AppActionRunResult{AppActionRunResult::Level::Succeeded, "Asked"}; }; - const NativeCommand opens = NativeCommands::with_person_form(tool, "K", "Commands", "", person); - const NativeCommand quiet = NativeCommands::with_person_form(tool, "K", "Commands", "", person, /*person_form_behind_dialogs=*/true); + const NativeCommand opens = NativeCommands::with_person_form(tool, person); + const NativeCommand quiet = NativeCommands::with_person_form(tool, person, /*person_form_behind_dialogs=*/true); // An agent's call asks the runtime's UI for the mutate check before the person's form runs: a context // without a runtime refuses it, and the form never runs. @@ -313,11 +861,12 @@ TEST_CASE("an agent's call of a person's form is checked as a mutate call, a per TEST_CASE("a silent call is journaled silent", "[CommandCatalog]") { - const NativeCommand tool = NativeCommands::long_command("k", "K", "", no_arguments(), [](const json& args, ToolContext& ctx) { + NativeCommand tool = NativeCommands::long_command("k", "K", "", no_arguments(), [](const json& args, ToolContext& ctx) { ctx.set_journal_args(args); return ToolResult::ok(); }); - const NativeCommand merged = NativeCommands::with_person_form(tool, "K", "Commands", "", [] { return AppActionRunResult{}; }); + tool.in_palette = true; + const NativeCommand merged = NativeCommands::with_person_form(tool, [](const json&) { return AppActionRunResult{}; }); TestContext agent; merged.run({{"silent", true}}, agent); @@ -326,7 +875,7 @@ TEST_CASE("a silent call is journaled silent", "[CommandCatalog]") TEST_CASE("a recording started with arguments lasts an hour by default", "[CommandCatalog]") { - const NativeCommand* start = NativeCommands::find("start_recording"); + const NativeCommand* start = NativeCommands::find("recording_start"); REQUIRE(start != nullptr); CHECK_THAT(start->input_schema["properties"]["max_seconds"]["description"].get(), ContainsSubstring("default 3600")); } @@ -346,19 +895,21 @@ TEST_CASE("the catalog needs no runtime", "[CommandCatalog]") std::set names; for (const json& tool : tools) names.insert(tool["name"].get()); - CHECK(names.count("get_app_state") == 1); - CHECK(names.count("call_tool") == 1); - CHECK(names.count("obj_arrange") == 0); + CHECK(names.count("app_state") == 1); + CHECK(names.count("tool_call") == 1); + CHECK(names.count("object_mirror") == 1); + // A menu row with no argument form is not. + CHECK(names.count("settings_toggle_developer_mode") == 0); } -TEST_CASE("a Speed Dial command is found by the one lookup", "[CommandCatalog]") +TEST_CASE("a command made from menu rows is found by the one lookup", "[CommandCatalog]") { const CommandCatalog& catalog = NativeCommands::instance(); - CHECK(catalog.lookup("obj_arrange") != nullptr); - // A misspelt key is answered with the closest command, which call_tool runs, not with a tile's run_action. - const std::string unknown = catalog.unknown_command("obj_arange", /*suggest=*/true); - CHECK_THAT(unknown, ContainsSubstring("obj_arrange")); - CHECK_THAT(unknown, !ContainsSubstring("run_action")); + CHECK(catalog.lookup("object_mirror") != nullptr); + // A misspelt key is answered with the closest command, which tool_call runs, not with a tile's action_run. + const std::string unknown = catalog.unknown_command("object_miror", /*suggest=*/true); + CHECK_THAT(unknown, ContainsSubstring("object_mirror")); + CHECK_THAT(unknown, !ContainsSubstring("action_run")); } TEST_CASE("a command the catalog leaves out is unknown with the reason", "[CommandCatalog]") @@ -390,7 +941,7 @@ TEST_CASE("a command the catalog leaves out is unknown with the reason", "[Comma #else CHECK(no_cad.left_out("extrude") == nullptr); #endif - CHECK(no_cad.left_out("obj_arrange") == nullptr); + CHECK(no_cad.left_out("object_arrange") == nullptr); } TEST_CASE("every expected-id argument of a schema is in id_args", "[CommandCatalog]") @@ -404,7 +955,7 @@ TEST_CASE("every expected-id argument of a schema is in id_args", "[CommandCatal in_schema.insert(name); CHECK(std::set(c.id_args.begin(), c.id_args.end()) == in_schema); } - for (const char* key : {"transform", "select_objects", "set_settings"}) { + for (const char* key : {"object_transform", "object_select", "settings_set"}) { INFO(key); const NativeCommand* takes_ids = NativeCommands::find(key); REQUIRE(takes_ids != nullptr); @@ -420,24 +971,39 @@ TEST_CASE("the process catalog is built once", "[CommandCatalog]") CHECK(&NativeCommands::instance() == &catalog); } -TEST_CASE("the palette is the commands with in_palette", "[CommandCatalog]") +TEST_CASE("the palette is the commands' own tiles and their items, in the catalog's order", "[CommandCatalog]") { CommandCatalog catalog; catalog.add(command("first", true)); catalog.add(command("typed_tool", false)); - catalog.add(command("last", true)); + NativeCommand folded = command("folded", true); + folded.tiles = json::array({NativeCommands::tile("folded_x", "X", "View", "", {{"axis", "x"}}, "Along X."), + NativeCommands::tile("folded_y", "Y", "View", "", {{"axis", "y"}}, "Along Y.")}); + catalog.add(std::move(folded)); + // A listed command's tiles are the palette's as any other's. + NativeCommand items_only = command("items_only", false); + items_only.listed = true; + items_only.tiles = json::array({NativeCommands::tile("items_only_tab", "Tab", "Commands", "", json::object(), "A tab.", "tab")}); + catalog.add(std::move(items_only)); catalog.seal(); - const std::vector palette = NativeCommands::palette_commands(catalog); - REQUIRE(palette.size() == 2); - CHECK(palette[0] == catalog.find("first")); - CHECK(palette[1] == catalog.find("last")); + const std::vector palette = NativeCommands::palette_tiles(catalog); + REQUIRE(palette.size() == 5); + CHECK(palette[0].command == catalog.find("first")); + CHECK(palette[0].tile == nullptr); + CHECK(palette[1].command == catalog.find("folded")); + CHECK(palette[1].tile == nullptr); + CHECK(palette[2].tile == &catalog.find("folded")->tiles[0]); + CHECK(palette[3].tile == &catalog.find("folded")->tiles[1]); + CHECK(palette[4].command == catalog.find("items_only")); + REQUIRE(palette[4].tile != nullptr); + CHECK(palette[4].tile->at("input") == "tab"); } TEST_CASE("a sealed catalog is read from eight threads", "[CommandCatalog]") { // Keys the catalog holds, misspells and lacks; each thread asks about them in turn. - const std::vector keys{"slice_all", "undo", "slice_al", "export_gcod", "no_such_command"}; + const std::vector keys{"plate_slice", "undo", "plate_slic", "project_expor", "no_such_command"}; struct Answer { const NativeCommand* found = nullptr; @@ -472,17 +1038,17 @@ TEST_CASE("a sealed catalog is read from eight threads", "[CommandCatalog]") // And they are the right answers. const std::vector& first = answers.front(); REQUIRE(first[0].found != nullptr); - CHECK(first[0].found->key == "slice_all"); + CHECK(first[0].found->key == "plate_slice"); CHECK(first[2].found == nullptr); REQUIRE_FALSE(first[2].similar.empty()); - CHECK(first[2].similar.front() == "slice_all"); + CHECK(first[2].similar.front() == "plate_slice"); CHECK(first[4].found == nullptr); } TEST_CASE("a person's pick runs the function in place", "[CommandCatalog]") { int calls = 0; - const NativeCommand c = NativeCommands::ui_command("k", "K", "Commands", no_arguments(), [&calls](const json&) { + const NativeCommand c = NativeCommands::ui_command("k", "K", "The app", no_arguments(), [&calls](const json&) { ++calls; return AppActionRunResult{AppActionRunResult::Level::Succeeded, "Done"}; }); @@ -496,7 +1062,7 @@ TEST_CASE("a person's pick runs the function in place", "[CommandCatalog]") TEST_CASE("a person's pick shows a command's refusal as an error", "[CommandCatalog]") { - const NativeCommand refuses = NativeCommands::ui_command("k", "K", "Commands", no_arguments(), [](const json&) -> AppActionRunResult { + const NativeCommand refuses = NativeCommands::ui_command("k", "K", "The app", no_arguments(), [](const json&) -> AppActionRunResult { throw ToolFailure("Nothing is selected"); }); const AppActionRunResult shown = NativeCommands::run(refuses); @@ -508,7 +1074,7 @@ TEST_CASE("a person's pick shows a command's refusal as an error", "[CommandCata TEST_CASE("an exception that is not a command's refusal leaves a person's pick", "[CommandCatalog]") { // A defect, which the application's handler deals with as it does one from any other event handler. - const NativeCommand breaks = NativeCommands::ui_command("k", "K", "Commands", no_arguments(), [](const json&) -> AppActionRunResult { + const NativeCommand breaks = NativeCommands::ui_command("k", "K", "The app", no_arguments(), [](const json&) -> AppActionRunResult { throw std::out_of_range("no such element"); }); CHECK_THROWS_AS(NativeCommands::run(breaks), std::out_of_range); @@ -522,11 +1088,11 @@ TEST_CASE("a long command picked by a person is submitted", "[CommandCatalog]") return ToolResult::ok(); }; TestContext person(true); - NativeCommands::long_command("k", "K", "Commands", no_arguments(), fn).run(json::object(), person); + NativeCommands::long_command("k", "K", "The app", no_arguments(), fn).run(json::object(), person); CHECK(person.submitted == std::vector{"k"}); CHECK(calls == 0); - const NativeCommand in_place = NativeCommands::long_command("k", "K", "Commands", no_arguments(), fn, true); + const NativeCommand in_place = NativeCommands::long_command("k", "K", "The app", no_arguments(), fn, true); CHECK(in_place.inline_call); in_place.run(json::object(), person); CHECK(calls == 1); @@ -534,7 +1100,7 @@ TEST_CASE("a long command picked by a person is submitted", "[CommandCatalog]") // An agent's call is already a job: the function runs. TestContext agent; - NativeCommands::long_command("k", "K", "Commands", no_arguments(), fn).run(json::object(), agent); + NativeCommands::long_command("k", "K", "The app", no_arguments(), fn).run(json::object(), agent); CHECK(calls == 2); CHECK(agent.submitted.empty()); } @@ -544,13 +1110,13 @@ TEST_CASE("a person's submit refuses an unknown command, and starts no job witho // The lookup comes first; starting the runtime, the job and its notices need the app, which no unit test runs. Mcp::PersonContext person; CHECK_THROWS_WITH(person.submit("no_such_command", json::object()), ContainsSubstring("Unknown command no_such_command")); - CHECK_THROWS_AS(person.submit("run_script", json::object()), ToolFailure); + CHECK_THROWS_AS(person.submit("script_run", json::object()), ToolFailure); } TEST_CASE("an Export command called with arguments takes the project, and with none does not", "[CommandCatalog]") { const auto fails = [](const json&) { return AppActionRunResult{AppActionRunResult::Level::Error, "Nothing to export", false}; }; - const NativeCommand exporting = NativeCommands::ui_command("k", "K", "Commands", no_arguments(), fails, CommandCompletion::Deferred); + const NativeCommand exporting = NativeCommands::ui_command("k", "K", "The app", no_arguments(), fails, CommandCompletion::Deferred); CHECK(exporting.completion == CommandCompletion::Deferred); TestContext given; @@ -563,26 +1129,38 @@ TEST_CASE("an Export command called with arguments takes the project, and with n exporting.run(json::object(), none); CHECK(none.operations == 0); - const NativeCommand plain = NativeCommands::ui_command("k", "K", "Commands", no_arguments(), fails); + const NativeCommand plain = NativeCommands::ui_command("k", "K", "The app", no_arguments(), fails); TestContext either; plain.run({{"path", "a.gcode"}}, either); plain.run(json::object(), either); CHECK(either.operations == 0); } -TEST_CASE("a command with a second phase refuses a call without its value", "[CommandCatalog]") +TEST_CASE("a tile with a second phase takes its value, typed as its command's argument", "[CommandCatalog]") { - json none = json::object(); - CHECK_THAT(Mcp::argument_error(*NativeCommands::find("go_to_tab"), none), ContainsSubstring("tab")); - none = json::object(); - CHECK_THAT(Mcp::argument_error(*NativeCommands::find("go_to_layer"), none), ContainsSubstring("percent")); - json percent{{"percent", 50}}; - CHECK(Mcp::argument_error(*NativeCommands::find("go_to_layer"), percent).empty()); + const CommandCatalog& catalog = NativeCommands::instance(); + for (const auto& [key, input, value] : {std::make_tuple("go_to_tab", "tab", json("preview")), std::make_tuple("go_to_layer", "percent", json(50))}) { + INFO(key); + const auto [command, tile] = Slic3r::GUI::find_tile(catalog, key); + REQUIRE(command != nullptr); + REQUIRE(tile != nullptr); + const std::unique_ptr action = NativeCommands::make_action(*command, *tile); + CHECK(action->input == input); + CHECK(action->input_schema["required"] == json::array({input})); + // The pick's value reaches view_set under its argument, which checks it. + json call = Slic3r::GUI::tile_call_args(tile, {{input, value}}); + CHECK(Mcp::argument_error(*command, call).empty()); + } + // The layer is a share of the layer range. + const NativeCommand* view = NativeCommands::find("view_set"); + REQUIRE(view != nullptr); + json over{{"layer_percent", 150}}; + CHECK_THAT(Mcp::argument_error(*view, over), ContainsSubstring("layer_percent")); } TEST_CASE("a rename to an empty name is refused before anything is renamed", "[CommandCatalog]") { - const NativeCommand* rename = NativeCommands::find("obj_rename"); + const NativeCommand* rename = NativeCommands::find("object_rename"); REQUIRE(rename != nullptr); // No app runs here: the refusal comes before the command looks at the object list. TestContext agent; @@ -598,7 +1176,7 @@ TEST_CASE("undo takes a history", "[CommandCatalog]") const NativeCommand* command = NativeCommands::find(key); REQUIRE(command != nullptr); CHECK(command->in_palette); - CHECK_FALSE(command->listed); + CHECK(command->listed); json design{{"history", "design"}}; CHECK(Mcp::argument_error(*command, design).empty()); json project{{"history", "project"}}; @@ -632,7 +1210,7 @@ TEST_CASE("a person's undo shows nothing where the Edit menu's is greyed, an age } } -TEST_CASE("a command's result reads as run_action's did", "[CommandCatalog]") +TEST_CASE("a command's result reads as action_run's did", "[CommandCatalog]") { using Level = AppActionRunResult::Level; const ToolResult done = NativeCommands::from_run_result("k", {Level::Succeeded, "Done"}); @@ -743,21 +1321,23 @@ TEST_CASE("the reference shows both forms of a two-form command", "[CommandCatal CommandCatalog catalog = catalog_with_design(); catalog.seal(); const json reference = Slic3r::GUI::catalog_reference(catalog); - std::vector two_forms{"save_project"}; + // Each with what its person's forms are: {} alone, or the arguments of each of its tiles. + std::vector> two_forms{ + {"project_save", {{"not", {{"enum", json::array({json::object(), {{"save_as", true}}})}}}}}}; #ifdef SLIC3R_CAD - two_forms.push_back("fillet"); + two_forms.emplace_back("fillet", json{{"minProperties", 1}}); #endif - for (const std::string& key : two_forms) { + for (const auto& [key, person_forms] : two_forms) { INFO(key); const json entry = reference_entry(reference, key); REQUIRE(entry.is_object()); const json& schema = entry.at("input_schema"); CHECK(schema.at("properties").contains("silent")); - // The silent form's requirement holds once a call gives any argument; the person's form needs none. + // The silent form's requirement holds for any call but a person's form, which needs none of it. CHECK_FALSE(schema.contains("required")); - CHECK(schema.at("if") == json{{"minProperties", 1}}); + CHECK(schema.at("if") == person_forms); REQUIRE(schema.at("then").contains("required")); CHECK_FALSE(schema.at("then").at("required").empty()); } - CHECK(reference_entry(reference, "save_project")["input_schema"]["then"]["required"] == json::array({"path"})); + CHECK(reference_entry(reference, "project_save")["input_schema"]["then"]["required"] == json::array({"path"})); } diff --git a/tests/slic3rutils/test_mcp_cad.cpp b/tests/slic3rutils/test_mcp_cad.cpp index 01b15f2dd7..7e40e8bcb4 100644 --- a/tests/slic3rutils/test_mcp_cad.cpp +++ b/tests/slic3rutils/test_mcp_cad.cpp @@ -41,6 +41,7 @@ #include "slic3r/GUI/Mcp/McpTools.hpp" #include "slic3r/GUI/Mcp/McpToolsCad.hpp" #include "slic3r/GUI/NativeCommands.hpp" +#include "retired_names.hpp" #include "test_utils.hpp" #include @@ -62,6 +63,7 @@ #include #include #include +#include #include #include #include @@ -334,7 +336,7 @@ TEST_CASE("the CAD commands are the Design table's entries but its greyed and fo INFO(GUI::kDesignTools[i].id); CHECK(keys.count(GUI::kDesignTools[i].id) == (GUI::Mcp::is_design_command(GUI::kDesignTools[i]) ? 1u : 0u)); } - // The body's move is named apart from the Prepare tool transform; undo and redo are the shared commands. + // The body's move is named apart from the Prepare tool object_transform; undo and redo are the shared commands. CHECK(keys.count("body_transform") == 1); for (const char* gone : {"transform", "undo", "redo", "align_to", "colour", "sk_length"}) { INFO(gone); @@ -1699,20 +1701,35 @@ TEST_CASE("the Design commands are the design's 88, under its headings", "[Mcp][ "Menu rows"}); } -TEST_CASE("the search_tools description names every Design command under its heading", "[Mcp][CAD]") +TEST_CASE("the tool_search description names every Design command under its heading", "[Mcp][CAD]") { const GUI::CommandCatalog with = catalog_with_cad(); GUI::CommandCatalog without; GUI::NativeCommands::register_all_commands(without, {false}); without.seal(); - const std::string told = command_of(with, "search_tools").description; - const std::string plain = command_of(without, "search_tools").description; + const std::string told = command_of(with, "tool_search").description; + const std::string plain = command_of(without, "tool_search").description; // With the feature off the description says nothing of them; with it on, the index follows that text. REQUIRE(told.size() > plain.size()); CHECK(told.compare(0, plain.size(), plain) == 0); // The most a client is known to keep of a description. CHECK(told.size() <= 4096); + // An agent reads it before it calls anything: no word of it is a retired command's name, and before the Design tab's + // index it names no command, as the tool list shows them all. + CHECK(retired_names_in(told) == std::set{}); + std::set commands_named; + std::string word; + for (const char ch : plain + ' ') { + if (std::isalnum(static_cast(ch)) || ch == '_') { + word += ch; + continue; + } + if (without.find(word) != nullptr) + commands_named.insert(word); + word.clear(); + } + CHECK(commands_named == std::set{}); const std::string index = told.substr(plain.size()); CHECK_THAT(index, ContainsSubstring("CAD")); CHECK_THAT(index, ContainsSubstring("look one up with tool")); @@ -1931,8 +1948,11 @@ TEST_CASE("every example passes its command's schema", "[Mcp][CAD]") CHECK(calls.back().at("tool") == c.key); } } - // The 83 Design commands with a silent form, undo and redo. - CHECK(described == 85); + // The 83 Design commands with a silent form, undo and redo, the six object and part commands of Parts 4a and 4b, + // Part 4c's filament_add_mixed, Part 5a's printer_list_models, printer_install and printer_uninstall, Part 5b's + // filament_install and filament_uninstall, Part 5c's preferences_set, and Part 5d's plugin_list, plugin_enable, + // plugin_reload and plugin_uninstall. + CHECK(described == 102); } TEST_CASE("an example's argument goes by a name its command takes", "[Mcp][CAD]") diff --git a/tests/slic3rutils/test_mcp_config.cpp b/tests/slic3rutils/test_mcp_config.cpp index 5924311c5a..73e166a1f3 100644 --- a/tests/slic3rutils/test_mcp_config.cpp +++ b/tests/slic3rutils/test_mcp_config.cpp @@ -11,14 +11,20 @@ #include #endif +#include #include #include #include +#include "slic3r/GUI/CommandCatalog.hpp" #include "slic3r/GUI/CommandTypes.hpp" +#include "slic3r/GUI/FilamentMapPanel.hpp" +#include "slic3r/GUI/Mcp/McpArguments.hpp" #include "slic3r/GUI/Mcp/McpEndpoint.hpp" #include "slic3r/GUI/Mcp/McpTools.hpp" #include "slic3r/GUI/Mcp/PythonScriptsDialog.hpp" +#include "slic3r/GUI/NativeCommands.hpp" +#include "slic3r/GUI/Operations/PreferenceOps.hpp" #include "libslic3r/AppConfig.hpp" #include "libslic3r/Config.hpp" @@ -37,7 +43,11 @@ #include #include #include +#include #include +#include +#include +#include #include #include #include @@ -151,9 +161,10 @@ TEST_CASE("an object's effective value is its override, else the process's", "[M CHECK(e["source"] == "object"); CHECK_FALSE(e.contains("parts")); + // The process's value is the global one, as the Process panel's Global row names it. e = effective_setting("sparse_infill_density", s.process, *s.object, nullptr); CHECK(e["effective"] == "15%"); - CHECK(e["source"] == "process"); + CHECK(e["source"] == "global"); // A key the process does not carry takes the option's default. e = effective_setting("enable_support", s.process, *s.object, nullptr); @@ -171,7 +182,7 @@ TEST_CASE("a modifier's override applies only inside its own volume", "[Mcp]") // For the object: the process value, with the modifier's listed apart. json e = effective_setting("sparse_infill_density", s.process, *s.object, nullptr); CHECK(e["effective"] == "15%"); - CHECK(e["source"] == "process"); + CHECK(e["source"] == "global"); REQUIRE(e["parts"].size() == 1); CHECK(e["parts"][0]["part"] == 1); CHECK(e["parts"][0]["value"] == "40%"); @@ -214,12 +225,168 @@ TEST_CASE("a filament of 0 is no filament of its own", "[Mcp]") e = effective_setting("extruder", s.process, *s.object, part); CHECK(e["effective"] == "3"); CHECK(e["source"] == "part"); + // A modifier's filament of 0 takes the filament of the part it overlaps, the object's where that part has none. e = effective_setting("extruder", s.process, *s.object, modifier); - CHECK(e["effective"] == "2"); - CHECK(e["source"] == "object"); + CHECK(e["effective"].is_null()); + CHECK(e["source"] == "overlapped_part"); + CHECK(e["object_effective"] == "2"); + CHECK(e["object_source"] == "object"); + CHECK(e["parts"] == json::array({{{"part", 1}, {"value", "3"}}})); } -TEST_CASE("save_preset refuses the names the Save preset dialog refuses", "[Mcp]") +TEST_CASE("inside a modifier that sets none of a key, the value of the part it overlaps applies", "[Mcp]") +{ + Scene s; + s.object->config.set("wall_loops", 4); + s.object->volumes.front()->config.set("wall_loops", 5); + ModelVolume* modifier = s.add(ModelVolumeType::PARAMETER_MODIFIER); + + // The part's 5 prints inside the modifier where it overlaps that part, the object's 4 where it overlaps another + // part: no value is the one it prints with. + json e = effective_setting("wall_loops", s.process, *s.object, modifier); + CHECK(e["effective"].is_null()); + CHECK(e["source"] == "overlapped_part"); + CHECK(e["object_effective"] == "4"); + CHECK(e["object_source"] == "object"); + CHECK(e["parts"] == json::array({{{"part", 0}, {"value", "5"}}})); + CHECK_FALSE(e.contains("height_ranges")); + + // A modifier before it that sets the key is a region it can overlap too; one after it is not. + ModelVolume* later = s.add(ModelVolumeType::PARAMETER_MODIFIER); + later->config.set("wall_loops", 8); + CHECK(effective_setting("wall_loops", s.process, *s.object, modifier)["parts"] == json::array({{{"part", 0}, {"value", "5"}}})); + e = effective_setting("sparse_infill_density", s.process, *s.object, later); + CHECK(e["effective"] == "15%"); + CHECK(e["source"] == "global"); + modifier->config.set_key_value("sparse_infill_density", new ConfigOptionPercent(40)); + e = effective_setting("sparse_infill_density", s.process, *s.object, later); + CHECK(e["effective"].is_null()); + CHECK(e["object_effective"] == "15%"); + CHECK(e["object_source"] == "global"); + CHECK(e["parts"] == json::array({{{"part", 1}, {"value", "40%"}}})); + + // Where no part sets the key, the object's value is the one the modifier prints with. + e = effective_setting("enable_support", s.process, *s.object, modifier); + CHECK(e["effective"] == "0"); + CHECK(e["source"] == "default"); + CHECK_FALSE(e.contains("parts")); + CHECK_FALSE(e.contains("object_effective")); +} + +TEST_CASE("a painted modifier before a modifier that sets none of a key is a region it can overlap", "[Mcp]") +{ + Scene s; + s.object->config.set("wall_loops", 4); + ModelVolume* painted = s.add(ModelVolumeType::PAINTED_MODIFIER); + painted->config.set("wall_loops", 7); + ModelVolume* modifier = s.add(ModelVolumeType::PARAMETER_MODIFIER); + + // The slicer chains the mesh modifier's region onto the painted modifier's as onto a part's: 7 where it overlaps it. + const json e = effective_setting("wall_loops", s.process, *s.object, modifier); + CHECK(e["effective"].is_null()); + CHECK(e["source"] == "overlapped_part"); + CHECK(e["object_effective"] == "4"); + CHECK(e["object_source"] == "object"); + CHECK(e["parts"] == json::array({{{"part", 1}, {"value", "7"}}})); +} + +TEST_CASE("inside a painted modifier that sets none of a key, the value of the part it overlaps applies", "[Mcp]") +{ + Scene s; + s.object->config.set("wall_loops", 4); + s.object->volumes.front()->config.set("wall_loops", 5); + ModelVolume* painted = s.add(ModelVolumeType::PAINTED_MODIFIER); + DynamicPrintConfig lower; + lower.set_key_value("layer_height", new ConfigOptionFloat(0.2)); + lower.set_key_value("wall_loops", new ConfigOptionInt(6)); + s.object->layer_config_ranges[{0., 5.}].assign_config(lower); + + // As inside a mesh modifier: the part's value, and the range's between its heights. + json e = effective_setting("wall_loops", s.process, *s.object, painted); + CHECK(e["effective"].is_null()); + CHECK(e["source"] == "overlapped_part"); + CHECK(e["object_effective"] == "4"); + CHECK(e["object_source"] == "object"); + CHECK(e["parts"] == json::array({{{"part", 0}, {"value", "5"}}})); + CHECK(e["height_ranges"] == json::array({{{"min_z", 0.}, {"max_z", 5.}, {"value", "6"}}})); + + // One that sets the key holds its own value through the range. + painted->config.set("wall_loops", 7); + e = effective_setting("wall_loops", s.process, *s.object, painted); + CHECK(e["effective"] == "7"); + CHECK(e["source"] == "part"); + CHECK_FALSE(e.contains("height_ranges")); +} + +TEST_CASE("a painted modifier that sets a key is listed among an object's overriding volumes", "[Mcp]") +{ + Scene s; + s.object->config.set("wall_loops", 4); + ModelVolume* painted = s.add(ModelVolumeType::PAINTED_MODIFIER); + painted->config.set("wall_loops", 7); + DynamicPrintConfig lower; + lower.set_key_value("layer_height", new ConfigOptionFloat(0.2)); + lower.set_key_value("wall_loops", new ConfigOptionInt(6)); + s.object->layer_config_ranges[{0., 5.}].assign_config(lower); + const json painted_only = json::array({{{"part", 1}, {"value", "7"}}}); + + // For the object, and inside a height range that sets the key, where a modifier's own value still applies. + json e = effective_setting("wall_loops", s.process, *s.object, nullptr); + CHECK(e["effective"] == "4"); + CHECK(e["parts"] == painted_only); + e = effective_setting("wall_loops", s.process, *s.object, nullptr, &s.object->layer_config_ranges.begin()->second.get()); + CHECK(e["effective"] == "6"); + CHECK(e["source"] == "height_range"); + CHECK(e["parts"] == painted_only); +} + +TEST_CASE("a height range's value applies over its parts' own, and inside a modifier that sets none", "[Mcp]") +{ + Scene s; + s.object->config.set("wall_loops", 4); + ModelVolume* part = s.object->volumes.front(); + part->config.set("wall_loops", 5); + ModelVolume* modifier = s.add(ModelVolumeType::PARAMETER_MODIFIER); + DynamicPrintConfig lower; + lower.set_key_value("layer_height", new ConfigOptionFloat(0.2)); + lower.set_key_value("wall_loops", new ConfigOptionInt(6)); + s.object->layer_config_ranges[{0., 5.}].assign_config(lower); + const json ranges = json::array({{{"min_z", 0.}, {"max_z", 5.}, {"value", "6"}}}); + + // The object's and the part's own values, with the range's between its heights. + json e = effective_setting("wall_loops", s.process, *s.object, nullptr); + CHECK(e["effective"] == "4"); + CHECK(e["source"] == "object"); + CHECK(e["height_ranges"] == ranges); + e = effective_setting("wall_loops", s.process, *s.object, part); + CHECK(e["effective"] == "5"); + CHECK(e["source"] == "part"); + CHECK(e["height_ranges"] == ranges); + + // A modifier that sets none takes what it covers: the part's value, and the range's between its heights (its region + // inherits the part's region, which the range is applied to); one that sets the key holds its own value through + // the range. + e = effective_setting("wall_loops", s.process, *s.object, modifier); + CHECK(e["effective"].is_null()); + CHECK(e["source"] == "overlapped_part"); + CHECK(e["object_effective"] == "4"); + CHECK(e["parts"] == json::array({{{"part", 0}, {"value", "5"}}})); + CHECK(e["height_ranges"] == ranges); + modifier->config.set("wall_loops", 7); + e = effective_setting("wall_loops", s.process, *s.object, modifier); + CHECK(e["effective"] == "7"); + CHECK(e["source"] == "part"); + CHECK_FALSE(e.contains("height_ranges")); + + // The range itself: its value, over the part's, which it replaces; the modifier's still applies inside it. + e = effective_setting("wall_loops", s.process, *s.object, nullptr, &s.object->layer_config_ranges.begin()->second.get()); + CHECK(e["effective"] == "6"); + CHECK(e["source"] == "height_range"); + CHECK(e["parts"] == json::array({{{"part", 1}, {"value", "7"}}})); + CHECK_FALSE(e.contains("height_ranges")); +} + +TEST_CASE("preset_save refuses the names the Save preset dialog refuses", "[Mcp]") { using Catch::Matchers::ContainsSubstring; Processes p; @@ -230,7 +397,7 @@ TEST_CASE("save_preset refuses the names the Save preset dialog refuses", "[Mcp] CHECK_THROWS_AS(save_preset_inside_project(p.presets, "0.20mm Standard", json{{"overwrite", true}}), ToolFailure); } -TEST_CASE("save_preset replaces another preset only with overwrite, and saves the selected one again without", "[Mcp]") +TEST_CASE("preset_save replaces another preset only with overwrite, and saves the selected one again without", "[Mcp]") { using Catch::Matchers::ContainsSubstring; Processes p; @@ -240,7 +407,7 @@ TEST_CASE("save_preset replaces another preset only with overwrite, and saves th CHECK_FALSE(save_preset_inside_project(p.presets, "Mine", json::object())); } -TEST_CASE("save_preset keeps a preset where the Save preset dialog would", "[Mcp]") +TEST_CASE("preset_save keeps a preset where the Save preset dialog would", "[Mcp]") { Processes p; // A new name: where the edited preset is, unless inside_project says otherwise. @@ -361,7 +528,7 @@ TEST_CASE("the printer's machine limits and per-extruder values name their entri CHECK_FALSE(e.contains("active")); } -TEST_CASE("set_settings writes a single value to the per-variant entries in use, or one entry by index", "[Mcp]") +TEST_CASE("settings_set writes a single value to the per-variant entries in use, or one entry by index", "[Mcp]") { using Catch::Matchers::ContainsSubstring; const DynamicPrintConfig process = x1c_process(); @@ -490,7 +657,7 @@ void add_preset(PresetCollection& presets, const std::string& name, const std::s } // namespace -TEST_CASE("delete_preset refuses the presets the tab does not delete", "[Mcp]") +TEST_CASE("preset_delete refuses the presets the tab does not delete", "[Mcp]") { using Catch::Matchers::ContainsSubstring; Processes p; @@ -568,7 +735,7 @@ TEST_CASE("the project scope takes one colour per slot and leaves a mixed slot's CHECK_THROWS_AS(check_filament_colours({"#FF00001", "#000000", "#7F7F7F"}, current, mixed), ToolFailure); CHECK_THROWS_WITH(check_filament_colours({"#FFFFFF", "#000000", "#FF0000"}, current, mixed), ContainsSubstring("Slot 3 is a mixed filament")); - // One slot by index, through set_settings' entry write. + // One slot by index, through settings_set's entry write. DynamicPrintConfig project; project.set_key_value("filament_colour", new ConfigOptionStrings(current)); CHECK(preset_setting_value("filament_colour", {{"index", 1}, {"value", "#00FF00"}}, project, {}, {}) == "#FFFFFF;#00FF00;#7F7F7F"); @@ -699,28 +866,635 @@ TEST_CASE("a plate's layer G-codes read back by height, on the layer the Preview CHECK_FALSE(layer_gcode_json(codes, {})[0].contains("layer")); } -TEST_CASE("the preferences scope reads the keys it is given, as stored, and lists none unasked", "[Mcp]") +namespace { + +// Three rows of the Preferences dialog's table, as preferences_get lists them: a checkbox, a choice and a number. +std::vector preference_table() +{ + Ops::Preference arrange; + arrange.key = "auto_arrange"; + arrange.tab = "behaviour"; + arrange.section = "Prepare"; + arrange.label = "Auto arrange plate after cloning"; + arrange.fallback = "false"; + Ops::Preference flush = arrange; + flush.key = "auto_calculate_flush"; + flush.label = "Auto flush after changing..."; + flush.kind = Ops::PreferenceKind::Choice; + flush.choices = {{"all", "All"}, {"color change", "Color"}, {"disabled", "None"}}; + flush.fallback = "all"; + Ops::Preference fps = arrange; + fps.key = "opengl_fps_cap"; + fps.tab = "graphics"; + fps.section = "FPS"; + fps.label = "FPS cap"; + fps.kind = Ops::PreferenceKind::Number; + fps.min = 0; + fps.max = 240; + fps.fallback = ""; + fps.refused = "%1%: a reason a call may not write it."; + return {arrange, flush, fps}; +} + +} // namespace + +TEST_CASE("preferences_get lists the dialog's preferences, typed, and reads a named key outside them as stored", "[Mcp]") { using Catch::Matchers::ContainsSubstring; - AppConfig config; + const std::vector table = preference_table(); + AppConfig config; config.set("auto_calculate_flush", "disabled"); + config.set("opengl_fps_cap", "60"); config.set("region", ""); config.set("presets", "filament", "Bambu PLA Basic"); // another section than the preferences' - const json out = preferences_settings(config, json{{"keys", {"auto_calculate_flush", "region", "filament", "no_such_preference"}}}); - REQUIRE(out["total"] == 2); - CHECK(out["items"][0] == json{{"key", "auto_calculate_flush"}, {"value", "disabled"}}); + config.erase("app", "auto_arrange"); + + // With no argument, every row of the table, in its order, with its value typed by its kind. + const json all = preferences_settings(config, table, json::object()); + REQUIRE(all["items"].size() == 3); + CHECK(all["total"] == 3); + // Nothing stored: the value the dialog shows, the checkbox unchecked. + CHECK(all["items"][0] == json{{"key", "auto_arrange"}, {"tab", "behaviour"}, {"section", "Prepare"}, + {"label", "Auto arrange plate after cloning"}, {"kind", "checkbox"}, {"value", false}, + {"stored", false}}); + CHECK(all["items"][1]["value"] == "disabled"); + CHECK(all["items"][1]["kind"] == "choice"); + CHECK(all["items"][1]["choices"] == json::array({{{"value", "all"}, {"label", "All"}}, + {{"value", "color change"}, {"label", "Color"}}, + {{"value", "disabled"}, {"label", "None"}}})); + CHECK_FALSE(all["items"][1].contains("stored")); + CHECK(all["items"][2]["value"] == 60); + CHECK(all["items"][2]["kind"] == "number"); + CHECK(all["items"][2]["min"] == 0); + CHECK(all["items"][2]["max"] == 240); + // A row a call may not write says why. + CHECK(all["items"][2]["refused"] == "opengl_fps_cap: a reason a call may not write it."); + CHECK_FALSE(all.contains("unknown_keys")); + + // tab and query narrow the list: query by a key's, a label's or a section's words, in any case. + const json graphics = preferences_settings(config, table, json{{"tab", "graphics"}}); + REQUIRE(graphics["items"].size() == 1); + CHECK(graphics["items"][0]["key"] == "opengl_fps_cap"); + const json flush = preferences_settings(config, table, json{{"query", "FLUSH after"}}); + REQUIRE(flush["items"].size() == 1); + CHECK(flush["items"][0]["key"] == "auto_calculate_flush"); + CHECK(preferences_settings(config, table, json{{"query", "prepare"}})["items"].size() == 2); + CHECK(preferences_settings(config, table, json{{"query", "prepare"}, {"tab", "graphics"}})["items"].empty()); + + // Named keys: those of the table as listed, another key of the app section as stored, and the others unknown. + const json named = + preferences_settings(config, table, json{{"keys", {"region", "auto_calculate_flush", "filament", "no_such_preference"}}}); + REQUIRE(named["items"].size() == 2); + CHECK(named["items"][0]["key"] == "auto_calculate_flush"); + CHECK(named["items"][0]["kind"] == "choice"); // A key stored empty is known, with its empty value. - CHECK(out["items"][1] == json{{"key", "region"}, {"value", ""}}); - CHECK(out["unknown_keys"] == json{"filament", "no_such_preference"}); - CHECK_THAT(out["note"].get(), ContainsSubstring("never changed")); - const json known = preferences_settings(config, json{{"keys", {"region"}}}); + CHECK(named["items"][1] == json{{"key", "region"}, {"value", ""}}); + CHECK(named["unknown_keys"] == json{"filament", "no_such_preference"}); + CHECK_THAT(named["note"].get(), ContainsSubstring("not stored")); + const json known = preferences_settings(config, table, json{{"keys", {"region"}}}); CHECK_FALSE(known.contains("unknown_keys")); CHECK_FALSE(known.contains("note")); +} - // The app section also holds account and device state, so nothing is listed without keys. - CHECK_THROWS_WITH(preferences_settings(config, json::object()), ContainsSubstring("keys")); - CHECK_THROWS_AS(preferences_settings(config, json{{"query", "flush"}}), ToolFailure); - CHECK_THROWS_AS(preferences_settings(config, json{{"keys", {"region"}}, {"compare", ":saved"}}), ToolFailure); +TEST_CASE("preferences_get gives what the dialog shows where that is not the stored value, and marks a value read at the next start", + "[Mcp]") +{ + std::vector table = preference_table(); + table[0].restart_needed = true; + AppConfig config; + config.set("opengl_fps_cap", "60"); + config.erase("app", "auto_arrange"); + + // The dialog shows a value of its own for a key: it is the value, typed by the kind, and stored still says whether + // the configuration holds one. + const json shown = preferences_settings(config, table, json::object(), {{"auto_arrange", "true"}, {"opengl_fps_cap", "14100"}}); + REQUIRE(shown["items"].size() == 3); + CHECK(shown["items"][0]["value"] == true); + CHECK(shown["items"][0]["stored"] == false); + CHECK(shown["items"][2]["value"] == 14100); + CHECK_FALSE(shown["items"][2].contains("stored")); + // Without one, the stored value. + CHECK(preferences_settings(config, table, json::object())["items"][2]["value"] == 60); + + // A row read at the next start says so; the others say nothing of it. + CHECK(shown["items"][0]["restart_needed"] == true); + CHECK_FALSE(shown["items"][1].contains("restart_needed")); +} + +namespace { + +// The values of an enum property of `command`'s schema, as a set. +std::set enum_of(const NativeCommand& command, const char* property) +{ + std::set values; + for (const json& v : command.input_schema.at("properties").at(property).at("enum")) + values.insert(v.get()); + return values; +} + +// A call's context that fails the case when the call reaches its UI closure. +class NoUiContext final : public ToolContext +{ +public: + json run_ui(const std::function& /*fn*/) override + { + FAIL("the call reached its UI closure"); + return json(); + } + json observe_ui(const std::function& /*fn*/) override + { + FAIL("the call reached its UI closure"); + return json(); + } + const std::string& job_id() const override { return m_job; } + bool cancelled() const override { return false; } + ToolResult call_child(const std::string& /*tool*/, const json& /*args*/) override { return ToolResult::error("no child calls"); } + std::set lineage() const override { return {}; } + void set_journal_args(json /*args*/) override {} + void begin_operation() override {} + +private: + std::string m_job; +}; + +// A call's context that runs its UI closures in place, for a check a call makes there before it reads the app. +class InPlaceContext final : public ToolContext +{ +public: + json run_ui(const std::function& fn) override { return fn(); } + json observe_ui(const std::function& fn) override { return fn(); } + const std::string& job_id() const override { return m_job; } + bool cancelled() const override { return false; } + ToolResult call_child(const std::string& /*tool*/, const json& /*args*/) override + { + return ToolResult::error("no child calls"); + } + std::set lineage() const override { return {}; } + void set_journal_args(json /*args*/) override {} + void begin_operation() override {} + +private: + std::string m_job; +}; + +} // namespace + +TEST_CASE("the settings tools take a type and a target", "[Mcp]") +{ + using Catch::Matchers::ContainsSubstring; + const NativeCommand* get = NativeCommands::find("settings_get"); + const NativeCommand* set = NativeCommands::find("settings_set"); + const NativeCommand* list = NativeCommands::find("settings_list"); + REQUIRE(get != nullptr); + REQUIRE(set != nullptr); + REQUIRE(list != nullptr); + for (const NativeCommand* c : {get, set}) { + INFO(c->key); + CHECK(enum_of(*c, "type") == std::set{"printer", "process", "filament"}); + CHECK(enum_of(*c, "target") == std::set{"global", "object", "part", "height_range"}); + CHECK_FALSE(c->input_schema["properties"].contains("scope")); + for (const char* range : {"min_z", "max_z"}) + CHECK(c->input_schema["properties"].contains(range)); + } + json scoped{{"scope", "process"}, {"keys", {"layer_height"}}}; + CHECK_THAT(argument_error(*get, scoped), ContainsSubstring("unknown argument scope")); + + // A type's settings, whole or one page of them: a preset's, or those an object or a region takes. + CHECK(list->input_schema["required"] == json::array({"type"})); + CHECK(enum_of(*list, "type") == std::set{"printer", "process", "filament", "object", "region"}); + for (const char* absent : {"target", "keys", "compare", "scope"}) { + INFO(absent); + CHECK_FALSE(list->input_schema["properties"].contains(absent)); + } + for (const char* present : {"where", "preset", "filament_slot", "include_meta", "limit", "offset"}) { + INFO(present); + CHECK(list->input_schema["properties"].contains(present)); + } + + // The refusals the arguments alone decide. + const json nothing{{"type", "process"}}; + const json no_target{{"type", "filament"}, {"target", "object"}, {"object", 0}, {"keys", {"wall_loops"}}}; + // Nothing named is worded for the tool called: what settings_get reads by, what settings_set writes. + const std::string read_nothing = settings_request_error(nothing); + const std::string write_nothing = settings_request_error(nothing, true); + CHECK_THAT(read_nothing, ContainsSubstring("Nothing is named")); + CHECK_THAT(read_nothing, ContainsSubstring("keys, query or compare")); + CHECK_THAT(write_nothing, ContainsSubstring("Nothing is named")); + CHECK_THAT(write_nothing, ContainsSubstring("values")); + CHECK_THAT(write_nothing, !ContainsSubstring("query")); + CHECK_THAT(settings_request_error(no_target), ContainsSubstring("no target object")); + CHECK_THAT(settings_request_error(no_target, true), ContainsSubstring("no target object")); + CHECK(settings_request_error({{"target", "object"}, {"object", 0}}).empty()); + CHECK(settings_request_error({{"target", "object"}, {"object", 0}, {"values", {{"wall_loops", 3}}}}, true).empty()); + CHECK_THAT(settings_request_error({{"target", "part"}, {"part", 0}}), ContainsSubstring("object")); + // With no object, or no part for the target part, the selected one. + CHECK(settings_request_error({{"target", "object"}}).empty()); + CHECK(settings_request_error({{"target", "part"}}).empty()); + CHECK(settings_request_error({{"target", "height_range"}, {"min_z", 0}, {"max_z", 5}}).empty()); + // Both tools refuse them before their UI closure. + for (const NativeCommand* c : {get, set}) + for (const json& args : {nothing, no_target}) { + INFO(c->key << " " << args.dump()); + NoUiContext ctx; + CHECK_THROWS_WITH(c->run(args, ctx), settings_request_error(args, c == set)); + } +} + +TEST_CASE("the settings tools' object, part and height range go with the target they name", "[Mcp]") +{ + using Catch::Matchers::ContainsSubstring; + const NativeCommand* get = NativeCommands::find("settings_get"); + const NativeCommand* set = NativeCommands::find("settings_set"); + REQUIRE(get != nullptr); + REQUIRE(set != nullptr); + // Each refused before anything is read, worded for what is wrong. + const std::vector> refused{ + {{{"object", 0}, {"keys", {"wall_loops"}}}, "give target object, part or height_range"}, + {{{"target", "object"}, {"object", 0}, {"part", 1}, {"keys", {"wall_loops"}}}, "part goes with target part"}, + {{{"target", "height_range"}, {"object", 0}, {"min_z", 0}}, "target height_range needs min_z and max_z"}, + {{{"target", "part"}, {"object", 0}, {"min_z", 0}, {"max_z", 5}}, "min_z and max_z go with target height_range"}, + {{{"target", "part"}, {"object", 0}, {"keys", {"wall_loops"}}}, "target part names its part by object and part"}}; + for (const auto& [args, message] : refused) { + INFO(args.dump()); + CHECK_THAT(settings_request_error(args), ContainsSubstring(message)); + json written = args; + written.erase("keys"); + written["values"] = {{"wall_loops", 3}}; + CHECK_THAT(settings_request_error(written, true), ContainsSubstring(message)); + for (const NativeCommand* c : {get, set}) { + const json call = c == set ? written : args; + json given = call; + CHECK(argument_error(*c, given).empty()); + NoUiContext ctx; + CHECK_THROWS_WITH(c->run(call, ctx), ContainsSubstring(message)); + } + } +} + +TEST_CASE("filament_install names filaments by names, or by a vendor and a filament type together", "[Mcp]") +{ + const NativeCommand* install = NativeCommands::find("filament_install"); + REQUIRE(install != nullptr); + // Each passes the schema, and the command refuses it before it reads the app. + const std::vector> refused{ + {json::object(), "Give names, or vendor and filament_type"}, + {{{"names", {"Bambu PLA Basic"}}, {"vendor", "Bambu Lab"}, {"filament_type", "PLA"}}, + "Give names, or vendor and filament_type, not both"}, + {{{"names", {"Bambu PLA Basic"}}, {"filament_type", "PLA"}}, "Give names, or vendor and filament_type, not both"}, + {{{"vendor", "Bambu Lab"}}, "vendor and filament_type go together"}, + {{{"filament_type", "PLA"}}, "vendor and filament_type go together"}}; + for (const auto& [args, message] : refused) { + INFO(args.dump()); + json given = args; + CHECK(argument_error(*install, given).empty()); + NoUiContext ctx; + CHECK_THROWS_WITH(install->run(args, ctx), message); + } +} + +TEST_CASE("preferences_set needs a preference to write", "[Mcp]") +{ + const NativeCommand* write = NativeCommands::find("preferences_set"); + REQUIRE(write != nullptr); + // It passes the schema, and the command refuses it before it reads the app. + json given = {{"values", json::object()}}; + CHECK(argument_error(*write, given).empty()); + NoUiContext ctx; + CHECK_THROWS_WITH(write->run(json{{"values", json::object()}}, ctx), + "values names no preference: give {key: value}, e.g. {\"auto_arrange\": false}"); +} + +TEST_CASE("plugin_enable refuses an empty capability before it reads the app", "[Mcp]") +{ + const NativeCommand* enable = NativeCommands::find("plugin_enable"); + REQUIRE(enable != nullptr); + CHECK(enable->input_schema.at("properties").at("capability").at("minLength") == 1); + // An empty name is no capability, and not the plugin itself either, which enabled false would unload. + const json empty{{"plugin", "my_plugin"}, {"capability", ""}, {"enabled", false}}; + NoUiContext ctx; + CHECK_THROWS_WITH(enable->run(empty, ctx), + "capability is empty: name one of the plugin's capabilities, or leave capability out to turn the plugin " + "itself on or off"); +} + +TEST_CASE("a target takes the settings its panel offers", "[Mcp]") +{ + using Targets = std::vector; + CHECK(targets_taking("layer_height", 1) == Targets{"object", "height_range"}); + CHECK(targets_taking("wall_loops", 1) == Targets{"object", "part", "height_range"}); + CHECK(targets_taking("skirt_loops", 1).empty()); + // Support is an object's alone, and a feature's filament is offered once there is a second filament. + CHECK(targets_taking("enable_support", 1) == Targets{"object"}); + CHECK(targets_taking("sparse_infill_filament_id", 1).empty()); + CHECK(targets_taking("sparse_infill_filament_id", 2) == Targets{"object", "part", "height_range"}); + + const std::vector object = target_options("object", 1); + const std::vector part = target_options("part", 1); + const std::vector range = target_options("height_range", 1); + CHECK(has(part, "wall_loops")); + CHECK_FALSE(has(part, "layer_height")); + // A part takes what an object takes, and a height range what a part takes and the layer height. + for (const std::string& key : part) { + INFO(key); + CHECK(has(object, key)); + CHECK(has(range, key)); + } + CHECK(has(range, "layer_height")); + CHECK(range.size() == part.size() + 1); + // The filament each row's filament column sets. + for (const std::vector* keys : {&object, &part, &range}) + CHECK(has(*keys, "extruder")); + CHECK(target_options("global", 1).empty()); +} + +TEST_CASE("a setting a target does not take is refused with where it can be set", "[Mcp]") +{ + using Catch::Matchers::ContainsSubstring; + const std::string layer_height = untaken_setting_error("layer_height", "part", 1); + CHECK_THAT(layer_height, ContainsSubstring("layer_height is set on an object or a height range, not on a part")); + CHECK_THAT(untaken_setting_error("enable_support", "height_range", 1), + ContainsSubstring("enable_support is set on an object, not on a height range")); + // A process setting no target takes is the process's alone. + const std::string skirt = untaken_setting_error("skirt_loops", "object", 1); + CHECK_THAT(skirt, ContainsSubstring("skirt_loops is set globally only")); + CHECK_THAT(skirt, !ContainsSubstring("height range")); + for (const char* target : {"object", "part", "height_range"}) { + INFO(target); + CHECK(untaken_setting_error("wall_loops", target, 1).empty()); + } +} + +TEST_CASE("listing a type returns it whole unless it carries meta", "[Mcp]") +{ + const NativeCommand* list = NativeCommands::find("settings_list"); + REQUIRE(list != nullptr); + CHECK(enum_of(*list, "type") == std::set{"process", "printer", "filament", "object", "region"}); + // The process settings of an X1 Carbon, as many as the app lists. + json items = json::array(); + for (int i = 0; i < 395; ++i) + items.push_back({{"key", "setting_" + std::to_string(i)}, {"value", "0"}}); + const json whole = settings_list_page(items, json::object()); + CHECK(whole["total"] == 395); + CHECK(whole["items"].size() == 395); + CHECK_FALSE(whole.contains("next_offset")); + // With meta, which where carries too, 100 a page. + for (const json& args : {json{{"include_meta", true}}, json{{"where", "Strength"}}}) { + INFO(args.dump()); + const json meta = settings_list_page(items, args); + CHECK(meta["items"].size() == 100); + CHECK(meta["next_offset"] == 100); + } + CHECK(settings_list_page(items, {{"where", "Strength"}, {"include_meta", false}})["items"].size() == 395); + const json fifty = settings_list_page(items, {{"limit", 50}}); + CHECK(fifty["items"].size() == 50); + CHECK(fifty["next_offset"] == 50); + CHECK(settings_list_page(items, {{"offset", 350}})["items"].size() == 45); +} + +TEST_CASE("the preferences, a plate's settings and the project's settings are commands of their own", "[Mcp]") +{ + const NativeCommand* preferences = NativeCommands::find("preferences_get"); + REQUIRE(preferences != nullptr); + CHECK(preferences->listed); + // It takes keys, query and tab, and needs none: with none it lists the Preferences dialog's preferences. + for (const char* arg : {"keys", "query", "tab"}) { + INFO(arg); + CHECK(preferences->input_schema["properties"].contains(arg)); + } + CHECK(preferences->input_schema.value("required", json::array()).empty()); + const NativeCommand* write = NativeCommands::find("preferences_set"); + REQUIRE(write != nullptr); + CHECK(write->listed); + CHECK(write->input_schema["required"] == json::array({"values"})); + for (const char* key : {"plate_get_settings", "plate_set_settings", "project_get_settings", "project_set_settings"}) { + INFO(key); + const NativeCommand* c = NativeCommands::find(key); + REQUIRE(c != nullptr); + CHECK(c->listed); + } + for (const char* key : {"plate_set_settings", "project_set_settings"}) { + INFO(key); + CHECK(NativeCommands::find(key)->input_schema["required"] == json::array({"values"})); + } + for (const char* key : {"preferences_get", "plate_get_settings", "plate_set_settings", "project_get_settings", "project_set_settings"}) + for (const char* absent : {"type", "target", "scope"}) { + INFO(key << " " << absent); + CHECK_FALSE(NativeCommands::find(key)->input_schema["properties"].contains(absent)); + } +} + +TEST_CASE("a plate's settings are those of its Plate Settings and filament grouping dialogs, and its name and lock are none of them", + "[Mcp]") +{ + using Catch::Matchers::ContainsSubstring; + const std::vector keys = plate_setting_keys(); + CHECK(keys == std::vector{"curr_bed_type", "print_sequence", "spiral_mode", "first_layer_print_sequence", + "other_layers_print_sequence", "filament_map_mode", "filament_map"}); + CHECK_FALSE(has(keys, "name")); + CHECK_FALSE(has(keys, "locked")); + + // A key a plate's settings lack is refused before the plate is read, whatever the other values. + const NativeCommand* set = NativeCommands::find("plate_set_settings"); + REQUIRE(set != nullptr); + for (const auto& [key, value] : std::vector>{{"name", "x"}, {"locked", true}}) { + INFO(key); + const json args{{"plate", 0}, {"values", {{"print_sequence", "by object"}, {key, value}}}}; + InPlaceContext ctx; + CHECK_THROWS_WITH(set->run(args, ctx), ContainsSubstring("Unknown setting \"" + key + "\" for the plate settings")); + } +} + +TEST_CASE("preset_list lists the presets the selectors do not offer only when asked", "[Mcp]") +{ + const NativeCommand* list = NativeCommands::find("preset_list"); + REQUIRE(list != nullptr); + CHECK(list->input_schema["properties"].contains("include_uninstalled")); + CHECK_FALSE(list->input_schema["properties"].contains("include_hidden")); +} + +TEST_CASE("a plate's filament map gives each filament an extruder the printer has, in the manual grouping alone", "[Mcp]") +{ + using Catch::Matchers::ContainsSubstring; + // Three filaments on a printer with two extruders. + CHECK(filament_map_error("Manual", {1, 2, 2}, 3, 2).empty()); + CHECK_THAT(filament_map_error("Manual", {1, 2}, 3, 2), ContainsSubstring("3 filaments")); + CHECK_THAT(filament_map_error("Manual", {1, 2, 2, 1}, 3, 2), ContainsSubstring("3 filaments")); + CHECK_THAT(filament_map_error("Manual", {1, 3, 2}, 3, 2), ContainsSubstring("extruder 3")); + CHECK_THAT(filament_map_error("Manual", {0, 1, 2}, 3, 2), ContainsSubstring("extruder 0")); + // The automatic modes group the filaments themselves when the plate slices, and a plate following the + // project's grouping ("") has no map of its own. + CHECK_THAT(filament_map_error("Auto For Flush", {1, 2, 2}, 3, 2), ContainsSubstring("Manual")); + CHECK_THAT(filament_map_error("", {1, 2, 2}, 3, 2), ContainsSubstring("Manual")); +} + +TEST_CASE("a manual filament map needs a nozzle of each volume type its used extruders print with", "[Mcp]") +{ + // A left extruder with one Standard nozzle and a right one that can hold six, with six Standard nozzles. + NozzleInventory inventory{{1, 6}, {nvtStandard, nvtHighFlow}, {{{nvtStandard, 1}}, {{nvtStandard, 6}}}}; + REQUIRE(has_multi_nozzle_extruder(inventory.max_nozzle_counts)); + + // The right extruder prints High Flow and has no such nozzle: refused once a printed filament goes to it. + std::optional shortage = manual_map_nozzle_shortage(inventory, {1, 2}, {1, 2}, {0, 1}); + REQUIRE(shortage.has_value()); + CHECK(shortage->extruder == 1); + CHECK(shortage->volume_type == nvtHighFlow); + CHECK_FALSE(manual_map_nozzle_shortage(inventory, {1, 2}, {1, 1}, {0, 0}).has_value()); + // An extruder that only a filament the plate does not print goes to is not used. + CHECK_FALSE(manual_map_nozzle_shortage(inventory, {1}, {1, 2}, {0, 1}).has_value()); + // The left extruder's own type is what it needs, whatever the volume map says of its filaments. + inventory.volume_types = {nvtHighFlow, nvtStandard}; + shortage = manual_map_nozzle_shortage(inventory, {1, 2}, {1, 2}, {0, 0}); + REQUIRE(shortage.has_value()); + CHECK(shortage->extruder == 0); + CHECK(shortage->volume_type == nvtHighFlow); + + // A Hybrid extruder needs a nozzle of each type the volume map gives its filaments. + inventory.volume_types = {nvtStandard, nvtHybrid}; + CHECK_FALSE(manual_map_nozzle_shortage(inventory, {1, 2, 3}, {1, 2, 2}, {0, 0, 0}).has_value()); + shortage = manual_map_nozzle_shortage(inventory, {1, 2, 3}, {1, 2, 2}, {0, 0, 1}); + REQUIRE(shortage.has_value()); + CHECK(shortage->extruder == 1); + CHECK(shortage->volume_type == nvtHighFlow); + // With High Flow nozzles alone, its Standard filament is the one refused, and Standard is named before High Flow. + inventory.nozzle_counts[1] = {{nvtHighFlow, 6}}; + CHECK_FALSE(manual_map_nozzle_shortage(inventory, {1, 2}, {1, 2}, {0, 1}).has_value()); + shortage = manual_map_nozzle_shortage(inventory, {1, 2, 3}, {1, 2, 2}, {0, 0, 1}); + REQUIRE(shortage.has_value()); + CHECK(shortage->extruder == 1); + CHECK(shortage->volume_type == nvtStandard); + inventory.nozzle_counts[1] = {}; + shortage = manual_map_nozzle_shortage(inventory, {1, 2, 3}, {1, 2, 2}, {0, 1, 0}); + REQUIRE(shortage.has_value()); + CHECK(shortage->volume_type == nvtStandard); + + // A printer with no multi-nozzle extruder (a nil count is none) keeps no inventory to check. + for (const std::vector& counts : {std::vector{1, 1}, std::vector{1, ConfigOptionIntsNullable::nil_value()}}) { + inventory.max_nozzle_counts = counts; + CHECK_FALSE(has_multi_nozzle_extruder(inventory.max_nozzle_counts)); + CHECK_FALSE(manual_map_nozzle_shortage(inventory, {1, 2, 3}, {1, 2, 2}, {0, 1, 0}).has_value()); + } +} + +TEST_CASE("a preset list is filtered by vendor, filament type, printer and source", "[Mcp]") +{ + const NativeCommand* list = NativeCommands::find("preset_list"); + REQUIRE(list != nullptr); + for (const char* filter : {"vendor", "filament_type", "printer", "source"}) { + INFO(filter); + CHECK(list->input_schema["properties"].contains(filter)); + } + CHECK(enum_of(*list, "source") == std::set{"system", "user", "project"}); + + // Filaments as preset_list builds their items: two system ones of a vendor, a user one and one kept in the project + // of another, a system one incompatible with the selected printer and one a person has not installed. + const json items = json::array({ + {{"name", "Bambu PLA Basic @BBL X1C"}, {"system", true}, {"user", false}, {"vendor", "Bambu Lab"}, {"filament_type", "PLA"}}, + {{"name", "Bambu PETG HF @BBL X1C"}, {"system", true}, {"user", false}, {"vendor", "Bambu Lab"}, {"filament_type", "PETG"}}, + {{"name", "My PLA"}, {"system", false}, {"user", true}, {"vendor", "Generic"}, {"filament_type", "PLA"}, {"alias", "Mine"}}, + {{"name", "Kept PLA"}, {"system", false}, {"user", true}, {"project", true}, {"vendor", "Generic"}, {"filament_type", "PLA"}}, + {{"name", "Bambu PLA Basic @BBL X1C 0.2 nozzle"}, {"system", true}, {"user", false}, {"vendor", "Bambu Lab"}, + {"filament_type", "PLA"}, {"compatible", false}}, + {{"name", "Bambu PLA Silk @BBL X1C"}, {"system", true}, {"user", false}, {"vendor", "Bambu Lab"}, {"filament_type", "PLA"}, + {"installed", false}}, + }); + const auto names = [](const json& listed) { + std::vector out; + for (const json& item : listed) + out.push_back(item["name"].get()); + return out; + }; + using Names = std::vector; + const std::function selected_printer; + + // Unfiltered, the compatible and installed ones; a query matches a name or an alias. + CHECK(names(filter_preset_items(items, json::object(), selected_printer)) == + Names{"Bambu PLA Basic @BBL X1C", "Bambu PETG HF @BBL X1C", "My PLA", "Kept PLA"}); + CHECK(names(filter_preset_items(items, {{"query", "mine"}}, selected_printer)) == Names{"My PLA"}); + // A vendor and a filament type, in either case. + CHECK(names(filter_preset_items(items, {{"vendor", "bambu lab"}, {"filament_type", "pla"}}, selected_printer)) == + Names{"Bambu PLA Basic @BBL X1C"}); + CHECK(names(filter_preset_items(items, {{"vendor", "Bambu Lab"}, {"filament_type", "PLA"}, {"include_uninstalled", true}}, + selected_printer)) == Names{"Bambu PLA Basic @BBL X1C", "Bambu PLA Silk @BBL X1C"}); + CHECK(names(filter_preset_items(items, {{"vendor", "Polymaker"}}, selected_printer)).empty()); + // Where a preset comes from: a preset kept in the project is no user preset. + CHECK(names(filter_preset_items(items, {{"source", "system"}}, selected_printer)) == + Names{"Bambu PLA Basic @BBL X1C", "Bambu PETG HF @BBL X1C"}); + CHECK(names(filter_preset_items(items, {{"source", "user"}}, selected_printer)) == Names{"My PLA"}); + CHECK(names(filter_preset_items(items, {{"source", "project"}}, selected_printer)) == Names{"Kept PLA"}); + + // Another printer: what fits it decides, in place of the flag for the selected printer, and the items say so. + const std::function fits_nozzle_02 = [](const json& item) { + const std::string name = item["name"]; + return name.find("0.2 nozzle") != std::string::npos || name == "My PLA"; + }; + const json other = filter_preset_items(items, {{"printer", "Bambu Lab X1 Carbon 0.2 nozzle"}}, fits_nozzle_02); + CHECK(names(other) == Names{"My PLA", "Bambu PLA Basic @BBL X1C 0.2 nozzle"}); + CHECK_FALSE(other[1].contains("compatible")); + const json every = filter_preset_items(items, {{"printer", "Bambu Lab X1 Carbon 0.2 nozzle"}, {"include_incompatible", true}}, + fits_nozzle_02); + REQUIRE(every.size() == 5); + CHECK(every[0]["name"] == "Bambu PLA Basic @BBL X1C"); + CHECK(every[0]["compatible"] == false); + + // A filter goes with the presets it can name: a printer for the filaments and processes, a filament type for the + // filaments; refused before the app is read. + for (const json& args : {json{{"type", "printer"}, {"printer", "Bambu Lab X1 Carbon 0.2 nozzle"}}, + json{{"type", "process"}, {"filament_type", "PLA"}}}) { + INFO(args.dump()); + NoUiContext ctx; + CHECK_THROWS_AS(list->run(args, ctx), ToolFailure); + } +} + +TEST_CASE("the printer type of settings_set takes the extruder count, and each extruder's nozzle flow type and diameter", "[Mcp]") +{ + using Catch::Matchers::ContainsSubstring; + // The Extruders field of the Printer settings: 1 or more, up to the app's limit, and greyed out while single + // extruder multi-material is on. + CHECK(extruders_count_value(json(2), false) == 2); + CHECK(extruders_count_value(json("3"), false) == 3); + CHECK_THROWS_WITH(extruders_count_value(json(0), false), ContainsSubstring("1 to 64")); + CHECK_THROWS_WITH(extruders_count_value(json(65), false), ContainsSubstring("1 to 64")); + CHECK_THROWS_AS(extruders_count_value(json(1.5), false), ToolFailure); + CHECK_THROWS_WITH(extruders_count_value(json(2), true), ContainsSubstring("single extruder multimaterial")); + // It is set alone, on the printer, before the app is read: the extruders it adds take their settings in a + // following call. + const NativeCommand* set = NativeCommands::find("settings_set"); + REQUIRE(set != nullptr); + for (const json& args : {json{{"type", "printer"}, {"values", {{"extruders_count", 2}, {"nozzle_diameter", "0.4,0.4"}}}}, + json{{"type", "printer"}, {"values", {{"extruders_count", 2}}}, {"reset_all", true}}, + json{{"values", {{"extruders_count", 2}}}}}) { + INFO(args.dump()); + CHECK_THAT(settings_request_error(args, true), ContainsSubstring("extruders_count")); + NoUiContext ctx; + CHECK_THROWS_WITH(set->run(args, ctx), settings_request_error(args, true)); + } + CHECK(settings_request_error({{"type", "printer"}, {"values", {{"extruders_count", 2}}}}, true).empty()); + + // A nozzle flow type per extruder, as each extruder's card in the sidebar picks it. + DynamicPrintConfig printer; + printer.set_deserialize_strict("nozzle_diameter", "0.4,0.4"); + printer.set_deserialize_strict("nozzle_volume_type", "Standard,Standard"); + const std::vector two_extruders{etDirectDrive, etDirectDrive}; + const std::vector standard_nozzles{nvtStandard, nvtStandard}; + CHECK(variant_entries("nozzle_volume_type", printer, two_extruders, standard_nozzles)["variants"] == + json::array({"extruder 1", "extruder 2"})); + CHECK(preset_setting_value("nozzle_volume_type", {{"index", 1}, {"value", "High Flow"}}, printer, two_extruders, + standard_nozzles) == "Standard,High Flow"); + CHECK_THROWS_WITH(preset_setting_value("nozzle_volume_type", "High Flow", printer, two_extruders, standard_nozzles), + ContainsSubstring("holds 2 values")); + + // A diameter one of the printer model's variants has switches to that variant, as the sidebar's nozzle diameter + // does; any other is typed into the Printer settings. + const std::vector variants{"0.2", "0.4", "0.6", "0.8"}; + CHECK(nozzle_diameter_variant({0.6}, variants, "0.4") == "0.6"); + CHECK(nozzle_diameter_variant({0.6, 0.6}, variants, "0.4") == "0.6"); + CHECK(nozzle_diameter_variant({0.4, 0.6}, variants, "0.4").empty()); + CHECK(nozzle_diameter_variant({0.5}, variants, "0.4").empty()); + CHECK(nozzle_diameter_variant({0.4}, variants, "0.4").empty()); + CHECK(nozzle_diameter_variant({0.25}, {"0.25", "0.4"}, "0.4") == "0.25"); + // A named variant shares its diameter with the plain one, which the diameter switches back to. + CHECK(nozzle_diameter_variant({0.4}, {"0.4", "0.4 High Flow"}, "0.4 High Flow") == "0.4"); } TEST_CASE("the run's flag lets scripts run unrestricted without changing the setting", "[Mcp]") @@ -786,7 +1560,7 @@ Calib_Params calib_args(const json& args, const DynamicPrintConfig& printer = ca } // namespace -TEST_CASE("generate_calibration_test arguments map to the dialog's calibration modes", "[Mcp]") +TEST_CASE("calibration_generate_test arguments map to the dialog's calibration modes", "[Mcp]") { for (const auto& [args, mode] : std::initializer_list>{ {{{"test", "temperature"}}, CalibMode::Calib_Temp_Tower}, @@ -805,7 +1579,7 @@ TEST_CASE("generate_calibration_test arguments map to the dialog's calibration m CHECK_THROWS_AS(calib_args({{"test", "flow_ratio"}, {"method", "tower"}}), ToolFailure); } -TEST_CASE("omitted generate_calibration_test parameters take the dialog defaults", "[Mcp]") +TEST_CASE("omitted calibration_generate_test parameters take the dialog defaults", "[Mcp]") { const Calib_Params temp = calib_args({{"test", "temperature"}}); CHECK((temp.start == 230 && temp.end == 190 && temp.nozzle_based_resize)); @@ -838,7 +1612,7 @@ TEST_CASE("omitted generate_calibration_test parameters take the dialog defaults CHECK(calib_args({{"test", "cornering"}}, calib_printer(gcfKlipper, etDirectDrive, 0.1)).end == 15); } -TEST_CASE("generate_calibration_test refuses arguments its test does not take", "[Mcp]") +TEST_CASE("calibration_generate_test refuses arguments its test does not take", "[Mcp]") { using Catch::Matchers::ContainsSubstring; CHECK_THROWS_WITH(calib_args({{"test", "pressure_advance"}, {"speeds", {100}}}), @@ -878,7 +1652,7 @@ TEST_CASE("the input shaping Y range defaults to the X range, and RepRapFirmware CHECK(check_calib_params(p, calib_printer()) == CalibParamsError::Range); } -TEST_CASE("generate_calibration_test clamps temperatures to 155-500 C, rounded down to 5 C steps, as the dialog does", "[Mcp]") +TEST_CASE("calibration_generate_test clamps temperatures to 155-500 C, rounded down to 5 C steps, as the dialog does", "[Mcp]") { using Catch::Matchers::ContainsSubstring; std::vector warnings; @@ -988,7 +1762,7 @@ TEST_CASE("VFA's auto-adjust lowers the layer height, else the end speed, to sta CHECK(fit_vfa_speed(p, printer, print, filament, true, candidates).kind == VfaSpeedFit::Fits); } -TEST_CASE("generate_calibration_test records the parameters a test ran with, defaults included", "[Mcp]") +TEST_CASE("calibration_generate_test records the parameters a test ran with, defaults included", "[Mcp]") { const DynamicPrintConfig printer = calib_printer(); const json tower = {{"test", "pressure_advance"}, {"end", 0.06}}; @@ -1012,3 +1786,23 @@ TEST_CASE("generate_calibration_test records the parameters a test ran with, def const json vfa = {{"test", "vfa"}, {"auto_adjust", false}}; CHECK(calib_params_json(vfa, calib_args(vfa), printer)["auto_adjust"] == false); } + +TEST_CASE("filament_sync_ams takes the sync dialog's choice, map or overwrite, and called with none opens the dialog", "[Mcp]") +{ + const NativeCommand* sync = NativeCommands::find("filament_sync_ams"); + REQUIRE(sync != nullptr); + std::set modes; + for (const json& mode : sync->input_schema.at("properties").at("mode").at("enum")) + modes.insert(mode.get()); + CHECK(modes == std::set{"map", "overwrite"}); + for (const char* mode : {"map", "overwrite"}) { + INFO(mode); + json args{{"mode", mode}}; + CHECK(argument_error(*sync, args).empty()); + CHECK_FALSE(Mcp::person_form(*sync, args)); + } + json other{{"mode", "merge"}}; + CHECK_THAT(argument_error(*sync, other), Catch::Matchers::ContainsSubstring("mode")); + // Its tile's call, with no arguments, is the person's form, which opens the sync dialog. + CHECK(Mcp::person_form(*sync, json::object())); +} diff --git a/tests/slic3rutils/test_mcp_core.cpp b/tests/slic3rutils/test_mcp_core.cpp index 93a70f642a..327fe4be46 100644 --- a/tests/slic3rutils/test_mcp_core.cpp +++ b/tests/slic3rutils/test_mcp_core.cpp @@ -1,4 +1,5 @@ #include +#include #include #include "automation/automation_test_utils.hpp" @@ -61,11 +62,11 @@ TEST_CASE("a context with no runtime refuses", "[Mcp]") CHECK_FALSE(acted.data.contains("status")); } -TEST_CASE("a tile's journal update stays inside run_action's envelope", "[Mcp]") +TEST_CASE("a tile's journal update stays inside action_run's envelope", "[Mcp]") { Harness h; - h.registry.add(tool("run_action", GuardClass::Mutate, [](const json&, ToolContext& ctx) { - // The command's function, as run_action runs a tile with it. + h.registry.add(tool("action_run", GuardClass::Mutate, [](const json&, ToolContext& ctx) { + // The command's function, as action_run runs a tile with it. const auto command = [](const json&, ToolContext& own) { own.set_journal_args({{"a", 1}}); return ToolResult::ok(); @@ -74,11 +75,36 @@ TEST_CASE("a tile's journal update stays inside run_action's envelope", "[Mcp]") return command(json::object(), tile); })); h.start(); - const ToolResult ran = h.call("run_action", {{"id", "k"}}); + const ToolResult ran = h.call("action_run", {{"id", "k"}}); REQUIRE_FALSE(ran.is_error); REQUIRE_FALSE(ran.data.contains("status")); const json steps = h.journal.to_replay("s")["steps"]; REQUIRE(steps.size() == 1); - CHECK(steps[0]["tool"] == "run_action"); + CHECK(steps[0]["tool"] == "action_run"); CHECK(steps[0]["args"] == json{{"id", "orca_command:k:orca"}, {"args", {{"a", 1}}}}); } + +TEST_CASE("a tile of fixed arguments is journaled with the arguments action_run takes for it", "[Mcp]") +{ + // What action_run takes for the tile: a folded row's own arguments, none for a command's own tile outside the + // Design tab, or the value a tile with an input collects. + const json tile_args = GENERATE(json{{"type", "circular"}}, json::object(), json{{"percent", 50}}); + Harness h; + h.registry.add(tool("action_run", GuardClass::Mutate, [tile_args](const json&, ToolContext& ctx) { + // The command's function records what it ran with, as object_arrange records the settings in force and a + // Design command its arguments with their refs as locators. + const auto command = [](const json&, ToolContext& own) { + own.set_journal_args({{"type", "circular"}, {"spacing", 6}}); + return ToolResult::ok(); + }; + TileContext tile(ctx, "orca_command:k:orca", tile_args); + return command(json::object(), tile); + })); + h.start(); + REQUIRE_FALSE(h.call("action_run", {{"id", "k"}}).is_error); + const json steps = h.journal.to_replay("s")["steps"]; + REQUIRE(steps.size() == 1); + CHECK(steps[0]["tool"] == "action_run"); + // action_run refuses any other arguments for such a tile, so the step holds the tile's, which its replay runs. + CHECK(steps[0]["args"] == json{{"id", "orca_command:k:orca"}, {"args", tile_args}}); +} diff --git a/tests/slic3rutils/test_mcp_protocol.cpp b/tests/slic3rutils/test_mcp_protocol.cpp index cf0b99ad4e..b2158fd537 100644 --- a/tests/slic3rutils/test_mcp_protocol.cpp +++ b/tests/slic3rutils/test_mcp_protocol.cpp @@ -1,6 +1,7 @@ #include #include "automation/automation_test_utils.hpp" +#include "retired_names.hpp" #include "slic3r/GUI/CommandCatalog.hpp" #include "slic3r/GUI/Mcp/McpProtocol.hpp" @@ -48,17 +49,16 @@ TEST_CASE("tools/list lists the listed commands in the order they were added", " added.push_back(def.key); CHECK(names == added); - // The families in the order register_all_commands() adds them: the Speed Dial's commands before them are - // not listed. + // The search, the generic call and the app's state first, then the commands by place, the GUI-driving ones last. REQUIRE_FALSE(names.empty()); - CHECK(names.front() == "get_app_state"); + CHECK(names.front() == "tool_search"); const auto position = [&names](const std::string& name) { const auto it = std::find(names.begin(), names.end(), name); REQUIRE(it != names.end()); return it - names.begin(); }; - CHECK(position("search_tools") < position("open_files")); - CHECK(position("slice") < position("click")); + CHECK(position("tool_search") < position("project_open")); + CHECK(position("plate_slice") < position("widget_click")); } TEST_CASE("the catalog the stdio bridge lists without the app holds every tool family", "[Mcp]") @@ -70,9 +70,9 @@ TEST_CASE("the catalog the stdio bridge lists without the app holds every tool f continue; CHECK(names.insert(def.key).second); } - for (const char* name : {"get_app_state", "run_action", "open_files", "set_settings", "slice", "set_height_ranges", "set_view", - "list_widgets", "run_replay", "start_recording", "run_script", "call_tool", "set_variable_layer_height", - "set_custom_gcode_at_layer"}) + for (const char* name : {"app_state", "action_run", "project_open", "settings_set", "plate_slice", "object_set_height_ranges", "view_set", + "widget_list", "replay_run", "recording_start", "script_run", "tool_call", "object_set_variable_layer_height", + "plate_set_custom_gcode"}) CHECK(names.count(name) == 1); // Built once, for the life of the process. CHECK(&NativeCommands::instance() == &catalog); @@ -81,3 +81,9 @@ TEST_CASE("the catalog the stdio bridge lists without the app holds every tool f // Clients cut the instructions off after 4096 characters. CHECK(server_info().instructions.size() <= 4096); } + +TEST_CASE("the instructions name no retired command", "[Mcp]") +{ + // An agent reads them first: a word of them that was a command's name would send it to an unknown tool. + CHECK(retired_names_in(server_info().instructions) == std::set{}); +} diff --git a/tests/slic3rutils/test_mcp_recording.cpp b/tests/slic3rutils/test_mcp_recording.cpp index 4a287a912c..9eb7971e73 100644 --- a/tests/slic3rutils/test_mcp_recording.cpp +++ b/tests/slic3rutils/test_mcp_recording.cpp @@ -3,6 +3,7 @@ #include #include +#include "slic3r/GUI/ActionReplayDialog.hpp" #include "slic3r/GUI/CommandCatalog.hpp" #include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/Mcp/McpJournal.hpp" @@ -14,6 +15,7 @@ #include "slic3r/GUI/Mcp/ScreenCapture.hpp" #include "slic3r/GUI/Mcp/VideoEncode.hpp" #include "slic3r/GUI/Mcp/VideoOverlay.hpp" +#include "slic3r/GUI/NativeCommands.hpp" #include "test_utils.hpp" #include "libslic3r/AppConfig.hpp" @@ -1033,6 +1035,50 @@ TEST_CASE("a call with a tile's arguments is captioned with the tile's title", " CHECK(board.current(t0)->title == "Pattern sketch entities"); } +TEST_CASE("a tile's call is captioned with the tile's title, run by its id or as its command with its arguments", "[Mcp][Recording]") +{ + // As McpRecorder::call_started() hands a call to the board: action_run of a tile, and a call of the tile's command + // with the tile's arguments. + const CommandCatalog& catalog = NativeCommands::instance(); + const NativeCommand* action_run = catalog.find("action_run"); + const NativeCommand* mirror = catalog.find("object_mirror"); + REQUIRE(action_run != nullptr); + REQUIRE(mirror != nullptr); + CaptionBoard board; + const auto t0 = CaptionBoard::Clock::now(); + const auto [arrange, arranges] = shown_title(catalog, *action_run, {{"id", "orca_command:obj_arrange:orca"}}); + REQUIRE(arranges != nullptr); + CHECK(arranges->key == "object_arrange"); + board.call_started(1, arrange, "", t0); + REQUIRE(board.current(t0).has_value()); + CHECK(board.current(t0)->title == "Auto-Arrange"); + board.call_started(2, shown_title(catalog, *mirror, {{"axis", "x"}}).first, "", t0); + REQUIRE(board.current(t0).has_value()); + CHECK(board.current(t0)->title == "Mirror X"); + + // The name inside the id, as action_run takes it; a command's own tile, titled as its command. + CHECK(shown_title(catalog, *action_run, {{"id", "obj_arrange"}}).first == "Auto-Arrange"); + CHECK(shown_title(catalog, *action_run, {{"id", "orca_command:undo:orca"}}).first == "Undo"); + // Any other action, and an id no tile has, are action_run's own. + CHECK(shown_title(catalog, *action_run, {{"id", "orca_recent_project:C:/p/a.3mf:orca"}}).first == action_run->title); + CHECK(shown_title(catalog, *action_run, {{"id", "orca_command:no_such_tile:orca"}}).second == action_run); + CHECK(shown_title(catalog, *mirror, {{"axis", "x"}, {"silent", true}}).first == mirror->title); +} + +TEST_CASE("an Action Replay step that runs a tile is titled as the tile, with the value it collects", "[Mcp][Recording]") +{ + // describe_step()'s `what` for action_run of Go to layer with {percent: 50}, and of Mirror X. + const CommandCatalog& catalog = NativeCommands::instance(); + const json layer{{"kind", "command"}, {"key", "view_set"}, {"tile", "go_to_layer"}, {"args", {"layer_percent: 50"}}}; + const auto [layer_title, layer_detail] = replay_what_text(layer, catalog); + CHECK(layer_title == "Go to layer (percent)"); + CHECK(layer_detail == "layer_percent: 50"); + const json mirror{{"kind", "command"}, {"key", "object_mirror"}, {"tile", "obj_mirror_x"}}; + const auto [mirror_title, mirror_detail] = replay_what_text(mirror, catalog); + CHECK(mirror_title == "Mirror X"); + CHECK(mirror_detail.empty()); +} + TEST_CASE("the caption is the newest call that runs or lingers", "[Mcp][Recording]") { CaptionBoard board; @@ -1093,28 +1139,28 @@ TEST_CASE("a burst of quick steps never pushes out the replay still running", "[ TEST_CASE("a failure's caption hides what the call's caption hides", "[Mcp][Recording]") { const std::string dots = "\xE2\x80\xA2\xE2\x80\xA2\xE2\x80\xA2"; - // set_settings quotes a value it can't take; a sensitive one never shows. - const json settings = {{"scope", "printer"}, {"values", {{"printhost_apikey", json::array({{{"value", "SECRET42"}}})}}}}; - CHECK(caption_error("set_settings", settings, R"(Unsupported value [{"value":"SECRET42"}])") == + // settings_set quotes a value it can't take; a sensitive one never shows. + const json settings = {{"type", "printer"}, {"values", {{"printhost_apikey", json::array({{{"value", "SECRET42"}}})}}}}; + CHECK(caption_error("settings_set", settings, R"(Unsupported value [{"value":"SECRET42"}])") == "Unsupported value [{\"value\":\"" + dots + "\"}]"); // A value typed into a field found by its label may be a password. - CHECK(caption_error("set_widget_value", {{"target", {{"label", "Password"}}}, {"value", "hunter22"}}, "Cannot set hunter22") == + CHECK(caption_error("widget_set_value", {{"target", {{"label", "Password"}}}, {"value", "hunter22"}}, "Cannot set hunter22") == "Cannot set " + dots); // A setting field's value is shown in the caption, so its error stays as it is. - CHECK(caption_error("set_widget_value", {{"target", {{"option", "layer_height"}}}, {"value", "0.33"}}, "0.33 is out of range") == + CHECK(caption_error("widget_set_value", {{"target", {{"option", "layer_height"}}}, {"value", "0.33"}}, "0.33 is out of range") == "0.33 is out of range"); - CHECK(caption_error("press_keys", {{"text", "pa55word"}}, "typed pa55word into nothing") == "typed " + dots + " into nothing"); + CHECK(caption_error("keyboard_press", {{"text", "pa55word"}}, "typed pa55word into nothing") == "typed " + dots + " into nothing"); // A secret in a step of an inline replay is found under its key. - const json replay = {{"replay", {{"orca_replay_version", "0.1.0"}, {"steps", json::array({{{"tool", "set_settings"}, {"args", {{"values", {{"printhost_password", "letmein9"}}}}}}})}}}}; - CHECK(caption_error("run_replay", replay, "step 1 failed: letmein9 rejected") == "step 1 failed: " + dots + " rejected"); + const json replay = {{"replay", {{"orca_replay_version", "0.2.0"}, {"steps", json::array({{{"tool", "settings_set"}, {"args", {{"values", {{"printhost_password", "letmein9"}}}}}}})}}}}; + CHECK(caption_error("replay_run", replay, "step 1 failed: letmein9 rejected") == "step 1 failed: " + dots + " rejected"); // Too short to take out safely: the error is left out. - CHECK(caption_error("press_keys", {{"text", "ab"}}, "typed ab").empty()); + CHECK(caption_error("keyboard_press", {{"text", "ab"}}, "typed ab").empty()); // As JSON quotes it inside an error that dumps the arguments. const json quoted = {{"values", {{"printhost_apikey", "alpha\"omega"}}}}; - CHECK(caption_error("set_settings", quoted, R"(Unsupported value "alpha\"omega")") == "Unsupported value \"" + dots + "\""); + CHECK(caption_error("settings_set", quoted, R"(Unsupported value "alpha\"omega")") == "Unsupported value \"" + dots + "\""); // Masked in the whole error before it is shortened, so no start of a value is left past the cut. const std::string long_error = std::string(95, 'x') + " SECRETVALUE"; - const std::string masked = shorten(caption_error("press_keys", {{"text", "SECRETVALUE"}}, long_error), 100); + const std::string masked = shorten(caption_error("keyboard_press", {{"text", "SECRETVALUE"}}, long_error), 100); CHECK(masked.find("SECRE") == std::string::npos); } @@ -1129,25 +1175,25 @@ TEST_CASE("an error is shortened to its first line at a character boundary", "[M TEST_CASE("captions name what a call acts on and never show secrets", "[Mcp][Recording]") { - CHECK(caption_detail("click", {{"target", {{"label", "Slice plate"}}}}) == "Slice plate"); - CHECK(caption_detail("click", {{"target", {{"menu", "File>Export>Export G-code"}}}}) == "File > Export > Export G-code"); - CHECK(caption_detail("click", {{"target", {{"row", "Plate 1>Cube"}, {"column", "Printable"}}}}) == "Plate 1 > Cube (Printable)"); - CHECK(caption_detail("click", {{"target", "w12"}}).empty()); // a ref: its locator comes later - CHECK(caption_detail("set_widget_value", {{"target", {{"option", "layer_height"}}}, {"value", 0.2}}) == "layer_height = 0.2"); - CHECK(caption_detail("set_widget_value", {{"target", {{"option", "printhost_apikey"}}}, {"value", "s3cret"}}) == "printhost_apikey"); - CHECK(caption_detail("set_widget_value", {{"target", {{"label", "Password"}}}, {"value", "s3cret"}}) == "Password"); - CHECK(caption_detail("set_widget_value", {{"target", "w3"}, {"value", "s3cret"}}).empty()); - CHECK(caption_detail("press_keys", {{"keys", "ctrl+s"}, {"text", "s3cret"}}) == "ctrl+s"); - CHECK(caption_detail("press_keys", {{"text", "s3cret"}}).empty()); + CHECK(caption_detail("widget_click", {{"target", {{"label", "Slice plate"}}}}) == "Slice plate"); + CHECK(caption_detail("widget_click", {{"target", {{"menu", "File>Export>Export G-code"}}}}) == "File > Export > Export G-code"); + CHECK(caption_detail("widget_click", {{"target", {{"row", "Plate 1>Cube"}, {"column", "Printable"}}}}) == "Plate 1 > Cube (Printable)"); + CHECK(caption_detail("widget_click", {{"target", "w12"}}).empty()); // a ref: its locator comes later + CHECK(caption_detail("widget_set_value", {{"target", {{"option", "layer_height"}}}, {"value", 0.2}}) == "layer_height = 0.2"); + CHECK(caption_detail("widget_set_value", {{"target", {{"option", "printhost_apikey"}}}, {"value", "s3cret"}}) == "printhost_apikey"); + CHECK(caption_detail("widget_set_value", {{"target", {{"label", "Password"}}}, {"value", "s3cret"}}) == "Password"); + CHECK(caption_detail("widget_set_value", {{"target", "w3"}, {"value", "s3cret"}}).empty()); + CHECK(caption_detail("keyboard_press", {{"keys", "ctrl+s"}, {"text", "s3cret"}}) == "ctrl+s"); + CHECK(caption_detail("keyboard_press", {{"text", "s3cret"}}).empty()); const std::string settings = - caption_detail("set_settings", {{"scope", "printer"}, {"values", {{"printhost_password", "s3cret"}, {"nozzle_diameter", "0.4"}}}}); + caption_detail("settings_set", {{"type", "printer"}, {"values", {{"printhost_password", "s3cret"}, {"nozzle_diameter", "0.4"}}}}); CHECK(settings.find("s3cret") == std::string::npos); CHECK(settings.find("nozzle_diameter = 0.4") != std::string::npos); - CHECK(caption_detail("open_files", {{"paths", {"C:/models/part.stl", "/tmp/b.3mf"}}}) == "part.stl, b.3mf"); - CHECK(caption_detail("run_action", {{"id", "orca_command:obj_arrange:orca"}}) == "obj_arrange"); - CHECK(caption_detail("run_action", {{"id", "orca_command:import_file:orca"}, {"args", {{"path", "C:/models/part.stl"}}}}) == - "import_file path: part.stl"); - CHECK(caption_detail("run_javascript", {{"code", "login('s3cret')"}}).empty()); + CHECK(caption_detail("project_import", {{"paths", {"C:/models/part.stl", "/tmp/b.3mf"}}}) == "part.stl, b.3mf"); + // A row's tile is its command's call; a command's own tile given arguments shows them. + CHECK(caption_detail("action_run", {{"id", "orca_command:obj_arrange:orca"}}) == "object_arrange"); + CHECK(caption_detail("action_run", {{"id", "orca_command:undo:orca"}, {"args", {{"history", "design"}}}}) == "undo history: design"); + CHECK(caption_detail("webview_run_javascript", {{"code", "login('s3cret')"}}).empty()); CHECK(is_sensitive_key("printhost_apikey")); CHECK(is_sensitive_key("cloud_Token")); CHECK_FALSE(is_sensitive_key("layer_height")); @@ -1282,7 +1328,7 @@ TEST_CASE("remembered recording settings come back, and a bad value keeps its de CHECK(loaded.profile == "main"); } -TEST_CASE("start_recording's encode arguments override the settings, a preset before the fields", "[Mcp][Recording]") +TEST_CASE("recording_start's encode arguments override the settings, a preset before the fields", "[Mcp][Recording]") { RecordingSettings s; // The tool's other arguments are left to it. @@ -1502,10 +1548,10 @@ TEST_CASE("an exported replay encodes the recording it makes and leaves other so { Journal j; auto ok = [&](const std::string& tool, const json& args) { j.end(j.begin(tool, args), ToolResult::ok()); }; - ok("start_recording", {{"save_path", "C:/Users/me/out/rec.mkv"}}); - ok("stop_recording", json::object()); - ok("encode_recording", {{"path", "C:/Users/me/out/rec.mkv"}, {"save_path", "C:/Users/me/out/rec.mp4"}}); - ok("encode_recording", {{"path", "D:/videos/old.mkv"}}); + ok("recording_start", {{"save_path", "C:/Users/me/out/rec.mkv"}}); + ok("recording_stop", json::object()); + ok("recording_encode", {{"path", "C:/Users/me/out/rec.mkv"}, {"save_path", "C:/Users/me/out/rec.mp4"}}); + ok("recording_encode", {{"path", "D:/videos/old.mkv"}}); const json steps = j.to_replay("s")["steps"]; REQUIRE(steps.size() == 4); CHECK(steps[0]["args"]["save_path"] == "${out_dir}/rec.mkv"); @@ -1514,28 +1560,22 @@ TEST_CASE("an exported replay encodes the recording it makes and leaves other so CHECK(steps[3]["args"]["path"] == "D:/videos/old.mkv"); } -TEST_CASE("an exported replay records a tile's recording into its own folder and encodes it there", "[Mcp][Recording]") +TEST_CASE("an exported replay records a silent recording into its own folder and keeps a pick of the tile as it is", "[Mcp][Recording]") { Journal j; auto ok = [&](const std::string& tool, const json& args) { j.end(j.begin(tool, args), ToolResult::ok()); }; - // run_action of the Start Recording tile, journaled as the tile's {id, args}, by its full id with the path the - // call gave. A call that gives none is journaled with the path its silent form chose in the session's output - // folder, as start_recording's own call is; the tile by its key here. - ok("run_action", {{"id", "orca_command:start_recording:orca"}, {"args", {{"silent", true}, {"save_path", "C:/Users/me/out/tile.mkv"}}}}); - ok("run_action", {{"id", "orca_command:stop_recording:orca"}}); - ok("encode_recording", {{"path", "C:/Users/me/out/tile.mkv"}}); - ok("run_action", {{"id", "start_recording"}, {"args", {{"silent", true}, {"save_path", "C:/Users/me/mcp/recording-20261113.mkv"}}}}); - ok("run_action", {{"id", "stop_recording"}}); - ok("encode_recording", {{"path", "C:/Users/me/mcp/recording-20261113.mkv"}, {"save_path", "C:/Users/me/mcp/take.mp4"}}); - // The person's form, which opens the Start Recording dialog, names no file. - ok("run_action", {{"id", "start_recording"}}); + // recording_start's silent form, journaled with the path it chose in the session's output folder. + ok("recording_start", {{"silent", true}, {"save_path", "C:/Users/me/mcp/recording-20261113.mkv"}}); + ok("recording_stop", {{"silent", true}}); + ok("recording_encode", {{"path", "C:/Users/me/mcp/recording-20261113.mkv"}, {"save_path", "C:/Users/me/mcp/take.mp4"}}); + // action_run of the Start Recording tile, which takes no arguments: the person's form, which opens the Start + // Recording dialog and names no file. + ok("action_run", {{"id", "orca_command:start_recording:orca"}}); const json steps = j.to_replay("s")["steps"]; - REQUIRE(steps.size() == 7); - CHECK(steps[0]["tool"] == "run_action"); - CHECK(steps[0]["args"] == json{{"id", "orca_command:start_recording:orca"}, {"args", {{"silent", true}, {"save_path", "${out_dir}/tile.mkv"}}}}); - CHECK(steps[2]["args"]["path"] == "${out_dir}/tile.mkv"); - CHECK(steps[3]["args"] == json{{"id", "start_recording"}, {"args", {{"silent", true}, {"save_path", "${out_dir}/recording-20261113.mkv"}}}}); - CHECK(steps[5]["args"]["path"] == "${out_dir}/recording-20261113.mkv"); - CHECK(steps[5]["args"]["save_path"] == "${out_dir}/take.mp4"); - CHECK(steps[6]["args"] == json{{"id", "start_recording"}}); + REQUIRE(steps.size() == 4); + CHECK(steps[0]["args"] == json{{"silent", true}, {"save_path", "${out_dir}/recording-20261113.mkv"}}); + CHECK(steps[2]["args"]["path"] == "${out_dir}/recording-20261113.mkv"); + CHECK(steps[2]["args"]["save_path"] == "${out_dir}/take.mp4"); + CHECK(steps[3]["tool"] == "action_run"); + CHECK(steps[3]["args"] == json{{"id", "orca_command:start_recording:orca"}}); } diff --git a/tests/slic3rutils/test_mcp_results.cpp b/tests/slic3rutils/test_mcp_results.cpp index 0de32c75fa..aee5bc7372 100644 --- a/tests/slic3rutils/test_mcp_results.cpp +++ b/tests/slic3rutils/test_mcp_results.cpp @@ -264,7 +264,7 @@ TEST_CASE("a toolbar item reads the enabled state its callback gives now, not th toolbar.update_items_state(); // the last idle event, before the selection REQUIRE(toolbar.get_item("layersediting")->is_disabled()); - can_edit = true; // `select_objects` picked an object + can_edit = true; // `object_select` picked an object bool changed = false; CHECK_FALSE(toolbar_items(toolbar, &changed).front()->is_disabled()); CHECK(changed); @@ -301,7 +301,7 @@ TEST_CASE("an auto-answer rule presses a wx dialog's button, and answers a nativ CHECK(tracker.top() == nullptr); CHECK(tracker.rules_json()[0]["uses"] == 1); - // A modal opened above it before its loop ran leaves it to answer_dialog. + // A modal opened above it before its loop ran leaves it to dialog_answer. wxDialog above(nullptr, wxID_ANY, "Other"); CHECK(wxModalDialogHook::CallEnter(&dialog) == wxID_NONE); CHECK(wxModalDialogHook::CallEnter(&above) == wxID_NONE); @@ -865,7 +865,7 @@ TEST_CASE("preview layers count from 1, with each height above the layer below", } } -TEST_CASE("a preview object carries its list_objects index only when its name is unique", "[Mcp]") +TEST_CASE("a preview object carries its object_list index only when its name is unique", "[Mcp]") { using Catch::Matchers::WithinAbs; GCodeProcessorResult result; @@ -905,7 +905,7 @@ TEST_CASE("a preview object carries its list_objects index only when its name is CHECK_FALSE(object.contains("object")); } -TEST_CASE("set_view's legend keys name one feature type or option each, as get_slice_stats lists them", "[Mcp]") +TEST_CASE("view_set's legend keys name one feature type or option each, as plate_slice_stats lists them", "[Mcp]") { // A feature type goes by the English name of its ;FEATURE: tag, which names no other role. std::set features; @@ -947,7 +947,7 @@ TEST_CASE("a height picks the first layer whose top is at or above it, as the sl // Between two tops: the layer that covers that height. CHECK(layers.get_tick_from_value(0.45, true) == 2); CHECK(layers.get_tick_from_value(0.8, true) == 3); - // Above the top layer: no layer, which set_view refuses. + // Above the top layer: no layer, which view_set refuses. CHECK(layers.get_tick_from_value(0.81, true) == -1); } @@ -1095,7 +1095,7 @@ TEST_CASE("a click that only listed a menu is dropped from the replay when the n // Nor does a pick after another call, or one on another target. Journal other; other.end(other.begin("mouse_gesture", click), listed); - other.end(other.begin("select_objects", {{"objects", {0}}}), ToolResult::ok()); + other.end(other.begin("object_select", {{"objects", {0}}}), ToolResult::ok()); other.end(other.begin("mouse_gesture", pick), ran); CHECK(steps(other).size() == 3); nlohmann::json elsewhere = pick; @@ -1114,19 +1114,19 @@ TEST_CASE("the UI activity hook brackets each closure that runs, not one its gua UiInvoker invoker( dispatcher, [&] { GuardState g; g.modal = modal; return g; }, {}, {}, [&seen](const std::string& tool, bool running) { seen.emplace_back(tool, running); }); - invoker.run(GuardClass::Mutate, "click", [&] { - invoker.run(GuardClass::Inspect, "get_app_state", [] { return nlohmann::json(); }); + invoker.run(GuardClass::Mutate, "widget_click", [&] { + invoker.run(GuardClass::Inspect, "app_state", [] { return nlohmann::json(); }); return nlohmann::json(); }); CHECK(seen == - std::vector>{{"click", true}, {"get_app_state", true}, {"get_app_state", false}, {"click", false}}); + std::vector>{{"widget_click", true}, {"app_state", true}, {"app_state", false}, {"widget_click", false}}); seen.clear(); // A closure that throws still ends; one refused before it runs never starts. - CHECK_THROWS_AS(invoker.run(GuardClass::Mutate, "press_keys", []() -> nlohmann::json { throw ToolFailure("no"); }), ToolFailure); - CHECK(seen == std::vector>{{"press_keys", true}, {"press_keys", false}}); + CHECK_THROWS_AS(invoker.run(GuardClass::Mutate, "keyboard_press", []() -> nlohmann::json { throw ToolFailure("no"); }), ToolFailure); + CHECK(seen == std::vector>{{"keyboard_press", true}, {"keyboard_press", false}}); seen.clear(); modal = true; - CHECK_THROWS_AS(invoker.run(GuardClass::Mutate, "select_objects", [] { return nlohmann::json(); }), ToolFailure); + CHECK_THROWS_AS(invoker.run(GuardClass::Mutate, "object_select", [] { return nlohmann::json(); }), ToolFailure); CHECK(seen.empty()); } @@ -1173,7 +1173,7 @@ TEST_CASE("a menu opened while a call acts on the UI is listed, run by its path // A person's menu, with no call acting on the UI, is shown, not taken. CHECK_FALSE(inspector.on_menu(menu, frame)); - inspector.ui_activity("click", true); + inspector.ui_activity("widget_click", true); int token = inspector.arm_menu(""); CHECK(popup_menu(frame, menu)); nlohmann::json out = inspector.disarm_menu(token); @@ -1210,7 +1210,7 @@ TEST_CASE("a menu opened while a call acts on the UI is listed, run by its path CHECK(popup_menu(frame, menu)); CHECK(inspector.disarm_menu(token)["menus_closed"] == 1); CHECK(inspector.closed_menus().size() == 1); - inspector.ui_activity("click", false); + inspector.ui_activity("widget_click", false); // A menu from a call that armed nothing is closed unseen, until the first idle after the call. inspector.ui_activity("extrude", true); @@ -1233,18 +1233,18 @@ TEST_CASE("a menu opened while a call acts on the UI is listed, run by its path // Only menus of the event loop the call ran in are taken: a person's right click in a dialog's // loop shows its menu. - inspector.ui_activity("click", true); + inspector.ui_activity("widget_click", true); { wxEventLoop dialog_loop; wxEventLoopActivator inside(&dialog_loop); CHECK_FALSE(inspector.on_menu(menu, frame)); } CHECK(inspector.on_menu(menu, frame)); - // get_app_state keeps the last three. + // app_state keeps the last three. CHECK(inspector.on_menu(menu, frame)); CHECK(inspector.closed_menus().size() == 3); - CHECK(inspector.closed_menus()[2]["tool"] == "click"); - inspector.ui_activity("click", false); + CHECK(inspector.closed_menus()[2]["tool"] == "widget_click"); + inspector.ui_activity("widget_click", false); inspector.capture_menus(false); } } @@ -2086,7 +2086,7 @@ TEST_CASE("a long label is cut where a character starts, and a toggle's tooltip wxDialog dialog(nullptr, wxID_ANY, "Overlay"); auto* toggle = new wxBitmapToggleButton(&dialog, wxID_ANY, wxBitmap(16, 16)); toggle->SetToolTip(wxString::FromUTF8(tip)); - // list_widgets's label is cut at 120 bytes, where a character starts. + // widget_list's label is cut at 120 bytes, where a character starts. const std::string label = label_of(toggle); CHECK(label.size() < tip.size()); CHECK(label.substr(label.size() - 3) == "..."); @@ -2232,7 +2232,7 @@ TEST_CASE("a dialog that can't be described is still listed, by its title", "[Mc } } -TEST_CASE("set_widget_value false is refused on a selected radio button, which selecting another unselects", "[Mcp]") +TEST_CASE("widget_set_value false is refused on a selected radio button, which selecting another unselects", "[Mcp]") { #if defined(__linux__) if (!std::getenv("DISPLAY") && !std::getenv("WAYLAND_DISPLAY")) @@ -2419,7 +2419,7 @@ TEST_CASE("a bed picking id decodes to its plate and icon", "[Mcp]") namespace { // A core whose tools need no UI thread: `build` outlives its reply budget until `release` is set, -// then returns `build_result` (a slow CAD rebuild); `edit` succeeds at once; `wait` hands back a +// then returns `build_result` (a slow CAD rebuild); `edit` succeeds at once; `app_wait` hands back a // job's result, or reports it still running, as the real tool does. struct JobJournal { @@ -2454,7 +2454,7 @@ struct JobJournal }; registry.add(edit); NativeCommand wait; - wait.key = "wait"; + wait.key = "app_wait"; wait.guard = GuardClass::Inspect; wait.inline_call = true; wait.run = [this](const nlohmann::json& args, ToolContext&) { @@ -2496,7 +2496,7 @@ TEST_CASE("a mutation whose job fails after its reply is dropped from the replay h.build_result = ToolResult::error("The thread could not be built"); const std::string job = h.start_build(); h.release = true; - const ToolResult failed = h.call("wait", {{"for", "job"}, {"job", job}}); + const ToolResult failed = h.call("app_wait", {{"for", "job"}, {"job", job}}); CHECK(failed.is_error); CHECK_FALSE(h.call("edit", {{"value", 3}}).is_error); @@ -2507,11 +2507,11 @@ TEST_CASE("a mutation whose job fails after its reply is dropped from the replay CHECK(exported["steps"][0]["args"] == nlohmann::json{{"value", 3}}); CHECK(running.empty()); - // The replay runs the edit alone, as a run_replay job's children. + // The replay runs the edit alone, as a replay_run job's children. std::string err; const std::optional parsed = parse_replay(exported.dump(), err); REQUIRE(parsed.has_value()); - const std::string parent = h.jobs.create("run_replay", ""); + const std::string parent = h.jobs.create("replay_run", ""); ReplayContext sctx; ReplayHost host; host.call = [&](const std::string& tool, const nlohmann::json& args) { return h.core->call_child(*h.registry.find(tool), args, parent); }; @@ -2531,8 +2531,8 @@ TEST_CASE("an export while a mutation's job runs leaves the call out and names i h.build_result = ToolResult::ok({{"built", true}}); const std::string job = h.start_build(); CHECK_FALSE(h.call("edit", {{"value", 1}}).is_error); - // A wait that times out names the job too, but it is not the wait's own. - const ToolResult still = h.call("wait", {{"for", "job"}, {"job", job}, {"timeout_ms", 0}}); + // An app_wait that times out names the job too, but it is not the app_wait's own. + const ToolResult still = h.call("app_wait", {{"for", "job"}, {"job", job}, {"timeout_ms", 0}}); CHECK(still.data["status"] == "running"); nlohmann::json running; @@ -2542,7 +2542,7 @@ TEST_CASE("an export while a mutation's job runs leaves the call out and names i CHECK(running == nlohmann::json::array({{{"tool", "build"}, {"job", job}}})); h.release = true; - CHECK(h.call("wait", {{"for", "job"}, {"job", job}}).data["built"] == true); + CHECK(h.call("app_wait", {{"for", "job"}, {"job", job}}).data["built"] == true); steps = h.journal.to_replay("t", &running)["steps"]; CHECK(running.empty()); REQUIRE(steps.size() == 4); @@ -2558,23 +2558,23 @@ TEST_CASE("an export while a mutation's job runs leaves the call out and names i TEST_CASE("a job that waits on a dialog stays in the replay, and a call yet to reply is left out", "[Mcp]") { Journal journal; - const uint64_t open = journal.begin("run_action", {{"id", "orca_command:open_preferences:orca"}}); + const uint64_t open = journal.begin("action_run", {{"id", "orca_command:open_preferences:orca"}}); journal.job_started(open, "j1"); - journal.end(open, ToolResult::ok({{"status", "blocked_by_dialog"}, {"job", "j1"}, {"tool", "run_action"}})); - const uint64_t answer = journal.begin("answer_dialog", {{"button", "cancel"}}); + journal.end(open, ToolResult::ok({{"status", "blocked_by_dialog"}, {"job", "j1"}, {"tool", "action_run"}})); + const uint64_t answer = journal.begin("dialog_answer", {{"button", "cancel"}}); journal.job_started(answer, "j2"); journal.job_ended(answer, ToolResult::ok()); journal.end(answer, ToolResult::ok()); - const uint64_t slice = journal.begin("slice", nlohmann::json::object()); + const uint64_t slice = journal.begin("plate_slice", nlohmann::json::object()); journal.job_started(slice, "j3"); - journal.begin("screenshot", {{"target", "canvas"}}); + journal.begin("window_screenshot", {{"target", "canvas"}}); nlohmann::json running; nlohmann::json steps = journal.to_replay("t", &running)["steps"]; REQUIRE(steps.size() == 2); CHECK(steps[0]["save_as"] == "job1"); - CHECK(steps[1]["tool"] == "answer_dialog"); - CHECK(running == nlohmann::json::array({{{"tool", "slice"}, {"job", "j3"}}, {{"tool", "screenshot"}}})); + CHECK(steps[1]["tool"] == "dialog_answer"); + CHECK(running == nlohmann::json::array({{{"tool", "plate_slice"}, {"job", "j3"}}, {{"tool", "window_screenshot"}}})); // The dialog's answer follows it in the replay, so it stays when its job then fails. journal.job_ended(open, ToolResult::error("Cancelled")); @@ -2582,52 +2582,52 @@ TEST_CASE("a job that waits on a dialog stays in the replay, and a call yet to r journal.job_ended(slice, ToolResult::ok()); steps = journal.to_replay("t", &running)["steps"]; REQUIRE(steps.size() == 3); - CHECK(steps[0]["tool"] == "run_action"); - CHECK(steps[2]["tool"] == "slice"); + CHECK(steps[0]["tool"] == "action_run"); + CHECK(steps[2]["tool"] == "plate_slice"); CHECK_FALSE(steps[2].contains("await")); - CHECK(running == nlohmann::json::array({{{"tool", "screenshot"}}})); + CHECK(running == nlohmann::json::array({{{"tool", "window_screenshot"}}})); } TEST_CASE("a job that was running when a dialog was answered stays in the replay before the answer", "[Mcp]") { // A replay past its reply budget opens Preferences, which a later call answers. Journal journal; - const uint64_t replay_call = journal.begin("run_replay", {{"path", "s.json"}}); + const uint64_t replay_call = journal.begin("replay_run", {{"path", "s.json"}}); journal.job_started(replay_call, "j1"); - journal.end(replay_call, ToolResult::ok({{"status", "running"}, {"job", "j1"}, {"tool", "run_replay"}})); + journal.end(replay_call, ToolResult::ok({{"status", "running"}, {"job", "j1"}, {"tool", "replay_run"}})); // A call still within its reply budget, whose dialog is answered before it replies. - const uint64_t open = journal.begin("run_action", {{"id", "orca_command:open_preferences:orca"}}); + const uint64_t open = journal.begin("action_run", {{"id", "orca_command:open_preferences:orca"}}); journal.job_started(open, "j2"); - const uint64_t slice = journal.begin("slice", nlohmann::json::object()); + const uint64_t slice = journal.begin("plate_slice", nlohmann::json::object()); journal.job_started(slice, "j3"); - journal.end(slice, ToolResult::ok({{"status", "running"}, {"job", "j3"}, {"tool", "slice"}})); + journal.end(slice, ToolResult::ok({{"status", "running"}, {"job", "j3"}, {"tool", "plate_slice"}})); journal.job_ended(slice, ToolResult::error("Cancelled")); - const uint64_t answer = journal.begin("answer_dialog", {{"button", "close"}}, true); + const uint64_t answer = journal.begin("dialog_answer", {{"button", "close"}}, true); journal.job_started(answer, "j4"); journal.job_ended(answer, ToolResult::ok()); journal.end(answer, ToolResult::ok()); // Input with no dialog open ties nothing to the jobs then running. - const uint64_t click = journal.begin("click", {{"target", "w1"}}); + const uint64_t click = journal.begin("widget_click", {{"target", "w1"}}); journal.job_started(click, "j5"); journal.job_ended(click, ToolResult::ok()); journal.end(click, ToolResult::ok()); - const uint64_t later = journal.begin("run_action", {{"id", "obj_arrange"}}); + const uint64_t later = journal.begin("action_run", {{"id", "obj_arrange"}}); journal.job_started(later, "j6"); - journal.end(later, ToolResult::ok({{"status", "running"}, {"job", "j6"}, {"tool", "run_action"}})); - journal.begin("click", {{"target", "w2"}}); + journal.end(later, ToolResult::ok({{"status", "running"}, {"job", "j6"}, {"tool", "action_run"}})); + journal.begin("widget_click", {{"target", "w2"}}); nlohmann::json running; nlohmann::json steps = journal.to_replay("t", &running)["steps"]; REQUIRE(steps.size() == 5); - CHECK(steps[0]["tool"] == "run_replay"); + CHECK(steps[0]["tool"] == "replay_run"); CHECK(steps[0]["await"] == false); - CHECK(steps[1]["tool"] == "run_action"); + CHECK(steps[1]["tool"] == "action_run"); CHECK(steps[1]["await"] == false); // The answer waits for its dialog, which the replayed job may open later than its reply. - CHECK(steps[2] == nlohmann::json({{"tool", "wait"}, {"args", {{"for", "dialog"}, {"timeout_s", 50}}}, {"expect", {{"/satisfied", {{"eq", true}}}}}})); - CHECK(steps[3]["tool"] == "answer_dialog"); - CHECK(steps[4]["tool"] == "click"); - CHECK(running == nlohmann::json::array({{{"tool", "run_action"}, {"job", "j6"}}, {{"tool", "click"}}})); + CHECK(steps[2] == nlohmann::json({{"tool", "app_wait"}, {"args", {{"for", "dialog"}, {"timeout_s", 50}}}, {"expect", {{"/satisfied", {{"eq", true}}}}}})); + CHECK(steps[3]["tool"] == "dialog_answer"); + CHECK(steps[4]["tool"] == "widget_click"); + CHECK(running == nlohmann::json::array({{{"tool", "action_run"}, {"job", "j6"}}, {{"tool", "widget_click"}}})); // They stay whatever their jobs' results: the answer after them needs a dialog one of them opens. journal.job_ended(replay_call, ToolResult::error("Step 4 failed")); @@ -2635,7 +2635,7 @@ TEST_CASE("a job that was running when a dialog was answered stays in the replay journal.end(open, ToolResult::ok({{"ran", "orca_command:open_preferences:orca"}})); steps = journal.to_replay("t")["steps"]; REQUIRE(steps.size() == 5); - CHECK(steps[0]["tool"] == "run_replay"); + CHECK(steps[0]["tool"] == "replay_run"); CHECK(steps[1]["await"] == false); } @@ -2643,14 +2643,14 @@ TEST_CASE("an exported answer to a dialog a job opens after its reply replays on { // A replay replies running, opens Preferences later, and is answered while it keeps running. Journal journal; - const uint64_t replay_call = journal.begin("run_replay", {{"path", "s.json"}}); + const uint64_t replay_call = journal.begin("replay_run", {{"path", "s.json"}}); journal.job_started(replay_call, "j1"); - journal.end(replay_call, ToolResult::ok({{"status", "running"}, {"job", "j1"}, {"tool", "run_replay"}})); - const uint64_t answer = journal.begin("answer_dialog", {{"button", "close"}}, true); + journal.end(replay_call, ToolResult::ok({{"status", "running"}, {"job", "j1"}, {"tool", "replay_run"}})); + const uint64_t answer = journal.begin("dialog_answer", {{"button", "close"}}, true); journal.job_started(answer, "j2"); journal.job_ended(answer, ToolResult::ok()); journal.end(answer, ToolResult::ok()); - const uint64_t waited = journal.begin("wait", {{"for", "job"}, {"job", "j1"}}); + const uint64_t waited = journal.begin("app_wait", {{"for", "job"}, {"job", "j1"}}); journal.end(waited, ToolResult::ok()); journal.job_ended(replay_call, ToolResult::ok()); @@ -2664,19 +2664,19 @@ TEST_CASE("an exported answer to a dialog a job opens after its reply replays on ReplayHost host; host.call = [&](const std::string& tool, const nlohmann::json& args) { calls.push_back(tool); - if (tool == "run_replay") { + if (tool == "replay_run") { opener = std::thread([&dialog] { std::this_thread::sleep_for(std::chrono::milliseconds(300)); dialog = true; }); - return ToolResult::ok({{"status", "running"}, {"job", "r1"}, {"tool", "run_replay"}}); + return ToolResult::ok({{"status", "running"}, {"job", "r1"}, {"tool", "replay_run"}}); } - if (tool == "wait" && args["for"] == "dialog") { + if (tool == "app_wait" && args["for"] == "dialog") { for (int i = 0; i < 100 && !dialog; ++i) std::this_thread::sleep_for(std::chrono::milliseconds(20)); return ToolResult::ok({{"satisfied", dialog.load()}}); } - if (tool == "answer_dialog") { + if (tool == "dialog_answer") { if (!dialog) return ToolResult::error("No modal dialog is open"); dialog = false; @@ -2690,7 +2690,7 @@ TEST_CASE("an exported answer to a dialog a job opens after its reply replays on const nlohmann::json replay = run_replay(*parsed, sctx, host); opener.join(); CHECK(replay["passed"] == true); - CHECK(calls == std::vector{"run_replay", "wait", "answer_dialog", "wait"}); + CHECK(calls == std::vector{"replay_run", "app_wait", "dialog_answer", "app_wait"}); } TEST_CASE("an upload's row reaches 100 percent only once the host has answered", "[Mcp][PrintHost]") @@ -2707,23 +2707,26 @@ TEST_CASE("an upload's row reaches 100 percent only once the host has answered", CHECK(percent(4096, 4096) == 99); } -TEST_CASE("the send command is a Slice & Export command that takes no arguments", "[Mcp][SpeedDial]") +TEST_CASE("the send command is a Slice & Export tile that takes no arguments", "[Mcp][SpeedDial]") { - const NativeCommand* send = NativeCommands::find("send_gcode"); + const NativeCommand* send = NativeCommands::find("printer_send"); REQUIRE(send != nullptr); CHECK(send->title == "Send G-code to printer host"); - CHECK(send->group == "Slice & Export"); + const auto [command, tile] = Slic3r::GUI::find_tile(NativeCommands::instance(), "send_gcode"); + CHECK(command == send); + REQUIRE(tile != nullptr); + CHECK(tile->at("group") == "Slice & Export"); CHECK(send->input_schema.at("properties").empty()); CHECK(send->completion == CommandCompletion::Immediate); - CHECK(send->description.find("get_app_state.uploads") != std::string::npos); + CHECK(send->description.find("app_state.uploads") != std::string::npos); } -TEST_CASE("run_action with a param is refused by name", "[Mcp][SpeedDial]") +TEST_CASE("action_run with a param is refused by name", "[Mcp][SpeedDial]") { - const NativeCommand* run_action = NativeCommands::find("run_action"); - REQUIRE(run_action != nullptr); + const NativeCommand* action_run = NativeCommands::find("action_run"); + REQUIRE(action_run != nullptr); nlohmann::json args{{"id", "x"}, {"param", "1"}}; - CHECK_THAT(argument_error(*run_action, args), Catch::Matchers::ContainsSubstring("param")); + CHECK_THAT(argument_error(*action_run, args), Catch::Matchers::ContainsSubstring("param")); nlohmann::json given{{"id", "x"}, {"args", {{"percent", 50}}}}; - CHECK(argument_error(*run_action, given).empty()); + CHECK(argument_error(*action_run, given).empty()); } diff --git a/tests/slic3rutils/test_mcp_scene.cpp b/tests/slic3rutils/test_mcp_scene.cpp index df09cc0ca1..b416c7021d 100644 --- a/tests/slic3rutils/test_mcp_scene.cpp +++ b/tests/slic3rutils/test_mcp_scene.cpp @@ -1,8 +1,9 @@ -// Scene tools: transform's size argument, the arguments of the commands that replace a dialog, the -// notifications MCP operations raise before the 3D view has drawn, arrange's options, the admission that -// holds a UI worker job a call starts, how list_objects describes objects, instances and parts, -// add_part's type names and shape sizes, the object structure commands, the height -// ranges set_height_ranges takes and list_objects reports, and set_custom_gcode_at_layer's edits of the layer slider. +// Scene tools: object_transform's size argument, the arguments of the commands that replace a dialog, the +// notifications MCP operations raise before the 3D view has drawn, object_arrange's options, the admission that +// holds a UI worker job a call starts, how object_list describes objects, instances and parts, +// part_add's type names and shape sizes, the object structure commands, the targets a command reads from its arguments +// and the reply that names them, the height ranges object_set_height_ranges takes and object_list reports, +// plate_set_custom_gcode's edits of the layer slider, view_set's display switches and a plate's place on the bed. // GLCanvas3D.hpp reaches wx's MSW headers after OCCT has hidden the USER and GDI declarations they need; // the Windows headers first keep them, as in test_plugin_host_api.cpp. #ifdef WIN32 @@ -22,6 +23,7 @@ #include #include +#include #include #include @@ -31,13 +33,19 @@ #include "slic3r/GUI/IMSlider.hpp" #include "slic3r/GUI/ImGuiWrapper.hpp" #include "slic3r/GUI/Mcp/JobRegistry.hpp" +#include "slic3r/GUI/Mcp/McpArguments.hpp" #include "slic3r/GUI/Mcp/McpCore.hpp" #include "slic3r/GUI/Mcp/McpJournal.hpp" +#include "slic3r/GUI/Mcp/McpTargets.hpp" #include "slic3r/GUI/Mcp/McpTools.hpp" #include "slic3r/GUI/Mcp/UiInvoker.hpp" #include "slic3r/GUI/NativeCommands.hpp" #include "slic3r/GUI/NotificationManager.hpp" +#include "slic3r/GUI/Operations/ObjectOps.hpp" +#include "slic3r/GUI/Operations/Outcome.hpp" +#include "slic3r/GUI/PartPlate.hpp" +#include "libslic3r/BoundingBox.hpp" #include "libslic3r/Config.hpp" #include "libslic3r/CustomGCode.hpp" #include "libslic3r/Model.hpp" @@ -64,6 +72,7 @@ #include #include #include +#include #include #include @@ -123,8 +132,8 @@ TEST_CASE("the arrange options keep Align to Y axis off while auto rotation is o CHECK(settings.enable_rotation); } -// A command that replaces a dialog takes, as JSON arguments, what the dialog asks; Go to layer and Go to tab -// take the value of the Speed Dial's second phase, which they need. +// A command that replaces a dialog takes, as JSON arguments, what the dialog asks; Go to layer and Go to tab, tiles of +// view_set, take the value of the Speed Dial's second phase, which they need. TEST_CASE("the commands that replace a dialog take the arguments the table gives", "[Mcp][Scene]") { using Names = std::set; @@ -135,39 +144,66 @@ TEST_CASE("the commands that replace a dialog take the arguments the table gives out.insert(name); return out; }; - const Names path{"path"}, output{"path", "overwrite"}, all{"all"}, size{"size"}; + const Names path{"path"}; const Names recording{"target", "fps", "max_dim", "jpeg_quality", "max_seconds", "captions", "pointer", "encode", "encode_preset", "codec", "crf", "speed", "profile", "keep_raw_video_file", "save_path", "overwrite", "silent"}; - REQUIRE(names("go_to_layer") == Names{"percent"}); - REQUIRE(names("go_to_tab") == Names{"tab"}); - for (const char* key : {"load_project", "import_file", "add_primitive_svg", "install_local_plugin"}) + for (const char* key : {"object_add_svg", "preset_export"}) REQUIRE(names(key) == path); - for (const char* key : {"save_project_as", "export_gcode", "export_stl", "export_3mf", "export_sliced_file", "export_all_sliced_file"}) - REQUIRE(names(key) == output); - for (const char* key : {"export_stl_multi", "export_config"}) - REQUIRE(names(key) == path); - REQUIRE(names("import_configs") == Names{"path", "on_conflict"}); - REQUIRE(names("open_preferences") == Names{"tab", "key"}); - REQUIRE(names("obj_rename") == Names{"name"}); - REQUIRE(names("obj_set_instances") == Names{"count"}); - for (const char* key : {"obj_order_by_name", "obj_order_by_filament", "obj_order_by_height", "obj_order_by_size"}) - REQUIRE(names(key) == all); - for (const char* key : {"add_primitive_cube", "add_primitive_cylinder", "add_primitive_sphere", "add_primitive_cone", - "add_primitive_disc", "add_primitive_torus"}) - REQUIRE(names(key) == size); - REQUIRE(names("plate_goto") == Names{"plate"}); - REQUIRE(names("filament_delete") == Names{"filament_slot"}); - REQUIRE(names("start_recording") == recording); + const Names view = names("view_set"); + for (const char* name : {"tab", "layer_percent", "camera", "projection", "layout"}) { + INFO(name); + CHECK(view.count(name) == 1); + } + // A command whose tile asks takes, in its place, the arguments of the tile and silent. + REQUIRE(names("project_open") == Names{"path", "discard_changes", "silent"}); + REQUIRE(names("project_import") == Names{"paths", "entries", "archive", "silent"}); + REQUIRE(names("project_save") == Names{"path", "overwrite", "save_as", "silent"}); + REQUIRE(names("project_export") == Names{"format", "path", "objects", "object_ids", "plates", "per_object", "overwrite", "silent"}); + REQUIRE(names("preset_import") == Names{"path", "on_conflict", "silent"}); + REQUIRE(names("plugin_install_local") == Names{"path", "overwrite", "silent"}); + REQUIRE(names("window_open") == Names{"window", "tab", "key"}); + // The object commands made from rows take their targets, by index or by the ids object_list reports. + 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"}); + 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_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_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"}); + REQUIRE(names("object_reload_from_disk") == Names{"objects", "object_ids", "parts", "part_ids", "all"}); + REQUIRE(names("part_replace") == Names{"object", "object_id", "part", "part_id", "path"}); + // The plate commands made from rows take the plate, and what their dialog or icon gives. + REQUIRE(names("plate_select") == Names{"plate"}); + REQUIRE(names("plate_delete") == Names{"plate"}); + REQUIRE(names("plate_duplicate") == Names{"plate"}); + REQUIRE(names("plate_rename") == Names{"plate", "name", "silent"}); + REQUIRE(names("plate_lock") == Names{"plate", "locked"}); + REQUIRE(names("filament_delete") == Names{"filament_slot", "merge_into"}); + REQUIRE(names("filament_add_mixed") == Names{"components", "ratios"}); + REQUIRE(names("recording_start") == recording); // The object arrange fills a plate with is named as an object, not as a count. - CHECK(names("arrange").count("fill_object") == 1); - CHECK(names("arrange").count("fill") == 0); + CHECK(names("object_arrange").count("fill_object") == 1); + CHECK(names("object_arrange").count("fill") == 0); - // Of the tiles, only the two values of the second phase are required; every other tile does its person's - // form when it is given no arguments. - for (const NativeCommand* c : NativeCommands::palette_commands(NativeCommands::instance())) { - INFO(c->key); - CHECK(c->input_schema.contains("required") == (c->key == "go_to_layer" || c->key == "go_to_tab")); + // A command with a tile of its own requires nothing: it does its person's form when it is given no arguments. + for (const NativeCommands::PaletteTile& t : NativeCommands::palette_tiles(NativeCommands::instance())) { + if (t.tile != nullptr) + continue; + INFO(t.command->key); + CHECK_FALSE(t.command->input_schema.contains("required")); } } @@ -177,10 +213,10 @@ TEST_CASE("the view, window and gesture tools are titled by all they do", "[Mcp] const NativeCommand* c = NativeCommands::find(key); return c != nullptr ? c->title : std::string(); }; - CHECK(title("set_view") == "Set up the view"); - CHECK(title("set_window") == "Size, move or raise a window"); + CHECK(title("view_set") == "Set up the view"); + CHECK(title("window_set") == "Size, move or raise a window"); CHECK(title("mouse_gesture") == "Mouse gesture on a 3D view or page element"); - CHECK(title("pick_gizmo_file") == "Load or save the open gizmo's SVG or texture file"); + CHECK(title("gizmo_pick_file") == "Load or save the open gizmo's SVG or texture file"); } // The app opens on Home, so a slice or arrange an agent starts at once updates its progress @@ -300,8 +336,8 @@ struct FakeWorker } }; -// A core with stand-ins for the tools that start an arrange (the typed arrange, run_action -// obj_arrange, a click on a plate's Arrange icon, which queues its event), change the scene (a +// A core with stand-ins for the tools that start an arrange (the typed object_arrange, action_run of the +// obj_arrange tile, a click on a plate's Arrange icon, which queues its event), change the scene (a // mutate tool, a key on the canvas), answer a dialog, read, and cancel. struct Harness { @@ -318,7 +354,7 @@ struct Harness Harness() { timing.soft_budget = 100ms; - add("arrange", GuardClass::Mutate, [this](const json&, ToolContext& ctx) { + add("object_arrange", GuardClass::Mutate, [this](const json&, ToolContext& ctx) { ctx.run_ui([&] { worker.start(job_length); return json(); @@ -327,14 +363,14 @@ struct Harness std::this_thread::sleep_for(20ms); return ToolResult::ok({{"arranged", true}}); }); - add("run_action", GuardClass::Mutate, [this](const json&, ToolContext& ctx) { + add("action_run", GuardClass::Mutate, [this](const json&, ToolContext& ctx) { ctx.run_ui([&] { worker.start(job_length); return json(); }); - return ToolResult::ok({{"ran", "obj_arrange"}}); + return ToolResult::ok({{"ran", "orca_command:obj_arrange:orca"}}); }); - add("click", GuardClass::Recover, [this](const json&, ToolContext& ctx) { + add("widget_click", GuardClass::Recover, [this](const json&, ToolContext& ctx) { ctx.run_ui([&] { core->admit({}); // the target is outside any dialog ui.post([this] { worker.start(job_length); }); @@ -343,19 +379,19 @@ struct Harness ctx.observe_ui([] { return json(); }); // settle return ToolResult::ok(); }); - add("press_keys", GuardClass::Recover, [this](const json&, ToolContext& ctx) { + add("keyboard_press", GuardClass::Recover, [this](const json&, ToolContext& ctx) { return ToolResult::ok(ctx.run_ui([&] { core->admit({}); return json("deleted"); })); }); - add("answer_dialog", GuardClass::Recover, + add("dialog_answer", GuardClass::Recover, [](const json&, ToolContext& ctx) { return ToolResult::ok(ctx.run_ui([] { return json("pressed"); })); }); add("edit", GuardClass::Mutate, [](const json&, ToolContext& ctx) { return ToolResult::ok(ctx.run_ui([] { return json("edited"); })); }); add("read", GuardClass::Inspect, [this](const json&, ToolContext& ctx) { return ToolResult::ok(ctx.run_ui([&] { return json(worker.busy()); })); }); - add("cancel_job", GuardClass::Recover, [this](const json&, ToolContext& ctx) { + add("job_cancel", GuardClass::Recover, [this](const json&, ToolContext& ctx) { return ToolResult::ok(ctx.run_ui([&] { for (const std::string& op : jobs.running_operations()) if (core->cancel_worker(op)) @@ -378,7 +414,7 @@ struct Harness d.key = name; d.guard = guard; d.inline_call = guard == GuardClass::Inspect; - d.allowed_during_operation = name == "cancel_job"; + d.allowed_during_operation = name == "job_cancel"; d.budget_ms = 200; d.run = std::move(handler); registry.add(std::move(d)); @@ -410,14 +446,14 @@ TEST_CASE("a worker job a call starts holds admission past the reply budget unti { Harness h; h.start(); - const std::string job = h.start_job("run_action"); + const std::string job = h.start_job("action_run"); CHECK(h.refused_by(h.call("edit"), job)); CHECK_FALSE(h.call("read").is_error); const auto done = h.jobs.wait(job, 5000ms); REQUIRE(done.has_value()); CHECK_FALSE(done->is_error); - CHECK(done->data["ran"] == "obj_arrange"); + CHECK(done->data["ran"] == "orca_command:obj_arrange:orca"); // The job ends only once the worker is idle, so a change right after it is admitted. CHECK_FALSE(h.worker.busy()); CHECK_FALSE(h.call("edit").is_error); @@ -428,11 +464,11 @@ TEST_CASE("a cancelled worker job keeps admission until the worker is really idl Harness h; h.job_length = 10s; h.worker.cancel_delay = 800ms; // slower than the reply budget - SECTION("cancel_job") + SECTION("job_cancel") { h.start(); - const std::string job = h.start_job("arrange"); - const ToolResult cancel = h.call("cancel_job"); + const std::string job = h.start_job("object_arrange"); + const ToolResult cancel = h.call("job_cancel"); REQUIRE_FALSE(cancel.is_error); CHECK(cancel.data == job); CHECK(h.refused_by(h.call("edit"), job)); @@ -449,7 +485,7 @@ TEST_CASE("a cancelled worker job keeps admission until the worker is really idl { h.timing.worker_timeout = 300ms; h.start(); - const std::string job = h.start_job("run_action"); + const std::string job = h.start_job("action_run"); std::this_thread::sleep_for(500ms); // past the timeout, before the cancelled job stops CHECK(h.worker.cancels == 1); CHECK(h.worker.busy()); @@ -467,8 +503,8 @@ TEST_CASE("a cancelled worker job keeps admission until the worker is really idl TEST_CASE("a change is refused while an arrange an MCP call started runs, however it started", "[Mcp][Scene]") { - // The typed arrange, run_action obj_arrange, and a recover input whose click queues the job. - for (const char* starter : {"arrange", "run_action", "click"}) { + // The typed object_arrange, action_run of the obj_arrange tile, and a recover input whose click queues the job. + for (const char* starter : {"object_arrange", "action_run", "widget_click"}) { DYNAMIC_SECTION(starter) { Harness h; @@ -488,12 +524,12 @@ TEST_CASE("a scene-changing input is refused while that job runs, and a dialog a { Harness h; h.start(); - const std::string job = h.start_job("run_action"); - CHECK(h.refused_by(h.call("press_keys"), job)); // Delete on the canvas - CHECK(h.refused_by(h.call("click"), job)); // a GL toolbar item - CHECK_FALSE(h.call("answer_dialog").is_error); + const std::string job = h.start_job("action_run"); + CHECK(h.refused_by(h.call("keyboard_press"), job)); // Delete on the canvas + CHECK(h.refused_by(h.call("widget_click"), job)); // a GL toolbar item + CHECK_FALSE(h.call("dialog_answer").is_error); REQUIRE(h.jobs.wait(job, 5000ms).has_value()); - CHECK_FALSE(h.call("press_keys").is_error); + CHECK_FALSE(h.call("keyboard_press").is_error); } TEST_CASE("a worker job that starts between a call's closures is the call's, whoever started it", "[Mcp][Scene]") @@ -522,12 +558,12 @@ TEST_CASE("a worker job that starts between a call's closures is the call's, who CHECK_FALSE(h.worker.busy()); } -TEST_CASE("a worker job a person started refuses changes but not reads, and cancel_job leaves it", "[Mcp][Scene]") +TEST_CASE("a worker job a person started refuses changes but not reads, and job_cancel leaves it", "[Mcp][Scene]") { Harness h; h.start(); h.worker.start(800ms); // Text typing - for (const char* change : {"edit", "press_keys"}) { + for (const char* change : {"edit", "keyboard_press"}) { const ToolResult refused = h.call(change); CHECK(refused.is_error); CHECK(refused.message.find("Busy: a background job") != std::string::npos); @@ -535,7 +571,7 @@ TEST_CASE("a worker job a person started refuses changes but not reads, and canc const ToolResult read = h.call("read"); CHECK_FALSE(read.is_error); CHECK(read.data == true); - CHECK(h.call("cancel_job").data.is_null()); + CHECK(h.call("job_cancel").data.is_null()); CHECK(h.worker.cancels == 0); while (h.worker.busy()) std::this_thread::sleep_for(20ms); @@ -658,6 +694,267 @@ TEST_CASE("a precise seam reports its subtype, and an object its auto drop", "[M CHECK_FALSE(info["parts"][1].contains("filament")); } +TEST_CASE("object_list reports an object's mesh errors: its open edges and what was repaired", "[Mcp][Scene]") +{ + Model model; + // A 20 mm cube with one triangle taken out, which leaves three open edges, and a closed one whose mesh the loader + // repaired: two edges fixed and a facet reversed. + indexed_triangle_set open = make_cube(20., 20., 20.).its; + open.indices.pop_back(); + ModelObject* holed = model.add_object(); + holed->add_volume(TriangleMesh(std::move(open))); + holed->add_instance(); + RepairedMeshErrors repaired; + repaired.edges_fixed = 2; + repaired.facets_reversed = 1; + ModelObject* closed = model.add_object(); + closed->add_volume(TriangleMesh(make_cube(20., 20., 20.).its, repaired)); + closed->add_instance(); + + const json errors = Mcp::object_info(*holed, 0).at("mesh_errors"); + CHECK(errors["open_edges"] == 3); + CHECK(errors["manifold"] == false); + CHECK(errors["edges_fixed"] == 0); + const json fixed = Mcp::object_info(*closed, 1).at("mesh_errors"); + CHECK(fixed["open_edges"] == 0); + CHECK(fixed["manifold"] == true); + CHECK(fixed["edges_fixed"] == 2); + CHECK(fixed["facets_reversed"] == 1); + for (const char* count : {"degenerate_facets", "facets_removed", "backwards_edges"}) { + INFO(count); + CHECK(fixed[count] == 0); + } +} + +TEST_CASE("Printable and Auto Drop take their state, and Fix Model all the objects or some", "[Mcp][Scene]") +{ + const auto command = [](const char* key) { + const NativeCommand* found = NativeCommands::find(key); + REQUIRE(found != nullptr); + return found; + }; + // The state is a required boolean. + for (const auto& [key, state] : {std::pair{"object_set_printable", "printable"}, + std::pair{"object_set_auto_drop", "auto_drop"}}) { + INFO(key); + json none{{"objects", json::array({0})}}; + CHECK_THAT(Mcp::argument_error(*command(key), none), ContainsSubstring(state)); + json word{{"objects", json::array({0})}, {state, "yes"}}; + CHECK_THAT(Mcp::argument_error(*command(key), word), ContainsSubstring(state)); + json given{{"objects", json::array({0})}, {state, false}}; + CHECK(Mcp::argument_error(*command(key), given).empty()); + } + json instance{{"instances", json::array({json::array({0, 1})})}, {"printable", false}}; + CHECK(Mcp::argument_error(*command("object_set_printable"), instance).empty()); + + // all needs no other target; a plate, objects or parts name what is repaired. + for (json args : {json{{"all", true}}, json{{"plate", 1}}, json{{"objects", json::array({0, 2})}}, + json{{"parts", json::array({json::array({0, 1})})}}, json::object()}) { + INFO(args.dump()); + CHECK(Mcp::argument_error(*command("object_fix"), args).empty()); + } + // The repair is cancelled with job_cancel {job}. + CHECK(command("object_fix")->cancellable); +} + +namespace { + +// A call's context that fails the case when the call reaches its UI closure. +class NoUiContext final : public ToolContext +{ +public: + json run_ui(const std::function& /*fn*/) override + { + FAIL("the call reached its UI closure"); + return json(); + } + json observe_ui(const std::function& /*fn*/) override + { + FAIL("the call reached its UI closure"); + return json(); + } + const std::string& job_id() const override { return m_job; } + bool cancelled() const override { return false; } + ToolResult call_child(const std::string& /*tool*/, const json& /*args*/) override { return ToolResult::error("no child calls"); } + std::set lineage() const override { return {}; } + void set_journal_args(json /*args*/) override {} + void begin_operation() override {} + +private: + std::string m_job; +}; + +} // namespace + +TEST_CASE("Fix Model and Reload refuse all or a plate given with targets, and Fix Model all with a plate", "[Mcp][Scene]") +{ + const NativeCommand* fix = NativeCommands::find("object_fix"); + const NativeCommand* reload = NativeCommands::find("object_reload_from_disk"); + REQUIRE(fix != nullptr); + REQUIRE(reload != nullptr); + // Each passes the schema, and the command refuses it before it reads the app. + const std::vector> refused{ + {fix, {{"all", true}, {"plate", 0}}, "Give all or plate, not both"}, + {fix, {{"all", true}, {"objects", json::array({0})}}, "all repairs every object; leave the targets out"}, + {fix, {{"plate", 0}, {"parts", json::array({json::array({0, 1})})}}, "plate repairs the objects on it; leave the targets out"}, + {reload, {{"all", true}, {"objects", json::array({0})}}, "all reloads every object; leave the targets out"}}; + for (const auto& [command, args, message] : refused) { + INFO(command->key << " " << args.dump()); + json given = args; + CHECK(Mcp::argument_error(*command, given).empty()); + NoUiContext ctx; + CHECK_THROWS_WITH(command->run(args, ctx), message); + } +} + +TEST_CASE("an order of objects is by a key or the objects named, of one plate, and descending goes with a key", "[Mcp][Scene]") +{ + const NativeCommand* order = NativeCommands::find("object_order"); + REQUIRE(order != nullptr); + // Each passes the schema, and the command refuses it before it reads the app. + const std::vector> refused{ + {json::object(), "Give by, or the objects in order"}, + {{{"by", "name"}, {"order", json::array({1, 0})}}, "Give by or order, not both"}, + {{{"order", json::array({1, 0})}, {"all", true}}, "order names the objects of one plate: leave all out"}, + {{{"order", json::array({1, 0})}, {"descending", true}}, "descending goes with by: order gives the objects in their order"}, + {{{"by", "name"}, {"all", true}, {"plate", 0}}, "Give plate or all, not both"}}; + for (const auto& [args, message] : refused) { + INFO(args.dump()); + json given = args; + CHECK(Mcp::argument_error(*order, given).empty()); + NoUiContext ctx; + CHECK_THROWS_WITH(order->run(args, ctx), message); + } + // An order names at least one object. + json empty{{"order", json::array()}}; + CHECK_THAT(Mcp::argument_error(*order, empty), ContainsSubstring("order")); +} + +TEST_CASE("Import takes entries with one ZIP archive, and an export a file per object in STL or DRC alone", "[Mcp][Scene]") +{ + const NativeCommand* import_ = NativeCommands::find("project_import"); + const NativeCommand* export_ = NativeCommands::find("project_export"); + REQUIRE(import_ != nullptr); + REQUIRE(export_ != nullptr); + // Each passes the schema, and the command refuses it before it reads the app or the files. + const json one_cube = json::array({"cube.stl"}); + const std::vector> refused{ + {import_, {{"paths", json::array({"/models/cube.stl"})}, {"entries", one_cube}}, + "entries names files of a .zip archive: give the archive in paths"}, + {import_, {{"paths", json::array({"/models/a.zip", "/models/b.zip"})}, {"entries", one_cube}}, + "entries names the files of one archive: give one .zip in paths"}, + {export_, {{"format", "gcode"}, {"path", "/out/plate.gcode"}, {"per_object", true}}, "per_object goes with format stl or drc"}, + {export_, {{"format", "toolpaths_obj"}, {"path", "/out/toolpaths.obj"}, {"per_object", true}}, + "per_object goes with format stl or drc"}, + {export_, {{"format", "toolpaths_obj"}, {"path", "/out/toolpaths.obj"}, {"plates", 1}}, + "toolpaths_obj writes the toolpaths the Preview shows: plates goes with the other formats"}, + {export_, {{"format", "drc"}, {"path", "/out/objects"}, {"per_object", true}, {"plates", 1}}, + "per_object writes every object into the folder path names: plates and overwrite go with one file"}, + {export_, {{"format", "stl"}, {"path", "/out/objects"}, {"per_object", true}, {"overwrite", true}}, + "per_object writes every object into the folder path names: plates and overwrite go with one file"}}; + for (const auto& [command, args, message] : refused) { + INFO(command->key << " " << args.dump()); + json given = args; + CHECK(Mcp::argument_error(*command, given).empty()); + NoUiContext ctx; + CHECK_THROWS_WITH(command->run(args, ctx), message); + } + // entries names one file or more; an empty list is refused by the schema. + json no_entries{{"paths", json::array({"/models/a.zip"})}, {"entries", json::array()}}; + CHECK(Mcp::argument_error(*import_, no_entries).find("entries must hold at least 1 item") != std::string::npos); +} + +TEST_CASE("view_set takes the display switches, the sidebar, and the Preview's legend fold and G-code window", "[Mcp][Scene]") +{ + const NativeCommand* view = NativeCommands::find("view_set"); + REQUIRE(view != nullptr); + const json& properties = view->input_schema.at("properties"); + for (const char* name : {"sidebar_collapsed", "legend_collapsed", "gcode_window", "labels", "overhangs", "outline", "wireframe", + "gridlines", "axes", "navigator"}) { + INFO(name); + REQUIRE(properties.contains(name)); + CHECK(properties.at(name).at("type") == "boolean"); + } + // The sidebar's width is pixels, or "default". + REQUIRE(properties.contains("sidebar_width")); + for (const json& width : {json(420), json("default")}) { + json args{{"sidebar_width", width}}; + CHECK(Mcp::argument_error(*view, args).empty()); + } + for (const json& width : {json(0), json(true), json(12.5)}) { + INFO(width.dump()); + json args{{"sidebar_width", width}}; + CHECK_THAT(Mcp::argument_error(*view, args), ContainsSubstring("sidebar_width")); + } + // Outside the Design tab the section view is Prepare's and the Preview's, which takes on alone. + json section{{"section", {{"on", true}}}, {"labels", true}}; + CHECK(Mcp::argument_error(*view, section).empty()); + + // Each passes the schema, and the command refuses it before it changes anything: a width that is no number of pixels + // and the Design view's cut without the Design tab, also beside a switch the call would set. + const std::vector> refused{ + {{{"sidebar_width", "wide"}, {"labels", true}}, "sidebar_width is a width in pixels or \"default\""}, + {{{"section", {{"on", true}, {"z", 5}}}}, "z and keep are the Design view's cut"}, + {{{"tab", "prepare"}, {"section", {{"on", true}, {"keep", "upper"}}}, {"axes", false}}, "z and keep are the Design view's cut"}}; + for (const auto& [args, message] : refused) { + INFO(args.dump()); + json given = args; + CHECK(Mcp::argument_error(*view, given).empty()); + NoUiContext ctx; + CHECK_THROWS_WITH(view->run(args, ctx), ContainsSubstring(message)); + } +} + +TEST_CASE("a plate's origin and size are its rectangle on the bed, in bed coordinates", "[Mcp][Scene]") +{ + // The second plate of a row of 256 x 256 mm plates: the plate list moves the bed shape by the plate's position, which + // is neither the origin the plate was made with nor the box that holds its grabber in front. + PartPlate plate(nullptr, Vec3d(1000., 1000., 0.), 256, 256, 250., nullptr, nullptr); + plate.set_shape({{0., 0.}, {256., 0.}, {256., 256.}, {0., 256.}}, {}, {}, {}, Vec2d(307.2, 0.), 0.f, 0.f); + const json place = Mcp::plate_place(plate); + REQUIRE(place.at("origin").size() == 2); + REQUIRE(place.at("size").size() == 2); + CHECK_THAT(place["origin"][0].get(), WithinAbs(307.2, 1e-9)); + CHECK_THAT(place["origin"][1].get(), WithinAbs(0., 1e-9)); + CHECK_THAT(place["size"][0].get(), WithinAbs(256., 1e-9)); + CHECK_THAT(place["size"][1].get(), WithinAbs(256., 1e-9)); + // A cube placed at the origin plus half the size stands in the middle of the plate. + const BoundingBoxf3& box = plate.get_bounding_box(); + CHECK_THAT(place["origin"][0].get() + place["size"][0].get() / 2., WithinAbs(box.center().x(), 1e-9)); + CHECK_THAT(place["origin"][1].get() + place["size"][1].get() / 2., WithinAbs(box.center().y(), 1e-9)); +} + +TEST_CASE("Clone makes at least one copy, and Replace takes one part and the file it is replaced with", "[Mcp][Scene]") +{ + const auto command = [](const char* key) { + const NativeCommand* found = NativeCommands::find(key); + REQUIRE(found != nullptr); + return found; + }; + // A count written as a string of digits is taken as that number, as every integer argument is. + for (json count : {json(0), json(-2), json(1.5), json("three")}) { + INFO(count.dump()); + json args{{"objects", json::array({0})}, {"count", count}}; + CHECK_THAT(Mcp::argument_error(*command("object_clone"), args), ContainsSubstring("count")); + } + json three{{"objects", json::array({0})}, {"count", 3}, {"arrange", false}}; + CHECK(Mcp::argument_error(*command("object_clone"), three).empty()); + // With no count, one copy, as the Clone dialog's field starts. + json selection = json::object(); + CHECK(Mcp::argument_error(*command("object_clone"), selection).empty()); + + json no_path{{"object", 0}, {"part", 0}}; + CHECK_THAT(Mcp::argument_error(*command("part_replace"), no_path), ContainsSubstring("path")); + json several{{"parts", json::array({json::array({0, 0})})}, {"path", "/models/cube.stl"}}; + CHECK_THAT(Mcp::argument_error(*command("part_replace"), several), ContainsSubstring("parts")); + json one{{"object", 0}, {"part", 1}, {"path", "/models/cube.stl"}}; + CHECK(Mcp::argument_error(*command("part_replace"), one).empty()); + + // A reload takes every object with all, which no other target goes with. + json all{{"all", true}}; + CHECK(Mcp::argument_error(*command("object_reload_from_disk"), all).empty()); +} + namespace { // Three objects of one cube each: "alone" on plate 0, "twice" with an instance on plate 0 and one on @@ -688,7 +985,7 @@ struct PlatedModel } // namespace -TEST_CASE("list_objects lists each plate's objects, then those on no plate", "[Mcp][Scene]") +TEST_CASE("object_list lists each plate's objects, then those on no plate", "[Mcp][Scene]") { const PlatedModel scene; const json out = scene.list(); @@ -723,7 +1020,7 @@ TEST_CASE("list_objects lists each plate's objects, then those on no plate", "[M CHECK_FALSE(out.contains("next_offset")); } -TEST_CASE("list_objects with a plate lists that plate alone", "[Mcp][Scene]") +TEST_CASE("object_list with a plate lists that plate alone", "[Mcp][Scene]") { const PlatedModel scene; const json out = scene.list({{"plate", 1}}); @@ -737,7 +1034,7 @@ TEST_CASE("list_objects with a plate lists that plate alone", "[Mcp][Scene]") CHECK_THROWS_WITH(scene.list({{"plate", 3}}), ContainsSubstring("Plate 3 does not exist (the project has plates 0..2)")); } -TEST_CASE("list_objects pages the objects, listing each under every plate it is on", "[Mcp][Scene]") +TEST_CASE("object_list pages the objects, listing each under every plate it is on", "[Mcp][Scene]") { const PlatedModel scene; // The second of the three objects is the one on two plates. @@ -760,7 +1057,7 @@ TEST_CASE("list_objects pages the objects, listing each under every plate it is CHECK_FALSE(out.contains("next_offset")); } -TEST_CASE("list_objects with a plate pages and counts that plate's objects", "[Mcp][Scene]") +TEST_CASE("object_list with a plate pages and counts that plate's objects", "[Mcp][Scene]") { const PlatedModel scene; const json out = scene.list({{"plate", 0}, {"offset", 1}, {"limit", 1}}); @@ -821,62 +1118,280 @@ TEST_CASE("a shape's size needs one positive number per field of the size dialog } } -// The object list's context-menu commands are Speed Dial commands beside the other object commands. +// The object list's context-menu rows are tiles of commands beside the other object and part commands. TEST_CASE("the object structure commands sit beside the other object commands", "[Mcp][Scene]") { - const NativeCommand* peer = NativeCommands::find("obj_delete"); - REQUIRE(peer != nullptr); - for (const char* key : {"obj_type_part", "obj_type_negative", "obj_type_modifier", "obj_type_support_blocker", - "obj_type_support_enforcer", "obj_type_precise_seam", "obj_rename", "obj_set_instances", "obj_assemble", - "obj_instances_to_objects", "obj_order_by_name", "obj_order_by_filament", "obj_order_by_height", - "obj_order_by_size"}) { + const NativeCommand* objects = NativeCommands::find("object_delete"); + const NativeCommand* parts = NativeCommands::find("part_add"); + REQUIRE(objects != nullptr); + REQUIRE(parts != nullptr); + for (const char* key : {"part_change_type", "object_rename", "object_set_instances", "object_assemble", "object_separate_instances", + "object_order"}) { INFO(key); const NativeCommand* c = NativeCommands::find(key); REQUIRE(c != nullptr); - CHECK(c->group == peer->group); + CHECK(c->group == (std::string(key).rfind("part_", 0) == 0 ? parts : objects)->group); CHECK_FALSE(c->description.empty()); + REQUIRE(c->tiles.is_array()); + for (const json& tile : c->tiles) + CHECK_FALSE(tile.at("description").get().empty()); + } +} + +TEST_CASE("a split is into objects or parts, a subtype is a precise seam's, and an order is by name, filament, height or size", "[Mcp][Scene]") +{ + const auto command = [](const char* key) { + const NativeCommand* found = NativeCommands::find(key); + REQUIRE(found != nullptr); + return found; + }; + const auto values = [&command](const char* key, const char* arg) { + std::set out; + for (const json& value : command(key)->input_schema.at("properties").at(arg).at("enum")) + out.insert(value.get()); + return out; + }; + CHECK(values("object_split", "into") == std::set{"objects", "parts"}); + for (const char* into : {"pieces", "object"}) { + INFO(into); + json args{{"object", 0}, {"into", into}}; + CHECK_THAT(Mcp::argument_error(*command("object_split"), args), ContainsSubstring("into")); + } + json split{{"object", 0}, {"into", "parts"}, {"keep_z", true}}; + CHECK(Mcp::argument_error(*command("object_split"), split).empty()); + + CHECK(values("object_order", "by") == std::set{"name", "filament", "height", "size"}); + + // A subtype is one of a precise seam's, and with another type it is refused. + CHECK(values("part_change_type", "subtype") == std::set{"center", "left", "right", "enforced", "blocked", "neutral"}); + CHECK(Mcp::precise_seam_subtype("left") == ModelVolumeType::PRECISE_SEAM_LEFT); + CHECK(Mcp::precise_seam_subtype("neutral") == ModelVolumeType::PRECISE_SEAM_NEUTRAL); + CHECK(Mcp::precise_seam_subtype("part") == ModelVolumeType::INVALID); + Model model; + ModelObject* object = model.add_object(); + object->add_volume(make_cube(10., 10., 10.), ModelVolumeType::MODEL_PART, false); + object->add_volume(make_cube(5., 5., 5.), ModelVolumeType::PARAMETER_MODIFIER, false); + object->add_instance(); + Ops::Targets modifier; + modifier.parts = {{0, 1}}; + const std::optional refused = + Ops::part_type_refusal(model, modifier, ModelVolumeType::NEGATIVE_VOLUME, ModelVolumeType::PRECISE_SEAM_LEFT); + REQUIRE(refused); + CHECK(std::string(refused->code) == "subtype_without_seam"); + CHECK_FALSE(Ops::part_type_refusal(model, modifier, ModelVolumeType::PRECISE_SEAM_CENTER, ModelVolumeType::PRECISE_SEAM_LEFT)); +} + +TEST_CASE("a mirror needs its axis, a centring takes a plate and no part, and a primitive its plate, position and name", "[Mcp][Scene]") +{ + const NativeCommand* mirror = NativeCommands::find("object_mirror"); + REQUIRE(mirror != nullptr); + for (const json& axis : {json("x"), json("y"), json("z")}) { + json args{{"objects", json::array({0})}, {"axis", axis}}; + CHECK(Mcp::argument_error(*mirror, args).empty()); + } + json no_axis{{"objects", json::array({0})}}; + CHECK_THAT(Mcp::argument_error(*mirror, no_axis), ContainsSubstring("axis")); + json bad_axis{{"axis", "w"}}; + CHECK_THAT(Mcp::argument_error(*mirror, bad_axis), ContainsSubstring("axis")); + + const NativeCommand* center = NativeCommands::find("object_center"); + REQUIRE(center != nullptr); + json on_plate{{"objects", json::array({0, 2})}, {"plate", 1}}; + CHECK(Mcp::argument_error(*center, on_plate).empty()); + json parts{{"parts", json::array({json::array({0, 0})})}}; + CHECK_THAT(Mcp::argument_error(*center, parts), ContainsSubstring("parts")); + + const NativeCommand* primitive = NativeCommands::find("object_add_primitive"); + REQUIRE(primitive != nullptr); + json placed{{"shape", "cube"}, {"size", json::array({20, 20, 20})}, {"plate", 1}, {"position", json::array({100, 100, 0})}, {"name", "block"}}; + CHECK(Mcp::argument_error(*primitive, placed).empty()); + // A call with more than a tile's shape is the silent form, which asks for no size. + CHECK_FALSE(Mcp::person_form(*primitive, placed)); + // Its size is checked as part_add's is: the size dialog's fields, each above 0. + const std::vector cylinder = Mcp::part_shape_size("cylinder", json::array({30, 10})); + REQUIRE(cylinder.size() == 2); + CHECK_THAT(cylinder[0], WithinAbs(30., 1e-9)); + CHECK_THAT(cylinder[1], WithinAbs(10., 1e-9)); + CHECK(Mcp::part_shape_size("cube", json()).empty()); + CHECK_THROWS_WITH(Mcp::part_shape_size("cube", json::array({20, 20})), ContainsSubstring("[X, Y, Z]")); + CHECK_THROWS_AS(Mcp::part_shape_size("sphere", json::array({0})), ToolFailure); + // Its operation names the object, so it reaches the rename's as well. + CHECK(primitive->operations == std::vector{"add_primitive", "rename_object"}); +} + +namespace { + +// Three objects of cubes, named for what they have: "first" with one instance and one part, "second" with two +// instances and two parts, "third" with one of each. +struct TargetModel +{ + Model model; + + TargetModel() + { + for (const auto& [name, instances, parts] : std::vector>{{"first", 1, 1}, {"second", 2, 2}, {"third", 1, 1}}) { + ModelObject* object = model.add_object(); + object->name = name; + for (int p = 0; p < parts; ++p) + object->add_volume(make_cube(10., 10., 10.), ModelVolumeType::MODEL_PART, false)->name = name + " part " + std::to_string(p); + for (int i = 0; i < instances; ++i) + object->add_instance(); + } + } +}; + +constexpr unsigned kEveryKind = Mcp::kObjects | Mcp::kInstances | Mcp::kParts; + +// The targets a call's `args` name, with no selection to fall back on. +Ops::Outcome named_targets(const Model& model, const json& args, unsigned kinds, bool one = false) +{ + return Mcp::resolve_targets(model, nullptr, args, kinds, one); +} + +json pairs(std::initializer_list> list) +{ + json out = json::array(); + for (const auto& [a, b] : list) + out.push_back(json::array({a, b})); + return out; +} + +} // namespace + +TEST_CASE("a command's targets are what its arguments name, else the selection", "[Mcp][Scene]") +{ + const TargetModel m; + const Model& model = m.model; + + const auto named = named_targets(model, {{"objects", json::array({0, 2})}}, Mcp::kObjects); + REQUIRE(named); + CHECK(named.value().objects == std::vector{0, 2}); + CHECK(named.value().instances.empty()); + CHECK(named.value().parts.empty()); + CHECK_FALSE(named.value().from_selection); + + // One target, named in the singular: an instance of the second object, then one of its parts by index and id. + const auto instance = named_targets(model, {{"object", 1}, {"instance", 1}}, kEveryKind, true); + REQUIRE(instance); + CHECK(instance.value().instances == std::vector>{{1, 1}}); + const auto part = named_targets(model, {{"object", 1}, {"part", 1}, {"part_id", model.objects[1]->volumes[1]->id().id}}, kEveryKind, true); + REQUIRE(part); + CHECK(part.value().parts == std::vector>{{1, 1}}); + + // Every index and every expected id is checked before anything is returned, and a miss is named. + CHECK_THROWS_WITH(named_targets(model, {{"objects", json::array({0, 3})}}, Mcp::kObjects), ContainsSubstring("object index 3")); + const std::size_t other = model.objects[1]->id().id; + CHECK_THROWS_WITH(named_targets(model, {{"objects", json::array({0})}, {"object_ids", json::array({other})}}, Mcp::kObjects), + ContainsSubstring(std::to_string(other))); + CHECK_THROWS_WITH(named_targets(model, {{"parts", pairs({{1, 5}})}}, Mcp::kParts), ContainsSubstring("part 5")); + CHECK_THROWS_WITH(named_targets(model, {{"instances", pairs({{0, 1}})}}, Mcp::kInstances), ContainsSubstring("instance 1")); + // Both forms of one target at once. + CHECK_THROWS_AS(named_targets(model, {{"object", 1}, {"objects", json::array({0})}}, Mcp::kObjects), ToolFailure); + + // With none named, the targets are the selection, and a null selection holds nothing. + const auto none = named_targets(model, json::object(), kEveryKind); + REQUIRE_FALSE(none); + CHECK(std::string(none.refusal().code) == "nothing_selected"); + // A command of one target refuses two. + const auto two = named_targets(model, {{"objects", json::array({0, 2})}}, Mcp::kObjects, true); + REQUIRE_FALSE(two); + CHECK(std::string(two.refusal().code) == "one_object_only"); + + // A command's schema has the forms of the kinds it takes, and no other. + NativeCommand command; + command.input_schema = Mcp::with_targets(Mcp::object_schema({}), Mcp::kObjects, false); + json parts{{"parts", pairs({{1, 0}})}}; + CHECK_THAT(Mcp::argument_error(command, parts), ContainsSubstring("parts")); + json objects{{"objects", json::array({1})}}; + CHECK(Mcp::argument_error(command, objects).empty()); + const auto names = [](const std::vector& props) { + std::set out; + for (const Mcp::Property& p : props) + out.insert(p.first); + 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"}); +} + +TEST_CASE("a reply names what the command acted on", "[Mcp][Scene]") +{ + const TargetModel m; + Ops::Targets acted; + acted.objects = {0}; + acted.parts = {{1, 1}}; + const json reply = Mcp::targets_reply(m.model, acted); + REQUIRE(reply.at("objects").size() == 1); + CHECK(reply["objects"][0] == json{{"index", 0}, {"object_id", m.model.objects[0]->id().id}, {"name", "first"}}); + REQUIRE(reply.at("parts").size() == 1); + CHECK(reply["parts"][0] == + 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")); +} + +TEST_CASE("a command's target is optional, and a plate defaults to the current one", "[Mcp][Scene]") +{ + const auto required = [](const json& schema) { + std::set out; + for (const json* list : {&schema, schema.contains("then") ? &schema.at("then") : nullptr}) + if (list != nullptr) + for (const json& name : list->value("required", json::array())) + out.insert(name.get()); + return out; + }; + // With no object, the object selected in the Prepare view. + for (const char* key : {"object_set_variable_layer_height", "object_set_height_ranges", "object_transform", "part_add"}) { + INFO(key); + const NativeCommand* command = NativeCommands::find(key); + REQUIRE(command != nullptr); + CHECK(command->input_schema.at("properties").contains("object")); + CHECK(required(command->input_schema).count("object") == 0); + } + // With no plate, the current plate. + for (const NativeCommand& command : NativeCommands::instance().commands()) { + INFO(command.key); + CHECK(required(command.input_schema).count("plate") == 0); } } namespace { // What the object list gives a new range: the object's layer height and its filament ("Default"). -DynamicPrintConfig new_range_config() +DynamicPrintConfig new_range_config(double layer_height = 0.2) { DynamicPrintConfig config; - config.set_key_value("layer_height", new ConfigOptionFloat(0.2)); + config.set_key_value("layer_height", new ConfigOptionFloat(layer_height)); config.set_key_value("extruder", new ConfigOptionInt(0)); return config; } -// set_height_ranges' parse on a two-filament printer whose layer heights are 0.08-0.28. -t_layer_config_ranges parse_ranges(const json& ranges) +// object_set_height_ranges' parse of `ranges` for an object that has `current`. +t_layer_config_ranges parse_ranges(const json& ranges, const t_layer_config_ranges& current = {}) { - return Mcp::layer_config_ranges_from_json(ranges, new_range_config(), 2, [](int) { return std::make_pair(0.08, 0.28); }); + return Mcp::layer_config_ranges_from_json(ranges, current, new_range_config()); } -json range(double min_z, double max_z, json values = json::object()) +json range(double min_z, double max_z) { - return {{"min_z", min_z}, {"max_z", max_z}, {"values", std::move(values)}}; + return {{"min_z", min_z}, {"max_z", max_z}}; } } // namespace TEST_CASE("height ranges are checked before the object changes", "[Mcp][Scene][Layers]") { - // Sorted by height; touching ranges are fine; each starts from the new-range config. - const t_layer_config_ranges ranges = parse_ranges( - json::array({range(10, 20, {{"sparse_infill_density", "25%"}}), range(0, 10, {{"layer_height", 0.12}, {"extruder", "2"}})})); + // Sorted by height; touching ranges are fine; each new one starts from the new-range config. + const t_layer_config_ranges ranges = parse_ranges(json::array({range(10, 20), range(0, 10)})); REQUIRE(ranges.size() == 2); const auto& [low, low_config] = *ranges.begin(); const auto& [high, high_config] = *std::next(ranges.begin()); CHECK(low == t_layer_height_range(0., 10.)); CHECK(high == t_layer_height_range(10., 20.)); - CHECK_THAT(low_config.opt_float("layer_height"), WithinAbs(0.12, 1e-9)); - CHECK(low_config.opt_int("extruder") == 2); - CHECK_THAT(high_config.opt_float("layer_height"), WithinAbs(0.2, 1e-9)); - CHECK(high_config.opt_int("extruder") == 0); - CHECK(high_config.opt_serialize("sparse_infill_density") == "25%"); + CHECK_THAT(low_config.opt_float("layer_height"), WithinAbs(0.2, 1e-9)); + CHECK(low_config.opt_int("extruder") == 0); + CHECK(high_config.get() == new_range_config()); CHECK(parse_ranges(json::array()).empty()); // An overlap names both ranges, whatever order they come in. @@ -888,29 +1403,72 @@ TEST_CASE("height ranges are checked before the object changes", "[Mcp][Scene][L CHECK_THROWS_AS(parse_ranges(json::array({range(6, 5)})), ToolFailure); CHECK_THROWS_AS(parse_ranges(json::array({range(-1, 5)})), ToolFailure); CHECK_THROWS_AS(parse_ranges(json::array({json{{"min_z", 0}}})), ToolFailure); +} - // A layer height given is checked against the printer's, with the range's filament. - int asked = -1; +TEST_CASE("a range that stays keeps its settings, and a new one starts from the object's layer height", "[Mcp][Scene][Layers]") +{ + // A range is min_z and max_z; its settings are the settings tools' target height_range. + const NativeCommand* set_ranges = NativeCommands::find("object_set_height_ranges"); + REQUIRE(set_ranges != nullptr); + const json& item = set_ranges->input_schema.at("properties").at("ranges").at("items"); + CHECK(item.at("properties").contains("min_z")); + CHECK(item.at("properties").contains("max_z")); + CHECK_FALSE(item.at("properties").contains("values")); + json with_values{{"object", 0}, {"ranges", json::array({{{"min_z", 0}, {"max_z", 5}, {"values", {{"wall_loops", 3}}}}})}}; + CHECK_THAT(Mcp::argument_error(*set_ranges, with_values), ContainsSubstring("unknown argument ranges[0].values")); + + Model model; + ModelObject* object = model.add_object(); + object->add_volume(make_cube(20., 20., 20.), ModelVolumeType::MODEL_PART, false); + object->add_instance(); + DynamicPrintConfig fine = new_range_config(0.12); + fine.set_key_value("sparse_infill_density", new ConfigOptionPercent(40)); + fine.set_key_value("extruder", new ConfigOptionInt(2)); + object->layer_config_ranges[{0., 5.}].assign_config(std::move(fine)); + object->layer_config_ranges[{5., 10.}].assign_config(new_range_config(0.28)); + + // [0, 5] stays; [5, 10] goes and [5, 12] comes, at the object's layer height (0.16 here). + const t_layer_config_ranges after = Mcp::layer_config_ranges_from_json(json::array({range(0, 5), range(5, 12)}), + object->layer_config_ranges, new_range_config(0.16)); + REQUIRE(after.size() == 2); + const auto& [kept, kept_config] = *after.begin(); + const auto& [added, added_config] = *std::next(after.begin()); + CHECK(kept == t_layer_height_range(0., 5.)); + CHECK(kept_config.get() == object->layer_config_ranges.at({0., 5.}).get()); + CHECK_THAT(kept_config.opt_float("layer_height"), WithinAbs(0.12, 1e-9)); + CHECK(kept_config.opt_serialize("sparse_infill_density") == "40%"); + CHECK(kept_config.opt_int("extruder") == 2); + CHECK(added == t_layer_height_range(5., 12.)); + CHECK(added_config.get() == new_range_config(0.16)); +} + +TEST_CASE("a height range's layer height is checked against the printer's for the range's filament", "[Mcp][Scene][Layers]") +{ + int asked = -1; const auto bounds = [&asked](int extruder) { asked = extruder; return std::make_pair(0.08, 0.28); }; - CHECK_THROWS_WITH(Mcp::layer_config_ranges_from_json(json::array({range(0, 5, {{"layer_height", 0.4}, {"extruder", 2}})}), - new_range_config(), 2, bounds), + DynamicPrintConfig range = new_range_config(); + range.set_key_value("extruder", new ConfigOptionInt(2)); + DynamicPrintConfig thick; + thick.set_key_value("layer_height", new ConfigOptionFloat(0.4)); + CHECK_THROWS_WITH(Mcp::check_height_range_layer_height(thick, range, bounds), ContainsSubstring("layer_height 0.4 is outside this printer's 0.08-0.28")); CHECK(asked == 2); - // The object's layer height a range starts from is not checked, as the range editor checks only what is typed. - DynamicPrintConfig thick = new_range_config(); - thick.set_key_value("layer_height", new ConfigOptionFloat(0.4)); - CHECK(Mcp::layer_config_ranges_from_json(json::array({range(0, 5)}), thick, 2, bounds).size() == 1); - - // Filaments are 0 (the object's) up to the slot count. - CHECK_THROWS_WITH(parse_ranges(json::array({range(0, 5, {{"extruder", 3}})})), ContainsSubstring("1-2")); - CHECK_THROWS_AS(parse_ranges(json::array({range(0, 5, {{"extruder", -1}})})), ToolFailure); - // Values are parsed strictly. - CHECK_THROWS_WITH(parse_ranges(json::array({range(0, 5, {{"sparse_infill_density", "lots"}})})), - ContainsSubstring("Invalid value for sparse_infill_density")); - CHECK_THROWS_AS(parse_ranges(json::array({range(0, 5, {{"wall_loops", nullptr}})})), ToolFailure); + // With the filament given beside it, that filament's. + thick.set_key_value("extruder", new ConfigOptionInt(1)); + CHECK_THROWS_AS(Mcp::check_height_range_layer_height(thick, range, bounds), ToolFailure); + CHECK(asked == 1); + DynamicPrintConfig fine; + fine.set_key_value("layer_height", new ConfigOptionFloat(0.12)); + CHECK_NOTHROW(Mcp::check_height_range_layer_height(fine, range, bounds)); + // A call that gives no layer height checks none: the range editor checks only what is typed. + asked = -1; + DynamicPrintConfig infill; + infill.set_key_value("sparse_infill_density", new ConfigOptionPercent(40)); + CHECK_NOTHROW(Mcp::check_height_range_layer_height(infill, new_range_config(0.4), bounds)); + CHECK(asked == -1); } TEST_CASE("range settings take the keys the range settings page offers", "[Mcp][Scene][Layers]") @@ -924,23 +1482,11 @@ TEST_CASE("range settings take the keys the range settings page offers", "[Mcp][ CHECK_FALSE(has(two, key)); // With one filament the object list offers no per-feature filament. CHECK_FALSE(has(Mcp::layer_range_option_keys(1), "sparse_infill_filament_id")); - - try { - parse_ranges(json::array({range(0, 5, {{"enable_support", true}})})); - FAIL("an object setting was accepted for a range"); - } catch (const ToolFailure& e) { - CHECK_THAT(e.what(), ContainsSubstring("not a height range setting")); - } - try { - parse_ranges(json::array({range(0, 5, {{"sparse_infill_dens", "20%"}})})); - FAIL("an unknown key was accepted"); - } catch (const ToolFailure& e) { - REQUIRE(e.details.contains("similar")); - CHECK(std::find(e.details["similar"].begin(), e.details["similar"].end(), json("sparse_infill_density")) != e.details["similar"].end()); - } + // What a height range takes as a target is these. + CHECK(Mcp::target_options("height_range", 2) == two); } -TEST_CASE("list_objects reports an object's height ranges", "[Mcp][Scene][Layers]") +TEST_CASE("object_list reports an object's height ranges", "[Mcp][Scene][Layers]") { Model model; ModelObject* object = model.add_object(); @@ -948,7 +1494,10 @@ TEST_CASE("list_objects reports an object's height ranges", "[Mcp][Scene][Layers object->add_instance(); CHECK_FALSE(Mcp::object_info(*object, 0).contains("layer_config_ranges")); - object->layer_config_ranges = parse_ranges(json::array({range(15, 30, {{"sparse_infill_density", "40%"}}), range(0, 15, {{"layer_height", 0.12}})})); + DynamicPrintConfig open = new_range_config(); + open.set_key_value("sparse_infill_density", new ConfigOptionPercent(40)); + object->layer_config_ranges[{15., 30.}].assign_config(std::move(open)); + object->layer_config_ranges[{0., 15.}].assign_config(new_range_config(0.12)); const json info = Mcp::object_info(*object, 0); REQUIRE(info["layer_config_ranges"].size() == 2); const json& low = info["layer_config_ranges"][0]; @@ -959,8 +1508,11 @@ TEST_CASE("list_objects reports an object's height ranges", "[Mcp][Scene][Layers // Ranges are not the object's own overrides. CHECK(info["overrides"].empty()); - // What list_objects shows can be given back unchanged. - const t_layer_config_ranges again = parse_ranges(info["layer_config_ranges"]); + // Its ranges given back, each its min_z and max_z, keep every range with its settings. + json bounds = json::array(); + for (const json& listed : info["layer_config_ranges"]) + bounds.push_back(range(listed["min_z"].get(), listed["max_z"].get())); + const t_layer_config_ranges again = parse_ranges(bounds, object->layer_config_ranges); REQUIRE(again.size() == object->layer_config_ranges.size()); for (auto a = again.cbegin(), b = object->layer_config_ranges.cbegin(); a != again.cend(); ++a, ++b) { CHECK(a->first == b->first); @@ -968,7 +1520,7 @@ TEST_CASE("list_objects reports an object's height ranges", "[Mcp][Scene][Layers } } -TEST_CASE("list_objects reports a variable layer height profile as the object list does", "[Mcp][Scene][Layers]") +TEST_CASE("object_list reports a variable layer height profile as the object list does", "[Mcp][Scene][Layers]") { // [z0, h0, z1, h1, ...]: the object list marks no flat bottom-to-top pair as variable. Heights are // rounded to 0.001 mm. @@ -1000,7 +1552,9 @@ TEST_CASE("list_objects reports a variable layer height profile as the object li // What Smooth stores on an object without a profile: the profile its height ranges give, smoothed, // so the ranges' heights bound it. object->layer_height_profile.clear(); - object->layer_config_ranges = parse_ranges(json::array({range(0, 10, {{"layer_height", 0.1}}), range(10, 20, {{"layer_height", 0.25}})})); + object->layer_config_ranges.clear(); + object->layer_config_ranges[{0., 10.}].assign_config(new_range_config(0.1)); + object->layer_config_ranges[{10., 20.}].assign_config(new_range_config(0.25)); std::vector from_ranges; PrintObject::update_layer_height_profile(*object, params, from_ranges); object->layer_height_profile.set(smooth_height_profile(from_ranges, params, HeightProfileSmoothingParams())); @@ -1012,7 +1566,7 @@ TEST_CASE("list_objects reports a variable layer height profile as the object li within(profile); } -TEST_CASE("layer code types have the names list_plates reads", "[Mcp][Scene][Layers]") +TEST_CASE("layer code types have the names plate_list reads", "[Mcp][Scene][Layers]") { for (const auto& [name, type] : std::vector>{{"pause", CustomGCode::PausePrint}, {"custom", CustomGCode::Custom}, diff --git a/tests/slic3rutils/test_mcp_tools.cpp b/tests/slic3rutils/test_mcp_tools.cpp index f4f7d9fc00..1e0819e46c 100644 --- a/tests/slic3rutils/test_mcp_tools.cpp +++ b/tests/slic3rutils/test_mcp_tools.cpp @@ -17,6 +17,7 @@ #include #include "python_test_support.hpp" +#include "retired_names.hpp" #include "slic3r/GUI/ActionRegistry.hpp" #include "slic3r/GUI/CommandCatalog.hpp" @@ -26,6 +27,7 @@ #include "slic3r/GUI/Mcp/McpTools.hpp" #include "slic3r/GUI/Mcp/McpJournal.hpp" #include "slic3r/GUI/Mcp/WindowControl.hpp" +#include "slic3r/GUI/Operations/Outcome.hpp" #include "slic3r/GUI/Camera.hpp" #include "libslic3r/BoundingBox.hpp" @@ -39,10 +41,14 @@ #include #include +#include +#include #include #include +#include #include #include +#include #include #include #include @@ -129,9 +135,9 @@ TEST_CASE("a search matches query words at the start of a text's words, CamelCas CHECK(match_score(query_words("retract"), "retraction_length", "") == std::pair{1, 1}); } -TEST_CASE("an action search ranks by the query's words and puts the plainer command first", "[Mcp]") +TEST_CASE("an action search ranks by the query's words and puts the plainer tile first", "[Mcp]") { - // Four of the Speed Dial's commands as it lists them. + // Four of the Speed Dial's tiles as it lists them. const json listed = json::array({ {{"id", "orca_command:obj_delete_all:orca"}, {"title", "Delete All Objects"}, {"group", "Object"}, {"description", "Delete all objects."}}, @@ -149,7 +155,7 @@ TEST_CASE("an action search ranks by the query's words and puts the plainer comm }; // No entry holds "delete object" as one text. Two are the Object group's deletes, which the palette - // names by group and title, and the shorter name, the plainer command, leads; the third only + // names by group and title, and the shorter name, the plainer tile, leads; the third only // mentions objects. CHECK(ids(rank_actions(listed, query_words("delete object"))) == std::vector{"orca_command:obj_delete:orca", "orca_command:obj_delete_all:orca", "orca_command:filament_delete:orca"}); @@ -162,7 +168,7 @@ TEST_CASE("an action search ranks by the query's words and puts the plainer comm CHECK(rank_actions(listed, query_words("top")) == json::array({listed[2]})); } -TEST_CASE("run_action refuses arguments for an action that takes none", "[Mcp][SpeedDial]") +TEST_CASE("action_run refuses arguments for an action that takes none", "[Mcp][SpeedDial]") { // A plate's, a setting's, a recent project's and a plugin's action run what they are, whatever args says. for (const char* prefix : {"orca_plate_goto", "orca_setting", "orca_recent_project", "plugin_script_action", "plugin_page_action"}) { @@ -171,18 +177,297 @@ TEST_CASE("run_action refuses arguments for an action that takes none", "[Mcp][S CHECK_THAT(action_args_error(action, {{"plate", 2}}), Catch::Matchers::ContainsSubstring("takes no arguments")); CHECK(action_args_error(action, json::object()).empty()); } - // A command's tile takes its command's arguments, which the command checks against its schema. - IdleAction tile("orca_command", "plate_goto"); - tile.command = "plate_goto"; - CHECK(action_args_error(tile, {{"plate", 2}}).empty()); + // A command's own tile outside the Design tab takes none, as an item with no arguments does: the refusal names the + // command that takes them. + const NativeCommand* filament_delete = NativeCommands::find("filament_delete"); + REQUIRE(filament_delete != nullptr); + const std::unique_ptr own = NativeCommands::make_action(*filament_delete); + CHECK(own->input_schema.at("properties").empty()); + CHECK(action_args_error(*own, json::object()).empty()); + const std::string refused = action_args_error(*own, {{"filament_slot", 2}}); + CHECK_THAT(refused, Catch::Matchers::ContainsSubstring("filament_delete")); + // A row's tile takes no arguments, or exactly its own; a row's former arguments are refused, naming the command. + const auto [export_command, export_gcode] = find_tile(NativeCommands::instance(), "export_gcode"); + REQUIRE(export_gcode != nullptr); + const std::unique_ptr gcode = NativeCommands::make_action(*export_command, *export_gcode); + CHECK(action_args_error(*gcode, json::object()).empty()); + CHECK(action_args_error(*gcode, {{"format", "gcode"}}).empty()); + const std::string with_path = action_args_error(*gcode, {{"path", "x.gcode"}}); + CHECK_FALSE(with_path.empty()); + CHECK_THAT(with_path, Catch::Matchers::ContainsSubstring("call project_export")); +#ifdef SLIC3R_CAD + // A Design command's own tile takes the command's arguments, which the command checks. + CommandCatalog design; + NativeCommands::register_all_commands(design, {true}); + design.seal(); + const NativeCommand* shell = design.find("shell"); + REQUIRE(shell != nullptr); + REQUIRE(shell->in_palette); + const std::unique_ptr design_tile = NativeCommands::make_action(*shell); + CHECK(design_tile->input_schema == shell->input_schema); + CHECK(action_args_error(*design_tile, {{"thickness", 2}}).empty()); +#endif } -TEST_CASE("run_action says where an action it cannot find is", "[Mcp][SpeedDial]") +TEST_CASE("what action_run journals for a tile of fixed arguments is a call it takes", "[Mcp][SpeedDial]") { - CHECK_THAT(unknown_action("obj_arange", NativeCommands::instance()), Catch::Matchers::ContainsSubstring("search_actions")); + // Every command's tile: its journal step's arguments are the tile's own, or the value a tile with an input + // collects, and action_run takes them, so a replay of the step is never refused. + const auto check_tiles = [](const CommandCatalog& catalog) { + int tiles = 0; + for (const NativeCommand& command : catalog.commands()) { + std::vector> actions; + if (command.in_palette) + actions.push_back(NativeCommands::make_action(command)); + if (command.tiles.is_array()) + for (const json& tile : command.tiles) + actions.push_back(NativeCommands::make_action(command, tile)); + for (const std::unique_ptr& action : actions) { + INFO(action->id()); + const json given = action->input.empty() ? json::object() : json{{action->input, 1}}; + const json recorded = tile_journal_args(*action, given); + if (action->preset.is_null()) { + // A Design command's own tile takes its command's arguments: the command's rewrite stands. + CHECK(recorded.is_null()); + continue; + } + ++tiles; + CHECK(recorded == (action->input.empty() ? action->preset : given)); + CHECK(action_args_error(*action, recorded).empty()); + } + } + return tiles; + }; + // The 129 Speed Dial entries outside the Design tab are commands' tiles: eight own and 121 items. + CHECK(check_tiles(NativeCommands::instance()) == 129); + + const auto recorded_for = [](const CommandCatalog& catalog, const char* key, const json& given) { + const auto [command, tile] = find_tile(catalog, key); + REQUIRE(command != nullptr); + return tile_journal_args(*(tile != nullptr ? NativeCommands::make_action(*command, *tile) : NativeCommands::make_action(*command)), given); + }; + CHECK(recorded_for(NativeCommands::instance(), "obj_arrange", json::object()) == json::object()); + CHECK(recorded_for(NativeCommands::instance(), "go_to_layer", {{"percent", 50}}) == json{{"percent", 50}}); +#ifdef SLIC3R_CAD + CommandCatalog design; + NativeCommands::register_all_commands(design, {true}); + design.seal(); + CHECK(check_tiles(design) > 129); + CHECK(recorded_for(design, "sk_array_polar", json::object()) == json{{"type", "circular"}}); +#endif +} + +TEST_CASE("a call with a tile's arguments asks, and one more argument runs", "[Mcp]") +{ + // The commands whose tiles ask, as the design's table "When a call does what a row does" lists them: called with + // exactly a tile's arguments a command is its person's form, and with silent beside them its silent form. + const CommandCatalog& catalog = NativeCommands::instance(); + for (const char* key : {"project_open", "project_import", "project_save", "project_export", "object_add_primitive", "object_rename", + "plate_rename", "object_set_instances", "calibration_generate_test", "preset_import", "preset_export", + "plugin_install_local", "project_new", "recording_start", "recording_stop"}) { + const NativeCommand* command = catalog.find(key); + REQUIRE(command != nullptr); + const std::vector forms = person_forms(*command); + REQUIRE_FALSE(forms.empty()); + for (const json& form : forms) { + INFO(key << " " << form.dump()); + CHECK(person_form(*command, form)); + json silent = form; + silent["silent"] = true; + CHECK_FALSE(person_form(*command, silent)); + } + } + // The tiles each is called with, by the table: their arguments are a person's form. + for (const auto& [key, args] : std::vector>{ + {"project_import", {{"archive", true}}}, + {"project_save", {{"save_as", true}}}, + {"project_export", {{"format", "sliced_3mf"}, {"plates", "all"}}}, + {"project_export", {{"format", "stl"}, {"per_object", true}}}, + {"object_add_primitive", {{"shape", "torus"}}}, + {"calibration_generate_test", {{"test", "vfa"}}}}) { + INFO(key << " " << args.dump()); + CHECK(person_form(*catalog.find(key), args)); + } + // Where the table's silent form is silent: true, the schema takes it beside the tile's arguments, and the call is + // valid: the default size of a primitive, a test with its dialog's defaults. + for (const auto& [key, args] : std::vector>{{"object_add_primitive", {{"shape", "cube"}}}, + {"calibration_generate_test", {{"test", "temperature"}}}}) { + INFO(key); + const NativeCommand* command = catalog.find(key); + REQUIRE(command != nullptr); + CHECK(command->input_schema.at("properties").contains("silent")); + json silent = args; + silent["silent"] = true; + CHECK(argument_error(*command, silent).empty()); + // Neither form needs more than the variant; with nothing at all the silent form is refused for it. + json tile = args; + CHECK(argument_error(*command, tile).empty()); + json none = json::object(); + CHECK_FALSE(argument_error(*command, none).empty()); + } + // silent says what a person's form of the command is: a call with no arguments where that is the only one, else a + // call with a tile's arguments. + const auto silent_text = [&catalog](const char* key) { + return catalog.find(key)->input_schema.at("properties").at("silent").at("description").get(); + }; + CHECK_THAT(silent_text("project_new"), Catch::Matchers::ContainsSubstring("no arguments")); + CHECK_THAT(silent_text("project_export"), !Catch::Matchers::ContainsSubstring("no arguments")); + CHECK_THAT(silent_text("project_export"), Catch::Matchers::ContainsSubstring("tile")); + CHECK_THAT(silent_text("calibration_generate_test"), Catch::Matchers::ContainsSubstring("tile")); +} + +TEST_CASE("a tile that collects a value takes exactly that argument", "[Mcp][SpeedDial]") +{ + json given; // what the command's function was last called with + NativeCommand view = NativeCommands::ui_command( + "view_it", "View it", "View", + object_schema({{"tab", prop("string", "A tab.")}, + {"camera", prop("string", "A camera.")}, + {"layer_percent", {{"type", "number"}, {"minimum", 0}, {"maximum", 100}}}}), + [&given](const json& args) { + given = args; + return Slic3r::GUI::AppActionRunResult{Slic3r::GUI::AppActionRunResult::Level::Succeeded}; + }); + view.tiles = json::array({NativeCommands::tile("view_it_tab", "Go to tab", "Commands", "", json::object(), "Goes to a tab.", "tab"), + NativeCommands::tile("view_it_layer", "Go to layer", "Commands", "", json::object(), "Goes to a layer.", + "percent", "layer_percent"), + NativeCommands::tile("view_it_x", "Along X", "View", "", {{"axis", "x"}}, "Along X.")}); + + // Go to tab's value is the command's argument of the same name. + const std::unique_ptr tab = NativeCommands::make_action(view, view.tiles[0]); + CHECK(tab->input == "tab"); + CHECK(tab->group_en == "Commands"); + REQUIRE(tab->input_schema["properties"].size() == 1); + CHECK(tab->input_schema["properties"]["tab"]["type"] == "string"); + CHECK(tab->input_schema["required"] == json::array({"tab"})); + CHECK_FALSE(action_args_error(*tab, json::object()).empty()); + CHECK_FALSE(action_args_error(*tab, {{"tab", "preview"}, {"camera", "top"}}).empty()); + CHECK(action_args_error(*tab, {{"tab", "preview"}}).empty()); + tab->run({{"tab", "preview"}}); + CHECK(given == json{{"tab", "preview"}}); + + // Go to layer's value goes to the command's argument the tile names. + const std::unique_ptr layer = NativeCommands::make_action(view, view.tiles[1]); + CHECK(layer->input == "percent"); + REQUIRE(layer->input_schema["properties"].size() == 1); + CHECK(layer->input_schema["properties"]["percent"]["type"] == "number"); + CHECK(layer->input_schema["required"] == json::array({"percent"})); + layer->run({{"percent", 50}}); + CHECK(given == json{{"layer_percent", 50}}); + CHECK(tile_call_args(&view.tiles[1], {{"percent", 50}}) == json{{"layer_percent", 50}}); + + // An item made without a group has none, and is in its command's section. + const json grouped_with_command = NativeCommands::tile("view_it_y", "Along Y", "", "", {{"axis", "y"}}, "Along Y."); + CHECK_FALSE(grouped_with_command.contains("group")); + CHECK(NativeCommands::make_action(view, grouped_with_command)->group_en == "View"); + + // A tile that collects nothing runs its command with its own arguments, and a command's own tile with the call's. + CHECK(tile_call_args(&view.tiles[2], json::object()) == json{{"axis", "x"}}); + CHECK(tile_call_args(nullptr, {{"plate", 2}}) == json{{"plate", 2}}); + CHECK(tile_call_args(nullptr, json::object()) == json::object()); +} + +TEST_CASE("Go to tab takes the Device tab as device and any other page by its id", "[Mcp][SpeedDial]") +{ + // The main window's pages as the Speed Dial's tab picker lists them, a plugin's among them. + const std::vector pages{"home", "design", "prepare", "preview", "monitor", "monitor_web", "multi_device", "project", + "calibration", "a_plugin_page"}; + CHECK(view_tab_page("device", pages) == std::optional("monitor")); + CHECK(view_tab_page("preview", pages) == std::optional("preview")); + // The Device tab's page is reached by its word alone. + CHECK_FALSE(view_tab_page("monitor", pages).has_value()); + // A page no word names, by its id. + CHECK(view_tab_page("monitor_web", pages) == std::optional("monitor_web")); + CHECK(view_tab_page("a_plugin_page", pages) == std::optional("a_plugin_page")); + // An id no page has, and a word whose page the window does not show. + CHECK_FALSE(view_tab_page("no_such_page", pages).has_value()); + CHECK_FALSE(view_tab_page("device", {"home", "prepare"}).has_value()); + + // The tab picker sends the page's id, which the tile gives view_set as the page's word. + const auto [command, tile] = find_tile(NativeCommands::instance(), "go_to_tab"); + REQUIRE(command != nullptr); + REQUIRE(tile != nullptr); + CHECK(command->key == "view_set"); + CHECK(tile_call_args(tile, {{"tab", "monitor"}}) == json{{"tab", "device"}}); + CHECK(tile_call_args(tile, {{"tab", "preview"}}) == json{{"tab", "preview"}}); + CHECK(tile_call_args(tile, {{"tab", "a_plugin_page"}}) == json{{"tab", "a_plugin_page"}}); + // view_set takes a plugin's page by its id. + json plugin{{"tab", "a_plugin_page"}}; + CHECK(argument_error(*command, plugin).empty()); +} + +TEST_CASE("preset_export takes the folder of its dialog and has no silent form", "[Mcp]") +{ + const NativeCommand* export_ = NativeCommands::find("preset_export"); + REQUIRE(export_ != nullptr); + CHECK(export_->input_schema.at("properties").size() == 1); + json folder{{"path", "out"}}; + CHECK(argument_error(*export_, folder).empty()); + json silent{{"silent", true}}; + CHECK_THAT(argument_error(*export_, silent), Catch::Matchers::ContainsSubstring("silent")); +} + +TEST_CASE("the filament commands take the filaments they mix, and the slot a deleted one merges into", "[Mcp]") +{ + using Catch::Matchers::ContainsSubstring; + const NativeCommand* mixed = NativeCommands::find("filament_add_mixed"); + REQUIRE(mixed != nullptr); + CHECK(mixed->listed); + CHECK_FALSE(mixed->in_palette); + CHECK(mixed->tiles.is_null()); + CHECK(mixed->input_schema["required"] == json::array({"components", "ratios"})); + json half{{"components", json::array({1, 2})}, {"ratios", json::array({50, 50})}}; + CHECK(argument_error(*mixed, half).empty()); + json thirds{{"components", json::array({1, 2, 3})}, {"ratios", json::array({33, 33, 34})}}; + CHECK(argument_error(*mixed, thirds).empty()); + // Slots are numbered from 1, and a ratio is a whole percentage above 0, as the Add Mixed Filament dialog sets it. + json fraction{{"components", json::array({1, 2})}, {"ratios", json::array({12.5, 87.5})}}; + CHECK_THAT(argument_error(*mixed, fraction), ContainsSubstring("ratios")); + json slot_zero{{"components", json::array({0, 2})}, {"ratios", json::array({50, 50})}}; + CHECK_THAT(argument_error(*mixed, slot_zero), ContainsSubstring("components")); + json no_share{{"components", json::array({1, 2})}, {"ratios", json::array({0, 100})}}; + CHECK_THAT(argument_error(*mixed, no_share), ContainsSubstring("ratios")); + json no_ratios{{"components", json::array({1, 2})}}; + CHECK_THAT(argument_error(*mixed, no_ratios), ContainsSubstring("ratios")); + + // Delete Filament Slot keeps its tile of its own, which deletes the last physical slot, and takes the slot to merge into. + const NativeCommand* remove = NativeCommands::find("filament_delete"); + REQUIRE(remove != nullptr); + CHECK(remove->in_palette); + CHECK_FALSE(remove->input_schema.contains("required")); + json merge{{"filament_slot", 2}, {"merge_into", 1}}; + CHECK(argument_error(*remove, merge).empty()); + json merge_zero{{"filament_slot", 2}, {"merge_into", 0}}; + CHECK_THAT(argument_error(*remove, merge_zero), ContainsSubstring("merge_into")); +} + +TEST_CASE("project_export writes six formats, and project_import takes the entries of a ZIP archive", "[Mcp]") +{ + const NativeCommand* export_ = NativeCommands::find("project_export"); + REQUIRE(export_ != nullptr); + std::set formats; + for (const json& format : export_->input_schema.at("properties").at("format").at("enum")) + formats.insert(format.get()); + CHECK(formats == std::set{"gcode", "sliced_3mf", "3mf", "stl", "drc", "toolpaths_obj"}); + // Some objects, by index or by id, as the object commands name them. + json some{{"format", "stl"}, {"path", "/out/two.stl"}, {"objects", json::array({0, 2})}}; + CHECK(argument_error(*export_, some).empty()); + json drc{{"format", "drc"}, {"path", "/out/parts"}, {"per_object", true}, {"objects", json::array({1})}}; + CHECK(argument_error(*export_, drc).empty()); + + const NativeCommand* import_ = NativeCommands::find("project_import"); + REQUIRE(import_ != nullptr); + json zip{{"paths", json::array({"/models/parts.zip"})}, {"entries", json::array({"cube.stl", "parts/cylinder.obj"})}}; + CHECK(argument_error(*import_, zip).empty()); + CHECK(import_->input_schema.at("properties").at("entries").at("items") == json{{"type", "string"}}); +} + +TEST_CASE("action_run says where an action it cannot find is", "[Mcp][SpeedDial]") +{ + CHECK_THAT(unknown_action("obj_arange", NativeCommands::instance()), Catch::Matchers::ContainsSubstring("action_search")); #ifdef SLIC3R_CAD // A Design tab tile, by its id or its key, while it is not shown: in a run with the CAD feature on at startup - // call_tool runs its command from any tab, and in one with it off there is no such command. + // tool_call runs its command from any tab, and in one with it off there is no such command. for (const bool cad : {true, false}) { CommandCatalog catalog; NativeCommands::register_all_commands(catalog, {cad}); @@ -192,7 +477,7 @@ TEST_CASE("run_action says where an action it cannot find is", "[Mcp][SpeedDial] const std::string why = unknown_action(id, catalog); if (cad) { CHECK_THAT(why, Catch::Matchers::ContainsSubstring("while the Design tab is shown")); - CHECK_THAT(why, Catch::Matchers::ContainsSubstring("call_tool {\"tool\": \"shell\"}")); + CHECK_THAT(why, Catch::Matchers::ContainsSubstring("tool_call {\"tool\": \"shell\"}")); } else { CHECK(why == id + " is a Design tab tile, and the CAD feature was off when OrcaSlicer started: a person " "turns it on in Preferences > Features and restarts OrcaSlicer, or starts it with " @@ -205,13 +490,13 @@ TEST_CASE("run_action says where an action it cannot find is", "[Mcp][SpeedDial] INFO(folded << (cad ? ", the CAD feature on" : ", the CAD feature off")); if (cad) CHECK_THAT(unknown_action(folded, catalog), - Catch::Matchers::ContainsSubstring("call_tool {\"tool\": \"sketch_pattern\", \"args\": {\"type\": \"linear\"}}")); + Catch::Matchers::ContainsSubstring("tool_call {\"tool\": \"sketch_pattern\", \"args\": {\"type\": \"linear\"}}")); else CHECK(unknown_action(folded, catalog) == folded + " is a Design tab tile, and the CAD feature was off when OrcaSlicer " "started: a person turns it on in Preferences > Features and restarts " "OrcaSlicer, or starts it with --cad"); // A Design command without a tile is any unknown action. - CHECK_THAT(unknown_action("orca_command:describe_design:orca", catalog), Catch::Matchers::ContainsSubstring("search_actions")); + CHECK_THAT(unknown_action("orca_command:describe_design:orca", catalog), Catch::Matchers::ContainsSubstring("action_search")); } #endif } @@ -230,7 +515,167 @@ TEST_CASE("a listing summary is a documentation's first sentence on one line", " CHECK(first_sentence("") == ""); } -TEST_CASE("search_python_api's reference covers the orca package with constructors and named instances", "[Mcp][Python]") +TEST_CASE("a tool of the old vocabulary is no command", "[Mcp]") +{ + const CommandCatalog& catalog = NativeCommands::instance(); + REQUIRE(kRetiredTools.size() == 45); + for (const std::string& retired : kRetiredTools) { + INFO(retired); + CHECK(catalog.find(retired) == nullptr); + } + + // Each of the 42 under its name, listed, the first sentence of its description pinned (the commands that sentence + // names under their names too). + struct Renamed + { + const char* retired; + const char* name; + const char* first_sentence; + }; + static const Renamed renamed[] = { + {"search_tools", "tool_search", "Find what does something, in one search, or look up one command."}, + {"call_tool", "tool_call", "Call any command by name with its arguments: a tool, or one the tool list does not show, a menu row " + "that takes no arguments, a Design tab command or an operation a plugin offers (see tool_search)."}, + {"generate_calibration_test", "calibration_generate_test", + "Generate a Calibration menu test as its dialog's OK does: a new project named after the test with the test model, and the " + "process, filament and printer presets changed as the test needs (presets_changed)."}, + {"export", "project_export", "Write the project to a file without a dialog."}, + {"list_presets", "preset_list", + "Printer, process or filament presets, each with its name, alias (the name its selector shows, when another), system, user, " + "project (kept inside the project), inherits, selected (and modified), compatible: false or installed: false when so, and " + "vendor; a filament its filament_type and the slots using it (filament_slots), a printer its printer_model and nozzle."}, + {"select_preset", "preset_select", "Select a printer, process or filament preset by the name its selector shows (or its " + "internal name), as a person would."}, + {"save_preset", "preset_save", "Save the printer, process or filament preset being edited, with its unsaved changes, as a preset " + "called name, which is then selected: what the tab's Save button does through its dialog."}, + {"delete_preset", "preset_delete", "Delete a user preset or one inside the project, its file and its cloud copy, as the tab's " + "Delete does, without asking."}, + {"list_plates", "plate_list", + "Plates with name, locked, current, objects (how many are on it; object_list lists them), and the settings they print with: " + "curr_bed_type, print_sequence, spiral_mode, first_layer_print_sequence and other_layers_print_sequence (null: Auto), with " + "several extruders filament_map_mode and filament_map; overrides lists those the plate sets itself (plate_set_settings)."}, + {"list_objects", "object_list", "The project as the Objects panel lists it."}, + {"transform", "object_transform", "Change one instance's placement, or one part's with part."}, + {"add_part", "part_add", "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..."}, + {"arrange", "object_arrange", "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."}, + {"slice", "plate_slice", "Slice the current plate, all plates, or one plate by index, the way the toolbar's Slice button does, " + "and wait for the result (or reply with a job id when it takes longer than the reply budget)."}, + {"set_height_ranges", "object_set_height_ranges", + "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 the target " + "height_range."}, + {"set_variable_layer_height", "object_set_variable_layer_height", + "Run the Variable layer height panel's Adaptive, Smooth or Reset on an object, without opening the panel: adaptive computes " + "layer heights from the object's shape (inside a height range, the range's layer_height), smooth smooths its profile (or " + "the one its height ranges give), reset goes back to its layer height and ranges."}, + {"set_custom_gcode_at_layer", "plate_set_custom_gcode", + "Add or remove pauses, custom G-code, custom templates and filament changes at the start of a layer, as the Preview layer " + "slider's menu does; they are saved per plate in the project."}, + {"get_slice_stats", "plate_slice_stats", "What the Preview shows for a sliced plate."}, + {"get_app_state", "app_state", "Snapshot of OrcaSlicer."}, + {"wait", "app_wait", "Block until a condition holds or timeout_s passes (max 50)."}, + {"get_log", "app_log", "The last lines of OrcaSlicer's current log file, optionally only those at or above a level."}, + {"cancel_job", "job_cancel", "Stop the running operation: a slice or G-code export, as the slicing progress's cancel button " + "does, or a background job an MCP call started (an arrange, orient or fill bed)."}, + {"run_replay", "replay_run", "Replay a list of tool calls in order and report each step: {orca_replay_version:\"0.2.0\", name, " + "vars, steps:[{tool, args, expect, optional, await, save_as, timeout_s}]}, JSON with comments."}, + {"export_replay", "replay_export", + "Turn the calls this session made into a replay that replay_run runs: mutating calls, app_wait, window_screenshot and the " + "recording tools, in order, with refs replaced by locators, job replies replayed with await:false, and window_screenshot " + "and recording paths moved under ${out_dir}."}, + {"run_script", "script_run", + "Run Python code inside OrcaSlicer as its main program (__name__ == \"__main__\") against orca.host, the whole plugin API " + "(script_search_api searches it): read objects, meshes and settings, compute, use orca.host.ui and the preset API, and call " + "these same tools, with their guards and undo, through orca.host.tools.call(name, args)."}, + {"search_python_api", "script_search_api", + "Search orca, the Python API of script_run scripts and plugins, in the running build: orca.host (the project's model and " + "meshes, presets and their editors, slicing data, orca.host.ui windows and dialogs, orca.host.tools calling these tools) and " + "the classes, events and pages plugins build on."}, + {"answer_dialog", "dialog_answer", "Press a button of the topmost modal dialog: yes, no, ok, cancel, close, apply, a button's " + "label, or a numeric id."}, + {"auto_answer_dialogs", "dialog_auto_answer", "Answer modal dialogs automatically when their title or message matches a rule's " + "regex (case-insensitive)."}, + {"select_objects", "object_select", "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."}, + {"screenshot", "window_screenshot", + "Capture what OrcaSlicer shows and return it as an image, downscaled to max_dim on the long edge (default 1280), plus the " + "full-size PNG written to save_path (or the session's output folder)."}, + {"set_view", "view_set", + "Set up what the window shows, for screenshots and GUI work: the main tab, the 3D view (canvas: Prepare's, the preview or the " + "assemble view, which has its own gizmos), the camera of the 3D view shown (a named direction, the default view, or fit to " + "bed / objects / selection, then look_at, the point it looks at, an orbit to look from between the named directions, and the " + "zoom), the preview's color scheme (picked as in the legend's combo, which shows every feature type again), legend rows, " + "time estimate and layers (1-based, or up to a height)."}, + {"encode_recording", "recording_encode", "Encode a recording into an H.265 (or H.264) MP4 with the system ffmpeg (ORCA_FFMPEG, " + "else ffmpeg on PATH; it needs libx265 or libx264), keeping its timing."}, + {"search_actions", "action_search", "Search everything the Speed Dial can run: built-in commands (slice, export, views, object " + "operations, plates, calibration wizards, help), recent projects, plugin scripts and pages."}, + {"run_action", "action_run", "Run one action by the id action_search returned (orca_command:view_front:orca, or the name " + "inside it, view_front), with args, the command's arguments, when it takes some (its " + "input_schema)."}, + {"list_windows", "window_list", + "List OrcaSlicer's open windows: the main window, then the windows that don't block the app (Plugins, an object's settings, " + "a dock panel floating on its own), then the modal dialogs in the order they opened, the topmost last."}, + {"set_window", "window_set", "Size, move, maximize, minimize or raise a window: the main window (default), the topmost modal " + "dialog, or one window_list lists, also while a modal dialog is open."}, + {"list_widgets", "widget_list", + "Describe what is on screen as an indented tree, one element per line with a ref to pass to widget_click, widget_set_value, " + "keyboard_press and webview_run_javascript (a page element's to mouse_gesture too): the widgets of every shown window, the " + "rows of lists, trees and tables, each shown popup after the window it opened from, the main menus, the 3D canvas's " + "toolbar items and gizmos, each ImGui panel drawn in the last frame with its items and text, and the elements of each shown " + "web page (dialogs, the setup wizard, sign-in, plugin windows) under its web view."}, + {"click", "widget_click", "Click a GUI element as a person would."}, + {"set_widget_value", "widget_set_value", "Set a widget's value and send the events a person's edit would."}, + {"press_keys", "keyboard_press", + "Send a key chord (\"Ctrl+S\", \"Escape\", \"Return\", \"Delete\", \"Shift+Tab\", \"Left\", \"F5\") and/or type text to a " + "target or, without one, to the focused window (the topmost dialog while one is open, the shown 3D view when nothing has " + "focus)."}, + {"pick_gizmo_file", "gizmo_pick_file", + "Do what a file picker inside the open gizmo does, with a path instead of its dialog: svg_change loads another SVG file into " + "the SVG part being edited, svg_save_as writes that part's SVG to a new file (an existing one only with overwrite), " + "texture_import imports a height-map image into the texture library and puts it on Texture Displacement's active layer."}, + {"run_javascript", "webview_run_javascript", "Evaluate JavaScript in one of OrcaSlicer's web views (Home, the device page, " + "dialogs, plugin windows)."}, + }; + REQUIRE(std::size(renamed) == 42); + for (const Renamed& r : renamed) { + INFO(r.retired << " is " << r.name); + CHECK(std::find(kRetiredTools.begin(), kRetiredTools.end(), r.retired) != kRetiredTools.end()); + const NativeCommand* command = catalog.find(r.name); + REQUIRE(command != nullptr); + CHECK(command->listed); + CHECK(first_sentence(command->description) == r.first_sentence); + } + + // Outside the Design group 115 commands are listed: every one that runs from its arguments, all but the three menu + // rows that take none (Task 3's 98, the seven Parts 4a to 4c add, Part 5a's three, Part 5b's two, Part 5c's one and + // Part 5d's four). + std::size_t listed = 0; + for (const NativeCommand& c : catalog.commands()) + if (c.listed && c.group != Slic3r::GUI::kDesignGroup) + ++listed; + CHECK(listed == 115); +} + +TEST_CASE("opening a project and importing models are two commands", "[Mcp]") +{ + const NativeCommand* open = NativeCommands::find("project_open"); + const NativeCommand* import_ = NativeCommands::find("project_import"); + REQUIRE(open != nullptr); + REQUIRE(import_ != nullptr); + CHECK(open->listed); + CHECK(import_->listed); + json as_project{{"path", "a.3mf"}, {"as", "project"}}; + CHECK_THAT(argument_error(*open, as_project), Catch::Matchers::ContainsSubstring("unknown argument as")); + json models{{"paths", {"a.stl"}}}; + CHECK(argument_error(*import_, models).empty()); + CHECK_FALSE(open->input_schema["properties"].contains("paths")); + CHECK_FALSE(import_->input_schema["properties"].contains("as")); +} + +TEST_CASE("script_search_api's reference covers the orca package with constructors and named instances", "[Mcp][Python]") { (void) import_orca_module(); const json reference = python_api_reference(); @@ -282,30 +727,6 @@ TEST_CASE("search_python_api's reference covers the orca package with constructo CHECK(rank_python_api(reference, "mesh normals")[0]["name"] == "orca.host.TriangleMesh.face_normals"); } -TEST_CASE("a typed tool's group is core, api or ui, and a merged command's is Commands", "[Mcp]") -{ - const std::set core{"get_app_state", "wait", "cancel_job", "get_log", "run_replay", "export_replay", - "answer_dialog", "auto_answer_dialogs", "run_script", "search_python_api"}; - const std::set ui{"list_windows", "set_window", "list_widgets", "click", "set_widget_value", "press_keys", - "mouse_gesture", "pick_gizmo_file", "run_javascript", "set_view", "screenshot", - "encode_recording", "search_actions", "run_action", "select_objects"}; - const std::set merged{"new_project", "save_project", "start_recording", "stop_recording"}; - REQUIRE(core.size() == 10); - REQUIRE(ui.size() == 15); - - std::map> by_group; - for (const NativeCommand& def : Slic3r::GUI::NativeCommands::instance().commands()) - if (def.listed) - by_group[def.group].insert(def.key); - CHECK(by_group.size() == 4); - CHECK(by_group["core"] == core); - CHECK(by_group["ui"] == ui); - CHECK(by_group["Commands"] == merged); - // The rest act on project data by index and name. - for (const char* name : {"set_settings", "slice", "generate_calibration_test", "get_slice_stats", "search_tools", "call_tool"}) - CHECK(by_group["api"].count(name) == 1); -} - TEST_CASE("no description starts with a bracketed tag", "[Mcp]") { const std::regex tag(R"(^\[[a-z]+\] )"); @@ -318,15 +739,15 @@ TEST_CASE("no description starts with a bracketed tag", "[Mcp]") // The catalog keeps a listed command's description as it is given. CommandCatalog registry; NativeCommand def; - def.key = "click"; + def.key = "widget_click"; def.description = "Click a widget."; def.listed = true; registry.add(def); - REQUIRE(registry.find("click") != nullptr); - CHECK(registry.find("click")->description == "Click a widget."); + REQUIRE(registry.find("widget_click") != nullptr); + CHECK(registry.find("widget_click")->description == "Click a widget."); } -TEST_CASE("search_tools reads one inventory", "[Mcp]") +TEST_CASE("tool_search reads one inventory", "[Mcp]") { const auto command = [](const char* key, const char* group, bool listed, const char* description) { NativeCommand c; @@ -338,11 +759,12 @@ TEST_CASE("search_tools reads one inventory", "[Mcp]") return c; }; CommandCatalog catalog; - catalog.add(command("measure_bed", "api", true, "Measure the bed. In mm.")); + catalog.add(command("measure_bed", "Plugins", true, "Measure the bed. In mm.")); NativeCommand tile = command("measure_tile", "View", false, "Measure what the view shows."); tile.in_palette = true; catalog.add(tile); - catalog.add_source(std::make_unique(command("plugin.fixture.measure", "api", false, "Offered by a plugin. Doubles a."))); + catalog.add_source( + std::make_unique(command("plugin.fixture.measure", "Plugins", false, "Offered by a plugin. Doubles a."))); catalog.seal(); const json found = search_commands(catalog, {{"query", "measure"}}); @@ -362,7 +784,7 @@ TEST_CASE("search_tools reads one inventory", "[Mcp]") } // An operation's first sentence only says a plugin offers it. CHECK(items["plugin.fixture.measure"]["description"] == "Offered by a plugin. Doubles a."); - CHECK(found["use"].get().find("call_tool {tool, args}") != std::string::npos); + CHECK(found["use"].get().find("tool_call {tool, args}") != std::string::npos); // {tool} describes any of them. const json described = search_commands(catalog, {{"tool", "measure_tile"}}); @@ -372,7 +794,7 @@ TEST_CASE("search_tools reads one inventory", "[Mcp]") // group narrows the names and the matches, in any case, a source's commands included. CHECK(search_commands(catalog, json::object())["names"] == json::array({"measure_bed", "measure_tile", "plugin.fixture.measure"})); - CHECK(search_commands(catalog, {{"group", "API"}})["names"] == json::array({"measure_bed", "plugin.fixture.measure"})); + CHECK(search_commands(catalog, {{"group", "PLUGINS"}})["names"] == json::array({"measure_bed", "plugin.fixture.measure"})); CHECK(search_commands(catalog, {{"group", "view"}})["names"] == json::array({"measure_tile"})); const json in_view = search_commands(catalog, {{"group", "View"}, {"query", "measure"}}); REQUIRE(in_view["items"].size() == 1); @@ -383,11 +805,84 @@ TEST_CASE("search_tools reads one inventory", "[Mcp]") FAIL("an unknown group was not refused"); } catch (const ToolFailure& f) { CHECK(std::string(f.what()).find("Unknown group: commands") != std::string::npos); - CHECK(f.details["groups"] == json::array({"api", "View"})); + CHECK(f.details["groups"] == json::array({"Plugins", "View"})); } } -TEST_CASE("search_tools finds a Design command by the name of a row folded into it", "[Mcp][CAD]") +TEST_CASE("tool_search's groups are the places' headings and Design", "[Mcp]") +{ + CommandCatalog catalog; + NativeCommands::register_all_commands(catalog, {true}); + catalog.seal(); + const auto names_of = [&catalog](const char* group) { + const json found = search_commands(catalog, {{"group", group}}); + std::vector names; + for (const json& name : found["names"]) + names.push_back(name.get()); + return names; + }; + + // A place's heading, in any case: its commands alone. + const std::vector objects = names_of("Objects"); + REQUIRE_FALSE(objects.empty()); + for (const std::string& name : objects) { + INFO(name); + CHECK(name.rfind("object_", 0) == 0); + } + CHECK(names_of("objects") == objects); + // Every Design tab command, as the group has been. + const std::vector design = names_of("Design"); + for (const NativeCommand& c : catalog.commands()) + if (c.group == Slic3r::GUI::kDesignGroup) { + INFO(c.key); + CHECK(std::count(design.begin(), design.end(), c.key) == 1); + } + CHECK(design.size() == 88); + // The groups of how a tool acts are no group. + for (const char* gone : {"api", "core", "ui", "Commands"}) { + INFO(gone); + try { + search_commands(catalog, {{"group", gone}}); + FAIL("an unknown group was not refused"); + } catch (const ToolFailure& f) { + CHECK_THAT(std::string(f.what()), Catch::Matchers::ContainsSubstring(std::string("Unknown group: ") + gone)); + } + } +} + +TEST_CASE("a guessed type is read as a command's one variant argument", "[Mcp]") +{ + const CommandCatalog& catalog = NativeCommands::instance(); + const NativeCommand* export_ = catalog.find("project_export"); + REQUIRE(export_ != nullptr); + json args{{"type", "stl"}, {"path", "a.stl"}}; + CHECK(argument_error(*export_, args).empty()); + CHECK(args == json{{"format", "stl"}, {"path", "a.stl"}}); + + const NativeCommand* primitive = catalog.find("object_add_primitive"); + REQUIRE(primitive != nullptr); + json shape{{"type", "cube"}, {"silent", true}}; + CHECK(argument_error(*primitive, shape).empty()); + CHECK(shape == json{{"shape", "cube"}, {"silent", true}}); + + // part_add has a type of its own beside its shape: type stays the part's type. + const NativeCommand* part = catalog.find("part_add"); + REQUIRE(part != nullptr); + json part_args{{"object", 0}, {"type", "modifier"}}; + CHECK(argument_error(*part, part_args).empty()); + CHECK(part_args == json{{"object", 0}, {"type", "modifier"}}); + + // A command with two such arguments leaves a guessed type to be refused: it could be either. + NativeCommand two; + two.key = "two_variants"; + two.input_schema = object_schema({{"format", enum_prop({"stl", "obj"}, "A format.")}, + {"shape", enum_prop({"cube", "stl"}, "A shape.")}}); + json either{{"type", "stl"}}; + CHECK_THAT(argument_error(two, either), Catch::Matchers::ContainsSubstring("type")); + CHECK(either == json{{"type", "stl"}}); +} + +TEST_CASE("tool_search finds a Design command by the name of a row folded into it", "[Mcp][CAD]") { CommandCatalog catalog; NativeCommands::register_all_commands(catalog, {true}); @@ -401,7 +896,7 @@ TEST_CASE("search_tools finds a Design command by the name of a row folded into } } -TEST_CASE("set_window refuses a request the window can't take, before changing anything", "[Mcp]") +TEST_CASE("window_set refuses a request the window can't take, before changing anything", "[Mcp]") { WindowAbilities main; main.main = true; WindowAbilities modal; modal.modal = true; modal.can_maximize = true; modal.can_minimize = true; @@ -426,7 +921,7 @@ TEST_CASE("set_window refuses a request the window can't take, before changing a CHECK(window_request_refusal({{"raise", true}}, fixed).empty()); } -TEST_CASE("set_window's reply lists the fields the window changed, with a note on why", "[Mcp]") +TEST_CASE("window_set's reply lists the fields the window changed, with a note on why", "[Mcp]") { const json sized{{"size", {800, 600}}}; WindowSettling taken; @@ -497,7 +992,7 @@ TEST_CASE("set_window's reply lists the fields the window changed, with a note o CHECK_FALSE(reply.contains("note")); } -TEST_CASE("set_window sizes a window by what it shows, held to its limits", "[Mcp]") +TEST_CASE("window_set sizes a window by what it shows, held to its limits", "[Mcp]") { bool limited = true; // No invisible margins and no limits: the size asked for. @@ -516,7 +1011,7 @@ TEST_CASE("set_window sizes a window by what it shows, held to its limits", "[Mc CHECK(limited); } -TEST_CASE("camera_state reads the camera set_view leaves", "[Mcp]") +TEST_CASE("camera_state reads the camera view_set leaves", "[Mcp]") { using Slic3r::Vec3d; using Slic3r::GUI::Camera; @@ -528,7 +1023,7 @@ TEST_CASE("camera_state reads the camera set_view leaves", "[Mcp]") camera.set_zoom(2.0); const json s = camera_state(camera, 1.5); CHECK(s["type"] == "ortho"); - // The point it looks at goes by the name set_view takes it under. + // The point it looks at goes by the name view_set takes it under. CHECK(s["look_at"] == json{10.0, 20.0, 0.0}); CHECK_FALSE(s.contains("target")); CHECK(s["zoom"] == 2.0); @@ -540,11 +1035,11 @@ TEST_CASE("camera_state reads the camera set_view leaves", "[Mcp]") CHECK(camera_state(camera, 1.0)["azimuth"] == -90); } -TEST_CASE("set_view takes the Design tab's camera, section view and switches", "[Mcp]") +TEST_CASE("view_set takes the Design tab's camera, section view and switches", "[Mcp]") { - const NativeCommand* set_view = NativeCommands::find("set_view"); - REQUIRE(set_view != nullptr); - const json& properties = set_view->input_schema.at("properties"); + const NativeCommand* view_set = NativeCommands::find("view_set"); + REQUIRE(view_set != nullptr); + const json& properties = view_set->input_schema.at("properties"); for (const char* name : {"section", "origin_planes", "world_axes", "origin", "bed"}) { INFO(name); CHECK(properties.contains(name)); @@ -553,12 +1048,12 @@ TEST_CASE("set_view takes the Design tab's camera, section view and switches", " CHECK(std::find(cameras.begin(), cameras.end(), json("sketch_normal")) != cameras.end()); json section{{"tab", "design"}, {"section", {{"on", true}, {"z", 2}, {"keep", "upper"}}}, {"origin", true}}; - CHECK(argument_error(*set_view, section).empty()); + CHECK(argument_error(*view_set, section).empty()); // The section view is read whole: a key it has no use for, and a half it does not keep, are refused. json unknown{{"tab", "design"}, {"section", {{"on", true}, {"height", 2}}}}; - CHECK_THAT(argument_error(*set_view, unknown), Catch::Matchers::ContainsSubstring("section.height")); + CHECK_THAT(argument_error(*view_set, unknown), Catch::Matchers::ContainsSubstring("section.height")); json left{{"tab", "design"}, {"section", {{"on", true}, {"keep", "left"}}}}; - CHECK_THAT(argument_error(*set_view, left), Catch::Matchers::ContainsSubstring("section.keep")); + CHECK_THAT(argument_error(*view_set, left), Catch::Matchers::ContainsSubstring("section.keep")); } TEST_CASE("a call naming an object's id is refused once its index names another object", "[Mcp]") @@ -587,44 +1082,151 @@ TEST_CASE("a call naming an object's id is refused once its index names another TEST_CASE("the journal records indices without expected ids, except a Python step's arguments", "[Mcp]") { const CommandCatalog& catalog = Slic3r::GUI::NativeCommands::instance(); - CHECK(without_expected_ids(catalog, "set_settings", json{{"object", 0}, {"object_id", 7}, {"part_id", 8}}) == json{{"object", 0}}); - CHECK(without_expected_ids(catalog, "set_height_ranges", json{{"object", 0}, {"object_id", 7}}) == json{{"object", 0}}); - CHECK(without_expected_ids(catalog, "set_variable_layer_height", json{{"object", 0}, {"object_id", 7}}) == json{{"object", 0}}); - const json replay{{"replay", {{"orca_replay_version", "0.1.0"}, - {"steps", {{{"tool", "transform"}, {"args", {{"object", 1}, {"object_id", 9}}}}, - {{"tool", "run_script"}, {"args", {{"code", "x"}, {"args", {{"object_id", 9}}}}}}}}}}}; - const json recorded = without_expected_ids(catalog, "run_replay", replay); + 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}}); + 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); CHECK(recorded["replay"]["steps"][0]["args"] == json{{"object", 1}}); CHECK(recorded["replay"]["steps"][1]["args"]["args"]["object_id"] == 9); - CHECK(without_expected_ids(catalog, "run_script", json{{"code", "x"}, {"args", {{"object_id", 3}}}})["args"]["object_id"] == 3); + CHECK(without_expected_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]") { const CommandCatalog& catalog = Slic3r::GUI::NativeCommands::instance(); const json as_text{{"replay", "// moves the lid\n" - R"({"orca_replay_version": "0.1.0", "steps": [{"tool": "transform", "args": {"object": 1, "object_id": 9}}]})"}}; - const json recorded = without_expected_ids(catalog, "run_replay", as_text); + 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); 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, "run_replay", json{{"replay", "{\"orca_replay_version\": \"0.1.0\","}}) == json{{"replay", "{\"orca_replay_version\": \"0.1.0\","}}); + CHECK(without_expected_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]") { const CommandCatalog& catalog = Slic3r::GUI::NativeCommands::instance(); - CHECK(without_expected_ids(catalog, "transform", json{{"object", 0}, {"object_id", 7}}) == json{{"object", 0}}); - // Inside the call_tool and run_replay wrappers too. - CHECK(without_expected_ids(catalog, "call_tool", json{{"tool", "transform"}, {"args", {{"object", 1}, {"object_id", 9}}}}) == - json{{"tool", "transform"}, {"args", {{"object", 1}}}}); - const json replay{{"replay", {{"orca_replay_version", "0.1.0"}, - {"steps", {{{"tool", "call_tool"}, {"args", {{"tool", "transform"}, {"args", {{"object", 1}, {"object_id", 9}}}}}}}}}}}; - CHECK(without_expected_ids(catalog, "run_replay", replay)["replay"]["steps"][0]["args"]["args"] == json{{"object", 1}}); + 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}}}}) == + 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}}); // 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, "call_tool", json{{"tool", "plugin.measure.area"}, {"args", {{"object_id", 4}}}})["args"]["object_id"] == 4); - CHECK(without_expected_ids(catalog, "select_objects", json{{"objects", {0, 1}}, {"object_ids", {5, 6}}}) == json{{"objects", {0, 1}}}); - CHECK(without_expected_ids(catalog, "select_objects", json{{"instances", {{0, 1}}}, {"instance_object_ids", {5}}}) == + 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}}}) == json{{"instances", {{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]") +{ + // As the log file sink writes them (utils.cpp): the level, a tab, the time and thread, then the message, whose own + // line breaks start lines with no level of their own. + const std::string text = "[info]\t2026-11-17 10:00:00.000001[Thread 0x1]:loaded \"[error] notes.3mf\"\n" + "[error]\t2026-11-17 10:00:01.000001[Thread 0x1]:Failed to load the project:\n" + " the file has no model\n" + "[debug]\t2026-11-17 10:00:02.000001[Thread 0x2]:frame [warning] skipped\n" + " with a second line\n" + "[warning]\t2026-11-17 10:00:03.000001[Thread 0x1]:slow\n" + "[fatal]\t2026-11-17 10:00:04.000001[Thread 0x1]:out of memory\n"; + const auto read = [&text](const std::string& level, std::size_t lines) { + std::istringstream in(text); + return log_tail(in, level, lines); + }; + // An info line whose message holds [error] is no error line; the error's second line comes with it. + CHECK(read("error", 200) == std::vector{"[error]\t2026-11-17 10:00:01.000001[Thread 0x1]:Failed to load the project:", + " the file has no model", + "[fatal]\t2026-11-17 10:00:04.000001[Thread 0x1]:out of memory"}); + // A debug line whose message holds [warning] is no warning line, and its second line goes with it. + const std::vector warnings = read("warning", 200); + REQUIRE(warnings.size() == 4); + CHECK(warnings[2] == "[warning]\t2026-11-17 10:00:03.000001[Thread 0x1]:slow"); + // Every line at trace, the continuations among them; at info, all but the debug entry and its second line. + CHECK(read("trace", 200).size() == 7); + CHECK(read("info", 200).size() == 5); + // The last lines are whole entries: a continuation line never comes without its first line. + CHECK(read("error", 2) == std::vector{"[fatal]\t2026-11-17 10:00:04.000001[Thread 0x1]:out of memory"}); + CHECK(read("error", 3).size() == 3); + // An entry longer than the lines asked for gives its first lines. + CHECK(read("error", 1) == std::vector{"[fatal]\t2026-11-17 10:00:04.000001[Thread 0x1]:out of memory"}); + std::istringstream long_entry("[error]\tt:one\n two\n three\n"); + CHECK(log_tail(long_entry, "error", 2) == std::vector{"[error]\tt:one", " two"}); +} + +TEST_CASE("a plugin command refused after it changed the plugin names how the plugin is left", "[Mcp]") +{ + const json before{{"key", "cloud_one"}, {"name", "Cloud One"}, {"installed", false}, {"enabled", false}, {"error", ""}}; + const Slic3r::GUI::Ops::Refusal refusal{Slic3r::GUI::Ops::RefusalKind::Precondition, "manifest_not_found", + "Plugin manifest was not found."}; + + // A refusal after the call installed the plugin (a cloud download) says it is installed, and carries its row. + json installed = before; + installed["installed"] = true; + const ToolFailure after_install = plugin_refusal_after(refusal, before, installed); + CHECK(std::string(after_install.what()) == "Plugin manifest was not found. It is installed, disabled."); + CHECK(after_install.details.at("code") == "manifest_not_found"); + CHECK(after_install.details.at("plugin") == installed); + + // A failed download records its error on the plugin, which the error names. + json errored = before; + errored["error"] = "the download timed out"; + const ToolFailure after_error = plugin_refusal_after( + {Slic3r::GUI::Ops::RefusalKind::Failed, "download_failed", "the download timed out"}, before, errored); + // The plugin's own error, which has no full stop, is a sentence of its own. + CHECK(std::string(after_error.what()) == + "the download timed out. It is not installed, disabled, with the error \"the download timed out\"."); + CHECK(after_error.details.at("plugin") == errored); + + // A change of enabled alone is a change too: a plugin left loaded by a refused call. + json loaded = before; + loaded["enabled"] = true; + const ToolFailure after_load = plugin_refusal_after(refusal, before, loaded); + CHECK(std::string(after_load.what()) == "Plugin manifest was not found. It is not installed, enabled."); + CHECK(after_load.details.at("plugin") == loaded); + + // A plugin no longer listed afterwards is said so. + const ToolFailure after_gone = plugin_refusal_after(refusal, before, json()); + CHECK(std::string(after_gone.what()) == "Plugin manifest was not found. It is no longer listed."); + + // With the plugin as it was, the refusal is bare: no state, no row. + const ToolFailure unchanged = plugin_refusal_after(refusal, before, before); + CHECK(std::string(unchanged.what()) == "Plugin manifest was not found."); + CHECK(unchanged.details.at("code") == "manifest_not_found"); + CHECK_FALSE(unchanged.details.contains("plugin")); +} + +TEST_CASE("plugin_enable's reply says a plugin is no longer listed", "[Mcp]") +{ + // A load that ended with the plugin gone from the list did not load, and the error says so. + std::optional gone; + try { + plugin_enable_reply("my_plugin", true, /*load_started=*/true, /*still_loading=*/false, json()); + } catch (const ToolFailure& e) { + gone = e; + } + REQUIRE(gone); + CHECK(std::string(gone->what()) == "my_plugin did not load. It is no longer listed."); + CHECK(gone->details.at("code") == "not_loaded"); + CHECK(gone->details.at("plugin").is_null()); + + // Without a load, the reply carries the null row and says the plugin is no longer listed. + const json unloaded = plugin_enable_reply("my_plugin", true, false, false, json()); + CHECK(unloaded.at("plugin").is_null()); + CHECK(unloaded.at("changed") == true); + CHECK(unloaded.at("note") == "my_plugin is no longer listed."); + + // A load that ended with the plugin listed and on is the row; one that ended with it off is an error with its row. + const json on{{"key", "my_plugin"}, {"installed", true}, {"enabled", true}, {"error", ""}}; + const json loaded = plugin_enable_reply("my_plugin", true, true, false, on); + CHECK(loaded.at("plugin") == on); + CHECK_FALSE(loaded.contains("note")); + json off = on; + off["enabled"] = false; + CHECK_THROWS_WITH(plugin_enable_reply("my_plugin", true, true, false, off), "my_plugin did not load. It is installed, disabled."); +} diff --git a/tests/slic3rutils/test_mcp_web.cpp b/tests/slic3rutils/test_mcp_web.cpp index b0114c7b78..25feab6e36 100644 --- a/tests/slic3rutils/test_mcp_web.cpp +++ b/tests/slic3rutils/test_mcp_web.cpp @@ -220,7 +220,7 @@ TEST_CASE("Ctrl in a chord is the platform's command key on a page", "[Mcp]") { const json mods = web_key("Ctrl+S")["mods"]; #ifdef __APPLE__ - // Command on macOS, as press_keys's Ctrl is for widgets; RawCtrl is the Control key. + // Command on macOS, as keyboard_press's Ctrl is for widgets; RawCtrl is the Control key. CHECK(mods["meta"] == true); CHECK(mods["ctrl"] == false); const json raw = web_key("RawCtrl+S")["mods"]; diff --git a/tests/slic3rutils/test_object_list.cpp b/tests/slic3rutils/test_object_list.cpp index 16e41cfabe..c1ec5bb575 100644 --- a/tests/slic3rutils/test_object_list.cpp +++ b/tests/slic3rutils/test_object_list.cpp @@ -3,6 +3,7 @@ #include #include "slic3r/GUI/GUI_ObjectList.hpp" +#include "slic3r/GUI/Operations/Outcome.hpp" #include #include @@ -11,6 +12,7 @@ #include #include +#include #include using namespace Slic3r; @@ -93,6 +95,113 @@ TEST_CASE("Objects sort by bounding box volume", "[ObjectList]") CHECK(sorted_names(model, ObjectOrder::Size) == std::vector{"cube", "tall", "flat"}); } +namespace { + +// The names of `objects` in their order. +std::vector names_of(const std::vector& objects) +{ + std::vector names; + for (const ModelObject* object : objects) + names.push_back(object->name); + return names; +} + +} // namespace + +TEST_CASE("Order By orders by each key, ascending and descending", "[ObjectList]") +{ + // Each key gives the three another order: a is mid in filament, tallest and mid in volume; b the last filament, + // the lowest and the largest; c the first filament, mid in height and the smallest. + Model model; + add_box(model, "a", {10., 10., 30.}, 2); // 3000 mm3 + add_box(model, "b", {20., 20., 10.}, 3); // 4000 mm3 + add_box(model, "c", {10., 10., 20.}, 1); // 2000 mm3 + using Names = std::vector; + struct Case { ObjectOrder order; Names ascending; }; + const Case c = GENERATE(Case{ObjectOrder::Name, {"a", "b", "c"}}, Case{ObjectOrder::Filament, {"c", "a", "b"}}, + Case{ObjectOrder::Height, {"b", "c", "a"}}, Case{ObjectOrder::Size, {"c", "a", "b"}}); + const auto on_one_plate = [](std::size_t) { return 0; }; + CHECK(names_of(plate_order(model.objects, on_one_plate, 0, c.order, false)) == c.ascending); + const Names descending(c.ascending.rbegin(), c.ascending.rend()); + CHECK(names_of(plate_order(model.objects, on_one_plate, 0, c.order, true)) == descending); +} + +TEST_CASE("Order By sorts a plate's objects in the list positions they hold, and the other plates keep theirs", "[ObjectList]") +{ + Model model; + for (const char* name : {"d", "y", "b", "x", "a"}) + add_box(model, name, {10., 10., 10.}); + // d, b and a are on plate 0; y and x on plate 1. + const auto plate_of = [](std::size_t object) { return object == 1 || object == 3 ? 1 : 0; }; + CHECK(names_of(plate_order(model.objects, plate_of, 0, ObjectOrder::Name, false)) == std::vector{"a", "y", "b", "x", "d"}); + CHECK(names_of(plate_order(model.objects, plate_of, 1, ObjectOrder::Name, false)) == std::vector{"d", "x", "b", "y", "a"}); + // Every plate at once, each in its own positions. + CHECK(names_of(plate_order(model.objects, plate_of, -1, ObjectOrder::Name, true)) == std::vector{"d", "y", "b", "x", "a"}); + // An object on no plate keeps its place. + const auto one_off = [](std::size_t object) { return object == 0 ? -1 : 0; }; + CHECK(names_of(plate_order(model.objects, one_off, -1, ObjectOrder::Name, false)) == std::vector{"d", "a", "b", "x", "y"}); +} + +// The names of `objects` after the drops `moves`, each as the object list makes it (move_object_in_list()). +std::vector names_after(std::vector objects, const std::vector& moves) +{ + for (const ObjectMove& move : moves) + move_object_in_list(objects, move.from, move.to); + return names_of(objects); +} + +TEST_CASE("An order of a plate's objects becomes the drops that put them in that order, the other plates keeping theirs", "[ObjectList]") +{ + Model model; + for (const char* name : {"a", "x", "b", "c", "y"}) + add_box(model, name, {10., 10., 10.}); + // a, b and c are on plate 0; x and y on plate 1. + const std::vector plate_of{0, 1, 0, 0, 1}; + + const Ops::Outcome> moves = object_order_moves(plate_of, 0, {3, 0, 2}); + REQUIRE(moves); + CHECK_FALSE(moves.value().empty()); + // c, dropped on a, takes its place, and those after it move down: plate 0 reads c, a, b, and x stays before y. + CHECK(names_after(model.objects, moves.value()) == std::vector{"c", "a", "x", "b", "y"}); + + const Ops::Outcome> other = object_order_moves(plate_of, 1, {4, 1}); + REQUIRE(other); + CHECK(names_after(model.objects, other.value()) == std::vector{"a", "y", "x", "b", "c"}); + + // The order they have already takes no drop. + const Ops::Outcome> kept = object_order_moves(plate_of, 0, {0, 2, 3}); + REQUIRE(kept); + CHECK(kept.value().empty()); +} + +TEST_CASE("An order is refused when it leaves out an object of the plate, repeats one, or names one of another plate", "[ObjectList]") +{ + // Objects 0, 2 and 3 are on plate 0, 1 on plate 1, and 4 on no plate. + const std::vector plate_of{0, 1, 0, 0, -1}; + const auto refusal = [&plate_of](const std::vector& order) { + const Ops::Outcome> moves = object_order_moves(plate_of, 0, order); + REQUIRE_FALSE(moves); + return moves.refusal(); + }; + const Ops::Refusal missing = refusal({3, 0}); + CHECK(std::string(missing.code) == "order_misses_object"); + CHECK(missing.names == std::vector{"2"}); + CHECK(missing.english() == "The order leaves out objects of plate 0: 2. Name each of its objects once."); + + const Ops::Refusal repeated = refusal({0, 2, 2, 3}); + CHECK(std::string(repeated.code) == "order_repeats_object"); + CHECK(repeated.english() == "The order names object 2 twice."); + + const Ops::Refusal elsewhere = refusal({0, 1, 2, 3}); + CHECK(std::string(elsewhere.code) == "object_not_on_plate"); + CHECK(elsewhere.english() == "Object 1 is not on plate 0."); + CHECK(std::string(refusal({0, 2, 3, 4}).code) == "object_not_on_plate"); + + const Ops::Refusal unknown = refusal({0, 2, 3, 7}); + CHECK(std::string(unknown.code) == "no_such_object"); + CHECK(unknown.english() == "Object 7 does not exist: the project has objects 0 to 4."); +} + TEST_CASE("Imported part names sort only their presentation and survive cloning", "[ObjectList][OriginalNames]") { Model model; diff --git a/tests/slic3rutils/test_operations.cpp b/tests/slic3rutils/test_operations.cpp index e658ab8cd6..ad00c8aab8 100644 --- a/tests/slic3rutils/test_operations.cpp +++ b/tests/slic3rutils/test_operations.cpp @@ -1,22 +1,47 @@ #include #include +#include +#include #include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/Mcp/PythonScriptsDialog.hpp" #include "slic3r/GUI/NativeCommands.hpp" +#include "slic3r/GUI/Operations/ExportOps.hpp" +#include "slic3r/GUI/Operations/InstallOps.hpp" +#include "slic3r/GUI/Operations/ObjectOps.hpp" #include "slic3r/GUI/Operations/Outcome.hpp" #include "slic3r/GUI/Operations/PlateOps.hpp" +#include "slic3r/GUI/Operations/PluginOps.hpp" +#include "slic3r/GUI/Operations/PreferenceOps.hpp" +#include "slic3r/GUI/Operations/PresetOps.hpp" #include "slic3r/GUI/Operations/ProjectOps.hpp" #include "slic3r/GUI/Operations/RunStatus.hpp" #include "slic3r/GUI/PresetComboBoxes.hpp" +#include "slic3r/Utils/FixModelByCgal.hpp" +#include "slic3r/plugin/PluginDescriptor.hpp" +#include "libslic3r/AppConfig.hpp" +#include "libslic3r/Model.hpp" +#include "libslic3r/TextConfiguration.hpp" +#include "libslic3r/TriangleMesh.hpp" + +#include #include +#include +#include #include +#include #include +#include #include +#include +#include #include #include +#include #include +#include #include #include @@ -349,28 +374,1664 @@ TEST_CASE("a project is not saved under a sliced file's name", "[Operations]") CHECK(std::string(upper.refusal().code) == "sliced_file_name"); } -// ---- The catalogs name their operations --------------------------------------------------------------- -// -// A tool that changes something, and a palette command that takes arguments, either names the operations -// (GUI/Operations) it reaches or is listed here with the reason it reaches none. The lists are what a -// new tool or command has to be added to, or kept off, in plain sight. They say how an entry is -// classified; they do not check what its handler calls, which scripts/check_operation_calls.py does -// for the owner calls an operation stands for. +// ---- The object commands' checks, on a model built in the case ------------------------------------------------------ namespace { -// A command a person picks from the Speed Dial whose arguments stand for what it asks: it has a tile, no -// tool lists it (a listed command is under the tools' rule), and its schema has an argument beside the -// `silent` every two-form command takes. A Design command acts on the Design tab's document, which no -// operation stands for. -bool palette_command_with_arguments(const Slic3r::GUI::NativeCommand& command) +// An object named `name` of `parts` cubes, solid parts all, with `instances` instances. +Slic3r::ModelObject* add_cubes(Slic3r::Model& model, const std::string& name, int instances, int parts) { - if (!command.in_palette || command.listed || command.group == Slic3r::GUI::kDesignGroup) + Slic3r::ModelObject* object = model.add_object(); + object->name = name; + for (int p = 0; p < parts; ++p) + object->add_volume(Slic3r::make_cube(10., 10., 10.), Slic3r::ModelVolumeType::MODEL_PART, false); + for (int i = 0; i < instances; ++i) + object->add_instance(); + return object; +} + +std::string code_of(const std::optional& refusal) { return refusal ? refusal->code : ""; } + +} // namespace + +TEST_CASE("the refusals of a command's targets have their codes and say what to do", "[Operations]") +{ + for (const auto& [refusal, code] : std::vector>{{nothing_selected(), "nothing_selected"}, + {wrong_selection(), "wrong_selection"}, + {one_object_only(), "one_object_only"}, + {gizmo_keeps_selection(), "gizmo_open"}}) { + INFO(code); + CHECK(refusal.code == code); + CHECK(refusal.kind == RefusalKind::Precondition); + CHECK_FALSE(refusal.english().empty()); + // No placeholder is left in the text. + CHECK(refusal.english().find('%') == std::string::npos); + } + CHECK(nothing_selected().english() == "Nothing is selected: name the objects, or select them first."); +} + +TEST_CASE("deleting part of a cut object is refused with the question the object list asks", "[Operations]") +{ + Slic3r::Model model; + add_cubes(model, "half", 1, 2)->cut_id.init(); + add_cubes(model, "twice", 2, 1); + + Targets part; + part.parts = {{0, 1}}; + const std::optional refused = delete_refusal(model, part); + REQUIRE(refused); + CHECK(code_of(refused) == "cut_object"); + CHECK(refused->english() == "This action will break a cut correspondence.\nAfter that, model consistency can't be guaranteed.\n\nTo " + "manipulate with solid parts or negative volumes you have to invalidate cut information first."); + // A whole cut object is asked about too: a call without a person to answer is refused. + Targets half; + half.objects = {0}; + CHECK(code_of(delete_refusal(model, half)) == "cut_object"); + + // Neither a whole object nor one instance of an object with two. + Targets whole; + whole.objects = {1}; + CHECK_FALSE(delete_refusal(model, whole)); + Targets instance; + instance.instances = {{1, 1}}; + CHECK_FALSE(delete_refusal(model, instance)); + + // An object keeps a solid part: its last one is not deleted alone, while with every part it is the whole object. + Slic3r::Model parts; + Slic3r::ModelObject* object = add_cubes(parts, "with modifier", 1, 1); + object->add_volume(Slic3r::make_cube(5., 5., 5.), Slic3r::ModelVolumeType::PARAMETER_MODIFIER, false); + Targets last; + last.parts = {{0, 0}}; + CHECK(code_of(delete_refusal(parts, last)) == "last_solid_part"); + last.parts = {{0, 0}, {0, 1}}; + CHECK_FALSE(delete_refusal(parts, last)); + CHECK(deletion(parts, last).objects == std::vector{0}); +} + +TEST_CASE("a delete names what went and what stayed of what it was asked for, by identity", "[Operations]") +{ + using Pairs = std::vector>; + // An object of two solid parts and a modifier, both solid parts asked for: the object list deletes the second and + // refuses the first, the object's last solid part. + Slic3r::Model model; + Slic3r::ModelObject* object = add_cubes(model, "two parts", 1, 2); + object->add_volume(Slic3r::make_cube(5., 5., 5.), Slic3r::ModelVolumeType::PARAMETER_MODIFIER, false); + Targets doomed; + doomed.parts = {{0, 0}, {0, 1}}; + const TargetIds two_parts = target_ids(model, doomed); + object->delete_volume(1); + const DeletedTargets refused_one = deleted_targets(doomed, two_parts, model); + CHECK(refused_one.deleted.parts == Pairs{{0, 1}}); + CHECK(refused_one.kept.parts == Pairs{{0, 0}}); + + // What stayed is found where it is now: a part after a deleted one has moved down. + Slic3r::Model three; + Slic3r::ModelObject* parts = add_cubes(three, "three parts", 1, 3); + doomed.parts = {{0, 0}, {0, 1}}; + const TargetIds first_two = target_ids(three, doomed); + parts->delete_volume(0); + const DeletedTargets moved = deleted_targets(doomed, first_two, three); + CHECK(moved.deleted.parts == Pairs{{0, 0}}); + CHECK(moved.kept.parts == Pairs{{0, 0}}); + + // Objects and instances alike: of two objects and an instance asked for, one object went, and the other object and + // the instance, of an object after it, stayed. + Slic3r::Model objects; + add_cubes(objects, "a", 1, 1); + add_cubes(objects, "b", 1, 1); + add_cubes(objects, "c", 2, 1); + Targets named; + named.objects = {0, 1}; + named.instances = {{2, 1}}; + const TargetIds named_ids = target_ids(objects, named); + objects.delete_object(std::size_t(1)); + const DeletedTargets one_object = deleted_targets(named, named_ids, objects); + CHECK(one_object.deleted.objects == std::vector{1}); + CHECK(one_object.deleted.instances.empty()); + CHECK(one_object.kept.objects == std::vector{0}); + CHECK(one_object.kept.instances == Pairs{{1, 1}}); + + // Everything asked for went: nothing kept. + const DeletedTargets all_gone = deleted_targets(named, named_ids, Slic3r::Model()); + CHECK(all_gone.deleted.objects == named.objects); + CHECK(all_gone.deleted.instances == named.instances); + CHECK(all_gone.kept.objects.empty()); + CHECK(all_gone.kept.instances.empty()); +} + +TEST_CASE("a rename is refused an empty name and a name a file name cannot hold", "[Operations]") +{ + CHECK(code_of(rename_refusal("")) == "empty_name"); + for (const char* name : {"a/b", "ab", "a:b", "a\\b", "a|b", "a?b", "a*b", "a\"b"}) { + INFO(name); + CHECK(code_of(rename_refusal(name)) == "invalid_name"); + } + CHECK_FALSE(rename_refusal("infill zone")); +} + +TEST_CASE("an object's number of instances is from 1 to 1000, and a cut object keeps its own", "[Operations]") +{ + Slic3r::Model model; + add_cubes(model, "plain", 1, 1); + add_cubes(model, "half", 1, 1)->cut_id.init(); + add_cubes(model, "hidden", 2, 1)->instances[1]->printable = false; + add_cubes(model, "three", 3, 1); + + CHECK_FALSE(instance_count_refusal(model, 0, 1)); + CHECK_FALSE(instance_count_refusal(model, 0, 1000)); + for (int count : {-2, 1001}) { + INFO(count); + CHECK(code_of(instance_count_refusal(model, 3, count)) == "bad_instance_count"); + } + CHECK(code_of(instance_count_refusal(model, 1, 2)) == "cut_object"); + // An object keeps one instance at least, and the refusal says that is why. + const std::optional last = instance_count_refusal(model, 0, 0); + CHECK(code_of(last) == "last_instance"); + REQUIRE(last); + CHECK_THAT(last->english(), Catch::Matchers::ContainsSubstring("\"plain\" has one instance")); +} + +TEST_CASE("an instance that is not printable keeps instances from being added, not from being removed", "[Operations]") +{ + // As Increase Instances and Decrease Instances are enabled (Plater::priv::can_increase_instances(), + // can_decrease_instances()): only the first has the printable rule. + Slic3r::Model model; + add_cubes(model, "hidden", 2, 1)->instances[1]->printable = false; + CHECK_FALSE(instance_count_refusal(model, 0, 1)); + CHECK_FALSE(instance_count_refusal(model, 0, 2)); + CHECK(code_of(instance_count_refusal(model, 0, 3)) == "unprintable_instance"); + // A cut object neither gains nor loses one. + Slic3r::Model cut; + add_cubes(cut, "half", 2, 1)->cut_id.init(); + CHECK(code_of(instance_count_refusal(cut, 0, 1)) == "cut_object"); + // Set Number of Instances, whose dialog may ask for more, is disabled as Increase Instances is. + CHECK(code_of(add_instances_refusal(model, 0)) == "unprintable_instance"); + CHECK(code_of(add_instances_refusal(cut, 0)) == "cut_object"); + Slic3r::Model plain; + add_cubes(plain, "plain", 1, 1); + CHECK_FALSE(add_instances_refusal(plain, 0)); +} + +TEST_CASE("separating instances is refused for an object of one instance and for an instance it lacks", "[Operations]") +{ + Slic3r::Model model; + add_cubes(model, "single", 1, 1); + add_cubes(model, "twice", 2, 1); + + Targets single; + single.objects = {0}; + const std::optional one = separate_refusal(model, single); + CHECK(code_of(one) == "one_instance"); + REQUIRE(one); + CHECK_THAT(one->english(), Catch::Matchers::ContainsSubstring("\"single\" has one instance")); + + Targets lacks; + lacks.instances = {{1, 5}}; + const std::optional missing = separate_refusal(model, lacks); + CHECK(code_of(missing) == "no_such_instance"); + REQUIRE(missing); + CHECK_THAT(missing->english(), Catch::Matchers::ContainsSubstring("5")); + + Targets whole; + whole.objects = {1}; + CHECK_FALSE(separate_refusal(model, whole)); + Targets some; + some.instances = {{1, 0}}; + CHECK_FALSE(separate_refusal(model, some)); + // Instances of two objects are two separations. + Targets both; + both.objects = {0, 1}; + CHECK(code_of(separate_refusal(model, both)) == "one_object_only"); +} + +TEST_CASE("a split is refused a mesh of one shell, saying so, and not a mesh of two", "[Operations]") +{ + Slic3r::Model model; + add_cubes(model, "solid", 1, 1); + Slic3r::TriangleMesh two = Slic3r::make_cube(10., 10., 10.); + Slic3r::TriangleMesh apart = Slic3r::make_cube(10., 10., 10.); + apart.translate(30.f, 0.f, 0.f); + two.merge(apart); + Slic3r::ModelObject* pair = model.add_object(); + pair->name = "pair"; + pair->add_volume(std::move(two), Slic3r::ModelVolumeType::MODEL_PART, false); + pair->add_instance(); + add_cubes(model, "assembly", 1, 2); + + Targets solid; + solid.objects = {0}; + const std::optional one = split_refusal(model, solid); + CHECK(code_of(one) == "one_shell"); + REQUIRE(one); + CHECK_THAT(one->english(), Catch::Matchers::ContainsSubstring("\"solid\"")); + CHECK_THAT(one->english(), Catch::Matchers::ContainsSubstring("one piece")); + + Targets shells; + shells.objects = {1}; + CHECK_FALSE(split_refusal(model, shells)); + // A part is split by its own shells: one cube of an object of two is one piece. + Targets part; + part.parts = {{2, 1}}; + CHECK(code_of(split_refusal(model, part)) == "one_shell"); + // An object of several parts splits into objects by its parts. + Targets parts; + parts.objects = {2}; + CHECK_FALSE(split_refusal(model, parts)); +} + +TEST_CASE("an assembly needs two objects or instances, none of them cut", "[Operations]") +{ + Slic3r::Model model; + add_cubes(model, "one", 1, 1); + add_cubes(model, "two", 2, 1); + add_cubes(model, "half", 1, 1)->cut_id.init(); + + Targets single; + single.objects = {0}; + const std::optional alone = assemble_refusal(model, single); + CHECK(code_of(alone) == "too_few_objects"); + REQUIRE(alone); + CHECK(alone->english() == "Select two or more objects first."); + CHECK(code_of(assemble_refusal(model, Targets{})) == "too_few_objects"); + + Targets pair; + pair.objects = {0, 1}; + CHECK_FALSE(assemble_refusal(model, pair)); + // Two instances of one object are two, as the object list counts its rows. + Targets instances; + instances.instances = {{1, 0}, {1, 1}}; + CHECK_FALSE(assemble_refusal(model, instances)); + + Targets cut; + cut.objects = {0, 2}; + const std::optional refused = assemble_refusal(model, cut); + CHECK(code_of(refused) == "cut_object"); + REQUIRE(refused); + CHECK(refused->english() == "Cut objects can't be assembled."); +} + +TEST_CASE("a part's type change keeps an object's last solid part, and a subtype is a precise seam's", "[Operations]") +{ + using Slic3r::ModelVolumeType; + Slic3r::Model model; + Slic3r::ModelObject* object = add_cubes(model, "body", 1, 2); + object->add_volume(Slic3r::make_cube(5., 5., 5.), ModelVolumeType::PARAMETER_MODIFIER, false); + + // One solid part of two may become anything; both may not, unless they stay solid. + Targets one; + one.parts = {{0, 0}}; + CHECK_FALSE(part_type_refusal(model, one, ModelVolumeType::NEGATIVE_VOLUME, std::nullopt)); + Targets both; + both.parts = {{0, 0}, {0, 1}}; + const std::optional last = part_type_refusal(model, both, ModelVolumeType::PARAMETER_MODIFIER, std::nullopt); + CHECK(code_of(last) == "last_solid_part"); + REQUIRE(last); + CHECK(last->english() == "The type of the last solid object part cannot be changed."); + CHECK_FALSE(part_type_refusal(model, both, ModelVolumeType::MODEL_PART, std::nullopt)); + // The modifier with a solid part: what it becomes leaves the solid parts as they are. + Targets mixed; + mixed.parts = {{0, 2}, {0, 0}}; + CHECK_FALSE(part_type_refusal(model, mixed, ModelVolumeType::SUPPORT_BLOCKER, std::nullopt)); + + // A subtype goes with a precise seam. + Targets modifier; + modifier.parts = {{0, 2}}; + CHECK(code_of(part_type_refusal(model, modifier, ModelVolumeType::PARAMETER_MODIFIER, ModelVolumeType::PRECISE_SEAM_RIGHT)) == + "subtype_without_seam"); + CHECK_FALSE(part_type_refusal(model, modifier, ModelVolumeType::PRECISE_SEAM_CENTER, ModelVolumeType::PRECISE_SEAM_RIGHT)); +} + +TEST_CASE("a text part becomes a part, a negative part or a modifier, and nothing else", "[Operations]") +{ + using Slic3r::ModelVolumeType; + Slic3r::Model model; + Slic3r::ModelObject* object = add_cubes(model, "body", 1, 1); + Slic3r::ModelVolume* text = object->add_volume(Slic3r::make_cube(5., 5., 1.), ModelVolumeType::PARAMETER_MODIFIER, false); + text->text_configuration = Slic3r::TextConfiguration{}; + REQUIRE(text->is_text()); + + Targets lettering; + lettering.parts = {{0, 1}}; + for (const ModelVolumeType kept : {ModelVolumeType::MODEL_PART, ModelVolumeType::NEGATIVE_VOLUME, ModelVolumeType::PARAMETER_MODIFIER}) + CHECK_FALSE(part_type_refusal(model, lettering, kept, std::nullopt)); + for (const ModelVolumeType refused : {ModelVolumeType::SUPPORT_BLOCKER, ModelVolumeType::SUPPORT_ENFORCER, ModelVolumeType::PRECISE_SEAM_CENTER}) { + const std::optional why = part_type_refusal(model, lettering, refused, std::nullopt); + CHECK(code_of(why) == "text_part"); + REQUIRE(why); + CHECK(why->english() == "A text or SVG part can only be a part, a negative part or a modifier."); + } +} + +TEST_CASE("a cut object is not mirrored, saying so", "[Operations]") +{ + Slic3r::Model model; + add_cubes(model, "plain", 1, 1); + add_cubes(model, "half", 1, 1)->cut_id.init(); + + Targets plain; + plain.objects = {0}; + CHECK_FALSE(mirror_refusal(model, plain)); + Targets cut; + cut.parts = {{1, 0}}; + const std::optional refused = mirror_refusal(model, cut); + CHECK(code_of(refused) == "cut_object"); + REQUIRE(refused); + CHECK_THAT(refused->english(), Catch::Matchers::ContainsSubstring("Cut objects")); + CHECK_THAT(refused->english(), Catch::Matchers::ContainsSubstring("mirrored")); +} + +TEST_CASE("objects are centred by the plate each stands on, one on no plate with the current plate's", "[Operations]") +{ + // Objects 0 and 1 stand on plate 1, object 2 on plate 2, object 3 on no plate; plate 1 is current. + const std::map stands{{0, 1}, {1, 1}, {2, 2}, {3, -1}}; + const auto plate_of = [&stands](int object) { return stands.at(object); }; + const std::map> groups = objects_by_plate({0, 1, 2}, plate_of, 1); + CHECK(groups == std::map>{{1, {0, 1}}, {2, {2}}}); + CHECK(objects_by_plate({2, 3}, plate_of, 1) == std::map>{{1, {3}}, {2, {2}}}); + // A plate named holds them all. + const auto on_plate_0 = [](int) { return 0; }; + CHECK(objects_by_plate({0, 1, 2, 3}, on_plate_0, 1) == std::map>{{0, {0, 1, 2, 3}}}); +} + +TEST_CASE("what does not rest on the bed is dropped, and what does is left as it is", "[Operations]") +{ + Slic3r::Model model; + add_cubes(model, "resting", 1, 1); + add_cubes(model, "lifted", 2, 1)->instances[1]->set_offset(Slic3r::Vec3d(0., 0., 15.)); + Slic3r::ModelObject* parts = add_cubes(model, "parts", 1, 2); + parts->volumes[1]->set_offset(Slic3r::Vec3d(0., 0., 30.)); + + Targets resting; + resting.objects = {0}; + resting.parts = {{2, 0}}; + const Targets none = objects_above_bed(model, resting); + CHECK(none.objects.empty()); + CHECK(none.instances.empty()); + CHECK(none.parts.empty()); + + Targets named; + named.objects = {0, 1}; + named.instances = {{1, 0}, {1, 1}}; + named.parts = {{2, 0}, {2, 1}}; + const Targets above = objects_above_bed(model, named); + // An object one of whose instances is above the bed, that instance, and the part above it. + CHECK(above.objects == std::vector{1}); + CHECK(above.instances == std::vector>{{1, 1}}); + CHECK(above.parts == std::vector>{{2, 1}}); +} + +TEST_CASE("Auto-Orient turns the instances of printable objects that stand on no locked plate", "[Operations]") +{ + Slic3r::Model model; + add_cubes(model, "free", 2, 1); + add_cubes(model, "not printable", 1, 1)->printable = false; + add_cubes(model, "locked", 1, 1); + // Instance 1 of "free" and the instance of "locked" stand on a locked plate. + const auto locked = [](int object, int instance) { return (object == 0 && instance == 1) || object == 2; }; + + CHECK(orientable(model, {0, 1, 2}, locked) == std::vector>{{0, 0}}); + // Nothing of these can be turned, which the job would take for nothing selected. + CHECK(orientable(model, {1}, locked).empty()); + CHECK(orientable(model, {1, 2}, locked).empty()); + CHECK(orientable(model, {}, locked).empty()); +} + +namespace { + +// Whether each instance of `model` is printable, object by object. +std::vector instances_printable(const Slic3r::Model& model) +{ + std::vector out; + for (const Slic3r::ModelObject* object : model.objects) + for (const Slic3r::ModelInstance* instance : object->instances) + out.push_back(instance->printable); + return out; +} + +// A 20 mm cube, closed, or with one triangle taken out, which leaves a hole of three open edges. +Slic3r::ModelObject* add_cube_mesh(Slic3r::Model& model, const std::string& name, bool open) +{ + indexed_triangle_set its = Slic3r::make_cube(20., 20., 20.).its; + if (open) + its.indices.pop_back(); + Slic3r::ModelObject* object = model.add_object(); + object->name = name; + object->add_volume(Slic3r::TriangleMesh(std::move(its))); + object->add_instance(); + return object; +} + +} // namespace + +TEST_CASE("an instance is made not printable alone, and an object with every instance of it", "[Operations]") +{ + Slic3r::Model model; + add_cubes(model, "three", 3, 1); + add_cubes(model, "other", 1, 1); + + Targets instance; + instance.instances = {{0, 1}}; + CHECK(set_printable(model, instance, false) == std::vector>{{0, 1}}); + // Its two siblings and the other object are as they were. + CHECK(instances_printable(model) == std::vector{true, false, true, true}); + + Targets object; + object.objects = {0}; + CHECK(set_printable(model, object, false) == std::vector>{{0, 0}, {0, 1}, {0, 2}}); + CHECK(instances_printable(model) == std::vector{false, false, false, true}); + CHECK(set_printable(model, object, true).size() == 3); + CHECK(instances_printable(model) == std::vector{true, true, true, true}); +} + +TEST_CASE("Auto Drop is set on the objects named alone", "[Operations]") +{ + Slic3r::Model model; + add_cubes(model, "first", 2, 1); + add_cubes(model, "second", 1, 1); + add_cubes(model, "third", 1, 1); + + Targets named; + named.objects = {0, 2}; + CHECK(set_auto_drop(model, named, false) == std::vector{0, 2}); + CHECK_FALSE(model.objects[0]->auto_drop); + CHECK(model.objects[1]->auto_drop); + CHECK_FALSE(model.objects[2]->auto_drop); + named.objects = {2}; + CHECK(set_auto_drop(model, named, true) == std::vector{2}); + CHECK_FALSE(model.objects[0]->auto_drop); + CHECK(model.objects[2]->auto_drop); +} + +TEST_CASE("an object's mesh errors count the open edges of its meshes", "[Operations]") +{ + Slic3r::Model model; + const MeshErrors closed = mesh_errors(*add_cube_mesh(model, "closed", false)); + CHECK(closed.open_edges == 0); + CHECK(closed.manifold); + const MeshErrors open = mesh_errors(*add_cube_mesh(model, "open", true)); + CHECK(open.open_edges == 3); + CHECK_FALSE(open.manifold); +} + +TEST_CASE("a repair closes a mesh's hole, and a progress that says stop cancels it", "[Operations]") +{ + Slic3r::Model model; + Slic3r::ModelObject* repaired = add_cube_mesh(model, "repaired", true); + std::string result; + bool modified = false; + CHECK(Slic3r::fix_model_with_cgal(*repaired, -1, [](int, const std::string&) { return true; }, result, false, &modified)); + CHECK(modified); + CHECK(result.empty()); + CHECK(mesh_errors(*repaired).open_edges == 0); + + Slic3r::ModelObject* cancelled = add_cube_mesh(model, "cancelled", true); + CHECK_FALSE(Slic3r::fix_model_with_cgal(*cancelled, -1, [](int, const std::string&) { return false; }, result, false)); + CHECK(mesh_errors(*cancelled).open_edges == 3); +} + +TEST_CASE("a repair cancelled after an object's first part was repaired lists that object as changed and cancelled", "[Operations]") +{ + Slic3r::Model model; + Slic3r::ModelObject* object = add_cube_mesh(model, "two parts", true); + add_cube_mesh(model, "untouched", true); + object->volumes[0]->name = "first"; + // A second part, a sphere of 43,680 triangles less the one taken out to open it, whose repair outlasts the cancel + // given when it starts. + indexed_triangle_set sphere = Slic3r::its_make_sphere(10., 0.03); + sphere.indices.pop_back(); + object->add_volume(Slic3r::TriangleMesh(std::move(sphere)))->name = "second"; + const int open_before = mesh_errors(*object).open_edges; + REQUIRE(open_before > 3); + + // The progress names the part being repaired; anything after the first part cancels. + const auto first_only = [](std::size_t, int, const std::string& what) { return what.empty() || what == "first"; }; + std::vector> updated; + const FixedModels fixed = repair_models(model, {{0, -1}, {1, -1}}, first_only, false, + [&updated](int object, int part) { updated.emplace_back(object, part); }); + CHECK(fixed.cancelled); + REQUIRE(fixed.models.size() == 1); + CHECK(fixed.models[0].object == 0); + CHECK(fixed.models[0].changed); + CHECK(fixed.models[0].cancelled); + CHECK(fixed.models[0].before.open_edges == open_before); + // The first part's hole is closed; the object it stopped in is given to the scene, and the next object is as it was. + CHECK(fixed.models[0].after.open_edges < open_before); + CHECK(updated == std::vector>{{0, -1}}); + CHECK(mesh_errors(*model.objects[1]).open_edges == 3); +} + +namespace { + +// `paths` as generic paths, which compare alike whatever separator a platform joins them with. +std::set generic(const std::vector& paths) +{ + std::set out; + for (const std::string& path : paths) + out.insert(boost::filesystem::path(path).generic_string()); + return out; +} + +} // namespace + +TEST_CASE("a reload finds each part's file, beside its object's when it moved, and lists those it cannot find", "[Operations]") +{ + Slic3r::Model model; + Slic3r::ModelObject* files = add_cubes(model, "files", 1, 5); + files->input_file = "/project/model.3mf"; + files->volumes[0]->source.input_file = "/models/there.stl"; + files->volumes[1]->source.input_file = "/models/gone.stl"; + // A primitive was loaded from no file, and a built-in model is reloaded from none. + files->volumes[3]->source.input_file = "/resources/handy_models/cube.stl"; + files->volumes[3]->source.is_from_builtin_objects = true; + // Its file moved from where it was loaded, and one of its name is beside the project. + files->volumes[4]->source.input_file = "/old/beside.stl"; + const std::set present{"/models/there.stl", "/project/beside.stl", "/resources/handy_models/cube.stl"}; + const auto exists = [&present](const std::string& path) { return present.count(boost::filesystem::path(path).generic_string()) != 0; }; + + Targets object; + object.objects = {0}; + const ReloadSources all = reload_sources(model, object, exists); + CHECK(all.parts == std::vector>{{0, 0}, {0, 4}}); + CHECK(generic(all.paths) == std::set{"/models/there.stl", "/project/beside.stl"}); + CHECK(all.missing == std::vector>{{0, 1}}); + + // Parts named are the only ones looked at. + Targets gone; + gone.parts = {{0, 1}, {0, 2}}; + const ReloadSources missing = reload_sources(model, gone, exists); + CHECK(missing.parts.empty()); + CHECK(missing.paths.empty()); + CHECK(missing.missing == std::vector>{{0, 1}}); + Targets primitive; + primitive.parts = {{0, 2}, {0, 3}}; + const ReloadSources none = reload_sources(model, primitive, exists); + CHECK(none.parts.empty()); + CHECK(none.missing.empty()); +} + +TEST_CASE("a part is replaced with a file of one mesh, and a file of two objects or two parts is refused", "[Operations]") +{ + Slic3r::Model one; + add_cubes(one, "one", 1, 1); + CHECK_FALSE(replacement_refusal(one)); + + Slic3r::Model two_objects; + add_cubes(two_objects, "first", 1, 1); + add_cubes(two_objects, "second", 1, 1); + const std::optional objects = replacement_refusal(two_objects); + CHECK(code_of(objects) == "several_parts"); + REQUIRE(objects); + CHECK(objects->english() == "Unable to replace with more than one volume"); + + Slic3r::Model two_parts; + add_cubes(two_parts, "parts", 1, 2); + CHECK(code_of(replacement_refusal(two_parts)) == "several_parts"); + + // The part replaced: the one named, or the one part of an object named; an object of two parts names none. + Slic3r::Model model; + add_cubes(model, "single", 1, 1); + add_cubes(model, "double", 1, 2); + Targets part; + part.parts = {{1, 1}}; + REQUIRE(replaced_part(model, part)); + CHECK(replaced_part(model, part).value() == std::make_pair(1, 1)); + Targets single; + single.objects = {0}; + REQUIRE(replaced_part(model, single)); + CHECK(replaced_part(model, single).value() == std::make_pair(0, 0)); + Targets two; + two.objects = {1}; + REQUIRE_FALSE(replaced_part(model, two)); + CHECK(std::string(replaced_part(model, two).refusal().code) == "several_parts"); +} + +// ---- The plate commands' checks, on a project's plate count ------------------------------------------------------ + +TEST_CASE("a plate operation refuses an index the project lacks as no_such_plate", "[Operations]") +{ + // A project of three plates, 0 to 2. Renaming, locking and selecting a plate check its index alone; deleting and + // duplicating it check the index first. + for (int plate : {-1, 3, 9}) { + INFO(plate); + CHECK(code_of(plate_index_refusal(plate, 3)) == "no_such_plate"); + CHECK(code_of(delete_plate_refusal(plate, 3)) == "no_such_plate"); + CHECK(code_of(duplicate_plate_refusal(plate, 3, false)) == "no_such_plate"); + } + const std::optional missing = plate_index_refusal(9, 3); + REQUIRE(missing); + CHECK(missing->kind == RefusalKind::Precondition); + CHECK(missing->english() == "Plate 9 does not exist (the project has plates 0..2)"); + for (int plate : {0, 2}) { + INFO(plate); + CHECK_FALSE(plate_index_refusal(plate, 3)); + CHECK_FALSE(delete_plate_refusal(plate, 3)); + CHECK_FALSE(duplicate_plate_refusal(plate, 3, false)); + } +} + +TEST_CASE("the only plate is not deleted, and a plate is not duplicated past the most a project holds or while slicing", "[Operations]") +{ + const std::optional only = delete_plate_refusal(0, 1); + CHECK(code_of(only) == "last_plate"); + REQUIRE(only); + CHECK(only->english() == "Cannot delete the only plate."); + CHECK_FALSE(delete_plate_refusal(0, 2)); + + // A thousand plates are more than a project holds. + const std::optional full = duplicate_plate_refusal(0, 1000, false); + CHECK(code_of(full) == "too_many_plates"); + REQUIRE(full); + CHECK(full->english() == "Cannot duplicate a plate (maximum reached)."); + // No plate is added while a slice runs; it says so, and to wait. + const std::optional slicing = duplicate_plate_refusal(0, 2, true); + CHECK(code_of(slicing) == "slicing_in_progress"); + REQUIRE(slicing); + CHECK(slicing->kind == RefusalKind::Busy); +} + +// ---- Filament slots, exports and imports: their checks, on the counts and names a project has ---------------------- + +TEST_CASE("a mixed filament mixes two or more of the project's filaments, each once and of one type, with one ratio each that " + "add up to 100", "[Operations]") +{ + // A project of three PLA filaments that mix, 1 to 3. + const std::vector pla{"PLA", "PLA", "PLA"}; + CHECK_FALSE(mixed_filament_refusal(pla, {1, 2}, {50, 50})); + CHECK_FALSE(mixed_filament_refusal(pla, {3, 1, 2}, {20, 30, 50})); + CHECK_FALSE(mixed_filament_refusal(pla, {1, 3}, {12.5, 87.5})); + + const std::optional one = mixed_filament_refusal(pla, {2}, {100}); + CHECK(code_of(one) == "too_few_components"); + REQUIRE(one); + CHECK(one->english() == "A mixed filament mixes two filaments or more."); + CHECK(code_of(mixed_filament_refusal(pla, {}, {})) == "too_few_components"); + // A filament named twice, which the Add Mixed Filament dialog's selectors never offer, with two others or alone. + for (const std::vector& components : std::vector>{{2, 2}, {1, 2, 2}, {3, 1, 3}}) { + INFO(components.size()); + CHECK(code_of(mixed_filament_refusal(pla, components, std::vector(components.size(), 100. / 3))) == + "duplicate_component"); + } + const std::optional twice = mixed_filament_refusal(pla, {1, 2, 2}, {40, 30, 30}); + REQUIRE(twice); + CHECK(twice->english() == "Filament 2 is named twice: a mixed filament mixes each filament once."); + + for (const std::vector& components : std::vector>{{1, 4}, {0, 1}, {2, -1}}) { + INFO(components[0] << ", " << components[1]); + CHECK(code_of(mixed_filament_refusal(pla, components, {50, 50})) == "no_such_slot"); + } + const std::optional missing = mixed_filament_refusal(pla, {1, 4}, {50, 50}); + REQUIRE(missing); + CHECK(missing->english() == "Filament 4 does not exist: the filaments that mix are 1 to 3."); + + // Filaments of one type: the dialog's OK takes no other mix, and the sidebar marks one broken. + const std::vector pla_petg{"PLA", "PETG", "PLA"}; + CHECK_FALSE(mixed_filament_refusal(pla_petg, {1, 3}, {50, 50})); + const std::optional types = mixed_filament_refusal(pla_petg, {1, 2}, {50, 50}); + CHECK(code_of(types) == "mixed_types"); + REQUIRE(types); + CHECK(types->english() == "Cannot mix different filament types"); + CHECK(types->names == std::vector{"1: PLA", "2: PETG"}); + + // A ratio per filament, as percentages that add up to 100. + for (const std::vector& ratios : std::vector>{{100}, {40, 50, 10}, {40, 50}, {60, 50}, {}, {0, 100}}) { + INFO(ratios.size()); + CHECK(code_of(mixed_filament_refusal(pla, {1, 2}, ratios)) == "bad_ratios"); + } + const std::optional ratios = mixed_filament_refusal(pla, {1, 2}, {40, 50}); + REQUIRE(ratios); + CHECK(ratios->english() == "Give one ratio per filament, as percentages that add up to 100."); +} + +TEST_CASE("a filament slot is deleted, or merged into another, unless it is the only one or names none", "[Operations]") +{ + // A project of three filament slots, 1 to 3. + CHECK_FALSE(filament_delete_refusal(3, 3, std::nullopt)); + CHECK_FALSE(filament_delete_refusal(3, 1, 3)); + CHECK_FALSE(filament_delete_refusal(3, 2, 1)); + + const std::optional only = filament_delete_refusal(1, 1, std::nullopt); + CHECK(code_of(only) == "last_filament_slot"); + REQUIRE(only); + CHECK(only->english() == "The only filament slot cannot be deleted."); + + for (int slot : {0, 4, -1}) { + INFO(slot); + CHECK(code_of(filament_delete_refusal(3, slot, std::nullopt)) == "no_such_slot"); + } + const std::optional missing = filament_delete_refusal(3, 4, std::nullopt); + REQUIRE(missing); + CHECK(missing->english() == "Filament slot must be 1 to 3."); + + for (int into : {0, 4}) { + INFO(into); + CHECK(code_of(filament_delete_refusal(3, 2, into)) == "no_such_slot"); + } + const std::optional nowhere = filament_delete_refusal(3, 2, 4); + REQUIRE(nowhere); + CHECK(nowhere->english() == "The slot to merge into must be 1 to 3."); + + const std::optional itself = filament_delete_refusal(3, 2, 2); + CHECK(code_of(itself) == "merge_into_itself"); + REQUIRE(itself); + CHECK(itself->english() == "A filament slot cannot be merged into itself."); +} + +TEST_CASE("an export of some objects names objects the project has, in a format that writes objects", "[Operations]") +{ + Slic3r::Model empty; + Slic3r::Model model; + add_cubes(model, "first", 1, 1); + add_cubes(model, "second", 2, 1); + + // A file per object needs objects to write. + for (const char* format : {"stl", "drc"}) { + INFO(format); + CHECK(code_of(export_objects_refusal(format, {}, true, empty)) == "no_objects"); + CHECK_FALSE(export_objects_refusal(format, {}, true, model)); + CHECK_FALSE(export_objects_refusal(format, {1}, true, model)); + CHECK_FALSE(export_objects_refusal(format, {0, 1}, false, model)); + } + const std::optional nothing = export_objects_refusal("stl", {}, true, empty); + REQUIRE(nothing); + CHECK(nothing->english() == "The project has no objects."); + + // The other formats write the whole model, a plate's slice or what the Preview shows. + for (const char* format : {"gcode", "sliced_3mf", "3mf", "toolpaths_obj"}) { + INFO(format); + CHECK(code_of(export_objects_refusal(format, {0}, false, model)) == "objects_not_taken"); + CHECK_FALSE(export_objects_refusal(format, {}, false, model)); + } + const std::optional whole = export_objects_refusal("3mf", {0}, false, model); + REQUIRE(whole); + CHECK(whole->english() == "Only an STL or a DRC export takes objects, not 3mf."); + + for (int object : {2, -1}) { + INFO(object); + CHECK(code_of(export_objects_refusal("stl", {0, object}, false, model)) == "no_such_object"); + } + const std::optional missing = export_objects_refusal("drc", {5}, true, model); + REQUIRE(missing); + CHECK(missing->english() == "Object 5 does not exist (the project has objects 0..1)"); + CHECK(code_of(export_objects_refusal("stl", {0}, false, empty)) == "no_objects"); +} + +TEST_CASE("the files taken from a ZIP archive are model files it holds", "[Operations]") +{ + const std::vector in_archive{"cube.stl", "parts/cylinder.obj", "parts/bracket.step"}; + CHECK_FALSE(zip_entries_refusal(in_archive, {})); + CHECK_FALSE(zip_entries_refusal(in_archive, {"parts/cylinder.obj"})); + CHECK_FALSE(zip_entries_refusal(in_archive, {"cube.stl", "parts/bracket.step"})); + + for (const std::vector& asked : + std::vector>{{"cylinder.obj"}, {"cube.stl", "readme.txt"}, {"CUBE.STL"}}) { + INFO(asked.back()); + const std::optional refused = zip_entries_refusal(in_archive, asked); + CHECK(code_of(refused) == "no_such_entry"); + REQUIRE(refused); + CHECK(refused->english() == "The archive holds no model file " + asked.back() + "."); + // With the names it has. + CHECK(refused->names == in_archive); + } +} + +// ---- Printer models and system filaments ---------------------------------------------------------------- + +namespace { + +// The models section of an installed set: vendor -> model -> nozzles. +using Printers = std::map>>; + +// An installed set of these printers and one filament. +InstallSet install_set(Printers printers) +{ + InstallSet set; + set.printers = std::move(printers); + set.filaments = {{"Bambu PLA Basic @BBL X1C", "true"}}; + return set; +} + +const std::string kX1C = "Bambu Lab X1 Carbon"; + +} // namespace + +TEST_CASE("installing a printer model changes the named models and keeps the rest", "[Operations]") +{ + const InstallSet installed = install_set({{"BBL", {{kX1C, {"0.4"}}}}, {"Prusa", {{"Original Prusa MK4S", {"0.4", "0.6"}}}}}); + + // A model of another vendor, with one nozzle, joins the two. + InstallSet changed = changed_install_set(installed, {{"Goofoo", "Goofoo Velo+", {"0.4"}}}, {}); + CHECK(changed.printers == Printers{{"BBL", {{kX1C, {"0.4"}}}}, + {"Goofoo", {{"Goofoo Velo+", {"0.4"}}}}, + {"Prusa", {{"Original Prusa MK4S", {"0.4", "0.6"}}}}}); + // The filaments are not the models' to change. + CHECK(changed.filaments == installed.filaments); + + // A second nozzle of an installed model keeps its first. + changed = changed_install_set(installed, {{"BBL", kX1C, {"0.6"}}}, {}); + CHECK(changed.printers == Printers{{"BBL", {{kX1C, {"0.4", "0.6"}}}}, {"Prusa", {{"Original Prusa MK4S", {"0.4", "0.6"}}}}}); + + // Removing one nozzle keeps the model's other. + changed = changed_install_set(installed, {}, {{"Prusa", "Original Prusa MK4S", {"0.6"}}}); + CHECK(changed.printers == Printers{{"BBL", {{kX1C, {"0.4"}}}}, {"Prusa", {{"Original Prusa MK4S", {"0.4"}}}}}); + + // Removing a model's last nozzle removes the model, and a vendor left with none goes with it. + changed = changed_install_set(installed, {}, {{"BBL", kX1C, {"0.4"}}}); + CHECK(changed.printers == Printers{{"Prusa", {{"Original Prusa MK4S", {"0.4", "0.6"}}}}}); + + // Removing a model that is not installed, or a nozzle of an installed one that is not, changes nothing. + CHECK(changed_install_set(installed, {}, {{"Goofoo", "Goofoo Velo+", {"0.4"}}}).printers == installed.printers); + CHECK(changed_install_set(installed, {}, {{"BBL", kX1C, {"0.8"}}}).printers == installed.printers); + // Nor does the model of that name under another vendor. + CHECK(changed_install_set(installed, {}, {{"Clone", kX1C, {"0.4"}}}).printers == installed.printers); +} + +TEST_CASE("the printer models are every vendor's, with their nozzles and those installed", "[Operations]") +{ + // The Printer Selection dialog's data (printer_profile_data()): the models of two vendors, and a third vendor + // with a model of the first one's name. + const nlohmann::json profile = { + {"model", nlohmann::json::array({{{"model", kX1C}, {"name", kX1C}, {"vendor", "BBL"}, {"nozzle_diameter", "0.4;0.6"}}, + {{"model", "Bambu Lab A1 mini"}, + {"name", "Bambu Lab A1 mini"}, + {"vendor", "BBL"}, + {"nozzle_diameter", "0.2;0.4"}}, + {{"model", "Goofoo Velo+"}, + {"name", "Goofoo Velo+"}, + {"vendor", "Goofoo"}, + {"nozzle_diameter", "0.2;0.4;0.6"}}, + {{"model", kX1C}, {"name", kX1C}, {"vendor", "Clone"}, {"nozzle_diameter", "0.4;0.6"}}})}, + {"machine", nlohmann::json::object()}}; + const InstallSet installed = install_set({{"BBL", {{kX1C, {"0.4"}}}}}); + + const std::vector all = printer_models_from(profile, installed, "", ""); + REQUIRE(all.size() == 4); + CHECK(all[0].vendor == "BBL"); + CHECK(all[0].model == kX1C); + CHECK(all[0].nozzles == std::vector{"0.4", "0.6"}); + CHECK(all[0].installed_nozzles == std::vector{"0.4"}); + CHECK(all[1].model == "Bambu Lab A1 mini"); + CHECK(all[1].installed_nozzles.empty()); + CHECK(all[2].nozzles == std::vector{"0.2", "0.4", "0.6"}); + // The model of that name under another vendor is not the one installed. + CHECK(all[3].vendor == "Clone"); + CHECK(all[3].installed_nozzles.empty()); + + // vendor keeps one vendor's models, in either case. + const std::vector goofoo = printer_models_from(profile, installed, "goofoo", ""); + REQUIRE(goofoo.size() == 1); + CHECK(goofoo[0].model == "Goofoo Velo+"); + CHECK(printer_models_from(profile, installed, "BBL", "").size() == 2); + + // query matches a model's name whatever its case. + const std::vector carbon = printer_models_from(profile, installed, "bbl", "x1 CARBON"); + REQUIRE(carbon.size() == 1); + CHECK(carbon[0].vendor == "BBL"); + CHECK(printer_models_from(profile, installed, "", "MINI").at(0).model == "Bambu Lab A1 mini"); + CHECK(printer_models_from(profile, installed, "", "carbon").size() == 2); + CHECK(printer_models_from(profile, installed, "Goofoo", "carbon").empty()); +} + +TEST_CASE("uninstalling is refused the last printer's last nozzle and not one of two", "[Operations]") +{ + const InstallSet one = install_set({{"BBL", {{kX1C, {"0.4"}}}}}); + const std::optional last = uninstall_refusal(one, {{"BBL", kX1C, {"0.4"}}}); + CHECK(code_of(last) == "last_printer"); + REQUIRE(last); + CHECK(last->english() == "At least one printer model must stay installed."); + // Both nozzles of the only model. + CHECK(code_of(uninstall_refusal(install_set({{"BBL", {{kX1C, {"0.4", "0.6"}}}}}), {{"BBL", kX1C, {"0.4", "0.6"}}})) == + "last_printer"); + + // One of two nozzles, one of two models, and a model that is not installed. + CHECK_FALSE(uninstall_refusal(install_set({{"BBL", {{kX1C, {"0.4", "0.6"}}}}}), {{"BBL", kX1C, {"0.4"}}})); + CHECK_FALSE(uninstall_refusal(install_set({{"BBL", {{kX1C, {"0.4"}}}}, {"Goofoo", {{"Goofoo Velo+", {"0.4"}}}}}), + {{"BBL", kX1C, {"0.4"}}})); + CHECK_FALSE(uninstall_refusal(one, {{"Goofoo", "Goofoo Velo+", {"0.4"}}})); +} + +TEST_CASE("the installed set of a configuration without a filaments section keeps every filament the selectors offer", "[Operations]") +{ + const std::vector offered = {"Bambu PLA Basic @BBL X1C", "Generic PLA @System"}; + Slic3r::AppConfig config; + config.set_vendors(Printers{{"BBL", {{kX1C, {"0.4"}}}}}); + // No section installs every filament: the set a printer change writes back names those the selectors offer, so + // that writing it hides none of them. + REQUIRE_FALSE(config.has_section(Slic3r::AppConfig::SECTION_FILAMENTS)); + const InstallSet without = installed_set_from(config, offered); + CHECK(without.printers == Printers{{"BBL", {{kX1C, {"0.4"}}}}}); + CHECK(without.filaments == std::map{{"Bambu PLA Basic @BBL X1C", "true"}, {"Generic PLA @System", "true"}}); + // A printer installed into it keeps them. + CHECK(changed_install_set(without, {{"Goofoo", "Goofoo Velo+", {"0.4"}}}, {}).filaments == without.filaments); + + // A section, even an empty one, is the set as it stands. + config.set_section(Slic3r::AppConfig::SECTION_FILAMENTS, {{"Generic PLA @System", "true"}}); + CHECK(installed_set_from(config, offered).filaments == std::map{{"Generic PLA @System", "true"}}); + config.set_section(Slic3r::AppConfig::SECTION_FILAMENTS, {}); + REQUIRE(config.has_section(Slic3r::AppConfig::SECTION_FILAMENTS)); + CHECK(installed_set_from(config, offered).filaments.empty()); +} + +TEST_CASE("a call names a printer model by its name, its vendor where two have it, and its nozzles", "[Operations]") +{ + const std::vector known = {{"BBL", kX1C, {"0.4", "0.6"}, {}}, + {"Clone", kX1C, {"0.4"}, {}}, + {"Goofoo", "Goofoo Velo+", {"0.2", "0.4", "0.6"}, {}}}; + + // Without nozzles, all of the model's; with them, those; the vendor in either case. + const Outcome> every = resolve_models(known, {{"", "Goofoo Velo+", {}}}); + REQUIRE(every); + REQUIRE(every.value().size() == 1); + CHECK(every.value()[0].vendor == "Goofoo"); + CHECK(every.value()[0].nozzles == std::vector{"0.2", "0.4", "0.6"}); + const Outcome> named = resolve_models(known, {{"bbl", kX1C, {"0.6"}}}); + REQUIRE(named); + CHECK(named.value()[0].vendor == "BBL"); + CHECK(named.value()[0].nozzles == std::vector{"0.6"}); + + // A name two vendors have needs its vendor, and the refusal names them. + const Outcome> two = resolve_models(known, {{"", kX1C, {"0.4"}}}); + REQUIRE_FALSE(two); + CHECK(two.refusal().code == std::string("ambiguous_model")); + CHECK(two.refusal().names == std::vector{"BBL", "Clone"}); + + // An unknown model, vendor or nozzle, with the closest names; every model is checked, not only the first. + const Outcome> typo = resolve_models(known, {{"", "Goofoo Velo+", {}}, {"", "Goofoo Velo", {}}}); + REQUIRE_FALSE(typo); + CHECK(typo.refusal().code == std::string("no_such_model")); + CHECK(typo.refusal().english() == "No printer model is called \"Goofoo Velo\"."); + REQUIRE_FALSE(typo.refusal().names.empty()); + CHECK(typo.refusal().names.front() == "Goofoo Velo+"); + const Outcome> elsewhere = resolve_models(known, {{"Goofoo", kX1C, {}}}); + REQUIRE_FALSE(elsewhere); + CHECK(elsewhere.refusal().code == std::string("no_such_model")); + CHECK(elsewhere.refusal().english() == "Goofoo has no printer model called \"Bambu Lab X1 Carbon\"."); + CHECK(elsewhere.refusal().names == std::vector{"Goofoo Velo+"}); + const Outcome> vendor = resolve_models(known, {{"Bambu", kX1C, {}}}); + REQUIRE_FALSE(vendor); + CHECK(vendor.refusal().code == std::string("no_such_vendor")); + CHECK(vendor.refusal().english() == "No printer vendor is called \"Bambu\"."); + REQUIRE_FALSE(vendor.refusal().names.empty()); + CHECK(vendor.refusal().names.front() == "BBL"); + const Outcome> nozzle = resolve_models(known, {{"BBL", kX1C, {"0.4", "0.8"}}}); + REQUIRE_FALSE(nozzle); + CHECK(nozzle.refusal().code == std::string("no_such_nozzle")); + CHECK(nozzle.refusal().english() == "Bambu Lab X1 Carbon has no nozzle \"0.8\"."); + CHECK(nozzle.refusal().names == std::vector{"0.4", "0.6"}); +} + +namespace { + +// System filaments as the System Filaments dialog lists them: the Bambu PLA Basic of three printers, two of them +// installed; a Generic PLA whose name is another preset's short name; and a filament no installed printer fits. +const std::vector kFilaments = { + {"Bambu PLA Basic @BBL X1C", "Bambu PLA Basic", "Bambu Lab", "PLA", true}, + {"Bambu PLA Basic @BBL A1", "Bambu PLA Basic", "Bambu Lab", "PLA", true}, + {"Bambu PLA Basic @BBL P1P", "Bambu PLA Basic", "Bambu Lab", "PLA", false}, + {"Bambu PETG HF @BBL X1C", "Bambu PETG HF", "Bambu Lab", "PETG", true}, + {"Generic PLA @System", "Generic PLA", "Generic", "PLA", true}, + {"Generic PLA", "Generic PLA", "Generic", "PLA", true}, + {"Polymaker PLA @P1P", "Polymaker PLA", "Polymaker", "PLA", false}, +}; + +InstallFilamentsArgs named(std::vector names) +{ + InstallFilamentsArgs args; + args.names = std::move(names); + return args; +} + +InstallFilamentsArgs of_type(std::string vendor, std::string type) +{ + InstallFilamentsArgs args; + args.vendor = std::move(vendor); + args.filament_type = std::move(type); + return args; +} + +} // namespace + +TEST_CASE("a filament's short name stands for its preset of each printer it fits, and a preset's name for itself", "[Operations]") +{ + using Names = std::vector; + // The short name the selector shows: the presets of the installed printers, not the P1P's. + CHECK(filament_presets_named(kFilaments, "Bambu PLA Basic") == Names{"Bambu PLA Basic @BBL X1C", "Bambu PLA Basic @BBL A1"}); + // A preset's own name: that preset, whether an installed printer fits it or not. + CHECK(filament_presets_named(kFilaments, "Bambu PLA Basic @BBL P1P") == Names{"Bambu PLA Basic @BBL P1P"}); + CHECK(filament_presets_named(kFilaments, "Generic PLA") == Names{"Generic PLA"}); + CHECK(filament_presets_named(kFilaments, "Generic PLA @System") == Names{"Generic PLA @System"}); + // A short name of a filament no installed printer fits, and a name in another case, stand for nothing. + CHECK(filament_presets_named(kFilaments, "Polymaker PLA").empty()); + CHECK(filament_presets_named(kFilaments, "bambu pla basic").empty()); + + // A call's names, each preset once. + const Outcome both = filaments_named(kFilaments, named({"Bambu PLA Basic", "Bambu PETG HF", "Bambu PLA Basic @BBL A1"})); + REQUIRE(both); + CHECK(both.value() == Names{"Bambu PLA Basic @BBL X1C", "Bambu PLA Basic @BBL A1", "Bambu PETG HF @BBL X1C"}); + // A vendor and a type, in any case: every preset of them that fits an installed printer. + const Outcome bambu_pla = filaments_named(kFilaments, of_type("bambu lab", "pla")); + REQUIRE(bambu_pla); + CHECK(bambu_pla.value() == Names{"Bambu PLA Basic @BBL X1C", "Bambu PLA Basic @BBL A1"}); +} + +TEST_CASE("a filament name that matches nothing is refused with the closest names", "[Operations]") +{ + const Outcome> typo = filaments_named(kFilaments, named({"Bambu PETG HF", "Bambu PLA Basik"})); + REQUIRE_FALSE(typo); + CHECK(typo.refusal().code == std::string("no_such_filament")); + CHECK(typo.refusal().english() == "No system filament is called \"Bambu PLA Basik\"."); + REQUIRE_FALSE(typo.refusal().names.empty()); + CHECK(typo.refusal().names.front() == "Bambu PLA Basic"); + + // A short name no installed printer fits, with its presets. + const Outcome> unfit = filaments_named(kFilaments, named({"Polymaker PLA"})); + REQUIRE_FALSE(unfit); + CHECK(unfit.refusal().code == std::string("fits_no_printer")); + CHECK(unfit.refusal().names == std::vector{"Polymaker PLA @P1P"}); + + // A vendor without the type, with the types it has; a vendor no filament has, with the closest vendors. + const Outcome> tpu = filaments_named(kFilaments, of_type("Bambu Lab", "TPU")); + REQUIRE_FALSE(tpu); + CHECK(tpu.refusal().code == std::string("no_matching_filament")); + CHECK(tpu.refusal().english() == "No system filament of Bambu Lab of type TPU fits an installed printer."); + CHECK(tpu.refusal().names == std::vector{"PETG", "PLA"}); + const Outcome> vendor = filaments_named(kFilaments, of_type("Bambu", "PLA")); + REQUIRE_FALSE(vendor); + CHECK(vendor.refusal().code == std::string("no_filament_vendor")); + REQUIRE_FALSE(vendor.refusal().names.empty()); + CHECK(vendor.refusal().names.front() == "Bambu Lab"); +} + +TEST_CASE("uninstalling a filament is refused the preset a slot uses, naming the slot", "[Operations]") +{ + const std::vector slots = {"Bambu PLA Basic @BBL X1C", "Generic PLA @System"}; + const std::optional first = filament_uninstall_refusal({"Bambu PETG HF @BBL X1C", "Bambu PLA Basic @BBL X1C"}, slots); + CHECK(code_of(first) == "filament_in_use"); + REQUIRE(first); + CHECK(first->english() == "Filament slot 1 uses Bambu PLA Basic @BBL X1C."); + const std::optional second = filament_uninstall_refusal({"Generic PLA @System"}, slots); + REQUIRE(second); + CHECK(second->english() == "Filament slot 2 uses Generic PLA @System."); + // One no slot uses. + CHECK_FALSE(filament_uninstall_refusal({"Bambu PETG HF @BBL X1C"}, slots)); +} + +// ---- Preferences ---------------------------------------------------------------------------------------- + +TEST_CASE("the preferences table names each key once, with a kind and a tab", "[Operations]") +{ + const std::set tabs{"general", "files", "behaviour", "control", "graphics", "online", "developer"}; + // The setting that lets Python scripts run unrestricted, by the key python_scripts_setting() reads. + Slic3r::AppConfig python; + python.set_bool("python_scripts_unrestricted", true); + REQUIRE(Slic3r::GUI::Mcp::python_scripts_setting(python)); + + std::set keys; + for (const Preference& p : preferences()) { + INFO(p.key); + CHECK(keys.insert(p.key).second); + CHECK(tabs.count(p.tab) == 1); + CHECK_FALSE(p.section.empty()); + CHECK_FALSE(p.label.empty()); + if (p.kind == PreferenceKind::Choice) { + std::set values; + for (const auto& [value, label] : p.choices) { + CHECK(values.insert(value).second); + CHECK_FALSE(label.empty()); + } + // Only the two whose entries the running app lists have none, and a call may write neither. + if (p.choices.empty()) { + CHECK(std::set{"language", "network_plugin_version"}.count(p.key) == 1); + CHECK(p.refused != nullptr); + } else + CHECK(p.choices.size() >= 2); + // A row the dialog builds from the table shows its first choice where nothing is stored. + if (!p.own_row) + CHECK(values.count(p.fallback) == 1); + } + if (p.kind == PreferenceKind::Number) { + CHECK(p.min.has_value()); + if (p.min && p.max) + CHECK(*p.min < *p.max); + // A row the dialog builds from the table is a spin control or a decimal field, with both bounds. + if (!p.own_row) + CHECK(p.max.has_value()); + } + // Its key is not the Python scripts' setting. + Slic3r::AppConfig config; + config.set_bool(p.key, true); + CHECK_FALSE(Slic3r::GUI::Mcp::python_scripts_setting(config)); + } + const Preference* language = find_preference(preferences(), "language"); + REQUIRE(language != nullptr); + CHECK(language->tab == "general"); + REQUIRE(language->refused != nullptr); + // The checking function refuses the Python scripts' setting as a key the table lacks. + const std::optional python_refused = check_preferences(preferences(), {{"python_scripts_unrestricted", true}}); + CHECK(code_of(python_refused) == "not_a_preference"); + REQUIRE(python_refused); + CHECK(python_refused->english() == "python_scripts_unrestricted is not a setting of the Preferences dialog."); +} + +TEST_CASE("a preference whose control has a side effect is written, and one whose control asks first or moves this server is refused", + "[Operations]") +{ + // Preset sync and stealth mode run their control's effect (apply_preference()). + for (const char* key : {"sync_user_preset", "stealth_mode"}) { + INFO(key); + const Preference* p = find_preference(preferences(), key); + REQUIRE(p != nullptr); + CHECK(p->refused == nullptr); + } + CHECK_FALSE(check_preferences(preferences(), {{"stealth_mode", true}, {"sync_user_preset", false}})); + // The mixed-temperature switch asks to confirm a warning; the MCP server's switch and port end or move the + // connection of the call that asks. + for (const char* key : {"enable_high_low_temp_mixed_printing", "mcp_enabled", "mcp_port"}) { + INFO(key); + const Preference* p = find_preference(preferences(), key); + REQUIRE(p != nullptr); + CHECK(p->refused != nullptr); + } + CHECK(code_of(check_preferences(preferences(), {{"stealth_mode", true}, {"mcp_enabled", false}})) == "preference_refused"); +} + +TEST_CASE("the rows the Preferences dialog marks as needing a restart are flagged as read at the next start", "[Operations]") +{ + std::set flagged; + for (const Preference& p : preferences()) + if (p.restart_needed) + flagged.insert(p.key); + std::set expected = {"enable_multi_machine", SETTING_OPENGL_AA_SAMPLES, SETTING_USE_ENCRYPTED_TOKEN_FILE}; +#ifdef SLIC3R_CAD + expected.insert("enable_cad_feature"); +#endif +#ifdef __linux__ + expected.insert({"window_buttons_on_left", "prefer_discrete_gpu"}); +#endif + CHECK(flagged == expected); + // Each is a value a call may write. + for (const std::string& key : flagged) { + INFO(key); + CHECK(find_preference(preferences(), key)->refused == nullptr); + } +} + +namespace { + +// A table of five rows, as the Preferences dialog's table holds them. +std::vector preference_rows() +{ + Preference arrange; + arrange.key = "auto_arrange"; + arrange.tab = "behaviour"; + arrange.section = "Prepare"; + arrange.label = "Auto arrange plate after cloning"; + arrange.kind = PreferenceKind::Checkbox; + arrange.fallback = "false"; + Preference flush = arrange; + flush.key = "auto_calculate_flush"; + flush.label = "Auto flush after changing..."; + flush.kind = PreferenceKind::Choice; + flush.choices = {{"all", "All"}, {"color change", "Color"}, {"disabled", "None"}}; + flush.fallback = "all"; + Preference fps = arrange; + fps.section = "FPS"; + fps.tab = "graphics"; + fps.key = "opengl_fps_cap"; + fps.label = "FPS cap"; + fps.kind = PreferenceKind::Number; + fps.min = 0; + fps.max = 240; + fps.fallback = ""; + Preference language = flush; + language.tab = "general"; + language.key = "language"; + language.label = "Language"; + language.choices = {}; + language.refused = "%1%: changing the language restarts OrcaSlicer."; + Preference downloads = arrange; + downloads.tab = "files"; + downloads.section = "Files"; + downloads.key = "download_path"; + downloads.label = "Downloads folder"; + downloads.kind = PreferenceKind::Text; + downloads.folder = true; + downloads.fallback = ""; + return {arrange, flush, fps, language, downloads}; +} + +} // namespace + +TEST_CASE("a write of several preferences is checked whole before any is written", "[Operations]") +{ + const std::vector table = preference_rows(); + // Good keys and values pass. + CHECK_FALSE(check_preferences(table, {{"auto_arrange", false}, {"auto_calculate_flush", "color change"}, {"opengl_fps_cap", 60}})); + + // One refused key among good ones refuses the call, naming it, whether it comes before or after them. + std::optional refused = check_preferences(table, {{"auto_arrange", true}, {"language", "de"}}); + CHECK(code_of(refused) == "preference_refused"); + REQUIRE(refused); + CHECK(refused->english() == "language: changing the language restarts OrcaSlicer."); + CHECK(refused->names == std::vector{"language"}); + refused = check_preferences(table, {{"language", "de"}, {"opengl_fps_cap", 60}}); + CHECK(code_of(refused) == "preference_refused"); + + // A value outside a choice's values names the values. + refused = check_preferences(table, {{"auto_arrange", true}, {"auto_calculate_flush", "colour"}}); + CHECK(code_of(refused) == "no_such_choice"); + REQUIRE(refused); + CHECK(refused->english() == "auto_calculate_flush has no choice \"colour\"."); + CHECK(refused->names == std::vector{"all", "color change", "disabled"}); + + // A number outside its range names the range, and a number field takes no fraction where it takes whole numbers. + refused = check_preferences(table, {{"opengl_fps_cap", 300}}); + CHECK(code_of(refused) == "out_of_range"); + REQUIRE(refused); + CHECK(refused->english() == "opengl_fps_cap takes a number from 0 to 240."); + CHECK(refused->names == std::vector{"0", "240"}); + CHECK(code_of(check_preferences(table, {{"opengl_fps_cap", 59.5}})) == "not_a_whole_number"); + CHECK(code_of(check_preferences(table, {{"opengl_fps_cap", "60"}})) == "not_a_number"); + + // A checkbox takes true or false, not their text. + CHECK(code_of(check_preferences(table, {{"auto_arrange", "true"}})) == "not_a_boolean"); + + // A folder's text takes the absolute path of an existing folder; a number, a missing folder, a file or a relative + // path is refused, naming the text it was given. + const std::string folder = std::string(TEST_DATA_DIR); + CHECK_FALSE(check_preferences(table, {{"download_path", folder}})); + refused = check_preferences(table, {{"download_path", 5}}); + CHECK(code_of(refused) == "not_a_text"); + REQUIRE(refused); + CHECK(refused->english() == "download_path takes a text."); + const std::string missing = folder + "/no_such_folder"; + refused = check_preferences(table, {{"auto_arrange", true}, {"download_path", missing}}); + CHECK(code_of(refused) == "not_a_folder"); + REQUIRE(refused); + CHECK(refused->english() == "download_path takes the absolute path of an existing folder, which \"" + missing + "\" is not."); + CHECK(code_of(check_preferences(table, {{"download_path", folder + "/20mm_cube.obj"}})) == "not_a_folder"); + CHECK(code_of(check_preferences(table, {{"download_path", "data"}})) == "not_a_folder"); + CHECK(code_of(check_preferences(table, {{"download_path", ""}})) == "not_a_folder"); + + // A key the table lacks is refused with the closest keys. + refused = check_preferences(table, {{"auto_arange", true}}); + CHECK(code_of(refused) == "not_a_preference"); + REQUIRE(refused); + REQUIRE_FALSE(refused->names.empty()); + CHECK(refused->names.front() == "auto_arrange"); +} + +TEST_CASE("a preference's value is stored as its control stores it and read back by its kind", "[Operations]") +{ + std::vector table = preference_rows(); + const Preference& arrange = table[0]; + CHECK(preference_text(arrange, true) == "true"); + CHECK(preference_text(arrange, false) == "false"); + CHECK(preference_value(arrange, "true") == true); + CHECK(preference_value(arrange, "1") == true); + CHECK(preference_value(arrange, "") == false); + // The dark mode's checkbox stores 1 or 0, which its fallback says. + Preference dark_mode = arrange; + dark_mode.fallback = "0"; + CHECK(preference_text(dark_mode, true) == "1"); + CHECK(preference_text(dark_mode, false) == "0"); + + const Preference& flush = table[1]; + CHECK(preference_text(flush, "disabled") == "disabled"); + CHECK(preference_value(flush, "disabled") == "disabled"); + + // A whole number as the spin control writes it; a decimal field's with its decimals, as wxString::FromCDouble(). + const Preference& fps = table[2]; + CHECK(preference_text(fps, 60) == "60"); + CHECK(preference_value(fps, "60") == 60); + CHECK(preference_value(fps, "60").is_number_integer()); + Preference orbit = fps; + orbit.decimals = 2; + CHECK(preference_text(orbit, 0.5) == "0.50"); + CHECK(preference_text(orbit, 1) == "1.00"); + CHECK(preference_value(orbit, "1.0") == 1.0); + // Text no number reads as itself. + CHECK(preference_value(orbit, "fast") == "fast"); + + // A text is stored and read as it is. + const Preference& downloads = table[4]; + CHECK(preference_text(downloads, "C:/Downloads") == "C:/Downloads"); + CHECK(preference_value(downloads, "C:/Downloads") == "C:/Downloads"); +} + +// ---- Syncing the filaments from the AMS --------------------------------------------------------------------- + +TEST_CASE("the filaments sync from the AMS of a connected printer of the selected model, and map only for a project with objects", + "[Operations]") +{ + AmsSyncState ready; + ready.printer = true; + ready.printer_name = "Lab X1C"; + ready.selected_printer = "Bambu Lab X1 Carbon"; + ready.slots_listed = true; + ready.printer_answered = true; + ready.filament_loaded = true; + ready.filament_installed = true; + ready.same_printer = true; + ready.project_has_objects = true; + CHECK_FALSE(ams_sync_refusal(ready, AmsSyncMode::Map)); + CHECK_FALSE(ams_sync_refusal(ready, AmsSyncMode::Overwrite)); + CHECK_FALSE(ams_sync_refusal(ready, std::nullopt)); + + const auto code = [](const AmsSyncState& state, std::optional mode) { + const std::optional refusal = ams_sync_refusal(state, mode); + return refusal ? std::string(refusal->code) : std::string("(none)"); + }; + AmsSyncState none; + CHECK(code(none, AmsSyncMode::Overwrite) == "no_printer"); + CHECK(ams_sync_refusal(none, std::nullopt)->english() == "Connect a printer to synchronize the AMS filament list."); + + // A printer that answered with no slot has no filament system; one that did not answer is not connected. + AmsSyncState no_slots = ready; + no_slots.slots_listed = false; + CHECK(code(no_slots, AmsSyncMode::Overwrite) == "no_filament_system"); + CHECK_THAT(ams_sync_refusal(no_slots, AmsSyncMode::Overwrite)->english(), Catch::Matchers::ContainsSubstring("Lab X1C is connected")); + no_slots.printer_answered = false; + CHECK(code(no_slots, AmsSyncMode::Overwrite) == "not_connected"); + CHECK_THAT(ams_sync_refusal(no_slots, AmsSyncMode::Overwrite)->english(), Catch::Matchers::ContainsSubstring("Bambu Lab X1 Carbon")); + + AmsSyncState empty = ready; + empty.filament_loaded = false; + CHECK(code(empty, AmsSyncMode::Map) == "unknown_filaments"); + empty.filament_installed = false; + CHECK(code(empty, AmsSyncMode::Map) == "no_filament"); + + AmsSyncState other = ready; + other.same_printer = false; + CHECK(code(other, AmsSyncMode::Overwrite) == "other_printer"); + + // With no objects the sync dialog does not ask: the list is overwritten, which a call of map is not. + AmsSyncState no_objects = ready; + no_objects.project_has_objects = false; + CHECK(code(no_objects, AmsSyncMode::Map) == "nothing_to_map"); + CHECK(code(no_objects, AmsSyncMode::Overwrite) == "(none)"); + CHECK(code(no_objects, std::nullopt) == "(none)"); +} + +// ---- Plugins ------------------------------------------------------------------------------------------------ + +namespace { + +// The status of `ticket` once it is no longer pending, or Pending after ten seconds. +RefreshRun::Status settled(const RefreshRun& run, RefreshRun::Ticket ticket) +{ + const auto deadline = std::chrono::steady_clock::now() + 10s; + RefreshRun::Status status = run.status(ticket); + while (status.state == RefreshRun::State::Pending && std::chrono::steady_clock::now() < deadline) { + std::this_thread::sleep_for(10ms); + status = run.status(ticket); + } + return status; +} + +Slic3r::PluginDescriptor local_plugin(const std::string& key, const std::string& name, const std::string& version) +{ + Slic3r::PluginDescriptor plugin; + plugin.plugin_key = key; + plugin.name = name; + plugin.version = version; + plugin.plugin_root = "C:/plugins/" + key; + plugin.entry_path = plugin.plugin_root + "/" + key + ".py"; + plugin.metadata_valid = true; + return plugin; +} + +Slic3r::PluginDescriptor cloud_plugin(const std::string& key, const std::string& name, bool installed) +{ + Slic3r::PluginDescriptor plugin; + plugin.plugin_key = key; + plugin.name = name; + plugin.version = "2.0.0"; + plugin.latest_version = "2.1.0"; + plugin.metadata_valid = true; + plugin.cloud = Slic3r::CloudPluginState{}; + plugin.cloud->uuid = key; + if (installed) { + plugin.cloud->installed = true; + plugin.installed_version = "1.0.0"; + plugin.plugin_root = "C:/plugins/" + key; + } + return plugin; +} + +} // namespace + +TEST_CASE("a plugin refresh is pending until its work returns", "[Operations]") +{ + RefreshRun run; + // The case holds the first work until it releases it. Each work notes when it begins and when it returns, so + // the case reads the order on its own thread. + std::promise release; + std::shared_future held = release.get_future().share(); + std::mutex events_mutex; + std::vector events; + const auto note = [&events_mutex, &events](const char* event) { + std::lock_guard lock(events_mutex); + events.emplace_back(event); + }; + const auto noted = [&events_mutex, &events] { + std::lock_guard lock(events_mutex); + return events; + }; + const RefreshRun::Ticket first = run.start([held, note] { + note("first begins"); + held.wait(); + note("first returns"); + }); + CHECK(run.status(first).state == RefreshRun::State::Pending); + // A second refresh while the first runs is a run of its own, which waits for the first. + const RefreshRun::Ticket second = run.start([note] { note("second begins"); }); + CHECK(second != first); + std::this_thread::sleep_for(50ms); + CHECK(run.status(first).state == RefreshRun::State::Pending); + CHECK(run.status(second).state == RefreshRun::State::Pending); + CHECK(noted() == std::vector{"first begins"}); + release.set_value(); + CHECK(settled(run, first).state == RefreshRun::State::Done); + CHECK(settled(run, second).state == RefreshRun::State::Done); + CHECK(noted() == std::vector{"first begins", "first returns", "second begins"}); + + // A work that throws leaves its run failed, with what it threw, and the work asked for after it still runs. + std::promise release_failing; + std::shared_future failing_held = release_failing.get_future().share(); + const RefreshRun::Ticket third = run.start([failing_held] { + failing_held.wait(); + throw std::runtime_error("the plugin hub did not answer"); + }); + const RefreshRun::Ticket fourth = run.start([note] { note("fourth begins"); }); + CHECK(third != second); + CHECK(fourth != third); + release_failing.set_value(); + const RefreshRun::Status failed = settled(run, third); + CHECK(failed.state == RefreshRun::State::Failed); + CHECK(failed.error == "the plugin hub did not answer"); + CHECK(settled(run, fourth).state == RefreshRun::State::Done); + CHECK(noted().back() == "fourth begins"); + // The first run's status stays as it ended, and a ticket never given is no run. + CHECK(run.status(first).state == RefreshRun::State::Done); + CHECK(run.status(RefreshRun::Ticket{}).state == RefreshRun::State::Failed); + + // An object that goes away while one work runs and another waits leaves both to run, in turn. + auto order = std::make_shared>(); + auto order_mutex = std::make_shared(); + std::promise release_last; + std::shared_future last_held = release_last.get_future().share(); + std::promise last_ran; + std::future last_done = last_ran.get_future(); + { + RefreshRun gone; + gone.start([last_held, order, order_mutex] { + last_held.wait(); + std::lock_guard lock(*order_mutex); + order->push_back(1); + }); + gone.start([order, order_mutex, done = std::make_shared>(std::move(last_ran))] { + { + std::lock_guard lock(*order_mutex); + order->push_back(2); + } + done->set_value(); + }); + } + release_last.set_value(); + REQUIRE(last_done.wait_for(10s) == std::future_status::ready); + std::lock_guard lock(*order_mutex); + CHECK(*order == std::vector{1, 2}); +} + +TEST_CASE("a refresh's ticket reads how its own run ended however many refreshes end after it", "[Operations]") +{ + RefreshRun run; + const RefreshRun::Ticket returned = run.start([] {}); + const RefreshRun::Ticket threw = run.start([] { throw std::runtime_error("the plugin hub did not answer"); }); + RefreshRun::Ticket last; + for (int i = 0; i < 200; ++i) + last = run.start([] {}); + REQUIRE(settled(run, last).state == RefreshRun::State::Done); + CHECK(run.status(returned).state == RefreshRun::State::Done); + const RefreshRun::Status failed = run.status(threw); + CHECK(failed.state == RefreshRun::State::Failed); + CHECK(failed.error == "the plugin hub did not answer"); +} + +TEST_CASE("a wait that last saw its refresh pending returns how it ended, however many refreshes end meanwhile", + "[Operations]") +{ + RefreshRun run; + std::promise release_run; + std::shared_future run_held = release_run.get_future().share(); + const RefreshRun::Ticket ticket = run.start([run_held] { run_held.wait(); }); + // The waiter is held in its `cancelled`, which it asks after it has seen the run pending, until the case lets it go. + std::promise asked; + std::future waiter_held = asked.get_future(); + std::promise release_waiter; + std::shared_future waiter_go = release_waiter.get_future().share(); + std::atomic first{true}; + auto cancelled = [&asked, &first, waiter_go] { + if (first.exchange(false)) { + asked.set_value(); + waiter_go.wait(); + } return false; - for (const auto& [name, schema] : command.input_schema.at("properties").items()) - if (name != "silent") - return true; - return false; + }; + auto waited = std::async(std::launch::async, [&] { return wait_for_refresh(run, ticket, cancelled, 1ms); }); + REQUIRE(waiter_held.wait_for(5s) == std::future_status::ready); + // Its run and two hundred more end while it is held. + release_run.set_value(); + RefreshRun::Ticket last; + for (int i = 0; i < 200; ++i) + last = run.start([] {}); + REQUIRE(settled(run, last).state == RefreshRun::State::Done); + release_waiter.set_value(); + REQUIRE(waited.wait_for(5s) == std::future_status::ready); + const std::optional status = waited.get(); + REQUIRE(status.has_value()); + CHECK(status->state == RefreshRun::State::Done); +} + +TEST_CASE("a wait for a plugin refresh stops when its call is cancelled, and the refresh goes on", "[Operations]") +{ + RefreshRun run; + std::promise release; + std::shared_future held = release.get_future().share(); + const RefreshRun::Ticket ticket = run.start([held] { held.wait(); }); + std::atomic cancel{false}; + auto waited = std::async(std::launch::async, [&] { return wait_for_refresh(run, ticket, [&cancel] { return cancel.load(); }, 10ms); }); + // While the refresh runs and nothing cancels, the wait goes on. + CHECK(waited.wait_for(200ms) == std::future_status::timeout); + cancel = true; + REQUIRE(waited.wait_for(5s) == std::future_status::ready); + // Stopped, while the refresh still runs. + CHECK_FALSE(waited.get().has_value()); + CHECK(run.status(ticket).state == RefreshRun::State::Pending); + release.set_value(); + CHECK(settled(run, ticket).state == RefreshRun::State::Done); + + // A wait on a refresh that has ended returns its status, Done or Failed with its text. + const std::optional done = wait_for_refresh(run, ticket, [] { return false; }, 10ms); + REQUIRE(done.has_value()); + CHECK(done->state == RefreshRun::State::Done); + const RefreshRun::Ticket failing = run.start([] { throw std::runtime_error("the plugin hub did not answer"); }); + const std::optional failed = wait_for_refresh(run, failing, [] { return false; }, 10ms); + REQUIRE(failed.has_value()); + CHECK(failed->state == RefreshRun::State::Failed); + CHECK(failed->error == "the plugin hub did not answer"); +} + +TEST_CASE("the plugin list gives each plugin's key, name, version, state, capabilities and error", "[Operations]") +{ + Slic3r::PluginDescriptor loaded = local_plugin("loaded_key", "Loaded", "1.2.0"); + Slic3r::PluginDescriptor broken = local_plugin("broken_key", "Broken", "0.1.0"); + broken.error = " the package has no entry point \n"; + Slic3r::PluginDescriptor loading = local_plugin("loading_key", "Loading", "3.0.0"); + Slic3r::PluginDescriptor offered = cloud_plugin("cloud_offered", "Offered", false); + Slic3r::PluginDescriptor mine = cloud_plugin("cloud_mine", "Mine", true); + mine.cloud->is_mine = true; + + std::map runtime; + runtime["loaded_key"].loaded = true; + runtime["loaded_key"].capabilities = {{"Run it", "script", true}, {"Read it", "importer", false}}; + runtime["loading_key"].loading = true; + + const std::vector rows = plugin_rows_from({loaded, broken, loading, offered, mine}, runtime); + REQUIRE(rows.size() == 5); + + CHECK(rows[0].key == "loaded_key"); + CHECK(rows[0].name == "Loaded"); + CHECK(rows[0].version == "1.2.0"); + CHECK(rows[0].installed); + CHECK(rows[0].enabled); + CHECK(rows[0].status == "Activated"); + CHECK(rows[0].source == "local"); + CHECK(rows[0].error.empty()); + REQUIRE(rows[0].capabilities.size() == 2); + CHECK(rows[0].capabilities[0].name == "Run it"); + CHECK(rows[0].capabilities[0].type == "script"); + CHECK(rows[0].capabilities[0].enabled); + CHECK(rows[0].capabilities[1].name == "Read it"); + CHECK(rows[0].capabilities[1].type == "importer"); + CHECK_FALSE(rows[0].capabilities[1].enabled); + + // An error is the row's, trimmed, and a plugin not loaded has no capabilities. + CHECK(rows[1].key == "broken_key"); + CHECK(rows[1].installed); + CHECK_FALSE(rows[1].enabled); + CHECK(rows[1].status == "Error"); + CHECK(rows[1].error == "the package has no entry point"); + CHECK(rows[1].capabilities.empty()); + + CHECK(rows[2].status == "Loading"); + CHECK_FALSE(rows[2].enabled); + + // A cloud plugin not installed shows the latest version offered; one installed, the version on disk. + CHECK(rows[3].key == "cloud_offered"); + CHECK_FALSE(rows[3].installed); + CHECK(rows[3].version == "2.1.0"); + CHECK(rows[3].source == "subscribed"); + CHECK(rows[3].status == "Inactive"); + CHECK(rows[4].installed); + CHECK(rows[4].version == "1.0.0"); + CHECK(rows[4].source == "mine"); +} + +// ---- The catalog names its operations ------------------------------------------------------------------ +// +// A command that changes something either names the operations (GUI/Operations) it reaches or is listed +// here with the reason it reaches none. The list is what a new command has to be added to, or kept off, in +// plain sight. It says how an entry is classified; it does not check what its function calls, which +// scripts/check_operation_calls.py does for the owner calls an operation stands for. + +namespace { + +// Whether `command` is under the rule: it changes something, and it is not the Design tab's, whose commands +// act on the tab's document, which no operation stands for. Listed or not. +bool under_operations_rule(const Slic3r::GUI::NativeCommand& command) +{ + return !command.read_only && command.group != Slic3r::GUI::kDesignGroup; } // Every function of GUI/Operations a catalog entry may name. @@ -378,7 +2039,15 @@ const std::set kOperations = { "start_gcode_export", "export_sliced_3mf", "export_model_3mf", "export_stl", "send_gcode_to_host", "import_models", "open_project", "new_project", "save_project_as", "set_instance_count", "select_plate", "set_plate_locked", "start_arrange", "start_slice", "show_layer_range", - "resolve_preset", "select_preset", "assign_filament_preset", "import_presets", + "resolve_preset", "select_preset", "assign_filament_preset", "import_presets", "delete_objects", + "rename_object", "separate_instances", "split_object", "assemble_objects", "change_part_type", + "order_objects", "mirror_objects", "center_objects", "scale_to_fit", "drop_objects", + "orient_objects", "add_primitive", "delete_plate", "duplicate_plate", "rename_plate", + "set_objects_printable", "set_objects_auto_drop", "fix_objects", "clone_objects", "reload_parts", "replace_part", + "add_filament_slot", "delete_filament_slot", "add_mixed_filament", "sync_presets", "export_toolpaths_obj", + "printer_models", "install_printers", "uninstall_printers", "install_filaments", "uninstall_filaments", + "set_preferences", "set_plugin_enabled", "uninstall_plugin", "reload_plugin", "start_plugin_refresh", + "reorder_objects", "sync_filaments_from_ams", }; // What an exception is, so that the reason reads the same for every entry of a kind. @@ -386,61 +2055,62 @@ constexpr const char* kRunsWhatItIsGiven = "runs what its arguments name, which constexpr const char* kDrivesTheGui = "drives the GUI as a person does: the widget it acts on decides what happens"; constexpr const char* kSessionState = "changes the automation session (jobs, the journal, recordings), not the project"; constexpr const char* kOneEntryPoint = "its function has one automation entry point, so no second caller can drift from it"; -constexpr const char* kAsks = "the asking path: it calls the owner's method, which asks the person"; constexpr const char* kHistory = "it calls the undo and redo of the history it names, which no operation stands for"; +constexpr const char* kRowAdds = "it runs its menu row's function, which adds an object, a part, a plate or a filament slot"; +constexpr const char* kRowOpens = "it runs its menu row's function, which opens a window, a panel or a web page for a person"; +constexpr const char* kRowAppSetting = "it runs its menu row's function, which changes a setting of the app, not the project"; -const std::map kToolExceptions = { - {"run_replay", kRunsWhatItIsGiven}, - {"run_script", kRunsWhatItIsGiven}, - {"run_action", kRunsWhatItIsGiven}, - {"call_tool", kRunsWhatItIsGiven}, - {"run_javascript", kRunsWhatItIsGiven}, - {"click", kDrivesTheGui}, - {"set_widget_value", kDrivesTheGui}, - {"press_keys", kDrivesTheGui}, +const std::map kExceptions = { + // The typed tools. + {"replay_run", kRunsWhatItIsGiven}, + {"script_run", kRunsWhatItIsGiven}, + {"action_run", kRunsWhatItIsGiven}, + {"tool_call", kRunsWhatItIsGiven}, + {"webview_run_javascript", kRunsWhatItIsGiven}, + {"widget_click", kDrivesTheGui}, + {"widget_set_value", kDrivesTheGui}, + {"keyboard_press", kDrivesTheGui}, {"mouse_gesture", kDrivesTheGui}, - {"pick_gizmo_file", kDrivesTheGui}, - {"answer_dialog", kDrivesTheGui}, - {"auto_answer_dialogs", kDrivesTheGui}, - {"set_window", kDrivesTheGui}, - {"cancel_job", kSessionState}, - {"export_replay", kSessionState}, - {"start_recording", kSessionState}, - {"stop_recording", kSessionState}, - {"encode_recording", kSessionState}, - {"generate_calibration_test", kOneEntryPoint}, - {"save_preset", kOneEntryPoint}, - {"delete_preset", kOneEntryPoint}, - {"transform", kOneEntryPoint}, - {"add_part", kOneEntryPoint}, - {"select_objects", kOneEntryPoint}, - {"set_height_ranges", kOneEntryPoint}, - {"set_variable_layer_height", kOneEntryPoint}, - {"set_custom_gcode_at_layer", kOneEntryPoint}, -}; - -const std::map kCommandExceptions = { - {"load_project", kAsks}, - {"go_to_tab", kOneEntryPoint}, - {"open_preferences", kOneEntryPoint}, - {"export_stl_multi", kOneEntryPoint}, - {"export_config", kOneEntryPoint}, - {"obj_rename", kOneEntryPoint}, - {"obj_order_by_name", kOneEntryPoint}, - {"obj_order_by_filament", kOneEntryPoint}, - {"obj_order_by_height", kOneEntryPoint}, - {"obj_order_by_size", kOneEntryPoint}, - {"add_primitive_svg", kOneEntryPoint}, - {"add_primitive_cube", kOneEntryPoint}, - {"add_primitive_cylinder", kOneEntryPoint}, - {"add_primitive_sphere", kOneEntryPoint}, - {"add_primitive_cone", kOneEntryPoint}, - {"add_primitive_disc", kOneEntryPoint}, - {"add_primitive_torus", kOneEntryPoint}, - {"install_local_plugin", kOneEntryPoint}, - {"filament_delete", kOneEntryPoint}, + {"gizmo_pick_file", kDrivesTheGui}, + {"dialog_answer", kDrivesTheGui}, + {"dialog_auto_answer", kDrivesTheGui}, + {"window_set", kDrivesTheGui}, + {"job_cancel", kSessionState}, + {"replay_export", kSessionState}, + {"recording_start", kSessionState}, + {"recording_stop", kSessionState}, + {"recording_encode", kSessionState}, + {"calibration_generate_test", kOneEntryPoint}, + {"preset_save", kOneEntryPoint}, + {"preset_delete", kOneEntryPoint}, + {"object_transform", kOneEntryPoint}, + {"part_add", kOneEntryPoint}, + {"object_select", kOneEntryPoint}, + {"object_set_height_ranges", kOneEntryPoint}, + {"object_set_variable_layer_height", kOneEntryPoint}, + {"plate_set_custom_gcode", kOneEntryPoint}, + {"settings_set", kOneEntryPoint}, + {"plate_set_settings", kOneEntryPoint}, + {"project_set_settings", kOneEntryPoint}, + // The commands made from menu rows, which run their rows' functions. + {"object_add_handy_model", kRowAdds}, + {"object_add_text", kRowAdds}, + {"object_add_svg", kRowAdds}, + {"plate_add", kRowAdds}, + {"window_open", kRowOpens}, + {"app_open_web_page", kRowOpens}, + {"app_show_config_folder", kRowOpens}, + {"script_toggle_panel", "it runs its menu row's function, which shows or hides the Run Script panel for a person"}, + {"settings_set_mode", kRowAppSetting}, + {"settings_toggle_developer_mode", kRowAppSetting}, {"undo", kHistory}, {"redo", kHistory}, + {"preset_export", kOneEntryPoint}, + {"plugin_install_local", kOneEntryPoint}, + {"preset_migrate_filaments", "it runs its menu row's function, which asks before it migrates the legacy user filament presets"}, + {"app_check_for_updates", "it runs its menu row's function, which asks the update server and shows its answer"}, + {"app_benchmark_3d_scene", "it runs its menu row's function, which times the 3D views on a test model in place of the project"}, + {"window_save_screenshot", "it runs its menu row's function, which saves a picture of the main window where recordings go"}, }; } // namespace @@ -501,25 +2171,14 @@ TEST_CASE("a filament pick finds the selector's row that stores the preset, else CHECK(row_for_preset({}, "Bambu ABS") == -1); } -TEST_CASE("a listed command that is not read-only names its operations or is a listed exception", "[Operations]") -{ - for (const Slic3r::GUI::NativeCommand& tool : Slic3r::GUI::NativeCommands::instance().commands()) { - if (!tool.listed || tool.read_only) - continue; - INFO(tool.key); - const bool excepted = kToolExceptions.count(tool.key) != 0; - // One or the other: an exception that names operations has stopped being one. - CHECK(tool.operations.empty() == excepted); - } -} - -TEST_CASE("a palette command that takes arguments names its operations or is a listed exception", "[Operations]") +TEST_CASE("a command that changes something names its operations or is a listed exception", "[Operations]") { for (const Slic3r::GUI::NativeCommand& command : Slic3r::GUI::NativeCommands::instance().commands()) { - if (!palette_command_with_arguments(command)) + if (!under_operations_rule(command)) continue; INFO(command.key); - const bool excepted = kCommandExceptions.count(command.key) != 0; + const bool excepted = kExceptions.count(command.key) != 0; + // One or the other: an exception that names operations has stopped being one. CHECK(command.operations.empty() == excepted); } } @@ -533,54 +2192,46 @@ TEST_CASE("a catalog entry names only operations the layer has", "[Operations]") } } -TEST_CASE("the exception lists name only entries the catalogs have", "[Operations]") +TEST_CASE("the exception list names only commands the catalog has under the rule", "[Operations]") { - for (const auto& [name, reason] : kToolExceptions) { + for (const auto& [name, reason] : kExceptions) { INFO(name << ": " << reason); - const Slic3r::GUI::NativeCommand* tool = Slic3r::GUI::NativeCommands::find(name); - REQUIRE(tool != nullptr); - CHECK(tool->listed); - // A read-only tool needs no exception. - CHECK_FALSE(tool->read_only); - } - for (const auto& [key, reason] : kCommandExceptions) { - INFO(key << ": " << reason); - const Slic3r::GUI::NativeCommand* command = Slic3r::GUI::NativeCommands::find(key); + const Slic3r::GUI::NativeCommand* command = Slic3r::GUI::NativeCommands::find(name); REQUIRE(command != nullptr); - CHECK(palette_command_with_arguments(*command)); + // A read-only command needs no exception. + CHECK(under_operations_rule(*command)); } } // The Design tab's commands act on its document, which no operation stands for, as // scripts/check_operation_calls.py leaves McpToolsCad.cpp out. -TEST_CASE("the operations rule leaves the Design group out", "[Operations]") +TEST_CASE("the operations rule leaves the Design group and the read-only commands out", "[Operations]") { Slic3r::GUI::NativeCommand tile; - tile.key = "shell"; - tile.group = "Design"; - tile.in_palette = true; - tile.input_schema = {{"type", "object"}, {"properties", {{"thickness", {{"type", "number"}}}, {"silent", {{"type", "boolean"}}}}}}; - CHECK_FALSE(palette_command_with_arguments(tile)); - tile.group = "Commands"; - CHECK(palette_command_with_arguments(tile)); + tile.key = "shell"; + tile.group = "Design"; + CHECK_FALSE(under_operations_rule(tile)); + tile.group = "Objects"; + CHECK(under_operations_rule(tile)); + tile.read_only = true; + CHECK_FALSE(under_operations_rule(tile)); - // With the CAD feature on, no Design command is under the rule, and none is on an exception list. + // With the CAD feature on, no Design command is under the rule, and none is on the exception list. Slic3r::GUI::CommandCatalog catalog; Slic3r::GUI::NativeCommands::register_all_commands(catalog, {true}); for (const Slic3r::GUI::NativeCommand& command : catalog.commands()) { if (command.group != "Design") continue; INFO(command.key); - CHECK_FALSE(palette_command_with_arguments(command)); - CHECK(kToolExceptions.count(command.key) == 0); - CHECK(kCommandExceptions.count(command.key) == 0); + CHECK_FALSE(under_operations_rule(command)); + CHECK(kExceptions.count(command.key) == 0); } } TEST_CASE("the field that names a tool's operations is in no listing", "[Operations]") { - // tools/list and search_actions stay as they are: the field is for the catalog test alone. - const Slic3r::GUI::NativeCommand* tool = Slic3r::GUI::NativeCommands::find("export"); + // tools/list and action_search stay as they are: the field is for the catalog test alone. + const Slic3r::GUI::NativeCommand* tool = Slic3r::GUI::NativeCommands::find("project_export"); REQUIRE(tool != nullptr); REQUIRE_FALSE(tool->operations.empty()); CHECK(tool->input_schema.dump().find("start_gcode_export") == std::string::npos); diff --git a/tests/slic3rutils/test_plugin_host_api.cpp b/tests/slic3rutils/test_plugin_host_api.cpp index 762142061d..bd481126b3 100644 --- a/tests/slic3rutils/test_plugin_host_api.cpp +++ b/tests/slic3rutils/test_plugin_host_api.cpp @@ -654,7 +654,7 @@ TEST_CASE("a script reads the catalog", "[PluginHost][Python]") py::exec(R"PY( import orca tools = orca.host.tools -state = tools.describe("get_app_state") +state = tools.describe("app_state") commands = tools.list() names = [entry["name"] for entry in commands] fields = sorted(commands[0]) @@ -666,7 +666,7 @@ try: except tools.ToolError as error: unknown = (str(error), error.details) try: - tools.describe("get_app_stat") + tools.describe("app_stat") mistyped = None except tools.ToolError as error: mistyped = error.details @@ -679,18 +679,18 @@ except tools.ToolError as error: Slic3r::PluginOperations::instance().remove_plugin("catalog_reader"); CHECK(scope["state"]["read_only"].cast()); - CHECK(scope["state"]["key"].cast() == "get_app_state"); + CHECK(scope["state"]["key"].cast() == "app_state"); CHECK(scope["state"].contains("input_schema")); CHECK(py::len(scope["commands"]) >= 53); const std::vector list_fields{"description", "group", "listed", "name", "read_only", "title"}; CHECK(scope["fields"].cast>() == list_fields); CHECK(scope["plugin_fields"].cast>() == list_fields); const auto names = scope["names"].cast>(); - for (const char* name : {"get_app_state", "obj_arrange", "plugin.catalog_reader.measure"}) { + for (const char* name : {"app_state", "object_mirror", "plugin.catalog_reader.measure"}) { CAPTURE(name); CHECK(std::count(names.begin(), names.end(), name) == 1); } - CHECK(scope["operation"]["group"].cast() == "api"); + CHECK(scope["operation"]["group"].cast() == "Plugins"); CHECK(scope["operation"]["read_only"].cast()); REQUIRE_FALSE(scope["unknown"].is_none()); CHECK(scope["unknown"].cast()[0].cast() == "Unknown tool: nope"); @@ -700,9 +700,9 @@ except tools.ToolError as error: REQUIRE_FALSE(scope["mistyped"].is_none()); const auto close = scope["mistyped"]["did_you_mean"].cast>(); REQUIRE_FALSE(close.empty()); - CHECK(close.front() == "get_app_state"); + CHECK(close.front() == "app_state"); - // search_python_api documents both, as it does every function of the package. + // script_search_api documents both, as it does every function of the package. std::set documented; for (const nlohmann::json& entry : Slic3r::GUI::Mcp::python_api_reference()) if (entry["kind"] == "function" && !entry["doc"].get().empty()) @@ -713,7 +713,7 @@ except tools.ToolError as error: TEST_CASE("every public member of the orca package has documentation and named parameters", "[PluginHost][Python]") { - // search_python_api serves this documentation to agents writing scripts and plugins: a member without it, or + // script_search_api serves this documentation to agents writing scripts and plugins: a member without it, or // with a parameter pybind11 names argN, is one they can only guess at. A constant's documentation is // the documentation that names it, and a class's goes on with what its constructors say; an enum's // constructor takes one of the values its documentation lists. diff --git a/tests/slic3rutils/test_python_script_runner.cpp b/tests/slic3rutils/test_python_script_runner.cpp index 7e83f7ac19..405fa1d360 100644 --- a/tests/slic3rutils/test_python_script_runner.cpp +++ b/tests/slic3rutils/test_python_script_runner.cpp @@ -235,7 +235,7 @@ TEST_CASE("code run from a file sees the file's path as __file__, and code under REQUIRE(from_file.status == "finished"); CHECK(from_file.result == json{{"file", path}, {"name", "__main__"}}); - const PythonRunOutcome from_name = run_file("", code); + const PythonRunOutcome from_name = run_file("", code); REQUIRE(from_name.status == "finished"); CHECK(from_name.result["file"].is_null()); } @@ -600,7 +600,7 @@ TEST_CASE("a script that raises reports the exception and its traceback", "[Pyth const PythonRunOutcome out = run("print('before')\nraise ValueError('x')"); CHECK(out.status == "raised"); CHECK(out.message == "ValueError: x"); - CHECK_THAT(out.traceback, ContainsSubstring("")); + CHECK_THAT(out.traceback, ContainsSubstring("")); CHECK_THAT(out.traceback, ContainsSubstring("ValueError: x")); CHECK(out.output == "before\n"); @@ -727,7 +727,7 @@ TEST_CASE("a restricted script's file run reads its own folder and writes nothin namespace { -// Answers tool calls as the MCP core would for a run: get_app_state and run_replay succeed, anything else is +// Answers tool calls as the MCP core would for a run: app_state and replay_run succeed, anything else is // an error. struct FakeBridge : ToolBridge { @@ -757,11 +757,11 @@ struct FakeBridge : ToolBridge if (hook) if (std::optional answer = hook(tool, args)) return *answer; - if (tool == "get_app_state") + if (tool == "app_state") return json{{"ready", true}, {"args", args}}; - if (tool == "run_replay") + if (tool == "replay_run") return json{{"passed", true}}; - throw ToolCallError("Unknown tool: " + tool, json{{"did_you_mean", {"get_app_state"}}}); + throw ToolCallError("Unknown tool: " + tool, json{{"did_you_mean", {"app_state"}}}); } }; @@ -777,7 +777,7 @@ TEST_CASE("a script calls tools through its run's bridge, and an error result ra ScopedToolBridge bound(bridge); const PythonRunOutcome out = run(R"PY( import orca -state = orca.host.tools.call("get_app_state", {"verbose": True}) +state = orca.host.tools.call("app_state", {"verbose": True}) try: orca.host.tools.call("no_such_tool") error = None @@ -788,11 +788,11 @@ result = {"state": state, "error": error} REQUIRE(out.status == "finished"); CHECK(out.result["state"] == json{{"ready", true}, {"args", {{"verbose", true}}}}); CHECK(out.result["error"]["message"] == "Unknown tool: no_such_tool"); - CHECK(out.result["error"]["details"] == json{{"did_you_mean", {"get_app_state"}}}); - CHECK(bridge.calls == std::vector{"get_app_state", "no_such_tool"}); + CHECK(out.result["error"]["details"] == json{{"did_you_mean", {"app_state"}}}); + CHECK(bridge.calls == std::vector{"app_state", "no_such_tool"}); } -TEST_CASE("a script hands run_replay a script given as JSON text as it is, with its vars", "[PythonScript][Python]") +TEST_CASE("a script hands replay_run a script given as JSON text as it is, with its vars", "[PythonScript][Python]") { RunnerHarness harness; if (!harness.initialized) @@ -802,13 +802,13 @@ TEST_CASE("a script hands run_replay a script given as JSON text as it is, with ScopedToolBridge bound(bridge); const PythonRunOutcome out = run(R"PY( import orca -text = '{"orca_replay_version": "0.1.0", "steps": []} // replayed' +text = '{"orca_replay_version": "0.2.0", "steps": []} // replayed' result = orca.host.tools.run_replay(text, {"part": "lid"}) )PY"); REQUIRE(out.status == "finished"); CHECK(out.result == json{{"passed", true}}); - CHECK(bridge.calls == std::vector{"run_replay"}); - CHECK(bridge.last_args == json{{"replay", R"({"orca_replay_version": "0.1.0", "steps": []} // replayed)"}, {"vars", {{"part", "lid"}}}}); + CHECK(bridge.calls == std::vector{"replay_run"}); + CHECK(bridge.last_args == json{{"replay", R"({"orca_replay_version": "0.2.0", "steps": []} // replayed)"}, {"vars", {{"part", "lid"}}}}); } TEST_CASE("a run waits for the non-daemon threads it starts, which call tools through it", "[PythonScript][Python]") @@ -820,10 +820,10 @@ TEST_CASE("a run waits for the non-daemon threads it starts, which call tools th FakeBridge bridge; ScopedToolBridge bound(bridge); const PythonRunOutcome out = run("import orca, threading, time\n" - "def work():\n time.sleep(0.2)\n orca.host.tools.call('get_app_state')\n" + "def work():\n time.sleep(0.2)\n orca.host.tools.call('app_state')\n" "threading.Thread(target=work).start()\n"); CHECK(out.status == "finished"); - CHECK(bridge.calls == std::vector{"get_app_state"}); + CHECK(bridge.calls == std::vector{"app_state"}); } TEST_CASE("a run on a thread Python didn't start waits for the threads it starts", "[PythonScript][Python]") @@ -838,12 +838,12 @@ TEST_CASE("a run on a thread Python didn't start waits for the threads it starts std::thread job([&] { ScopedToolBridge bound(bridge); out = run("import orca, threading, time\n" - "def work(orca=orca, time=time):\n time.sleep(0.2)\n orca.host.tools.call('get_app_state')\n" + "def work(orca=orca, time=time):\n time.sleep(0.2)\n orca.host.tools.call('app_state')\n" "threading.Thread(target=work).start()\n"); }); job.join(); CHECK(out.status == "finished"); - CHECK(bridge.calls == std::vector{"get_app_state"}); + CHECK(bridge.calls == std::vector{"app_state"}); } TEST_CASE("a thread started just before the code returns is waited for", "[PythonScript][Python]") @@ -855,9 +855,9 @@ TEST_CASE("a thread started just before the code returns is waited for", "[Pytho FakeBridge bridge; ScopedToolBridge bound(bridge); CHECK(run("import orca, threading\n" - "threading.Thread(target=lambda: orca.host.tools.call('get_app_state')).start()\n") + "threading.Thread(target=lambda: orca.host.tools.call('app_state')).start()\n") .status == "finished"); - CHECK(bridge.calls == std::vector{"get_app_state"}); + CHECK(bridge.calls == std::vector{"app_state"}); } TEST_CASE("a thread started by another of the run's threads after the code returned is waited for", "[PythonScript][Python]") @@ -869,11 +869,11 @@ TEST_CASE("a thread started by another of the run's threads after the code retur FakeBridge bridge; ScopedToolBridge bound(bridge); CHECK(run("import orca, threading, time\n" - "def second():\n time.sleep(0.3)\n orca.host.tools.call('get_app_state')\n" + "def second():\n time.sleep(0.3)\n orca.host.tools.call('app_state')\n" "def first():\n time.sleep(0.3)\n threading.Thread(target=second).start()\n" "threading.Thread(target=first).start()\n") .status == "finished"); - CHECK(bridge.calls == std::vector{"get_app_state"}); + CHECK(bridge.calls == std::vector{"app_state"}); } TEST_CASE("a callback already running when the code returns is waited for, and the thread it starts too", "[PythonScript][Python]") @@ -902,14 +902,14 @@ TEST_CASE("a callback already running when the code returns is waited for, and t if (!run_scope->callback_entering()) return; py_run("import orca, threading, time, _cb\n_cb.entered.set()\ntime.sleep(0.3)\n" - "threading.Thread(target=lambda: orca.host.tools.call('get_app_state')).start()\n"); + "threading.Thread(target=lambda: orca.host.tools.call('app_state')).start()\n"); run_scope->callback_left(); }); }; const PythonRunOutcome out = run("import orca, _cb\norca.host.tools.call('capture_run')\n_cb.entered.wait(10)\n"); callback.join(); CHECK(out.status == "finished"); - CHECK(bridge.calls == std::vector{"capture_run", "get_app_state"}); + CHECK(bridge.calls == std::vector{"capture_run", "app_state"}); } TEST_CASE("a raw thread can't start a thread after its run has ended", "[PythonScript][Python]") @@ -940,10 +940,10 @@ TEST_CASE("a script that exits with sys.exit(0) still waits for its threads", "[ FakeBridge bridge; ScopedToolBridge bound(bridge); CHECK(run("import orca, sys, threading, time\n" - "def work():\n time.sleep(0.2)\n orca.host.tools.call('get_app_state')\n" + "def work():\n time.sleep(0.2)\n orca.host.tools.call('app_state')\n" "threading.Thread(target=work).start()\nsys.exit(0)\n") .status == "finished"); - CHECK(bridge.calls == std::vector{"get_app_state"}); + CHECK(bridge.calls == std::vector{"app_state"}); } TEST_CASE("a daemon thread still running after its run is refused tool calls", "[PythonScript][Python]") @@ -956,7 +956,7 @@ TEST_CASE("a daemon thread still running after its run is refused tool calls", " FakeBridge bridge; ScopedToolBridge bound(bridge); REQUIRE(run("import orca, threading, _late\n" - "def work(orca=orca, late=_late):\n late.go.wait(10)\n try:\n orca.host.tools.call('get_app_state')\n" + "def work(orca=orca, late=_late):\n late.go.wait(10)\n try:\n orca.host.tools.call('app_state')\n" " except RuntimeError as e:\n late.error = str(e)\n late.done.set()\n" "threading.Thread(target=work, daemon=True).start()\n") .status == "finished"); @@ -982,7 +982,7 @@ TEST_CASE("a tool call in flight when the run ends finishes before the run does" ScopedToolBridge bound(bridge); const auto start = std::chrono::steady_clock::now(); REQUIRE(run("import orca, threading, _late\n" - "def work(orca=orca, late=_late):\n late.result = orca.host.tools.call('get_app_state')\n" + "def work(orca=orca, late=_late):\n late.result = orca.host.tools.call('app_state')\n" "threading.Thread(target=work, daemon=True).start()\n_late.in_call.wait(10)\n") .status == "finished"); CHECK(std::chrono::steady_clock::now() - start >= std::chrono::seconds(1)); @@ -1010,7 +1010,7 @@ TEST_CASE("a stop during the in-flight wait still ends the run as cancelled", "[ int stops = 0; PythonRunRequest request; request.code = "import orca, threading, _late\n" - "threading.Thread(target=lambda: orca.host.tools.call('get_app_state'), daemon=True).start()\n" + "threading.Thread(target=lambda: orca.host.tools.call('app_state'), daemon=True).start()\n" "_late.in_call.wait(10)\n"; request.identity = kScriptIdentityAgent; request.budget = by_budget ? std::chrono::milliseconds(1000) : std::chrono::minutes(1); @@ -1048,13 +1048,13 @@ TEST_CASE("a task the run submits is waited for and runs inside the run", "[Pyth "pool = libpool_task.POOL\n"; const std::string code = "import orca, time, _kept\n" + make + "_kept.pool = pool\n" - "def task():\n time.sleep(0.3)\n orca.host.tools.call('get_app_state')\n" + "def task():\n time.sleep(0.3)\n orca.host.tools.call('app_state')\n" "pool.submit(task)\n"; FakeBridge bridge; ScopedToolBridge bound(bridge); const PythonRunOutcome out = run_file(macro.write("main.py", code), code, std::chrono::seconds(20)); CHECK(out.status == "finished"); - CHECK(bridge.calls == std::vector{"get_app_state"}); + CHECK(bridge.calls == std::vector{"app_state"}); CHECK(shared.get("pool._shutdown") == (where != "library")); if (where == "library") { CHECK(py_json("__import__('_kept').pool.submit(int, '3').result()") == 3); @@ -1078,11 +1078,11 @@ TEST_CASE("a pool worker another run started runs this run's task inside this ru } { ScopedToolBridge bound(bridge_b); - REQUIRE(run("import orca, _kept\n_kept.pool.submit(lambda: orca.host.tools.call('get_app_state')).result()\n").status == + REQUIRE(run("import orca, _kept\n_kept.pool.submit(lambda: orca.host.tools.call('app_state')).result()\n").status == "finished"); } CHECK(bridge_a.calls.empty()); - CHECK(bridge_b.calls == std::vector{"get_app_state"}); + CHECK(bridge_b.calls == std::vector{"app_state"}); py_run("import _kept\n_kept.pool.shutdown()\n"); } @@ -1171,11 +1171,11 @@ TEST_CASE("a task's done callbacks run inside the run that submitted it, and it shared.set("release"); }); const PythonRunOutcome out = run("import orca, time, _cb\n" - "def cb(future):\n time.sleep(0.3)\n print('callback ran')\n orca.host.tools.call('get_app_state')\n" + "def cb(future):\n time.sleep(0.3)\n print('callback ran')\n orca.host.tools.call('app_state')\n" "_cb.pool.submit(_cb.release.wait, 10).add_done_callback(cb)\n"); releaser.join(); CHECK(out.status == "finished"); - CHECK(bridge.calls == std::vector{"get_app_state"}); + CHECK(bridge.calls == std::vector{"app_state"}); CHECK_THAT(out.output, ContainsSubstring("callback ran")); py_run("import _cb\n_cb.pool.shutdown()\n"); } @@ -1268,12 +1268,12 @@ TEST_CASE("a pool's initializer runs inside the run that started its worker", "[ FakeBridge bridge; ScopedToolBridge bound(bridge); const PythonRunOutcome out = run("import orca\nfrom concurrent.futures import ThreadPoolExecutor\n" - "def init():\n print('init ran')\n orca.host.tools.call('get_app_state')\n" + "def init():\n print('init ran')\n orca.host.tools.call('app_state')\n" "pool = ThreadPoolExecutor(1, initializer=init)\nresult = pool.submit(int, '5').result(10)\n"); CHECK(out.status == "finished"); CHECK(out.result == 5); CHECK_THAT(out.output, ContainsSubstring("init ran")); - CHECK(bridge.calls == std::vector{"get_app_state"}); + CHECK(bridge.calls == std::vector{"app_state"}); } TEST_CASE("a pool's initializer in a plugin's run runs under the plugin's identity", "[PythonScript][Python]") @@ -1311,13 +1311,13 @@ TEST_CASE("a run waits for a pool's initializer whose task it cancelled", "[Pyth }); const PythonRunOutcome out = run("import orca, _ini\nfrom concurrent.futures import ThreadPoolExecutor\n" "def init():\n _ini.entered.set()\n _ini.go.wait(10)\n print('init done')\n" - " orca.host.tools.call('get_app_state')\n" + " orca.host.tools.call('app_state')\n" "pool = ThreadPoolExecutor(1, initializer=init)\nf = pool.submit(int)\n_ini.entered.wait(10)\n" "cancelled = f.cancel()\n"); releaser.join(); CHECK(out.status == "finished"); CHECK_THAT(out.output, ContainsSubstring("init done")); - CHECK(bridge.calls == std::vector{"get_app_state"}); + CHECK(bridge.calls == std::vector{"app_state"}); } TEST_CASE("a thread of an ended run can't start a pool worker whose initializer would run outside it", "[PythonScript][Python]") @@ -1471,9 +1471,9 @@ TEST_CASE("an untagged pool is still a pool to a run", "[PythonScript][Python]") FakeBridge bridge; ScopedToolBridge bound(bridge); const auto start = std::chrono::steady_clock::now(); - CHECK(run("import orca, _kept\n_kept.pool.submit(lambda: orca.host.tools.call('get_app_state'))\n").status == "finished"); + CHECK(run("import orca, _kept\n_kept.pool.submit(lambda: orca.host.tools.call('app_state'))\n").status == "finished"); CHECK(std::chrono::steady_clock::now() - start < std::chrono::seconds(5)); - CHECK(bridge.calls == std::vector{"get_app_state"}); + CHECK(bridge.calls == std::vector{"app_state"}); py_run("import _kept\n_kept.pool.shutdown()\n"); } @@ -1759,7 +1759,7 @@ TEST_CASE("a window callback of a run is refused tool calls", "[PythonScript][Py ScopedPythonRun in_run(scope, PythonRunThread::Callback); PythonGILState gil; py::dict ns; - py::exec("import orca\ntry:\n orca.host.tools.call('get_app_state')\n error = None\nexcept RuntimeError as e:\n error = str(e)\n", ns); + py::exec("import orca\ntry:\n orca.host.tools.call('app_state')\n error = None\nexcept RuntimeError as e:\n error = str(e)\n", ns); CHECK_THAT(ns["error"].cast(), ContainsSubstring("window callbacks")); CHECK(bridge.calls.empty()); } @@ -1846,10 +1846,10 @@ import orca, threading, _cb def on_message(data): _cb.storage = orca.host.plugin.storage() try: - orca.host.tools.call("get_app_state") + orca.host.tools.call("app_state") except RuntimeError as e: _cb.refused = str(e) - worker = threading.Thread(target=lambda: orca.host.tools.call("get_app_state")) + worker = threading.Thread(target=lambda: orca.host.tools.call("app_state")) worker.start() worker.join() _cb.done.set() @@ -1861,7 +1861,7 @@ _cb.done.wait(10) delivery.join(); CHECK(utf8_path(shared.get("storage").get()) == macro.dir); CHECK_THAT(shared.get("refused").get(), ContainsSubstring("window callbacks")); - CHECK(bridge.calls == std::vector{"take_callback", "get_app_state"}); + CHECK(bridge.calls == std::vector{"take_callback", "app_state"}); } TEST_CASE("a run's callbacks do nothing and its threads open no UI once its UI is closed", "[PythonScript][Python]") @@ -1955,7 +1955,7 @@ TEST_CASE("orca.host.tools refuses code that is neither a plugin nor a script", // Code with no audit identity: a plugin window's callback today. PythonRunRequest request; - request.code = "import orca\ntry:\n orca.host.tools.call('get_app_state')\n result = 'called'\nexcept RuntimeError as e:\n result = str(e)"; + request.code = "import orca\ntry:\n orca.host.tools.call('app_state')\n result = 'called'\nexcept RuntimeError as e:\n result = str(e)"; request.identity = ""; const PythonRunOutcome out = run_python_code(request); REQUIRE(out.status == "finished"); @@ -2055,7 +2055,7 @@ TEST_CASE("a plugin calls tools only from a thread that may wait for the UI thre return json{{"plugin", plugin}}; }); PythonRunRequest request; - request.code = "import orca\ntry:\n result = orca.host.tools.call('get_app_state')\n" + request.code = "import orca\ntry:\n result = orca.host.tools.call('app_state')\n" "except RuntimeError as e:\n result = str(e)"; request.identity = "measure"; @@ -2071,7 +2071,7 @@ TEST_CASE("a plugin calls tools only from a thread that may wait for the UI thre REQUIRE(called.status == "finished"); CHECK(called.result == json{{"plugin", "measure"}}); } - CHECK(calls == std::vector{"measure:get_app_state"}); + CHECK(calls == std::vector{"measure:app_state"}); set_plugin_tool_caller({}); } @@ -2294,7 +2294,7 @@ struct HostedSession std::thread host; std::atomic returned{false}; - static PythonSessionRequest person_session(std::string filename = "") + static PythonSessionRequest person_session(std::string filename = "") { PythonSessionRequest request; request.identity = kScriptIdentityPerson; @@ -2474,7 +2474,7 @@ TEST_CASE("a cell ending in an expression shows its value, and so does a file ru CHECK(file.finished->status == "finished"); CHECK(file.output() == "2\n"); - const PythonRunOutcome agent = run_file("", "1 + 1\n[1, 2]\n"); + const PythonRunOutcome agent = run_file("", "1 + 1\n[1, 2]\n"); CHECK(agent.status == "finished"); CHECK(agent.output.empty()); } diff --git a/tools/mcp/README.md b/tools/mcp/README.md index 80006d3864..8db094b411 100644 --- a/tools/mcp/README.md +++ b/tools/mcp/README.md @@ -10,7 +10,7 @@ Python. It uses only the standard library. `docs/HLSD/mcp-server.md` covers the | `launch [--headless [kwin\|mutter] \| --xvfb] [--cad] [--unrestricted-scripts] [--printer "@"] [--vendor V] [--filament F] [--datadir DIR] [--port N] [--bin PATH] [--print-config] [-- app args]` | Start OrcaSlicer with `--mcp`, wait until it is ready, print the session | | `call TOOL [''] [--wait]` | Call a tool and print its JSON result; `--wait` follows a returned job to its result | | `tools` | List the tools, with the first line of each description | -| `widgets ['']` | Print the `list_widgets` tree | +| `widgets ['']` | Print the `widget_list` tree | | `screenshot OUT [--target main\|canvas\|dialog]` | Save a full-size PNG, replacing `OUT` if it exists | | `run-replay FILE [--out DIR]` | Run a replay in the launched instance and print the result; exit 0 when it passes | | `stop` | Stop the app and its private display, and remove the session | @@ -26,7 +26,7 @@ screen, and the tests' views and screenshots all have one size; the tests that s the same 1600×900. `--cad` starts the app with `--cad`, which turns the Design (CAD) tab on for that run, and with it its commands, and `--unrestricted-scripts` starts it with `--unrestricted-scripts`, which lets Python scripts -(`run_script`) run unrestricted for that run. Neither writes the datadir's `OrcaSlicer.conf`, and a later +(`script_run`) run unrestricted for that run. Neither writes the datadir's `OrcaSlicer.conf`, and a later launch without them has the settings the datadir holds. The token comes from `ORCA_MCP_TOKEN` or is generated, and it reaches the app through the environment, not the command line. On Linux, `launch` also sets `SSL_CERT_FILE`, so a fresh datadir doesn't prompt for a CA @@ -75,14 +75,14 @@ sys.path.insert(0, "tools/mcp") from orca_mcp import OrcaMcp, McpError orca = OrcaMcp(port=13619, token=os.environ["ORCA_MCP_TOKEN"]) -orca.call("open_files", paths=["/abs/path/part.stl"]) -result = orca.await_job(orca.call("slice")) # follows a job envelope to the end -orca.call("wait", **{"for": "idle"}) # "for" is a Python keyword -info, pngs = orca.images("screenshot", target="canvas") +orca.call("project_import", paths=["/abs/path/part.stl"]) +result = orca.await_job(orca.call("plate_slice")) # follows a job envelope to the end +orca.call("app_wait", **{"for": "idle"}) # "for" is a Python keyword +info, pngs = orca.images("window_screenshot", target="canvas") ``` `call()` returns the tool's JSON result and raises `McpError` when the tool reports an error. -`call_with_text()` also returns the text blocks after the JSON one, such as `list_widgets`'s tree. +`call_with_text()` also returns the text blocks after the JSON one, such as `widget_list`'s tree. `images()` also returns the PNG bytes of the image blocks. `call_raw()` returns the MCP result unchanged. With `ORCA_MCP_CALL_LOG` set to a file, every call appends a JSON line with its tool, its time in milliseconds and whether it succeeded, which shows where a test spends its time. @@ -109,25 +109,28 @@ unverified, which matters only for a symlinked binary. When the file is missing, port it names fails (nothing listens there, or another server answers), `from_datadir()` raises `McpError` saying so, with the failure as its cause. -`call_command(tool, **args)` calls `call_tool {tool, args}`, follows a running job to its end and +`call_command(tool, **args)` calls `tool_call {tool, args}`, follows a running job to its end and returns the command's whole reply, which for a Design command is `{"result": ...}`. A call whose first reply says a dialog blocks it fails at once, naming the dialog, rather than waiting on it. A call that -first replied `running` and opens a dialog later is waited on up to the timeout (600 s), since `wait` +first replied `running` and opens a dialog later is waited on up to the timeout (600 s), since `app_wait` reports only that its job is still running. Every `McpError` it raises starts with the command's name -(`"extrude: ..."`) and has the original error as its cause. `search_tools {group: "Design"}` names the -Design commands, and `search_tools {tool}` gives one's arguments and examples. +(`"extrude: ..."`) and has the original error as its cause. `tool_search {group: "Design"}` names the +Design commands, and `tool_search {tool}` gives one's arguments and examples. -## The skill's list of commands +## The skill's list of tiles `gen_skill_reference.py [--check]` writes `skills/orcaslicer-mcp-skills/references/actions.md` in a checkout of the orcaslicer-mcp-skills repository: -the Speed Dial's commands section by section, each with its key, title, arguments and description, from -the command reference `tests/data/command_catalog.json` (`docs/HLSD/mcp-server.md`, "Making a feature -reachable"), and before them what the reference says of particular commands: those with one form, which -needs its value, and the typed tools that are tiles too. A command has a row of its own when it has a tile -of its own (`in_palette`); each Design menu row folded into a command follows it as a row with the -command's key, the row's title and the arguments that open its tool (`sketch_pattern` with -`{"type": "linear"}` for Linear array). It needs no running app. With `--check` it writes +the Speed Dial's tiles section by section, from the command reference `tests/data/command_catalog.json` +(`docs/HLSD/mcp-server.md`, "Making a feature reachable"), and before them what the reference says of +particular commands: the Design commands with one form, which needs its value, and the commands of tiles +the tool list does not show. Outside the Design tab a section is a Speed Dial section (a tile's `group`, or +the `tile_group` of a command's own tile), and each tile has a row with its key, its title, the command and +arguments it runs (`project_export {"format": "gcode"}` for Export G-code) and its description. In the +Design section a command has a row of its own when it has a tile of its own (`in_palette`), and each Design +menu row folded into a command follows it as a row with the command's key, the row's title and the +arguments that open its tool (`sketch_pattern` with `{"type": "linear"}` for Linear array). It needs no +running app. With `--check` it writes nothing, prints the difference and exits 1 when the file is not what it would write. When a command changed, regenerate the reference first: run `slic3rutils_tests "[Reference]"` with `ORCA_UPDATE_COMMAND_REFERENCE=1` in the environment. @@ -175,10 +178,11 @@ the run that outlives its reply budget runs with the budget capped at 4 s (`ORCA `test_plugin_tools.py` checks a plugin's calls into the tools in the running app: it side-loads `tests/plugins/mcp_tools_fixture` into a fresh data folder and launches twice: over MCP, with the Design tab -on (its operation is reached through `search_tools` and `call_tool` and stays out of `tools/list`, a Speed -Dial command is found among `search_tools`' commands with its schema and not again among its actions, a -Design command is found there too, in no section of its own, calls from its Script worker -and a thread it starts reach the tools, an auto-answer rule it sets is the plugin's, `export_replay` is +on (its operation is in the group Plugins, reached through `tool_search` and `tool_call` and out of +`tools/list`; a menu row's command is found among `tool_search`'s commands with its schema and its tile not +among its actions, and `tool_call` runs it; a group is a place's heading, in any case; a Design command is +found there too, in no section of its own; calls from its Script worker +and a thread it starts reach the tools, an auto-answer rule it sets is the plugin's, `replay_export` is refused, nothing it calls is journaled, a script that finds its progress dialog handle can use it, `tests/plugins/mcp_tools_broken`, whose load fails, offers none of its operations, and unticking the plugin in the Plugins dialog withdraws its operation and ends its rule); and without MCP, @@ -188,7 +192,7 @@ Run Script panel's `.py` files are not driven from here: the panel is hidden fro files through a file picker, so how it reads and saves them is covered by the unit tests of `decode_python_source()` and `encode_python_source()`. -A `.py` file given to `--run` runs as a Python script (`run_script`) instead, exiting 0 when it +A `.py` file given to `--run` runs as a Python script (`script_run`) instead, exiting 0 when it finishes and 1 when it raises, is cancelled or runs out of time; its traceback goes to the log. A script's own file access is held to OrcaSlicer's folders, and it starts no programs or threads and reaches no network, unless scripts run unrestricted: start the app with `--unrestricted-scripts` for one run (as @@ -218,7 +222,7 @@ def main(): window = orca.host.ui.create_window("", on_message=pages.put) pages.get() # the person pressed Go - worker = threading.Thread(target=lambda: print(orca.host.tools.call("get_app_state")["ready"])) + worker = threading.Thread(target=lambda: print(orca.host.tools.call("app_state")["ready"])) worker.start() # waited for before the run ends if __name__ == "__main__": @@ -232,104 +236,118 @@ overlapping runs, imports, pools, `atexit` and Stop. `tests/gizmos.json` drives every gizmo through the GUI tools, the way a person does: each one's icon, its panel's fields, combos, toggles and links, and clicks or strokes at points of the model, then -checks what it left on the model (`list_objects`), with an undo and redo and a canvas screenshot per +checks what it left on the model (`object_list`), with an undo and redo and a canvas screenshot per gizmo. It uses the fixtures beside it (`tests/fixtures/star.svg`, `tests/fixtures/heightmap.png`). -Run it at a second window size through `run_replay`'s `vars`: +Run it at a second window size through `replay_run`'s `vars`: ```bash -tools/mcp/orca_mcp.py call run_replay '{"path": "/abs/tools/mcp/tests/gizmos.json", "out_dir": "/tmp/gizmos-small", "vars": {"window_size": [1100, 760]}}' --wait +tools/mcp/orca_mcp.py call replay_run '{"path": "/abs/tools/mcp/tests/gizmos.json", "out_dir": "/tmp/gizmos-small", "vars": {"window_size": [1100, 760]}}' --wait ``` -`tests/scene.json` checks object structure and placement: `transform` on an instance (the drop after a -scale, `size`, a move to another plate), on a part, what `list_objects` reports of them (bounding boxes -on the bed, filament, the scaled volume, a mirrored part and instance), the selection as `select_objects` and -`get_app_state` report it (parts, whole instances, one instance of two), the shape commands given a size -(`run_action` with `args` `{"size": [...]}`), `arrange` on one plate and every plate, Fill bed, the Speed -Dial no-op that `run_action` reports as an error, `add_part` (shapes at a size and a position, a model +`tests/scene.json` checks object structure and placement: `object_transform` on an instance (the drop after a +scale, `size`, a move to another plate), on a part, what `object_list` reports of them (bounding boxes +on the bed, filament, the scaled volume, a mirrored part and instance), the selection as `object_select` and +`app_state` report it (parts, whole instances, one instance of two), shapes given a size +(`object_add_primitive {shape, size}`), `object_arrange` on one plate and every plate, Fill bed, the Speed +Dial no-op that `action_run` reports as an error, `part_add` (shapes at a size and a position, a model file, one undo step, and what it refuses), and the object structure commands (Change Type, Rename, number of instances, individual objects, Assemble, Order By and its reversal, and what each refuses). It ends with all of them on one scene: a block with a magnet pocket and a boss, sized, moved to a second plate, copied six times and arranged there, split into objects, one mirrored, two assembled, ordered, the plate filled and sliced. -`tests/layers.json` checks height range modifiers: `set_height_ranges` with ranges given out of order, -their read-back in `list_objects`, one undo step (and none for the same ranges again), the layer count -of a slice with them, the refusals (an overlap, a layer height beyond the printer's, a missing filament, -an object setting, an empty range), a range in the second filament, a 3MF round trip, and `[]`. Then -variable layer height profiles on a Benchy with `set_variable_layer_height`: Adaptive called from the +`tests/layers.json` checks height range modifiers: `object_set_height_ranges` with ranges given out of order +and their settings set with `settings_set` (target `height_range`), their read-back in `object_list`, one +undo step each (and none for the same ranges again, which keep their settings), the layer count of a slice +with them, the refusals (an overlap, a layer height beyond the printer's, a missing filament, an object +setting, an empty range), a range in the second filament, a 3MF round trip, and `[]`. Then +variable layer height profiles on a Benchy with `object_set_variable_layer_height`: Adaptive called from the Preview tab, its quality's effect on the point count, the layer count of a slice with it, Smooth as one undo step, Reset and a Reset that changes nothing, the refusals (an argument of another action, the assemble view), Smooth and Adaptive over height ranges, and a 3MF round trip. Last, layer G-codes on a -cube with `set_custom_gcode_at_layer`: refused before a slice, a pause by layer and custom G-code by height called +cube with `plate_set_custom_gcode`: refused before a slice, a pause by layer and custom G-code by height called from Prepare (it shows the Preview), the same code again changing nothing, a removal and an in-place custom edit in one call, the refusals (a layer above the top, a code where another is, nothing to remove, a missing filament, a missing plate, a plate changed since its slice that the Preview does not show), a filament change, a 3MF round trip, and `clear`. +`tests/settings_targets.json` checks `settings_list` (each type whole, a saved preset's and a slot's values, +what an object and a region take) and the settings tools' targets on a cube with a modifier and two height +ranges: a value set on the object, the modifier and a range, each read back by index and from the selection +with the value it prints with and where that comes from, and ranges replaced keeping the settings of the one +that stays. `tests/view_switches.json` checks `view_set`'s sidebar, legend, G-code window, section view and +display switches, each set and read back from its reply and `app_state`; a cube placed in the middle of a +plate from `plate_list`'s origin and size; and `app_state`'s account, network plug-in and configuration folder. +`test_sidebar_floating.py` launches its own app twice, the second time with the sidebar floating in the saved window +layout, and checks that `view_set`'s `sidebar_width` is refused there. + `tests/recording.json` records while it drives the GUI: clicks on the 3D view, a setting typed, the Preferences dialog opened and closed, a slice. It stops the recording (frames, length, size) and encodes it to H.265, then has a nested replay start a recording of the 3D view that it never stops, checks the replay's end closed it, and encodes that to H.264. Short recordings check that a recording has no overlays unless `captions` or `pointer` turns one on, that one started with a path and no `max_seconds` runs under an -hour's limit, and that one started with `encode` is encoded as a job once `stop_recording` reports it, the +hour's limit, and that one started with `encode` is encoded as a job once `recording_stop` reports it, the encode deleting its `.mkv` unless `keep_raw_video_file` keeps it. Its -`new_project` and `stop_recording` calls pass `silent: true`: with no arguments they would do what a +`project_new` and `recording_stop` calls pass `silent: true`: with no arguments they would do what a person's pick does, asking and stopping without a report. The encodes need an ffmpeg with libx265 and libx264 (`ORCA_FFMPEG`, or `ffmpeg` on `PATH`) and are optional without one. Look at the videos, or at frames `ffmpeg -i session.mkv -vf fps=1 frame%02d.png` extracts, for the caption, the pointer and the dialog. -`tests/multicolor.json` assigns filaments to objects and parts through `set_settings`' object and -part scopes, with undo and redo, and reads them back with `get_settings`' effective values. It then -sets the project's slot colours, flushing multiplier, one flushing volume and plate type through the -project scope (in one call, the colour first), checks the refusals that leave everything as it was +`tests/multicolor.json` assigns filaments to objects and parts through `settings_set`'s object and +part targets, with undo and redo, and reads them back with `settings_get`'s effective values. It then +sets the project's slot colours, flushing multiplier, one flushing volume and plate type through +`project_set_settings` (in one call, the colour first), checks the refusals that leave everything as it was (the read-only `filament_is_mixed`, a bad colour, a purge mode the printer has no button for, a non-zero diagonal, a tower off the plate), and moves the prime tower with an undo, before slicing. -`tests/presets.json` saves filament, process and printer presets with `save_preset` (a user preset, +`tests/presets.json` saves filament, process and printer presets with `preset_save` (a user preset, one inside the project that a saved and reopened project keeps, a detached one, and the overwrite -rule), and drops unsaved edits with `set_settings {"reset_all": true}`. It selects a hidden filament, -one the setup wizard has not added, by name. It reads presets that are not selected and compares presets (`get_settings` `preset` and `compare`), writes one entry of a -per-variant value, and checks `set_settings`' `changed` after the spiral vase dialog. It reads what -settings do from `get_settings`' meta (`description`, `where`): by key, for one group, and found by -the words of their descriptions, in one scope and in all three. Keys named without a scope are read -from the scope that has each one, and a key named in the wrong scope is listed with the scope that has -it (`scope_of`) and refused by `set_settings`. It reverts single keys (`null`, `reset_to`), and answers the unsaved-changes prompts: -`select_preset` without `preset_changes` still opens the prompt, `preset_changes` transfers or discards without it, -and `new_project` keeps modified presets unless `preset_changes` is `"discard"`. It ends by deleting the -presets it made with `delete_preset`: filaments the tab edits and does not, a base process and its +rule), and drops unsaved edits with `settings_set {"reset_all": true}`. It selects a filament the selector +does not offer, one the setup wizard has not installed, by name. It reads presets that are not selected and +compares presets (`settings_get` `preset` and `compare`), writes one entry of a +per-variant value, and checks `settings_set`'s `changed` after the spiral vase dialog. It reads what +settings do from their meta (`description`, `where`): by key with `settings_get`, for one group with +`settings_list`, and found by the words of their descriptions, in one type and in all three. Keys named +without a type are read from the type that has each one, and a key named in the wrong type is listed with +the type that has it (`type_of`) and refused by `settings_set`. It reverts single keys (`null`, `reset_to`), +and answers the unsaved-changes prompts: +`preset_select` without `preset_changes` still opens the prompt, `preset_changes` transfers or discards without it, +and `project_new` keeps modified presets unless `preset_changes` is `"discard"`. It ends by deleting the +presets it made with `preset_delete`: filaments the tab edits and does not, a base process and its child, and a printer once selected, with the refusals for system presets, a preset another inherits from, unsaved changes and a printer that is not selected. It exports a filament with the Export -Preset Bundle dialog to its `out_dir` (`export_config` with a directory), imports the archive again -with `import_configs` and a path (kept while the preset exists, imported once it is deleted) and +Preset Bundle dialog to its `out_dir` (`preset_export` with a directory), imports the archive again +with `preset_import` and a path (kept while the preset exists, imported once it is deleted) and imports `tests/fixtures/mcp_import_pla.json`. It changes a preference in the Preferences dialog -opened with `open_preferences` `behaviour:auto_arrange`, by the control's name, and reads it back with -`get_settings {"scope": "preferences"}`. It starts from the harness's default printer with one +opened with `window_open {"window": "preferences", "tab": "behaviour", "key": "auto_arrange"}`, by the +control's name, and reads it back with `preferences_get`. It starts from the harness's default printer with one filament slot in Simple mode, deleting slots and selecting the mode first, and reruns on the same datadir. `tests/plates.json` sets a plate type and print sequence on one plate only (with undo and redo), the -first and other layers' filament orders, spiral vase, the lock (twice, which leaves it locked) and a -name through `set_settings`' plate scope, and reads them back with `list_plates` and `get_settings`. +first and other layers' filament orders and spiral vase through `plate_set_settings`, the lock (twice, +which leaves it locked) through `plate_lock` and a name through `plate_rename`, and reads them back +with `plate_list` and `plate_get_settings`. It brings the filament list to two slots with the `filament_add` and `filament_delete` commands first, and ends with a mixed filament, whose slot the delete command refuses and ahead of which a new slot goes. It reruns on the same datadir. -`tests/calibration.json` makes every calibration test with `generate_calibration_test` (each pressure advance method, +`tests/calibration.json` makes every calibration test with `calibration_generate_test` (each pressure advance method, a 2 x 2 pattern batch, the four flow ratio passes) and checks the objects it added, the parameters it used and the presets it changed, slicing some of them. It checks the temperature rounding, the refusals that leave the project as it was (modified presets without `preset_changes`, an argument the test -does not take), `preset_changes: "keep"` keeping an edit, and `new_project` dropping the test's settings. It +does not take), `preset_changes: "keep"` keeping an edit, and `project_new` dropping the test's settings. It starts from the harness's default printer and reruns on the same datadir. `tests/ops_*.json` drive each operation of the operations layer (`docs/HLSD/mcp-server.md`, "The -operations layer") through every route that reaches it: the Speed Dial command run with `run_action`, -the typed tool and, for presets, a pick in the sidebar and the plugin API called from a `run_script` -step. One replay per operation, named after it: G-code, sliced 3MF, model 3MF and STL exports, a model +operations layer") through the routes that reach it: the command, a Speed Dial tile run with `action_run` +where one runs it from a call, and, for presets, a pick in the sidebar and the plugin API called from a +`script_run` step. One replay per operation, named after it: G-code, sliced 3MF, model 3MF and STL exports, a model import, a project opened, started anew and saved, a plate selected and locked, arrange, slice, the Preview's layer range, a printer or process preset selected (`ops_select_preset`), a filament assigned to a slot on a printer with one slot and with several (`ops_assign_filament_preset_one_slot`, -`_multi_slot`), presets imported, an object's instance count, and the refusals of `send_gcode`, which -never sets a print host, so nothing is sent. Each records what a call leaves: its reply or its +`_multi_slot`), presets imported, an object's instance count, and the refusals of `printer_send`'s tile, +whose id is `send_gcode`, which never sets a print host, so nothing is sent. Each records what a call leaves: its reply or its refusal's text, the state read back after it, and the undo snapshots it took, which `tests/fixtures/ops_undo.py` reads from the app's log since no tool lists the undo history. Their `expect`s are on the setup and on what is read back. A replay cannot assert a refusal's text, so a @@ -337,20 +355,21 @@ call that a route refuses is `optional`, and `result.json` is the record of thos between two builds. The preset replays share `tests/fixtures/ops_presets.py`, which sets the slots, colours and flushing volumes to known values before each case, and each needs a freshly launched app, since a hidden -preset that `select_preset` shows stays shown until a restart. The replays whose commands write files -need a fresh `--out`, since those commands write without `overwrite`. Launch the app from a folder that +preset that `preset_select` shows stays shown until a restart. The replays whose calls write files +need a fresh `--out`, since some of those calls write without `overwrite`. Launch the app from a folder that holds no `.py` files, since the app's working directory is on Python's module path and a file there can -shadow a standard module that `run_script` needs. +shadow a standard module that `script_run` needs. -`test_operation_routes.py` asserts what those replays only record: that a command, the tool that does -the same thing and the plugin API's binding refuse the same states with the same code and words, and -accept the same ones. It covers a project saved under a `.gcode.3mf` name, the exports of a project -with no objects, a layer asked of a Preview with none, an arrangement from the assemble view and with -a gizmo open, a mixed-colour filament slot, and a hidden printer selected through the plugin API. Run +`test_operation_routes.py` asserts what those replays only record: that a command, a Speed Dial tile that +runs it and the plugin API's binding refuse the same states with the same code and words, and accept the +same ones: a layer asked of a Preview with none (the Go to layer tile and `view_set`), a mixed-colour +filament slot, and a hidden printer selected through the plugin API. It also checks what a command refuses +or does in those states alone: a project saved under a `.gcode.3mf` name, the exports of a project with no +objects, and an arrangement from the assemble view and with a gizmo open. Run it on a freshly launched app, for the reasons above and because the Preview keeps the last slice's layers. -The Design-tab replays drive the Design commands through `call_tool` and need an instance launched with +The Design-tab replays drive the Design commands through `tool_call` and need an instance launched with `--cad`. Each starts from a new project and checks what it builds by volume and by what the reading commands give back, under each reply's `result`; steps marked `optional` are calls that must be refused and change nothing. @@ -382,29 +401,29 @@ marked `optional` are calls that must be refused and change nothing. an edit and of a rename), suppresses, moves and deletes features, names, hides and colours bodies, commits only the shown one, and saves and reopens the project to check that a body's name and colour were kept. -- `tests/cad_canvas.json` drives the Design view as a canvas: `set_view` shows the Design tab and +- `tests/cad_canvas.json` drives the Design view as a canvas: `view_set` shows the Design tab and points its camera (and refuses Prepare's and Preview's fields there), canvas and widget screenshots capture the view, a click at its centre picks the block and a right click lists the - verbs for the pick, and `press_keys` reaches the Design panel's key hook (Shift+E opens the Extrude + verbs for the pick, and `keyboard_press` reaches the Design panel's key hook (Shift+E opens the Extrude card, Escape with no target closes it). Last, a change made only in the Design tab marks the project modified, and reopening the saved design-only project with `discard_changes` asks nothing and names the project after its file. Three harness tests run on an instance launched with `--cad`. `test_cad_replay.py` makes calls as a -client, so they are journaled, exports the session with `export_replay`, replays it into a new +client, so they are journaled, exports the session with `replay_export`, replays it into a new project and compares the body's mass properties and the features. The session has an empty sketch commit, a missed hole and a fillet the kernel refuses, which must fail and be left out, a shell thicker than the plate answering ok false, which stays in, and face and edge ids passed with their `generation`, which the journal drops. `test_cad_slow_build.py` runs a long thread build (an M8 thread tapped 60 mm deep, about 8 s) and -checks that while it builds `get_app_state` answers, a window screenshot succeeds, `list_widgets` lists +checks that while it builds `app_state` answers, a window screenshot succeeds, `widget_list` lists the progress dialog and a screenshot of that dialog captures it, and another Design command is refused. `test_cad_failed_job.py` sweeps a coil whose every rebuild outlasts the reply budget (its turns sized from the session's first build), then a hole that misses it replies with a running job and fails after the reply budget: an export while it runs leaves it out and names it in `left_out_running`, the export after it has the rename made next and not the hole, and that replay runs to the same coil. It takes four to eight minutes, or under a minute with the reply budget capped at 4 s by -`ORCA_MCP_REPLY_BUDGET_MS=4000` for the app and the test, as the sweep runs it. `test_cad_examples.py` runs the examples `search_tools {tool}` gives for +`ORCA_MCP_REPLY_BUDGET_MS=4000` for the app and the test, as the sweep runs it. `test_cad_examples.py` runs the examples `tool_search {tool}` gives for every Design command, and for `undo` and `redo`, each on a fresh design, and fails one whose call fails or whose result has `ok` false, an error, or is the person's form; `--tool NAME` runs one command's. @@ -415,20 +434,20 @@ commands with their arguments and grades what `describe_design`, `feature_descri shapes drawn once with its tool on the canvas and once with `sketch_draw`, which must agree in entities, constraints, loops and degrees of freedom; `sketch_edit` and its replace, cancel and refusals; `sketch_project` with and without an open sketch, `sketch_text`, `sketch_insert_svg` and Scale artwork; -`feature_edit`'s `refs` and a card's picks while it edits a feature; `set_view`'s Design options; +`feature_edit`'s `refs` and a card's picks while it edits a feature; `view_set`'s Design options; `select_geometry`, `confirm_tool`, `cancel_tool` and `body_place`; the Boolean card a call opens; and a pick of a folded row's tile from the Speed Dial, and its replay. Its docstring lists the rungs. Three more harness tests on a `--cad` instance drive the Design tab the way a person does. Every action goes -through the UI tools (`set_view`, `click`, `mouse_gesture`, `press_keys`, `set_widget_value`, `answer_dialog` -and `auto_answer_dialogs`), and the Design commands only read the result back (`sketch_describe`, +through the UI tools (`view_set`, `widget_click`, `mouse_gesture`, `keyboard_press`, `widget_set_value`, +`dialog_answer` and `dialog_auto_answer`), and the Design commands only read the result back (`sketch_describe`, `describe_design`, `feature_describe`), save for one call in the scale rung; the right-click menu's layout they grade against is read from `scripts/CAD/tool_atlas.json`, the Design table the app's own is generated from, for the selection `describe_design` names. Buttons and rows are found by label, and canvas positions come from a calibration that maps the open sketch's plane to canvas pixels, so nothing in them is tuned to a window size, screen scaling or theme. A map fitted from five probe points is reused, once one probe confirms it, while the canvas size and the camera stay the ones it was fitted on. The sketch tool's pick budgets and badge layout are in the canvas's GL pixels, -which `cad_gui.py` turns into click pixels by the canvas scale that `set_view`'s `camera_state` gives (`zoom` +which `cad_gui.py` turns into click pixels by the canvas scale that `view_set`'s `camera_state` gives (`zoom` over `click_px_per_mm`). What they share is in `cad_gui.py` beside them. `test_cad_sketching.py` draws each sketch tool's primitive with clicks on the canvas and types its exact values into the canvas's value field, drives the edit operations and each constraint button on drawn geometry, undoes inside a sketch and across its @@ -485,19 +504,20 @@ Plate Settings opened and cancelled, arrange of a second plate's two cubes (the job), the plate menu from a right click, and move to front. `test_webview_modal.py` runs JavaScript in the web views of modal dialogs: the preset bundle dialog's -page takes it by default and by locator, `run_javascript` is refused in the Home tab's web view behind a +page takes it by default and by locator, `webview_run_javascript` is refused in the Home tab's web view behind a modal and in a dialog under the topmost, the Flushing volumes dialog's page takes it as any topmost dialog's does, and a page that closes its dialog replies `closed` at once. -Web pages are driven like widgets: `list_widgets` lists each shown page's elements under its web view -with `d` refs, and `click`, `set_widget_value`, `press_keys`, `mouse_gesture` and `answer_dialog` act on them, by +Web pages are driven like widgets: `widget_list` lists each shown page's elements under its web view +with `d` refs, and `widget_click`, `widget_set_value`, `keyboard_press`, `mouse_gesture` and `dialog_answer` act on them, by ref or by `{web: "Next", kind, css, within, index}`. `tests/web_dialogs.json` drives Orca's own web dialogs that way alone: the preset bundle dialog, the colour picker behind a filament swatch (its hex field, and a drag on its spectrum) and the setup wizard's first steps. `test_web_ui.py` covers every kind of page control, action and what it changed on its page, refusal, locator, timeout and close on the pages of a fixture plugin, in a modal dialog, a modeless window, a dock panel and the Plugins dialog's configuration frame, a token in a page's URL shown redacted, and the permission prompt the -plugin's thread opens, answered with `answer_dialog` and with a rule registered while it is open. +plugin's thread opens, answered with `dialog_answer` and with a rule registered while it is open, and the +plugin's page among the main window's tabs, which the Go to tab tile shows by its id. Side-load the plugin into the datadir first: ```bash @@ -506,11 +526,11 @@ tools/mcp/orca_mcp.py launch --datadir /tmp/orca-mcp-test tools/mcp/test_web_ui.py ``` -`test_list_windows.py` checks `list_windows`: the main window first, the Plugins window (which doesn't -block the app) with a ref that `screenshot` captures alone, `list_widgets` reads alone and `press_keys` Escape +`test_list_windows.py` checks `window_list`: the main window first, the Plugins window (which doesn't +block the app) with a ref that `window_screenshot` captures alone, `widget_list` reads alone and `keyboard_press` Escape closes, Preferences last as a modal dialog, and Action Replay listed as hidden, without a ref. -`test_set_window.py` checks `set_window` on the main window (sized twice, moved, placed over its +`test_set_window.py` checks `window_set` on the main window (sized twice, moved, placed over its display's work area, maximized, minimized and restored), on the Plugins window by its ref and on Preferences by its `{label}` locator. On Wayland it checks that a window screenshot is the size the reply gives and skips positions, which Wayland neither reports @@ -518,12 +538,12 @@ nor takes. On X11 it reads the X server's stacking order through libX11 to check restored and raised while Preferences is open, stays under it. `test_action_replay_hidden.py` opens Action Replay -and checks that the GUI tools don't see it: `list_widgets` lists no window for it, `run_javascript` +and checks that the GUI tools don't see it: `widget_list` lists no window for it, `webview_run_javascript` without a target behaves as before it opened, and a key sent without a target never reaches it. It then shows the Run Script panel on -Prepare and checks the same for it, with no more web views in `list_widgets` than before, a key sent -without a target reaching the 3D view, a window screenshot, and an agent's `run_script` finishing -while it is shown; `run_replay` still runs the smoke test and a nested inline replay. +Prepare and checks the same for it, with no more web views in `widget_list` than before, a key sent +without a target reaching the 3D view, a window screenshot, and an agent's `script_run` finishing +while it is shown; `replay_run` still runs the smoke test and a nested inline replay. `test_speed_dial_open.py` goes from Home to Prepare, the Design tab (launched with `--cad`) and Preview by their tabs, and checks that the page's 3D view then holds the keyboard focus and that Space opens the Speed @@ -532,56 +552,97 @@ proved only where no pointer rests on the view: on a native Wayland display, or elsewhere. Where KWin runs the display, it also checks through KWin's D-Bus that KWin draws no title bar on the dial. -`tests/slice_stats.json` slices one cube, then two cubes in two colours, and checks the slice -reply's statistics: layers, max Z, filament changes, and each filament slot's model, flush and +`tests/slice_stats.json` slices one cube, then two cubes in two colours, and checks the statistics of +`plate_slice`'s reply: layers, max Z, filament changes, and each filament slot's model, flush and prime tower grams. -`tests/preview.json` slices a cube and reads it back with `get_slice_stats` (summary, feature and layer -tables, the object, the legend's state and colour ranges) and `get_app_state.preview` as `set_view` +`tests/preview.json` slices a cube and reads it back with `plate_slice_stats` (summary, feature and layer +tables, the object, the legend's state and colour ranges) and `app_state.preview` as `view_set` changes the layer (by number and by height), the view type, legend rows and time estimate, then reads the cube's G-code opened for viewing the same way. Run it on a fresh datadir: modified presets left by an earlier replay make opening the G-code ask about them. `test_set_view_preview.py` checks -what that replay cannot: `set_view {view_type}` acts as the legend's combo (a feature type hidden by +what that replay cannot: `view_set {view_type}` acts as the legend's combo (a feature type hidden by a click on its row shows again on Line Type, and the pick reaches the app config), a canvas screenshot straight after a layer or view type change shows the new layers and the legend laid out (it matches the capture after it), and the refusals of the preview arguments. -`test_set_view_camera.py`, on an instance launched with `--cad`, checks `set_view`'s `look_at` and `zoom` +`test_set_view_camera.py`, on an instance launched with `--cad`, checks `view_set`'s `look_at` and `zoom` on Prepare, Preview and the Design tab, and `orbit` on Prepare and the Design tab, against the reply's -`camera_state` and `get_app_state.camera`, including straight after `new_project`, whose fit runs at the +`camera_state` and `app_state.camera`, including straight after `project_new`, whose fit runs at the next frame, and a fit on Prepare after the window was sized on the Home tab. -`tests/agent_forms.json` calls tools the way agents often write them: a lone path for `paths`, +`tests/agent_forms.json` calls commands the way agents often write them: a lone path for `paths`, `object` for `objects` with the index as a string, an action by the key inside its id, `action` for -`id`, a camera direction as `set_view`'s `canvas`, which is read as its `camera`, `transform` to a `position`, `key` for `keys`, -`wait` with no condition, a gizmo by its toolbar title, `plate` for `plates`, legend rows in another -case or with `_` for a space, and `export` with the format taken from the path. It also checks that a -preset scope's whole `get_settings` listing leaves meta out. +`id`, a camera direction as `view_set`'s `canvas`, which is read as its `camera`, `object_transform` to a +`position`, `key` for `keys`, `app_wait` with no condition, a gizmo by its toolbar title, `plate` for +`plates`, legend rows in another case or with `_` for a space, and `project_export` with the format taken +from the path. It also checks that a type's whole `settings_list` listing leaves meta out. `test_stdio_bridge.py [--bin PATH]` checks `orca-slicer --mcp-stdio` against the launched instance: the handshake, notifications, tool calls in both protocol eras, and errors. With no instance answering, it checks that the bridge answers the handshake and lists the launched instance's tools without starting OrcaSlicer, and that a tool call then starts OrcaSlicer on the bridge's port (the test stops that app). -`test_recovery_under_load.py` fills the server's connections with 32 blocked `wait` calls and 32 -idle or half-sent connections while a dialog is open, and checks that `answer_dialog` on a new +`test_recovery_under_load.py` fills the server's connections with 32 blocked `app_wait` calls and 32 +idle or half-sent connections while a dialog is open, and checks that `dialog_answer` on a new connection still closes it. `test_cancel_pending_slice.py` cancels a slice while it still waits for the update a setting change scheduled, and checks that it never starts. `test_ref_locator_export.py` uses ImGui refs after their items changed (the Text gizmo's font button, whose label shows the font, and a Texture Displacement layer row renamed by its place when a layer before it goes) and checks -that the exported session replays. `test_worker_admission.py` starts a long arrange three ways (the -`arrange` tool, `run_action obj_arrange`, a click on the Arrange options panel's button) and checks -that changes, canvas keys and toolbar clicks are refused while it runs, reads answer, and `cancel_job` +that the exported session replays. `test_worker_admission.py` starts a long arrange three ways +(`object_arrange` with arguments, `action_run` of its Auto-Arrange tile, whose id is `obj_arrange`, a click on +the Arrange options panel's button) and +checks that changes, canvas keys and toolbar clicks are refused while it runs, reads answer, and `job_cancel` stops it. `test_export_running_job.py` exports while a call's job runs past its reply budget (left out, named in `left_out_running`), after it ends (an `await: false` step that replays) and while a dialog holds its call (kept); it takes about 100 s, or about 45 s with the reply budget capped at 10 s by `ORCA_MCP_REPLY_BUDGET_MS=10000` for the app and the test, as the sweep runs it. -`test_send_gcode.py` starts an OctoPrint-compatible stub host and sends a sliced cube to it with the -Speed Dial's `send_gcode`, the Send dialog answered with `set_widget_value` and `answer_dialog`: the command -is refused for a Bambu network printer and one without a print host, an upload the stub accepts -reads uploading at 99 until the stub answers and then completed in `get_app_state.uploads`, its exported +`test_send_gcode.py` starts an OctoPrint-compatible stub host and sends a sliced cube to it with +`printer_send`'s Speed Dial tile, `send_gcode`, the Send dialog answered with `widget_set_value` and `dialog_answer`: the +tile is refused for a Bambu network printer and one without a print host, an upload the stub accepts +reads uploading at 99 until the stub answers and then completed in `app_state.uploads`, its exported replay uploads again, and one the stub refuses with HTTP 500 never reads completed and ends as an -error whose dialog `answer_dialog` closes. +error whose dialog `dialog_answer` closes. + +`tests/tiles_ask.json` and `test_person_forms.py` check a call with exactly a tile's arguments, which may ask +as a person's pick of the tile does: `calibration_generate_test {test}` asks in the test's dialog and with +`silent` runs with its defaults, View: Top turns the Design tab's camera, Go to tab and Go to layer take their +value through `action_run`, and the slice tiles slice and show the Preview tab (the replay, on an instance +launched with `--cad`); `project_save {save_as: true}` and `project_export {format: gcode}` open their file +pickers while a path writes without one, `preset_export` always opens its dialog, `object_arrange {}` and +`object_select {all: true}` (and `action_run` of their tiles) reply as their commands do, the selection in the +assemble view's too, and the Speed Dial's own picks of a view tile, Deselect All, Go to layer, Auto-Arrange and +Select All Objects run in place (the script). `test_project_open_settings.py` +launches its own app, whose Preferences load a project's geometry only, and checks that `project_open` loads +the settings a project was saved with all the same. + +The commands that do a menu row's job take their targets by index, and the replays call them so and read each +back: `tests/rows_objects.json` (rename, instances, separate, delete, height ranges), `rows_structure.json` +(split, assemble, change type, order), `rows_placement.json` (add a primitive by numbers, mirror, drop, centre, +scale to fit, auto-orient) and `rows_plates.json` (duplicate, rename, lock, select and delete a plate); +`objects_state.json` (`object_set_printable`, `object_fix`, `object_set_auto_drop`), `objects_files.json` +(`object_clone`, `object_reload_from_disk`, `part_replace`, with the files `tests/fixtures/objects_files.py` +writes), `objects_order.json` (`object_order {order}`), `filaments_and_files.json` (a slot merged into +another, a mixed filament, exports of some objects and of each object, a ZIP's entries, a STEP file), +`settings_targets.json` (`settings_list`, and the settings commands' targets object, part and height range), +`presets_and_plate_map.json` (`preset_list`'s filters, a plate's filament map, a nozzle variant) and +`view_switches.json` (`view_set`'s display switches, sidebar and legend, and an object placed by a plate's +`origin` and `size`). A replay cannot expect an error, so the refusals are Python tests: +`test_rows_refusals.py` checks that each object command made from rows refuses with its own reason, and +`test_additions_refusals.py` the filament, preset, export and import commands'. `test_preferences.py` checks +`preferences_get` and `preferences_set` against the Preferences dialog, tab by tab. Some launch their own app, +on a fresh data folder and printers the sweep does not seed: `test_install_printers.py` and +`test_install_filaments.py` (installs and uninstalls, read back after a restart), `test_plugin_commands.py` +(the plugin commands on the fixture plugins of `tests/plugins`, against the Plugins window), +`test_printer_extruders.py` (a printer of two extruders) and `test_sidebar_floating.py` (`view_set`'s +`sidebar_width` refused while the sidebar floats). + +`test_every_tile.py` runs each of the 129 Speed Dial tiles of `tests/data/speed_dial_tiles.json` through +`action_run`, each from a state its table sets up afresh, answers the dialog or file picker it opens, and reads what +its row's job leaves: a change only that tile makes, the window it opens, the file it writes, or the refusal of a +tile that needs a printer or an account. It also checks the reply's `ran` and the step `replay_export` keeps against +`tests/data/speed_dial_tile_calls.json`. Its web-page and configuration-folder tiles hand over to the system's +browser and file manager, so the sweep runs it on its own. ## The sweep diff --git a/tools/mcp/cad_gui.py b/tools/mcp/cad_gui.py index 0228a4b1e1..ed68230d54 100644 --- a/tools/mcp/cad_gui.py +++ b/tools/mcp/cad_gui.py @@ -1,7 +1,7 @@ """Drive the Design tab of a running OrcaSlicer the way a person does, for the Design-tab GUI tests. -Every action goes through the MCP server's UI tools (set_view, click, mouse_gesture, press_keys, -set_widget_value, answer_dialog); the Design commands are used only to read results back (sketch_describe, +Every action goes through the MCP server's UI tools (view_set, widget_click, mouse_gesture, keyboard_press, +widget_set_value, dialog_answer); the Design commands are used only to read results back (sketch_describe, describe_design, feature_describe), and the right-click menu's layout is read from the Design table's source, scripts/CAD/tool_atlas.json, as the app's own table is generated from it. Nothing here knows a pixel: buttons and rows are found by label, and canvas positions come from a calibration that maps the open sketch's plane @@ -37,7 +37,7 @@ NEW_DESIGN = "New Design — clear the feature tree" # reset_view()'s zoom, in click pixels per mm at the camera's target, about 1.6: close enough that a # 40 mm line is long beside the pixel-sized reach of its value label, and far enough that the region # calibrate() measures holds every shape the tests draw at the default window. In click pixels, so -# the tests' clicks have the same room on every display; set_view takes screenshot pixels, which +# the tests' clicks have the same room on every display; view_set takes screenshot pixels, which # are GL pixels, two per click pixel on a Retina display. RESET_ZOOM = 250 / 1.4 ** 15 @@ -65,7 +65,7 @@ BADGE_CELL_PX = 11.0 BADGE_STEP_PX = 1.5 * BADGE_CELL_PX BADGE_PICK_PX = 0.6 * BADGE_CELL_PX -# One line of list_widgets' tree. rect is (x, y, w, h) in logical pixels, from the main window's +# One line of widget_list's tree. rect is (x, y, w, h) in logical pixels, from the main window's # client area for a window's widgets and from the canvas's top left for its ImGui items, or None. # parent is the index of the parent node in the list widgets() returns, or None at the top. # focused: the line is marked [focused], the window or ImGui text field that typed keys go to. @@ -103,7 +103,7 @@ def _same(a, b, tol=1e-12): return a == b -# ---------------------------------------------------------------- list_widgets' tree +# ---------------------------------------------------------------- widget_list's tree # The parts of a line that can follow its value, in their order; a label or value ends at a quote # followed by one of them or by the end of the line. @@ -111,7 +111,7 @@ _AFTER_VALUE = (" (", " name=", " option=", ' in "', " [") def parse_widgets(text): - """list_widgets' text tree as [Widget]. A line is + """widget_list's text tree as [Widget]. A line is `[ref] kind "label" = "value" (class) name=NAME option=O in "W" [flags] @x,y wxh`, every part after the kind optional and in that order.""" out, stack = [], [] @@ -315,7 +315,7 @@ class CadGui: released before reset_view(), whose N would otherwise act under it.""" steps = [("cancel dialogs", self._cancel_dialogs), ("cancel modeless dialogs", self._cancel_modeless), - ("show the Design tab", lambda: self.client.call("set_view", tab="design")), + ("show the Design tab", lambda: self.client.call("view_set", tab="design")), ("release the mouse", lambda: self.gesture(action="up", **self._canvas_centre())), ("reset the view", self.reset_view), ("Escape", lambda: self.keys("Escape", target=CANVAS)), @@ -329,30 +329,30 @@ class CadGui: def _cancel_dialogs(self): for _ in range(5): - dialogs = self.client.call("get_app_state").get("dialogs", []) + dialogs = self.client.call("app_state").get("dialogs", []) if not dialogs: return buttons = {b.get("label", "").lower() for b in dialogs[-1].get("buttons", [])} button = next((b for b in ("cancel", "no", "close") if b in buttons), "cancel") - self.client.call("answer_dialog", button=button) + self.client.call("dialog_answer", button=button) raise RuntimeError("dialogs keep opening") def _cancel_modeless(self): """Close each shown dialog that is not modal as a person would: with its own Cancel, or with - Escape in it when it has none, as the Speed Dial has none. answer_dialog and get_app_state's - dialogs know only modal ones, so these are found among list_windows' windows. The Cancel is + Escape in it when it has none, as the Speed Dial has none. dialog_answer and app_state's + dialogs know only modal ones, so these are found among window_list's windows. The Cancel is looked for among that window's own widgets: within an empty title, as the Speed Dial's is, matches every window, so a click by label could press another's, such as the Design tab's.""" for _ in range(5): shown = self._modeless_windows() if not shown: return - _, texts = self.client.call_with_text("list_widgets", target=shown[0]["ref"], max_nodes=5000, + _, texts = self.client.call_with_text("widget_list", target=shown[0]["ref"], max_nodes=5000, max_web_nodes=5000) own = parse_widgets(texts[0] if texts else "") cancel = next((w for w in own if w.kind == "button" and w.label == "Cancel"), None) if cancel is not None: - self.client.call("click", target=cancel.ref) + self.client.call("widget_click", target=cancel.ref) else: page = next((w for w in own if w.kind == "webview"), None) self.keys("Escape", target=page.ref if page is not None else shown[0]["ref"]) @@ -380,14 +380,14 @@ class CadGui: raise def widgets(self): - """list_widgets' tree as [Widget], asked for at the tool's largest size. A tree larger than + """widget_list's tree as [Widget], asked for at the tool's largest size. A tree larger than that raises: the nodes past the cut include the canvas and its ImGui items, which would otherwise read as not shown.""" - _, texts = self.client.call_with_text("list_widgets", max_nodes=5000, max_web_nodes=5000) + _, texts = self.client.call_with_text("widget_list", max_nodes=5000, max_web_nodes=5000) text = texts[0] if texts else "" cut = next((line for line in text.splitlines() if line.startswith("... ") and " more nodes" in line), None) if cut is not None: - raise RuntimeError(f"list_widgets cut its tree short: {cut}") + raise RuntimeError(f"widget_list cut its tree short: {cut}") return parse_widgets(text) def modeless(self): @@ -395,9 +395,9 @@ class CadGui: return [w["title"] for w in self._modeless_windows()] def _modeless_windows(self): - """list_windows' shown dialogs that are not modal, leaving out the person's own (hidden), such + """window_list's shown dialogs that are not modal, leaving out the person's own (hidden), such as Action Replay, which no tool reaches.""" - items = self.client.call("list_windows").get("items", []) + items = self.client.call("window_list").get("items", []) return [w for w in items if w.get("kind") == "dialog" and not w.get("modal") and not w.get("hidden")] @staticmethod @@ -459,10 +459,10 @@ class CadGui: args = {"keys": chord} if target is not None: args["target"] = target - return self.client.call("press_keys", **args) + return self.client.call("keyboard_press", **args) def text(self, s): - return self.client.call("press_keys", text=s) + return self.client.call("keyboard_press", text=s) def press(self, label, within=None): """Click a widget by its label, in the window titled `within` when one is named. A click @@ -470,19 +470,19 @@ class CadGui: target = {"label": label} if within is not None: target["within"] = within - return self.client.call("click", target=target) + return self.client.call("widget_click", target=target) def fill(self, target, value, submit=True): - """Give the widget `target` names (a list_widgets locator) `value` with set_widget_value, + """Give the widget `target` names (a widget_list locator) `value` with widget_set_value, the way into a native text field, which key presses never type into. `submit` also presses Enter in it, as the tool does by default.""" - return self.client.call("set_widget_value", target=target, value=value, submit=submit) + return self.client.call("widget_set_value", target=target, value=value, submit=submit) def row(self, label, double=False): - return self.client.call("click", target={"row": label}, double=double) + return self.client.call("widget_click", target={"row": label}, double=double) def menu(self, path): - return self.client.call("click", target={"menu": path}) + return self.client.call("widget_click", target={"menu": path}) def gesture(self, **args): return self.client.call("mouse_gesture", canvas="design", **args) @@ -491,7 +491,7 @@ class CadGui: """When `reply` is a call held by the dialog titled `title`, answer it and finish the call.""" if reply.get("status") != "blocked_by_dialog": return reply - self.client.call("answer_dialog", button=button, dialog={"title": title}) + self.client.call("dialog_answer", button=button, dialog={"title": title}) return self.client.await_job(reply, timeout=60) # ------------------------------------------------------------ session @@ -501,7 +501,7 @@ class CadGui: tab lays its canvas out on its first showing (in a fresh instance) as on a later one, make the window wide enough for the sketch ribbon, show the Design tab in reset_view()'s view and start an empty design.""" - if not self.client.call("get_app_state").get("design_tab"): + if not self.client.call("app_state").get("design_tab"): print("the Design tab is off: launch the app with tools/mcp/orca_mcp.py launch --cad") sys.exit(2) ws = self.widgets() @@ -511,13 +511,13 @@ class CadGui: sys.exit(2) # A run killed before it cleared its auto-answer rules leaves them in force, and they would # answer this run's dialogs and pickers; an empty list clears the rules a client set. - self.client.call("auto_answer_dialogs", rules=[]) + self.client.call("dialog_auto_answer", rules=[]) # A canvas laid out under a ribbon of the wrong height moves when the tab is shown again, and a # click aimed through a map fitted before the move misses by that much. - self.client.call("set_view", tab="design") + self.client.call("view_set", tab="design") first = self._canvas(self.widgets()).rect - self.client.call("set_view", tab="prepare") - self.client.call("set_view", tab="design") + self.client.call("view_set", tab="prepare") + self.client.call("view_set", tab="design") again = self._canvas(self.widgets()).rect self.check("the Design tab's first showing lays out its canvas as a later one does", first == again, f"{first}, then {again}") @@ -535,14 +535,14 @@ class CadGui: over = cancel.rect[0] + cancel.rect[2] - (cx + cw) self.cancel() if over > 0: - width, height = self.client.call("get_app_state")["window"]["size"] - self.client.call("set_window", size=[width + over + cancel.rect[3], height]) + width, height = self.client.call("app_state")["window"]["size"] + self.client.call("window_set", size=[width + over + cancel.rect[3], height]) self.show_design() self.new_design() def show_design(self): """Bring the Design tab to the front, in the view reset_view() sets.""" - self.client.call("set_view", tab="design") + self.client.call("view_set", tab="design") self.reset_view() def reset_view(self): @@ -550,18 +550,18 @@ class CadGui: the top camera at RESET_ZOOM, centred on describe_design's modeling_origin, the sketch planes' origin, and squared to the sketch's plane when a sketch is open. - set_view's look_at is in the Design view's world coordinates, where modeling_origin is not + view_set's look_at is in the Design view's world coordinates, where modeling_origin is not zero: a new design puts it at the Design bed's centre. Its directions fit only what has volumes, so on an empty design they turn the camera and keep its zoom and centre; the look_at and zoom it applies after the direction set both. N in a sketch squares the view to the sketch's plane and centres it on the plane's origin, keeping the zoom. Every map calibrate() fits stands - on this view, so the camera set_view reports is checked. Its camera_state gives the canvas's + on this view, so the camera view_set reports is checked. Its camera_state gives the canvas's GL pixels per click pixel, and the view is set again when they differ from the ones the zoom assumed.""" origin = self.cad("describe_design")["modeling_origin"] def aim(): - return self.client.call("set_view", tab="design", camera="top", look_at=origin, + return self.client.call("view_set", tab="design", camera="top", look_at=origin, zoom=RESET_ZOOM * self.gl_per_px).get("camera_state", {}) state = aim() @@ -573,7 +573,7 @@ class CadGui: zoom, target = state.get("zoom"), state.get("look_at") if (zoom is None or abs(zoom - RESET_ZOOM * self.gl_per_px) > 1e-3 or target is None or max(abs(a - b) for a, b in zip(target, origin)) > 1e-3): - raise RuntimeError(f"set_view left the Design camera at {state}, not at modeling_origin " + raise RuntimeError(f"view_set left the Design camera at {state}, not at modeling_origin " f"{origin} with zoom {RESET_ZOOM * self.gl_per_px:.4f}") if self._sketch_or_none(): self.keys("n", target=CANVAS) @@ -732,8 +732,8 @@ class CadGui: def _view_key(self, w, h): """What a plane-to-pixel map stands on besides the sketch's plane: the canvas's size and - the Design camera get_app_state reports.""" - camera = self.client.call("get_app_state").get("camera") or {} + the Design camera app_state reports.""" + camera = self.client.call("app_state").get("camera") or {} return (w, h, json.dumps(camera, sort_keys=True)) def _check_map(self, H, w, h): diff --git a/tools/mcp/gen_skill_reference.py b/tools/mcp/gen_skill_reference.py index ee7b98a7cb..f3f8bb301b 100644 --- a/tools/mcp/gen_skill_reference.py +++ b/tools/mcp/gen_skill_reference.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Write the skill's list of the Speed Dial's commands from the command reference. +"""Write the skill's list of the Speed Dial's tiles from the command reference. python tools/mcp/gen_skill_reference.py # rewrite actions.md python tools/mcp/gen_skill_reference.py --check # exit 1 when it differs @@ -7,12 +7,15 @@ Reads tests/data/command_catalog.json, the reference of the command catalog that the unit test "the checked-in command reference matches the catalog" keeps current, and writes skills/orcaslicer-mcp-skills/references/actions.md in the checkout of the orcaslicer-mcp-skills -repository: every command a person can pick, section by section in the order the catalog adds them. -A command with a tile of its own (in_palette) has a row with its key, title, arguments and -description; each Design menu row folded into a command (its tiles) has a row after it, with the -command's key, the tile's title, the arguments that open it and its description. The file is -generated: edit the commands in OrcaSlicer and regenerate it. A header that names a command the reference does not have is an -error, so that a renamed or removed command cannot leave it stale. Standard library only. +repository: every tile a person can pick, section by section in the order the catalog adds them. +Outside the Design tab a section is a Speed Dial section (a tile's group, or the tile_group of a +command's own tile), and each tile has a row with its key, its title, the command and arguments it +runs and its description. In the Design section a command with a tile of its own (in_palette) has a +row with its key, title, arguments and description, and each Design menu row folded into a command +(its tiles) a row after it, with the command's key, the tile's title, the arguments that open it and +its description. The file is generated: edit the commands in OrcaSlicer and regenerate it. A header +that names a command the reference does not have is an error, so that a renamed or removed command +cannot leave it stale. Standard library only. """ import argparse @@ -26,6 +29,7 @@ from pathlib import Path REPO = Path(__file__).resolve().parents[2] REFERENCE = REPO / "tests" / "data" / "command_catalog.json" TARGET = Path("skills") / "orcaslicer-mcp-skills" / "references" / "actions.md" +DESIGN = "Design" HEADER = """\ # Speed Dial commands @@ -33,34 +37,38 @@ HEADER = """\ Generated by OrcaSlicer's `tools/mcp/gen_skill_reference.py` from its command reference (`tests/data/command_catalog.json`); do not edit it by hand. -These are the commands a person picks in the Speed Dial, by section. Call one with -`call_tool {"tool": "", "args": {...}}`, or run its tile with `run_action {"id": "", "args": {...}}`; -`search_tools {"tool": ""}` gives its whole schema, and its examples when it has some. Some are the -person's own. Action Replay, Run Script, Take Screenshot and the calibration dialogs have a tool for agents -(`run_replay`, `run_script`, `screenshot`, `generate_calibration_test`); the wiki and YouTube links, About, -the plugin hub and the configuration folder (`open_wiki`, `open_youtube`, `help_about`, `install_plugin`, -`help_open_config_folder`) are left to the person. +These are the tiles a person picks in the Speed Dial, by section. Each runs a command with the arguments +its row gives. Call the command by its name, with those arguments or others, and one the tool list does not +show with `tool_call {"tool": "", "args": {...}}`; `tool_search {"tool": ""}` gives its whole +schema, and its examples when it has some. `action_run {"id": ""}` runs a tile as a call with the +tile's arguments does. Action Replay, Run Script, Take Screenshot and the calibration dialogs have a command +for agents (`replay_run`, `script_run`, `window_screenshot`, `calibration_generate_test`); the wiki and +YouTube links, About, the plugin hub and the configuration folder (`app_open_web_page`, +`window_open {"window": "about"}`, `app_show_config_folder`) are left to the person. -A command whose schema has `silent`, or whose description says what it does with no arguments, does what a -person's pick does when called with none: one that asks in a dialog opens it, which a call reports as -`blocked_by_dialog`. Given its arguments, or `silent: true` if it takes `silent`, it runs without asking and -needs the arguments marked required. A command whose schema requires an argument has no person's form -(`go_to_tab {}` is refused), and one whose dialog is what it does opens it with arguments too -(`export_config {"path": "/abs/dir"}` only spares it the folder question). +A call with exactly a tile's arguments is the tile's own call: where the tile asks in a dialog, the call opens +it, which it reports as `blocked_by_dialog`, and where the tile acts on the selection, so does the call. A +tile whose row does what its command does (a camera view, Select All, Deselect All, Auto-Arrange, Auto-Orient, +Refresh Plugins) runs the command's own function and replies as the command does. Any other arguments, or +`silent: true` where the schema has `silent`, run the command without asking, with the arguments its schema +marks required. Go to tab and Go to layer collect their value in the Speed Dial: `action_run` gives such a +tile its one value (`{"tab": "preview"}`, `{"percent": 50}`), and the command takes it as the argument its +row names. A command whose dialog is what it does opens it with arguments too +(`preset_export {"path": "/abs/dir"}` only spares it the folder question). -The Design section lists the Design tab's commands that have a tile; `search_tools {"group": "Design"}` lists +The Design section lists the Design tab's commands that have a tile; `tool_search {"group": "Design"}` lists them all, and `references/cad.md` covers them. They run only with the CAD feature on, which a person turns on -in Preferences > Features before restarting OrcaSlicer: `get_app_state.design_tab` says whether the Design tab +in Preferences > Features before restarting OrcaSlicer: `app_state.design_tab` says whether the Design tab is on, and `cad_note`, while its commands cannot run, how to turn it on (a test instance gets it with -`tools/mcp/orca_mcp.py launch --cad`). A Design tile is in the Speed Dial, and `run_action` runs it, only while -the Design tab is shown in the tile's mode (in a sketch or outside one); `call_tool` runs its command from any +`tools/mcp/orca_mcp.py launch --cad`). A Design tile is in the Speed Dial, and `action_run` runs it, only while +the Design tab is shown in the tile's mode (in a sketch or outside one); `tool_call` runs its command from any tab. Called with no arguments, a tile's command does what its right-click menu row does, which may be to act at once (a Delete row deletes what is selected) or to decline. -A row whose arguments are written as a call's own (`{"type": "linear"}`, or `{}`) is one tool of its command: -`call_tool` given exactly those arguments opens that tool, as a person's pick of its tile does, and any other call -runs the command from its arguments. The tile has an id of its own, which `search_actions` gives, and `run_action` -runs it with no arguments or with exactly those. +A Design row whose arguments are written as a call's own (`{"type": "linear"}`, or `{}`) is one tool of its +command: `tool_call` given exactly those arguments opens that tool, as a person's pick of its tile does, and any +other call runs the command from its arguments. The tile has an id of its own, which `action_search` gives, and +`action_run` runs it with no arguments or with exactly those. """ # The words HEADER writes in backticks that name no command: an argument, a reply's status and a field. @@ -110,40 +118,60 @@ def names(commands): return keys[0] if len(keys) == 1 else ", ".join(keys[:-1]) + " and " + keys[-1] -def header(palette): - """HEADER, with what it says of particular commands read from the reference: the commands with one form, - which needs a value (a top-level `required`), and the typed tools that are tiles too (`listed`).""" - needs = [c for c in palette if c["input_schema"].get("required")] - both = [c for c in palette if c["listed"]] +def header(design, unlisted): + """HEADER, with what it says of particular commands read from the reference: the Design commands with a tile of + their own that need a value (a top-level `required`), and the commands of tiles the tool list does not show.""" + needs = [c for c in design if c["in_palette"] and c["input_schema"].get("required")] facts = [] if needs: facts.append("%s %s." % (names(needs), "needs its value" if len(needs) == 1 else "need their value")) - if both: - facts.append("A typed tool that is also a tile (%s) is in the tool list too." % names(both)) + if unlisted: + facts.append("The tool list does not show %s, menu rows that take no arguments: call %s with `tool_call`." % + (names(unlisted), "it" if len(unlisted) == 1 else "them")) if not facts: return HEADER return HEADER + "\n" + "\n".join(textwrap.wrap(" ".join(facts), width=110)) + "\n" +def runs(command, tile): + """The call a tile runs: its command with the tile's arguments, and the value an input tile collects under the + argument that takes it.""" + args = json.dumps(tile["args"]) if tile else "{}" + if tile and tile.get("input"): + args = '{"%s": <%s>}' % (tile.get("input_arg") or tile["input"], tile["input"]) + return "`%s %s`" % (command["key"], args) + + def row(key, title, args, does): """One row of a section's table.""" return "| `%s` | %s | %s | %s |\n" % (key, cell(title), cell(args), cell(does)) def render(reference): - # A command is in the palette with a tile of its own, or through the tiles of the menu rows folded into it. + # A command is in the palette with a tile of its own, or through the tiles folded into it. Outside the Design tab + # each tile is a row of its Speed Dial section; a Design command's rows stay together in the Design section. palette = [command for command in reference["commands"] if command["in_palette"] or command.get("tiles")] sections = {} - for command in palette: - sections.setdefault(command["group"], []).append(command) - out = [header([command for command in palette if command["in_palette"]])] - for group, commands in sections.items(): - out.append("\n## %s\n\n| key | title | arguments | does |\n|---|---|---|---|\n" % group) - for c in commands: + for c in palette: + if c["group"] == DESIGN: + rows = sections.setdefault(DESIGN, []) if c["in_palette"]: - out.append(row(c["key"], c["title"], arguments(c["input_schema"]), c["description"])) + rows.append(row(c["key"], c["title"], arguments(c["input_schema"]), c["description"])) for tile in c.get("tiles", []): - out.append(row(c["key"], tile["title"], "`%s`" % json.dumps(tile["args"]), tile["description"])) + rows.append(row(c["key"], tile["title"], "`%s`" % json.dumps(tile["args"]), tile["description"])) + continue + if c["in_palette"]: + sections.setdefault(c.get("tile_group") or c["group"], []).append(row(c["key"], c["title"], runs(c, None), + c["description"])) + for tile in c.get("tiles", []): + sections.setdefault(tile.get("group") or c["group"], []).append(row(tile["key"], tile["title"], runs(c, tile), + tile["description"])) + unlisted = [c for c in palette if c["group"] != DESIGN and not c["listed"]] + out = [header([c for c in palette if c["group"] == DESIGN], unlisted)] + for section, rows in sections.items(): + columns = "arguments" if section == DESIGN else "runs" + out.append("\n## %s\n\n| key | title | %s | does |\n|---|---|---|---|\n" % (section, columns)) + out.extend(rows) return "".join(out) diff --git a/tools/mcp/orca_mcp.py b/tools/mcp/orca_mcp.py index b038322dd1..8b6665dc4b 100755 --- a/tools/mcp/orca_mcp.py +++ b/tools/mcp/orca_mcp.py @@ -9,10 +9,10 @@ Standard library only. Two halves: tools/mcp/orca_mcp.py launch --headless # fresh datadir on a private headless desktop (Linux), wait until ready tools/mcp/orca_mcp.py launch --xvfb # on a private Xvfb display, for a Linux machine without a desktop - tools/mcp/orca_mcp.py launch --cad # with the Design (CAD) tab on, for its commands (search_tools group Design) - tools/mcp/orca_mcp.py launch --unrestricted-scripts # with Python scripts (run_script) unrestricted - tools/mcp/orca_mcp.py call get_app_state - tools/mcp/orca_mcp.py call open_files '{"paths": ["/abs/model.stl"]}' + tools/mcp/orca_mcp.py launch --cad # with the Design (CAD) tab on, for its commands (tool_search group Design) + tools/mcp/orca_mcp.py launch --unrestricted-scripts # with Python scripts (script_run) unrestricted + tools/mcp/orca_mcp.py call app_state + tools/mcp/orca_mcp.py call project_import '{"paths": ["/abs/model.stl"]}' tools/mcp/orca_mcp.py screenshot /tmp/shot.png --target canvas tools/mcp/orca_mcp.py widgets tools/mcp/orca_mcp.py run-replay tools/mcp/smoke_test.json --out /tmp/smoke @@ -180,11 +180,11 @@ class OrcaMcp: """Call a tool and return its JSON result; raise McpError when the tool reports an error. A call that returns a job envelope (running / blocked_by_dialog) is returned as is. The tool - name is positional-only, so an argument named tool (call_tool's) goes to the tool.""" + name is positional-only, so an argument named tool (tool_call's) goes to the tool.""" return self.call_with_text(tool, _timeout, **args)[0] def call_with_text(self, tool, /, _timeout=None, **args): - """Like call(), plus the text blocks after the JSON one (list_widgets's tree).""" + """Like call(), plus the text blocks after the JSON one (widget_list's tree).""" result = self.call_raw(tool, args, timeout=_timeout) texts = [c["text"] for c in result.get("content", []) if c.get("type") == "text"] text = texts[0] if texts else "" @@ -215,21 +215,21 @@ class OrcaMcp: while isinstance(result, dict) and result.get("status") in ("running", "blocked_by_dialog") and "job" in result: if time.time() > deadline: raise McpError(f"job {result['job']} did not finish in {timeout} s", result) - result = self.call("wait", **{"for": "job", "job": result["job"], "timeout_s": 45}) + result = self.call("app_wait", **{"for": "job", "job": result["job"], "timeout_s": 45}) return result def call_command(self, tool, /, **args): """Call one command, a tool or one the tool list does not show (a Design command), through - call_tool and return its whole reply; a Design command's result is the reply's "result". + tool_call and return its whole reply; a Design command's result is the reply's "result". A running job is followed to its end. A call whose first reply is blocked_by_dialog fails at once, since a script that waited would wait on a dialog nobody answers. A call that first - replied running and opens a dialog later is waited on up to await_job's timeout, since wait + replied running and opens a dialog later is waited on up to await_job's timeout, since app_wait reports only that its job is still running. Every McpError's message starts ": ", with the original error as its cause. The command's name is positional-only, so its own argument named tool goes to the command.""" try: - reply = self.call("call_tool", _timeout=600, tool=tool, args=args) + reply = self.call("tool_call", _timeout=600, tool=tool, args=args) if reply.get("status") == "blocked_by_dialog": titles = ", ".join(f"\"{d.get('title', '')}\"" for d in reply.get("dialogs", [])) raise McpError(f"blocked by a dialog: {titles} (job {reply.get('job')} goes on once it is answered)", reply) @@ -241,7 +241,7 @@ class OrcaMcp: deadline = time.time() + timeout while time.time() < deadline: try: - if self.call("wait", **{"for": "ready", "timeout_s": 5}).get("satisfied"): + if self.call("app_wait", **{"for": "ready", "timeout_s": 5}).get("satisfied"): return True except (McpError, OSError): time.sleep(0.5) @@ -387,7 +387,7 @@ def start_display(args, datadir): continue if name == "mutter": print("headless mutter is not tested yet (test required): check the window, input, screenshots " - "and that get_log reports the GPU's OpenGL driver", file=sys.stderr) + "and that app_log reports the GPU's OpenGL driver", file=sys.stderr) started = start_headless(name, args.width, args.height, datadir) if started: return (name,) + started @@ -501,13 +501,13 @@ def answer_certificate_prompt(client): window when it has to find a CA bundle itself, and the endpoint serves by then, so a launch nobody watches answers it here. True when it pressed the button.""" try: - dialogs = client.call("get_app_state").get("dialogs") or [] + dialogs = client.call("app_state").get("dialogs") or [] except (McpError, OSError): return False for dialog in dialogs: if "system certificate" in (dialog.get("message") or ""): try: - client.call("answer_dialog", dialog={"title": dialog.get("title", "")}, button="yes") + client.call("dialog_answer", dialog={"title": dialog.get("title", "")}, button="yes") except (McpError, OSError): return False return True @@ -520,7 +520,7 @@ def wait_ready(client, timeout): deadline = time.time() + timeout while time.time() < deadline: try: - if client.call("wait", **{"for": "ready", "timeout_s": 2}).get("satisfied"): + if client.call("app_wait", **{"for": "ready", "timeout_s": 2}).get("satisfied"): return True except (McpError, OSError): time.sleep(0.5) @@ -611,9 +611,9 @@ def main(): p.add_argument("--vendor", default="BBL") p.add_argument("--filament") p.add_argument("--cad", action="store_true", - help="start the app with --cad: the Design (CAD) tab on for this run, for its commands (search_tools group Design)") + help="start the app with --cad: the Design (CAD) tab on for this run, for its commands (tool_search group Design)") p.add_argument("--unrestricted-scripts", action="store_true", - help="start the app with --unrestricted-scripts: Python scripts (run_script) unrestricted for this run") + help="start the app with --unrestricted-scripts: Python scripts (script_run) unrestricted for this run") p.add_argument("--timeout", type=int, default=120) p.add_argument("--print-config", action="store_true", help="print client setup commands") p.add_argument("extra", nargs="*", help="extra orca-slicer arguments after --") @@ -626,8 +626,8 @@ def main(): p.add_argument("--wait", action="store_true", help="follow a returned job to its result") sub.add_parser("tools", help="list tools") - p = sub.add_parser("widgets", help="print the list_widgets tree") - p.add_argument("args", nargs="?", help="list_widgets arguments as JSON") + p = sub.add_parser("widgets", help="print the widget_list tree") + p.add_argument("args", nargs="?", help="widget_list arguments as JSON") p = sub.add_parser("screenshot", help="save a screenshot") p.add_argument("out") @@ -656,16 +656,16 @@ def main(): print(f"{t['name']:20} {t.get('description', '').splitlines()[0][:100]}") elif args.cmd == "widgets": a = json.loads(args.args) if getattr(args, "args", None) else {} - data, texts = client.call_with_text("list_widgets", **a) + data, texts = client.call_with_text("widget_list", **a) print("\n".join(texts) or json.dumps(data, indent=2)) elif args.cmd == "screenshot": out = os.path.abspath(args.out) - print(json.dumps(client.call("screenshot", target=args.target, save_path=out, overwrite=True, include_image=False), indent=2)) + print(json.dumps(client.call("window_screenshot", target=args.target, save_path=out, overwrite=True, include_image=False), indent=2)) elif args.cmd == "run-replay": a = {"path": os.path.abspath(args.replay)} if args.out: a["out_dir"] = os.path.abspath(args.out) - result = client.await_job(client.call("run_replay", **a), timeout=3600) + result = client.await_job(client.call("replay_run", **a), timeout=3600) print(json.dumps(result, indent=2)) return 0 if result.get("passed") else 1 except McpError as e: diff --git a/tools/mcp/run_sweep.py b/tools/mcp/run_sweep.py index 3ec73f007f..4d389240b9 100755 --- a/tools/mcp/run_sweep.py +++ b/tools/mcp/run_sweep.py @@ -133,7 +133,7 @@ class RunContext: @property def cwd(self): - # Empty: a .py file in the folder a script runs from shadows the modules run_script needs. + # Empty: a .py file in the folder a script runs from shadows the modules script_run needs. return os.path.join(self.run_dir, "cwd") diff --git a/tools/mcp/smoke_test.json b/tools/mcp/smoke_test.json index a1a7393c29..ec9661402c 100644 --- a/tools/mcp/smoke_test.json +++ b/tools/mcp/smoke_test.json @@ -5,32 +5,32 @@ // or headless with // orca-slicer --run tools/mcp/smoke_test.json --outputdir /tmp/smoke { - "orca_replay_version": "0.1.0", + "orca_replay_version": "0.2.0", "name": "smoke", "vars": {"model": "${replay_dir}/../../resources/handy_models/3DBenchy.drc"}, "steps": [ - {"tool": "wait", "args": {"for": "ready"}}, - // Startup may ask to restore a project an earlier run left unsaved, and new_project asks about + {"tool": "app_wait", "args": {"for": "ready"}}, + // Startup may ask to restore a project an earlier run left unsaved, and project_new asks about // unsaved changes. The rules end with the replay, so they never answer a prompt after the run. - {"tool": "auto_answer_dialogs", "args": {"rules": [{"match": "unsaved changes", "button": "no"}, - {"match": "restore", "button": "no"}]}}, - {"tool": "new_project", "args": {"silent": true}}, - {"tool": "open_files", "args": {"paths": ["${vars.model}"]}, "expect": {"/added": {"eq": 1}}}, - {"tool": "set_settings", "args": {"scope": "process", "values": {"wall_loops": 3}}}, - {"tool": "get_settings", "args": {"scope": "process", "keys": ["wall_loops"]}, "expect": {"/items/0/value": {"eq": "3"}}}, - {"tool": "slice", "expect": {"/status": {"eq": "done"}, "/plates/0/outcome": {"eq": "ok"}}}, - {"tool": "export", "args": {"format": "gcode", "path": "${out_dir}/benchy.gcode", "overwrite": true}}, + {"tool": "dialog_auto_answer", "args": {"rules": [{"match": "unsaved changes", "button": "no"}, + {"match": "restore", "button": "no"}]}}, + {"tool": "project_new", "args": {"silent": true}}, + {"tool": "project_import", "args": {"paths": ["${vars.model}"]}, "expect": {"/added": {"eq": 1}}}, + {"tool": "settings_set", "args": {"type": "process", "values": {"wall_loops": 3}}}, + {"tool": "settings_get", "args": {"type": "process", "keys": ["wall_loops"]}, "expect": {"/items/0/value": {"eq": "3"}}}, + {"tool": "plate_slice", "expect": {"/status": {"eq": "done"}, "/plates/0/outcome": {"eq": "ok"}}}, + {"tool": "project_export", "args": {"format": "gcode", "path": "${out_dir}/benchy.gcode", "overwrite": true}}, // The action blocks in the dialog it opens, so it is not awaited until the dialog is answered. - {"tool": "run_action", "args": {"id": "orca_command:open_preferences:orca"}, "await": false, "save_as": "prefs"}, - {"tool": "wait", "args": {"for": "dialog", "timeout_s": 10}, "expect": {"/satisfied": {"eq": true}}}, - {"tool": "list_widgets", "args": {"target": "dialog", "query": "splash"}, "expect": {"/nodes": {"ge": 1}}}, - {"tool": "screenshot", "args": {"target": "dialog", "save_path": "${out_dir}/preferences.png", "overwrite": true, "include_image": false}}, - {"tool": "answer_dialog", "args": {"dialog": {"title": "Preferences"}, "button": "close"}}, - {"tool": "wait", "args": {"for": "job", "job": "${jobs.prefs}"}}, + {"tool": "action_run", "args": {"id": "orca_command:open_preferences:orca"}, "await": false, "save_as": "prefs"}, + {"tool": "app_wait", "args": {"for": "dialog", "timeout_s": 10}, "expect": {"/satisfied": {"eq": true}}}, + {"tool": "widget_list", "args": {"target": "dialog", "query": "splash"}, "expect": {"/nodes": {"ge": 1}}}, + {"tool": "window_screenshot", "args": {"target": "dialog", "save_path": "${out_dir}/preferences.png", "overwrite": true, "include_image": false}}, + {"tool": "dialog_answer", "args": {"dialog": {"title": "Preferences"}, "button": "close"}}, + {"tool": "app_wait", "args": {"for": "job", "job": "${jobs.prefs}"}}, - {"tool": "set_view", "args": {"tab": "preview", "camera": "iso"}}, - {"tool": "screenshot", "args": {"target": "canvas", "save_path": "${out_dir}/preview.png", "overwrite": true, "include_image": false}}, - {"tool": "screenshot", "args": {"target": "main", "save_path": "${out_dir}/window.png", "overwrite": true, "include_image": false}} + {"tool": "view_set", "args": {"tab": "preview", "camera": "iso"}}, + {"tool": "window_screenshot", "args": {"target": "canvas", "save_path": "${out_dir}/preview.png", "overwrite": true, "include_image": false}}, + {"tool": "window_screenshot", "args": {"target": "main", "save_path": "${out_dir}/window.png", "overwrite": true, "include_image": false}} ] } diff --git a/tools/mcp/sweep.json b/tools/mcp/sweep.json index e63b6f89aa..8d70cbba19 100644 --- a/tools/mcp/sweep.json +++ b/tools/mcp/sweep.json @@ -11,10 +11,14 @@ "calibration": {"path": "tests/calibration.json"}, "context_menus": {"path": "tests/context_menus.json"}, "dialogs_canvas_input": {"path": "tests/dialogs_canvas_input.json"}, + "filaments_and_files": {"path": "tests/filaments_and_files.json"}, "gizmos": {"path": "tests/gizmos.json"}, "layers": {"path": "tests/layers.json"}, "multicolor": {"path": "tests/multicolor.json"}, "new_project_keeps_layer_gcode": {"path": "tests/new_project_keeps_layer_gcode.json"}, + "objects_files": {"path": "tests/objects_files.json"}, + "objects_order": {"path": "tests/objects_order.json"}, + "objects_state": {"path": "tests/objects_state.json"}, "ops_assign_filament_preset_multi_slot": {"path": "tests/ops_assign_filament_preset_multi_slot.json"}, "ops_assign_filament_preset_one_slot": {"path": "tests/ops_assign_filament_preset_one_slot.json"}, "ops_export_gcode": {"path": "tests/ops_export_gcode.json"}, @@ -37,13 +41,22 @@ "plate_icons": {"path": "tests/plate_icons.json"}, "plates": {"path": "tests/plates.json"}, "presets": {"path": "tests/presets.json"}, + "presets_and_plate_map": {"path": "tests/presets_and_plate_map.json"}, "preview": {"path": "tests/preview.json"}, "recording": {"path": "tests/recording.json"}, "rows": {"path": "tests/rows.json"}, + "rows_objects": {"path": "tests/rows_objects.json"}, + "rows_placement": {"path": "tests/rows_placement.json"}, + "rows_plates": {"path": "tests/rows_plates.json"}, + "rows_structure": {"path": "tests/rows_structure.json"}, "scene": {"path": "tests/scene.json"}, + "settings_targets": {"path": "tests/settings_targets.json"}, "slice_stats": {"path": "tests/slice_stats.json"}, + "tiles_ask": {"path": "tests/tiles_ask.json", "cad": true}, + "view_switches": {"path": "tests/view_switches.json"}, "web_dialogs": {"path": "tests/web_dialogs.json"}, "test_action_replay_hidden": {"path": "test_action_replay_hidden.py"}, + "test_additions_refusals": {"path": "test_additions_refusals.py"}, "test_cad_click_edit": {"path": "test_cad_click_edit.py", "cad": true}, "test_cad_commands": {"path": "test_cad_commands.py", "cad": true}, "test_cad_context_menu": {"path": "test_cad_context_menu.py", "cad": true}, @@ -54,19 +67,29 @@ "test_cad_slow_build": {"path": "test_cad_slow_build.py", "cad": true}, "test_cancel_pending_slice": {"path": "test_cancel_pending_slice.py"}, "test_command_line": {"path": "test_command_line.py", "launch": "own", "args": ["--bin", "{bin}"], "locks": ["port-13694"], "why": "both serve on the fixed port 13694"}, + "test_every_tile": {"path": "test_every_tile.py", "exclusive": true, "why": "its tiles open web pages in the system's browser and the configuration folder in the file manager, which take the focus from the other instances"}, "test_export_running_job": {"path": "test_export_running_job.py", "env": {"ORCA_MCP_REPLY_BUDGET_MS": "10000"}}, + "test_install_filaments": {"path": "test_install_filaments.py", "launch": "own", "args": ["--bin", "{bin}"]}, + "test_install_printers": {"path": "test_install_printers.py", "launch": "own", "args": ["--bin", "{bin}"]}, "test_list_windows": {"path": "test_list_windows.py"}, "test_operation_routes": {"path": "test_operation_routes.py"}, "test_orca_mcp_attach": {"path": "test_orca_mcp_attach.py", "launch": "none"}, + "test_person_forms": {"path": "test_person_forms.py"}, + "test_plugin_commands": {"path": "test_plugin_commands.py", "launch": "own", "args": ["--bin", "{bin}"]}, "test_plugin_tools": {"path": "test_plugin_tools.py", "launch": "own", "args": ["--bin", "{bin}"]}, + "test_preferences": {"path": "test_preferences.py"}, + "test_printer_extruders": {"path": "test_printer_extruders.py", "launch": "own", "args": ["--bin", "{bin}"]}, + "test_project_open_settings": {"path": "test_project_open_settings.py", "launch": "own", "args": ["--bin", "{bin}"]}, "test_recovery_under_load": {"path": "test_recovery_under_load.py"}, "test_ref_locator_export": {"path": "test_ref_locator_export.py"}, + "test_rows_refusals": {"path": "test_rows_refusals.py"}, "test_run_sweep": {"path": "test_run_sweep.py", "launch": "none"}, "test_runtime_lifecycle": {"path": "test_runtime_lifecycle.py", "launch": "own", "args": ["--bin", "{bin}"], "locks": ["port-13694"], "why": "both serve on the fixed port 13694"}, "test_send_gcode": {"path": "test_send_gcode.py"}, "test_set_view_camera": {"path": "test_set_view_camera.py", "cad": true}, "test_set_view_preview": {"path": "test_set_view_preview.py"}, "test_set_window": {"path": "test_set_window.py"}, + "test_sidebar_floating": {"path": "test_sidebar_floating.py", "launch": "own", "args": ["--bin", "{bin}"]}, "test_speed_dial_open": {"path": "test_speed_dial_open.py", "cad": true, "exclusive": true, "why": "reads the keyboard focus, which another instance's launch takes on macOS"}, "test_stdio_bridge": {"path": "test_stdio_bridge.py", "args": ["--bin", "{bin}"]}, "test_web_ui": {"path": "test_web_ui.py", "setup": ["--install", "{datadir}"]}, diff --git a/tools/mcp/test_action_replay_hidden.py b/tools/mcp/test_action_replay_hidden.py index 670417b73a..c3852ccbdb 100755 --- a/tools/mcp/test_action_replay_hidden.py +++ b/tools/mcp/test_action_replay_hidden.py @@ -5,12 +5,12 @@ replay or a script can't act on them. tools/mcp/orca_mcp.py launch tools/mcp/test_action_replay_hidden.py -With Action Replay open: list_widgets lists no window for it, a window screenshot still works, -run_javascript without a target behaves as it did before the window opened (it must not find a second -web view), and press_keys without a target never reaches its web view. With the Run Script panel shown on -Prepare: list_widgets lists no more web views than before, run_javascript without a target behaves as -before, press_keys without a target reaches the 3D view, a window screenshot works and an agent's run_script -finishes. run_replay still runs the smoke test, and a replay nesting an inline run_replay passes. Exits +With Action Replay open: widget_list lists no window for it, a window screenshot still works, +webview_run_javascript without a target behaves as it did before the window opened (it must not find a second +web view), and keyboard_press without a target never reaches its web view. With the Run Script panel shown on +Prepare: widget_list lists no more web views than before, webview_run_javascript without a target behaves as +before, keyboard_press without a target reaches the 3D view, a window screenshot works and an agent's script_run +finishes. replay_run still runs the smoke test, and a replay nesting an inline replay_run passes. Exits 0 when every check passes. """ @@ -35,61 +35,61 @@ def main(): def eval_outcome(): try: - return "result: " + str(client.call("run_javascript", code="1 + 1").get("result")) + return "result: " + str(client.call("webview_run_javascript", code="1 + 1").get("result")) except orca_mcp.McpError as e: return "error: " + str(e) def webview_nodes(): - _snap, texts = client.call_with_text("list_widgets") + _snap, texts = client.call_with_text("widget_list") return len(re.findall(r"\bwebview\b", texts[0] if texts else "")) - client.call("new_project", discard_changes=True) - client.call("set_view", tab="home") + client.call("project_new", discard_changes=True) + client.call("view_set", tab="home") before = eval_outcome() - client.call("run_action", id="orca_command:open_action_replay:orca") + client.call("action_run", id="orca_command:open_action_replay:orca") time.sleep(1.0) # let its web view load - snap, texts = client.call_with_text("list_widgets") + snap, texts = client.call_with_text("widget_list") tree = texts[0] if texts else "" # The File menu's "Action Replay..." item is listed; the window must not be. - check("list_widgets lists no Action Replay window", 'window "Action Replay"' not in tree) - check("list_widgets still lists the main window", "(MainFrame)" in tree) - check("a window screenshot works", client.call("screenshot", target="main").get("path")) - check("run_javascript without a target behaves as before", eval_outcome() == before, f"{before} / {eval_outcome()}") + check("widget_list lists no Action Replay window", 'window "Action Replay"' not in tree) + check("widget_list still lists the main window", "(MainFrame)" in tree) + check("a window screenshot works", client.call("window_screenshot", target="main").get("path")) + check("webview_run_javascript without a target behaves as before", eval_outcome() == before, f"{before} / {eval_outcome()}") - client.call("set_view", tab="prepare") - client.call("run_action", id="orca_command:open_action_replay:orca") # raised again, so it has the focus - key = client.call("press_keys", keys="Escape") + client.call("view_set", tab="prepare") + client.call("action_run", id="orca_command:open_action_replay:orca") # raised again, so it has the focus + key = client.call("keyboard_press", keys="Escape") check("a key without a target never goes to Action Replay's web view", "webview" not in str(key.get("to", "")).lower(), key) # The Run Script panel, docked under the 3D view of Prepare. - client.call("set_view", tab="prepare") + client.call("view_set", tab="prepare") nodes_before = webview_nodes() prepare_eval = eval_outcome() - client.call("run_action", id="orca_command:toggle_run_script_panel:orca") + client.call("action_run", id="orca_command:toggle_run_script_panel:orca") time.sleep(1.0) # let its web view load - check("list_widgets lists no node of the Run Script panel", webview_nodes() == nodes_before, f"{nodes_before} / {webview_nodes()}") - check("run_javascript without a target behaves as before the panel", eval_outcome() == prepare_eval, f"{prepare_eval} / {eval_outcome()}") - key = client.call("press_keys", keys="Escape") + check("widget_list lists no node of the Run Script panel", webview_nodes() == nodes_before, f"{nodes_before} / {webview_nodes()}") + check("webview_run_javascript without a target behaves as before the panel", eval_outcome() == prepare_eval, f"{prepare_eval} / {eval_outcome()}") + key = client.call("keyboard_press", keys="Escape") check("a key without a target reaches the 3D view", "canvas" in str(key.get("to", "")).lower(), key) - check("a window screenshot works with the panel shown", client.call("screenshot", target="main").get("path")) - python = client.await_job(client.call("run_script", code="print('agent run')")) - check("an agent's run_script finishes while the panel is shown", python.get("status") == "finished", python) - client.call("run_action", id="orca_command:toggle_run_script_panel:orca") # hidden again + check("a window screenshot works with the panel shown", client.call("window_screenshot", target="main").get("path")) + python = client.await_job(client.call("script_run", code="print('agent run')")) + check("an agent's script_run finishes while the panel is shown", python.get("status") == "finished", python) + client.call("action_run", id="orca_command:toggle_run_script_panel:orca") # hidden again out = tempfile.mkdtemp(prefix="orca-runner-") - smoke = client.await_job(client.call("run_replay", path=os.path.join(HERE, "smoke_test.json"), out_dir=out)) - check("run_replay still runs the smoke test", smoke.get("passed") is True, smoke.get("failed_step")) + smoke = client.await_job(client.call("replay_run", path=os.path.join(HERE, "smoke_test.json"), out_dir=out)) + check("replay_run still runs the smoke test", smoke.get("passed") is True, smoke.get("failed_step")) nested = { - "orca_replay_version": "0.1.0", + "orca_replay_version": "0.2.0", "name": "nested", - "steps": [{"tool": "run_replay", "args": {"replay": {"orca_replay_version": "0.1.0", "steps": [{"tool": "get_app_state"}]}}, + "steps": [{"tool": "replay_run", "args": {"replay": {"orca_replay_version": "0.2.0", "steps": [{"tool": "app_state"}]}}, "expect": {"/passed": {"eq": True}}}], } - result = client.await_job(client.call("run_replay", replay=nested, out_dir=os.path.join(out, "nested"))) - check("a replay nesting an inline run_replay passes", result.get("passed") is True, result) + result = client.await_job(client.call("replay_run", replay=nested, out_dir=os.path.join(out, "nested"))) + check("a replay nesting an inline replay_run passes", result.get("passed") is True, result) failed = [c for c in checks if not c[1]] for name, ok, detail in checks: diff --git a/tools/mcp/test_additions_refusals.py b/tools/mcp/test_additions_refusals.py new file mode 100644 index 0000000000..4d617a5552 --- /dev/null +++ b/tools/mcp/test_additions_refusals.py @@ -0,0 +1,259 @@ +#!/usr/bin/env python3 +"""Checks that the filament, preset, export and import commands refuse with an error where they cannot run. + + tools/mcp/orca_mcp.py launch + tools/mcp/test_additions_refusals.py + +preset_sync while signed out is refused, and so is filament_sync_ams, as its tile and with each mode, with no printer +connected. view_set of a layer on a plate with no slice is refused, and leaves the legend's +fold and the G-code window, given beside it, as they were. project_export of each object as its own STL, as its tile and with a folder, +is refused for a project with no objects, and of the toolpaths as an OBJ while the Preview shows none; a pick of either +tile from the Speed Dial (Space on the 3D view, the search field, a click on the tile) shows the refusal as a notice and +opens no dialog. project_import of an entry a ZIP archive lacks is refused with the names the archive has, and imports +nothing (the archive is written by tests/fixtures/filaments_and_files.py, in the configuration folder). + +On a cube with a modifier and two height ranges, settings_set of layer_height on the modifier, and settings_get of it, +are refused naming where it is set (an object or a height range); settings_set of a null layer_height on a height range +is refused, the range always having one; settings_get of a height range the cube lacks is refused with the ranges it +has; and settings_get of the filament settings with target object is refused, a target's settings being process +settings. None of them changes the settings. A height range's own settings show on its row of the object list (the +row's note in widget_list says "has settings", as the icon that resets them shows), set by settings_set and gone when +a null leaves the range none, and the list's selection stays as it was. With a G-code file of no settings open, the +sidebar is off, and view_set of it is refused. + +filament_delete of the only filament slot is refused. With a mixed filament of slots 1 and 2, a merge of slot 1 into it +is refused with the question Merge with asks, and filament_delete of the mixed slot is refused. filament_add once the +project holds as many filament slots as it can is refused, and a pick of Add Filament Slot then says so, as its row did. + +object_order with an order that leaves out an object of the plate is refused, naming it, and leaves the order as it was. + +A refusal is an error a replay cannot expect, which is why this is a script. Exits 0 when every check passes. +""" + +import json +import os +import re +import sys +import tempfile + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import orca_mcp # noqa: E402 + +CANVAS = {"name": "OrcaSceneCanvas"} +FILES = os.path.join(os.path.dirname(os.path.abspath(__file__)), "tests", "fixtures", "filaments_and_files.py") +# A G-code file with no settings in it, which the app shows without its sidebar. +GCODE = """G90 +M82 +G28 +G1 Z0.2 F3000 +G1 X50 Y50 F6000 +G1 X100 Y50 E5 F1200 +G1 X100 Y100 E10 +G1 X50 Y100 E15 +""" +CUBE = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "resources", "handy_models", + "OrcaCube_v2.drc")) +# The most filament slots a project holds (MAXIMUM_EXTRUDER_NUMBER, libslic3r.h). +MOST_SLOTS = 64 + + +def main(): + client, _session = orca_mcp.session_client() + checks = [] + + def check(name, ok, detail=""): + checks.append((name, bool(ok), detail)) + + def refused(name, tool, args, expect, code=None): + """Calls `tool` and checks that it fails with an error whose text holds `expect` and, when `code` is given, + whose details carry that refusal code; returns the error's details.""" + try: + reply = client.call(tool, **args) + check(name, False, reply) + return {} + except orca_mcp.McpError as e: + check(name, expect in str(e), str(e)) + # A refusal's details, its code among them, are on the line after its text. + try: + details = json.loads(str(e).rpartition("\n")[2]) + except ValueError: + details = {} + if code is not None: + check(name + f", as {code}", isinstance(details, dict) and details.get("code") == code, str(e)) + return details if isinstance(details, dict) else {} + + def slots(): + """How many filament slots the project has: app_state names each slot's preset.""" + return len(client.call("app_state")["presets"]["filaments"]) + + def dial_pick(title): + """Opens the Speed Dial on the shown 3D view and picks the tile titled `title`, as a person's click does.""" + client.call("keyboard_press", keys="space", target=CANVAS) + client.call("widget_set_value", target={"web": "Search actions"}, value=title, submit=False) + return client.call("widget_click", target={"web": f"{title} from Orcaslicer", "kind": "button"}) + + def picked(title): + """The notices and dialogs once a pick of `title` has run.""" + dial_pick(title) + client.call("app_wait", **{"for": "idle"}) + state = client.call("app_state") + return [n.get("text", "") for n in state.get("notifications", [])], state.get("dialogs", []) + + client.call("app_wait", **{"for": "ready"}) + client.call("project_new", discard_changes=True, preset_changes="discard") + client.call("view_set", tab="prepare") + + # ---- Syncing presets needs an account ---- + refused("preset_sync while signed out is refused", "preset_sync", {}, "Sign in", "not_signed_in") + + # ---- Syncing the filaments from the AMS needs a printer ---- + refused("filament_sync_ams with no printer connected is refused", "filament_sync_ams", {}, "Connect a printer", "no_printer") + for mode in ("map", "overwrite"): + refused(f"filament_sync_ams {{mode: {mode}}} with no printer connected is refused", "filament_sync_ams", {"mode": mode}, + "Connect a printer", "no_printer") + + # ---- A view_set refused for its layer leaves the legend's fold and the G-code window ---- + view = client.call("app_state")["view"] + refused("view_set of a layer on a plate with no slice is refused", "view_set", + {"gcode_window": not view["gcode_window"], "legend_collapsed": not view["legend_collapsed"], "layer": 3}, + "Slice the plate first", "no_layers") + after = client.call("app_state")["view"] + check("and leaves the G-code window and the legend's fold as they were", + (after["gcode_window"], after["legend_collapsed"]) == (view["gcode_window"], view["legend_collapsed"]), (view, after)) + client.call("view_set", tab="prepare") + + # ---- Exports of a project with no objects, and of toolpaths the Preview does not show ---- + check("the project has no objects", client.call("object_list").get("total") == 0) + refused("project_export of each object as an STL, as its tile, is refused for a project with no objects", "project_export", + {"format": "stl", "per_object": True}, "no objects", "no_objects") + folder = tempfile.mkdtemp(prefix="per_object_") + refused("project_export of each object as an STL into a folder is refused for a project with no objects", "project_export", + {"format": "stl", "per_object": True, "path": folder}, "no objects", "no_objects") + check("and writes no file", os.listdir(folder) == [], os.listdir(folder)) + refused("project_export of the toolpaths as an OBJ is refused while the Preview shows none", "project_export", + {"format": "toolpaths_obj"}, "Preview", "no_toolpaths") + notices, dialogs = picked("Export All Objects as STLs") + check("a pick of Export All Objects as STLs on a project with no objects says it has none", + "The project has no objects." in notices, notices) + check("and opens no dialog", dialogs == [], dialogs) + notices, dialogs = picked("Export Toolpaths as OBJ") + check("a pick of Export Toolpaths as OBJ with no toolpaths in the Preview says so", + any("The Preview shows no toolpaths" in text for text in notices), notices) + check("and opens no dialog", dialogs == [], dialogs) + + # ---- An entry a ZIP archive lacks ---- + archive = client.call("script_run", filename=FILES, code="import filaments_and_files\nresult = filaments_and_files.write_zip(args)", + args={"name": "refusals.zip", "cubes": {"cube.stl": 10, "parts/block.stl": 15}})["result"]["path"] + details = refused("project_import of an entry the ZIP archive lacks is refused", "project_import", + {"paths": [archive], "entries": ["cube.stl", "missing.stl"]}, "no model file missing.stl", "no_such_entry") + check("with the model files the archive has", details.get("entries") == ["cube.stl", "parts/block.stl"], details) + check("and imports nothing", client.call("object_list").get("total") == 0) + + # ---- Settings on a target that does not take them, a height range the object lacks, a type with a target ---- + client.call("project_import", paths=[CUBE]) + client.call("object_transform", object=0, size=[20, 20, 20]) + client.call("part_add", object=0, type="modifier", shape="cube", size=[5, 5, 5]) + client.call("object_set_height_ranges", object=0, ranges=[{"min_z": 0, "max_z": 5}, {"min_z": 5, "max_z": 10}]) + + def overrides(**target): + return {item["key"]: item["value"] for item in client.call("settings_get", **target)["items"]} + + def range_row(heights): + """The object list's row of object 0's height range `heights` ("0-5"), as widget_list's tree lists it.""" + _, texts = client.call_with_text("widget_list", target="main", query="row", include_menus=False, include_web=False) + rows = [line for text in texts for line in text.splitlines() if f"object 0 layer range {heights}" in line] + return rows[0] if rows else "" + + def selected_rows(): + """The object list's selected rows, without the refs, which change at every listing.""" + _, texts = client.call_with_text("widget_list", target="main", query="row", include_menus=False, include_web=False) + return [re.sub(r"^\[r\d+\] ", "", line.strip()) for text in texts for line in text.splitlines() if "selected]" in line] + + modifier = {"target": "part", "object": 0, "part": 1} + lower = {"target": "height_range", "object": 0, "min_z": 0, "max_z": 5} + before = overrides(**modifier) + refused("settings_set of layer_height on a part is refused, naming the object and the height range", "settings_set", + {**modifier, "values": {"layer_height": 0.1}}, "layer_height is set on an object or a height range, not on a part") + check("and leaves the part's settings", overrides(**modifier) == before, overrides(**modifier)) + refused("settings_get of layer_height on a part is refused, naming where it is set", "settings_get", + {**modifier, "keys": ["layer_height"]}, "layer_height is set on an object or a height range, not on a part") + check("and leaves the part's settings too", overrides(**modifier) == before, overrides(**modifier)) + range_before = overrides(**lower) + refused("settings_set of a null layer_height on a height range is refused", "settings_set", + {**lower, "values": {"layer_height": None}}, "A height range keeps its layer_height") + check("and leaves the range's settings", overrides(**lower) == range_before, (range_before, overrides(**lower))) + + # A height range's own settings show on its row, as a change in its panel shows them. + shown = selected_rows() + check("height range 0-5 has no settings of its own on its row", "has settings" not in range_row("0-5"), range_row("0-5")) + client.call("settings_set", **lower, values={"wall_loops": 6}) + check("settings_set of wall_loops on it shows the row with settings", "has settings" in range_row("0-5"), range_row("0-5")) + client.call("settings_set", **lower, values={"wall_loops": None}) + check("and a null that leaves the range none takes them away", "has settings" not in range_row("0-5"), range_row("0-5")) + check("the object list's selection stays as it was", selected_rows() == shown, (shown, selected_rows())) + details = refused("settings_get of a height range the object lacks is refused", "settings_get", + {"target": "height_range", "object": 0, "min_z": 0, "max_z": 7}, "object 0 has no height range 0-7; it has 0-5, 5-10") + check("with the ranges it has", details.get("height_ranges") == [{"min_z": 0, "max_z": 5}, {"min_z": 5, "max_z": 10}], details) + refused("settings_get of the filament settings with target object is refused", "settings_get", + {"type": "filament", "target": "object", "object": 0}, "The filament settings have no target object") + check("and the object's ranges stay", len(client.call("object_list")["plates"][0]["objects"][0]["layer_config_ranges"]) == 2) + client.call("project_new", discard_changes=True) + + # ---- The sidebar is off while a G-code file without its settings is shown ---- + gcode = os.path.join(tempfile.mkdtemp(prefix="no_settings_"), "lines.gcode") + with open(gcode, "w", encoding="utf-8") as f: + f.write(GCODE) + client.call("project_open", path=gcode) + view = client.call("app_state")["view"] + refused("view_set of the sidebar while a G-code file without its settings is shown is refused", "view_set", + {"sidebar_collapsed": not view["sidebar_collapsed"]}, "The sidebar is off while a G-code file is shown") + check("and leaves the sidebar as it was", client.call("app_state")["view"]["sidebar_collapsed"] == view["sidebar_collapsed"]) + client.call("project_new", discard_changes=True) + client.call("view_set", tab="prepare") + + # ---- Filament slots: the only one is not deleted, and a slot is not merged into a mixed filament that mixes it ---- + check("the project has one filament slot", slots() == 1, slots()) + refused("filament_delete of the only filament slot is refused", "filament_delete", {}, "only filament slot", + "last_filament_slot") + check("and deletes no slot", slots() == 1, slots()) + client.call("filament_add") + mixed = client.call("filament_add_mixed", components=[1, 2], ratios=[50, 50]) + check("a mixed filament of slots 1 and 2 is slot 3", mixed.get("filament_slot") == 3, mixed) + refused("filament_delete of slot 1 merged into the mixed filament that mixes it is refused", "filament_delete", + {"filament_slot": 1, "merge_into": 3}, "uses this physical filament", "mixed_uses_slot") + refused("filament_delete of the mixed filament is refused", "filament_delete", {"filament_slot": 3}, "is a mixed filament", + "mixed_filament_slot") + check("and both leave the three slots", slots() == 3, slots()) + + # ---- No slot is added past the most a project holds ---- + for _ in range(MOST_SLOTS - slots()): + client.call("filament_add") + check(f"{MOST_SLOTS} filament slots", slots() == MOST_SLOTS, slots()) + refused("filament_add with as many filament slots as a project holds is refused", "filament_add", {}, "No more filament slots", + "too_many_filaments") + check("and adds no slot", slots() == MOST_SLOTS, slots()) + notices, dialogs = picked("Add Filament Slot") + check("a pick of Add Filament Slot then says no more can be added", "No more filament slots can be added." in notices, notices) + check("and adds no slot either", slots() == MOST_SLOTS, slots()) + + # ---- An order of objects names each of the plate's objects once ---- + client.call("project_new", discard_changes=True) + client.call("view_set", tab="prepare") + for _ in range(2): + client.call("object_add_primitive", shape="cube", size=[20, 20, 20]) + client.call("object_select", none=True) + names = lambda: [o["name"] for o in client.call("object_list")["plates"][0]["objects"]] + before = names() + refused("object_order with an order that leaves out an object of the plate is refused, naming it", "object_order", + {"plate": 0, "order": [1]}, "leaves out objects of plate 0: 0", "order_misses_object") + check("and leaves the order as it was", names() == before, (before, names())) + + failed = [c for c in checks if not c[1]] + for name, ok, detail in checks: + print(("PASS " if ok else "FAIL ") + name + ("" if ok else f": {detail}")) + print(f"{len(checks) - len(failed)}/{len(checks)} checks passed") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/mcp/test_cad_click_edit.py b/tools/mcp/test_cad_click_edit.py index 294ef69638..baebd107b6 100755 --- a/tools/mcp/test_cad_click_edit.py +++ b/tools/mcp/test_cad_click_edit.py @@ -98,7 +98,7 @@ def type_into_open_field(rung, value, what, measure, opened_by="by itself"): the field took it; returns whether a field opened. No click and no target for the keys: the field opens holding the keyboard, as a person sees it. - list_widgets reads the field as an ImGui input whose value is its text, the prefill until + widget_list reads the field as an ImGui input whose value is its text, the prefill until something is typed and then the digits that landed. Return commits the text the field holds, so a field the digits never reached commits its prefill, which the geometry then shows. `what` names the quantity `measure` reads off sketch_describe, the one the field sets.""" diff --git a/tools/mcp/test_cad_commands.py b/tools/mcp/test_cad_commands.py index eb58432892..74835c5f55 100644 --- a/tools/mcp/test_cad_commands.py +++ b/tools/mcp/test_cad_commands.py @@ -28,7 +28,7 @@ card's width and height, a Project sketch, and any index while a sketch is open. shrinks the sketch of a block whose top edge is filleted until the fillet cannot rebuild, and sketch_edit_empty deletes every entity: in both sketch_finish replies ok false, that the sketch was not replaced and why, the design and its undo depth are as they were, and the next sketch_create opens a new sketch, which its sketch_finish adds -after the others. The failed replace's session, exported with export_replay, keeps that sketch_finish and replays +after the others. The failed replace's session, exported with replay_export, keeps that sketch_finish and replays in a new project to the same features. sketch_edit_failed_leave leaves the same failing edit through sketch_text {} and through K, which finish the sketch before they open the Text dialog or Constrain mode: each stops with the status line saying the sketch could not be replaced, nothing open and the design as it was. @@ -55,7 +55,7 @@ opens the card of a Hole drilled into a block's side, which a later Fillet renum the Hole goes into that face, its plane read in the model before it. edit_repick_hidden hides a second block and opens the Fillet's card: a click on the hidden block picks nothing, and after the block is shown and hidden again with the card open, an edge picked is still named by its id in the model before the Fillet. -design_view sets set_view's Design options on a block: a section view at a height and its upper half, one at the +design_view sets view_set's Design options on a block: a section view at a height and its upper half, one at the model's middle when the height is left out, and each of the four switches on and off, as the reply reads them back. sketch_normal with no sketch open is refused, leaving the view as it was, and in a sketch on XZ looks along the plane's normal; the Design options given without tab design are refused. @@ -94,7 +94,7 @@ boolean_opens calls boolean {} and boolean {operation: "cut"} with two bodies an a tool is open, and the card it opened, confirmed with confirm_tool, adds a join and a cut; with target and tool the cut runs. tile_pick opens the Speed Dial in a sketch with a line selected and picks the Polar array tile, a row folded into sketch_pattern, which arms the polar array tool, and the Trim tile, sketch_trim's own, which arms the trim tool. -tile_replay runs the Polar array tile with run_action, exports the session, whose step carries the row's arguments +tile_replay runs the Polar array tile with action_run, exports the session, whose step carries the row's arguments {"type": "circular"}, and replays it in a new project to the same armed tool. """ @@ -475,7 +475,7 @@ def rung_sketch_edit_cancel(): gui.cad("sketch_edit", sketch=sketch) gui.cad("sketch_draw", type="circle_center", center=[10, 5], radius=2) gui.cad("sketch_cancel") - dialogs = gui.client.call("get_app_state").get("dialogs", []) + dialogs = gui.client.call("app_state").get("dialogs", []) gui.check("sketch_edit_cancel: sketch_cancel asks nothing", not dialogs, dialogs) gui.check("sketch_edit_cancel: no sketch is left open", gui._sketch_or_none() is None, gui._sketch_or_none()) gui.check("sketch_edit_cancel: the design is as it was", state() == before, f"{before} -> {state()}") @@ -533,7 +533,7 @@ def not_replaced(rung, reply, sketch, why): def steps_of(path): - """The steps of the replay export_replay wrote at `path`, its // comment lines left out.""" + """The steps of the replay replay_export wrote at `path`, its // comment lines left out.""" with open(path) as f: text = f.read() return json.loads("\n".join(l for l in text.splitlines() if not l.lstrip().startswith("//")))["steps"] @@ -542,7 +542,7 @@ def steps_of(path): def rung_sketch_edit_failed_replace(): # The session the replay must reproduce starts on the empty design. gui.new_design() - gui.client.call("export_replay", clear=True) + gui.client.call("replay_export", clear=True) sketch = block_on_rectangle() round_top_edge() before = state() @@ -559,12 +559,12 @@ def rung_sketch_edit_failed_replace(): live = [f["type"] for f in gui.cad("describe_design")["features"]] out_dir = tempfile.mkdtemp(prefix="orca-mcp-sketch-edit-") path = os.path.join(out_dir, "session.json") - gui.client.call("export_replay", path=path, overwrite=True) + gui.client.call("replay_export", path=path, overwrite=True) tools = [s["tool"] for s in steps_of(path)] gui.check("sketch_edit_failed_replace: the export keeps the sketch_finish that did not replace", tools.count("sketch_edit") == 1 and tools.count("sketch_finish") == 3, tools) - gui.client.call("new_project", discard_changes=True) - replay = gui.client.await_job(gui.client.call("run_replay", path=path, out_dir=out_dir), timeout=900) + gui.client.call("project_new", discard_changes=True) + replay = gui.client.await_job(gui.client.call("replay_run", path=path, out_dir=out_dir), timeout=900) gui.check("sketch_edit_failed_replace: the exported session replays", replay.get("passed") is True, [s for s in replay.get("steps", []) if not s.get("ok")][:1]) replayed = [f["type"] for f in gui.cad("describe_design")["features"]] @@ -694,7 +694,7 @@ def features(): def nothing_open(rung): """No dialog is open, modal or modeless, and no sketch session: no placement step was left for a person.""" - dialogs = gui.client.call("get_app_state").get("dialogs", []) + dialogs = gui.client.call("app_state").get("dialogs", []) gui.check(f"{rung}: no dialog is open", not dialogs and not gui.modeless(), [dialogs, gui.modeless()]) gui.check(f"{rung}: no sketch session is open", gui._sketch_or_none() is None, gui._sketch_or_none()) @@ -773,7 +773,7 @@ def rung_svg_art(): def row_menu(name, item): """The item `item` of the Feature tree row `name`'s right-click menu.""" - gui.client.call("click", target={"row": name}, button="right", popup_item=item) + gui.client.call("widget_click", target={"row": name}, button="right", popup_item=item) def rung_scale_artwork(): @@ -829,14 +829,14 @@ def rung_surface_revolve_flip(): def view(**args): - """set_view's reply to `args` given with tab design.""" - return gui.client.call("set_view", tab="design", **args) + """view_set's reply to `args` given with tab design.""" + return gui.client.call("view_set", tab="design", **args) def view_refused(**args): - """Why set_view refuses `args`; empty when it runs.""" + """Why view_set refuses `args`; empty when it runs.""" try: - gui.client.call("set_view", **args) + gui.client.call("view_set", **args) except orca_mcp.McpError as e: return str(e) return "" @@ -878,7 +878,7 @@ def rung_design_view(): why = view_refused(tab="design", camera="fit_bed", section={"on": True}) section = view().get("design", {}).get("section") or {} gui.check("design_view: fit_bed is refused, leaving the section view off", - "fit_bed is not offered" in why and section.get("on") is False, [why, section]) + "The Design tab has no bed to fit the view to." in why and section.get("on") is False, [why, section]) frame = gui.cad("sketch_create", plane="XZ")["frame"] state = view(camera="sketch_normal").get("camera_state", {}) @@ -926,7 +926,7 @@ def canvas_rows(out_dir, name): """The upper three quarters of a canvas screenshot's rows as its PNG stores them, apart from the status line and the readout the canvas draws along its bottom: equal for two screenshots exactly when their pixels there are.""" path = os.path.join(out_dir, name + ".png") - gui.client.call("screenshot", target="canvas", include_image=False, save_path=path, overwrite=True) + gui.client.call("window_screenshot", target="canvas", include_image=False, save_path=path, overwrite=True) with open(path, "rb") as f: data = f.read() pos, idat, width, height, channels = 8, b"", 0, 0, 0 @@ -1146,7 +1146,7 @@ def rung_select_loops(): gui.check("select_loops: {sketch, loop: 1} reads back sk_loop", r["selection"]["id"] == "sk_loop", r) # zoom_to_selection centres the view on what is selected: the loop sketch_describe calls 1. gui.cad("zoom_to_selection") - look = gui.client.call("get_app_state").get("camera", {}).get("look_at", []) + look = gui.client.call("app_state").get("camera", {}).get("look_at", []) want = centre(loops[1]) gui.check("select_loops: it selects the loop sketch_describe calls 1", len(look) == 3 and near(look[0], want[0], 1e-3) and near(look[1], want[1], 1e-3), [look, want]) @@ -1369,8 +1369,8 @@ def rung_edit_repick_hidden(): picked = selection() gui.check("edit_repick_hidden: a click on the hidden block picks nothing in the Fillet's card", picked == "none", picked) # The Bodies row's eye, as a person shows and hides a body with the card open. - gui.client.call("click", target={"row": "Body 2 — Block B", "column": "Show"}) - gui.client.call("click", target={"row": "Body 2 — Block B", "column": "Hide"}) + gui.client.call("widget_click", target={"row": "Body 2 — Block B", "column": "Show"}) + gui.client.call("widget_click", target={"row": "Body 2 — Block B", "column": "Hide"}) gui._follow_canvas() gui.click_mm(*on_frame(frame, mid(edge))) gui.click_mm(*on_frame(frame, other["centroid"])) @@ -1524,17 +1524,17 @@ COMMIT = "Commit to Plate — send the solid to Prepare" # the ribbon's Commit def plate_objects(): """How many objects the Prepare plate holds, on its plates and off them.""" - listed = gui.client.call("list_objects") + listed = gui.client.call("object_list") return sum(len(p["objects"]) for p in listed.get("plates", [])) + len(listed.get("outside", [])) def commit_stops(rung): """Press Commit to Plate over a card whose Confirm does not take, and check that it stops there: nothing sent to the plate, the Design tab still in front.""" - sent, tab = plate_objects(), gui.client.call("get_app_state").get("tab") + sent, tab = plate_objects(), gui.client.call("app_state").get("tab") gui.press(COMMIT) gui.check(f"{rung}: Commit to Plate sends nothing to the plate", plate_objects() == sent, [sent, plate_objects()]) - now = gui.client.call("get_app_state").get("tab") + now = gui.client.call("app_state").get("tab") gui.check(f"{rung}: the Design tab stays in front", now == tab, [tab, now]) @@ -1662,7 +1662,7 @@ def plate_offset(replace): room, so a part's place is read against another part of the same object.""" r = gui.cad("commit_to_plate", mode="assembly", replace=[] if replace is None else [replace]) index = r["objects"][0]["index"] - listed = gui.client.call("list_objects") + listed = gui.client.call("object_list") objects = [o for p in listed.get("plates", []) for o in p["objects"]] + listed.get("outside", []) parts = {p["name"]: p for o in objects if o["index"] == index for p in o["parts"]} return parts["Design Body 1"]["bbox"]["min"][0] - parts["Design Body 2"]["bbox"]["min"][0], index @@ -1859,8 +1859,8 @@ def rung_boolean_opens(): def dial_pick(title): """Opens the Speed Dial on the Design view and picks the tile titled `title` from it, as a person's click does.""" gui.keys("space", target=CANVAS) - gui.client.call("set_widget_value", target={"web": "Search actions"}, value=title, submit=False) - return gui.client.call("click", target={"web": f"{title} from Orcaslicer", "kind": "button"}) + gui.client.call("widget_set_value", target={"web": "Search actions"}, value=title, submit=False) + return gui.client.call("widget_click", target={"web": f"{title} from Orcaslicer", "kind": "button"}) def line_selected(): @@ -1885,25 +1885,25 @@ def rung_tile_pick(): def rung_tile_replay(): - # run_action of a folded row's tile is journaled with the row's arguments, so the exported session replays the pick. + # action_run of a folded row's tile is journaled with the row's arguments, so the exported session replays the pick. gui.new_design() - gui.client.call("export_replay", clear=True) + gui.client.call("replay_export", clear=True) gui.cad("sketch_create", plane="XY") gui.cad("sketch_draw", type="line", p0=[0, 0], p1=[10, 0]) gui.cad("sketch_select", entities=[0]) - r = gui.client.call("run_action", id="sk_array_polar") - gui.check("tile_replay: run_action of the Polar array tile opens its tool", r.get("result", {}).get("interactive") is True, r) + r = gui.client.call("action_run", id="sk_array_polar") + gui.check("tile_replay: action_run of the Polar array tile opens its tool", r.get("result", {}).get("interactive") is True, r) gui.check("tile_replay: it arms the polar array tool", gui.sketch()["tool"] == "array_polar", gui.sketch()["tool"]) out_dir = tempfile.mkdtemp(prefix="orca-mcp-tile-replay-") path = os.path.join(out_dir, "session.json") - gui.client.call("export_replay", path=path, overwrite=True) - picks = [s for s in steps_of(path) if s["tool"] == "run_action"] + gui.client.call("replay_export", path=path, overwrite=True) + picks = [s for s in steps_of(path) if s["tool"] == "action_run"] gui.check("tile_replay: the export keeps the pick with the row's arguments", len(picks) == 1 and picks[0]["args"].get("id") == "orca_command:sk_array_polar:orca" and picks[0]["args"].get("args") == {"type": "circular"}, picks) gui.cad("sketch_cancel") - gui.client.call("new_project", discard_changes=True) - replay = gui.client.await_job(gui.client.call("run_replay", path=path, out_dir=out_dir), timeout=900) + gui.client.call("project_new", discard_changes=True) + replay = gui.client.await_job(gui.client.call("replay_run", path=path, out_dir=out_dir), timeout=900) gui.check("tile_replay: the exported session replays", replay.get("passed") is True, [s for s in replay.get("steps", []) if not s.get("ok")][:1]) gui.check("tile_replay: the replayed pick arms the polar array tool", gui.sketch()["tool"] == "array_polar", diff --git a/tools/mcp/test_cad_context_menu.py b/tools/mcp/test_cad_context_menu.py index 8a767959d2..6d0eb6410d 100755 --- a/tools/mcp/test_cad_context_menu.py +++ b/tools/mcp/test_cad_context_menu.py @@ -803,8 +803,8 @@ def feature_names(): def rung_art(): """O7: Text and SVG, the two verbs that go through a dialog. - Text opens the Design tab's own Text dialog, which is modeless: answer_dialog and the - auto-answer rules never see it, so its field takes set_widget_value and its OK a click by + Text opens the Design tab's own Text dialog, which is modeless: dialog_answer and the + auto-answer rules never see it, so its field takes widget_set_value and its OK a click by label. Choosing it ends the empty sketch, and the text becomes a feature of its own, placed with the Insert gizmo. A text OK'd and then cancelled there must leave the design as it was, and a text kept with Confirm is graded. SVG opens a file picker, which a rule answers with the @@ -872,12 +872,12 @@ def rung_art(): leave() return # The picker is matched by its prompt, unanchored: a picker answered unshown has no title. - gui.client.call("auto_answer_dialogs", rules=[{"match": "Import SVG", "button": "ok", "path": SVG}]) + gui.client.call("dialog_auto_answer", rules=[{"match": "Import SVG", "button": "ok", "path": SVG}]) try: choose(o, *free, "sketch_insert_svg") finally: try: - gui.client.call("auto_answer_dialogs", rules=[]) + gui.client.call("dialog_auto_answer", rules=[]) except Exception as e: # reported, so that it does not hide an error from the choice gui.check("art: the Import SVG rule is cleared", False, f"{type(e).__name__}: {e}") ls, lp = ents("line"), loops() diff --git a/tools/mcp/test_cad_examples.py b/tools/mcp/test_cad_examples.py index 4e88635dfd..fe9469be43 100755 --- a/tools/mcp/test_cad_examples.py +++ b/tools/mcp/test_cad_examples.py @@ -4,8 +4,8 @@ tools/mcp/orca_mcp.py launch --cad tools/mcp/test_cad_examples.py [--tool NAME ...] -Lists the Design commands (search_tools {group: "Design"}), with undo and redo, which document the -Design history, reads each one's examples (search_tools {tool}), and runs every example of the named +Lists the Design commands (tool_search {group: "Design"}), with undo and redo, which document the +Design history, reads each one's examples (tool_search {tool}), and runs every example of the named commands (of all of them without --tool), each on a fresh, empty design: an open sketch is cancelled and new_design discards the rest. An argument {"from_call": i, "key": k} is the value under k in the result of call i of the same example. Every call is checked: an example fails when a call fails, or @@ -84,7 +84,7 @@ def main(): args = ap.parse_args() client, _ = orca_mcp.session_client() - names = client.call("search_tools", group="Design")["names"] + HISTORY + names = client.call("tool_search", group="Design")["names"] + HISTORY unknown = [t for t in args.tool if t not in names] if unknown: sys.exit(f"not Design commands: {', '.join(unknown)}") @@ -92,7 +92,7 @@ def main(): total = skipped = failures = 0 for name in wanted: - for example in client.call("search_tools", tool=name).get("examples") or []: + for example in client.call("tool_search", tool=name).get("examples") or []: total += 1 label = f"{name}: {example['title']}" if example.get("needs"): diff --git a/tools/mcp/test_cad_failed_job.py b/tools/mcp/test_cad_failed_job.py index 4c5e1ebde1..bd64575771 100755 --- a/tools/mcp/test_cad_failed_job.py +++ b/tools/mcp/test_cad_failed_job.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Checks that a Design-tab call whose job fails after its reply is left out of export_replay. +"""Checks that a Design-tab call whose job fails after its reply is left out of replay_export. tools/mcp/orca_mcp.py launch --cad tools/mcp/test_cad_failed_job.py @@ -35,7 +35,7 @@ REBUILD_S = max(orca_mcp.reply_budget_s() * 4 / 3, orca_mcp.reply_budget_s() + 4 def cad(client, tool, **args): """A Design command's reply: its {result}, or the envelope of the job it runs as.""" - return client.call("call_tool", _timeout=600, tool=tool, args=args) + return client.call("tool_call", _timeout=600, tool=tool, args=args) def coil(client, turns): @@ -64,8 +64,8 @@ def main(): # sizes has more turns. The hole must reply running and still run at the export after its reply. # One that fails inside the budget, or whose job has ended by the export, is made again with a # bigger coil. - client.call("export_replay", clear=True) - client.call("new_project", discard_changes=True) + client.call("replay_export", clear=True) + client.call("project_new", discard_changes=True) built = 12 calibration = coil(client, built) turns = max(built, min(40, round(built * (REBUILD_S / max(calibration, 0.5)) ** (1 / 3)))) @@ -74,8 +74,8 @@ def main(): running = False while True: if turns != built: - client.call("export_replay", clear=True) - client.call("new_project", discard_changes=True) + client.call("replay_export", clear=True) + client.call("project_new", discard_changes=True) coil(client, turns) built = turns start = time.time() @@ -90,11 +90,11 @@ def main(): continue if started.get("status") != "running": break - during = client.call("export_replay") + during = client.call("replay_export") # Asked of the job itself, which needs no UI thread (the rebuild may hold it); a failed job's - # reply is its error. The export leaves this wait out with the hole. + # reply is its error. The export leaves this app_wait out with the hole. try: - running = client.call("wait", **{"for": "job", "job": started["job"], "timeout_s": 0}).get("status") == "running" + running = client.call("app_wait", **{"for": "job", "job": started["job"], "timeout_s": 0}).get("status") == "running" except orca_mcp.McpError: running = False if during.get("left_out_running") or running or turns >= 40: @@ -124,7 +124,7 @@ def main(): live_scene = cad(client, "describe_design")["result"] live_mass = cad(client, "body_mass_properties", body=0)["result"] - after = client.call("export_replay", path=path, overwrite=True) + after = client.call("replay_export", path=path, overwrite=True) # A Design command's call is journaled as its own. tools = [s["tool"] for s in after["replay"]["steps"]] check("the export leaves the failed hole out", "hole" not in tools, tools) @@ -141,8 +141,8 @@ def main(): run_path = os.path.join(out_dir, "run.json") with open(run_path, "w") as f: json.dump(exported, f, indent=1) - client.call("new_project", discard_changes=True) - replay = client.await_job(client.call("run_replay", path=run_path, out_dir=out_dir), timeout=1800) + client.call("project_new", discard_changes=True) + replay = client.await_job(client.call("replay_run", path=run_path, out_dir=out_dir), timeout=1800) check("the exported session replays", replay.get("passed") is True, json.dumps([s for s in replay.get("steps", []) if not s.get("ok")][:1])) scene = cad(client, "describe_design")["result"] diff --git a/tools/mcp/test_cad_replay.py b/tools/mcp/test_cad_replay.py index cd0771e0eb..ba35286ba2 100755 --- a/tools/mcp/test_cad_replay.py +++ b/tools/mcp/test_cad_replay.py @@ -1,13 +1,13 @@ #!/usr/bin/env python3 -"""Checks that a Design-tab session exported with export_replay replays to the same part. +"""Checks that a Design-tab session exported with replay_export replays to the same part. tools/mcp/orca_mcp.py launch --cad tools/mcp/test_cad_replay.py -Records a session of Design command calls made through call_tool (replay steps are not journaled) on the +Records a session of Design command calls made through tool_call (replay steps are not journaled) on the paths a replay breaks on: a sketch on a base plane, which passes through modeling_origin as every plane does; an empty sketch commit, which fails and must keep the sketch open for the next call; commands -failing as an error (a hole that misses, a fillet the kernel refuses), which export_replay must +failing as an error (a hole that misses, a fillet the kernel refuses), which replay_export must leave out; a shell thicker than the plate, which reports the rejected rebuild in its reply (ok false) and stays in to replay the same rejection; and face and edge ids passed with the generation they were read at, which the journal drops, since the replay reaches other generation numbers. The @@ -27,7 +27,7 @@ import orca_mcp # noqa: E402 def cad(client, tool, **args): - return client.call("call_tool", _timeout=300, tool=tool, args=args)["result"] + return client.call("tool_call", _timeout=300, tool=tool, args=args)["result"] def refused(client, tool, **args): @@ -41,8 +41,8 @@ def refused(client, tool, **args): def record(client): """The session to export; returns the reads the replay must match and the refusals seen.""" - client.call("export_replay", clear=True) - client.call("new_project", discard_changes=True) + client.call("replay_export", clear=True) + client.call("project_new", discard_changes=True) cad(client, "new_design", discard_changes=True) frame = cad(client, "sketch_create", plane="XY")["frame"] empty_commit = refused(client, "sketch_finish") @@ -60,7 +60,7 @@ def record(client): rejected_shell = cad(client, "shell", thickness=20, body=0) bores = cad(client, "body_describe", body=0, kinds=["cylindrical"]) bore = next(f["id"] for f in bores["faces"] if f.get("internal")) - thread = client.await_job(client.call("call_tool", _timeout=300, tool="thread", + thread = client.await_job(client.call("tool_call", _timeout=300, tool="thread", args={"body": 0, "face": bore, "generation": bores["generation"]})) return {"mass": cad(client, "body_mass_properties", body=0), "scene": cad(client, "describe_design"), "frame": frame, "empty_commit": empty_commit, "missed_hole": missed_hole, "refused_fillet": refused_fillet, @@ -76,16 +76,16 @@ def main(): live = record(client) out_dir = tempfile.mkdtemp(prefix="orca-mcp-cad-replay-") path = os.path.join(out_dir, "session.json") - client.call("export_replay", path=path, overwrite=True) + client.call("replay_export", path=path, overwrite=True) with open(path) as f: text = f.read() steps = json.loads("\n".join(l for l in text.splitlines() if not l.lstrip().startswith("//")))["steps"] - # A Design command's call is journaled as its own; the session starts with new_project. - calls = [s for s in steps if s["tool"] != "new_project"] + # A Design command's call is journaled as its own; the session starts with project_new. + calls = [s for s in steps if s["tool"] != "project_new"] tools = [s["tool"] for s in calls] - client.call("new_project", discard_changes=True) - replay = client.await_job(client.call("run_replay", path=path, out_dir=out_dir), timeout=900) + client.call("project_new", discard_changes=True) + replay = client.await_job(client.call("replay_run", path=path, out_dir=out_dir), timeout=900) mass = cad(client, "body_mass_properties", body=0) scene = cad(client, "describe_design") kinds = lambda s: [f["type"] for f in s["features"]] # noqa: E731 (names count on across projects) diff --git a/tools/mcp/test_cad_sketching.py b/tools/mcp/test_cad_sketching.py index 63b2a1a0b8..267452f760 100755 --- a/tools/mcp/test_cad_sketching.py +++ b/tools/mcp/test_cad_sketching.py @@ -23,7 +23,7 @@ constraint produced and that it survives committing the sketch and opening it ag checks that a button that cannot apply stores nothing. badge clicks a constraint's badge, which selects it and deletes nothing, as does a double-click, then deletes it with Delete. undo and feature_undo undo inside a sketch and across its commit, from the keyboard. roundtrip saves the project and opens it again through -the File menu, its file pickers answered by auto_answer_dialogs rules with the path (skipped on +the File menu, its file pickers answered by dialog_auto_answer rules with the path (skipped on Linux, where a GTK picker can't take one). scale draws on top of a sketch holding 1204 entities, which it loads with one sketch_draw command while a tool is armed; the call says why. calibration_cache checks the harness itself: a sketch's plane-to-pixel map is reused in the view it @@ -128,16 +128,16 @@ def rung_calibration_cache(): gui.check("calibration_cache: the same view reuses its map", gui.full_calibrations == n, f"{gui.full_calibrations - n} more fit(s)") gui.cancel() - width, height = gui.client.call("get_app_state")["window"]["size"] + width, height = gui.client.call("app_state")["window"]["size"] # Shorter, not narrower: the ribbon's Cancel needs the width start() gave the window. - gui.client.call("set_window", size=[width, height - 120]) + gui.client.call("window_set", size=[width, height - 120]) try: gui.enter_sketch() gui.check("calibration_cache: a resized canvas is fitted again", gui.full_calibrations == n + 1, f"{gui.full_calibrations - n} more fit(s)") gui.cancel() finally: - gui.client.call("set_window", size=[width, height]) + gui.client.call("window_set", size=[width, height]) gui.enter_sketch("l") reused = gui.full_calibrations == n + 1 gui.click_mm(-20, 0) @@ -1497,7 +1497,7 @@ def rung_roundtrip(): # The pickers are matched by their prompts, unanchored: a picker answered unshown has no # title. Save Project as, not Save: once the project has a path, Save writes to it with no # picker. - gui.client.call("auto_answer_dialogs", + gui.client.call("dialog_auto_answer", rules=[{"match": "Save file as", "button": "ok", "path": path, "overwrite": True}]) unanswered(gui.menu("File>Save Project as..."), "saving") size = os.path.getsize(path) if os.path.isfile(path) else 0 @@ -1505,12 +1505,12 @@ def rung_roundtrip(): gui.new_design() # empty the tree, then read it back from the file # Opening asks first whether to save the current project when it has unsaved changes. No: # saving would write the emptied design over the file about to be opened. - gui.client.call("auto_answer_dialogs", + gui.client.call("dialog_auto_answer", rules=[{"match": "Choose one file", "button": "ok", "path": path}, {"match": "unsaved changes", "button": "no"}]) unanswered(gui.menu("File>Open Project..."), "opening") finally: - gui.client.call("auto_answer_dialogs", rules=[]) + gui.client.call("dialog_auto_answer", rules=[]) shutil.rmtree(folder, ignore_errors=True) # Opening a project lands on Prepare, and leaves the Design view fitted to the plates. gui.show_design() diff --git a/tools/mcp/test_cad_slow_build.py b/tools/mcp/test_cad_slow_build.py index 4887bef717..2be4d14006 100755 --- a/tools/mcp/test_cad_slow_build.py +++ b/tools/mcp/test_cad_slow_build.py @@ -5,8 +5,8 @@ tools/mcp/test_cad_slow_build.py The thread, sweep and loft commands rebuild as their cards do, off the UI thread behind the progress -dialog (DesignPanel::recompute_guarded). While a long thread builds: get_app_state answers, a screenshot -of the main window succeeds, list_widgets lists the progress dialog and a screenshot of that window +dialog (DesignPanel::recompute_guarded). While a long thread builds: app_state answers, a screenshot +of the main window succeeds, widget_list lists the progress dialog and a screenshot of that window captures it (not on Windows, where the dialog is the system's task dialog), and another Design command is refused rather than run inside the rebuild. The thread then lands as one feature. Exits 0 when all hold. """ @@ -28,8 +28,8 @@ THREAD = {"plane": "XY", "internal": True, "designation": "M8", "length": 60} def progress_dialog_ref(client): - """The ref of the rebuild's progress dialog (titled "Design") in list_widgets, or None.""" - _, texts = client.call_with_text("list_widgets") + """The ref of the rebuild's progress dialog (titled "Design") in widget_list, or None.""" + _, texts = client.call_with_text("widget_list") for line in "\n".join(texts).splitlines(): m = re.match(r'\[(w\d+)\] (?:window|dialog) "Design" \((\w+)\)', line) if m and "Progress" in m.group(2): @@ -40,15 +40,15 @@ def progress_dialog_ref(client): def main(): client, _ = orca_mcp.session_client() out = tempfile.mkdtemp(prefix="orca-mcp-slow-") - client.call("new_project", discard_changes=True) - client.call("call_tool", tool="new_design", args={"discard_changes": True}) - client.call("call_tool", tool="extrude", args=BLOCK) + client.call("project_new", discard_changes=True) + client.call("tool_call", tool="new_design", args={"discard_changes": True}) + client.call("tool_call", tool="extrude", args=BLOCK) box = {} def build(): try: - box["result"] = client.call("call_tool", _timeout=600, tool="thread", args=THREAD) + box["result"] = client.call("tool_call", _timeout=600, tool="thread", args=THREAD) except orca_mcp.McpError as e: box["error"] = str(e) @@ -57,7 +57,7 @@ def main(): worker.start() # On Windows the progress dialog is the system's task dialog, on a thread of its own: no wx window - # list_widgets lists. There the probes start once the build has run for 2 s, past the dialog's delay. + # widget_list lists. There the probes start once the build has run for 2 s, past the dialog's delay. native_dialog = sys.platform == "win32" probed, state_ms, window_shot, dialog_shot, refused = False, None, None, None, None while worker.is_alive() and time.time() - started < 300: @@ -67,36 +67,36 @@ def main(): if ref is not None or (native_dialog and time.time() - started > 2): probed = True t0 = time.time() - client.call("get_app_state") + client.call("app_state") state_ms = (time.time() - t0) * 1000 - window_shot = client.call("screenshot", target="main", include_image=False, + window_shot = client.call("window_screenshot", target="main", include_image=False, save_path=os.path.join(out, "window.png")) if ref is not None: - dialog_shot = client.call("screenshot", target=ref, include_image=False, + dialog_shot = client.call("window_screenshot", target=ref, include_image=False, save_path=os.path.join(out, "progress.png")) try: - client.call("call_tool", tool="describe_design") + client.call("tool_call", tool="describe_design") refused = False except orca_mcp.McpError as e: refused = str(e) worker.join(600) seconds = time.time() - started result = client.await_job(box.get("result")) if "result" in box else None - scene = client.call("call_tool", tool="describe_design")["result"] + scene = client.call("tool_call", tool="describe_design")["result"] threads = [f for f in scene["features"] if f["type"] == "Thread"] print(f"build took {seconds:.1f} s; screenshots in {out}") failures = 0 checks = [ ("the thread call succeeds", result is not None and result.get("result", {}).get("ok") is True, box), - ("get_app_state answers during the build", state_ms is not None, state_ms), + ("app_state answers during the build", state_ms is not None, state_ms), ("a window screenshot succeeds during the build", bool(window_shot and window_shot.get("width")), window_shot), ("another Design command is refused during the build", bool(refused) and "Busy" in refused, refused), ("one thread feature and one body", len(threads) == 1 and len(scene["bodies"]) == 1, scene["features"]), ] if not native_dialog: checks[1:1] = [ - ("the progress dialog is listed while it builds", dialog_shot is not None, "no window \"Design\" in list_widgets"), + ("the progress dialog is listed while it builds", dialog_shot is not None, "no window \"Design\" in widget_list"), ("a screenshot of the progress dialog captures it", bool(dialog_shot and dialog_shot.get("width")) and dialog_shot.get("width") < (window_shot or {}).get("width", 0), dialog_shot), ] diff --git a/tools/mcp/test_cancel_pending_slice.py b/tools/mcp/test_cancel_pending_slice.py index 1e64cf7096..ee3c37b167 100755 --- a/tools/mcp/test_cancel_pending_slice.py +++ b/tools/mcp/test_cancel_pending_slice.py @@ -23,31 +23,31 @@ MODEL = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "re def main(): client, _ = orca_mcp.session_client() - client.call("auto_answer_dialogs", rules=[{"match": "unsaved changes", "button": "no"}]) - client.call("new_project", discard_changes=True) - client.call("open_files", paths=[os.path.abspath(MODEL)]) - client.call("wait", **{"for": "idle"}) + client.call("dialog_auto_answer", rules=[{"match": "unsaved changes", "button": "no"}]) + client.call("project_new", discard_changes=True) + client.call("project_import", paths=[os.path.abspath(MODEL)]) + client.call("app_wait", **{"for": "idle"}) - client.call("set_settings", scope="process", values={"sparse_infill_density": "35%"}) + client.call("settings_set", type="process", values={"sparse_infill_density": "35%"}) box = {} - worker = threading.Thread(target=lambda: box.update(result=client.call("slice", _timeout=600))) + worker = threading.Thread(target=lambda: box.update(result=client.call("plate_slice", _timeout=600))) worker.start() time.sleep(0.1) - cancel = client.call("cancel_job") + cancel = client.call("job_cancel") worker.join(600) result = client.await_job(box["result"]) - client.call("auto_answer_dialogs", rules=[]) + client.call("dialog_auto_answer", rules=[]) # Once the scheduled update has run, the plate must still have no result to export. - client.call("wait", **{"for": "idle"}) + client.call("app_wait", **{"for": "idle"}) try: - client.call("export", format="gcode", path=os.path.join(tempfile.mkdtemp(prefix="orca-mcp-"), "plate.gcode")) + client.call("project_export", format="gcode", path=os.path.join(tempfile.mkdtemp(prefix="orca-mcp-"), "plate.gcode")) unsliced = False except orca_mcp.McpError: unsliced = True failures = 0 for name, ok, detail in [ - ("cancel_job reports the waiting slice", cancel.get("was_running") is True, cancel), + ("job_cancel reports the waiting slice", cancel.get("was_running") is True, cancel), ("the slice reports its plate cancelled", result["plates"][0]["outcome"] == "cancelled", result), ("the plate stays unsliced", unsliced, "a G-code export succeeded"), ]: diff --git a/tools/mcp/test_command_line.py b/tools/mcp/test_command_line.py index 395c7b882f..3f27280698 100644 --- a/tools/mcp/test_command_line.py +++ b/tools/mcp/test_command_line.py @@ -6,14 +6,14 @@ Each check starts the built app as this script's child, on a fresh data folder w folder, seeded as orca_mcp.py launch seeds one, with preset sync off and the update check sent to the loopback's discard port. Only a process's parent can read its exit code on every system. The replays and scripts a check runs are written by the check into a temporary folder of its own. An app that serves is closed as a person closes it, by a click -on the File menu's Quit item that list_widgets lists; an app still running when its check is done is killed with its +on the File menu's Quit item that widget_list lists; an app still running when its check is done is killed with its child processes. - refused_options: --mcp-run r.json, --mcp-run-out d, --mcp-token t and --no-mcp each exit non-zero within 10 s with "Invalid option" on stderr, and the data folder holds only the seeded OrcaSlicer.conf, which a GUI that started would have added its log and cache folders to. - run_invalid_file: --run missing.json exits 2, and so does --run a.txt, whose text is a valid replay. -- run_replay_folders: --run r.json, a replay whose one step is get_app_state, exits 0 with result.json in r.out beside +- run_replay_folders: --run r.json, a replay whose one step is app_state, exits 0 with result.json in r.out beside it; with --outputdir D, a folder that does not exist yet, it exits 0, D holds result.json, and r.out is not created. - run_script_output_folder: --run s.py, whose code takes a screenshot with no path, exits 0 with one .png in D when given --outputdir D, and without it in /automation/out, while /mcp/out does not exist. @@ -26,7 +26,7 @@ child processes. - unrestricted_scripts_flag: --unrestricted-scripts --run r.py, where r.py reads a file the test wrote in a temporary folder that is neither the data folder, the resources folder nor the script's own, exits 0, and the conf's python_scripts_unrestricted is absent or false after exit; without the flag the same run exits 1. -- cad_flag: --cad --mcp on a fresh data folder: search_tools {group: Design} finds commands and get_app_state has no +- cad_flag: --cad --mcp on a fresh data folder: tool_search {group: Design} finds commands and app_state has no cad_note; after exit the conf's enable_cad_feature is absent or false. A second start without the flag on the same folder finds no Design command. - run_beside_open_window: with single_instance true in the conf and a first window serving on the same data folder, @@ -68,10 +68,10 @@ HANDED_OVER = (-1, 255) # a start that handed its command line to a window, MODEL = os.path.join(HERE, "..", "..", "resources", "handy_models", "OrcaCube_v2.drc") DROPPED = (McpError, OSError, http.client.HTTPException) -REPLAY = {"orca_replay_version": "0.1.0", "name": "the app's state", "steps": [{"tool": "get_app_state"}]} +REPLAY = {"orca_replay_version": "0.2.0", "name": "the app's state", "steps": [{"tool": "app_state"}]} SCREENSHOT_SCRIPT = """ import orca -orca.host.tools.call("screenshot", {"include_image": False}) +orca.host.tools.call("window_screenshot", {"include_image": False}) """ results = [] @@ -184,7 +184,7 @@ class App: deadline = time.monotonic() + READY_LIMIT_S while time.monotonic() < deadline and self.proc.poll() is None: try: - if not orca.call("wait", _timeout=15, **{"for": "ready", "timeout_s": 5}).get("satisfied"): + if not orca.call("app_wait", _timeout=15, **{"for": "ready", "timeout_s": 5}).get("satisfied"): continue except DROPPED: time.sleep(0.5) @@ -207,10 +207,10 @@ class App: The click's reply may not arrive, since the server closes with the app.""" if self.orca is not None and self.proc.poll() is None: try: - _, texts = self.orca.call_with_text("list_widgets", _timeout=10, query="Quit") + _, texts = self.orca.call_with_text("widget_list", _timeout=10, query="Quit") found = re.search(r'\[(\w+)\] menu_item "Quit"', "".join(texts)) if found: - self.orca.call_raw("click", {"target": found.group(1)}, timeout=10) + self.orca.call_raw("widget_click", {"target": found.group(1)}, timeout=10) except DROPPED: pass try: @@ -380,16 +380,21 @@ with open({target!r}, encoding="utf-8") as f: def design_commands(orca): - """How many commands search_tools lists in the group Design, and "" or why the answer was not one. With the Design - tab off no command has that group, and search_tools refuses it as unknown, naming the groups there are; that + """How many commands tool_search lists in the group Design, and "" or why the answer was not one. With the Design + tab off no command has that group, and tool_search refuses it as unknown, naming the groups there are; that refusal counts as none, and any other error is a problem.""" try: - return len(orca.call("search_tools", group="Design").get("names", [])), "" + return len(orca.call("tool_search", group="Design").get("names", [])), "" except McpError as e: - refused = re.search(r"Unknown group: Design; the groups are ([^\"]*)", str(e)) - if refused and "Design" not in [g.strip() for g in refused.group(1).split(",")]: + # The refusal's details, on the line after its text, list the groups: places' headings, some with a comma. + text, _, details = str(e).rpartition("\n") + try: + groups = json.loads(details).get("groups") + except (ValueError, AttributeError): + groups = None + if text.startswith("Unknown group: Design;") and isinstance(groups, list) and "Design" not in groups: return 0, "" - return 0, f"search_tools {{group: Design}} failed: {str(e)[:300]}" + return 0, f"tool_search {{group: Design}} failed: {str(e)[:300]}" def cad_flag(binary): @@ -404,10 +409,10 @@ def cad_flag(binary): if error: problems.append(f"--cad --mcp: {error}") elif found == 0: - problems.append("--cad --mcp: search_tools finds no Design command") - note = app.orca.call("get_app_state").get("cad_note") + problems.append("--cad --mcp: tool_search finds no Design command") + note = app.orca.call("app_state").get("cad_note") if note is not None: - problems.append(f"--cad --mcp: get_app_state has cad_note {note!r}") + problems.append(f"--cad --mcp: app_state has cad_note {note!r}") app.quit() value = read_conf(work.datadir).get("enable_cad_feature") if not is_off(value): @@ -420,7 +425,7 @@ def cad_flag(binary): if error: problems.append(f"--mcp without --cad: {error}") elif count != 0: - problems.append(f"--mcp without --cad: search_tools finds {count} Design commands") + problems.append(f"--mcp without --cad: tool_search finds {count} Design commands") app.quit() check("cad_flag", problems, f"{found} Design commands with --cad, none without, enable_cad_feature stayed off") @@ -438,7 +443,7 @@ def run_beside_open_window(binary): problems.append(f"--run r.json beside the first window: exit code {code}") if not os.path.isfile(os.path.join(out, "result.json")): problems.append("--run r.json beside the first window: no result.json") - objects = first.orca.call("get_app_state").get("objects") + objects = first.orca.call("app_state").get("objects") if objects != 0: problems.append(f"the first window has {objects} objects") first.quit() @@ -493,7 +498,7 @@ def window_per_data_folder(binary): break if sys.platform != "linux": deadline = time.monotonic() + 30 - while (objects := first.orca.call("get_app_state").get("objects")) != n and time.monotonic() < deadline: + while (objects := first.orca.call("app_state").get("objects")) != n and time.monotonic() < deadline: time.sleep(0.5) if objects != n: problems.append(f"the first window has {objects} objects after a start on {what} handed it a model") diff --git a/tools/mcp/test_every_tile.py b/tools/mcp/test_every_tile.py new file mode 100644 index 0000000000..ae3236ec18 --- /dev/null +++ b/tools/mcp/test_every_tile.py @@ -0,0 +1,769 @@ +#!/usr/bin/env python3 +"""Runs every Speed Dial tile of tests/data/speed_dial_tiles.json through action_run and checks that it does its row's +job: the change its variant alone makes, the window it opens, the file it writes, or the refusal of a tile this harness +cannot give a state to (a printer, an AMS, an account). + + tools/mcp/orca_mcp.py launch + tools/mcp/test_every_tile.py [--out DIR] + +ROWS holds one row per tile key; a key of the tiles file with no row, or a row of a key the file lacks, fails the test. +Before each tile its state is set up afresh by calls (STATES), so that no tile sees what another left: New Project and +Delete All among them. A row's dialog is answered as the row says: a button of one of the app's own dialogs, a text +typed into it first, or a rule for a native file picker registered beforehand, with a file in the output folder. + +For every tile that ran, the reply's ran is the tile's id, and the step replay_export writes for the call is the tile's +action_run with the arguments of tests/data/speed_dial_tile_calls.json (for Go to tab and Go to layer the value under +the tile's input token), the tile naming the fixture's command in action_search. A tile expected to be refused has +neither: action_run adds ran only when the command ran, and a failed call is not exported. + +Three tiles open a web page in the system's browser and one opens the configuration folder in the file manager; the +test runs them once and leaves what they opened. Send G-code, Synchronize Filament List from AMS and Sync Presets are +expected to be refused: the seeded printer prints through the Bambu network and nothing is signed in. Import, Import +Configs and SVG open a file picker that dialog_auto_answer cannot give a file (a multi-select picker, and one whose +caller reads GetPaths()): the rule cancels it, and the row checks that the picker was answered and nothing loaded. The +dialogs whose choices are a person's (Export Preset Bundle, the Setup Wizard, the Network Test) are closed. Every file the +test writes is in its output folder (a new temporary folder unless --out names one) or in the app's configuration +folder; Start Recording's folder, where Take Screenshot saves too, is set to the output folder through the Start +Recording dialog before the tiles run. Exits 0 when every check passes. +""" + +import argparse +import json +import os +import shutil +import sys +import tempfile +import time +import zipfile + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import orca_mcp # noqa: E402 + +DATA = os.path.join(HERE, "..", "..", "tests", "data") +FIXTURES = os.path.join(HERE, "tests", "fixtures") +PLUGINS = os.path.join(HERE, "tests", "plugins") +PREFIX, SUFFIX = "orca_command:", ":orca" +BED_CENTRE = 128.0 # the seeded Bambu Lab X1 Carbon's 256 mm bed +CANVAS = {"name": "OrcaSceneCanvas"} +IMPORTED_PRESET = "MCP Import PLA" # the filament fixtures/mcp_import_pla.json holds +LOCAL_PLUGIN, SIDE_LOADED = "MCP Tools Fixture", "MCP Web Fixture" # the fixture plugins' names, from their manifests + + +def tile_id(key): + return PREFIX + key + SUFFIX + + +class Run: + """The client, the output folder and what one tile's checks read.""" + + def __init__(self, client, out, datadir): + self.client, self.out, self.datadir = client, out, datadir + self.reply = None # the tile's final reply + self.before = None # what the row's before() read after the state was set up + self.windows = [] # the titles window_list gave before the tile ran + self.seen = [] # the titles of the dialogs the row's answers found open + + def call(self, tool, /, **args): + return self.client.call(tool, **args) + + def wait(self, reply): + return self.client.await_job(reply) + + def objects(self): + """Every object, in object_list's order of plates, each with the plate it stands on (None off every plate).""" + listing = self.call("object_list") + out = [dict(o, plate=p["index"]) for p in listing.get("plates", []) for o in p.get("objects", [])] + return out + [dict(o, plate=None) for o in listing.get("outside", []) if isinstance(o, dict)] + + def names(self): + return [o["name"] for o in self.objects()] + + def plates(self): + return self.call("plate_list").get("items", []) + + def state(self): + return self.call("app_state") + + def slots(self): + return len(self.state().get("presets", {}).get("filaments", [])) + + def file(self, name): + path = os.path.join(self.out, name) + return path if os.path.isfile(path) and os.path.getsize(path) > 0 else None + + def path(self, name): + return os.path.join(self.out, name) + + def preference(self, key): + items = self.call("preferences_get", keys=[key]).get("items", []) + return items[0].get("value") if items else None + + def plugin_names(self): + return [r.get("name") for r in self.call("plugin_list").get("plugins", [])] + + def canvas_height(self): + """The height of the 3D view as widget_list gives it.""" + _, texts = self.client.call_with_text("widget_list", include_menus=False, include_imgui=False, include_web=False) + for line in "\n".join(texts).splitlines(): + if 'canvas "OrcaSceneCanvas"' in line: + return int(line.rsplit("x", 1)[1]) + return None + + def imgui_windows(self): + _, texts = self.client.call_with_text("widget_list", include_menus=False, include_web=False) + return [line.split('"')[1] for line in "\n".join(texts).splitlines() if "imgui_window" in line and '"' in line] + + def new_windows(self): + """The windows the tile opened: those its answers found open, and those still open that were not before.""" + shown = [w["title"] for w in self.call("window_list").get("items", []) if w["title"] not in self.windows] + return self.seen + [t for t in shown if t not in self.seen] + + +# ---- The files the tiles read ---- + +def box(x0, size): + """The twelve facets of an axis-aligned cube of `size` mm whose corner is at (x0, 0, 0), as ASCII STL text.""" + v = [(x0 + dx * size, dy * size, dz * size) for dx in (0, 1) for dy in (0, 1) for dz in (0, 1)] + faces = [(0, 2, 3), (0, 3, 1), (4, 5, 7), (4, 7, 6), (0, 1, 5), (0, 5, 4), (2, 6, 7), (2, 7, 3), (0, 4, 6), (0, 6, 2), + (1, 3, 7), (1, 7, 5)] + return "".join("facet normal 0 0 0\nouter loop\n" + "".join("vertex %g %g %g\n" % v[i] for i in f) + "endloop\nendfacet\n" + for f in faces) + + +def write_inputs(out): + """The files the import, open and install tiles pick: an STL of one mesh with two shells, a ZIP holding it, the + fixture preset, SVG and plugin.""" + stl = os.path.join(out, "two_shells.stl") + with open(stl, "w") as f: + f.write("solid two_shells\n" + box(0, 10) + box(20, 10) + "endsolid two_shells\n") + with zipfile.ZipFile(os.path.join(out, "two_shells.zip"), "w") as z: + z.write(stl, "two_shells.stl") + shutil.copy(os.path.join(FIXTURES, "mcp_import_pla.json"), out) + shutil.copy(os.path.join(FIXTURES, "star.svg"), out) + shutil.copy(os.path.join(PLUGINS, "mcp_tools_fixture", "mcp_tools_fixture.py"), out) + for folder in ("stl_multi", "drc_multi"): + os.makedirs(os.path.join(out, folder), exist_ok=True) + + +# ---- States: each set up afresh by calls before its tile ---- + +RESTORE = {"match": "restore", "button": "no"} # the prompt to restore unsaved items after a start + + +def empty(run): + run.call("dialog_auto_answer", rules=[RESTORE]) + if run.state().get("recording"): + run.call("recording_stop", silent=True) + run.call("project_new", discard_changes=True, preset_changes="discard") + run.call("view_set", tab="prepare", canvas="3d") + while run.slots() > 1: + run.call("filament_delete") + run.call("settings_set_mode", mode="expert") + run.call("app_wait", **{"for": "idle"}) + + +def two_cubes(run): + """Two 20 mm cubes side by side on the plate, the first selected.""" + empty(run) + for x in (100, 156): + run.call("object_select", none=True) + run.call("object_add_primitive", shape="cube", silent=True, size=[20, 20, 20], position=[x, BED_CENTRE, 10]) + run.call("object_select", objects=[0]) + + +def sliced(run): + two_cubes(run) + run.wait(run.call("plate_slice")) + + +def assembled(run): + """The two cubes assembled into one object of two parts, selected.""" + two_cubes(run) + run.call("object_assemble", objects=[0, 1]) + run.call("object_select", objects=[0]) + + +def part_selected(run): + """The assembled object with its second part selected.""" + assembled(run) + run.call("object_select", parts=[[0, 1]]) + + +def offset_parts(run): + """One object of two parts apart along x, y and z, selected: a mirror across any axis moves them.""" + empty(run) + for position in ([100, 110, 10], [156, 150, 10]): + run.call("object_select", none=True) + run.call("object_add_primitive", shape="cube", silent=True, size=[20, 20, 20], position=position) + run.call("object_assemble", objects=[0, 1]) + run.call("object_transform", object=0, part=1, translate=[0, 0, 10]) + run.call("object_select", objects=[0]) + + +def two_plates(run): + """The two cubes, the second on a second plate, which is current.""" + two_cubes(run) + run.call("plate_add") + run.call("object_transform", object=1, plate=1) + run.call("plate_select", plate=1) + + +def sliced_plates(run): + """The two plates, both sliced, the second current.""" + two_plates(run) + run.wait(run.call("plate_slice", plates="all")) + run.call("plate_select", plate=1) + + +def two_shells(run): + """One object whose mesh is two shells, selected.""" + empty(run) + run.call("project_import", paths=[run.path("two_shells.stl")]) + run.call("object_select", objects=[0]) + + +def undone(run): + """The two cubes with the second's addition undone.""" + two_cubes(run) + run.call("undo") + + +def saved_project(run): + """An empty project, after the two cubes were saved as load_me.3mf in the output folder.""" + two_cubes(run) + run.call("project_save", path=run.path("load_me.3mf"), overwrite=True) + run.call("project_new", discard_changes=True) + + +def recording(run): + empty(run) + run.call("recording_start", save_path=run.path("stopped.mkv"), overwrite=True) + + +STATES = {"empty": empty, "two_cubes": two_cubes, "sliced": sliced, "assembled": assembled, "part_selected": part_selected, + "two_plates": two_plates, "sliced_plates": sliced_plates, "offset_parts": offset_parts, "two_shells": two_shells, + "undone": undone, + "saved_project": saved_project, "recording": recording} + + +# ---- Answers ---- + +def picker(name): + """A rule for the native file or folder picker the tile opens: it returns `name` in the output folder.""" + return ("picker", name) + + +def button(title, label): + """Press `label` on the app's dialog whose title holds `title`, once it is open.""" + return ("button", title, label) + + +def typed(title, cls, value, label="ok"): + """Type `value` into the `cls` control of the dialog titled `title`, then press `label`.""" + return ("typed", title, cls, value, label) + + +def answer(run, answers): + """Carries out the row's answers that come after the call: the dialog buttons and typed values.""" + for a in answers: + if a[0] == "picker": + continue + title = a[1] + deadline = time.time() + 30 + while time.time() < deadline and not any(title.lower() in d.get("title", "").lower() for d in run.state()["dialogs"]): + time.sleep(0.3) + run.seen += [d["title"] for d in run.state()["dialogs"] if d["title"] not in run.seen] + if a[0] == "typed": + run.call("widget_set_value", target={"class": a[2], "within": a[1]}, value=a[3], submit=False) + run.call("dialog_answer", dialog={"title": title}, button=a[-1]) + + +# ---- Expectations ---- + +def objects(fn): + return ("object_list", fn) + + +def plates(fn): + return ("plate_list", fn) + + +def app_state(fn): + return ("app_state", fn) + + +def window(title): + """The tile opened the window or dialog titled `title`, which it had not shown before.""" + return ("window", lambda r: (any(title.lower() in t.lower() for t in r.new_windows()), r.new_windows())) + + +def written(name): + return ("file", lambda r: (r.file(name) is not None, os.listdir(r.out))) + + +def plates_in(name, plates): + """The sliced file `name` holds the G-code of `plates` (numbered from 1, as the archive names them) and of no other.""" + def check(r): + if r.file(name) is None: + return False, os.listdir(r.out) + with zipfile.ZipFile(r.path(name)) as z: + held = sorted(n for n in z.namelist() if n.startswith("Metadata/plate_") and n.endswith(".gcode")) + return held == [f"Metadata/plate_{p}.gcode" for p in plates], held + return ("file", check) + + +def written_each(folder, extension, count): + def check(r): + found = [f for f in os.listdir(r.path(folder)) if f.lower().endswith(extension)] + return len(found) == count, found + return ("file", check) + + +# Why a row that opens a file picker is shown by the picker it opened and not by the file it would load. +PATHLESS = "dialog_auto_answer cannot give this picker a file, so its rule cancels it and nothing is loaded" + + +def picked(unchanged): + """The tile opened its file picker, which the row's rule answered, and with nothing chosen `unchanged` holds.""" + def check(r): + uses = [rule.get("uses", 0) for rule in r.state().get("auto_answer_rules", []) if rule.get("path")] + return uses == [1] and unchanged(r), (uses, r.names()) + return ("picker", check) + + +def external(why): + return ("external", why) + + +def refused(code, why): + return ("refused", code, why) + + +def near(a, b, tolerance=1.0): + return abs(a - b) <= tolerance + + +def centre(o): + box_ = o["bbox"] + return [(box_["min"][i] + box_["max"][i]) / 2 for i in range(3)] + + +def camera(elevation=None, azimuth=None): + def check(r): + cam = r.state().get("camera") or {} + ok = (elevation is None or near(cam.get("elevation", 999), elevation, 2)) and \ + (azimuth is None or near(cam.get("azimuth", 999), azimuth, 2) or near(abs(cam.get("azimuth", 999)), abs(azimuth), 2) and + abs(azimuth) == 180) + return ok, cam + return app_state(check) + + +def part_centres(r): + return [centre(p) for p in r.objects()[0]["parts"]] + + +def mirrored_along(r, axis): + """Whether the parts' centres moved along `axis` alone, as a mirror of their object across that axis moves them, and + the object stays mirrored.""" + after = part_centres(r) + moved = [any(not near(a[i], b[i], 0.01) for a, b in zip(r.before, after)) for i in range(3)] + return moved == [i == axis for i in range(3)] and r.objects()[0]["instances"][0]["mirrored"] is True + + +def part_types(r): + return sorted(p["type"] for p in r.objects()[0]["parts"]) + + +def heights(r): + return [round(o["bbox"]["size"][2]) for o in r.objects()] + + +def call(tool, /, **args): + return (tool, args) + + +def row(key, state, expect, *, value=None, answers=(), pre=(), post=(), before=None, why=""): + return key, {"state": state, "expect": expect, "value": value, "answers": tuple(answers), "pre": tuple(pre), + "post": tuple(post), "before": before, "why": why} + + +CUBE_OFF_PLATE = call("object_transform", object=1, position=[-150, BED_CENTRE, 10]) +LIFTED = call("object_transform", object=0, translate=[0, 0, 15], drop_to_bed=False) +TWO_SLOTS = call("filament_add") +ORDER_NAMES = (call("object_rename", object=0, name="b_cube"), call("object_rename", object=1, name="a_cube")) +# Three objects in an order that is neither ascending nor descending by height or by size, and whose order by height +# is the reverse of their order by size: a tile that sorts by the other key, or reverses an order it finds sorted +# (ObjectList::order_objects()), leaves another order. +ORDER_SIZES = (call("object_select", none=True), + call("object_add_primitive", shape="cube", silent=True, size=[10, 10, 30], position=[BED_CENTRE, 200, 15]), + call("object_transform", object=0, size=[20, 20, 20]), call("object_transform", object=1, size=[40, 40, 10])) +ORDER_FILAMENTS = (TWO_SLOTS, call("settings_set", target="object", object=0, values={"extruder": 2})) +SHAPES = {"cube": "Cube", "cylinder": "Cylinder", "sphere": "Sphere", "cone": "Cone", "disc": "Disc", "torus": "Torus"} +# The objects each handy model adds to an empty project, as its files name them. +HANDY = {"orca_cube": ["OrcaCube_v2.drc", "OrcaPlug_v2.drc"], + "orcasliced_combo": ["Orca Head", "OrcaCube_v2.drc", "OrcaPlug_v2.drc", "Orca Belly", "Orca Pedestal"], + "orca_badge": ["OrcaSlicer Badge Horizontal", "OrcaSlicer Badge Vertical", "OrcaSlicer Badge Logo"], + "orca_tolerance_test": ["OrcaToleranceTest.drc"], "3dbenchy": ["3DBenchy.drc"], "cali_cat": ["calicat.drc"], + "autodesk_fdm_test": ["ksr_fdmtest_v4.drc"], "voron_cube": ["Voron_Design_Cube_v7.drc"], + "stanford_bunny": ["Stanford_Bunny.drc"], "orca_string_hell": ["Orca_stringhell.drc"]} +# The question a handy model asks once it is loaded, which the test answers so that no setting changes. +HANDY_ASKS = {"orca_string_hell": [("button", "Suggestion", "no")]} +CALIBRATIONS = {"temperature": ("Temperature calibration", "Nozzle temperature test"), + "max_volumetric": ("Max volumetric speed test", "Max volumetric speed test"), + "pressure_advance": ("PA Calibration", "Pressure Advance Test"), + "flow_ratio": ("Flow Ratio Calibration", "Orca YOLO Flow Calibration"), + "retraction": ("Retraction", "Retraction"), + "cornering": ("Cornering test", "Cornering test"), + "input_shaping_freq": ("Input shaping Frequency test", "Input shaping Frequency test"), + "input_shaping_damp": ("Input shaping Damp test", "Input shaping Damping test"), + "vfa": ("VFA test", "VFA test")} + + +def dialog_tile(key, title, why=""): + """A Help or window tile whose job is to show one of the app's dialogs, which the test then closes.""" + return row(key, "empty", window(title), answers=[button(title, "close")], why=why) + + +ROWS = dict([ + # ---- Slice & Export ---- + row("slice_and_preview", "two_cubes", plates(lambda r: (r.plates()[0]["sliced"] and r.state()["tab"] == "preview", + (r.plates()[0]["sliced"], r.state()["tab"])))), + row("slice_all", "two_plates", plates(lambda r: (all(p["sliced"] for p in r.plates()) and len(r.plates()) == 2, + [p["sliced"] for p in r.plates()]))), + row("export_gcode", "sliced", written("plate.gcode"), answers=[picker("plate.gcode")]), + row("export_stl", "two_cubes", written("model.stl"), answers=[picker("model.stl")]), + row("export_3mf", "two_cubes", written("model.3mf"), answers=[picker("model.3mf")]), + # From two sliced plates, the second current: the current plate's G-code alone, and both plates'. + row("export_sliced_file", "sliced_plates", plates_in("plate.gcode.3mf", [2]), answers=[picker("plate.gcode.3mf")]), + row("export_all_sliced_file", "sliced_plates", plates_in("all.gcode.3mf", [1, 2]), answers=[picker("all.gcode.3mf")]), + row("send_gcode", "sliced", refused("not_a_print_host_printer", "the seeded X1 Carbon prints through the Bambu network, " + "not a print host, and the test uploads to no printer")), + # ---- Commands ---- + row("go_to_layer", "sliced", plates(lambda r: (lambda v: (v.get("layer_count", 0) > 0 and + near((v.get("layers") or [0, 0])[1], v.get("layer_count", 0) / 2, 2), v))( + r.call("plate_slice_stats", include=["view"]).get("view") or {})), value={"percent": 50}), + row("go_to_tab", "two_cubes", app_state(lambda r: (r.state()["tab"] == "preview", r.state()["tab"])), value={"tab": "preview"}), + row("load_project", "saved_project", objects(lambda r: (len(r.objects()) == 2 and + r.state()["project"]["path"].endswith("load_me.3mf"), + (r.names(), r.state()["project"]))), + answers=[picker("load_me.3mf")]), + row("save_project_as", "two_cubes", written("saved_as.3mf"), answers=[picker("saved_as.3mf")]), + row("undo", "two_cubes", objects(lambda r: (len(r.objects()) == 1, r.names()))), + row("redo", "undone", objects(lambda r: (len(r.objects()) == 2, r.names()))), + row("toggle_run_script_panel", "empty", + ("widget", lambda r: (r.canvas_height() not in (None, r.before), (r.before, r.canvas_height()))), + before=lambda r: r.canvas_height(), post=[call("tool_call", tool="script_toggle_panel", args={})], + why="the Run Script panel is kept from automation, so widget_list reads the 3D view it docks under"), + row("open_action_replay", "empty", window("Action Replay"), + why="Action Replay is the person's window, which no tool closes: it stays open"), + dialog_tile("open_preferences", "Preferences"), + row("take_screenshot", "two_cubes", ("file", lambda r: (bool(r.reply.get("path")) and os.path.isfile(r.reply["path"]) and + os.path.dirname(r.reply["path"]) == r.out, r.reply))), + # ---- Mode ---- + row("mode_simple", "empty", app_state(lambda r: (r.state()["mode"] == "simple", r.state()["mode"]))), + row("mode_advanced", "empty", app_state(lambda r: (r.state()["mode"] == "advanced", r.state()["mode"]))), + row("mode_expert", "empty", app_state(lambda r: (r.state()["mode"] == "expert", r.state()["mode"])), + pre=[call("settings_set_mode", mode="simple")]), + row("toggle_developer_mode", "empty", + ("preferences_get", lambda r: (r.preference("developer_mode") == (not r.before), (r.before, r.preference("developer_mode")))), + before=lambda r: r.preference("developer_mode"), post=[call("tool_call", tool="settings_toggle_developer_mode", args={})]), + # ---- Calibration ---- + *[row("calib_" + test, "empty", app_state(lambda r, name=name: (r.state()["project"]["name"] == name and len(r.objects()) > 0, + (r.state()["project"], r.names()))), + answers=[button(title, "ok")]) for test, (title, name) in CALIBRATIONS.items()], + # ---- View ---- + row("view_top", "two_cubes", camera(elevation=90), pre=[call("view_set", camera="front")]), + row("view_bottom", "two_cubes", camera(elevation=-90), pre=[call("view_set", camera="front")]), + row("view_front", "two_cubes", camera(elevation=0, azimuth=-90), pre=[call("view_set", camera="top")]), + row("view_rear", "two_cubes", camera(elevation=0, azimuth=90), pre=[call("view_set", camera="top")]), + row("view_left", "two_cubes", camera(elevation=0, azimuth=180), pre=[call("view_set", camera="top")]), + row("view_right", "two_cubes", camera(elevation=0, azimuth=0), pre=[call("view_set", camera="top")]), + row("view_iso", "two_cubes", camera(elevation=45, azimuth=-135), pre=[call("view_set", camera="top")]), + row("view_default", "two_cubes", camera(elevation=45, azimuth=-90), pre=[call("view_set", camera="top")]), + row("view_fit_bed", "two_cubes", app_state(lambda r: (lambda cam: (cam.get("zoom", 0) < r.before and + near(cam["look_at"][0], BED_CENTRE, 5), (r.before, cam)))( + r.state()["camera"])), pre=[call("view_set", camera="fit_selection")], before=lambda r: r.state()["camera"]["zoom"]), + row("view_toggle_perspective", "two_cubes", + app_state(lambda r: (r.state()["view"]["projection"] != r.before, (r.before, r.state()["view"]["projection"]))), + before=lambda r: r.state()["view"]["projection"], post=[call("view_set", projection="toggle")]), + row("reset_window_layout", "two_cubes", + app_state(lambda r: (r.state()["view"]["sidebar_collapsed"] is False, r.state()["view"])), + pre=[call("view_set", sidebar_collapsed=True)]), + # ---- Object ---- + row("obj_delete", "two_cubes", objects(lambda r: ([o["id"] for o in r.objects()] == [r.before], r.objects())), + before=lambda r: r.objects()[1]["id"]), + row("obj_delete_all", "two_cubes", objects(lambda r: (r.objects() == [], r.names()))), + row("select_all", "two_cubes", app_state(lambda r: (r.state()["selection"]["objects"] == [0, 1], r.state()["selection"])), + pre=[call("object_select", none=True)]), + row("deselect_all", "two_cubes", app_state(lambda r: (r.state()["selection"]["empty"] is True, r.state()["selection"]))), + *[row("obj_mirror_" + axis, "offset_parts", objects(lambda r, i=i: (mirrored_along(r, i), (r.before, part_centres(r)))), + before=part_centres) for i, axis in enumerate("xyz")], + row("obj_split_objects", "two_shells", objects(lambda r: (len(r.objects()) == 2, r.names()))), + row("obj_split_parts", "two_shells", objects(lambda r: (len(r.objects()) == 1 and len(r.objects()[0]["parts"]) == 2, + [len(o["parts"]) for o in r.objects()]))), + row("obj_center", "two_cubes", objects(lambda r: (near(centre(r.objects()[0])[0], BED_CENTRE) and + near(centre(r.objects()[0])[1], BED_CENTRE), centre(r.objects()[0]))), + pre=[call("object_transform", object=0, position=[60, 60, 10])]), + row("obj_drop", "assembled", objects(lambda r: (near(r.objects()[0]["bbox"]["min"][2], 0, 0.01), r.objects()[0]["bbox"])), + pre=[LIFTED]), + row("obj_fit_volume", "two_cubes", objects(lambda r: (r.objects()[0]["bbox"]["size"][0] > 200, r.objects()[0]["bbox"]))), + row("obj_instances_up", "two_cubes", objects(lambda r: (len(r.objects()[0]["instances"]) == 2, + len(r.objects()[0]["instances"])))), + row("obj_instances_down", "two_cubes", objects(lambda r: (len(r.objects()[0]["instances"]) == 1, + len(r.objects()[0]["instances"]))), + pre=[call("object_set_instances", object=0, count=2), call("object_select", objects=[0])]), + row("obj_arrange", "two_cubes", objects(lambda r: (len(r.objects()) == 2 and all(o["plate"] is not None for o in r.objects()), + [(o["name"], o["plate"]) for o in r.objects()])), pre=[CUBE_OFF_PLATE]), + row("obj_orient", "two_cubes", objects(lambda r: (near(r.objects()[0]["bbox"]["size"][2], 20, 0.5), r.objects()[0]["bbox"])), + pre=[call("object_transform", object=0, rotate=[45, 0, 0]), call("object_select", objects=[0])]), + *[row("obj_type_" + tile, "part_selected", objects(lambda r, t=t: (part_types(r) == sorted(["part", t]), part_types(r)))) + for tile, t in (("negative", "negative"), ("modifier", "modifier"), ("support_blocker", "support_blocker"), + ("support_enforcer", "support_enforcer"), ("precise_seam", "precise_seam"))], + row("obj_type_part", "part_selected", objects(lambda r: (part_types(r) == ["part", "part"], part_types(r))), + pre=[call("part_change_type", parts=[[0, 1]], type="modifier"), call("object_select", parts=[[0, 1]])]), + row("obj_rename", "two_cubes", objects(lambda r: (r.names()[0] == "Renamed by its tile", r.names())), + answers=[typed("Renaming", "wxTextCtrl", "Renamed by its tile")]), + row("obj_set_instances", "two_cubes", objects(lambda r: (len(r.objects()[0]["instances"]) == 3, + len(r.objects()[0]["instances"]))), + answers=[typed("Copies of the selected object", "wxSpinCtrl", 3)]), + row("obj_assemble", "two_cubes", objects(lambda r: (len(r.objects()) == 1 and len(r.objects()[0]["parts"]) == 2, + [len(o["parts"]) for o in r.objects()])), + pre=[call("object_select", all=True)]), + row("obj_instances_to_objects", "two_cubes", objects(lambda r: (len(r.objects()) == 3 and + all(len(o["instances"]) == 1 for o in r.objects()), r.names())), + pre=[call("object_set_instances", object=0, count=2), call("object_select", objects=[0])]), + row("obj_order_by_name", "two_cubes", objects(lambda r: (r.names() == ["a_cube", "b_cube"], r.names())), pre=ORDER_NAMES), + row("obj_order_by_filament", "two_cubes", objects(lambda r: ([o["filament"] for o in r.objects()] == [1, 2], + [o["filament"] for o in r.objects()])), pre=ORDER_FILAMENTS), + row("obj_order_by_height", "two_cubes", objects(lambda r: (heights(r) == [10, 20, 30], heights(r))), pre=ORDER_SIZES), + row("obj_order_by_size", "two_cubes", objects(lambda r: (heights(r) == [30, 20, 10], heights(r))), pre=ORDER_SIZES), + # ---- Add Primitive, Add Handy models ---- + *[row("add_primitive_" + shape, "empty", objects(lambda r, n=name: (len(r.objects()) == 1 and n in r.names()[0], r.names())), + answers=[button(name, "ok")]) for shape, name in SHAPES.items()], + row("add_primitive_text", "empty", app_state(lambda r: ((r.state().get("gizmo") or {}).get("name") == "Text" and + len(r.objects()) == 1, (r.state().get("gizmo"), r.names()))), + post=[call("keyboard_press", keys="Escape", target=CANVAS)]), + row("add_primitive_svg", "empty", picked(lambda r: r.objects() == []), answers=[picker("star.svg")], + why=PATHLESS + " (the SVG gizmo reads the picker's GetPaths(), which a path answer leaves empty)"), + *[row("add_handy_" + model, "empty", objects(lambda r, n=names: (r.names() == n, r.names())), answers=HANDY_ASKS.get(model, ())) + for model, names in HANDY.items()], + # ---- Plate ---- + row("plate_add", "two_cubes", plates(lambda r: ([p["objects"] for p in r.plates()] == [2, 0], [p["objects"] for p in r.plates()]))), + row("plate_duplicate", "two_cubes", plates(lambda r: (len(r.plates()) == 2 and r.plates()[1]["objects"] == 2, + [p["objects"] for p in r.plates()]))), + # The plate goes and its objects stay, off every plate (PartPlateList::delete_plate()). + row("plate_delete", "two_plates", plates(lambda r: (len(r.plates()) == 1 and [o["plate"] for o in r.objects()] == [0, None], + (len(r.plates()), [o["plate"] for o in r.objects()])))), + row("plate_rename", "two_cubes", plates(lambda r: (r.plates()[0]["name"] == "Plate by its tile", r.plates()[0]["name"])), + answers=[typed("Edit Plate Name", "TextInput", "Plate by its tile")]), + row("plate_toggle_lock", "two_cubes", plates(lambda r: (r.plates()[0]["locked"] is True, r.plates()[0]["locked"]))), + row("plate_goto", "two_plates", plates(lambda r: (r.state()["plates"]["current"] == 0, r.state()["plates"]))), + # ---- Printer, Filament, Presets ---- + row("sync_ams", "two_cubes", refused("no_printer", "no printer is connected, and the test connects to none")), + row("filament_add", "empty", app_state(lambda r: (r.slots() == 2, r.slots()))), + row("filament_delete", "empty", app_state(lambda r: (r.slots() == 1, r.slots())), pre=[TWO_SLOTS]), + dialog_tile("preset_bundle", "Preset Bundle"), + row("sync_presets", "empty", refused("not_signed_in", "nothing is signed in, and the test signs in to no account")), + # ---- Import ---- + row("import_file", "empty", picked(lambda r: r.objects() == []), answers=[picker("two_shells.stl")], + why=PATHLESS + " (a multi-select picker)"), + row("import_zip_archive", "empty", objects(lambda r: (len(r.objects()) == 1, r.names())), + answers=[picker("two_shells.zip"), button("Archive preview", "ok")]), + row("import_configs", "empty", picked(lambda r: IMPORTED_PRESET not in [ + i.get("name") for i in r.call("preset_list", type="filament", query=IMPORTED_PRESET).get("items", [])]), + answers=[picker("mcp_import_pla.json")], why=PATHLESS + " (a multi-select picker)"), + # ---- Export ---- + row("export_stl_multi", "two_cubes", written_each("stl_multi", ".stl", 2), answers=[picker("stl_multi")]), + row("export_drc_single", "two_cubes", written("model.drc"), answers=[picker("model.drc")]), + row("export_drc_multi", "two_cubes", written_each("drc_multi", ".drc", 2), answers=[picker("drc_multi")]), + row("export_toolpaths_obj", "sliced", written("toolpaths.obj"), answers=[picker("toolpaths.obj")], + pre=[call("view_set", tab="preview")]), + row("export_config", "empty", window("Export Preset Bundle"), answers=[button("Export Preset Bundle", "cancel")], + why="the dialog's kinds and presets are the person's to pick, so the test closes it"), + # ---- Help ---- + dialog_tile("help_keyboard_shortcuts", "Keyboard Shortcuts"), + dialog_tile("help_setup_wizard", "Setup Wizard", why="the wizard installs printers on Finish, so the test closes it"), + row("help_open_config_folder", "empty", external("it opens the configuration folder in the system's file manager")), + row("help_migrate_filament_presets", "empty", window("Migrate Filament Presets"), + answers=[button("Migrate Filament Presets", "ok")]), + dialog_tile("help_troubleshoot", "Troubleshoot Center"), + dialog_tile("help_network_test", "Network Test", why="its tests reach the network, so the test closes it"), + # Once Start is pressed the OrcaSliced Combo replaces the empty project, and the benchmark's own window, which times + # the views and slices, stays open beside the main window (run_scene_benchmark()). + row("help_benchmark_3d_scene", "empty", objects(lambda r: (lambda shown: ( + len(r.objects()) > 1 and any("Orca" in n for n in r.names()) and "Benchmark 3D Scene" in shown, (r.names(), shown)))( + [w["title"] for w in r.call("window_list").get("items", []) if not w.get("modal")])), + answers=[button("Benchmark 3D Scene", "Start")], + post=[call("keyboard_press", keys="Escape", target={"label": "Benchmark 3D Scene"})]), + row("help_tip_of_the_day", "empty", ("widget", lambda r: ("Daily Tips" in r.imgui_windows(), r.imgui_windows()))), + row("help_check_updates", "empty", ("window", lambda r: (r.new_windows() != [], r.new_windows())), + answers=[button("", "ok")], why="the dialog says whether a newer version exists, which depends on the day"), + dialog_tile("help_about", "About Orca Slicer"), + row("open_wiki", "empty", external("it opens the wiki in the system's browser")), + row("open_youtube", "empty", external("it opens the YouTube channel in the system's browser")), + # ---- Plugins ---- + row("open_plugins", "empty", window("Plugins"), post=[call("keyboard_press", keys="Escape", target={"label": "Plugins"})]), + row("refresh_plugins", "empty", ("plugin_list", lambda r: (SIDE_LOADED in r.plugin_names(), r.plugin_names())), + before=lambda r: side_load(r)), + row("install_plugin", "empty", external("it opens the plugin hub in the system's browser")), + row("install_local_plugin", "empty", ("plugin_list", lambda r: (LOCAL_PLUGIN in r.plugin_names(), r.plugin_names())), + answers=[picker("mcp_tools_fixture.py")]), + # ---- Commands ---- + row("new_project", "two_cubes", objects(lambda r: (r.objects() == [], r.names())), answers=[button("Save", "no")]), + row("save_project", "two_cubes", written("saved.3mf"), answers=[picker("saved.3mf")]), + row("start_recording", "empty", app_state(lambda r: (lambda rec: (bool(rec) and os.path.dirname(rec.get("path", "")) == r.out, + rec))(r.state().get("recording"))), + answers=[button("Start Recording", "Start recording")], post=[call("recording_stop", silent=True)]), + row("stop_recording", "recording", app_state(lambda r: (r.state().get("recording") is None and r.file("stopped.mkv") is not None, + (r.state().get("recording"), os.listdir(r.out))))), +]) + + +def side_load(run): + """Copies the web fixture plugin into the plugins folder, where only a refresh finds it.""" + dest = os.path.join(run.datadir, "orca_plugins", "mcp_web_fixture") + os.makedirs(dest, exist_ok=True) + shutil.copy(os.path.join(PLUGINS, "mcp_web_fixture", "mcp_web_fixture.py"), dest) + return SIDE_LOADED in run.plugin_names() + + +def use_capture_folder(run): + """Points Start Recording's folder, where Take Screenshot saves too, at the output folder: the dialog's Change... + picker takes it, and a recording started and stopped there makes the dialog keep it.""" + run.call("dialog_auto_answer", rules=[RESTORE, {"match": ".", "button": "ok", "path": run.out}]) + run.call("recording_start") + run.call("widget_click", target={"label": "Change...", "within": "Start Recording"}) + run.call("dialog_answer", dialog={"title": "Start Recording"}, button="Start recording") + stopped = run.call("recording_stop", silent=True) + run.call("dialog_auto_answer", rules=[RESTORE]) + return os.path.dirname(stopped.get("path", "")) == run.out, stopped + + +def journal_step(run, key): + """The step replay_export writes for the tile's action_run, or None.""" + steps = run.call("replay_export", clear=True)["replay"]["steps"] + return next((s for s in steps if s.get("tool") == "action_run" and s.get("args", {}).get("id") == tile_id(key)), None) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--out", help="output folder (default: a new temporary one)") + ap.add_argument("--only", nargs="+", metavar="KEY", help="run these tiles alone") + args = ap.parse_args() + out = os.path.abspath(args.out) if args.out else tempfile.mkdtemp(prefix="every-tile-") + os.makedirs(out, exist_ok=True) + write_inputs(out) + with open(os.path.join(DATA, "speed_dial_tiles.json"), encoding="utf-8") as f: + tiles = json.load(f) + with open(os.path.join(DATA, "speed_dial_tile_calls.json"), encoding="utf-8") as f: + fixture = {c["key"]: c for c in json.load(f)} + + client, session = orca_mcp.session_client() + client.call("app_wait", **{"for": "ready"}) + run = Run(client, out, session["datadir"]) + checks, shown_otherwise = [], [] + + def check(name, ok, detail=""): + checks.append((name, bool(ok), detail)) + print(("PASS " if ok else "FAIL ") + name + ("" if ok else f": {str(detail)[:600]}"), flush=True) + + keys = [t["key"] for t in tiles] + check("every tile has a row", set(keys) <= set(ROWS), sorted(set(keys) - set(ROWS))) + check("every row is a tile", set(ROWS) <= set(keys), sorted(set(ROWS) - set(keys))) + check("every tile has a call in the fixture", set(keys) <= set(fixture), sorted(set(keys) - set(fixture))) + commands, offset = {}, 0 + while True: + page = client.call("action_search", group="", limit=200, offset=offset) + commands.update({a["id"]: a.get("command") for a in page.get("items", [])}) + offset = page.get("next_offset") + if not offset: + break + empty(run) + check("Start Recording's folder is the output folder", *use_capture_folder(run)) + + for key in [k for k in keys if not args.only or k in args.only]: + r = ROWS.get(key) + if r is None: + continue + name = f"{key} ({r['state']})" + try: + STATES[r["state"]](run) + for tool, a in r["pre"]: + run.wait(run.call(tool, **a)) + run.call("app_wait", **{"for": "idle"}) + run.before = r["before"](run) if r["before"] else None + run.windows = [w["title"] for w in run.call("window_list").get("items", [])] + run.seen = [] + pickers = [{"match": ".", "button": "ok", "path": run.path(a[1]), "overwrite": True} + for a in r["answers"] if a[0] == "picker"] + run.call("dialog_auto_answer", rules=[RESTORE] + pickers) + run.call("replay_export", clear=True) + kind = r["expect"][0] + try: + first = run.call("action_run", id=tile_id(key), **({"args": r["value"]} if r["value"] else {})) + except orca_mcp.McpError as e: + if kind == "refused": + code = json.loads(str(e).rpartition("\n")[2] or "{}").get("code") + check(f"{name} is refused as {r['expect'][1]}", code == r["expect"][1], str(e)) + check(f"{name}: and the journal keeps no step for it", journal_step(run, key) is None) + shown_otherwise.append((key, "refused", r["expect"][2])) + else: + check(f"{name} runs", False, str(e)) + continue + if kind == "refused": + check(f"{name} is refused as {r['expect'][1]}", False, first) + continue + answer(run, r["answers"]) + cancelled = any(a[0] == "button" and a[-1] == "cancel" for a in r["answers"]) + try: + run.reply = run.wait(first) + except orca_mcp.McpError as e: + run.reply = {"error": str(e)} + if not cancelled: + check(f"{name} runs", False, str(e)) + continue + run.call("app_wait", **{"for": "idle", "timeout_s": 50}) + if kind == "external": + check(f"{name} runs, handing over to another program", run.reply.get("ran") == tile_id(key), run.reply) + shown_otherwise.append((key, "external", r["expect"][1])) + else: + ok, detail = r["expect"][1](run) + check(f"{name} does its row's job ({kind})", ok, detail) + if not cancelled: + check(f"{name}: its reply names the tile it ran", run.reply.get("ran") == tile_id(key), run.reply) + step = journal_step(run, key) + spec = fixture.get(key, {}) + given = step.get("args", {}).get("args", {}) if step else None + wanted = ({spec["input"]: list(r["value"].values())[0]} if spec.get("input") else spec.get("args")) + check(f"{name}: the journal keeps the tile's action_run with the fixture's arguments", + step is not None and given in ({}, wanted) and (given == wanted or not spec.get("input")), step) + check(f"{name}: whose tile names the fixture's command", commands.get(tile_id(key)) == spec.get("command"), + (commands.get(tile_id(key)), spec.get("command"))) + if r["why"]: + shown_otherwise.append((key, kind, r["why"])) + except orca_mcp.McpError as e: + check(f"{name} runs", False, str(e)) + finally: + for d in run.state().get("dialogs", []): + try: + run.call("dialog_answer", button="close") + except orca_mcp.McpError: + pass + for tool, a in r["post"]: + try: + run.wait(run.call(tool, **a)) + except orca_mcp.McpError as e: + print(f" after {key}: {tool} failed: {e}", flush=True) + + empty(run) + print("\nTiles shown by a refusal or as handing over, and rows that read less than a change of their own:") + for key, kind, why in shown_otherwise: + print(f" {key}: {kind}: {why}") + failed = [c for c in checks if not c[1]] + print(f"{len(checks) - len(failed)}/{len(checks)} checks passed") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/mcp/test_export_running_job.py b/tools/mcp/test_export_running_job.py index dfd3cd2da9..df47b8898d 100755 --- a/tools/mcp/test_export_running_job.py +++ b/tools/mcp/test_export_running_job.py @@ -1,14 +1,14 @@ #!/usr/bin/env python3 -"""Checks what export_replay does with a call whose job outlived its reply. +"""Checks what replay_export does with a call whose job outlived its reply. tools/mcp/orca_mcp.py launch tools/mcp/test_export_running_job.py -A run_replay whose one step waits 3 s past the reply budget replies with its running job once the budget is spent: +A replay_run whose one step waits 3 s past the reply budget replies with its running job once the budget is spent: 45 s, or the cap ORCA_MCP_REPLY_BUDGET_MS sets when the app and this script have it (the sweep sets 10 s, as a shorter cap can end the call opening Preferences before a slow or busy machine has opened it). An export while it runs leaves it out and names it in left_out_running; an export after it succeeded has it as -an await:false step that the later wait refers to, and that replay runs. A call blocked on a +an await:false step that the later app_wait refers to, and that replay runs. A call blocked on a dialog stays in the replay while the dialog is open, since the steps after it answer the dialog. A job that fails after its reply is dropped; no tool fails that late on demand, so the unit tests in test_mcp_results.cpp cover it. Takes about two minutes with the full budget, 45 s with a 10 s one. Exits 0 when @@ -36,46 +36,46 @@ def main(): def tools(replay): return [s["tool"] for s in replay["steps"]] - client.call("export_replay", clear=True) + client.call("replay_export", clear=True) # ---- A job past the reply budget, exported while it runs and after it ends ---- start = time.time() - slow = {"orca_replay_version": "0.1.0", "name": "slow", - "steps": [{"tool": "wait", "args": {"for": "dialog", "timeout_s": orca_mcp.reply_budget_s() + 3}}]} - started = client.call("run_replay", _timeout=120, replay=slow, out_dir=os.path.join(work, "slow")) + slow = {"orca_replay_version": "0.2.0", "name": "slow", + "steps": [{"tool": "app_wait", "args": {"for": "dialog", "timeout_s": orca_mcp.reply_budget_s() + 3}}]} + started = client.call("replay_run", _timeout=120, replay=slow, out_dir=os.path.join(work, "slow")) check("the slow replay replies with its running job", started.get("status") == "running", f"{started.get('status')} after {time.time() - start:.1f} s") job = started.get("job") - client.call("set_settings", values={"wall_loops": 3}) - during = client.call("export_replay") - check("an export while it runs leaves it out", tools(during["replay"]) == ["set_settings"], tools(during["replay"])) - check("and names it in left_out_running", during.get("left_out_running") == [{"tool": "run_replay", "job": job}], + client.call("settings_set", values={"wall_loops": 3}) + during = client.call("replay_export") + check("an export while it runs leaves it out", tools(during["replay"]) == ["settings_set"], tools(during["replay"])) + check("and names it in left_out_running", during.get("left_out_running") == [{"tool": "replay_run", "job": job}], during.get("left_out_running")) - done = client.await_job(started) # a journaled wait on the job + done = client.await_job(started) # a journaled app_wait on the job check("the job then succeeds", done.get("passed") is True, done) path = os.path.join(work, "after.json") - after = client.call("export_replay", path=path, overwrite=True) + after = client.call("replay_export", path=path, overwrite=True) steps = after["replay"]["steps"] - check("an export after it ends has it as a step", tools(after["replay"]) == ["run_replay", "set_settings", "wait"], + check("an export after it ends has it as a step", tools(after["replay"]) == ["replay_run", "settings_set", "app_wait"], tools(after["replay"])) check("replayed with await:false", steps[0].get("await") is False and steps[0].get("save_as") == "job1", steps[0]) - check("the wait refers to it", steps[2]["args"].get("job") == "${jobs.job1}", steps[2]) + check("the app_wait refers to it", steps[2]["args"].get("job") == "${jobs.job1}", steps[2]) check("nothing is left out", "left_out_running" not in after, after.get("left_out_running")) # ---- A call blocked on a dialog stays while the dialog is open ---- - client.call("export_replay", clear=True) - blocked = client.call("run_action", id="orca_command:open_preferences:orca") + client.call("replay_export", clear=True) + blocked = client.call("action_run", id="orca_command:open_preferences:orca") check("Preferences blocks its call", blocked.get("status") == "blocked_by_dialog", blocked.get("status")) - open_export = client.call("export_replay") - check("an export with the dialog open keeps the call", tools(open_export["replay"]) == ["run_action"], + open_export = client.call("replay_export") + check("an export with the dialog open keeps the call", tools(open_export["replay"]) == ["action_run"], tools(open_export["replay"])) check("and leaves nothing out", "left_out_running" not in open_export, open_export.get("left_out_running")) - client.call("answer_dialog", button="close") + client.call("dialog_answer", button="close") client.await_job(blocked) # ---- The replay exported after the slow job runs ---- - replay = client.await_job(client.call("run_replay", _timeout=120, path=path, out_dir=os.path.join(work, "replay"))) + replay = client.await_job(client.call("replay_run", _timeout=120, path=path, out_dir=os.path.join(work, "replay"))) check("the exported replay runs", replay.get("passed") is True, json.dumps([(s["tool"], s["ok"]) for s in replay.get("steps", [])])) diff --git a/tools/mcp/test_install_filaments.py b/tools/mcp/test_install_filaments.py new file mode 100644 index 0000000000..12aae2d5fb --- /dev/null +++ b/tools/mcp/test_install_filaments.py @@ -0,0 +1,262 @@ +"""Checks filament_install and filament_uninstall: a system filament installed by the short name the filament selector +shows is offered for a slot, also after a restart, and goes again when uninstalled; the filament a slot uses is not +uninstalled; and the app keeps a printer's default filaments installed: when an uninstall leaves an installed printer (a +second one, the Goofoo Velo+ 0.4, installed from the shipped profiles) with no filament that fits it, its default filaments +are installed again at once, the reply names them, and a restart shows the same. A printer that is only shown, not installed +(the Bambu Lab A1 mini 0.4, selected once), is not one of those: a filament call installs none of its default filaments, +then or after a restart. + +It launches OrcaSlicer itself, twice, on a fresh data folder seeded with one printer, the Bambu Lab X1 Carbon 0.4 nozzle, +and one filament, Bambu PLA Basic @BBL X1C, in slot 1; the restart shows that a filament installed stays installed. Each +launch is stopped on every path out, and nothing but a launch of this test is stopped. It needs no network, signs in to +nothing and connects to no printer. +Run it as python tools/mcp/test_install_filaments.py [--bin PATH] [--datadir PATH]. +""" +import contextlib +import json +import os +import shutil +import socket +import subprocess +import sys +import tempfile +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from orca_mcp import McpError, OrcaMcp, app_env # noqa: E402 + +TOKEN = "install-filaments-test-token" +SLOT_ONE = "Bambu PLA Basic @BBL X1C" +# A printer of the seeded printer's bundle that the folder does not install and that SLOT_ONE does not fit, and a +# filament that fits only the seeded printer's family, so that installing it gives the A1 mini nothing that fits. +SHOWN_PRINTER = "Bambu Lab A1 mini 0.4 nozzle" +X1C_ONLY = "Bambu PLA Matte @BBL X1C" +results = [] + + +def check(name, ok, detail=""): + results.append((name, bool(ok))) + print(("PASS " if ok else "FAIL ") + name + ("" if ok else " " + str(detail)[:400]), flush=True) + + +def free_port(): + """A port nothing listens on now, so that this test runs beside the others of a sweep.""" + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def harness(env, *args): + return subprocess.run([sys.executable, os.path.join(HERE, "orca_mcp.py"), *args], env=env, capture_output=True, text=True, + timeout=300) + + +@contextlib.contextmanager +def launched(datadir, binary): + """An instance on `datadir`: its client, or None when it did not start, stopped on every path out of the block. + + A launch writes its session file before it waits for the app, and one that is not ready exits leaving its app + running, so the stop goes by that file whenever it is there. Only this launch writes it: a file an earlier run left + is removed first, so that no other app is ever stopped.""" + port = free_port() + session = os.path.join(datadir, "session.json") + env = app_env(dict(os.environ, ORCA_MCP_SESSION=session, ORCA_MCP_TOKEN=TOKEN), datadir) + if os.path.exists(session): + os.remove(session) + try: + started = harness(env, "launch", "--datadir", datadir, "--port", str(port), *binary) + if started.returncode != 0: + print(started.stdout, started.stderr) + yield None + return + orca = OrcaMcp(port=port, token=TOKEN) + orca.call("app_wait", **{"for": "ready"}) + yield orca + finally: + if os.path.exists(session): + harness(env, "stop") + time.sleep(2) + + +def refusal(orca, tool, **args): + """The text and details of the error `tool` replies, or None when it runs.""" + try: + orca.call(tool, **args) + except McpError as e: + text = str(e) + try: + details = json.loads(text.rpartition("\n")[2]) + except ValueError: + details = {} + return text, details if isinstance(details, dict) else {} + return None + + +def filaments(orca, **args): + """preset_list's filament items by name, every page of them: those the selectors offer, or with include_uninstalled + every one.""" + items, offset = {}, 0 + while offset is not None: + page = orca.call("preset_list", type="filament", limit=500, offset=offset, **args) + items.update((item["name"], item) for item in page["items"]) + offset = page.get("next_offset") + return items + + +def offered_for_slot(orca, name, preset): + """Whether preset_select assigns `name` to slot 1 as the selector offers it: the slot then holds `preset`, and the + reply shows no hidden preset. Slot 1 gets its filament back afterwards.""" + reply = orca.call("preset_select", type="filament", name=name, filament_slot=1) + orca.call("preset_select", type="filament", name=SLOT_ONE, filament_slot=1) + return reply.get("selected") == preset and "shown" not in reply, reply + + +def bbl_printer(orca, name): + """preset_list's item for the printer preset `name` of the seeded printer's bundle, installed or not.""" + items = orca.call("preset_list", type="printer", vendor="BBL", include_uninstalled=True, limit=500)["items"] + return next((item for item in items if item["name"] == name), {}) + + +def shown_printer_left_out(orca): + """Selects a printer that is not installed and then the seeded printer again, which shows the printer and its + default filaments for this session only; a filament call then installs none of those filaments, as a restart would + not, and leaves the printer shown. The selection is as it was afterwards. Returns the default filaments it showed.""" + selected = orca.call("app_state")["presets"] + listed = bbl_printer(orca, SHOWN_PRINTER) + check("a printer of the seeded bundle is not installed and no installed filament fits it", + listed.get("installed") is False and not fitting(orca, SHOWN_PRINTER), (listed, sorted(fitting(orca, SHOWN_PRINTER)))) + before = set(filaments(orca, include_incompatible=True)) + orca.call("preset_select", type="printer", name=SHOWN_PRINTER) + orca.call("preset_select", type="printer", name=selected["printer"]) + orca.call("preset_select", type="process", name=selected["process"]) + orca.call("preset_select", type="filament", name=SLOT_ONE, filament_slot=1) + shown = set(filaments(orca, include_incompatible=True)) - before + check("selecting it shows it and its default filaments for this session", + shown and "installed" not in bbl_printer(orca, SHOWN_PRINTER), (sorted(shown), bbl_printer(orca, SHOWN_PRINTER))) + + reply = orca.call("filament_install", names=[X1C_ONLY]) + print(f"filament_install {X1C_ONLY!r} with {SHOWN_PRINTER!r} shown: {reply}", flush=True) + after = set(filaments(orca, include_incompatible=True)) + check("a filament call then names none of that printer's default filaments as installed", + reply.get("installed") == [X1C_ONLY] and not reply.get("filaments_installed"), reply) + check("and what is installed is what was installed before and the filament it named", after == before | {X1C_ONLY}, + (sorted(after - before - {X1C_ONLY}), sorted(before - after))) + check("and the printer stays shown for this session", "installed" not in bbl_printer(orca, SHOWN_PRINTER), + bbl_printer(orca, SHOWN_PRINTER)) + return sorted(shown) + + +def first_run(orca): + shown = shown_printer_left_out(orca) + # A short name also stands for the presets whose compatible_printers name no printer, as the dialog's row does, which + # a compatibility condition can keep from the selected printer: preset_list lists those with include_incompatible. + every = filaments(orca, include_uninstalled=True, include_incompatible=True) + # A filament of the seeded printer the folder has not installed, and the short name its selector shows. + candidate = next((item for item in every.values() if item.get("installed") is False and item.get("compatible", True) + and item.get("alias") and item.get("vendor") == "Bambu Lab"), None) + check("preset_list lists a compatible filament with installed: false", candidate is not None) + if candidate is None: + return None + short = candidate["alias"] + + found = refusal(orca, "filament_install", names=[short + "X"]) + check("a name no filament has is refused with the closest names", found is not None + and found[1].get("code") == "no_such_filament" and short in found[1].get("similar", []), found) + + installed = orca.call("filament_install", names=[short]) + print(f"filament_install {short!r}: {installed}", flush=True) + offered = filaments(orca) + check("filament_install by the short name installs its preset of the seeded printer", + candidate["name"] in installed.get("installed", []) and candidate["name"] in offered + and "installed" not in offered[candidate["name"]], (installed, short)) + check("each preset it installed is of that short name", all(every[name].get("alias") == short + for name in installed.get("installed", [])), installed) + ok, reply = offered_for_slot(orca, short, candidate["name"]) + check("and the slot's selector offers it (preset_select shows no hidden preset)", ok, reply) + again = orca.call("filament_install", names=[short]) + check("installing it again changes nothing and says so", again.get("installed") == [] + and candidate["name"] in again.get("installed_already", []), again) + return short, candidate["name"], defaults_given_back(orca), shown + + +def fitting(orca, printer): + """The installed filaments preset_list offers for `printer`, a printer preset, by name.""" + return set(filaments(orca, printer=printer)) + + +def defaults_given_back(orca): + """With a second printer installed and not selected, uninstalls every installed filament that fits it and no slot + uses: the app keeps a printer's default filaments installed, so they are installed again at once, and the reply + names them. Returns the second printer's preset and the filaments offered for it afterwards, which a restart keeps.""" + seeded = orca.call("app_state")["presets"]["printer"] + added = orca.await_job(orca.call("printer_install", models=[{"vendor": "Goofoo", "model": "Goofoo Velo+", "nozzles": ["0.4"]}])) + velo = added["selected"] + orca.call("preset_select", type="printer", name=seeded) + in_slots = {name for name, item in filaments(orca).items() if item.get("filament_slots")} + fits = fitting(orca, velo) - in_slots + check("a second printer, not selected, has installed filaments that fit it and no slot uses", fits and velo != seeded, + (added, sorted(fits))) + removed = orca.call("filament_uninstall", names=sorted(fits)) + print(f"filament_uninstall {sorted(fits)}: {removed}", flush=True) + given = set(removed.get("filaments_installed", [])) + now = fitting(orca, velo) + installed = set(filaments(orca, include_incompatible=True)) + check("the reply names the default filaments the app gives the second printer again, and only those", + given and given == now - in_slots and given <= installed, (removed, sorted(now))) + check("what the reply calls uninstalled is no longer installed", not set(removed.get("uninstalled", [])) & installed, removed) + return velo, sorted(now) + + +def second_run(orca, short, preset, given_back, shown): + installed = set(filaments(orca, include_incompatible=True)) + check("after a restart none of the default filaments of the printer that was only shown is installed", + not installed & set(shown), sorted(installed & set(shown))) + velo, offered_for_velo = given_back + check("after a restart the filaments offered for the second printer are what the uninstall replied", + sorted(fitting(orca, velo)) == offered_for_velo, (sorted(fitting(orca, velo)), offered_for_velo)) + offered = filaments(orca) + check("after a restart it is still installed", preset in offered and "installed" not in offered[preset], + offered.get(preset)) + ok, reply = offered_for_slot(orca, short, preset) + check("and offered for a slot", ok, reply) + + removed = orca.call("filament_uninstall", names=[short]) + check("filament_uninstall by the short name uninstalls it", preset in removed.get("uninstalled", []) + and preset not in filaments(orca) and filaments(orca, include_uninstalled=True)[preset].get("installed") is False, + removed) + + found = refusal(orca, "filament_uninstall", names=["Bambu PLA Basic"]) + check("uninstalling the filament slot 1 uses is refused, naming the slot", found is not None + and found[1].get("code") == "filament_in_use" and "Filament slot 1 uses " + SLOT_ONE + "." in found[0], found) + check("and it stays installed", SLOT_ONE in filaments(orca)) + + +def main(): + extra = sys.argv[1:] + binary = ["--bin", extra[extra.index("--bin") + 1]] if "--bin" in extra else [] + given = "--datadir" in extra + root = os.path.abspath(extra[extra.index("--datadir") + 1]) if given else tempfile.mkdtemp(prefix="oif-") + datadir = os.path.join(root, "filaments") + try: + named = None + with launched(datadir, binary) as orca: + check("the app starts", orca is not None) + if orca is not None: + named = first_run(orca) + if named is not None: + with launched(datadir, binary) as orca: + check("the app starts again on the same folder", orca is not None) + if orca is not None: + second_run(orca, *named) + finally: + if not given: + shutil.rmtree(root, ignore_errors=True) + + failed = [r for r in results if not r[1]] + print(f"\n{len(results) - len(failed)}/{len(results)} passed") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/mcp/test_install_printers.py b/tools/mcp/test_install_printers.py new file mode 100644 index 0000000000..fa2848f5b8 --- /dev/null +++ b/tools/mcp/test_install_printers.py @@ -0,0 +1,346 @@ +"""Checks printer_list_models, printer_install and printer_uninstall, and that the Printer Selection dialog's Confirm, +which applies the printers through the same step, installs a model ticked in its page and keeps the others. + +It launches OrcaSlicer itself, twice, on a fresh data folder seeded with one printer, the Bambu Lab X1 Carbon 0.4 nozzle, +and no cache/wizard_profile_data.json, so that the first printer_list_models builds that file; the restart shows that a +printer installed stays installed. Each launch is stopped on every path out, and nothing but a launch of this test is +stopped. What it installs comes from the profiles OrcaSlicer ships (the Goofoo Velo+ with its 0.4 nozzle, of a vendor +the folder has not installed); it needs no network, signs in to nothing and connects to no printer. + +The dialog is opened as a person opens it, with the button beside the sidebar's Printer title. Its Confirm installs every +nozzle of each model it shows ticked, so the test installs the X1 Carbon's other nozzles first, with the presets' unsaved +changes carried over (preset_changes transfer, a process change and the printer's own), which makes the set the dialog +collects the set installed; it then ticks the Velo+, which printer_uninstall took out, clicking its block in the page as a +person does, confirms, and reads every Velo+ nozzle installed and the X1 Carbon's kept. Last, with Generic ABS @System installed, it +installs a model of a third vendor (the Voxelab Aquila X2) and reads the filaments its reload changed in the reply and in +preset_list. +Run it as python tools/mcp/test_install_printers.py [--bin PATH] [--datadir PATH]. +""" +import contextlib +import json +import os +import re +import shutil +import socket +import subprocess +import sys +import tempfile +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from orca_mcp import McpError, OrcaMcp, app_env # noqa: E402 + +TOKEN = "install-printers-test-token" +X1C = "Bambu Lab X1 Carbon" +VELO = {"vendor": "Goofoo", "model": "Goofoo Velo+"} +results = [] + + +def check(name, ok, detail=""): + results.append((name, bool(ok))) + print(("PASS " if ok else "FAIL ") + name + ("" if ok else " " + str(detail)[:400]), flush=True) + + +def free_port(): + """A port nothing listens on now, so that this test runs beside the others of a sweep.""" + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def harness(env, *args): + return subprocess.run([sys.executable, os.path.join(HERE, "orca_mcp.py"), *args], env=env, capture_output=True, text=True, + timeout=300) + + +@contextlib.contextmanager +def launched(datadir, binary): + """An instance on `datadir`: its client, or None when it did not start, stopped on every path out of the block. + + A launch writes its session file before it waits for the app, and one that is not ready exits leaving its app + running, so the stop goes by that file whenever it is there. Only this launch writes it: a file an earlier run left + is removed first, so that no other app is ever stopped.""" + port = free_port() + session = os.path.join(datadir, "session.json") + env = app_env(dict(os.environ, ORCA_MCP_SESSION=session, ORCA_MCP_TOKEN=TOKEN), datadir) + if os.path.exists(session): + os.remove(session) + try: + started = harness(env, "launch", "--datadir", datadir, "--port", str(port), *binary) + if started.returncode != 0: + print(started.stdout, started.stderr) + yield None + return + orca = OrcaMcp(port=port, token=TOKEN) + orca.call("app_wait", **{"for": "ready"}) + yield orca + finally: + if os.path.exists(session): + harness(env, "stop") + time.sleep(2) + + +def call(orca, tool, **args): + """`tool`'s result, followed to its end when it runs as a job.""" + return orca.await_job(orca.call(tool, **args)) + + +def refusal(orca, tool, **args): + """The text and details of the error `tool` replies, or None when it runs.""" + try: + call(orca, tool, **args) + except McpError as e: + text = str(e) + try: + details = json.loads(text.rpartition("\n")[2]) + except ValueError: + details = {} + return text, details if isinstance(details, dict) else {} + return None + + +def printers(orca): + """The printer presets the printer selector offers, and the one selected.""" + items = orca.call("preset_list", type="printer", limit=500)["items"] + return sorted(item["name"] for item in items), next((item["name"] for item in items if item.get("selected")), None) + + +def model(orca, vendor, name): + """printer_list_models' item for `vendor`'s model `name`.""" + items = call(orca, "printer_list_models", vendor=vendor, query=name, limit=500)["items"] + return next((item for item in items if item["model"] == name), None) + + +def preset_of(orca, model_name, nozzle): + """The installed printer preset of `model_name` with `nozzle`, or None.""" + for item in orca.call("preset_list", type="printer", limit=500)["items"]: + if item.get("printer_model") == model_name and item.get("nozzle") == nozzle: + return item["name"] + return None + + +def first_run(orca, datadir): + cache = os.path.join(datadir, "cache", "wizard_profile_data.json") + check("the fresh folder holds no printer data cache", not os.path.exists(cache)) + listed = call(orca, "printer_list_models", limit=500) + vendors = {item["vendor"] for item in listed["items"]} + check("printer_list_models lists more than one vendor", len(vendors) > 1 and listed["total"] > 100, + (len(vendors), listed["total"])) + x1c = next((item for item in listed["items"] if item["vendor"] == "BBL" and item["model"] == X1C), None) + check("the seeded model is marked installed with its nozzle", x1c is not None and x1c["installed_nozzles"] == ["0.4"] + and "0.2" in x1c["nozzles"], x1c) + check("and the printer data cache is written", os.path.exists(cache)) + velo = model(orca, "goofoo", VELO["model"]) + check("a model of a vendor not installed has several nozzles, none installed", + velo is not None and {"0.2", "0.4", "0.6"} <= set(velo["nozzles"]) and velo["installed_nozzles"] == [], velo) + + found = refusal(orca, "printer_install", models=[{"model": "Goofoo Velo"}]) + check("a model name no vendor has is refused with the closest names", found is not None and + found[1].get("code") == "no_such_model" and "Goofoo Velo+" in found[1].get("similar", []), found) + found = refusal(orca, "printer_install", models=[dict(VELO, nozzles=["0.3"])]) + check("a nozzle the model lacks is refused with its nozzles", found is not None and found[1].get("code") == "no_such_nozzle" + and "0.4" in found[1].get("nozzles", []), found) + check("and nothing was installed", preset_of(orca, VELO["model"], "0.4") is None) + + before, _ = printers(orca) + installed = call(orca, "printer_install", models=[dict(VELO, nozzles=["0.4"])]) + print(f"printer_install: {installed}", flush=True) + velo_preset = preset_of(orca, VELO["model"], "0.4") + names, selected = printers(orca) + check("printer_install of the Velo+ with its 0.4 nozzle offers its preset, selected", velo_preset is not None + and installed.get("added") == [velo_preset] and selected == velo_preset == installed.get("selected"), + (installed, names, selected)) + check("and not its other nozzles, and keeps the seeded printer", + preset_of(orca, VELO["model"], "0.2") is None and set(before) <= set(names), names) + velo = model(orca, "Goofoo", VELO["model"]) + check("printer_list_models marks its 0.4 nozzle installed", velo is not None and velo["installed_nozzles"] == ["0.4"], velo) + # The reload installs a printer's default filaments where no installed one fits it: the reply names them, and the + # selectors offer them. + offered = {item["name"] for item in orca.call("preset_list", type="filament", printer=velo_preset, limit=500)["items"]} + check("the filaments the reload installed are named and offered for it", + set(installed.get("filaments_installed", [])) <= offered and installed.get("filaments_uninstalled") is None, + (installed.get("filaments_installed"), sorted(offered))) + return velo_preset + + +def second_run(orca, velo_preset): + names, selected = printers(orca) + check("after a restart the Velo+ is still installed", velo_preset in names, names) + seeded = preset_of(orca, X1C, "0.4") + orca.call("preset_select", type="printer", name=seeded) + fits_velo = {item["name"] for item in orca.call("preset_list", type="filament", printer=velo_preset, limit=500)["items"]} + fits_x1c = {item["name"] for item in orca.call("preset_list", type="filament", limit=500)["items"]} + check("with the seeded printer selected, preset_list {printer} lists what fits the Velo+", + fits_velo and "Bambu PLA Basic @BBL X1C" in fits_x1c and "Bambu PLA Basic @BBL X1C" not in fits_velo, + (sorted(fits_velo), sorted(fits_x1c))) + + orca.call("preset_select", type="printer", name=velo_preset) + removed = call(orca, "printer_uninstall", models=[VELO]) + names, selected = printers(orca) + check("printer_uninstall of the selected Velo+ takes its preset out and selects the seeded printer", + velo_preset not in names and removed.get("removed") == [velo_preset] and selected == seeded == removed.get("selected"), + (removed, names, selected)) + + found = refusal(orca, "printer_uninstall", models=[{"model": X1C, "nozzles": ["0.4"]}]) + check("uninstalling the last printer is refused", found is not None and found[1].get("code") == "last_printer" + and "At least one printer model must stay installed." in found[0], found) + check("and leaves it installed", printers(orca) == (names, selected), printers(orca)) + + # Unsaved changes: refused without preset_changes, carried over with transfer: the process's, and the printer's own + # onto the printer the install selects, whose printable height (250 mm) is not the one changed. + orca.call("settings_set", type="process", values={"layer_height": 0.12}) + orca.call("settings_set", type="printer", values={"printable_height": 240}) + found = refusal(orca, "printer_install", models=[{"vendor": "BBL", "model": X1C}]) + check("an install while a preset has unsaved changes is refused, saying what to pass", + found is not None and found[1].get("code") == "unsaved_preset_changes" and "preset_changes" in found[0], found) + check("and installs nothing", printers(orca) == (names, selected), printers(orca)) + every = call(orca, "printer_install", models=[{"vendor": "BBL", "model": X1C}], preset_changes="transfer") + kept = orca.call("settings_get", type="process", keys=["layer_height"])["items"][0] + check("printer_install of every X1 Carbon nozzle with transfer keeps the process's unsaved change", + sorted(every.get("added", [])) == sorted(p for p in (preset_of(orca, X1C, n) for n in ("0.2", "0.6", "0.8")) if p) + and len(every.get("added", [])) == 3 and float(kept["value"]) == 0.12 + and "layer_height" in every.get("modified", {}).get("process", {}).get("keys", []), (every, kept)) + height = orca.call("settings_get", type="printer", keys=["printable_height"])["items"][0] + saved = orca.call("settings_get", type="printer", keys=["printable_height"], preset=every.get("selected"))["items"][0] + check("and puts the printer's own unsaved change on the printer it selects", every.get("selected") != seeded + and float(height["value"]) == 240 and float(saved["value"]) == 250 + and "printable_height" in every.get("modified", {}).get("printer", {}).get("keys", []), (every, height, saved)) + orca.call("settings_set", type="process", reset_all=True) + orca.call("settings_set", type="printer", reset_all=True) + + # The dialog's Confirm with a model ticked in its page, the Velo+ that printer_uninstall took out: it installs every + # nozzle of it and keeps the X1 Carbon's. + names_before, _ = printers(orca) + x1c_before, velo_before = model(orca, "BBL", X1C), model(orca, "Goofoo", VELO["model"]) + check("before the dialog, the Velo+ is not installed", velo_before is not None and velo_before["installed_nozzles"] == [], + velo_before) + confirmed = confirm_printer_selection(orca, tick=VELO) + check("the Printer Selection dialog opens from the sidebar, takes a tick of the Velo+, and its Confirm closes it", + confirmed is True, confirmed) + names_after, selected_after = printers(orca) + velo_after, x1c_after = model(orca, "Goofoo", VELO["model"]), model(orca, "BBL", X1C) + velo_presets = sorted(p for p in (preset_of(orca, VELO["model"], n) for n in velo_before["nozzles"]) if p) + check("confirmed, it installs every nozzle of the Velo+, which the printer selector offers", + velo_after is not None and sorted(velo_after["installed_nozzles"]) == sorted(velo_before["nozzles"]) + and len(velo_presets) == len(velo_before["nozzles"]) and set(velo_presets) == set(names_after) - set(names_before), + (velo_after, velo_presets, sorted(set(names_after) - set(names_before)))) + check("and keeps the X1 Carbon's nozzles and printers installed", + x1c_after == x1c_before and set(names_before) <= set(names_after), (x1c_before, x1c_after)) + check("and selects a printer the Confirm added", selected_after in velo_presets, selected_after) + + # The filaments the reload of a printer install changes, with a @System filament installed, which the reload swaps for + # its vendor's own where a vendor's profile names one: the reply and preset_list agree. + orca.call("filament_install", names=["Generic ABS @System"]) + before = installed_filaments(orca) + voxelab = call(orca, "printer_install", models=[{"vendor": "Voxelab", "model": "Voxelab Aquila X2"}]) + after = installed_filaments(orca) + print(f"printer_install of another vendor's model: {voxelab}", flush=True) + check("printer_install's filaments_installed and filaments_uninstalled are what preset_list shows changed", + set(voxelab.get("filaments_installed", [])) == after - before + and set(voxelab.get("filaments_uninstalled", [])) == before - after, (voxelab, sorted(after ^ before))) + check("and Generic ABS @System is reported uninstalled exactly when preset_list no longer has it installed", + ("Generic ABS @System" in voxelab.get("filaments_uninstalled", [])) == ("Generic ABS @System" not in after), + (voxelab, "Generic ABS @System" in after)) + + +def installed_filaments(orca): + """The names of every installed filament, whatever its compatibility with the printer selected.""" + names, offset = set(), 0 + while offset is not None: + page = orca.call("preset_list", type="filament", include_incompatible=True, limit=500, offset=offset) + names.update(item["name"] for item in page["items"]) + offset = page.get("next_offset") + return names + + +def printer_settings_button(orca): + """The ref of the button beside the sidebar's Printer title that opens the Printer Selection dialog: the title row's + last icon button, which says nothing of itself (no label, no tooltip), after the icons that do.""" + orca.call("view_set", tab="prepare") + _, texts = orca.call_with_text("widget_list", target="main", include_menus=False, include_imgui=False, include_web=False, + max_nodes=3000) + lines = "\n".join(texts).splitlines() + title = next((i for i, line in enumerate(lines) if re.search(r'label "Printer" \(Label\)', line)), None) + if title is None: + return None + ref = None + for line in lines[title + 1:]: + if "combo" in line: + break + found = re.match(r"\s*\[(\w+)\] button \(ScalableButton\)", line) + if found: + ref = found.group(1) + return ref + + +def confirm_printer_selection(orca, tick): + """Opens the Printer Selection dialog with the button beside the sidebar's Printer title, as a person does, clicks + the model `tick` ({vendor, model}) in its page, as a person ticks or unticks it, presses its Confirm, and waits until + the dialog has closed and the click's job has ended. True, or what went wrong.""" + ref = printer_settings_button(orca) + if ref is None: + return "no button beside the sidebar's Printer title" + clicked = orca.call("widget_click", target=ref) + if not orca.call("app_wait", **{"for": "dialog", "timeout_s": 30}).get("satisfied"): + return ("no dialog opened", clicked) + # The page lists the models once it has the dialog's data, a moment after it opens, on a page it navigates to. A + # model is ticked by a click on its block, which marks its box. + box = f".ModelCheckBox[vendor='{tick['vendor']}'][model='{tick['model']}']" + block = f".PrinterBlock[onclick=\"ChooseModel('{tick['vendor']}','{tick['model']}')\"]" + selected = (f'(function () {{ var e = document.querySelector("{box}"); ' + 'return e ? e.classList.contains("ModelCheckBoxSelected") : null; })()') + + def box_state(): + try: + return orca.call("webview_run_javascript", code=selected).get("result") + except McpError: # the page is navigating + return None + + ticked, button = None, "#PreBtn" + try: + deadline = time.time() + 40 + while box_state() is None and time.time() < deadline: + time.sleep(0.5) + orca.call("widget_click", target={"css": block}, timeout_s=40) + ticked = box_state() + # A page that did not take the tick is left with its Cancel, so that nothing is confirmed. + if ticked is True: + button = "#AcceptBtn" + except McpError as e: + ticked = "the page could not be driven: " + str(e) + orca.call("widget_click", target={"css": button}, timeout_s=40) + if not orca.call("app_wait", **{"for": "no_dialog", "timeout_s": 50}).get("satisfied"): + return "the dialog stayed open" + orca.await_job(clicked) + return True if button == "#AcceptBtn" else ("the model's box did not take the tick", ticked) + + +def main(): + extra = sys.argv[1:] + binary = ["--bin", extra[extra.index("--bin") + 1]] if "--bin" in extra else [] + given = "--datadir" in extra + root = os.path.abspath(extra[extra.index("--datadir") + 1]) if given else tempfile.mkdtemp(prefix="oip-") + datadir = os.path.join(root, "printers") + try: + velo_preset = None + with launched(datadir, binary) as orca: + check("the app starts", orca is not None) + if orca is not None: + velo_preset = first_run(orca, datadir) + if velo_preset is not None: + with launched(datadir, binary) as orca: + check("the app starts again on the same folder", orca is not None) + if orca is not None: + second_run(orca, velo_preset) + finally: + if not given: + shutil.rmtree(root, ignore_errors=True) + + failed = [r for r in results if not r[1]] + print(f"\n{len(results) - len(failed)}/{len(results)} passed") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/mcp/test_list_windows.py b/tools/mcp/test_list_windows.py index 7dd4fb73e0..f0200d89d7 100644 --- a/tools/mcp/test_list_windows.py +++ b/tools/mcp/test_list_windows.py @@ -1,12 +1,12 @@ #!/usr/bin/env python3 -"""Checks list_windows: every open window, with a ref that screenshot and the GUI tools take. +"""Checks window_list: every open window, with a ref that window_screenshot and the GUI tools take. tools/mcp/orca_mcp.py launch tools/mcp/test_list_windows.py The main window comes first. The Plugins window, which doesn't block the app, is listed with a ref: -a screenshot of that ref captures the window, list_widgets with it as target reads that window alone, -and press_keys Escape sent to it closes it, after which the list leaves it out. Preferences, a modal +a screenshot of that ref captures the window, widget_list with it as target reads that window alone, +and keyboard_press Escape sent to it closes it, after which the list leaves it out. Preferences, a modal dialog, comes last. Action Replay is listed as hidden, without a ref. Exits 0 when every check passes. """ @@ -26,7 +26,7 @@ def main(): checks.append((name, bool(ok), detail)) def windows(): - return client.call("list_windows").get("items", []) + return client.call("window_list").get("items", []) def find(title): return next((w for w in windows() if w.get("title") == title), None) @@ -40,10 +40,10 @@ def main(): time.sleep(0.25) return predicate() - client.call("new_project", discard_changes=True) - client.call("set_view", tab="prepare") + client.call("project_new", discard_changes=True) + client.call("view_set", tab="prepare") - listed = client.call("list_windows") + listed = client.call("window_list") items = listed.get("items", []) check("the reply is a page of windows", listed.get("total") == len(items) and listed.get("offset") == 0, listed) main_window = items[0] if items else {} @@ -52,37 +52,37 @@ def main(): check("the main window has a size", main_window.get("width", 0) > 0 and main_window.get("height", 0) > 0, main_window) # The Plugins window doesn't block the app. - client.call("run_action", id="orca_command:open_plugins:orca") + client.call("action_run", id="orca_command:open_plugins:orca") plugins = wait_for(lambda: find("Plugins"), 15) check("the Plugins window is listed", plugins, windows()) plugins = plugins or {} check("it is a window that doesn't block, with a ref", plugins.get("modal") is False and plugins.get("ref"), plugins) check("it holds a web page", plugins.get("web") is True, plugins) if plugins.get("ref"): - shot = client.call("screenshot", target=plugins["ref"], include_image=False) - whole = client.call("screenshot", target="main", include_image=False) + shot = client.call("window_screenshot", target=plugins["ref"], include_image=False) + whole = client.call("window_screenshot", target="main", include_image=False) check("a screenshot of its ref captures it", shot.get("path") and shot.get("width", 0) > 0, shot) check("and not the main window", (shot.get("width"), shot.get("height")) != (whole.get("width"), whole.get("height")), f"{shot} / {whole}") - _snap, texts = client.call_with_text("list_widgets", target=plugins["ref"], include_web=False) + _snap, texts = client.call_with_text("widget_list", target=plugins["ref"], include_web=False) tree = texts[0] if texts else "" first = tree.splitlines()[0] if tree else "" - check("list_widgets with its ref reads that window alone", '"Plugins"' in first and "MainFrame" not in tree, first) - client.call("press_keys", keys="Escape", target=plugins["ref"]) - check("press_keys Escape on its ref closes it", wait_for(lambda: find("Plugins") is None, 10), windows()) + check("widget_list with its ref reads that window alone", '"Plugins"' in first and "MainFrame" not in tree, first) + client.call("keyboard_press", keys="Escape", target=plugins["ref"]) + check("keyboard_press Escape on its ref closes it", wait_for(lambda: find("Plugins") is None, 10), windows()) # A modal dialog comes last. - prefs = client.call("run_action", id="orca_command:open_preferences:orca") + prefs = client.call("action_run", id="orca_command:open_preferences:orca") modal = wait_for(lambda: find("Preferences"), 15) listed = windows() check("Preferences is listed as modal, with a ref", modal and modal.get("modal") is True and modal.get("ref"), listed) check("the modal dialog comes last", listed and listed[-1].get("title") == "Preferences", listed) - client.call("answer_dialog", dialog={"title": "Preferences"}, button="close") + client.call("dialog_answer", dialog={"title": "Preferences"}, button="close") client.await_job(prefs) check("Preferences is gone from the list once closed", find("Preferences") is None, windows()) # Action Replay is the person's own window: listed, but out of reach. - client.call("run_action", id="orca_command:open_action_replay:orca") + client.call("action_run", id="orca_command:open_action_replay:orca") replay = wait_for(lambda: find("Action Replay"), 15) check("Action Replay is listed as hidden", replay and replay.get("hidden") is True, windows()) check("without a ref", replay is not None and "ref" not in replay, replay) diff --git a/tools/mcp/test_operation_routes.py b/tools/mcp/test_operation_routes.py index eff9f5927c..8618aa5763 100644 --- a/tools/mcp/test_operation_routes.py +++ b/tools/mcp/test_operation_routes.py @@ -4,12 +4,13 @@ tools/mcp/orca_mcp.py launch tools/mcp/test_operation_routes.py -A Speed Dial command (run with run_action), the tool that does the same thing and the plugin API's -binding run one operation of GUI/Operations, so each pair here gets one answer: a project saved under -a .gcode.3mf name; an export of a project with no objects (a .3mf is written, an STL and a sliced file -are refused); a layer asked of a Preview that has none; an arrangement from the assemble view and with -a gizmo open; a preset for a mixed-colour filament slot; and a hidden printer selected by name through -the plugin API, as the select_preset tool selects one. The last two need the Bambu Lab X1 Carbon among +A command, a Speed Dial tile that runs it (with action_run) and the plugin API's binding run one +operation of GUI/Operations, so each pair here gets one answer: a layer asked of a Preview that has none +(the Go to layer tile and view_set); a preset for a mixed-colour filament slot; and a hidden printer +selected by name through the plugin API, as preset_select selects one. It also checks what a command +refuses or does in those states alone: a project saved under a .gcode.3mf name; an export of a project +with no objects (a .3mf is written, an STL and a sliced file are refused); an arrangement from the +assemble view and with a gizmo open. The last two pairs need the Bambu Lab X1 Carbon among the printers, which the harness's datadir has. Run it on a freshly launched app: the Preview keeps the layers of the last slice, and a hidden preset stays shown until the app restarts. Exits 0 when every check passes. @@ -60,105 +61,98 @@ def main(): return "blocked_by_dialog", json.dumps(reply.get("dialogs")) return None, client.await_job(reply) - def command(name, **command_args): - return answer("run_action", id="orca_command:%s:orca" % name, args=command_args) + def tile(name, **tile_args): + return answer("action_run", id="orca_command:%s:orca" % name, args=tile_args) def plugin_api(**args): code = "import ops_presets\nresult = ops_presets.preset_api(args)" - return client.call("run_script", filename=FIXTURE, code=code, args=args)["result"] + return client.call("script_run", filename=FIXTURE, code=code, args=args)["result"] def offsets(): - return [o["instances"][0]["offset"][:2] for o in client.call("list_objects")["plates"][0]["objects"]] + return [o["instances"][0]["offset"][:2] for o in client.call("object_list")["plates"][0]["objects"]] - client.call("new_project", discard_changes=True, preset_changes="discard") - client.call("set_view", tab="prepare") + client.call("project_new", discard_changes=True, preset_changes="discard") + client.call("view_set", tab="prepare") # ---- A project with no objects ---- - code_c, text_c = command("save_project_as", path=path("cmd.gcode.3mf")) - code_t, text_t = answer("save_project", path=path("tool.gcode.3mf")) - check("the command refuses a .gcode.3mf name", code_c == "sliced_file_name", (code_c, text_c)) - check("the tool refuses a .gcode.3mf name", code_t == "sliced_file_name", (code_t, text_t)) - check("the tool's refusal is the command's, with its hint after it", - code_c == code_t == "sliced_file_name" and text_t.startswith(text_c) and "sliced_3mf" in text_t, (text_c, text_t)) - check("neither wrote a file", not os.path.exists(path("cmd.gcode.3mf")) and not os.path.exists(path("tool.gcode.3mf"))) + code, text = answer("project_save", path=path("project.gcode.3mf")) + check("project_save refuses a .gcode.3mf name", code == "sliced_file_name", (code, text)) + check("with the hint after its refusal", "sliced_3mf" in text, text) + check("and writes no file", not os.path.exists(path("project.gcode.3mf"))) - code_c, text_c = command("export_3mf", path=path("cmd.3mf")) - code_t, text_t = answer("export", format="3mf", path=path("tool.3mf")) - check("the command writes a .3mf of a project with no objects", code_c is None and os.path.exists(path("cmd.3mf")), text_c) - check("the tool writes a .3mf of a project with no objects", code_t is None and os.path.exists(path("tool.3mf")), text_t) - for fmt, name, ext in (("stl", "export_stl", ".stl"), ("sliced_3mf", "export_sliced_file", "_sliced.gcode.3mf")): - code_c, text_c = command(name, path=path("cmd" + ext)) - code_t, text_t = answer("export", format=fmt, path=path("tool" + ext)) - check("the command refuses %s of a project with no objects" % fmt, code_c == "no_objects", (code_c, text_c)) - check("the tool refuses %s of a project with no objects" % fmt, code_t == "no_objects", (code_t, text_t)) - check("in the same words (%s)" % fmt, text_c == text_t, (text_c, text_t)) - check("neither wrote a file (%s)" % fmt, not os.path.exists(path("cmd" + ext)) and not os.path.exists(path("tool" + ext))) + code, text = answer("project_export", format="3mf", path=path("model.3mf")) + check("project_export writes a .3mf of a project with no objects", code is None and os.path.exists(path("model.3mf")), text) + for fmt, ext in (("stl", ".stl"), ("sliced_3mf", ".gcode.3mf")): + code, text = answer("project_export", format=fmt, path=path("model" + ext)) + check("project_export refuses %s of a project with no objects" % fmt, code == "no_objects", (code, text)) + check("and writes no file (%s)" % fmt, not os.path.exists(path("model" + ext))) - code_c, text_c = command("go_to_layer", percent=50) - code_t, text_t = answer("set_view", layer=1) - check("the command refuses a layer of a Preview with none", code_c == "no_layers", (code_c, text_c)) - check("the tool refuses a layer of a Preview with none", code_t == "no_layers", (code_t, text_t)) + code_c, text_c = tile("go_to_layer", percent=50) + code_t, text_t = answer("view_set", layer=1) + check("the Go to layer tile refuses a layer of a Preview with none", code_c == "no_layers", (code_c, text_c)) + check("view_set refuses a layer of a Preview with none", code_t == "no_layers", (code_t, text_t)) check("in the same words (layer)", text_c == text_t, (text_c, text_t)) - client.call("set_view", tab="prepare") + client.call("view_set", tab="prepare") # ---- Two cubes on one spot ---- for _ in range(2): - client.call("select_objects", none=True) - client.call("run_action", id="orca_command:add_primitive_cube:orca", args={"size": [20, 20, 20]}) - client.call("wait", **{"for": "idle"}) + client.call("object_select", none=True) + client.call("object_add_primitive", shape="cube", size=[20, 20, 20]) + client.call("app_wait", **{"for": "idle"}) before = offsets() - client.call("set_view", canvas="assemble") - code, reply = answer("arrange") - state = client.call("get_app_state") - check("the tool arranges from the assemble view", code is None and reply.get("off_plate") == [], reply) + client.call("view_set", canvas="assemble") + # object_arrange with no arguments, Auto-Arrange's, replies with what it left off the plates, as any call of it does. + code, reply = answer("object_arrange") + state = client.call("app_state") + check("object_arrange arranges from the assemble view", code is None and reply.get("off_plate") == [], reply) check("and the arrangement moved a cube", offsets() != before, (before, offsets())) check("and the Prepare view is shown afterwards", state["selection"].get("canvas") == "3d", state["selection"]) - client.call("set_view", canvas="3d") - client.call("select_objects", objects=[0]) - opened = client.call("click", target={"gizmo": "Move"}) - code, reply = answer("arrange") - state = client.call("get_app_state") - check("the tool arranges with the Move gizmo open", opened.get("active") is True and code is None, (opened, reply)) + client.call("view_set", canvas="3d") + client.call("object_select", objects=[0]) + opened = client.call("widget_click", target={"gizmo": "Move"}) + code, reply = answer("object_arrange") + state = client.call("app_state") + check("object_arrange arranges with the Move gizmo open", opened.get("active") is True and code is None, (opened, reply)) check("and the gizmo stays open", state.get("gizmo") is not None, state.get("gizmo")) if state.get("gizmo") is not None: - client.call("click", target={"gizmo": "Move"}) + client.call("widget_click", target={"gizmo": "Move"}) # ---- A mixed-colour filament slot, and a hidden printer ---- - client.call("new_project", discard_changes=True, preset_changes="discard") - client.call("select_preset", type="printer", name=PRINTER, preset_changes="discard") - while len(client.call("get_app_state")["presets"]["filaments"]) < 2: - client.call("run_action", id="orca_command:filament_add:orca") - slot_preset = client.call("get_app_state")["presets"]["filaments"][0] - blocked = client.call("click", target={"label": "Add Mixed Filament"}) + client.call("project_new", discard_changes=True, preset_changes="discard") + client.call("preset_select", type="printer", name=PRINTER, preset_changes="discard") + while len(client.call("app_state")["presets"]["filaments"]) < 2: + client.call("action_run", id="orca_command:filament_add:orca") + slot_preset = client.call("app_state")["presets"]["filaments"][0] + blocked = client.call("widget_click", target={"label": "Add Mixed Filament"}) if blocked.get("status") == "blocked_by_dialog": - client.call("answer_dialog", button="OK") + client.call("dialog_answer", button="OK") client.await_job(blocked) - flags = client.call("get_settings", scope="project", keys=["filament_is_mixed"])["items"][0]["value"].split(",") + flags = client.call("project_get_settings", keys=["filament_is_mixed"])["items"][0]["value"].split(",") check("a mixed filament was added", "1" in flags, flags) if "1" in flags: slot = flags.index("1") + 1 - code_t, text_t = answer("select_preset", type="filament", name=slot_preset, filament_slot=slot) + code_t, text_t = answer("preset_select", type="filament", name=slot_preset, filament_slot=slot) raised = plugin_api(editor="filament", form="begin_update", slot=slot, name=slot_preset, commit=True).get("raised", {}) - check("the tool refuses a mixed-colour slot as one", code_t == "mixed_filament_slot", (code_t, text_t)) + check("preset_select refuses a mixed-colour slot as one", code_t == "mixed_filament_slot", (code_t, text_t)) check("the plugin API refuses it with a ValueError in the same words", raised.get("type") == "ValueError" and raised.get("message") == text_t, (raised, text_t)) - client.call("click", target={"label": "Remove last mixed filament"}) + client.call("widget_click", target={"label": "Remove last mixed filament"}) - listed = client.call("list_presets", type="printer", include_hidden=True, limit=500)["items"] - hidden = [p["name"] for p in listed if p.get("visible") is False and p.get("compatible", True) is not False] + listed = client.call("preset_list", type="printer", include_uninstalled=True, limit=500)["items"] + hidden = [p["name"] for p in listed if p.get("installed") is False and p.get("compatible", True) is not False] # A printer of the same family first: its process and filament suit the one selected. hidden.sort(key=lambda name: not name.startswith("Bambu Lab X1")) check("a printer is still hidden (else restart the app)", bool(hidden), len(listed)) if hidden: got = plugin_api(editor="printer", form="begin_update", name=hidden[0], commit=True) - client.call("wait", **{"for": "idle"}) - selected = client.call("get_app_state")["presets"]["printer"] + client.call("app_wait", **{"for": "idle"}) + selected = client.call("app_state")["presets"]["printer"] check("the plugin API shows a hidden printer and selects it", "raised" not in got and selected == hidden[0], (got, selected)) - client.call("select_preset", type="printer", name=PRINTER, preset_changes="discard") + client.call("preset_select", type="printer", name=PRINTER, preset_changes="discard") - while len(client.call("get_app_state")["presets"]["filaments"]) > 1: - client.call("run_action", id="orca_command:filament_delete:orca") - client.call("new_project", discard_changes=True, preset_changes="discard") + while len(client.call("app_state")["presets"]["filaments"]) > 1: + client.call("action_run", id="orca_command:filament_delete:orca") + client.call("project_new", discard_changes=True, preset_changes="discard") failed = [c for c in checks if not c[1]] for name, ok, detail in checks: diff --git a/tools/mcp/test_orca_mcp_attach.py b/tools/mcp/test_orca_mcp_attach.py index d88749471e..7d9cffdb95 100755 --- a/tools/mcp/test_orca_mcp_attach.py +++ b/tools/mcp/test_orca_mcp_attach.py @@ -228,12 +228,12 @@ def check_call_command(): calls = stub(client, {"result": {"ok": True}}) assert client.call_command("extrude", distance=5) == {"result": {"ok": True}} - assert calls == [("call_tool", 600, {"tool": "extrude", "args": {"distance": 5}})], calls - ok("call_command() calls call_tool and returns the command's whole reply") + assert calls == [("tool_call", 600, {"tool": "extrude", "args": {"distance": 5}})], calls + ok("call_command() calls tool_call and returns the command's whole reply") calls = stub(client, {"status": "running", "job": "j"}, {"result": 7}) assert client.call_command("sweep", sketch=1, path=0) == {"result": 7} - assert calls[1][0] == "wait" and calls[1][2]["job"] == "j", calls + assert calls[1][0] == "app_wait" and calls[1][2]["job"] == "j", calls ok("call_command() follows a running job to its reply") refused = McpError("kernel refused the hole") @@ -252,13 +252,13 @@ def check_call_log(): reply = json.dumps({"jsonrpc": "2.0", "id": 1, "result": {"content": [{"type": "text", "text": "{}"}]}}).encode() with mock.patch.dict(os.environ, {"ORCA_MCP_CALL_LOG": log}): with Listener(200, reply) as port: - OrcaMcp(port, "t").call("get_app_state") + OrcaMcp(port, "t").call("app_state") with open(log, encoding="utf-8") as f: lines = [json.loads(line) for line in f] assert len(lines) == 1, lines - assert lines[0]["tool"] == "get_app_state" and lines[0]["ok"] is True and lines[0]["ms"] >= 0, lines + assert lines[0]["tool"] == "app_state" and lines[0]["ok"] is True and lines[0]["ms"] >= 0, lines with Listener(500, b"boom") as port: - raises(lambda: OrcaMcp(port, "t").call("get_app_state"), "HTTP 500") + raises(lambda: OrcaMcp(port, "t").call("app_state"), "HTTP 500") with open(log, encoding="utf-8") as f: lines = [json.loads(line) for line in f] assert len(lines) == 2 and lines[1]["ok"] is False, lines diff --git a/tools/mcp/test_person_forms.py b/tools/mcp/test_person_forms.py new file mode 100644 index 0000000000..ca1a4368d8 --- /dev/null +++ b/tools/mcp/test_person_forms.py @@ -0,0 +1,348 @@ +#!/usr/bin/env python3 +"""Checks that a call with exactly a tile's arguments asks as a person's pick does, that one with a path does not, and +that a person's pick of a view tile or Deselect All runs in place, as its row did. + + tools/mcp/orca_mcp.py launch + tools/mcp/test_person_forms.py + +project_save with a path writes the file without a picker. project_save {save_as: true} and project_export {format: +gcode} open their file pickers, which a dialog_auto_answer rule cancels: the rule says it answered a picker for each, +the save is an error, and nothing is written where either picker starts (the project's folder, or the folder the app +remembers for its last export). preset_export always opens the Export Preset Bundle dialog (it has no silent form): on a +folder it replies blocked_by_dialog, a cancelled dialog ends the call in an error with nothing written to the folder, +and silent is refused. view_set's tab refusal is the operation's, with its code. + +Picks from the Speed Dial, opened with Space on the 3D view and searched by title as a person types: View: Top turns +the camera, Deselect All on the Preview tab clears the Prepare selection without leaving the tab, and Go to layer takes +its percentage from the second phase. None of them starts a job or shows a notice. + +Auto-Arrange and Select All Objects, on a plate of three cubes: object_arrange {} and action_run of the tile wait and +reply as the command does (the settings in force, what was left off the plates); the journal keeps the call with the +settings in force, and action_run of the tile with the tile's arguments, whose exported replay runs. object_select +{all: true} and action_run of its tile reply with the selection; in the assemble view the call selects there and leaves +the view shown, and with the Measure gizmo open there it is refused as gizmo_open. A pick of either runs in place: +Auto-Arrange puts a cube moved off the plate back on it, and Select All Objects selects the three, in Prepare, which it +shows when picked in the assemble view. A replay cannot expect a failed step, which is why this is a script. Exits 0 +when every check passes. +""" + +import json +import os +import sys +import tempfile +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import orca_mcp # noqa: E402 + +CUBE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "resources", "handy_models", "OrcaCube_v2.drc") +# The prompts of the save and export pickers ("Save file as", "Save G-code file as:"), which have no title until shown. +PICKER = "save" +CANVAS = {"name": "OrcaSceneCanvas"} +# Where the three cubes of the arrange and select checks stand on the bed, and where one goes off it: left of the bed, +# where no plate is. +CUBES_X = (60, 128, 196) +OFF_PLATE = [-150, 128, 10] + + +def last_output_dir(session): + """The folder the app remembers for its last export (app.last_export_path), where the G-code picker starts; None when + it has none. On Windows the app writes a checksum line after the config file's JSON, so only the JSON is read.""" + try: + with open(os.path.join(session["datadir"], "OrcaSlicer.conf"), encoding="utf-8") as f: + text = f.read() + return json.loads(text[:text.rfind("}") + 1]).get("app", {}).get("last_export_path") or None + except (OSError, ValueError, KeyError, TypeError, AttributeError): + return None + + +def main(): + client, session = orca_mcp.session_client() + work = tempfile.mkdtemp(prefix="orca-person-forms-") + checks = [] + + def check(name, ok, detail=""): + checks.append((name, bool(ok), detail)) + + def picker_uses(): + for rule in client.call("app_state").get("auto_answer_rules", []): + if rule.get("match") == PICKER: + return rule.get("uses", 0) + return None + + def written_since(folders, since): + """The files in `folders` written at or after `since`.""" + out = [] + for folder in folders: + for name in os.listdir(folder): + if os.path.getmtime(os.path.join(folder, name)) >= since: + out.append(os.path.join(folder, name)) + return out + + def dial_pick(title): + """Opens the Speed Dial on the shown 3D view and picks the tile titled `title`, as a person's click does.""" + client.call("keyboard_press", keys="space", target=CANVAS) + client.call("widget_set_value", target={"web": "Search actions"}, value=title, submit=False) + return client.call("widget_click", target={"web": f"{title} from Orcaslicer", "kind": "button"}) + + def last_job(): + """The number of the newest job app_state lists; every call of this script is one.""" + return max([int(j["id"][1:]) for j in client.call("app_state").get("jobs", []) if j.get("id", "").startswith("j")] or [0]) + + def settled(): + client.call("app_wait", **{"for": "idle"}) + return client.call("app_state") + + def ran_in_place(name, command, state, since): + # A pick started as a job is listed under its command, beside the input calls that made the pick. + jobs = [j for j in state.get("jobs", []) if int(j["id"][1:]) > since and j.get("tool") == command] + check(f"{name} starts no {command} job", jobs == [], jobs) + notes = [n["text"] for n in state.get("notifications", []) if "Started" in n.get("text", "") + or "Finished" in n.get("text", "")] + check(f"{name} shows no Started or Finished notice", notes == [], notes) + + def outside(): + """The objects object_list lists off every plate.""" + return client.call("object_list").get("outside", []) + + def cube_off_plate(name): + """Moves a cube off the plate, so that the arrangement `name` checks has something to put back.""" + client.call("object_transform", object=2, position=OFF_PLATE) + check(f"before {name}, a cube is off the plate", len(outside()) == 1, outside()) + + def refusal_code(error): + """The code of a refusal, whose details are on the line after its text; None for another error.""" + try: + return json.loads(str(error).rpartition("\n")[2]).get("code") + except (ValueError, AttributeError): + return None + + client.call("app_wait", **{"for": "ready"}) + client.call("project_new", discard_changes=True, preset_changes="discard") + client.call("project_import", paths=[os.path.abspath(CUBE)]) + client.call("object_transform", object=0, size=[20, 20, 20]) + sliced = client.call("plate_slice") + check("the plate slices", sliced.get("status") == "done", sliced.get("status")) + + # ---- A path skips the picker; the project's folder is then where both pickers start ---- + client.call("dialog_auto_answer", rules=[{"match": "restore", "button": "no"}, {"match": PICKER, "button": "cancel"}]) + before = picker_uses() + path = os.path.join(work, "saved.3mf") + client.call("project_save", path=path) + check("project_save with a path writes the file", os.path.isfile(path), os.listdir(work)) + check("with no picker", picker_uses() == before, f"{before} -> {picker_uses()}") + + # ---- The tiles' arguments open the pickers, which the rule cancels ---- + last = last_output_dir(session) + folders = [work] + ([last] if last and os.path.isdir(last) else []) + since = time.time() + try: + saved = client.call("project_save", save_as=True) + check("a cancelled Save Project As is an error", False, saved) + except orca_mcp.McpError as e: + check("a cancelled Save Project As is an error", True, str(e)) + after_save = picker_uses() + check("Save Project As opened its picker", after_save == before + 1, f"{before} -> {after_save}") + client.call("project_export", format="gcode") + after_export = picker_uses() + check("Export G-code opened its picker", after_export == after_save + 1, f"{after_save} -> {after_export}") + check("nothing was written where the pickers start", written_since(folders, since) == [], + {"folders": folders, "written": written_since(folders, since)}) + + # ---- preset_export opens its dialog whatever it is given ---- + client.call("dialog_auto_answer", rules=[]) + folder = os.path.join(work, "bundle") + os.makedirs(folder) + blocked = client.call("preset_export", path=folder) + dialogs = blocked.get("dialogs", []) + check("preset_export on a folder is blocked by its dialog", blocked.get("status") == "blocked_by_dialog", blocked.get("status")) + check("titled Export Preset Bundle", bool(dialogs) and "Export Preset Bundle" in dialogs[-1].get("title", ""), dialogs) + client.call("dialog_answer", dialog={"title": "Export Preset Bundle"}, button="cancel") + try: + ended = client.await_job(blocked) + check("a cancelled Export Preset Bundle is an error", False, ended) + except orca_mcp.McpError as e: + check("a cancelled Export Preset Bundle is an error", True, str(e)) + check("with nothing written to the folder", os.listdir(folder) == [], os.listdir(folder)) + try: + refused = client.call("preset_export", silent=True) + check("preset_export refuses silent", False, refused) + except orca_mcp.McpError as e: + check("preset_export refuses silent", "silent" in str(e), str(e)) + + # ---- view_set's tab refusal is the operation's ---- + try: + client.call("view_set", tab="no_such_page") + check("view_set refuses a tab no page has", False) + except orca_mcp.McpError as e: + check("view_set refuses a tab no page has, in the refusal's words", str(e).startswith('No tab has the id "no_such_page".'), + str(e)) + check("with the refusal's code", "no_such_tab" in json.dumps(e.payload), e.payload) + + # ---- Picks from the Speed Dial run in place ---- + client.call("view_set", tab="prepare", camera="front") + since = last_job() + dial_pick("View: Top") + state = settled() + check("a pick of View: Top turns the camera", state.get("camera", {}).get("elevation", 0) >= 85, state.get("camera")) + ran_in_place("View: Top", "view_set", state, since) + + client.call("object_select", objects=[0]) + client.call("view_set", tab="preview") + since = last_job() + dial_pick("Deselect All") + state = settled() + check("a pick of Deselect All on the Preview tab stays there", state.get("tab") == "preview", state.get("tab")) + ran_in_place("Deselect All", "object_select", state, since) + client.call("view_set", tab="prepare") + check("and the Prepare selection is clear", client.call("app_state").get("selection", {}).get("empty") is True, + client.call("app_state").get("selection")) + + # Go to layer's second phase takes the percentage typed in the search field, and Enter runs it. + client.call("view_set", tab="preview") + since = last_job() + dial_pick("Go to layer (percent)") + client.call("widget_set_value", target={"web": "Search actions"}, value="50", submit=False) + client.call("keyboard_press", keys="Enter", target={"web": "Search actions"}) + state = settled() + stats = client.call("plate_slice_stats", include=["view"]).get("view") or {} + count = stats.get("layer_count", 0) + top = (stats.get("layers") or [0, 0])[1] + check("a pick of Go to layer at 50 shows half of the layers", count > 0 and abs(top - (round((count - 1) / 2) + 1)) <= 1, + {"layers": stats.get("layers"), "layer_count": count}) + ran_in_place("Go to layer", "view_set", state, since) + + # ---- Auto-Arrange and Select All Objects: a call is the command's, with its reply; a pick runs in place ---- + client.call("project_new", discard_changes=True, preset_changes="discard") + client.call("view_set", tab="prepare") + for _ in CUBES_X: + client.call("object_select", none=True) + client.call("object_add_primitive", shape="cube", size=[20, 20, 20]) + for o, x in enumerate(CUBES_X): + client.call("object_transform", object=o, position=[x, 128, 10]) + check("three cubes on the plate", client.call("object_list").get("total") == 3 and outside() == [], outside()) + + client.call("replay_export", clear=True) + cube_off_plate("object_arrange {}") + arranged = client.await_job(client.call("object_arrange")) + check("object_arrange {} replies with the settings in force and what it left off the plates", + "settings" in arranged and arranged.get("off_plate") == [], arranged) + check("and not with ran", "ran" not in arranged, arranged) + check("and puts the cube back on the plate", outside() == [], outside()) + step = (client.call("replay_export", clear=True)["replay"]["steps"] or [{}])[-1] + check("and the journal keeps it with the settings in force", step.get("tool") == "object_arrange" + and "spacing" in step.get("args", {}), step) + + # action_run names the tile it ran in ran, whatever the command replies; the row replied level besides. + cube_off_plate("action_run of Auto-Arrange") + arranged = client.await_job(client.call("action_run", id="orca_command:obj_arrange:orca")) + check("action_run of Auto-Arrange replies with the settings in force and what it left off the plates", + "settings" in arranged and arranged.get("off_plate") == [], arranged) + check("and not with the row's level", "level" not in arranged, arranged) + check("and with ran, the tile's id", arranged.get("ran") == "orca_command:obj_arrange:orca", arranged) + check("and puts the cube back on the plate", outside() == [], outside()) + # action_run takes the tile with its own arguments alone, none here, so the journal keeps those in place of the + # settings the command records, and the step replays. + exported = client.call("replay_export", clear=True)["replay"] + step = (exported["steps"] or [{}])[-1] + check("and the journal keeps the tile's call", step.get("tool") == "action_run" + and step.get("args") == {"id": "orca_command:obj_arrange:orca", "args": {}}, step) + exported["steps"] = [s for s in exported["steps"] if s.get("tool") in ("object_transform", "action_run")] + replayed = client.await_job(client.call("replay_run", replay=exported)) + check("which replays: the cube moved off the plate again and put back", replayed.get("passed") is True and outside() == [], + {"replay": replayed, "outside": outside()}) + + cube_off_plate("a pick of Auto-Arrange") + since = last_job() + dial_pick("Auto-Arrange") + # The pick returns while the arrangement runs. + state = settled() + ran_in_place("Auto-Arrange", "object_arrange", state, since) + check("a pick of Auto-Arrange puts the cube back on the plate", outside() == [], outside()) + + client.call("object_select", none=True) + client.call("replay_export", clear=True) + chosen = client.call("object_select", all=True) + check("object_select {all: true} replies with the selection, the three cubes", chosen.get("objects") == [0, 1, 2], chosen) + check("and not with ran", "ran" not in chosen, chosen) + # The journal keeps the call as it was made, and a replay of that step selects the three from an empty selection. + exported = client.call("replay_export", clear=True)["replay"] + step = (exported["steps"] or [{}])[-1] + check("and the journal keeps the call as it was made", step.get("tool") == "object_select" and step.get("args") == {"all": True}, + step) + client.call("object_select", none=True) + exported["steps"] = [step] + replayed = client.await_job(client.call("replay_run", replay=exported)) + selected = client.call("app_state").get("selection", {}).get("objects") + check("which replays: the replay passes and selects the three cubes from an empty selection", + replayed.get("passed") is True and selected == [0, 1, 2], {"replay": replayed, "selection": selected}) + client.call("object_select", none=True) + chosen = client.call("action_run", id="orca_command:select_all:orca") + check("action_run of Select All Objects replies with the selection, the three cubes", chosen.get("objects") == [0, 1, 2], + chosen) + check("and not with the row's level", "level" not in chosen, chosen) + check("and with ran, the tile's id", chosen.get("ran") == "orca_command:select_all:orca", chosen) + + client.call("view_set", canvas="assemble") + client.call("object_select", none=True) + chosen = client.call("object_select", all=True) + # app_state reads the assemble view's selection only while that view is shown, else Prepare's. + selection = client.call("app_state").get("selection", {}) + check("in the assemble view object_select {all: true} selects the three there", + chosen.get("canvas") == "assemble" and chosen.get("objects") == [0, 1, 2], chosen) + check("and the assemble view stays shown, with the three selected", + selection.get("canvas") == "assemble" and selection.get("objects") == [0, 1, 2], selection) + + # The assemble view has gizmos of its own; Measure keeps its selection, as Place on face does in Prepare. + client.call("view_set", canvas="assemble") + client.call("object_select", objects=[0]) + measure = {"gizmo": "Measure", "canvas": "assemble"} + opened = client.call("widget_click", target=measure) + gizmo = client.call("app_state").get("gizmo") or {} + check("the Measure gizmo opens in the assemble view", gizmo == {"name": "Measure", "canvas": "assemble"}, (opened, gizmo)) + try: + reply = client.call("object_select", all=True) + check("with Measure open in the assemble view, object_select {all: true} is refused", False, reply) + except orca_mcp.McpError as e: + check("with Measure open in the assemble view, object_select {all: true} is refused as gizmo_open", + refusal_code(e) == "gizmo_open", str(e)) + selection = client.call("app_state").get("selection", {}) + check("and the assemble view's selection stays", selection.get("canvas") == "assemble" and selection.get("objects") == [0], + selection) + if (client.call("app_state").get("gizmo") or {}).get("canvas") == "assemble": + client.call("view_set", canvas="assemble") + client.call("widget_click", target=measure) + client.call("view_set", canvas="3d") + + client.call("object_select", none=True) + since = last_job() + dial_pick("Select All Objects") + state = settled() + ran_in_place("Select All Objects", "object_select", state, since) + check("a pick of Select All Objects selects the three cubes", state.get("selection", {}).get("objects") == [0, 1, 2], + state.get("selection")) + + # Where the pick and the call differ: picked while the assemble view is shown, Select All Objects shows Prepare and + # selects there, as its row did, where the call selects in the assemble view. + client.call("object_select", none=True) + client.call("view_set", canvas="assemble") + client.call("object_select", none=True) + since = last_job() + dial_pick("Select All Objects") + state = settled() + ran_in_place("Select All Objects in the assemble view", "object_select", state, since) + check("a pick of Select All Objects in the assemble view shows Prepare and selects the three there", + state.get("selection", {}).get("canvas") == "3d" and state.get("selection", {}).get("objects") == [0, 1, 2], + state.get("selection")) + client.call("view_set", canvas="3d") + + client.call("project_new", discard_changes=True) + failed = [c for c in checks if not c[1]] + for name, ok, detail in checks: + print(("PASS " if ok else "FAIL ") + name + ("" if ok else f": {detail}")) + print(f"{len(checks) - len(failed)}/{len(checks)} checks passed") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/mcp/test_plugin_commands.py b/tools/mcp/test_plugin_commands.py new file mode 100644 index 0000000000..3390671ac4 --- /dev/null +++ b/tools/mcp/test_plugin_commands.py @@ -0,0 +1,335 @@ +"""Checks plugin_list, plugin_install_local, plugin_enable, plugin_reload, plugin_uninstall and plugin_refresh, that a +person's pick of Refresh Plugins runs a refresh of its own, and that the Plugins window shows the rows plugin_list gives. + +It launches OrcaSlicer itself on a fresh data folder, signed in to nothing, and works only on the fixture plugins of +tests/plugins, which it installs itself: mcp_tools_fixture from a copy of its .py file outside the plugins folder, and +then, once uninstalled, side-loaded again; mcp_web_fixture side-loaded, its folder copied into the plugins folder, for +plugin_refresh to find. Nothing is installed from the network, and no plugin that came from the cloud is touched. The +launch is stopped on every path out, and the data folder removed unless it was given. +Run it as python tools/mcp/test_plugin_commands.py [--bin PATH] [--datadir PATH]. +""" +import contextlib +import json +import os +import re +import shutil +import socket +import subprocess +import sys +import tempfile +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from orca_mcp import McpError, OrcaMcp, app_env # noqa: E402 + +TOKEN = "plugin-commands-test-token" +PLUGINS = os.path.join(HERE, "tests", "plugins") +INSTALLED = "MCP Tools Fixture" # mcp_tools_fixture's name, from its manifest +CAPABILITY = "MCP tools fixture call" # one of its capabilities +SIDE_LOADED = "MCP Web Fixture" # mcp_web_fixture's name +REFRESHED = "Plugins refreshed." # the notification a refresh ends with (GUI_App::refresh_plugins()) +RESCAN = "Rescanning plugins..." # the log line of each rescan of the plugins folder +results = [] + + +def check(name, ok, detail=""): + results.append((name, bool(ok))) + print(("PASS " if ok else "FAIL ") + name + ("" if ok else " " + str(detail)[:400]), flush=True) + + +def free_port(): + """A port nothing listens on now, so that this test runs beside the others of a sweep.""" + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def harness(env, *args): + return subprocess.run([sys.executable, os.path.join(HERE, "orca_mcp.py"), *args], env=env, capture_output=True, text=True, + timeout=300) + + +@contextlib.contextmanager +def launched(datadir, binary): + """An instance on `datadir`: its client, or None when it did not start, stopped on every path out of the block. + + A launch writes its session file before it waits for the app, and one that is not ready exits leaving its app + running, so the stop goes by that file whenever it is there. Only this launch writes it: a file an earlier run left + is removed first, so that no other app is ever stopped.""" + port = free_port() + session = os.path.join(datadir, "session.json") + os.makedirs(datadir, exist_ok=True) + env = app_env(dict(os.environ, ORCA_MCP_SESSION=session, ORCA_MCP_TOKEN=TOKEN), datadir) + if os.path.exists(session): + os.remove(session) + try: + started = harness(env, "launch", "--datadir", datadir, "--port", str(port), *binary) + if started.returncode != 0: + print(started.stdout, started.stderr) + yield None + return + orca = OrcaMcp(port=port, token=TOKEN) + orca.call("app_wait", **{"for": "ready"}) + yield orca + finally: + if os.path.exists(session): + harness(env, "stop") + time.sleep(2) + + +def answered(orca, reply): + """`reply`, followed to its end; a permission dialog the call opened is answered Yes, as the person who called it + allows the plugin what it asks.""" + while isinstance(reply, dict) and reply.get("status") == "blocked_by_dialog": + titles = [d.get("title", "") for d in reply.get("dialogs", [])] + print(" answering the dialog the call opened:", titles, flush=True) + orca.call("dialog_answer", button="yes") + reply = orca.call("app_wait", **{"for": "job", "job": reply["job"], "timeout_s": 45}) + return orca.await_job(reply) + + +def call(orca, tool, **args): + return answered(orca, orca.call(tool, **args)) + + +def error_of(e): + """The text of error `e` and its details, from its last line, or {} where that line holds none.""" + text = str(e) + try: + details = json.loads(text.rpartition("\n")[2]) + except ValueError: + details = {} + return text, details if isinstance(details, dict) else {} + + +def refusal(orca, tool, **args): + """The text and details of the error `tool` replies, or None when it runs.""" + try: + call(orca, tool, **args) + except McpError as e: + return error_of(e) + return None + + +def rows(orca): + return orca.call("plugin_list")["plugins"] + + +def row_named(orca, name): + return next((row for row in rows(orca) if row["name"] == name), None) + + +def window_rows(orca): + """The Plugins window's rows: each plugin's key and whether its switch is on, read from its page.""" + code = ("JSON.stringify(Array.from(document.querySelectorAll('.plugin-row')).map(function (r) {" + " var box = r.querySelector('input.plugin-checkbox-input:not(.capability-checkbox-input)');" + " return {key: r.dataset.pluginKey, enabled: !!(box && box.checked)}; }))") + _, tree = orca.call_with_text("widget_list", query="PluginsDialog/index.html") + view = re.search(r"\[(\w+)\] webview", "\n".join(tree)) + if view is None: + return None + reply = orca.call("webview_run_javascript", code=code, target=view.group(1)) + result = reply.get("result") + return json.loads(result) if isinstance(result, str) else result + + +def wait_for(predicate, timeout): + deadline = time.time() + timeout + while time.time() < deadline: + if predicate(): + return True + time.sleep(0.5) + return predicate() + + +def run(orca, datadir, scratch): + before = rows(orca) + check("plugin_list lists the plugins with their fields", isinstance(before, list) and all( + {"key", "name", "version", "installed", "enabled", "status", "source", "capabilities", "error"} <= set(r) for r in before), + before) + check("no fixture plugin is installed yet", all(r["name"] not in (INSTALLED, SIDE_LOADED) for r in before), before) + + # --- plugin_install_local, and again with and without overwrite --- + package = os.path.join(scratch, "mcp_tools_fixture.py") + shutil.copy(os.path.join(PLUGINS, "mcp_tools_fixture", "mcp_tools_fixture.py"), package) + installed = call(orca, "plugin_install_local", path=package) + check("plugin_install_local installs the fixture", installed.get("level") == "success", installed) + row = row_named(orca, INSTALLED) + check("plugin_list finds it, installed", row is not None and row["installed"] and row["source"] == "local", row) + if row is None: + return + key = row["key"] + + again = refusal(orca, "plugin_install_local", path=package) + check("installing it again is refused with the question the dialog asks", again is not None and + "is already installed" in again[0] and again[1].get("code") == "plugin_installed", again) + replaced = orca.call("plugin_install_local", path=package, overwrite=True) + check("with overwrite true it is replaced, and nothing asks", replaced.get("status") not in ("blocked_by_dialog", "running") and + replaced.get("level") == "success", replaced) + check("and no dialog is open", orca.call("app_state").get("dialogs", []) == [], orca.call("app_state").get("dialogs")) + + # --- plugin_enable: the plugin and one of its capabilities, each read back --- + on = call(orca, "plugin_enable", plugin=key, enabled=True) + check("plugin_enable turns it on, the call waiting for its load", on.get("plugin", {}).get("enabled") is True and + on["plugin"]["status"] == "Activated", on) + check("plugin_list reads it on, with its capabilities", row_named(orca, INSTALLED)["enabled"] and + CAPABILITY in [c["name"] for c in row_named(orca, INSTALLED)["capabilities"]], row_named(orca, INSTALLED)) + off = call(orca, "plugin_enable", plugin=key, enabled=False) + check("plugin_enable turns it off", off.get("plugin", {}).get("enabled") is False and off.get("changed") is True, off) + check("plugin_list reads it off, with no capabilities", not row_named(orca, INSTALLED)["enabled"] and + row_named(orca, INSTALLED)["capabilities"] == [], row_named(orca, INSTALLED)) + capability_off = refusal(orca, "plugin_enable", plugin=key, capability=CAPABILITY, enabled=False) + check("a capability of a plugin that is off is refused", capability_off is not None and + capability_off[1].get("code") == "plugin_not_enabled", capability_off) + call(orca, "plugin_enable", plugin=INSTALLED, enabled=True) + check("plugin_enable names a plugin by its name too", row_named(orca, INSTALLED)["enabled"], row_named(orca, INSTALLED)) + cap_off = call(orca, "plugin_enable", plugin=key, capability=CAPABILITY, enabled=False) + capability = lambda: next((c for c in row_named(orca, INSTALLED)["capabilities"] if c["name"] == CAPABILITY), {}) + check("plugin_enable turns a capability off", cap_off.get("changed") is True and capability().get("enabled") is False, + (cap_off, capability())) + cap_on = call(orca, "plugin_enable", plugin=key, capability=CAPABILITY, enabled=True) + check("and on again", cap_on.get("changed") is True and capability().get("enabled") is True, (cap_on, capability())) + empty = refusal(orca, "plugin_enable", plugin=key, capability="", enabled=False) + check("an empty capability is refused", empty is not None and empty[1].get("code") == "empty_capability", empty) + check("and the plugin stays on, with the capability", row_named(orca, INSTALLED)["enabled"] is True and + capability().get("enabled") is True, row_named(orca, INSTALLED)) + unknown = refusal(orca, "plugin_enable", plugin=key, capability="No such capability", enabled=True) + check("a capability it lacks is refused, naming its capabilities", unknown is not None and + unknown[1].get("code") == "no_such_capability" and CAPABILITY in unknown[1].get("capabilities", []), unknown) + nobody = refusal(orca, "plugin_enable", plugin="mcp_tools_fixtur", enabled=True) + check("a plugin no key or name names is refused with the closest keys", nobody is not None and + nobody[1].get("code") == "no_such_plugin" and key in nobody[1].get("similar", []), nobody) + + # --- plugin_reload --- + reloaded = call(orca, "plugin_reload", plugin=key) + check("plugin_reload loads it again, and it stays on", reloaded.get("reloaded") == key and reloaded.get("reinstalled") is False and + reloaded.get("plugin", {}).get("enabled") is True, reloaded) + cache = call(orca, "plugin_reload", plugin=key, clear_cache=True) + check("and with clear_cache", cache.get("plugin", {}).get("enabled") is True, cache) + + # --- plugin_uninstall of the plugin while it runs --- + folder = os.path.join(datadir, "orca_plugins") + files = lambda: [os.path.join(r, f) for r, _, fs in os.walk(folder) for f in fs if f == "mcp_tools_fixture.py"] + check("its file is in the plugins folder", files() != [], folder) + # On this machine the removal of a single-file plugin just loaded now and then fails with "The request is not + # supported" from the file system (delete_plugin_root(), which the row's Delete runs too); the error then names how + # the plugin is left, and a second try, as a person's, removes it. Only that failure is tried again, once. + removed, failed = {}, None + try: + removed = call(orca, "plugin_uninstall", plugin=key) + except McpError as e: + failed = error_of(e) + if failed is not None and "Failed to delete plugin folder" in failed[0]: + check("a removal that fails says how the plugin is left", "It is installed" in failed[0] and + failed[1].get("code") == "not_uninstalled" and (failed[1].get("plugin") or {}).get("key") == key, failed) + print(" plugin_uninstall failed to delete the plugin folder once; trying again", flush=True) + time.sleep(2) + try: + removed = call(orca, "plugin_uninstall", plugin=key) + except McpError as e: + check("plugin_uninstall removes it on the second try", False, str(e)) + elif failed is not None: + check("plugin_uninstall fails only with the known folder deletion error", False, failed) + check("plugin_uninstall removes it, which was on", removed.get("uninstalled") == key and removed.get("unsubscribed") is False and + "plugin" not in removed, removed) + check("plugin_list no longer lists it", row_named(orca, INSTALLED) is None, rows(orca)) + check("and its file is gone", files() == [], files()) + gone = refusal(orca, "plugin_uninstall", plugin=key) + check("uninstalling it again is refused: no plugin has that key", gone is not None and gone[1].get("code") == "no_such_plugin", gone) + + # --- Refresh Plugins picked in the Speed Dial as a person picks it (the pick of test_person_forms.py; action_run of + # the tile is an automated call, which waits as plugin_refresh does): it returns at once and its refresh ends with + # its "Plugins refreshed." notification. It goes before the calls below, as the notification manager shows that + # text once for every refresh that ends with it. Each refresh rescans the plugins, which the log says + # (PluginManager::rescan_plugins()). Two refreshes that overlap take turns: the unit case of Ops::RefreshRun shows + # that, which needs two refreshes held at once. + def log_lines(): + return orca.call("app_log", lines=2000).get("lines", []) + + def rescans_since(before): + """The rescans the log has logged past the last line of `before`.""" + after = log_lines() + start = after.index(before[-1]) + 1 if before and before[-1] in after else 0 + return sum(RESCAN in line for line in after[start:]) + + def refreshed_notified(): + return any(n.get("text") == REFRESHED for n in orca.call("app_state").get("notifications", [])) + + check("no refresh has been notified yet", not refreshed_notified(), orca.call("app_state").get("notifications")) + orca.call("view_set", tab="prepare") + logged = log_lines() + orca.call("keyboard_press", keys="space", target={"name": "OrcaSceneCanvas"}) + orca.call("widget_set_value", target={"web": "Search actions"}, value="Refresh Plugins", submit=False) + started = time.monotonic() + picked = orca.call("widget_click", target={"web": "Refresh Plugins from Orcaslicer", "kind": "button"}) + check("a person's pick of Refresh Plugins returns at once", picked.get("status") not in ("running", "blocked_by_dialog") and + time.monotonic() - started < 10, picked) + check("and its refresh ends with its notification", wait_for(refreshed_notified, 60), orca.call("app_state").get("notifications")) + check("which came from a rescan of its own", rescans_since(logged) == 1, rescans_since(logged)) + + # --- plugin_refresh finds a plugin side-loaded into the plugins folder, and replies once it has --- + dest = os.path.join(folder, "mcp_web_fixture") + os.makedirs(dest, exist_ok=True) + shutil.copy(os.path.join(PLUGINS, "mcp_web_fixture", "mcp_web_fixture.py"), dest) + check("plugin_list does not list the side-loaded plugin before a refresh", row_named(orca, SIDE_LOADED) is None, rows(orca)) + first = orca.call("plugin_refresh") + waited = first.get("status") not in ("running", "blocked_by_dialog") + refreshed = orca.await_job(first) + check("plugin_refresh replies with the plugins once the refresh has ended", waited and + SIDE_LOADED in [r["name"] for r in refreshed.get("plugins", [])], first) + check("plugin_list lists it too", row_named(orca, SIDE_LOADED) is not None, rows(orca)) + + # --- a second fixture side-loaded, and plugin_refresh's reply has it --- + second = os.path.join(folder, "mcp_tools_fixture") + os.makedirs(second, exist_ok=True) + shutil.copy(os.path.join(PLUGINS, "mcp_tools_fixture", "mcp_tools_fixture.py"), second) + check("plugin_list does not list the second side-loaded plugin before a refresh", row_named(orca, INSTALLED) is None, rows(orca)) + again = orca.call("plugin_refresh") + waited = again.get("status") not in ("running", "blocked_by_dialog") + refreshed = orca.await_job(again) + check("plugin_refresh replies with the second plugin, from a rescan that began after it was asked", waited and + INSTALLED in [r["name"] for r in refreshed.get("plugins", [])], again) + + # --- The Plugins window shows the rows plugin_list gives --- + listed = {r["key"]: r["enabled"] for r in rows(orca)} + orca.call("window_open", window="plugins") + shown = None + + def read(): + nonlocal shown + try: + shown = window_rows(orca) + except McpError as e: + shown = str(e) + return isinstance(shown, list) and len(shown) == len(listed) + + wait_for(read, 20) + check("the Plugins window lists the same plugins, each switch as plugin_list says", + isinstance(shown, list) and {r["key"]: r["enabled"] for r in shown} == listed, (shown, listed)) + + +def main(): + extra = sys.argv[1:] + binary = ["--bin", extra[extra.index("--bin") + 1]] if "--bin" in extra else [] + given = "--datadir" in extra + root = os.path.abspath(extra[extra.index("--datadir") + 1]) if given else tempfile.mkdtemp(prefix="opc-") + datadir = os.path.join(root, "d") + scratch = os.path.join(root, "files") + os.makedirs(scratch, exist_ok=True) + try: + with launched(datadir, binary) as orca: + check("the app starts", orca is not None) + if orca is not None: + run(orca, datadir, scratch) + finally: + if not given: + shutil.rmtree(root, ignore_errors=True) + + failed = [r for r in results if not r[1]] + print(f"\n{len(results) - len(failed)}/{len(results)} passed") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/mcp/test_plugin_tools.py b/tools/mcp/test_plugin_tools.py index 5ef2f855b3..d43fe9844a 100644 --- a/tools/mcp/test_plugin_tools.py +++ b/tools/mcp/test_plugin_tools.py @@ -4,7 +4,7 @@ Launches OrcaSlicer on a fresh data folder with the Design tab on (in a build wi tests/plugins/mcp_tools_fixture side-loaded, and tests/plugins/mcp_tools_broken, whose load fails after declaring an operation: over MCP, then once without MCP, running a replay with --run, so the plugin's calls go to the runtime started without its endpoint. The first launch also checks that the plugin is sent the NewProject event when -the new_project tool or command starts a project, and ends by unticking the fixture in the Plugins dialog, as a person +project_new or its Speed Dial tile starts a project, and ends by unticking the fixture in the Plugins dialog, as a person unloads it. Run it as python tools/mcp/test_plugin_tools.py [--bin PATH]. """ @@ -93,7 +93,7 @@ def run_plugin_script(orca, plugin_dir, name, capability): out = os.path.join(plugin_dir, f"out_{name}.json") if os.path.exists(out): os.remove(out) - orca.call("run_action", id=f"plugin_script_action:{capability}:{PLUGIN}") + orca.call("action_run", id=f"plugin_script_action:{capability}:{PLUGIN}") deadline = time.time() + 60 while time.time() < deadline: if os.path.exists(out): @@ -125,16 +125,16 @@ def main(): # --- Over MCP: the plugin's operation and its tool calls, beside a plugin whose load fails. --- plugin_dir = install(datadir) install_broken(datadir) - # The Design tab on, so that its commands are among search_tools' commands; a build without CAD has none. + # The Design tab on, so that its commands are among tool_search's commands; a build without CAD has none. orca = launch(env, datadir, ["--cad", *extra]) - described = orca.call_raw("search_tools", {"tool": f"plugin.{PLUGIN}.measure"}) - check("search_tools describes the plugin's operation", not described.get("isError") and + described = orca.call_raw("tool_search", {"tool": f"plugin.{PLUGIN}.measure"}) + check("tool_search describes the plugin's operation", not described.get("isError") and "\"a\"" in described["content"][0]["text"], described) operation = {} if described.get("isError") else json.loads(described["content"][0]["text"]) - check("the operation is in the api group, its description saying a plugin offers it", - operation.get("group") == "api" and operation.get("description", "").startswith("Offered by a plugin."), operation) - called = orca.call_raw("call_tool", {"tool": f"plugin.{PLUGIN}.measure", "args": {"a": 2}}) - check("call_tool runs the plugin's operation", not called.get("isError") and + check("the operation is in the Plugins group, its description saying a plugin offers it", + operation.get("group") == "Plugins" and operation.get("description", "").startswith("Offered by a plugin."), operation) + called = orca.call_raw("tool_call", {"tool": f"plugin.{PLUGIN}.measure", "args": {"a": 2}}) + check("tool_call runs the plugin's operation", not called.get("isError") and json.loads(called["content"][0]["text"]) == {"twice": 4}, called) listed = [t["name"] for t in orca.request("tools/list")["tools"]] check("the operation is not in tools/list", f"plugin.{PLUGIN}.measure" not in listed) @@ -145,80 +145,82 @@ def main(): rule = run_plugin_script(orca, plugin_dir, "rule", CAPABILITIES[2]) check("an auto-answer rule a plugin sets is owned by the plugin", rule == {"ok": True, "result": "plugin"}, rule) exported = run_plugin_script(orca, plugin_dir, "export", CAPABILITIES[3]) - check("a plugin is refused export_replay", exported.get("ok") is False and "agent's session" in exported.get("error", ""), + check("a plugin is refused replay_export", exported.get("ok") is False and "agent's session" in exported.get("error", ""), exported) - # search_tools's one search: a command the tool list does not show (an operation, a Speed Dial command) with + # tool_search's one search: a command the tool list does not show (an operation, a menu row) with # its schema, a listed tool with its summary (its schema is in tools/list), and beside them the other # catalogs' best matches. - found = orca.call("search_tools", query="fixture measure") + found = orca.call("tool_search", query="fixture measure") operation = next((i for i in found["items"] if i["name"] == f"plugin.{PLUGIN}.measure"), {}) - check("search_tools's search finds the plugin's operation with its schema", + check("tool_search's search finds the plugin's operation with its schema", operation.get("listed") is False and "input_schema" in operation, found) - found = orca.call("search_tools", query="slice plate") - tool = next((i for i in found["items"] if i["name"] == "slice"), {}) - check("search_tools's search names a listed tool with its summary", + found = orca.call("tool_search", query="slice plate") + tool = next((i for i in found["items"] if i["name"] == "plate_slice"), {}) + check("tool_search's search names a listed tool with its summary", tool.get("listed") is True and tool.get("summary") and "input_schema" not in tool, found) - found = orca.call("search_tools", query="brim width") - check("search_tools's search finds settings", any(s["key"] == "brim_width" for s in found.get("settings", {}).get("items", [])), + found = orca.call("tool_search", query="brim width") + check("tool_search's search finds settings", any(s["key"] == "brim_width" for s in found.get("settings", {}).get("items", [])), found) - found = orca.call("search_tools", query="arrange") - command = next((i for i in found["items"] if i["name"] == "obj_arrange"), {}) - check("search_tools's search finds a Speed Dial command among the commands, with its schema", + found = orca.call("tool_search", query="developer mode") + command = next((i for i in found["items"] if i["name"] == "settings_toggle_developer_mode"), {}) + check("tool_search's search finds a menu row's command among the commands, with its schema", command.get("listed") is False and "input_schema" in command, found) - check("and not a second time among the actions", - not any("obj_arrange" in a["id"] for a in found.get("actions", {}).get("items", [])), found) - found = orca.call("search_tools", query="fixture") - check("search_tools's search finds the Speed Dial's other actions", + check("and not its tile among the actions", + not any("toggle_developer_mode" in a["id"] for a in found.get("actions", {}).get("items", [])), found) + found = orca.call("tool_search", query="fixture") + check("tool_search's search finds the Speed Dial's other actions", any("fixture" in a.get("title", "").lower() for a in found.get("actions", {}).get("items", [])), found) - described = orca.call_raw("search_tools", {"tool": "view_front"}) - view = {} if described.get("isError") else json.loads(described["content"][0]["text"]) - check("search_tools describes a Speed Dial command", view.get("listed") is False and "input_schema" in view, described) - names = orca.call("search_tools", group="object").get("names", []) - check("search_tools's group is any case, a Speed Dial section among the groups", "obj_arrange" in names, names) - unknown = orca.call_raw("search_tools", {"group": "commandz"}) + described = orca.call_raw("tool_search", {"tool": "script_toggle_panel"}) + row = {} if described.get("isError") else json.loads(described["content"][0]["text"]) + check("tool_search describes a menu row's command", row.get("listed") is False and "input_schema" in row, described) + names = orca.call("tool_search", group="objects").get("names", []) + check("tool_search's group is any case, a place's heading", "object_arrange" in names, names) + unknown = orca.call_raw("tool_search", {"group": "commandz"}) check("a group no command has is refused, naming the groups there are", - unknown.get("isError") and "Object" in unknown["content"][0]["text"], unknown) - ran = orca.call_raw("call_tool", {"tool": "view_front"}) - check("call_tool runs a Speed Dial command", not ran.get("isError"), ran) - found = orca.call("search_tools", query="mesh normals") - check("search_tools's search finds the Python API", found.get("python", {}).get("items", [{}])[0].get("name") == + unknown.get("isError") and "Objects" in unknown["content"][0]["text"], unknown) + # It shows the Run Script panel; the second call hides it again. + ran = orca.call_raw("tool_call", {"tool": "script_toggle_panel"}) + check("tool_call runs a menu row's command", not ran.get("isError"), ran) + orca.call_raw("tool_call", {"tool": "script_toggle_panel"}) + found = orca.call("tool_search", query="mesh normals") + check("tool_search's search finds the Python API", found.get("python", {}).get("items", [{}])[0].get("name") == "orca.host.TriangleMesh.face_normals", found) - found = orca.call("search_tools", query="extrude") - if orca.call("get_app_state").get("design_tab"): + found = orca.call("tool_search", query="extrude") + if orca.call("app_state").get("design_tab"): extrude = next((i for i in found["items"] if i["name"] == "extrude"), {}) - check("search_tools's search finds a Design command among the commands, with its schema", + check("tool_search's search finds a Design command among the commands, with its schema", extrude.get("group") == "Design" and extrude.get("listed") is False and "input_schema" in extrude, found) else: - check("without the Design tab, search_tools's search finds no Design command", + check("without the Design tab, tool_search's search finds no Design command", not any(i.get("group") == "Design" for i in found["items"]), found) check("and in no section of its own", "cad" not in found, found) - found = orca.call("search_tools", query="?") + found = orca.call("tool_search", query="?") check("a query with no words to search for matches nothing", found.get("total") == 0 and "names" not in found, found) - journal = orca.call("export_replay")["replay"]["steps"] - check("a plugin's calls are not in the agent's journal", not any(s["tool"] == "auto_answer_dialogs" for s in journal), + journal = orca.call("replay_export")["replay"]["steps"] + check("a plugin's calls are not in the agent's journal", not any(s["tool"] == "dialog_auto_answer" for s in journal), journal) - broken = orca.call_raw("search_tools", {"tool": f"plugin.{BROKEN}.measure"}) + broken = orca.call_raw("tool_search", {"tool": f"plugin.{BROKEN}.measure"}) check("a plugin whose load failed offers none of its operations", broken.get("isError"), broken) - # A project started by the tool or by the command tells plugins, as File > New Project does. + # A project started by project_new or by its tile tells plugins, as File > New Project does. started = lambda: lines_of(os.path.join(plugin_dir, "new_projects.txt")) before = started() - orca.call("new_project", discard_changes=True) - check("the new_project tool sends plugins the NewProject event", wait_for(lambda: started() == before + 1, 10), started()) - orca.call("run_action", id="orca_command:new_project:orca") - check("and so does the new_project command", wait_for(lambda: started() == before + 2, 10), started()) + orca.call("project_new", discard_changes=True) + check("project_new sends plugins the NewProject event", wait_for(lambda: started() == before + 1, 10), started()) + orca.call("action_run", id="orca_command:new_project:orca") + check("and so does its tile, new_project", wait_for(lambda: started() == before + 2, 10), started()) held = run_plugin_script(orca, plugin_dir, "handle", CAPABILITIES[4]) check("the plugin opens a progress dialog and keeps its handle", held.get("ok") is True, held) - grab = orca.await_job(orca.call("run_script", code=GRAB_HANDLE)) + grab = orca.await_job(orca.call("script_run", code=GRAB_HANDLE)) check("a script that finds a plugin's handle can use its methods", grab.get("result") is True, grab) # --- The plugin unloads, as a person unticks it in the Plugins dialog. --- - rules = lambda: json.dumps(orca.call("get_app_state").get("auto_answer_rules")) + rules = lambda: json.dumps(orca.call("app_state").get("auto_answer_rules")) check("the auto-answer rule the plugin set lasts while it is loaded", RULE in rules(), rules()) - orca.call("run_action", id="orca_command:open_plugins:orca") - untick = orca.call_raw("click", {"target": {"css": f'label.plugin-checkbox:has(input[data-plugin-key="{PLUGIN}"])', + orca.call("action_run", id="orca_command:open_plugins:orca") + untick = orca.call_raw("widget_click", {"target": {"css": f'label.plugin-checkbox:has(input[data-plugin-key="{PLUGIN}"])', "within": "Plugins"}}) check("the Plugins dialog unticks the plugin", not untick.get("isError"), untick) - withdrawn = lambda: orca.call_raw("search_tools", {"tool": f"plugin.{PLUGIN}.measure"}).get("isError") + withdrawn = lambda: orca.call_raw("tool_search", {"tool": f"plugin.{PLUGIN}.measure"}).get("isError") check("an unloaded plugin's operation is withdrawn", wait_for(withdrawn, 15)) check("and the auto-answer rule it set ends with it", wait_for(lambda: RULE not in rules(), 15), rules()) harness(env, "stop") @@ -228,9 +230,9 @@ def main(): install(datadir) # enabled again: unticking it saved it disabled steps = os.path.join(datadir, "plugin_rule.json") with open(steps, "w", encoding="utf-8") as f: - json.dump({"orca_replay_version": "0.1.0", "name": "a plugin's rule without MCP", "steps": [ - {"tool": "run_action", "args": {"id": f"plugin_script_action:{CAPABILITIES[2]}:{PLUGIN}"}}, - {"tool": "wait", "args": {"for": "dialog", "timeout_s": 10}}]}, f) + json.dump({"orca_replay_version": "0.2.0", "name": "a plugin's rule without MCP", "steps": [ + {"tool": "action_run", "args": {"id": f"plugin_script_action:{CAPABILITIES[2]}:{PLUGIN}"}}, + {"tool": "app_wait", "args": {"for": "dialog", "timeout_s": 10}}]}, f) out = os.path.join(plugin_dir, "out_rule.json") if os.path.exists(out): os.remove(out) diff --git a/tools/mcp/test_preferences.py b/tools/mcp/test_preferences.py new file mode 100644 index 0000000000..145c4a49d7 --- /dev/null +++ b/tools/mcp/test_preferences.py @@ -0,0 +1,331 @@ +#!/usr/bin/env python3 +"""Checks preferences_get and preferences_set against the Preferences dialog. + + tools/mcp/orca_mcp.py launch --datadir + tools/mcp/test_preferences.py + +On each of the dialog's tabs (window_open, then widget_list of the dialog), the controls named after a key are the keys +preferences_get lists for that tab. The MCP server's switch and port read as the dialog shows them: on, and the port this +session's launch gave. preferences_set writes a checkbox, a choice and a number in one call, and each reads back from +preferences_get and from its control in the dialog opened again. A preference read at the next start says so in +preferences_get and in the reply. A call with a good key and a refused one (the language) changes nothing, and so does a +value no choice has. The backup period runs the backup timer only while Auto backup is on, read from the timer's log +line. The downloads folder takes a folder this test makes in its own temporary folder, which preferences_get and the +dialog's row then show, and refuses one that does not exist; while the dialog is open a call cannot write it, and its +Browse button, answered with another such folder, shows that folder in the open dialog's row. Hide login side panel, +whose control has an effect in the app (Ops::apply_preference()): the Home page hides its login side panel as soon as +preferences_set writes it, without the dialog, and shows it again when it is written back. Last, preset sync and stealth +mode are written on and off again: with no account signed in, turning sync on starts no sync, and stealth mode signs out +of no account. + +It writes only preferences whose effect stays inside the app it drives; it signs in to nothing and needs no network. +Exits 0 when every check passes. +""" + +import os +import re +import sys +import tempfile +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import orca_mcp # noqa: E402 +from orca_mcp import McpError # noqa: E402 + +TABS = ["general", "files", "behaviour", "control", "graphics", "online", "developer"] +# A widget_list line of a control named after a key: its kind, its label and value, its name and its state. +CONTROL = re.compile(r'^\s*\[w\d+\] (\w+)(?: "(?P