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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
"""AT-SPI menu (navigation) lane for SolveSpace (parametric 2D/3D CAD, GTK3 + OpenGL).

This lane tests MENUS AS NAVIGATION: triggering a menu command produces an
APP-AUTHORED EFFECT that identifies WHERE it navigated to --

  * a NEW modal DIALOG appears, identified by its CONTENT (reach), or
  * the OPAQUE OpenGL Property Browser canvas navigates to a specific text
    SCREEN (transition; verified by screenshot because the PB content is not in
    the AT-SPI tree).

It deliberately does NOT own CHECKED flips (state lane) and does NOT assert the
computed value inside a dialog (computation lane) -- here the verdict is the
NAVIGATION IDENTITY: which dialog opened, or which PB screen was reached.

All effects below were OBSERVED on the running reference (a pre-loaded box with a
translate/step group; active group = translate). Nothing is read from source.

PROVEN MECHANICS (verified at author time on the running reference):
- Menu-bar `check menu item` nodes have INVALID extents (-2147483648) -> cannot be
  pixel-clicked. Commands fire via ``do_action(item,"click")`` (PB-navigating /
  inline) or ``do_action_safe(item,"click")`` (modal-opener About -- bounded so a
  nested dialog loop can't hang the module).
- Modal message dialogs are role ``alert`` / name "Information", SEPARATE X windows
  titled "Message -- SolveSpace" with readable `label` children + an OK push button.
  They appear in the tree, so ``rb_showing``/``rb_reach`` prove the reach (the
  "Information" alert surface newly appears); the labels prove it is the RIGHT dialog.
- The Property Browser is an OPAQUE OpenGL text canvas: "PB navigated to screen X"
  is verified by ``screenshot_assert`` (VLM) cropped to the PB frame, NOT by reading
  tree text -- expected and correct for this app.
- Pressing Escape in the PB window navigates it back to the group-list HOME screen
  (verified) -- the teardown uses this to reset the PB between tests.
"""

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
from rb_atspi import rb_showing, rb_reach  # noqa: E402


# --------------------------------------------------------------------------- #
# Embedded helpers (encode the proven SolveSpace menu-navigation mechanics)
# --------------------------------------------------------------------------- #
def _gw(app):
    """The graphics-window frame (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 _pb(app):
    """The Property Browser top-level frame, or None if it is not present."""
    for i in range(app.get_child_count()):
        f = app.get_child_at_index(i)
        if "Property Browser" in (f.get_name() or ""):
            return f
    return None


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 (with spaces collapsed) so identity substrings
    match regardless of how a multi-line message is split across labels or wrapped
    with embedded newlines (e.g. 'GNU\\nGeneral Public License')."""
    return " ".join(" ".join(_alert_labels(app)).split())


# --- modal message/error dialog handling (separate X windows) --------------- #
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 _dialog_present(app):
    """True while any Message-/Error- dialog X window is open."""
    return len(_dialog_wids(app)) > 0


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 _raise_dialogs(app):
    """Activate/raise any open Message-/Error- dialog so a full-screen grab captures
    it on top. do_action-opened dialogs can open UN-raised behind the GW."""
    for w in _dialog_wids(app):
        subprocess.run(["xdotool", "windowactivate", "--sync", w])
    time.sleep(0.4)


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)


# --- graphics window / accelerator (for keyboard-triggered menu commands) ---- #
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 _pb_wid(app):
    """X window id of the Property Browser window."""
    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.startswith("Property Browser"):
            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 _pb_home(app):
    """Reset the Property Browser to its group-list HOME screen. Pressing Escape in
    the PB window returns it home (verified on the reference). Best-effort; each
    PB-navigation test also triggers its OWN navigation, so a stale screen would be
    overwritten regardless."""
    w = _pb_wid(app)
    if w:
        subprocess.run(["xdotool", "windowactivate", "--sync", w])
        time.sleep(0.2)
        subprocess.run(["xdotool", "key", "--clearmodifiers", "Escape"])
        time.sleep(0.4)


