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
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
"""AT-SPI text (content/output) lane for SolveSpace (parametric 2D/3D CAD, GTK3 + OpenGL).

This lane asserts CONTENT / OUTPUT TEXT that an interaction PRODUCES:
  * the app-authored *label strings* inside message/error dialogs (About license
    text, the Measure-Volume/Area report sentences) -- read via AT-SPI (primary
    verdict) as the exact phrasing observed on the running reference;
  * the *window-title* text of the two top-level frames (the loaded-document title
    on the graphics window, and the Property Browser's own title) -- read via
    AT-SPI as `value` tests on the title CONTENT;
  * the *rendered text* on the Property Browser's OPAQUE OpenGL canvas (the
    group-list home screen), which is NOT in the AT-SPI tree -> asserted via a VLM
    ``screenshot_assert`` (the sole verdict for opaque rendered text, exactly this
    lane's specialty).

It deliberately does NOT re-score the computed NUMBER inside a dialog (that is the
computation lane's "3 cm3" value) -- here the verdict is the TEXTUAL sentence
content / titles / rendered screens. Every asserted string was OBSERVED on the
running reference (a pre-loaded box with a translate/step group); nothing is read
from source, glyphs, or a version constant.

Screenshot coordination (one shot per DISTINCT rendered state across the suite):
the menu lane already screenshots the About dialog, the Line Styles / View
Projection / Configuration PB screens; the computation lane already screenshots the
Volume / Area report dialogs. To avoid near-duplicate shots, THIS lane contributes
the one rendered state no other lane captures -- the Property Browser GROUP-LIST
HOME screen -- and takes the programmatic label/title read as the verdict for the
dialog-text and window-title tests (whose dialogs are already screenshotted
elsewhere).

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")`` (inline: Measure
  Area) or ``do_action_safe(item,"click")`` (modal-opener: About -- bounded so a
  nested dialog loop can't hang the module); Measure Volume is driven by its
  keyboard ACCELERATOR (Ctrl+Shift+V) into the focused+hovered graphics window.
- Modal message/error dialogs are role ``alert`` / name "Information", SEPARATE X
  windows titled "Message -- SolveSpace" / "Error -- SolveSpace", with readable
  `label` children (the TEXT asserted here) + an OK push button. Multi-line
  messages are split across labels AND carry embedded newlines, so labels are
  joined and whitespace-collapsed before substring matching.
- The Property Browser is an OPAQUE OpenGL text canvas: its group-list content 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
  returns it to the group-list HOME screen (used to guarantee/reset the home view).
"""

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 (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 and whitespace-collapsed into one string.
    Dialogs split multi-line messages across labels AND wrap phrases with embedded
    newlines (e.g. 'GNU\\nGeneral Public License', 'free\\nsoftware:'), so collapse
    all runs of whitespace to single spaces -> substring assertions become
    split-/wrap-agnostic and match the sentence as authored."""
    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."""
    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 reset to home, before + after each
# --------------------------------------------------------------------------- #
@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 is clean."""
    yield
    _close_dialogs(app)
    _pb_home(app)


# --------------------------------------------------------------------------- #
# A. WINDOW-TITLE text (value; read via AT-SPI, depth 0 -- no navigation)
# --------------------------------------------------------------------------- #
@pytest.mark.rb(
    jump_kind="value",
    expect="Graphics-window frame title contains the loaded filename 'launch_model.slvs' and ends with '— SolveSpace'",
)
def test_graphics_window_title_shows_loaded_filename(app, rb, results_dir, frame):
    """The graphics window's frame title is CONTENT text: it names the currently
    loaded document and ends with the app suffix. Asserted as observed on the
    running reference -> the filename STEM 'launch_model.slvs' appears AND the title
    ends with '— SolveSpace'. Only the filename + suffix are asserted, never the
    absolute path prefix (a recreation may load the same document from a different
    directory). No navigation -> honest depth 0."""
    gw = _gw(app)
    assert gw is not None, "graphics-window frame not found"
    title = gw.get_name() or ""

    check.is_in(
        "launch_model.slvs", title,
        f"graphics-window title does not name the loaded document; title={title!r}",
    )
    check.is_true(
        title.rstrip().endswith("— SolveSpace"),
        f"graphics-window title does not end with '— SolveSpace'; title={title!r}",
    )
    # The two facts co-occur in the one title string (document + app), not two views.
    check.is_true(
        "launch_model.slvs" in title and "SolveSpace" in title,
        f"title is not the '<file> — SolveSpace' document title; title={title!r}",
    )


@pytest.mark.rb(
    jump_kind="value",
    expect="Property Browser frame title is exactly 'Property Browser — SolveSpace'",
)
def test_property_browser_window_title(app, rb, results_dir):
    """The Property Browser's own frame title is a DISTINCT piece of content text
    (not the document title): exactly 'Property Browser — SolveSpace'. Asserted as
    observed on the running reference. No navigation -> honest depth 0."""
    pb = _pb(app)
    assert pb is not None, "Property Browser frame not found"
    title = pb.get_name() or ""

    check.is_in(
        "Property Browser", title,
        f"PB title does not identify the Property Browser; title={title!r}",
    )
    check.is_true(
        title.rstrip().endswith("— SolveSpace"),
        f"PB title does not end with '— SolveSpace'; title={title!r}",
    )
    # Distinct from the graphics-window title: it does NOT carry the document name.
    check.is_false(
        "launch_model.slvs" in title,
        f"PB title unexpectedly carries the document filename; title={title!r}",
    )


# --------------------------------------------------------------------------- #
# B. DIALOG LABEL text (value; read via AT-SPI = primary verdict, depth 1)
#    Dialogs themselves are screenshotted by the menu/computation lanes, so no
#    near-duplicate shot is added here -- the label STRING is the verdict.
# --------------------------------------------------------------------------- #
@pytest.mark.rb(
    jump_kind="value",
    expect="About dialog label text: 'SolveSpace is free software', 'GNU General Public License', 'NO WARRANTY'",
)
def test_about_dialog_license_text(app, rb, results_dir):
    """Help > About produces a message dialog whose LABEL TEXT is the app-authored
    license notice. The verdict is the textual content: it states SolveSpace is free
    software, that it may be redistributed under the GNU General Public License, and
    that there is NO WARRANTY -- the exact phrasing observed on the running
    reference. The version NUMBER in the same dialog is intentionally NOT asserted
    (that is version metadata, not stable content). Opened with do_action_safe (About
    is a modal-opener; bounded so its nested loop can't hang the module)."""
    _close_dialogs(app)
    it = _item(app, "About")
    assert it is not None, "Help>About menu item missing"

    rb.enter("about dialog")  # a modal opens -> a real surface crossing (depth 1)
    rb_atspi.do_action_safe(it, "click")
    got = _wait_alert(app, timeout=6.0)
    check.is_true(got, "About produced no dialog to read label text from")

    text = _labels_text(app)
    check.is_in(
        "SolveSpace is free software", text,
        f"About text does not state SolveSpace is free software; labels={text!r}",
    )
    check.is_in(
        "GNU General Public License", text,
        f"About text does not name the GNU General Public License; labels={text!r}",
    )
    check.is_in(
        "NO WARRANTY", text,
        f"About text does not carry the NO WARRANTY notice; labels={text!r}",
    )
    _close_dialogs(app)


@pytest.mark.rb(
    jump_kind="value",
    expect="Measure Volume dialog label text: 'The volume of the solid model is:' and 'Curved surfaces have been approximated as triangles.'",
)
def test_measure_volume_dialog_label_text(app, rb, results_dir):
    """Analyze > Measure Volume (Ctrl+Shift+V) produces a report dialog; the verdict
    here is its LABEL TEXT (the report SENTENCES, not the number the computation lane
    owns): it announces 'The volume of the solid model is:' and explains that
    'Curved surfaces have been approximated as triangles.' -- the exact phrasing
    observed on the running reference. Triggered by the keyboard accelerator into the
    focused graphics window (never a blocking do_action on a modal-opener)."""
    _close_dialogs(app)
    assert _item(app, "Measure Volume") is not None, "Analyze>Measure Volume missing"

    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)")

    text = _labels_text(app)
    check.is_in(
        "The volume of the solid model is:", text,
        f"volume-report announcement sentence absent; labels={text!r}",
    )
    check.is_in(
        "Curved surfaces have been approximated as triangles.", text,
        f"triangulation-approximation sentence absent; labels={text!r}",
    )
    _close_dialogs(app)


@pytest.mark.rb(
    jump_kind="value",
    expect="Measure Area error dialog label text: 'This group does not contain a correctly-formed 2d closed area.' and 'It is open, not coplanar, or self-intersecting.'",
)
def test_measure_area_dialog_label_text(app, rb, results_dir):
    """Analyze > Measure Area on the active 3d translate group produces an ERROR
    dialog; the verdict is its LABEL TEXT (the validation SENTENCES): it states
    'This group does not contain a correctly-formed 2d closed area.' followed by
    'It is open, not coplanar, or self-intersecting.' -- the exact phrasing observed
    on the running reference. Area fires inline via do_action (its dialog does not
    block the D-Bus reply here)."""
    _close_dialogs(app)
    it = _item(app, "Measure Area")
    assert it is not None, "Analyze>Measure Area missing"

    rb.enter("measure area dialog")
    rb_atspi.do_action(it, "click")
    got = _wait_alert(app, timeout=6.0)
    check.is_true(got, "Measure Area produced no dialog to read label text from")

    text = _labels_text(app)
    check.is_in(
        "This group does not contain a correctly-formed 2d closed area.", text,
        f"closed-area validation sentence absent; labels={text!r}",
    )
    check.is_in(
        "It is open, not coplanar, or self-intersecting.", text,
        f"open/not-coplanar explanation sentence absent; labels={text!r}",
    )
    _close_dialogs(app)


# --------------------------------------------------------------------------- #
# C. OPAQUE RENDERED TEXT screen (Property Browser home) -> VLM screenshot is the
#    SOLE verdict (this text is NOT in the AT-SPI tree). Unique to this lane.
# --------------------------------------------------------------------------- #
@pytest.mark.rb(
    jump_kind="value",
    expect="Property Browser group-list HOME screen renders header 'shown dof group-name' over rows g001-#references / g002-sketch-in-plane / g003-extrude / g004-translate plus 'line styles / view / configuration' links",
)
def test_property_browser_group_list_text(app, rb, results_dir):
    """The Property Browser's group-list HOME screen is CONTENT TEXT rendered on an
    OPAQUE OpenGL canvas -- it is NOT exposed in the AT-SPI tree, so the VLM
    screenshot is the SOLE verdict for this rendered text (exactly this lane's job).
    The PB is reset to its home screen (Escape) so the shot is deterministic, then
    the rendered text is asserted: the 'shown / dof / group-name' column header over
    the model's four named group rows (g001-#references, g002-sketch-in-plane,
    g003-extrude, g004-translate) plus the 'show all / only unconstrained / hide all'
    and 'line styles / view / configuration' link rows -- the group names/text
    observed on the running reference for THIS document. No other lane captures the
    home screen. Home is the default view -> honest depth 0."""
    _close_dialogs(app)
    _pb_home(app)  # guarantee the group-list home screen is showing
    check.is_true(_pb(app) is not None, "Property Browser frame is not present")

    w = _pb_wid(app)
    if w:  # bring the PB to the front so the crop captures its content on top
        subprocess.run(["xdotool", "windowraise", w])
        time.sleep(0.3)
    ok = rb_atspi.screenshot_assert(
        "test_property_browser_group_list_text",
        "The SolveSpace Property Browser panel showing its GROUP-LIST HOME screen: an "
        "'active' marker and a three-column header 'shown   dof   group-name' above a "
        "vertical list of the document's groups -- rows reading 'g001-#references', "
        "'g002-sketch-in-plane', 'g003-extrude', 'g004-translate' -- each with a "
        "small radio/checkbox and a dof number; below the list a link row "
        "'show all / only unconstrained / hide all' and a link row "
        "'line styles / view / configuration'. It is a GROUP LIST, NOT a line-styles "
        "'color / style-name' list and NOT a view/configuration parameter screen.",
        results_dir,
        window=_pb(app),
    )
    check.is_true(ok, "failed to capture the Property Browser home-screen screenshot")