From a9c73c76b2cbdf2d7683054233f0b4a3a0ed9a1f Mon Sep 17 00:00:00 2001 From: SoftFever Date: Thu, 12 Nov 2026 01:39:39 +0800 Subject: [PATCH] Fix macOS issues found driving the app over MCP set_window brings a window minimized while zoomed back to normal, and its documentation covers raising windows and native dialogs. A right-click in the Design tab picks what it points at on Retina displays, where the Design tab GUI tests now run too, and the Text dialog opens in a plain font. The app no longer hangs when dialogs open and close with the display asleep, and no longer crashes when a new project or a delete removes an object that has parts. --- docs/HLSD/design-tab.md | 3 +- docs/HLSD/mcp-server.md | 16 +++++-- src/slic3r/GUI/CAD/DesignCanvas.cpp | 11 +++-- src/slic3r/GUI/CAD/DesignSketchTool.hpp | 7 ++-- src/slic3r/GUI/CAD/DesignTextDialog.cpp | 7 +++- src/slic3r/GUI/GUI_App.cpp | 1 + src/slic3r/GUI/Mcp/McpToolsUi.cpp | 9 +++- src/slic3r/GUI/Mcp/WindowControl.cpp | 11 +++++ src/slic3r/GUI/Mcp/WindowControl.hpp | 14 +++++-- src/slic3r/GUI/ObjectDataViewModel.cpp | 9 ++++ src/slic3r/Utils/MacDarkMode.hpp | 2 + src/slic3r/Utils/MacDarkMode.mm | 23 ++++++++++ tools/mcp/README.md | 4 +- tools/mcp/cad_gui.py | 56 +++++++++++++++++-------- tools/mcp/test_cad_click_edit.py | 16 +++---- tools/mcp/test_cad_context_menu.py | 10 ++--- tools/mcp/test_cad_sketching.py | 4 +- tools/mcp/test_set_view_camera.py | 2 +- tools/mcp/test_set_window.py | 4 ++ 19 files changed, 157 insertions(+), 52 deletions(-) diff --git a/docs/HLSD/design-tab.md b/docs/HLSD/design-tab.md index 511be9b205..e0bee6f579 100644 --- a/docs/HLSD/design-tab.md +++ b/docs/HLSD/design-tab.md @@ -170,7 +170,8 @@ rather than to its end points: a press that wandered past the budget at any mome navigation, even if it comes back to where it started, which is what stops a slow, careful orbit from ending in a menu. There is no time budget — a gesture that means something different when it is slow is exactly what the interaction charter rules out. The raycast uses the press -position, not the release. The sketch tool sees a right press only once the release has shown it +position, not the release, scaled to the canvas's GL pixels as every mouse event the canvas passes +on is (two per logical pixel on a Retina display). The sketch tool sees a right press only once the release has shown it was a click: the press itself goes to the camera, which may pan or orbit with that button, and the canvas replays it to the tool on a stationary release. A tool that uses the click (to terminate a chain, say) keeps the menu closed. Past either budget the event is navigation, and navigation diff --git a/docs/HLSD/mcp-server.md b/docs/HLSD/mcp-server.md index 5fb5716672..c43898ff32 100644 --- a/docs/HLSD/mcp-server.md +++ b/docs/HLSD/mcp-server.md @@ -1666,7 +1666,9 @@ listed among the others, `modal` from `wxDialog::IsModal()`. window (`main`, the default), the topmost modal dialog (`dialog`), or the window a ref or locator is in, so a widget's ref names its window and a replay's `{label: "Preferences"}` finds the dialog again. It refuses a native dialog, which `answer_dialog` answers, a window named `kHiddenFromAutomation`, a popup, -which the window it opened from places, and a window no longer shown. A dialog that doesn't block is +which the window it opened from places, and a window no longer shown. On macOS a native dialog holds +the UI thread, so a call made while one is open waits on it as every call that needs the UI thread does +(`blocked_by_dialog`) and never reaches that refusal. A dialog that doesn't block is hidden when it closes, so its ref still resolves; that refusal and the one for a stale ref point to `list_windows`. A window's geometry changes nothing in the project, so `set_window` is a recover call allowed during an operation that applies no mutate checks: it runs behind a modal dialog, on it, or on @@ -1686,7 +1688,11 @@ it un-minimizes, Windows activates a normal window it un-maximizes, and a Waylan 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 +out from the maximized window's decorations. On macOS a minimized window stays in the Dock until the +animation that brings it back ends, about half a second, and AppKit ignores a zoom until then, so a +window minimized while zoomed comes back zoomed; the wait for the window to settle takes it out of that +once it is back (`finish_restore()`), and it returns to the size and place it had before the zoom. A +size given meanwhile is kept, as it leaves the window no longer zoomed. 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 @@ -1725,7 +1731,11 @@ 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. +the window's zoomed state, not full screen, and `raise` brings the window in front of the app's other +windows, but while another app is active it stays behind that app's windows and `active` reads false. +OrcaSlicer doesn't activate itself for it, which would take the keyboard from the person's app, and no +tool needs it active: a capture reads a covered window whole and input goes through wx. 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 diff --git a/src/slic3r/GUI/CAD/DesignCanvas.cpp b/src/slic3r/GUI/CAD/DesignCanvas.cpp index c2b0b3aa14..e89f8c1e96 100644 --- a/src/slic3r/GUI/CAD/DesignCanvas.cpp +++ b/src/slic3r/GUI/CAD/DesignCanvas.cpp @@ -1109,9 +1109,14 @@ void DesignCanvas::set_on_context_menu(std::function cb) // guarantee rather than a coincidence. Pick first, so a right-click on a line offers // that line's verbs instead of the empty-selection vocabulary. Selecting an entity // that is already selected is a no-op, so a multi-entity pick survives a - // right-click on one of its members. - if (m_canvas && m_sketch_tool.select_at_screen(*m_canvas, m_ctx_press.x, m_ctx_press.y)) - request_repaint(); + // right-click on one of its members. The press is in the widget's logical pixels and + // the tool picks in the canvas's GL pixels, as GLCanvas3D::on_mouse() scales every + // event it passes on (twice as many on a Retina display). + if (m_canvas) { + const float scale = m_canvas->get_scale(); + if (m_sketch_tool.select_at_screen(*m_canvas, int(m_ctx_press.x * scale), int(m_ctx_press.y * scale))) + request_repaint(); + } m_on_context_menu(m_canvas_widget->ClientToScreen(m_ctx_press)); return; // consumed } diff --git a/src/slic3r/GUI/CAD/DesignSketchTool.hpp b/src/slic3r/GUI/CAD/DesignSketchTool.hpp index 156deaa519..84489047e3 100644 --- a/src/slic3r/GUI/CAD/DesignSketchTool.hpp +++ b/src/slic3r/GUI/CAD/DesignSketchTool.hpp @@ -590,9 +590,10 @@ public: out = m_entities[i].type; return true; } - // Right-click pick: select the entity (or point handle) under the given canvas pixel, so - // the context menu describes what was pointed at. No-op when it is already selected, or - // when nothing is there. Returns true if the selection changed. + // Right-click pick: select the entity (or point handle) under the given canvas pixel, in + // the canvas's GL pixels as its mouse events carry them, so the context menu describes + // what was pointed at. No-op when it is already selected, or when nothing is there. + // Returns true if the selection changed. bool select_at_screen(GLCanvas3D& canvas, int sx, int sy); // Open the in-canvas value field on the SELECTION's defining number (a line's length, an // arc's radius, a circle's diameter, the angle between two lines, a point-to-point or diff --git a/src/slic3r/GUI/CAD/DesignTextDialog.cpp b/src/slic3r/GUI/CAD/DesignTextDialog.cpp index 334f9afca8..120c153fde 100644 --- a/src/slic3r/GUI/CAD/DesignTextDialog.cpp +++ b/src/slic3r/GUI/CAD/DesignTextDialog.cpp @@ -105,7 +105,12 @@ DesignTextDialog::DesignTextDialog(wxWindow* parent, const Spec* initial) const wxArrayString& faces = font_faces(); for (const wxString& f : faces) m_face->Append(f); - const int sel = faces.Index(font.GetFaceName()); + // The font's face when it is installed, else the plain sans-serif that wxFONTFAMILY_SWISS maps + // to, else the first face. macOS's GUI font is its UI font, .AppleSystemUIFont, which is not an + // installed face; the first face there is a decorative one whose letters carry engraved holes. + int sel = faces.Index(font.GetFaceName()); + if (sel == wxNOT_FOUND) + sel = faces.Index(wxFont(wxFontInfo().Family(wxFONTFAMILY_SWISS)).GetFaceName()); m_face->SetSelection(sel != wxNOT_FOUND ? sel : 0); label(_L("Font")); form->Add(m_face, 1, wxEXPAND); diff --git a/src/slic3r/GUI/GUI_App.cpp b/src/slic3r/GUI/GUI_App.cpp index e2740baf94..cae413e274 100644 --- a/src/slic3r/GUI/GUI_App.cpp +++ b/src/slic3r/GUI/GUI_App.cpp @@ -3226,6 +3226,7 @@ bool GUI_App::on_init_inner() // Override wxWidgets' kAEGetURL handler so orcaslicer:// deep links keep // working after the wxWidgets 3.3.2 upgrade on macOS (#13119). register_mac_deep_link_handler(); + pause_window_animations_while_screens_sleep(); #endif #if BBL_RELEASE_TO_PUBLIC wxLog::SetLogLevel(wxLOG_Message); diff --git a/src/slic3r/GUI/Mcp/McpToolsUi.cpp b/src/slic3r/GUI/Mcp/McpToolsUi.cpp index c30fcb406f..3d3380014a 100644 --- a/src/slic3r/GUI/Mcp/McpToolsUi.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsUi.cpp @@ -1103,7 +1103,8 @@ wxTopLevelWindow* live_window(wxTopLevelWindow* window) // 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. +// the restore sizes the window again, and wx would size it by the maximized window's decorations. A window +// brought back from the minimized state is finished restoring once it is back (finish_restore(), macOS). ToolResult set_window(McpService& service, ToolContext& ctx, const json& args) { const json target = args.value("target", json("main")); @@ -1111,7 +1112,7 @@ 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, restoring = false; + bool main = false, modal = false, restoring = false, unminimizing = false; WindowSettling settling; const bool placing = args.contains("size") || args.contains("position"); const std::string state = arg_string(args, "state"); @@ -1129,6 +1130,7 @@ ToolResult set_window(McpService& service, ToolContext& ctx, const json& args) minimize_window(w); } else if (state == "normal") { settling.activation = settling.activation || (restore_needs_activation() && minimized(w)); + unminimizing = unminimizing || minimized(w); restore_window(w); } if (arg_bool(args, "raise", false)) @@ -1150,6 +1152,7 @@ ToolResult set_window(McpService& service, ToolContext& ctx, const json& args) window = &w; if (placing && std::string(window_state(w)) != "normal") { settling.activation = restore_needs_activation() && minimized(w); + unminimizing = minimized(w); restoring = restore_window(w); } if (!restoring) @@ -1199,6 +1202,8 @@ ToolResult set_window(McpService& service, ToolContext& ctx, const json& args) const json done = poll_until( ctx, [&]() -> json { + if (wxTopLevelWindow* w = live_window(window); w != nullptr && unminimizing) + unminimizing = !finish_restore(*w); settling.held = holds(wanted); if (!settling.held) return json(); diff --git a/src/slic3r/GUI/Mcp/WindowControl.cpp b/src/slic3r/GUI/Mcp/WindowControl.cpp index 74880dfe58..72d3fcf99f 100644 --- a/src/slic3r/GUI/Mcp/WindowControl.cpp +++ b/src/slic3r/GUI/Mcp/WindowControl.cpp @@ -353,6 +353,17 @@ bool restore_window(wxTopLevelWindow& window) #endif } +bool finish_restore([[maybe_unused]] wxTopLevelWindow& window) +{ +#if defined(__WXOSX__) + if (window.IsIconized()) + return false; + if (window.IsMaximized()) + window.Maximize(false); +#endif + return true; +} + void raise_window(wxTopLevelWindow& window) { window.Raise(); diff --git a/src/slic3r/GUI/Mcp/WindowControl.hpp b/src/slic3r/GUI/Mcp/WindowControl.hpp index 5422ae408a..da765a6eea 100644 --- a/src/slic3r/GUI/Mcp/WindowControl.hpp +++ b/src/slic3r/GUI/Mcp/WindowControl.hpp @@ -9,11 +9,12 @@ 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 +// 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. +// maximizes or minimizes a window unless the app does it itself. On macOS, AppKit ignores a zoom while a +// window is in the Dock, so a window minimized while zoomed comes back zoomed. 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(). @@ -41,8 +42,13 @@ 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. +// it reads back would go to the window as it was. A window it un-minimized may need finish_restore() too. bool restore_window(wxTopLevelWindow& window); +// Finishes restore_window() of a minimized window once the window has left the minimized state, and returns +// whether it is finished. On macOS the window stays in the Dock until the animation that brings it back +// ends, and AppKit ignores restore_window()'s un-zoom until then, so a window minimized while zoomed is +// un-zoomed here. Elsewhere restore_window() did it all. +bool finish_restore(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 diff --git a/src/slic3r/GUI/ObjectDataViewModel.cpp b/src/slic3r/GUI/ObjectDataViewModel.cpp index 7eaa8ee6bb..edd2ed6923 100644 --- a/src/slic3r/GUI/ObjectDataViewModel.cpp +++ b/src/slic3r/GUI/ObjectDataViewModel.cpp @@ -1009,6 +1009,9 @@ wxDataViewItem ObjectDataViewModel::Delete(const wxDataViewItem &item) } if (node->m_type & itObject) { + // The plater deletes the ModelObject before its row, and on macOS each notification below + // has the control re-read the tree at once, so the row must not read it from here on. + node->m_model_object = nullptr; auto it = find(m_objects.begin(), m_objects.end(), node); if (it != m_objects.end()) { @@ -1223,6 +1226,12 @@ wxDataViewItem ObjectDataViewModel::DeleteLastInstance(const wxDataViewItem &par void ObjectDataViewModel::ResetAll() { + // Every object row goes, and their ModelObjects may already be deleted (a new project clears the + // model first). On macOS each notification while the plates go has the control re-read the + // remaining rows at once, so none of them may read its ModelObject any more. + for (auto object : m_objects) + object->m_model_object = nullptr; + // BBS // FIX: should remove from children collection soon, or will conflict GetChildren while (!m_plates.empty()) { diff --git a/src/slic3r/Utils/MacDarkMode.hpp b/src/slic3r/Utils/MacDarkMode.hpp index 83a766b4e1..8d37ec6104 100644 --- a/src/slic3r/Utils/MacDarkMode.hpp +++ b/src/slic3r/Utils/MacDarkMode.hpp @@ -25,6 +25,8 @@ void set_title_colour_after_set_title(void * window); // window: it stays in sight when the parent is raised and moves with it. wx never attaches dialogs this // way (it broke modal dialogs across Spaces), so a macOS dialog otherwise falls behind a raised parent. void keep_window_above(void * window, void * parent, bool keep); +// Turns AppKit's window open and close animations off while the screens sleep. Called once, at startup. +void pause_window_animations_while_screens_sleep(); void initGestures(void * view, wxEvtHandler * handler); void openFolderForFile(wxString const & file); void StaticGroup_layoutBadge(void * group, void * badge); diff --git a/src/slic3r/Utils/MacDarkMode.mm b/src/slic3r/Utils/MacDarkMode.mm index 67a0fece4c..e07488dabe 100644 --- a/src/slic3r/Utils/MacDarkMode.mm +++ b/src/slic3r/Utils/MacDarkMode.mm @@ -100,6 +100,29 @@ void keep_window_above(void * window, void * parent, bool keep) [owner removeChildWindow:child]; } +// AppKit animates a window as it opens and closes, on a dispatch worker paced by the screen's +// display link. A sleeping screen never fires that link, and the link stays silent after the +// screen wakes, so each window shown or hidden while the screens sleep blocks a worker for good. +// The app driven unattended (over MCP, say) with the display off opens and closes dialogs by the +// hundred; once about 80 workers are blocked, libdispatch starts no more at that priority, and the +// OpenGL driver's texture uploads, which wait on that pool, hang the UI thread. The animations are +// therefore off while the screens sleep, and on otherwise, so the windows look as they always do. +void pause_window_animations_while_screens_sleep() +{ + // The registration domain lives in memory: nothing is written to the user's defaults. + auto set_animations = [](bool on) { + [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"NSAutomaticWindowAnimationsEnabled": @(on)}]; + }; + // The app may start with the display already off. + set_animations(!CGDisplayIsAsleep(CGMainDisplayID())); + NSNotificationCenter* center = [[NSWorkspace sharedWorkspace] notificationCenter]; + NSOperationQueue* main = [NSOperationQueue mainQueue]; + [center addObserverForName:NSWorkspaceScreensDidSleepNotification object:nil queue:main + usingBlock:^(NSNotification*) { set_animations(false); }]; + [center addObserverForName:NSWorkspaceScreensDidWakeNotification object:nil queue:main + usingBlock:^(NSNotification*) { set_animations(true); }]; +} + void WKWebView_evaluateJavaScript(void * web, wxString const & script, void (*callback)(wxString const &)) { [(WKWebView*)web evaluateJavaScript:wxCFStringRef(script).AsNSString() completionHandler: ^(id result, NSError *error) { diff --git a/tools/mcp/README.md b/tools/mcp/README.md index 61a52b7e02..65c966d99d 100644 --- a/tools/mcp/README.md +++ b/tools/mcp/README.md @@ -333,7 +333,9 @@ action goes through the UI tools (`set_view`, `click`, `mouse_gesture`, `press_k result back (`sketch_describe`, `describe_scene`, `describe_feature`, `list_verbs`), save for one call in the scale rung. Buttons and rows are found by label, and canvas positions come from a calibration that maps the open sketch's plane to canvas pixels, so nothing in them is tuned to a -window size, screen scaling or theme. What they share is in `cad_gui.py` beside them. +window size, screen scaling or theme. The sketch tool's pick budgets and badge layout are in the +canvas's GL pixels, which `cad_gui.py` turns into click pixels by the canvas scale that `set_view`'s +`camera_state` gives (`zoom` over `click_px_per_mm`). What they share is in `cad_gui.py` beside them. `test_cad_sketching.py` draws each sketch tool's primitive with clicks on the canvas and types its exact values into the canvas's value field, drives the edit operations and each constraint button on drawn geometry, undoes inside a sketch and across its commit, saves the project and opens it again diff --git a/tools/mcp/cad_gui.py b/tools/mcp/cad_gui.py index 923c558c2d..0b292bdbdd 100644 --- a/tools/mcp/cad_gui.py +++ b/tools/mcp/cad_gui.py @@ -28,10 +28,11 @@ sys.stdout.reconfigure(errors="backslashreplace") 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: -# close enough that a 40 mm line is long beside the pixel-sized reach of its value label, and far -# enough that the region calibrate() measures holds every shape the tests draw at the default -# window. +# reset_view()'s zoom, in click pixels per mm at the camera's target, about 1.6: close enough that a +# 40 mm line is long beside the pixel-sized reach of its value label, and far enough that the region +# calibrate() measures holds every shape the tests draw at the default window. In click pixels, so +# the tests' clicks have the same room on every display; set_view takes screenshot pixels, which +# are GL pixels, two per click pixel on a Retina display. RESET_ZOOM = 250 / 1.4 ** 15 # Where calibrate() clicks its probes, as shares of the canvas's width and height: four around @@ -42,12 +43,14 @@ RESET_ZOOM = 250 / 1.4 ** 15 PROBE_LAYOUTS = (((0.35, 0.35), (0.65, 0.35), (0.65, 0.65), (0.35, 0.65), (0.30, 0.45)), ((0.25, 0.25), (0.75, 0.25), (0.75, 0.75), (0.25, 0.75), (0.22, 0.42))) -# DesignSketchTool's pick budgets in Select, in screen pixels: a click within kLabelPx of a value -# label's centre takes the label, and one within kPickPx of a handle, a point or a curve takes it. +# DesignSketchTool's pixel budgets are in the canvas's GL pixels, which its mouse events carry: two +# per click pixel on a Retina display. CadGui.budget() turns one into click pixels. +# Its pick budgets in Select: a click within kLabelPx of a value label's centre takes the label, and +# one within kPickPx of a handle, a point or a curve takes it. LABEL_PICK_PX = 24.0 PICK_PX = 8.0 -# How far past those budgets clear_pick() keeps a click: a label's centre is read from the window -# it is drawn in, to a pixel or so. +# How far past those budgets clear_pick() keeps a click, in click pixels: a label's centre is read +# from the window it is drawn in, to a pixel or so. PICK_MARGIN_PX = 3.0 # DesignSketchTool::constraint_badges: each constraint's badge is an 11 px cell, the badges of one # entity stacked up the plane's +Y from its middle 1.5 cells apart, the first one step up. A click @@ -252,6 +255,7 @@ class CadGui: self.safe = None # (x0, x1, y0, y1) mm: the plane region the calibration probes covered self._H = None # plane -> canvas pixel self._size = None # (w, h) of the canvas _H maps onto + self.gl_per_px = 1.0 # the canvas's GL pixels per click pixel, from reset_view()'s camera_state # ------------------------------------------------------------ results @@ -501,15 +505,26 @@ class CadGui: empty design they turn the camera and keep its zoom and centre; the look_at and zoom it applies after the direction set both. N in a sketch squares the view to the sketch's plane and centres it on the plane's origin, keeping the zoom. Every map calibrate() fits stands - on this view, so the camera set_view reports is checked.""" + on this view, so the camera set_view reports is checked. Its camera_state gives the canvas's + GL pixels per click pixel, and the view is set again when they differ from the ones the zoom + assumed.""" origin = self.cad("describe_scene")["modeling_origin"] - state = self.client.call("set_view", tab="design", camera="top", look_at=origin, - zoom=RESET_ZOOM).get("camera_state", {}) + + def aim(): + return self.client.call("set_view", tab="design", camera="top", look_at=origin, + zoom=RESET_ZOOM * self.gl_per_px).get("camera_state", {}) + + state = aim() + if state.get("click_px_per_mm"): + gl_per_px = state["zoom"] / state["click_px_per_mm"] + if abs(gl_per_px - self.gl_per_px) > 1e-3: + self.gl_per_px = gl_per_px + state = aim() zoom, target = state.get("zoom"), state.get("look_at") - if (zoom is None or abs(zoom - RESET_ZOOM) > 1e-3 or target is None + if (zoom is None or abs(zoom - RESET_ZOOM * self.gl_per_px) > 1e-3 or target is None or max(abs(a - b) for a, b in zip(target, origin)) > 1e-3): raise RuntimeError(f"set_view left the Design camera at {state}, not at modeling_origin " - f"{origin} with zoom {RESET_ZOOM:.4f}") + f"{origin} with zoom {RESET_ZOOM * self.gl_per_px:.4f}") if self._sketch_or_none(): self.keys("n", target=CANVAS) @@ -718,11 +733,15 @@ class CadGui: back. A construction graded against it grades the tool, not the click's rounding.""" return self.unpx(*self._pixel(X, Y)) + def budget(self, gl_px): + """A length in the canvas's GL pixels, as DesignSketchTool's budgets are, in click pixels.""" + return gl_px / self.gl_per_px + def badge(self, line, k): """Where badge `k` (from 0) of the sketch line `line` is drawn, in mm (BADGE_STEP_PX).""" (ax, ay), (bx, by) = line["p0"], line["p1"] mx, my = (ax + bx) / 2.0, (ay + by) / 2.0 - return (mx, my + BADGE_STEP_PX * (k + 1) * self.mm_per_px(mx, my)) + return (mx, my + self.budget(BADGE_STEP_PX) * (k + 1) * self.mm_per_px(mx, my)) def move_mm(self, X, Y): u, v = self._pixel(X, Y) @@ -762,14 +781,15 @@ class CadGui: avoid_points = [self.px(*p) for e in [target] + others for p in _handles(e)] avoid_curves = [[self.px(*p) for p in _outline(e)] for e in others] w, h = self._size + pick, label = self.budget(PICK_PX), self.budget(LABEL_PICK_PX) best = None for q in sorted({(round(u), round(v)) for u, v in curve}): if not (0 <= q[0] < w and 0 <= q[1] < h): continue - slack = min([PICK_PX - _polyline_dist(q, curve)] - + [math.dist(q, a) - PICK_PX for a in avoid_points] - + [_polyline_dist(q, c) - PICK_PX for c in avoid_curves] - + [math.dist(q, (x + rw / 2.0, y + rh / 2.0)) - LABEL_PICK_PX for x, y, rw, rh in windows] + slack = min([pick - _polyline_dist(q, curve)] + + [math.dist(q, a) - pick for a in avoid_points] + + [_polyline_dist(q, c) - pick for c in avoid_curves] + + [math.dist(q, (x + rw / 2.0, y + rh / 2.0)) - label for x, y, rw, rh in windows] + [_rect_dist(q, r) for r in windows]) if best is None or slack > best[0]: best = (slack, q) diff --git a/tools/mcp/test_cad_click_edit.py b/tools/mcp/test_cad_click_edit.py index becf755af1..97286f9fb6 100755 --- a/tools/mcp/test_cad_click_edit.py +++ b/tools/mcp/test_cad_click_edit.py @@ -245,15 +245,15 @@ def width_label(edge, th): return ((ax + bx) / 2.0 + nx * off, (ay + by) / 2.0 + ny * off) -# The height of a value label, DesignSketchTool's 15 px. +# The height of a value label, DesignSketchTool's 15 px, in the canvas's GL pixels as its badges are. LABEL_PX = 15.0 -def width_on_badge(mm_per_px, k): +def width_on_badge(mm_per_gl_px, k): """The width at which a rectangle's width label is centred on its top edge's badge `k`: the label sits max(0.18 L, 8) + 1.5 mm and 0.7 label heights off the edge (width_label), and the badge - BADGE_STEP_PX * (k + 1) over the edge's middle (CadGui.badge).""" - return ((BADGE_STEP_PX * (k + 1) - 0.7 * LABEL_PX) * mm_per_px - 1.5) / 0.18 + BADGE_STEP_PX * (k + 1) over the edge's middle (CadGui.badge), both pixel lengths in GL pixels.""" + return ((BADGE_STEP_PX * (k + 1) - 0.7 * LABEL_PX) * mm_per_gl_px - 1.5) / 0.18 def rung_label(): @@ -266,7 +266,7 @@ def rung_label(): fields), so it is where its clicks put it, and Esc then drops the tool to Select. A shape's labels show while it is picked, so a click on its top edge picks it first.""" gui.enter_sketch("r") - width = width_on_badge(gui.mm_per_px(0, 30), 2) + width = width_on_badge(gui.mm_per_px(0, 30) / gui.gl_per_px, 2) gui.click_mm(*inside((-width / 2.0, 30))) gui.click_mm(*inside((width / 2.0, -30))) if until(gui.value_field) is None: @@ -291,11 +291,11 @@ def rung_label(): raise AssertionError("the click on the top edge picked nothing") # The label's centre, read from the window it is drawn in; the badge under it, from the layout. - mm_per_px = gui.mm_per_px(*mid) - want = gui.px(*width_label(top, LABEL_PX * mm_per_px)) + mm_per_gl_px = gui.mm_per_px(*mid) / gui.gl_per_px + want = gui.px(*width_label(top, LABEL_PX * mm_per_gl_px)) x, y, w, h = min(gui.overlays(), key=lambda r: math.dist((r[0] + r[2] / 2.0, r[1] + r[3] / 2.0), want)) centre = (x + w / 2.0, y + h / 2.0) - if math.dist(centre, gui.px(*gui.badge(top, 2))) > BADGE_PICK_PX: + if math.dist(centre, gui.px(*gui.badge(top, 2))) > gui.budget(BADGE_PICK_PX): raise AssertionError(f"the width label's centre {centre} is off the top edge's third badge " f"{gui.px(*gui.badge(top, 2))}: the badge or label layout moved, and this rung " f"no longer clicks a label drawn over a badge") diff --git a/tools/mcp/test_cad_context_menu.py b/tools/mcp/test_cad_context_menu.py index 325f69e4c6..56f5cacd62 100755 --- a/tools/mcp/test_cad_context_menu.py +++ b/tools/mcp/test_cad_context_menu.py @@ -690,9 +690,9 @@ def tf_fixture(cx, cy, W, L=40): def tf_label(pivot, handle, at): """Where the transform gizmo prints its value, by its own formula (render_tf_gizmo): past the - handle, away from the pivot, by 1.2 label heights, a label height being 15 px in millimetres - at `at`.""" - th = max(15.0 * gui.mm_per_px(*at), 1e-4) + handle, away from the pivot, by 1.2 label heights, a label height being 15 GL pixels in + millimetres at `at`.""" + th = max(gui.budget(15.0) * gui.mm_per_px(*at), 1e-4) d = (handle[0] - pivot[0], handle[1] - pivot[1]) n = math.hypot(*d) or 1.0 return (handle[0] + d[0] / n * th * 1.2, handle[1] + d[1] / n * th * 1.2) @@ -700,8 +700,8 @@ def tf_label(pivot, handle, at): def tf_count_label(pivot, at): """Where an array gizmo prints its count ("x4"), by render_tf_gizmo's formula: 1.5 label - heights up and right of the pivot.""" - th = max(15.0 * gui.mm_per_px(*at), 1e-4) + heights up and right of the pivot, a label height being 15 GL pixels.""" + th = max(gui.budget(15.0) * gui.mm_per_px(*at), 1e-4) return (pivot[0] + th * 1.5, pivot[1] + th * 1.5) diff --git a/tools/mcp/test_cad_sketching.py b/tools/mcp/test_cad_sketching.py index 38e2004c58..205f0ed0dc 100755 --- a/tools/mcp/test_cad_sketching.py +++ b/tools/mcp/test_cad_sketching.py @@ -276,8 +276,8 @@ def rung_voids(): def op_label_mm(anchor, direction, value, at): """Where an operation's value label sits: past the arrow's tip at anchor + dir * value, by 1.2 - label heights, a label height being 15 px in millimetres at `at`.""" - th = max(15 * gui.mm_per_px(*at), 1e-4) + label heights, a label height being 15 GL pixels in millimetres at `at`.""" + th = max(gui.budget(15.0) * gui.mm_per_px(*at), 1e-4) n = math.hypot(*direction) d = (direction[0] / n, direction[1] / n) tip = (anchor[0] + d[0] * value, anchor[1] + d[1] * value) diff --git a/tools/mcp/test_set_view_camera.py b/tools/mcp/test_set_view_camera.py index f1cc8d2d15..420c39bfcf 100644 --- a/tools/mcp/test_set_view_camera.py +++ b/tools/mcp/test_set_view_camera.py @@ -22,7 +22,7 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import orca_mcp # noqa: E402 MODEL = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "resources", "handy_models", "OrcaCube_v2.drc") -# The Design GUI tests' zoom, cad_gui.RESET_ZOOM. +# The Design GUI tests' zoom where a canvas has one GL pixel per click pixel, cad_gui.RESET_ZOOM. DESIGN_ZOOM = 250 / 1.4**15 diff --git a/tools/mcp/test_set_window.py b/tools/mcp/test_set_window.py index 7f8d50398b..6195aa7ec9 100644 --- a/tools/mcp/test_set_window.py +++ b/tools/mcp/test_set_window.py @@ -192,6 +192,10 @@ def main(): normal = client.call("set_window", state="normal") check("maximized, minimized, then normal: the reply says normal", normal.get("state") == "normal", normal) check("without a note that the window manager kept the request waiting", "note" not in normal, normal) + # On macOS the window comes back from the Dock zoomed and is un-zoomed once it is back, so it must not + # turn maximized again after the reply. + time.sleep(1) + check("and list_windows still reads it normal a second later", main_entry().get("state") == "normal", main_entry()) client.call("set_window", state="maximized") client.call("set_window", state="minimized") sized = client.call("set_window", size=[1350, 880])