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

SOLE OWNER of CHECKED-state, radio mutual-exclusion, ENABLED and focus.
Every test reads a widget's STATE BEFORE -> drives the real user path -> reads
AFTER -> verifies the transition, and PAIRS each flip with the app-authored
consequence it must cause (a radio flip must turn its sibling off; toggling the
Property Browser off must make the PB frame stop showing; toggling Snap Grid on
with no active workplane must pop the "no workplane" message dialog).

All before/after values were OBSERVED on the running reference (a pre-loaded box
with a translate/step group; active group = translate). Nothing is read from
source or constants -- a pixel-perfect dead shell that does not actually flip
CHECKED must fail here.

Mechanics (proven by recon):
- The menu-bar `check menu item` nodes have INVALID extents (-2147483648) -> they
  cannot be clicked by pixel. They are toggled IN PLACE with
  ``rb_atspi.do_action(item, "click")`` -- this flips CHECKED with no focus, no
  window activation and (except Snap Grid) no modal. This is the primary trigger.
- The tree updates after the action, so every item is RE-FETCHED before reading
  its post-state.
- Toggling "Show Snap Grid" ON with no active workplane also pops a modal
  "Message -- SolveSpace" alert; the autouse teardown force-closes any leftover
  Message-/Error- dialog and restores every toggled state so tests are
  order-independent.

