"""AT-SPI computation lane for SolveSpace (parametric 2D/3D CAD, GTK3 + OpenGL). CORE FUNCTION = drive real model geometry to a COMPUTED number and read it back. Every test feeds an input (a menu accelerator / do_action that runs an Analyze command, or a Dimension-Units setting) and asserts the exact value SolveSpace computed on the running reference and displayed in its Message/Error dialog. All asserted values were OBSERVED on the running reference (a pre-loaded box with a translate/step group), never read from source: - Measure Volume -> "The volume of the solid model is:" + "3 cm3" - Measure Area -> "This group does not contain a correctly-formed 2d closed area." - Measure Perimeter-> "Bad selection for perimeter; select line segments, arcs, and curves." - Units->Inches, Measure Volume -> value reported in "in3" (setting -> value round-trip) - Show Naked Edges -> "The model contains 24 triangles, from 12 surfaces." - Show Interfering Parts -> "6 edges interfere with other triangles, bad." Mechanics (proven by recon): menu items have NO usable coordinates -> cannot be pixel-clicked. Inline commands fire via do_action(item,"click"); measure commands open a MODAL message dialog (separate X window) so they are driven by keyboard ACCELERATOR into the focused+hovered graphics window (never plain do_action, which would hang in the modal's nested loop). Dialog labels are read via AT-SPI (the primary verdict); the dialog is a separate X window dismissed by activating it and clicking OK's live bottom-center geometry. """ import os, time, subprocess, gi gi.require_version("Atspi", "2.0") from gi.repository import Atspi # noqa: E402 import pytest # noqa: E402 from pytest_check import check # noqa: E402 import rb_atspi # noqa: E402 # --------------------------------------------------------------------------- # # Embedded helpers (encode the proven SolveSpace mechanics; module-local only) # --------------------------------------------------------------------------- # def _gw(app): """The graphics-window frame (the one that owns the menu bar), not the Property Browser.""" for i in range(app.get_child_count()): f = app.get_child_at_index(i) nm = f.get_name() or "" if "SolveSpace" in nm and "Property Browser" not in nm: return f return rb_atspi.get_main_frame(app) def _item(app, name): """A `check menu item` in the graphics window's menu bar, by its plain (mnemonic-stripped) visible label.""" return rb_atspi.find_first(_gw(app), role="check menu item", name=name) def _alert_labels(app): """All non-empty label texts across every showing `alert` (message/error) dialog currently owned by the app.""" out = [] for i in range(app.get_child_count()): f = app.get_child_at_index(i) if f.get_role_name() == "alert" and rb_atspi.is_showing(f): for l in rb_atspi.find_all(f, role="label"): if l.get_name(): out.append(l.get_name()) return out def _labels_text(app): """All alert label text joined into one string (dialogs split multi-line messages across labels; join so substring assertions are split-agnostic).""" return "\n".join(_alert_labels(app)) def _dialog_wids(app): """X window ids of the app's open Message-/Error- dialogs (separate windows).""" pid = app.get_process_id() r = subprocess.run( ["xdotool", "search", "--pid", str(pid)], capture_output=True, text=True ) wids = [] for w in r.stdout.split(): nm = subprocess.run( ["xdotool", "getwindowname", w], capture_output=True, text=True ).stdout.strip() if nm.startswith("Message —") or nm.startswith("Error —"): wids.append(w) return wids def _close_dialogs(app, rounds=6): """Force-close any open Message-/Error- dialog by activating its X window and clicking OK's live bottom-center (AT-SPI OK extents go stale under overlap).""" for _ in range(rounds): wids = _dialog_wids(app) if not wids: break for w in wids: g = subprocess.run( ["xdotool", "getwindowgeometry", "--shell", w], capture_output=True, text=True, ).stdout d = dict(l.split("=") for l in g.strip().splitlines() if "=" in l) if not d: continue subprocess.run(["xdotool", "windowactivate", "--sync", w]) time.sleep(0.2) cx = int(d["X"]) + int(d["WIDTH"]) // 2 cy = int(d["Y"]) + int(d["HEIGHT"]) - 22 subprocess.run(["xdotool", "mousemove", str(cx), str(cy), "click", "1"]) time.sleep(0.3) def _gw_wid(app): """X window id of the graphics window (not the PB, not a dialog).""" pid = app.get_process_id() r = subprocess.run( ["xdotool", "search", "--pid", str(pid)], capture_output=True, text=True ) for w in r.stdout.split(): nm = subprocess.run( ["xdotool", "getwindowname", w], capture_output=True, text=True ).stdout.strip() if ( nm.endswith("— SolveSpace") and "Property Browser" not in nm and not nm.startswith(("Message", "Error")) ): return w return None def _accel(app, keys): """Focus+raise the graphics window, hover the canvas, then send an accelerator (e.g. 'ctrl+shift+v'). The key is dropped unless the GW is focused AND the pointer is over its canvas first.""" wid = _gw_wid(app) if wid: subprocess.run( ["xdotool", "windowactivate", "--sync", wid, "windowfocus", wid] ) time.sleep(0.4) subprocess.run(["xdotool", "mousemove", "400", "400"]) time.sleep(0.2) subprocess.run(["xdotool", "key", "--clearmodifiers", keys]) time.sleep(0.8) def _wait_alert(app, timeout=6.0): """Poll until at least one alert label is readable; True if a dialog appeared.""" return rb_atspi.wait_for(lambda: len(_alert_labels(app)) > 0, timeout=timeout) def _raise_dialogs(app): """Activate/raise any open Message-/Error- dialog so a full-screen grab captures it. do_action-opened dialogs (Measure Area) open UN-raised behind the GW; accel dialogs already raise the GW first, so this is a no-op for them. Call right before screenshot_assert so the shot is deterministic regardless of trigger.""" for w in _dialog_wids(app): subprocess.run(["xdotool", "windowactivate", "--sync", w]) time.sleep(0.4) # --------------------------------------------------------------------------- # # Order-independence: clear leftover dialogs + restore units to Millimeters # --------------------------------------------------------------------------- # @pytest.fixture(autouse=True, scope="module") def _clean_between(app): """Before the module and after EACH test, force-close any leftover Message-/Error- dialog and restore Dimension Units to Millimeters so every test starts from the same known state and none can wedge the next.""" _close_dialogs(app) _restore_mm(app) yield _close_dialogs(app) _restore_mm(app) def _restore_mm(app): """Set Dimension Units back to Millimeters if not already (a no-op click on an already-checked radio is harmless; guarded so we don't toggle spuriously).""" mm = _item(app, "Dimensions in Millimeters") if mm is not None and not rb_atspi.is_checked(mm): rb_atspi.do_action(mm, "click") time.sleep(0.4) @pytest.fixture(autouse=True) def _post_test_cleanup(app): """Per-test teardown: never leave a modal open (it would block the next test).""" yield _close_dialogs(app) _restore_mm(app) # --------------------------------------------------------------------------- # # Tests # --------------------------------------------------------------------------- # @pytest.mark.rb( jump_kind="value", expect="Message dialog: 'The volume of the solid model is:' and '3 cm3'", ) def test_measure_volume_reports_3cm3(app, rb, results_dir): """Measure Volume computes the box's volume = 3 cm3 (core CAD function: real triangulated geometry -> a computed number in a message dialog).""" _close_dialogs(app) assert _item(app, "Measure Volume") is not None, "Analyze>Measure Volume missing" rb.enter("measure volume dialog") # accelerator opens a modal -> crosses a surface _accel(app, "ctrl+shift+v") got = _wait_alert(app, timeout=6.0) check.is_true(got, "Measure Volume produced no message dialog") text = _labels_text(app) check.is_in( "volume of the solid model", text, f"volume-of-solid-model phrasing absent; labels={text!r}", ) # The computed magnitude+unit, observed on the reference for this box. check.is_true( "3 cm³" in text or ("cm³" in text and "3" in text), f"expected computed volume '3 cm3' absent; labels={text!r}", ) _raise_dialogs(app) rb_atspi.screenshot_assert( "test_measure_volume_reports_3cm3", "A SolveSpace 'Message' dialog reading 'The volume of the solid model is:' " "with the computed value '3 cm3' below it, and an OK button.", results_dir, ) _close_dialogs(app) @pytest.mark.rb( jump_kind="value", expect="Error dialog: 'This group does not contain a correctly-formed 2d closed area.'", ) def test_measure_area_error_not_closed_2d(app, rb, results_dir): """Measure Area on the active 3d translate group is real validation output: the group is not a closed 2d region, so it reports the specific error.""" _close_dialogs(app) item = _item(app, "Measure Area") assert item is not None, "Analyze>Measure Area missing" rb.enter("measure area dialog") # Area does NOT need the accelerator: do_action fires it and its dialog does not # block the D-Bus reply here (confirmed on the reference). rb_atspi.do_action(item, "click") got = _wait_alert(app, timeout=6.0) check.is_true(got, "Measure Area produced no dialog") text = _labels_text(app) check.is_in( "correctly-formed 2d closed area", text, f"expected closed-area validation error absent; labels={text!r}", ) _raise_dialogs(app) rb_atspi.screenshot_assert( "test_measure_area_error_not_closed_2d", "A SolveSpace 'Error' dialog reading 'This group does not contain a " "correctly-formed 2d closed area. It is open, not coplanar, or " "self-intersecting.' with an OK button.", results_dir, ) _close_dialogs(app) @pytest.mark.rb( jump_kind="value", expect="Error dialog: 'Bad selection for perimeter; select line segments, arcs, and curves.'", ) def test_measure_perimeter_bad_selection(app, rb, results_dir): """Measure Perimeter with nothing selected reports the specific bad-selection validation message observed on the reference for this group.""" _close_dialogs(app) assert _item(app, "Measure Perimeter") is not None, "Analyze>Measure Perimeter missing" rb.enter("measure perimeter dialog") _accel(app, "ctrl+shift+p") got = _wait_alert(app, timeout=6.0) if not got: pytest.skip("Measure Perimeter produced no dialog in this environment") text = _labels_text(app) check.is_in( "Bad selection for perimeter", text, f"expected perimeter bad-selection message absent; labels={text!r}", ) _raise_dialogs(app) rb_atspi.screenshot_assert( "test_measure_perimeter_bad_selection", "A SolveSpace 'Error' dialog reading 'Bad selection for perimeter; select " "line segments, arcs, and curves.' with an OK button.", results_dir, ) _close_dialogs(app) @pytest.mark.rb( jump_kind="value", expect="After Units->Inches, Measure Volume reports the value in 'in3' (not cm3/mm3)", ) def test_measure_volume_units_inches_roundtrip(app, rb, results_dir): """Setting -> value round-trip: switching Dimension Units to Inches changes the Measure Volume unit token from 'cm3' to 'in3' (same geometry, unit follows the setting). Restores Millimeters at the end so order-independence holds.""" _close_dialogs(app) inches = _item(app, "Dimensions in Inches") mm = _item(app, "Dimensions in Millimeters") assert inches is not None and mm is not None, "Dimension Units radio items missing" # Baseline: in Millimeters the volume prints the metric token (precondition of # the round-trip, not the verdict). _restore_mm(app) _accel(app, "ctrl+shift+v") _wait_alert(app, timeout=6.0) mm_text = _labels_text(app) _close_dialogs(app) check.is_true( "cm³" in mm_text or "mm³" in mm_text, f"metric volume token absent before unit switch; labels={mm_text!r}", ) # Input: switch units to Inches, then open a volume dialog in the new unit. rb.enter("measure volume dialog (inches)") rb_atspi.do_action(inches, "click") check.is_true( rb_atspi.wait_for(lambda: rb_atspi.is_checked(inches), timeout=3.0), "Dimensions in Inches did not become checked", ) time.sleep(0.3) # Output: the recomputed volume now reports inches (in3). _accel(app, "ctrl+shift+v") got = _wait_alert(app, timeout=6.0) check.is_true(got, "Measure Volume produced no dialog after switching to Inches") in_text = _labels_text(app) check.is_in( "in³", in_text, f"expected cubic-inch token 'in3' after switching units; labels={in_text!r}", ) check.is_in( "volume of the solid model", in_text, f"volume phrasing missing in inches dialog; labels={in_text!r}", ) # The token genuinely CHANGED (not still metric) -> proves the setting drove it. check.is_false( "cm³" in in_text or "mm³" in in_text, f"metric token still present after switching to Inches; labels={in_text!r}", ) _raise_dialogs(app) rb_atspi.screenshot_assert( "test_measure_volume_units_inches_roundtrip", "A SolveSpace 'Message' dialog after switching Dimension Units to Inches: " "'The volume of the solid model is:' with the value expressed in cubic " "inches (a number followed by 'in3').", results_dir, ) _close_dialogs(app) # Restore Millimeters and confirm the token round-trips back to metric. rb_atspi.do_action(mm, "click") check.is_true( rb_atspi.wait_for(lambda: rb_atspi.is_checked(mm), timeout=3.0), "Dimensions in Millimeters did not restore", ) time.sleep(0.3) _accel(app, "ctrl+shift+v") _wait_alert(app, timeout=6.0) back_text = _labels_text(app) check.is_true( "cm³" in back_text or "mm³" in back_text, f"metric token did not return after restoring Millimeters; labels={back_text!r}", ) _close_dialogs(app) @pytest.mark.rb( jump_kind="value", expect="Message dialog: 'The model contains 24 triangles, from 12 surfaces.'", ) def test_naked_edges_reports_triangle_surface_counts(app, rb, results_dir): """Show Naked Edges runs a mesh analysis and reports the model's computed triangle and surface counts (24 triangles, 12 surfaces) observed for this box.""" _close_dialogs(app) assert _item(app, "Show Naked Edges") is not None, "Analyze>Show Naked Edges missing" rb.enter("naked edges dialog") _accel(app, "ctrl+shift+n") got = _wait_alert(app, timeout=6.0) check.is_true(got, "Show Naked Edges produced no dialog") text = _labels_text(app) # Exact computed counts observed on the reference model. check.is_in( "24 triangles", text, f"expected computed '24 triangles' absent; labels={text!r}", ) check.is_in( "12 surfaces", text, f"expected computed '12 surfaces' absent; labels={text!r}", ) # The full computed sentence, tolerant to label splitting. check.is_in( "The model contains", text, f"triangle/surface-count sentence absent; labels={text!r}", ) _raise_dialogs(app) rb_atspi.screenshot_assert( "test_naked_edges_reports_triangle_surface_counts", "A SolveSpace analysis dialog whose text includes 'The model contains 24 " "triangles, from 12 surfaces.' (mesh naked-edge/self-intersection report).", results_dir, ) _close_dialogs(app) @pytest.mark.rb( jump_kind="value", expect="Error dialog: '6 edges interfere with other triangles, bad.'", ) def test_interference_reports_edge_count(app, rb, results_dir): """Show Interfering Parts runs a self-intersection analysis and reports the computed count of interfering edges (6) for this model's mesh.""" _close_dialogs(app) assert _item(app, "Show Interfering Parts") is not None, "Analyze>Show Interfering Parts missing" rb.enter("interference dialog") _accel(app, "ctrl+shift+i") got = _wait_alert(app, timeout=6.0) check.is_true(got, "Show Interfering Parts produced no dialog") text = _labels_text(app) check.is_in( "6 edges interfere", text, f"expected computed '6 edges interfere' absent; labels={text!r}", ) check.is_in( "interfere with other triangles", text, f"interference sentence absent; labels={text!r}", ) _raise_dialogs(app) rb_atspi.screenshot_assert( "test_interference_reports_edge_count", "A SolveSpace 'Error' dialog reading '6 edges interfere with other " "triangles, bad.' with an OK button.", results_dir, ) _close_dialogs(app)