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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
"""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)