mirror of
https://github.com/OrcaSlicer/OrcaSlicer.git
synced 2026-12-04 10:48:00 -05:00
Let MCP clients inspect and drive the GUI, answer dialogs and run web view scripts
This commit is contained in:
1 parent
dc522e59e4
commit
47a90ff25e
31 files changed
+2489
-33
No files matched your search
@@ -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
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "libslic3r/libslic3r.h"
|
||||
#include "slic3r/GUI/SyntheticInput.hpp"
|
||||
#include "libslic3r/Point.hpp"
|
||||
#include <limits>
|
||||
#include <string>
|
||||
@@ -4427,7 +4428,7 @@ static std::set<int> 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))
|
||||
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -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<GLToolbarItem*>& 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); }
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "GLGizmoCut.hpp"
|
||||
#include "slic3r/GUI/SyntheticInput.hpp"
|
||||
#include "slic3r/GUI/GLCanvas3D.hpp"
|
||||
|
||||
#include <cmath>
|
||||
@@ -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;
|
||||
|
||||
@@ -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<Measure::SurfaceFeature> 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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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()) {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "ImGuiWrapper.hpp"
|
||||
#include "slic3r/GUI/SyntheticInput.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
@@ -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<wxKeyCode>(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<wxKeyCode>(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;
|
||||
}
|
||||
|
||||
|
||||
@@ -93,8 +93,14 @@ nlohmann::json JobRegistry::list() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
// Newest first.
|
||||
std::vector<std::pair<std::string, const Job*>> 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"},
|
||||
|
||||
@@ -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<WxDispatcher>();
|
||||
m_modals = std::make_unique<ModalTracker>();
|
||||
m_inspector = std::make_unique<UiInspector>(*this);
|
||||
m_invoker = std::make_unique<UiInvoker>(*m_dispatcher, [this] { return guards_on_ui(); });
|
||||
m_core = std::make_unique<McpCore>(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<AutoAnswerRule> rules, const std::set<std::string>& lineage)
|
||||
{
|
||||
std::lock_guard<std::mutex> 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<std::mutex> lock(m_rules_mutex);
|
||||
m_script_rule_layers.emplace(job, std::vector<int>{});
|
||||
}
|
||||
|
||||
void McpService::end_script_scope(const std::string& job)
|
||||
{
|
||||
std::lock_guard<std::mutex> 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;
|
||||
|
||||
@@ -12,15 +12,21 @@
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
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<AutoAnswerRule> rules, const std::set<std::string>& 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<McpProtocol> m_protocol;
|
||||
std::unique_ptr<McpHttpServer> m_http;
|
||||
std::unique_ptr<ModalTracker> m_modals;
|
||||
std::unique_ptr<UiInspector> m_inspector;
|
||||
|
||||
std::mutex m_rules_mutex;
|
||||
std::map<std::string, std::vector<int>> m_script_rule_layers; // running script job -> layers
|
||||
int m_session_rule_layer = 0;
|
||||
|
||||
std::atomic<bool> m_ready{false};
|
||||
std::atomic<bool> m_suspended{false};
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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&) {}
|
||||
}}}
|
||||
@@ -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 <wx/button.h>
|
||||
#include <wx/dialog.h>
|
||||
#include <wx/glcanvas.h>
|
||||
#include <wx/toplevel.h>
|
||||
#include <wx/webview.h>
|
||||
#include <wx/weakref.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<wxWebView*> visible_webviews()
|
||||
{
|
||||
std::vector<wxWebView*> out;
|
||||
std::function<void(wxWindow*)> visit = [&](wxWindow* w) {
|
||||
if (!w->IsShownOnScreen())
|
||||
return;
|
||||
if (auto* web = dynamic_cast<wxWebView*>(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> state) : m_state(std::move(state)) {}
|
||||
|
||||
void on_result(wxWebViewEvent& evt)
|
||||
{
|
||||
if (evt.GetClientData() != this) {
|
||||
evt.Skip();
|
||||
return;
|
||||
}
|
||||
std::lock_guard<std::mutex> lock(m_state->mutex);
|
||||
m_state->done = true;
|
||||
m_state->error = evt.IsError();
|
||||
m_state->text = into_u8(evt.GetString());
|
||||
}
|
||||
|
||||
private:
|
||||
std::shared_ptr<State> 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 | <ref of a window>.")},
|
||||
{"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<std::string>();
|
||||
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<std::string>{});
|
||||
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<UiTarget> 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<void(wxWindow*)> find = [&](wxWindow* w) {
|
||||
for (wxWindow* child : w->GetChildren()) {
|
||||
if (pressed != nullptr || dynamic_cast<wxTopLevelWindow*>(child) != nullptr)
|
||||
continue;
|
||||
if (child->GetId() == id && child->IsShown() && child->IsEnabled() &&
|
||||
(dynamic_cast<wxButton*>(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<AutoAnswerRule> rules;
|
||||
for (const json& r : args["rules"])
|
||||
rules.push_back(make_rule(r["match"].get<std::string>(), r["button"].get<std::string>()));
|
||||
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<ScriptSink::State>();
|
||||
auto sink = std::make_shared<ScriptSink*>(nullptr);
|
||||
auto web_ref = std::make_shared<wxWeakRef<wxWebView>>();
|
||||
json started = ctx.run_ui([&]() -> json {
|
||||
wxWebView* web = nullptr;
|
||||
if (args.contains("target")) {
|
||||
UiTarget t = service.inspector().resolve(args["target"]);
|
||||
web = dynamic_cast<wxWebView*>(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<std::mutex> 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<bool>())
|
||||
throw ToolFailure("The script failed: " + result["text"].get<std::string>());
|
||||
const std::string text = result["text"].get<std::string>();
|
||||
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
|
||||
@@ -4,6 +4,8 @@
|
||||
#include "slic3r/GUI/GUI.hpp"
|
||||
#include "slic3r/GUI/Widgets/Button.hpp"
|
||||
|
||||
#include <boost/log/trivial.hpp>
|
||||
|
||||
#include <wx/button.h>
|
||||
#include <wx/dialog.h>
|
||||
#include <wx/dirdlg.h>
|
||||
@@ -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<std::string>() << "\" with "
|
||||
<< rule.button << " (rule \"" << rule.pattern << "\")";
|
||||
return id; // ShowModal() returns it without showing the dialog
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,101 @@
|
||||
#pragma once
|
||||
|
||||
#include "UiRefs.hpp"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <wx/weakref.h>
|
||||
#include <wx/window.h>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
class wxMenu;
|
||||
class wxTopLevelWindow;
|
||||
|
||||
namespace Slic3r { namespace GUI {
|
||||
|
||||
class GLCanvas3D;
|
||||
|
||||
namespace Mcp {
|
||||
|
||||
class McpService;
|
||||
|
||||
// What a ref or locator points at.
|
||||
struct UiTarget
|
||||
{
|
||||
enum class Kind { Window, MenuItem, ToolbarItem, Gizmo, ImGuiItem };
|
||||
Kind kind = Kind::Window;
|
||||
wxWeakRef<wxWindow> window; // Window: the window; others: the frame or GL canvas window
|
||||
GLCanvas3D* canvas = nullptr;
|
||||
int menu_id = -1; // MenuItem
|
||||
std::string menu_path; // "File>Export>Export G-code"
|
||||
std::string name; // ToolbarItem name, Gizmo name
|
||||
int gizmo = -1;
|
||||
unsigned imgui_id = 0; // ImGuiItem
|
||||
std::string imgui_label, imgui_window;
|
||||
float x = 0.f, y = 0.f, w = 0.f, h = 0.f; // ImGuiItem rectangle in ImGui coordinates
|
||||
nlohmann::json locator;
|
||||
};
|
||||
|
||||
struct SnapshotOptions
|
||||
{
|
||||
std::string root = "all"; // all | main | dialog | <ref of a window>
|
||||
int max_nodes = 400;
|
||||
bool include_imgui = true;
|
||||
bool include_menus = true;
|
||||
bool visible_only = true;
|
||||
std::string query;
|
||||
};
|
||||
|
||||
struct ClickOptions
|
||||
{
|
||||
std::string button = "left"; // left | right | middle
|
||||
bool double_click = false;
|
||||
std::vector<std::string> modifiers; // ctrl, shift, alt, cmd
|
||||
// Canvas coordinates (logical pixels) when clicking a point of a 3D canvas.
|
||||
bool at_point = false;
|
||||
int x = 0, y = 0;
|
||||
};
|
||||
|
||||
// Lists and drives the GUI for the ui_* tools: wx widgets of every shown top-level window, the
|
||||
// menus, the 3D canvases' toolbar items, gizmos and ImGui items. Input is synthesized as wx
|
||||
// events delivered to the widgets' own handlers (no OS input, focus or pointer needed), with
|
||||
// semantic activation for controls whose handlers listen to command events. UI thread only.
|
||||
class UiInspector
|
||||
{
|
||||
public:
|
||||
explicit UiInspector(McpService& service) : m_service(service) {}
|
||||
|
||||
// {tree, nodes, omitted}
|
||||
nlohmann::json snapshot(const SnapshotOptions& options);
|
||||
// A ref ("w12") or a locator object. Throws ToolFailure.
|
||||
UiTarget resolve(const nlohmann::json& target);
|
||||
nlohmann::json locator_for(const UiTarget& target) const { return target.locator; }
|
||||
|
||||
nlohmann::json click(const UiTarget& target, const ClickOptions& options);
|
||||
nlohmann::json input(const UiTarget& target, const nlohmann::json& value, bool submit);
|
||||
nlohmann::json key(const UiTarget* target, const std::string& chord, const std::string& text);
|
||||
// Where keys without a target go: the focused window inside the topmost modal dialog or that
|
||||
// dialog itself while one is open, else the focused window, else the current 3D canvas.
|
||||
wxWindow* key_target(const UiTarget* target) const;
|
||||
// Mouse gestures on a 3D canvas: move, down, up, click, drag, wheel.
|
||||
nlohmann::json mouse(GLCanvas3D& canvas, const nlohmann::json& gesture);
|
||||
// The 3D canvas a target is in (or the current one when `target` is null).
|
||||
GLCanvas3D* canvas_of(const UiTarget* target) const;
|
||||
|
||||
private:
|
||||
void walk(wxWindow* window, int depth, std::vector<UiNode>& nodes, std::size_t& omitted, const SnapshotOptions& options);
|
||||
void add_menus(wxMenu* menu, const std::string& path, wxWindow* frame, int depth, std::vector<UiNode>& nodes, std::size_t& omitted,
|
||||
const SnapshotOptions& options);
|
||||
void add_canvas_items(GLCanvas3D& canvas, int depth, std::vector<UiNode>& nodes, std::size_t& omitted, const SnapshotOptions& options);
|
||||
bool push(UiNode node, UiTarget target, std::vector<UiNode>& nodes, std::size_t& omitted, const SnapshotOptions& options);
|
||||
|
||||
McpService& m_service;
|
||||
RefTable<UiTarget> m_refs;
|
||||
};
|
||||
|
||||
// The canvases of the plater that are alive now: the 3D view, the preview and the assembly view.
|
||||
std::vector<GLCanvas3D*> live_canvases();
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -79,12 +79,11 @@ nlohmann::json UiInvoker::run(GuardClass guard, const std::string& tool, const s
|
||||
error = "OrcaSlicer is shutting down";
|
||||
else if (g.suspended)
|
||||
error = "The UI is being recreated (language change); retry in a moment";
|
||||
else if (guard == GuardClass::Mutate && !shared->running_tools.empty())
|
||||
error = "Busy: " + shared->running_tools.front() + " is still running; only inspection and dialog tools can run now";
|
||||
else if (guard == GuardClass::Mutate && g.modal) {
|
||||
error = "A modal dialog is open; answer it first (ui_snapshot, dialog_respond)";
|
||||
details = {{"dialogs", g.dialogs}};
|
||||
}
|
||||
} else if (guard == GuardClass::Mutate && !shared->running_tools.empty())
|
||||
error = "Busy: " + shared->running_tools.front() + " is still running; only inspection and dialog tools can run now";
|
||||
}
|
||||
if (error.empty()) {
|
||||
shared->running_tools.push_back(tool);
|
||||
@@ -158,6 +157,20 @@ std::optional<UiInvoker::Probe> UiInvoker::probe(std::chrono::milliseconds timeo
|
||||
return call->probe;
|
||||
}
|
||||
|
||||
void UiInvoker::require_mutate() const
|
||||
{
|
||||
// The calling closure is the last entry; anything before it is a call whose nested loop we
|
||||
// are running in.
|
||||
if (m_shared->guards_on_ui) {
|
||||
const GuardState g = m_shared->guards_on_ui();
|
||||
if (g.modal)
|
||||
throw ToolFailure("A modal dialog is open; answer it first (ui_snapshot, dialog_respond)", {{"dialogs", g.dialogs}});
|
||||
}
|
||||
if (m_shared->running_tools.size() > 1)
|
||||
throw ToolFailure("Busy: " + m_shared->running_tools.front() +
|
||||
" is still running; only inspection and dialog tools can run now");
|
||||
}
|
||||
|
||||
void UiInvoker::shutdown()
|
||||
{
|
||||
if (m_shared->stopped.exchange(true))
|
||||
|
||||
@@ -59,6 +59,12 @@ public:
|
||||
};
|
||||
std::optional<Probe> probe(std::chrono::milliseconds timeout);
|
||||
|
||||
// Applies the mutate guard from inside a closure that run() is executing under a weaker class:
|
||||
// the GUI input tools run as recover calls so they can answer the topmost dialog, and call
|
||||
// this once their target turns out to be elsewhere. Throws ToolFailure when another call's
|
||||
// nested loop is running or a modal dialog is open. UI thread only.
|
||||
void require_mutate() const;
|
||||
|
||||
// Wakes every waiting caller with "shutting down"; closures that run afterwards do nothing.
|
||||
void shutdown();
|
||||
bool is_shutdown() const;
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
#include "UiRefs.hpp"
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
std::string clean_imgui_label(const std::string& label)
|
||||
{
|
||||
const auto hash = label.find("##");
|
||||
std::string out = hash == std::string::npos ? label : label.substr(0, hash);
|
||||
// Orca marks colored text and icons with control characters; drop them and the padding.
|
||||
std::string clean;
|
||||
for (std::size_t i = 0; i < out.size(); ++i) {
|
||||
const unsigned char c = static_cast<unsigned char>(out[i]);
|
||||
if (c >= 0x20)
|
||||
clean.push_back(char(c));
|
||||
}
|
||||
const auto first = clean.find_first_not_of(' ');
|
||||
if (first == std::string::npos)
|
||||
return {};
|
||||
return clean.substr(first, clean.find_last_not_of(' ') - first + 1);
|
||||
}
|
||||
|
||||
std::string format_snapshot(const std::vector<UiNode>& nodes, std::size_t omitted)
|
||||
{
|
||||
std::string out;
|
||||
for (const UiNode& n : nodes) {
|
||||
out.append(std::size_t(n.depth) * 2, ' ');
|
||||
out += "[" + n.ref + "] " + n.kind;
|
||||
if (!n.label.empty())
|
||||
out += " \"" + n.label + "\"";
|
||||
if (!n.value.empty())
|
||||
out += " = \"" + n.value + "\"";
|
||||
if (!n.cls.empty() && n.cls != n.kind)
|
||||
out += " (" + n.cls + ")";
|
||||
if (!n.name.empty())
|
||||
out += " name=" + n.name;
|
||||
if (!n.option.empty())
|
||||
out += " option=" + n.option;
|
||||
if (n.checked >= 0)
|
||||
out += n.checked ? " [checked]" : " [unchecked]";
|
||||
if (!n.enabled)
|
||||
out += " [disabled]";
|
||||
if (n.focused)
|
||||
out += " [focused]";
|
||||
if (n.w > 0 && n.h > 0)
|
||||
out += " @" + std::to_string(n.x) + "," + std::to_string(n.y) + " " + std::to_string(n.w) + "x" + std::to_string(n.h);
|
||||
out += "\n";
|
||||
}
|
||||
if (omitted > 0)
|
||||
out += "... " + std::to_string(omitted) + " more nodes; narrow with root, query or a larger max_nodes\n";
|
||||
return out;
|
||||
}
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -0,0 +1,86 @@
|
||||
#pragma once
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
// The part of a label ImGui shows: "Move##gizmo" -> "Move", "###id" -> "".
|
||||
std::string clean_imgui_label(const std::string& label);
|
||||
|
||||
// One line of a ui_snapshot.
|
||||
struct UiNode
|
||||
{
|
||||
std::string ref; // "w12", "m3", "t5", "z2", "g7"
|
||||
std::string kind; // button, checkbox, text, menu_item, gltoolbar, gizmo, imgui, canvas, dialog, ...
|
||||
std::string cls; // C++ class without namespaces, for wx windows
|
||||
std::string label;
|
||||
std::string value;
|
||||
std::string name; // wx name, when it is not a default one
|
||||
std::string option; // config option key of a setting field
|
||||
bool enabled = true;
|
||||
bool focused = false;
|
||||
int checked = -1; // -1 not checkable, 0/1 state
|
||||
int depth = 0;
|
||||
int x = 0, y = 0, w = 0, h = 0; // client coordinates in the parent window / canvas
|
||||
};
|
||||
|
||||
// Compact indented text, one node per line, e.g. ` [w12] button "Slice plate"`.
|
||||
std::string format_snapshot(const std::vector<UiNode>& nodes, std::size_t omitted);
|
||||
|
||||
// The refs ui_snapshot hands out. Ids are never reused, so two clients can't confuse each other's
|
||||
// refs; each stores what it points at and how to tell whether that still exists, plus the UI
|
||||
// generation it was taken in (a rebuilt main window invalidates every ref).
|
||||
template<class Payload> class RefTable
|
||||
{
|
||||
public:
|
||||
static constexpr std::size_t kMaxRefs = 20000;
|
||||
|
||||
std::string add(char kind, uint64_t generation, Payload payload, std::function<bool()> alive)
|
||||
{
|
||||
std::string ref = std::string(1, kind) + std::to_string(++m_next);
|
||||
m_entries.emplace(ref, Entry{generation, std::move(payload), std::move(alive)});
|
||||
m_order.push_back(ref);
|
||||
while (m_order.size() > kMaxRefs) {
|
||||
m_entries.erase(m_order.front());
|
||||
m_order.pop_front();
|
||||
}
|
||||
return ref;
|
||||
}
|
||||
|
||||
// The payload of a live ref, or nullptr with `err` saying why not.
|
||||
const Payload* resolve(const std::string& ref, uint64_t generation, std::string& err) const
|
||||
{
|
||||
auto it = m_entries.find(ref);
|
||||
if (it == m_entries.end()) {
|
||||
err = "Unknown ref " + ref + "; take a new ui_snapshot";
|
||||
return nullptr;
|
||||
}
|
||||
if (it->second.generation != generation || (it->second.alive && !it->second.alive())) {
|
||||
err = "Stale ref " + ref + ": the element is gone or the window was rebuilt; take a new ui_snapshot";
|
||||
return nullptr;
|
||||
}
|
||||
return &it->second.payload;
|
||||
}
|
||||
|
||||
private:
|
||||
struct Entry
|
||||
{
|
||||
uint64_t generation;
|
||||
Payload payload;
|
||||
std::function<bool()> alive;
|
||||
};
|
||||
std::map<std::string, Entry> m_entries;
|
||||
std::deque<std::string> m_order;
|
||||
uint64_t m_next = 0;
|
||||
};
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -0,0 +1,77 @@
|
||||
#include "SyntheticInput.hpp"
|
||||
|
||||
#include <wx/utils.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
|
||||
namespace Slic3r { namespace GUI {
|
||||
|
||||
namespace {
|
||||
|
||||
std::vector<int>& held_keys() { static std::vector<int> keys; return keys; }
|
||||
std::optional<wxMouseState>& held_mouse() { static std::optional<wxMouseState> mouse; return mouse; }
|
||||
|
||||
// The modifier a key code stands for, so a held Shift also reads as WXK_SHIFT etc.
|
||||
bool same_key(int held, int asked)
|
||||
{
|
||||
if (held == asked)
|
||||
return true;
|
||||
#ifdef __APPLE__
|
||||
// WXK_CONTROL is Command on macOS; WXK_RAW_CONTROL is the Control key.
|
||||
return false;
|
||||
#else
|
||||
return (held == WXK_CONTROL && asked == WXK_RAW_CONTROL) || (held == WXK_RAW_CONTROL && asked == WXK_CONTROL);
|
||||
#endif
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
namespace SyntheticInput {
|
||||
|
||||
void press_key(int key_code)
|
||||
{
|
||||
if (!is_key_down(key_code))
|
||||
held_keys().push_back(key_code);
|
||||
}
|
||||
|
||||
void release_key(int key_code)
|
||||
{
|
||||
auto& keys = held_keys();
|
||||
keys.erase(std::remove(keys.begin(), keys.end(), key_code), keys.end());
|
||||
}
|
||||
|
||||
bool is_key_down(int key_code)
|
||||
{
|
||||
const auto& keys = held_keys();
|
||||
return std::any_of(keys.begin(), keys.end(), [key_code](int k) { return same_key(k, key_code); });
|
||||
}
|
||||
|
||||
void set_mouse(const wxMouseState& state) { held_mouse() = state; }
|
||||
|
||||
void release_mouse() { held_mouse().reset(); }
|
||||
|
||||
void clear()
|
||||
{
|
||||
held_keys().clear();
|
||||
held_mouse().reset();
|
||||
}
|
||||
|
||||
} // namespace SyntheticInput
|
||||
|
||||
bool get_key_state(wxKeyCode key)
|
||||
{
|
||||
if (SyntheticInput::is_key_down(int(key)))
|
||||
return true;
|
||||
return wxGetKeyState(key);
|
||||
}
|
||||
|
||||
wxMouseState get_mouse_state()
|
||||
{
|
||||
if (const auto& mouse = held_mouse())
|
||||
return *mouse;
|
||||
return wxGetMouseState();
|
||||
}
|
||||
|
||||
}} // namespace Slic3r::GUI
|
||||
@@ -0,0 +1,29 @@
|
||||
#pragma once
|
||||
|
||||
#include <wx/defs.h>
|
||||
#include <wx/mousestate.h>
|
||||
|
||||
namespace Slic3r { namespace GUI {
|
||||
|
||||
// Input state that automation (the MCP server) holds down while it synthesizes a gesture.
|
||||
// Synthesized wx events carry their own modifier and button flags, but parts of the 3D view also
|
||||
// ask the system for the keyboard and mouse state; those reads go through get_key_state() and
|
||||
// get_mouse_state(), which add whatever automation is holding. Empty unless a synthesized gesture
|
||||
// is in progress, so real input is unaffected. UI thread only.
|
||||
namespace SyntheticInput {
|
||||
void press_key(int key_code);
|
||||
void release_key(int key_code);
|
||||
bool is_key_down(int key_code);
|
||||
// The pointer automation drives, in screen coordinates, with its buttons.
|
||||
void set_mouse(const wxMouseState& state);
|
||||
void release_mouse();
|
||||
// Drops everything held, e.g. when a gesture fails half-way.
|
||||
void clear();
|
||||
} // namespace SyntheticInput
|
||||
|
||||
// wxGetKeyState() plus the keys automation holds down.
|
||||
bool get_key_state(wxKeyCode key);
|
||||
// wxGetMouseState(), or automation's pointer while it drives one.
|
||||
wxMouseState get_mouse_state();
|
||||
|
||||
}} // namespace Slic3r::GUI
|
||||
@@ -27,6 +27,7 @@ add_executable(${_TEST_NAME}_tests
|
||||
test_mcp_operations.cpp
|
||||
test_mcp_protocol.cpp
|
||||
test_mcp_script.cpp
|
||||
test_mcp_ui.cpp
|
||||
test_prebuild_queue.cpp
|
||||
test_staged_build.cpp
|
||||
test_network_versions.cpp
|
||||
|
||||
@@ -289,6 +289,56 @@ TEST_CASE("a mutate call is refused inside another call's nested loop but inspec
|
||||
CHECK(nested_inspect == "seen");
|
||||
}
|
||||
|
||||
TEST_CASE("a recover call that targets outside the dialog applies the mutate guard itself", "[Mcp]")
|
||||
{
|
||||
ManualDispatcher ui;
|
||||
GuardState guards;
|
||||
UiInvoker invoker(ui, [&] { return guards; });
|
||||
auto attempt = [&]() -> std::string {
|
||||
auto fut = std::async(std::launch::async, [&]() -> std::string {
|
||||
try {
|
||||
invoker.run(GuardClass::Recover, "ui_click", [&] {
|
||||
invoker.require_mutate();
|
||||
return json();
|
||||
});
|
||||
return "ok";
|
||||
} catch (const ToolFailure& f) {
|
||||
return f.what();
|
||||
}
|
||||
});
|
||||
ui.pump_until([&] { return fut.wait_for(0ms) == std::future_status::ready; });
|
||||
return fut.get();
|
||||
};
|
||||
CHECK(attempt() == "ok");
|
||||
guards.modal = true;
|
||||
CHECK(attempt().find("modal dialog") != std::string::npos);
|
||||
guards = {};
|
||||
|
||||
// Inside another call's nested loop it is busy, as a mutate call would be.
|
||||
std::string nested;
|
||||
auto outer = std::async(std::launch::async, [&] {
|
||||
return invoker.run(GuardClass::Mutate, "outer", [&] {
|
||||
auto m = std::async(std::launch::async, [&]() -> std::string {
|
||||
try {
|
||||
invoker.run(GuardClass::Recover, "ui_click", [&] {
|
||||
invoker.require_mutate();
|
||||
return json();
|
||||
});
|
||||
return "ok";
|
||||
} catch (const ToolFailure& f) {
|
||||
return f.what();
|
||||
}
|
||||
});
|
||||
ui.pump_until([&] { return m.wait_for(0ms) == std::future_status::ready; });
|
||||
nested = m.get();
|
||||
return json();
|
||||
});
|
||||
});
|
||||
ui.pump_until([&] { return outer.wait_for(0ms) == std::future_status::ready; });
|
||||
outer.get();
|
||||
CHECK(nested.find("Busy: outer") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST_CASE("a job outlives its reply and wait() returns its result", "[Mcp]")
|
||||
{
|
||||
Harness h;
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
#include <catch2/catch_test_macros.hpp>
|
||||
|
||||
#include "slic3r/GUI/Mcp/UiRefs.hpp"
|
||||
#include "slic3r/GUI/SyntheticInput.hpp"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace Slic3r::GUI;
|
||||
using namespace Slic3r::GUI::Mcp;
|
||||
using nlohmann::json;
|
||||
|
||||
namespace {
|
||||
|
||||
struct FakeTarget
|
||||
{
|
||||
std::string name;
|
||||
json locator;
|
||||
};
|
||||
|
||||
UiNode node(const std::string& ref, const std::string& kind, const std::string& label, int depth)
|
||||
{
|
||||
UiNode n;
|
||||
n.ref = ref;
|
||||
n.kind = kind;
|
||||
n.label = label;
|
||||
n.depth = depth;
|
||||
return n;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("clean_imgui_label keeps the shown part of an ImGui label", "[Mcp]")
|
||||
{
|
||||
CHECK(clean_imgui_label("Move##gizmo") == "Move");
|
||||
CHECK(clean_imgui_label("###hidden") == "");
|
||||
CHECK(clean_imgui_label("Plain") == "Plain");
|
||||
CHECK(clean_imgui_label("\x01" "Colored\x02##x") == "Colored");
|
||||
}
|
||||
|
||||
TEST_CASE("snapshot text shows depth, ref, kind, label, class and state", "[Mcp]")
|
||||
{
|
||||
UiNode button = node("w2", "button", "Slice plate", 1);
|
||||
button.cls = "Button";
|
||||
UiNode check = node("w3", "checkbox", "Auto arrange", 1);
|
||||
check.cls = "wxCheckBox";
|
||||
check.checked = 1;
|
||||
check.enabled = false;
|
||||
UiNode text = node("w4", "text", "", 2);
|
||||
text.cls = "TextInput";
|
||||
text.value = "0.2";
|
||||
text.focused = true;
|
||||
text.x = 10, text.y = 20, text.w = 80, text.h = 24;
|
||||
const std::string out = format_snapshot({node("w1", "window", "OrcaSlicer", 0), button, check, text}, 0);
|
||||
CHECK(out ==
|
||||
"[w1] window \"OrcaSlicer\"\n"
|
||||
" [w2] button \"Slice plate\" (Button)\n"
|
||||
" [w3] checkbox \"Auto arrange\" (wxCheckBox) [checked] [disabled]\n"
|
||||
" [w4] text = \"0.2\" (TextInput) [focused] @10,20 80x24\n");
|
||||
}
|
||||
|
||||
TEST_CASE("a truncated snapshot ends with a marker naming how much was left out", "[Mcp]")
|
||||
{
|
||||
const std::string out = format_snapshot({node("w1", "window", "Main", 0)}, 37);
|
||||
CHECK(out.find("... 37 more nodes") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST_CASE("refs are never reused and resolve to their payload while alive", "[Mcp]")
|
||||
{
|
||||
RefTable<FakeTarget> refs;
|
||||
std::set<std::string> seen;
|
||||
for (int i = 0; i < 100; ++i)
|
||||
CHECK(seen.insert(refs.add('w', 1, FakeTarget{"t" + std::to_string(i), {}}, [] { return true; })).second);
|
||||
std::string err;
|
||||
const std::string ref = refs.add('m', 1, FakeTarget{"menu", {{"menu", "File>Open"}}}, [] { return true; });
|
||||
CHECK(ref.front() == 'm');
|
||||
const FakeTarget* t = refs.resolve(ref, 1, err);
|
||||
REQUIRE(t != nullptr);
|
||||
CHECK(t->name == "menu");
|
||||
CHECK(t->locator == json{{"menu", "File>Open"}});
|
||||
CHECK(refs.resolve("w999999", 1, err) == nullptr);
|
||||
CHECK(err.find("Unknown ref") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST_CASE("a ref whose element is gone is stale", "[Mcp]")
|
||||
{
|
||||
RefTable<FakeTarget> refs;
|
||||
bool alive = true;
|
||||
const std::string ref = refs.add('w', 1, FakeTarget{"button", {}}, [&] { return alive; });
|
||||
std::string err;
|
||||
CHECK(refs.resolve(ref, 1, err) != nullptr);
|
||||
alive = false;
|
||||
CHECK(refs.resolve(ref, 1, err) == nullptr);
|
||||
CHECK(err.find("Stale ref") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST_CASE("a ref from before a UI rebuild is stale", "[Mcp]")
|
||||
{
|
||||
RefTable<FakeTarget> refs;
|
||||
const std::string ref = refs.add('w', 3, FakeTarget{"button", {}}, [] { return true; });
|
||||
std::string err;
|
||||
CHECK(refs.resolve(ref, 3, err) != nullptr);
|
||||
CHECK(refs.resolve(ref, 4, err) == nullptr);
|
||||
CHECK(err.find("Stale ref") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST_CASE("a menu ref is stale when its label path changed", "[Mcp]")
|
||||
{
|
||||
// Menu refs remember the label path they were listed under; a rebuilt menu (another language,
|
||||
// another layout) with the same id under a different path no longer matches.
|
||||
RefTable<FakeTarget> refs;
|
||||
std::string current_path = "File>Export>Export G-code";
|
||||
const std::string taken = current_path;
|
||||
const std::string ref = refs.add('m', 1, FakeTarget{"export", {{"menu", taken}}}, [&] { return current_path == taken; });
|
||||
std::string err;
|
||||
CHECK(refs.resolve(ref, 1, err) != nullptr);
|
||||
current_path = "Datei>Exportieren>G-Code exportieren";
|
||||
CHECK(refs.resolve(ref, 1, err) == nullptr);
|
||||
}
|
||||
|
||||
TEST_CASE("the ref table forgets the oldest refs beyond its cap", "[Mcp]")
|
||||
{
|
||||
RefTable<FakeTarget> refs;
|
||||
const std::string first = refs.add('w', 1, FakeTarget{}, [] { return true; });
|
||||
for (std::size_t i = 0; i < RefTable<FakeTarget>::kMaxRefs; ++i)
|
||||
refs.add('w', 1, FakeTarget{}, [] { return true; });
|
||||
std::string err;
|
||||
CHECK(refs.resolve(first, 1, err) == nullptr);
|
||||
CHECK(err.find("Unknown ref") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST_CASE("synthetic key state is visible through get_key_state and cleared after a gesture", "[Mcp]")
|
||||
{
|
||||
SyntheticInput::press_key(WXK_SHIFT);
|
||||
SyntheticInput::press_key(WXK_CONTROL);
|
||||
CHECK(SyntheticInput::is_key_down(WXK_SHIFT));
|
||||
CHECK(get_key_state(WXK_SHIFT));
|
||||
#ifndef __APPLE__
|
||||
// Elsewhere Control and raw control are the same key.
|
||||
CHECK(SyntheticInput::is_key_down(WXK_RAW_CONTROL));
|
||||
#endif
|
||||
SyntheticInput::release_key(WXK_SHIFT);
|
||||
CHECK_FALSE(SyntheticInput::is_key_down(WXK_SHIFT));
|
||||
CHECK(SyntheticInput::is_key_down(WXK_CONTROL));
|
||||
SyntheticInput::clear();
|
||||
CHECK_FALSE(SyntheticInput::is_key_down(WXK_CONTROL));
|
||||
}
|
||||
+17
-6
@@ -93,14 +93,20 @@ class OrcaMcp:
|
||||
"""Call a tool and return its JSON result; raise McpError when the tool reports an error.
|
||||
|
||||
A call that returns a job envelope (running / blocked_by_dialog) is returned as is."""
|
||||
return self.call_with_text(tool, _timeout, **args)[0]
|
||||
|
||||
def call_with_text(self, tool, _timeout=None, **args):
|
||||
"""Like call(), plus the text blocks after the JSON one (ui_snapshot's tree)."""
|
||||
result = self.call_raw(tool, args, timeout=_timeout)
|
||||
text = next((c["text"] for c in result.get("content", []) if c.get("type") == "text"), "")
|
||||
texts = [c["text"] for c in result.get("content", []) if c.get("type") == "text"]
|
||||
text = texts[0] if texts else ""
|
||||
if result.get("isError"):
|
||||
raise McpError(text, result)
|
||||
try:
|
||||
return json.loads(text) if text else {}
|
||||
data = json.loads(text) if text else {}
|
||||
except json.JSONDecodeError:
|
||||
return {"text": text}
|
||||
data = {"text": text}
|
||||
return data, texts[1:]
|
||||
|
||||
def images(self, tool, **args):
|
||||
"""Call a tool and return (json_result, [png bytes...]) for image content blocks."""
|
||||
@@ -263,7 +269,8 @@ def main():
|
||||
p.add_argument("--wait", action="store_true", help="follow a returned job to its result")
|
||||
|
||||
sub.add_parser("tools", help="list tools")
|
||||
sub.add_parser("snapshot", help="print the ui_snapshot tree")
|
||||
p = sub.add_parser("snapshot", help="print the ui_snapshot tree")
|
||||
p.add_argument("args", nargs="?", help="ui_snapshot arguments as JSON")
|
||||
|
||||
p = sub.add_parser("screenshot", help="save a screenshot")
|
||||
p.add_argument("out")
|
||||
@@ -281,15 +288,19 @@ def main():
|
||||
client, _ = session_client()
|
||||
try:
|
||||
if args.cmd == "call":
|
||||
result = client.call(args.tool, **json.loads(args.args))
|
||||
result, texts = client.call_with_text(args.tool, **json.loads(args.args))
|
||||
if args.wait:
|
||||
result = client.await_job(result)
|
||||
print(json.dumps(result, indent=2))
|
||||
for t in texts:
|
||||
print(t)
|
||||
elif args.cmd == "tools":
|
||||
for t in client.tools():
|
||||
print(f"{t['name']:20} {t.get('description', '').splitlines()[0][:100]}")
|
||||
elif args.cmd == "snapshot":
|
||||
print(client.call("ui_snapshot").get("tree", ""))
|
||||
a = json.loads(args.args) if getattr(args, "args", None) else {}
|
||||
data, texts = client.call_with_text("ui_snapshot", **a)
|
||||
print("\n".join(texts) or json.dumps(data, indent=2))
|
||||
elif args.cmd == "screenshot":
|
||||
out = os.path.abspath(args.out)
|
||||
print(json.dumps(client.call("screenshot", target=args.target, save_path=out, overwrite=True, include_image=False), indent=2))
|
||||
|
||||
Reference in new issue
Block a user