File size: 17,532 Bytes
e5a3ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
"""AT-SPI button (push-button effect-by-consequence) lane for SolveSpace
(parametric 2D/3D CAD, GTK3 + OpenGL).

This lane tests PUSH BUTTONS by the app-authored CONSEQUENCE each one CAUSES --
here, the effect is *the button dismisses its dialog*: press it and the modal
window it lives in DISAPPEARS. The verdict is the disappearance the press causes
(before: exactly one showing alert, identified by its body text + its own X
window; after pressing OK: zero showing alerts AND that X window gone). A dead
shell that renders a dialog whose OK does nothing FAILS these -- existence /
has-action / "still alive" never passes here.

WHY DIALOG-OK IS THE PUSH-BUTTON SURFACE HERE (verified on the running reference):
SolveSpace has NO persistent AT-SPI push buttons. Its main toolbar and the whole
Property Browser are drawn on an OpenGL canvas, so they expose NO `push button`
nodes and no coordinates (a pixel click on the canvas toolbar produced no
observable change during recon). The ONLY real `push button` AT-SPI nodes are the
"OK" buttons INSIDE the modal message/error dialogs. So the genuine
effect-by-consequence test on this app is: open ONE dialog -> its OK `push button`
is present+showing (a PRECONDITION, not the verdict) -> PRESS OK -> the dialog
window disappears. That IS a real button consequence (the button does something
observable). This is legitimate and behavioral.

LANE BOUNDARIES: this lane does NOT assert the computed VALUE inside a dialog
(that is the computation lane) and does NOT own CHECKED flips (that is the state
lane). It also does NOT re-screenshot the About / Volume dialog bodies -- the
menu & computation lanes already capture those rendered states; duplicating them
adds no coverage. The before/after showing-alert count + the dialog's own X
window is the primary (AT-SPI, programmatic) verdict and is sufficient here.

PROVEN MECHANICS (verified at author time on the running reference, pid-attached):
- A dialog is role ``alert`` / name "Information" (same name for all three), a
  SEPARATE X window titled "Message — SolveSpace" (info) or "Error — SolveSpace"
  (validation error), containing exactly ONE ``push button`` named "OK"
  (actions: ["click"]) plus readable ``label`` children. WHICH dialog is
  identified by those labels, not by the alert name.
- Triggers that open exactly ONE dialog: About via
  ``do_action_safe(item,"click")`` (bounded, never a blocking do_action on a
  modal-opener); Measure Volume via the ``ctrl+shift+v`` accelerator into the
  focused+hovered graphics window; Measure Area via ``do_action(item,"click")``
  (its error dialog does not need the accelerator); Measure Perimeter via the
  ``ctrl+shift+p`` accelerator.
- With a SINGLE (non-overlapping) dialog open, ``do_action(ok,"click")`` cleanly
  dismisses it -- verified showing-alert count 1 -> 0 and the X window gone for
  every dialog below. Each test opens EXACTLY ONE dialog so the OK press is
  reliable (stacked dialogs make AT-SPI extents stale -- avoided).
"""

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  (kit import surface)


# --------------------------------------------------------------------------- #
# Embedded helpers (encode the proven SolveSpace dialog/push-button 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 _item(app, name):
    """A `check menu item` in the graphics window's menu bar, by plain label."""
    return rb_atspi.find_first(_gw(app), role="check menu item", name=name)


def _alerts(app):
    """Every currently-SHOWING top-level `alert` (Message/Error) dialog the app owns."""
    return [
        app.get_child_at_index(i)
        for i in range(app.get_child_count())
        if app.get_child_at_index(i).get_role_name() == "alert"
        and rb_atspi.is_showing(app.get_child_at_index(i))
    ]