# --------------------------------------------------------------------------- #
# Order-independence: no leftover dialog, PB back home, before + after each test
# --------------------------------------------------------------------------- #
@pytest.fixture(autouse=True, scope="module")
def _clean_module(app):
    _close_dialogs(app)
    _pb_home(app)
    yield
    _close_dialogs(app)
    _pb_home(app)


@pytest.fixture(autouse=True)
def _clean_between(app):
    """Per-test teardown on this shared single-instance app: close any Message-/Error-
    dialog and return the PB to its home screen so the next test starts clean."""
    yield
    _close_dialogs(app)
    _pb_home(app)


# --------------------------------------------------------------------------- #
# A. Menu command -> a NEW DIALOG appears (reach)
# --------------------------------------------------------------------------- #
@pytest.mark.rb(
    jump_kind="reach",
    expect="Help>About opens the 'Information' alert whose text says SolveSpace is free software under the GNU General Public License",
)
def test_about_menu_opens_about_dialog(app, rb, results_dir):
    """Help > About navigates to the About dialog: a new modal 'Information' alert
    window materialises (the graphics-window menu is the source; the alert is the
    target). Asserted BOTH ways: (a) rb_reach proves the 'Information' alert surface
    newly APPEARED, and (b) its labels contain the About-identifying text
    ('free software' / 'GNU General Public License') so it is the RIGHT dialog, not
    just any alert. The version number is intentionally NOT asserted (it drifts)."""
    _close_dialogs(app)
    it = _item(app, "About")
    assert it is not None, "Help>About menu item missing"

    before = rb_showing(app)
    rb.enter("about dialog")  # a modal opens -> a real surface crossing (depth 1)
    # About opens a modal -> do_action_safe (bounded), never a plain blocking do_action.
    rb_atspi.do_action_safe(it, "click")

    got = _wait_alert(app, timeout=6.0)
    check.is_true(got, "About produced no 'Information' dialog")
    after = rb_showing(app)

    # (a) The reach: the alert surface appeared that was not there before.
    check.is_true(
        rb_reach(before, after, target="Information"),
        "About did not open a new 'Information' alert surface (reach not proven)",
    )
    check.is_true(_dialog_present(app), "no 'Message — SolveSpace' dialog window after About")

    # (b) It is the ABOUT dialog specifically (identity), tolerant to label splitting
    #     and the embedded newline in 'GNU\nGeneral Public License'.
    text = _labels_text(app)
    check.is_in(
        "free software", text,
        f"About dialog does not mention 'free software'; labels={text!r}",
    )
    check.is_in(
        "General Public License", text,
        f"About dialog does not mention the GNU General Public License; labels={text!r}",
    )

    _raise_dialogs(app)
    rb_atspi.screenshot_assert(
        "test_about_menu_opens_about_dialog",
        "A SolveSpace 'Message' dialog (the About box) whose body text states that "
        "SolveSpace is free software you may modify and redistribute under the terms "
        "of the GNU General Public License (GPL) version 3 or later, mentions NO "
        "WARRANTY, and shows a copyright line '© 2008-... Jonathan Westhues and other "
        "authors', with a single OK button.",
        results_dir,
    )
    _close_dialogs(app)


