Files
OrcaSlicer/src/slic3r/GUI/Mcp/UiInvoker.cpp
T
SoftFever d64e10f4dd Regroup the slicer's MCP commands and let each run from its arguments
Outside the Design tab an agent had 175 commands, 50 of them in the tool
list. There are now 118, named by what they act on (`object_`, `plate_`,
`preset_`, `filament_`, `plugin_` and so on), and 115 are listed. Each takes
its target and values in the call, acts on the selection when it names no
target and says what it acted on; an old name is refused. Printers and
system filaments install and uninstall, preferences read and write, plugins
enable, reload, uninstall and refresh, and objects reorder, with no dialog
to drive.

The Speed Dial keeps its 129 tiles under the same ids. Eight defects in the
rows these commands share with the menus are fixed. For a person: an object
row that cannot run says why instead of "Select an object first.", rows
that failed no longer claim success, Duplicate Plate can be undone, and
Refresh Plugins picked while a refresh runs now runs after it instead of
beside it.
2026-11-18 16:50:32 +08:00

226 lines
8.6 KiB
C++

#include "slic3r/GUI/CommandTypes.hpp"
#include "UiInvoker.hpp"
#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdint>
#include <exception>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <utility>
#include <vector>
namespace Slic3r { namespace GUI { namespace Mcp {
namespace {
enum class CallState { Queued, Running, Done, Abandoned };
struct UiCall
{
std::mutex mutex;
std::condition_variable cv;
CallState state = CallState::Queued;
nlohmann::json value;
std::string error;
nlohmann::json error_details;
};
} // namespace
// State shared with posted closures, which may run after the invoker is gone.
struct UiInvoker::Shared
{
std::function<GuardState()> guards_on_ui;
std::function<uint64_t()> generation;
std::function<nlohmann::json()> open_dialogs;
std::function<void(const std::string&, bool)> activity;
std::atomic<bool> stopped{false};
// UI-thread only: the calls currently executing, outermost first. More than one means a call is
// running inside another call's nested event loop.
std::vector<std::string> running_tools;
std::mutex waiters_mutex;
std::vector<std::weak_ptr<UiCall>> waiters;
};
UiInvoker::UiInvoker(UiDispatcher& dispatcher, std::function<GuardState()> guards_on_ui, std::function<uint64_t()> generation,
std::function<nlohmann::json()> open_dialogs, std::function<void(const std::string&, bool)> activity)
: m_shared(std::make_shared<Shared>()), m_dispatcher(dispatcher)
{
m_shared->guards_on_ui = std::move(guards_on_ui);
m_shared->generation = std::move(generation);
m_shared->open_dialogs = std::move(open_dialogs);
m_shared->activity = std::move(activity);
}
UiInvoker::~UiInvoker() { shutdown(); }
nlohmann::json UiInvoker::run(GuardClass guard, const std::string& tool, const std::function<nlohmann::json()>& fn,
std::chrono::milliseconds queue_timeout)
{
if (m_shared->stopped)
throw ToolFailure("OrcaSlicer is shutting down");
auto call = std::make_shared<UiCall>();
{
std::lock_guard<std::mutex> lock(m_shared->waiters_mutex);
auto& w = m_shared->waiters;
w.erase(std::remove_if(w.begin(), w.end(), [](const std::weak_ptr<UiCall>& c) { return c.expired(); }), w.end());
w.push_back(call);
}
const uint64_t generation = m_shared->generation ? m_shared->generation() : 0;
m_dispatcher.post([shared = m_shared, call, guard, tool, fn, generation]() {
{
std::lock_guard<std::mutex> lock(call->mutex);
if (call->state != CallState::Queued)
return; // abandoned by its caller
call->state = CallState::Running;
}
std::string error;
nlohmann::json details;
nlohmann::json value;
if (shared->stopped) {
error = "OrcaSlicer is shutting down";
} else {
const GuardState g = shared->guards_on_ui ? shared->guards_on_ui() : GuardState{};
if (g.closing)
error = "OrcaSlicer is shutting down";
else if (g.suspended)
error = "The UI is being recreated (language change); retry in a moment";
else if (shared->generation && shared->generation() != generation)
error = "The UI was recreated (language change) before the call ran; it was not run, so it is safe to retry";
else if (guard == GuardClass::Mutate && g.modal) {
error = "A modal dialog is open; answer it first (widget_list, dialog_answer)";
details = {{"dialogs", g.dialogs}};
} else if (guard == GuardClass::Mutate && !shared->running_tools.empty())
error = "Busy: " + shared->running_tools.front() + " is still running; only inspection and dialog tools can run now";
}
if (error.empty()) {
shared->running_tools.push_back(tool);
if (shared->activity)
shared->activity(tool, true);
try {
value = fn();
} catch (const ToolFailure& f) {
error = f.what();
details = f.details;
} catch (const std::exception& e) {
error = std::string("Internal error: ") + e.what();
} catch (...) {
error = "Internal error";
}
if (shared->activity)
shared->activity(tool, false);
shared->running_tools.pop_back();
}
{
std::lock_guard<std::mutex> lock(call->mutex);
call->state = CallState::Done;
call->value = std::move(value);
call->error = std::move(error);
call->error_details = std::move(details);
}
call->cv.notify_all();
});
std::unique_lock<std::mutex> lock(call->mutex);
call->cv.wait_for(lock, queue_timeout, [&] { return call->state != CallState::Queued || m_shared->stopped; });
if (call->state == CallState::Queued) {
call->state = CallState::Abandoned;
if (m_shared->stopped)
throw ToolFailure("OrcaSlicer is shutting down");
if (nlohmann::json dialogs = open_dialogs(); topmost_dialog_is_native(dialogs))
throw ToolFailure("A native dialog holds the UI thread until a person answers it, so the call was not run; register "
"dialog_auto_answer before the step that opens one",
{{"dialogs", std::move(dialogs)}});
throw ToolFailure("The UI thread is busy and did not run the call; it was not run, so it is safe to retry");
}
// Once running, the closure may use this thread's stack (fn's captures), so it is waited for
// even through shutdown; it ends when the UI thread unwinds out of it.
call->cv.wait(lock, [&] { return call->state == CallState::Done; });
if (!call->error.empty())
throw ToolFailure(call->error, call->error_details);
return std::move(call->value);
}
std::optional<UiInvoker::Probe> UiInvoker::probe(std::chrono::milliseconds timeout)
{
if (m_shared->stopped)
return std::nullopt;
struct ProbeCall
{
std::mutex mutex;
std::condition_variable cv;
bool done = false;
Probe probe;
};
auto call = std::make_shared<ProbeCall>();
m_dispatcher.post([shared = m_shared, call]() {
Probe p;
p.call_running = !shared->running_tools.empty();
if (p.call_running)
p.running_tool = shared->running_tools.front();
if (!shared->stopped && shared->guards_on_ui)
p.guards = shared->guards_on_ui();
{
std::lock_guard<std::mutex> lock(call->mutex);
call->probe = std::move(p);
call->done = true;
}
call->cv.notify_all();
});
std::unique_lock<std::mutex> lock(call->mutex);
if (!call->cv.wait_for(lock, timeout, [&] { return call->done; }))
return std::nullopt;
return call->probe;
}
void UiInvoker::require_mutate() const
{
// The calling closure is the last entry; anything before it is a call whose nested loop we
// are running in.
if (m_shared->guards_on_ui) {
const GuardState g = m_shared->guards_on_ui();
if (g.modal)
throw ToolFailure("A modal dialog is open; answer it first (widget_list, dialog_answer)", {{"dialogs", g.dialogs}});
}
if (m_shared->running_tools.size() > 1)
throw ToolFailure("Busy: " + m_shared->running_tools.front() +
" is still running; only inspection and dialog tools can run now");
}
void UiInvoker::shutdown()
{
if (m_shared->stopped.exchange(true))
return;
std::vector<std::weak_ptr<UiCall>> waiters;
{
std::lock_guard<std::mutex> lock(m_shared->waiters_mutex);
waiters.swap(m_shared->waiters);
}
for (auto& weak : waiters)
if (auto call = weak.lock()) {
{ std::lock_guard<std::mutex> lock(call->mutex); }
call->cv.notify_all();
}
}
bool UiInvoker::is_shutdown() const { return m_shared->stopped; }
nlohmann::json UiInvoker::open_dialogs() const { return m_shared->open_dialogs ? m_shared->open_dialogs() : nlohmann::json::array(); }
bool topmost_dialog_is_native(const nlohmann::json& dialogs)
{
return dialogs.is_array() && !dialogs.empty() && dialogs.back().is_object() && dialogs.back().value("native", false);
}
}}} // namespace Slic3r::GUI::Mcp