diff --git a/docs/HLSD/mcp-server.md b/docs/HLSD/mcp-server.md index 1504513ed0..f9e78308ea 100644 --- a/docs/HLSD/mcp-server.md +++ b/docs/HLSD/mcp-server.md @@ -1609,17 +1609,29 @@ anything changes, so a refused call leaves the window as it was: at least one ch and position, no `maximized` or `minimized` with a size or position (the system sets those), a state only when the title bar offers it (always for the main window, else `wxMAXIMIZE_BOX` and `wxMINIMIZE_BOX`), a modal dialog never minimized, since the app would stay blocked with nothing showing, and no position on -Wayland. One UI closure then applies it in a fixed order: a size or position restores a maximized or -minimized window first (`restore_normal()`: out of the minimized state, then out of the maximized one, +Wayland. A UI closure then applies it in a fixed order. A size or position restores a maximized or +minimized window first (`restore_window()`): out of the minimized state, then out of the maximized one, since `Restore()` presents, so raises, the window on GTK and brings a window minimized while maximized -back maximized on Windows; it un-minimizes only a minimized window, as GTK raises a mapped X11 window it -un-minimizes, and un-maximizes only a maximized one except on GTK, as Windows activates a normal window -it un-maximizes, while GTK's `IsMaximized()` can lag a maximize on its way), then the size, held to the -window's minimum and maximum (what its sizer needs), the position (`wxSIZE_ALLOW_MINUS_ONE`: -1 is a -place on a screen left of or above the primary one), the state and the raise. A window without a resize border is resized all the same. Sizes and positions are -wx window coordinates, as `list_windows` and `get_app_state` report them: physical pixels on Windows, -points on macOS, logical pixels on GTK. The argument normalizer reads `list_windows`'s flat `x`/`y` and -`width`/`height` as `position` and `size`. +back maximized on Windows. It touches only the state the window is in, as GTK raises a mapped X11 window +it un-minimizes, Windows activates a normal window it un-maximizes, and a Wayland compositor answers an +un-maximize with the window's current size, which replaces a size asked for right after. GTK reports +the restore once the window manager or compositor has applied it (X11, Wayland), so there the call polls +until the window reads normal before it goes on, since a size given before that would be lost, or worked +out from the maximized window's decorations. Then come the size, held to the window's minimum and maximum (what its sizer +needs), the position (`wxSIZE_ALLOW_MINUS_ONE`: -1 is a place on a screen left of or above the primary +one), the state and the raise. A window without a resize border is resized all the same. Sizes and +positions are wx window coordinates, as `list_windows` and `get_app_state` report them: physical pixels +on Windows, points on macOS, logical pixels on GTK. The argument normalizer reads `list_windows`'s flat +`x`/`y` and `width`/`height` as `position` and `size`. + +On Wayland a size is the window the compositor shows, which a window screenshot captures +(`window_size()`). GTK decorates OrcaSlicer's main window itself, as the window draws its own title bar, +and keeps margins around it for its shadow and resize border (45 pixels a side with Breeze). wx counts +those margins in the window's size after some allocations and not after others. It also adds decoration +sizes it reads only where GTK decorates a window the compositor would rather not +(`gdk_wayland_display_prefers_ssd()` false, as on Mutter), and counts none on KWin. So the size is read +from GTK's allocation less the margins, and `resize_window()` gives wx the size plus the decorations wx +takes off again, less a title bar GTK shows. A window manager may apply a request later (X11), animate it (macOS) or change it, so the call polls every 50 ms (`poll_until()`, which returns null on timeout or cancellation instead of throwing) until two readings of the screen @@ -1628,8 +1640,9 @@ main window it also waits, asking for a frame each poll, until the shown 3D view the camera's viewport, which only a frame sets, must match the canvas, or a `set_view` fit or a `screen_rect` that follows would use the old size. The Design tab swaps its camera into the plater's slot while it is shown, so the one check covers every 3D view. A minimized window and a hidden canvas draw no -frames, so neither is waited for. After 3 s the call replies with what it read and a note. A call -cancelled during the wait fails, and so does one whose window closes, saying the request was applied. +frames, so neither is waited for. After 3 s (5 s for a minimize on Wayland, `state_change_timeout()`) +the call replies with what it read and a note. A call cancelled during the wait fails, and so does one +whose window closes, saying the request was applied. The reply is the window's `list_windows` entry, from the same `window_entry()` with a new ref, in `set_window`'s own form: `title`, `kind`, `ref`, `size`, `position` (not on Wayland), `state` and @@ -1643,14 +1656,38 @@ whether it is primary, so an agent can choose a position. On Windows a change takes effect at once, but `raise` may only flash the taskbar button while another app has the focus, since the OS locks the foreground; `active` says which happened. On macOS `maximized` is -the window's zoomed state. Under X11 the window manager may adjust a request, and under Xvfb with no -window manager maximizing does nothing: the reply says `normal` with a note. Wayland neither reports nor -accepts positions, so a call with `position` is refused there, pointing to X11. Size, maximize and normal -work there. Minimize is taken, but GTK on Wayland never reports a minimized window, and Wayland gives an -app no way to restore one, so the wait asks neither for the state nor for a frame, and the reply, whose -`state` can't show the minimize, has a note saying so and no `state` under `adjusted`. The call -remembers the windows it minimized there (`wayland_minimized()`), and a later `normal` for one, which -can't bring it back, says the same. +the window's zoomed state. Under X11 the window manager may adjust a request. + +With no window manager, as under a bare Xvfb, the app does the window manager's part +(`WindowControl.cpp`); every EWMH window manager lists `_NET_WM_STATE` among the hints it takes, so its +absence says none runs. `maximized` remembers the normal rect, adds the maximized atoms to the window's +`_NET_WM_STATE`, which GDK reads back, so `IsMaximized()` follows, and fills the work area of the window's +display. `normal` takes the atoms out and puts the rect back. `minimized` unmaps the window, which GDK +reports as minimized, and wx's `Iconize(false)` maps it again. Mapping a window raises it, and nothing +keeps a dialog above the window it belongs to, while an X11 capture reads the screen. So after a restore +and after a `raise`, the windows transient for the window are raised over it, in the order they were +created. + +Wayland has no request to place a window or to read where it is, and no portal offers one; only +compositor-private interfaces do (KWin's scripting, sway's IPC), and GNOME has none. So a call with +`position` is refused there, naming `GDK_BACKEND=x11`, under which the app runs through XWayland and every +field works. `list_windows`, `set_window` and `get_app_state.window` leave positions out. Size, +maximize and normal work. GTK never reports a minimized window, but the compositor's `suspended` state +(xdg-shell 6) reaches it as a fully obscured visibility notify, which emission hooks installed when the +service starts record on the window (`track_window_states()`). Hidden is not minimized: KWin hides a +minimized window at once, but also one on another virtual desktop and every window while the screens are +off, and Mutter hides any window it has not shown for 3 s. So a window reads minimized while it is hidden +and a minimize from `set_window` stands, which ends once the window shows, takes the focus or closes. A +minimize the person makes from the desktop reads `normal`, since nothing tells the app of it. The wait for +a minimize lasts 5 s on Wayland, as Mutter hides the window 3 s after it, and sway never minimizes a +window. + +Wayland gives an app no request to un-minimize a window, only to activate it (`gtk_window_present()` +over xdg-activation), which `normal` and `raise` do. The compositor grants it only while the app may take +the focus. KWin grants it while no window is active, or when no click or key has gone elsewhere since the +app's own last input; MCP input goes through wx, not the compositor, so it counts as none. Mutter grants +it only while one of the app's windows has the focus. A refused `normal` replies `minimized`, with a note +that the person restores the window from the taskbar, and a refused `raise` replies `active: false`. ### Menus @@ -3398,9 +3435,10 @@ the MCP web fixture plugin's dialog, window, dock panel and configuration UI (si `--install DATADIR`), `tools/mcp/test_set_view_preview.py` the legend combo's semantics of `set_view {view_type}`, a canvas screenshot straight after a layer or view type change, and the preview refusals of `set_view`, `tools/mcp/test_set_window.py` -`set_window` on the main window (sized, moved, maximized and minimized, and restored from both), on the -Plugins window by its ref and on Preferences by its `{label}` locator, and `set_view`'s refusal of -`window_size`, `tools/mcp/test_set_view_camera.py` +`set_window` on the main window (sized twice, moved, placed over its display's work area, maximized and +minimized, and restored from both, with a window screenshot of the size on Wayland), on the Plugins +window by its ref and on Preferences by its `{label}` locator (on X11 with the main window kept under it +in the X server's stacking order), and `set_view`'s refusal of `window_size`, `tools/mcp/test_set_view_camera.py` `set_view`'s `target` and `zoom` after a queued fit (and its note while no 3D view draws), clamping, an orbit that keeps the target, the camera Preview shares and the Design tab's own, with `camera_state` and `get_app_state.camera`, and a fit after the window was sized while no 3D view showed, diff --git a/src/slic3r/CMakeLists.txt b/src/slic3r/CMakeLists.txt index feff31bc48..8a100b7486 100644 --- a/src/slic3r/CMakeLists.txt +++ b/src/slic3r/CMakeLists.txt @@ -223,6 +223,8 @@ set(SLIC3R_GUI_SOURCES GUI/Mcp/VideoOverlay.hpp GUI/Mcp/WebPages.cpp GUI/Mcp/WebPages.hpp + GUI/Mcp/WindowControl.cpp + GUI/Mcp/WindowControl.hpp GUI/PluginsConfigDialog.cpp GUI/PluginsConfigDialog.hpp GUI/ProcessRunner.cpp diff --git a/src/slic3r/GUI/CAD/DesignSketchTool.cpp b/src/slic3r/GUI/CAD/DesignSketchTool.cpp index 8cbb874820..81053d6af9 100644 --- a/src/slic3r/GUI/CAD/DesignSketchTool.cpp +++ b/src/slic3r/GUI/CAD/DesignSketchTool.cpp @@ -12419,7 +12419,10 @@ bool DesignSketchTool::on_mouse_impl(wxMouseEvent& evt, GLCanvas3D& canvas) const int base = int(m_entities.size()); begin_feature(FeatureKind::Polygon); append_entities(make_polygon(m_points[0], p, m_polygon_sides)); - infer_auto_constraints(base); + // The polygon is regular as drawn, so only an edge already on an axis is pinned to it: + // a solve meeting a pin on an edge a little off the axis moves that edge's ends and + // leaves the polygon irregular. + infer_auto_constraints(base, 1e-9); end_feature(m_points[0], p, (p - m_points[0]).norm(), m_polygon_sides); m_points.clear(); } diff --git a/src/slic3r/GUI/Mcp/McpService.cpp b/src/slic3r/GUI/Mcp/McpService.cpp index e1e4e7a600..05467f6d5f 100644 --- a/src/slic3r/GUI/Mcp/McpService.cpp +++ b/src/slic3r/GUI/Mcp/McpService.cpp @@ -12,6 +12,7 @@ #include "ModalTracker.hpp" #include "UiInspector.hpp" #include "WebPages.hpp" +#include "WindowControl.hpp" #include "McpPaths.hpp" #include "McpReplay.hpp" #include "McpPersonRun.hpp" @@ -275,6 +276,7 @@ bool McpService::start(const McpLaunchOptions& options, bool serve, std::string& m_web_presses = std::make_shared(); m_modals->set_before_press([this] { release_web_presses(m_web_presses, nullptr); }); register_tools(); + track_window_states(); m_inspector->capture_menus(true); if (ImGuiWrapper* imgui = wxGetApp().imgui()) imgui->set_item_recording(true); diff --git a/src/slic3r/GUI/Mcp/McpTools.hpp b/src/slic3r/GUI/Mcp/McpTools.hpp index 4791fef8a0..84e8d97ae4 100644 --- a/src/slic3r/GUI/Mcp/McpTools.hpp +++ b/src/slic3r/GUI/Mcp/McpTools.hpp @@ -378,13 +378,13 @@ struct WindowSettling bool limited = false; // the size was held to the window's minimum or maximum size bool held = false; // the window held still in the state asked for bool drawn = false; // and the main window's 3D view drew at its size, or needn't - bool unreported = false; // Wayland: a minimize, or a normal for a window set_window minimized + bool activation = false; // the request restored a minimized window by activating it (Wayland) + int seconds = 3; // how long the wait for the window lasted at most std::string undrawn; // undrawn_window()'s reason the 3D view isn't drawn, or empty }; // Adds to set_window's `reply`, which holds the size, position and state the window reads back, // adjusted, the fields of `args` the window differs from, and a note on why: a size limit, the window -// manager, a 3D view that didn't draw, or a minimize Wayland never reports, whose state is never listed -// as adjusted. +// manager, a compositor that refused to activate a minimized window, or a 3D view that didn't draw. void add_window_notes(const nlohmann::json& args, const WindowSettling& settling, nlohmann::json& reply); // Whether the shown 3D view has drawn at its canvas's size, asking for a frame when it hasn't: until it // has, the camera's viewport is the old size, which a fit or a screen_rect would use. True when no 3D diff --git a/src/slic3r/GUI/Mcp/McpToolsApp.cpp b/src/slic3r/GUI/Mcp/McpToolsApp.cpp index b64b356e83..ae9fe5cc36 100644 --- a/src/slic3r/GUI/Mcp/McpToolsApp.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsApp.cpp @@ -10,7 +10,9 @@ #include "McpTypes.hpp" #include "ModalTracker.hpp" #include "PythonScriptsDialog.hpp" +#include "ScreenCapture.hpp" #include "UiInspector.hpp" +#include "WindowControl.hpp" #include "slic3r/GUI/GCodeViewer.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI.hpp" @@ -129,13 +131,18 @@ json app_state(McpService& service) 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()}}; + // The size and state list_windows reports, and the place where the platform knows it. + const wxSize size = window_size(*frame); + const std::string frame_state = window_state(*frame); + state["window"] = {{"title", into_u8(frame->GetTitle())}, + {"size", {size.x, size.y}}, + {"maximized", frame_state == "maximized"}, + {"minimized", frame_state == "minimized"}, + {"shown", frame->IsShown()}}; + if (window_positions_known()) { + const wxPoint pos = frame->GetScreenPosition(); + state["window"]["position"] = {pos.x, pos.y}; + } if (Notebook* tabs = frame->m_tabpanel; tabs != nullptr && tabs->GetSelection() != wxNOT_FOUND) state["tab"] = into_u8(tabs->GetPageName(size_t(tabs->GetSelection()))); // The page exists only when the CAD preference was on at startup. diff --git a/src/slic3r/GUI/Mcp/McpToolsUi.cpp b/src/slic3r/GUI/Mcp/McpToolsUi.cpp index 211b29af34..6ba0c861ed 100644 --- a/src/slic3r/GUI/Mcp/McpToolsUi.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsUi.cpp @@ -12,6 +12,7 @@ #include "ScreenCapture.hpp" #include "UiInspector.hpp" #include "WebPages.hpp" +#include "WindowControl.hpp" #include "slic3r/GUI/Camera.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI.hpp" @@ -1098,38 +1099,11 @@ wxTopLevelWindow* live_window(wxTopLevelWindow* window) return nullptr; } -// The windows set_window has minimized on Wayland, which never says whether one still is and gives an app -// no way to restore one: a later normal for such a window can't bring it back, and its reply says so. UI -// thread, where the weak refs are made and dropped. -std::vector>& wayland_minimized() -{ - static std::vector> windows; - windows.erase(std::remove_if(windows.begin(), windows.end(), [](const wxWeakRef& w) { return w.get() == nullptr; }), - windows.end()); - return windows; -} - -// Takes a window out of its minimized state, then out of its maximized one. Restore() won't do: on wxGTK -// it presents the window, which raises it, and on Windows a window minimized while maximized comes back -// maximized. Un-minimizing goes out only for a minimized window, as on GTK it shows a mapped X11 window -// again, which raises it; set_window replies to a minimize once it reads back, so the next call sees it. -// Un-maximizing goes out only for a maximized window except on GTK: on Windows it restores, so -// activates, a normal window too, while GTK's IsMaximized() can lag a maximize still on its way, and -// un-maximizing a normal window changes nothing there. UI thread. -void restore_normal(wxTopLevelWindow& w) -{ - if (w.IsIconized()) - w.Iconize(false); -#ifdef __WXGTK__ - w.Maximize(false); -#else - if (w.IsMaximized()) - w.Maximize(false); -#endif -} - // set_window: checks the request and applies it in one UI closure, waits for the window to take it, -// then replies with what the window became. +// then replies with what the window became. A size or position applies to the normal window, so a +// maximized or minimized one is restored first. Where the window system restores it later (GTK), the call +// waits for that before sizing, as a size given meanwhile is lost: on Wayland the compositor's answer to +// the restore sizes the window again, and wx would size it by the maximized window's decorations. ToolResult set_window(McpService& service, ToolContext& ctx, const json& args) { const json target = args.value("target", json("main")); @@ -1137,8 +1111,29 @@ ToolResult set_window(McpService& service, ToolContext& ctx, const json& args) // Never followed off the UI thread, and checked by live_window() on it: a wxWeakRef can't be made or // dropped on this thread. wxTopLevelWindow* window = nullptr; - bool main = false, modal = false; + bool main = false, modal = false, restoring = false; WindowSettling settling; + const bool placing = args.contains("size") || args.contains("position"); + const std::string state = arg_string(args, "state"); + const auto minimized = [](const wxTopLevelWindow& w) { return std::string(window_state(w)) == "minimized"; }; + // The request, less the restore that comes before a size or position. UI thread. + const auto apply = [&](wxTopLevelWindow& w) { + if (args.contains("size")) + settling.limited = resize_window(w, wxSize(args["size"][0].get(), args["size"][1].get())); + // -1 is a place on a screen left of or above the primary one, not "keep this coordinate". + if (args.contains("position")) + w.Move(args["position"][0].get(), args["position"][1].get(), wxSIZE_ALLOW_MINUS_ONE); + if (state == "maximized") { + maximize_window(w); + } else if (state == "minimized") { + minimize_window(w); + } else if (state == "normal") { + settling.activation = settling.activation || (restore_needs_activation() && minimized(w)); + restore_window(w); + } + if (arg_bool(args, "raise", false)) + raise_window(w); + }; ctx.run_ui([&] { wxTopLevelWindow& w = window_target(service, target, locator); auto* dlg = dynamic_cast(&w); @@ -1152,69 +1147,66 @@ ToolResult set_window(McpService& service, ToolContext& ctx, const json& args) abilities.positions_known = window_positions_known(); if (const std::string refusal = window_request_refusal(args, abilities); !refusal.empty()) throw ToolFailure(refusal); - // A size or position applies to the normal window, so a maximized or minimized one is restored first. - if (args.contains("size") || args.contains("position")) - restore_normal(w); - if (args.contains("size")) { - const wxSize asked(args["size"][0].get(), args["size"][1].get()); - wxSize size = asked; - size.IncTo(w.GetMinSize()); - size.DecToIfSpecified(w.GetMaxSize()); - settling.limited = size != asked; - w.SetSize(size); - } - // -1 is a place on a screen left of or above the primary one, not "keep this coordinate". - if (args.contains("position")) - w.Move(args["position"][0].get(), args["position"][1].get(), wxSIZE_ALLOW_MINUS_ONE); - const std::string state = arg_string(args, "state"); - if (!abilities.positions_known && (state == "minimized" || state == "normal")) { - std::vector>& minimized = wayland_minimized(); - const bool known = std::any_of(minimized.begin(), minimized.end(), [&w](const wxWeakRef& m) { return m.get() == &w; }); - if (state == "minimized" && !known) - minimized.emplace_back(&w); - settling.unreported = state == "minimized" || known; - } - if (state == "maximized") - w.Maximize(); - else if (state == "minimized") - w.Iconize(); - else if (state == "normal") - restore_normal(w); - if (arg_bool(args, "raise", false)) - w.Raise(); window = &w; + if (placing && std::string(window_state(w)) != "normal") { + settling.activation = restore_needs_activation() && minimized(w); + restoring = restore_window(w); + } + if (!restoring) + apply(w); return json(); }); journal_with_locator(ctx, args, locator); - // The window manager may apply the request later (X11) or animate it (macOS): the wait ends at two - // equal readings in a row in the state asked for, and for the main window once its 3D view has - // drawn at the new size, which a minimized window never does. Wayland never reports a minimize, so - // there the wait asks neither for that state nor for a frame from a window that may be minimized. - std::string wanted = arg_string(args, "state"); - if (wanted.empty() && (args.contains("size") || args.contains("position"))) - wanted = "normal"; - if (settling.unreported && wanted == "minimized") - wanted.clear(); + // The window manager may apply a request later (X11) or animate it (macOS): a wait ends at two equal + // readings in a row in the state asked for. `holds` takes a reading and says whether the window held + // still in `wanted` (any state when empty). UI thread. const char* closed = "The request was applied before the window closed"; json last; - const json done = poll_until( - ctx, - [&]() -> json { + const auto holds = [&](const std::string& wanted) { + wxTopLevelWindow* w = live_window(window); + if (w == nullptr) + throw ToolFailure(closed); + const wxPoint pos = w->GetScreenPosition(); + const wxSize size = window_size(*w); + const std::string now = window_state(*w); + const json reading{pos.x, pos.y, size.x, size.y, now}; + return reading == std::exchange(last, reading) && (wanted.empty() || now == wanted); + }; + const auto cancelled = [] { return ToolFailure("Cancelled: OrcaSlicer is closing or the replay or script was stopped"); }; + if (restoring) { + // The rest of the request goes to the window the restore left, normal or not. + poll_until(ctx, [&] { return holds("normal") ? json(true) : json(); }, state_change_timeout("normal"), std::chrono::milliseconds(50)); + if (ctx.cancelled()) + throw cancelled(); + ctx.run_ui([&] { wxTopLevelWindow* w = live_window(window); if (w == nullptr) throw ToolFailure(closed); - const wxRect rect = w->GetScreenRect(); - const std::string state = window_state(*w); - const json reading{rect.x, rect.y, rect.width, rect.height, state}; - settling.held = reading == std::exchange(last, reading) && (wanted.empty() || state == wanted); + apply(*w); + return json(); + }); + last = json(); + } + + // For the main window the wait also lasts until its 3D view has drawn at the new size, which a + // minimized window never does. + std::string wanted = state; + if (wanted.empty() && placing) + wanted = "normal"; + const std::chrono::seconds timeout = state_change_timeout(wanted); + settling.seconds = int(timeout.count()); + const json done = poll_until( + ctx, + [&]() -> json { + settling.held = holds(wanted); if (!settling.held) return json(); - return !main || state == "minimized" || settling.unreported || view_drawn_at_size() ? json(true) : json(); + return !main || minimized(*live_window(window)) || view_drawn_at_size() ? json(true) : json(); }, - std::chrono::seconds(3), std::chrono::milliseconds(50)); + timeout, std::chrono::milliseconds(50)); if (done.is_null() && ctx.cancelled()) - throw ToolFailure("Cancelled: OrcaSlicer is closing or the replay or script was stopped"); + throw cancelled(); settling.drawn = !done.is_null(); if (settling.held && !settling.drawn) settling.undrawn = undrawn_window(ctx); @@ -1265,17 +1257,19 @@ void add_window_notes(const json& args, const WindowSettling& settling, json& re { json adjusted = json::array(); for (const std::string field : {"size", "position", "state"}) - if (args.contains(field) && reply.contains(field) && reply[field] != args[field] && !(settling.unreported && field == "state")) + if (args.contains(field) && reply.contains(field) && reply[field] != args[field]) adjusted.push_back(field); std::string note = settling.limited ? "size is held to the window's minimum or maximum size" : ""; const auto add = [¬e](const std::string& why) { note += (note.empty() ? "" : "; ") + why; }; - if (settling.unreported) - add("Wayland neither reports a minimized window nor lets an app restore one, so state can't show it, and only the " - "person can bring the window back from the desktop"); + if (!settling.held && settling.activation) + add("the compositor did not bring the window back: Wayland lets an app restore its minimized window only by " + "activating it, which the compositor allows only while the app may take the focus, so the person restores it " + "from the taskbar"); else if (!settling.held) - add("the window manager did not apply the request within 3 s"); + add("the window manager did not apply the request within " + std::to_string(settling.seconds) + " s"); else if (!settling.drawn) - add("the 3D view did not draw at the window's size within 3 s" + (settling.undrawn.empty() ? "" : ": " + settling.undrawn)); + add("the 3D view did not draw at the window's size within " + std::to_string(settling.seconds) + " s" + + (settling.undrawn.empty() ? "" : ": " + settling.undrawn)); else if (note.empty() && !adjusted.empty()) note = "the window manager adjusted the request"; if (!adjusted.empty()) @@ -1316,7 +1310,8 @@ std::string window_request_refusal(const json& args, const WindowAbilities& wind if (state == "minimized" && !window.main && !window.can_minimize) return "This window's title bar has no minimize button: move it aside with position, or close it, instead"; if (position && !window.positions_known) - return "position needs X11; Wayland places windows itself, so leave position out or run OrcaSlicer under X11"; + return "position needs X11: Wayland gives an app no way to place its window or to read where it is. Leave position " + "out, or start OrcaSlicer with GDK_BACKEND=x11 to run it under XWayland, where every field works"; return {}; } diff --git a/src/slic3r/GUI/Mcp/UiInspector.cpp b/src/slic3r/GUI/Mcp/UiInspector.cpp index 9f5be58f16..4f01781a05 100644 --- a/src/slic3r/GUI/Mcp/UiInspector.cpp +++ b/src/slic3r/GUI/Mcp/UiInspector.cpp @@ -6,6 +6,7 @@ #include "McpTypes.hpp" #include "ModalTracker.hpp" #include "ScreenCapture.hpp" +#include "WindowControl.hpp" #include "slic3r/GUI/3DScene.hpp" #include "slic3r/GUI/BBLTopbar.hpp" #include "slic3r/GUI/Camera.hpp" @@ -2620,11 +2621,6 @@ bool shows_web_view(wxWindow* w) } // namespace -const char* window_state(const wxTopLevelWindow& window) -{ - return window.IsIconized() ? "minimized" : window.IsMaximized() ? "maximized" : "normal"; -} - json UiInspector::window_entry(wxTopLevelWindow& tlw, bool modal) { const bool main = &tlw == wxGetApp().mainframe; @@ -2654,7 +2650,7 @@ json UiInspector::window_entry(wxTopLevelWindow& tlw, bool modal) const wxPoint pos = tlw.GetScreenPosition(); w["x"] = pos.x, w["y"] = pos.y; } - const wxSize size = tlw.GetSize(); + const wxSize size = window_size(tlw); w["width"] = size.x, w["height"] = size.y; w["state"] = window_state(tlw); // The main window's style leaves wxRESIZE_BORDER out on macOS, where a person resizes it all the same. diff --git a/src/slic3r/GUI/Mcp/UiInspector.hpp b/src/slic3r/GUI/Mcp/UiInspector.hpp index f1c7bac481..116d98cc5e 100644 --- a/src/slic3r/GUI/Mcp/UiInspector.hpp +++ b/src/slic3r/GUI/Mcp/UiInspector.hpp @@ -379,8 +379,6 @@ GLCanvas3D* design_canvas(); std::vector ui_canvases(); // The 3D view on screen: the Design view while its tab is shown, else the plater's current canvas. GLCanvas3D* shown_canvas(); -// "minimized", "maximized" or "normal": a window's state as list_windows reports it and set_window takes it. -const char* window_state(const wxTopLevelWindow& window); // "3d", "preview", "assemble" or "design". const char* canvas_name(GLCanvas3D* canvas); // The canvas of a name canvas_name() gives; "" is the Prepare view. Null for an unknown name, and for diff --git a/src/slic3r/GUI/Mcp/WindowControl.cpp b/src/slic3r/GUI/Mcp/WindowControl.cpp new file mode 100644 index 0000000000..74880dfe58 --- /dev/null +++ b/src/slic3r/GUI/Mcp/WindowControl.cpp @@ -0,0 +1,383 @@ +#include "WindowControl.hpp" + +#include +#include +#include +#include +#include + +#include +#include +#include + +#if defined(__WXGTK__) +#include "slic3r/GUI/LinuxDisplayBackend.hpp" + +#include +#ifdef GDK_WINDOWING_WAYLAND +#include +#endif +#ifdef wxHAVE_GDK_X11 +#include +#include +#include +#include + +#include +#endif +#endif + +namespace Slic3r { namespace GUI { namespace Mcp { + +namespace { + +#if defined(__WXGTK__) + +GtkWidget* gtk_window_of(const wxTopLevelWindow& window) +{ + auto* widget = static_cast(window.GetHandle()); + return widget != nullptr && GTK_IS_WINDOW(widget) ? widget : nullptr; +} + +// What a Wayland compositor says of a window, which GTK passes on as a visibility notify and wx ignores: +// it hides the window (xdg_toplevel's suspended state). KWin hides a minimized window, but also one on +// another virtual desktop and every window while the screens are off; Mutter hides any window it has not +// shown for 3 s. So a hidden window reads minimized only while set_window's minimize of it stands, which +// ends once the window shows, takes the focus or closes. +constexpr const char* kSuspendedKey = "orca-mcp-suspended"; +constexpr const char* kMinimizedKey = "orca-mcp-minimized"; + +void set_flag(GObject* window, const char* key, bool on) { g_object_set_data(window, key, on ? GINT_TO_POINTER(1) : nullptr); } + +bool window_flag(const wxTopLevelWindow& window, const char* key) +{ + GtkWidget* widget = gtk_window_of(window); + return widget != nullptr && g_object_get_data(G_OBJECT(widget), key) != nullptr; +} + +// The GtkWindow an emission hook's signal was emitted on, or null for any other widget. +GObject* hooked_window(guint count, const GValue* values) +{ + return count >= 1 && G_VALUE_HOLDS_OBJECT(&values[0]) && GTK_IS_WINDOW(g_value_get_object(&values[0])) ? + G_OBJECT(g_value_get_object(&values[0])) : + nullptr; +} + +gboolean on_visibility_notify(GSignalInvocationHint*, guint count, const GValue* values, gpointer) +{ + if (GObject* window = hooked_window(count, values); window != nullptr && count >= 2) { + if (const auto* event = static_cast(g_value_get_boxed(&values[1])); event != nullptr) { + const bool hidden = event->state == GDK_VISIBILITY_FULLY_OBSCURED; + set_flag(window, kSuspendedKey, hidden); + if (!hidden) + set_flag(window, kMinimizedKey, false); + } + } + return TRUE; // stay installed +} + +// A minimized window never has the focus, though one shown while the screens are off is never shown. +gboolean on_focus_in(GSignalInvocationHint*, guint count, const GValue* values, gpointer) +{ + if (GObject* window = hooked_window(count, values)) + set_flag(window, kMinimizedKey, false); + return TRUE; +} + +// A window shown again gets a new surface, which starts out shown. +gboolean on_unmap(GSignalInvocationHint*, guint count, const GValue* values, gpointer) +{ + if (GObject* window = hooked_window(count, values)) { + set_flag(window, kSuspendedKey, false); + set_flag(window, kMinimizedKey, false); + } + return TRUE; +} + +// How GTK lays out a top-level window on Wayland: its whole allocation, the content wx puts in it, and a +// title bar GTK shows above the content. Unset off Wayland and before the window has a surface. +struct WaylandFrame +{ + bool realized = false; + wxSize outer, inner; + int title = 0; + + // The margins GTK draws the shadow and resize border of a window it decorates in: the compositor + // shows the window without them, and a window capture draws only its content. + wxSize margins() const { return {std::max(0, outer.x - inner.x), std::max(0, outer.y - inner.y - title)}; } +}; + +WaylandFrame wayland_frame(const wxTopLevelWindow& window) +{ + WaylandFrame frame; + GtkWidget* widget = gtk_window_of(window); + GtkWidget* content = widget != nullptr ? gtk_bin_get_child(GTK_BIN(widget)) : nullptr; + if (content == nullptr || !is_running_on_wayland() || !gtk_widget_get_realized(widget)) + return frame; + GtkAllocation a; + gtk_widget_get_allocation(widget, &a); + frame.outer = {a.width, a.height}; + gtk_widget_get_allocation(content, &a); + frame.inner = {a.width, a.height}; + if (GtkWidget* bar = gtk_window_get_titlebar(GTK_WINDOW(widget)); bar != nullptr && gtk_widget_get_visible(bar)) { + gtk_widget_get_allocation(bar, &a); + frame.title = a.height; + } + frame.realized = true; + return frame; +} + +// The decorations wx takes off a window's size before it gives the size to GTK, which wx keeps to itself. +// On Wayland wx measures them, as the whole allocation less the content, only for a window GTK decorates +// while the compositor would rather not (gdk_wayland_display_prefers_ssd() false, as on Mutter); for every +// other window it counts none, even one GTK decorates on KWin, as OrcaSlicer's main window with its own +// title bar. +wxSize wx_decorations(const wxTopLevelWindow& window, const WaylandFrame& frame) +{ +#ifdef GDK_WINDOWING_WAYLAND + GtkWidget* widget = gtk_window_of(window); + GdkDisplay* display = widget != nullptr ? gtk_widget_get_display(widget) : nullptr; + if (display != nullptr && GDK_IS_WAYLAND_DISPLAY(display) && gtk_window_get_decorated(GTK_WINDOW(widget)) && + !gdk_wayland_display_prefers_ssd(display)) + return frame.outer - frame.inner; +#endif + return {0, 0}; +} + +#ifdef wxHAVE_GDK_X11 +// The window's X11 window while no window manager runs, as on a bare Xvfb, else null. Every EWMH window +// manager lists _NET_WM_STATE among the hints it takes; with none, nothing maximizes, minimizes or stacks a +// window unless the app does it. +GdkWindow* unmanaged_x11_window(const wxTopLevelWindow& window) +{ + GtkWidget* widget = gtk_window_of(window); + GdkWindow* gdk = widget != nullptr ? gtk_widget_get_window(widget) : nullptr; + if (gdk == nullptr || !GDK_IS_X11_WINDOW(gdk)) + return nullptr; + return gdk_x11_screen_supports_net_wm_hint(gdk_window_get_screen(gdk), gdk_atom_intern_static_string("_NET_WM_STATE")) ? nullptr : gdk; +} + +// Raises the shown windows GTK has as transient for `window`, and theirs in turn, in the order they were +// created, as a window manager keeps a dialog above the window it belongs to. +void raise_transients(const wxTopLevelWindow& window) +{ + std::vector owners{GTK_WINDOW(gtk_window_of(window))}; + for (wxWindow* w : wxTopLevelWindows) { + auto* tlw = dynamic_cast(w); + GtkWidget* widget = tlw != nullptr && tlw->IsShown() ? gtk_window_of(*tlw) : nullptr; + if (widget == nullptr || !gtk_widget_get_realized(widget)) + continue; + GtkWindow* parent = gtk_window_get_transient_for(GTK_WINDOW(widget)); + if (parent != nullptr && std::find(owners.begin(), owners.end(), parent) != owners.end()) { + gdk_window_raise(gtk_widget_get_window(widget)); + owners.push_back(GTK_WINDOW(widget)); + } + } +} + +// The window's normal rect, kept on the GtkWindow while set_window keeps it maximized itself. +constexpr const char* kNormalRectKey = "orca-mcp-normal-rect"; + +// Adds or removes the maximized atoms in the window's _NET_WM_STATE, keeping the others GDK set. With no +// window manager to do it, GDK reads the property back when it changes and reports the window maximized +// or not, so wx's IsMaximized() follows. +void set_maximized_hint(GdkWindow* gdk, bool maximized) +{ + GdkDisplay* display = gdk_window_get_display(gdk); + Display* dpy = GDK_DISPLAY_XDISPLAY(display); + const Window xid = GDK_WINDOW_XID(gdk); + const Atom state = gdk_x11_get_xatom_by_name_for_display(display, "_NET_WM_STATE"); + const Atom vert = gdk_x11_get_xatom_by_name_for_display(display, "_NET_WM_STATE_MAXIMIZED_VERT"); + const Atom horz = gdk_x11_get_xatom_by_name_for_display(display, "_NET_WM_STATE_MAXIMIZED_HORZ"); + + std::vector atoms; + Atom type = None; + int format = 0; + unsigned long count = 0, after = 0; + unsigned char* data = nullptr; + if (XGetWindowProperty(dpy, xid, state, 0, 1024, False, XA_ATOM, &type, &format, &count, &after, &data) == Success && + data != nullptr) { + if (type == XA_ATOM && format == 32) { + const auto* got = reinterpret_cast(data); // 32-bit properties come back as longs + for (unsigned long i = 0; i < count; ++i) + if (Atom(got[i]) != vert && Atom(got[i]) != horz) + atoms.push_back(Atom(got[i])); + } + XFree(data); + } + if (maximized) { + atoms.push_back(vert); + atoms.push_back(horz); + } + XChangeProperty(dpy, xid, state, XA_ATOM, 32, PropModeReplace, reinterpret_cast(atoms.data()), + int(atoms.size())); + XFlush(dpy); +} +#endif // wxHAVE_GDK_X11 + +#endif // __WXGTK__ + +} // namespace + +void track_window_states() +{ +#if defined(__WXGTK__) + if (!is_running_on_wayland()) + return; + g_signal_add_emission_hook(g_signal_lookup("visibility-notify-event", GTK_TYPE_WIDGET), 0, on_visibility_notify, nullptr, nullptr); + g_signal_add_emission_hook(g_signal_lookup("focus-in-event", GTK_TYPE_WIDGET), 0, on_focus_in, nullptr, nullptr); + g_signal_add_emission_hook(g_signal_lookup("unmap", GTK_TYPE_WIDGET), 0, on_unmap, nullptr, nullptr); +#endif +} + +const char* window_state(const wxTopLevelWindow& window) +{ +#if defined(__WXGTK__) + if (window_flag(window, kSuspendedKey) && window_flag(window, kMinimizedKey)) + return "minimized"; +#endif + return window.IsIconized() ? "minimized" : window.IsMaximized() ? "maximized" : "normal"; +} + +wxSize window_size(wxTopLevelWindow& window) +{ +#if defined(__WXGTK__) + // On Wayland, what GTK allocated less the shadow: wx's own size counts the shadow after some + // allocations and not after others. + if (const WaylandFrame frame = wayland_frame(window); frame.realized) + return frame.outer - frame.margins(); +#endif + return window.GetSize(); +} + +wxSize frame_size_for(const wxSize& asked, const wxSize& extra, const wxSize& min, const wxSize& max, bool& limited) +{ + const wxSize wanted = asked + extra; + wxSize size = wanted; + size.IncTo(min); + size.DecToIfSpecified(max); + limited = size != wanted; + return size; +} + +bool resize_window(wxTopLevelWindow& window, const wxSize& size) +{ + // wx gives GTK its size less the decorations it counts, and GTK adds a title bar it shows: the wx size + // for `size` is `size` plus those decorations less that title bar. Nothing but on Wayland. + wxSize extra(0, 0); +#if defined(__WXGTK__) + if (const WaylandFrame frame = wayland_frame(window); frame.realized) + extra = wx_decorations(window, frame) - wxSize(0, frame.title); +#endif + bool limited = false; + window.SetSize(frame_size_for(size, extra, window.GetMinSize(), window.GetMaxSize(), limited)); + return limited; +} + +void maximize_window(wxTopLevelWindow& window) +{ +#if defined(__WXGTK__) && defined(wxHAVE_GDK_X11) + // With no window manager the app is its own: it remembers the normal rect, marks the window + // maximized and fills the work area of its display. + if (GdkWindow* gdk = unmanaged_x11_window(window); gdk != nullptr) { + if (window.IsMaximized()) + return; + GtkWidget* widget = gtk_window_of(window); + g_object_set_data_full(G_OBJECT(widget), kNormalRectKey, new wxRect(window.GetPosition(), window.GetSize()), + [](gpointer rect) { delete static_cast(rect); }); + set_maximized_hint(gdk, true); + const int index = wxDisplay::GetFromWindow(&window); + window.SetSize(wxDisplay(unsigned(index == wxNOT_FOUND ? 0 : index)).GetClientArea()); + return; + } +#endif + window.Maximize(); +} + +void minimize_window(wxTopLevelWindow& window) +{ +#if defined(__WXGTK__) && defined(wxHAVE_GDK_X11) + // An iconify asks the window manager; with none, the app unmaps the window itself, which GDK then + // reports as minimized, and wx's Iconize(false) maps it again. + if (GdkWindow* gdk = unmanaged_x11_window(window); gdk != nullptr) { + XUnmapWindow(GDK_WINDOW_XDISPLAY(gdk), GDK_WINDOW_XID(gdk)); + XFlush(GDK_WINDOW_XDISPLAY(gdk)); + return; + } +#endif +#if defined(__WXGTK__) + if (GtkWidget* widget = gtk_window_of(window); widget != nullptr && is_running_on_wayland()) + set_flag(G_OBJECT(widget), kMinimizedKey, true); +#endif + window.Iconize(); +} + +bool restore_window(wxTopLevelWindow& window) +{ + // Restore() won't do: on wxGTK it presents the window, which raises it, and on Windows a window + // minimized while maximized comes back maximized. Un-minimizing goes out only for a minimized window, + // as GTK raises a mapped X11 window it un-minimizes. Un-maximizing goes out only for a maximized + // window: on Windows it restores, so activates, a normal window too, and on Wayland the compositor + // answers it with the window's current size, which replaces a size asked for right after. + if (std::string(window_state(window)) == "minimized") { + // Wayland gives an app no request to un-minimize a window, only to activate it, which brings it + // back when the compositor allows the app the focus. + if (restore_needs_activation()) { + window.Raise(); + } else { + window.Iconize(false); +#if defined(__WXGTK__) && defined(wxHAVE_GDK_X11) + if (unmanaged_x11_window(window) != nullptr) + raise_transients(window); // mapping it again raised it +#endif + } + } + if (window.IsMaximized()) { +#if defined(__WXGTK__) && defined(wxHAVE_GDK_X11) + if (GdkWindow* gdk = unmanaged_x11_window(window); gdk != nullptr) { + GtkWidget* widget = gtk_window_of(window); + const auto* normal = static_cast(g_object_get_data(G_OBJECT(widget), kNormalRectKey)); + const wxRect rect = normal != nullptr ? *normal : window.GetRect(); + set_maximized_hint(gdk, false); + window.SetSize(rect); + g_object_set_data(G_OBJECT(widget), kNormalRectKey, nullptr); + } else +#endif + window.Maximize(false); + } +#if defined(__WXGTK__) + // GTK reports the state once the window manager or the compositor has applied it. + return std::string(window_state(window)) != "normal"; +#else + return false; +#endif +} + +void raise_window(wxTopLevelWindow& window) +{ + window.Raise(); +#if defined(__WXGTK__) && defined(wxHAVE_GDK_X11) + if (unmanaged_x11_window(window) != nullptr) + raise_transients(window); +#endif +} + +bool restore_needs_activation() +{ +#if defined(__WXGTK__) + return is_running_on_wayland(); +#else + return false; +#endif +} + +std::chrono::seconds state_change_timeout(const std::string& state) +{ +#if defined(__WXGTK__) + if (state == "minimized" && is_running_on_wayland()) + return std::chrono::seconds(5); +#endif + return std::chrono::seconds(3); +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/WindowControl.hpp b/src/slic3r/GUI/Mcp/WindowControl.hpp new file mode 100644 index 0000000000..5422ae408a --- /dev/null +++ b/src/slic3r/GUI/Mcp/WindowControl.hpp @@ -0,0 +1,55 @@ +#pragma once + +#include + +#include +#include + +class wxTopLevelWindow; + +namespace Slic3r { namespace GUI { namespace Mcp { + +// How the MCP tools read and change a top-level window's size and state where wx alone falls short, on +// Linux: on Wayland GTK never reports a minimized window, and wx counts the invisible margins of a +// client-side decorated window in its size; under X11 with no window manager, as on a bare Xvfb, nothing +// maximizes or minimizes a window unless the app does it itself. Elsewhere each call is wx's own. UI +// thread. + +// Starts following the windows a Wayland compositor hides, which GTK passes on only as a visibility +// change, and the focus that ends a minimize. Once, before the first window_state(). +void track_window_states(); + +// "minimized", "maximized" or "normal": a window's state as list_windows reports it and set_window takes +// it. On Wayland, which reports no minimize, a window reads minimized while the compositor hides it after +// set_window minimized it. +const char* window_state(const wxTopLevelWindow& window); + +// The window's size as the window system shows it, in the units list_windows reports: wx's size, less +// the margins GTK draws a client-side decorated window's shadow in on Wayland, which the compositor and a +// window screenshot leave out. +wxSize window_size(wxTopLevelWindow& window); + +// The wx size that gives a window `asked` in window_size()'s terms: `asked` plus the `extra` wx counts in +// the window's size beyond window_size(), held to its `min` and `max` wx sizes (wxDefaultCoord for none). +// `limited` says whether a limit held it. +wxSize frame_size_for(const wxSize& asked, const wxSize& extra, const wxSize& min, const wxSize& max, bool& limited); + +// Gives the window `size` in window_size()'s terms, held to its minimum and maximum size; returns whether +// a limit held it. +bool resize_window(wxTopLevelWindow& window, const wxSize& size); +void maximize_window(wxTopLevelWindow& window); +void minimize_window(wxTopLevelWindow& window); +// Takes a window out of its minimized state, then out of its maximized one, touching only the state it is +// in. Returns whether the window system applies that later (GTK), so that a size or position given before +// it reads back would go to the window as it was. +bool restore_window(wxTopLevelWindow& window); +// Brings the window in front of the app's other windows, keeping a dialog that belongs to it above it. +void raise_window(wxTopLevelWindow& window); +// Whether bringing a minimized window back takes the compositor's leave to activate it, which it may +// refuse (Wayland). +bool restore_needs_activation(); +// How long set_window waits for a window to report the `state` it was asked for: 3 s, and 5 s for a +// minimize on Wayland, where Mutter reports a window hidden once it has not shown it for 3 s. +std::chrono::seconds state_change_timeout(const std::string& state); + +}}} // namespace Slic3r::GUI::Mcp diff --git a/tests/slic3rutils/test_mcp_tools.cpp b/tests/slic3rutils/test_mcp_tools.cpp index 863a1b3e6e..f3fdec1738 100644 --- a/tests/slic3rutils/test_mcp_tools.cpp +++ b/tests/slic3rutils/test_mcp_tools.cpp @@ -18,6 +18,7 @@ #include "slic3r/GUI/Mcp/McpTools.hpp" #include "slic3r/GUI/Mcp/McpTypes.hpp" #include "slic3r/GUI/Mcp/McpJournal.hpp" +#include "slic3r/GUI/Mcp/WindowControl.hpp" #include "slic3r/GUI/Camera.hpp" #include "libslic3r/BoundingBox.hpp" @@ -27,6 +28,8 @@ #include "libslic3r/Point.hpp" #include +#include +#include #include #include @@ -193,6 +196,7 @@ TEST_CASE("set_window refuses a request the window can't take, before changing a CHECK(window_request_refusal({{"size", {0, 600}}}, main).find("size") != std::string::npos); CHECK(window_request_refusal({{"size", {800}}}, main).find("[width, height]") != std::string::npos); CHECK(window_request_refusal({{"position", {0, 0}}}, wayland).find("X11") != std::string::npos); + CHECK(window_request_refusal({{"position", {0, 0}}}, wayland).find("GDK_BACKEND=x11") != std::string::npos); CHECK(window_request_refusal({{"size", {800, 600}}, {"state", "maximized"}}, wayland).find("maximized") != std::string::npos); CHECK(window_request_refusal({{"state", "minimized"}}, wayland).empty()); CHECK(window_request_refusal({{"raise", true}}, fixed).empty()); @@ -242,21 +246,50 @@ TEST_CASE("set_window's reply lists the fields the window changed, with a note o CHECK(note(reply).find(undrawn.undrawn) != std::string::npos); CHECK(note(reply).find("window manager") == std::string::npos); - // Wayland reads a minimized window back as normal: state is not adjusted, and the note says why. - WindowSettling wayland = taken; - wayland.unreported = true; - reply = {{"size", {800, 600}}, {"state", "normal"}}; - add_window_notes({{"state", "minimized"}}, wayland, reply); - CHECK_FALSE(reply.contains("adjusted")); - CHECK(note(reply).find("Wayland neither reports a minimized window nor lets an app restore one") != std::string::npos); + // The wait ran out: the note gives how long it lasted. + WindowSettling slow; + slow.seconds = 5; + reply = {{"size", {800, 600}}, {"state", "normal"}}; + add_window_notes({{"state", "minimized"}}, slow, reply); + CHECK(reply["adjusted"] == json::array({"state"})); + CHECK(note(reply) == "the window manager did not apply the request within 5 s"); - // A normal after such a minimize says the same, even when the wait ran out. - WindowSettling restored; - restored.unreported = true; - reply = {{"size", {800, 600}}, {"state", "normal"}}; - add_window_notes({{"state", "normal"}}, restored, reply); - CHECK(note(reply).find("Wayland neither reports") != std::string::npos); + // A Wayland compositor that refused to activate a minimized window: the note says so and how the person + // brings it back, not that the window manager was slow. + WindowSettling refused; + refused.activation = true; + reply = {{"size", {800, 600}}, {"state", "minimized"}}; + add_window_notes({{"state", "normal"}}, refused, reply); + CHECK(reply["adjusted"] == json::array({"state"})); + CHECK(note(reply).find("the compositor did not bring the window back") != std::string::npos); + CHECK(note(reply).find("taskbar") != std::string::npos); CHECK(note(reply).find("window manager") == std::string::npos); + + // An activation that brought the window back needs no note. + WindowSettling activated = taken; + activated.activation = true; + reply = {{"size", {800, 600}}, {"state", "normal"}}; + add_window_notes({{"state", "normal"}}, activated, reply); + CHECK_FALSE(reply.contains("note")); +} + +TEST_CASE("set_window sizes a window by what it shows, held to its limits", "[Mcp]") +{ + bool limited = true; + // No invisible margins and no limits: the size asked for. + CHECK(frame_size_for({800, 600}, {0, 0}, wxDefaultSize, wxDefaultSize, limited) == wxSize(800, 600)); + CHECK_FALSE(limited); + // The margins of a client-side decorated window on Wayland go on top, so it shows the size asked for. + CHECK(frame_size_for({800, 600}, {90, 90}, wxDefaultSize, wxDefaultSize, limited) == wxSize(890, 690)); + CHECK_FALSE(limited); + // A minimum holds it, in wx's sizes, which count the margins: 836 x 539 shows 746 x 449. + CHECK(frame_size_for({700, 400}, {90, 90}, wxSize(836, 539), wxDefaultSize, limited) == wxSize(836, 539)); + CHECK(limited); + CHECK(frame_size_for({746, 449}, {90, 90}, wxSize(836, 539), wxDefaultSize, limited) == wxSize(836, 539)); + CHECK_FALSE(limited); + // So does a maximum, on one side alone. + CHECK(frame_size_for({2000, 600}, {0, 0}, wxDefaultSize, wxSize(1600, wxDefaultCoord), limited) == wxSize(1600, 600)); + CHECK(limited); } TEST_CASE("camera_state reads the camera set_view leaves", "[Mcp]") diff --git a/tools/mcp/README.md b/tools/mcp/README.md index 7048e2a9c5..a5bde2cca7 100644 --- a/tools/mcp/README.md +++ b/tools/mcp/README.md @@ -10,7 +10,7 @@ Python. It uses only the standard library. `docs/HLSD/mcp-server.md` covers the | `launch [--xvfb] [--cad] [--printer "@"] [--vendor V] [--filament F] [--datadir DIR] [--port N] [--bin PATH] [--print-config] [-- app args]` | Start OrcaSlicer with `--mcp`, wait until it is ready, print the session | | `call TOOL [''] [--wait]` | Call a tool and print its JSON result; `--wait` follows a returned job to its result | | `tools` | List the tools, with the first line of each description | -| `snapshot ['']` | Print the `list_widgets` tree | +| `widgets ['']` | Print the `list_widgets` tree | | `screenshot OUT [--target window\|canvas\|dialog]` | Save a full-size PNG, replacing `OUT` if it exists | | `run-replay FILE [--out DIR]` | Run a replay in the launched instance and print the result; exit 0 when it passes | | `stop` | Stop the app and its Xvfb, and remove the session | @@ -397,9 +397,12 @@ tools/mcp/test_web_ui.py block the app) with a ref that `screenshot` captures alone, `list_widgets` reads alone and `press_keys` Escape closes, Preferences last as a modal dialog, and Action Replay listed as hidden, without a ref. -`test_set_window.py` checks `set_window` on the main window (sized, moved, maximized, minimized and -restored), on the Plugins window by its ref and on Preferences by its `{label}` locator, and that -`set_view` refuses `window_size`. +`test_set_window.py` checks `set_window` on the main window (sized twice, moved, placed over its +display's work area, maximized, minimized and restored), on the Plugins window by its ref and on +Preferences by its `{label}` locator, and that `set_view` refuses `window_size`. On Wayland it checks +that a window screenshot is the size the reply gives and skips positions, which Wayland neither reports +nor takes. On X11 it reads the X server's stacking order through libX11 to check that the main window, +restored and raised while Preferences is open, stays under it. `test_action_replay_hidden.py` opens Action Replay and checks that the GUI tools don't see it: `list_widgets` lists no window for it, `run_javascript` without a target behaves as before it diff --git a/tools/mcp/cad_gui.py b/tools/mcp/cad_gui.py index c0a91b0ed7..69f5dc4b74 100644 --- a/tools/mcp/cad_gui.py +++ b/tools/mcp/cad_gui.py @@ -24,7 +24,8 @@ import orca_mcp # the system's legacy code page, which may lack them: they print escaped rather than raise. sys.stdout.reconfigure(errors="backslashreplace") -CANVAS = {"label": "OrcaSceneCanvas"} +# The 3D canvas by its window name, which every platform lists; only Windows gives it as its label too. +CANVAS = {"name": "OrcaSceneCanvas"} NEW_DESIGN = "New Design — clear the feature tree" # reset_view()'s zoom, in set_view's screenshot pixels per mm at the camera's target, about 1.6: @@ -359,13 +360,14 @@ class CadGui: return parse_widgets(text) def modeless(self): - """The titles of the shown dialogs that are not modal, from list_windows.""" + """The titles of the shown dialogs that are not modal, from list_windows, leaving out the person's + own (hidden), such as Action Replay, which no tool reaches.""" items = self.client.call("list_windows").get("items", []) - return [w["title"] for w in items if w.get("kind") == "dialog" and not w.get("modal")] + return [w["title"] for w in items if w.get("kind") == "dialog" and not w.get("modal") and not w.get("hidden")] @staticmethod def _canvas(ws): - canvas = next((w for w in ws if w.kind == "canvas" and w.label == CANVAS["label"]), None) + canvas = next((w for w in ws if w.kind == "canvas" and w.name == CANVAS["name"]), None) if canvas is None or canvas.rect is None: raise RuntimeError("the Design canvas is not shown") return canvas diff --git a/tools/mcp/test_cad_sketching.py b/tools/mcp/test_cad_sketching.py index dde323596d..38e2004c58 100755 --- a/tools/mcp/test_cad_sketching.py +++ b/tools/mcp/test_cad_sketching.py @@ -164,7 +164,9 @@ def rung_slot(): def rung_polygon(): gui.enter_sketch("g") gui.click_mm(0, 0) - gui.click_mm(35, 0) + # A vertex a little off the X axis puts two edges within the axis inference's 3 degrees of + # horizontal, on every screen whatever pixel the click lands on: the polygon stays regular. + gui.click_mm(35, 1) gui.values(30, 0) d = gui.sketch() e = [x for x in d["entities"] if x["type"] == "line"] diff --git a/tools/mcp/test_set_window.py b/tools/mcp/test_set_window.py index cd97493103..f7388d5d08 100644 --- a/tools/mcp/test_set_window.py +++ b/tools/mcp/test_set_window.py @@ -5,15 +5,20 @@ modal dialog, with the read side that list_windows and get_app_state give. tools/mcp/orca_mcp.py launch tools/mcp/test_set_window.py -The main window is sized, moved, maximized, given a size while maximized (which restores it first), +The main window is sized twice, the second time from the normal state, and on Wayland a window screenshot +is the size the reply gives. Where positions are known it is moved, then placed over its display's work area +by position and size. It is maximized, given a size while maximized (which restores it first), minimized and restored, after which the 3D view still captures, and minimized while maximized, from which state normal and a size both bring it back to normal. A request that contradicts itself is refused before anything changes. The Plugins window is sized and moved by its ref, which fails, pointing to list_windows, once the window has closed. Preferences, a modal dialog, is sized as "dialog" and moved by its -{label} locator, and never minimized. set_view refuses a window_size, pointing to set_window. Exits 0 +{label} locator, and never minimized; on X11 the main window, minimized, restored and raised while it is +open, stays under it in the X server's stacking order. set_view refuses a window_size, pointing to set_window. Exits 0 when every check passes. """ +import ctypes +import ctypes.util import os import sys import time @@ -22,8 +27,68 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import orca_mcp # noqa: E402 +class _XWindowAttributes(ctypes.Structure): + _fields_ = [("x", ctypes.c_int), ("y", ctypes.c_int), ("width", ctypes.c_int), ("height", ctypes.c_int), + ("border_width", ctypes.c_int), ("depth", ctypes.c_int), ("visual", ctypes.c_void_p), ("root", ctypes.c_ulong), + ("class_", ctypes.c_int), ("bit_gravity", ctypes.c_int), ("win_gravity", ctypes.c_int), + ("backing_store", ctypes.c_int), ("backing_planes", ctypes.c_ulong), ("backing_pixel", ctypes.c_ulong), + ("save_under", ctypes.c_int), ("colormap", ctypes.c_ulong), ("map_installed", ctypes.c_int), + ("map_state", ctypes.c_int), ("all_event_masks", ctypes.c_long), ("your_event_mask", ctypes.c_long), + ("do_not_propagate_mask", ctypes.c_long), ("override_redirect", ctypes.c_int), ("screen", ctypes.c_void_p)] + + +def x11_stacking(display): + """The titles of the mapped top-level windows of an X display, bottom to top, or None when libX11 or the + display can't be opened. A window manager's frame stands for the titled window it holds.""" + path = ctypes.util.find_library("X11") + if not path or not display: + return None + x = ctypes.CDLL(path) + x.XOpenDisplay.restype = ctypes.c_void_p + x.XOpenDisplay.argtypes = [ctypes.c_char_p] + x.XDefaultRootWindow.restype = ctypes.c_ulong + x.XDefaultRootWindow.argtypes = [ctypes.c_void_p] + x.XQueryTree.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.POINTER(ctypes.c_ulong), ctypes.POINTER(ctypes.c_ulong), + ctypes.POINTER(ctypes.POINTER(ctypes.c_ulong)), ctypes.POINTER(ctypes.c_uint)] + x.XFetchName.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.POINTER(ctypes.c_char_p)] + x.XFree.argtypes = [ctypes.c_void_p] + x.XCloseDisplay.argtypes = [ctypes.c_void_p] + x.XGetWindowAttributes.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.POINTER(_XWindowAttributes)] + dpy = x.XOpenDisplay(display.encode()) + if not dpy: + return None + + def children(window): + root, parent, n = ctypes.c_ulong(), ctypes.c_ulong(), ctypes.c_uint() + kids = ctypes.POINTER(ctypes.c_ulong)() + if not x.XQueryTree(dpy, window, ctypes.byref(root), ctypes.byref(parent), ctypes.byref(kids), ctypes.byref(n)): + return [] + out = [kids[i] for i in range(n.value)] + if kids: + x.XFree(kids) + return out + + def viewable(window): + attrs = _XWindowAttributes() + return x.XGetWindowAttributes(dpy, window, ctypes.byref(attrs)) and attrs.map_state == 2 # IsViewable + + def title(window, depth=3): + name = ctypes.c_char_p() + if x.XFetchName(dpy, window, ctypes.byref(name)) and name.value: + return name.value.decode(errors="replace") + for kid in reversed(children(window)) if depth else []: + found = title(kid, depth - 1) + if found: + return found + return None + + order = [title(w) for w in children(x.XDefaultRootWindow(dpy)) if viewable(w)] + x.XCloseDisplay(dpy) + return [t for t in order if t] + + def main(): - client, _session = orca_mcp.session_client() + client, session = orca_mcp.session_client() checks = [] def check(name, ok, detail=""): @@ -66,14 +131,37 @@ def main(): check("size: the window is in its normal state", sized.get("state") == "normal", sized) entry = main_entry() check("size: list_windows reports it", (entry.get("width"), entry.get("height")) == (1400, 900), entry) + # A second size from the normal state. Taking a normal window out of a maximize it isn't in makes a + # Wayland compositor send it its current size, which replaced the one asked for. + again = client.call("set_window", size=[1300, 820]) + check("a second size: the reply has it", again.get("size") == [1300, 820], again) + entry = main_entry() + check("a second size: list_windows reports it", (entry.get("width"), entry.get("height")) == (1300, 820), entry) + if wayland: + # The size is the window as the compositor shows it, which a window screenshot captures; the shadow + # GTK draws around it is not part of it. + shot = client.call("screenshot", target="window", include_image=False) + scale = again.get("scale", 1) + check("a second size: a window screenshot is that size", (shot.get("width"), shot.get("height")) == + (round(1300 * scale), round(820 * scale)), f"{shot} / {again}") # 2. Position. if wayland: print("NOTE position: skipped, as Wayland neither reports nor accepts positions") + window = client.call("get_app_state").get("window", {}) + check("position: get_app_state reports none on Wayland", "position" not in window, window) else: client.call("set_window", position=[40, 30]) window = client.call("get_app_state").get("window", {}) check("position: get_app_state reports it", window.get("position") == [40, 30], window) + # The display's work area, given as a place and a size, is taken as it is: a window manager keeps a + # window that fits it there, and with none the window goes exactly there. + area = sized.get("display", {}) + filled = client.call("set_window", position=[area.get("x", 0), area.get("y", 0)], + size=[area.get("width", 0), area.get("height", 0)]) + check("position and size: the window fills the display's work area", + filled.get("position") == [area.get("x"), area.get("y")] and filled.get("size") == [area.get("width"), area.get("height")], + f"{filled} / {area}") # 3. Maximize. maximized = client.call("set_window", state="maximized") @@ -166,6 +254,18 @@ def main(): check("dialog: a {label} locator finds it", False, str(e)) error = refusal(target="dialog", state="minimized") check("dialog: a modal dialog never minimizes", error is not None, error) + # The main window restored and raised behind the dialog stays under it, as X11 captures read the + # screen: a window manager keeps a dialog above its window, and with none the app does. + client.call("set_window", state="minimized") + client.call("set_window", state="normal") + client.call("set_window", **{"raise": True}) + order = None if wayland else x11_stacking(session.get("display") or os.environ.get("DISPLAY")) + if order is None: + print("NOTE dialog stacking: skipped, as the X server's stacking order can't be read here") + else: + title = main_entry().get("title") + check("dialog: the main window, restored and raised, stays under it", + title in order and "Preferences" in order and order.index(title) < order.index("Preferences"), order) client.call("answer_dialog", dialog={"title": "Preferences"}, button="close") client.await_job(prefs) check("Preferences closes", find("Preferences") is None, windows())