@pytest.mark.rb(
    jump_kind="reach",
    expect="Analyze>Measure Volume (Ctrl+Shift+V) opens the 'Information' alert reporting 'The volume of the solid model is:'",
)
def test_measure_volume_menu_opens_volume_dialog(app, rb, results_dir):
    """Analyze > Measure Volume, triggered by its keyboard accelerator into the
    focused graphics window, navigates to a result dialog: a new modal 'Information'
    alert appears (reach) whose text identifies it as the VOLUME report ('the volume
    of the solid model'). This lane proves the menu navigation opened the RIGHT
    dialog; the exact computed magnitude/unit is the computation lane's job."""
    _close_dialogs(app)
    assert _item(app, "Measure Volume") is not None, "Analyze>Measure Volume missing"

    before = rb_showing(app)
    rb.enter("measure volume dialog")  # accelerator opens a modal -> depth 1
    _accel(app, "ctrl+shift+v")

    got = _wait_alert(app, timeout=6.0)
    if not got:
        pytest.skip("Measure Volume produced no dialog in this environment (focus)")
    after = rb_showing(app)

    # The reach: a new 'Information' alert surface appeared.
    check.is_true(
        rb_reach(before, after, target="Information"),
        "Measure Volume did not open a new 'Information' alert surface (reach not proven)",
    )
    check.is_true(_dialog_present(app), "no 'Message — SolveSpace' dialog window after Measure Volume")

    # Identity (not the value): it is the VOLUME dialog.
    text = _labels_text(app)
    check.is_in(
        "volume of the solid model", text,
        f"opened dialog is not the volume report; labels={text!r}",
    )

    _raise_dialogs(app)
    rb_atspi.screenshot_assert(
        "test_measure_volume_menu_opens_volume_dialog",
        "A SolveSpace 'Message' dialog opened from Analyze > Measure Volume, reading "
        "'The volume of the solid model is:' followed by a value, and mentioning that "
        "curved surfaces have been approximated as triangles, with an OK button.",
        results_dir,
    )
    _close_dialogs(app)


# --------------------------------------------------------------------------- #
# B. Menu command -> the Property Browser navigates to a specific SCREEN
#    (opaque OpenGL canvas -> the screenshot is the verdict; marked transition)
# --------------------------------------------------------------------------- #
@pytest.mark.rb(
    jump_kind="transition",
    expect="Edit>Line Styles... navigates the Property Browser to the Line Styles screen (a 'color / style-name' list: s001-#def-active-grp, s002-#def-construction, ...)",
)
def test_line_styles_navigates_property_browser(app, rb, frame, results_dir):
    """Edit > Line Styles... navigates the Property Browser (an opaque OpenGL text
    canvas) to its Line Styles screen. Because the PB content is not exposed in the
    AT-SPI tree, the app-authored effect is verified by screenshot: the PB now shows
    a 'color / style-name' header over a list of named styles. Programmatic guards
    confirm the command was reachable and produced NO error dialog (a failed
    navigation would); the screenshot carries the identity verdict. Teardown returns
    the PB home via Escape."""
    _close_dialogs(app)
    _pb_home(app)
    it = _item(app, "Line Styles...")
    assert it is not None, "Edit>Line Styles... missing"
    check.is_true(rb_atspi.is_enabled(it), "Line Styles... is not enabled")
    check.is_true(_pb(app) is not None, "Property Browser frame is not present")

    rb.enter("line styles screen")  # navigating the PB is a real surface crossing
    rb_atspi.do_action(it, "click")
    time.sleep(0.8)

    # This navigates the PB in place; it must NOT pop an error dialog.
    check.is_false(
        _dialog_present(app),
        "Line Styles... unexpectedly opened a dialog instead of navigating the PB",
    )

    w = _pb_wid(app)
    if w:  # bring the PB to the front so the crop captures the new screen on top
        subprocess.run(["xdotool", "windowraise", w])
        time.sleep(0.3)
    rb_atspi.screenshot_assert(
        "test_line_styles_navigates_property_browser",
        "The SolveSpace Property Browser panel showing its LINE STYLES screen: a "
        "two-column header 'color   style-name' above a vertical list of style rows, "
        "each with a small colored swatch on the left and a name like "
        "'s001-#def-active-grp', 's002-#def-construction', 's003-#def-inactive-grp', "
        "'s004-#def-datum', 's005-#def-solid-edge'. NOT a group list of "
        "g001/g002/g003 rows.",
        results_dir,
        window=_pb(app),
    )
    _pb_home(app)