Focus note: SolveSpace's OpenGL `drawing area` never reports the AT-SPI FOCUSED
state (verified on the reference -- no node in the graphics-window subtree ever
carries FOCUSED, and the frame does not carry ACTIVE), so a focus-transition test
would not reproduce. Per the lane guidance it is intentionally omitted rather than
shipped as a non-reproducing assertion.
"""

import time, subprocess

import pytest
from pytest_check import check

import rb_atspi


# --------------------------------------------------------------------------- #
# Embedded helpers (encode the proven SolveSpace state mechanics; module-local)
# --------------------------------------------------------------------------- #
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_frame(app):
    """The Property Browser top-level frame, or None if it is not present/showing
    (toggling Show Property Browser off removes it from the tree entirely)."""
    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 _checked(app, name):
    """CHECKED of a menu item, re-fetched fresh (the tree updates after actions)."""
    it = _item(app, name)
    return rb_atspi.is_checked(it) if it is not None else None


def _toggle(app, name, settle=0.45):
    """do_action('click') on a `check menu item` -> flips CHECKED in place. Returns
    the item node that was clicked (RE-FETCH via _item/_checked to read after)."""
    it = _item(app, name)
    if it is not None:
        rb_atspi.do_action(it, "click")
        time.sleep(settle)
    return it


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


# --------------------------------------------------------------------------- #
# Order-independence: known-good baseline before + after EACH test.
# Every toggle used below returns to its OBSERVED initial CHECKED value, so any
# test can run alone or in any order without a leftover flip / modal skewing it.
# --------------------------------------------------------------------------- #
_INITIAL = {
    "Use Perspective Projection": False,
    "Darken Inactive Solids": True,
    "Show Toolbar": True,
    "Show Property Browser": True,
    "Show Snap Grid": False,
}


def _restore_toggles(app):
    """Return each boolean toggle to its recorded initial CHECKED value (guarded,
    so an already-correct item is not clicked spuriously)."""
    for name, want in _INITIAL.items():
        it = _item(app, name)
        if it is not None and rb_atspi.is_checked(it) != want:
            rb_atspi.do_action(it, "click")
            time.sleep(0.4)
            _close_dialogs(app)  # Snap Grid restore can also pop the modal


def _restore_mm(app):
    """Dimension Units back to Millimeters (the reference default) if not already."""
    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)


def _restore_all(app):
    _close_dialogs(app)
    _restore_toggles(app)
    _restore_mm(app)
    _close_dialogs(app)


@pytest.fixture(autouse=True, scope="module")
def _clean_module(app):
    """Establish the known baseline once before the module and once after it."""
    _restore_all(app)
    yield
    _restore_all(app)


@pytest.fixture(autouse=True)
def _clean_between(app):
    """Per-test teardown: never leave a modal open or a toggle flipped -- both would
    wedge / skew the next test on this shared single-instance app."""
    yield
    _restore_all(app)


# --------------------------------------------------------------------------- #
# Boolean CHECKED-flip transitions (paired with a consequence where one exists)
# --------------------------------------------------------------------------- #
@pytest.mark.rb(
    jump_kind="transition",
    expect="View>Use Perspective Projection CHECKED flips False->True (canvas switches to perspective projection)",
)
def test_use_perspective_projection_checks(app, rb):
    """View > Use Perspective Projection is a boolean toggle: CHECKED False -> True,
    which switches the 3D viewport from parallel to perspective projection."""
    _close_dialogs(app)
    it = _item(app, "Use Perspective Projection")
    assert it is not None, "View>Use Perspective Projection missing"

    before = rb_atspi.is_checked(it)
    check.is_false(before, "Perspective Projection should start unchecked on the reference")

    _toggle(app, "Use Perspective Projection")
    after = _checked(app, "Use Perspective Projection")
    # The verdict: the transition happened.
    check.is_true(after, "Use Perspective Projection did not become CHECKED after click")
    check.not_equal(before, after, "Perspective CHECKED did not change on toggle")
    # No modal is expected for this clean toggle.
    check.is_false(_dialog_present(app), "Perspective toggle unexpectedly opened a dialog")
    # (No screenshot: parallel vs perspective projection is not reliably distinguishable
    #  in this wireframe box view -- the CHECKED flip is the verdict.)


@pytest.mark.rb(
    jump_kind="transition",
    expect="View>Darken Inactive Solids CHECKED flips True->False (inactive solids stop being dimmed)",
)
def test_darken_inactive_solids_unchecks(app, rb):
    """View > Darken Inactive Solids is a boolean toggle that starts CHECKED (True):
    clicking it turns CHECKED False, so solids in inactive groups are no longer
    drawn dimmed."""
    _close_dialogs(app)
    it = _item(app, "Darken Inactive Solids")
    assert it is not None, "View>Darken Inactive Solids missing"

    before = rb_atspi.is_checked(it)
    check.is_true(before, "Darken Inactive Solids should start CHECKED on the reference")

    _toggle(app, "Darken Inactive Solids")
    after = _checked(app, "Darken Inactive Solids")
    check.is_false(after, "Darken Inactive Solids did not become UNCHECKED after click")
    check.not_equal(before, after, "Darken Inactive Solids CHECKED did not change on toggle")
    check.is_false(_dialog_present(app), "Darken toggle unexpectedly opened a dialog")
    # (No screenshot: this model renders as wireframe edges, so the dimming of inactive
    #  solid FACES is not visibly distinguishable here -- the CHECKED flip is the verdict.)


@pytest.mark.rb(
    jump_kind="transition",
    expect="View>Show Toolbar CHECKED flips True->False and the on-canvas toolbar disappears",
)
def test_show_toolbar_unchecks_and_hides_toolbar(app, rb):
    """View > Show Toolbar starts CHECKED (True): clicking it turns CHECKED False AND
    hides the left-edge on-canvas toolbar. The CHECKED flip is the verdict; no
    screenshot is attached here because the Property Browser window overlaps the
    graphics window's top-left in this layout (contaminating a toolbar-area crop with
    the PB's own icon row) -- the clean "full toolbar present vs absent" visual is
    instead captured, unobstructed, by the Show-Property-Browser test."""
    _close_dialogs(app)
    it = _item(app, "Show Toolbar")
    assert it is not None, "View>Show Toolbar missing"

    before = rb_atspi.is_checked(it)
    check.is_true(before, "Show Toolbar should start CHECKED on the reference")

    _toggle(app, "Show Toolbar")
    after = _checked(app, "Show Toolbar")
    check.is_false(after, "Show Toolbar did not become UNCHECKED after click")
    check.not_equal(before, after, "Show Toolbar CHECKED did not change on toggle")
    check.is_false(_dialog_present(app), "Show Toolbar toggle unexpectedly opened a dialog")


@pytest.mark.rb(
    jump_kind="transition",
    expect="View>Show Property Browser CHECKED True->False AND the 'Property Browser — SolveSpace' frame stops showing",
)
def test_show_property_browser_hides_pb_frame(app, rb, frame, results_dir):
    """View > Show Property Browser starts CHECKED (True): clicking it turns CHECKED
    False AND makes the separate 'Property Browser -- SolveSpace' top-level frame stop
    SHOWING / leave the tree. Both are asserted -- the frame vanishing is the
    app-authored consequence that discriminates from a bare toolkit toggle. The
    teardown toggles it back so the PB is restored for other tests."""
    _close_dialogs(app)
    it = _item(app, "Show Property Browser")
    assert it is not None, "View>Show Property Browser missing"

    # BEFORE: item checked and the PB frame is present + showing.
    before_checked = rb_atspi.is_checked(it)
    pb_before = _pb_frame(app)
    check.is_true(before_checked, "Show Property Browser should start CHECKED")
    check.is_true(
        pb_before is not None and rb_atspi.is_showing(pb_before),
        "Property Browser frame should be showing before the toggle",
    )

    _toggle(app, "Show Property Browser", settle=0.6)

    # AFTER: item unchecked AND the PB frame is gone (or no longer showing).
    after_checked = _checked(app, "Show Property Browser")
    pb_after = _pb_frame(app)
    pb_gone = pb_after is None or not rb_atspi.is_showing(pb_after)
    check.is_false(after_checked, "Show Property Browser did not become UNCHECKED")
    check.not_equal(before_checked, after_checked, "Show Property Browser CHECKED did not change")
    check.is_true(
        pb_gone,
        "consequence missing: the Property Browser frame is still showing after toggling it off",
    )

    # Screenshot cropped to the GRAPHICS window: with the PB hidden its overlaying
    # group-list panel is gone, so this region now shows the graphics window's OWN full
    # menu bar and complete left toolbar with the wireframe model -- a clean, judgeable
    # difference from the PB-shown state (which covers that corner with group-list text).
    rb_atspi.screenshot_assert(
        "test_show_property_browser_hides_pb_frame",
        "The SolveSpace graphics window with the Property Browser hidden: the top-left "
        "shows the application's own menu bar (File, Edit, View, New Group, Sketch, "
        "Constrain, Analyze, Help) and the FULL vertical column of tool icons down the "
        "left edge -- there is NO overlapping 'Property Browser' panel listing groups "
        "(no 'active / shown dof group-name' text, no g001/g002 group rows).",
        results_dir,
        window=frame,
    )

    # Restore explicitly (teardown also does this) and confirm the frame returns.
    _toggle(app, "Show Property Browser", settle=0.6)
    check.is_true(
        rb_atspi.wait_for(
            lambda: (_pb_frame(app) is not None) and rb_atspi.is_showing(_pb_frame(app)),
            timeout=4.0,
        ),
        "Property Browser frame did not reappear after toggling Show Property Browser back on",
    )


@pytest.mark.rb(
    jump_kind="transition",
    expect="View>Show Snap Grid CHECKED False->True and (no active workplane) a 'Message — SolveSpace' alert appears",
)
def test_show_snap_grid_checks_and_warns_no_workplane(app, rb):
    """View > Show Snap Grid starts CHECKED (False): clicking it turns CHECKED True AND
    -- because no workplane is active in this model -- pops a modal 'Message --
    SolveSpace' alert ('No workplane is active, so the grid will not appear.'). Both the
    CHECKED flip and the app-authored warning dialog are asserted. Teardown closes the
    dialog and restores CHECKED False."""
    _close_dialogs(app)
    it = _item(app, "Show Snap Grid")
    assert it is not None, "View>Show Snap Grid missing"

    before = rb_atspi.is_checked(it)
    check.is_false(before, "Show Snap Grid should start UNCHECKED on the reference")

    _toggle(app, "Show Snap Grid", settle=0.6)
    after = _checked(app, "Show Snap Grid")
    check.is_true(after, "Show Snap Grid did not become CHECKED after click")
    check.not_equal(before, after, "Show Snap Grid CHECKED did not change on toggle")

    # Consequence: with no active workplane the toggle-on pops the warning alert.
    got_dialog = rb_atspi.wait_for(lambda: _dialog_present(app), timeout=4.0)
    check.is_true(
        got_dialog,
        "expected 'Message — SolveSpace' no-workplane alert after enabling Snap Grid",
    )

    # (No screenshot: the on-canvas grid does not actually appear -- the warning says so
    #  -- and the alert text is covered by the menu/text lanes; the CHECKED flip + the
    #  alert-appeared assertion are the verdict here.)
    _close_dialogs(app)


# --------------------------------------------------------------------------- #
# Radio mutual-exclusion transitions (the strongest state tests)
# --------------------------------------------------------------------------- #
@pytest.mark.rb(
    jump_kind="transition",
    expect="Clicking 'Dimensions in Inches' -> Inches CHECKED True AND 'Dimensions in Millimeters' CHECKED True->False (radio exclusion)",
)
def test_dimension_units_radio_inches_excludes_mm(app, rb):
    """Dimension Units is a radio group. On the reference 'Dimensions in Millimeters'
    is CHECKED and the others are not. Clicking 'Dimensions in Inches' must turn Inches
    CHECKED True AND -- the app-authored mutual exclusion -- turn Millimeters CHECKED
    False. BOTH sides of the exclusion are asserted; teardown restores Millimeters."""
    _close_dialogs(app)
    _restore_mm(app)
    mm = _item(app, "Dimensions in Millimeters")
    inch = _item(app, "Dimensions in Inches")
    assert mm is not None and inch is not None, "Dimension Units radio items missing"

    # BEFORE: Millimeters checked, Inches not.
    check.is_true(rb_atspi.is_checked(mm), "Millimeters should start CHECKED")
    check.is_false(rb_atspi.is_checked(inch), "Inches should start UNCHECKED")

    _toggle(app, "Dimensions in Inches")

    # AFTER: Inches checked, Millimeters cleared (mutual exclusion).
    inch_after = _checked(app, "Dimensions in Inches")
    mm_after = _checked(app, "Dimensions in Millimeters")
    check.is_true(inch_after, "clicked 'Dimensions in Inches' did not become CHECKED")
    check.is_false(
        mm_after,
        "radio exclusion failed: 'Dimensions in Millimeters' stayed CHECKED after selecting Inches",
    )

    # Restore Millimeters and confirm the exclusion runs the other way too.
    _toggle(app, "Dimensions in Millimeters")
    check.is_true(_checked(app, "Dimensions in Millimeters"), "Millimeters did not restore")
    check.is_false(
        _checked(app, "Dimensions in Inches"),
        "restoring Millimeters did not clear Inches (exclusion should be symmetric)",
    )


@pytest.mark.rb(
    jump_kind="transition",
    expect="Clicking 'Dimensions in Meters' -> Meters CHECKED True AND 'Dimensions in Millimeters' CHECKED True->False (radio exclusion)",
)
def test_dimension_units_radio_meters_excludes_mm(app, rb):
    """A second, distinct member of the same Dimension Units radio group: clicking
    'Dimensions in Meters' turns Meters CHECKED True AND clears 'Dimensions in
    Millimeters' -- proving the exclusion holds for the group generally, not just the
    Inches pairing. Teardown restores Millimeters."""
    _close_dialogs(app)
    _restore_mm(app)
    mm = _item(app, "Dimensions in Millimeters")
    meters = _item(app, "Dimensions in Meters")
    assert mm is not None and meters is not None, "Dimension Units radio items missing"

    check.is_true(rb_atspi.is_checked(mm), "Millimeters should start CHECKED")
    check.is_false(rb_atspi.is_checked(meters), "Meters should start UNCHECKED")

    _toggle(app, "Dimensions in Meters")

    meters_after = _checked(app, "Dimensions in Meters")
    mm_after = _checked(app, "Dimensions in Millimeters")
    check.is_true(meters_after, "clicked 'Dimensions in Meters' did not become CHECKED")
    check.is_false(
        mm_after,
        "radio exclusion failed: 'Dimensions in Millimeters' stayed CHECKED after selecting Meters",
    )

    _toggle(app, "Dimensions in Millimeters")
    check.is_true(_checked(app, "Dimensions in Millimeters"), "Millimeters did not restore")
    check.is_false(
        _checked(app, "Dimensions in Meters"),
        "restoring Millimeters did not clear Meters (exclusion should be symmetric)",
    )