def _alert_labels(app):
    """All non-empty label texts across every SHOWING alert (identity of the dialog)."""
    out = []
    for f in _alerts(app):
        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 showing-alert label text joined with whitespace collapsed, so an identity
    substring matches regardless of label splitting / embedded newlines."""
    return " ".join(" ".join(_alert_labels(app)).split())


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
    )
    out = []
    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 —"):
            out.append(w)
    return out


def _close_dialogs(app, rounds=6):
    """Force-close any leftover Message-/Error- dialog by activating its X window and
    clicking OK's live bottom-center (AT-SPI OK extents go stale under overlap). Used
    only in teardown so a failed press cannot wedge the next test -- order-independent."""
    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 _ok(app):
    """The OK ``push button`` inside the (single) currently-showing alert, or None."""
    al = _alerts(app)
    return rb_atspi.find_first(al[0], role="push button") if al else None


def _wait_alert(app, timeout=6.0):
    """Poll until at least one alert is showing; True if a dialog appeared."""
    return rb_atspi.wait_for(lambda: len(_alerts(app)) > 0, timeout=timeout)


def _wait_no_alert(app, timeout=6.0):
    """Poll until NO alert is showing; True if all dialogs are gone."""
    return rb_atspi.wait_for(lambda: len(_alerts(app)) == 0, timeout=timeout)


# --------------------------------------------------------------------------- #
# Order-independence: never leave a dialog open (shared single-instance app).
# autouse teardown force-closes any leftover Message-/Error- dialog so a FAILED
# OK press cannot wedge the next test. Each test also opens its OWN dialog.
# --------------------------------------------------------------------------- #
@pytest.fixture(autouse=True, scope="module")
def _clean_module(app):
    _close_dialogs(app)
    yield
    _close_dialogs(app)


@pytest.fixture(autouse=True)
def _clean_between(app):
    yield
    _close_dialogs(app)


# --------------------------------------------------------------------------- #
# Shared consequence body: open ONE dialog, assert OK present (precondition),
# capture the FULL before-state (exactly one showing alert whose text IDENTIFIES
# it, + its own X window), PRESS OK, assert the AFTER-state -- the alert is GONE
# (zero showing alerts) AND that dialog X window is gone. The disappearance the
# button press causes is the VERDICT; the identity check makes it discriminating.
# --------------------------------------------------------------------------- #
def _assert_ok_dismisses(app, check, id_substr, human_dialog):
    # --- precondition: exactly one dialog opened, with a pressable OK button ---
    got = _wait_alert(app, timeout=6.0)
    if not got:
        pytest.skip(f"{human_dialog} produced no dialog in this environment")
    ok = _ok(app)
    assert ok is not None, f"{human_dialog}: no OK push button in the alert"
    # OK present+showing+actionable is a PRECONDITION (not the verdict).
    check.is_true(rb_atspi.is_showing(ok), f"{human_dialog}: OK push button not showing")
    check.equal(ok.get_name(), "OK", f"{human_dialog}: dialog button is not named 'OK'")
    check.is_true("click" in rb_atspi.action_names(ok),
                  f"{human_dialog}: OK exposes no 'click' action")

    # --- BEFORE: one showing alert, its text identifies THIS dialog, its window is up ---
    before_n = len(_alerts(app))
    before_wids = _dialog_wids(app)
    text = _labels_text(app)
    check.equal(before_n, 1,
                f"{human_dialog}: expected exactly one showing alert before OK, got {before_n}")
    check.is_true(len(before_wids) >= 1,
                  f"{human_dialog}: no Message-/Error- X window before OK")
    check.is_in(id_substr, text,
                f"{human_dialog}: opened alert is not the expected one; labels={text!r}")

    # --- THE BUTTON CONSEQUENCE: press OK -> its dialog must DISAPPEAR ---
    pressed = rb_atspi.do_action(ok, "click")
    check.is_true(pressed, f"{human_dialog}: OK push button 'click' action did not fire")

    gone = _wait_no_alert(app, timeout=6.0)
    after_n = len(_alerts(app))
    after_wids = _dialog_wids(app)

    # VERDICT (AT-SPI, primary): the showing-alert count dropped 1 -> 0 ...
    check.is_true(gone,
                  f"{human_dialog}: OK press left the alert showing (dialog did not close)")
    check.equal(after_n, 0,
                f"{human_dialog}: after OK expected 0 showing alerts, got {after_n}")
    # ... AND the dialog's own X window is gone (the window really closed).
    check.equal(len(after_wids), 0,
                f"{human_dialog}: after OK the dialog X window is still open ({after_wids})")


# --------------------------------------------------------------------------- #
# 1. About dialog  (do_action_safe opener -> "Message —" info dialog)
# --------------------------------------------------------------------------- #
@pytest.mark.rb(
    jump_kind="transition",
    expect="About 'Message' dialog OK pressed -> the About alert (label 'free software') "
    "disappears: showing-alert count 1->0 and its 'Message — SolveSpace' window closes",
)
def test_about_dialog_ok_dismisses(app, rb):
    """Push-button consequence: the About dialog's OK closes the About dialog. Open
    Help>About (a modal opener -> do_action_safe, bounded). BEFORE: exactly one showing
    'Information' alert whose body text says SolveSpace is 'free software' (identity), and
    a 'Message — SolveSpace' X window is up. Press its OK `push button`. AFTER: zero
    showing alerts AND that X window is gone. The disappearance the OK press causes is the
    verdict; OK merely existing is only the precondition."""
    _close_dialogs(app)
    it = _item(app, "About")
    assert it is not None, "Help>About menu item missing"

    rb.enter("about dialog")  # navigated INTO the dialog before pressing OK -> depth 1
    rb_atspi.do_action_safe(it, "click")  # modal opener: bounded, never blocking do_action

    _assert_ok_dismisses(app, check, id_substr="free software", human_dialog="About")


# --------------------------------------------------------------------------- #
# 2. Measure Volume dialog  (ctrl+shift+v accelerator -> "Message —" info dialog)
# --------------------------------------------------------------------------- #
@pytest.mark.rb(
    jump_kind="transition",
    expect="Measure Volume 'Message' dialog OK pressed -> the volume alert (label "
    "'volume of the solid model') disappears: showing-alert count 1->0 and its "
    "'Message — SolveSpace' window closes",
)
def test_volume_dialog_ok_dismisses(app, rb):
    """Push-button consequence: the Measure Volume result dialog's OK closes it. Fire
    Analyze>Measure Volume by its ctrl+shift+v accelerator into the focused graphics
    window. BEFORE: exactly one showing alert reading 'The volume of the solid model
    is:' (identity), with a 'Message — SolveSpace' X window. Press its OK `push button`.
    AFTER: zero showing alerts AND that X window gone. (The exact magnitude/unit is the
    computation lane's verdict; here the verdict is the OK-caused disappearance.)"""
    _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")

    _assert_ok_dismisses(
        app, check, id_substr="volume of the solid model", human_dialog="Measure Volume"
    )


# --------------------------------------------------------------------------- #
# 3. Measure Area error dialog  (do_action -> "Error —" validation dialog)
# --------------------------------------------------------------------------- #
@pytest.mark.rb(
    jump_kind="transition",
    expect="Measure Area 'Error' dialog OK pressed -> the validation-error alert (label "
    "'2d closed area') disappears: showing-alert count 1->0 and its "
    "'Error — SolveSpace' window closes",
)
def test_area_error_dialog_ok_dismisses(app, rb):
    """Push-button consequence: the Measure Area ERROR dialog's OK closes it. On the
    active 3d translate group, Analyze>Measure Area (do_action -- its dialog does not
    need the accelerator) pops a validation error. BEFORE: exactly one showing alert
    reading 'This group does not contain a correctly-formed 2d closed area.' (identity),
    with an 'Error — SolveSpace' X window. Press its OK `push button`. AFTER: zero
    showing alerts AND that X window gone. Confirms the OK button dismisses an ERROR
    dialog (distinct window kind from tests 1-2), not just an info one."""
    _close_dialogs(app)
    it = _item(app, "Measure Area")
    assert it is not None, "Analyze>Measure Area missing"

    rb.enter("measure area error dialog")  # do_action opens the error modal -> depth 1
    rb_atspi.do_action(it, "click")

    _assert_ok_dismisses(
        app, check, id_substr="2d closed area", human_dialog="Measure Area"
    )


# --------------------------------------------------------------------------- #
# 4. Measure Perimeter error dialog  (ctrl+shift+p accelerator -> "Error —" dialog)
#    A DISTINCT trigger (accelerator) + a DISTINCT error message -> another OK
#    consequence, so the pass does not hinge on one code path or one dialog string.
# --------------------------------------------------------------------------- #
@pytest.mark.rb(
    jump_kind="transition",
    expect="Measure Perimeter 'Error' dialog OK pressed -> the bad-selection alert (label "
    "'Bad selection for perimeter') disappears: showing-alert count 1->0 and its "
    "'Error — SolveSpace' window closes",
)
def test_perimeter_error_dialog_ok_dismisses(app, rb):
    """Push-button consequence on a SECOND, distinct error dialog: Analyze>Measure
    Perimeter with nothing selected (ctrl+shift+p accelerator) pops the bad-selection
    error. BEFORE: exactly one showing alert reading 'Bad selection for perimeter; select
    line segments, arcs, and curves.' (identity), with an 'Error — SolveSpace' X window.
    Press its OK `push button`. AFTER: zero showing alerts AND that X window gone. Uses a
    different trigger + message from test 3 so the OK-dismiss consequence is proven
    across code paths, not memorised from one dialog."""
    _close_dialogs(app)
    assert _item(app, "Measure Perimeter") is not None, "Analyze>Measure Perimeter missing"

    rb.enter("measure perimeter error dialog")  # accelerator opens the error modal -> depth 1
    _accel(app, "ctrl+shift+p")

    _assert_ok_dismisses(
        app, check, id_substr="Bad selection for perimeter", human_dialog="Measure Perimeter"
    )