@pytest.mark.rb(
    jump_kind="transition",
    expect="Edit>View Projection... navigates the Property Browser to the '3D VIEW PARAMETERS' screen (overall scale factor, origin, projection right/up/out vectors)",
)
def test_view_projection_navigates_property_browser(app, rb, frame, results_dir):
    """Edit > View Projection... navigates the Property Browser to its projection /
    view-parameters screen (opaque OpenGL canvas). Verified by screenshot: the PB now
    shows a '3D VIEW PARAMETERS' screen with the overall scale factor, the origin, and
    the projection right/up/out basis vectors. Programmatic guards confirm reachability
    and that no error dialog popped. Teardown returns the PB home."""
    _close_dialogs(app)
    _pb_home(app)
    it = _item(app, "View Projection...")
    assert it is not None, "Edit>View Projection... missing"
    check.is_true(rb_atspi.is_enabled(it), "View Projection... is not enabled")
    check.is_true(_pb(app) is not None, "Property Browser frame is not present")

    rb.enter("view projection screen")
    rb_atspi.do_action(it, "click")
    time.sleep(0.8)

    check.is_false(
        _dialog_present(app),
        "View Projection... unexpectedly opened a dialog instead of navigating the PB",
    )

    w = _pb_wid(app)
    if w:
        subprocess.run(["xdotool", "windowraise", w])
        time.sleep(0.3)
    rb_atspi.screenshot_assert(
        "test_view_projection_navigates_property_browser",
        "The SolveSpace Property Browser panel showing its VIEW PROJECTION screen, "
        "headed '3D VIEW PARAMETERS', listing an 'overall scale factor' with a "
        "px/mm value and a 'set to full scale' link, an 'origin (maps to center of "
        "screen)' with an (x, y, z) coordinate, and a 'projection onto screen' block "
        "with 'right', 'up' and 'out' rows each holding a 3-number vector, plus a "
        "'perspective factor (0 for parallel)' line. NOT a group list.",
        results_dir,
        window=_pb(app),
    )
    _pb_home(app)


@pytest.mark.rb(
    jump_kind="transition",
    expect="Edit>Configuration... navigates the Property Browser to the Configuration screen (user color r,g,b table, chord tolerance in percents, max piecewise linear segments)",
)
def test_configuration_navigates_property_browser(app, rb, frame, results_dir):
    """Edit > Configuration... navigates the Property Browser to its Configuration
    screen (opaque OpenGL canvas). Verified by screenshot: the PB now shows a
    'user color (r, g, b)' table of numbered swatches with [change] links, a 'chord
    tolerance (in percents)' setting, and 'max piecewise linear segments'.
    Programmatic guards confirm reachability and no error dialog. Teardown returns
    the PB home."""
    _close_dialogs(app)
    _pb_home(app)
    it = _item(app, "Configuration...")
    assert it is not None, "Edit>Configuration... missing"
    check.is_true(rb_atspi.is_enabled(it), "Configuration... is not enabled")
    check.is_true(_pb(app) is not None, "Property Browser frame is not present")

    rb.enter("configuration screen")
    rb_atspi.do_action(it, "click")
    time.sleep(0.8)

    check.is_false(
        _dialog_present(app),
        "Configuration... unexpectedly opened a dialog instead of navigating the PB",
    )

    w = _pb_wid(app)
    if w:
        subprocess.run(["xdotool", "windowraise", w])
        time.sleep(0.3)
    rb_atspi.screenshot_assert(
        "test_configuration_navigates_property_browser",
        "The SolveSpace Property Browser panel showing its CONFIGURATION screen: a "
        "'user color (r, g, b)' table with numbered rows (#0, #1, #2, ...) each "
        "showing a colored swatch, three decimal r,g,b components, and a '[change]' "
        "link; below it a 'chord tolerance (in percents)' value with a triangle "
        "count, and a 'max piecewise linear segments' value with a '[change]' link. "
        "NOT a group list of g001/g002/g003 rows.",
        results_dir,
        window=_pb(app),
    )
    _pb_home(app)