Fix hang when MCP clicks an open printer selector (#17913)
Some checks are pending
Build all / Linux x86_64 (push) Blocked by required conditions
Build all / build_macos_arch (push) Waiting to run
Build all / Look for build script changes (push) Waiting to run
Build all / Windows build script tests (push) Blocked by required conditions
Build all / build_linux (push) Waiting to run
Build all / Build Windows (push) Blocked by required conditions
Build all / Build macOS Universal (push) Blocked by required conditions
Build all / Linux aarch64 (push) Blocked by required conditions
Build all / Windows x64 (push) Blocked by required conditions
Build all / Windows arm64 (push) Blocked by required conditions
Build all / macOS arm64 (push) Blocked by required conditions
Build all / Slice check (Linux aarch64) (push) Blocked by required conditions
Build all / Publish Test Results (push) Blocked by required conditions
Build all / Flatpak (push) Waiting to run

# Description

When an MCP client clicked the printer selector on the Device or
Calibration tab while its printer list was already open, OrcaSlicer
froze at full CPU on macOS and Linux and had to be force-quit. A
person's mouse can't trigger it, because the open list takes the click
and closes before the selector sees it, but an MCP click goes straight
to the selector. That click now closes the list, as a person's click
does, and Orca's popups no longer hang on macOS and Linux when they are
asked to open while already open. The hung call's reply was misleading
as well: it said the call had not run and was safe to retry, although
its click had run. A call that has already acted now says it may have
done some or all of what was asked, and to check with `app_state` before
calling it again.

**Included:**
- **GUI:** the Device and Calibration printer selectors close their open
list on a click; `PopupWindow` ignores a second open on macOS and Linux.
- **MCP:** "not run, safe to retry" is reported only while no step of
the call has run.
- **Tests:** an automation test for the MCP reply and a slic3rutils test
for the popup.
- **Docs:** the MCP server design doc and the orca-wxwidgets skill's
popup pages.

A person's clicks behave as before on every platform, and Windows popup
behaviour is unchanged.

# Screenshots/Recordings/Graphs

<!--
> UI changes need before and after screenshots, on each platform you
tested.
> See what each kind of PR needs:
https://github.com/OrcaSlicer/OrcaSlicer/blob/main/CONTRIBUTING.md#what-each-kind-of-pr-needs
> For other changes, please attach images that can help explain them.
-->

## Tests

- Reproduced the hang on macOS over MCP with two `widget_click
{target:{class:"SideToolsPanel"}}` calls on the Device tab. With the
fix, repeated clicks open and close the list, each reply comes back in
under 100 ms, and the app stays idle and answers `app_state` afterwards.
- New tests: "a call says it was not run only until a step of it has
run" (automation) and "a popup never links its event handlers to
themselves and a second click on its control closes it" (slic3rutils).
With the popup guard disabled, the popup test fails and still runs to
the end instead of hanging.
- On this branch, macOS arm64 Release: the build passes, the automation
suite passes (186 test cases) and the slic3rutils `[Mcp]` tests pass
(508 test cases).
- Windows and Linux were not built or run; their code paths were checked
against wxWidgets' source.

<!--
> A guide for users on how to download the artifacts from this PR.
-->

[How to Download Pull Requests Artifacts for
Testing](https://www.orcaslicer.com/wiki/how_to_download_pr_artifacts)
This commit is contained in:
SoftFever 2026-11-26 20:51:59 +08:00 • committed by GitHub
parent 04603d6ccd
commit d42123d2f1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 304 additions and 29 deletions

View file

@ -58,7 +58,8 @@ Contents: [Rules](#rules) · [Why the library exists](#why-the-library-exists)
18. `ProgressBar` colours are painted unmapped and its colour-setter names are swapped; use `SetHeight` for thin bars.
→ §ProgressBar
19. Transient popups derive from `PopupWindow`; on MSW call `BindUnfocusEvent()` when the popup must close with the
frame. → §PopupWindow
frame. An opener that toggles the popup starts its click handler with `if (popup.CloseOnToggle()) return;`.
→ §PopupWindow
20. Children of a `LabeledStaticBox` are created with the box as parent; its label is fixed at `Create()`.
→ §StaticBox, LabeledStaticBox, StaticLine
21. Links are `HyperLink`, or a `Label` given `LB_HYPERLINK` through `SetWindowStyleFlag` (the constructor ignores it).
@ -929,7 +930,10 @@ Command events from controls inside the popup stop at the popup on MSW and macOS
`wxWS_EX_BLOCK_EVENTS` (`src/gtk/popupwin.cpp`; `references/events.md §5`); bind them on the popup or its children,
as `ComboBox` binds `drop`'s `wxEVT_COMBOBOX`, and don't let an ancestor's unfiltered handler also act on them. When a click on the opener both
dismisses and reopens the popup, gate the reopen on `DropDown::HasDismissLongTime()` or an equivalent timestamp.
Dismissal contracts, per-port mechanics and parenting rules: `references/popups-menus.md`.
On macOS and GTK, `Popup()` does nothing while the popup is shown, and first removes the handlers a `Hide()`
left; on MSW it is wx's `Popup()`. An opener whose next click closes the popup starts its click handler with
`if (popup.CloseOnToggle()) return;`. Dismissal contracts, per-port mechanics, parenting rules and these two
members: `references/popups-menus.md` §2, §5, §6.
## ProgressDialog, WebView and device-page composites

View file

@ -30,7 +30,9 @@ Contents: [Rules](#rules) · [1. Choosing the window kind](#1-choosing-the-windo
2. Size the popup (`SetSizerAndFit`/`SetSize`) **before** `Position()`, and pass the *anchor's* height as the
second argument: `Position(anchor->ClientToScreen({0,0}), {0, anchor->GetSize().y})`. (§3)
3. On macOS, anchor a hover-driven transient popup flush against its opener, with no pixel gap. (§3)
4. Never call `Popup()` on a popup that is already shown: guard with `if (!popup->IsShown())`. (§2)
4. Never call `Popup()` on a popup that is already shown: guard with `if (!popup->IsShown())`. On macOS and GTK
a repeat hangs a raw `wxPopupTransientWindow`; `PopupWindow::Popup()` ignores it there. On MSW a repeat moves
the focus into the popup again, the one case to call it on purpose (`DropDown::mouseReleased`). (§2, §6)
5. Destroy a popup with one `Destroy()`, typically from `wxEVT_SHOW` when it hides. Never `delete` it or
call `Destroy()` twice. (§2)
6. Command events from controls inside a popup stop at the popup (`wxWS_EX_BLOCK_EVENTS`) on MSW and macOS,
@ -41,7 +43,9 @@ Contents: [Rules](#rules) · [1. Choosing the window kind](#1-choosing-the-windo
`OnDismiss()`. (§2)
9. `ProcessLeftDown` is never called on MSW. Keep-open logic needs a per-platform path. (§2, §5)
10. A control that opens a popup on click must debounce reopening right after a dismissal
(`DropDown::HasDismissLongTime`), because the dismissing click reaches the opener on MSW and macOS. (§5)
(`DropDown::HasDismissLongTime`), because the dismissing click reaches the opener on MSW and macOS. An
opener whose next click closes its `PopupWindow` starts its handler with `if (popup.CloseOnToggle()) return;`,
so a click that reaches it while the popup is shown closes the popup instead of reopening it. (§5, §6)
11. On MSW, a popup that must close when the frame deactivates or minimizes calls `BindUnfocusEvent()`. On
macOS, nothing dismisses a popup on app deactivation. (§5, §6)
12. On macOS, re-verify the cursor with `GetClientRect().Contains(ScreenToClient(wxGetMousePosition()))`
@ -128,11 +132,16 @@ Contents: [Rules](#rules) · [1. Choosing the window kind](#1-choosing-the-windo
(`src/common/popupcmn.cpp:536-543`, inside `#ifndef __WXMSW__`). `src/msw/popupwin.cpp` has no click
handler. An override that returns true does not keep the popup open on Windows (§5).
- **`Popup()` must not run on a shown popup (non-MSW).** `Popup()` pushes `m_handlerPopup` onto `m_child` and
`m_handlerFocus` onto the focus window every time (`popupcmn.cpp:308-332`). The "still in use" asserts are
compiled out in Orca. A second push links the handler chain into a cycle, and the next event that no handler
`m_handlerFocus` onto the focus window every time (`popupcmn.cpp:308-332`). The "still in use" asserts there
and `PushEventHandler`'s "shouldn't be part of a wxEvtHandler chain" assert (`src/common/wincmn.cpp:1414-1416`)
are compiled out in Orca. A second push links the handler chain into a cycle, and the next event that no handler
in the cycle consumes loops forever in `wxEvtHandler::DoTryChain` (`src/common/event.cpp:1591-1640`), so the
app hangs. On MSW, `Popup()` is just `Show()` plus an optional `SetFocus` (`src/msw/popupwin.cpp:184-193`), so
a repeat is harmless there.
- **Only `Dismiss()` removes the handlers.** `PopHandlers()` removes them and clears `m_child` and `m_focus`; wx
calls it from `Dismiss()` and from the destructor (`popupcmn.cpp:246-284`, 432-436). `Hide()` (`Show(false)`,
335-430) leaves them pushed, so a `Hide()` followed by `Popup()` builds the same cycle as a repeated `Popup()`.
`PopupWindow::Popup` guards both cases (§6).
- **`Destroy()` is deferred.** The popup goes into `wxPendingDelete`, and a second `Destroy()` fails a silent
`wxCHECK` "Shouldn't destroy the popup twice." (`popupcmn.cpp:209-221`). The comment explains why: "The popup
window can be deleted at any moment, even while some events are still being processed for it".
@ -170,7 +179,9 @@ A popup created per open is a child of its parent until it is destroyed. Destroy
**Pitfalls.**
- **Rule:** Guard every `Popup()` call with `IsShown()`.
**Why:** On non-MSW ports the second push creates a cycle in the handler chain and the app hangs on the next
unconsumed event. MSW is unaffected, which hides the bug from Windows testing.
unconsumed event. MSW is unaffected, which hides the bug from Windows testing. `PopupWindow::Popup()` ignores a
repeat on macOS and GTK, so a missing guard on a `PopupWindow` no longer hangs, but a raw
`wxPopupTransientWindow` (or a `wxTipWindow`) still does, and on MSW the repeat still moves the focus.
```cpp
// Wrong: re-pops on every motion or click
void on_motion(wxMouseEvent&) { m_popup->Popup(); }
@ -178,8 +189,8 @@ A popup created per open is a child of its parent until it is destroyed. Destroy
void on_motion(wxMouseEvent&) { if (!m_popup->IsShown()) m_popup->Popup(); }
```
Cite: `DropDown::mouseMove` (`if (!drop.IsShown()) drop.Popup(&drop)`), `SearchObjectDialog::Popup`
(`if (m_is_dismissing || this->IsShown()) return;`). `Button::OnParentMotion` may re-pop its `wxTipWindow` on
every move only because `Button::EnableTooltipEvenDisabled` is MSW-only.
(`if (m_is_dismissing || this->IsShown()) return;`), `PopupWindow::Popup`. `Button::OnParentMotion` may re-pop
its `wxTipWindow` on every move only because `Button::EnableTooltipEvenDisabled` is MSW-only.
- **Rule:** Veto in `Dismiss()`. In `OnDismiss()`, act only if the popup really closed.
**Why:** `DismissAndNotify` calls `OnDismiss` unconditionally after `Dismiss`.
```cpp
@ -434,6 +445,21 @@ geometry-based dismissal checks must use focus instead (§8).
```
Cite: `DropDown::HasDismissLongTime` (≥20 ms after `OnDismiss`, used by `ComboBox::mouseDown`),
`StatusPanel::on_switch_speed` (`speed_dismiss_time`, 200 ms).
- **Rule:** An opener whose next click closes its popup closes a shown popup with `CloseOnToggle()` before it
does anything else.
**Why:** A click can reach the opener while the popup is still shown. A person's click never does on macOS or
GTK, where the popup's capture or grab takes the click and closes the popup first. A mouse event sent straight
to the opener does, such as the MCP server's `widget_click`, and calling `Popup()` from it would re-pop the
shown popup. On MSW a person's click does too, before the deferred deactivation closes a
`wxPU_CONTAINS_CONTROLS` popup. wx's own combo control toggles the same way: `wxComboCtrlBase::OnButtonClick`
hides a shown popup and opens a hidden one (`src/common/combocmn.cpp:2060-2079`).
```cpp
// Wrong: a click that arrives while the popup is shown re-pops it
void on_opener_click(wxMouseEvent&) { if (!in_debounce()) m_popup.Popup(); }
// Right
void on_opener_click(wxMouseEvent&) { if (m_popup.CloseOnToggle()) return; if (!in_debounce()) m_popup.Popup(); }
```
Cite: `MonitorPanel::on_printer_clicked`, `CalibrationPanel::on_printer_clicked`.
- **Rule:** Don't rely on `ProcessLeftDown` to keep a popup open on Windows.
**Why:** MSW never calls it.
```cpp
@ -456,6 +482,8 @@ class PopupWindow : public wxPopupTransientWindow {
public:
PopupWindow(wxWindow* parent, int style = wxBORDER_NONE);
bool Create(wxWindow* parent, int flags = wxBORDER_NONE);
void Popup(wxWindow* focus = nullptr) override; // macOS/GTK: no-op while shown (§2)
bool CloseOnToggle(); // for an opener that toggles it (§5)
#ifdef __WXGTK__
bool Show(bool show = true) override; // hides GTK tooltips first on Wayland (§9)
#endif
@ -476,6 +504,20 @@ What it adds per platform:
| macOS | Only with `wxPU_CONTAINS_CONTROLS`: `OnMouseEvent2`, bound on the popup for `LEFT_DOWN/UP/DCLICK`, `MOTION` and `MOUSEWHEEL`, hit-tests the children (static `HitTest`) and re-dispatches the event to the deepest child under the cursor with `ProcessEventLocally`. On `MOTION` it synthesizes `ENTER`/`LEAVE` for the hovered target. This compensates for the capture rerouting in §5. |
Details [source] (`Widgets/PopupWindow.cpp`).
- `Popup()`: on macOS and GTK it returns at once while `IsShown()`, and when `m_child` or `m_focus` is still set
(a `Hide()` without `Dismiss()` left the handlers pushed) it calls `PopHandlers()` before wx's `Popup()` (§2).
`m_child`, `m_focus` and `PopHandlers()` are protected members of wx's non-MSW `wxPopupTransientWindow`
(`include/wx/popupwin.h:178-193`). The test wx's destructor uses, `m_handlerPopup->GetNextHandler()`, does not
compile outside wx: `wxPopupWindowHandler` is only forward-declared there (`include/wx/popupwin.h:154`). On MSW
it is wx's `Popup()`, unchanged: a repeat there moves the focus into the popup, which `DropDown::mouseReleased`
relies on to focus a sub-list that hovering already showed. An override of `Popup()` keeps the guard only if it
ends in `PopupWindow::Popup(focus)`, as `DropDown::Popup` and `SearchDialog::Popup` do.
- `CloseOnToggle()` returns false while the popup is hidden. While it is shown it returns true, and on macOS and
GTK it first closes the popup with `DismissAndNotify()`, so `OnDismiss()` runs as for a click outside. On MSW it
only returns true. A person's click that reached the opener also deactivated a `wxPU_CONTAINS_CONTROLS` popup,
and wx's deferred `DismissOnDeactivate` calls `DismissAndNotify()` without checking `IsShown()`
(`src/msw/popupwin.cpp:200-216`), so closing it here would run `OnDismiss()` twice. A click sent straight to the
opener deactivates nothing, so on MSW it leaves the popup open.
- `GetTopParent(w)` returns the first *strict* ancestor of `w` that is a `wxNonOwnedWindow`, or the root if there
is none. `Create` starts from `parent`, while `BindUnfocusEvent` and the destructor start from the popup. When
`parent` is itself a top-level window with a parent (a dialog), `Create` therefore binds the dialog's parent

View file

@ -165,9 +165,11 @@ using the app afterwards never has a prompt answered for them.
## Threading
Tool handlers never run on the UI thread. Anything that touches wx runs in a closure that `ToolContext::run_ui()`
posts through `UiInvoker` and waits for; a closure not started within 10 s is abandoned, and the call says it is safe
to retry. After a change a tool makes one more round trip (`settle()`), so the events the change queued are handled
before the reply. A person's pick is the one call that runs on the UI thread itself, in place.
posts through `UiInvoker` and waits for. A closure not started within 10 s is abandoned, and one that reaches a UI being
rebuilt is refused; either way the call says it is safe to retry, unless a step of it already ran (one of its
closures, or a call it made). The call then says part of it ran and that it may have done some or all of what was
asked, since a click that hangs the app has already run by the time the next closure waits. After a change a tool
makes one more round trip (`settle()`), so the events the change queued are handled before the reply. A person's pick is the one call that runs on the UI thread itself, in place.
**Guards.** The guard is checked in the closure, on the UI thread, since the app can change between posting and
running. mcp-tools.md (When a command may run) lists the commands of each.

View file

@ -691,6 +691,8 @@ bool CalibrationPanel::Show(bool show) {
void CalibrationPanel::on_printer_clicked(wxMouseEvent& event)
{
if (m_mobjectlist_popup.CloseOnToggle())
return;
auto mouse_pos = ClientToScreen(event.GetPosition());
wxPoint rect = m_side_tools->ClientToScreen(wxPoint(0, 0));

View file

@ -9,6 +9,7 @@
#include "slic3r/GUI/CommandTypes.hpp"
#include <algorithm>
#include <atomic>
#include <charconv>
#include <chrono>
#include <cstddef>
@ -80,13 +81,9 @@ public:
nlohmann::json run_ui(const std::function<nlohmann::json()>& fn) override
{
if (m_def.guard == GuardClass::Inspect)
return m_core.ui().run(m_def.guard, m_def.key, fn);
return run_step(m_def.guard, false, fn);
const bool admit = m_def.guard == GuardClass::Mutate && !m_def.allowed_during_operation;
return m_core.ui().run(m_def.guard, m_def.key, [&]() -> nlohmann::json {
// Admission again on the UI thread, where operations and worker jobs start: a call admitted
// before one began must not change the project under it.
if (admit)
m_core.admit(m_job);
return run_step(m_def.guard, admit, [&]() -> nlohmann::json {
if (!m_core.worker_busy())
m_saw_idle = true;
nlohmann::json out;
@ -104,7 +101,7 @@ public:
{
// A job the call's change queued for later (a toolbar event, a render) starts between its
// closures; the next one the call makes claims it.
return m_core.ui().run(GuardClass::Inspect, m_def.key, [&]() -> nlohmann::json {
return run_step(GuardClass::Inspect, false, [&]() -> nlohmann::json {
nlohmann::json out = fn();
claim_worker();
return out;
@ -128,6 +125,8 @@ public:
ToolResult call_child(const std::string& tool, const nlohmann::json& raw_args) override
{
// The child may change things whatever it replies. A script's threads call this too.
m_ran.store(true, std::memory_order_relaxed);
// An inline caller has no job of its own; its children are rooted at its parent.
return m_core.call_child_named(tool, raw_args, m_job.empty() ? m_parent : m_job, m_plugin);
}
@ -169,6 +168,35 @@ private:
m_core.claim_worker(m_job);
}
// Runs one of the call's closures on the UI thread. UiInvoker's "not run, safe to retry" for a closure the UI thread
// never ran holds for the call only until a step of it has run: one of its closures, Inspect ones included (a
// screenshot scrolls before it captures), or a call it made. After that the call may have done anything up to
// that step: a click that hangs the app has run by the time the next closure waits for the UI thread.
nlohmann::json run_step(GuardClass guard, bool admit, const std::function<nlohmann::json()>& fn)
{
try {
return m_core.ui().run(
guard, m_def.key,
[&]() -> nlohmann::json {
// Admission again on the UI thread, where operations and worker jobs start: a call admitted
// before one began must not change the project under it.
if (admit)
m_core.admit(m_job);
m_ran.store(true, std::memory_order_relaxed);
return fn();
},
m_core.timing().ui_queue_timeout);
} catch (const UiCallNotRun& f) {
if (!m_ran.load(std::memory_order_relaxed))
throw;
throw ToolFailure("Part of this call already ran, but the UI thread then did not run its next step (it stayed busy, "
"a native dialog held it, or the UI was being rebuilt), so the call could not finish or read back "
"its result. It may have done some or all of what was asked: check with app_state before calling "
"it again",
f.details);
}
}
McpCore& m_core;
const NativeCommand& m_def;
std::string m_job;
@ -179,6 +207,9 @@ private:
const std::vector<CallObserver*>& m_observers;
uint64_t m_call;
bool m_saw_idle = false; // UI thread
// Whether a step of the call has run (run_step()). Set on the UI thread and, through call_child(), on the call's
// thread and a script's threads; it publishes nothing else, so relaxed access is enough.
std::atomic<bool> m_ran{false};
};
ToolResult invoke(const NativeCommand& def, const nlohmann::json& args, ToolContext& ctx)

View file

@ -36,6 +36,8 @@ struct CoreTiming
// Above zero, the longest any command's reply budget runs: for tests that need a call to outlive its
// budget without waiting out the command's own (ORCA_MCP_REPLY_BUDGET_MS). Zero leaves each budget as is.
std::chrono::milliseconds reply_budget_cap{0};
// How long a call's UI closure waits for the UI thread to pick it up before it is abandoned (UiInvoker::run()).
std::chrono::milliseconds ui_queue_timeout{std::chrono::seconds(10)};
};
// The reply budget cap that ORCA_MCP_REPLY_BUDGET_MS's `value` sets: a whole positive number of milliseconds,
@ -130,6 +132,7 @@ public:
bool drain(std::chrono::milliseconds timeout);
const CommandCatalog& catalog() const { return m_catalog; }
const CoreTiming& timing() const { return m_timing; }
UiInvoker& ui() { return m_ui; }
JobRegistry& jobs() { return m_jobs; }
// The runtime that owns the core, which ToolContext::runtime() of its calls returns; nullptr for a core

View file

@ -29,6 +29,7 @@ struct UiCall
nlohmann::json value;
std::string error;
nlohmann::json error_details;
bool not_run = false; // a guard refused before the closure did anything, and retrying is safe
};
} // namespace
@ -87,17 +88,20 @@ nlohmann::json UiInvoker::run(GuardClass guard, const std::string& tool, const s
std::string error;
nlohmann::json details;
nlohmann::json value;
bool not_run = false;
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) {
else if (g.suspended) {
error = "The UI is being recreated (language change); retry in a moment";
not_run = true;
} 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";
not_run = true;
} else if (guard == GuardClass::Mutate && g.modal) {
error = "A modal dialog is open; answer it first (widget_list, dialog_answer)";
details = {{"dialogs", shared->open_dialogs ? shared->open_dialogs() : g.dialogs}};
} else if (guard == GuardClass::Mutate && !shared->running_tools.empty())
@ -127,6 +131,7 @@ nlohmann::json UiInvoker::run(GuardClass guard, const std::string& tool, const s
call->value = std::move(value);
call->error = std::move(error);
call->error_details = std::move(details);
call->not_run = not_run;
}
call->cv.notify_all();
});
@ -138,14 +143,16 @@ nlohmann::json UiInvoker::run(GuardClass guard, const std::string& tool, const s
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");
throw UiCallNotRun("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 UiCallNotRun("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->not_run)
throw UiCallNotRun(call->error, call->error_details);
if (!call->error.empty())
throw ToolFailure(call->error, call->error_details);
return std::move(call->value);

View file

@ -36,6 +36,14 @@ struct GuardState
bool top_closing = false;
};
// What UiInvoker::run() throws when the UI thread never ran its closure: the UI thread did not pick it up in time,
// or the UI was being rebuilt. Its message tells the caller that retrying is safe, which holds for the call only
// until a step of the call has run.
struct UiCallNotRun : ToolFailure
{
using ToolFailure::ToolFailure;
};
// Runs closures on the UI thread for tool handlers, which run on other threads. A closure re-checks
// the guards on the UI thread before doing anything, because the app can change between posting
// and running (a modal can open, the app can start closing, the UI can be rebuilt). A caller gives
@ -58,7 +66,8 @@ public:
// Runs `fn` on the UI thread under `guard` and returns its value. Throws ToolFailure when a
// guard refuses, when the UI thread does not pick the closure up within `queue_timeout`
// (the closure is then abandoned and never runs; the failure names the native dialog holding
// the UI thread, if that is why), or on shutdown. `tool` names the caller in busy messages.
// the UI thread, if that is why), or on shutdown. That failure, and the one for a closure that
// reaches a UI being rebuilt, is a UiCallNotRun. `tool` names the caller in busy messages.
nlohmann::json run(GuardClass guard, const std::string& tool, const std::function<nlohmann::json()>& fn,
std::chrono::milliseconds queue_timeout = std::chrono::seconds(10));

View file

@ -348,6 +348,8 @@ void MonitorPanel::on_machine_selected(MachineObject* obj)
void MonitorPanel::on_printer_clicked(wxMouseEvent &event)
{
if (m_select_machine.CloseOnToggle())
return;
auto mouse_pos = ClientToScreen(event.GetPosition());
wxPoint rect = m_side_tools->ClientToScreen(wxPoint(0, 0));

View file

@ -33,6 +33,30 @@ bool PopupWindow::Create(wxWindow *parent, int style)
return true;
}
void PopupWindow::Popup(wxWindow *focus)
{
// Windows pushes no handlers, and its Popup() on a shown popup moves the focus into it, which a grouped
// DropDown relies on when it opens a sub-list that hovering already showed.
#ifndef __WXMSW__
if (IsShown())
return;
// Popup() sets these as it pushes the handlers, and only PopHandlers() (Dismiss()) clears them.
if (m_child != nullptr || m_focus != nullptr)
PopHandlers();
#endif
wxPopupTransientWindow::Popup(focus);
}
bool PopupWindow::CloseOnToggle()
{
if (!IsShown())
return false;
#ifndef __WXMSW__
DismissAndNotify();
#endif
return true;
}
PopupWindow::~PopupWindow()
{
#ifdef __WXGTK__

View file

@ -14,6 +14,19 @@ public:
PopupWindow(wxWindow *parent, int style = wxBORDER_NONE) { Create(parent, style); }
bool Create(wxWindow *parent, int flags = wxBORDER_NONE);
// On macOS and GTK wx's Popup() pushes the popup's event handlers each time, and pushing them again while
// they are in place links each one to itself, so the next event sent through it never returns and the app
// hangs. There this does nothing while the popup is shown, and first removes the handlers a Hide() left in
// place. On Windows it is wx's Popup().
void Popup(wxWindow *focus = nullptr) override;
// For a control that opens this popup and closes it with its next click: false while the popup is
// hidden; true while it is shown, closing it as a click outside it does (Dismiss(), then OnDismiss()).
// On macOS and GTK a person's click never gets here with the popup shown, since the popup's mouse
// capture (a pointer grab on GTK) takes the click and closes it first; the MCP server's clicks do, as
// they go straight to the control. On Windows a person's click gets here with a popup that hosts
// controls (wxPU_CONTAINS_CONTROLS) still shown, and wx then closes it from the deactivation the click
// caused, so there this only reports that it is shown; any other popup is already closed by then.
bool CloseOnToggle();
#ifdef __WXGTK__
bool Show(bool show = true) override;
#endif

View file

@ -134,6 +134,8 @@ TEST_CASE("a UI call that is never picked up is abandoned and never runs", "[Mcp
CHECK(error.find("safe to retry") != std::string::npos);
ui.drain();
CHECK_FALSE(ran);
CHECK_THROWS_AS(invoker.run(GuardClass::Mutate, "t", [] { return json(); }, 100ms), UiCallNotRun);
ui.drain();
}
TEST_CASE("a UI call that times out behind a native dialog names the dialog", "[Mcp]")
@ -1241,6 +1243,76 @@ TEST_CASE("a closure queued before a UI rebuild does not run after it", "[Mcp]")
CHECK_FALSE(ran);
}
TEST_CASE("a call says it was not run only until a step of it has run", "[Mcp]")
{
std::atomic<bool> release{false};
Harness h;
SetOnExit releaser{release};
h.timing.ui_queue_timeout = 200ms;
// From here on the UI thread is busy for good, as after a click that hangs the app.
const auto hold_ui = [&] {
h.ui.post([&] {
while (!release)
std::this_thread::sleep_for(5ms);
});
};
const auto step = [&] {
hold_ui();
return json();
};
h.registry.add(tool("click_then_read", GuardClass::Mutate, [&](const json&, ToolContext& ctx) {
ctx.run_ui(step);
return ToolResult::ok(ctx.observe_ui([] { return json("read"); }));
}));
h.registry.add(tool("read_then_click", GuardClass::Mutate, [&](const json&, ToolContext& ctx) {
ctx.observe_ui(step);
return ToolResult::ok(ctx.run_ui([] { return json("clicked"); }));
}));
h.registry.add(tool("scroll_then_capture", GuardClass::Inspect, [&](const json&, ToolContext& ctx) {
ctx.run_ui(step);
return ToolResult::ok(ctx.run_ui([] { return json("captured"); }));
}));
h.registry.add(tool("noop", GuardClass::Inspect, [](const json&, ToolContext&) { return ToolResult::ok(); }));
h.registry.add(tool("child_then_edit", GuardClass::Mutate, [&](const json&, ToolContext& ctx) {
ctx.call_child("noop", json::object());
hold_ui();
return ToolResult::ok(ctx.run_ui([] { return json("edited"); }));
}));
h.registry.add(tool("edit", GuardClass::Mutate, [](const json&, ToolContext& ctx) {
return ToolResult::ok(ctx.run_ui([] { return json("edited"); }));
}));
h.start();
SECTION("a closure the UI thread never ran, after a step that ran")
{
const std::string called =
GENERATE(as<std::string>{}, "click_then_read", "read_then_click", "scroll_then_capture", "child_then_edit");
CAPTURE(called);
const ToolResult r = h.call(called);
CHECK(r.is_error);
CHECK_THAT(r.message, ContainsSubstring("Part of this call already ran"));
CHECK_THAT(r.message, !ContainsSubstring("safe to retry"));
}
SECTION("the call's first closure, never picked up")
{
hold_ui();
const ToolResult r = h.call("edit");
CHECK(r.is_error);
CHECK_THAT(r.message, ContainsSubstring("safe to retry"));
}
SECTION("the call's first closure, refused while the UI is being rebuilt")
{
{
std::lock_guard<std::mutex> lock(h.guards_mutex);
h.guards.suspended = true;
}
const ToolResult r = h.call("edit");
CHECK(r.is_error);
CHECK_THAT(r.message, ContainsSubstring("being recreated"));
CHECK_THAT(r.message, !ContainsSubstring("Part of this call"));
}
}
TEST_CASE("operation admission is checked again when a mutate call reaches the UI thread", "[Mcp]")
{
Harness h;

View file

@ -30,6 +30,7 @@
#include "slic3r/GUI/Mcp/WindowNames.hpp"
#include "slic3r/GUI/Mcp/UiInspector.hpp"
#include "slic3r/GUI/Mcp/UiRefs.hpp"
#include "slic3r/GUI/Widgets/PopupWindow.hpp"
#include <nlohmann/json.hpp>
@ -673,3 +674,66 @@ TEST_CASE("a window inside a pane hidden from automation is hidden, and the pane
CHECK_FALSE(hidden_from_automation(&frame));
}
}
TEST_CASE("a popup never links its event handlers to themselves and a second click on its control closes it", "[Mcp]")
{
#if defined(__linux__)
if (!std::getenv("DISPLAY") && !std::getenv("WAYLAND_DISPLAY"))
SKIP("This test needs a display (for example, xvfb-run).");
#endif
if (wxTheApp == nullptr)
wxApp::SetInstance(new wxApp);
wxInitializer init;
REQUIRE(init.IsOk());
{
// The list a printer selector opens: wx pushes the popup's event handlers onto the popup and its only child.
struct List : PopupWindow
{
using PopupWindow::PopupWindow;
int dismissed = 0;
void OnDismiss() override { ++dismissed; }
};
wxFrame frame(nullptr, wxID_ANY, "main");
auto* list = new List(&frame);
auto* row = new wxPanel(list);
// A handler linked to itself fails the check, and is linked back as one push leaves it, so the next event
// (wxGTK sends one from Hide()) and the teardown don't loop through it.
const auto none_to_self = [&] {
bool none = true;
for (wxWindow* w : {static_cast<wxWindow*>(list), static_cast<wxWindow*>(row)})
if (wxEvtHandler* h = w->GetEventHandler(); h->GetNextHandler() == h) {
h->SetNextHandler(w);
h->SetPreviousHandler(nullptr);
none = false;
}
return none;
};
// Opened again while shown, as a click that reaches the selector directly (an MCP click) opens it.
list->Popup();
REQUIRE(list->IsShown());
list->Popup();
CHECK(none_to_self());
// Opened again after Hide(), which leaves the handlers pushed.
list->Hide();
#ifndef __WXMSW__
CHECK(row->GetEventHandler() != row);
#endif
list->Popup();
CHECK(none_to_self());
// The selector's click while the list is shown closes it, through OnDismiss(), and doesn't open it. On
// Windows wx closes it from the deactivation a person's click caused, so it is still shown here.
CHECK(list->CloseOnToggle());
#ifdef __WXMSW__
CHECK(list->IsShown());
CHECK(list->dismissed == 0);
list->Dismiss();
#else
CHECK_FALSE(list->IsShown());
CHECK(list->dismissed == 1);
#endif
CHECK_FALSE(list->CloseOnToggle());
}
}