From 0fc5b70cf437556f8f9cf66a0608726d4aafe9af Mon Sep 17 00:00:00 2001 From: SoftFever Date: Thu, 29 Oct 2026 04:14:37 +0800 Subject: [PATCH] Let MCP clients drive every gizmo Also fixes a crash when a script answers the primitive size dialog, the Simplify ratio box being ignored, a Measure crash after a reload, and Mesh Boolean showing a bare "tool" label. --- .claude/skills/orca-mcp/SKILL.md | 39 +- deps_src/imgui/imgui_internal.h | 13 +- deps_src/imgui/imgui_widgets.cpp | 42 +- docs/HLSD/mcp-server.md | 113 ++- src/slic3r/CMakeLists.txt | 2 + src/slic3r/GUI/Gizmos/GLGizmoBase.cpp | 1 + src/slic3r/GUI/Gizmos/GLGizmoBase.hpp | 3 + src/slic3r/GUI/Gizmos/GLGizmoBrimEars.cpp | 1 + src/slic3r/GUI/Gizmos/GLGizmoEmboss.cpp | 57 +- src/slic3r/GUI/Gizmos/GLGizmoEmboss.hpp | 3 +- src/slic3r/GUI/Gizmos/GLGizmoFdmSupports.cpp | 7 +- src/slic3r/GUI/Gizmos/GLGizmoFuzzySkin.cpp | 8 +- src/slic3r/GUI/Gizmos/GLGizmoMeasure.cpp | 13 +- src/slic3r/GUI/Gizmos/GLGizmoMeshBoolean.cpp | 2 +- .../GUI/Gizmos/GLGizmoMmuSegmentation.cpp | 7 +- src/slic3r/GUI/Gizmos/GLGizmoSVG.cpp | 99 +- src/slic3r/GUI/Gizmos/GLGizmoSVG.hpp | 8 + src/slic3r/GUI/Gizmos/GLGizmoSeam.cpp | 7 +- src/slic3r/GUI/Gizmos/GLGizmoSimplify.cpp | 31 +- src/slic3r/GUI/Gizmos/GLGizmoSimplify.hpp | 5 +- .../GUI/Gizmos/GLGizmoTextureDisplacement.cpp | 39 +- .../GUI/Gizmos/GLGizmoTextureDisplacement.hpp | 10 + src/slic3r/GUI/Gizmos/GLGizmosManager.cpp | 36 +- src/slic3r/GUI/Gizmos/GLGizmosManager.hpp | 9 + .../GUI/Gizmos/GizmoObjectManipulation.cpp | 56 +- .../GUI/Gizmos/GizmoObjectManipulation.hpp | 4 +- src/slic3r/GUI/IconManager.cpp | 10 +- src/slic3r/GUI/IconManager.hpp | 7 +- src/slic3r/GUI/ImGuiWrapper.cpp | 177 +++- src/slic3r/GUI/ImGuiWrapper.hpp | 57 +- src/slic3r/GUI/Mcp/CanvasTarget.cpp | 182 ++++ src/slic3r/GUI/Mcp/CanvasTarget.hpp | 71 ++ src/slic3r/GUI/Mcp/McpService.cpp | 44 +- src/slic3r/GUI/Mcp/McpService.hpp | 10 +- src/slic3r/GUI/Mcp/McpToolsApp.cpp | 27 +- src/slic3r/GUI/Mcp/McpToolsScene.cpp | 157 ++- src/slic3r/GUI/Mcp/McpToolsUi.cpp | 161 ++- src/slic3r/GUI/Mcp/McpToolsView.cpp | 47 +- src/slic3r/GUI/Mcp/UiInspector.cpp | 943 +++++++++++++++--- src/slic3r/GUI/Mcp/UiInspector.hpp | 68 +- src/slic3r/GUI/Mcp/UiRefs.cpp | 38 +- src/slic3r/GUI/Mcp/UiRefs.hpp | 12 +- src/slic3r/GUI/NativeCommands.cpp | 26 +- src/slic3r/GUI/PrimitiveSizeDialog.cpp | 4 + tests/slic3rutils/test_imgui_wrapper.cpp | 241 +++++ tests/slic3rutils/test_mcp_ui.cpp | 354 ++++++- tools/mcp/README.md | 15 +- tools/mcp/test_ref_locator_export.py | 91 ++ tools/mcp/tests/fixtures/heightmap.png | Bin 0 -> 84 bytes tools/mcp/tests/fixtures/star.svg | 3 + tools/mcp/tests/gizmos.json | 322 ++++++ 51 files changed, 3300 insertions(+), 382 deletions(-) create mode 100644 src/slic3r/GUI/Mcp/CanvasTarget.cpp create mode 100644 src/slic3r/GUI/Mcp/CanvasTarget.hpp create mode 100755 tools/mcp/test_ref_locator_export.py create mode 100644 tools/mcp/tests/fixtures/heightmap.png create mode 100644 tools/mcp/tests/fixtures/star.svg create mode 100644 tools/mcp/tests/gizmos.json diff --git a/.claude/skills/orca-mcp/SKILL.md b/.claude/skills/orca-mcp/SKILL.md index 6b72b5bd86..4da8350dd9 100644 --- a/.claude/skills/orca-mcp/SKILL.md +++ b/.claude/skills/orca-mcp/SKILL.md @@ -120,8 +120,8 @@ You can talk to the app in two ways: - GUI tools act on a `target`: a ref from the latest `ui_snapshot` (`"w12"`), or a locator such as `{"option": "layer_height"}` (a setting field), `{"label": "Slice plate"}`, `{"label": "Show splash screen", "within": "Preferences"}`, - `{"menu": "File>Export>Export G-code"}`, `{"gltoolbar": "arrange"}`, `{"gizmo": "Move"}` or - `{"imgui": "label"}`. Examples: `ui_snapshot {"query": "Arrange"}` (`"root": "dialog"` for the + `{"menu": "File>Export>Export G-code"}`, `{"gltoolbar": "arrange"}`, `{"gizmo": "Move"}`, + `{"imgui": "label"}` or `{"imgui_name": "name"}`. Examples: `ui_snapshot {"query": "Arrange"}` (`"root": "dialog"` for the topmost modal), `ui_click {"target": "w12"}`, `ui_input {"target": {"option": "layer_height"}, "value": "0.16"}`, `ui_key {"keys": "Ctrl+Z"}` (to the topmost dialog when one is open), `dialog_respond {"button": "ok"}`. A target is scrolled @@ -138,6 +138,41 @@ You can talk to the app in two ways: `/mcp-launch.log`. - Never point `--datadir` at your real OrcaSlicer profile. +## Gizmos + +Every gizmo is driven like a person drives it: its icon, its panel's controls, clicks on the model. +`tools/mcp/tests/gizmos.json` does it for all of them; copy its steps. + +- Select the object (`select`), then `ui_click {"target": {"gizmo": "Seam"}}`. `ui_snapshot` lists + the gizmos of the shown 3D view, `[toolbar]` or `[no toolbar icon]` (Simplify, and SVG on a selected + SVG part). A second click closes the gizmo (`"active": false`); Text on an object with no text + creates a text part and replies `"created": true`. `get_state.gizmo` names the open one. +- `ui_snapshot` lists each ImGui panel with its items and text, in reading order. A control is + found by its label (a field with none takes the text left of it on its row, `{"imgui": "Brush size"}`) + or its name (`{"imgui_name": "Fill"}` for an icon button, `{"imgui_name": "extruder_color_2"}`). + Each item shows its kind and value: `slider`, `drag`, `input`, `multiline`, `combo`, `checkbox`, + `radio`, `toggle`, `button`; `[no typing]` marks a slider that takes no typed value. +- `ui_input` sets a control by its kind and reads the value back: a combo by option text or 0-based + index, a slider + through the number field beside it, multiline text with `\n`, a checkbox, radio or toggle with + true/false. A control below the visible part of a panel is scrolled into view first; a list that + only draws what shows (Texture Displacement's library) scrolls with `ui_mouse` `wheel` over it. +- Click the model at a point instead of a pixel: `ui_mouse {"at": {"object": 0, "spot": "top"}}`, or + `"point": [x, y, z]` in the part's mesh coordinates (`"frame": "world"` for scene coordinates; + add `"volume"` for a part). It fails, naming what is in the way, when the point is hidden, below + the bed or cut away; turn the camera with `set_view`. `"check": "point"` skips that, for a point + that is not on the surface (a cut plane). Strokes: `"action": "drag"` with `"path"` and `"to"` + points. `"modifiers": ["shift"]` holds Shift as a key (Measure's point picking); `"button": + "right"` paints blockers or erases. +- The panel's fields set grabber values (Position, rotation, scale, cut height); grabbers are not + dragged. File pickers inside a gizmo: `gizmo_file` (`svg_change`, `svg_save_as`, + `texture_import`); add an SVG with `run_action add_primitive_svg` and a path. +- The assemble view: `set_view {"view": "assemble"}`, gizmo targets with `"canvas": "assemble"`, + and its Return button (`{"imgui": "Return"}`) or `set_view {"view": "3d"}` to leave. +- Check the result in `list_objects`: per part `painted` (supports, seam, fuzzy_skin, mmu, texture), + `triangles`, `mesh_volume`, `text`, `svg`; per object `brim_ears`. After Simplify or a texture + preview, `wait {"for": "idle"}` first. + ## Script format ```jsonc diff --git a/deps_src/imgui/imgui_internal.h b/deps_src/imgui/imgui_internal.h index 70be29caa0..7f0671379a 100644 --- a/deps_src/imgui/imgui_internal.h +++ b/deps_src/imgui/imgui_internal.h @@ -759,7 +759,8 @@ enum ImGuiItemStatusFlags_ ImGuiItemStatusFlags_Openable = 1 << 20, // ImGuiItemStatusFlags_Opened = 1 << 21, // ImGuiItemStatusFlags_Checkable = 1 << 22, // - ImGuiItemStatusFlags_Checked = 1 << 23 // + ImGuiItemStatusFlags_Checked = 1 << 23, // + ImGuiItemStatusFlags_Inputable = 1 << 24 // [OrcaSlicer, as upstream] Takes typed input (a slider or drag without ImGuiSliderFlags_NoInput, an input field) #endif }; @@ -2666,17 +2667,25 @@ extern void ImGuiTestEngineHook_ItemInfo(ImGuiContext* ctx, ImGuiID id, extern void ImGuiTestEngineHook_IdInfo(ImGuiContext* ctx, ImGuiDataType data_type, ImGuiID id, const void* data_id); extern void ImGuiTestEngineHook_IdInfo(ImGuiContext* ctx, ImGuiDataType data_type, ImGuiID id, const void* data_id, const void* data_id_end); extern void ImGuiTestEngineHook_Log(ImGuiContext* ctx, const char* fmt, ...); +// OrcaSlicer: what a field shows and what kind of widget it is ("slider", "drag", "input", "multiline", "combo"), and the +// text TextEx() draws, for automation; upstream's test engine reads these by other means. +extern void ImGuiTestEngineHook_ItemValue(ImGuiContext* ctx, ImGuiID id, const char* kind, const char* value, ImGuiItemStatusFlags flags); +extern void ImGuiTestEngineHook_Text(ImGuiContext* ctx, const ImRect& bb, const char* text, const char* text_end); +#define IMGUI_TEST_ENGINE_ITEM_VALUE(_ID,_KIND,_VALUE,_FLAGS) if (g.TestEngineHookItems) ImGuiTestEngineHook_ItemValue(&g, _ID, _KIND, _VALUE, _FLAGS) +#define IMGUI_TEST_ENGINE_TEXT(_BB,_TEXT,_TEXT_END) if (g.TestEngineHookItems) ImGuiTestEngineHook_Text(&g, _BB, _TEXT, _TEXT_END) #define IMGUI_TEST_ENGINE_ITEM_ADD(_BB,_ID) if (g.TestEngineHookItems) ImGuiTestEngineHook_ItemAdd(&g, _BB, _ID) // Register item bounding box #define IMGUI_TEST_ENGINE_ITEM_INFO(_ID,_LABEL,_FLAGS) if (g.TestEngineHookItems) ImGuiTestEngineHook_ItemInfo(&g, _ID, _LABEL, _FLAGS) // Register item label and status flags (optional) #define IMGUI_TEST_ENGINE_LOG(_FMT,...) if (g.TestEngineHookItems) ImGuiTestEngineHook_Log(&g, _FMT, __VA_ARGS__) // Custom log entry from user land into test log #define IMGUI_TEST_ENGINE_ID_INFO(_ID,_TYPE,_DATA) if (g.TestEngineHookIdInfo == id) ImGuiTestEngineHook_IdInfo(&g, _TYPE, _ID, (const void*)(_DATA)); -#define IMGUI_TEST_ENGINE_ID_INFO2(_ID,_TYPE,_DATA,_DATA2) if (g.TestEngineHookIdInfo == id) ImGuiTestEngineHook_IdInfo(&g, _TYPE, _ID, (const void*)(_DATA), (const void*)(_DATA2)); +#define IMGUI_TEST_ENGINE_ID_INFO2(_ID,_TYPE,_DATA,_DATA2) if (g.TestEngineHookItems || g.TestEngineHookIdInfo == id) ImGuiTestEngineHook_IdInfo(&g, _TYPE, _ID, (const void*)(_DATA), (const void*)(_DATA2)); #else #define IMGUI_TEST_ENGINE_ITEM_ADD(_BB,_ID) do { } while (0) #define IMGUI_TEST_ENGINE_ITEM_INFO(_ID,_LABEL,_FLAGS) do { } while (0) #define IMGUI_TEST_ENGINE_LOG(_FMT,...) do { } while (0) #define IMGUI_TEST_ENGINE_ID_INFO(_ID,_TYPE,_DATA) do { } while (0) #define IMGUI_TEST_ENGINE_ID_INFO2(_ID,_TYPE,_DATA,_DATA2) do { } while (0) +#define IMGUI_TEST_ENGINE_ITEM_VALUE(_ID,_KIND,_VALUE,_FLAGS) do { } while (0) +#define IMGUI_TEST_ENGINE_TEXT(_BB,_TEXT,_TEXT_END) do { } while (0) #endif //----------------------------------------------------------------------------- diff --git a/deps_src/imgui/imgui_widgets.cpp b/deps_src/imgui/imgui_widgets.cpp index 38b3f1c5ba..6142b03edd 100644 --- a/deps_src/imgui/imgui_widgets.cpp +++ b/deps_src/imgui/imgui_widgets.cpp @@ -234,6 +234,7 @@ void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags) ImRect bb(text_pos, text_pos + text_size); ItemSize(text_size, 0.0f); + IMGUI_TEST_ENGINE_TEXT(bb, text_begin, text_end); ItemAdd(bb, 0); } else @@ -243,6 +244,7 @@ void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags) ImRect bb(text_pos, text_pos + text_size); ItemSize(text_size, 0.0f); + IMGUI_TEST_ENGINE_TEXT(bb, text_begin, text_end); if (!ItemAdd(bb, 0)) return; @@ -837,6 +839,10 @@ bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg, ImGuiBut bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); +#ifdef IMGUI_ENABLE_TEST_ENGINE + ImGuiContext& g = *GImGui; + IMGUI_TEST_ENGINE_ITEM_INFO(id, str_id, window->DC.LastItemStatusFlags); +#endif return pressed; } @@ -1329,6 +1335,7 @@ bool ImGui::ImageTextButton(const ImVec2& button_size, const char* text, ImTextu bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held); + IMGUI_TEST_ENGINE_ITEM_INFO(id, text, window->DC.LastItemStatusFlags); // Render const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); @@ -1556,7 +1563,8 @@ bool ImGui::RadioButton(const char* label, bool active) if (label_size.x > 0.0f) RenderText(label_pos, label); - IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags); + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags | ImGuiItemStatusFlags_Checkable | (active ? ImGuiItemStatusFlags_Checked : 0)); + IMGUI_TEST_ENGINE_ITEM_VALUE(id, "radio", "", 0); return pressed; } @@ -1603,7 +1611,8 @@ bool ImGui::BBLRadioButton(const char *label, bool active) if (g.LogEnabled) LogRenderedText(&label_pos, active ? "(x)" : "( )"); if (label_size.x > 0.0f) RenderText(label_pos, label); - IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags); + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags | ImGuiItemStatusFlags_Checkable | (active ? ImGuiItemStatusFlags_Checked : 0)); + IMGUI_TEST_ENGINE_ITEM_VALUE(id, "radio", "", 0); return pressed; } @@ -2052,6 +2061,8 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF popup_open = true; } + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags | ImGuiItemStatusFlags_Openable | (popup_open ? ImGuiItemStatusFlags_Opened : 0)); + IMGUI_TEST_ENGINE_ITEM_VALUE(id, "combo", preview_value, 0); if (!popup_open) return false; @@ -2168,6 +2179,8 @@ bool ImGui::BBLBeginCombo(const char *label, const char *preview_value, ImGuiCom popup_open = true; } if (push_color_count > 0) { ImGui::PopStyleColor(push_color_count); } + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags | ImGuiItemStatusFlags_Openable | (popup_open ? ImGuiItemStatusFlags_Opened : 0)); + IMGUI_TEST_ENGINE_ITEM_VALUE(id, "combo", preview_value, 0); if (!popup_open) return false; if (has_window_size_constraint) { @@ -2933,7 +2946,8 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); - IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags); + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags | (temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0)); + IMGUI_TEST_ENGINE_ITEM_VALUE(id, "drag", value_buf, temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0); return value_changed; } @@ -3019,7 +3033,8 @@ bool ImGui::BBLDragScalar(const char *label, ImGuiDataType data_type, void *p_da if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); if (push_color_count) { ImGui::PopStyleColor(1); } - IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags); + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags | (temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0)); + IMGUI_TEST_ENGINE_ITEM_VALUE(id, "drag", value_buf, temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0); return value_changed; } @@ -3643,7 +3658,8 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); - IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags); + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags | (temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0)); + IMGUI_TEST_ENGINE_ITEM_VALUE(id, "slider", value_buf, temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0); return value_changed; } @@ -3719,7 +3735,8 @@ bool ImGui::BBLSliderScalarIn(const char *label, ImGuiDataType data_type, void * float value_size = CalcTextSize(value_buf).x; RenderTextClipped(ImVec2(frame_bb.Min.x + end_x,frame_bb.Min.y),ImVec2(frame_bb.Max.x + value_size,frame_bb.Max.y), value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.5f)); - IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags); + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags | (temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0)); + IMGUI_TEST_ENGINE_ITEM_VALUE(id, "slider", value_buf, temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0); return value_changed; } @@ -3833,7 +3850,15 @@ bool ImGui::BBLSliderScalar(const char *label, ImGuiDataType data_type, void *p_ if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); - IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags); + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags | (temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0)); +#ifdef IMGUI_ENABLE_TEST_ENGINE + if (g.TestEngineHookItems) + { + char value_buf[64]; + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, p_data, format); + IMGUI_TEST_ENGINE_ITEM_VALUE(id, "slider", value_buf, temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0); + } +#endif return value_changed; } @@ -5564,7 +5589,8 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (value_changed && !(flags & ImGuiInputTextFlags_NoMarkEdited)) MarkItemEdited(id); - IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags); + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags | (is_readonly ? 0 : ImGuiItemStatusFlags_Inputable)); + IMGUI_TEST_ENGINE_ITEM_VALUE(id, is_multiline ? "multiline" : "input", is_password ? "" : buf, is_readonly ? 0 : ImGuiItemStatusFlags_Inputable); if ((flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0) return enter_pressed; else diff --git a/docs/HLSD/mcp-server.md b/docs/HLSD/mcp-server.md index a3816a5942..687faf4664 100644 --- a/docs/HLSD/mcp-server.md +++ b/docs/HLSD/mcp-server.md @@ -263,7 +263,10 @@ decision logic is in `McpOperations`, which uses neither wx nor `Plater`. **Idle.** `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. It also needs no job running other than the caller and its ancestors, +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 +(Simplify's calculation until `worker_finished()` has run, Texture Displacement's adjustment +preview). It also needs no job running other than the caller and its ancestors, so a script waiting for idle doesn't wait on itself. Only the job registry, the `ModalTracker` snapshot and the journal are shared between threads, each behind a mutex. All app state is read on the UI thread. @@ -272,7 +275,7 @@ the UI thread. | Group | Tool | Purpose | |---|---|---| -| App | `get_state` | version, platform and display backend, ready, tab, mode, project, presets, plates, objects, slicing, dialogs, notifications, jobs, window | +| App | `get_state` | version, platform and display backend, ready, tab, mode, project, presets, plates, objects, slicing, the open gizmo, dialogs, notifications, jobs, window | | | `wait` | `ready`, `idle`, `dialog`, `no_dialog` or a `job`; `timeout_s` up to 50 | | | `get_log` | end of the current log file, filtered by minimum level | | Speed Dial | `list_actions` | search the action catalog, paged | @@ -285,18 +288,19 @@ the UI thread. | | `select_preset` | select by name through the selector (filament per slot) | | | `get_settings` | values and metadata of a preset, or of an object's or part's overrides | | | `set_settings` | set values the way the settings tab does, all or none; object and part overrides | -| Objects | `list_objects` | objects, instances, parts, bounding boxes, overrides, paged | +| Objects | `list_objects` | objects, instances (with their canvas rectangles on request), parts (triangles, mesh volume, painted facets, text and SVG sources), bounding boxes, brim ears, overrides, paged | | | `select` | select objects, instances or parts, all, or none | | | `transform` | translate, rotate or scale one instance, relative or absolute | | Slice | `slice` | current, one or all plates, then the Preview tab as after the Slice button; outcome and stats for each plate | | | `cancel` | stop the running slice or G-code export, or a pending automatic reslice (optionally only a given job); allowed during an operation | -| View | `set_view` | tab, camera, preview layers and color scheme, window size | +| View | `set_view` | tab, 3D view (Prepare, preview, assemble), camera, preview layers and color scheme, window size | | | `screenshot` | window, 3D canvas, topmost dialog or one widget: a downscaled image and a full-size PNG | | GUI | `ui_snapshot` | widgets, menus, GL toolbar items, gizmos and ImGui items, with refs | | | `ui_click` | activate a ref or locator | | | `ui_input` | set a control's text, value, selection or checked state | | | `ui_key` | send a key chord to a target or the focused window | -| | `ui_mouse` | canvas gestures: move, down, up, click, drag, wheel | +| | `ui_mouse` | canvas gestures: move, down, up, click, drag, wheel, at pixels or at points of the model | +| | `gizmo_file` | what the open gizmo's file pickers do, with a path: SVG change file and save as, texture import | | | `dialog_respond` | press a button of the topmost wx dialog | | | `dialog_auto_answer` | answer matching modals before they show, and one already open | | | `webview_eval` | run JavaScript in a web view and return the result | @@ -348,6 +352,7 @@ turns a bad path into an Error result. | `export_stl` | output `.stl` | `Plater::export_stl(..., path)` | | `export_3mf` | output `.3mf` | `Plater::export_core_3mf(path)` | | `export_stl_multi` | existing directory | `Plater::export_stl(..., multiple, dir)` | +| `add_primitive_svg` | `.svg` | `GLGizmoSVG::create_volume(path, type)`: a new object, or a part of the selected one; a job | Commands that still open a dialog, such as `export_config` or `plate_rename`, return `blocked_by_dialog`, and the agent answers the dialog. @@ -396,7 +401,7 @@ journal stores. A locator is one of: - `{label, class, name, within, index}` for other widgets; - `{tab: "General", within}` for a notebook page; - `{menu: "File>Export>Export G-code"}`, `{gltoolbar: "arrange"}` or `{gizmo: "Move"}`; -- `{imgui: "label", window, canvas, index}` for an ImGui item. +- `{imgui: "label", imgui_name: "name", window, canvas, index}` for an ImGui item, by either or both. The object list's rows are items of a `wxDataViewCtrl`, not windows, so no locator names one. `select` selects objects, instances and parts, after which `run_action` runs the object operations @@ -413,20 +418,100 @@ window's adjustment, as the mouse wheel does, because `wxScrollHelper::Scroll()` labels unpainted. Activation prefers a widget's own dispatch: `wxEVT_MENU`, `GLToolbar::force_left_action()` (or -`force_right_action()` for a right click), `GLGizmosManager::open_gizmo()`, a notebook's +`force_right_action()` for a right click), `GLGizmosManager::click_toolbar_icon()`, a notebook's `SetSelection()`, a native control's semantic event, or a custom widget's public API. Canvas gestures and ImGui items get synthesized wx events with a render between steps. -`ImGuiWrapper::set_item_recording()` supplies the ImGui items with their rectangles and checked -state; `ui_input` on an ImGui checkbox clicks it only when its state differs. `SyntheticInput` holds +`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 `ui_key` 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 `ui_mouse` `down` keeps its button held, and a -`move` drags with it, until an `up`, another gesture or the service's stop. Keys without a target go to the +`move` drags with it, until an `up`, another gesture (one that fails included; a request the server +rejects for its arguments never runs and changes nothing), the end of the script that pressed it, +the closing of the endpoint for a client's press, or the service's stop. A client's gesture that +reaches the UI thread after its endpoint closed is refused. Keys without a target go to the focused window inside the topmost modal, else that modal, else the focused window, else the 3D canvas. +### ImGui items and gizmos + +The 3D canvases draw their panels with ImGui, which has no widgets to walk. ImGui's test-engine +hooks (`IMGUI_ENABLE_TEST_ENGINE`) report every item a frame adds while +`ImGuiContext::TestEngineHookItems` is set, which `ImGuiWrapper` does only while the service runs; +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, and whether the item lies outside the +visible part of its window. The hooks reach the recorder through `ImGuiContext::TestEngine`, so they +work without the app. Orca's copy of ImGui adds two hooks upstream lacks: `ItemValue`, through which +sliders, drags, inputs, combos and radio buttons report their kind, the value they show and whether +they take typed input (`ImGuiItemStatusFlags_Inputable`, upstream's flag), and `Text`, through which +`TextEx` reports text, kept apart from the items. A clipped widget returns before it reports its +label, so the string its id was hashed from (`GetID()`'s hook) stands in for it. + +Some controls have no label, or no item at all: icon buttons drawn as a `Dummy` or an `Image` with a +hand-made click test (the painters' tools, the Text and SVG icons), links that are bold text with a +hover test, image buttons, combos with an empty label, options drawn as an empty `Selectable` and +text. Their code calls `ImGuiWrapper::record_named_item()` with an English name right after drawing +them: a real item is named in its own record, so its value stays on it; anything else gets a record +of its own at its rectangle, with the id the name hashes to in the current ID scope, so repeated +rows under `PushID` stay apart. Same-named ones in one scope can only be told apart by their order, +so their ids follow it: a target taken among them is not found once their number changes, and after +a reorder it names the control now in its place. Call sites give each control a name of its own +(Text's "Revert Depth", Texture's "Remove "). A synthesized click at the rectangle goes +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. + +`ui_snapshot` 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. +The locator is the label when no other item in the window shares it, else the name, else both; +text is never matched. A ref follows its item by id, or by name when the label shows a value that +changes (Text's font button); it takes the item's current name (a layer row renamed by its place), +and the locator recorded for a call is the one that finds the item then. Before acting on a clipped item, the inspector scrolls its window, and the +windows it is a child of, to bring it into view (`SetScrollFromPosY()`, then two frames). A list that +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. + +`ui_input` 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 +typing is Ctrl+clicked first; a slider set through the number field beside it when it has one, as +Orca pairs them; a combo is opened and its option, by its text or its 0-based place, clicked in +its popup. + +A gizmo is listed per canvas as its toolbar shows it (`GLGizmosManager::is_on_toolbar()`), and +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 `ui_click` waits for. `get_state.gizmo` names the open gizmo and its canvas. The +assemble view is entered and left with `set_view view` (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` 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 `gizmo_file`, whose +actions are the bodies of those pickers (`GLGizmoSVG::change_file()`, `save_svg_as()`, +`GLGizmoTextureDisplacement::import_texture()`). + +`ui_mouse` takes points of the model (`CanvasTarget`): `{object, instance, volume}` with `point` in +the part's mesh coordinates (`frame: "volume"`, mapped by `GLVolume::world_matrix()`, which follows +the assemble view's offset and explosion) or in the scene's (`"world"`), or `spot`, where a ray along +an axis through the part's displayed bounding box first meets it. A point is projected through the +camera the canvas was drawn with and converted to logical pixels. With `check: "surface"` (the +default) the point must lie on the part, above the bed and on the side the clipping plane keeps; +the ray through the whole pixel the click goes to must meet nothing before it (active parts, the +parts of the instance the open gizmo works on, which it draws itself while their scene entries are +inactive, and the plates), and must then meet the part near the point. A part the view does not +draw (`GLVolume::visible`, false for objects the assemble view left out) is neither a target nor in +the way. Other inactive parts are hidden by the gizmo and modifiers are see-through, so neither counts. +`check: "point"` only projects, for points off the surface such as a cut plane. Every point of a +gesture is resolved before its first event, and the journal keeps the model points, so a script +replays at another window size or camera. A gesture's modifiers are pressed as a keyboard does: a +key-down event each before it and a key-up after, which is what switches Measure and Assembly to +point picking and the painters to their Shift and Alt modes. + +### Dialogs and web views + `ModalTracker`, a `wxModalDialogHook`, sees every `ShowModal()`, native dialogs included, and publishes the snapshot `[{title, message, class, native, buttons}]`. Message boxes and file and folder pickers are native; a picker's message is its prompt, such as "Choose Download Directory", since its @@ -604,10 +689,14 @@ who owns the discovery file and when a port counts as held by another window; `t `UiInvoker`, `McpCore` and `JobRegistry` on a hand-stepped dispatcher (guards, abandoned calls, jobs, blocked_by_dialog, admission, slots, idle, journal); `test_mcp_operations` the slice and export outcomes; `test_mcp_script` parsing, substitution, matchers and await; `test_mcp_ui` labels, -snapshot text, ref liveness and synthetic key state; `test_mcp_tools` setting serialization. End to end, `tools/mcp/orca_mcp.py` launches +snapshot text, ref liveness, synthetic key state, how ImGui items are labelled and named, value +matching and the model-target projection and surface check (`CanvasTarget`); `test_imgui_wrapper` the +ImGui recorder (named items, kinds, values, text, clipping) on frames drawn without OpenGL; +`test_mcp_tools` setting serialization. End to end, `tools/mcp/orca_mcp.py` launches the app on a private Xvfb display on Linux (with `-noreset`, and the pointer parked in a corner so no tooltip lands in a screenshot), or on the desktop on macOS and Windows, and runs `tools/mcp/smoke_test.json`. `tools/mcp/tests/script_basic.json` -checks `--mcp-script` headless, `tools/mcp/test_stdio_bridge.py` the stdio bridge, and +checks `--mcp-script` headless, `tools/mcp/tests/gizmos.json` every gizmo through the GUI tools, +`tools/mcp/test_stdio_bridge.py` the stdio bridge, and `tools/mcp/test_recovery_under_load.py` answering a dialog while stalled clients hold every connection. See `tools/mcp/README.md` and the `orca-mcp` skill. diff --git a/src/slic3r/CMakeLists.txt b/src/slic3r/CMakeLists.txt index bd07a3c1cb..215a9c0ac8 100644 --- a/src/slic3r/CMakeLists.txt +++ b/src/slic3r/CMakeLists.txt @@ -138,6 +138,8 @@ set(SLIC3R_GUI_SOURCES GUI/NativeCommands.hpp GUI/SyntheticInput.cpp GUI/SyntheticInput.hpp + GUI/Mcp/CanvasTarget.cpp + GUI/Mcp/CanvasTarget.hpp GUI/Mcp/JobRegistry.cpp GUI/Mcp/JobRegistry.hpp GUI/Mcp/McpCore.cpp diff --git a/src/slic3r/GUI/Gizmos/GLGizmoBase.cpp b/src/slic3r/GUI/Gizmos/GLGizmoBase.cpp index ac158fcf00..d685e60011 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoBase.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoBase.cpp @@ -238,6 +238,7 @@ bool GLGizmoBase::render_combo(const std::string &label, const std::vectorrecord_named_item(lines[line_idx], "option"); ImGui::SameLine(); ImGui::Text("%s", lines[line_idx].c_str()); diff --git a/src/slic3r/GUI/Gizmos/GLGizmoBase.hpp b/src/slic3r/GUI/Gizmos/GLGizmoBase.hpp index c19b5e4c05..31b14c53fc 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoBase.hpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoBase.hpp @@ -234,6 +234,9 @@ public: virtual bool is_in_editing_mode() const { return false; } virtual bool is_selection_rectangle_dragging() const { return false; } + // Whether work the gizmo started in the background has yet to show its latest result, for + // automation waiting for the app to settle. + virtual bool is_busy() const { return false; } protected: float last_input_window_width = 0; diff --git a/src/slic3r/GUI/Gizmos/GLGizmoBrimEars.cpp b/src/slic3r/GUI/Gizmos/GLGizmoBrimEars.cpp index 34f49dfc53..0501e12ff9 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoBrimEars.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoBrimEars.cpp @@ -802,6 +802,7 @@ void GLGizmoBrimEars::on_render_input_window(float x, float y, float bottom_limi ImVec2 min = ImGui::GetItemRectMin(); ImVec2 max = ImGui::GetItemRectMax(); ImGui::GetWindowDrawList()->AddLine(ImVec2(min.x, max.y - 2.0f), ImVec2(max.x, max.y - 2.0f), HyperColor); + m_imgui->record_named_item("Set brim type to painted", "button", min, max); if (ImGui::IsMouseHoveringRect(min, max)) { m_link_text_hover = true; diff --git a/src/slic3r/GUI/Gizmos/GLGizmoEmboss.cpp b/src/slic3r/GUI/Gizmos/GLGizmoEmboss.cpp index f4c049c935..12a53242db 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoEmboss.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoEmboss.cpp @@ -226,6 +226,7 @@ enum class IconState : unsigned { activable = 0, hovered /*1*/, disabled /*2*/ } const IconManager::Icon &get_icon(const IconManager::VIcons& icons, IconType type, IconState state); // short call of Slic3r::GUI::button bool draw_button(const IconManager::VIcons& icons, IconType type, bool disable = false); +std::string icon_button_name(IconType type); struct FaceName { @@ -392,20 +393,19 @@ bool GLGizmoEmboss::create_volume(ModelVolumeType volume_type) } -void GLGizmoEmboss::on_shortcut_key() { +bool GLGizmoEmboss::on_shortcut_key() { set_volume_by_selection(); if (m_volume == nullptr) { // No volume to select from selection so create volume. // NOTE: After finish job for creation emboss Text volume, // GLGizmoEmboss will be opened - create_volume(ModelVolumeType::MODEL_PART); - } - else { - // shortcut is pressed when text is selected soo start edit it. - auto& mng = m_parent.get_gizmos_manager(); - if (mng.get_current_type() != GLGizmosManager::Emboss) - mng.open_gizmo(GLGizmosManager::Emboss); + return create_volume(ModelVolumeType::MODEL_PART); } + // shortcut is pressed when text is selected soo start edit it. + auto& mng = m_parent.get_gizmos_manager(); + if (mng.get_current_type() != GLGizmosManager::Emboss) + mng.open_gizmo(GLGizmosManager::Emboss); + return false; } bool GLGizmoEmboss::re_emboss(const ModelVolume &text_volume, std::shared_ptr> job_cancel) @@ -1864,7 +1864,7 @@ void GLGizmoEmboss::draw_font_list_line() } ImGui::SameLine(); - if (Slic3r::GUI::button(r_icon, r_icon, r_icon)) { // ORCA draw bottom with same orange color + if (Slic3r::GUI::button(r_icon, r_icon, r_icon, false, "Revert font")) { // ORCA draw bottom with same orange color const EmbossStyle *stored_style = m_style_manager.get_stored_style(); style.path = stored_style->path; @@ -2488,7 +2488,7 @@ bool GLGizmoEmboss::draw_italic_button() if (is_font_italic) { // unset italic if (clickable(get_icon(m_icons, IconType::italic, IconState::hovered), - get_icon(m_icons, IconType::unitalic, IconState::hovered))) { + get_icon(m_icons, IconType::unitalic, IconState::hovered), icon_button_name(IconType::italic))) { skew.reset(); if (wx_font.GetStyle() != wxFontStyle::wxFONTSTYLE_NORMAL) { wxFont new_wx_font = wx_font; // copy @@ -2534,7 +2534,7 @@ bool GLGizmoEmboss::draw_bold_button() { if (is_font_bold) { // unset bold if (clickable(get_icon(m_icons, IconType::bold, IconState::hovered), - get_icon(m_icons, IconType::unbold, IconState::hovered))) { + get_icon(m_icons, IconType::unbold, IconState::hovered), icon_button_name(IconType::bold))) { boldness.reset(); if (wx_font.GetWeight() != wxFontWeight::wxFONTWEIGHT_NORMAL) { wxFont new_wx_font = wx_font; // copy @@ -2610,7 +2610,7 @@ bool GLGizmoEmboss::revertible(const std::string &name, ImGuiWindow *window = ImGui::GetCurrentWindow(); float prev_x = window->DC.CursorPosPrevLine.x; ImGui::SameLine(undo_offset); // change cursor postion - if (Slic3r::GUI::button(r_icon, r_icon, r_icon)) { // ORCA draw bottom with same orange color + if (Slic3r::GUI::button(r_icon, r_icon, r_icon, false, icon_button_name(IconType::undo) + " " + name)) { // ORCA draw bottom with same orange color value = *default_value; // !! Fix to detect change of value after revert of float-slider @@ -3128,7 +3128,7 @@ void GLGizmoEmboss::draw_advanced() const IconManager::Icon &icon = get_icon(m_icons, m_keep_up ? IconType::lock : IconType::unlock, IconState::activable); const IconManager::Icon &icon_hover = get_icon(m_icons, m_keep_up ? IconType::lock_bold : IconType::unlock_bold, IconState::activable); const IconManager::Icon &icon_disable = get_icon(m_icons, m_keep_up ? IconType::lock : IconType::unlock, IconState::disabled); - if (button(icon, icon_hover, icon_disable)) + if (button(icon, icon_hover, icon_disable, false, icon_button_name(IconType::lock))) m_keep_up = !m_keep_up; if (ImGui::IsItemHovered()) @@ -3422,12 +3422,41 @@ namespace { const IconManager::Icon &get_icon(const IconManager::VIcons& icons, IconType type, IconState state) { return *icons[(unsigned) type][(unsigned) state]; } +// English names of the icon buttons, for automation. +std::string icon_button_name(IconType type) +{ + switch (type) { + case IconType::rename: return "Rename style"; + case IconType::erase: return "Remove style"; + case IconType::add: return "Add style"; + case IconType::save: return "Save style"; + case IconType::undo: return "Revert"; + case IconType::italic: + case IconType::unitalic: return "Italic"; + case IconType::bold: + case IconType::unbold: return "Bold"; + case IconType::system_selector: return "Font selector"; + case IconType::open_file: return "Open font file"; + case IconType::lock: + case IconType::lock_bold: + case IconType::unlock: + case IconType::unlock_bold: return "Keep up"; + case IconType::align_horizontal_left: return "Align left"; + case IconType::align_horizontal_center: return "Align center"; + case IconType::align_horizontal_right: return "Align right"; + case IconType::align_vertical_top: return "Align top"; + case IconType::align_vertical_center: return "Align middle"; + case IconType::align_vertical_bottom: return "Align bottom"; + default: return {}; + } +} + bool draw_button(const IconManager::VIcons &icons, IconType type, bool disable){ return Slic3r::GUI::button( get_icon(icons, type, IconState::activable), get_icon(icons, type, IconState::hovered), get_icon(icons, type, IconState::disabled), - disable);} + disable, icon_button_name(type));} TextDataBase::TextDataBase(DataBase &&parent, const FontFileWithCache &font_file, diff --git a/src/slic3r/GUI/Gizmos/GLGizmoEmboss.hpp b/src/slic3r/GUI/Gizmos/GLGizmoEmboss.hpp index 0823e613a3..77256f6646 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoEmboss.hpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoEmboss.hpp @@ -57,7 +57,8 @@ public: /// /// Handle pressing of shortcut /// - void on_shortcut_key(); + /// True when it started creating a text part, whose job opens the gizmo when it ends + bool on_shortcut_key(); /// /// Mirroring from object manipulation panel diff --git a/src/slic3r/GUI/Gizmos/GLGizmoFdmSupports.cpp b/src/slic3r/GUI/Gizmos/GLGizmoFdmSupports.cpp index 1b83e16a24..144e60940e 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoFdmSupports.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoFdmSupports.cpp @@ -284,7 +284,8 @@ void GLGizmoFdmSupports::on_render_input_window(float x, float y, float bottom_l else icons = { ImGui::CircleButtonIcon, ImGui::SphereButtonIcon, ImGui::FillButtonIcon, ImGui::GapFillIcon }; - std::array tool_tips = { _L("Circle"), _L("Sphere"), _L("Fill"), _L("Gap Fill") }; + // English, as the tools are named for automation; the tooltips translate them. + std::array tool_names = { L("Circle"), L("Sphere"), L("Fill"), L("Gap Fill") }; for (int i = 0; i < tool_ids.size(); i++) { //std::string str_label = std::string("##"); //std::wstring btn_name = icons[i] + boost::nowide::widen(str_label); @@ -301,7 +302,7 @@ void GLGizmoFdmSupports::on_render_input_window(float x, float y, float bottom_l ImGui::PushStyleColor(ImGuiCol_ButtonActive , is_active ? ImVec4(0.f, .59f, .53f, .30f) : ImVec4(0,0,0,0)); // ORCA ImGui::PushStyleColor(ImGuiCol_Border , is_active ? ImGuiWrapper::COL_ORCA : ImVec4(0,0,0,0)); // ORCA ImGui::PushStyleColor(ImGuiCol_BorderActive , is_active ? ImGuiWrapper::COL_ORCA : ImVec4(0,0,0,0)); // ORCA matched color for fixing flicker on click - bool btn_clicked = m_imgui->glyph_button(icons[i], ImVec2(16.f * scale, 16.f * scale)); // ORCA glyph_button for fixing unequal paddings + bool btn_clicked = m_imgui->glyph_button(icons[i], ImVec2(16.f * scale, 16.f * scale), tool_names[i]); // ORCA glyph_button for fixing unequal paddings ImGui::PopStyleColor(6); ImGui::PopStyleVar(3); @@ -314,7 +315,7 @@ void GLGizmoFdmSupports::on_render_input_window(float x, float y, float bottom_l } if (ImGui::IsItemHovered()) { - m_imgui->tooltip(tool_tips[i], max_tooltip_width); + m_imgui->tooltip(_(tool_names[i]), max_tooltip_width); } } diff --git a/src/slic3r/GUI/Gizmos/GLGizmoFuzzySkin.cpp b/src/slic3r/GUI/Gizmos/GLGizmoFuzzySkin.cpp index b5aee19f86..1e7cec9edc 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoFuzzySkin.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoFuzzySkin.cpp @@ -210,7 +210,8 @@ void GLGizmoFuzzySkin::on_render_input_window(float x, float y, float bottom_lim icons = { ImGui::CircleButtonDarkIcon, ImGui::SphereButtonDarkIcon, ImGui::TriangleButtonDarkIcon, ImGui::FillButtonDarkIcon }; else icons = { ImGui::CircleButtonIcon, ImGui::SphereButtonIcon, ImGui::TriangleButtonIcon, ImGui::FillButtonIcon }; - std::array tool_tips = { _L("Circle"), _L("Sphere"), _L("Triangle"), _L("Fill") }; + // English, as the tools are named for automation; the tooltips translate them. + std::array tool_names = { L("Circle"), L("Sphere"), L("Triangle"), L("Fill") }; for (int i = 0; i < tool_ids.size(); i++) { //std::string str_label = std::string(""); //std::wstring btn_name = icons[i] + boost::nowide::widen(str_label); @@ -227,7 +228,7 @@ void GLGizmoFuzzySkin::on_render_input_window(float x, float y, float bottom_lim ImGui::PushStyleColor(ImGuiCol_ButtonActive , is_active ? ImVec4(0.f, .59f, .53f, .30f) : ImVec4(0,0,0,0)); // ORCA ImGui::PushStyleColor(ImGuiCol_Border , is_active ? ImGuiWrapper::COL_ORCA : ImVec4(0,0,0,0)); // ORCA ImGui::PushStyleColor(ImGuiCol_BorderActive , is_active ? ImGuiWrapper::COL_ORCA : ImVec4(0,0,0,0)); // ORCA matched color for fixing flicker on click - bool btn_clicked = m_imgui->glyph_button(icons[i], ImVec2(16.f * scale, 16.f * scale)); // ORCA glyph_button for fixing unequal paddings + bool btn_clicked = m_imgui->glyph_button(icons[i], ImVec2(16.f * scale, 16.f * scale), tool_names[i]); // ORCA glyph_button for fixing unequal paddings ImGui::PopStyleColor(6); ImGui::PopStyleVar(3); @@ -240,7 +241,7 @@ void GLGizmoFuzzySkin::on_render_input_window(float x, float y, float bottom_lim } if (ImGui::IsItemHovered()) { - m_imgui->tooltip(tool_tips[i], max_tooltip_width); + m_imgui->tooltip(_(tool_names[i]), max_tooltip_width); } } @@ -331,6 +332,7 @@ void GLGizmoFuzzySkin::on_render_input_window(float x, float y, float bottom_lim ImGui::SameLine(); m_imgui->bold_text(_u8L("Enable painted fuzzy skin for this object")); ImGui::PopStyleColor(); + m_imgui->record_named_item("Enable painted fuzzy skin", "button"); ImVec2 line_end = ImGui::GetItemRectMax(); line_end.y -= 2.0f; ImVec2 line_start = line_end; diff --git a/src/slic3r/GUI/Gizmos/GLGizmoMeasure.cpp b/src/slic3r/GUI/Gizmos/GLGizmoMeasure.cpp index 542c9faf74..2957dcd2e3 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoMeasure.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoMeasure.cpp @@ -521,6 +521,11 @@ void GLGizmoMeasure::on_set_state() m_editing_distance = false; m_is_editing_distance_first_frame = true; std::map>().swap(m_mesh_measure_map); + // The raycasters point into the scene's volumes, which a reload frees while the gizmo is + // closed; the next open rebuilds them in data_changed(), which must not take the path kept + // for the gizmo's own pending transform. + reset_all_pick(); + m_pending_scale = 0; } else { m_mode = EMode::FeatureSelection; @@ -1350,7 +1355,7 @@ void GLGizmoMeasure::render_dimensioning() m_imgui->text(txt); if (m_hit_different_volumes.size() < 2 && wxGetApp().plater()->canvas3D()->get_canvas_type() == GLCanvas3D::ECanvasType::CanvasView3D) { ImGui::SameLine(); - if (m_imgui->image_button(ImGui::SliderFloatEditBtnIcon, _L("Edit to scale"))) { + if (m_imgui->image_button(ImGui::SliderFloatEditBtnIcon, _L("Edit to scale"), "Edit to scale")) { m_editing_distance = true; edit_value = curr_value; m_imgui->requires_extra_frame(); @@ -1950,7 +1955,7 @@ void GLGizmoMeasure::show_selection_ui() ImGui::SameLine(selection_cap_length + feature_first_text_length + space_size * 2); ImGui::PushItemWidth(space_size * 2); ImGui::PushID("Reset1"); // for image_button - if (m_imgui->image_button(m_is_dark_mode ? ImGui::RevertBtn : ImGui::RevertBtn, _L("Reset"))) { reset_feature1(); } + if (m_imgui->image_button(m_is_dark_mode ? ImGui::RevertBtn : ImGui::RevertBtn, _L("Reset"), "Reset feature 1")) { reset_feature1(); } ImGui::PopID(); } ImGui::PopStyleColor(); @@ -1976,7 +1981,7 @@ void GLGizmoMeasure::show_selection_ui() ImGui::SameLine(selection_cap_length + feature_second_text_length + space_size * 2); ImGui::PushItemWidth(space_size * 2); ImGui::PushID("Reset2"); - if (m_imgui->image_button(m_is_dark_mode ? ImGui::RevertBtn : ImGui::RevertBtn, _L("Reset"))) { reset_feature2(); } + if (m_imgui->image_button(m_is_dark_mode ? ImGui::RevertBtn : ImGui::RevertBtn, _L("Reset"), "Reset feature 2")) { reset_feature2(); } ImGui::PopID(); } ImGui::PopStyleColor(); @@ -2006,7 +2011,7 @@ void GLGizmoMeasure::show_distance_xyz_ui() ImGui::TableSetColumnIndex(1); m_imgui->text_colored(col_2_color, col_2); ImGui::TableSetColumnIndex(2); - if (m_imgui->image_button(m_is_dark_mode ? ImGui::ClipboardBtnDarkIcon : ImGui::ClipboardBtnIcon, _L("Copy to clipboard"))) { + if (m_imgui->image_button(m_is_dark_mode ? ImGui::ClipboardBtnDarkIcon : ImGui::ClipboardBtnIcon, _L("Copy to clipboard"), "Copy to clipboard")) { wxTheClipboard->Open(); wxTheClipboard->SetData(new wxTextDataObject(wxString((col_1 + ": " + col_2).c_str(), wxConvUTF8))); wxTheClipboard->Close(); diff --git a/src/slic3r/GUI/Gizmos/GLGizmoMeshBoolean.cpp b/src/slic3r/GUI/Gizmos/GLGizmoMeshBoolean.cpp index 003455d2f9..ca466f4660 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoMeshBoolean.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoMeshBoolean.cpp @@ -369,7 +369,7 @@ void GLGizmoMeshBoolean::on_render_input_window(float x, float y, float bottom_l ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImGui::GetStyleColorVec4(ImGuiCol_Button)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImGui::GetStyleColorVec4(ImGuiCol_Button)); ImGui::PushStyleColor(ImGuiCol_Border, { 0, 0, 0, 0 }); - if (ImGui::Button((into_u8(ImGui::TextSearchCloseIcon) + "tool").c_str(), {18, 18})) + if (ImGui::Button((into_u8(ImGui::TextSearchCloseIcon) + "##tool").c_str(), {18, 18})) { m_tool.reset(); } diff --git a/src/slic3r/GUI/Gizmos/GLGizmoMmuSegmentation.cpp b/src/slic3r/GUI/Gizmos/GLGizmoMmuSegmentation.cpp index 54faee28e7..5937f8c2b9 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoMmuSegmentation.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoMmuSegmentation.cpp @@ -513,7 +513,8 @@ void GLGizmoMmuSegmentation::on_render_input_window(float x, float y, float bott icons = { ImGui::CircleButtonDarkIcon, ImGui::SphereButtonDarkIcon, ImGui::TriangleButtonDarkIcon, ImGui::HeightRangeDarkIcon, ImGui::FillButtonDarkIcon, ImGui::GapFillDarkIcon }; else icons = { ImGui::CircleButtonIcon, ImGui::SphereButtonIcon, ImGui::TriangleButtonIcon, ImGui::HeightRangeIcon, ImGui::FillButtonIcon, ImGui::GapFillIcon }; - std::array tool_tips = { _L("Circle"), _L("Sphere"), _L("Triangle"), _L("Height Range"), _L("Fill"), _L("Gap Fill") }; + // English, as the tools are named for automation; the tooltips translate them. + std::array tool_names = { L("Circle"), L("Sphere"), L("Triangle"), L("Height Range"), L("Fill"), L("Gap Fill") }; for (int i = 0; i < tool_ids.size(); i++) { //std::string str_label = std::string(""); //std::wstring btn_name = icons[i] + boost::nowide::widen(str_label); @@ -530,7 +531,7 @@ void GLGizmoMmuSegmentation::on_render_input_window(float x, float y, float bott ImGui::PushStyleColor(ImGuiCol_ButtonActive , is_active ? ImVec4(0.f, .59f, .53f, .30f) : ImVec4(0,0,0,0)); // ORCA ImGui::PushStyleColor(ImGuiCol_Border , is_active ? ImGuiWrapper::COL_ORCA : ImVec4(0,0,0,0)); // ORCA ImGui::PushStyleColor(ImGuiCol_BorderActive , is_active ? ImGuiWrapper::COL_ORCA : ImVec4(0,0,0,0)); // ORCA matched color for fixing flicker on click - bool btn_clicked = m_imgui->glyph_button(icons[i], ImVec2(16.f * scale, 16.f * scale)); // ORCA glyph_button for fixing unequal paddings + bool btn_clicked = m_imgui->glyph_button(icons[i], ImVec2(16.f * scale, 16.f * scale), tool_names[i]); // ORCA glyph_button for fixing unequal paddings ImGui::PopStyleColor(6); ImGui::PopStyleVar(3); @@ -543,7 +544,7 @@ void GLGizmoMmuSegmentation::on_render_input_window(float x, float y, float bott } if (ImGui::IsItemHovered()) { - m_imgui->tooltip(tool_tips[i], max_tooltip_width); + m_imgui->tooltip(_(tool_names[i]), max_tooltip_width); } } diff --git a/src/slic3r/GUI/Gizmos/GLGizmoSVG.cpp b/src/slic3r/GUI/Gizmos/GLGizmoSVG.cpp index c7699bdfd3..c48d682a5d 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoSVG.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoSVG.cpp @@ -41,6 +41,7 @@ #include "slic3r/GUI/3DScene.hpp" #include #include +#include #include "libslic3r/Utils.hpp" #include #include "libslic3r/Line.hpp" @@ -458,12 +459,13 @@ IconManager::VIcons init_icons(IconManager &mng, const GuiCfg &cfg) // icons.push_back(i.front()); //return icons; } -bool draw_clickable(const IconManager::VIcons &icons, IconType type) +// `name` is the button's English name, for automation. +bool draw_clickable(const IconManager::VIcons &icons, IconType type, const std::string &name) { - return clickable(get_icon(icons, type, IconState::activable), get_icon(icons, type, IconState::hovered)); + return clickable(get_icon(icons, type, IconState::activable), get_icon(icons, type, IconState::hovered), name); } -bool reset_button(const IconManager::VIcons &icons) +bool reset_button(const IconManager::VIcons &icons, const std::string &name) { float reset_offset = ImGui::GetStyle().WindowPadding.x; ImGui::SameLine(reset_offset); @@ -475,7 +477,7 @@ bool reset_button(const IconManager::VIcons &icons) //return ImGui::Button((btn_label + "##" + label_id).c_str()); auto icon = get_icon(icons, IconType::reset_value, IconState::hovered); - return clickable(icon, icon); // ORCA use orange color for both states + return clickable(icon, icon, name); // ORCA use orange color for both states } } // namespace @@ -1514,7 +1516,7 @@ void GLGizmoSVG::draw_filename(){ bool can_reload = !m_volume_shape.svg_file->path.empty(); if (can_reload) { ImGui::SameLine(); - if (draw_clickable(m_icons, IconType::refresh)) { + if (draw_clickable(m_icons, IconType::refresh, "Reload")) { if (!boost::filesystem::exists(m_volume_shape.svg_file->path)) { m_volume_shape.svg_file->path.clear(); } else { @@ -1606,23 +1608,7 @@ void GLGizmoSVG::draw_filename(){ wxFileDialog dlg(parent, dlg_title, last_used_directory, dlg_file, wildcard, wxFD_SAVE | wxFD_OVERWRITE_PROMPT); if (dlg.ShowModal() == wxID_OK ){ last_used_directory = dlg.GetDirectory(); - wxString out_path = dlg.GetPath(); - std::string path{out_path.c_str()}; - //Slic3r::save(*m_volume_shape.svg_file.image, path); - - std::ofstream stream(path); - if (stream.is_open()){ - stream << *svg.file_data; - - // change source file - m_filename_preview.clear(); - m_volume_shape.svg_file->path = path; - m_volume_shape.svg_file->path_in_3mf.clear(); // possible change name - m_volume->emboss_shape->svg_file = m_volume_shape.svg_file; // copy - write changes into volume - } else { - BOOST_LOG_TRIVIAL(error) << "Opening file: \"" << path << "\" Failed"; - } - + save_svg_as(into_u8(dlg.GetPath())); } } else if (ImGui::IsItemHovered()) { tooltip = _u8L("Save as SVG file."); @@ -1652,17 +1638,52 @@ void GLGizmoSVG::draw_filename(){ if (!tooltip.empty()) m_imgui->tooltip(tooltip, m_gui_cfg->max_tooltip_width); - if (file_changed) { - float scale = get_scale_for_tolerance(); - double tes_tol = get_tesselation_tolerance(scale); - EmbossShape es_ = select_shape(m_volume_shape.svg_file->path, tes_tol); - m_volume_shape.svg_file = std::move(es_.svg_file); - m_volume_shape.shapes_with_ids = std::move(es_.shapes_with_ids); - m_volume_shape.final_shape = {}; // clear cache - m_shape_warnings = create_shape_warnings(m_volume_shape, scale); - init_texture(m_texture, m_volume_shape.shapes_with_ids, m_gui_cfg->texture_max_size_px, m_shape_warnings); - process(); + if (file_changed) + load_svg_file(); +} + +void GLGizmoSVG::load_svg_file() +{ + float scale = get_scale_for_tolerance(); + double tes_tol = get_tesselation_tolerance(scale); + EmbossShape es_ = select_shape(m_volume_shape.svg_file->path, tes_tol); + m_volume_shape.svg_file = std::move(es_.svg_file); + m_volume_shape.shapes_with_ids = std::move(es_.shapes_with_ids); + m_volume_shape.final_shape = {}; // clear cache + m_shape_warnings = create_shape_warnings(m_volume_shape, scale); + init_texture(m_texture, m_volume_shape.shapes_with_ids, m_gui_cfg->texture_max_size_px, m_shape_warnings); + process(); +} + +bool GLGizmoSVG::change_file(const std::string &path) +{ + if (m_volume == nullptr || m_gui_cfg == nullptr) + return false; + EmbossShape::SvgFile svg_file_new; + svg_file_new.path = path; + m_volume_shape.svg_file = svg_file_new; // clear data + m_filename_preview.clear(); // draw_filename() makes it again from the new file + load_svg_file(); + return !m_volume_shape.shapes_with_ids.empty(); +} + +bool GLGizmoSVG::save_svg_as(const std::string &path) +{ + if (m_volume == nullptr || !m_volume_shape.svg_file.has_value() || m_volume_shape.svg_file->file_data == nullptr) + return false; + boost::nowide::ofstream stream(path); + if (!stream.is_open()) { + BOOST_LOG_TRIVIAL(error) << "Opening file: \"" << path << "\" Failed"; + return false; } + stream << *m_volume_shape.svg_file->file_data; + + // change source file + m_filename_preview.clear(); + m_volume_shape.svg_file->path = path; + m_volume_shape.svg_file->path_in_3mf.clear(); // possible change name + m_volume->emboss_shape->svg_file = m_volume_shape.svg_file; // copy - write changes into volume + return bool(stream); } void GLGizmoSVG::draw_depth() @@ -1806,7 +1827,7 @@ void GLGizmoSVG::draw_size() ImGui::SameLine(m_gui_cfg->lock_offset); const IconManager::Icon &icon = get_icon(m_icons, m_keep_ratio ? IconType::lock : IconType::unlock, IconState::activable); const IconManager::Icon &icon_hover = get_icon(m_icons, m_keep_ratio ? IconType::lock : IconType::unlock, IconState::hovered); - if (button(icon, icon_hover, icon)) + if (button(icon, icon_hover, icon, false, "Keep ratio")) m_keep_ratio = !m_keep_ratio; if (ImGui::IsItemHovered()) m_imgui->tooltip(_u8L("Lock/unlock the aspect ratio of the SVG."), m_gui_cfg->max_tooltip_width); @@ -1815,7 +1836,7 @@ void GLGizmoSVG::draw_size() // reset button //bool can_reset = m_scale_width.has_value() || m_scale_height.has_value(); // ORCA update variable above if condition change if (can_reset) { - if (reset_button(m_icons)) { + if (reset_button(m_icons, "Reset size")) { new_relative_scale = Vec3d(1./m_scale_width.value_or(1.f), 1./m_scale_height.value_or(1.f), 1.); make_snap = true; } else if (ImGui::IsItemHovered()) @@ -1909,7 +1930,7 @@ void GLGizmoSVG::draw_distance() bool is_stop_sliding = m_imgui->get_last_slider_status().deactivated_after_edit; bool is_reseted = false; if (m_distance.has_value()) { - if (reset_button(m_icons)) { + if (reset_button(m_icons, "Reset distance")) { m_distance.reset(); is_reseted = true; } else if (ImGui::IsItemHovered()) @@ -1957,7 +1978,7 @@ void GLGizmoSVG::draw_rotation() // Reset button bool is_reseted = false; if (m_angle.has_value()) { - if (reset_button(m_icons)) { + if (reset_button(m_icons, "Reset rotation")) { do_local_z_rotate(m_parent.get_selection(), -(*m_angle)); m_angle.reset(); @@ -1979,7 +2000,7 @@ void GLGizmoSVG::draw_rotation() ImGui::SameLine(m_gui_cfg->lock_offset); const IconManager::Icon &icon = get_icon(m_icons, m_keep_up ? IconType::lock : IconType::unlock, IconState::activable); const IconManager::Icon &icon_hover = get_icon(m_icons, m_keep_up ? IconType::lock : IconType::unlock, IconState::hovered); - if (button(icon, icon_hover, icon)) + if (button(icon, icon_hover, icon, false, "Keep up")) m_keep_up = !m_keep_up; if (ImGui::IsItemHovered()) m_imgui->tooltip(_u8L("Lock/unlock rotation angle when dragging above the surface."), m_gui_cfg->max_tooltip_width); @@ -1992,14 +2013,14 @@ void GLGizmoSVG::draw_mirroring() ImGui::Text("%s", m_gui_cfg->translations.mirror.c_str()); ImGui::SameLine(m_gui_cfg->input_offset); Axis axis = Axis::UNKNOWN_AXIS; - if (draw_clickable(m_icons, IconType::reflection_x)) { + if (draw_clickable(m_icons, IconType::reflection_x, "Mirror horizontally")) { axis = Axis::X; } else if (ImGui::IsItemHovered()) { m_imgui->tooltip(_u8L("Mirror vertically"), m_gui_cfg->max_tooltip_width); } ImGui::SameLine(); - if (draw_clickable(m_icons, IconType::reflection_y)) { + if (draw_clickable(m_icons, IconType::reflection_y, "Mirror vertically")) { axis = Axis::Y; } else if (ImGui::IsItemHovered()) { m_imgui->tooltip(_u8L("Mirror horizontally"), m_gui_cfg->max_tooltip_width); diff --git a/src/slic3r/GUI/Gizmos/GLGizmoSVG.hpp b/src/slic3r/GUI/Gizmos/GLGizmoSVG.hpp index 2d59135769..7aadb6b4bf 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoSVG.hpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoSVG.hpp @@ -84,6 +84,12 @@ public: /// True when constain emboss data otherwise False static bool is_svg(const ModelVolume &volume); + // What the file menu's "Change file" and "Save as" do after their dialogs, for the part being + // edited; change_file() also shows the new file's name, which the menu's own path leaves as it + // was. change_file() returns whether the file gave shapes; save_svg_as() whether it wrote. + bool change_file(const std::string &path); + bool save_svg_as(const std::string &path); + protected: bool on_init() override; std::string on_get_name() const override; @@ -123,6 +129,8 @@ private: void draw_window(); void draw_preview(); void draw_filename(); + // Reads the SVG file m_volume_shape names into its shapes and preview, and re-creates the part. + void load_svg_file(); void draw_depth(); void draw_size(); void draw_use_surface(); diff --git a/src/slic3r/GUI/Gizmos/GLGizmoSeam.cpp b/src/slic3r/GUI/Gizmos/GLGizmoSeam.cpp index 6a0019caf2..9b4fad9dfc 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoSeam.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoSeam.cpp @@ -179,7 +179,8 @@ void GLGizmoSeam::on_render_input_window(float x, float y, float bottom_limit) icons = { ImGui::CircleButtonDarkIcon, ImGui::SphereButtonDarkIcon}; else icons = { ImGui::CircleButtonIcon, ImGui::SphereButtonIcon }; - std::array tool_tips = { _L("Circle"), _L("Sphere")}; + // English, as the tools are named for automation; the tooltips translate them. + std::array tool_names = { L("Circle"), L("Sphere") }; for (int i = 0; i < tool_ids.size(); i++) { //std::string str_label = std::string("##"); //std::wstring btn_name = icons[i] + boost::nowide::widen(str_label); @@ -196,7 +197,7 @@ void GLGizmoSeam::on_render_input_window(float x, float y, float bottom_limit) ImGui::PushStyleColor(ImGuiCol_ButtonActive , is_active ? ImVec4(0.f, .59f, .53f, .30f) : ImVec4(0,0,0,0)); // ORCA ImGui::PushStyleColor(ImGuiCol_Border , is_active ? ImGuiWrapper::COL_ORCA : ImVec4(0,0,0,0)); // ORCA ImGui::PushStyleColor(ImGuiCol_BorderActive , is_active ? ImGuiWrapper::COL_ORCA : ImVec4(0,0,0,0)); // ORCA matched color for fixing flicker on click - bool btn_clicked = m_imgui->glyph_button(icons[i], ImVec2(16.f * scale, 16.f * scale)); // ORCA glyph_button for fixing unequal paddings + bool btn_clicked = m_imgui->glyph_button(icons[i], ImVec2(16.f * scale, 16.f * scale), tool_names[i]); // ORCA glyph_button for fixing unequal paddings ImGui::PopStyleColor(6); ImGui::PopStyleVar(3); @@ -209,7 +210,7 @@ void GLGizmoSeam::on_render_input_window(float x, float y, float bottom_limit) } if (ImGui::IsItemHovered()) { - m_imgui->tooltip(tool_tips[i], max_tooltip_width); + m_imgui->tooltip(_(tool_names[i]), max_tooltip_width); } } diff --git a/src/slic3r/GUI/Gizmos/GLGizmoSimplify.cpp b/src/slic3r/GUI/Gizmos/GLGizmoSimplify.cpp index 78bd36d7b7..0f371670de 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoSimplify.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoSimplify.cpp @@ -339,20 +339,24 @@ void GLGizmoSimplify::on_render_input_window(float x, float y, float bottom_limi ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0); ImGui::PushItemWidth(slider_width + space_size); - if (m_imgui->bbl_slider_float_style("##decimate_ratio", &m_configuration.decimate_ratio, 0.f, 100.f, format)) { + // The slider and the number box beside it set the ratio alike. + auto ratio_changed = [&]() { if (m_configuration.decimate_ratio < 0.f) m_configuration.decimate_ratio = 0.01f; if (m_configuration.decimate_ratio > 100.f) m_configuration.decimate_ratio = 100.f; m_configuration.fix_count_by_ratio(orig_triangle_count); start_process = true; - } + }; + if (m_imgui->bbl_slider_float_style("##decimate_ratio", &m_configuration.decimate_ratio, 0.f, 100.f, format)) + ratio_changed(); ImGui::SameLine(); ImGui::PopStyleVar(1); ImGui::PushItemWidth(ImGui::CalcTextSize("100.00%").x + space_size); - ImGui::BBLDragFloat("##decimate_ratio_input", &m_configuration.decimate_ratio, 0.05f, 0.0f, 0.0f, "%.2f%%"); + if (ImGui::BBLDragFloat("##decimate_ratio_input", &m_configuration.decimate_ratio, 0.05f, 0.0f, 0.0f, "%.2f%%")) + ratio_changed(); ImGui::NewLine(); ImGui::SameLine(bottom_left_width + space_size); @@ -424,6 +428,15 @@ void GLGizmoSimplify::close() { gizmos_mgr.open_gizmo(GLGizmosManager::EType::Simplify); } +bool GLGizmoSimplify::is_busy() const +{ + std::lock_guard lk(m_state_mutex); + // A calculation runs until its worker sets idle. While the gizmo is open, worker_finished() then + // joins the thread, so a joinable one has a result not yet shown; while it is closed nothing is + // shown, and opening it joins a thread that ended meanwhile. + return m_state.status != State::idle || (m_worker.joinable() && GLGizmoBase::m_state == On); +} + void GLGizmoSimplify::stop_worker_thread_request() { std::lock_guard lk(m_state_mutex); @@ -543,9 +556,10 @@ void GLGizmoSimplify::process() std::lock_guard lk(m_state_mutex); if (m_state.status == State::Status::running) { // We were not cancelled, the result is valid. - m_state.status = State::Status::idle; m_state.result = std::move(its); } + // A cancellation that came after the calculation's last check ends here too. + m_state.status = State::Status::idle; // Update UI. Use CallAfter so the function is run on UI thread. call_after_if_active([this]() { worker_finished(); }); @@ -603,6 +617,15 @@ void GLGizmoSimplify::on_set_state() m_volume = nullptr; // invalidate selected model m_glmodel.reset(); } else if (GLGizmoBase::m_state == GLGizmoBase::On) { + // A calculation that ended while the gizmo was closed had its worker_finished() dropped, so + // nothing else joins its thread. + bool ended = false; + { + std::lock_guard lk(m_state_mutex); + ended = m_state.status == State::idle; + } + if (ended && m_worker.joinable()) + m_worker.join(); // when open by hyperlink it needs to show up request_rerender(); } diff --git a/src/slic3r/GUI/Gizmos/GLGizmoSimplify.hpp b/src/slic3r/GUI/Gizmos/GLGizmoSimplify.hpp index fa43291705..882f882714 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoSimplify.hpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoSimplify.hpp @@ -43,6 +43,9 @@ protected: virtual void on_render_input_window(float x, float y, float bottom_limit) override; virtual bool on_is_activable() const override; virtual bool on_is_selectable() const override { return false; } + // Busy from the start of a calculation until worker_finished() has shown its result, restarts + // and cancellations included; once closed, until a cancelled calculation has stopped. + bool is_busy() const override; virtual void on_set_state() override; // must implement @@ -112,7 +115,7 @@ private: }; std::thread m_worker; - std::mutex m_state_mutex; // guards m_state + mutable std::mutex m_state_mutex; // guards m_state State m_state; // accessed by both threads diff --git a/src/slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.cpp b/src/slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.cpp index f386e6713e..c67de1d320 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.cpp @@ -4340,17 +4340,31 @@ void GLGizmoTextureDisplacement::import_custom_texture(TextureDisplacementLayer wxFD_OPEN | wxFD_FILE_MUST_EXIST); if (dialog.ShowModal() != wxID_OK) return; + std::string error; + if (!import_texture(layer, into_u8(dialog.GetPath()), error)) + show_error(nullptr, error); +} +bool GLGizmoTextureDisplacement::import_texture(TextureDisplacementLayer &layer, const std::string &path, std::string &error) +{ // Converts to the 8-bit grayscale PNG the bake code understands and copies it into the user's // own texture folder, so it stays available for later models (and survives an app update, which // rewrites the shipped folder wholesale). - std::string error; - const std::optional entry = import_texture_to_library(into_u8(dialog.GetPath()), error); - if (!entry) { - show_error(nullptr, error); - return; - } + const std::optional entry = import_texture_to_library(path, error); + if (!entry) + return false; set_layer_texture(layer, *entry); + return true; +} + +bool GLGizmoTextureDisplacement::import_texture(const std::string &path, std::string &error) +{ + TextureDisplacementLayer *layer = active_layer(); + if (layer == nullptr) { + error = "There is no active layer to put the texture on; add a layer first"; + return false; + } + return import_texture(*layer, path, error); } void GLGizmoTextureDisplacement::ease_wheel_scroll(float &target, float &applied) @@ -4572,6 +4586,7 @@ void GLGizmoTextureDisplacement::render_texture_library_popup(const ImVec2 &pane } else { clicked = ImGui::Button("?", ImVec2(tile, tile)); } + m_imgui->record_named_item(entry->name); if (removable) ImGui::SetItemAllowOverlap(); // the remove button drawn over its corner takes its own clicks const ImVec2 a = ImGui::GetItemRectMin(), b = ImGui::GetItemRectMax(); @@ -4593,6 +4608,7 @@ void GLGizmoTextureDisplacement::render_texture_library_popup(const ImVec2 &pane const ImVec2 c(b.x - r - 2.f, a.y + r + 2.f); ImGui::SetCursorScreenPos(ImVec2(c.x - r, c.y - r)); const bool remove_clicked = ImGui::InvisibleButton("##remove", ImVec2(2.f * r, 2.f * r)); + m_imgui->record_named_item("Remove " + entry->name); const bool hot = ImGui::IsItemHovered(); dl->AddCircleFilled(c, r, hot ? IM_COL32(214, 72, 64, 235) : IM_COL32(0, 0, 0, 170)); const float k = 0.42f * r; @@ -4922,6 +4938,11 @@ void GLGizmoTextureDisplacement::close_image_adjust() } } +bool GLGizmoTextureDisplacement::is_busy() const +{ + return !m_adjust_preview_source.empty() && (m_adjust_preview_job.valid() || m_adjust != m_adjust_preview_shown); +} + void GLGizmoTextureDisplacement::update_image_adjust_preview() { if (m_adjust_preview_source.empty()) @@ -7139,6 +7160,7 @@ void GLGizmoTextureDisplacement::on_render_input_window(float x, float y, float } else { clicked = ImGui::Button(label.ToUTF8().data(), ImVec2(0.f, sz)); // the control is never lost to a missing icon } + m_imgui->record_named_item(into_u8(label), "toggle", active ? 1 : 0); ImGui::GetWindowDrawList()->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), ImGui::GetColorU32(active ? orca : col_frame), style.FrameRounding); ImGui::PopStyleColor(na ? 3 : 1); @@ -7164,6 +7186,7 @@ void GLGizmoTextureDisplacement::on_render_input_window(float x, float y, float } else { clicked = ImGui::Button(label.ToUTF8().data(), ImVec2(0.f, sz)); } + m_imgui->record_named_item(into_u8(label)); ImGui::PopStyleColor(); ImGui::PopStyleVar(); ImGui::PopID(); @@ -7741,6 +7764,8 @@ void GLGizmoTextureDisplacement::on_render_input_window(float x, float y, float } else if (ImGui::Button("?##thumb", ImVec2(frame_h, frame_h))) { open_picker(layer.slot); } + // Named by position for automation: texture names repeat ("heightmap (2)"). + m_imgui->record_named_item("Layer " + std::to_string(li + 1) + " image"); hover_tip(_u8L("Pick a different image for this layer. The paint, depth and tiling stay as they are.")); { // The teal outline on the thumbnail is what marks this card as the layer being painted. @@ -8231,6 +8256,7 @@ void GLGizmoTextureDisplacement::on_render_input_window(float x, float y, float const float row_w = content_rx - p0.x; if (ImGui::InvisibleButton("##row", ImVec2(row_w, row_h))) activate_slot = layer.slot; + m_imgui->record_named_item("Layer " + std::to_string(li + 1)); const bool row_hovered = ImGui::IsItemHovered(); ImGui::SetItemAllowOverlap(); // the row's own buttons, submitted after it, still take their clicks drop_target(li, layer.slot, p0, ImVec2(p0.x + row_w, p0.y + row_h)); @@ -8259,6 +8285,7 @@ void GLGizmoTextureDisplacement::on_render_input_window(float x, float y, float } else if (ImGui::Button("?##thumb", ImVec2(th, th))) { open_picker(layer.slot); } + m_imgui->record_named_item("Layer " + std::to_string(li + 1) + " image"); hover_tip(_u8L("Pick a different image for this layer. The paint, depth and tiling stay as they are.")); ImGui::SameLine(); diff --git a/src/slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.hpp b/src/slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.hpp index e798c40243..e52d5777cc 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.hpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.hpp @@ -266,6 +266,14 @@ public: void render_painter_gizmo() override; + // Busy while the image adjustment preview has a pass in flight or one still to start for the + // latest slider values. Its displacement preview runs on the plater's job worker. + bool is_busy() const override; + + // Imports the height map at `path` into the texture library and puts it on the active layer, + // as the library's import tile does after its file dialog. False with `error` saying why not. + bool import_texture(const std::string &path, std::string &error); + // Intercepts mouse input while "Adjust Texture" mode is on (dragging the on-canvas offset/ // rotation handles instead of painting); otherwise forwards to the normal painting handling. bool on_mouse(const wxMouseEvent &mouse_event) override; @@ -512,6 +520,8 @@ private: float m_picker_scroll_applied = -1.f; void set_layer_texture(TextureDisplacementLayer &layer, const TextureLibraryEntry &entry); void import_custom_texture(TextureDisplacementLayer &layer); + // What import_custom_texture() does with the file its dialog picked. + bool import_texture(TextureDisplacementLayer &layer, const std::string &path, std::string &error); // Paint / Erase, from the panel. See get_left_button_state_type(). bool m_erase_mode = false; diff --git a/src/slic3r/GUI/Gizmos/GLGizmosManager.cpp b/src/slic3r/GUI/Gizmos/GLGizmosManager.cpp index 3193916125..0cb97816a2 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmosManager.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmosManager.cpp @@ -108,6 +108,14 @@ std::vector GLGizmosManager::get_selectable_idxs() const return out; } +bool GLGizmosManager::is_on_toolbar(EType type) const +{ + for (size_t idx : get_selectable_idxs()) + if (m_gizmos[idx]->get_sprite_id() == (unsigned int) type) + return true; + return false; +} + //BBS: GUI refactor: GLToolbar&&Gizmo adjust GLGizmosManager::EType GLGizmosManager::get_gizmo_from_mouse(const Vec2d &mouse_pos) const { @@ -477,6 +485,22 @@ bool GLGizmosManager::open_gizmo(EType type) } +GLGizmosManager::ToolbarClick GLGizmosManager::click_toolbar_icon(EType type) +{ + if (m_gizmos.empty()) + return ToolbarClick::Nothing; + const EType before = m_current; + if (type == Emboss) { + if (dynamic_cast(m_gizmos[Emboss].get())->on_shortcut_key()) + return ToolbarClick::CreationStarted; + } else { + open_gizmo(type); + } + if (m_current == type) + return ToolbarClick::Opened; + return before == type ? ToolbarClick::Closed : ToolbarClick::Nothing; +} + bool GLGizmosManager::check_gizmos_closed_except(EType type) const { if (get_current_type() != type && get_current_type() != Undefined) { @@ -545,6 +569,11 @@ bool GLGizmosManager::is_running() const return m_current != Undefined; } +bool GLGizmosManager::is_busy() const +{ + return std::any_of(m_gizmos.begin(), m_gizmos.end(), [](const auto &g) { return g->is_busy(); }); +} + bool GLGizmosManager::open_gizmo_by_shortcut(Shortcut shortcut) { if (!m_enabled || m_gizmos.empty()) @@ -796,12 +825,7 @@ bool GLGizmosManager::gizmos_toolbar_on_mouse(const wxMouseEvent &mouse_event) { // mouse is above toolbar if (mouse_event.LeftDown() || mouse_event.LeftDClick()) { mc.left = true; - if (gizmo == Emboss) { - GLGizmoBase *gizmo_emboss = m_gizmos[Emboss].get(); - dynamic_cast(gizmo_emboss)->on_shortcut_key(); - } else { - open_gizmo(gizmo); - } + click_toolbar_icon(gizmo); return true; } else if (mouse_event.RightDown()) { diff --git a/src/slic3r/GUI/Gizmos/GLGizmosManager.hpp b/src/slic3r/GUI/Gizmos/GLGizmosManager.hpp index d08b50f61d..fff43f3d20 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmosManager.hpp +++ b/src/slic3r/GUI/Gizmos/GLGizmosManager.hpp @@ -284,6 +284,11 @@ public: void refresh_on_off_state(); void reset_all_states(); bool open_gizmo(EType type); + // What a left click on a gizmo's toolbar icon did. + enum class ToolbarClick { Nothing, Opened, Closed, CreationStarted }; + // Does what that click does: the Text gizmo starts creating a text part when no text is + // selected (the creation job opens the gizmo), the others open or close. + ToolbarClick click_toolbar_icon(EType type); bool check_gizmos_closed_except(EType) const; void set_hover_id(int id); @@ -302,6 +307,10 @@ public: EType get_gizmo_from_name(const std::string& gizmo_name) const; bool is_running() const; + // Whether this canvas's gizmo toolbar shows an icon for `type`. + bool is_on_toolbar(EType type) const; + // Whether any gizmo still works in the background, see GLGizmoBase::is_busy(). + bool is_busy() const; // Opens the gizmo bound to a Plater-context shortcut; false when no gizmo has it or it cannot open now. bool open_gizmo_by_shortcut(Shortcut shortcut); // Lets the current gizmo consume the delete key; false when it did not. diff --git a/src/slic3r/GUI/Gizmos/GizmoObjectManipulation.cpp b/src/slic3r/GUI/Gizmos/GizmoObjectManipulation.cpp index 9e17c2a015..6bcca9623e 100644 --- a/src/slic3r/GUI/Gizmos/GizmoObjectManipulation.cpp +++ b/src/slic3r/GUI/Gizmos/GizmoObjectManipulation.cpp @@ -509,8 +509,13 @@ void GizmoObjectManipulation::on_change(const std::string &opt_key, int axis, do change_size_value(axis, new_value); } -bool GizmoObjectManipulation::render_combo( - ImGuiWrapper *imgui_wrapper, const std::string &label, const std::vector &lines, size_t &selection_idx, float label_width, float item_width) +bool GizmoObjectManipulation::render_combo(ImGuiWrapper *imgui_wrapper, + const std::string &label, + const std::vector &lines, + size_t &selection_idx, + float label_width, + float item_width, + const std::string &name) { if(!label.empty()){ ImGui::AlignTextToFramePadding(); @@ -523,10 +528,14 @@ bool GizmoObjectManipulation::render_combo( size_t selection_out = selection_idx; const char *selected_str = (selection_idx >= 0 && selection_idx < int(lines.size())) ? lines[selection_idx].c_str() : ""; - if (ImGui::BBLBeginCombo(("##" + label).c_str(), selected_str, 0)) { + const std::string combo_label = "##" + label; + // Taken before the combo, as an open combo leaves its popup as the current window. + const ImGuiID combo_id = ImGui::GetCurrentWindow()->GetIDNoKeepAlive(combo_label.c_str()); + if (ImGui::BBLBeginCombo(combo_label.c_str(), selected_str, 0)) { for (size_t line_idx = 0; line_idx < lines.size(); ++line_idx) { ImGui::PushID(int(line_idx)); if (ImGui::Selectable("", line_idx == selection_idx)) selection_out = line_idx; + imgui_wrapper->record_named_item(lines[line_idx], "option"); ImGui::SameLine(); ImGui::Text("%s", lines[line_idx].c_str()); @@ -535,6 +544,7 @@ bool GizmoObjectManipulation::render_combo( ImGui::EndCombo(); } + imgui_wrapper->record_item_name(combo_id, name, "combo"); bool is_changed = selection_idx != selection_out; selection_idx = selection_out; @@ -670,6 +680,7 @@ bool GizmoObjectManipulation::reset_button(ImGuiWrapper *imgui_wrapper, bool ena ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); pressed = ImGui::ImageButton3(normal_id, hover_id, button_size, {0,0}, {1,1}, -1, {0,0,0,0}, {1,1,1, enabled ? 1.f : 0.f}); // ORCA make icon invisible to prevent changes on layout + imgui_wrapper->record_named_item("Reset"); ImGui::PopStyleVar(1); @@ -694,6 +705,7 @@ bool GizmoObjectManipulation::reset_zero_button(ImGuiWrapper *imgui_wrapper, bo ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); pressed = ImGui::ImageButton3(normal_id, hover_id, button_size, {0,0}, {1,1}, -1, {0,0,0,0}, {1,1,1, enabled ? 1.f : 0.f}); // ORCA make icon invisible to prevent changes on layout + imgui_wrapper->record_named_item("Reset to zero"); ImGui::PopStyleVar(1); @@ -855,7 +867,7 @@ void GizmoObjectManipulation::do_render_move_window(ImGuiWrapper *imgui_wrapper, ImGuiWrapper::push_combo_style(m_glcanvas.get_scale()); bool combox_changed = false; - if (render_combo(imgui_wrapper, "", modes, selection_idx, 0, coord_combo_width)) { + if (render_combo(imgui_wrapper, "", modes, selection_idx, 0, coord_combo_width, "coordinates")) { combox_changed = true; } ImGuiWrapper::pop_combo_style(); @@ -970,7 +982,7 @@ void GizmoObjectManipulation::do_render_move_window(ImGuiWrapper *imgui_wrapper, ImGuiWrapper::push_combo_style(m_glcanvas.get_scale()); // render_combo() takes its ImGui id from the empty label, which the coordinate combo uses too. ImGui::PushID("align_mode"); - if (render_combo(imgui_wrapper, "", align_modes, align_mode_idx, 0, coord_combo_width)) + if (render_combo(imgui_wrapper, "", align_modes, align_mode_idx, 0, coord_combo_width, "align_to")) m_align_to_parent = align_mode_idx + 1 == align_modes.size(); ImGui::PopID(); ImGuiWrapper::pop_combo_style(); @@ -982,8 +994,10 @@ void GizmoObjectManipulation::do_render_move_window(ImGuiWrapper *imgui_wrapper, const bool dark_mode = wxGetApp().dark_mode(); int current_axis = -1; + // `name` is English, as automation names the button; the tooltip translates it. auto align_icon = [&](int axis, AlignType type, GLGizmosManager::MENU_ICON_NAME icon, - GLGizmosManager::MENU_ICON_NAME dark_icon, const wxString &tip) { + GLGizmosManager::MENU_ICON_NAME dark_icon, const char *name, const char *suffix) { + const wxString tip = _(name) + suffix; const bool distribute = type >= AlignType::DISTRIBUTE_X; const bool enabled = m_align_to_parent ? m_alignment_helper.can_align(type, true) : distribute ? m_alignment_helper.can_distribute(type) : @@ -1002,7 +1016,9 @@ void GizmoObjectManipulation::do_render_move_window(ImGuiWrapper *imgui_wrapper, ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImGui::GetStyle().Colors[ImGuiCol_Button]); } ImTextureID texture = m_glcanvas.get_gizmos_manager().get_icon_texture_id(dark_mode ? dark_icon : icon); - if (ImGui::ImageButton3(texture, texture, ImVec2(align_icon_size, align_icon_size)) && enabled) { + const bool clicked = ImGui::ImageButton3(texture, texture, ImVec2(align_icon_size, align_icon_size)); + imgui_wrapper->record_named_item(name); + if (clicked && enabled) { if (distribute) m_alignment_helper.distribute_objects(type); else @@ -1030,26 +1046,26 @@ void GizmoObjectManipulation::do_render_move_window(ImGuiWrapper *imgui_wrapper, } }; ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); - align_icon(0, AlignType::X_MIN, GLGizmosManager::IC_ALIGN_X_MIN, GLGizmosManager::IC_ALIGN_X_MIN_DARK, _L("Align left") + " (-X)"); - align_icon(0, AlignType::CENTER_X, GLGizmosManager::IC_ALIGN_X_CENTER, GLGizmosManager::IC_ALIGN_X_CENTER_DARK, _L("Align left-right center") + " (X)"); - align_icon(0, AlignType::X_MAX, GLGizmosManager::IC_ALIGN_X_MAX, GLGizmosManager::IC_ALIGN_X_MAX_DARK, _L("Align right") + " (+X)"); + align_icon(0, AlignType::X_MIN, GLGizmosManager::IC_ALIGN_X_MIN, GLGizmosManager::IC_ALIGN_X_MIN_DARK, L("Align left"), " (-X)"); + align_icon(0, AlignType::CENTER_X, GLGizmosManager::IC_ALIGN_X_CENTER, GLGizmosManager::IC_ALIGN_X_CENTER_DARK, L("Align left-right center"), " (X)"); + align_icon(0, AlignType::X_MAX, GLGizmosManager::IC_ALIGN_X_MAX, GLGizmosManager::IC_ALIGN_X_MAX_DARK, L("Align right"), " (+X)"); - align_icon(1, AlignType::Y_MIN, GLGizmosManager::IC_ALIGN_Y_MIN, GLGizmosManager::IC_ALIGN_Y_MIN_DARK, _L("Align front") + " (-Y)"); - align_icon(1, AlignType::CENTER_Y, GLGizmosManager::IC_ALIGN_Y_CENTER, GLGizmosManager::IC_ALIGN_Y_CENTER_DARK, _L("Align front-back center") + " (Y)"); - align_icon(1, AlignType::Y_MAX, GLGizmosManager::IC_ALIGN_Y_MAX, GLGizmosManager::IC_ALIGN_Y_MAX_DARK, _L("Align back") + " (+Y)"); + align_icon(1, AlignType::Y_MIN, GLGizmosManager::IC_ALIGN_Y_MIN, GLGizmosManager::IC_ALIGN_Y_MIN_DARK, L("Align front"), " (-Y)"); + align_icon(1, AlignType::CENTER_Y, GLGizmosManager::IC_ALIGN_Y_CENTER, GLGizmosManager::IC_ALIGN_Y_CENTER_DARK, L("Align front-back center"), " (Y)"); + align_icon(1, AlignType::Y_MAX, GLGizmosManager::IC_ALIGN_Y_MAX, GLGizmosManager::IC_ALIGN_Y_MAX_DARK, L("Align back"), " (+Y)"); - align_icon(2, AlignType::Z_MIN, GLGizmosManager::IC_ALIGN_Z_MIN, GLGizmosManager::IC_ALIGN_Z_MIN_DARK, _L("Align bottom") + " (-Z)"); - align_icon(2, AlignType::CENTER_Z, GLGizmosManager::IC_ALIGN_Z_CENTER, GLGizmosManager::IC_ALIGN_Z_CENTER_DARK, _L("Align top-bottom center") + " (Z)"); - align_icon(2, AlignType::Z_MAX, GLGizmosManager::IC_ALIGN_Z_MAX, GLGizmosManager::IC_ALIGN_Z_MAX_DARK, _L("Align top") + " (+Z)"); + align_icon(2, AlignType::Z_MIN, GLGizmosManager::IC_ALIGN_Z_MIN, GLGizmosManager::IC_ALIGN_Z_MIN_DARK, L("Align bottom"), " (-Z)"); + align_icon(2, AlignType::CENTER_Z, GLGizmosManager::IC_ALIGN_Z_CENTER, GLGizmosManager::IC_ALIGN_Z_CENTER_DARK, L("Align top-bottom center"), " (Z)"); + align_icon(2, AlignType::Z_MAX, GLGizmosManager::IC_ALIGN_Z_MAX, GLGizmosManager::IC_ALIGN_Z_MAX_DARK, L("Align top"), " (+Z)"); if (!m_align_to_parent) { row = 1; current_axis = -1; ImGui::SetCursorPosY(center_in_row(row, ImGui::GetTextLineHeight())); imgui_wrapper->text(_L("Distribute")); - align_icon(0, AlignType::DISTRIBUTE_X, GLGizmosManager::IC_DISTRIBUTE_X, GLGizmosManager::IC_DISTRIBUTE_X_DARK, _L("Distribute left-right") + " (X)"); - align_icon(1, AlignType::DISTRIBUTE_Y, GLGizmosManager::IC_DISTRIBUTE_Y, GLGizmosManager::IC_DISTRIBUTE_Y_DARK, _L("Distribute front-back") + " (Y)"); - align_icon(2, AlignType::DISTRIBUTE_Z, GLGizmosManager::IC_DISTRIBUTE_Z, GLGizmosManager::IC_DISTRIBUTE_Z_DARK, _L("Distribute top-bottom") + " (Z)"); + align_icon(0, AlignType::DISTRIBUTE_X, GLGizmosManager::IC_DISTRIBUTE_X, GLGizmosManager::IC_DISTRIBUTE_X_DARK, L("Distribute left-right"), " (X)"); + align_icon(1, AlignType::DISTRIBUTE_Y, GLGizmosManager::IC_DISTRIBUTE_Y, GLGizmosManager::IC_DISTRIBUTE_Y_DARK, L("Distribute front-back"), " (Y)"); + align_icon(2, AlignType::DISTRIBUTE_Z, GLGizmosManager::IC_DISTRIBUTE_Z, GLGizmosManager::IC_DISTRIBUTE_Z_DARK, L("Distribute top-bottom"), " (Z)"); } ImGui::PopStyleVar(); ImGui::SetCursorPosY(row_top(row + 1)); @@ -1384,7 +1400,7 @@ void GizmoObjectManipulation::do_render_scale_input_window(ImGuiWrapper* imgui_w ImGuiWrapper::push_combo_style(m_glcanvas.get_scale()); bool combox_changed = false; - if (render_combo(imgui_wrapper, "", modes, selection_idx, 0, coord_combo_width)) { + if (render_combo(imgui_wrapper, "", modes, selection_idx, 0, coord_combo_width, "coordinates")) { combox_changed = true; } ImGuiWrapper::pop_combo_style(); diff --git a/src/slic3r/GUI/Gizmos/GizmoObjectManipulation.hpp b/src/slic3r/GUI/Gizmos/GizmoObjectManipulation.hpp index e69ed2be3a..196daec9fe 100644 --- a/src/slic3r/GUI/Gizmos/GizmoObjectManipulation.hpp +++ b/src/slic3r/GUI/Gizmos/GizmoObjectManipulation.hpp @@ -141,7 +141,9 @@ public: void limit_scaling_ratio(Vec3d &scaling_factor) const; void on_change(const std::string& opt_key, int axis, double new_value); - bool render_combo(ImGuiWrapper *imgui_wrapper, const std::string &label, const std::vector &lines, size_t &selection_idx, float label_width, float item_width); + // `name` names the combo for automation when `label` is empty. + bool render_combo(ImGuiWrapper *imgui_wrapper, const std::string &label, const std::vector &lines, size_t &selection_idx, float label_width, float item_width, + const std::string &name = {}); void do_render_move_window(ImGuiWrapper *imgui_wrapper, std::string window_name, float x, float y, float bottom_limit); void do_render_rotate_window(ImGuiWrapper *imgui_wrapper, std::string window_name, float x, float y, float bottom_limit); void do_render_scale_input_window(ImGuiWrapper* imgui_wrapper, std::string window_name, float x, float y, float bottom_limit); diff --git a/src/slic3r/GUI/IconManager.cpp b/src/slic3r/GUI/IconManager.cpp index a014202b84..4c8b1c037d 100644 --- a/src/slic3r/GUI/IconManager.cpp +++ b/src/slic3r/GUI/IconManager.cpp @@ -1,4 +1,6 @@ #include "IconManager.hpp" +#include "GUI_App.hpp" +#include "ImGuiWrapper.hpp" #include #include #include @@ -396,7 +398,7 @@ void draw(const IconManager::Icon &icon, const ImVec2 &size, const ImVec4 &tint_ window->DC.CursorPosPrevLine.y = cursor_y; } -bool clickable(const IconManager::Icon &icon, const IconManager::Icon &icon_hover) +bool clickable(const IconManager::Icon &icon, const IconManager::Icon &icon_hover, const std::string &name) { // check of hover ImGuiWindow *window = ImGui::GetCurrentWindow(); @@ -412,16 +414,18 @@ bool clickable(const IconManager::Icon &icon, const IconManager::Icon &icon_hove // redraw normal image draw(icon); } + wxGetApp().imgui()->record_named_item(name); return ImGui::IsItemClicked(); } -bool button(const IconManager::Icon &activ, const IconManager::Icon &hover, const IconManager::Icon &disable, bool disabled) +bool button(const IconManager::Icon &activ, const IconManager::Icon &hover, const IconManager::Icon &disable, bool disabled, const std::string &name) { if (disabled) { draw(disable); + wxGetApp().imgui()->record_named_item(name); return false; } - return clickable(activ, hover); + return clickable(activ, hover, name); } } // namespace Slic3r::GUI diff --git a/src/slic3r/GUI/IconManager.hpp b/src/slic3r/GUI/IconManager.hpp index b5d86fbd6e..57c1fb6631 100644 --- a/src/slic3r/GUI/IconManager.hpp +++ b/src/slic3r/GUI/IconManager.hpp @@ -119,8 +119,9 @@ void draw(const IconManager::Icon &icon, /// /// Draw when no hover /// Draw when hover +/// Names the icon for automation (ImGuiWrapper::record_named_item()) /// True when click, otherwise False -bool clickable(const IconManager::Icon &icon, const IconManager::Icon &icon_hover); +bool clickable(const IconManager::Icon &icon, const IconManager::Icon &icon_hover, const std::string &name = {}); /// /// Use icon as button with 3 states activ hover and disabled @@ -128,8 +129,10 @@ bool clickable(const IconManager::Icon &icon, const IconManager::Icon &icon_hove /// Not disabled not hovered image /// Hovered image /// Disabled image +/// Names the button for automation (ImGuiWrapper::record_named_item()) /// True when click on enabled, otherwise False -bool button(const IconManager::Icon &activ, const IconManager::Icon &hover, const IconManager::Icon &disable, bool disabled = false); +bool button(const IconManager::Icon &activ, const IconManager::Icon &hover, const IconManager::Icon &disable, bool disabled = false, + const std::string &name = {}); } // namespace Slic3r::GUI #endif // slic3r_IconManager_hpp_ \ No newline at end of file diff --git a/src/slic3r/GUI/ImGuiWrapper.cpp b/src/slic3r/GUI/ImGuiWrapper.cpp index e2ba881ebb..69c018d1a4 100644 --- a/src/slic3r/GUI/ImGuiWrapper.cpp +++ b/src/slic3r/GUI/ImGuiWrapper.cpp @@ -582,7 +582,6 @@ void ImGuiWrapper::new_frame() if (m_new_frame_open) { return; } - m_frame_items.clear(); if (m_font_texture == 0) { init_font(true); @@ -629,7 +628,10 @@ void ImGuiWrapper::new_frame() ImDrawData* ImGuiWrapper::end_frame() { if (m_item_recording && m_frame_owner != nullptr) - m_recorded_items[m_frame_owner] = m_frame_items; + m_recorded[m_frame_owner] = m_frame; + m_frame.items.clear(); + m_frame.texts.clear(); + m_last_string_id = 0; #ifdef __APPLE__ // io.ImeWindowHandle is the focused canvas' view (GLCanvas3D::on_set_focus()). if (void* view = ImGui::GetIO().ImeWindowHandle) @@ -643,38 +645,105 @@ ImDrawData* ImGuiWrapper::end_frame() void ImGuiWrapper::set_item_recording(bool on) { m_item_recording = on; - if (ImGuiContext* ctx = ImGui::GetCurrentContext()) + // The hooks find the recorder through the context, the slot ImGui keeps for its test engine. + if (ImGuiContext* ctx = ImGui::GetCurrentContext()) { ctx->TestEngineHookItems = on; + ctx->TestEngine = on ? this : nullptr; + } if (!on) { - m_frame_items.clear(); - m_recorded_items.clear(); + m_frame = {}; + m_recorded.clear(); } } std::vector ImGuiWrapper::recorded_items(const void* owner) const { - auto it = m_recorded_items.find(owner); - return it == m_recorded_items.end() ? std::vector{} : it->second; + auto it = m_recorded.find(owner); + return it == m_recorded.end() ? std::vector{} : it->second.items; } -void ImGuiWrapper::record_item_add(unsigned id, float x0, float y0, float x1, float y1, const char* window) +std::vector ImGuiWrapper::recorded_texts(const void* owner) const +{ + auto it = m_recorded.find(owner); + return it == m_recorded.end() ? std::vector{} : it->second.texts; +} + +// The status flags of a control that reports `checked` (0 or 1, -1 for none). +static int checked_flags(int checked) +{ + return checked < 0 ? 0 : ImGuiItemStatusFlags_Checkable | (checked > 0 ? ImGuiItemStatusFlags_Checked : 0); +} + +void ImGuiWrapper::record_named_item(const std::string& name, const char* kind, int checked) +{ + if (!m_item_recording || name.empty() || ImGui::GetCurrentContext() == nullptr) + return; + if (const ImGuiID id = ImGui::GetItemID(); id == 0 || !record_item_name(id, name, kind, checked)) + record_named_item(name, kind, ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), checked); +} + +bool ImGuiWrapper::record_item_name(unsigned id, const std::string& name, const char* kind, int checked) +{ + if (!m_item_recording || name.empty()) + return false; + for (auto it = m_frame.items.rbegin(); it != m_frame.items.rend(); ++it) + if (it->id == id) { + it->name = name; + if (it->kind.empty() && kind != nullptr) + it->kind = kind; + it->flags |= checked_flags(checked); + return true; + } + return false; +} + +void ImGuiWrapper::record_named_item(const std::string& name, const char* kind, const ImVec2& min, const ImVec2& max, int checked) +{ + if (!m_item_recording || name.empty() || ImGui::GetCurrentContext() == nullptr) + return; + ImGuiWindow* window = ImGui::GetCurrentWindowRead(); + if (window == nullptr) + return; + RecordedItem item; + // Same-named controls in one ID scope (rows a loop draws without PushID) stay apart by their + // order in the frame. + const ImGuiID base = window->GetIDNoKeepAlive(name.c_str()); + item.id = base; + for (int n = 1; std::any_of(m_frame.items.begin(), m_frame.items.end(), [&](const RecordedItem& i) { return i.id == item.id; }); ++n) + item.id = ImHashData(&n, sizeof(n), base); + item.name = name; + item.kind = kind != nullptr ? kind : ""; + item.window = window->Name; + item.x = min.x, item.y = min.y, item.w = max.x - min.x, item.h = max.y - min.y; + item.flags = checked_flags(checked); + item.clipped = !ImRect(min, max).Overlaps(window->ClipRect); + m_frame.items.push_back(std::move(item)); +} + +void ImGuiWrapper::record_item_add(unsigned id, float x0, float y0, float x1, float y1, const char* window, bool clipped) { // ImGui reports an item again when it re-submits it within a frame; keep the last rectangle. - for (RecordedItem& item : m_frame_items) + for (RecordedItem& item : m_frame.items) if (item.id == id) { item.x = x0, item.y = y0, item.w = x1 - x0, item.h = y1 - y0; + item.clipped = clipped; return; } RecordedItem item; - item.id = id; - item.window = window != nullptr ? window : ""; + item.id = id; + item.window = window != nullptr ? window : ""; item.x = x0, item.y = y0, item.w = x1 - x0, item.h = y1 - y0; - m_frame_items.push_back(std::move(item)); + item.clipped = clipped; + // A clipped widget returns before it reports its label; the string its id was hashed from is that + // label. ImGui's own "#image"-style ids are not labels. + if (id == m_last_string_id && !(m_last_string.size() > 1 && m_last_string[0] == '#' && m_last_string[1] != '#')) + item.label = m_last_string; + m_frame.items.push_back(std::move(item)); } void ImGuiWrapper::record_item_info(unsigned id, const char* label, int flags) { - for (auto it = m_frame_items.rbegin(); it != m_frame_items.rend(); ++it) + for (auto it = m_frame.items.rbegin(); it != m_frame.items.rend(); ++it) if (it->id == id) { it->label = label != nullptr ? label : ""; it->flags = flags; @@ -682,6 +751,37 @@ void ImGuiWrapper::record_item_info(unsigned id, const char* label, int flags) } } +void ImGuiWrapper::record_item_value(unsigned id, const char* kind, const char* value, int flags) +{ + for (auto it = m_frame.items.rbegin(); it != m_frame.items.rend(); ++it) + if (it->id == id) { + it->kind = kind != nullptr ? kind : ""; + it->value = value != nullptr ? value : ""; + it->flags |= flags; + return; + } +} + +void ImGuiWrapper::record_text(const char* window, float x0, float y0, float x1, float y1, const char* text, const char* text_end) +{ + if (text == nullptr || text == text_end) + return; + RecordedText t; + t.window = window != nullptr ? window : ""; + t.text.assign(text, text_end != nullptr ? text_end : text + strlen(text)); + t.x = x0, t.y = y0, t.w = x1 - x0, t.h = y1 - y0; + m_frame.texts.push_back(std::move(t)); +} + +void ImGuiWrapper::record_string_id(unsigned id, const char* str, const char* str_end) +{ + m_last_string_id = id; + if (str_end != nullptr) + m_last_string.assign(str, str_end); + else + m_last_string.assign(str); +} + void ImGuiWrapper::render(ImDrawData* draw_data) { render_draw_data(draw_data); @@ -821,6 +921,8 @@ bool ImGuiWrapper::bbl_combo_with_filter(const char* label, const std::string& p ImGui::OpenPopup(label); is_new_open = true; } + // A combo to automation, which picks its options in the popup; the button shows the value. + record_named_item(label + std::strspn(label, "#"), "combo"); g.Style.ButtonTextAlign.x = ButtonTextAlignX; ImGui::PopStyleVar(); ImGui::PopStyleColor(); @@ -1045,7 +1147,7 @@ bool ImGuiWrapper::button(const wxString& label, const ImVec2 &size, bool enable // ORCA Glyph based button for correctly rendering icon size based Glyph // excludes spacings after Glyph and centers icon properly // compared to image_button this supports styling -bool ImGuiWrapper::glyph_button(wchar_t icon_char, ImVec2 icon_size) +bool ImGuiWrapper::glyph_button(wchar_t icon_char, ImVec2 icon_size, const std::string& name) { ImDrawList* draw_list = ImGui::GetWindowDrawList(); ImFont* font = ImGui::GetFont(); @@ -1062,6 +1164,7 @@ bool ImGuiWrapper::glyph_button(wchar_t icon_char, ImVec2 icon_size) ImVec2 rc_max = ImVec2(rc_min.x + width, rc_min.y + height); ImGui::Dummy(ImVec2(width, height)); + record_named_item(name, "button", rc_min, rc_max); ImGuiCol bg_color = ImGuiCol_Button; ImGuiCol border_color = ImGuiCol_Border; @@ -1403,7 +1506,7 @@ bool ImGuiWrapper::image_button(ImTextureID user_texture_id, const ImVec2& size, return image_button_ex(id, user_texture_id, size, uv0, uv1, padding, bg_col, tint_col, flags); } -bool ImGuiWrapper::image_button(const wchar_t icon, const wxString& tooltip) +bool ImGuiWrapper::image_button(const wchar_t icon, const wxString& tooltip, const std::string& name) { const ImGuiIO& io = ImGui::GetIO(); const ImTextureID tex_id = io.Fonts->TexID; @@ -1418,6 +1521,7 @@ bool ImGuiWrapper::image_button(const wchar_t icon, const wxString& tooltip) ImGui::PushStyleColor(ImGuiCol_ButtonHovered, { 0.4f, 0.4f, 0.4f, 1.0f }); ImGui::PushStyleColor(ImGuiCol_ButtonActive, { 0.25f, 0.25f, 0.25f, 1.0f }); const bool res = image_button(tex_id, size, uv0, uv1); + record_named_item(name); ImGui::PopStyleColor(3); if (!tooltip.empty() && ImGui::IsItemHovered()) @@ -3751,19 +3855,48 @@ bool IMTexture::load_from_svg_file(const std::string& filename, unsigned width, } // namespace Slic3r // ImGui's test-engine hooks (IMGUI_ENABLE_TEST_ENGINE in imconfig.h). ImGui calls them only while -// ImGuiContext::TestEngineHookItems is set, i.e. while ImGuiWrapper records items for automation. -void ImGuiTestEngineHook_ItemAdd(ImGuiContext* ctx, const ImRect& bb, ImGuiID id) +// ImGuiContext::TestEngineHookItems is set, i.e. while an ImGuiWrapper records items for automation; +// that wrapper is the context's TestEngine. +static Slic3r::GUI::ImGuiWrapper* recorder(ImGuiContext* ctx) { - if (Slic3r::GUI::ImGuiWrapper* imgui = Slic3r::GUI::wxGetApp().imgui(); imgui != nullptr && imgui->item_recording()) - imgui->record_item_add(id, bb.Min.x, bb.Min.y, bb.Max.x, bb.Max.y, ctx->CurrentWindow ? ctx->CurrentWindow->Name : nullptr); + auto* imgui = static_cast(ctx->TestEngine); + return imgui != nullptr && imgui->item_recording() ? imgui : nullptr; } -void ImGuiTestEngineHook_ItemInfo(ImGuiContext*, ImGuiID id, const char* label, ImGuiItemStatusFlags flags) +void ImGuiTestEngineHook_ItemAdd(ImGuiContext* ctx, const ImRect& bb, ImGuiID id) { - if (Slic3r::GUI::ImGuiWrapper* imgui = Slic3r::GUI::wxGetApp().imgui(); imgui != nullptr && imgui->item_recording()) + if (Slic3r::GUI::ImGuiWrapper* imgui = recorder(ctx)) { + ImGuiWindow* window = ctx->CurrentWindow; + imgui->record_item_add(id, bb.Min.x, bb.Min.y, bb.Max.x, bb.Max.y, window ? window->Name : nullptr, + window != nullptr && !bb.Overlaps(window->ClipRect)); + } +} + +void ImGuiTestEngineHook_ItemInfo(ImGuiContext* ctx, ImGuiID id, const char* label, ImGuiItemStatusFlags flags) +{ + if (Slic3r::GUI::ImGuiWrapper* imgui = recorder(ctx)) imgui->record_item_info(id, label, int(flags)); } +void ImGuiTestEngineHook_ItemValue(ImGuiContext* ctx, ImGuiID id, const char* kind, const char* value, ImGuiItemStatusFlags flags) +{ + if (Slic3r::GUI::ImGuiWrapper* imgui = recorder(ctx)) + imgui->record_item_value(id, kind, value, int(flags)); +} + +void ImGuiTestEngineHook_Text(ImGuiContext* ctx, const ImRect& bb, const char* text, const char* text_end) +{ + if (Slic3r::GUI::ImGuiWrapper* imgui = recorder(ctx)) + imgui->record_text(ctx->CurrentWindow ? ctx->CurrentWindow->Name : nullptr, bb.Min.x, bb.Min.y, bb.Max.x, bb.Max.y, text, text_end); +} + void ImGuiTestEngineHook_IdInfo(ImGuiContext*, ImGuiDataType, ImGuiID, const void*) {} -void ImGuiTestEngineHook_IdInfo(ImGuiContext*, ImGuiDataType, ImGuiID, const void*, const void*) {} + +void ImGuiTestEngineHook_IdInfo(ImGuiContext* ctx, ImGuiDataType data_type, ImGuiID id, const void* data_id, const void* data_id_end) +{ + if (data_type != ImGuiDataType_String) + return; + if (Slic3r::GUI::ImGuiWrapper* imgui = recorder(ctx)) + imgui->record_string_id(id, static_cast(data_id), static_cast(data_id_end)); +} void ImGuiTestEngineHook_Log(ImGuiContext*, const char*, ...) {} diff --git a/src/slic3r/GUI/ImGuiWrapper.hpp b/src/slic3r/GUI/ImGuiWrapper.hpp index ad7e444b2e..78c49e6054 100644 --- a/src/slic3r/GUI/ImGuiWrapper.hpp +++ b/src/slic3r/GUI/ImGuiWrapper.hpp @@ -60,16 +60,28 @@ class ImGuiWrapper public: // Automation (the MCP server) lists and clicks ImGui items, which have no window handles. While // recording is on, every item a frame adds is recorded with its id, label, window and rectangle - // (in ImGui coordinates), per canvas: the canvas calls set_frame_owner() before new_frame(), and - // end_frame() publishes the frame's items as that owner's latest. Off unless the MCP server runs; - // ImGui then skips the hooks with one branch per item. + // (in ImGui coordinates), along with the values fields show and the text the frame draws, per + // canvas: the canvas calls set_frame_owner() before new_frame(), and end_frame() publishes the + // frame's items as that owner's latest. Off unless the MCP server runs; ImGui then skips the + // hooks with one branch per item. struct RecordedItem { unsigned id = 0; std::string label; // as passed to ImGui, "##" suffix included + std::string name; // given by record_named_item(), for a control whose label names nothing std::string window; // name of the ImGui window the item belongs to + std::string kind; // slider, drag, input, multiline, combo, or a named control's kind; empty for buttons and checkboxes + std::string value; // what a field or a combo shows + float x = 0.f, y = 0.f, w = 0.f, h = 0.f; + int flags = 0; // ImGuiItemStatusFlags + bool clipped = false; // outside the visible part of its window when drawn + }; + // Text a frame draws with ImGui::Text() and the like; never an item. + struct RecordedText + { + std::string window; + std::string text; float x = 0.f, y = 0.f, w = 0.f, h = 0.f; - int flags = 0; // ImGuiItemStatusFlags }; private: @@ -95,10 +107,18 @@ private: // Keys held down, each with whether ImGui claimed its press. std::map m_key_claims; // Item recording for automation, see set_item_recording(). UI thread only. + struct RecordedFrame + { + std::vector items; + std::vector texts; + }; bool m_item_recording{ false }; const void* m_frame_owner{ nullptr }; - std::vector m_frame_items; - std::map> m_recorded_items; + RecordedFrame m_frame; + std::map m_recorded; + // The last string ImGui hashed into an id, the label of the item it is about to add. + unsigned m_last_string_id{ 0 }; + std::string m_last_string; // Whether ImGui claimed the last key-down, for the char event that follows it. std::optional m_char_claim; @@ -138,9 +158,26 @@ public: bool item_recording() const { return m_item_recording; } void set_frame_owner(const void* owner) { m_frame_owner = owner; } std::vector recorded_items(const void* owner) const; + std::vector recorded_texts(const void* owner) const; + // Names the control just drawn for automation when its ImGui label names nothing: an empty or + // "##"-only label, or no item at all (Dummy, Image, a hand-made click test). A real item (an + // image button, an empty-label combo) is named in its own record; anything else gets a record of + // its own at the last item's rectangle, or at [min, max], with the id `name` hashes to in the + // current ID scope (and its place among same-named ones there). Changes nothing ImGui does, and + // costs one branch while recording is off. + // `checked` (0 or 1) makes it a toggle that reports its state; -1 leaves it a plain control. + void record_named_item(const std::string& name, const char* kind = "button", int checked = -1); + void record_named_item(const std::string& name, const char* kind, const ImVec2& min, const ImVec2& max, int checked = -1); + // Names the item `id` drawn earlier this frame, for a control that is no longer the current + // window's last item (a combo, whose popup is the current window while it is open). Returns + // whether this frame recorded that item. + bool record_item_name(unsigned id, const std::string& name, const char* kind, int checked = -1); // Called by the ImGui test-engine hooks; not for other use. - void record_item_add(unsigned id, float x0, float y0, float x1, float y1, const char* window); + void record_item_add(unsigned id, float x0, float y0, float x1, float y1, const char* window, bool clipped); void record_item_info(unsigned id, const char* label, int flags); + void record_item_value(unsigned id, const char* kind, const char* value, int flags); + void record_text(const char* window, float x0, float y0, float x1, float y1, const char* text, const char* text_end); + void record_string_id(unsigned id, const char* str, const char* str_end); void render(ImDrawData* draw_data); // Hash of every draw list's vertices, indices and commands. static ImGuiID draw_data_signature(const ImDrawData* draw_data); @@ -180,7 +217,8 @@ public: bool bbl_button(const wxString &label, const wxString& tooltip = {}); bool button(const wxString& label, float width, float height); bool button(const wxString& label, const ImVec2 &size, bool enable); // default size = ImVec2(0.f, 0.f) - bool glyph_button(wchar_t icon_char, ImVec2 icon_size); // ORCA + // `name` names the button for automation (see record_named_item()). + bool glyph_button(wchar_t icon_char, ImVec2 icon_size, const std::string& name = {}); // ORCA bool radio_button(const wxString &label, bool active); static ImVec4 to_ImVec4(const ColorRGB &color); bool input_double(const std::string &label, const double &value, const std::string &format = "%.3f"); @@ -224,7 +262,8 @@ public: #endif // ENABLE_ENHANCED_IMGUI_SLIDER_FLOAT bool image_button(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0.0, 0.0), const ImVec2& uv1 = ImVec2(1.0, 1.0), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0.0, 0.0, 0.0, 0.0), const ImVec4& tint_col = ImVec4(1.0, 1.0, 1.0, 1.0), ImGuiButtonFlags flags = 0); - bool image_button(const wchar_t icon, const wxString& tooltip = L""); + // `name` names the button for automation (see record_named_item()). + bool image_button(const wchar_t icon, const wxString& tooltip = L"", const std::string& name = {}); // Use selection = -1 to not mark any option as selected bool combo(const std::string& label, const std::vector& options, int& selection, ImGuiComboFlags flags = 0, float label_width = 0.0f, float item_width = 0.0f); diff --git a/src/slic3r/GUI/Mcp/CanvasTarget.cpp b/src/slic3r/GUI/Mcp/CanvasTarget.cpp new file mode 100644 index 0000000000..d88f6c2736 --- /dev/null +++ b/src/slic3r/GUI/Mcp/CanvasTarget.cpp @@ -0,0 +1,182 @@ +#include "CanvasTarget.hpp" + +#include "libslic3r/AABBMesh.hpp" +#include "libslic3r/BoundingBox.hpp" +#include "libslic3r/Polygon.hpp" +#include "slic3r/GUI/MeshUtils.hpp" + +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +namespace { + +struct RayHit +{ + double t; // distance along the ray + Vec3d p; + Vec3d n; // the hit triangle's unit normal +}; + +// The points where a scene-space ray meets a mesh placed by `world`, nearest first. +std::vector ray_hits(const AABBMesh& mesh, const Transform3d& world, const Vec3d& origin, const Vec3d& dir) +{ + const Transform3d inverse = world.inverse(); + std::vector out; + for (const AABBMesh::hit_result& hit : mesh.query_ray_hits(inverse * origin, (inverse.linear() * dir).normalized())) + if (hit.is_hit()) { + const Vec3d p = world * hit.position(); + out.push_back({(p - origin).dot(dir), p, (inverse.linear().transpose() * hit.normal()).normalized()}); + } + std::sort(out.begin(), out.end(), [](const RayHit& a, const RayHit& b) { return a.t < b.t; }); + return out; +} + +} // namespace + +std::optional project_point(const CanvasView& view, const Vec3d& point) +{ + const Eigen::Vector4d clip = view.projection.matrix() * view.view.matrix() * Eigen::Vector4d(point.x(), point.y(), point.z(), 1.); + if (clip.w() <= 0.) + return std::nullopt; + const Vec3d ndc = clip.head<3>() / clip.w(); + if (std::abs(ndc.x()) > 1. || std::abs(ndc.y()) > 1. || std::abs(ndc.z()) > 1.) + return std::nullopt; + const double x = view.viewport[0] + 0.5 * (ndc.x() + 1.) * view.viewport[2]; + const double y = view.viewport[1] + 0.5 * (1. - ndc.y()) * view.viewport[3]; + return Vec2d(x / view.scale, y / view.scale); +} + +std::pair pixel_ray(const CanvasView& view, const Vec2d& pixel) +{ + const double x = 2. * (pixel.x() * view.scale - view.viewport[0]) / view.viewport[2] - 1.; + const double y = 1. - 2. * (pixel.y() * view.scale - view.viewport[1]) / view.viewport[3]; + const Eigen::Matrix4d inverse = (view.projection.matrix() * view.view.matrix()).inverse(); + Eigen::Vector4d near_point = inverse * Eigen::Vector4d(x, y, -1., 1.); + Eigen::Vector4d far_point = inverse * Eigen::Vector4d(x, y, 1., 1.); + const Vec3d origin = near_point.head<3>() / near_point.w(); + const Vec3d end = far_point.head<3>() / far_point.w(); + return {origin, (end - origin).normalized()}; +} + +std::optional spot_point(const AABBMesh& mesh, const Transform3d& world, const std::string& spot) +{ + BoundingBoxf3 box; + for (const Vec3f& v : mesh.vertices()) + box.merge(world * v.cast()); + if (!box.defined) + return std::nullopt; + const Vec3d c = box.center(); + const double margin = 1. + box.size().maxCoeff(); + Vec3d origin, dir; + if (spot == "top") + origin = {c.x(), c.y(), box.max.z() + margin}, dir = -Vec3d::UnitZ(); + else if (spot == "bottom") + origin = {c.x(), c.y(), box.min.z() - margin}, dir = Vec3d::UnitZ(); + else if (spot == "front") + origin = {c.x(), box.min.y() - margin, c.z()}, dir = Vec3d::UnitY(); + else if (spot == "back") + origin = {c.x(), box.max.y() + margin, c.z()}, dir = -Vec3d::UnitY(); + else if (spot == "left") + origin = {box.min.x() - margin, c.y(), c.z()}, dir = Vec3d::UnitX(); + else if (spot == "right") + origin = {box.max.x() + margin, c.y(), c.z()}, dir = -Vec3d::UnitX(); + else + return std::nullopt; + const auto hits = ray_hits(mesh, world, origin, dir); + if (hits.empty()) + return std::nullopt; + return hits.front().p; +} + +std::string check_surface(const Vec3d& point, + const std::pair& ray, + const std::vector& meshes, + const ClippingPlane* clip, + const std::vector& beds, + double tolerance) +{ + const auto& [origin, dir] = ray; + const auto on_bed = [&](const Vec3d& p) { + return std::any_of(beds.begin(), beds.end(), [&](const Polygon& bed) { return bed.contains(Point::new_scale(p.x(), p.y())); }); + }; + // On the target's surface: the nearest point of its mesh is within tolerance. Not demanded of + // the ray's hit, which can slip between two triangles when it passes along their shared edge. + double off = std::numeric_limits::infinity(); + bool clipped_target = false; + for (const SurfaceMesh& m : meshes) + if (m.target && m.mesh != nullptr) { + const Transform3d inverse = m.world.inverse(); + int face = -1; + Vec3d closest; + m.mesh->squared_distance(inverse * point, face, closest); + off = std::min(off, (m.world * closest - point).norm()); + clipped_target = clipped_target || m.clipped; + } + if (off > tolerance) + return "the point is not on the part's surface"; + // A part sunk into the bed is drawn see-through below it, and clicks there do not reach it. + if (point.z() < -tolerance && on_bed(point)) + return "the point is below the bed"; + // Within the tolerance of the cut, a click can land on either side of it. + if (clipped_target && clip != nullptr && clip->distance(point) < tolerance) + return "the point is on the side of the clipping plane that is cut away"; + + // What the ray meets, nearest first: each mesh's surfaces (a clipped mesh's only where the plane + // keeps them) and the bed. + struct Hit + { + double t; + Vec3d p; + Vec3d n; // the hit triangle's unit normal + const SurfaceMesh* mesh; // null for the bed + }; + std::vector hits; + for (const SurfaceMesh& m : meshes) { + if (m.mesh == nullptr) + continue; + for (const RayHit& h : ray_hits(*m.mesh, m.world, origin, dir)) + if (!(m.clipped && clip != nullptr && clip->is_point_clipped(h.p))) + hits.push_back({h.t, h.p, h.n, &m}); + } + if (std::abs(dir.z()) > 1e-9) { + const double t = -origin.z() / dir.z(); + const Vec3d p = origin + t * dir; + if (t > 0. && on_bed(p)) + hits.push_back({t, p, Vec3d::UnitZ(), nullptr}); + } + std::sort(hits.begin(), hits.end(), [](const Hit& a, const Hit& b) { return a.t < b.t; }); + + // The first thing the ray meets is the part, within the slack of the point, on a triangle whose + // plane holds the point: the ray through a rounded pixel may meet the point's own surface nearer + // to the camera or beyond it (a slope), but not another one (a face past an edge, a layer above, + // the near side of a thin wall). + const double along = (point - origin).dot(dir); + const double slack = tolerance + 2. * (point - origin - along * dir).norm(); + for (const Hit& hit : hits) { + // Not `near`: windows.h defines that as a macro. + const bool close_by = hit.mesh != nullptr && hit.mesh->target && (hit.p - point).norm() <= slack; + if (close_by && std::abs(hit.n.dot(point - hit.p)) <= tolerance) + return {}; + if (hit.t < along - tolerance) { + if (hit.mesh == nullptr) + return "the bed is in front of the point"; + if (hit.mesh->target) + return "a nearer surface of the same part is in front of the point"; + return (hit.mesh->name.empty() ? std::string("another part or object") : hit.mesh->name) + " is in front of the point"; + } + if (hit.mesh == nullptr) + return "the click at the point's pixel lands on the bed beside the part"; + if (!hit.mesh->target) + return "the click at the point's pixel lands on " + + (hit.mesh->name.empty() ? std::string("another part or object") : hit.mesh->name) + " beside the part"; + if (close_by) + return "the click at the point's pixel lands on another face of the part"; + return "the click at the point's pixel lands on the part away from the point"; + } + return "the click at the point's pixel misses the part"; +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/CanvasTarget.hpp b/src/slic3r/GUI/Mcp/CanvasTarget.hpp new file mode 100644 index 0000000000..b86aa47e43 --- /dev/null +++ b/src/slic3r/GUI/Mcp/CanvasTarget.hpp @@ -0,0 +1,71 @@ +#pragma once + +#include "libslic3r/Point.hpp" +#include "libslic3r/Polygon.hpp" + +#include +#include +#include +#include +#include + +namespace Slic3r { +class AABBMesh; +namespace GUI { +class ClippingPlane; +namespace Mcp { + +// ui_mouse aims at points of the model instead of pixels guessed from a screenshot: a point is +// projected through the camera the canvas was last drawn with, and the ray a click there casts is +// checked to land on that point's mesh. Pure functions of the camera and the meshes, so they are +// tested without the app. + +// The camera a canvas was last drawn with. +struct CanvasView +{ + Transform3d view = Transform3d::Identity(); + Transform3d projection = Transform3d::Identity(); + std::array viewport{0, 0, 0, 0}; // physical pixels + double scale = 1.; // physical pixels per logical pixel +}; + +// The logical canvas pixel that shows `point` (scene coordinates), or nullopt when the point is +// outside what the camera shows: beside the canvas, behind the camera, or before its near or beyond +// its far plane. +std::optional project_point(const CanvasView& view, const Vec3d& point); + +// The ray a click at logical pixel `pixel` casts: its origin on the near plane and unit direction. +std::pair pixel_ray(const CanvasView& view, const Vec2d& pixel); + +// Where a ray from outside the mesh's displayed bounding box, along the axis `spot` names and +// through the box's centre, first meets the mesh: "top" looks down, "bottom" up, "front" from -Y, +// "back" from +Y, "left" from -X, "right" from +X. Nullopt when the ray misses the mesh or `spot` +// names no side. +std::optional spot_point(const AABBMesh& mesh, const Transform3d& world, const std::string& spot); + +// A mesh as the scene shows it, for check_surface(). +struct SurfaceMesh +{ + const AABBMesh* mesh = nullptr; + Transform3d world = Transform3d::Identity(); + bool target = false; + bool clipped = false; // the clipping plane cuts it (the open gizmo's object) + std::string name; // what a reason calls it, "object 1 part 0" +}; + +// Why a click along `ray`, the ray through the pixel the click goes to, would not land on the target +// mesh at `point`, or empty when it would. `point` must lie on a target mesh, above the bed (the plane +// z = 0 inside one of the `beds`, each plate's outline, scaled) and on the side of `clip` it keeps +// when that mesh is clipped. The first thing the ray meets among `meshes` (clipped ones only where +// `clip` keeps them) and on the beds must be a target mesh near `point`: within `tolerance` plus twice +// the ray's distance from `point`, which a whole pixel adds, on a triangle whose plane holds `point` +// within `tolerance`. So on a slope the click may meet the point's surface a little nearer to the +// camera or beyond, but not another surface. +std::string check_surface(const Vec3d& point, + const std::pair& ray, + const std::vector& meshes, + const ClippingPlane* clip, + const std::vector& beds, + double tolerance); + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpService.cpp b/src/slic3r/GUI/Mcp/McpService.cpp index 8b46130d05..a329b97a3b 100644 --- a/src/slic3r/GUI/Mcp/McpService.cpp +++ b/src/slic3r/GUI/Mcp/McpService.cpp @@ -283,6 +283,8 @@ void McpService::stop() m_modals->pop_rules(layer); m_script_rule_layers.clear(); } + if (m_inspector) + m_inspector->release_held(nullptr); SyntheticInput::clear(); if (wxTheApp != nullptr) if (ImGuiWrapper* imgui = wxGetApp().imgui()) @@ -330,20 +332,48 @@ void McpService::begin_script_scope(const std::string& job) } void McpService::end_script_scope(const std::string& job) +{ + { + std::lock_guard lock(m_rules_mutex); + auto it = m_script_rule_layers.find(job); + if (it == m_script_rule_layers.end()) + return; + if (m_modals) + for (int layer : it->second) + m_modals->pop_rules(layer); + m_script_rule_layers.erase(it); + } + // Found again on the UI thread: the service may be gone by the time the closure runs. + if (m_dispatcher && !m_stopping) + m_dispatcher->post([job] { + if (McpService* service = wxGetApp().mcp_service(); service != nullptr && service->m_inspector) + service->m_inspector->release_held(&job); + }); +} + +std::string McpService::script_owner(const std::vector& ancestry) const { std::lock_guard lock(m_rules_mutex); - auto it = m_script_rule_layers.find(job); - if (it == m_script_rule_layers.end()) - return; - if (m_modals) - for (int layer : it->second) - m_modals->pop_rules(layer); - m_script_rule_layers.erase(it); + for (const std::string& job : ancestry) + if (m_script_rule_layers.count(job) != 0) + return job; + return {}; +} + +bool McpService::endpoint_open() const +{ + std::lock_guard lock(m_rules_mutex); + return m_endpoint_open; } void McpService::stop_serving() { m_port_held_by_other = false; + // So does a press a client's ui_mouse left held. + if (m_inspector) { + const std::string client; + m_inspector->release_held(&client); + } { // A client's rules end with its endpoint; a person using the app afterwards must not have // dialogs answered for them. diff --git a/src/slic3r/GUI/Mcp/McpService.hpp b/src/slic3r/GUI/Mcp/McpService.hpp index 19ffd33b5f..25be98ef8f 100644 --- a/src/slic3r/GUI/Mcp/McpService.hpp +++ b/src/slic3r/GUI/Mcp/McpService.hpp @@ -97,9 +97,15 @@ public: // closes: with no endpoint open (the server turned off meanwhile), a client's rules are refused. // Returns "script" or "session". Any thread. std::string set_auto_answer(std::vector rules, const std::vector& ancestry); - // run_script brackets its steps with these. + // run_script brackets its steps with these. A mouse press the script left held is released + // when it ends. void begin_script_scope(const std::string& job); void end_script_scope(const std::string& job); + // The job of the nearest running script in `ancestry`, or "" for a client's own call. Any thread. + std::string script_owner(const std::vector& ancestry) const; + // Whether clients can reach the server: false from stop_serving() until the endpoint opens again. + // A client's call still running then must not leave state behind that the closing ended. Any thread. + bool endpoint_open() const; // Where screenshots and script outputs go when no path is given. boost::filesystem::path output_dir() const; @@ -141,7 +147,7 @@ private: std::shared_ptr m_gate; std::unique_ptr m_inspector; - std::mutex m_rules_mutex; + mutable std::mutex m_rules_mutex; std::map> m_script_rule_layers; // running script job -> layers int m_session_rule_layer = 0; bool m_endpoint_open = false; diff --git a/src/slic3r/GUI/Mcp/McpToolsApp.cpp b/src/slic3r/GUI/Mcp/McpToolsApp.cpp index 81481426d1..61961403b3 100644 --- a/src/slic3r/GUI/Mcp/McpToolsApp.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsApp.cpp @@ -7,8 +7,12 @@ #include "McpTools.hpp" #include "McpTypes.hpp" #include "ModalTracker.hpp" +#include "UiInspector.hpp" +#include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/GUI_App.hpp" +#include "slic3r/GUI/Gizmos/GLGizmosManager.hpp" +#include "slic3r/GUI/Jobs/Worker.hpp" #include "slic3r/GUI/MainFrame.hpp" #include "slic3r/GUI/Notebook.hpp" #include "slic3r/GUI/NotificationManager.hpp" @@ -125,6 +129,15 @@ json app_state(McpService& service) PartPlateList& plates = plater->get_partplate_list(); state["plates"] = {{"count", plates.get_plate_count()}, {"current", plates.get_curr_plate_index()}}; + // The open gizmo, on the canvas shown first. + state["gizmo"] = nullptr; + std::vector canvases = live_canvases(); + std::stable_partition(canvases.begin(), canvases.end(), [&](GLCanvas3D* c) { return c == plater->get_current_canvas3D(); }); + for (GLCanvas3D* c : canvases) + if (const auto type = c->get_gizmos_manager().get_current_type(); type != GLGizmosManager::Undefined) { + state["gizmo"] = {{"name", gizmo_name(type)}, {"canvas", canvas_name(c)}}; + break; + } state["objects"] = plater->model().objects.size(); state["slicing"] = plater->is_slicing_any(); @@ -148,7 +161,13 @@ bool condition_holds(McpService& service, const std::string& condition, const st if (service.modals().any_open() || service.jobs().any_running_except(own_jobs)) return false; Plater* plater = wxGetApp().plater(); - return plater == nullptr || (!plater->is_slicing_any() && plater->get_ui_job_worker().is_idle()); + if (plater == nullptr) + return true; + if (plater->is_slicing_any() || !plater->get_ui_job_worker().is_idle()) + return false; + // Gizmos working in the background (Simplify's calculation, a texture preview). + const auto canvases = live_canvases(); + return std::none_of(canvases.begin(), canvases.end(), [](GLCanvas3D* c) { return c->get_gizmos_manager().is_busy(); }); } throw ToolFailure("Unknown condition " + condition); } @@ -162,14 +181,16 @@ void register_app_tools(McpService& service) reg.add(inspect_tool( "get_state", "Get app state", "Snapshot of OrcaSlicer: version, platform, whether it is ready, current tab and mode, project, selected printer/process/" - "filament presets, plates, object count, slicing state, open modal dialogs, notifications and running jobs. Call it " + "filament presets, plates, object count, slicing state, the open gizmo, open modal dialogs, notifications and running " + "jobs. Call it " "first and whenever you are unsure what the app is doing.", object_schema({}), [&service](const json&, ToolContext& ctx) { return ToolResult::ok(ctx.run_ui([&service] { return app_state(service); })); })); ToolDef wait = inspect_tool( "wait", "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), \"dialog\" / \"no_dialog\", or \"job\" with a job id returned by " + "no running job, nothing slicing or arranging, no gizmo working in the background), \"dialog\" / \"no_dialog\", or " + "\"job\" with a job id returned by " "an earlier call - then the reply is that job's result. Returns {satisfied:false} on timeout; call it again.", object_schema({{"for", enum_prop({"ready", "idle", "dialog", "no_dialog", "job"}, "What to wait for.")}, {"job", prop("string", "Job id, for \"job\".")}, diff --git a/src/slic3r/GUI/Mcp/McpToolsScene.cpp b/src/slic3r/GUI/Mcp/McpToolsScene.cpp index bc41333e0f..879ca5115c 100644 --- a/src/slic3r/GUI/Mcp/McpToolsScene.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsScene.cpp @@ -1,6 +1,7 @@ // list_objects, select, transform, slice and cancel: the model on the plates, and the slice // operation, which reports its own outcome per plate (see McpOperations). +#include "CanvasTarget.hpp" #include "JobRegistry.hpp" #include "libslic3r/Config.hpp" #include "libslic3r/Point.hpp" @@ -8,6 +9,8 @@ #include "McpService.hpp" #include "McpTools.hpp" #include "McpTypes.hpp" +#include "slic3r/GUI/3DScene.hpp" +#include "slic3r/GUI/Camera.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/GUI_App.hpp" @@ -19,9 +22,14 @@ #include "slic3r/GUI/Selection.hpp" #include "libslic3r/BoundingBox.hpp" +#include "libslic3r/EmbossShape.hpp" #include "libslic3r/GCode/GCodeProcessor.hpp" #include "libslic3r/Geometry.hpp" #include "libslic3r/Model.hpp" +#include "libslic3r/TextConfiguration.hpp" +#include "libslic3r/TextureDisplacement.hpp" +#include "libslic3r/TriangleMesh.hpp" +#include "libslic3r/TriangleSelector.hpp" #include "libslic3r/Utils.hpp" #include @@ -64,15 +72,106 @@ const char* volume_type_name(ModelVolumeType type) } } -// The Prepare view and its selection: object operations act on the 3D view. -void show_prepare() +// 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.select_view_3D("3D"); if (MainFrame* mf = wxGetApp().mainframe) mf->select_tab(TAB_ID_PREPARE); } + return *plater.canvas3D(); +} + +// Facets painted in each state of an annotation: [none, state 1, state 2, ...], empty when unpainted. +std::vector painted_facets(const FacetsAnnotation& paint, const ModelVolume& volume) +{ + std::vector out; + if (paint.empty()) + return out; + std::vector per_state; + paint.get_facets(volume, per_state); + for (const indexed_triangle_set& its : per_state) + out.push_back(its.indices.size()); + return out; +} + +std::size_t painted_in(const std::vector& counts, EnforcerBlockerType state) +{ + return std::size_t(state) < counts.size() ? counts[std::size_t(state)] : 0; +} + +// A part as list_objects describes it: its mesh, what is painted on it, and what a text or SVG part +// was made from. +json volume_info(const ModelVolume& v, std::size_t index) +{ + const TriangleMesh& mesh = v.mesh(); + json out{{"index", index}, + {"name", v.name}, + {"type", volume_type_name(v.type())}, + {"triangles", mesh.its.indices.size()}, + {"mesh_volume", std::round(its_volume(mesh.its) * 1000.) / 1000.}}; + json painted = json::object(); + if (const auto c = painted_facets(v.supported_facets, v); !c.empty()) + painted["supports"] = {{"enforcers", painted_in(c, EnforcerBlockerType::ENFORCER)}, {"blockers", painted_in(c, EnforcerBlockerType::BLOCKER)}}; + if (const auto c = painted_facets(v.seam_facets, v); !c.empty()) + painted["seam"] = {{"enforcers", painted_in(c, EnforcerBlockerType::ENFORCER)}, {"blockers", painted_in(c, EnforcerBlockerType::BLOCKER)}}; + if (const auto c = painted_facets(v.fuzzy_skin_facets, v); !c.empty()) + painted["fuzzy_skin"] = painted_in(c, EnforcerBlockerType::FUZZY_SKIN); + if (const auto c = painted_facets(v.mmu_segmentation_facets, v); !c.empty()) { + json mmu = json::object(); + for (std::size_t state = 1; state < c.size(); ++state) + if (c[state] > 0) + mmu[std::to_string(state)] = c[state]; // filament (extruder) number + painted["mmu"] = std::move(mmu); + } + if (!v.texture_displacement_layers.empty()) { + json layers = json::array(); + for (const TextureDisplacementLayer& layer : v.texture_displacement_layers) { + json l{{"slot", layer.slot}, {"name", layer.name}, {"path", layer.path}, {"depth_mm", layer.depth_mm}}; + if (layer.slot >= 0 && layer.slot < int(TEXTURE_DISPLACEMENT_MAX_LAYERS)) + l["painted"] = painted_in(painted_facets(v.texture_displacement_facet(layer.slot), v), EnforcerBlockerType::ENFORCER); + layers.push_back(std::move(l)); + } + painted["texture"] = std::move(layers); + } + if (!painted.empty()) + out["painted"] = std::move(painted); + if (v.text_configuration) { + const EmbossStyle& style = v.text_configuration->style; + out["text"] = {{"text", v.text_configuration->text}, + {"style", style.name}, + {"font", style.prop.face_name ? *style.prop.face_name : style.path}}; + } + if (v.emboss_shape && v.emboss_shape->svg_file) + out["svg"] = {{"path", v.emboss_shape->svg_file->path}, {"path_in_3mf", v.emboss_shape->svg_file->path_in_3mf}}; + return out; +} + +// The rectangle of logical canvas pixels an instance covers in the shown 3D view, or null when none +// of it is on screen. +json screen_rect(GLCanvas3D& canvas, int object, int instance) +{ + BoundingBoxf3 box; + for (const GLVolume* v : canvas.get_volumes().volumes) + if (v->object_idx() == object && v->instance_idx() == instance && !v->is_wipe_tower) + box.merge(v->transformed_bounding_box()); + if (!box.defined) + return nullptr; + const Camera& camera = wxGetApp().plater()->get_camera(); + CanvasView view{camera.get_view_matrix(), camera.get_projection_matrix(), camera.get_viewport(), canvas.get_scale()}; + BoundingBoxf rect; + for (int corner = 0; corner < 8; ++corner) + if (const auto p = project_point(view, Vec3d(corner & 1 ? box.max.x() : box.min.x(), corner & 2 ? box.max.y() : box.min.y(), + corner & 4 ? box.max.z() : box.min.z()))) + rect.merge(*p); + if (!rect.defined) + return nullptr; + return {std::lround(rect.min.x()), std::lround(rect.min.y()), std::lround(rect.size().x()), std::lround(rect.size().y())}; } json list_objects(const json& args) @@ -81,6 +180,13 @@ json list_objects(const json& args) PartPlateList& plates = plater.get_partplate_list(); const ModelObjectPtrs& objects = plater.model().objects; const int only_plate = arg_int(args, "plate", -1); + // Screen rectangles are of the 3D view shown, Prepare's or the assemble view's. + GLCanvas3D* canvas = nullptr; + 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)"); + } json items = json::array(); for (size_t i = 0; i < objects.size(); ++i) { const ModelObject* o = objects[i]; @@ -97,12 +203,14 @@ json list_objects(const json& args) {"rotation_deg", vec3(Vec3d(Geometry::rad2deg(rot.x()), Geometry::rad2deg(rot.y()), Geometry::rad2deg(rot.z())))}, {"scale", vec3(inst->get_scaling_factor())}, {"printable", inst->printable}}); + if (canvas != nullptr) + instances.back()["screen"] = screen_rect(*canvas, int(i), int(j)); } if (!on_plate) continue; json volumes = json::array(); for (size_t v = 0; v < o->volumes.size(); ++v) - volumes.push_back({{"index", v}, {"name", o->volumes[v]->name}, {"type", volume_type_name(o->volumes[v]->type())}}); + volumes.push_back(volume_info(*o->volumes[v], v)); const BoundingBoxf3 bb = o->instance_bounding_box(0); json overrides = json::array(); for (const std::string& key : o->config.keys()) @@ -112,6 +220,7 @@ json list_objects(const json& args) {"instances", std::move(instances)}, {"volumes", std::move(volumes)}, {"bbox", {{"min", vec3(bb.min)}, {"max", vec3(bb.max)}, {"size", vec3(bb.size())}}}, + {"brim_ears", o->brim_points.size()}, {"overrides", std::move(overrides)}}); } json out = page(items, args, 200); @@ -119,11 +228,9 @@ json list_objects(const json& args) return out; } -json selection_summary() +json selection_summary(const Selection& sel) { - Plater& plater = ui_plater(); - const Selection& sel = plater.get_selection(); - json out{{"empty", sel.is_empty()}}; + json out{{"empty", sel.is_empty()}}; if (!sel.is_empty()) { out["object"] = sel.get_object_idx(); out["instance"] = sel.get_instance_idx(); @@ -171,17 +278,20 @@ void register_scene_tools(McpService& service) reg.add(inspect_tool( "list_objects", "List objects", - "Objects in the project with their instances (plate, position, rotation in degrees, scale), parts and modifiers, " - "bounding box and the settings they override. Indices are what select, transform and the object/volume settings " + "Objects in the project with their instances (plate, position, rotation in degrees, scale), parts and modifiers " + "(triangle count and mesh volume in 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), bounding box, brim ear count and " + "the settings they override. Indices are what select, transform, ui_mouse targets and the object/volume settings " "scopes take.", object_schema({{"plate", {{"type", "integer"}, {"minimum", 0}, {"description", "Only objects on this plate."}}}, + {"screen", prop("boolean", "Add each instance's rectangle in the shown 3D view, logical pixels [x, y, w, h].")}, {"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 500}}}, {"offset", {{"type", "integer"}, {"minimum", 0}}}}), [](const json& args, ToolContext& ctx) { return ToolResult::ok(ctx.run_ui([&] { return list_objects(args); })); })); reg.add(mutate_tool( "select", "Select objects", - "Select objects, instances or parts in the 3D view (switching to Prepare), as clicking them would. Give 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 volumes ([[object, part], ...]); add keeps the current selection; all / " "none select everything or nothing.", object_schema({{"objects", array_prop({{"type", "integer"}}, "Object indices.")}, @@ -192,17 +302,26 @@ void register_scene_tools(McpService& service) {"none", prop("boolean", "Clear the selection.")}}), [](const json& args, ToolContext& ctx) { json out = ctx.run_ui([&] { - Plater& plater = ui_plater(); - show_prepare(); + Plater& plater = ui_plater(); + GLCanvas3D& canvas = object_canvas(); + Selection& sel = canvas.get_selection(); + const bool assemble = &canvas == plater.get_assmeble_canvas3D(); if (arg_bool(args, "none", false)) { - plater.deselect_all(); - return selection_summary(); + if (assemble) + sel.remove_all(); + else + plater.deselect_all(); + canvas.set_as_dirty(); + return selection_summary(sel); } if (arg_bool(args, "all", false)) { - plater.select_all(); - return selection_summary(); + if (assemble) + sel.add_all(); + else + plater.select_all(); + canvas.set_as_dirty(); + return selection_summary(sel); } - Selection& sel = plater.canvas3D()->get_selection(); const size_t count = plater.model().objects.size(); bool first = !arg_bool(args, "add", false); auto check_obj = [&](int o) { @@ -225,8 +344,8 @@ void register_scene_tools(McpService& service) first = false; } wxGetApp().obj_list()->update_selections(); - plater.canvas3D()->set_as_dirty(); - return selection_summary(); + canvas.set_as_dirty(); + return selection_summary(sel); }); settle(ctx); return ToolResult::ok(out); diff --git a/src/slic3r/GUI/Mcp/McpToolsUi.cpp b/src/slic3r/GUI/Mcp/McpToolsUi.cpp index 186e1a5b1f..e7a3f96969 100644 --- a/src/slic3r/GUI/Mcp/McpToolsUi.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsUi.cpp @@ -2,6 +2,7 @@ // dialogs and run JavaScript in web views. #include "JobRegistry.hpp" +#include "McpPaths.hpp" #include "McpService.hpp" #include "McpTools.hpp" #include "McpTypes.hpp" @@ -10,6 +11,10 @@ #include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/GUI_App.hpp" +#include "slic3r/GUI/Gizmos/GLGizmoSVG.hpp" +#include "slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.hpp" +#include "slic3r/GUI/Gizmos/GLGizmosManager.hpp" +#include "slic3r/GUI/Jobs/Worker.hpp" #include "slic3r/GUI/MainFrame.hpp" #include "slic3r/GUI/Plater.hpp" @@ -48,7 +53,7 @@ const json kTargetSchema = {{"type", json::array({"string", "object"})}, {"description", "A ref from the latest ui_snapshot (\"w12\") or a locator: {label, class, name, within, index} for " "widgets, {option:\"layer_height\"} for a setting field, {menu:\"File>Export>Export G-code\"}, {gltoolbar:\"arrange\"}, {gizmo:\"Move\"}, or " - "{imgui:\"label\", window?, canvas?}."}}; + "{imgui:\"label\", imgui_name?:\"name\", window?, canvas?, index?} for an ImGui item, by its label, its name or both."}}; const json kModifiersSchema = {{"type", "array"}, {"items", {{"type", "string"}, {"enum", {"ctrl", "cmd", "rawctrl", "shift", "alt"}}}}, @@ -203,7 +208,8 @@ void register_ui_tools(McpService& service) "ui_snapshot", "List the GUI", "Describe what is on screen as an indented tree, one element per line with a ref: wx widgets of every shown window " "(buttons, fields, checkboxes, combos, tabs, labels), the main menus, the 3D canvas's toolbar items and gizmos, and " - "the ImGui items drawn in the last frame. Pass the refs to ui_click / ui_input / ui_key. Refs go stale when the " + "each ImGui panel drawn in the last frame with its items (kind, value, name) and text. Pass the refs to ui_click / " + "ui_input / ui_key. Refs go stale when the " "element goes away; take a new snapshot then. root: \"all\" (default), \"main\", \"dialog\" (topmost modal) or a " "window's ref. query filters by label, value, name or class. Prefer run_action and the typed tools when one fits.", object_schema({{"root", prop("string", "all | main | dialog | .")}, @@ -232,7 +238,9 @@ void register_ui_tools(McpService& service) reg.add(recover_input_tool( "ui_click", "Click an element", "Activate a GUI element: menu items, buttons, checkboxes, toggles, radio buttons, toolbar items and gizmos are activated " - "the way their owners expect; other widgets and ImGui items get a synthesized mouse click. With x/y on a 3D canvas " + "the way their owners expect (a gizmo as its toolbar icon: it opens, a second click closes it, and Text on an object " + "with no text creates a text part and replies created); other widgets and ImGui items get a synthesized mouse click, " + "after the item is scrolled into view. With x/y on a 3D canvas " "target, clicks that point (logical pixels from the canvas's top left). Modifiers are seen by the 3D canvas, the " "object list and handlers that read the event. A click that opens a dialog returns blocked_by_dialog with the job.", object_schema({{"target", kTargetSchema}, @@ -250,14 +258,33 @@ void register_ui_tools(McpService& service) o.at_point = args.contains("x") || args.contains("y"); o.x = arg_int(args, "x", 0); o.y = arg_int(args, "y", 0); - json locator; + json locator; + GLCanvas3D* canvas = nullptr; + int gizmo = -1; json out = ctx.run_ui([&] { UiTarget t = service.inspector().resolve(args["target"]); locator = service.inspector().locator_for(t); guard_target(service, target_window(t)); + canvas = t.canvas; + gizmo = t.gizmo; return service.inspector().click(t, o); }); journal_with_locator(ctx, args, locator); + if (out.value("creating", false)) { + // The Text gizmo's icon with no text selected queued a job that creates a text part + // and opens the gizmo when it ends. + out = poll_ui( + ctx, + [&]() -> json { + if (!ui_plater().get_ui_job_worker().is_idle()) + return json(); + const auto canvases = live_canvases(); + const bool active = std::find(canvases.begin(), canvases.end(), canvas) != canvases.end() && + int(canvas->get_gizmos_manager().get_current_type()) == gizmo; + return json{{"gizmo", out["gizmo"]}, {"created", true}, {"active", active}}; + }, + std::chrono::seconds(30), "the new text part"); + } settle(ctx); return ToolResult::ok(out); })); @@ -266,8 +293,11 @@ void register_ui_tools(McpService& service) "ui_input", "Set a control's value", "Set the text, number, selection or checked state of a control and send the event a person's edit would: text fields " "(submit:true also presses Enter and leaves the field, which is when Orca's setting fields commit), spin controls, " - "sliders, choice / combo / list boxes (by option text or index), checkboxes and toggles (true/false). On an ImGui " - "field it clicks, selects all and types. For settings, set_settings is more reliable.", + "sliders, choice / combo / list boxes (by option text or index), checkboxes and toggles (true/false). An ImGui item " + "is set by its kind and its 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, a checkbox, radio or toggle " + "clicked when it differs. For " + "settings, set_settings 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).")}}, @@ -312,35 +342,114 @@ void register_ui_tools(McpService& service) return ToolResult::ok(out); })); + const json target_schema = { + {"type", "object"}, + {"description", "A point of the model: {object, instance (default 0), volume (part, default 0), and point [x, y, z] in " + "the part's own mesh coordinates (frame \"volume\", the default) or the scene's (frame \"world\"), or " + "spot: top | bottom | front | back | left | right, where a ray along that axis first meets the part}."}, + {"properties", + {{"object", {{"type", "integer"}, {"minimum", 0}}}, + {"instance", {{"type", "integer"}, {"minimum", 0}}}, + {"volume", {{"type", "integer"}, {"minimum", 0}}}, + {"point", array_prop({{"type", "number"}}, "[x, y, z] mm")}, + {"frame", enum_prop({"volume", "world"}, "Default volume.")}, + {"spot", enum_prop({"top", "bottom", "front", "back", "left", "right"}, "A side of the part.")}}}, + {"required", {"object"}}, + {"additionalProperties", false}}; + const json pixel_or_target = {{"type", json::array({"array", "object"})}, + {"description", "A canvas pixel [x, y] or a point of the model, as for at."}}; reg.add(mutate_tool( "ui_mouse", "Mouse gesture on the 3D view", - "Synthesize a mouse gesture on a 3D canvas at logical pixel coordinates from its top left: move, down, up, click, " - "drag (from x,y to `to`, in `steps` moves; the left button rotates the camera, right or middle pans, on an object it " - "moves it) or wheel (delta in notches, positive zooms in). A down keeps its button held, so moves drag with it, " - "until an up or another gesture. Coordinates come from a canvas screenshot divided by the screen scale, or from " - "ui_snapshot's ImGui item rectangles.", + "Synthesize a mouse gesture on a 3D canvas, as a person's would: move, down, up, click, drag (from the start through " + "`path` to `to`, `steps` moves per leg; the left button rotates the camera, right or middle pans, on an object it " + "moves it, in a painting gizmo it paints) or wheel (delta in notches, positive zooms in or scrolls a panel up). Give " + "the start as `at`, a point of the model, which is projected through the camera and by default checked to land on " + "that part there (check \"point\" only projects it), or as x/y, logical pixels from the canvas's top left. " + "Modifiers are pressed as keys for the gesture (shift for Measure's point picking, alt for erasing). A down keeps " + "its button and modifiers held, so moves drag with it, until an up or another gesture. Grabbers are set through " + "the gizmo's panel fields or transform, not dragged.", object_schema({{"action", enum_prop({"move", "down", "up", "click", "drag", "wheel"}, "Default click.")}, {"canvas", enum_prop({"3d", "preview", "assemble", "current"}, "Default current.")}, - {"x", prop("integer", "Start x.")}, - {"y", prop("integer", "Start y.")}, - {"to", array_prop({{"type", "integer"}}, "Drag end [x, y].")}, - {"steps", {{"type", "integer"}, {"minimum", 1}, {"maximum", 200}, {"description", "Drag moves (default 10)."}}}, + {"at", target_schema}, + {"x", prop("integer", "Start x, instead of at.")}, + {"y", prop("integer", "Start y, instead of at.")}, + {"to", pixel_or_target}, + {"path", array_prop(pixel_or_target, "Drag waypoints after the start, before to.")}, + {"check", enum_prop({"surface", "point"}, "For model points: surface (default) or projection only.")}, + {"tolerance", {{"type", "number"}, {"minimum", 0}, {"description", "Surface check distance in mm (default 1% of the part's size, at least 0.1)."}}}, + {"steps", {{"type", "integer"}, {"minimum", 1}, {"maximum", 200}, {"description", "Moves per drag leg (default 10)."}}}, {"button", enum_prop({"left", "right", "middle"}, "Default left.")}, {"double", prop("boolean", "Double click.")}, {"delta", prop("integer", "Wheel notches.")}, - {"modifiers", kModifiersSchema}}, - {"x", "y"}), + {"modifiers", kModifiersSchema}}), [&service](const json& args, ToolContext& ctx) { + const std::string owner = service.script_owner(service.jobs().ancestry(ctx.job_id())); json out = ctx.run_ui([&] { - const std::string name = arg_string(args, "canvas", "current"); - Plater& plater = ui_plater(); - GLCanvas3D* canvas = name == "3d" ? plater.get_view3D_canvas3D() : - name == "preview" ? plater.get_preview_canvas3D() : - name == "assemble" ? plater.get_assmeble_canvas3D() : - plater.get_current_canvas3D(); - if (canvas == nullptr || !canvas->get_wxglcanvas()->IsShownOnScreen()) - throw ToolFailure("That 3D view is not shown; switch to it with set_view first"); - return service.inspector().mouse(*canvas, args); + // A client's press that runs after the endpoint closed would stay held, with no one left + // to release it. + if (owner.empty() && !service.endpoint_open()) + throw ToolFailure("The MCP server was turned off before this gesture ran; it was not performed"); + try { + const std::string name = arg_string(args, "canvas", "current"); + Plater& plater = ui_plater(); + GLCanvas3D* canvas = name == "3d" ? plater.get_view3D_canvas3D() : + name == "preview" ? plater.get_preview_canvas3D() : + name == "assemble" ? plater.get_assmeble_canvas3D() : + plater.get_current_canvas3D(); + if (canvas == nullptr || !canvas->get_wxglcanvas()->IsShownOnScreen()) + throw ToolFailure("That 3D view is not shown; switch to it with set_view first"); + return service.inspector().mouse(*canvas, args, owner); + } catch (...) { + // A gesture that fails ends a press held from before it, as any other gesture would. + service.inspector().release_held(nullptr); + throw; + } + }); + settle(ctx); + return ToolResult::ok(out); + })); + + reg.add(mutate_tool( + "gizmo_file", "Use a file in the open gizmo", + "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.", + 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.")}}, + {"action", "path"}), + [](const json& args, ToolContext& ctx) { + const std::string action = arg_string(args, "action"); + json out = ctx.run_ui([&]() -> json { + GLCanvas3D* canvas = ui_plater().get_current_canvas3D(); + if (canvas == nullptr) + throw ToolFailure("No 3D view is shown"); + GLGizmosManager& gizmos = canvas->get_gizmos_manager(); + const GLGizmosManager::EType needed = action == "texture_import" ? GLGizmosManager::TextureDisplacement : GLGizmosManager::Svg; + if (gizmos.get_current_type() != needed) + throw ToolFailure(needed == GLGizmosManager::Svg ? "Open the SVG gizmo on an SVG part first" : + "Open the Texture displacement gizmo first"); + std::string err; + const auto path = action == "svg_save_as" ? resolve_output_path(arg_string(args, "path"), arg_bool(args, "overwrite", false), err) : + resolve_input_path(arg_string(args, "path"), err); + if (!path) + throw ToolFailure(err); + const std::string file = path_to_utf8(*path); + if (action == "texture_import") { + if (!dynamic_cast(gizmos.get_current())->import_texture(file, err)) + throw ToolFailure(err); + return {{"imported", file}}; + } + auto* svg = dynamic_cast(gizmos.get_current()); + if (action == "svg_change") { + if (!svg->change_file(file)) + throw ToolFailure("The file has no shapes the SVG gizmo can use"); + return {{"changed_to", file}}; + } + if (!svg->save_svg_as(file)) + throw ToolFailure("Could not write " + file); + return {{"saved", file}}; }); settle(ctx); return ToolResult::ok(out); diff --git a/src/slic3r/GUI/Mcp/McpToolsView.cpp b/src/slic3r/GUI/Mcp/McpToolsView.cpp index 07ca2a9e17..1a87ac8edd 100644 --- a/src/slic3r/GUI/Mcp/McpToolsView.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsView.cpp @@ -115,7 +115,8 @@ void register_view_tools(McpService& service) if (target != "window" && target != "canvas" && target != "dialog") // Scrolled into view first, and painted before the capture below runs. ctx.run_ui([&] { - service.inspector().reveal(service.inspector().resolve(target_arg)); + UiTarget t = service.inspector().resolve(target_arg); + service.inspector().reveal(t); return json(); }); // A canvas that comes back blank has not drawn yet; it does within moments. @@ -225,10 +226,12 @@ void register_view_tools(McpService& service) reg.add(mutate_tool( "set_view", "Point the view", - "Set up what the window shows, for screenshots and GUI work: the main tab, the 3D camera (a named direction, the " - "default view, or fit to bed / objects / selection), the preview's layer or layer range (1-based) and color " - "scheme, and the window size. Only the given fields change.", + "Set up what the window shows, for screenshots and GUI work: the main tab, the 3D view (Prepare's, the preview or " + "the assemble view, which has its own gizmos), the 3D camera (a named direction, the default view, or fit to bed / " + "objects / selection), the preview's layer or layer range (1-based) and color scheme, and the window size. Only " + "the given fields change.", object_schema({{"tab", enum_prop({"home", "prepare", "preview", "device", "multi_device", "project", "calibration"}, "Main window tab.")}, + {"view", 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"}, "Camera direction or fit.")}, {"layer", {{"type", "integer"}, {"minimum", 1}, {"description", "Preview: show layers up to this one (1-based)."}}}, @@ -256,8 +259,32 @@ void register_view_tools(McpService& service) frame->select_tab(wxString(id)); done["tab"] = arg_string(args, "tab"); } + if (args.contains("view")) { + const std::string view = arg_string(args, "view"); + GLCanvas3D* assemble = plater.get_assmeble_canvas3D(); + const bool in_assemble = assemble != nullptr && plater.get_current_canvas3D() == assemble; + if (view == "assemble") { + if (!plater.has_assmeble_view()) + throw ToolFailure("The assemble view needs an object on the plate"); + frame->select_tab(wxString(TAB_ID_PREPARE)); + plater.select_view_3D("Assemble"); + } else if (in_assemble) { + // What the assemble view's Return button does. + assemble->get_gizmos_manager().reset_all_states(); + plater.select_view_3D("3D"); + if (GLCanvas3D* view3d = plater.get_view3D_canvas3D()) { + view3d->get_gizmos_manager().reset_all_states(); + view3d->reload_scene(true); + } + } + if (view == "3d") + frame->select_tab(wxString(TAB_ID_PREPARE)); + else if (view == "preview") + frame->select_tab(wxString(TAB_ID_PREVIEW)); + done["view"] = view; + } const bool preview_args = args.contains("layer") || args.contains("layer_range") || args.contains("view_type"); - if (preview_args && !args.contains("tab")) { + if (preview_args && !args.contains("tab") && !args.contains("view")) { plater.select_view_3D("Preview", false); frame->select_tab(wxString(TAB_ID_PREVIEW)); } @@ -324,6 +351,16 @@ void register_view_tools(McpService& service) canvas->set_as_dirty(); return done; }); + if (out.value("view", "") == "assemble") + // A canvas shown for the first time loads its scene at its first frame, once its GL + // surface exists (a moment later on Wayland), and the next call may act on its objects. + poll_ui( + ctx, + []() -> json { + const GLCanvas3D* assemble = ui_plater().get_assmeble_canvas3D(); + return assemble != nullptr && assemble->is_initialized() && !assemble->is_reload_delayed() ? json(true) : json(); + }, + std::chrono::seconds(15), "the assemble view to show its objects"); settle(ctx); return ToolResult::ok(out); })); diff --git a/src/slic3r/GUI/Mcp/UiInspector.cpp b/src/slic3r/GUI/Mcp/UiInspector.cpp index c60ad11e67..94f4f8497a 100644 --- a/src/slic3r/GUI/Mcp/UiInspector.cpp +++ b/src/slic3r/GUI/Mcp/UiInspector.cpp @@ -1,30 +1,43 @@ #include "libslic3r/Config.hpp" #include "UiInspector.hpp" +#include "CanvasTarget.hpp" #include "McpService.hpp" #include "McpTypes.hpp" #include "ModalTracker.hpp" +#include "slic3r/GUI/3DScene.hpp" #include "slic3r/GUI/BBLTopbar.hpp" +#include "slic3r/GUI/Camera.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GLToolbar.hpp" #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/I18N.hpp" #include "slic3r/GUI/Gizmos/GLGizmoBase.hpp" +#include "slic3r/GUI/Gizmos/GLGizmoSVG.hpp" #include "slic3r/GUI/Gizmos/GLGizmosManager.hpp" #include "slic3r/GUI/ImGuiWrapper.hpp" #include "slic3r/GUI/KeyChord.hpp" #include "slic3r/GUI/MainFrame.hpp" +#include "slic3r/GUI/MeshUtils.hpp" +#include "slic3r/GUI/PartPlate.hpp" #include "slic3r/GUI/Plater.hpp" +#include "slic3r/GUI/Selection.hpp" #include "slic3r/GUI/SyntheticInput.hpp" #include "slic3r/GUI/Widgets/Button.hpp" #include "slic3r/GUI/Widgets/SideButton.hpp" #include "slic3r/GUI/Widgets/ComboBox.hpp" #include "slic3r/GUI/Widgets/SpinInput.hpp" #include "slic3r/GUI/Widgets/TextInput.hpp" +#include "libslic3r/AABBMesh.hpp" +#include "libslic3r/BoundingBox.hpp" +#include "libslic3r/Model.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/Polygon.hpp" #include "libslic3r/PrintConfig.hpp" #include "UiRefs.hpp" +#include #include #include @@ -66,12 +79,15 @@ #include #include +#include #include #include #include #include +#include #include #include +#include #include #include #include @@ -395,11 +411,13 @@ wxMenuItem* find_menu_path(const std::string& wanted, int& id) return nullptr; } +} // namespace + // Stable English gizmo names for refs and locators: the names Orca uses for the gizmos it names, // and the enum's own for the rest. -std::string gizmo_name(GLGizmosManager::EType type) +std::string gizmo_name(int type) { - if (std::string name = get_name_from_gizmo_etype(type); !name.empty()) + if (std::string name = get_name_from_gizmo_etype(GLGizmosManager::EType(type)); !name.empty()) return name; switch (type) { case GLGizmosManager::Svg: return "SVG"; @@ -407,10 +425,12 @@ std::string gizmo_name(GLGizmosManager::EType type) case GLGizmosManager::Assembly: return "Assembly"; case GLGizmosManager::Simplify: return "Simplify"; case GLGizmosManager::BrimEars: return "Brim Ears"; - default: return "Gizmo " + std::to_string(int(type)); + default: return "Gizmo " + std::to_string(type); } } +namespace { + GLGizmosManager::EType gizmo_from_name(const std::string& name) { for (int t = 0; t < int(GLGizmosManager::Undefined); ++t) @@ -557,23 +577,39 @@ void click_window(wxWindow* w, const ClickOptions& o) } // Delivers synthesized mouse events to a 3D canvas, drawing a frame after each so ImGui sees the -// hover, the press and the release on separate frames, as with a real mouse. +// hover, the press and the release on separate frames, as with a real mouse. Its modifiers are +// pressed as a keyboard does, with a key-down event each before the gesture and a key-up after it, +// so gizmos that switch modes on the key (Measure's Shift point picking) see them. class CanvasMouse { public: - CanvasMouse(GLCanvas3D& canvas, const std::vector& mods) : m_canvas(canvas), m_mods(parse_modifiers(mods)) + // `keys_down`: the modifiers' keys are already down, held by an earlier gesture. + CanvasMouse(GLCanvas3D& canvas, int mods, bool keys_down = false) : m_canvas(canvas), m_mods(mods) { - for (int k : modifier_keys(m_mods)) + if (keys_down) + return; + int down = wxMOD_NONE; + for (int k : modifier_keys(m_mods)) { SyntheticInput::press_key(k); + down |= modifier_of(k); + key_event(wxEVT_KEY_DOWN, k, down); + } } ~CanvasMouse() { - if (!m_keep_held) + if (!m_keep_held) { + int down = m_mods; + for (int k : modifier_keys(m_mods)) { + SyntheticInput::release_key(k); + down &= ~modifier_of(k); + key_event(wxEVT_KEY_UP, k, down); + } SyntheticInput::clear(); + } m_canvas.set_as_dirty(); } - // A press that the next call releases: the button stays down for code that asks for the mouse - // state, until a later gesture or the service's stop clears it. + // A press that a later call releases: the button and the modifier keys stay down for code that + // asks for their state, until UiInspector::release_held() ends the gesture. void keep_held() { m_keep_held = true; } void event(wxEventType type, const wxPoint& pos, bool left, bool right, bool middle, int wheel = 0) { @@ -595,14 +631,47 @@ public: } private: + static int modifier_of(int key) + { + switch (key) { + case WXK_CONTROL: return wxMOD_CONTROL; +#ifdef __APPLE__ + case WXK_RAW_CONTROL: return wxMOD_RAW_CONTROL; +#endif + case WXK_SHIFT: return wxMOD_SHIFT; + case WXK_ALT: return wxMOD_ALT; + default: return wxMOD_NONE; + } + } + // A modifier key's own event, carrying the modifiers down once it has happened. + void key_event(wxEventType type, int key, int down) + { + wxKeyEvent evt(type); + evt.m_keyCode = key; + set_modifiers(evt, down); + send(m_canvas.get_wxglcanvas(), evt); + m_canvas.render(); + } + GLCanvas3D& m_canvas; int m_mods; bool m_keep_held = false; }; +// The pointer arriving with no modifier held, as a person moves onto a spot before holding Shift to +// click it: gizmos that prepare on hover (Measure's point picking) see the spot first. +void hover(GLCanvas3D& canvas, const wxPoint& pos) +{ + CanvasMouse m(canvas, wxMOD_NONE); + m.event(wxEVT_MOTION, pos, false, false, false); +} + void canvas_click(GLCanvas3D& canvas, const wxPoint& pos, const ClickOptions& o) { - CanvasMouse m(canvas, o.modifiers); + const int mods = parse_modifiers(o.modifiers); + if (mods != wxMOD_NONE) + hover(canvas, pos); + CanvasMouse m(canvas, mods); const bool right = o.button == "right", middle = o.button == "middle", left = !right && !middle; m.event(wxEVT_MOTION, pos, false, false, false); m.event(left ? wxEVT_LEFT_DOWN : right ? wxEVT_RIGHT_DOWN : wxEVT_MIDDLE_DOWN, pos, left, right, middle); @@ -620,6 +689,145 @@ wxPoint imgui_to_canvas(GLCanvas3D& canvas, float x, float y) return {int(std::lround(x / scale)), int(std::lround(y / scale))}; } +// Kinds of ImGui items that hold a value a person types or picks. +bool is_imgui_field(const std::string& kind) +{ + return kind == "slider" || kind == "drag" || kind == "input" || kind == "multiline" || kind == "combo"; +} + +// What a listed ImGui item is: its widget kind, else a checkbox or a button. +std::string imgui_kind(const ImGuiWrapper::RecordedItem& item) +{ + if (!item.kind.empty()) + return item.kind; + return (item.flags & ImGuiItemStatusFlags_Checkable) != 0 ? "checkbox" : "button"; +} + +// What an item shows as its value: a field's recorded value, or for a combo drawn as a button (the +// Text gizmo's font list) the button's own label. +std::string imgui_value(const ImGuiWrapper::RecordedItem& item) +{ + return item.value.empty() && item.kind == "combo" ? clean_imgui_label(item.label) : item.value; +} + +// Whether an item is in the popup of a combo or a popup-list (ImGui names those windows +// "##Combo_NN" and "##Popup_XXXXXXXX", and their children after them). +bool in_popup(const ImGuiWrapper::RecordedItem& item) +{ + return item.window.rfind("##Combo", 0) == 0 || item.window.rfind("##Popup", 0) == 0; +} + +// The logical pixel of `canvas` showing a point of the model: {object, instance, volume} and either +// `point` (with `frame` "volume", the part's mesh coordinates, or "world", the scene's) or `spot`. +// With `check` "surface" a click there must land on that part at that point (see check_surface()). +wxPoint target_pixel(GLCanvas3D& canvas, const json& target, const std::string& check, double tolerance) +{ + if (!target.is_object()) + throw ToolFailure("A model target is {object, instance, volume, point | spot}"); + const int oi = target.value("object", -1), ii = target.value("instance", 0), vi = target.value("volume", 0); + const std::string what = "object " + std::to_string(oi) + " instance " + std::to_string(ii) + " part " + std::to_string(vi); + // The instance the open gizmo works on draws its parts itself, even while their scene entries are + // inactive (the painters deactivate them). + GLGizmosManager& gizmos = canvas.get_gizmos_manager(); + const Selection& selection = canvas.get_selection(); + const bool gizmo = gizmos.get_current_type() != GLGizmosManager::Undefined; + auto own = [&](const GLVolume* v) { + return gizmo && v->object_idx() == selection.get_object_idx() && v->instance_idx() == selection.get_instance_idx(); + }; + const GLVolume* shown = nullptr; + for (const GLVolume* v : canvas.get_volumes().volumes) + if (v->object_idx() == oi && v->instance_idx() == ii && v->volume_idx() == vi && !v->is_wipe_tower) + shown = v; + // 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)"); + const Transform3d world = shown->world_matrix(); + const AABBMesh& mesh = shown->mesh_raycaster->get_aabb_mesh(); + + Vec3d point; + if (target.contains("spot")) { + const std::string spot = target["spot"].get(); + const auto hit = spot_point(mesh, world, spot); + if (!hit) + throw ToolFailure("No " + spot + " spot on " + what + " (spot: top, bottom, front, back, left, right)"); + point = *hit; + } else if (target.contains("point")) { + const json& p = target["point"]; + if (!p.is_array() || p.size() != 3) + throw ToolFailure("point is [x, y, z]"); + point = Vec3d(p[0].get(), p[1].get(), p[2].get()); + const std::string frame = target.value("frame", "volume"); + if (frame == "volume") + point = world * point; + else if (frame != "world") + throw ToolFailure("frame is volume or world"); + } else { + throw ToolFailure("A model target needs point or spot"); + } + + CanvasView view; + const Camera& camera = wxGetApp().plater()->get_camera(); + view.view = camera.get_view_matrix(); + view.projection = camera.get_projection_matrix(); + view.viewport = camera.get_viewport(); + view.scale = canvas.get_scale(); + 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"); + // 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()))); + + if (check == "surface") { + // What a person sees: active parts, and the parts of the instance the open gizmo works on. + // Other inactive parts are hidden, modifiers are see-through, and gizmo geometry takes clicks + // as it would from a person. + // The manager hands the plane out flipped, for drawing; the gizmos' own raycasts use it as + // the object clipper holds it. + std::optional clip; + if (gizmo) + if (const auto drawn = gizmos.get_clipping_plane()) + clip = drawn->inverted_normal(); + std::vector meshes; + BoundingBoxf3 target_box; + for (const GLVolume* v : canvas.get_volumes().volumes) { + if (v->mesh_raycaster == nullptr || !v->visible || v->is_modifier || (!v->is_active && !own(v))) + continue; + meshes.push_back({&v->mesh_raycaster->get_aabb_mesh(), v->world_matrix(), v == shown, own(v), + "object " + std::to_string(v->object_idx()) + " instance " + std::to_string(v->instance_idx()) + + " part " + std::to_string(v->volume_idx())}); + } + for (const Vec3f& vertex : mesh.vertices()) + target_box.merge(world * vertex.cast()); + std::vector beds; + PartPlateList& plates = wxGetApp().plater()->get_partplate_list(); + for (int i = 0; i < plates.get_plate_count(); ++i) + if (PartPlate* plate = plates.get_plate(i)) + beds.push_back(Polygon::new_scale(plate->get_shape())); + const double limit = tolerance > 0. ? tolerance : std::max(0.1, 0.01 * target_box.size().norm()); + 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"); + } else if (check != "point") { + throw ToolFailure("check is surface or point"); + } + return pixel; +} + +// Whether the selection is one SVG part, the only selection the SVG gizmo opens on. +bool selection_is_svg_part(GLCanvas3D& canvas) +{ + const GLVolume* gl_volume = get_selected_gl_volume(canvas.get_selection()); + const Model* model = canvas.get_selection().get_model(); + if (gl_volume == nullptr || model == nullptr) + return false; + const ModelVolume* volume = get_model_volume(*gl_volume, model->objects); + return volume != nullptr && GLGizmoSVG::is_svg(*volume); +} + +} // namespace + const char* canvas_name(GLCanvas3D* canvas) { Plater* plater = wxGetApp().plater(); @@ -634,6 +842,8 @@ const char* canvas_name(GLCanvas3D* canvas) return ""; } +namespace { + GLCanvas3D* canvas_by_name(const std::string& name) { Plater* plater = wxGetApp().plater(); @@ -724,14 +934,9 @@ bool UiInspector::push(UiNode node, UiTarget target, std::vector& nodes, case UiTarget::Kind::ImGuiItem: { kind = 'g'; GLCanvas3D* canvas = target.canvas; - const unsigned id = target.imgui_id; - alive = [canvas, id] { - if (!is_live_canvas(canvas) || wxGetApp().imgui() == nullptr) - return false; - for (const auto& item : wxGetApp().imgui()->recorded_items(canvas)) - if (item.id == id) - return true; - return false; + alive = [canvas, id = target.imgui_id, name = target.imgui_name, window = target.imgui_window, twins = target.imgui_twins] { + return is_live_canvas(canvas) && wxGetApp().imgui() != nullptr && + imgui_find_item(wxGetApp().imgui()->recorded_items(canvas), id, name, window, twins).has_value(); }; break; } @@ -801,13 +1006,21 @@ void UiInspector::add_canvas_items(GLCanvas3D& canvas, int depth, std::vectoris_selectable()) + if (g == nullptr) + continue; + // The toolbar's gizmos, and on the Prepare canvas the two that open from the object list + // while they can open now: Simplify, and SVG on a selected SVG part. + const bool on_toolbar = gizmos.is_on_toolbar(GLGizmosManager::EType(type)); + const bool prepare = cname == std::string("3d"); + if (!on_toolbar && !(prepare && type == GLGizmosManager::Simplify && g->is_activable()) && + !(prepare && type == GLGizmosManager::Svg && selection_is_svg_part(canvas))) continue; UiNode node; node.kind = "gizmo"; - node.label = gizmo_name(GLGizmosManager::EType(type)); + node.label = gizmo_name(type); node.enabled = g->is_activable(); node.checked = gizmos.get_current_type() == GLGizmosManager::EType(type) ? 1 : 0; + node.note = on_toolbar ? "toolbar" : "no toolbar icon"; node.depth = depth; UiTarget t; t.kind = UiTarget::Kind::Gizmo; @@ -818,32 +1031,145 @@ void UiInspector::add_canvas_items(GLCanvas3D& canvas, int depth, std::vectorrecorded_items(&canvas)) { - const std::string label = clean_imgui_label(item.label); - if (label.empty()) - continue; - const wxPoint at = imgui_to_canvas(canvas, item.x, item.y); - const wxPoint br = imgui_to_canvas(canvas, item.x + item.w, item.y + item.h); - UiNode node; - node.kind = "imgui"; - node.label = label; - if (item.flags & ImGuiItemStatusFlags_Checkable) - node.checked = (item.flags & ImGuiItemStatusFlags_Checked) ? 1 : 0; - node.cls = clean_imgui_label(item.window); - node.depth = depth; - node.x = at.x, node.y = at.y, node.w = br.x - at.x, node.h = br.y - at.y; - UiTarget t; - t.kind = UiTarget::Kind::ImGuiItem; - t.window = canvas.get_wxglcanvas(); - t.canvas = &canvas; - t.imgui_id = item.id; - t.imgui_label = label; - t.imgui_window = item.window; - t.x = item.x, t.y = item.y, t.w = item.w, t.h = item.h; - t.locator = {{"imgui", label}, {"window", clean_imgui_label(item.window)}, {"canvas", cname}}; - push(std::move(node), std::move(t), nodes, omitted, o); + if (o.include_imgui && wxGetApp().imgui() != nullptr) + add_imgui_items(canvas, depth, nodes, omitted, o); +} + +// The ImGui windows of a canvas's last frame, each with its items and text in reading order. Text +// is listed for reading only: it has no ref and no locator matches it. +void UiInspector::add_imgui_items(GLCanvas3D& canvas, int depth, std::vector& nodes, std::size_t& omitted, const SnapshotOptions& o) +{ + const std::string cname = canvas_name(&canvas); + const auto items = wxGetApp().imgui()->recorded_items(&canvas); + const auto texts = wxGetApp().imgui()->recorded_texts(&canvas); + const auto labels = imgui_display_labels(items, texts); + + // A window's items and texts, row by row (by their middles: a label sits lower than its field's + // frame) and left to right. + struct Entry + { + float y, x; // middle, left + int item; // index into items, or -1 for texts[text] + std::size_t text; + }; + std::vector windows; + std::map> entries; + auto add = [&](const std::string& window, Entry e) { + if (entries.find(window) == entries.end()) + windows.push_back(window); + entries[window].push_back(e); + }; + for (std::size_t i = 0; i < items.size(); ++i) + if (!labels[i].empty() || !imgui_item_name(items[i]).empty()) + add(items[i].window, {items[i].y + items[i].h / 2.f, items[i].x, int(i), 0}); + for (std::size_t i = 0; i < texts.size(); ++i) + add(texts[i].window, {texts[i].y + texts[i].h / 2.f, texts[i].x, -1, i}); + + // Nodes without a ref (window headers, text) obey the query and the node limit too. + auto push_plain = [&](UiNode node) { + if (!o.query.empty()) { + const std::string q = lower(o.query); + if (lower(node.label).find(q) == std::string::npos && lower(node.kind) != q) + return; + } + if (int(nodes.size()) >= o.max_nodes) { + ++omitted; + return; + } + node.ref = "-"; + nodes.push_back(std::move(node)); + }; + for (const std::string& window : windows) { + UiNode header; + header.kind = "imgui_window"; + header.label = imgui_window_label(window); + header.depth = depth; + // A child window is "/_<8 hex digits>"; its name says which part of the panel it is. + if (const auto slash = window.rfind('/'); slash != std::string::npos) { + const std::string child = window.substr(slash + 1); + const std::string stem = child.size() > 9 ? child.substr(0, child.size() - 9) : child; + header.name = imgui_label_name(stem).empty() ? clean_imgui_label(stem) : imgui_label_name(stem); + } + if (ImGuiWindow* w = ImGui::GetCurrentContext() != nullptr ? ImGui::FindWindowByName(window.c_str()) : nullptr) { + const wxPoint at = imgui_to_canvas(canvas, w->Pos.x, w->Pos.y); + const wxPoint br = imgui_to_canvas(canvas, w->Pos.x + w->Size.x, w->Pos.y + w->Size.y); + header.x = at.x, header.y = at.y, header.w = br.x - at.x, header.h = br.y - at.y; + if (w->ScrollMax.y > 0.f) + header.note = "scroll " + std::to_string(int(w->Scroll.y)) + "/" + std::to_string(int(w->ScrollMax.y)) + + "; ui_mouse wheel over it scrolls it"; + } + push_plain(std::move(header)); + + std::vector& list = entries[window]; + std::stable_sort(list.begin(), list.end(), [](const Entry& a, const Entry& b) { return a.y < b.y; }); + for (auto row = list.begin(); row != list.end();) { + const auto end = std::find_if(row, list.end(), [&](const Entry& e) { return e.y - row->y > 4.f; }); + std::stable_sort(row, end, [](const Entry& a, const Entry& b) { return a.x < b.x; }); + row = end; + } + for (const Entry& e : list) { + if (e.item < 0) { + const ImGuiWrapper::RecordedText& text = texts[e.text]; + UiNode node; + node.kind = "text"; + node.label = text.text.size() > 120 ? text.text.substr(0, 117) + "..." : text.text; + std::replace(node.label.begin(), node.label.end(), '\n', ' '); + node.depth = depth + 1; + const wxPoint at = imgui_to_canvas(canvas, text.x, text.y); + const wxPoint br = imgui_to_canvas(canvas, text.x + text.w, text.y + text.h); + node.x = at.x, node.y = at.y, node.w = br.x - at.x, node.h = br.y - at.y; + push_plain(std::move(node)); + continue; + } + const ImGuiWrapper::RecordedItem& item = items[std::size_t(e.item)]; + const std::string name = imgui_item_name(item); + const wxPoint at = imgui_to_canvas(canvas, item.x, item.y); + const wxPoint br = imgui_to_canvas(canvas, item.x + item.w, item.y + item.h); + UiNode node; + node.kind = "imgui"; + node.cls = imgui_kind(item); + node.label = labels[std::size_t(e.item)]; + node.name = name == node.label ? std::string() : name; + node.value = imgui_value(item); + if (item.flags & ImGuiItemStatusFlags_Checkable) + node.checked = (item.flags & ImGuiItemStatusFlags_Checked) ? 1 : 0; + if ((node.cls == "slider" || node.cls == "drag") && (item.flags & ImGuiItemStatusFlags_Inputable) == 0) + node.note = "no typing"; + if (item.clipped) + node.note += std::string(node.note.empty() ? "" : ", ") + "clipped: ui_click and ui_input scroll it into view"; + node.depth = depth + 1; + node.x = at.x, node.y = at.y, node.w = br.x - at.x, node.h = br.y - at.y; + UiTarget t; + t.kind = UiTarget::Kind::ImGuiItem; + t.window = canvas.get_wxglcanvas(); + t.canvas = &canvas; + t.imgui_id = item.id; + t.imgui_label = node.label.empty() ? name : node.label; + t.imgui_name = name; + t.imgui_window = item.window; + t.imgui_twins = imgui_twins(items, name, item.window); + t.x = item.x, t.y = item.y, t.w = item.w, t.h = item.h; + // The shown label when no other item in its window shares it, else the name when that is + // unique, else both (Cut's "Keep" checkboxes, named by their row); locator_for() adds an + // index when even both repeat. + const std::string wlabel = imgui_window_label(item.window); + int same_label = 0, same_name = 0; + for (std::size_t j = 0; j < items.size(); ++j) + if (imgui_window_label(items[j].window) == wlabel) { + same_label += labels[j] == node.label ? 1 : 0; + same_name += imgui_item_name(items[j]) == name ? 1 : 0; + } + if (!node.label.empty() && (same_label == 1 || name.empty())) + t.locator = {{"imgui", node.label}}; + else if (node.label.empty() || same_name == 1) + t.locator = {{"imgui_name", name}}; + else + t.locator = {{"imgui", node.label}, {"imgui_name", name}}; + if (!wlabel.empty()) + t.locator["window"] = wlabel; + t.locator["canvas"] = cname; + push(std::move(node), std::move(t), nodes, omitted, o); + } } } @@ -976,10 +1302,17 @@ UiTarget UiInspector::resolve(const json& target) if (t == nullptr) throw ToolFailure(err); UiTarget out = *t; - if (out.kind == UiTarget::Kind::ImGuiItem) // the item may have moved since the snapshot - for (const auto& item : wxGetApp().imgui()->recorded_items(out.canvas)) - if (item.id == out.imgui_id) - out.x = item.x, out.y = item.y, out.w = item.w, out.h = item.h; + // The item may have moved since the snapshot, changed its id with its label, or been renamed by + // its place ("Layer 3" becoming "Layer 2" when a layer before it goes). + if (out.kind == UiTarget::Kind::ImGuiItem) { + const auto items = wxGetApp().imgui()->recorded_items(out.canvas); + if (const auto at = imgui_find_item(items, out.imgui_id, out.imgui_name, out.imgui_window, out.imgui_twins)) { + const ImGuiWrapper::RecordedItem& item = items[*at]; + out.imgui_id = item.id; + out.imgui_name = imgui_item_name(item); + out.x = item.x, out.y = item.y, out.w = item.w, out.h = item.h; + } + } return out; } if (!target.is_object()) @@ -998,8 +1331,9 @@ UiTarget UiInspector::resolve(const json& target) t.menu_path = path; return t; } - if (target.contains("gltoolbar") || target.contains("gizmo") || target.contains("imgui")) { - t.canvas = canvas_by_name(target.value("canvas", target.contains("imgui") ? "" : "3d")); + const bool imgui = target.contains("imgui") || target.contains("imgui_name"); + if (target.contains("gltoolbar") || target.contains("gizmo") || imgui) { + t.canvas = canvas_by_name(target.value("canvas", imgui ? "" : "3d")); if (t.canvas == nullptr) throw ToolFailure("No such canvas"); t.window = t.canvas->get_wxglcanvas(); @@ -1022,7 +1356,7 @@ UiTarget UiInspector::resolve(const json& target) const auto matches = match_imgui(target); const int index = target.value("index", -1); if (matches.empty()) - throw ToolFailure("No ImGui item \"" + target["imgui"].get() + "\" in the last frame; show its panel first"); + throw ToolFailure("No ImGui item matches " + target.dump() + " in the last frame; show its panel first (ui_snapshot 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())) @@ -1032,8 +1366,10 @@ UiTarget UiInspector::resolve(const json& target) t.canvas = canvas; t.window = canvas->get_wxglcanvas(); t.imgui_id = item.id; - t.imgui_label = clean_imgui_label(item.label); + t.imgui_label = target.contains("imgui") ? target["imgui"].get() : target["imgui_name"].get(); + t.imgui_name = imgui_item_name(item); t.imgui_window = item.window; + t.imgui_twins = imgui_twins(wxGetApp().imgui()->recorded_items(canvas), t.imgui_name, item.window); t.x = item.x, t.y = item.y, t.w = item.w, t.h = item.h; return t; } @@ -1057,7 +1393,7 @@ UiTarget UiInspector::resolve(const json& target) // A wx window by option key, class, label or name, optionally within a titled top-level window. if (!target.contains("option") && !target.contains("class") && !target.contains("label") && !target.contains("name")) - throw ToolFailure("A locator needs option, label, name or class (or menu, tab, gltoolbar, gizmo, imgui)"); + throw ToolFailure("A locator needs option, label, name or class (or menu, tab, gltoolbar, gizmo, imgui, imgui_name)"); const std::vector matches = match_windows(target); if (matches.empty()) throw ToolFailure("Nothing matches " + target.dump() + "; take a ui_snapshot"); @@ -1108,20 +1444,30 @@ std::vector UiInspector::match_windows(const json& locator) return matches; } +// {imgui: