mirror of
https://github.com/OrcaSlicer/OrcaSlicer.git
synced 2026-11-25 23:01:09 -05:00
Start an opt-in MCP server with slicer, preset, action and screenshot tools
This commit is contained in:
1 parent
16c4ef8675
commit
dc522e59e4
58 files changed
+5234
-160
No files matched your search
@@ -14,6 +14,10 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
// OrcaSlicer: let automation (the MCP server) record items through the test-engine hooks, which
|
||||
// ImGuiWrapper implements. ImGui calls them only while ImGuiContext::TestEngineHookItems is set.
|
||||
#define IMGUI_ENABLE_TEST_ENGINE
|
||||
|
||||
//---- Define assertion handler. Defaults to calling assert().
|
||||
// If your macro uses multiple statements, make sure is enclosed in a 'do { .. } while (0)' block so it can be used as a single statement.
|
||||
//#define IM_ASSERT(_EXPR) MyAssert(_EXPR)
|
||||
|
||||
@@ -7219,7 +7219,7 @@ bool ImGui::BBLImageSelectable(ImTextureID user_texture_id, const ImVec2& size_a
|
||||
if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_DontClosePopups) && !(g.CurrentItemFlags & ImGuiItemFlags_SelectableDontClosePopup))
|
||||
CloseCurrentPopup();
|
||||
|
||||
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags);
|
||||
IMGUI_TEST_ENGINE_ITEM_INFO(id, NULL, window->DC.LastItemStatusFlags);
|
||||
|
||||
return pressed;
|
||||
}
|
||||
|
||||
@@ -169,6 +169,7 @@ using json = nlohmann::json;
|
||||
|
||||
#ifdef SLIC3R_GUI
|
||||
#include "slic3r/GUI/GUI_Init.hpp"
|
||||
#include "slic3r/GUI/Mcp/McpStdioBridge.hpp"
|
||||
// BBLPrinterAgent::from_orca_filament_id(); the map and its lookups live in libslic3r_gui,
|
||||
// which only a SLIC3R_GUI build links (see target_link_libraries(OrcaSlicer libslic3r_gui)
|
||||
// in CMakeLists).
|
||||
@@ -1203,6 +1204,13 @@ int CLI::run(int argc, char **argv)
|
||||
// Save the thread ID of the main thread.
|
||||
save_main_thread_id();
|
||||
|
||||
#ifdef SLIC3R_GUI
|
||||
// The stdio bridge is a plain pipe to a running GUI instance; it needs none of the setup below.
|
||||
for (int i = 1; i < argc; ++i)
|
||||
if (std::strcmp(argv[i], "--mcp-stdio") == 0)
|
||||
return Slic3r::GUI::Mcp::run_stdio_bridge(argc, argv);
|
||||
#endif
|
||||
|
||||
#ifdef __WXGTK__
|
||||
// ------------------------------------------------------------------
|
||||
// Linux backend selection — runtime, based on GDK_BACKEND env var.
|
||||
@@ -1511,6 +1519,18 @@ int CLI::run(int argc, char **argv)
|
||||
//BBS: remove GCodeViewer as separate APP logic
|
||||
//params.start_as_gcodeviewer = start_as_gcodeviewer;
|
||||
|
||||
if (const auto *opt = m_config.opt<ConfigOptionBool>("mcp"))
|
||||
params.mcp.enable = opt->value;
|
||||
if (const auto *opt = m_config.opt<ConfigOptionInt>("mcp_port"))
|
||||
params.mcp.port = opt->value;
|
||||
if (const auto *opt = m_config.opt<ConfigOptionString>("mcp_token"))
|
||||
params.mcp.token = opt->value;
|
||||
// Resolved now: the GUI moves the working directory to <data_dir>/log before the script runs.
|
||||
if (const auto *opt = m_config.opt<ConfigOptionString>("mcp_script"))
|
||||
params.mcp.script = resolve_cli_input_path(opt->value);
|
||||
if (const auto *opt = m_config.opt<ConfigOptionString>("mcp_script_out"))
|
||||
params.mcp.script_out = resolve_cli_input_path(opt->value);
|
||||
|
||||
BOOST_LOG_TRIVIAL(info) << "begin to launch OrcaSlicer GUI soon";
|
||||
return Slic3r::GUI::GUI_Run(params);
|
||||
#else // SLIC3R_GUI
|
||||
|
||||
@@ -13173,6 +13173,42 @@ CLIMiscConfigDef::CLIMiscConfigDef()
|
||||
def->tooltip = L("Load and store settings at the given directory. This is useful for maintaining different profiles or including configurations from a network storage.");
|
||||
|
||||
|
||||
def = this->add("mcp", coBool);
|
||||
def->label = L("MCP server");
|
||||
def->tooltip = L("Start the MCP server for AI agents on 127.0.0.1 for this run, whatever the preference says.");
|
||||
def->set_default_value(new ConfigOptionBool(false));
|
||||
|
||||
def = this->add("mcp_port", coInt);
|
||||
def->label = L("MCP server port");
|
||||
def->tooltip = L("Port of the MCP server. Defaults to the preference, or 13619.");
|
||||
def->cli_params = "port";
|
||||
def->min = 0;
|
||||
def->max = 65535;
|
||||
def->set_default_value(new ConfigOptionInt(0));
|
||||
|
||||
def = this->add("mcp_token", coString);
|
||||
def->label = L("MCP server token");
|
||||
def->tooltip = L("Bearer token the MCP server requires for this run. The ORCA_MCP_TOKEN environment variable takes precedence and does not show up in the process list.");
|
||||
def->cli_params = "token";
|
||||
def->set_default_value(new ConfigOptionString());
|
||||
|
||||
def = this->add("mcp_script", coString);
|
||||
def->label = L("MCP script");
|
||||
def->tooltip = L("Run an MCP script once the GUI is ready, write its results, and exit: 0 when it passed, 1 when a step failed, 2 when the script is invalid.");
|
||||
def->cli_params = "file";
|
||||
def->set_default_value(new ConfigOptionString());
|
||||
|
||||
def = this->add("mcp_script_out", coString);
|
||||
def->label = L("MCP script output directory");
|
||||
def->tooltip = L("Where --mcp-script writes result.json and screenshots. Defaults to <script name>.out next to the script.");
|
||||
def->cli_params = "dir";
|
||||
def->set_default_value(new ConfigOptionString());
|
||||
|
||||
def = this->add("mcp_stdio", coBool);
|
||||
def->label = L("MCP stdio bridge");
|
||||
def->tooltip = L("Act as an MCP server on standard input and output for clients that cannot use HTTP, forwarding to the running OrcaSlicer (started with --mcp when none answers).");
|
||||
def->set_default_value(new ConfigOptionBool(false));
|
||||
|
||||
def = this->add("outputdir", coString);
|
||||
def->label = L("Output directory");
|
||||
def->tooltip = L("This is the output directory for exported files.");
|
||||
|
||||
@@ -148,9 +148,31 @@ set(SLIC3R_GUI_SOURCES
|
||||
GUI/Mcp/McpOperations.hpp
|
||||
GUI/Mcp/McpProtocol.cpp
|
||||
GUI/Mcp/McpProtocol.hpp
|
||||
GUI/Mcp/McpOptions.hpp
|
||||
GUI/Mcp/McpScript.cpp
|
||||
GUI/Mcp/McpScript.hpp
|
||||
GUI/Mcp/McpService.cpp
|
||||
GUI/Mcp/McpService.hpp
|
||||
GUI/Mcp/McpStdioBridge.cpp
|
||||
GUI/Mcp/McpStdioBridge.hpp
|
||||
GUI/Mcp/McpToken.cpp
|
||||
GUI/Mcp/McpToken.hpp
|
||||
GUI/Mcp/McpTools.hpp
|
||||
GUI/Mcp/McpPaths.cpp
|
||||
GUI/Mcp/McpPaths.hpp
|
||||
GUI/Mcp/McpToolsActions.cpp
|
||||
GUI/Mcp/McpToolsApp.cpp
|
||||
GUI/Mcp/McpToolsCommon.cpp
|
||||
GUI/Mcp/McpToolsConfig.cpp
|
||||
GUI/Mcp/McpToolsPending.cpp
|
||||
GUI/Mcp/McpToolsProject.cpp
|
||||
GUI/Mcp/McpToolsScene.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/UiInvoker.cpp
|
||||
GUI/Mcp/UiInvoker.hpp
|
||||
GUI/PluginsConfigDialog.cpp
|
||||
@@ -901,6 +923,7 @@ if (WIN32)
|
||||
GUI/dark_mode/UAHMenuBar.hpp
|
||||
GUI/dark_mode.hpp
|
||||
GUI/dark_mode.cpp
|
||||
GUI/Mcp/ScreenCapture_win.cpp
|
||||
)
|
||||
endif ()
|
||||
|
||||
@@ -918,6 +941,7 @@ if (APPLE)
|
||||
GUI/GUI_UtilsMac.mm
|
||||
GUI/MacIME.mm
|
||||
GUI/MacIME.hpp
|
||||
GUI/Mcp/ScreenCapture_mac.mm
|
||||
)
|
||||
FIND_LIBRARY(DISKARBITRATION_LIBRARY DiskArbitration)
|
||||
endif ()
|
||||
|
||||
@@ -34,6 +34,7 @@
|
||||
#include <boost/nowide/convert.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cmath>
|
||||
#include <ctime>
|
||||
#include <exception>
|
||||
@@ -163,7 +164,10 @@ struct PluginScriptAction : AppAction
|
||||
std::move(source_name))
|
||||
, plugin_key(std::move(plugin_key_in))
|
||||
, capability(std::move(capability_in))
|
||||
{}
|
||||
{
|
||||
this->automation_description = "Run the plugin script \"" + this->title() + "\" (" + this->source_name() +
|
||||
"). Its result arrives as a notification.";
|
||||
}
|
||||
|
||||
AppActionRunResult run(const std::string& /*param*/) const override
|
||||
{
|
||||
@@ -236,7 +240,8 @@ struct PluginPageAction : AppAction
|
||||
, capability(std::move(capability_in))
|
||||
{
|
||||
// Stay classified as a plugin: grouped under "Plugins" and gated by the same run-confirm.
|
||||
this->kind = AppActionKind::Plugin;
|
||||
this->kind = AppActionKind::Plugin;
|
||||
this->automation_description = "Open the plugin page \"" + this->title() + "\" (" + this->source_name() + ").";
|
||||
// Icon is left empty on purpose: the webview builds resources/images/<icon>.svg, which a
|
||||
// plugin filesystem icon path would not resolve to.
|
||||
}
|
||||
@@ -402,9 +407,10 @@ struct PlateAction : AppAction
|
||||
PlateAction(int index, std::string title, std::string source_name)
|
||||
: AppAction(AppActionId{id_for(index)}, std::move(title), kOrcaSourceKey, std::move(source_name)), plate_index(index)
|
||||
{
|
||||
this->kind = AppActionKind::Command;
|
||||
this->group_en = L("Plate");
|
||||
this->group = I18N::translate_utf8(this->group_en);
|
||||
this->kind = AppActionKind::Command;
|
||||
this->group_en = L("Plate");
|
||||
this->group = I18N::translate_utf8(this->group_en);
|
||||
this->automation_description = "Make plate " + std::to_string(index + 1) + " (index " + std::to_string(index) + ") the current plate.";
|
||||
}
|
||||
|
||||
AppActionRunResult run(const std::string& /*param*/) const override
|
||||
@@ -426,9 +432,10 @@ struct RecentProjectAction : AppAction
|
||||
RecentProjectAction(std::string path, std::string title, std::string source)
|
||||
: AppAction(AppActionId{id_for(path)}, std::move(title), kOrcaSourceKey, std::move(source)), file_path(std::move(path))
|
||||
{
|
||||
this->kind = AppActionKind::Command;
|
||||
this->group_en = L("Recent Projects");
|
||||
this->group = I18N::translate_utf8(this->group_en);
|
||||
this->kind = AppActionKind::Command;
|
||||
this->group_en = L("Recent Projects");
|
||||
this->group = I18N::translate_utf8(this->group_en);
|
||||
this->automation_description = "Open the recent project " + file_path + ".";
|
||||
}
|
||||
|
||||
AppActionRunResult run(const std::string& /*param*/) const override
|
||||
@@ -690,7 +697,7 @@ AppAction* ActionRegistry::find(const std::string& id) { return const_cast<AppAc
|
||||
|
||||
// ---- dispatch + write-through ----------------------------------------------
|
||||
|
||||
AppActionRunResult ActionRegistry::run(const std::string& id, const std::string& param)
|
||||
AppActionRunResult ActionRegistry::run(const std::string& id, const std::string& param, bool record_stats)
|
||||
{
|
||||
assert(wxThread::IsMain());
|
||||
auto it = m_actions.find(id);
|
||||
@@ -701,7 +708,7 @@ AppActionRunResult ActionRegistry::run(const std::string& id, const std::string&
|
||||
// keep-alive preserves the action until run returns.
|
||||
std::shared_ptr<AppAction> keep = it->second;
|
||||
AppActionRunResult o = keep->run(param);
|
||||
if (o.level == AppActionRunResult::Level::Busy)
|
||||
if (o.level == AppActionRunResult::Level::Busy || !record_stats)
|
||||
return o;
|
||||
|
||||
// Bump stats (write-through). Re-read to avoid clobbering a concurrent field.
|
||||
@@ -1037,6 +1044,77 @@ nlohmann::json ActionRegistry::snapshot()
|
||||
{"tooltip_expanded", tooltip_expanded()}};
|
||||
}
|
||||
|
||||
// ---- automation catalog -------------------------------------------------------
|
||||
|
||||
nlohmann::json ActionRegistry::describe(const Query& query)
|
||||
{
|
||||
assert(wxThread::IsMain());
|
||||
materialize_plate_actions();
|
||||
materialize_recent_project_actions();
|
||||
if (query.include_settings)
|
||||
materialize_setting_actions();
|
||||
|
||||
auto lower = [](std::string s) {
|
||||
std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return char(std::tolower(c)); });
|
||||
return s;
|
||||
};
|
||||
const std::string text = lower(query.text);
|
||||
const std::string group = lower(query.group);
|
||||
|
||||
std::vector<const AppAction*> matches;
|
||||
for (const auto& [id, action] : m_actions) {
|
||||
const AppAction& a = *action;
|
||||
if (!query.include_settings && id.rfind(kSettingPrefix, 0) == 0)
|
||||
continue;
|
||||
if (!group.empty() && lower(a.group) != group && lower(a.group_en) != group)
|
||||
continue;
|
||||
if (!text.empty()) {
|
||||
bool hit = false;
|
||||
for (const std::string* field : {&a.id(), &a.title(), &a.title_en, &a.group, &a.group_en, &a.source_name(), &a.source_en,
|
||||
&a.full_label, &a.full_label_en, &a.automation_description})
|
||||
if (lower(*field).find(text) != std::string::npos) {
|
||||
hit = true;
|
||||
break;
|
||||
}
|
||||
if (!hit)
|
||||
continue;
|
||||
}
|
||||
matches.push_back(&a);
|
||||
}
|
||||
std::sort(matches.begin(), matches.end(), [](const AppAction* a, const AppAction* b) {
|
||||
const std::string& ga = a->group_en.empty() ? a->group : a->group_en;
|
||||
const std::string& gb = b->group_en.empty() ? b->group : b->group_en;
|
||||
if (ga != gb)
|
||||
return ga < gb;
|
||||
if (a->title() != b->title())
|
||||
return a->title() < b->title();
|
||||
return a->id() < b->id();
|
||||
});
|
||||
|
||||
nlohmann::json actions = nlohmann::json::array();
|
||||
for (std::size_t i = query.offset; i < matches.size() && actions.size() < query.limit; ++i) {
|
||||
const AppAction& a = *matches[i];
|
||||
nlohmann::json j{{"id", a.id()},
|
||||
{"title", a.title_en.empty() ? a.title() : a.title_en},
|
||||
{"group", a.group_en.empty() ? (a.group.empty() ? a.source_name() : a.group) : a.group_en},
|
||||
{"kind", a.kind == AppActionKind::Plugin ? "plugin" : "command"}};
|
||||
std::string description = a.automation_description;
|
||||
if (description.empty() && !a.tooltip.empty())
|
||||
description = a.tooltip.substr(0, 300);
|
||||
if (!description.empty())
|
||||
j["description"] = description;
|
||||
if (a.param_type != "none")
|
||||
j["param"] = {{"type", a.param_type}, {"help", a.param_help}};
|
||||
if (a.completes_in_background)
|
||||
j["completes"] = "export";
|
||||
actions.push_back(std::move(j));
|
||||
}
|
||||
nlohmann::json out{{"total", matches.size()}, {"offset", query.offset}, {"actions", std::move(actions)}};
|
||||
if (query.offset + query.limit < matches.size())
|
||||
out["next_offset"] = query.offset + query.limit;
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- tab options (enumerate the MainFrame notebook's current pages) ----------
|
||||
|
||||
nlohmann::json ActionRegistry::tab_options() const
|
||||
|
||||
@@ -98,6 +98,13 @@ struct AppAction
|
||||
std::string full_label_en;
|
||||
// Full wiki URL, when the action has one (SettingActions whose row declared a label_path).
|
||||
std::string help_url;
|
||||
// For automation (MCP, scripts): what the action does in English, what `param` means
|
||||
// ("none", "percent", "tab", "path", "index", "text") and whether its effect finishes after
|
||||
// run() returns (an export that runs in the background). Not shown in the palette.
|
||||
std::string automation_description;
|
||||
std::string param_type = "none";
|
||||
std::string param_help;
|
||||
bool completes_in_background = false;
|
||||
|
||||
virtual ~AppAction() = default;
|
||||
// Re-resolves + runs (UI thread). `param` carries an optional per-run argument for
|
||||
@@ -194,8 +201,22 @@ public:
|
||||
// Hard cap on the favourites bar: the numbered quick-launch slots (Alt/Option+1..9, 0).
|
||||
static constexpr size_t kFavLimit = 10;
|
||||
|
||||
// Dispatch + write-through (registry is the only thing that touches AppConfig).
|
||||
AppActionRunResult run(const std::string& id, const std::string& param = {}); // runs + bumps stats
|
||||
// Dispatch + write-through (registry is the only thing that touches AppConfig). Automation passes
|
||||
// record_stats = false so agent runs don't reorder the user's palette.
|
||||
AppActionRunResult run(const std::string& id, const std::string& param = {}, bool record_stats = true);
|
||||
|
||||
// The catalog for agents: actions whose id, title, group, source or description contains `text`
|
||||
// (case-insensitive, English aliases included), sorted by group then title, paged. Settings are
|
||||
// listed only when asked for, since there are thousands.
|
||||
struct Query
|
||||
{
|
||||
std::string text;
|
||||
std::string group;
|
||||
bool include_settings = false;
|
||||
std::size_t offset = 0;
|
||||
std::size_t limit = 50;
|
||||
};
|
||||
nlohmann::json describe(const Query& query);
|
||||
// Pin/unpin. Returns false when `on` would exceed kFavLimit (the bar is full) so the
|
||||
// caller can surface a "favourites are full" hint instead of silently dropping the pin.
|
||||
bool set_favourite(const std::string& id, bool on);
|
||||
|
||||
@@ -2517,6 +2517,27 @@ void GLCanvas3D::render(bool only_init)
|
||||
_render_frame(true, only_init);
|
||||
}
|
||||
|
||||
bool GLCanvas3D::render_and_capture(wxImage& out, std::string& err)
|
||||
{
|
||||
if (m_in_render) {
|
||||
err = "The 3D view is in the middle of drawing a frame (a dialog was opened from it); capture the window instead";
|
||||
return false;
|
||||
}
|
||||
if (m_canvas == nullptr || !_is_shown_on_screen()) {
|
||||
err = "The 3D view is not shown; switch to the Prepare or Preview tab first";
|
||||
return false;
|
||||
}
|
||||
out = wxImage();
|
||||
m_frame_capture = &out;
|
||||
Slic3r::ScopeGuard reset([this]() { m_frame_capture = nullptr; });
|
||||
render();
|
||||
if (!out.IsOk()) {
|
||||
err = "The 3D view did not draw a frame";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void GLCanvas3D::_render_frame(bool scene_dirty, bool only_init)
|
||||
{
|
||||
if (m_in_render) {
|
||||
@@ -2600,6 +2621,8 @@ void GLCanvas3D::_render_frame(bool scene_dirty, bool only_init)
|
||||
|
||||
camera.apply_projection(_max_bounding_box(true, true, true));
|
||||
|
||||
// Automation records ImGui items per canvas (ImGuiWrapper::set_item_recording).
|
||||
wxGetApp().imgui()->set_frame_owner(this);
|
||||
wxGetApp().imgui()->new_frame();
|
||||
|
||||
if (_update_inactive_plates_visibility())
|
||||
@@ -2773,6 +2796,28 @@ void GLCanvas3D::_render_frame(bool scene_dirty, bool only_init)
|
||||
wxGetApp().imgui()->render(draw_data);
|
||||
m_frame_profiler.mark("imgui draw");
|
||||
|
||||
if (m_frame_capture != nullptr) {
|
||||
const Size size = get_canvas_size();
|
||||
const int w = size.get_width(), h = size.get_height();
|
||||
if (w > 0 && h > 0) {
|
||||
std::vector<unsigned char> pixels(size_t(w) * size_t(h) * 4);
|
||||
glsafe(::glPixelStorei(GL_PACK_ALIGNMENT, 1));
|
||||
glsafe(::glReadBuffer(GL_BACK));
|
||||
glsafe(::glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data()));
|
||||
m_frame_capture->Create(w, h, false);
|
||||
unsigned char* rgb = m_frame_capture->GetData();
|
||||
// OpenGL rows run bottom-up.
|
||||
for (int y = 0; y < h; ++y) {
|
||||
const unsigned char* src = pixels.data() + size_t(h - 1 - y) * size_t(w) * 4;
|
||||
for (int x = 0; x < w; ++x, src += 4, rgb += 3) {
|
||||
rgb[0] = src[0];
|
||||
rgb[1] = src[1];
|
||||
rgb[2] = src[2];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// On Wayland, eglSwapBuffers blocks when the canvas is hidden or
|
||||
// occluded. Skip the swap to avoid stalling the render loop.
|
||||
// Code run from inside this frame - a modal dialog a gizmo opened from its ImGui panel, a
|
||||
|
||||
@@ -52,6 +52,8 @@
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <wx/string.h>
|
||||
|
||||
class wxImage;
|
||||
#include <wx/colour.h>
|
||||
#include <wx/time.h>
|
||||
#include <wx/timer.h>
|
||||
@@ -647,6 +649,8 @@ private:
|
||||
#endif
|
||||
unsigned int m_last_w, m_last_h;
|
||||
bool m_in_render;
|
||||
// Set only during render_and_capture(): the frame is read back into it before the swap.
|
||||
wxImage* m_frame_capture{ nullptr };
|
||||
// How many canvases are inside _render_frame() right now - see is_frame_in_progress().
|
||||
static int s_frames_in_progress;
|
||||
wxTimer m_timer;
|
||||
@@ -1158,6 +1162,11 @@ public:
|
||||
bool has_mouse_capture() const;
|
||||
|
||||
void render(bool only_init = false);
|
||||
// Draws a full frame now and copies it, as presented (scene, toolpaths, toolbars and ImGui
|
||||
// overlays), into `out` at the canvas's pixel size. Used by automation screenshots. Fails with
|
||||
// `err` when the canvas is hidden, not drawable, or already inside a frame (a dialog opened
|
||||
// from one of its panels). UI thread.
|
||||
bool render_and_capture(wxImage& out, std::string& err);
|
||||
bool is_rendering_enabled()
|
||||
{
|
||||
return m_enable_render;
|
||||
|
||||
@@ -255,6 +255,8 @@
|
||||
#include "slic3r/GUI/ConfigWizardTypes.hpp"
|
||||
#include "slic3r/GUI/Gizmos/GLGizmosManager.hpp"
|
||||
#include "slic3r/GUI/HttpServer.hpp"
|
||||
#include "slic3r/GUI/Mcp/McpOptions.hpp"
|
||||
#include "slic3r/GUI/Mcp/McpService.hpp"
|
||||
#include "slic3r/GUI/ImGuiWrapper.hpp"
|
||||
#include "slic3r/GUI/ParamsDialog.hpp"
|
||||
#include "slic3r/GUI/ParamsPanel.hpp"
|
||||
@@ -1233,6 +1235,9 @@ void GUI_App::post_init()
|
||||
if (m_startup_cloud_report)
|
||||
std::exchange(m_startup_cloud_report, nullptr)();
|
||||
|
||||
if (m_mcp)
|
||||
m_mcp->mark_ready();
|
||||
|
||||
BOOST_LOG_TRIVIAL(info) << "finished post_init";
|
||||
//BBS: remove the single instance currently
|
||||
#ifdef _WIN32
|
||||
@@ -2845,6 +2850,8 @@ void GUI_App::init_app_config()
|
||||
// MainFrame shortcut read the same value; an existing config (true or false) is left untouched.
|
||||
if (app_config->get("enable_speed_dial").empty())
|
||||
app_config->set_bool("enable_speed_dial", true);
|
||||
if (app_config->get("mcp_port").empty())
|
||||
app_config->set("mcp_port", std::to_string(Mcp::kDefaultPort));
|
||||
set_logging_level(Slic3r::level_string_to_boost(app_config->get("log_severity_level")));
|
||||
|
||||
}
|
||||
@@ -2925,6 +2932,7 @@ bool GUI_App::OnInit()
|
||||
|
||||
int GUI_App::OnExit()
|
||||
{
|
||||
stop_mcp_service();
|
||||
stop_http_server();
|
||||
stop_sync_user_preset();
|
||||
if (m_startup_cloud_plugin_fetch_thread.joinable())
|
||||
@@ -2987,6 +2995,9 @@ void GUI_App::CleanUp()
|
||||
stop_orca_health_check(m_agent);
|
||||
if (m_startup_cloud_plugin_fetch_thread.joinable())
|
||||
m_startup_cloud_plugin_fetch_thread.join();
|
||||
// Same reason: the MCP server started before the first startup dialog, so an initialization that
|
||||
// failed after it never reaches OnExit().
|
||||
stop_mcp_service();
|
||||
wxApp::CleanUp();
|
||||
}
|
||||
|
||||
@@ -3273,6 +3284,7 @@ bool GUI_App::on_init_inner()
|
||||
// Stop the Orca Cloud health check as OnExit() does, so no request is in flight while exit() tears down.
|
||||
wxGetApp().Bind(wxEVT_END_SESSION, [this](wxCloseEvent &e) {
|
||||
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << "received wxEVT_END_SESSION";
|
||||
stop_mcp_service();
|
||||
stop_sync_user_preset();
|
||||
stop_orca_health_check(m_agent);
|
||||
// Before the plugin manager and network module go away.
|
||||
@@ -3337,6 +3349,14 @@ bool GUI_App::on_init_inner()
|
||||
// wxSystemOptions::SetOption("msw.notebook.themed-background", 0);
|
||||
|
||||
// Slic3r::debugf "wxWidgets version %s, Wx version %s\n", wxVERSION_STRING, wxVERSION;
|
||||
// The MCP server starts before the first startup dialog (the TLS prompt below, the setup wizard)
|
||||
// so an agent can see and answer it; tools that need the main window report not-ready until
|
||||
// post_init() has run.
|
||||
if (init_params != nullptr) {
|
||||
const bool serve = init_params->mcp.enable || app_config->get_bool("mcp_enabled");
|
||||
if (serve || !init_params->mcp.script.empty())
|
||||
start_mcp_service(serve);
|
||||
}
|
||||
if (is_editor()) {
|
||||
std::string msg = Slic3r::Http::tls_global_init();
|
||||
std::string ssl_cert_store = app_config->get("tls_accepted_cert_store_location");
|
||||
@@ -5047,6 +5067,8 @@ void GUI_App::recreate_GUI(const wxString &msg_name)
|
||||
update_publish_status();
|
||||
|
||||
m_is_recreating_gui = false;
|
||||
if (m_mcp)
|
||||
m_mcp->resume();
|
||||
|
||||
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << "recreate_GUI exit";
|
||||
}
|
||||
@@ -8435,6 +8457,43 @@ void GUI_App::stop_http_server()
|
||||
m_http_server->stop();
|
||||
}
|
||||
|
||||
bool GUI_App::start_mcp_service(bool serve, std::string* error)
|
||||
{
|
||||
// Only the launch options from the command line carry a script; a later start from Preferences
|
||||
// must not run it again.
|
||||
Mcp::McpLaunchOptions options;
|
||||
if (init_params != nullptr && !m_post_initialized)
|
||||
options = init_params->mcp;
|
||||
else if (init_params != nullptr) {
|
||||
options.port = init_params->mcp.port;
|
||||
options.token = init_params->mcp.token;
|
||||
}
|
||||
if (!m_mcp)
|
||||
m_mcp = std::make_unique<Mcp::McpService>();
|
||||
std::string err;
|
||||
const bool ok = m_mcp->start(options, serve, err);
|
||||
if (!ok) {
|
||||
BOOST_LOG_TRIVIAL(error) << err;
|
||||
if (plater() != nullptr)
|
||||
plater()->get_notification_manager()->push_notification(NotificationType::CustomNotification,
|
||||
NotificationManager::NotificationLevel::ErrorNotificationLevel,
|
||||
err);
|
||||
}
|
||||
if (m_post_initialized)
|
||||
m_mcp->mark_ready();
|
||||
if (error != nullptr)
|
||||
*error = err;
|
||||
return ok;
|
||||
}
|
||||
|
||||
void GUI_App::stop_mcp_service()
|
||||
{
|
||||
if (!m_mcp)
|
||||
return;
|
||||
m_mcp->stop();
|
||||
m_mcp.reset();
|
||||
}
|
||||
|
||||
#ifdef __linux__
|
||||
static const wxLanguageInfo* linux_get_existing_locale_language(const wxLanguageInfo* language,
|
||||
const wxLanguageInfo* system_language)
|
||||
|
||||
@@ -114,6 +114,7 @@ class SpeedDialWebDialog;
|
||||
class TerminalDialog;
|
||||
class ActionRegistry;
|
||||
class HttpServer;
|
||||
namespace Mcp { class McpService; }
|
||||
class ImGuiWrapper;
|
||||
class OpenGLManager;
|
||||
class UpgradeNetworkJob;
|
||||
@@ -383,6 +384,7 @@ private:
|
||||
bool m_show_error_msgdlg{false};
|
||||
wxString m_info_dialog_content;
|
||||
std::unique_ptr<HttpServer> m_http_server;
|
||||
std::unique_ptr<Mcp::McpService> m_mcp;
|
||||
bool m_show_gcode_window{true};
|
||||
boost::thread m_check_network_thread;
|
||||
public:
|
||||
@@ -661,6 +663,12 @@ public:
|
||||
void start_http_server(int port, const std::string& provider = ORCA_CLOUD_PROVIDER);
|
||||
void stop_http_server();
|
||||
|
||||
// MCP server for AI agents, from Preferences or --mcp/--mcp-script. `serve` opens the HTTP
|
||||
// endpoint; a --mcp-script alone needs only the tool catalog. UI thread.
|
||||
bool start_mcp_service(bool serve, std::string* error = nullptr);
|
||||
void stop_mcp_service();
|
||||
Mcp::McpService* mcp_service() { return m_mcp.get(); }
|
||||
|
||||
void on_show_check_privacy_dlg(int online_login = 0, const std::string& provider = ORCA_CLOUD_PROVIDER);
|
||||
void show_check_privacy_dlg(wxCommandEvent& evt);
|
||||
void on_check_privacy_update(wxCommandEvent &evt);
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
#include "slic3r/GUI/GUI_App.hpp"
|
||||
#include "slic3r/GUI/InstanceCheck.hpp"
|
||||
#include "slic3r/GUI/Mcp/McpService.hpp"
|
||||
#include "slic3r/GUI/format.hpp"
|
||||
#include "slic3r/GUI/MainFrame.hpp"
|
||||
#include "slic3r/GUI/I18N.hpp"
|
||||
@@ -61,16 +62,21 @@ int GUI_Run(GUI_InitParams ¶ms)
|
||||
GUI::GUI_App::SetInstance(gui);
|
||||
gui->init_params = ¶ms;
|
||||
|
||||
int result = 0;
|
||||
if (params.argc > 1) {
|
||||
// STUDIO-273 wxWidgets report error when opening some files with specific names
|
||||
// wxWidgets does not handle parameters, so intercept parameters here, only keep the app name
|
||||
int argc = 1;
|
||||
std::vector<char *> argv;
|
||||
argv.push_back(params.argv[0]);
|
||||
return wxEntry(argc, argv.data());
|
||||
result = wxEntry(argc, argv.data());
|
||||
} else {
|
||||
return wxEntry(params.argc, params.argv);
|
||||
result = wxEntry(params.argc, params.argv);
|
||||
}
|
||||
// An --mcp-script run reports its outcome as the process exit code.
|
||||
if (const int script_code = Mcp::McpService::script_exit_code(); script_code >= 0)
|
||||
return script_code;
|
||||
return result;
|
||||
} catch (const Slic3r::Exception &ex) {
|
||||
BOOST_LOG_TRIVIAL(error) << ex.what() << std::endl;
|
||||
wxMessageBox(boost::nowide::widen(ex.what()), _L("Orca Slicer GUI initialization failed"), wxICON_STOP);
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
#include <libslic3r/Preset.hpp>
|
||||
#include <libslic3r/PrintConfig.hpp>
|
||||
#include "slic3r/GUI/Mcp/McpOptions.hpp"
|
||||
#include <vector>
|
||||
#include <utility>
|
||||
#include <string>
|
||||
@@ -35,6 +36,8 @@ struct GUI_InitParams
|
||||
//BBS: remove start_as_gcodeviewer logic
|
||||
//bool start_as_gcodeviewer;
|
||||
bool input_gcode { false };
|
||||
|
||||
Mcp::McpLaunchOptions mcp;
|
||||
};
|
||||
|
||||
int GUI_Run(GUI_InitParams ¶ms);
|
||||
|
||||
@@ -581,6 +581,7 @@ void ImGuiWrapper::new_frame()
|
||||
if (m_new_frame_open) {
|
||||
return;
|
||||
}
|
||||
m_frame_items.clear();
|
||||
|
||||
if (m_font_texture == 0) {
|
||||
init_font(true);
|
||||
@@ -626,6 +627,8 @@ void ImGuiWrapper::new_frame()
|
||||
|
||||
ImDrawData* ImGuiWrapper::end_frame()
|
||||
{
|
||||
if (m_item_recording && m_frame_owner != nullptr)
|
||||
m_recorded_items[m_frame_owner] = m_frame_items;
|
||||
#ifdef __APPLE__
|
||||
// io.ImeWindowHandle is the focused canvas' view (GLCanvas3D::on_set_focus()).
|
||||
if (void* view = ImGui::GetIO().ImeWindowHandle)
|
||||
@@ -636,6 +639,48 @@ ImDrawData* ImGuiWrapper::end_frame()
|
||||
return ImGui::GetDrawData();
|
||||
}
|
||||
|
||||
void ImGuiWrapper::set_item_recording(bool on)
|
||||
{
|
||||
m_item_recording = on;
|
||||
if (ImGuiContext* ctx = ImGui::GetCurrentContext())
|
||||
ctx->TestEngineHookItems = on;
|
||||
if (!on) {
|
||||
m_frame_items.clear();
|
||||
m_recorded_items.clear();
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<ImGuiWrapper::RecordedItem> ImGuiWrapper::recorded_items(const void* owner) const
|
||||
{
|
||||
auto it = m_recorded_items.find(owner);
|
||||
return it == m_recorded_items.end() ? std::vector<RecordedItem>{} : it->second;
|
||||
}
|
||||
|
||||
void ImGuiWrapper::record_item_add(unsigned id, float x0, float y0, float x1, float y1, const char* window)
|
||||
{
|
||||
// ImGui reports an item again when it re-submits it within a frame; keep the last rectangle.
|
||||
for (RecordedItem& item : m_frame_items)
|
||||
if (item.id == id) {
|
||||
item.x = x0, item.y = y0, item.w = x1 - x0, item.h = y1 - y0;
|
||||
return;
|
||||
}
|
||||
RecordedItem item;
|
||||
item.id = id;
|
||||
item.window = window != nullptr ? window : "";
|
||||
item.x = x0, item.y = y0, item.w = x1 - x0, item.h = y1 - y0;
|
||||
m_frame_items.push_back(std::move(item));
|
||||
}
|
||||
|
||||
void ImGuiWrapper::record_item_info(unsigned id, const char* label, int flags)
|
||||
{
|
||||
for (auto it = m_frame_items.rbegin(); it != m_frame_items.rend(); ++it)
|
||||
if (it->id == id) {
|
||||
it->label = label != nullptr ? label : "";
|
||||
it->flags = flags;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void ImGuiWrapper::render(ImDrawData* draw_data)
|
||||
{
|
||||
render_draw_data(draw_data);
|
||||
@@ -3703,3 +3748,21 @@ bool IMTexture::load_from_svg_file(const std::string& filename, unsigned width,
|
||||
|
||||
} // namespace GUI
|
||||
} // namespace Slic3r
|
||||
|
||||
// ImGui's test-engine hooks (IMGUI_ENABLE_TEST_ENGINE in imconfig.h). ImGui calls them only while
|
||||
// ImGuiContext::TestEngineHookItems is set, i.e. while ImGuiWrapper records items for automation.
|
||||
void ImGuiTestEngineHook_ItemAdd(ImGuiContext* ctx, const ImRect& bb, ImGuiID id)
|
||||
{
|
||||
if (Slic3r::GUI::ImGuiWrapper* imgui = Slic3r::GUI::wxGetApp().imgui(); imgui != nullptr && imgui->item_recording())
|
||||
imgui->record_item_add(id, bb.Min.x, bb.Min.y, bb.Max.x, bb.Max.y, ctx->CurrentWindow ? ctx->CurrentWindow->Name : nullptr);
|
||||
}
|
||||
|
||||
void ImGuiTestEngineHook_ItemInfo(ImGuiContext*, ImGuiID id, const char* label, ImGuiItemStatusFlags flags)
|
||||
{
|
||||
if (Slic3r::GUI::ImGuiWrapper* imgui = Slic3r::GUI::wxGetApp().imgui(); imgui != nullptr && imgui->item_recording())
|
||||
imgui->record_item_info(id, label, int(flags));
|
||||
}
|
||||
|
||||
void ImGuiTestEngineHook_IdInfo(ImGuiContext*, ImGuiDataType, ImGuiID, const void*) {}
|
||||
void ImGuiTestEngineHook_IdInfo(ImGuiContext*, ImGuiDataType, ImGuiID, const void*, const void*) {}
|
||||
void ImGuiTestEngineHook_Log(ImGuiContext*, const char*, ...) {}
|
||||
@@ -57,6 +57,22 @@ bool menu_item_with_icon(const char *label, const char *shortcut, ImVec2 icon_si
|
||||
|
||||
class ImGuiWrapper
|
||||
{
|
||||
public:
|
||||
// Automation (the MCP server) lists and clicks ImGui items, which have no window handles. While
|
||||
// recording is on, every item a frame adds is recorded with its id, label, window and rectangle
|
||||
// (in ImGui coordinates), per canvas: the canvas calls set_frame_owner() before new_frame(), and
|
||||
// end_frame() publishes the frame's items as that owner's latest. Off unless the MCP server runs;
|
||||
// ImGui then skips the hooks with one branch per item.
|
||||
struct RecordedItem
|
||||
{
|
||||
unsigned id = 0;
|
||||
std::string label; // as passed to ImGui, "##" suffix included
|
||||
std::string window; // name of the ImGui window the item belongs to
|
||||
float x = 0.f, y = 0.f, w = 0.f, h = 0.f;
|
||||
int flags = 0; // ImGuiItemStatusFlags
|
||||
};
|
||||
|
||||
private:
|
||||
const ImWchar* m_glyph_ranges{ nullptr };
|
||||
const ImWchar* m_glyph_basic_ranges { nullptr };
|
||||
// Chinese, Japanese, Korean
|
||||
@@ -78,6 +94,11 @@ class ImGuiWrapper
|
||||
std::string m_clipboard_text;
|
||||
// Keys held down, each with whether ImGui claimed its press.
|
||||
std::map<int, bool> m_key_claims;
|
||||
// Item recording for automation, see set_item_recording(). UI thread only.
|
||||
bool m_item_recording{ false };
|
||||
const void* m_frame_owner{ nullptr };
|
||||
std::vector<RecordedItem> m_frame_items;
|
||||
std::map<const void*, std::vector<RecordedItem>> m_recorded_items;
|
||||
// Whether ImGui claimed the last key-down, for the char event that follows it.
|
||||
std::optional<bool> m_char_claim;
|
||||
|
||||
@@ -112,6 +133,14 @@ public:
|
||||
void new_frame();
|
||||
// Ends the frame and returns its draw data without drawing it.
|
||||
ImDrawData* end_frame();
|
||||
|
||||
void set_item_recording(bool on);
|
||||
bool item_recording() const { return m_item_recording; }
|
||||
void set_frame_owner(const void* owner) { m_frame_owner = owner; }
|
||||
std::vector<RecordedItem> recorded_items(const void* owner) const;
|
||||
// Called by the ImGui test-engine hooks; not for other use.
|
||||
void record_item_add(unsigned id, float x0, float y0, float x1, float y1, const char* window);
|
||||
void record_item_info(unsigned id, const char* label, int flags);
|
||||
void render(ImDrawData* draw_data);
|
||||
// Hash of every draw list's vertices, indices and commands.
|
||||
static ImGuiID draw_data_signature(const ImDrawData* draw_data);
|
||||
|
||||
@@ -112,6 +112,7 @@
|
||||
#include "../Utils/PrintHost.hpp"
|
||||
|
||||
#include "GUI_App.hpp"
|
||||
#include "Mcp/McpService.hpp"
|
||||
#include "ImGuiWrapper.hpp"
|
||||
#include "OpenGLManager.hpp"
|
||||
#include "Shortcuts.hpp"
|
||||
@@ -1330,6 +1331,14 @@ void MainFrame::update_edge_panels()
|
||||
void MainFrame::shutdown()
|
||||
{
|
||||
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << "MainFrame::shutdown enter";
|
||||
// MCP calls must not reach panels that are about to go away. A language change rebuilds the
|
||||
// frame, so the server only pauses until GUI_App::recreate_GUI() resumes it.
|
||||
if (Mcp::McpService* mcp = wxGetApp().mcp_service()) {
|
||||
if (wxGetApp().is_recreating_gui())
|
||||
mcp->suspend();
|
||||
else
|
||||
wxGetApp().stop_mcp_service();
|
||||
}
|
||||
m_idle.stop();
|
||||
if (ProjectPanel* project = ProjectPanel::if_built())
|
||||
project->shutdown();
|
||||
|
||||
@@ -72,12 +72,19 @@ bool JobRegistry::any_running_except(const std::set<std::string>& excluded) cons
|
||||
[&](const auto& kv) { return !kv.second.finished && excluded.count(kv.first) == 0; });
|
||||
}
|
||||
|
||||
std::vector<std::string> JobRegistry::running_of(const std::set<std::string>& tools, const std::set<std::string>& excluded) const
|
||||
void JobRegistry::set_operation(const std::string& id)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
if (auto it = m_jobs.find(id); it != m_jobs.end())
|
||||
it->second.operation = true;
|
||||
}
|
||||
|
||||
std::vector<std::string> JobRegistry::running_operations() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
std::vector<std::string> out;
|
||||
for (const auto& [id, job] : m_jobs)
|
||||
if (!job.finished && tools.count(job.tool) != 0 && excluded.count(id) == 0)
|
||||
if (!job.finished && job.operation)
|
||||
out.push_back(id);
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -39,8 +39,9 @@ public:
|
||||
std::set<std::string> lineage(const std::string& id) const;
|
||||
// True when a running job exists that is not in `excluded`.
|
||||
bool any_running_except(const std::set<std::string>& excluded) const;
|
||||
// Running jobs of the given tools that are not in `excluded`, for operation admission.
|
||||
std::vector<std::string> running_of(const std::set<std::string>& tools, const std::set<std::string>& excluded) const;
|
||||
// Operation admission: a job marked as an operation holds the project until it finishes.
|
||||
void set_operation(const std::string& id);
|
||||
std::vector<std::string> running_operations() const;
|
||||
|
||||
// [{id, tool, parent, state, age_ms}] for get_state.
|
||||
nlohmann::json list() const;
|
||||
@@ -53,7 +54,8 @@ private:
|
||||
{
|
||||
std::string tool;
|
||||
std::string parent;
|
||||
bool finished = false;
|
||||
bool finished = false;
|
||||
bool operation = false;
|
||||
ToolResult result;
|
||||
std::chrono::steady_clock::time_point created;
|
||||
};
|
||||
|
||||
@@ -44,6 +44,12 @@ public:
|
||||
m_journal->set_args(m_seq, std::move(args));
|
||||
}
|
||||
|
||||
void begin_operation() override
|
||||
{
|
||||
if (!m_job.empty())
|
||||
m_core.jobs().set_operation(m_job);
|
||||
}
|
||||
|
||||
private:
|
||||
McpCore& m_core;
|
||||
const ToolDef& m_def;
|
||||
@@ -108,7 +114,7 @@ ToolResult McpCore::run(const ToolDef& def, const nlohmann::json& args, const st
|
||||
// Operation admission: an MCP slice/export holds the project until it finishes; only recovery
|
||||
// input and the tools that may run during an operation (cancel) get through.
|
||||
if (def.guard == GuardClass::Mutate && !def.allowed_during_operation)
|
||||
if (const auto busy = m_jobs.running_of(m_operation_tools, {}); !busy.empty())
|
||||
if (const auto busy = m_jobs.running_operations(); !busy.empty())
|
||||
return finish(ToolResult::error("Busy: job " + busy.front() +
|
||||
" (a slice or export) is running; wait for it or cancel it before changing the project",
|
||||
{{"job", busy.front()}}));
|
||||
|
||||
@@ -41,10 +41,6 @@ public:
|
||||
// exempts it from operation admission against its own ancestors.
|
||||
ToolResult call_child(const ToolDef& def, const nlohmann::json& args, const std::string& parent_job);
|
||||
|
||||
// Tools whose jobs hold the operation lock (slice, export): while one runs, other mutate calls
|
||||
// outside its job tree are refused.
|
||||
void set_operation_tools(std::set<std::string> tools) { m_operation_tools = std::move(tools); }
|
||||
|
||||
// Wakes all waiters (UiInvoker and JobRegistry must be woken by the owner first or after) and
|
||||
// waits, bounded, for job threads to return.
|
||||
void shutdown();
|
||||
@@ -61,7 +57,6 @@ private:
|
||||
JobRegistry& m_jobs;
|
||||
Journal* m_journal;
|
||||
CoreTiming m_timing;
|
||||
std::set<std::string> m_operation_tools;
|
||||
|
||||
// Requests that may block (a job within its reply budget, or wait) hold a slot, so the number of
|
||||
// blocked request threads stays below the connection limit and recovery calls always get through.
|
||||
|
||||
@@ -328,7 +328,11 @@ bool McpHttpServer::start(uint16_t port, std::string& error)
|
||||
try {
|
||||
const tcp::endpoint endpoint(net::ip::address_v4::loopback(), port);
|
||||
m_impl->acceptor.open(endpoint.protocol());
|
||||
// Not reuse_address: a second instance on the same port must fail instead of sharing it.
|
||||
#ifndef _WIN32
|
||||
// Lets a restarted server bind while its old connections sit in TIME_WAIT. POSIX still
|
||||
// refuses a second listener on the port; Windows' SO_REUSEADDR would not, so it stays off.
|
||||
m_impl->acceptor.set_option(tcp::acceptor::reuse_address(true));
|
||||
#endif
|
||||
m_impl->acceptor.bind(endpoint);
|
||||
m_impl->acceptor.listen(net::socket_base::max_listen_connections);
|
||||
m_impl->bound_port = m_impl->acceptor.local_endpoint().port();
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
// Default port of the MCP endpoint; 13618 is the OAuth callback server.
|
||||
inline constexpr int kDefaultPort = 13619;
|
||||
|
||||
// MCP settings from the command line. Script paths are absolute: OrcaSlicer.cpp resolves them
|
||||
// against the original working directory before the GUI changes it.
|
||||
struct McpLaunchOptions
|
||||
{
|
||||
bool enable = false; // --mcp
|
||||
int port = 0; // --mcp-port; 0 = the preference
|
||||
std::string token; // --mcp-token; ORCA_MCP_TOKEN takes precedence
|
||||
std::string script; // --mcp-script
|
||||
std::string script_out; // --mcp-script-out
|
||||
};
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -0,0 +1,109 @@
|
||||
#include "McpPaths.hpp"
|
||||
|
||||
#include <boost/filesystem/operations.hpp>
|
||||
#include <boost/nowide/convert.hpp>
|
||||
#include <boost/system/error_code.hpp>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
namespace fs = boost::filesystem;
|
||||
|
||||
namespace {
|
||||
|
||||
// UTF-8 to a native path (wide on Windows).
|
||||
fs::path to_path(const std::string& utf8)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
return fs::path(boost::nowide::widen(utf8));
|
||||
#else
|
||||
return fs::path(utf8);
|
||||
#endif
|
||||
}
|
||||
|
||||
std::optional<fs::path> absolute(const std::string& path, std::string& err)
|
||||
{
|
||||
if (path.empty()) {
|
||||
err = "path is empty";
|
||||
return std::nullopt;
|
||||
}
|
||||
fs::path p = to_path(path);
|
||||
if (!p.is_absolute()) {
|
||||
err = "path must be absolute: " + path;
|
||||
return std::nullopt;
|
||||
}
|
||||
return p.lexically_normal();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::optional<fs::path> resolve_input_path(const std::string& path, std::string& err)
|
||||
{
|
||||
auto p = absolute(path, err);
|
||||
if (!p)
|
||||
return std::nullopt;
|
||||
boost::system::error_code ec;
|
||||
if (!fs::exists(*p, ec)) {
|
||||
err = "file not found: " + path;
|
||||
return std::nullopt;
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
std::optional<fs::path> resolve_output_path(const std::string& path, bool overwrite, std::string& err)
|
||||
{
|
||||
auto p = absolute(path, err);
|
||||
if (!p)
|
||||
return std::nullopt;
|
||||
boost::system::error_code ec;
|
||||
if (p->filename().empty() || fs::is_directory(*p, ec)) {
|
||||
err = "path names a directory, not a file: " + path;
|
||||
return std::nullopt;
|
||||
}
|
||||
if (!fs::is_directory(p->parent_path(), ec)) {
|
||||
err = "directory does not exist: " + p->parent_path().string();
|
||||
return std::nullopt;
|
||||
}
|
||||
if (fs::exists(*p, ec) && !overwrite) {
|
||||
err = "file exists (pass overwrite: true to replace it): " + path;
|
||||
return std::nullopt;
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
std::optional<fs::path> resolve_output_dir(const std::string& path, std::string& err)
|
||||
{
|
||||
auto p = absolute(path, err);
|
||||
if (!p)
|
||||
return std::nullopt;
|
||||
boost::system::error_code ec;
|
||||
if (!fs::is_directory(*p, ec)) {
|
||||
err = "directory does not exist: " + path;
|
||||
return std::nullopt;
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
std::optional<PathParam> parse_path_param(const std::string& param, std::string& err)
|
||||
{
|
||||
PathParam out;
|
||||
const auto first = param.find_first_not_of(" \t");
|
||||
if (first != std::string::npos && param[first] == '{') {
|
||||
const nlohmann::json j = nlohmann::json::parse(param, nullptr, false);
|
||||
if (j.is_discarded() || !j.is_object() || !j.contains("path") || !j["path"].is_string()) {
|
||||
err = "the parameter must be a path or {\"path\": \"...\", \"overwrite\": true}";
|
||||
return std::nullopt;
|
||||
}
|
||||
out.path = j["path"].get<std::string>();
|
||||
out.overwrite = j.value("overwrite", false);
|
||||
} else {
|
||||
out.path = param;
|
||||
}
|
||||
if (out.path.empty()) {
|
||||
err = "path is empty";
|
||||
return std::nullopt;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -0,0 +1,30 @@
|
||||
#pragma once
|
||||
|
||||
#include <boost/filesystem/path.hpp>
|
||||
|
||||
#include <optional>
|
||||
#include <string>
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
// A file argument from an agent or a script. Paths are UTF-8 and must be absolute: a relative path
|
||||
// would resolve against <datadir>/log, where the GUI keeps its working directory.
|
||||
std::optional<boost::filesystem::path> resolve_input_path(const std::string& path, std::string& err);
|
||||
|
||||
// An output file: absolute, its directory must exist, and an existing file is replaced only when
|
||||
// `overwrite` is true.
|
||||
std::optional<boost::filesystem::path> resolve_output_path(const std::string& path, bool overwrite, std::string& err);
|
||||
|
||||
// An existing directory (multi-file exports).
|
||||
std::optional<boost::filesystem::path> resolve_output_dir(const std::string& path, std::string& err);
|
||||
|
||||
// The parameter of a Speed Dial command that takes a path: a plain absolute path, or a JSON object
|
||||
// string {"path": "...", "overwrite": true}.
|
||||
struct PathParam
|
||||
{
|
||||
std::string path;
|
||||
bool overwrite = false;
|
||||
};
|
||||
std::optional<PathParam> parse_path_param(const std::string& param, std::string& err);
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -0,0 +1,271 @@
|
||||
#include "McpService.hpp"
|
||||
|
||||
#include "McpHttpServer.hpp"
|
||||
#include "McpProtocol.hpp"
|
||||
#include "McpToken.hpp"
|
||||
#include "McpTools.hpp"
|
||||
#include "ModalTracker.hpp"
|
||||
#include "slic3r/GUI/GUI_App.hpp"
|
||||
#include "slic3r/GUI/ImGuiWrapper.hpp"
|
||||
#include "slic3r/GUI/MainFrame.hpp"
|
||||
|
||||
#include "libslic3r/AppConfig.hpp"
|
||||
#include "libslic3r/Utils.hpp"
|
||||
#include "libslic3r_version.h"
|
||||
|
||||
#include <boost/filesystem/operations.hpp>
|
||||
#include <boost/log/trivial.hpp>
|
||||
#include <boost/nowide/cstdlib.hpp>
|
||||
#include <boost/nowide/fstream.hpp>
|
||||
|
||||
#include <wx/app.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <exception>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <process.h>
|
||||
#define getpid _getpid
|
||||
#else
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
using nlohmann::json;
|
||||
namespace fs = boost::filesystem;
|
||||
|
||||
namespace {
|
||||
|
||||
std::atomic<int> g_script_exit_code{-1};
|
||||
|
||||
class WxDispatcher final : public UiDispatcher
|
||||
{
|
||||
public:
|
||||
void post(std::function<void()> fn) override
|
||||
{
|
||||
// CallAfter queues a thread-safe event; without an app the closure never runs and its
|
||||
// caller gives up after the queue timeout.
|
||||
if (wxTheApp != nullptr)
|
||||
wxTheApp->CallAfter(std::move(fn));
|
||||
}
|
||||
};
|
||||
|
||||
// Server instructions shown to the model; clients truncate them at 4096 characters.
|
||||
const char* kInstructions =
|
||||
"OrcaSlicer, a 3D-printing slicer, driven through its GUI.\n"
|
||||
"Workflow: get_state (is it ready? which presets, plates, dialogs?) -> act -> wait -> screenshot.\n"
|
||||
"- Prefer typed tools (open_files, select_preset, set_settings, slice, export) and run_action (every Speed Dial "
|
||||
"command: list_actions to search) over GUI clicks.\n"
|
||||
"- For anything else use the GUI tools: ui_snapshot lists widgets, menus, 3D toolbar items, gizmos and ImGui "
|
||||
"items with refs; ui_click / ui_input / ui_key / ui_mouse act on refs from the latest snapshot.\n"
|
||||
"- A call that takes long or opens a dialog returns {status:\"running\"|\"blocked_by_dialog\", job}. It keeps "
|
||||
"running: never retry it. Answer dialogs with dialog_respond (see get_state.dialogs), then wait {for:\"job\"}.\n"
|
||||
"- While a slice or export runs, other changes are refused; use wait or cancel.\n"
|
||||
"- Paths are absolute. Outputs never overwrite an existing file unless overwrite is true.\n"
|
||||
"- screenshot returns a downscaled image plus the full-size PNG path; target \"canvas\" is the 3D view.\n"
|
||||
"- export_script saves this session's calls as a replayable script; run_script replays one.";
|
||||
|
||||
} // namespace
|
||||
|
||||
McpService::McpService() = default;
|
||||
|
||||
McpService::~McpService() { stop(); }
|
||||
|
||||
int McpService::script_exit_code() { return g_script_exit_code.load(); }
|
||||
|
||||
bool McpService::serving() const { return m_http != nullptr && m_http->running(); }
|
||||
|
||||
uint16_t McpService::port() const { return m_http ? m_http->port() : 0; }
|
||||
|
||||
fs::path McpService::output_dir() const
|
||||
{
|
||||
const fs::path dir = mcp_dir(fs::path(data_dir())) / "out";
|
||||
boost::system::error_code ec;
|
||||
fs::create_directories(dir, ec);
|
||||
return dir;
|
||||
}
|
||||
|
||||
GuardState McpService::guards_on_ui() const
|
||||
{
|
||||
GuardState g;
|
||||
g.closing = m_stopping || wxTheApp == nullptr || wxGetApp().is_closing();
|
||||
g.suspended = m_suspended;
|
||||
if (m_modals) {
|
||||
g.dialogs = m_modals->snapshot();
|
||||
g.modal = !g.dialogs.empty();
|
||||
}
|
||||
return g;
|
||||
}
|
||||
|
||||
bool McpService::start(const McpLaunchOptions& options, bool serve, std::string& err)
|
||||
{
|
||||
if (m_core == nullptr) {
|
||||
m_options = options;
|
||||
m_dispatcher = std::make_unique<WxDispatcher>();
|
||||
m_modals = std::make_unique<ModalTracker>();
|
||||
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();
|
||||
if (ImGuiWrapper* imgui = wxGetApp().imgui())
|
||||
imgui->set_item_recording(true);
|
||||
}
|
||||
if (!serve || serving())
|
||||
return true;
|
||||
|
||||
AppConfig* config = wxGetApp().app_config;
|
||||
int port = options.port;
|
||||
if (port <= 0 && config != nullptr) {
|
||||
try {
|
||||
port = std::stoi(config->get("mcp_port"));
|
||||
} catch (const std::exception&) {
|
||||
port = 0;
|
||||
}
|
||||
}
|
||||
if (port <= 0 || port > 65535)
|
||||
port = kDefaultPort;
|
||||
|
||||
std::string token;
|
||||
if (const char* env = boost::nowide::getenv("ORCA_MCP_TOKEN"); env != nullptr && *env != '\0')
|
||||
token = env;
|
||||
else if (!options.token.empty())
|
||||
token = options.token;
|
||||
else
|
||||
token = load_or_create_token(fs::path(data_dir()), err);
|
||||
if (token.empty()) {
|
||||
err = "MCP server: no token (" + err + ")";
|
||||
return false;
|
||||
}
|
||||
m_token = token;
|
||||
|
||||
ServerInfo info;
|
||||
info.version = SLIC3R_VERSION;
|
||||
info.instructions = kInstructions;
|
||||
m_protocol = std::make_unique<McpProtocol>(m_registry, *m_core, info);
|
||||
m_http = std::make_unique<McpHttpServer>(token, [this](const PostRequest& r) { return m_protocol->handle_post(r); });
|
||||
if (!m_http->start(uint16_t(port), err)) {
|
||||
err = "MCP server: cannot listen on 127.0.0.1:" + std::to_string(port) + " (" + err + ")";
|
||||
BOOST_LOG_TRIVIAL(error) << err;
|
||||
m_http.reset();
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string discovery_err;
|
||||
if (!write_discovery(fs::path(data_dir()),
|
||||
{{"url", "http://127.0.0.1:" + std::to_string(m_http->port()) + "/mcp"},
|
||||
{"port", m_http->port()},
|
||||
{"pid", int(getpid())},
|
||||
{"version", SLIC3R_VERSION},
|
||||
{"token", token}},
|
||||
discovery_err))
|
||||
BOOST_LOG_TRIVIAL(warning) << "MCP server: " << discovery_err;
|
||||
BOOST_LOG_TRIVIAL(info) << "MCP server listening on http://127.0.0.1:" << m_http->port() << "/mcp";
|
||||
return true;
|
||||
}
|
||||
|
||||
void McpService::stop()
|
||||
{
|
||||
if (m_core == nullptr || m_stopping.exchange(true))
|
||||
return;
|
||||
BOOST_LOG_TRIVIAL(info) << "MCP server stopping";
|
||||
// Wake everything that waits before joining anything.
|
||||
m_invoker->shutdown();
|
||||
m_jobs.wake_all();
|
||||
m_core->shutdown();
|
||||
if (m_http) {
|
||||
m_http->stop();
|
||||
remove_discovery(fs::path(data_dir()));
|
||||
}
|
||||
if (m_script_thread.joinable())
|
||||
m_script_thread.join();
|
||||
if (wxTheApp != nullptr)
|
||||
if (ImGuiWrapper* imgui = wxGetApp().imgui())
|
||||
imgui->set_item_recording(false);
|
||||
m_modals.reset();
|
||||
}
|
||||
|
||||
void McpService::suspend()
|
||||
{
|
||||
m_suspended = true;
|
||||
++m_generation;
|
||||
}
|
||||
|
||||
void McpService::resume()
|
||||
{
|
||||
++m_generation;
|
||||
m_suspended = false;
|
||||
}
|
||||
|
||||
void McpService::mark_ready()
|
||||
{
|
||||
if (m_ready.exchange(true))
|
||||
return;
|
||||
if (!m_options.script.empty())
|
||||
run_launch_script();
|
||||
}
|
||||
|
||||
json McpService::describe() const
|
||||
{
|
||||
json out{{"serving", serving()}, {"ready", ready()}, {"version", SLIC3R_VERSION}};
|
||||
if (serving()) {
|
||||
out["port"] = port();
|
||||
out["url"] = "http://127.0.0.1:" + std::to_string(port()) + "/mcp";
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
void McpService::register_tools()
|
||||
{
|
||||
register_app_tools(*this);
|
||||
register_action_tools(*this);
|
||||
register_project_tools(*this);
|
||||
register_config_tools(*this);
|
||||
register_scene_tools(*this);
|
||||
register_view_tools(*this);
|
||||
register_ui_tools(*this);
|
||||
register_script_tools(*this);
|
||||
#ifdef SLIC3R_CAD
|
||||
register_cad_tools(*this);
|
||||
#endif
|
||||
}
|
||||
|
||||
void McpService::run_launch_script()
|
||||
{
|
||||
m_script_thread = std::thread([this] {
|
||||
int code = 2;
|
||||
try {
|
||||
json args{{"path", m_options.script}};
|
||||
if (!m_options.script_out.empty())
|
||||
args["out_dir"] = m_options.script_out;
|
||||
const ToolDef* def = m_registry.find("run_script");
|
||||
ToolResult r = m_core->call(*def, args);
|
||||
if (!r.is_error && r.data.value("status", "") == "running" && r.data.contains("job")) {
|
||||
std::optional<ToolResult> done;
|
||||
while (!done && !m_stopping)
|
||||
done = m_jobs.wait(r.data["job"].get<std::string>(), std::chrono::seconds(5));
|
||||
if (done)
|
||||
r = *done;
|
||||
}
|
||||
if (r.is_error)
|
||||
BOOST_LOG_TRIVIAL(error) << "MCP script: " << r.message;
|
||||
code = r.is_error ? (r.data.value("invalid", false) ? 2 : 1) : (r.data.value("passed", false) ? 0 : 1);
|
||||
} catch (const std::exception& e) {
|
||||
BOOST_LOG_TRIVIAL(error) << "MCP script: " << e.what();
|
||||
}
|
||||
g_script_exit_code = code;
|
||||
BOOST_LOG_TRIVIAL(info) << "MCP script finished with exit code " << code;
|
||||
if (m_stopping || wxTheApp == nullptr)
|
||||
return;
|
||||
// Close without the unsaved-project prompt: the script owns this session.
|
||||
m_dispatcher->post([] {
|
||||
if (wxTheApp != nullptr && wxGetApp().mainframe != nullptr)
|
||||
wxGetApp().mainframe->Close(true);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -0,0 +1,104 @@
|
||||
#pragma once
|
||||
|
||||
#include "JobRegistry.hpp"
|
||||
#include "McpCore.hpp"
|
||||
#include "McpJournal.hpp"
|
||||
#include "McpOptions.hpp"
|
||||
#include "McpTypes.hpp"
|
||||
#include "UiInvoker.hpp"
|
||||
|
||||
#include <boost/filesystem/path.hpp>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
class McpHttpServer;
|
||||
class McpProtocol;
|
||||
class ModalTracker;
|
||||
|
||||
// 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
|
||||
// ready. Created by GUI_App; started, suspended and stopped on the UI thread.
|
||||
//
|
||||
// Off unless the preference or --mcp/--mcp-script asks for it; when off, none of this exists.
|
||||
class McpService
|
||||
{
|
||||
public:
|
||||
McpService();
|
||||
~McpService();
|
||||
McpService(const McpService&) = delete;
|
||||
McpService& operator=(const McpService&) = delete;
|
||||
|
||||
// Builds the catalog and, when `serve` is true, opens the HTTP endpoint. A script from
|
||||
// `options` runs after mark_ready(). Returns false with `err` set when the endpoint can't start;
|
||||
// the catalog stays usable for the script either way.
|
||||
bool start(const McpLaunchOptions& options, bool serve, std::string& err);
|
||||
// Stops everything; idempotent. Wakes every waiting call first, so no thread is left behind.
|
||||
void stop();
|
||||
bool started() const { return m_core != nullptr; }
|
||||
bool serving() const;
|
||||
uint16_t port() const;
|
||||
const std::string& token() const { return m_token; }
|
||||
|
||||
// Main frame recreation (language change): refs become stale and UI calls fail with "retry"
|
||||
// until resume().
|
||||
void suspend();
|
||||
void resume();
|
||||
bool suspended() const { return m_suspended; }
|
||||
|
||||
// The main frame finished starting up (end of GUI_App::post_init).
|
||||
void mark_ready();
|
||||
bool ready() const { return m_ready && !m_suspended; }
|
||||
|
||||
// Monotonic counter bumped by suspend(); refs carry it to detect a rebuilt UI.
|
||||
uint64_t ui_generation() const { return m_generation; }
|
||||
|
||||
ToolRegistry& registry() { return m_registry; }
|
||||
JobRegistry& jobs() { return m_jobs; }
|
||||
Journal& journal() { return m_journal; }
|
||||
UiInvoker& ui() { return *m_invoker; }
|
||||
McpCore& core() { return *m_core; }
|
||||
ModalTracker& modals() { return *m_modals; }
|
||||
|
||||
// Where screenshots and script outputs go when no path is given.
|
||||
boost::filesystem::path output_dir() const;
|
||||
|
||||
// {enabled, port, url, token_file, ...} for Preferences and get_state.
|
||||
nlohmann::json describe() const;
|
||||
|
||||
// Exit code of a --mcp-script run (0 passed, 1 failed, 2 invalid), -1 when none ran. Read by
|
||||
// GUI_Run after the event loop ends; wx ignores OnExit()'s return value.
|
||||
static int script_exit_code();
|
||||
|
||||
private:
|
||||
void register_tools();
|
||||
void run_launch_script();
|
||||
GuardState guards_on_ui() const;
|
||||
|
||||
McpLaunchOptions m_options;
|
||||
std::string m_token;
|
||||
|
||||
std::unique_ptr<UiDispatcher> m_dispatcher;
|
||||
ToolRegistry m_registry;
|
||||
JobRegistry m_jobs;
|
||||
Journal m_journal;
|
||||
std::unique_ptr<UiInvoker> m_invoker;
|
||||
std::unique_ptr<McpCore> m_core;
|
||||
std::unique_ptr<McpProtocol> m_protocol;
|
||||
std::unique_ptr<McpHttpServer> m_http;
|
||||
std::unique_ptr<ModalTracker> m_modals;
|
||||
|
||||
std::atomic<bool> m_ready{false};
|
||||
std::atomic<bool> m_suspended{false};
|
||||
std::atomic<bool> m_stopping{false};
|
||||
std::atomic<uint64_t> m_generation{1};
|
||||
std::thread m_script_thread;
|
||||
};
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -0,0 +1,372 @@
|
||||
#include "McpStdioBridge.hpp"
|
||||
|
||||
#include "McpOptions.hpp"
|
||||
#include "libslic3r/Utils.hpp"
|
||||
#include "libslic3r_version.h"
|
||||
|
||||
#include <boost/asio/connect.hpp>
|
||||
#include <boost/asio/io_context.hpp>
|
||||
#include <boost/asio/ip/tcp.hpp>
|
||||
#include <boost/beast/core/flat_buffer.hpp>
|
||||
#include <boost/beast/http/read.hpp>
|
||||
#include <boost/beast/http/string_body.hpp>
|
||||
#include <boost/beast/http/write.hpp>
|
||||
#include <boost/filesystem/operations.hpp>
|
||||
#include <boost/filesystem/path.hpp>
|
||||
#include <boost/nowide/cstdlib.hpp>
|
||||
#include <boost/nowide/fstream.hpp>
|
||||
#include <boost/nowide/iostream.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <map>
|
||||
#include <vector>
|
||||
#include <exception>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
#ifdef _WIN32
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#include <fcntl.h>
|
||||
#include <io.h>
|
||||
#include <windows.h>
|
||||
#else
|
||||
#include <csignal>
|
||||
#include <sys/types.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
#ifdef __APPLE__
|
||||
#include <mach-o/dyld.h>
|
||||
#endif
|
||||
#endif
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
using nlohmann::json;
|
||||
namespace fs = boost::filesystem;
|
||||
namespace net = boost::asio;
|
||||
namespace http = boost::beast::http;
|
||||
using tcp = net::ip::tcp;
|
||||
|
||||
namespace {
|
||||
|
||||
struct Endpoint
|
||||
{
|
||||
int port = 0;
|
||||
std::string token;
|
||||
};
|
||||
|
||||
std::string base64(const std::string& in)
|
||||
{
|
||||
static const char* table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
std::string out;
|
||||
int val = 0, bits = -6;
|
||||
for (unsigned char c : in) {
|
||||
val = (val << 8) + c;
|
||||
bits += 8;
|
||||
while (bits >= 0) {
|
||||
out.push_back(table[(val >> bits) & 0x3F]);
|
||||
bits -= 6;
|
||||
}
|
||||
}
|
||||
if (bits > -6)
|
||||
out.push_back(table[((val << 8) >> (bits + 8)) & 0x3F]);
|
||||
while (out.size() % 4)
|
||||
out.push_back('=');
|
||||
return out;
|
||||
}
|
||||
|
||||
bool header_safe(const std::string& v)
|
||||
{
|
||||
if (v.empty() || v.front() == ' ' || v.back() == ' ' || (v.rfind("=?base64?", 0) == 0))
|
||||
return false;
|
||||
for (unsigned char c : v)
|
||||
if (c < 0x20 || c > 0x7E)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Mirrors GUI_App::init_app_config's choice without a wxApp.
|
||||
fs::path default_datadir()
|
||||
{
|
||||
#ifdef __linux__
|
||||
return fs::path(default_data_dir());
|
||||
#elif defined(_WIN32)
|
||||
wchar_t exe[MAX_PATH] = {0};
|
||||
GetModuleFileNameW(nullptr, exe, MAX_PATH);
|
||||
const fs::path portable = fs::path(exe).parent_path() / "data_dir";
|
||||
if (fs::exists(portable))
|
||||
return portable;
|
||||
const char* appdata = boost::nowide::getenv("APPDATA");
|
||||
return fs::path(appdata ? appdata : ".") / SLIC3R_APP_KEY;
|
||||
#else
|
||||
char exe[4096] = {0};
|
||||
uint32_t size = sizeof(exe);
|
||||
if (_NSGetExecutablePath(exe, &size) == 0) {
|
||||
const fs::path portable = fs::path(exe).parent_path().parent_path().parent_path().parent_path() / "data_dir";
|
||||
if (fs::exists(portable))
|
||||
return portable;
|
||||
}
|
||||
const char* home = boost::nowide::getenv("HOME");
|
||||
return fs::path(home ? home : ".") / "Library" / "Application Support" / SLIC3R_APP_KEY;
|
||||
#endif
|
||||
}
|
||||
|
||||
std::optional<Endpoint> read_discovery(const fs::path& datadir)
|
||||
{
|
||||
boost::nowide::ifstream in((datadir / "mcp" / "server.json").string());
|
||||
if (!in)
|
||||
return std::nullopt;
|
||||
const json info = json::parse(in, nullptr, false);
|
||||
if (info.is_discarded() || !info.contains("port"))
|
||||
return std::nullopt;
|
||||
Endpoint e;
|
||||
e.port = info.value("port", 0);
|
||||
e.token = info.value("token", "");
|
||||
return e;
|
||||
}
|
||||
|
||||
// POSTs one message; nullopt when the endpoint does not accept a connection.
|
||||
std::optional<std::pair<int, std::string>> post(const Endpoint& e, const std::string& body, const std::map<std::string, std::string>& headers)
|
||||
{
|
||||
try {
|
||||
net::io_context ioc;
|
||||
tcp::socket socket(ioc);
|
||||
socket.connect(tcp::endpoint(net::ip::make_address("127.0.0.1"), uint16_t(e.port)));
|
||||
http::request<http::string_body> req{http::verb::post, "/mcp", 11};
|
||||
req.set(http::field::host, "127.0.0.1:" + std::to_string(e.port));
|
||||
req.set(http::field::content_type, "application/json");
|
||||
req.set(http::field::accept, "application/json, text/event-stream");
|
||||
req.set(http::field::authorization, "Bearer " + e.token);
|
||||
for (const auto& [k, v] : headers)
|
||||
req.set(k, v);
|
||||
req.body() = body;
|
||||
req.prepare_payload();
|
||||
http::write(socket, req);
|
||||
boost::beast::flat_buffer buffer;
|
||||
http::response<http::string_body> res;
|
||||
http::read(socket, buffer, res);
|
||||
return std::make_pair(int(res.result_int()), res.body());
|
||||
} catch (const std::exception&) {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
|
||||
bool alive(const Endpoint& e)
|
||||
{
|
||||
const json ping{{"jsonrpc", "2.0"}, {"id", "bridge-probe"}, {"method", "ping"}};
|
||||
auto r = post(e, ping.dump(), {{"Mcp-Method", "ping"}});
|
||||
return r && r->first == 200;
|
||||
}
|
||||
|
||||
std::string self_executable(char** argv)
|
||||
{
|
||||
// An AppImage is relaunched through its runtime, not the extracted binary.
|
||||
if (const char* appimage = boost::nowide::getenv("APPIMAGE"); appimage && *appimage)
|
||||
return appimage;
|
||||
#ifdef _WIN32
|
||||
wchar_t exe[MAX_PATH] = {0};
|
||||
GetModuleFileNameW(nullptr, exe, MAX_PATH);
|
||||
return fs::path(exe).string();
|
||||
#elif defined(__APPLE__)
|
||||
char exe[4096] = {0};
|
||||
uint32_t size = sizeof(exe);
|
||||
return _NSGetExecutablePath(exe, &size) == 0 ? std::string(exe) : std::string(argv[0]);
|
||||
#else
|
||||
char exe[4096] = {0};
|
||||
ssize_t n = readlink("/proc/self/exe", exe, sizeof(exe) - 1);
|
||||
return n > 0 ? std::string(exe, std::size_t(n)) : std::string(argv[0]);
|
||||
#endif
|
||||
}
|
||||
|
||||
// Starts `exe --mcp [--datadir dir]` detached from this process. Returns false when it could not be
|
||||
// started or exited within a moment (a running instance without MCP took the launch over).
|
||||
bool launch_app(const std::string& exe, const std::string& datadir)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
std::wstring cmd = L"\"" + fs::path(exe).wstring() + L"\" --mcp";
|
||||
if (!datadir.empty())
|
||||
cmd += L" --datadir \"" + fs::path(datadir).wstring() + L"\"";
|
||||
STARTUPINFOW si{};
|
||||
PROCESS_INFORMATION pi{};
|
||||
si.cb = sizeof(si);
|
||||
if (!CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, FALSE, DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP, nullptr, nullptr, &si, &pi))
|
||||
return false;
|
||||
const DWORD wait = WaitForSingleObject(pi.hProcess, 5000);
|
||||
CloseHandle(pi.hThread);
|
||||
CloseHandle(pi.hProcess);
|
||||
return wait == WAIT_TIMEOUT;
|
||||
#else
|
||||
const pid_t pid = fork();
|
||||
if (pid < 0)
|
||||
return false;
|
||||
if (pid == 0) {
|
||||
setsid();
|
||||
// The GUI must not inherit the MCP stdio pipes.
|
||||
std::freopen("/dev/null", "r", stdin);
|
||||
std::freopen("/dev/null", "w", stdout);
|
||||
std::vector<std::string> args{exe, "--mcp"};
|
||||
if (!datadir.empty()) {
|
||||
args.push_back("--datadir");
|
||||
args.push_back(datadir);
|
||||
}
|
||||
std::vector<char*> cargs;
|
||||
for (std::string& a : args)
|
||||
cargs.push_back(a.data());
|
||||
cargs.push_back(nullptr);
|
||||
execv(exe.c_str(), cargs.data());
|
||||
_exit(127);
|
||||
}
|
||||
for (int i = 0; i < 50; ++i) {
|
||||
int status = 0;
|
||||
if (waitpid(pid, &status, WNOHANG) == pid)
|
||||
return false;
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
}
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
|
||||
void write_line(const std::string& s)
|
||||
{
|
||||
boost::nowide::cout << s << '\n';
|
||||
boost::nowide::cout.flush();
|
||||
}
|
||||
|
||||
json error_reply(const json& id, int code, const std::string& message)
|
||||
{
|
||||
return {{"jsonrpc", "2.0"}, {"id", id}, {"error", {{"code", code}, {"message", message}}}};
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::map<std::string, std::string> bridge_headers(const json& message, const std::string& negotiated_version)
|
||||
{
|
||||
std::map<std::string, std::string> h;
|
||||
const std::string method = message.value("method", "");
|
||||
const json params = message.contains("params") && message["params"].is_object() ? message["params"] : json::object();
|
||||
std::string version = negotiated_version;
|
||||
if (params.contains("_meta") && params["_meta"].is_object()) {
|
||||
const json& meta = params["_meta"];
|
||||
if (auto it = meta.find("io.modelcontextprotocol/protocolVersion"); it != meta.end() && it->is_string())
|
||||
version = it->get<std::string>();
|
||||
}
|
||||
if (!version.empty())
|
||||
h["MCP-Protocol-Version"] = version;
|
||||
if (!method.empty())
|
||||
h["Mcp-Method"] = method;
|
||||
std::string name;
|
||||
if (method == "tools/call" || method == "prompts/get")
|
||||
name = params.value("name", "");
|
||||
else if (method == "resources/read")
|
||||
name = params.value("uri", "");
|
||||
if (!name.empty())
|
||||
h["Mcp-Name"] = header_safe(name) ? name : "=?base64?" + base64(name) + "?=";
|
||||
return h;
|
||||
}
|
||||
|
||||
int run_stdio_bridge(int argc, char** argv)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
_setmode(_fileno(stdin), _O_BINARY);
|
||||
_setmode(_fileno(stdout), _O_BINARY);
|
||||
#else
|
||||
std::signal(SIGPIPE, SIG_IGN);
|
||||
#endif
|
||||
std::string datadir_arg;
|
||||
int port_arg = 0;
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
const std::string a = argv[i];
|
||||
auto value = [&](const char* name) -> std::optional<std::string> {
|
||||
const std::string flag = name;
|
||||
if (a == flag && i + 1 < argc)
|
||||
return std::string(argv[++i]);
|
||||
if (a.rfind(flag + "=", 0) == 0)
|
||||
return a.substr(flag.size() + 1);
|
||||
return std::nullopt;
|
||||
};
|
||||
if (auto v = value("--datadir"))
|
||||
datadir_arg = *v;
|
||||
else if (auto v = value("--mcp-port"))
|
||||
port_arg = std::atoi(v->c_str());
|
||||
}
|
||||
const fs::path datadir = datadir_arg.empty() ? default_datadir() : fs::path(datadir_arg);
|
||||
|
||||
auto resolve = [&]() -> std::optional<Endpoint> {
|
||||
std::optional<Endpoint> e = read_discovery(datadir);
|
||||
if (!e)
|
||||
e = Endpoint{};
|
||||
if (port_arg > 0)
|
||||
e->port = port_arg;
|
||||
if (const char* env = boost::nowide::getenv("ORCA_MCP_TOKEN"); env && *env)
|
||||
e->token = env;
|
||||
if (e->port <= 0)
|
||||
e->port = kDefaultPort;
|
||||
return alive(*e) ? e : std::nullopt;
|
||||
};
|
||||
|
||||
std::optional<Endpoint> endpoint = resolve();
|
||||
std::string failure;
|
||||
if (!endpoint) {
|
||||
if (!launch_app(self_executable(argv), datadir_arg))
|
||||
failure = "OrcaSlicer is running without the MCP server, or could not be started. Enable Preferences > "
|
||||
"MCP server in OrcaSlicer (or start it with --mcp) and reconnect.";
|
||||
else
|
||||
for (int i = 0; i < 120 && !endpoint; ++i) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
||||
endpoint = resolve();
|
||||
}
|
||||
if (!endpoint && failure.empty())
|
||||
failure = "OrcaSlicer did not start its MCP server within 60 seconds.";
|
||||
}
|
||||
|
||||
std::string negotiated;
|
||||
std::string line;
|
||||
while (std::getline(boost::nowide::cin, line)) {
|
||||
if (!line.empty() && line.back() == '\r')
|
||||
line.pop_back();
|
||||
if (line.find_first_not_of(" \t") == std::string::npos)
|
||||
continue;
|
||||
const json msg = json::parse(line, nullptr, false);
|
||||
if (msg.is_discarded()) {
|
||||
write_line(error_reply(nullptr, -32700, "Parse error").dump());
|
||||
continue;
|
||||
}
|
||||
const bool is_request = msg.is_object() && msg.contains("id") && msg.contains("method");
|
||||
if (!endpoint) {
|
||||
if (is_request)
|
||||
write_line(error_reply(msg["id"], -32603, failure).dump());
|
||||
continue;
|
||||
}
|
||||
auto reply = post(*endpoint, line, bridge_headers(msg, negotiated));
|
||||
if (!reply) {
|
||||
// The app went away; one reconnect attempt for a restarted instance.
|
||||
endpoint = resolve();
|
||||
if (endpoint)
|
||||
reply = post(*endpoint, line, bridge_headers(msg, negotiated));
|
||||
}
|
||||
if (!reply) {
|
||||
if (is_request)
|
||||
write_line(error_reply(msg["id"], -32603, "OrcaSlicer's MCP server is not reachable.").dump());
|
||||
continue;
|
||||
}
|
||||
if (reply->first == 202 || reply->second.empty())
|
||||
continue;
|
||||
const json body = json::parse(reply->second, nullptr, false);
|
||||
if (body.is_discarded() || !body.contains("jsonrpc")) {
|
||||
if (is_request)
|
||||
write_line(error_reply(msg["id"], -32603, "HTTP " + std::to_string(reply->first) + ": " + reply->second).dump());
|
||||
continue;
|
||||
}
|
||||
if (msg.value("method", "") == "initialize" && body.contains("result"))
|
||||
negotiated = body["result"].value("protocolVersion", "");
|
||||
write_line(body.dump());
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -0,0 +1,22 @@
|
||||
#pragma once
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
// `orca-slicer --mcp-stdio [--datadir DIR] [--mcp-port N]`: an MCP server on stdin/stdout for
|
||||
// clients that only speak stdio (Claude Desktop, for one). Each newline-delimited JSON-RPC message
|
||||
// is POSTed to the running OrcaSlicer's endpoint found through <datadir>/mcp/server.json; when none
|
||||
// answers, OrcaSlicer is started with --mcp and given up to 60 s. Runs before any GUI setup.
|
||||
int run_stdio_bridge(int argc, char** argv);
|
||||
|
||||
// The HTTP headers a Streamable HTTP client derives from a message: MCP-Protocol-Version (the
|
||||
// message's _meta version, else the version `initialize` negotiated), Mcp-Method and, for
|
||||
// tools/call, prompts/get and resources/read, Mcp-Name (base64-sentinel encoded when not plain
|
||||
// ASCII).
|
||||
std::map<std::string, std::string> bridge_headers(const nlohmann::json& message, const std::string& negotiated_version);
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -0,0 +1,141 @@
|
||||
#include "McpToken.hpp"
|
||||
|
||||
#include <boost/filesystem/operations.hpp>
|
||||
#include <boost/nowide/fstream.hpp>
|
||||
#include <boost/system/error_code.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cstdio>
|
||||
#include <random>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
|
||||
#ifndef _WIN32
|
||||
#include <fcntl.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
namespace fs = boost::filesystem;
|
||||
|
||||
namespace {
|
||||
|
||||
bool is_token(const std::string& s)
|
||||
{
|
||||
return s.size() == 64 && std::all_of(s.begin(), s.end(), [](unsigned char c) { return std::isxdigit(c) != 0; });
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string random_token()
|
||||
{
|
||||
std::random_device rd;
|
||||
std::string out;
|
||||
out.reserve(64);
|
||||
static const char* hex = "0123456789abcdef";
|
||||
for (int i = 0; i < 32; ++i) {
|
||||
const unsigned v = rd() & 0xFFu;
|
||||
out.push_back(hex[v >> 4]);
|
||||
out.push_back(hex[v & 0xF]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
fs::path mcp_dir(const fs::path& datadir)
|
||||
{
|
||||
const fs::path dir = datadir / "mcp";
|
||||
boost::system::error_code ec;
|
||||
if (!fs::exists(dir, ec)) {
|
||||
fs::create_directories(dir, ec);
|
||||
#ifndef _WIN32
|
||||
::chmod(dir.string().c_str(), 0700);
|
||||
#endif
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
|
||||
bool write_private_file(const fs::path& path, const std::string& content, std::string& err)
|
||||
{
|
||||
const fs::path tmp = path.parent_path() / (path.filename().string() + ".tmp-" + random_token().substr(0, 8));
|
||||
#ifndef _WIN32
|
||||
const int fd = ::open(tmp.string().c_str(), O_WRONLY | O_CREAT | O_EXCL, 0600);
|
||||
if (fd < 0) {
|
||||
err = "cannot create " + tmp.string();
|
||||
return false;
|
||||
}
|
||||
const char* data = content.data();
|
||||
std::size_t left = content.size();
|
||||
while (left > 0) {
|
||||
const ssize_t n = ::write(fd, data, left);
|
||||
if (n <= 0) {
|
||||
::close(fd);
|
||||
::unlink(tmp.string().c_str());
|
||||
err = "cannot write " + tmp.string();
|
||||
return false;
|
||||
}
|
||||
data += n;
|
||||
left -= std::size_t(n);
|
||||
}
|
||||
::close(fd);
|
||||
#else
|
||||
// %APPDATA% is private to the user through its ACL; the file inherits it.
|
||||
{
|
||||
boost::nowide::ofstream out(tmp.string(), std::ios::binary | std::ios::trunc);
|
||||
if (!out) {
|
||||
err = "cannot create " + tmp.string();
|
||||
return false;
|
||||
}
|
||||
out << content;
|
||||
}
|
||||
#endif
|
||||
boost::system::error_code ec;
|
||||
fs::rename(tmp, path, ec);
|
||||
if (ec) {
|
||||
fs::remove(tmp, ec);
|
||||
err = "cannot replace " + path.string();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string load_or_create_token(const fs::path& datadir, std::string& err)
|
||||
{
|
||||
const fs::path file = mcp_dir(datadir) / "token";
|
||||
boost::system::error_code ec;
|
||||
if (fs::exists(file, ec)) {
|
||||
boost::nowide::ifstream in(file.string());
|
||||
std::string token;
|
||||
std::getline(in, token);
|
||||
token.erase(std::remove_if(token.begin(), token.end(), [](unsigned char c) { return std::isspace(c) != 0; }), token.end());
|
||||
if (is_token(token))
|
||||
return token;
|
||||
}
|
||||
return regenerate_token(datadir, err);
|
||||
}
|
||||
|
||||
std::string regenerate_token(const fs::path& datadir, std::string& err)
|
||||
{
|
||||
const std::string token = random_token();
|
||||
if (!write_private_file(mcp_dir(datadir) / "token", token + "\n", err))
|
||||
return {};
|
||||
return token;
|
||||
}
|
||||
|
||||
fs::path discovery_path(const fs::path& datadir) { return datadir / "mcp" / "server.json"; }
|
||||
|
||||
bool write_discovery(const fs::path& datadir, const nlohmann::json& info, std::string& err)
|
||||
{
|
||||
mcp_dir(datadir);
|
||||
return write_private_file(discovery_path(datadir), info.dump(2) + "\n", err);
|
||||
}
|
||||
|
||||
void remove_discovery(const fs::path& datadir)
|
||||
{
|
||||
boost::system::error_code ec;
|
||||
fs::remove(discovery_path(datadir), ec);
|
||||
}
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -0,0 +1,34 @@
|
||||
#pragma once
|
||||
|
||||
#include <boost/filesystem/path.hpp>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
// <datadir>/mcp, created owner-only (0700) on POSIX.
|
||||
boost::filesystem::path mcp_dir(const boost::filesystem::path& datadir);
|
||||
|
||||
// The install's bearer token from <datadir>/mcp/token, created on first use as 64 hex characters in
|
||||
// an owner-only file. Kept out of AppConfig, whose atomic writes and backups use default
|
||||
// permissions. Empty with `err` set when the file cannot be read or created.
|
||||
std::string load_or_create_token(const boost::filesystem::path& datadir, std::string& err);
|
||||
|
||||
// Replaces the token file with a fresh token and returns it.
|
||||
std::string regenerate_token(const boost::filesystem::path& datadir, std::string& err);
|
||||
|
||||
// Writes `content` to `path` so that it is never readable by others, even briefly: a temporary
|
||||
// file created owner-only and exclusively, then renamed over the target.
|
||||
bool write_private_file(const boost::filesystem::path& path, const std::string& content, std::string& err);
|
||||
|
||||
// <datadir>/mcp/server.json: {url, port, pid, version, token} with the effective token, for the
|
||||
// stdio bridge and the developer harness.
|
||||
boost::filesystem::path discovery_path(const boost::filesystem::path& datadir);
|
||||
bool write_discovery(const boost::filesystem::path& datadir, const nlohmann::json& info, std::string& err);
|
||||
void remove_discovery(const boost::filesystem::path& datadir);
|
||||
|
||||
// 32 random bytes as lowercase hex.
|
||||
std::string random_token();
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -0,0 +1,80 @@
|
||||
#pragma once
|
||||
|
||||
#include "McpTypes.hpp"
|
||||
|
||||
#include <boost/filesystem/path.hpp>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <initializer_list>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Slic3r { namespace GUI {
|
||||
|
||||
class Plater;
|
||||
|
||||
namespace Mcp {
|
||||
|
||||
class McpService;
|
||||
|
||||
// Each tool family registers itself with the service.
|
||||
void register_app_tools(McpService& service);
|
||||
void register_action_tools(McpService& service);
|
||||
void register_project_tools(McpService& service);
|
||||
void register_config_tools(McpService& service);
|
||||
void register_scene_tools(McpService& service);
|
||||
void register_view_tools(McpService& service);
|
||||
void register_ui_tools(McpService& service);
|
||||
void register_script_tools(McpService& service);
|
||||
void register_cad_tools(McpService& service);
|
||||
|
||||
// ---- schema helpers --------------------------------------------------------------------------
|
||||
|
||||
using Property = std::pair<const char*, nlohmann::json>;
|
||||
|
||||
// {"type":"object","properties":{...},"required":[...],"additionalProperties":false}
|
||||
nlohmann::json object_schema(std::initializer_list<Property> properties, std::vector<std::string> required = {});
|
||||
nlohmann::json prop(const char* type, const std::string& description);
|
||||
nlohmann::json enum_prop(std::vector<std::string> values, const std::string& description);
|
||||
nlohmann::json array_prop(nlohmann::json items, const std::string& description);
|
||||
|
||||
// Pure observation: inline, read-only, inspect guard, not journaled.
|
||||
ToolDef inspect_tool(std::string name, std::string title, std::string description, nlohmann::json schema, ToolHandler handler);
|
||||
// Anything that changes the app: a job under the mutate guard, journaled.
|
||||
ToolDef mutate_tool(std::string name, std::string title, std::string description, nlohmann::json schema, ToolHandler handler,
|
||||
bool destructive = false);
|
||||
|
||||
// ---- handler helpers -------------------------------------------------------------------------
|
||||
|
||||
// One more UI round trip after a mutation, so events it queued are handled before the reply.
|
||||
void settle(ToolContext& ctx);
|
||||
|
||||
// The plater, or ToolFailure while the main window is not up yet (startup, language change).
|
||||
// UI thread only.
|
||||
Plater& ui_plater();
|
||||
|
||||
// Typed argument access with defaults; schema validation has already checked the types.
|
||||
std::string arg_string(const nlohmann::json& args, const char* key, const std::string& fallback = {});
|
||||
int arg_int(const nlohmann::json& args, const char* key, int fallback);
|
||||
double arg_double(const nlohmann::json& args, const char* key, double fallback);
|
||||
bool arg_bool(const nlohmann::json& args, const char* key, bool fallback);
|
||||
|
||||
// Page a JSON array: {total, offset, items:[...]}.
|
||||
nlohmann::json page(const nlohmann::json& items, const nlohmann::json& args, std::size_t default_limit = 100);
|
||||
|
||||
// Waits for a G-code export started between Plater export sequence numbers `before` and `after`
|
||||
// (unchanged = it never started: `rejection` explains why) and reports how it ended; `revision` is
|
||||
// the project revision when it started.
|
||||
ToolResult await_gcode_export(ToolContext& ctx, uint64_t before, uint64_t after, uint64_t revision, const std::string& rejection);
|
||||
|
||||
// Polls `poll` on the UI thread every 200 ms until it returns a non-null value or `timeout`
|
||||
// passes; throws ToolFailure on timeout or cancellation.
|
||||
nlohmann::json poll_ui(ToolContext& ctx, const std::function<nlohmann::json()>& poll, std::chrono::milliseconds timeout,
|
||||
const std::string& what);
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -0,0 +1,180 @@
|
||||
// list_actions and run_action: every Speed Dial action - built-in commands, plates, recent projects,
|
||||
// plugin scripts and pages, and (on request) settings - is reachable through these two tools.
|
||||
|
||||
#include "McpOperations.hpp"
|
||||
#include "McpService.hpp"
|
||||
#include "McpTools.hpp"
|
||||
#include "slic3r/GUI/ActionRegistry.hpp"
|
||||
#include "slic3r/GUI/GUI.hpp"
|
||||
#include "slic3r/GUI/GUI_App.hpp"
|
||||
#include "slic3r/GUI/Plater.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
using nlohmann::json;
|
||||
|
||||
namespace {
|
||||
|
||||
ActionRegistry& registry_or_fail()
|
||||
{
|
||||
ActionRegistry* reg = wxGetApp().m_action_registry.get();
|
||||
if (reg == nullptr)
|
||||
throw ToolFailure("The action catalog is not available yet; wait {for:\"ready\"} first");
|
||||
return *reg;
|
||||
}
|
||||
|
||||
std::size_t edit_distance(const std::string& a, const std::string& b)
|
||||
{
|
||||
std::vector<std::size_t> row(b.size() + 1);
|
||||
for (std::size_t j = 0; j <= b.size(); ++j)
|
||||
row[j] = j;
|
||||
for (std::size_t i = 1; i <= a.size(); ++i) {
|
||||
std::size_t diag = row[0];
|
||||
row[0] = i;
|
||||
for (std::size_t j = 1; j <= b.size(); ++j) {
|
||||
const std::size_t up = row[j];
|
||||
row[j] = std::min({row[j] + 1, row[j - 1] + 1, diag + (a[i - 1] == b[j - 1] ? 0 : 1)});
|
||||
diag = up;
|
||||
}
|
||||
}
|
||||
return row[b.size()];
|
||||
}
|
||||
|
||||
const char* level_name(AppActionRunResult::Level level)
|
||||
{
|
||||
switch (level) {
|
||||
case AppActionRunResult::Level::Success: return "success";
|
||||
case AppActionRunResult::Level::Error: return "error";
|
||||
case AppActionRunResult::Level::Busy: return "busy";
|
||||
default: return "info";
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
ToolResult await_gcode_export(ToolContext& ctx, uint64_t before, uint64_t after, uint64_t revision, const std::string& rejection)
|
||||
{
|
||||
if (after == before)
|
||||
return ToolResult::error(rejection.empty() ? "The export did not start" : rejection);
|
||||
json done = poll_ui(
|
||||
ctx,
|
||||
[before, after, revision]() -> json {
|
||||
Plater& plater = ui_plater();
|
||||
auto run = plater.export_run(after);
|
||||
std::optional<ExportRecord> record;
|
||||
if (run) {
|
||||
record = ExportRecord{run->seq, run->path, run->finished, run->ok, run->cancelled, run->error, run->revision_at_finish};
|
||||
}
|
||||
const ExportStatus status = export_status(before, after, record, revision);
|
||||
if (status == ExportStatus::Pending)
|
||||
return json();
|
||||
json out{{"export", to_string(status)}, {"path", run ? run->path : std::string()}};
|
||||
if (run && !run->error.empty())
|
||||
out["error"] = run->error;
|
||||
return out;
|
||||
},
|
||||
std::chrono::minutes(10), "the export to finish");
|
||||
const std::string status = done["export"];
|
||||
if (status == "ok")
|
||||
return ToolResult::ok(done);
|
||||
if (status == "superseded") {
|
||||
done["note"] = "The project changed while exporting; the file reflects the project as it was when the export started.";
|
||||
return ToolResult::ok(done);
|
||||
}
|
||||
return ToolResult::error("The export ended " + status, done);
|
||||
}
|
||||
|
||||
void register_action_tools(McpService& service)
|
||||
{
|
||||
ToolRegistry& reg = service.registry();
|
||||
|
||||
reg.add(inspect_tool(
|
||||
"list_actions", "Search Speed Dial actions",
|
||||
"Search everything the Speed Dial can run: built-in commands (slice, export, views, object operations, plates, "
|
||||
"calibration wizards, help), recent projects, plugin scripts and pages. Each entry has an id for run_action, a "
|
||||
"description and, when it takes one, a param (type and help). include_settings also lists settings (each jumps "
|
||||
"to that setting in the sidebar; use get_settings / set_settings to read or change values).",
|
||||
object_schema({{"query", prop("string", "Case-insensitive text to find in id, title, group or description.")},
|
||||
{"group", prop("string", "Only this group, e.g. \"Object\", \"View\", \"Slice & Export\".")},
|
||||
{"include_settings", prop("boolean", "Also list settings (thousands). Default false.")},
|
||||
{"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 200}, {"description", "Default 50."}}},
|
||||
{"offset", {{"type", "integer"}, {"minimum", 0}}}}),
|
||||
[](const json& args, ToolContext& ctx) {
|
||||
ActionRegistry::Query q;
|
||||
q.text = arg_string(args, "query");
|
||||
q.group = arg_string(args, "group");
|
||||
q.include_settings = arg_bool(args, "include_settings", false);
|
||||
q.limit = std::size_t(arg_int(args, "limit", 50));
|
||||
q.offset = std::size_t(arg_int(args, "offset", 0));
|
||||
return ToolResult::ok(ctx.run_ui([q] { return registry_or_fail().describe(q); }));
|
||||
}));
|
||||
|
||||
reg.add(mutate_tool(
|
||||
"run_action", "Run a Speed Dial action",
|
||||
"Run one action by the id list_actions returned, with its param when it takes one (a percent, tab id, plate index, "
|
||||
"or an absolute path - commands with a path parameter skip their file dialog; outputs need {\"path\": ..., "
|
||||
"\"overwrite\": true} to replace a file). Actions that open a dialog return blocked_by_dialog; answer it with "
|
||||
"dialog_respond. An export_gcode with a path completes when the file is written.",
|
||||
object_schema({{"id", prop("string", "Action id from list_actions.")},
|
||||
{"param", prop("string", "Parameter, when the action takes one.")}},
|
||||
{"id"}),
|
||||
[](const json& args, ToolContext& ctx) {
|
||||
const std::string id = arg_string(args, "id");
|
||||
const std::string param = arg_string(args, "param");
|
||||
json started = ctx.run_ui([&]() -> json {
|
||||
ActionRegistry& actions = registry_or_fail();
|
||||
const AppAction* action = actions.by_id(id);
|
||||
if (action == nullptr) {
|
||||
// Suggest the ids closest to the requested one.
|
||||
ActionRegistry::Query q;
|
||||
q.limit = 100000;
|
||||
std::vector<std::pair<std::size_t, std::string>> scored;
|
||||
const json all = actions.describe(q);
|
||||
for (const json& a : all["actions"]) {
|
||||
const std::string candidate = a["id"];
|
||||
scored.emplace_back(edit_distance(id, candidate), candidate);
|
||||
}
|
||||
std::sort(scored.begin(), scored.end());
|
||||
json similar = json::array();
|
||||
for (std::size_t i = 0; i < scored.size() && i < 3 && scored[i].first <= id.size() / 3 + 2; ++i)
|
||||
similar.push_back(scored[i].second);
|
||||
throw ToolFailure("Unknown action id " + id + "; search with list_actions", {{"similar", similar}});
|
||||
}
|
||||
const bool background = action->completes_in_background && !param.empty();
|
||||
Plater* plater = wxGetApp().plater();
|
||||
uint64_t before = 0, revision = 0;
|
||||
if (background && plater != nullptr) {
|
||||
before = plater->export_seq();
|
||||
revision = plater->project_revision();
|
||||
}
|
||||
const AppActionRunResult r = actions.run(id, param, /*record_stats=*/false);
|
||||
json out{{"level", level_name(r.level)}, {"message", into_u8(r.message)}, {"background", background}};
|
||||
if (background && plater != nullptr)
|
||||
out.update({{"before", before}, {"after", plater->export_seq()}, {"revision", revision}});
|
||||
return out;
|
||||
});
|
||||
if (started["background"].get<bool>()) {
|
||||
ctx.begin_operation();
|
||||
if (started["level"] == "error")
|
||||
return ToolResult::error(started["message"].get<std::string>());
|
||||
return await_gcode_export(ctx, started["before"], started["after"], started["revision"], started["message"]);
|
||||
}
|
||||
settle(ctx);
|
||||
const std::string level = started["level"];
|
||||
if (level == "error" || level == "busy")
|
||||
return ToolResult::error(started["message"].get<std::string>().empty() ? "The action failed" : started["message"].get<std::string>());
|
||||
json out{{"ran", id}, {"level", level}};
|
||||
if (!started["message"].get<std::string>().empty())
|
||||
out["message"] = started["message"];
|
||||
return ToolResult::ok(out);
|
||||
}));
|
||||
}
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -0,0 +1,224 @@
|
||||
// get_state, wait and get_log: what an agent reads before and after acting.
|
||||
|
||||
#include "JobRegistry.hpp"
|
||||
#include "McpService.hpp"
|
||||
#include "McpTools.hpp"
|
||||
#include "ModalTracker.hpp"
|
||||
#include "slic3r/GUI/GUI.hpp"
|
||||
#include "slic3r/GUI/GUI_App.hpp"
|
||||
#include "slic3r/GUI/MainFrame.hpp"
|
||||
#include "slic3r/GUI/Notebook.hpp"
|
||||
#include "slic3r/GUI/NotificationManager.hpp"
|
||||
#include "slic3r/GUI/PartPlate.hpp"
|
||||
#include "slic3r/GUI/Plater.hpp"
|
||||
#if defined(__WXGTK__)
|
||||
#include "slic3r/GUI/LinuxDisplayBackend.hpp"
|
||||
#endif
|
||||
|
||||
#include "libslic3r/Model.hpp"
|
||||
#include "libslic3r/PresetBundle.hpp"
|
||||
#include "libslic3r/Utils.hpp"
|
||||
#include "libslic3r_version.h"
|
||||
|
||||
#include <boost/filesystem/path.hpp>
|
||||
#include <boost/nowide/fstream.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <deque>
|
||||
#include <string>
|
||||
#include <set>
|
||||
#include <thread>
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
using nlohmann::json;
|
||||
|
||||
namespace {
|
||||
|
||||
const char* platform_name()
|
||||
{
|
||||
#if defined(_WIN32)
|
||||
return "windows";
|
||||
#elif defined(__APPLE__)
|
||||
return "macos";
|
||||
#else
|
||||
return "linux";
|
||||
#endif
|
||||
}
|
||||
|
||||
const char* display_backend()
|
||||
{
|
||||
#if defined(_WIN32)
|
||||
return "win32";
|
||||
#elif defined(__APPLE__)
|
||||
return "cocoa";
|
||||
#elif defined(__WXGTK__)
|
||||
switch (get_linux_display_backend()) {
|
||||
case LinuxDisplayBackend::X11: return "x11";
|
||||
case LinuxDisplayBackend::Wayland: return "wayland";
|
||||
default: return "unknown";
|
||||
}
|
||||
#else
|
||||
return "unknown";
|
||||
#endif
|
||||
}
|
||||
|
||||
const char* mode_name(ConfigOptionMode mode)
|
||||
{
|
||||
switch (mode) {
|
||||
case comSimple: return "simple";
|
||||
case comAdvanced: return "advanced";
|
||||
case comExpert: return "expert";
|
||||
case comDevelop: return "develop";
|
||||
default: return "simple";
|
||||
}
|
||||
}
|
||||
|
||||
// The app as an agent sees it. UI thread.
|
||||
json app_state(McpService& service)
|
||||
{
|
||||
json state{{"version", SLIC3R_VERSION},
|
||||
{"platform", platform_name()},
|
||||
{"display_backend", display_backend()},
|
||||
{"ready", service.ready()},
|
||||
{"dialogs", service.modals().snapshot()},
|
||||
{"jobs", service.jobs().list()}};
|
||||
MainFrame* frame = wxGetApp().mainframe;
|
||||
Plater* plater = wxGetApp().plater();
|
||||
if (frame == nullptr || plater == nullptr)
|
||||
return state;
|
||||
|
||||
const wxRect rect = frame->GetScreenRect();
|
||||
state["window"] = {{"title", into_u8(frame->GetTitle())},
|
||||
{"size", {rect.width, rect.height}},
|
||||
{"position", {rect.x, rect.y}},
|
||||
{"maximized", frame->IsMaximized()},
|
||||
{"minimized", frame->IsIconized()},
|
||||
{"shown", frame->IsShown()}};
|
||||
if (Notebook* tabs = frame->m_tabpanel; tabs != nullptr && tabs->GetSelection() != wxNOT_FOUND)
|
||||
state["tab"] = into_u8(tabs->GetPageName(size_t(tabs->GetSelection())));
|
||||
state["mode"] = mode_name(wxGetApp().get_mode());
|
||||
state["printer_technology"] = plater->printer_technology() == ptFFF ? "FFF" : "SLA";
|
||||
state["project"] = {{"name", into_u8(plater->get_project_name())},
|
||||
{"path", into_u8(plater->get_project_filename(".3mf"))},
|
||||
{"dirty", plater->is_project_dirty()}};
|
||||
|
||||
PresetBundle& bundle = *wxGetApp().preset_bundle;
|
||||
json filaments = json::array();
|
||||
for (const std::string& name : bundle.filament_presets)
|
||||
filaments.push_back(name);
|
||||
state["presets"] = {{"printer", bundle.printers.get_selected_preset_name()},
|
||||
{"process", bundle.prints.get_selected_preset_name()},
|
||||
{"filaments", std::move(filaments)}};
|
||||
|
||||
PartPlateList& plates = plater->get_partplate_list();
|
||||
state["plates"] = {{"count", plates.get_plate_count()}, {"current", plates.get_curr_plate_index()}};
|
||||
state["objects"] = plater->model().objects.size();
|
||||
state["slicing"] = plater->is_slicing_any();
|
||||
|
||||
json notes = json::array();
|
||||
for (const NotificationSummary& n : plater->get_notification_manager()->summaries())
|
||||
notes.push_back({{"type", n.type}, {"level", n.level}, {"text", n.text}});
|
||||
state["notifications"] = std::move(notes);
|
||||
return state;
|
||||
}
|
||||
|
||||
// Whether `condition` holds now. UI thread.
|
||||
bool condition_holds(McpService& service, const std::string& condition, const std::set<std::string>& own_jobs)
|
||||
{
|
||||
if (condition == "ready")
|
||||
return service.ready();
|
||||
if (condition == "dialog")
|
||||
return service.modals().any_open();
|
||||
if (condition == "no_dialog")
|
||||
return !service.modals().any_open();
|
||||
if (condition == "idle") {
|
||||
if (service.modals().any_open() || service.jobs().any_running_except(own_jobs))
|
||||
return false;
|
||||
Plater* plater = wxGetApp().plater();
|
||||
return plater == nullptr || (!plater->is_slicing_any() && plater->get_ui_job_worker().is_idle());
|
||||
}
|
||||
throw ToolFailure("Unknown condition " + condition);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void register_app_tools(McpService& service)
|
||||
{
|
||||
ToolRegistry& reg = service.registry();
|
||||
|
||||
reg.add(inspect_tool(
|
||||
"get_state", "Get app state",
|
||||
"Snapshot of OrcaSlicer: version, platform, whether it is ready, current tab and mode, project, selected printer/process/"
|
||||
"filament presets, plates, object count, slicing state, open modal dialogs, notifications and running jobs. Call it "
|
||||
"first and whenever you are unsure what the app is doing.",
|
||||
object_schema({}), [&service](const json&, ToolContext& ctx) { return ToolResult::ok(ctx.run_ui([&service] { return app_state(service); })); }));
|
||||
|
||||
ToolDef wait = inspect_tool(
|
||||
"wait", "Wait for a condition",
|
||||
"Block until a condition holds or timeout_s passes (max 50). for: \"ready\" (startup finished), \"idle\" (no dialog, "
|
||||
"no running job, nothing slicing or arranging), \"dialog\" / \"no_dialog\", or \"job\" with a job id returned by "
|
||||
"an earlier call - then the reply is that job's result. Returns {satisfied:false} on timeout; call it again.",
|
||||
object_schema({{"for", enum_prop({"ready", "idle", "dialog", "no_dialog", "job"}, "What to wait for.")},
|
||||
{"job", prop("string", "Job id, for \"job\".")},
|
||||
{"timeout_s", {{"type", "number"}, {"minimum", 0}, {"maximum", 50}, {"description", "Default 30."}}}},
|
||||
{"for"}),
|
||||
[&service](const json& args, ToolContext& ctx) {
|
||||
const std::string what = arg_string(args, "for");
|
||||
const auto timeout = std::chrono::milliseconds(int(arg_double(args, "timeout_s", 30) * 1000));
|
||||
const auto start = std::chrono::steady_clock::now();
|
||||
if (what == "job") {
|
||||
const std::string job = arg_string(args, "job");
|
||||
if (job.empty())
|
||||
throw ToolFailure("job is required for \"job\"");
|
||||
if (auto r = service.jobs().wait(job, timeout))
|
||||
return *r;
|
||||
return ToolResult::ok({{"status", "running"}, {"job", job}, {"note", "Still running; wait again."}});
|
||||
}
|
||||
const std::set<std::string> own = ctx.lineage();
|
||||
for (;;) {
|
||||
const bool holds = ctx.run_ui([&] { return json(condition_holds(service, what, own)); }).get<bool>();
|
||||
const auto waited = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start);
|
||||
if (holds)
|
||||
return ToolResult::ok({{"satisfied", true}, {"waited_ms", waited.count()}});
|
||||
if (waited >= timeout || ctx.cancelled())
|
||||
return ToolResult::ok({{"satisfied", false}, {"waited_ms", waited.count()}});
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(150));
|
||||
}
|
||||
});
|
||||
wait.journal = true; // a replay needs the same waits
|
||||
reg.add(wait);
|
||||
|
||||
reg.add(inspect_tool(
|
||||
"get_log", "Read the log",
|
||||
"The last lines of OrcaSlicer's current log file, optionally only those at or above a level.",
|
||||
object_schema({{"lines", {{"type", "integer"}, {"minimum", 1}, {"maximum", 2000}, {"description", "Default 200."}}},
|
||||
{"level", enum_prop({"trace", "debug", "info", "warning", "error", "fatal"}, "Minimum level.")}}),
|
||||
[](const json& args, ToolContext&) {
|
||||
const boost::filesystem::path file = get_log_file_name();
|
||||
if (file.empty())
|
||||
throw ToolFailure("No log file is open");
|
||||
static const std::vector<std::string> levels{"trace", "debug", "info", "warning", "error", "fatal"};
|
||||
const std::string min_level = arg_string(args, "level", "trace");
|
||||
const auto min_it = std::find(levels.begin(), levels.end(), min_level);
|
||||
const std::size_t lines = std::size_t(arg_int(args, "lines", 200));
|
||||
flush_logs();
|
||||
boost::nowide::ifstream in(file.string());
|
||||
std::deque<std::string> tail;
|
||||
std::string line;
|
||||
while (std::getline(in, line)) {
|
||||
bool keep = min_it == levels.begin();
|
||||
for (auto it = min_it; !keep && it != levels.end(); ++it)
|
||||
keep = line.find("[" + *it + "]") != std::string::npos;
|
||||
if (!keep)
|
||||
continue;
|
||||
tail.push_back(line);
|
||||
if (tail.size() > lines)
|
||||
tail.pop_front();
|
||||
}
|
||||
return ToolResult::ok({{"file", file.string()}, {"lines", json(std::vector<std::string>(tail.begin(), tail.end()))}});
|
||||
}));
|
||||
}
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -0,0 +1,128 @@
|
||||
#include "McpTools.hpp"
|
||||
|
||||
#include "slic3r/GUI/GUI_App.hpp"
|
||||
#include "slic3r/GUI/Plater.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
using nlohmann::json;
|
||||
|
||||
json object_schema(std::initializer_list<Property> properties, std::vector<std::string> required)
|
||||
{
|
||||
json props = json::object();
|
||||
for (const auto& [name, schema] : properties)
|
||||
props[name] = schema;
|
||||
json out{{"type", "object"}, {"properties", std::move(props)}, {"additionalProperties", false}};
|
||||
if (!required.empty())
|
||||
out["required"] = std::move(required);
|
||||
return out;
|
||||
}
|
||||
|
||||
json prop(const char* type, const std::string& description) { return {{"type", type}, {"description", description}}; }
|
||||
|
||||
json enum_prop(std::vector<std::string> values, const std::string& description)
|
||||
{
|
||||
return {{"type", "string"}, {"enum", std::move(values)}, {"description", description}};
|
||||
}
|
||||
|
||||
json array_prop(json items, const std::string& description) { return {{"type", "array"}, {"items", std::move(items)}, {"description", description}}; }
|
||||
|
||||
ToolDef inspect_tool(std::string name, std::string title, std::string description, json schema, ToolHandler handler)
|
||||
{
|
||||
ToolDef d;
|
||||
d.name = std::move(name);
|
||||
d.title = std::move(title);
|
||||
d.description = std::move(description);
|
||||
d.input_schema = std::move(schema);
|
||||
d.read_only = true;
|
||||
d.idempotent = true;
|
||||
d.guard = GuardClass::Inspect;
|
||||
d.inline_call = true;
|
||||
d.journal = false;
|
||||
d.handler = std::move(handler);
|
||||
return d;
|
||||
}
|
||||
|
||||
ToolDef mutate_tool(std::string name, std::string title, std::string description, json schema, ToolHandler handler, bool destructive)
|
||||
{
|
||||
ToolDef d;
|
||||
d.name = std::move(name);
|
||||
d.title = std::move(title);
|
||||
d.description = std::move(description);
|
||||
d.input_schema = std::move(schema);
|
||||
d.destructive = destructive;
|
||||
d.guard = GuardClass::Mutate;
|
||||
d.handler = std::move(handler);
|
||||
return d;
|
||||
}
|
||||
|
||||
void settle(ToolContext& ctx) { ctx.run_ui([] { return json(); }); }
|
||||
|
||||
Plater& ui_plater()
|
||||
{
|
||||
if (wxTheApp == nullptr || wxGetApp().is_closing())
|
||||
throw ToolFailure("OrcaSlicer is shutting down");
|
||||
Plater* plater = wxGetApp().plater();
|
||||
if (plater == nullptr || wxGetApp().mainframe == nullptr)
|
||||
throw ToolFailure("OrcaSlicer is still starting; wait {for:\"ready\"} first");
|
||||
return *plater;
|
||||
}
|
||||
|
||||
std::string arg_string(const json& args, const char* key, const std::string& fallback)
|
||||
{
|
||||
auto it = args.find(key);
|
||||
return it != args.end() && it->is_string() ? it->get<std::string>() : fallback;
|
||||
}
|
||||
|
||||
int arg_int(const json& args, const char* key, int fallback)
|
||||
{
|
||||
auto it = args.find(key);
|
||||
return it != args.end() && it->is_number() ? it->get<int>() : fallback;
|
||||
}
|
||||
|
||||
double arg_double(const json& args, const char* key, double fallback)
|
||||
{
|
||||
auto it = args.find(key);
|
||||
return it != args.end() && it->is_number() ? it->get<double>() : fallback;
|
||||
}
|
||||
|
||||
bool arg_bool(const json& args, const char* key, bool fallback)
|
||||
{
|
||||
auto it = args.find(key);
|
||||
return it != args.end() && it->is_boolean() ? it->get<bool>() : fallback;
|
||||
}
|
||||
|
||||
json page(const json& items, const json& args, std::size_t default_limit)
|
||||
{
|
||||
const std::size_t total = items.size();
|
||||
const std::size_t offset = std::min<std::size_t>(std::size_t(std::max(0, arg_int(args, "offset", 0))), total);
|
||||
const std::size_t limit = std::size_t(std::max(1, arg_int(args, "limit", int(default_limit))));
|
||||
json out = json::array();
|
||||
for (std::size_t i = offset; i < total && out.size() < limit; ++i)
|
||||
out.push_back(items[i]);
|
||||
json result{{"total", total}, {"offset", offset}, {"items", std::move(out)}};
|
||||
if (offset + limit < total)
|
||||
result["next_offset"] = offset + limit;
|
||||
return result;
|
||||
}
|
||||
|
||||
json poll_ui(ToolContext& ctx, const std::function<json()>& poll, std::chrono::milliseconds timeout, const std::string& what)
|
||||
{
|
||||
const auto end = std::chrono::steady_clock::now() + timeout;
|
||||
for (;;) {
|
||||
json v = ctx.run_ui(poll);
|
||||
if (!v.is_null())
|
||||
return v;
|
||||
if (ctx.cancelled())
|
||||
throw ToolFailure("OrcaSlicer is shutting down");
|
||||
if (std::chrono::steady_clock::now() >= end)
|
||||
throw ToolFailure("Timed out waiting for " + what);
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(200));
|
||||
}
|
||||
}
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -0,0 +1,478 @@
|
||||
// list_presets, select_preset, get_settings and set_settings: presets are selected through the
|
||||
// same selectors a person uses, and settings change through the Tab's own transaction (strict
|
||||
// parsing, on_change callbacks, rollback on failure), so the UI and the project stay consistent.
|
||||
|
||||
#include "McpService.hpp"
|
||||
#include "McpTools.hpp"
|
||||
#include "slic3r/GUI/GUI.hpp"
|
||||
#include "slic3r/GUI/GUI_App.hpp"
|
||||
#include "slic3r/GUI/GUI_ObjectList.hpp"
|
||||
#include "slic3r/GUI/Plater.hpp"
|
||||
#include "slic3r/GUI/PresetComboBoxes.hpp"
|
||||
#include "slic3r/GUI/Tab.hpp"
|
||||
|
||||
#include "libslic3r/Config.hpp"
|
||||
#include "libslic3r/Model.hpp"
|
||||
#include "libslic3r/Preset.hpp"
|
||||
#include "libslic3r/PresetBundle.hpp"
|
||||
#include "libslic3r/PrintConfig.hpp"
|
||||
|
||||
#include <wx/event.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cfloat>
|
||||
#include <cmath>
|
||||
#include <exception>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
using nlohmann::json;
|
||||
|
||||
namespace {
|
||||
|
||||
Preset::Type preset_type(const std::string& name)
|
||||
{
|
||||
if (name == "process" || name == "print")
|
||||
return Preset::TYPE_PRINT;
|
||||
if (name == "filament")
|
||||
return Preset::TYPE_FILAMENT;
|
||||
if (name == "printer")
|
||||
return Preset::TYPE_PRINTER;
|
||||
throw ToolFailure("Unknown preset type " + name + " (printer, process, filament)");
|
||||
}
|
||||
|
||||
PresetCollection& collection(Preset::Type type)
|
||||
{
|
||||
PresetBundle& b = *wxGetApp().preset_bundle;
|
||||
switch (type) {
|
||||
case Preset::TYPE_PRINT: return b.prints;
|
||||
case Preset::TYPE_FILAMENT: return b.filaments;
|
||||
default: return b.printers;
|
||||
}
|
||||
}
|
||||
|
||||
std::string lower(std::string s)
|
||||
{
|
||||
std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return char(std::tolower(c)); });
|
||||
return s;
|
||||
}
|
||||
|
||||
const char* mode_name(ConfigOptionMode mode)
|
||||
{
|
||||
switch (mode) {
|
||||
case comAdvanced: return "advanced";
|
||||
case comExpert: return "expert";
|
||||
case comDevelop: return "develop";
|
||||
default: return "simple";
|
||||
}
|
||||
}
|
||||
|
||||
const char* type_name(ConfigOptionType type)
|
||||
{
|
||||
switch (type) {
|
||||
case coFloat: return "float";
|
||||
case coFloats: return "floats";
|
||||
case coInt: return "int";
|
||||
case coInts: return "ints";
|
||||
case coString: return "string";
|
||||
case coStrings: return "strings";
|
||||
case coPercent: return "percent";
|
||||
case coPercents: return "percents";
|
||||
case coFloatOrPercent: return "float_or_percent";
|
||||
case coFloatsOrPercents: return "floats_or_percents";
|
||||
case coPoint: return "point";
|
||||
case coPoints: return "points";
|
||||
case coPoint3: return "point3";
|
||||
case coBool: return "bool";
|
||||
case coBools: return "bools";
|
||||
case coEnum: return "enum";
|
||||
case coEnums: return "enums";
|
||||
default: return "other";
|
||||
}
|
||||
}
|
||||
|
||||
json option_meta(const ConfigOptionDef& def)
|
||||
{
|
||||
json meta{{"label", def.full_label.empty() ? def.label : def.full_label},
|
||||
{"type", type_name(def.type)},
|
||||
{"mode", mode_name(def.mode)}};
|
||||
if (!def.category.empty())
|
||||
meta["category"] = def.category;
|
||||
if (!def.sidetext.empty())
|
||||
meta["unit"] = def.sidetext;
|
||||
if (!def.tooltip.empty())
|
||||
meta["tooltip"] = def.tooltip.size() > 300 ? def.tooltip.substr(0, 300) + "..." : def.tooltip;
|
||||
if (def.min > -FLT_MAX && def.min != -FLT_MAX)
|
||||
meta["min"] = def.min;
|
||||
if (def.max < FLT_MAX && def.max != FLT_MAX)
|
||||
meta["max"] = def.max;
|
||||
if (!def.enum_values.empty())
|
||||
meta["values"] = def.enum_values;
|
||||
return meta;
|
||||
}
|
||||
|
||||
// "3" for 3, "0.2" for 0.2, "1"/"0" for booleans, "a,b" for arrays: the serialized forms
|
||||
// set_deserialize accepts.
|
||||
std::string to_config_string(const json& v)
|
||||
{
|
||||
if (v.is_string())
|
||||
return v.get<std::string>();
|
||||
if (v.is_boolean())
|
||||
return v.get<bool>() ? "1" : "0";
|
||||
if (v.is_number_integer() || v.is_number_unsigned())
|
||||
return std::to_string(v.get<long long>());
|
||||
if (v.is_number()) {
|
||||
std::ostringstream out;
|
||||
out.precision(15);
|
||||
out << v.get<double>();
|
||||
return out.str();
|
||||
}
|
||||
if (v.is_array()) {
|
||||
std::string out;
|
||||
for (const json& e : v) {
|
||||
if (!out.empty())
|
||||
out += ",";
|
||||
out += to_config_string(e);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
throw ToolFailure("Unsupported value " + v.dump());
|
||||
}
|
||||
|
||||
// Option keys whose key or label contains `query`, for "did you mean" and for get_settings' query.
|
||||
std::vector<std::string> search_keys(const std::string& query, const std::vector<std::string>& within, std::size_t limit)
|
||||
{
|
||||
const std::string q = lower(query);
|
||||
std::vector<std::string> out;
|
||||
for (const std::string& key : within) {
|
||||
const ConfigOptionDef* def = print_config_def.get(key);
|
||||
const bool hit = lower(key).find(q) != std::string::npos ||
|
||||
(def != nullptr && (lower(def->label).find(q) != std::string::npos || lower(def->full_label).find(q) != std::string::npos));
|
||||
if (hit)
|
||||
out.push_back(key);
|
||||
if (out.size() >= limit)
|
||||
break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
struct ConfigTarget
|
||||
{
|
||||
Preset::Type type = Preset::TYPE_INVALID; // preset scopes
|
||||
ModelObject* object = nullptr; // object/volume scopes
|
||||
ModelVolume* volume = nullptr;
|
||||
int object_index = -1;
|
||||
const DynamicPrintConfig* config = nullptr;
|
||||
std::vector<std::string> options; // keys valid in this scope
|
||||
};
|
||||
|
||||
// Resolves the scope arguments to the config they read and write. UI thread.
|
||||
ConfigTarget resolve_target(const json& args, bool for_write)
|
||||
{
|
||||
const std::string scope = arg_string(args, "scope", "print");
|
||||
PresetBundle& bundle = *wxGetApp().preset_bundle;
|
||||
ConfigTarget t;
|
||||
if (scope == "object" || scope == "volume") {
|
||||
Plater& plater = ui_plater();
|
||||
const int idx = arg_int(args, "object", -1);
|
||||
ModelObjectPtrs& objects = plater.model().objects;
|
||||
if (idx < 0 || idx >= int(objects.size()))
|
||||
throw ToolFailure("object must be an index from list_objects (0.." + std::to_string(int(objects.size()) - 1) + ")");
|
||||
t.object = objects[size_t(idx)];
|
||||
t.object_index = idx;
|
||||
if (scope == "volume") {
|
||||
const int v = arg_int(args, "volume", -1);
|
||||
if (v < 0 || v >= int(t.object->volumes.size()))
|
||||
throw ToolFailure("volume must be a part index from list_objects");
|
||||
t.volume = t.object->volumes[size_t(v)];
|
||||
t.config = &t.volume->config.get();
|
||||
} else {
|
||||
t.config = &t.object->config.get();
|
||||
}
|
||||
// Per-object overrides take print (process) settings.
|
||||
t.options = Preset::print_options();
|
||||
return t;
|
||||
}
|
||||
t.type = preset_type(scope);
|
||||
t.options = t.type == Preset::TYPE_PRINT ? Preset::print_options() :
|
||||
t.type == Preset::TYPE_FILAMENT ? Preset::filament_options() : Preset::printer_options();
|
||||
if (t.type == Preset::TYPE_FILAMENT) {
|
||||
const int slot = arg_int(args, "filament_slot", 1);
|
||||
if (slot < 1 || slot > int(bundle.filament_presets.size()))
|
||||
throw ToolFailure("filament_slot must be 1.." + std::to_string(bundle.filament_presets.size()));
|
||||
const std::string& name = bundle.filament_presets[size_t(slot - 1)];
|
||||
Tab* tab = wxGetApp().get_tab(Preset::TYPE_FILAMENT);
|
||||
if (for_write && tab != nullptr && bundle.filaments.get_edited_preset().name != name) {
|
||||
// The filament tab edits one preset at a time; switch it to this slot's preset first,
|
||||
// through the normal flow (which asks about unsaved changes).
|
||||
if (!tab->select_preset(name))
|
||||
throw ToolFailure("Switching the filament tab to \"" + name + "\" was cancelled");
|
||||
if (TabPresetComboBox* combo = tab->get_combo_box())
|
||||
combo->set_filament_idx(slot - 1);
|
||||
}
|
||||
if (bundle.filaments.get_edited_preset().name == name)
|
||||
t.config = &bundle.filaments.get_edited_preset().config;
|
||||
else if (const Preset* p = bundle.filaments.find_preset(name))
|
||||
t.config = &p->config;
|
||||
else
|
||||
throw ToolFailure("Filament slot " + std::to_string(slot) + " has no preset");
|
||||
return t;
|
||||
}
|
||||
t.config = &collection(t.type).get_edited_preset().config;
|
||||
return t;
|
||||
}
|
||||
|
||||
json list_presets(const json& args)
|
||||
{
|
||||
const Preset::Type type = preset_type(arg_string(args, "type"));
|
||||
const bool include_incompatible = arg_bool(args, "include_incompatible", false);
|
||||
const bool include_hidden = arg_bool(args, "include_hidden", false);
|
||||
const std::string query = lower(arg_string(args, "query"));
|
||||
PresetCollection& presets = collection(type);
|
||||
const std::string selected = presets.get_selected_preset_name();
|
||||
PresetBundle& bundle = *wxGetApp().preset_bundle;
|
||||
json items = json::array();
|
||||
for (size_t i = 0; i < presets.size(); ++i) {
|
||||
const Preset& p = presets.preset(i);
|
||||
if (p.is_default && presets.size() > 1)
|
||||
continue;
|
||||
if (!include_incompatible && !p.is_compatible)
|
||||
continue;
|
||||
if (!include_hidden && !p.is_visible)
|
||||
continue;
|
||||
if (!query.empty() && lower(p.name).find(query) == std::string::npos && lower(p.alias).find(query) == std::string::npos)
|
||||
continue;
|
||||
json j{{"name", p.name}, {"system", p.is_system}, {"user", p.is_user()}};
|
||||
if (!p.alias.empty() && p.alias != p.name)
|
||||
j["alias"] = p.alias;
|
||||
if (!p.is_compatible)
|
||||
j["compatible"] = false;
|
||||
if (!p.is_visible)
|
||||
j["visible"] = false;
|
||||
if (p.name == selected) {
|
||||
j["selected"] = true;
|
||||
if (presets.current_is_dirty())
|
||||
j["modified"] = true;
|
||||
}
|
||||
if (type == Preset::TYPE_FILAMENT) {
|
||||
json slots = json::array();
|
||||
for (size_t s = 0; s < bundle.filament_presets.size(); ++s)
|
||||
if (bundle.filament_presets[s] == p.name)
|
||||
slots.push_back(int(s + 1));
|
||||
if (!slots.empty())
|
||||
j["filament_slots"] = std::move(slots);
|
||||
}
|
||||
items.push_back(std::move(j));
|
||||
}
|
||||
return page(items, args, 100);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void register_config_tools(McpService& service)
|
||||
{
|
||||
ToolRegistry& reg = service.registry();
|
||||
const json scope_prop = enum_prop({"print", "process", "filament", "printer", "object", "volume"},
|
||||
"Which settings: the process (print), filament or printer preset being edited, or an "
|
||||
"object's / part's own overrides.");
|
||||
|
||||
reg.add(inspect_tool(
|
||||
"list_presets", "List presets",
|
||||
"Printer, process or filament presets with flags: system or user, selected (and modified), compatible with the "
|
||||
"selected printer, and for filaments the slots using them. Only compatible, visible presets unless asked.",
|
||||
object_schema({{"type", enum_prop({"printer", "process", "filament"}, "Preset category.")},
|
||||
{"query", prop("string", "Case-insensitive part of the name.")},
|
||||
{"include_incompatible", prop("boolean", "Also list presets incompatible with the printer.")},
|
||||
{"include_hidden", prop("boolean", "Also list hidden presets.")},
|
||||
{"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 500}}},
|
||||
{"offset", {{"type", "integer"}, {"minimum", 0}}}},
|
||||
{"type"}),
|
||||
[](const json& args, ToolContext& ctx) { return ToolResult::ok(ctx.run_ui([&] { return list_presets(args); })); }));
|
||||
|
||||
reg.add(mutate_tool(
|
||||
"select_preset", "Select a preset",
|
||||
"Select a printer, process or filament preset by the name its selector shows (or its internal name), as a person "
|
||||
"would - which may open the unsaved-changes dialog (the reply is then blocked_by_dialog). A filament is assigned to "
|
||||
"filament_slot (1-based, default 1).",
|
||||
object_schema({{"type", enum_prop({"printer", "process", "filament"}, "Preset category.")},
|
||||
{"name", prop("string", "Preset name as list_presets shows it.")},
|
||||
{"filament_slot", {{"type", "integer"}, {"minimum", 1}, {"description", "Filament slot, 1-based."}}}},
|
||||
{"type", "name"}),
|
||||
[](const json& args, ToolContext& ctx) {
|
||||
const Preset::Type type = preset_type(arg_string(args, "type"));
|
||||
const std::string name = arg_string(args, "name");
|
||||
json result = ctx.run_ui([&]() -> json {
|
||||
ui_plater();
|
||||
PresetBundle& bundle = *wxGetApp().preset_bundle;
|
||||
if (type == Preset::TYPE_FILAMENT) {
|
||||
const int slot = arg_int(args, "filament_slot", 1);
|
||||
auto& combos = wxGetApp().plater()->sidebar().combos_filament();
|
||||
if (slot < 1 || slot > int(combos.size()) || combos[size_t(slot - 1)] == nullptr)
|
||||
throw ToolFailure("filament_slot must be 1.." + std::to_string(combos.size()));
|
||||
PlaterPresetComboBox* combo = combos[size_t(slot - 1)];
|
||||
const auto match = combo->find_by_name(name);
|
||||
if (match.ambiguous)
|
||||
throw ToolFailure("\"" + name + "\" is ambiguous in filament slot " + std::to_string(slot) + "'s selector; use the internal name");
|
||||
if (match.item < 0)
|
||||
throw ToolFailure("Filament slot " + std::to_string(slot) + " does not offer \"" + name + "\" (see list_presets)");
|
||||
// The sidebar's own selection path: mapping, flush volumes, badges, project state.
|
||||
combo->SetSelection(match.item);
|
||||
wxCommandEvent evt(wxEVT_COMBOBOX, combo->GetId());
|
||||
evt.SetEventObject(combo);
|
||||
evt.SetInt(match.item);
|
||||
evt.SetString(combo->GetString(match.item));
|
||||
combo->GetEventHandler()->ProcessEvent(evt);
|
||||
return {{"type", "filament"}, {"filament_slot", slot}, {"selected", bundle.filament_presets[size_t(slot - 1)]}};
|
||||
}
|
||||
Tab* tab = wxGetApp().get_tab(type);
|
||||
if (tab == nullptr)
|
||||
throw ToolFailure("The settings tab is not available");
|
||||
std::string target = name;
|
||||
if (TabPresetComboBox* combo = tab->get_combo_box(); combo != nullptr && combo->GetCount() > 0) {
|
||||
const auto match = combo->find_by_name(name);
|
||||
if (match.ambiguous)
|
||||
throw ToolFailure("\"" + name + "\" is ambiguous; use the internal name");
|
||||
if (match.item < 0)
|
||||
throw ToolFailure("The selector does not offer \"" + name + "\" (see list_presets)");
|
||||
target = match.internal_name;
|
||||
}
|
||||
if (!tab->select_preset(target))
|
||||
throw ToolFailure("Selecting \"" + target + "\" was cancelled");
|
||||
return {{"type", arg_string(args, "type")}, {"selected", collection(type).get_selected_preset_name()}};
|
||||
});
|
||||
settle(ctx);
|
||||
return ToolResult::ok(result);
|
||||
}));
|
||||
|
||||
reg.add(inspect_tool(
|
||||
"get_settings", "Read settings",
|
||||
"Read setting values (as OrcaSlicer serializes them) with label, type, unit, range, allowed values and mode. Name "
|
||||
"keys, or search with query (matches key or label); without either, every option of the scope is listed, paged. "
|
||||
"For object/volume scopes only the overrides that object or part carries are listed.",
|
||||
object_schema({{"scope", scope_prop},
|
||||
{"keys", array_prop({{"type", "string"}}, "Option keys, e.g. [\"layer_height\", \"wall_loops\"].")},
|
||||
{"query", prop("string", "Search keys and labels.")},
|
||||
{"object", {{"type", "integer"}, {"minimum", 0}, {"description", "Object index (object/volume scope)."}}},
|
||||
{"volume", {{"type", "integer"}, {"minimum", 0}, {"description", "Part index (volume scope)."}}},
|
||||
{"filament_slot", {{"type", "integer"}, {"minimum", 1}, {"description", "Filament slot, 1-based."}}},
|
||||
{"include_meta", prop("boolean", "Include labels, types and ranges. Default true.")},
|
||||
{"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 500}}},
|
||||
{"offset", {{"type", "integer"}, {"minimum", 0}}}}),
|
||||
[](const json& args, ToolContext& ctx) {
|
||||
return ToolResult::ok(ctx.run_ui([&] {
|
||||
const ConfigTarget t = resolve_target(args, false);
|
||||
const bool meta = arg_bool(args, "include_meta", true);
|
||||
std::vector<std::string> keys;
|
||||
if (args.contains("keys")) {
|
||||
for (const json& k : args["keys"])
|
||||
keys.push_back(k.get<std::string>());
|
||||
} else if (args.contains("query")) {
|
||||
keys = search_keys(arg_string(args, "query"), t.options, 200);
|
||||
} else if (t.object != nullptr) {
|
||||
keys = t.config->keys();
|
||||
} else {
|
||||
keys = t.options;
|
||||
}
|
||||
json items = json::array();
|
||||
json unknown = json::array();
|
||||
for (const std::string& key : keys) {
|
||||
const ConfigOptionDef* def = print_config_def.get(key);
|
||||
if (def == nullptr || std::find(t.options.begin(), t.options.end(), key) == t.options.end()) {
|
||||
unknown.push_back(key);
|
||||
continue;
|
||||
}
|
||||
json item{{"key", key}};
|
||||
if (t.config->has(key))
|
||||
item["value"] = t.config->opt_serialize(key);
|
||||
else
|
||||
item["value"] = nullptr; // not overridden at this level
|
||||
if (meta)
|
||||
item["meta"] = option_meta(*def);
|
||||
items.push_back(std::move(item));
|
||||
}
|
||||
json out = page(items, args, 100);
|
||||
if (!unknown.empty())
|
||||
out["unknown_keys"] = unknown;
|
||||
return out;
|
||||
}));
|
||||
}));
|
||||
|
||||
reg.add(mutate_tool(
|
||||
"set_settings", "Change settings",
|
||||
"Change settings as if typed into the settings tab: all values are parsed strictly first and applied together, and "
|
||||
"nothing changes if any is invalid. Values may be strings in OrcaSlicer's format (\"15%\", \"0.2\", \"1,2\") or JSON "
|
||||
"numbers, booleans and arrays. object/volume scopes set per-object or per-part overrides; a null value removes an "
|
||||
"override.",
|
||||
object_schema({{"scope", scope_prop},
|
||||
{"values", {{"type", "object"}, {"description", "{key: value}"}}},
|
||||
{"object", {{"type", "integer"}, {"minimum", 0}}},
|
||||
{"volume", {{"type", "integer"}, {"minimum", 0}}},
|
||||
{"filament_slot", {{"type", "integer"}, {"minimum", 1}}}},
|
||||
{"values"}),
|
||||
[](const json& args, ToolContext& ctx) {
|
||||
if (!args["values"].is_object() || args["values"].empty())
|
||||
throw ToolFailure("values must be a non-empty object {key: value}");
|
||||
json result = ctx.run_ui([&]() -> json {
|
||||
ui_plater();
|
||||
const ConfigTarget t = resolve_target(args, true);
|
||||
std::vector<std::pair<std::string, std::string>> values;
|
||||
std::vector<std::string> removals;
|
||||
for (auto it = args["values"].begin(); it != args["values"].end(); ++it) {
|
||||
if (std::find(t.options.begin(), t.options.end(), it.key()) == t.options.end())
|
||||
throw ToolFailure("Unknown setting \"" + it.key() + "\" for this scope",
|
||||
{{"similar", search_keys(it.key().substr(0, std::max<std::size_t>(3, it.key().size() / 2)), t.options, 5)}});
|
||||
if (it.value().is_null()) {
|
||||
if (t.object == nullptr)
|
||||
throw ToolFailure("null removes an object/part override; preset settings always have a value");
|
||||
removals.push_back(it.key());
|
||||
} else {
|
||||
values.emplace_back(it.key(), to_config_string(it.value()));
|
||||
}
|
||||
}
|
||||
if (t.object == nullptr) {
|
||||
Tab* tab = wxGetApp().get_tab(t.type);
|
||||
if (tab == nullptr)
|
||||
throw ToolFailure("The settings tab is not available");
|
||||
try {
|
||||
tab->apply_preset_config_values(values);
|
||||
} catch (const std::exception& e) {
|
||||
throw ToolFailure(e.what());
|
||||
}
|
||||
} else {
|
||||
// Strict-parse everything into a scratch config before touching the model.
|
||||
DynamicPrintConfig scratch;
|
||||
for (const auto& [key, value] : values)
|
||||
try {
|
||||
scratch.set_deserialize_strict(key, value);
|
||||
} catch (const std::exception& e) {
|
||||
throw ToolFailure("Invalid value for " + key + ": " + e.what());
|
||||
}
|
||||
Plater& plater = ui_plater();
|
||||
plater.take_snapshot("Change object settings");
|
||||
ModelConfig& cfg = t.volume != nullptr ? static_cast<ModelConfig&>(t.volume->config) : static_cast<ModelConfig&>(t.object->config);
|
||||
for (const auto& [key, value] : values)
|
||||
cfg.set_key_value(key, scratch.option(key)->clone());
|
||||
for (const std::string& key : removals)
|
||||
cfg.erase(key);
|
||||
wxGetApp().obj_list()->object_config_options_changed(ObjectVolumeID{t.object, t.volume});
|
||||
plater.changed_object(t.object_index);
|
||||
}
|
||||
const ConfigTarget after = resolve_target(args, false);
|
||||
json applied = json::object();
|
||||
for (const auto& [key, value] : values)
|
||||
applied[key] = after.config->has(key) ? json(after.config->opt_serialize(key)) : json();
|
||||
for (const std::string& key : removals)
|
||||
applied[key] = nullptr;
|
||||
return {{"applied", applied}};
|
||||
});
|
||||
settle(ctx);
|
||||
return ToolResult::ok(result);
|
||||
}));
|
||||
}
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -0,0 +1,7 @@
|
||||
#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,210 @@
|
||||
// open_files, new_project, save_project and export: files in and out without file dialogs.
|
||||
|
||||
#include "McpPaths.hpp"
|
||||
#include "McpService.hpp"
|
||||
#include "McpTools.hpp"
|
||||
#include "slic3r/GUI/GUI.hpp"
|
||||
#include "slic3r/GUI/GUI_App.hpp"
|
||||
#include "slic3r/GUI/MainFrame.hpp"
|
||||
#include "slic3r/GUI/PartPlate.hpp"
|
||||
#include "slic3r/GUI/Plater.hpp"
|
||||
|
||||
#include "libslic3r/Model.hpp"
|
||||
|
||||
#include <boost/algorithm/string/predicate.hpp>
|
||||
#include <boost/filesystem/operations.hpp>
|
||||
#include <boost/filesystem/path.hpp>
|
||||
|
||||
#include <initializer_list>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
using nlohmann::json;
|
||||
namespace fs = boost::filesystem;
|
||||
|
||||
namespace {
|
||||
|
||||
bool has_extension(const fs::path& p, std::initializer_list<const char*> exts)
|
||||
{
|
||||
const std::string name = p.filename().string();
|
||||
for (const char* e : exts)
|
||||
if (boost::algorithm::iends_with(name, e))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
json objects_summary(Plater& plater)
|
||||
{
|
||||
json names = json::array();
|
||||
for (const ModelObject* o : plater.model().objects)
|
||||
names.push_back(o->name);
|
||||
return {{"objects", plater.model().objects.size()}, {"names", std::move(names)}, {"plates", plater.get_partplate_list().get_plate_count()}};
|
||||
}
|
||||
|
||||
// Discards unsaved changes without a prompt when the caller said so, or fails.
|
||||
void require_clean_or_discard(Plater& plater, bool discard)
|
||||
{
|
||||
if (!plater.is_project_dirty())
|
||||
return;
|
||||
if (!discard)
|
||||
throw ToolFailure("The project has unsaved changes; save_project first, or pass discard_changes: true");
|
||||
plater.new_project(/*skip_confirm=*/true, /*silent=*/true);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void register_project_tools(McpService& service)
|
||||
{
|
||||
ToolRegistry& reg = service.registry();
|
||||
|
||||
reg.add(mutate_tool(
|
||||
"open_files", "Open files",
|
||||
"Open model files (STL, 3MF, STEP, OBJ, AMF, SVG...), a project (.3mf) or G-code by absolute path, without a file "
|
||||
"dialog. Models are added to the current project. A .3mf opens as a project (replacing the current one: pass "
|
||||
"discard_changes when it has unsaved changes) unless as is \"geometry\". Importing can open a dialog (STEP mesh "
|
||||
"options, for instance); the reply is then blocked_by_dialog.",
|
||||
object_schema({{"paths", array_prop({{"type", "string"}}, "Absolute paths.")},
|
||||
{"as", enum_prop({"auto", "geometry", "project"}, "How to open .3mf files. Default auto (= project).")},
|
||||
{"discard_changes", prop("boolean", "Replace a project with unsaved changes without asking.")}},
|
||||
{"paths"}),
|
||||
[](const json& args, ToolContext& ctx) {
|
||||
std::vector<fs::path> paths;
|
||||
for (const json& p : args["paths"]) {
|
||||
std::string err;
|
||||
auto resolved = resolve_input_path(p.get<std::string>(), err);
|
||||
if (!resolved)
|
||||
throw ToolFailure(err);
|
||||
paths.push_back(*resolved);
|
||||
}
|
||||
if (paths.empty())
|
||||
throw ToolFailure("paths is empty");
|
||||
const std::string as = arg_string(args, "as", "auto");
|
||||
const bool discard = arg_bool(args, "discard_changes", false);
|
||||
json out = ctx.run_ui([&]() -> json {
|
||||
Plater& plater = ui_plater();
|
||||
if (paths.size() == 1 && has_extension(paths[0], {".gcode", ".bgcode"})) {
|
||||
plater.load_gcode(from_path(paths[0]));
|
||||
return {{"opened", "gcode"}, {"path", paths[0].string()}};
|
||||
}
|
||||
if (paths.size() == 1 && as != "geometry" && has_extension(paths[0], {".3mf"})) {
|
||||
require_clean_or_discard(plater, discard);
|
||||
plater.load_project(from_path(paths[0]));
|
||||
json o = objects_summary(plater);
|
||||
o["opened"] = "project";
|
||||
return o;
|
||||
}
|
||||
const size_t before = plater.model().objects.size();
|
||||
const auto loaded = plater.load_files(paths, LoadStrategy::LoadModel);
|
||||
if (loaded.empty() && plater.model().objects.size() == before)
|
||||
throw ToolFailure("Nothing was loaded (see get_log for the reason)");
|
||||
json o = objects_summary(plater);
|
||||
o["opened"] = "models";
|
||||
o["added"] = plater.model().objects.size() - before;
|
||||
return o;
|
||||
});
|
||||
settle(ctx);
|
||||
return ToolResult::ok(out);
|
||||
}));
|
||||
|
||||
reg.add(mutate_tool(
|
||||
"new_project", "New project",
|
||||
"Start a new, empty project. Fails when the current project has unsaved changes unless discard_changes is true.",
|
||||
object_schema({{"discard_changes", prop("boolean", "Drop unsaved changes without asking.")}}),
|
||||
[](const json& args, ToolContext& ctx) {
|
||||
const bool discard = arg_bool(args, "discard_changes", false);
|
||||
json out = ctx.run_ui([&] {
|
||||
Plater& plater = ui_plater();
|
||||
if (plater.is_project_dirty() && !discard)
|
||||
throw ToolFailure("The project has unsaved changes; save_project first, or pass discard_changes: true");
|
||||
plater.new_project(/*skip_confirm=*/true, /*silent=*/true);
|
||||
return objects_summary(plater);
|
||||
});
|
||||
settle(ctx);
|
||||
return ToolResult::ok(out);
|
||||
},
|
||||
true));
|
||||
|
||||
reg.add(mutate_tool(
|
||||
"save_project", "Save the project",
|
||||
"Save the project as a .3mf at an absolute path without a dialog; it becomes the project's file.",
|
||||
object_schema({{"path", prop("string", "Absolute .3mf path.")}, {"overwrite", prop("boolean", "Replace an existing file.")}}, {"path"}),
|
||||
[](const json& args, ToolContext& ctx) {
|
||||
std::string err;
|
||||
auto path = resolve_output_path(arg_string(args, "path"), arg_bool(args, "overwrite", false), err);
|
||||
if (!path)
|
||||
throw ToolFailure(err);
|
||||
ctx.run_ui([&] {
|
||||
ui_plater().save_project(true, from_path(*path));
|
||||
return json();
|
||||
});
|
||||
settle(ctx);
|
||||
if (!fs::exists(*path))
|
||||
throw ToolFailure("The project was not saved (see get_log)");
|
||||
return ToolResult::ok({{"path", path->string()}, {"bytes", fs::file_size(*path)}});
|
||||
}));
|
||||
|
||||
reg.add(mutate_tool(
|
||||
"export", "Export",
|
||||
"Write the project to a file without a dialog. gcode: the current plate's G-code (slice first; runs in the "
|
||||
"background and the call completes when the file is written). sliced_3mf: the sliced plate (or all plates) as "
|
||||
".gcode.3mf. 3mf: the model without slicing data. stl: all objects as one STL. plate selects the plate first.",
|
||||
object_schema({{"format", enum_prop({"gcode", "sliced_3mf", "3mf", "stl"}, "What to write.")},
|
||||
{"path", prop("string", "Absolute output path.")},
|
||||
{"plate", {{"type", {"string", "integer"}}, {"description", "\"current\" (default), a plate index, or \"all\" (sliced_3mf only)."}}},
|
||||
{"overwrite", prop("boolean", "Replace an existing file.")}},
|
||||
{"format", "path"}),
|
||||
[](const json& args, ToolContext& ctx) {
|
||||
const std::string format = arg_string(args, "format");
|
||||
std::string err;
|
||||
auto path = resolve_output_path(arg_string(args, "path"), arg_bool(args, "overwrite", false), err);
|
||||
if (!path)
|
||||
throw ToolFailure(err);
|
||||
const json plate = args.value("plate", json("current"));
|
||||
const bool all = plate.is_string() && plate.get<std::string>() == "all";
|
||||
if (all && format != "sliced_3mf")
|
||||
throw ToolFailure("plate \"all\" applies to sliced_3mf only");
|
||||
if (format == "gcode")
|
||||
ctx.begin_operation();
|
||||
json started = ctx.run_ui([&]() -> json {
|
||||
Plater& plater = ui_plater();
|
||||
if (plater.model().objects.empty())
|
||||
throw ToolFailure("The project has no objects");
|
||||
if (plate.is_number_integer()) {
|
||||
const int index = plate.get<int>();
|
||||
if (index < 0 || index >= plater.get_partplate_list().get_plate_count())
|
||||
throw ToolFailure("plate index out of range");
|
||||
plater.select_plate(index);
|
||||
}
|
||||
if (format == "gcode") {
|
||||
if (plater.is_slicing_any())
|
||||
throw ToolFailure("Slicing is in progress; wait {for:\"idle\"} and export again");
|
||||
if (!plater.get_partplate_list().get_curr_plate()->is_slice_result_valid())
|
||||
throw ToolFailure("The plate is not sliced; slice it first");
|
||||
const uint64_t before = plater.export_seq();
|
||||
const uint64_t revision = plater.project_revision();
|
||||
plater.export_gcode_to(*path);
|
||||
return {{"before", before}, {"after", plater.export_seq()}, {"revision", revision}};
|
||||
}
|
||||
if (format == "sliced_3mf") {
|
||||
if (!plater.export_gcode_3mf(all, *path))
|
||||
throw ToolFailure("The sliced file was not written; slice first and check for errors");
|
||||
} else if (format == "3mf") {
|
||||
plater.export_core_3mf(from_path(*path));
|
||||
} else {
|
||||
plater.export_stl(false, false, false, FT_STL, from_path(*path));
|
||||
}
|
||||
return json();
|
||||
});
|
||||
if (format == "gcode")
|
||||
return await_gcode_export(ctx, started["before"], started["after"], started["revision"],
|
||||
"The export did not start; check get_state.notifications");
|
||||
settle(ctx);
|
||||
if (!fs::exists(*path))
|
||||
throw ToolFailure("The file was not written (see get_log)");
|
||||
return ToolResult::ok({{"path", path->string()}, {"bytes", fs::file_size(*path)}});
|
||||
}));
|
||||
}
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -0,0 +1,399 @@
|
||||
// list_objects, select, transform, slice and cancel: the model on the plates, and the slice
|
||||
// operation, which reports its own outcome per plate (see McpOperations).
|
||||
|
||||
#include "McpOperations.hpp"
|
||||
#include "McpService.hpp"
|
||||
#include "McpTools.hpp"
|
||||
#include "slic3r/GUI/GLCanvas3D.hpp"
|
||||
#include "slic3r/GUI/GUI.hpp"
|
||||
#include "slic3r/GUI/GUI_App.hpp"
|
||||
#include "slic3r/GUI/GUI_ObjectList.hpp"
|
||||
#include "slic3r/GUI/MainFrame.hpp"
|
||||
#include "slic3r/GUI/NotificationManager.hpp"
|
||||
#include "slic3r/GUI/PartPlate.hpp"
|
||||
#include "slic3r/GUI/Plater.hpp"
|
||||
#include "slic3r/GUI/Selection.hpp"
|
||||
|
||||
#include "libslic3r/BoundingBox.hpp"
|
||||
#include "libslic3r/GCode/GCodeProcessor.hpp"
|
||||
#include "libslic3r/Geometry.hpp"
|
||||
#include "libslic3r/Model.hpp"
|
||||
#include "libslic3r/Utils.hpp"
|
||||
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <memory>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
using nlohmann::json;
|
||||
|
||||
namespace {
|
||||
|
||||
json vec3(const Vec3d& v) { return {v.x(), v.y(), v.z()}; }
|
||||
|
||||
Vec3d to_vec3(const json& v, const char* what)
|
||||
{
|
||||
if (!v.is_array() || v.size() != 3)
|
||||
throw ToolFailure(std::string(what) + " must be [x, y, z]");
|
||||
return {v[0].get<double>(), v[1].get<double>(), v[2].get<double>()};
|
||||
}
|
||||
|
||||
const char* volume_type_name(ModelVolumeType type)
|
||||
{
|
||||
switch (type) {
|
||||
case ModelVolumeType::MODEL_PART: return "part";
|
||||
case ModelVolumeType::NEGATIVE_VOLUME: return "negative";
|
||||
case ModelVolumeType::PARAMETER_MODIFIER: return "modifier";
|
||||
case ModelVolumeType::SUPPORT_BLOCKER: return "support_blocker";
|
||||
case ModelVolumeType::SUPPORT_ENFORCER: return "support_enforcer";
|
||||
default: return "other";
|
||||
}
|
||||
}
|
||||
|
||||
// The Prepare view and its selection: object operations act on the 3D view.
|
||||
void show_prepare()
|
||||
{
|
||||
Plater& plater = ui_plater();
|
||||
if (!plater.is_view3D_shown()) {
|
||||
plater.select_view_3D("3D");
|
||||
if (MainFrame* mf = wxGetApp().mainframe)
|
||||
mf->select_tab(TAB_ID_PREPARE);
|
||||
}
|
||||
}
|
||||
|
||||
json list_objects(const json& args)
|
||||
{
|
||||
Plater& plater = ui_plater();
|
||||
PartPlateList& plates = plater.get_partplate_list();
|
||||
const ModelObjectPtrs& objects = plater.model().objects;
|
||||
const int only_plate = arg_int(args, "plate", -1);
|
||||
json items = json::array();
|
||||
for (size_t i = 0; i < objects.size(); ++i) {
|
||||
const ModelObject* o = objects[i];
|
||||
json instances = json::array();
|
||||
bool on_plate = only_plate < 0;
|
||||
for (size_t j = 0; j < o->instances.size(); ++j) {
|
||||
const ModelInstance* inst = o->instances[j];
|
||||
const int plate = plates.find_instance(int(i), int(j));
|
||||
on_plate = on_plate || plate == only_plate;
|
||||
const Vec3d rot = inst->get_rotation();
|
||||
instances.push_back({{"index", j},
|
||||
{"plate", plate},
|
||||
{"offset", vec3(inst->get_offset())},
|
||||
{"rotation_deg", vec3(Vec3d(Geometry::rad2deg(rot.x()), Geometry::rad2deg(rot.y()), Geometry::rad2deg(rot.z())))},
|
||||
{"scale", vec3(inst->get_scaling_factor())},
|
||||
{"printable", inst->printable}});
|
||||
}
|
||||
if (!on_plate)
|
||||
continue;
|
||||
json volumes = json::array();
|
||||
for (size_t v = 0; v < o->volumes.size(); ++v)
|
||||
volumes.push_back({{"index", v}, {"name", o->volumes[v]->name}, {"type", volume_type_name(o->volumes[v]->type())}});
|
||||
const BoundingBoxf3 bb = o->instance_bounding_box(0);
|
||||
json overrides = json::array();
|
||||
for (const std::string& key : o->config.keys())
|
||||
overrides.push_back(key);
|
||||
items.push_back({{"index", i},
|
||||
{"name", o->name},
|
||||
{"instances", std::move(instances)},
|
||||
{"volumes", std::move(volumes)},
|
||||
{"bbox", {{"min", vec3(bb.min)}, {"max", vec3(bb.max)}, {"size", vec3(bb.size())}}},
|
||||
{"overrides", std::move(overrides)}});
|
||||
}
|
||||
json out = page(items, args, 200);
|
||||
out["plates"] = plates.get_plate_count();
|
||||
return out;
|
||||
}
|
||||
|
||||
json selection_summary()
|
||||
{
|
||||
Plater& plater = ui_plater();
|
||||
const Selection& sel = plater.get_selection();
|
||||
json out{{"empty", sel.is_empty()}};
|
||||
if (!sel.is_empty()) {
|
||||
out["object"] = sel.get_object_idx();
|
||||
out["instance"] = sel.get_instance_idx();
|
||||
std::set<int> objects;
|
||||
for (unsigned int idx : sel.get_volume_idxs())
|
||||
if (const GLVolume* v = sel.get_volume(idx))
|
||||
objects.insert(v->object_idx());
|
||||
out["objects"] = std::vector<int>(objects.begin(), objects.end());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Per-plate statistics of a valid slice result.
|
||||
json plate_stats(PartPlate& plate)
|
||||
{
|
||||
json out = json::object();
|
||||
GCodeProcessorResult* result = plate.get_slice_result();
|
||||
if (result == nullptr)
|
||||
return out;
|
||||
const auto& stats = result->print_statistics;
|
||||
const double seconds = stats.modes[static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Normal)].time;
|
||||
double meters = 0., grams = 0.;
|
||||
for (const auto& [role, used] : stats.used_filaments_per_role) {
|
||||
meters += used.first;
|
||||
grams += used.second;
|
||||
}
|
||||
out["time_s"] = std::lround(seconds);
|
||||
out["time"] = get_time_dhms(float(seconds));
|
||||
out["filament_m"] = std::round(meters * 100.) / 100.;
|
||||
out["filament_g"] = std::round(grams * 100.) / 100.;
|
||||
return out;
|
||||
}
|
||||
|
||||
struct SliceTicket
|
||||
{
|
||||
SliceTicketState state;
|
||||
std::vector<int> plates;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
void register_scene_tools(McpService& service)
|
||||
{
|
||||
ToolRegistry& reg = service.registry();
|
||||
|
||||
reg.add(inspect_tool(
|
||||
"list_objects", "List objects",
|
||||
"Objects in the project with their instances (plate, position, rotation in degrees, scale), parts and modifiers, "
|
||||
"bounding box and the settings they override. Indices are what select, transform and the object/volume settings "
|
||||
"scopes take.",
|
||||
object_schema({{"plate", {{"type", "integer"}, {"minimum", 0}, {"description", "Only objects on this plate."}}},
|
||||
{"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 500}}},
|
||||
{"offset", {{"type", "integer"}, {"minimum", 0}}}}),
|
||||
[](const json& args, ToolContext& ctx) { return ToolResult::ok(ctx.run_ui([&] { return list_objects(args); })); }));
|
||||
|
||||
reg.add(mutate_tool(
|
||||
"select", "Select objects",
|
||||
"Select objects, instances or parts in the 3D view (switching to Prepare), as clicking them would. Give objects, "
|
||||
"instances ([[object, instance], ...]) or volumes ([[object, part], ...]); add keeps the current selection; all / "
|
||||
"none select everything or nothing.",
|
||||
object_schema({{"objects", array_prop({{"type", "integer"}}, "Object indices.")},
|
||||
{"instances", array_prop({{"type", "array"}}, "[[object, instance], ...]")},
|
||||
{"volumes", array_prop({{"type", "array"}}, "[[object, part], ...]")},
|
||||
{"add", prop("boolean", "Add to the selection instead of replacing it.")},
|
||||
{"all", prop("boolean", "Select all objects.")},
|
||||
{"none", prop("boolean", "Clear the selection.")}}),
|
||||
[](const json& args, ToolContext& ctx) {
|
||||
json out = ctx.run_ui([&] {
|
||||
Plater& plater = ui_plater();
|
||||
show_prepare();
|
||||
if (arg_bool(args, "none", false)) {
|
||||
plater.deselect_all();
|
||||
return selection_summary();
|
||||
}
|
||||
if (arg_bool(args, "all", false)) {
|
||||
plater.select_all();
|
||||
return selection_summary();
|
||||
}
|
||||
Selection& sel = plater.canvas3D()->get_selection();
|
||||
const size_t count = plater.model().objects.size();
|
||||
bool first = !arg_bool(args, "add", false);
|
||||
auto check_obj = [&](int o) {
|
||||
if (o < 0 || size_t(o) >= count)
|
||||
throw ToolFailure("object index " + std::to_string(o) + " is out of range");
|
||||
};
|
||||
for (const json& o : args.value("objects", json::array())) {
|
||||
check_obj(o.get<int>());
|
||||
sel.add_object(unsigned(o.get<int>()), first);
|
||||
first = false;
|
||||
}
|
||||
for (const json& p : args.value("instances", json::array())) {
|
||||
check_obj(p.at(0).get<int>());
|
||||
sel.add_instance(unsigned(p.at(0).get<int>()), unsigned(p.at(1).get<int>()), first);
|
||||
first = false;
|
||||
}
|
||||
for (const json& p : args.value("volumes", json::array())) {
|
||||
check_obj(p.at(0).get<int>());
|
||||
sel.add_volume(unsigned(p.at(0).get<int>()), unsigned(p.at(1).get<int>()), 0, first);
|
||||
first = false;
|
||||
}
|
||||
wxGetApp().obj_list()->update_selections();
|
||||
plater.canvas3D()->set_as_dirty();
|
||||
return selection_summary();
|
||||
});
|
||||
settle(ctx);
|
||||
return ToolResult::ok(out);
|
||||
}));
|
||||
|
||||
reg.add(mutate_tool(
|
||||
"transform", "Move, rotate or scale an instance",
|
||||
"Change one instance's placement. translate is in mm, rotate in degrees about X/Y/Z, scale a factor (one number or "
|
||||
"[x, y, z]). mode \"relative\" (default) adds to the current placement, \"absolute\" sets it. The object is dropped "
|
||||
"back onto the bed afterwards unless drop_to_bed is false. One undo step.",
|
||||
object_schema({{"object", {{"type", "integer"}, {"minimum", 0}}},
|
||||
{"instance", {{"type", "integer"}, {"minimum", 0}, {"description", "Default 0."}}},
|
||||
{"translate", array_prop({{"type", "number"}}, "[x, y, z] mm")},
|
||||
{"rotate", array_prop({{"type", "number"}}, "[x, y, z] degrees")},
|
||||
{"scale", {{"type", {"number", "array"}}, {"description", "Factor or [x, y, z] factors."}}},
|
||||
{"mode", enum_prop({"relative", "absolute"}, "Default relative.")},
|
||||
{"drop_to_bed", prop("boolean", "Default true.")}},
|
||||
{"object"}),
|
||||
[](const json& args, ToolContext& ctx) {
|
||||
json out = ctx.run_ui([&]() -> json {
|
||||
Plater& plater = ui_plater();
|
||||
ModelObjectPtrs& objects = plater.model().objects;
|
||||
const int oi = arg_int(args, "object", -1);
|
||||
if (oi < 0 || oi >= int(objects.size()))
|
||||
throw ToolFailure("object index out of range");
|
||||
ModelObject* object = objects[size_t(oi)];
|
||||
const int ii = arg_int(args, "instance", 0);
|
||||
if (ii < 0 || ii >= int(object->instances.size()))
|
||||
throw ToolFailure("instance index out of range");
|
||||
ModelInstance* inst = object->instances[size_t(ii)];
|
||||
const bool absolute = arg_string(args, "mode", "relative") == "absolute";
|
||||
plater.take_snapshot("Transform object");
|
||||
if (args.contains("translate")) {
|
||||
const Vec3d t = to_vec3(args["translate"], "translate");
|
||||
inst->set_offset(absolute ? t : Vec3d(inst->get_offset() + t));
|
||||
}
|
||||
if (args.contains("rotate")) {
|
||||
const Vec3d r = to_vec3(args["rotate"], "rotate") * (M_PI / 180.);
|
||||
if (absolute)
|
||||
inst->set_rotation(r);
|
||||
else {
|
||||
const Transform3d rot = Geometry::rotation_transform(r) * Geometry::rotation_transform(inst->get_rotation());
|
||||
inst->set_rotation(Geometry::extract_euler_angles(rot));
|
||||
}
|
||||
}
|
||||
if (args.contains("scale")) {
|
||||
const json& s = args["scale"];
|
||||
const Vec3d f = s.is_number() ? Vec3d(s.get<double>(), s.get<double>(), s.get<double>()) : to_vec3(s, "scale");
|
||||
if (f.minCoeff() <= 0.)
|
||||
throw ToolFailure("scale factors must be positive");
|
||||
inst->set_scaling_factor(absolute ? f : Vec3d(inst->get_scaling_factor().cwiseProduct(f)));
|
||||
}
|
||||
if (arg_bool(args, "drop_to_bed", true))
|
||||
object->ensure_on_bed();
|
||||
object->invalidate_bounding_box();
|
||||
plater.changed_object(oi);
|
||||
return {{"object", oi},
|
||||
{"instance", ii},
|
||||
{"offset", vec3(inst->get_offset())},
|
||||
{"scale", vec3(inst->get_scaling_factor())}};
|
||||
});
|
||||
settle(ctx);
|
||||
return ToolResult::ok(out);
|
||||
}));
|
||||
|
||||
ToolDef slice = mutate_tool(
|
||||
"slice", "Slice",
|
||||
"Slice the current plate, all plates, or one plate by index, the way the toolbar's Slice button does, and wait for "
|
||||
"the result (or reply with a job id when it takes longer than the reply budget). Each requested plate reports ok "
|
||||
"(with print time and filament), error, cancelled, empty or skipped; the whole operation is superseded when "
|
||||
"someone else started a slice or edited the project while it ran. Other changes are refused until it finishes; "
|
||||
"cancel stops it.",
|
||||
object_schema({{"plates", {{"type", {"string", "integer"}}, {"description", "\"current\" (default), \"all\", or a plate index."}}},
|
||||
{"timeout_s", {{"type", "integer"}, {"minimum", 10}, {"maximum", 7200}, {"description", "Give up after this long (default 1800)."}}}}),
|
||||
[](const json& args, ToolContext& ctx) {
|
||||
ctx.begin_operation();
|
||||
const json plates_arg = args.value("plates", json("current"));
|
||||
auto ticket = std::make_shared<SliceTicket>();
|
||||
ctx.run_ui([&] {
|
||||
Plater& plater = ui_plater();
|
||||
if (plater.printer_technology() != ptFFF)
|
||||
throw ToolFailure("Slicing through MCP supports FFF printers only");
|
||||
PartPlateList& list = plater.get_partplate_list();
|
||||
bool all = false;
|
||||
if (plates_arg.is_string() && plates_arg.get<std::string>() == "all") {
|
||||
all = true;
|
||||
for (int i = 0; i < list.get_plate_count(); ++i)
|
||||
ticket->plates.push_back(i);
|
||||
} else if (plates_arg.is_number_integer()) {
|
||||
const int index = plates_arg.get<int>();
|
||||
if (index < 0 || index >= list.get_plate_count())
|
||||
throw ToolFailure("plate index out of range");
|
||||
if (index != list.get_curr_plate_index())
|
||||
plater.select_plate(index);
|
||||
ticket->plates.push_back(index);
|
||||
} else {
|
||||
ticket->plates.push_back(list.get_curr_plate_index());
|
||||
}
|
||||
ticket->state.run_seq_before = plater.slice_run_seq();
|
||||
ticket->state.revision_at_start = plater.project_revision();
|
||||
ticket->state.started = std::chrono::steady_clock::now();
|
||||
plater.request_slice(all);
|
||||
ticket->state.request_seq_mine = plater.slice_request_seq();
|
||||
ticket->state.seen_running = plater.is_slicing_any();
|
||||
return json();
|
||||
});
|
||||
const auto timeout = std::chrono::seconds(arg_int(args, "timeout_s", 1800));
|
||||
json result = poll_ui(
|
||||
ctx,
|
||||
[ticket]() -> json {
|
||||
Plater& plater = ui_plater();
|
||||
SliceObservation obs;
|
||||
obs.slicing_any = plater.is_slicing_any();
|
||||
obs.request_seq = plater.slice_request_seq();
|
||||
obs.current_revision = plater.project_revision();
|
||||
for (uint64_t seq = ticket->state.run_seq_before + 1; seq <= plater.slice_run_seq(); ++seq)
|
||||
if (auto run = plater.slice_run(seq))
|
||||
obs.runs_since_start.push_back(
|
||||
{run->seq, run->finished, run->cancelled, run->error, run->revision_at_finish, run->request_seq_at_finish});
|
||||
ticket->state.seen_running = ticket->state.seen_running || obs.slicing_any || !obs.runs_since_start.empty();
|
||||
const TicketStatus status = slice_status(ticket->state, obs, std::chrono::steady_clock::now());
|
||||
if (status == TicketStatus::Pending)
|
||||
return json();
|
||||
json out{{"status", status == TicketStatus::Done ? "done" : "superseded"}};
|
||||
std::string error;
|
||||
for (const SliceRunRecord& run : obs.runs_since_start)
|
||||
if (!run.error.empty())
|
||||
error = run.error;
|
||||
PartPlateList& list = plater.get_partplate_list();
|
||||
std::vector<PlateObservation> observed;
|
||||
for (int index : ticket->plates)
|
||||
if (PartPlate* plate = list.get_plate(index)) {
|
||||
const bool valid = plate->is_slice_result_valid();
|
||||
observed.push_back({index, valid, !valid && !error.empty(), !plate->has_printable_instances()});
|
||||
}
|
||||
const auto outcomes = classify_plates(ticket->plates, observed, slice_cancelled(ticket->state, obs));
|
||||
json plates = json::array();
|
||||
for (size_t i = 0; i < ticket->plates.size(); ++i) {
|
||||
json p{{"index", ticket->plates[i]}, {"outcome", to_string(outcomes[i])}};
|
||||
if (outcomes[i] == PlateOutcome::Ok)
|
||||
if (PartPlate* plate = list.get_plate(ticket->plates[i]))
|
||||
p.update(plate_stats(*plate));
|
||||
if (outcomes[i] == PlateOutcome::Error)
|
||||
p["error"] = error;
|
||||
plates.push_back(std::move(p));
|
||||
}
|
||||
out["plates"] = std::move(plates);
|
||||
json notes = json::array();
|
||||
for (const NotificationSummary& n : plater.get_notification_manager()->summaries())
|
||||
if (n.level == "warning" || n.level == "error")
|
||||
notes.push_back({{"level", n.level}, {"text", n.text}});
|
||||
if (!notes.empty())
|
||||
out["notifications"] = std::move(notes);
|
||||
return out;
|
||||
},
|
||||
timeout, "slicing to finish");
|
||||
return ToolResult::ok(result);
|
||||
});
|
||||
slice.budget_ms = 45000;
|
||||
reg.add(slice);
|
||||
|
||||
ToolDef cancel = mutate_tool(
|
||||
"cancel", "Cancel slicing",
|
||||
"Stop the running slice or G-code export, as the cancel button on the slicing progress does. The slice or export "
|
||||
"job then reports cancelled. Allowed while a slice or export holds the project.",
|
||||
object_schema({}),
|
||||
[](const json&, ToolContext& ctx) {
|
||||
json out = ctx.run_ui([] {
|
||||
Plater& plater = ui_plater();
|
||||
const bool running = plater.is_slicing_any();
|
||||
plater.cancel_slicing();
|
||||
return json{{"was_running", running}};
|
||||
});
|
||||
return ToolResult::ok(out);
|
||||
});
|
||||
cancel.allowed_during_operation = true;
|
||||
reg.add(cancel);
|
||||
}
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -0,0 +1,255 @@
|
||||
// screenshot and set_view: what the agent looks at, and pointing the view before looking.
|
||||
|
||||
#include "McpPaths.hpp"
|
||||
#include "McpService.hpp"
|
||||
#include "McpTools.hpp"
|
||||
#include "ModalTracker.hpp"
|
||||
#include "ScreenCapture.hpp"
|
||||
#include "slic3r/GUI/GCodeViewer.hpp"
|
||||
#include "slic3r/GUI/GLCanvas3D.hpp"
|
||||
#include "slic3r/GUI/GUI.hpp"
|
||||
#include "slic3r/GUI/GUI_App.hpp"
|
||||
#include "slic3r/GUI/IMSlider.hpp"
|
||||
#include "slic3r/GUI/MainFrame.hpp"
|
||||
#include "slic3r/GUI/Plater.hpp"
|
||||
|
||||
#include <boost/beast/core/detail/base64.hpp>
|
||||
#include <boost/filesystem/operations.hpp>
|
||||
#include <boost/filesystem/path.hpp>
|
||||
|
||||
#include <wx/dialog.h>
|
||||
#include <wx/toplevel.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <ctime>
|
||||
#include <string>
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
using nlohmann::json;
|
||||
namespace fs = boost::filesystem;
|
||||
|
||||
namespace {
|
||||
|
||||
std::string base64(const std::string& bytes)
|
||||
{
|
||||
namespace b64 = boost::beast::detail::base64;
|
||||
std::string out(b64::encoded_size(bytes.size()), '\0');
|
||||
out.resize(b64::encode(out.data(), bytes.data(), bytes.size()));
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string timestamp_name()
|
||||
{
|
||||
const auto now = std::chrono::system_clock::now();
|
||||
const std::time_t t = std::chrono::system_clock::to_time_t(now);
|
||||
char buf[32];
|
||||
std::strftime(buf, sizeof(buf), "%Y%m%d-%H%M%S", std::localtime(&t));
|
||||
const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count() % 1000;
|
||||
return std::string("screenshot-") + buf + "-" + std::to_string(ms) + ".png";
|
||||
}
|
||||
|
||||
const char* tab_id(const std::string& name)
|
||||
{
|
||||
if (name == "home") return TAB_ID_HOME;
|
||||
if (name == "prepare") return TAB_ID_PREPARE;
|
||||
if (name == "preview") return TAB_ID_PREVIEW;
|
||||
if (name == "device" || name == "monitor") return TAB_ID_MONITOR;
|
||||
if (name == "multi_device") return TAB_ID_MULTI_DEVICE;
|
||||
if (name == "project") return TAB_ID_PROJECT;
|
||||
if (name == "calibration") return TAB_ID_CALIBRATION;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void register_view_tools(McpService& service)
|
||||
{
|
||||
ToolRegistry& reg = service.registry();
|
||||
|
||||
ToolDef screenshot = inspect_tool(
|
||||
"screenshot", "Take a screenshot",
|
||||
"Capture what OrcaSlicer shows and return it as an image, downscaled to max_dim on the long edge (default 1280), "
|
||||
"plus the full-size PNG written to save_path (or the session's output folder). target: \"window\" (the main "
|
||||
"window), \"canvas\" (the visible 3D view exactly as rendered: scene, toolpaths, toolbars, ImGui panels) or "
|
||||
"\"dialog\" (the topmost modal dialog). The result says when parts may differ from the screen (approximate). "
|
||||
"Point the view first with set_view.",
|
||||
object_schema({{"target", enum_prop({"window", "canvas", "dialog"}, "Default window.")},
|
||||
{"max_dim", {{"type", "integer"}, {"minimum", 256}, {"maximum", 2000}, {"description", "Long edge of the returned image."}}},
|
||||
{"save_path", prop("string", "Absolute .png path for the full-size image.")},
|
||||
{"overwrite", prop("boolean", "Replace an existing save_path.")},
|
||||
{"include_image", prop("boolean", "Return the image itself (default true); false returns only the path.")}}),
|
||||
[&service](const json& args, ToolContext& ctx) {
|
||||
const std::string target = arg_string(args, "target", "window");
|
||||
fs::path path;
|
||||
if (args.contains("save_path")) {
|
||||
std::string err;
|
||||
auto p = resolve_output_path(arg_string(args, "save_path"), arg_bool(args, "overwrite", false), err);
|
||||
if (!p)
|
||||
throw ToolFailure(err);
|
||||
path = *p;
|
||||
} else {
|
||||
path = service.output_dir() / timestamp_name();
|
||||
}
|
||||
const int max_dim = std::clamp(arg_int(args, "max_dim", 1280), 256, 2000);
|
||||
json info;
|
||||
wxImage full;
|
||||
ctx.run_ui([&] {
|
||||
std::string err;
|
||||
std::optional<Capture> cap;
|
||||
if (target == "canvas") {
|
||||
Plater& plater = ui_plater();
|
||||
GLCanvas3D* canvas = plater.get_current_canvas3D();
|
||||
if (canvas == nullptr)
|
||||
throw ToolFailure("No 3D view is shown; switch to Prepare or Preview (set_view tab)");
|
||||
cap = capture_canvas(*canvas, err);
|
||||
} else if (target == "dialog") {
|
||||
wxDialog* top = service.modals().top();
|
||||
if (top == nullptr)
|
||||
throw ToolFailure("No modal dialog is open");
|
||||
cap = capture_window(*top, err);
|
||||
} else {
|
||||
wxTopLevelWindow* frame = wxGetApp().mainframe;
|
||||
if (frame == nullptr)
|
||||
throw ToolFailure("The main window is not up yet");
|
||||
cap = capture_window(*frame, err);
|
||||
}
|
||||
if (!cap)
|
||||
throw ToolFailure(err);
|
||||
full = cap->image;
|
||||
info = {{"source", target}, {"width", full.GetWidth()}, {"height", full.GetHeight()}};
|
||||
if (cap->approximate)
|
||||
info["approximate"] = true;
|
||||
if (!cap->note.empty())
|
||||
info["note"] = cap->note;
|
||||
return json();
|
||||
});
|
||||
// Encoding and scaling run off the UI thread.
|
||||
if (!full.SaveFile(wxString::FromUTF8(path.string()), wxBITMAP_TYPE_PNG))
|
||||
throw ToolFailure("Could not write " + path.string());
|
||||
info["path"] = path.string();
|
||||
ToolResult out = ToolResult::ok(info);
|
||||
if (arg_bool(args, "include_image", true)) {
|
||||
const wxSize size = fit_within(full.GetSize(), max_dim);
|
||||
const wxImage small = size == full.GetSize() ? full : full.Scale(size.x, size.y, wxIMAGE_QUALITY_HIGH);
|
||||
out.data["image_width"] = size.x;
|
||||
out.data["image_height"] = size.y;
|
||||
out.content.push_back({{"type", "image"}, {"mimeType", "image/png"}, {"data", base64(encode_png(small))}});
|
||||
}
|
||||
return out;
|
||||
});
|
||||
screenshot.journal = true; // a replay takes the same screenshots
|
||||
reg.add(screenshot);
|
||||
|
||||
std::vector<std::string> view_types;
|
||||
for (int i = 0; i < int(libvgcode::EViewType::COUNT); ++i)
|
||||
view_types.push_back(GCodeViewer::view_type_to_config_name(libvgcode::EViewType(i)));
|
||||
|
||||
reg.add(mutate_tool(
|
||||
"set_view", "Point the view",
|
||||
"Set up what the window shows, for screenshots and GUI work: the main tab, the 3D camera (a named direction, the "
|
||||
"default view, or fit to bed / objects / selection), the preview's layer or layer range (1-based) and color "
|
||||
"scheme, and the window size. Only the given fields change.",
|
||||
object_schema({{"tab", enum_prop({"home", "prepare", "preview", "device", "multi_device", "project", "calibration"}, "Main window tab.")},
|
||||
{"camera", enum_prop({"iso", "top", "bottom", "front", "rear", "left", "right", "default", "fit_bed", "fit_objects", "fit_selection"},
|
||||
"Camera direction or fit.")},
|
||||
{"layer", {{"type", "integer"}, {"minimum", 1}, {"description", "Preview: show layers up to this one (1-based)."}}},
|
||||
{"layer_range", array_prop({{"type", "integer"}}, "Preview: [first, last] layers, 1-based.")},
|
||||
{"view_type", enum_prop(view_types, "Preview color scheme.")},
|
||||
{"window_size", array_prop({{"type", "integer"}}, "[width, height] of the main window in pixels.")}}),
|
||||
[](const json& args, ToolContext& ctx) {
|
||||
json out = ctx.run_ui([&]() -> json {
|
||||
Plater& plater = ui_plater();
|
||||
MainFrame* frame = wxGetApp().mainframe;
|
||||
json done = json::object();
|
||||
if (args.contains("window_size")) {
|
||||
const json& s = args["window_size"];
|
||||
if (!s.is_array() || s.size() != 2)
|
||||
throw ToolFailure("window_size must be [width, height]");
|
||||
if (frame->IsMaximized())
|
||||
frame->Maximize(false);
|
||||
frame->SetSize(wxSize(s[0].get<int>(), s[1].get<int>()));
|
||||
done["window_size"] = {frame->GetSize().x, frame->GetSize().y};
|
||||
}
|
||||
if (args.contains("tab")) {
|
||||
const char* id = tab_id(arg_string(args, "tab"));
|
||||
if (id == nullptr)
|
||||
throw ToolFailure("Unknown tab");
|
||||
frame->select_tab(wxString(id));
|
||||
done["tab"] = arg_string(args, "tab");
|
||||
}
|
||||
const bool preview_args = args.contains("layer") || args.contains("layer_range") || args.contains("view_type");
|
||||
if (preview_args && !args.contains("tab")) {
|
||||
plater.select_view_3D("Preview", false);
|
||||
frame->select_tab(wxString(TAB_ID_PREVIEW));
|
||||
}
|
||||
if (args.contains("camera")) {
|
||||
const std::string cam = arg_string(args, "camera");
|
||||
GLCanvas3D* canvas = plater.get_current_canvas3D();
|
||||
if (cam == "default") {
|
||||
plater.select_view("plate");
|
||||
if (canvas)
|
||||
canvas->zoom_to_bed();
|
||||
} else if (cam == "fit_bed") {
|
||||
if (canvas)
|
||||
canvas->zoom_to_bed();
|
||||
} else if (cam == "fit_objects") {
|
||||
if (canvas)
|
||||
canvas->zoom_to_volumes();
|
||||
} else if (cam == "fit_selection") {
|
||||
if (canvas)
|
||||
canvas->zoom_to_selection();
|
||||
} else {
|
||||
plater.select_view(cam);
|
||||
}
|
||||
done["camera"] = cam;
|
||||
}
|
||||
if (preview_args) {
|
||||
GLCanvas3D* canvas = plater.get_preview_canvas3D();
|
||||
if (canvas == nullptr)
|
||||
throw ToolFailure("The preview is not available");
|
||||
GCodeViewer& viewer = canvas->get_gcode_viewer();
|
||||
if (args.contains("view_type")) {
|
||||
libvgcode::EViewType type;
|
||||
if (!GCodeViewer::view_type_from_config_name(arg_string(args, "view_type"), type))
|
||||
throw ToolFailure("Unknown view_type");
|
||||
viewer.select_view_type(type);
|
||||
done["view_type"] = arg_string(args, "view_type");
|
||||
}
|
||||
if (args.contains("layer") || args.contains("layer_range")) {
|
||||
IMSlider* layers = viewer.get_layers_slider();
|
||||
if (layers == nullptr || layers->GetMaxValue() <= 0)
|
||||
throw ToolFailure("The preview has no layers; slice first");
|
||||
const int max = layers->GetMaxValue();
|
||||
int lo = 0, hi = max;
|
||||
if (args.contains("layer"))
|
||||
hi = std::clamp(args["layer"].get<int>() - 1, 0, max);
|
||||
if (args.contains("layer_range")) {
|
||||
const json& r = args["layer_range"];
|
||||
if (!r.is_array() || r.size() != 2)
|
||||
throw ToolFailure("layer_range must be [first, last]");
|
||||
lo = std::clamp(r[0].get<int>() - 1, 0, max);
|
||||
hi = std::clamp(r[1].get<int>() - 1, lo, max);
|
||||
}
|
||||
layers->SetHigherValue(hi);
|
||||
layers->SetLowerValue(lo);
|
||||
layers->set_as_dirty();
|
||||
if (IMSlider* moves = viewer.get_moves_slider()) {
|
||||
moves->SetHigherValue(moves->GetMaxValue());
|
||||
moves->set_as_dirty();
|
||||
}
|
||||
done["layers"] = {lo + 1, hi + 1, max + 1};
|
||||
}
|
||||
canvas->set_as_dirty();
|
||||
}
|
||||
if (GLCanvas3D* canvas = plater.get_current_canvas3D())
|
||||
canvas->set_as_dirty();
|
||||
return done;
|
||||
});
|
||||
settle(ctx);
|
||||
return ToolResult::ok(out);
|
||||
}));
|
||||
}
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -74,6 +74,9 @@ public:
|
||||
virtual std::set<std::string> lineage() const = 0;
|
||||
// Replaces the arguments the session journal records for this call (refs become locators).
|
||||
virtual void set_journal_args(nlohmann::json args) = 0;
|
||||
// Marks this job as a slice/export operation: until it finishes, other mutate calls are refused
|
||||
// so nothing changes the project under it. No-op for inline calls.
|
||||
virtual void begin_operation() = 0;
|
||||
};
|
||||
|
||||
using ToolHandler = std::function<ToolResult(const nlohmann::json& args, ToolContext& ctx)>;
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
#include "ModalTracker.hpp"
|
||||
|
||||
#include "McpTypes.hpp"
|
||||
#include "slic3r/GUI/GUI.hpp"
|
||||
#include "slic3r/GUI/Widgets/Button.hpp"
|
||||
|
||||
#include <wx/button.h>
|
||||
#include <wx/dialog.h>
|
||||
#include <wx/dirdlg.h>
|
||||
#include <wx/filedlg.h>
|
||||
#include <wx/html/htmlwin.h>
|
||||
#include <wx/msgdlg.h>
|
||||
#include <wx/stattext.h>
|
||||
#include <wx/textctrl.h>
|
||||
#include <wx/window.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cstdlib>
|
||||
#include <exception>
|
||||
#include <typeinfo>
|
||||
#include <utility>
|
||||
|
||||
#if defined(__GNUC__) || defined(__clang__)
|
||||
#include <cxxabi.h>
|
||||
#endif
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
using nlohmann::json;
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr std::size_t kMaxMessage = 2000;
|
||||
|
||||
std::string lower(std::string s)
|
||||
{
|
||||
std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return char(std::tolower(c)); });
|
||||
return s;
|
||||
}
|
||||
|
||||
// "&Yes" -> "yes": mnemonics and case don't matter when matching a label.
|
||||
std::string normalize_label(const wxString& label)
|
||||
{
|
||||
wxString l = wxStripMenuCodes(label);
|
||||
l.Trim().Trim(false);
|
||||
return lower(into_u8(l));
|
||||
}
|
||||
|
||||
void collect(wxWindow* w, std::string& message, json& buttons)
|
||||
{
|
||||
for (wxWindow* child : w->GetChildren()) {
|
||||
if (!child->IsShown())
|
||||
continue;
|
||||
if (auto* html = dynamic_cast<wxHtmlWindow*>(child)) {
|
||||
message += into_u8(html->ToText()) + "\n";
|
||||
continue;
|
||||
}
|
||||
if (dynamic_cast<wxButton*>(child) != nullptr || dynamic_cast<::Button*>(child) != nullptr) {
|
||||
const wxString label = wxStripMenuCodes(child->GetLabel());
|
||||
if (!label.empty())
|
||||
buttons.push_back({{"id", child->GetId()}, {"label", into_u8(label)}});
|
||||
continue;
|
||||
}
|
||||
if (auto* text = dynamic_cast<wxStaticText*>(child)) {
|
||||
const wxString t = text->GetLabel();
|
||||
if (!t.empty())
|
||||
message += into_u8(t) + "\n";
|
||||
}
|
||||
collect(child, message, buttons);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string class_name(const wxWindow* window)
|
||||
{
|
||||
if (window == nullptr)
|
||||
return {};
|
||||
const char* raw = typeid(*window).name();
|
||||
#if defined(__GNUC__) || defined(__clang__)
|
||||
int status = 0;
|
||||
char* demangled = abi::__cxa_demangle(raw, nullptr, nullptr, &status);
|
||||
std::string out = status == 0 && demangled != nullptr ? demangled : raw;
|
||||
std::free(demangled);
|
||||
return out;
|
||||
#else
|
||||
std::string out = raw;
|
||||
for (const char* prefix : {"class ", "struct "})
|
||||
if (out.rfind(prefix, 0) == 0)
|
||||
out.erase(0, std::char_traits<char>::length(prefix));
|
||||
return out;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool is_native_dialog(wxDialog* dialog)
|
||||
{
|
||||
return dynamic_cast<wxMessageDialogBase*>(dialog) != nullptr || dynamic_cast<wxFileDialogBase*>(dialog) != nullptr ||
|
||||
dynamic_cast<wxDirDialogBase*>(dialog) != nullptr;
|
||||
}
|
||||
|
||||
json describe_dialog(wxDialog* dialog)
|
||||
{
|
||||
json out{{"title", into_u8(dialog->GetTitle())}, {"class", class_name(dialog)}, {"native", is_native_dialog(dialog)}};
|
||||
std::string message;
|
||||
json buttons = json::array();
|
||||
if (auto* md = dynamic_cast<wxMessageDialogBase*>(dialog)) {
|
||||
message = into_u8(md->GetMessage());
|
||||
if (!md->GetExtendedMessage().empty())
|
||||
message += "\n" + into_u8(md->GetExtendedMessage());
|
||||
} else if (auto* fd = dynamic_cast<wxFileDialogBase*>(dialog)) {
|
||||
message = into_u8(fd->GetMessage());
|
||||
} else {
|
||||
collect(dialog, message, buttons);
|
||||
}
|
||||
if (message.size() > kMaxMessage)
|
||||
message = message.substr(0, kMaxMessage) + "...";
|
||||
while (!message.empty() && (message.back() == '\n' || message.back() == ' '))
|
||||
message.pop_back();
|
||||
out["message"] = message;
|
||||
out["buttons"] = std::move(buttons);
|
||||
return out;
|
||||
}
|
||||
|
||||
int resolve_dialog_button(wxDialog* dialog, const std::string& button)
|
||||
{
|
||||
const std::string name = lower(button);
|
||||
static const std::pair<const char*, int> standard[] = {{"yes", wxID_YES}, {"no", wxID_NO}, {"ok", wxID_OK},
|
||||
{"cancel", wxID_CANCEL}, {"close", wxID_CLOSE}, {"apply", wxID_APPLY}};
|
||||
// A button whose label matches wins, so "Don't save" or "Keep" reach the dialog's own ids.
|
||||
if (dialog != nullptr && !is_native_dialog(dialog)) {
|
||||
std::string message;
|
||||
json buttons = json::array();
|
||||
collect(dialog, message, buttons);
|
||||
for (const json& b : buttons)
|
||||
if (normalize_label(from_u8(b["label"].get<std::string>())) == name)
|
||||
return b["id"].get<int>();
|
||||
}
|
||||
for (const auto& [key, id] : standard)
|
||||
if (name == key)
|
||||
return id;
|
||||
if (!name.empty() && std::all_of(name.begin(), name.end(), [](unsigned char c) { return std::isdigit(c) || c == '-'; }))
|
||||
return std::atoi(name.c_str());
|
||||
return wxID_NONE;
|
||||
}
|
||||
|
||||
AutoAnswerRule make_rule(const std::string& pattern, const std::string& button)
|
||||
{
|
||||
AutoAnswerRule rule;
|
||||
rule.pattern = pattern;
|
||||
rule.button = button;
|
||||
try {
|
||||
rule.compiled = std::regex(pattern, std::regex::ECMAScript | std::regex::icase);
|
||||
} catch (const std::regex_error& e) {
|
||||
throw ToolFailure("Invalid pattern \"" + pattern + "\": " + e.what());
|
||||
}
|
||||
return rule;
|
||||
}
|
||||
|
||||
ModalTracker::ModalTracker() { Register(); }
|
||||
|
||||
ModalTracker::~ModalTracker() { Unregister(); }
|
||||
|
||||
int ModalTracker::push_rules(std::vector<AutoAnswerRule> rules)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
const int layer = m_next_layer++;
|
||||
m_layers.emplace_back(layer, std::move(rules));
|
||||
return layer;
|
||||
}
|
||||
|
||||
void ModalTracker::pop_rules(int layer)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
m_layers.erase(std::remove_if(m_layers.begin(), m_layers.end(), [layer](const auto& l) { return l.first == layer; }), m_layers.end());
|
||||
}
|
||||
|
||||
json ModalTracker::rules_json() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
json out = json::array();
|
||||
for (const auto& [layer, rules] : m_layers)
|
||||
for (const AutoAnswerRule& r : rules)
|
||||
out.push_back({{"layer", layer}, {"match", r.pattern}, {"button", r.button}, {"uses", r.uses}});
|
||||
return out;
|
||||
}
|
||||
|
||||
json ModalTracker::snapshot() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
return m_snapshot;
|
||||
}
|
||||
|
||||
bool ModalTracker::any_open() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
return !m_snapshot.empty();
|
||||
}
|
||||
|
||||
void ModalTracker::publish()
|
||||
{
|
||||
json snap = json::array();
|
||||
for (wxDialog* d : m_stack)
|
||||
snap.push_back(describe_dialog(d));
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
m_snapshot = std::move(snap);
|
||||
}
|
||||
|
||||
int ModalTracker::Enter(wxDialog* dialog)
|
||||
{
|
||||
// An exception must never escape into ShowModal().
|
||||
try {
|
||||
const json info = describe_dialog(dialog);
|
||||
const std::string text = info["title"].get<std::string>() + "\n" + info["message"].get<std::string>();
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
for (auto layer = m_layers.rbegin(); layer != m_layers.rend(); ++layer)
|
||||
for (AutoAnswerRule& rule : layer->second)
|
||||
if (std::regex_search(text, rule.compiled)) {
|
||||
const int id = resolve_dialog_button(dialog, rule.button);
|
||||
if (id != wxID_NONE) {
|
||||
++rule.uses;
|
||||
return id; // ShowModal() returns it without showing the dialog
|
||||
}
|
||||
}
|
||||
}
|
||||
m_stack.push_back(dialog);
|
||||
publish();
|
||||
} catch (...) {
|
||||
}
|
||||
return wxID_NONE;
|
||||
}
|
||||
|
||||
void ModalTracker::Exit(wxDialog* dialog)
|
||||
{
|
||||
try {
|
||||
m_stack.erase(std::remove(m_stack.begin(), m_stack.end(), dialog), m_stack.end());
|
||||
publish();
|
||||
} catch (...) {
|
||||
}
|
||||
}
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -0,0 +1,82 @@
|
||||
#pragma once
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <wx/modalhook.h>
|
||||
|
||||
#include <mutex>
|
||||
#include <regex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
class wxDialog;
|
||||
class wxWindow;
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
// A pre-registered answer for modal dialogs whose title or message matches `pattern`.
|
||||
struct AutoAnswerRule
|
||||
{
|
||||
std::string pattern; // ECMAScript regex, case-insensitive, searched in "title\nmessage"
|
||||
std::string button; // yes|no|ok|cancel|close|apply|<button label>|<numeric id>
|
||||
std::regex compiled;
|
||||
int uses = 0; // how often it answered a dialog
|
||||
};
|
||||
|
||||
// Builds a rule, compiling its pattern. Throws ToolFailure on an invalid pattern.
|
||||
AutoAnswerRule make_rule(const std::string& pattern, const std::string& button);
|
||||
|
||||
// Every modal dialog shown through ShowModal - Orca's own, wxMessageDialog and the native file
|
||||
// dialogs alike - passes through this hook. It keeps the stack of open modals for the guards and
|
||||
// the tools, answers dialogs that match a registered rule without showing them, and publishes a
|
||||
// description snapshot that other threads may read.
|
||||
class ModalTracker final : public wxModalDialogHook
|
||||
{
|
||||
public:
|
||||
ModalTracker();
|
||||
~ModalTracker() override;
|
||||
|
||||
// UI thread only.
|
||||
const std::vector<wxDialog*>& stack() const { return m_stack; }
|
||||
wxDialog* top() const { return m_stack.empty() ? nullptr : m_stack.back(); }
|
||||
|
||||
// Rule sets are layered so a script can add its own and drop exactly those when it ends.
|
||||
// Returns the layer id to pass to pop_rules(). Any thread.
|
||||
int push_rules(std::vector<AutoAnswerRule> rules);
|
||||
void pop_rules(int layer);
|
||||
nlohmann::json rules_json() const;
|
||||
|
||||
// [{title, message, class, native, buttons:[{id,label}]}] of the open modals, outermost first.
|
||||
// Any thread.
|
||||
nlohmann::json snapshot() const;
|
||||
bool any_open() const;
|
||||
|
||||
protected:
|
||||
int Enter(wxDialog* dialog) override;
|
||||
void Exit(wxDialog* dialog) override;
|
||||
|
||||
private:
|
||||
void publish();
|
||||
|
||||
std::vector<wxDialog*> m_stack;
|
||||
|
||||
mutable std::mutex m_mutex;
|
||||
nlohmann::json m_snapshot = nlohmann::json::array();
|
||||
std::vector<std::pair<int, std::vector<AutoAnswerRule>>> m_layers;
|
||||
int m_next_layer = 1;
|
||||
};
|
||||
|
||||
// {title, message, class, native, buttons:[{id,label}]} for a dialog. UI thread only.
|
||||
nlohmann::json describe_dialog(wxDialog* dialog);
|
||||
|
||||
// True for dialogs implemented by the OS (wxMessageDialog, file and directory pickers): they have
|
||||
// no wx children to inspect or click and can only be pre-answered.
|
||||
bool is_native_dialog(wxDialog* dialog);
|
||||
|
||||
// The id a button name or label stands for in `dialog`, or wxID_NONE. UI thread only.
|
||||
int resolve_dialog_button(wxDialog* dialog, const std::string& button);
|
||||
|
||||
// Demangled C++ class name of a window, e.g. "Slic3r::GUI::MessageDialog".
|
||||
std::string class_name(const wxWindow* window);
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -0,0 +1,210 @@
|
||||
#include "ScreenCapture.hpp"
|
||||
|
||||
#include "slic3r/GUI/GLCanvas3D.hpp"
|
||||
#include "slic3r/GUI/GUI_App.hpp"
|
||||
#include "slic3r/GUI/Plater.hpp"
|
||||
|
||||
#include <wx/glcanvas.h>
|
||||
#include <wx/mstream.h>
|
||||
#include <wx/toplevel.h>
|
||||
#include <wx/window.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#if defined(__WXGTK__)
|
||||
#include <gtk/gtk.h>
|
||||
#ifdef wxHAVE_GDK_X11
|
||||
#include <X11/Xlib.h>
|
||||
#include <X11/Xutil.h>
|
||||
#include <gdk/gdkx.h>
|
||||
#endif
|
||||
#endif
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
wxSize fit_within(const wxSize& size, int max_dim)
|
||||
{
|
||||
if (size.x <= 0 || size.y <= 0 || max_dim <= 0 || std::max(size.x, size.y) <= max_dim)
|
||||
return size;
|
||||
const double scale = double(max_dim) / double(std::max(size.x, size.y));
|
||||
return {std::max(1, int(std::lround(size.x * scale))), std::max(1, int(std::lround(size.y * scale)))};
|
||||
}
|
||||
|
||||
void composite(wxImage& dst, const wxImage& src, const wxPoint& at)
|
||||
{
|
||||
if (!dst.IsOk() || !src.IsOk())
|
||||
return;
|
||||
const int x0 = std::max(0, at.x), y0 = std::max(0, at.y);
|
||||
const int x1 = std::min(dst.GetWidth(), at.x + src.GetWidth()), y1 = std::min(dst.GetHeight(), at.y + src.GetHeight());
|
||||
for (int y = y0; y < y1; ++y) {
|
||||
const unsigned char* s = src.GetData() + (size_t(y - at.y) * size_t(src.GetWidth()) + size_t(x0 - at.x)) * 3;
|
||||
unsigned char* d = dst.GetData() + (size_t(y) * size_t(dst.GetWidth()) + size_t(x0)) * 3;
|
||||
std::copy(s, s + size_t(std::max(0, x1 - x0)) * 3, d);
|
||||
}
|
||||
}
|
||||
|
||||
std::string encode_png(const wxImage& image)
|
||||
{
|
||||
wxMemoryOutputStream stream;
|
||||
if (!image.SaveFile(stream, wxBITMAP_TYPE_PNG))
|
||||
return {};
|
||||
std::string out(stream.GetLength(), '\0');
|
||||
stream.CopyTo(out.data(), out.size());
|
||||
return out;
|
||||
}
|
||||
|
||||
wxPoint client_offset_in(wxWindow& child, wxTopLevelWindow& top)
|
||||
{
|
||||
const wxPoint logical = child.ClientToScreen(wxPoint(0, 0)) - top.ClientToScreen(wxPoint(0, 0));
|
||||
#if defined(__WXMSW__)
|
||||
return logical; // wxMSW coordinates are already physical pixels
|
||||
#else
|
||||
const double scale = top.GetContentScaleFactor();
|
||||
return {int(std::lround(logical.x * scale)), int(std::lround(logical.y * scale))};
|
||||
#endif
|
||||
}
|
||||
|
||||
std::optional<Capture> capture_canvas(GLCanvas3D& canvas, std::string& err)
|
||||
{
|
||||
Capture c;
|
||||
if (!canvas.render_and_capture(c.image, err))
|
||||
return std::nullopt;
|
||||
return c;
|
||||
}
|
||||
|
||||
std::optional<Capture> capture_window(wxTopLevelWindow& window, std::string& err)
|
||||
{
|
||||
if (window.IsIconized() || !window.IsShownOnScreen()) {
|
||||
err = "The window is minimized or hidden";
|
||||
return std::nullopt;
|
||||
}
|
||||
Capture c;
|
||||
if (!capture_native_window(window, c.image, c.approximate, c.note, err))
|
||||
return std::nullopt;
|
||||
|
||||
// Composite every visible 3D canvas inside this window from an exact frame capture.
|
||||
Plater* plater = wxGetApp().plater();
|
||||
if (plater != nullptr)
|
||||
for (GLCanvas3D* canvas : {plater->get_view3D_canvas3D(), plater->get_preview_canvas3D(), plater->get_assmeble_canvas3D()}) {
|
||||
if (canvas == nullptr || canvas->get_wxglcanvas() == nullptr)
|
||||
continue;
|
||||
wxGLCanvas* glc = canvas->get_wxglcanvas();
|
||||
if (!glc->IsShownOnScreen() || wxGetTopLevelParent(glc) != &window)
|
||||
continue;
|
||||
std::string canvas_err;
|
||||
wxImage frame;
|
||||
if (!canvas->render_and_capture(frame, canvas_err)) {
|
||||
c.approximate = true;
|
||||
c.note += (c.note.empty() ? "" : "; ") + std::string("3D view not composited: ") + canvas_err;
|
||||
continue;
|
||||
}
|
||||
composite(c.image, frame, client_offset_in(*glc, window));
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
#if defined(__WXGTK__)
|
||||
|
||||
namespace {
|
||||
|
||||
// RGB of a cairo ARGB32 surface (premultiplied, native-endian 32-bit words).
|
||||
wxImage from_cairo(cairo_surface_t* surface)
|
||||
{
|
||||
cairo_surface_flush(surface);
|
||||
const int w = cairo_image_surface_get_width(surface), h = cairo_image_surface_get_height(surface);
|
||||
const int stride = cairo_image_surface_get_stride(surface);
|
||||
const unsigned char* data = cairo_image_surface_get_data(surface);
|
||||
wxImage img(w, h, false);
|
||||
unsigned char* rgb = img.GetData();
|
||||
for (int y = 0; y < h; ++y) {
|
||||
const uint32_t* row = reinterpret_cast<const uint32_t*>(data + size_t(y) * size_t(stride));
|
||||
for (int x = 0; x < w; ++x, rgb += 3) {
|
||||
const uint32_t p = row[x];
|
||||
rgb[0] = (p >> 16) & 0xFF;
|
||||
rgb[1] = (p >> 8) & 0xFF;
|
||||
rgb[2] = p & 0xFF;
|
||||
}
|
||||
}
|
||||
return img;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool capture_native_window(wxTopLevelWindow& window, wxImage& out, bool& approximate, std::string& note, std::string& err)
|
||||
{
|
||||
GtkWidget* widget = static_cast<GtkWidget*>(window.GetHandle());
|
||||
GdkWindow* gdkwin = widget != nullptr ? gtk_widget_get_window(widget) : nullptr;
|
||||
if (gdkwin == nullptr) {
|
||||
err = "The window has no native surface yet";
|
||||
return false;
|
||||
}
|
||||
#ifdef wxHAVE_GDK_X11
|
||||
if (GDK_IS_X11_DISPLAY(gdk_window_get_display(gdkwin))) {
|
||||
Display* dpy = GDK_DISPLAY_XDISPLAY(gdk_window_get_display(gdkwin));
|
||||
const Window xid = GDK_WINDOW_XID(gdkwin);
|
||||
XWindowAttributes attr;
|
||||
if (!XGetWindowAttributes(dpy, xid, &attr) || attr.map_state != IsViewable) {
|
||||
err = "The window is not viewable";
|
||||
return false;
|
||||
}
|
||||
// Only regions on the screen are defined without backing store.
|
||||
int rx = 0, ry = 0;
|
||||
Window child;
|
||||
XTranslateCoordinates(dpy, xid, attr.root, 0, 0, &rx, &ry, &child);
|
||||
XWindowAttributes root;
|
||||
XGetWindowAttributes(dpy, attr.root, &root);
|
||||
if (rx < 0 || ry < 0 || rx + attr.width > root.width || ry + attr.height > root.height) {
|
||||
approximate = true;
|
||||
note = "part of the window is off-screen";
|
||||
}
|
||||
XImage* img = XGetImage(dpy, xid, 0, 0, unsigned(attr.width), unsigned(attr.height), AllPlanes, ZPixmap);
|
||||
if (img == nullptr) {
|
||||
err = "XGetImage failed";
|
||||
return false;
|
||||
}
|
||||
out.Create(attr.width, attr.height, false);
|
||||
unsigned char* rgb = out.GetData();
|
||||
auto shift = [](unsigned long mask) {
|
||||
int s = 0;
|
||||
while (mask != 0 && (mask & 1) == 0) {
|
||||
mask >>= 1;
|
||||
++s;
|
||||
}
|
||||
return s;
|
||||
};
|
||||
const int rs = shift(img->red_mask), gs = shift(img->green_mask), bs = shift(img->blue_mask);
|
||||
for (int y = 0; y < attr.height; ++y)
|
||||
for (int x = 0; x < attr.width; ++x, rgb += 3) {
|
||||
const unsigned long p = XGetPixel(img, x, y);
|
||||
rgb[0] = (unsigned char) ((p & img->red_mask) >> rs);
|
||||
rgb[1] = (unsigned char) ((p & img->green_mask) >> gs);
|
||||
rgb[2] = (unsigned char) ((p & img->blue_mask) >> bs);
|
||||
}
|
||||
XDestroyImage(img);
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
// Wayland offers no way to read a window back; draw the widget tree into an image instead.
|
||||
// Widgets drawn by GTK come out right; web views may stay blank, and the 3D canvases are
|
||||
// composited by the caller.
|
||||
const int scale = gtk_widget_get_scale_factor(widget);
|
||||
const int w = gtk_widget_get_allocated_width(widget), h = gtk_widget_get_allocated_height(widget);
|
||||
cairo_surface_t* surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, w * scale, h * scale);
|
||||
cairo_surface_set_device_scale(surface, scale, scale);
|
||||
cairo_t* cr = cairo_create(surface);
|
||||
gtk_widget_draw(widget, cr);
|
||||
cairo_destroy(cr);
|
||||
out = from_cairo(surface);
|
||||
cairo_surface_destroy(surface);
|
||||
approximate = true;
|
||||
note = "drawn from the widget tree (Wayland); web views may be blank";
|
||||
return out.IsOk();
|
||||
}
|
||||
|
||||
#endif // __WXGTK__
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -0,0 +1,53 @@
|
||||
#pragma once
|
||||
|
||||
#include <wx/gdicmn.h>
|
||||
#include <wx/image.h>
|
||||
|
||||
#include <optional>
|
||||
#include <string>
|
||||
|
||||
class wxTopLevelWindow;
|
||||
class wxWindow;
|
||||
|
||||
namespace Slic3r { namespace GUI {
|
||||
|
||||
class GLCanvas3D;
|
||||
|
||||
namespace Mcp {
|
||||
|
||||
struct Capture
|
||||
{
|
||||
wxImage image;
|
||||
// Some regions may not show what is on screen (a web view under Wayland, a part of the window
|
||||
// off-screen, a canvas that was mid-frame); `note` says which.
|
||||
bool approximate = false;
|
||||
std::string note;
|
||||
};
|
||||
|
||||
// The canvas exactly as presented: scene, toolpaths, toolbars and ImGui overlays. All platforms.
|
||||
std::optional<Capture> capture_canvas(GLCanvas3D& canvas, std::string& err);
|
||||
|
||||
// A top-level window's own pixels (never other windows on the screen), with every visible 3D
|
||||
// canvas composited in from its canvas capture, since window capture APIs miss or mangle OpenGL
|
||||
// content on several platforms. Minimized windows fail.
|
||||
std::optional<Capture> capture_window(wxTopLevelWindow& window, std::string& err);
|
||||
|
||||
// The OS part of capture_window(): Windows PrintWindow, macOS cacheDisplayInRect, Linux X11
|
||||
// XGetImage or (Wayland) gtk_widget_draw. Implemented per platform.
|
||||
bool capture_native_window(wxTopLevelWindow& window, wxImage& out, bool& approximate, std::string& note, std::string& err);
|
||||
|
||||
// Physical-pixel offset of `child`'s client area inside `top`'s client area.
|
||||
wxPoint client_offset_in(wxWindow& child, wxTopLevelWindow& top);
|
||||
|
||||
// The largest size within `max_dim` on its long edge that keeps the aspect ratio; sizes already
|
||||
// small enough are unchanged.
|
||||
wxSize fit_within(const wxSize& size, int max_dim);
|
||||
|
||||
// Copies `src` into `dst` at `at`, clipped to `dst`.
|
||||
void composite(wxImage& dst, const wxImage& src, const wxPoint& at);
|
||||
|
||||
// PNG bytes of an image.
|
||||
std::string encode_png(const wxImage& image);
|
||||
|
||||
} // namespace Mcp
|
||||
}} // namespace Slic3r::GUI
|
||||
@@ -0,0 +1,53 @@
|
||||
// macOS window capture for automation screenshots (see ScreenCapture.hpp).
|
||||
|
||||
#include "ScreenCapture.hpp"
|
||||
|
||||
#include <wx/toplevel.h>
|
||||
|
||||
#include <string>
|
||||
|
||||
#import <AppKit/AppKit.h>
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
bool capture_native_window(wxTopLevelWindow& window, wxImage& out, bool& approximate, std::string& note, std::string& err)
|
||||
{
|
||||
NSView* view = (NSView*) window.GetHandle();
|
||||
if (view == nil) {
|
||||
err = "The window has no native view";
|
||||
return false;
|
||||
}
|
||||
// The content view draws itself into a bitmap, so this needs no screen-recording permission
|
||||
// and works for covered windows. Layer-backed OpenGL and web views don't draw this way; the 3D
|
||||
// canvases are composited from their own frames afterwards, web views may stay blank.
|
||||
NSRect bounds = [view bounds];
|
||||
NSBitmapImageRep* rep = [view bitmapImageRepForCachingDisplayInRect:bounds];
|
||||
if (rep == nil) {
|
||||
err = "Could not create a bitmap for the window";
|
||||
return false;
|
||||
}
|
||||
[view cacheDisplayInRect:bounds toBitmapImageRep:rep];
|
||||
|
||||
const NSInteger w = [rep pixelsWide], h = [rep pixelsHigh];
|
||||
const NSInteger spp = [rep samplesPerPixel], bpr = [rep bytesPerRow];
|
||||
const unsigned char* data = [rep bitmapData];
|
||||
if (data == nullptr || w <= 0 || h <= 0 || spp < 3 || [rep bitsPerSample] != 8) {
|
||||
err = "Unsupported window bitmap format";
|
||||
return false;
|
||||
}
|
||||
out.Create(int(w), int(h), false);
|
||||
unsigned char* rgb = out.GetData();
|
||||
for (NSInteger y = 0; y < h; ++y) {
|
||||
const unsigned char* row = data + y * bpr;
|
||||
for (NSInteger x = 0; x < w; ++x, rgb += 3) {
|
||||
rgb[0] = row[x * spp + 0];
|
||||
rgb[1] = row[x * spp + 1];
|
||||
rgb[2] = row[x * spp + 2];
|
||||
}
|
||||
}
|
||||
approximate = true;
|
||||
note = "drawn from the view hierarchy; web views may be blank";
|
||||
return true;
|
||||
}
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -0,0 +1,76 @@
|
||||
// Windows window capture for automation screenshots (see ScreenCapture.hpp).
|
||||
|
||||
#include "ScreenCapture.hpp"
|
||||
|
||||
#include <wx/toplevel.h>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#include <windows.h>
|
||||
|
||||
#ifndef PW_RENDERFULLCONTENT
|
||||
#define PW_RENDERFULLCONTENT 0x00000002
|
||||
#endif
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
bool capture_native_window(wxTopLevelWindow& window, wxImage& out, bool& approximate, std::string& note, std::string& err)
|
||||
{
|
||||
HWND hwnd = static_cast<HWND>(window.GetHWND());
|
||||
RECT rc{};
|
||||
if (hwnd == nullptr || !GetClientRect(hwnd, &rc)) {
|
||||
err = "The window has no native handle";
|
||||
return false;
|
||||
}
|
||||
const int w = rc.right - rc.left, h = rc.bottom - rc.top;
|
||||
if (w <= 0 || h <= 0) {
|
||||
err = "The window has no client area";
|
||||
return false;
|
||||
}
|
||||
HDC screen = GetDC(hwnd);
|
||||
HDC mem = CreateCompatibleDC(screen);
|
||||
HBITMAP bmp = CreateCompatibleBitmap(screen, w, h);
|
||||
HGDIOBJ old = SelectObject(mem, bmp);
|
||||
// PW_RENDERFULLCONTENT asks DWM for the composed content, which includes most hardware-drawn
|
||||
// children; the 3D canvases are composited from their own frames afterwards anyway.
|
||||
const BOOL printed = PrintWindow(hwnd, mem, PW_CLIENTONLY | PW_RENDERFULLCONTENT);
|
||||
if (!printed) {
|
||||
approximate = true;
|
||||
note = "PrintWindow failed; copied from the screen";
|
||||
BitBlt(mem, 0, 0, w, h, screen, 0, 0, SRCCOPY);
|
||||
}
|
||||
SelectObject(mem, old);
|
||||
|
||||
BITMAPINFO bi{};
|
||||
bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
|
||||
bi.bmiHeader.biWidth = w;
|
||||
bi.bmiHeader.biHeight = -h; // top-down rows
|
||||
bi.bmiHeader.biPlanes = 1;
|
||||
bi.bmiHeader.biBitCount = 32;
|
||||
bi.bmiHeader.biCompression = BI_RGB;
|
||||
std::vector<unsigned char> bgra(size_t(w) * size_t(h) * 4);
|
||||
const int lines = GetDIBits(mem, bmp, 0, UINT(h), bgra.data(), &bi, DIB_RGB_COLORS);
|
||||
|
||||
DeleteObject(bmp);
|
||||
DeleteDC(mem);
|
||||
ReleaseDC(hwnd, screen);
|
||||
if (lines != h) {
|
||||
err = "Reading the window bitmap failed";
|
||||
return false;
|
||||
}
|
||||
|
||||
out.Create(w, h, false);
|
||||
unsigned char* rgb = out.GetData();
|
||||
for (size_t i = 0; i < size_t(w) * size_t(h); ++i, rgb += 3) {
|
||||
rgb[0] = bgra[i * 4 + 2];
|
||||
rgb[1] = bgra[i * 4 + 1];
|
||||
rgb[2] = bgra[i * 4 + 0];
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -20,8 +20,11 @@
|
||||
#include "PlateSettingsDialog.hpp"
|
||||
#include "SceneBenchmark.hpp"
|
||||
#include "DeviceCore/DevManager.h"
|
||||
#include "Mcp/McpPaths.hpp"
|
||||
|
||||
#include "libslic3r/Config.hpp"
|
||||
#include <boost/filesystem/operations.hpp>
|
||||
#include <boost/filesystem/path.hpp>
|
||||
#include <functional>
|
||||
#include <initializer_list>
|
||||
#include <libslic3r/Model.hpp>
|
||||
@@ -111,6 +114,28 @@ void go_to_layer(Plater* plater, const std::string& param)
|
||||
}
|
||||
}
|
||||
|
||||
// The path a command was given, checked for reading (`output` false) or writing. nullopt with an
|
||||
// Error in `fail` when the parameter is unusable.
|
||||
std::optional<boost::filesystem::path> path_param(const std::string& param, bool output, AppActionRunResult& fail)
|
||||
{
|
||||
std::string err;
|
||||
auto pp = Mcp::parse_path_param(param, err);
|
||||
std::optional<boost::filesystem::path> path;
|
||||
if (pp)
|
||||
path = output ? Mcp::resolve_output_path(pp->path, pp->overwrite, err) : Mcp::resolve_input_path(pp->path, err);
|
||||
if (!path)
|
||||
fail = {AppActionRunResult::Level::Error, from_u8(err)};
|
||||
return path;
|
||||
}
|
||||
|
||||
AppActionRunResult written(const boost::filesystem::path& path)
|
||||
{
|
||||
boost::system::error_code ec;
|
||||
if (boost::filesystem::exists(path, ec))
|
||||
return {AppActionRunResult::Level::Success, from_u8(path.string())};
|
||||
return {AppActionRunResult::Level::Error, _L("The file was not written.")};
|
||||
}
|
||||
|
||||
// Select a named camera view. Plater::select_view dispatches to the current panel.
|
||||
AppActionRunResult view_command(Plater* plater, const std::string& dir)
|
||||
{
|
||||
@@ -153,9 +178,117 @@ struct CommandAction : AppAction
|
||||
this->group_en = c.group;
|
||||
this->input = c.input;
|
||||
this->icon = c.icon;
|
||||
this->automation_description = c.description;
|
||||
this->param_type = NativeCommands::param_type_name(c.param.type);
|
||||
this->param_help = c.param.help;
|
||||
this->completes_in_background = c.completion == CommandCompletion::Export;
|
||||
}
|
||||
};
|
||||
|
||||
// What automation needs to call each command: a description for agents (English, never shown in the
|
||||
// palette), the meaning of `param`, and whether the effect finishes after run() returns. Commands
|
||||
// without an entry run immediately and ignore `param`.
|
||||
void describe_commands(std::vector<NativeCommand>& commands)
|
||||
{
|
||||
struct Detail
|
||||
{
|
||||
const char* key;
|
||||
const char* description;
|
||||
CommandParamType param = CommandParamType::None;
|
||||
const char* param_help = "";
|
||||
CommandCompletion completion = CommandCompletion::None;
|
||||
};
|
||||
static const Detail details[] = {
|
||||
{"slice_and_preview", "Slice the current plate and show the Preview tab. Returns at once; use the slice tool to wait for the result."},
|
||||
{"slice_all", "Slice every plate and show the Preview tab. Returns at once; use the slice tool to wait for results."},
|
||||
{"go_to_layer", "Show the Preview tab at a layer chosen as a percentage of the layer range.", CommandParamType::Percent, "0-100"},
|
||||
{"go_to_tab", "Switch to a main window tab.", CommandParamType::Tab, "tab id: home, prepare, preview, monitor, project, calibration, or a plugin page id"},
|
||||
{"load_project", "Open a project. With a path, opens that file without a dialog (asks first if the current project has unsaved changes).", CommandParamType::Path, "absolute path of a .3mf project"},
|
||||
{"save_project", "Save the project to its current file (asks for a name if it has none)."},
|
||||
{"save_project_as", "Save the project as a .3mf file. With a path, saves there without a dialog.", CommandParamType::Path, "absolute output path, or {\"path\": ..., \"overwrite\": true}"},
|
||||
{"new_project", "Start a new, empty project (asks first if the current one has unsaved changes)."},
|
||||
{"undo", "Undo the last change to the project."},
|
||||
{"redo", "Redo the last undone change."},
|
||||
{"open_preferences", "Open the Preferences dialog."},
|
||||
{"mode_simple", "Switch the settings view to Simple mode."},
|
||||
{"mode_advanced", "Switch the settings view to Advanced mode."},
|
||||
{"mode_expert", "Switch the settings view to Expert mode."},
|
||||
{"toggle_developer_mode", "Turn Developer mode on or off."},
|
||||
{"export_gcode", "Export the current plate's G-code. With a path, exports there without a dialog once the plate is sliced; the export runs in the background.", CommandParamType::Path, "absolute .gcode path, or {\"path\": ..., \"overwrite\": true}", CommandCompletion::Export},
|
||||
{"export_stl", "Export all objects as one STL. With a path, writes there without a dialog.", CommandParamType::Path, "absolute .stl path, or {\"path\": ..., \"overwrite\": true}"},
|
||||
{"export_3mf", "Export the model as a .3mf without slicing data. With a path, writes there without a dialog.", CommandParamType::Path, "absolute .3mf path, or {\"path\": ..., \"overwrite\": true}"},
|
||||
{"export_sliced_file", "Export the current plate's sliced file (.gcode.3mf). With a path, writes there without a dialog.", CommandParamType::Path, "absolute .3mf path, or {\"path\": ..., \"overwrite\": true}"},
|
||||
{"export_all_sliced_file", "Export every plate's sliced file into one .gcode.3mf. With a path, writes there without a dialog.", CommandParamType::Path, "absolute .3mf path, or {\"path\": ..., \"overwrite\": true}"},
|
||||
{"export_stl_multi", "Export each object as its own STL. With a directory, writes there without a dialog.", CommandParamType::Path, "absolute path of an existing directory"},
|
||||
{"export_drc_single", "Export all objects as one Draco (.drc) file."},
|
||||
{"export_drc_multi", "Export each object as its own Draco (.drc) file."},
|
||||
{"export_toolpaths_obj", "Export the sliced toolpaths as an OBJ."},
|
||||
{"export_config", "Export presets as a bundle (opens a dialog to choose them)."},
|
||||
{"import_file", "Import models (3MF/STL/STEP/SVG/OBJ/AMF). With a path, imports that file without a dialog.", CommandParamType::Path, "absolute path of a model file"},
|
||||
{"import_zip_archive", "Import models from a ZIP archive (opens a file dialog)."},
|
||||
{"import_configs", "Import configuration presets. With a path, loads that .ini/.json without a dialog.", CommandParamType::Path, "absolute path of a config file"},
|
||||
{"view_default", "Reset the 3D camera to the default view and fit the plate."},
|
||||
{"view_fit_bed", "Fit the build plate in the 3D view."},
|
||||
{"view_toggle_perspective", "Switch the 3D camera between perspective and orthographic."},
|
||||
{"reset_window_layout", "Restore the default window layout."},
|
||||
{"obj_delete", "Delete the selected objects or parts."},
|
||||
{"obj_delete_all", "Delete all objects."},
|
||||
{"select_all", "Select all objects in the 3D view."},
|
||||
{"deselect_all", "Clear the selection."},
|
||||
{"obj_mirror_x", "Mirror the selection along X."},
|
||||
{"obj_mirror_y", "Mirror the selection along Y."},
|
||||
{"obj_mirror_z", "Mirror the selection along Z."},
|
||||
{"obj_split_objects", "Split the selected object into separate objects."},
|
||||
{"obj_split_parts", "Split the selected object into parts."},
|
||||
{"obj_center", "Center the selection on its plate."},
|
||||
{"obj_drop", "Drop the selection onto the bed."},
|
||||
{"obj_fit_volume", "Scale the selection to fit the print volume."},
|
||||
{"obj_instances_up", "Add an instance of the selected object."},
|
||||
{"obj_instances_down", "Remove an instance of the selected object."},
|
||||
{"obj_arrange", "Arrange all objects on the plates (runs in the background)."},
|
||||
{"obj_orient", "Auto-orient the selection (runs in the background)."},
|
||||
{"plate_add", "Add a plate."},
|
||||
{"plate_duplicate", "Duplicate the current plate."},
|
||||
{"plate_delete", "Delete the current plate."},
|
||||
{"plate_rename", "Rename the current plate (opens a dialog)."},
|
||||
{"plate_toggle_lock", "Lock or unlock the current plate."},
|
||||
{"plate_goto", "Make a plate the current one.", CommandParamType::Index, "0-based plate index"},
|
||||
{"sync_ams", "Synchronize the filament list from the connected printer's AMS."},
|
||||
{"preset_bundle", "Open the preset bundle manager."},
|
||||
{"sync_presets", "Synchronize user presets with the cloud account."},
|
||||
{"help_keyboard_shortcuts", "Show the keyboard shortcuts dialog."},
|
||||
{"help_setup_wizard", "Open the setup wizard."},
|
||||
{"help_open_config_folder", "Open the configuration folder in the file manager."},
|
||||
{"help_migrate_filament_presets", "Migrate legacy user filament presets."},
|
||||
{"help_troubleshoot", "Open the troubleshooting center."},
|
||||
{"help_network_test", "Open the network test dialog."},
|
||||
{"help_benchmark_3d_scene", "Benchmark rendering of the current 3D scene."},
|
||||
{"help_tip_of_the_day", "Show a tip of the day."},
|
||||
{"help_check_updates", "Check for a newer OrcaSlicer."},
|
||||
{"help_about", "Show the About dialog."},
|
||||
{"open_wiki", "Open the OrcaSlicer wiki in the browser."},
|
||||
{"open_youtube", "Open the OrcaSlicer YouTube channel in the browser."},
|
||||
{"open_plugins", "Open the plugins dialog."},
|
||||
{"refresh_plugins", "Reload plugins."},
|
||||
{"install_plugin", "Open the plugin hub to install a plugin."},
|
||||
{"install_local_plugin", "Install a plugin from a local file (opens a file dialog)."},
|
||||
};
|
||||
for (NativeCommand& c : commands) {
|
||||
auto it = std::find_if(std::begin(details), std::end(details), [&](const Detail& d) { return c.key == d.key; });
|
||||
if (it != std::end(details)) {
|
||||
c.description = it->description;
|
||||
c.param = {it->param, it->param_help};
|
||||
c.completion = it->completion;
|
||||
} else if (c.key.rfind("calib_", 0) == 0) {
|
||||
c.description = "Open the " + c.title + " wizard.";
|
||||
} else if (c.key.rfind("view_", 0) == 0) {
|
||||
c.description = "Point the 3D camera: " + c.title + ".";
|
||||
} else if (c.key.rfind("add_primitive_", 0) == 0 || c.key.rfind("add_handy_", 0) == 0) {
|
||||
c.description = "Add a " + c.title + " object to the current plate.";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<NativeCommand> build_command_catalog()
|
||||
{
|
||||
std::vector<NativeCommand> out;
|
||||
@@ -172,16 +305,26 @@ std::vector<NativeCommand> build_command_catalog()
|
||||
};
|
||||
|
||||
// ---- Slice & Export ----
|
||||
// Slices through the toolbar's path, so it counts as a user slice request (Plater::request_slice).
|
||||
add_with_icon("slice_and_preview", L("Slice and Preview"), L("Slice & Export"), "media_play", [](const std::string&) {
|
||||
Plater* plater = wxGetApp().plater();
|
||||
if (plater) {
|
||||
plater->reslice();
|
||||
plater->request_slice(false);
|
||||
plater->select_view_3D("Preview", false);
|
||||
if (MainFrame* mf = wxGetApp().mainframe; mf)
|
||||
mf->select_tab(TAB_ID_PREVIEW);
|
||||
}
|
||||
return AppActionRunResult{AppActionRunResult::Level::Success};
|
||||
});
|
||||
add_with_icon("slice_all", L("Slice All Plates"), L("Slice & Export"), "media_play", [](const std::string&) {
|
||||
Plater* plater = wxGetApp().plater();
|
||||
if (plater) {
|
||||
plater->request_slice(true);
|
||||
if (MainFrame* mf = wxGetApp().mainframe; mf)
|
||||
mf->select_tab(TAB_ID_PREVIEW);
|
||||
}
|
||||
return AppActionRunResult{AppActionRunResult::Level::Success};
|
||||
});
|
||||
|
||||
add_with_icon(
|
||||
"go_to_layer", L("Go to layer (percent)"), L("Commands"), "height_range_layer",
|
||||
@@ -208,9 +351,19 @@ std::vector<NativeCommand> build_command_catalog()
|
||||
},
|
||||
"tab");
|
||||
|
||||
add_with_icon("load_project", L("Load Project"), L("Commands"), "menu_open", [](const std::string&) {
|
||||
if (Plater* plater = wxGetApp().plater())
|
||||
add_with_icon("load_project", L("Load Project"), L("Commands"), "menu_open", [](const std::string& param) {
|
||||
Plater* plater = wxGetApp().plater();
|
||||
if (plater == nullptr)
|
||||
return AppActionRunResult{};
|
||||
if (param.empty()) {
|
||||
plater->load_project();
|
||||
return AppActionRunResult{AppActionRunResult::Level::Success};
|
||||
}
|
||||
AppActionRunResult fail;
|
||||
const auto path = path_param(param, false, fail);
|
||||
if (!path)
|
||||
return fail;
|
||||
plater->load_project(from_path(*path));
|
||||
return AppActionRunResult{AppActionRunResult::Level::Success};
|
||||
});
|
||||
add_with_icon("save_project", L("Save Project"), L("Commands"), "menu_save", [](const std::string&) {
|
||||
@@ -218,9 +371,35 @@ std::vector<NativeCommand> build_command_catalog()
|
||||
plater->save_project(false);
|
||||
return AppActionRunResult{AppActionRunResult::Level::Success};
|
||||
});
|
||||
add_with_icon("save_project_as", L("Save Project As"), L("Commands"), "menu_save", [](const std::string&) {
|
||||
if (Plater* plater = wxGetApp().plater())
|
||||
add_with_icon("save_project_as", L("Save Project As"), L("Commands"), "menu_save", [](const std::string& param) {
|
||||
Plater* plater = wxGetApp().plater();
|
||||
if (plater == nullptr)
|
||||
return AppActionRunResult{};
|
||||
if (param.empty()) {
|
||||
plater->save_project(true);
|
||||
return AppActionRunResult{AppActionRunResult::Level::Success};
|
||||
}
|
||||
AppActionRunResult fail;
|
||||
const auto path = path_param(param, true, fail);
|
||||
if (!path)
|
||||
return fail;
|
||||
if (plater->save_project(true, from_path(*path)) != wxID_YES && !boost::filesystem::exists(*path))
|
||||
return AppActionRunResult{AppActionRunResult::Level::Error, _L("The project was not saved.")};
|
||||
return written(*path);
|
||||
});
|
||||
add_with_icon("new_project", L("New Project"), L("Commands"), "menu_open", [](const std::string&) {
|
||||
if (Plater* plater = wxGetApp().plater())
|
||||
plater->new_project();
|
||||
return AppActionRunResult{AppActionRunResult::Level::Success};
|
||||
});
|
||||
add_with_icon("undo", L("Undo"), L("Commands"), "menu_undo", [](const std::string&) {
|
||||
if (Plater* plater = wxGetApp().plater())
|
||||
plater->undo();
|
||||
return AppActionRunResult{AppActionRunResult::Level::Success};
|
||||
});
|
||||
add_with_icon("redo", L("Redo"), L("Commands"), "menu_redo", [](const std::string&) {
|
||||
if (Plater* plater = wxGetApp().plater())
|
||||
plater->redo();
|
||||
return AppActionRunResult{AppActionRunResult::Level::Success};
|
||||
});
|
||||
add_with_icon("open_preferences", L("Preferences"), L("Commands"), "cog", [](const std::string&) {
|
||||
@@ -252,31 +431,74 @@ std::vector<NativeCommand> build_command_catalog()
|
||||
});
|
||||
|
||||
// ---- Export pipeline ----
|
||||
add_with_icon("export_gcode", L("Export G-code"), L("Slice & Export"), "custom-gcode_gcode", [](const std::string&) {
|
||||
if (Plater* plater = wxGetApp().plater())
|
||||
add_with_icon("export_gcode", L("Export G-code"), L("Slice & Export"), "custom-gcode_gcode", [](const std::string& param) {
|
||||
Plater* plater = wxGetApp().plater();
|
||||
if (plater == nullptr)
|
||||
return AppActionRunResult{};
|
||||
if (param.empty()) {
|
||||
plater->export_gcode(false);
|
||||
return AppActionRunResult{AppActionRunResult::Level::Success};
|
||||
return AppActionRunResult{AppActionRunResult::Level::Success};
|
||||
}
|
||||
AppActionRunResult fail;
|
||||
const auto path = path_param(param, true, fail);
|
||||
if (!path)
|
||||
return fail;
|
||||
if (plater->is_slicing_any())
|
||||
return AppActionRunResult{AppActionRunResult::Level::Error, _L("Slicing is in progress. Wait for it to finish and export again.")};
|
||||
if (!plater->export_gcode_to(*path))
|
||||
return AppActionRunResult{AppActionRunResult::Level::Error, _L("The export could not start. Slice the plate first and check for slicing errors.")};
|
||||
return AppActionRunResult{AppActionRunResult::Level::Info, from_u8(path->string())};
|
||||
});
|
||||
add_with_icon("export_stl", L("Export STL"), L("Slice & Export"), "save", [](const std::string&) {
|
||||
if (Plater* plater = wxGetApp().plater())
|
||||
add_with_icon("export_stl", L("Export STL"), L("Slice & Export"), "save", [](const std::string& param) {
|
||||
Plater* plater = wxGetApp().plater();
|
||||
if (plater == nullptr)
|
||||
return AppActionRunResult{};
|
||||
if (param.empty()) {
|
||||
plater->export_stl();
|
||||
return AppActionRunResult{AppActionRunResult::Level::Success};
|
||||
return AppActionRunResult{AppActionRunResult::Level::Success};
|
||||
}
|
||||
AppActionRunResult fail;
|
||||
const auto path = path_param(param, true, fail);
|
||||
if (!path)
|
||||
return fail;
|
||||
plater->export_stl(false, false, false, FT_STL, from_path(*path));
|
||||
return written(*path);
|
||||
});
|
||||
add_with_icon("export_3mf", L("Export 3MF"), L("Slice & Export"), "menu_save", [](const std::string&) {
|
||||
if (Plater* plater = wxGetApp().plater())
|
||||
add_with_icon("export_3mf", L("Export 3MF"), L("Slice & Export"), "menu_save", [](const std::string& param) {
|
||||
Plater* plater = wxGetApp().plater();
|
||||
if (plater == nullptr)
|
||||
return AppActionRunResult{};
|
||||
if (param.empty()) {
|
||||
plater->export_core_3mf();
|
||||
return AppActionRunResult{AppActionRunResult::Level::Success};
|
||||
});
|
||||
add_with_icon("export_sliced_file", L("Export Sliced File"), L("Slice & Export"), "save", [](const std::string&) {
|
||||
if (Plater* plater = wxGetApp().plater())
|
||||
plater->export_gcode_3mf(false);
|
||||
return AppActionRunResult{AppActionRunResult::Level::Success};
|
||||
});
|
||||
add_with_icon("export_all_sliced_file", L("Export All Sliced Files"), L("Slice & Export"), "save", [](const std::string&) {
|
||||
if (Plater* plater = wxGetApp().plater())
|
||||
plater->export_gcode_3mf(true);
|
||||
return AppActionRunResult{AppActionRunResult::Level::Success};
|
||||
return AppActionRunResult{AppActionRunResult::Level::Success};
|
||||
}
|
||||
AppActionRunResult fail;
|
||||
const auto path = path_param(param, true, fail);
|
||||
if (!path)
|
||||
return fail;
|
||||
plater->export_core_3mf(from_path(*path));
|
||||
return written(*path);
|
||||
});
|
||||
auto export_sliced = [](bool all) {
|
||||
return [all](const std::string& param) {
|
||||
Plater* plater = wxGetApp().plater();
|
||||
if (plater == nullptr)
|
||||
return AppActionRunResult{};
|
||||
if (param.empty()) {
|
||||
plater->export_gcode_3mf(all);
|
||||
return AppActionRunResult{AppActionRunResult::Level::Success};
|
||||
}
|
||||
AppActionRunResult fail;
|
||||
const auto path = path_param(param, true, fail);
|
||||
if (!path)
|
||||
return fail;
|
||||
if (!plater->export_gcode_3mf(all, *path))
|
||||
return AppActionRunResult{AppActionRunResult::Level::Error, _L("The sliced file was not written. Slice first and check for slicing errors.")};
|
||||
return written(*path);
|
||||
};
|
||||
};
|
||||
add_with_icon("export_sliced_file", L("Export Sliced File"), L("Slice & Export"), "save", export_sliced(false));
|
||||
add_with_icon("export_all_sliced_file", L("Export All Sliced Files"), L("Slice & Export"), "save", export_sliced(true));
|
||||
|
||||
// ---- Calibration ----
|
||||
// The tab-strip calib_sf glyph is drawn white for the dark tab bar and vanishes on the palette's
|
||||
@@ -347,6 +569,19 @@ std::vector<NativeCommand> build_command_catalog()
|
||||
return object_op(
|
||||
wxGetApp().plater(), [](Plater* p) { return p->can_delete_all(); }, [](Plater* p) { p->delete_all_objects_from_model(); });
|
||||
});
|
||||
add("select_all", L("Select All Objects"), L("Object"), [](const std::string&) {
|
||||
Plater* plater = wxGetApp().plater();
|
||||
if (plater == nullptr)
|
||||
return AppActionRunResult{};
|
||||
ensure_3d_view(plater);
|
||||
plater->select_all();
|
||||
return AppActionRunResult{AppActionRunResult::Level::Success};
|
||||
});
|
||||
add("deselect_all", L("Deselect All"), L("Object"), [](const std::string&) {
|
||||
if (Plater* plater = wxGetApp().plater())
|
||||
plater->deselect_all();
|
||||
return AppActionRunResult{AppActionRunResult::Level::Success};
|
||||
});
|
||||
add_with_icon("obj_mirror_x", L("Mirror X"), L("Object"), "menu_mirror_x", [](const std::string&) {
|
||||
return object_op(wxGetApp().plater(), [](Plater* p) { return p->can_mirror(); }, [](Plater* p) { p->mirror(Axis::X); });
|
||||
});
|
||||
@@ -529,14 +764,24 @@ std::vector<NativeCommand> build_command_catalog()
|
||||
});
|
||||
|
||||
// ---- Import ----
|
||||
add_with_icon("import_file", L("Import 3MF/STL/STEP/SVG/OBJ/AMF"), L("Import"), "menu_open", [](const std::string&) {
|
||||
if (Plater* plater = wxGetApp().plater()) {
|
||||
add_with_icon("import_file", L("Import 3MF/STL/STEP/SVG/OBJ/AMF"), L("Import"), "menu_open", [](const std::string& param) {
|
||||
Plater* plater = wxGetApp().plater();
|
||||
if (plater == nullptr)
|
||||
return AppActionRunResult{};
|
||||
if (param.empty()) {
|
||||
#ifdef __APPLE__
|
||||
plater->add_model();
|
||||
#else
|
||||
plater->add_file();
|
||||
plater->add_file();
|
||||
#endif
|
||||
return AppActionRunResult{AppActionRunResult::Level::Success};
|
||||
}
|
||||
AppActionRunResult fail;
|
||||
const auto path = path_param(param, false, fail);
|
||||
if (!path)
|
||||
return fail;
|
||||
if (plater->load_files(std::vector<boost::filesystem::path>{*path}).empty())
|
||||
return AppActionRunResult{AppActionRunResult::Level::Error, _L("Nothing was imported.")};
|
||||
return AppActionRunResult{AppActionRunResult::Level::Success};
|
||||
});
|
||||
add_with_icon("import_zip_archive", L("Import ZIP Archive"), L("Import"), "menu_open", [](const std::string&) {
|
||||
@@ -544,17 +789,39 @@ std::vector<NativeCommand> build_command_catalog()
|
||||
plater->import_zip_archive();
|
||||
return AppActionRunResult{AppActionRunResult::Level::Success};
|
||||
});
|
||||
add_with_icon("import_configs", L("Import Configs"), L("Import"), "menu_open", [](const std::string&) {
|
||||
if (MainFrame* mf = wxGetApp().mainframe)
|
||||
add_with_icon("import_configs", L("Import Configs"), L("Import"), "menu_open", [](const std::string& param) {
|
||||
MainFrame* mf = wxGetApp().mainframe;
|
||||
if (mf == nullptr)
|
||||
return AppActionRunResult{};
|
||||
if (param.empty()) {
|
||||
mf->load_config_file();
|
||||
return AppActionRunResult{AppActionRunResult::Level::Success};
|
||||
}
|
||||
AppActionRunResult fail;
|
||||
const auto path = path_param(param, false, fail);
|
||||
if (!path)
|
||||
return fail;
|
||||
if (!mf->load_config_file(path->string()))
|
||||
return AppActionRunResult{AppActionRunResult::Level::Error, _L("The configuration was not loaded.")};
|
||||
return AppActionRunResult{AppActionRunResult::Level::Success};
|
||||
});
|
||||
|
||||
// ---- Export extras ----
|
||||
add_with_icon("export_stl_multi", L("Export All Objects as STLs"), L("Export"), "save", [](const std::string&) {
|
||||
if (Plater* plater = wxGetApp().plater())
|
||||
add_with_icon("export_stl_multi", L("Export All Objects as STLs"), L("Export"), "save", [](const std::string& param) {
|
||||
Plater* plater = wxGetApp().plater();
|
||||
if (plater == nullptr)
|
||||
return AppActionRunResult{};
|
||||
if (param.empty()) {
|
||||
plater->export_stl(false, false, true);
|
||||
return AppActionRunResult{AppActionRunResult::Level::Success};
|
||||
return AppActionRunResult{AppActionRunResult::Level::Success};
|
||||
}
|
||||
std::string err;
|
||||
auto pp = Mcp::parse_path_param(param, err);
|
||||
auto dir = pp ? Mcp::resolve_output_dir(pp->path, err) : std::nullopt;
|
||||
if (!dir)
|
||||
return AppActionRunResult{AppActionRunResult::Level::Error, from_u8(err)};
|
||||
plater->export_stl(false, false, true, FT_STL, from_path(*dir));
|
||||
return AppActionRunResult{AppActionRunResult::Level::Success, from_u8(dir->string())};
|
||||
});
|
||||
add_with_icon("export_drc_single", L("Export All Objects as DRC (one file)"), L("Export"), "save", [](const std::string&) {
|
||||
if (Plater* plater = wxGetApp().plater())
|
||||
@@ -650,6 +917,7 @@ std::vector<NativeCommand> build_command_catalog()
|
||||
return AppActionRunResult{AppActionRunResult::Level::Success};
|
||||
});
|
||||
|
||||
describe_commands(out);
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -666,6 +934,26 @@ std::unique_ptr<AppAction> NativeCommands::make_action(const NativeCommand& comm
|
||||
return std::make_unique<CommandAction>(command);
|
||||
}
|
||||
|
||||
const NativeCommand* NativeCommands::find(const std::string& key)
|
||||
{
|
||||
for (const NativeCommand& c : catalog())
|
||||
if (c.key == key)
|
||||
return &c;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const char* NativeCommands::param_type_name(CommandParamType type)
|
||||
{
|
||||
switch (type) {
|
||||
case CommandParamType::Percent: return "percent";
|
||||
case CommandParamType::Tab: return "tab";
|
||||
case CommandParamType::Path: return "path";
|
||||
case CommandParamType::Index: return "index";
|
||||
case CommandParamType::Text: return "text";
|
||||
default: return "none";
|
||||
}
|
||||
}
|
||||
|
||||
AppActionRunResult NativeCommands::run(const std::string& key, const std::string& param)
|
||||
{
|
||||
GUI_App& app = wxGetApp();
|
||||
|
||||
@@ -9,10 +9,26 @@
|
||||
|
||||
namespace Slic3r { namespace GUI {
|
||||
|
||||
// What a command's `param` means, for callers other than the palette (MCP, scripts). The palette
|
||||
// keeps using `input` for its second-phase picker and never passes a path, so a command that takes
|
||||
// one still opens its file dialog there.
|
||||
enum class CommandParamType { None, Percent, Tab, Path, Index, Text };
|
||||
|
||||
struct CommandParam
|
||||
{
|
||||
CommandParamType type = CommandParamType::None;
|
||||
std::string help; // English, for agents
|
||||
};
|
||||
|
||||
// Commands whose effect finishes after run() returns. Export: the G-code export runs in the
|
||||
// background process, so an automated caller waits for its file.
|
||||
enum class CommandCompletion { None, Export };
|
||||
|
||||
// A built-in speed-dial command: identity + how to run it. make_action() wraps a value as a thin
|
||||
// AppAction for the registry, so this catalog is the single source of truth for the behaviour
|
||||
// (runner => an owner method), the presentation (title/group/input), and the tile pictogram
|
||||
// (icon = an SVG base name under resources/images, "" for no icon).
|
||||
// (runner => an owner method), the presentation (title/group/input), the tile pictogram
|
||||
// (icon = an SVG base name under resources/images, "" for no icon), and what automation needs to
|
||||
// call it (description, param, completion).
|
||||
struct NativeCommand
|
||||
{
|
||||
std::string key;
|
||||
@@ -21,6 +37,9 @@ struct NativeCommand
|
||||
std::string input; // "percent"/"tab" or "" for immediate run
|
||||
std::string icon; // SVG base name, or "" to render a blank tile
|
||||
std::function<AppActionRunResult(const std::string& param)> runner;
|
||||
std::string description; // English, for agents; not shown in the palette
|
||||
CommandParam param;
|
||||
CommandCompletion completion = CommandCompletion::None;
|
||||
};
|
||||
|
||||
namespace NativeCommands {
|
||||
@@ -31,6 +50,11 @@ const std::vector<NativeCommand>& catalog();
|
||||
// Dispatches `key` to its runner (unknown keys return a quiet Info). UI thread only.
|
||||
AppActionRunResult run(const std::string& key, const std::string& param = {});
|
||||
|
||||
// The catalog entry for `key`, or nullptr.
|
||||
const NativeCommand* find(const std::string& key);
|
||||
|
||||
const char* param_type_name(CommandParamType type);
|
||||
|
||||
// Materialises one catalog entry as a runnable AppAction, titled in the current UI language with the
|
||||
// English title/group kept as search aliases. Keeps the catalog's identity, presentation and
|
||||
// behaviour as the single source of truth; ActionRegistry only stores and dispatches the result.
|
||||
|
||||
@@ -3376,6 +3376,35 @@ void NotificationManager::device_ejected()
|
||||
notification->close();
|
||||
}
|
||||
}
|
||||
std::vector<NotificationSummary> NotificationManager::summaries() const
|
||||
{
|
||||
std::vector<NotificationSummary> out;
|
||||
for (const std::unique_ptr<PopNotification>& n : m_pop_notifications) {
|
||||
if (n->is_finished())
|
||||
continue;
|
||||
const NotificationData& data = n->get_data();
|
||||
NotificationSummary s;
|
||||
s.type = int(data.type);
|
||||
switch (data.level) {
|
||||
case NotificationLevel::ErrorNotificationLevel: s.level = "error"; break;
|
||||
case NotificationLevel::WarningNotificationLevel:
|
||||
case NotificationLevel::SeriousWarningNotificationLevel: s.level = "warning"; break;
|
||||
case NotificationLevel::ProgressBarNotificationLevel: s.level = "progress"; break;
|
||||
case NotificationLevel::HintNotificationLevel: s.level = "hint"; break;
|
||||
default: s.level = "info"; break;
|
||||
}
|
||||
s.text = data.text1;
|
||||
if (!data.hypertext.empty())
|
||||
s.text += " " + data.hypertext;
|
||||
if (!data.text2.empty())
|
||||
s.text += " " + data.text2;
|
||||
if (s.text.find_first_not_of(" \n") == std::string::npos)
|
||||
continue; // progress bars and other notifications without text
|
||||
out.push_back(std::move(s));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
size_t NotificationManager::get_notification_count() const
|
||||
{
|
||||
size_t ret = 0;
|
||||
|
||||
@@ -201,6 +201,14 @@ enum class NotificationType
|
||||
|
||||
};
|
||||
|
||||
// A notification as text, for automation (MCP get_state).
|
||||
struct NotificationSummary
|
||||
{
|
||||
int type = 0; // NotificationType value
|
||||
std::string level; // "info", "warning", "error", "progress", "hint"
|
||||
std::string text;
|
||||
};
|
||||
|
||||
class NotificationManager
|
||||
{
|
||||
public:
|
||||
@@ -379,6 +387,8 @@ public:
|
||||
bool update_notifications(GLCanvas3D& canvas);
|
||||
// returns number of all notifications shown
|
||||
size_t get_notification_count() const;
|
||||
// The notifications currently shown (not finished or closing), oldest first.
|
||||
std::vector<NotificationSummary> summaries() const;
|
||||
|
||||
|
||||
//BBS Notice
|
||||
|
||||
+177
-25
@@ -19,6 +19,7 @@
|
||||
#include <boost/filesystem/fstream.hpp>
|
||||
#include <clocale>
|
||||
#include <cstddef>
|
||||
#include <deque>
|
||||
#include <algorithm>
|
||||
#include <ios>
|
||||
#include <iomanip>
|
||||
@@ -7230,6 +7231,20 @@ struct Plater::priv
|
||||
bool m_ignore_event{false};
|
||||
bool m_slice_all{false};
|
||||
bool m_is_slicing {false};
|
||||
|
||||
// Automation bookkeeping behind Plater::SliceRun / ExportRun.
|
||||
static constexpr std::size_t kKeepSliceRuns = 1024; // far more than one Slice All's runs (MAX_PLATE_COUNT)
|
||||
static constexpr std::size_t kKeepExportRuns = 16;
|
||||
uint64_t project_revision {0};
|
||||
uint64_t slice_request_seq {0};
|
||||
uint64_t slice_run_seq {0};
|
||||
uint64_t export_seq {0};
|
||||
std::deque<Plater::SliceRun> slice_runs;
|
||||
std::deque<Plater::ExportRun> export_runs;
|
||||
// A background run started; a run still open from before was restarted, so it ends cancelled.
|
||||
void note_run_started();
|
||||
// The background process reported completion: closes the open run and any export in flight.
|
||||
void note_process_completed(bool cancelled, bool success, const std::string& error);
|
||||
// Missing-plugin set signatures (sorted full refs joined by '\n'), one per notification. They
|
||||
// gate plugin-load re-validation and avoid needlessly recreating the notification when the set
|
||||
// is unchanged. Whether missing plugins block slicing is derived directly from PluginResolver
|
||||
@@ -7588,7 +7603,9 @@ struct Plater::priv
|
||||
GUI::show_error(this->q, msg);
|
||||
}
|
||||
}
|
||||
void export_gcode(fs::path output_path, bool output_path_on_removable_media);
|
||||
// `tracked` numbers the export for automation and, when it cannot start right away, unschedules
|
||||
// it instead of leaving it for a later restart. Returns whether it started.
|
||||
bool export_gcode(fs::path output_path, bool output_path_on_removable_media, bool tracked = false);
|
||||
void export_gcode(fs::path output_path, bool output_path_on_removable_media, PrintHostJob upload_job);
|
||||
|
||||
void reload_from_disk();
|
||||
@@ -10850,6 +10867,7 @@ void Plater::priv::delete_all_objects_from_model()
|
||||
|
||||
void Plater::priv::reset(bool apply_presets_change, bool reload_presets)
|
||||
{
|
||||
++project_revision;
|
||||
// TakeSnapshot below and load_current_presets() further down each re-evaluate the
|
||||
// aggregate dirty flag against a baseline that hasn't been reset yet, so they can toggle
|
||||
// is_dirty() back and forth several times before it settles; coalesce those into one event.
|
||||
@@ -11664,6 +11682,7 @@ bool Plater::priv::restart_background_process(unsigned int state)
|
||||
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format(", Line %1%: print is valid, try to start it now")%__LINE__;
|
||||
// The print is valid and it can be started.
|
||||
if (this->background_process.start()) {
|
||||
note_run_started();
|
||||
if (!show_warning_dialog)
|
||||
on_slicing_began();
|
||||
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format(", Line %1%: start successfully")%__LINE__;
|
||||
@@ -11674,6 +11693,7 @@ bool Plater::priv::restart_background_process(unsigned int state)
|
||||
PartPlate* cur_plate = background_process.get_current_plate();
|
||||
if (cur_plate->is_slice_result_valid() && ((state & UPDATE_BACKGROUND_PROCESS_FORCE_RESTART) != 0)) {
|
||||
if (this->background_process.start()) {
|
||||
note_run_started();
|
||||
if (!show_warning_dialog)
|
||||
on_slicing_began();
|
||||
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format(", Line %1%: start successfully")%__LINE__;
|
||||
@@ -11685,17 +11705,17 @@ bool Plater::priv::restart_background_process(unsigned int state)
|
||||
return false;
|
||||
}
|
||||
|
||||
void Plater::priv::export_gcode(fs::path output_path, bool output_path_on_removable_media)
|
||||
bool Plater::priv::export_gcode(fs::path output_path, bool output_path_on_removable_media, bool tracked)
|
||||
{
|
||||
wxCHECK_RET(!(output_path.empty()), "export_gcode: output_path and upload_job empty");
|
||||
wxCHECK_MSG(!(output_path.empty()), false, "export_gcode: output_path and upload_job empty");
|
||||
|
||||
BOOST_LOG_TRIVIAL(trace) << boost::format("export_gcode: output_path %1%")%output_path.string();
|
||||
if (model.objects.empty())
|
||||
return;
|
||||
return false;
|
||||
|
||||
if (background_process.is_export_scheduled()) {
|
||||
GUI::show_error(q, _L("Another export job is running."));
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
// bitmask of UpdateBackgroundProcessReturnState
|
||||
@@ -11704,7 +11724,7 @@ void Plater::priv::export_gcode(fs::path output_path, bool output_path_on_remova
|
||||
view3D->reload_scene(false);
|
||||
|
||||
if ((state & priv::UPDATE_BACKGROUND_PROCESS_INVALID) != 0)
|
||||
return;
|
||||
return false;
|
||||
|
||||
show_warning_dialog = true;
|
||||
if (! output_path.empty()) {
|
||||
@@ -11716,7 +11736,22 @@ void Plater::priv::export_gcode(fs::path output_path, bool output_path_on_remova
|
||||
|
||||
// If the SLA processing of just a single object's supports is running, restart slicing for the whole object.
|
||||
this->background_process.set_task(PrintBase::TaskParams());
|
||||
this->restart_background_process(priv::UPDATE_BACKGROUND_PROCESS_FORCE_EXPORT);
|
||||
const bool started = this->restart_background_process(priv::UPDATE_BACKGROUND_PROCESS_FORCE_EXPORT);
|
||||
if (!tracked)
|
||||
return started;
|
||||
if (!started) {
|
||||
// The caller refused to export while the process was running, so reset_export() is effective.
|
||||
background_process.reset_export();
|
||||
notification_manager->close_notification_of_type(NotificationType::ExportOngoing);
|
||||
return false;
|
||||
}
|
||||
Plater::ExportRun run;
|
||||
run.seq = ++export_seq;
|
||||
run.path = output_path.string();
|
||||
export_runs.push_back(std::move(run));
|
||||
while (export_runs.size() > kKeepExportRuns)
|
||||
export_runs.pop_front();
|
||||
return true;
|
||||
}
|
||||
void Plater::priv::export_gcode(fs::path output_path, bool output_path_on_removable_media, PrintHostJob upload_job)
|
||||
{
|
||||
@@ -13537,6 +13572,7 @@ void Plater::priv::on_process_completed(SlicingProcessCompletedEvent &evt)
|
||||
}
|
||||
}
|
||||
|
||||
note_process_completed(evt.cancelled(), evt.success(), has_error ? lifecycle_error_msg : std::string());
|
||||
exporting_status = ExportingStatus::NOT_EXPORTING;
|
||||
|
||||
|
||||
@@ -13766,6 +13802,7 @@ static std::vector<wxString> collect_imex_warnings(PartPlate* plate)
|
||||
void Plater::priv::on_action_slice_plate(SimpleEvent&)
|
||||
{
|
||||
if (q != nullptr) {
|
||||
++slice_request_seq;
|
||||
BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << ":received slice plate event\n" ;
|
||||
// IMEX parallel mode warnings (current plate only)
|
||||
if (wxGetApp().app_config->get("imex_pre_slice_warnings") != "false") {
|
||||
@@ -13807,6 +13844,7 @@ void Plater::priv::on_action_slice_plate(SimpleEvent&)
|
||||
void Plater::priv::on_action_slice_all(SimpleEvent&)
|
||||
{
|
||||
if (q != nullptr) {
|
||||
++slice_request_seq;
|
||||
BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << ":received slice project event\n" ;
|
||||
// IMEX parallel mode warnings (all plates)
|
||||
if (wxGetApp().app_config->get("imex_pre_slice_warnings") != "false") {
|
||||
@@ -15287,6 +15325,8 @@ int Plater::priv::get_active_snapshot_index()
|
||||
|
||||
void Plater::priv::take_snapshot(const std::string& snapshot_name, const UndoRedo::SnapshotType snapshot_type)
|
||||
{
|
||||
// A suppressed snapshot is still an edit.
|
||||
++project_revision;
|
||||
if (m_prevent_snapshots > 0)
|
||||
return;
|
||||
assert(m_prevent_snapshots >= 0);
|
||||
@@ -15433,6 +15473,7 @@ bool Plater::priv::up_to_date(bool saved, bool backup)
|
||||
|
||||
void Plater::priv::undo_redo_to(std::vector<UndoRedo::Snapshot>::const_iterator it_snapshot)
|
||||
{
|
||||
++project_revision;
|
||||
// Make sure that no updating function calls take_snapshot until we are done.
|
||||
SuppressSnapshots snapshot_supressor(q);
|
||||
|
||||
@@ -16324,15 +16365,19 @@ void Plater::load_project(wxString const& filename2,
|
||||
}
|
||||
|
||||
// BBS: save logic
|
||||
int Plater::save_project(bool saveAs)
|
||||
int Plater::save_project(bool saveAs, const wxString& path)
|
||||
{
|
||||
//if (up_to_date(false, false)) // should we always save
|
||||
// return;
|
||||
auto filename = get_project_filename(".3mf");
|
||||
if (!saveAs && filename.IsEmpty())
|
||||
saveAs = true;
|
||||
if (saveAs)
|
||||
filename = p->get_export_file(FT_3MF);
|
||||
if (!path.empty())
|
||||
filename = path;
|
||||
else {
|
||||
if (!saveAs && filename.IsEmpty())
|
||||
saveAs = true;
|
||||
if (saveAs)
|
||||
filename = p->get_export_file(FT_3MF);
|
||||
}
|
||||
if (filename.empty())
|
||||
return wxID_NO;
|
||||
if (filename == "<cancel>")
|
||||
@@ -19633,13 +19678,13 @@ void Plater::send_to_printer(bool isall)
|
||||
}
|
||||
|
||||
//BBS export gcode 3mf to file
|
||||
void Plater::export_gcode_3mf(bool export_all)
|
||||
bool Plater::export_gcode_3mf(bool export_all, const boost::filesystem::path& given_output_path)
|
||||
{
|
||||
if (p->model.objects.empty())
|
||||
return;
|
||||
return false;
|
||||
|
||||
if (p->process_completed_with_error == p->partplate_list.get_curr_plate_index())
|
||||
return;
|
||||
return false;
|
||||
|
||||
//calc default_output_file, get default output file from background process
|
||||
fs::path default_output_file;
|
||||
@@ -19650,18 +19695,18 @@ void Plater::export_gcode_3mf(bool export_all)
|
||||
// Also if there is something wrong with the current configuration, a pop-up dialog will be shown and the export will not be performed.
|
||||
unsigned int state = this->p->update_restart_background_process(false, false);
|
||||
if (state & priv::UPDATE_BACKGROUND_PROCESS_INVALID)
|
||||
return;
|
||||
return false;
|
||||
default_output_file = this->p->background_process.output_filepath_for_project(
|
||||
into_path(this->p->get_project_filename(".3mf")));
|
||||
}
|
||||
catch (const Slic3r::PlaceholderParserError& ex) {
|
||||
// Show the error with monospaced font.
|
||||
show_error(this, ex.what(), true);
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
catch (const std::exception& ex) {
|
||||
show_error(this, ex.what(), false);
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
default_output_file.replace_extension(".gcode.3mf");
|
||||
default_output_file = fs::path(Slic3r::fold_utf8_to_ascii(default_output_file.string()));
|
||||
@@ -19669,8 +19714,8 @@ void Plater::export_gcode_3mf(bool export_all)
|
||||
//Get a last save path
|
||||
start_dir = appconfig.get_last_output_dir(default_output_file.parent_path().string(), false);
|
||||
|
||||
fs::path output_path;
|
||||
{
|
||||
fs::path output_path = given_output_path;
|
||||
if (output_path.empty()) {
|
||||
std::string ext = default_output_file.extension().string();
|
||||
wxFileDialog dlg(this, _L("Save Sliced file as:"),
|
||||
start_dir,
|
||||
@@ -19703,7 +19748,7 @@ void Plater::export_gcode_3mf(bool export_all)
|
||||
if (export_3mf(output_path, strategy, plate_idx) < 0) {
|
||||
// No file was written (e.g. a post-processing script failed), don't report a successful export.
|
||||
p->exporting_status = ExportingStatus::NOT_EXPORTING;
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
RemovableDriveManager& removable_drive_manager = *wxGetApp().removable_drive_manager();
|
||||
@@ -19716,6 +19761,7 @@ void Plater::export_gcode_3mf(bool export_all)
|
||||
appconfig.update_last_output_dir(output_path.parent_path().string(), false);
|
||||
p->notification_manager->push_exporting_finished_notification(output_path.string(), p->last_output_dir_path, on_removable);
|
||||
}
|
||||
return !output_path.empty();
|
||||
}
|
||||
|
||||
void Plater::send_gcode_finish(wxString name)
|
||||
@@ -19755,9 +19801,9 @@ private:
|
||||
|
||||
} // namespace
|
||||
|
||||
void Plater::export_core_3mf()
|
||||
void Plater::export_core_3mf(const wxString& output_path)
|
||||
{
|
||||
wxString path = p->get_export_file(FT_3MF);
|
||||
wxString path = output_path.empty() ? p->get_export_file(FT_3MF) : output_path;
|
||||
if (path.empty()) { return; }
|
||||
const std::string path_u8 = into_u8(path);
|
||||
export_3mf(path_u8, SaveStrategy::Silence);
|
||||
@@ -20101,7 +20147,7 @@ TriangleMesh Plater::combine_mesh_fff(const ModelObject& mo, int instance_id, st
|
||||
|
||||
// BBS export with/without boolean, however, stil merge mesh
|
||||
#define EXPORT_WITH_BOOLEAN 0
|
||||
void Plater::export_stl(bool extended, bool selection_only, bool multi_stls, FileType file_type)
|
||||
void Plater::export_stl(bool extended, bool selection_only, bool multi_stls, FileType file_type, const wxString& output_path)
|
||||
{
|
||||
if (p->model.objects.empty()) { return; }
|
||||
|
||||
@@ -20118,7 +20164,11 @@ void Plater::export_stl(bool extended, bool selection_only, bool multi_stls, Fil
|
||||
}
|
||||
|
||||
wxString path;
|
||||
if (multi_stls) {
|
||||
if (!output_path.empty()) {
|
||||
path = output_path;
|
||||
if (multi_stls && !path.EndsWith("/") && !path.EndsWith("\\"))
|
||||
path += "/";
|
||||
} else if (multi_stls) {
|
||||
wxDirDialog dlg(this, _L("Choose a directory"), from_u8(wxGetApp().app_config->get_last_dir()),
|
||||
wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST);
|
||||
if (dlg.ShowModal() == wxID_OK) {
|
||||
@@ -21563,6 +21613,7 @@ void Plater::config_change_notification(const DynamicPrintConfig &config, const
|
||||
|
||||
void Plater::on_config_change(const DynamicPrintConfig &config)
|
||||
{
|
||||
++p->project_revision;
|
||||
bool update_scheduled = false;
|
||||
bool bed_shape_changed = false;
|
||||
bool exclusion_preview_changed = false;
|
||||
@@ -23657,6 +23708,107 @@ bool Plater::is_background_process_slicing() const
|
||||
return p->m_is_slicing;
|
||||
}
|
||||
|
||||
bool Plater::is_slicing_any() const
|
||||
{
|
||||
return p->m_is_slicing || p->background_process.running() || is_background_process_update_scheduled();
|
||||
}
|
||||
|
||||
void Plater::request_slice(bool all_plates)
|
||||
{
|
||||
SimpleEvent evt(all_plates ? EVT_GLTOOLBAR_SLICE_ALL : EVT_GLTOOLBAR_SLICE_PLATE);
|
||||
if (all_plates)
|
||||
p->on_action_slice_all(evt);
|
||||
else
|
||||
p->on_action_slice_plate(evt);
|
||||
}
|
||||
|
||||
void Plater::cancel_slicing()
|
||||
{
|
||||
if (!p->background_process.idle())
|
||||
p->background_process.stop();
|
||||
}
|
||||
|
||||
bool Plater::export_gcode_to(const boost::filesystem::path& output_path)
|
||||
{
|
||||
// Only a finished, valid slice is exported: anything that would start the background process
|
||||
// first could leave the export scheduled behind a running slice, out of the caller's sight.
|
||||
if (p->model.objects.empty() || is_slicing_any())
|
||||
return false;
|
||||
if (p->process_completed_with_error == p->partplate_list.get_curr_plate_index() ||
|
||||
!p->partplate_list.get_curr_plate()->is_slice_result_valid())
|
||||
return false;
|
||||
p->notification_manager->new_export_began(false);
|
||||
p->exporting_status = ExportingStatus::EXPORTING_TO_LOCAL;
|
||||
p->last_output_path = output_path.string();
|
||||
p->last_output_dir_path = output_path.parent_path().string();
|
||||
if (!p->export_gcode(output_path, false, /*tracked=*/true)) {
|
||||
p->exporting_status = ExportingStatus::NOT_EXPORTING;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
uint64_t Plater::project_revision() const { return p->project_revision; }
|
||||
uint64_t Plater::slice_request_seq() const { return p->slice_request_seq; }
|
||||
uint64_t Plater::slice_run_seq() const { return p->slice_run_seq; }
|
||||
uint64_t Plater::export_seq() const { return p->export_seq; }
|
||||
|
||||
std::optional<Plater::SliceRun> Plater::slice_run(uint64_t seq) const
|
||||
{
|
||||
for (const SliceRun& run : p->slice_runs)
|
||||
if (run.seq == seq)
|
||||
return run;
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::optional<Plater::ExportRun> Plater::export_run(uint64_t seq) const
|
||||
{
|
||||
for (const ExportRun& run : p->export_runs)
|
||||
if (run.seq == seq)
|
||||
return run;
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
void Plater::priv::note_run_started()
|
||||
{
|
||||
for (Plater::SliceRun& run : slice_runs)
|
||||
if (!run.finished) {
|
||||
run.finished = true;
|
||||
run.cancelled = true;
|
||||
run.revision_at_finish = project_revision;
|
||||
run.request_seq_at_finish = slice_request_seq;
|
||||
}
|
||||
Plater::SliceRun run;
|
||||
run.seq = ++slice_run_seq;
|
||||
slice_runs.push_back(run);
|
||||
while (slice_runs.size() > kKeepSliceRuns)
|
||||
slice_runs.pop_front();
|
||||
}
|
||||
|
||||
void Plater::priv::note_process_completed(bool cancelled, bool success, const std::string& error)
|
||||
{
|
||||
for (auto it = slice_runs.rbegin(); it != slice_runs.rend(); ++it)
|
||||
if (!it->finished) {
|
||||
it->finished = true;
|
||||
it->cancelled = cancelled;
|
||||
it->error = error;
|
||||
it->revision_at_finish = project_revision;
|
||||
it->request_seq_at_finish = slice_request_seq;
|
||||
break;
|
||||
}
|
||||
if (exporting_status == ExportingStatus::NOT_EXPORTING)
|
||||
return;
|
||||
for (auto it = export_runs.rbegin(); it != export_runs.rend(); ++it)
|
||||
if (!it->finished) {
|
||||
it->finished = true;
|
||||
it->cancelled = cancelled;
|
||||
it->ok = success && !cancelled;
|
||||
it->error = error;
|
||||
it->revision_at_finish = project_revision;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
//BBS: update slicing context
|
||||
void Plater::update_slicing_context_to_current_partplate()
|
||||
{
|
||||
|
||||
@@ -13,7 +13,9 @@
|
||||
#include "libslic3r/Point.hpp"
|
||||
#include "libslic3r/libslic3r.h"
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include "slic3r/GUI/Event.hpp"
|
||||
#include "slic3r/GUI/I18N.hpp"
|
||||
#include <string>
|
||||
@@ -379,7 +381,8 @@ public:
|
||||
int new_project(bool skip_confirm = false, bool silent = false, const wxString& project_name = wxString(), bool reload_presets = true);
|
||||
// BBS: save & backup
|
||||
void load_project(wxString const & filename = "", wxString const & originfile = "-");
|
||||
int save_project(bool saveAs = false);
|
||||
// `path` saves there without asking (automation); empty keeps the interactive behaviour.
|
||||
int save_project(bool saveAs = false, const wxString& path = {});
|
||||
//BBS download project by project id
|
||||
void import_model_id(wxString download_info);
|
||||
void download_project(const wxString& project_id);
|
||||
@@ -575,9 +578,10 @@ public:
|
||||
|
||||
void send_to_printer(bool isall = false);
|
||||
void export_gcode(bool prefer_removable);
|
||||
void export_gcode_3mf(bool export_all = false);
|
||||
// `output_path` writes there without the file dialog; returns whether the file was written.
|
||||
bool export_gcode_3mf(bool export_all = false, const boost::filesystem::path& output_path = {});
|
||||
void send_gcode_finish(wxString name);
|
||||
void export_core_3mf();
|
||||
void export_core_3mf(const wxString& output_path = {});
|
||||
// Write the project to output_path as a copy: the project's file name, dirty state and model stay
|
||||
// as they are, and the signed-in account is not added as the designer. False when the write fails.
|
||||
bool export_3mf_copy(const boost::filesystem::path& output_path);
|
||||
@@ -589,7 +593,9 @@ public:
|
||||
bool get_pending_published(std::vector<std::string>& out_keys, std::vector<Slic3r::PublishedMaterialEntry>& out_material, bool& out_legacy_process) const;
|
||||
void set_pending_published(const std::vector<std::string>& published_keys, const std::vector<Slic3r::PublishedMaterialEntry>& material_keys);
|
||||
static TriangleMesh combine_mesh_fff(const ModelObject& mo, int instance_id, std::function<void(const std::string&)> notify_func = {});
|
||||
void export_stl(bool extended = false, bool selection_only = false, bool multi_stls = false, FileType file_type = FT_STL);
|
||||
// `output_path` (a directory for multi_stls) skips the file dialog.
|
||||
void export_stl(bool extended = false, bool selection_only = false, bool multi_stls = false, FileType file_type = FT_STL,
|
||||
const wxString& output_path = {});
|
||||
//BBS: remove amf
|
||||
//void export_amf();
|
||||
//BBS add extra param for exporting 3mf silence
|
||||
@@ -879,6 +885,47 @@ public:
|
||||
void set_bed_position(Vec2d& pos);
|
||||
//BBS: is the background process slicing currently
|
||||
bool is_background_process_slicing() const;
|
||||
// Slicing in any form: the background process running, Slice All in progress, or an update
|
||||
// scheduled to start one.
|
||||
bool is_slicing_any() const;
|
||||
|
||||
// A slice request from a user-facing entry point (toolbar, menu, shortcut, Speed Dial, MCP):
|
||||
// the same path as the toolbar's Slice plate / Slice all.
|
||||
void request_slice(bool all_plates);
|
||||
// What the slicing progress notification's cancel button does.
|
||||
void cancel_slicing();
|
||||
// Starts a G-code export to `output_path` without a dialog. Refused while the background process
|
||||
// is running; when it cannot start, nothing is left scheduled. Returns whether it started.
|
||||
bool export_gcode_to(const boost::filesystem::path& output_path);
|
||||
|
||||
// Bookkeeping that lets an automated caller tell its own slice or export from anyone else's.
|
||||
// The project revision moves on every edit (snapshot, undo/redo, preset or setting change,
|
||||
// reset, load); slice requests, background runs and exports are numbered.
|
||||
struct SliceRun
|
||||
{
|
||||
uint64_t seq = 0;
|
||||
bool finished = false;
|
||||
bool cancelled = false;
|
||||
std::string error;
|
||||
uint64_t revision_at_finish = 0;
|
||||
uint64_t request_seq_at_finish = 0;
|
||||
};
|
||||
struct ExportRun
|
||||
{
|
||||
uint64_t seq = 0;
|
||||
std::string path;
|
||||
bool finished = false;
|
||||
bool ok = false;
|
||||
bool cancelled = false;
|
||||
std::string error;
|
||||
uint64_t revision_at_finish = 0;
|
||||
};
|
||||
uint64_t project_revision() const;
|
||||
uint64_t slice_request_seq() const;
|
||||
uint64_t slice_run_seq() const;
|
||||
std::optional<SliceRun> slice_run(uint64_t seq) const;
|
||||
uint64_t export_seq() const;
|
||||
std::optional<ExportRun> export_run(uint64_t seq) const;
|
||||
//BBS: update slicing context
|
||||
void update_slicing_context_to_current_partplate();
|
||||
//BBS: show object info
|
||||
|
||||
@@ -200,6 +200,50 @@ BitmapCache& PresetComboBox::bitmap_cache()
|
||||
return bmps;
|
||||
}
|
||||
|
||||
bool PresetComboBox::is_marker_item(int item)
|
||||
{
|
||||
const auto marker = reinterpret_cast<std::size_t>(GetClientData(item));
|
||||
return marker >= LABEL_ITEM_DISABLED && marker < LABEL_ITEM_MAX;
|
||||
}
|
||||
|
||||
PresetComboBox::NameMatch PresetComboBox::find_by_name(const std::string& requested)
|
||||
{
|
||||
NameMatch match;
|
||||
const std::string want = Preset::remove_suffix_modified(requested);
|
||||
const int item_count = GetCount();
|
||||
for (int item = 0; item < item_count; ++item) {
|
||||
if (is_marker_item(item))
|
||||
continue;
|
||||
const wxString alias = GetItemAlias(item);
|
||||
const std::string alias_name = alias.empty() ? std::string() : Preset::remove_suffix_modified(alias.ToUTF8().data());
|
||||
const std::string label_name = Preset::remove_suffix_modified(GetString(item).ToUTF8().data());
|
||||
if ((alias_name.empty() || alias_name != want) && label_name != want)
|
||||
continue;
|
||||
if (match.item >= 0 && match.item != item) {
|
||||
match.ambiguous = true;
|
||||
return match;
|
||||
}
|
||||
match.item = item;
|
||||
match.internal_name = alias_name.empty() ? label_name : alias_name;
|
||||
}
|
||||
return match;
|
||||
}
|
||||
|
||||
int PresetComboBox::item_for_preset(const std::string& preset_name)
|
||||
{
|
||||
const std::string want = Preset::remove_suffix_modified(preset_name);
|
||||
const int item_count = GetCount();
|
||||
for (int item = 0; item < item_count; ++item) {
|
||||
if (is_marker_item(item))
|
||||
continue;
|
||||
const wxString alias = GetItemAlias(item);
|
||||
const std::string alias_name = alias.empty() ? std::string() : Preset::remove_suffix_modified(alias.ToUTF8().data());
|
||||
if (!alias_name.empty() && alias_name == want)
|
||||
return item;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
void PresetComboBox::set_label_marker(int item, LabelItemType label_item_type)
|
||||
{
|
||||
this->SetClientData(item, (void*)label_item_type);
|
||||
|
||||
@@ -70,6 +70,25 @@ public:
|
||||
void set_label_marker(int item, LabelItemType label_item_type = LABEL_ITEM_MARKER);
|
||||
bool set_printer_technology(PrinterTechnology pt);
|
||||
|
||||
// True for a row that is a group header, a marker or disabled: not a selectable preset.
|
||||
bool is_marker_item(int item);
|
||||
// How a caller-supplied preset name resolved against this combo's items.
|
||||
struct NameMatch
|
||||
{
|
||||
int item = -1; // first matching item, or -1
|
||||
bool ambiguous = false; // two distinct items carry this name
|
||||
std::string internal_name; // internal preset name of the match (empty when none)
|
||||
};
|
||||
// Resolves `requested` by the name each item shows: its display label, or its stored item alias
|
||||
// (the internal preset name, or the printer model for a system printer preset). Names are
|
||||
// compared with the modified-dirty suffix removed, i.e. exactly what the dropdown shows, so this
|
||||
// respects the combo's real selectable model (visibility, show-incompatible state, and for a
|
||||
// filament slot combo that slot's compatibility). A name two distinct items carry is reported
|
||||
// ambiguous instead of being resolved by position. Used by scripts and automation.
|
||||
NameMatch find_by_name(const std::string& requested);
|
||||
// Index of the item whose internal name is `preset_name`, or -1.
|
||||
int item_for_preset(const std::string& preset_name);
|
||||
|
||||
void set_selection_changed_function(std::function<void(int)> sel_changed) { on_selection_changed = sel_changed; }
|
||||
|
||||
bool is_selected_physical_printer();
|
||||
|
||||
@@ -182,77 +182,13 @@ GUI::Tab* require_tab(GUI::GUI_App& app, Preset::Type type)
|
||||
return tab;
|
||||
}
|
||||
|
||||
// True for a combo row that is a group header, a marker or a disabled row: it carries a marker in
|
||||
// its client data and is not a selectable preset.
|
||||
bool combo_item_is_marker(GUI::PresetComboBox& combo, int item)
|
||||
{
|
||||
const auto marker = reinterpret_cast<std::size_t>(combo.GetClientData(item));
|
||||
return marker >= GUI::PresetComboBox::LABEL_ITEM_DISABLED && marker < GUI::PresetComboBox::LABEL_ITEM_MAX;
|
||||
}
|
||||
|
||||
// How a caller-supplied name resolved against a combo's actual items.
|
||||
struct ComboPresetMatch
|
||||
{
|
||||
int item = -1; // first matching item, or -1
|
||||
bool ambiguous = false; // two distinct items carry this name
|
||||
std::string internal_name; // internal preset name of the match (empty when none)
|
||||
};
|
||||
|
||||
// Resolve `requested` by the name each combo item shows: its display label, or its stored item
|
||||
// alias (the internal preset name, or the printer model for a system printer preset). Names are
|
||||
// compared with the modified-dirty suffix removed, i.e. exactly what the dropdown shows. Reading
|
||||
// the combo's own items means this respects the combo's real selectable model (visibility, its
|
||||
// show-incompatible state and, for a slot combo, that slot's compatibility). A name that two
|
||||
// distinct items carry is reported ambiguous instead of being resolved by position.
|
||||
ComboPresetMatch resolve_combo_preset(GUI::PresetComboBox& combo, const std::string& requested)
|
||||
{
|
||||
ComboPresetMatch match;
|
||||
const std::string want = Preset::remove_suffix_modified(requested);
|
||||
const int item_count = combo.GetCount();
|
||||
for (int item = 0; item < item_count; ++item) {
|
||||
if (combo_item_is_marker(combo, item))
|
||||
continue;
|
||||
const wxString alias = combo.GetItemAlias(item);
|
||||
const std::string alias_name = alias.empty() ? std::string()
|
||||
: Preset::remove_suffix_modified(alias.ToUTF8().data());
|
||||
const std::string label_name = Preset::remove_suffix_modified(combo.GetString(item).ToUTF8().data());
|
||||
if ((alias_name.empty() || alias_name != want) && label_name != want)
|
||||
continue;
|
||||
if (match.item >= 0 && match.item != item) {
|
||||
match.ambiguous = true;
|
||||
return match;
|
||||
}
|
||||
match.item = item;
|
||||
match.internal_name = alias_name.empty() ? label_name : alias_name;
|
||||
}
|
||||
return match;
|
||||
}
|
||||
|
||||
// Index of the item whose internal name is `preset_name`, or -1. Used for per-item flags (the AMS
|
||||
// sync badge); the internal name is unique, so no ambiguity handling is needed here.
|
||||
int combo_item_for_preset(GUI::PresetComboBox& combo, const std::string& preset_name)
|
||||
{
|
||||
const std::string want = Preset::remove_suffix_modified(preset_name);
|
||||
const int item_count = combo.GetCount();
|
||||
for (int item = 0; item < item_count; ++item) {
|
||||
if (combo_item_is_marker(combo, item))
|
||||
continue;
|
||||
const wxString alias = combo.GetItemAlias(item);
|
||||
const std::string alias_name = alias.empty() ? std::string()
|
||||
: Preset::remove_suffix_modified(alias.ToUTF8().data());
|
||||
if (!alias_name.empty() && alias_name == want)
|
||||
return item;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Resolve `requested` to the internal preset name its dropdown entry names, or throw. `category`
|
||||
// and `selector` are used only for the error text. A name the selector does not offer, or that two
|
||||
// entries share, raises std::invalid_argument.
|
||||
std::string resolve_preset_in_combo(GUI::PresetComboBox& combo, const std::string& requested,
|
||||
const std::string& category, const std::string& selector)
|
||||
{
|
||||
const ComboPresetMatch match = resolve_combo_preset(combo, requested);
|
||||
const GUI::PresetComboBox::NameMatch match = combo.find_by_name(requested);
|
||||
if (match.ambiguous)
|
||||
throw std::invalid_argument("The " + category + " name \"" + requested + "\" is ambiguous in the " + selector
|
||||
+ "; more than one entry shows it, so name the preset by its own entry");
|
||||
@@ -456,7 +392,7 @@ void bind_filament_target(int slot_number, const std::string& preset_name, Prese
|
||||
GUI::PlaterPresetComboBox* slot_combo = slot_index < slot_combos.size() ? slot_combos[slot_index] : nullptr;
|
||||
std::string resolved;
|
||||
if (slot_combo != nullptr && slot_combo->GetCount() > 0) {
|
||||
const ComboPresetMatch match = resolve_combo_preset(*slot_combo, preset_name);
|
||||
const GUI::PresetComboBox::NameMatch match = slot_combo->find_by_name(preset_name);
|
||||
if (match.ambiguous)
|
||||
throw std::invalid_argument("The filament name \"" + preset_name
|
||||
+ "\" is ambiguous in the filament preset selector for filament slot "
|
||||
@@ -540,7 +476,7 @@ void bind_filament_target(int slot_number, const std::string& preset_name, Prese
|
||||
slot_combo->update();
|
||||
// Keep the slot's AMS sync badge truthful, reading the item's own flag, the same source
|
||||
// on_select_preset() reads, so no UI state is invented here.
|
||||
const int item = combo_item_for_preset(*slot_combo, target);
|
||||
const int item = slot_combo->item_for_preset(target);
|
||||
if (item >= 0)
|
||||
slot_combo->set_sync_badge(slot_combo->GetFlag(item)
|
||||
== static_cast<int>(GUI::PresetComboBox::FilamentAMSType::FROM_AMS));
|
||||
|
||||
@@ -386,7 +386,8 @@ TEST_CASE("every mutate call is refused while a slice job runs, but cancel and r
|
||||
{
|
||||
Harness h;
|
||||
std::atomic<bool> release{false};
|
||||
ToolDef slice = tool("slice", GuardClass::Mutate, [&](const json&, ToolContext&) {
|
||||
ToolDef slice = tool("slice", GuardClass::Mutate, [&](const json&, ToolContext& ctx) {
|
||||
ctx.begin_operation();
|
||||
while (!release)
|
||||
std::this_thread::sleep_for(10ms);
|
||||
return ToolResult::ok();
|
||||
@@ -402,7 +403,6 @@ TEST_CASE("every mutate call is refused while a slice job runs, but cancel and r
|
||||
h.registry.add(cancel);
|
||||
h.registry.add(tool("answer", GuardClass::Recover, [](const json&, ToolContext&) { return ToolResult::ok(); }));
|
||||
h.start();
|
||||
h.core->set_operation_tools({"slice"});
|
||||
|
||||
const ToolResult running = h.call("slice");
|
||||
REQUIRE(running.data["status"] == "running");
|
||||
@@ -456,7 +456,8 @@ TEST_CASE("idle ignores the caller and its ancestors", "[Mcp]")
|
||||
CHECK(jobs.any_running_except(jobs.lineage(step)));
|
||||
jobs.finish(other, ToolResult::ok());
|
||||
CHECK_FALSE(jobs.any_running_except(jobs.lineage(step)));
|
||||
CHECK(jobs.running_of({"slice"}, {}) == std::vector<std::string>{step});
|
||||
jobs.set_operation(step);
|
||||
CHECK(jobs.running_operations() == std::vector<std::string>{step});
|
||||
}
|
||||
|
||||
TEST_CASE("the job registry caps running jobs and forgets old finished ones", "[Mcp]")
|
||||
|
||||
@@ -29,6 +29,7 @@ public:
|
||||
ToolResult call_child(const std::string&, const json&) override { return ToolResult::error("no children"); }
|
||||
std::set<std::string> lineage() const override { return {}; }
|
||||
void set_journal_args(json) override {}
|
||||
void begin_operation() override {}
|
||||
} ctx;
|
||||
return def.handler(args, ctx);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Drive OrcaSlicer's MCP server from Python or a shell, for development and tests.
|
||||
|
||||
Standard library only. Two halves:
|
||||
|
||||
* ``OrcaMcp``: a minimal client for the server's HTTP endpoint (``call(tool, **args)``).
|
||||
* A command line that launches OrcaSlicer for an agent or a test and talks to it::
|
||||
|
||||
tools/mcp/orca_mcp.py launch --xvfb # fresh datadir, wait until ready, print client config
|
||||
tools/mcp/orca_mcp.py call get_state
|
||||
tools/mcp/orca_mcp.py call open_files '{"paths": ["/abs/model.stl"]}'
|
||||
tools/mcp/orca_mcp.py screenshot /tmp/shot.png --target canvas
|
||||
tools/mcp/orca_mcp.py snapshot
|
||||
tools/mcp/orca_mcp.py run-script tools/mcp/smoke_test.json --out /tmp/smoke
|
||||
tools/mcp/orca_mcp.py stop
|
||||
|
||||
``launch`` records the instance (port, token, pid, datadir) in a session file
|
||||
(``$ORCA_MCP_SESSION`` or ``~/.cache/orca-mcp/session.json``) that the other commands read.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
DEFAULT_PORT = 13619
|
||||
SESSION_FILE = os.environ.get("ORCA_MCP_SESSION", os.path.expanduser("~/.cache/orca-mcp/session.json"))
|
||||
PROTOCOL = "2025-11-25"
|
||||
|
||||
# A finished setup with one printer, so a fresh datadir opens straight into the main window.
|
||||
DEFAULT_PRINTER = ("BBL", "Bambu Lab X1 Carbon", "0.4", "Bambu PLA Basic @BBL X1C")
|
||||
|
||||
|
||||
class McpError(RuntimeError):
|
||||
"""A tool returned isError, or the server answered with a JSON-RPC error."""
|
||||
|
||||
def __init__(self, message, payload=None):
|
||||
super().__init__(message)
|
||||
self.payload = payload
|
||||
|
||||
|
||||
class OrcaMcp:
|
||||
def __init__(self, port=DEFAULT_PORT, token="", host="127.0.0.1", timeout=120):
|
||||
self.url = f"http://{host}:{port}/mcp"
|
||||
self.port = port
|
||||
self.token = token
|
||||
self.timeout = timeout
|
||||
self._id = 0
|
||||
|
||||
def request(self, method, params=None, timeout=None):
|
||||
self._id += 1
|
||||
body = {"jsonrpc": "2.0", "id": self._id, "method": method}
|
||||
if params is not None:
|
||||
body["params"] = params
|
||||
req = urllib.request.Request(
|
||||
self.url,
|
||||
data=json.dumps(body).encode(),
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json, text/event-stream",
|
||||
"Authorization": f"Bearer {self.token}",
|
||||
"MCP-Protocol-Version": PROTOCOL,
|
||||
},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout or self.timeout) as r:
|
||||
reply = json.loads(r.read() or b"{}")
|
||||
except urllib.error.HTTPError as e:
|
||||
raise McpError(f"HTTP {e.code}: {e.read().decode(errors='replace')}") from None
|
||||
if "error" in reply:
|
||||
raise McpError(reply["error"].get("message", "error"), reply["error"])
|
||||
return reply.get("result", {})
|
||||
|
||||
def initialize(self):
|
||||
return self.request("initialize", {"protocolVersion": PROTOCOL, "capabilities": {},
|
||||
"clientInfo": {"name": "orca_mcp.py", "version": "1"}})
|
||||
|
||||
def tools(self):
|
||||
return self.request("tools/list")["tools"]
|
||||
|
||||
def call_raw(self, tool, args=None, timeout=None):
|
||||
return self.request("tools/call", {"name": tool, "arguments": args or {}}, timeout=timeout)
|
||||
|
||||
def call(self, tool, _timeout=None, **args):
|
||||
"""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."""
|
||||
result = self.call_raw(tool, args, timeout=_timeout)
|
||||
text = next((c["text"] for c in result.get("content", []) if c.get("type") == "text"), "")
|
||||
if result.get("isError"):
|
||||
raise McpError(text, result)
|
||||
try:
|
||||
return json.loads(text) if text else {}
|
||||
except json.JSONDecodeError:
|
||||
return {"text": text}
|
||||
|
||||
def images(self, tool, **args):
|
||||
"""Call a tool and return (json_result, [png bytes...]) for image content blocks."""
|
||||
result = self.call_raw(tool, args)
|
||||
if result.get("isError"):
|
||||
raise McpError(result["content"][0]["text"], result)
|
||||
data, imgs = {}, []
|
||||
for c in result.get("content", []):
|
||||
if c.get("type") == "text":
|
||||
data = json.loads(c["text"])
|
||||
elif c.get("type") == "image":
|
||||
imgs.append(base64.b64decode(c["data"]))
|
||||
return data, imgs
|
||||
|
||||
def await_job(self, result, timeout=600):
|
||||
"""Follow a job envelope until the job finishes and return its result."""
|
||||
deadline = time.time() + timeout
|
||||
while isinstance(result, dict) and result.get("status") in ("running", "blocked_by_dialog") and "job" in result:
|
||||
if time.time() > deadline:
|
||||
raise McpError(f"job {result['job']} did not finish in {timeout} s", result)
|
||||
result = self.call("wait", **{"for": "job", "job": result["job"], "timeout_s": 45})
|
||||
return result
|
||||
|
||||
def ready(self, timeout=120):
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
if self.call("wait", **{"for": "ready", "timeout_s": 5}).get("satisfied"):
|
||||
return True
|
||||
except (McpError, OSError):
|
||||
time.sleep(0.5)
|
||||
return False
|
||||
|
||||
|
||||
# ---- launching ------------------------------------------------------------------------------
|
||||
|
||||
def find_binary(explicit):
|
||||
candidates = [explicit] if explicit else []
|
||||
here = os.path.dirname(os.path.abspath(__file__))
|
||||
repo = os.path.dirname(os.path.dirname(here))
|
||||
candidates += [os.path.join(repo, "build", "src", "Release", "orca-slicer"),
|
||||
os.path.join(repo, "build", "package", "bin", "orca-slicer"),
|
||||
shutil.which("orca-slicer") or ""]
|
||||
for c in candidates:
|
||||
if c and os.path.exists(c):
|
||||
return os.path.abspath(c)
|
||||
sys.exit("orca-slicer not found; pass --bin")
|
||||
|
||||
|
||||
def seed_datadir(datadir, printer):
|
||||
vendor, model, nozzle, filament = printer
|
||||
os.makedirs(datadir, exist_ok=True)
|
||||
conf = os.path.join(datadir, "OrcaSlicer.conf")
|
||||
if os.path.exists(conf):
|
||||
return
|
||||
with open(conf, "w") as f:
|
||||
json.dump({"firstguide": {"finish": True},
|
||||
"models": [{"model": model, "nozzle_diameter": nozzle, "vendor": vendor}],
|
||||
"filaments": [filament],
|
||||
"presets": {"machine": f"{model} {nozzle} nozzle"},
|
||||
"app": {"check_for_updates": False, "show_daily_tips": False}}, f, indent=2)
|
||||
|
||||
|
||||
def start_xvfb(width, height):
|
||||
for display in range(90, 120):
|
||||
if not os.path.exists(f"/tmp/.X11-unix/X{display}") and not os.path.exists(f"/tmp/.X{display}-lock"):
|
||||
proc = subprocess.Popen(["Xvfb", f":{display}", "-screen", "0", f"{width}x{height}x24", "-nolisten", "tcp"],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
|
||||
time.sleep(0.7)
|
||||
return f":{display}", proc.pid
|
||||
sys.exit("no free X display for Xvfb")
|
||||
|
||||
|
||||
def launch(args):
|
||||
token = os.environ.get("ORCA_MCP_TOKEN") or base64.b16encode(os.urandom(32)).decode().lower()
|
||||
datadir = os.path.abspath(args.datadir or tempfile.mkdtemp(prefix="orca-mcp-"))
|
||||
printer = DEFAULT_PRINTER
|
||||
if args.printer:
|
||||
model, _, nozzle = args.printer.partition("@")
|
||||
printer = (args.vendor, model, nozzle or "0.4", args.filament or DEFAULT_PRINTER[3])
|
||||
seed_datadir(datadir, printer)
|
||||
|
||||
env = dict(os.environ, ORCA_MCP_TOKEN=token)
|
||||
xvfb_pid = None
|
||||
if args.xvfb:
|
||||
display, xvfb_pid = start_xvfb(args.width, args.height)
|
||||
env.pop("WAYLAND_DISPLAY", None)
|
||||
env.update(DISPLAY=display, GDK_BACKEND="x11")
|
||||
if sys.platform.startswith("linux"):
|
||||
# A static OpenSSL asks at startup which CA bundle to trust unless told.
|
||||
for bundle in ("/etc/ssl/certs/ca-certificates.crt", "/etc/pki/tls/certs/ca-bundle.crt"):
|
||||
if os.path.exists(bundle):
|
||||
env.setdefault("SSL_CERT_FILE", bundle)
|
||||
break
|
||||
cmd = [find_binary(args.bin), "--datadir", datadir, "--mcp", "--mcp-port", str(args.port)] + args.extra
|
||||
log = open(os.path.join(datadir, "mcp-launch.log"), "w")
|
||||
proc = subprocess.Popen(cmd, env=env, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
|
||||
|
||||
session = {"port": args.port, "token": token, "pid": proc.pid, "datadir": datadir,
|
||||
"xvfb_pid": xvfb_pid, "display": env.get("DISPLAY")}
|
||||
os.makedirs(os.path.dirname(SESSION_FILE), exist_ok=True)
|
||||
with open(SESSION_FILE, "w") as f:
|
||||
json.dump(session, f)
|
||||
os.chmod(SESSION_FILE, 0o600)
|
||||
|
||||
client = OrcaMcp(args.port, token)
|
||||
if not client.ready(args.timeout):
|
||||
sys.exit(f"OrcaSlicer did not become ready in {args.timeout} s; see {log.name}")
|
||||
url = f"http://127.0.0.1:{args.port}/mcp"
|
||||
print(json.dumps({**session, "url": url}, indent=2))
|
||||
if args.print_config:
|
||||
print(f"\nclaude mcp add --transport http orcaslicer {url} --header \"Authorization: Bearer {token}\"")
|
||||
print(f"codex mcp add orcaslicer --url {url} --bearer-token-env-var ORCA_MCP_TOKEN # export ORCA_MCP_TOKEN={token}")
|
||||
|
||||
|
||||
def session_client():
|
||||
try:
|
||||
with open(SESSION_FILE) as f:
|
||||
s = json.load(f)
|
||||
except OSError:
|
||||
sys.exit("no session; run launch first (or set ORCA_MCP_SESSION)")
|
||||
return OrcaMcp(s["port"], s["token"]), s
|
||||
|
||||
|
||||
def stop(_args):
|
||||
_, s = session_client()
|
||||
for key in ("pid", "xvfb_pid"):
|
||||
pid = s.get(key)
|
||||
if pid:
|
||||
try:
|
||||
os.killpg(pid, signal.SIGTERM)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
os.remove(SESSION_FILE)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
sub = ap.add_subparsers(dest="cmd", required=True)
|
||||
|
||||
p = sub.add_parser("launch", help="start OrcaSlicer with the MCP server")
|
||||
p.add_argument("--bin")
|
||||
p.add_argument("--datadir", help="data directory (default: a fresh temporary one)")
|
||||
p.add_argument("--port", type=int, default=DEFAULT_PORT)
|
||||
p.add_argument("--xvfb", action="store_true", help="run on a private Xvfb display (Linux)")
|
||||
p.add_argument("--width", type=int, default=1600)
|
||||
p.add_argument("--height", type=int, default=1000)
|
||||
p.add_argument("--printer", help="\"<model>@<nozzle>\" for a fresh datadir, e.g. \"Bambu Lab X1 Carbon@0.4\"")
|
||||
p.add_argument("--vendor", default="BBL")
|
||||
p.add_argument("--filament")
|
||||
p.add_argument("--timeout", type=int, default=120)
|
||||
p.add_argument("--print-config", action="store_true", help="print client setup commands")
|
||||
p.add_argument("extra", nargs="*", help="extra orca-slicer arguments after --")
|
||||
|
||||
sub.add_parser("stop", help="stop the launched instance")
|
||||
|
||||
p = sub.add_parser("call", help="call a tool and print its JSON result")
|
||||
p.add_argument("tool")
|
||||
p.add_argument("args", nargs="?", default="{}")
|
||||
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("screenshot", help="save a screenshot")
|
||||
p.add_argument("out")
|
||||
p.add_argument("--target", default="window")
|
||||
|
||||
p = sub.add_parser("run-script", help="run an MCP script in the launched instance")
|
||||
p.add_argument("script")
|
||||
p.add_argument("--out", help="output directory")
|
||||
|
||||
args = ap.parse_args()
|
||||
if args.cmd == "launch":
|
||||
return launch(args)
|
||||
if args.cmd == "stop":
|
||||
return stop(args)
|
||||
client, _ = session_client()
|
||||
try:
|
||||
if args.cmd == "call":
|
||||
result = client.call(args.tool, **json.loads(args.args))
|
||||
if args.wait:
|
||||
result = client.await_job(result)
|
||||
print(json.dumps(result, indent=2))
|
||||
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", ""))
|
||||
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))
|
||||
elif args.cmd == "run-script":
|
||||
a = {"path": os.path.abspath(args.script)}
|
||||
if args.out:
|
||||
a["out_dir"] = os.path.abspath(args.out)
|
||||
result = client.await_job(client.call("run_script", **a), timeout=3600)
|
||||
print(json.dumps(result, indent=2))
|
||||
return 0 if result.get("passed") else 1
|
||||
except McpError as e:
|
||||
print(f"error: {e}", file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in new issue
Block a user