From 47a90ff25e2f89b2b4e4cdea49f6d7f9641565f8 Mon Sep 17 00:00:00 2001 From: SoftFever Date: Wed, 28 Oct 2026 05:57:17 +0800 Subject: [PATCH] Let MCP clients inspect and drive the GUI, answer dialogs and run web view scripts --- src/slic3r/CMakeLists.txt | 7 + src/slic3r/GUI/BBLTopbar.hpp | 1 + src/slic3r/GUI/GLCanvas3D.cpp | 17 +- src/slic3r/GUI/GLCanvas3D.hpp | 1 + src/slic3r/GUI/GLToolbar.hpp | 1 + src/slic3r/GUI/GUI_ObjectList.cpp | 7 +- src/slic3r/GUI/Gizmos/GLGizmoCut.cpp | 3 +- src/slic3r/GUI/Gizmos/GLGizmoMeasure.cpp | 3 +- src/slic3r/GUI/Gizmos/GLGizmoMove.cpp | 3 +- src/slic3r/GUI/Gizmos/GLGizmoScale.cpp | 7 +- src/slic3r/GUI/IMSlider.cpp | 7 +- src/slic3r/GUI/ImGuiWrapper.cpp | 5 +- src/slic3r/GUI/Mcp/JobRegistry.cpp | 8 +- src/slic3r/GUI/Mcp/McpService.cpp | 37 + src/slic3r/GUI/Mcp/McpService.hpp | 21 + src/slic3r/GUI/Mcp/McpToolsApp.cpp | 1 + src/slic3r/GUI/Mcp/McpToolsPending.cpp | 1 - src/slic3r/GUI/Mcp/McpToolsUi.cpp | 466 ++++++++ src/slic3r/GUI/Mcp/ModalTracker.cpp | 4 + src/slic3r/GUI/Mcp/UiInspector.cpp | 1325 ++++++++++++++++++++++ src/slic3r/GUI/Mcp/UiInspector.hpp | 101 ++ src/slic3r/GUI/Mcp/UiInvoker.cpp | 19 +- src/slic3r/GUI/Mcp/UiInvoker.hpp | 6 + src/slic3r/GUI/Mcp/UiRefs.cpp | 55 + src/slic3r/GUI/Mcp/UiRefs.hpp | 86 ++ src/slic3r/GUI/SyntheticInput.cpp | 77 ++ src/slic3r/GUI/SyntheticInput.hpp | 29 + tests/slic3rutils/CMakeLists.txt | 1 + tests/slic3rutils/test_mcp_core.cpp | 50 + tests/slic3rutils/test_mcp_ui.cpp | 150 +++ tools/mcp/orca_mcp.py | 23 +- 31 files changed, 2489 insertions(+), 33 deletions(-) create mode 100644 src/slic3r/GUI/Mcp/McpToolsUi.cpp create mode 100644 src/slic3r/GUI/Mcp/UiInspector.cpp create mode 100644 src/slic3r/GUI/Mcp/UiInspector.hpp create mode 100644 src/slic3r/GUI/Mcp/UiRefs.cpp create mode 100644 src/slic3r/GUI/Mcp/UiRefs.hpp create mode 100644 src/slic3r/GUI/SyntheticInput.cpp create mode 100644 src/slic3r/GUI/SyntheticInput.hpp create mode 100644 tests/slic3rutils/test_mcp_ui.cpp diff --git a/src/slic3r/CMakeLists.txt b/src/slic3r/CMakeLists.txt index cef5ac03c4..7d7155fa91 100644 --- a/src/slic3r/CMakeLists.txt +++ b/src/slic3r/CMakeLists.txt @@ -136,6 +136,8 @@ set(SLIC3R_GUI_SOURCES GUI/ActionRegistry.hpp GUI/NativeCommands.cpp GUI/NativeCommands.hpp + GUI/SyntheticInput.cpp + GUI/SyntheticInput.hpp GUI/Mcp/JobRegistry.cpp GUI/Mcp/JobRegistry.hpp GUI/Mcp/McpCore.cpp @@ -167,14 +169,19 @@ set(SLIC3R_GUI_SOURCES GUI/Mcp/McpToolsPending.cpp GUI/Mcp/McpToolsProject.cpp GUI/Mcp/McpToolsScene.cpp + GUI/Mcp/McpToolsUi.cpp GUI/Mcp/McpToolsView.cpp GUI/Mcp/ScreenCapture.cpp GUI/Mcp/ScreenCapture.hpp GUI/Mcp/McpTypes.hpp GUI/Mcp/ModalTracker.cpp GUI/Mcp/ModalTracker.hpp + GUI/Mcp/UiInspector.cpp + GUI/Mcp/UiInspector.hpp GUI/Mcp/UiInvoker.cpp GUI/Mcp/UiInvoker.hpp + GUI/Mcp/UiRefs.cpp + GUI/Mcp/UiRefs.hpp GUI/PluginsConfigDialog.cpp GUI/PluginsConfigDialog.hpp GUI/ProcessRunner.cpp diff --git a/src/slic3r/GUI/BBLTopbar.hpp b/src/slic3r/GUI/BBLTopbar.hpp index bad0727452..fde68cdd69 100644 --- a/src/slic3r/GUI/BBLTopbar.hpp +++ b/src/slic3r/GUI/BBLTopbar.hpp @@ -65,6 +65,7 @@ public: wxAuiToolBarItem* FindToolByCurrentPosition(); void SetFileMenu(wxMenu* file_menu); + wxMenu* GetFileMenu() { return m_file_menu; } void AddDropDownSubMenu(wxMenu* sub_menu, const wxString& title); void AddDropDownMenuItem(wxMenuItem* menu_item); wxMenu *GetTopMenu(); diff --git a/src/slic3r/GUI/GLCanvas3D.cpp b/src/slic3r/GUI/GLCanvas3D.cpp index 97fe842a07..4de38bdce4 100644 --- a/src/slic3r/GUI/GLCanvas3D.cpp +++ b/src/slic3r/GUI/GLCanvas3D.cpp @@ -1,4 +1,5 @@ #include "libslic3r/libslic3r.h" +#include "slic3r/GUI/SyntheticInput.hpp" #include "libslic3r/Point.hpp" #include #include @@ -4427,7 +4428,7 @@ static std::set s_keys_down; static bool key_repeats(int key) { for (auto it = s_keys_down.begin(); it != s_keys_down.end();) // drops keys released while no canvas had the focus - it = wxGetKeyState(wxKeyCode(*it)) ? std::next(it) : s_keys_down.erase(it); + it = Slic3r::GUI::get_key_state(wxKeyCode(*it)) ? std::next(it) : s_keys_down.erase(it); return !s_keys_down.insert(key).second; } @@ -4821,11 +4822,11 @@ void GLCanvas3D::on_mouse(wxMouseEvent& evt) // For other events, all buttons are reported as non-pressed, such as window leaving event. This causes // imgui stopped responding if cursor moved out of window, such as // https://github.com/OrcaSlicer/OrcaSlicer/pull/14999#issuecomment-5151344759 - // We solve this by correcting the state of the event from the actual mouse state querying with `wxGetMouseState()` + // We solve this by correcting the state of the event from the actual mouse state querying with `get_mouse_state()` // so it works like on other platforms. // Only fill in state the event does not carry, to preserve wx's synthetic right button for Ctrl+left. if (!evt.ButtonIsDown(wxMOUSE_BTN_ANY)) { - const auto state = wxGetMouseState(); + const auto state = Slic3r::GUI::get_mouse_state(); evt.SetLeftDown(state.LeftIsDown()); evt.SetMiddleDown(state.MiddleIsDown()); evt.SetRightDown(state.RightIsDown()); @@ -8063,7 +8064,7 @@ void GLCanvas3D::_picking_pass() const GLVolume* volume = m_volumes.volumes[hit.raycaster_id]; if (volume->is_active && !volume->disabled && (volume->composite_id.volume_id >= 0 || m_render_sla_auxiliaries)) { // do not add the volume id if CTRL is pressed while a gizmo that does not allow Ctrl+click selection is active - if (m_gizmos.is_allow_multi_select_parts_or_objects() || !wxGetKeyState(WXK_CONTROL)) + if (m_gizmos.is_allow_multi_select_parts_or_objects() || !Slic3r::GUI::get_key_state(WXK_CONTROL)) m_hover_volume_idxs.emplace_back(hit.raycaster_id); m_gizmos.set_hover_id(-1); } @@ -12028,9 +12029,9 @@ void GLCanvas3D::_update_volumes_hover_state() if (m_hover_volume_idxs.empty()) return; - bool ctrl_pressed = wxGetKeyState(WXK_CONTROL); // additive select/deselect - bool shift_pressed = wxGetKeyState(WXK_SHIFT); // select by rectangle - bool alt_pressed = wxGetKeyState(WXK_ALT); // deselect by rectangle + bool ctrl_pressed = Slic3r::GUI::get_key_state(WXK_CONTROL); // additive select/deselect + bool shift_pressed = Slic3r::GUI::get_key_state(WXK_SHIFT); // select by rectangle + bool alt_pressed = Slic3r::GUI::get_key_state(WXK_ALT); // deselect by rectangle if (alt_pressed && (shift_pressed || ctrl_pressed)) { // illegal combinations of keys @@ -12775,7 +12776,7 @@ bool GLCanvas3D::_is_any_volume_outside() const void GLCanvas3D::_update_selection_from_hover() { - bool ctrl_pressed = wxGetKeyState(WXK_CONTROL); + bool ctrl_pressed = Slic3r::GUI::get_key_state(WXK_CONTROL); if (m_hover_volume_idxs.empty()) { if (!ctrl_pressed && (m_rectangle_selection.get_state() == GLSelectionRectangle::Select)) diff --git a/src/slic3r/GUI/GLCanvas3D.hpp b/src/slic3r/GUI/GLCanvas3D.hpp index a1c3608f88..9a740c3405 100644 --- a/src/slic3r/GUI/GLCanvas3D.hpp +++ b/src/slic3r/GUI/GLCanvas3D.hpp @@ -1038,6 +1038,7 @@ public: const GLGizmosManager& get_gizmos_manager() const { return m_gizmos; } GLGizmosManager& get_gizmos_manager() { return m_gizmos; } + GLToolbar& get_main_toolbar() { return m_main_toolbar; } void bed_shape_changed(); diff --git a/src/slic3r/GUI/GLToolbar.hpp b/src/slic3r/GUI/GLToolbar.hpp index 571f75a35c..46869503a1 100644 --- a/src/slic3r/GUI/GLToolbar.hpp +++ b/src/slic3r/GUI/GLToolbar.hpp @@ -398,6 +398,7 @@ public: bool is_any_item_pressed() const; unsigned int get_items_count() const { return (unsigned int)m_items.size(); } + const std::vector& get_items() const { return m_items; } int get_item_id(const std::string& name) const; void force_left_action(int item_id, GLCanvas3D& parent) { do_action(GLToolbarItem::Left, item_id, parent, false); } diff --git a/src/slic3r/GUI/GUI_ObjectList.cpp b/src/slic3r/GUI/GUI_ObjectList.cpp index 4bd988e3fb..996dc487c3 100644 --- a/src/slic3r/GUI/GUI_ObjectList.cpp +++ b/src/slic3r/GUI/GUI_ObjectList.cpp @@ -1,4 +1,5 @@ #include "libslic3r/libslic3r.h" +#include "slic3r/GUI/SyntheticInput.hpp" #include "libslic3r/AppConfig.hpp" #include "libslic3r/PresetBundle.hpp" #include "libslic3r/LifecycleEvents.hpp" @@ -251,7 +252,7 @@ ObjectList::ObjectList(wxWindow* parent) : // Workaround for entering the column editing mode on Windows. Simulate keyboard enter when another column of the active line is selected. int new_selected_column = -1; #endif //__WXMSW__ - if (wxGetKeyState(WXK_SHIFT)) + if (Slic3r::GUI::get_key_state(WXK_SHIFT)) { wxDataViewItemArray sels; GetSelections(sels); @@ -1509,7 +1510,7 @@ void ObjectList::OnChar(wxKeyEvent& event) if (event.GetKeyCode() == WXK_BACK){ remove(); } - else if (wxGetKeyState(wxKeyCode('A')) && wxGetKeyState(WXK_SHIFT)) + else if (Slic3r::GUI::get_key_state(wxKeyCode('A')) && Slic3r::GUI::get_key_state(WXK_SHIFT)) select_item_all_children(); event.Skip(); @@ -5507,7 +5508,7 @@ bool ObjectList::check_last_selection(wxString& msg_str) if (!m_last_selected_item) return true; - const bool is_shift_pressed = wxGetKeyState(WXK_SHIFT); + const bool is_shift_pressed = Slic3r::GUI::get_key_state(WXK_SHIFT); /* We can't mix Volumes, Layers and Objects/Instances. * So, show information about it diff --git a/src/slic3r/GUI/Gizmos/GLGizmoCut.cpp b/src/slic3r/GUI/Gizmos/GLGizmoCut.cpp index a8dfc71a69..da5726c468 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoCut.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoCut.cpp @@ -1,4 +1,5 @@ #include "GLGizmoCut.hpp" +#include "slic3r/GUI/SyntheticInput.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" #include @@ -1749,7 +1750,7 @@ void GLGizmoCut3D::dragging_grabber_move(const GLGizmoBase::UpdateData &data) // finds projection of the vector along the staring direction projection = inters_vec.dot(starting_vec); } - if (wxGetKeyState(WXK_SHIFT)) + if (Slic3r::GUI::get_key_state(WXK_SHIFT)) projection = m_snap_step * std::round(projection / m_snap_step); const Vec3d shift = starting_vec * projection; diff --git a/src/slic3r/GUI/Gizmos/GLGizmoMeasure.cpp b/src/slic3r/GUI/Gizmos/GLGizmoMeasure.cpp index 3232041e4e..542c9faf74 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoMeasure.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoMeasure.cpp @@ -1,4 +1,5 @@ #include "GLGizmoMeasure.hpp" +#include "slic3r/GUI/SyntheticInput.hpp" #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI_App.hpp" @@ -746,7 +747,7 @@ void GLGizmoMeasure::on_render() else { std::optional curr_feature = std::nullopt; if (m_curr_measuring) { - curr_feature = wxGetMouseState().LeftIsDown() ? m_curr_feature : + curr_feature = Slic3r::GUI::get_mouse_state().LeftIsDown() ? m_curr_feature : mouse_on_object ? m_curr_measuring->get_feature(model_facet_idx, position_on_model, m_mesh_raycaster_map[m_last_hit_volume]->get_transform(), m_only_select_plane) : std::nullopt; diff --git a/src/slic3r/GUI/Gizmos/GLGizmoMove.cpp b/src/slic3r/GUI/Gizmos/GLGizmoMove.cpp index 22629570cb..6eb61479e8 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoMove.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoMove.cpp @@ -1,4 +1,5 @@ #include "GLGizmoMove.hpp" +#include "slic3r/GUI/SyntheticInput.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/Shortcuts.hpp" @@ -343,7 +344,7 @@ double GLGizmoMove3D::calc_projection(const UpdateData& data) const projection = inters_vec.dot(starting_vec.normalized()); } - if (wxGetKeyState(WXK_SHIFT)) + if (Slic3r::GUI::get_key_state(WXK_SHIFT)) projection = m_snap_step * (double)std::round(projection / m_snap_step); return projection; diff --git a/src/slic3r/GUI/Gizmos/GLGizmoScale.cpp b/src/slic3r/GUI/Gizmos/GLGizmoScale.cpp index e0609d5660..167292266f 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoScale.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoScale.cpp @@ -1,4 +1,5 @@ #include "GLGizmoScale.hpp" +#include "slic3r/GUI/SyntheticInput.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/Shortcuts.hpp" @@ -204,7 +205,7 @@ void GLGizmoScale3D::on_start_dragging() m_starting.drag_position = grabbers_transform * m_grabbers[m_hover_id].center; m_starting.plane_center = grabbers_transform * m_grabbers[4].center; // plane_center = bottom center m_starting.plane_nromal = (grabbers_transform * m_grabbers[5].center - grabbers_transform * m_grabbers[4].center).normalized(); - m_starting.ctrl_down = wxGetKeyState(WXK_CONTROL); + m_starting.ctrl_down = Slic3r::GUI::get_key_state(WXK_CONTROL); m_starting.box = m_bounding_box; m_starting.center = m_center; @@ -255,7 +256,7 @@ void GLGizmoScale3D::update_grabbers_data() m_instance_center = (selection.is_single_full_instance() || selection.is_single_volume_or_modifier()) ? selection.get_first_volume()->get_instance_offset() : m_center; const Vec3d box_half_size = 0.5 * m_bounding_box.size(); - bool ctrl_down = wxGetKeyState(WXK_CONTROL); + bool ctrl_down = Slic3r::GUI::get_key_state(WXK_CONTROL); bool single_instance = selection.is_single_full_instance(); @@ -537,7 +538,7 @@ double GLGizmoScale3D::calc_ratio(const UpdateData& data) const ratio = (len_starting_vec + proj) / len_starting_vec; } - if (wxGetKeyState(WXK_SHIFT)) + if (Slic3r::GUI::get_key_state(WXK_SHIFT)) ratio = m_snap_step * (double)std::round(ratio / m_snap_step); return ratio; diff --git a/src/slic3r/GUI/IMSlider.cpp b/src/slic3r/GUI/IMSlider.cpp index c0c2decfac..7ddc5413de 100644 --- a/src/slic3r/GUI/IMSlider.cpp +++ b/src/slic3r/GUI/IMSlider.cpp @@ -1,4 +1,5 @@ #include "IMSlider.hpp" +#include "slic3r/GUI/SyntheticInput.hpp" #include "GUI_App.hpp" #include "GUI.hpp" #include "NotificationManager.hpp" @@ -1659,14 +1660,14 @@ void IMSlider::on_mouse_wheel(wxMouseEvent& evt) { wheel = wheel > 0 ? 1.0f : -1.0f; #ifdef __WXOSX__ - if (wxGetKeyState(WXK_SHIFT)) { + if (Slic3r::GUI::get_key_state(WXK_SHIFT)) { wheel *= -5; } - else if (wxGetKeyState(WXK_RAW_CONTROL)) { + else if (Slic3r::GUI::get_key_state(WXK_RAW_CONTROL)) { wheel *= 5; } #else - if (wxGetKeyState(WXK_COMMAND) || wxGetKeyState(WXK_SHIFT)) + if (Slic3r::GUI::get_key_state(WXK_COMMAND) || Slic3r::GUI::get_key_state(WXK_SHIFT)) wheel *= 5; #endif if (is_horizontal()) { diff --git a/src/slic3r/GUI/ImGuiWrapper.cpp b/src/slic3r/GUI/ImGuiWrapper.cpp index 156e2a37e7..e2ba881ebb 100644 --- a/src/slic3r/GUI/ImGuiWrapper.cpp +++ b/src/slic3r/GUI/ImGuiWrapper.cpp @@ -1,4 +1,5 @@ #include "ImGuiWrapper.hpp" +#include "slic3r/GUI/SyntheticInput.hpp" #include #include @@ -611,14 +612,14 @@ void ImGuiWrapper::new_frame() // values from 33 to 126 are reserved for the standard ASCII characters for (size_t i = 33; i <= 126; ++i) { wxKeyCode keycode = static_cast(i); - if (io.KeysDown[i] && keycode != WXK_NONE && !wxGetKeyState(keycode)) + if (io.KeysDown[i] && keycode != WXK_NONE && !Slic3r::GUI::get_key_state(keycode)) io.KeysDown[i] = false; } // special keys: delete, backspace, ... for (int key : io.KeyMap) { wxKeyCode keycode = static_cast(key); - if (io.KeysDown[key] && keycode != WXK_NONE && !wxGetKeyState(keycode)) + if (io.KeysDown[key] && keycode != WXK_NONE && !Slic3r::GUI::get_key_state(keycode)) io.KeysDown[key] = false; } diff --git a/src/slic3r/GUI/Mcp/JobRegistry.cpp b/src/slic3r/GUI/Mcp/JobRegistry.cpp index 00fdc77a84..6c9b59ee60 100644 --- a/src/slic3r/GUI/Mcp/JobRegistry.cpp +++ b/src/slic3r/GUI/Mcp/JobRegistry.cpp @@ -93,8 +93,14 @@ nlohmann::json JobRegistry::list() const { std::lock_guard lock(m_mutex); const auto now = std::chrono::steady_clock::now(); + // Newest first. + std::vector> jobs; + for (const auto& [id, job] : m_jobs) + jobs.emplace_back(id, &job); + std::sort(jobs.begin(), jobs.end(), [](const auto& a, const auto& b) { return a.second->created > b.second->created; }); nlohmann::json out = nlohmann::json::array(); - for (const auto& [id, job] : m_jobs) { + for (const auto& [id, job_ptr] : jobs) { + const Job& job = *job_ptr; nlohmann::json j{{"id", id}, {"tool", job.tool}, {"state", job.finished ? (job.result.is_error ? "failed" : "done") : "running"}, diff --git a/src/slic3r/GUI/Mcp/McpService.cpp b/src/slic3r/GUI/Mcp/McpService.cpp index 3c4fda6c9d..f265ad6fdf 100644 --- a/src/slic3r/GUI/Mcp/McpService.cpp +++ b/src/slic3r/GUI/Mcp/McpService.cpp @@ -5,6 +5,7 @@ #include "McpToken.hpp" #include "McpTools.hpp" #include "ModalTracker.hpp" +#include "UiInspector.hpp" #include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/ImGuiWrapper.hpp" #include "slic3r/GUI/MainFrame.hpp" @@ -108,6 +109,7 @@ bool McpService::start(const McpLaunchOptions& options, bool serve, std::string& m_options = options; m_dispatcher = std::make_unique(); m_modals = std::make_unique(); + m_inspector = std::make_unique(*this); m_invoker = std::make_unique(*m_dispatcher, [this] { return guards_on_ui(); }); m_core = std::make_unique(m_registry, *m_invoker, m_jobs, &m_journal); register_tools(); @@ -185,9 +187,44 @@ void McpService::stop() if (wxTheApp != nullptr) if (ImGuiWrapper* imgui = wxGetApp().imgui()) imgui->set_item_recording(false); + m_inspector.reset(); m_modals.reset(); } +std::string McpService::set_auto_answer(std::vector rules, const std::set& lineage) +{ + std::lock_guard lock(m_rules_mutex); + // A running script in the caller's lineage owns the rules. + for (const std::string& job : lineage) + if (auto it = m_script_rule_layers.find(job); it != m_script_rule_layers.end()) { + if (!rules.empty()) + it->second.push_back(m_modals->push_rules(std::move(rules))); + return "script"; + } + if (m_session_rule_layer != 0) + m_modals->pop_rules(m_session_rule_layer); + m_session_rule_layer = rules.empty() ? 0 : m_modals->push_rules(std::move(rules)); + return "session"; +} + +void McpService::begin_script_scope(const std::string& job) +{ + std::lock_guard lock(m_rules_mutex); + m_script_rule_layers.emplace(job, std::vector{}); +} + +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); +} + void McpService::suspend() { m_suspended = true; diff --git a/src/slic3r/GUI/Mcp/McpService.hpp b/src/slic3r/GUI/Mcp/McpService.hpp index b49fd1fe3f..7f68b4c37d 100644 --- a/src/slic3r/GUI/Mcp/McpService.hpp +++ b/src/slic3r/GUI/Mcp/McpService.hpp @@ -12,15 +12,21 @@ #include #include +#include #include +#include +#include #include #include +#include namespace Slic3r { namespace GUI { namespace Mcp { class McpHttpServer; class McpProtocol; class ModalTracker; +class UiInspector; +struct AutoAnswerRule; // The MCP server inside the running app: owns the tool catalog, the UI invoker, jobs, the session // journal, the modal-dialog tracker and the HTTP endpoint, and runs a --mcp-script once the app is @@ -65,6 +71,16 @@ public: UiInvoker& ui() { return *m_invoker; } McpCore& core() { return *m_core; } ModalTracker& modals() { return *m_modals; } + // Refs from ui_snapshot live here, so they survive between calls. UI thread only. + UiInspector& inspector() { return *m_inspector; } + + // Auto-answer rules from dialog_auto_answer. Rules registered from inside a script (a job in + // `lineage` is a running script) last until that script ends; a client's rules replace the + // ones it registered before. Returns "script" or "session". Any thread. + std::string set_auto_answer(std::vector rules, const std::set& lineage); + // run_script brackets its steps with these. + void begin_script_scope(const std::string& job); + void end_script_scope(const std::string& job); // Where screenshots and script outputs go when no path is given. boost::filesystem::path output_dir() const; @@ -93,6 +109,11 @@ private: std::unique_ptr m_protocol; std::unique_ptr m_http; std::unique_ptr m_modals; + std::unique_ptr m_inspector; + + std::mutex m_rules_mutex; + std::map> m_script_rule_layers; // running script job -> layers + int m_session_rule_layer = 0; std::atomic m_ready{false}; std::atomic m_suspended{false}; diff --git a/src/slic3r/GUI/Mcp/McpToolsApp.cpp b/src/slic3r/GUI/Mcp/McpToolsApp.cpp index 13baad14d0..4e3dc68058 100644 --- a/src/slic3r/GUI/Mcp/McpToolsApp.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsApp.cpp @@ -83,6 +83,7 @@ json app_state(McpService& service) {"display_backend", display_backend()}, {"ready", service.ready()}, {"dialogs", service.modals().snapshot()}, + {"auto_answer_rules", service.modals().rules_json()}, {"jobs", service.jobs().list()}}; MainFrame* frame = wxGetApp().mainframe; Plater* plater = wxGetApp().plater(); diff --git a/src/slic3r/GUI/Mcp/McpToolsPending.cpp b/src/slic3r/GUI/Mcp/McpToolsPending.cpp index 7e4559f39e..8d1d088739 100644 --- a/src/slic3r/GUI/Mcp/McpToolsPending.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsPending.cpp @@ -1,7 +1,6 @@ #include "McpTools.hpp" namespace Slic3r { namespace GUI { namespace Mcp { -void register_ui_tools(McpService&) {} void register_script_tools(McpService&) {} void register_cad_tools(McpService&) {} }}} diff --git a/src/slic3r/GUI/Mcp/McpToolsUi.cpp b/src/slic3r/GUI/Mcp/McpToolsUi.cpp new file mode 100644 index 0000000000..30a952ad1a --- /dev/null +++ b/src/slic3r/GUI/Mcp/McpToolsUi.cpp @@ -0,0 +1,466 @@ +// GUI automation: look at the widget tree, click, type, press keys, drag on the 3D canvas, answer +// dialogs and run JavaScript in web views. + +#include "JobRegistry.hpp" +#include "McpService.hpp" +#include "McpTools.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/MainFrame.hpp" +#include "slic3r/GUI/Plater.hpp" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +using nlohmann::json; +using namespace std::chrono_literals; + +namespace { + +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?}."}}; + +const json kModifiersSchema = {{"type", "array"}, + {"items", {{"type", "string"}, {"enum", {"ctrl", "shift", "alt", "cmd"}}}}, + {"description", "Modifier keys held during the click."}}; + +bool in_top_dialog(McpService& service, wxWindow* window) +{ + wxDialog* top = service.modals().top(); + return top != nullptr && window != nullptr && wxGetTopLevelParent(window) == top; +} + +// GUI input tools run under the recover guard so they can work in the topmost modal dialog; a +// target anywhere else gets the checks a mutate call would: no other call's nested loop, no open +// modal, and no MCP slice or export holding the project. +void guard_target(McpService& service, wxWindow* window) +{ + if (in_top_dialog(service, window)) + return; + service.ui().require_mutate(); + if (const auto ops = service.jobs().running_operations(); !ops.empty()) + throw ToolFailure("Busy: job " + ops.front() + " (a slice or export) is running; wait for it or cancel it first", + {{"job", ops.front()}}); +} + +wxWindow* target_window(const UiTarget& t) { return t.kind == UiTarget::Kind::Window ? t.window.get() : nullptr; } + +// The journal replays locators, never refs: refs mean nothing in another session. +void journal_with_locator(ToolContext& ctx, const json& args, const json& locator) +{ + json recorded = args; + if (recorded.contains("target") && recorded["target"].is_string() && !locator.is_null()) + recorded["target"] = locator; + ctx.set_journal_args(std::move(recorded)); +} + +ToolDef recover_input_tool(std::string name, std::string title, std::string description, json schema, ToolHandler handler) +{ + ToolDef d = mutate_tool(std::move(name), std::move(title), std::move(description), std::move(schema), std::move(handler)); + d.guard = GuardClass::Recover; + return d; +} + +// Every shown web view, main window first. +std::vector visible_webviews() +{ + std::vector out; + std::function visit = [&](wxWindow* w) { + if (!w->IsShownOnScreen()) + return; + if (auto* web = dynamic_cast(w)) { + out.push_back(web); + return; + } + for (wxWindow* child : w->GetChildren()) + visit(child); + }; + if (wxGetApp().mainframe != nullptr) + visit(wxGetApp().mainframe); + for (wxWindow* tlw : wxTopLevelWindows) + if (tlw != wxGetApp().mainframe) + visit(tlw); + return out; +} + +// Receives the result of one RunScriptAsync call. Deleting it disconnects it from the web view. +class ScriptSink : public wxEvtHandler +{ +public: + struct State + { + std::mutex mutex; + bool done = false; + bool error = false; + std::string text; + }; + + explicit ScriptSink(std::shared_ptr state) : m_state(std::move(state)) {} + + void on_result(wxWebViewEvent& evt) + { + if (evt.GetClientData() != this) { + evt.Skip(); + return; + } + std::lock_guard lock(m_state->mutex); + m_state->done = true; + m_state->error = evt.IsError(); + m_state->text = into_u8(evt.GetString()); + } + +private: + std::shared_ptr m_state; +}; + +} // namespace + +void register_ui_tools(McpService& service) +{ + ToolRegistry& reg = service.registry(); + + { + ToolDef def = inspect_tool( + "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 " + "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 | .")}, + {"query", prop("string", "Case-insensitive text to look for.")}, + {"max_nodes", {{"type", "integer"}, {"minimum", 1}, {"maximum", 5000}, {"description", "Default 400."}}}, + {"include_imgui", prop("boolean", "List ImGui items (default true).")}, + {"include_menus", prop("boolean", "List menu items (default true).")}}), + [&service](const json& args, ToolContext& ctx) { + SnapshotOptions o; + o.root = arg_string(args, "root", "all"); + o.query = arg_string(args, "query"); + o.max_nodes = arg_int(args, "max_nodes", 400); + o.include_imgui = arg_bool(args, "include_imgui", true); + o.include_menus = arg_bool(args, "include_menus", true); + json snap = ctx.run_ui([&] { return service.inspector().snapshot(o); }); + ToolResult r = ToolResult::ok(); + const std::string tree = snap["tree"].get(); + snap.erase("tree"); + r.data = std::move(snap); + r.content.push_back({{"type", "text"}, {"text", tree.empty() ? std::string("(nothing shown)") : tree}}); + return r; + }); + reg.add(def); + } + + 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 " + "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}, + {"button", enum_prop({"left", "right", "middle"}, "Default left.")}, + {"double", prop("boolean", "Double click.")}, + {"modifiers", kModifiersSchema}, + {"x", prop("integer", "Canvas x for a click on a 3D canvas.")}, + {"y", prop("integer", "Canvas y for a click on a 3D canvas.")}}, + {"target"}), + [&service](const json& args, ToolContext& ctx) { + ClickOptions o; + o.button = arg_string(args, "button", "left"); + o.double_click = arg_bool(args, "double", false); + o.modifiers = args.value("modifiers", std::vector{}); + 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 out = ctx.run_ui([&] { + UiTarget t = service.inspector().resolve(args["target"]); + locator = t.locator; + guard_target(service, target_window(t)); + return service.inspector().click(t, o); + }); + journal_with_locator(ctx, args, locator); + settle(ctx); + return ToolResult::ok(out); + })); + + reg.add(recover_input_tool( + "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.", + 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).")}}, + {"target", "value"}), + [&service](const json& args, ToolContext& ctx) { + json locator; + json out = ctx.run_ui([&] { + UiTarget t = service.inspector().resolve(args["target"]); + locator = t.locator; + guard_target(service, target_window(t)); + return service.inspector().input(t, args["value"], arg_bool(args, "submit", true)); + }); + journal_with_locator(ctx, args, locator); + settle(ctx); + return ToolResult::ok(out); + })); + + reg.add(recover_input_tool( + "ui_key", "Press keys", + "Send a key chord (\"Ctrl+S\", \"Escape\", \"Return\", \"Delete\", \"Shift+Tab\", \"Left\", \"F5\") and/or type text to " + "a target or, without one, to the focused window (the topmost dialog while one is open, the 3D canvas when nothing " + "has focus). The window's shortcut handling " + "sees it first, as with a real key press. Typing reaches ImGui fields and key handlers; to fill a native text field " + "use ui_input.", + object_schema({{"target", kTargetSchema}, {"keys", prop("string", "Key chord.")}, {"text", prop("string", "Characters to type.")}}), + [&service](const json& args, ToolContext& ctx) { + const std::string keys = arg_string(args, "keys"), text = arg_string(args, "text"); + if (keys.empty() && text.empty()) + throw ToolFailure("Give keys, text or both"); + json locator; + json out = ctx.run_ui([&] { + std::optional t; + if (args.contains("target")) { + t = service.inspector().resolve(args["target"]); + locator = t->locator; + } + guard_target(service, service.inspector().key_target(t ? &*t : nullptr)); + return service.inspector().key(t ? &*t : nullptr, keys, text); + }); + journal_with_locator(ctx, args, locator); + settle(ctx); + return ToolResult::ok(out); + })); + + 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). Coordinates come from a canvas screenshot divided by the " + "screen scale, or from ui_snapshot's ImGui item rectangles.", + 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)."}}}, + {"button", enum_prop({"left", "right", "middle"}, "Default left.")}, + {"double", prop("boolean", "Double click.")}, + {"delta", prop("integer", "Wheel notches.")}, + {"modifiers", kModifiersSchema}}, + {"x", "y"}), + [&service](const json& args, ToolContext& ctx) { + 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); + }); + settle(ctx); + return ToolResult::ok(out); + })); + + reg.add(recover_input_tool( + "dialog_respond", "Answer a dialog", + "Press a button of the topmost modal dialog (or of the one whose title contains dialog.title, which must be the " + "topmost): yes, no, ok, cancel, close, apply, a button's label, or a numeric id. Native dialogs (system message " + "boxes, file pickers) can't be answered here; register dialog_auto_answer before opening them.", + object_schema({{"button", prop("string", "Button to press.")}, + {"dialog", {{"type", "object"}, + {"properties", {{"title", prop("string", "Text the dialog's title contains (case-insensitive).")}}}, + {"additionalProperties", false}, + {"description", "Which dialog; default the topmost."}}}}, + {"button"}), + [&service](const json& args, ToolContext& ctx) { + const std::string button = arg_string(args, "button"); + const std::string title = args.contains("dialog") ? args["dialog"].value("title", "") : std::string(); + json out = ctx.run_ui([&]() -> json { + const auto& stack = service.modals().stack(); + if (stack.empty()) + throw ToolFailure("No modal dialog is open"); + wxDialog* dialog = stack.back(); + if (!title.empty()) { + auto contains = [&](wxDialog* d) { + std::string t = into_u8(d->GetTitle()), want = title; + std::transform(t.begin(), t.end(), t.begin(), ::tolower); + std::transform(want.begin(), want.end(), want.begin(), ::tolower); + return t.find(want) != std::string::npos; + }; + if (!contains(dialog)) { + for (wxDialog* d : stack) + if (contains(d)) + throw ToolFailure("\"" + into_u8(d->GetTitle()) + "\" is under \"" + into_u8(dialog->GetTitle()) + + "\"; answer the topmost dialog first"); + throw ToolFailure("No open dialog's title contains \"" + title + "\"", {{"dialogs", service.modals().snapshot()}}); + } + } + if (is_native_dialog(dialog)) + throw ToolFailure("This is a native dialog, which can't be clicked; cancel the job's dialog by registering " + "dialog_auto_answer before the action that opens it", + {{"dialog", describe_dialog(dialog)}}); + const int id = resolve_dialog_button(dialog, button); + if (id == wxID_NONE) + throw ToolFailure("The dialog has no button \"" + button + "\"", {{"dialog", describe_dialog(dialog)}}); + const std::string dialog_title = into_u8(dialog->GetTitle()); + // Press the button itself when there is one, so the dialog's own handler runs. + wxWindow* pressed = nullptr; + std::function find = [&](wxWindow* w) { + for (wxWindow* child : w->GetChildren()) { + if (pressed != nullptr || dynamic_cast(child) != nullptr) + continue; + if (child->GetId() == id && child->IsShown() && child->IsEnabled() && + (dynamic_cast(child) != nullptr || class_name(child).find("Button") != std::string::npos)) + pressed = child; + else + find(child); + } + }; + find(dialog); + if (pressed != nullptr) { + wxCommandEvent evt(wxEVT_BUTTON, id); + evt.SetEventObject(pressed); + pressed->GetEventHandler()->ProcessEvent(evt); + } else { + dialog->EndModal(id); + } + return {{"dialog", dialog_title}, {"button", button}, {"id", id}, {"pressed", pressed != nullptr}}; + }); + settle(ctx); + return ToolResult::ok(out); + })); + + { + ToolDef def = inspect_tool( + "dialog_auto_answer", "Pre-answer dialogs", + "Answer future modal dialogs automatically, native ones included: a dialog whose title or message matches a rule's " + "regex (case-insensitive) returns that button at once and never shows. Native file pickers can only be cancelled. " + "Called from a script, the rules last until the script ends; otherwise they replace the rules this session set " + "before (an empty list clears them).", + object_schema({{"rules", array_prop({{"type", "object"}, + {"properties", {{"match", prop("string", "Regex searched in \"title\\nmessage\".")}, + {"button", prop("string", "yes | no | ok | cancel | close | apply | label | id")}}}, + {"required", {"match", "button"}}, + {"additionalProperties", false}}, + "Rules, first match wins.")}}, + {"rules"}), + [&service](const json& args, ToolContext& ctx) { + std::vector rules; + for (const json& r : args["rules"]) + rules.push_back(make_rule(r["match"].get(), r["button"].get())); + const std::string scope = service.set_auto_answer(std::move(rules), ctx.lineage()); + return ToolResult::ok({{"scope", scope}, {"rules", service.modals().rules_json()}}); + }); + def.read_only = false; + def.idempotent = true; + def.guard = GuardClass::Recover; + def.journal = true; + reg.add(def); + } + + reg.add(mutate_tool( + "webview_eval", "Run JavaScript in a web view", + "Evaluate JavaScript in one of OrcaSlicer's web views (Home, the device page, login and others) and return the value of " + "its last expression (JSON values come back parsed). Without a target the only shown web view is used. Waits up to " + "timeout_s (default 10).", + object_schema({{"script", prop("string", "JavaScript to run.")}, + {"target", kTargetSchema}, + {"timeout_s", {{"type", "integer"}, {"minimum", 1}, {"maximum", 120}, {"description", "Default 10."}}}}, + {"script"}), + [&service](const json& args, ToolContext& ctx) { + const std::string script = arg_string(args, "script"); + const auto timeout = std::chrono::seconds(arg_int(args, "timeout_s", 10)); + auto state = std::make_shared(); + auto sink = std::make_shared(nullptr); + auto web_ref = std::make_shared>(); + json started = ctx.run_ui([&]() -> json { + wxWebView* web = nullptr; + if (args.contains("target")) { + UiTarget t = service.inspector().resolve(args["target"]); + web = dynamic_cast(target_window(t)); + if (web == nullptr) + throw ToolFailure("The target is not a web view (ui_snapshot lists them as kind webview)"); + } else { + const auto all = visible_webviews(); + if (all.empty()) + throw ToolFailure("No web view is shown (the Home tab has one: set_view tab=home)"); + if (all.size() > 1) { + json urls = json::array(); + for (wxWebView* w : all) + urls.push_back(into_u8(w->GetCurrentURL())); + throw ToolFailure("Several web views are shown; pass target (ui_snapshot query=webview)", {{"web_views", urls}}); + } + web = all.front(); + } + *web_ref = web; + *sink = new ScriptSink(state); + web->Bind(wxEVT_WEBVIEW_SCRIPT_RESULT, &ScriptSink::on_result, *sink); + web->RunScriptAsync(from_u8(script), *sink); + return {{"url", into_u8(web->GetCurrentURL())}}; + }); + auto cleanup = [&] { + try { + ctx.run_ui([&] { + if (wxWebView* web = web_ref->get()) + web->Unbind(wxEVT_WEBVIEW_SCRIPT_RESULT, &ScriptSink::on_result, *sink); + delete *sink; + *sink = nullptr; + return json(); + }); + } catch (const ToolFailure&) { + // The UI is shutting down; the sink is leaked rather than deleted off the UI thread. + } + }; + json result; + try { + result = poll_ui( + ctx, + [&]() -> json { + std::lock_guard lock(state->mutex); + if (!state->done) + return json(); + return json{{"error", state->error}, {"text", state->text}}; + }, + timeout, "the script result"); + } catch (const ToolFailure&) { + cleanup(); + throw; + } + cleanup(); + if (result["error"].get()) + throw ToolFailure("The script failed: " + result["text"].get()); + const std::string text = result["text"].get(); + json value = json::parse(text, nullptr, false); + if (value.is_discarded()) + value = text; + return ToolResult::ok({{"result", value}, {"url", started["url"]}}); + })); +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/ModalTracker.cpp b/src/slic3r/GUI/Mcp/ModalTracker.cpp index 71a85be15f..2643e33f55 100644 --- a/src/slic3r/GUI/Mcp/ModalTracker.cpp +++ b/src/slic3r/GUI/Mcp/ModalTracker.cpp @@ -4,6 +4,8 @@ #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/Widgets/Button.hpp" +#include + #include #include #include @@ -220,6 +222,8 @@ int ModalTracker::Enter(wxDialog* dialog) const int id = resolve_dialog_button(dialog, rule.button); if (id != wxID_NONE) { ++rule.uses; + BOOST_LOG_TRIVIAL(info) << "MCP: auto-answered dialog \"" << info["title"].get() << "\" with " + << rule.button << " (rule \"" << rule.pattern << "\")"; return id; // ShowModal() returns it without showing the dialog } } diff --git a/src/slic3r/GUI/Mcp/UiInspector.cpp b/src/slic3r/GUI/Mcp/UiInspector.cpp new file mode 100644 index 0000000000..ac10a8a701 --- /dev/null +++ b/src/slic3r/GUI/Mcp/UiInspector.cpp @@ -0,0 +1,1325 @@ +#include "UiInspector.hpp" + +#include "McpService.hpp" +#include "McpTypes.hpp" +#include "ModalTracker.hpp" +#include "slic3r/GUI/BBLTopbar.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/GLGizmosManager.hpp" +#include "slic3r/GUI/ImGuiWrapper.hpp" +#include "slic3r/GUI/KeyChord.hpp" +#include "slic3r/GUI/MainFrame.hpp" +#include "slic3r/GUI/Plater.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/PrintConfig.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +using nlohmann::json; + +namespace { + +std::string lower(std::string s) +{ + std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return char(std::tolower(c)); }); + return s; +} + +std::string short_class(const wxWindow* w) +{ + std::string c = class_name(w); + if (const auto lt = c.find('<'); lt != std::string::npos) + c = c.substr(0, lt); + if (const auto colon = c.rfind("::"); colon != std::string::npos) + c = c.substr(colon + 2); + return c; +} + +// The role a window plays for an agent; empty for plain containers. +std::string kind_of(wxWindow* w) +{ + if (dynamic_cast(w) != nullptr) + return "dialog"; + if (dynamic_cast(w) != nullptr) + return "window"; + if (dynamic_cast(w) != nullptr) + return "canvas"; + if (dynamic_cast(w) != nullptr) + return "webview"; + if (dynamic_cast<::Button*>(w) != nullptr || dynamic_cast(w) != nullptr || dynamic_cast<::SideButton*>(w) != nullptr) + return "button"; + if (dynamic_cast(w) != nullptr) + return "checkbox"; + if (dynamic_cast(w) != nullptr || dynamic_cast(w) != nullptr) + return "toggle"; + if (dynamic_cast(w) != nullptr) + return "radio"; + if (dynamic_cast<::ComboBox*>(w) != nullptr || dynamic_cast(w) != nullptr) + return "combo"; + if (dynamic_cast(w) != nullptr) + return "choice"; + if (dynamic_cast<::SpinInput*>(w) != nullptr || dynamic_cast(w) != nullptr || dynamic_cast(w) != nullptr) + return "spin"; + if (dynamic_cast<::TextInput*>(w) != nullptr || dynamic_cast(w) != nullptr) + return "text"; + if (dynamic_cast(w) != nullptr) + return "slider"; + if (dynamic_cast(w) != nullptr || dynamic_cast(w) != nullptr) + return "list"; + if (dynamic_cast(w) != nullptr) + return "tabs"; + if (dynamic_cast(w) != nullptr) + return "label"; + // Custom-drawn controls (Orca's StaticBox family and the like) show a label but have no + // class of their own here. + if (w->GetChildren().empty() && !w->GetLabel().empty()) + return "control"; + return {}; +} + +wxTextEntry* text_entry(wxWindow* w) +{ + if (dynamic_cast<::ComboBox*>(w) != nullptr) + return nullptr; // a TextInput too, but its value is the selection + if (auto* ti = dynamic_cast<::TextInput*>(w)) + return ti->GetTextCtrl(); + return dynamic_cast(w); +} + +std::string value_of(wxWindow* w) +{ + if (auto* web = dynamic_cast(w)) + return into_u8(web->GetCurrentURL()); + if (auto* spin = dynamic_cast<::SpinInput*>(w)) + return std::to_string(spin->GetValue()); + if (auto* spin = dynamic_cast(w)) + return std::to_string(spin->GetValue()); + if (auto* spin = dynamic_cast(w)) + return std::to_string(spin->GetValue()); + if (auto* slider = dynamic_cast(w)) + return std::to_string(slider->GetValue()); + if (auto* items = dynamic_cast(w); items != nullptr && dynamic_cast(w) == nullptr) { + const int sel = items->GetSelection(); + if (sel != wxNOT_FOUND) + return into_u8(items->GetString(unsigned(sel))); + } + if (wxTextEntry* te = text_entry(w)) + return into_u8(te->GetValue()); + return {}; +} + +int checked_of(wxWindow* w) +{ + if (auto* c = dynamic_cast(w)) + return c->GetValue() ? 1 : 0; + if (auto* t = dynamic_cast(w)) + return t->GetValue() ? 1 : 0; + if (auto* t = dynamic_cast(w)) + return t->GetValue() ? 1 : 0; + if (auto* r = dynamic_cast(w)) + return r->GetValue() ? 1 : 0; + return -1; +} + +std::string option_key_of(wxWindow* w); + +// The text left of a control on its row: how Orca's forms label their fields. +std::string row_label(wxWindow* w) +{ + wxWindow* parent = w->GetParent(); + if (parent == nullptr) + return {}; + const wxRect r = w->GetRect(); + const int cy = r.y + r.height / 2; + wxWindow* best = nullptr; + int best_dx = INT_MAX; + for (wxWindow* sib : parent->GetChildren()) { + if (sib == w || !sib->IsShown() || sib->GetLabel().Trim().empty()) + continue; + if (dynamic_cast(sib) == nullptr && kind_of(sib) != "control") + continue; + const wxRect s = sib->GetRect(); + if (s.GetRight() > r.x || cy < s.y || cy > s.GetBottom()) + continue; + if (r.x - s.GetRight() < best_dx) { + best_dx = r.x - s.GetRight(); + best = sib; + } + } + if (best == nullptr) + return {}; + wxString label = best->GetLabel(); + label.Replace("\n", " "); + return into_u8(label.Trim().Trim(false)); +} + +// The label of a setting from its definition, in the UI language. +std::string option_label(const std::string& key) +{ + const ConfigOptionDef* def = print_config_def.get(key.substr(0, key.find('['))); + return def == nullptr || def->label.empty() ? std::string() : into_u8(_(def->label)); +} + +std::string label_of(wxWindow* w) +{ + if (auto* tlw = dynamic_cast(w)) + return into_u8(tlw->GetTitle()); + // Input fields are named by the setting they edit or the label on their row; their own label is + // a unit ("mm") or nothing. + const std::string kind = kind_of(w); + if (kind == "text" || kind == "spin" || kind == "combo" || kind == "choice" || kind == "slider" || kind == "toggle" || + ((kind == "checkbox" || kind == "radio") && w->GetLabel().Trim().empty())) { + if (const std::string key = option_key_of(w); !key.empty()) + if (std::string l = option_label(key); !l.empty()) + return l; + if (std::string l = row_label(w); !l.empty()) + return l; + } + wxString label = w->GetLabel(); + if (label.Trim().Trim(false).empty() && dynamic_cast(w) == nullptr) { + // Icon buttons say what they do in their tooltip. + label = w->GetToolTipText().BeforeFirst('\n'); + if (label.StartsWith(_L("parameter name") + ": ")) + label.clear(); + } + label.Replace("\n", " "); + std::string out = into_u8(wxStripMenuCodes(label)); + if (out.size() > 120) + out = out.substr(0, 117) + "..."; + return out; +} + +// Orca's setting fields have a "parameter name: