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
 
 
 
 
 
 
 
 
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
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
"""Shared AT-SPI primitives for RecreationBench pytest tests.

Tier-1 testgen ships ONE of these (uploaded next to the tests) instead of a
bespoke ~500-line ``atspi_helpers.py`` per app. Every generic primitive the
per-app helpers reinvented lives here — tree search, state, actions, real input
(xdotool), waits, and the VLM ``screenshot_assert``. The only app-specific bit,
"which frame is my app", is parameterized: ``get_app()`` resolves the target by
the ``RB_APP_NAME`` the runner already detected, so the SAME module works for
every app.

Tests import this and use pytest-check for soft assertions; result collection is
handled by ``conftest.py`` (which writes the legacy ``<module>_results.json`` so
the frozen-manifest scorer is unchanged). App-specific *workflows* (open a file,
expand a tree) stay in the test file or a local fixture — only the primitives are
shared.
"""

from __future__ import annotations

import json
import os
import subprocess
import time

import gi

gi.require_version("Atspi", "2.0")
from gi.repository import Atspi  # noqa: E402

# Bound EVERY AT-SPI method call. A synchronous action (do_action) on an item that opens
# a MODAL runs the app's handler on its single main thread; if that handler enters a
# nested event loop (GTK gtk_dialog_run, Qt QDialog::exec, wx modal), it does not return
# until the dialog closes, so the D-Bus reply never comes and the call HANGS the whole
# pytest module. libatspi has a global call timeout (default ~800ms) but it is not
# reliably applied to actions that enter a nested loop; set it explicitly so a blocked
# call raises fast (and the test is dropped) instead of wedging the module. Reads are
# well under this; only nested-loop blocks hit it. (call_timeout_ms, app_startup_ms)
try:
    Atspi.set_timeout(1500, 15000)
except Exception:  # older libatspi without set_timeout
    pass

# Re-export the kit's true-jump helpers so a test file has ONE import surface:
# ``from rb_atspi import rb_showing, rb_reach``. (Depth is measured via the ``rb``
# pytest fixture in conftest.py; app attach is the ``app`` fixture — both by RB_APP_NAME.)
try:  # noqa: E402
    from rb_testgen_kit import rb_reach, rb_showing  # noqa: F401
except Exception:  # pragma: no cover - kit absent; primitives below still work
    pass


# --------------------------------------------------------------------------- #
# App / frame resolution
# --------------------------------------------------------------------------- #
def _desktop():
    return Atspi.get_desktop(0)


def get_app(name: str | None = None, timeout: float = 25.0):
    """Return the AT-SPI application Accessible for the app under test.

    ``name`` defaults to the ``RB_APP_NAME`` the runner detected (a process-tree
    match). Falls back to the single non-shell app on the bus if the name does
    not match, so tests are robust to a11y-name drift.
    """
    name = name or os.environ.get("RB_APP_NAME", "")
    deadline = time.time() + timeout
    ignore = {"", "gnome-shell", "at-spi2-registryd", "mutter-x11-frames"}
    last_apps: list = []
    while time.time() < deadline:
        desktop = _desktop()
        apps = []
        for i in range(desktop.get_child_count()):
            app = desktop.get_child_at_index(i)
            if app is None:
                continue
            an = app.get_name() or ""
            if an in ignore:
                continue
            apps.append(app)
            if name and (an == name or name in an or an in name):
                return app
        last_apps = apps
        time.sleep(0.4)
    # name never matched: if exactly one real app is on the bus, use it.
    if len(last_apps) == 1:
        return last_apps[0]
    for app in last_apps:
        if (app.get_name() or "").strip():
            return app
    return None


def get_main_frame(app=None):
    """Return the app's top-level frame (or the app node itself)."""
    if app is None:
        app = get_app()
    if app is None:
        return None
    for i in range(app.get_child_count()):
        c = app.get_child_at_index(i)
        if c is not None and (c.get_role_name() or "") in ("frame", "window"):
            return c
    return app


# --------------------------------------------------------------------------- #
# Tree traversal / finding
# --------------------------------------------------------------------------- #
def walk(node, cb, depth: int = 0, maxdepth: int = 60):
    if node is None or depth > maxdepth:
        return
    try:
        cb(node, depth)
    except Exception:
        pass
    try:
        n = node.get_child_count()
    except Exception:
        return
    for i in range(n):
        try:
            c = node.get_child_at_index(i)
        except Exception:
            continue
        walk(c, cb, depth + 1, maxdepth)


def find_all(
    root, role: str | None = None, name: str | None = None, name_sub: str | None = None
):
    out: list = []

    def cb(n, _d):
        try:
            if role is not None and (n.get_role_name() or "") != role:
                return
            nm = n.get_name() or ""
            if name is not None and nm != name:
                return
            if name_sub is not None and name_sub not in nm:
                return
            out.append(n)
        except Exception:
            pass

    walk(root, cb)
    return out


def find_first(
    root, role: str | None = None, name: str | None = None, name_sub: str | None = None
):
    res = find_all(root, role=role, name=name, name_sub=name_sub)
    return res[0] if res else None


def cell_names(root):
    return [(c.get_name() or "") for c in find_all(root, role="table cell")]


def roles_present(root):
    seen: set[str] = set()
    walk(root, lambda n, _d: seen.add(n.get_role_name() or ""))
    return seen


def widget_count(root):
    n = [0]
    walk(root, lambda _n, _d: n.__setitem__(0, n[0] + 1))
    return n[0]


# --------------------------------------------------------------------------- #
# State
# --------------------------------------------------------------------------- #
def _state(n, st) -> bool:
    try:
        return n.get_state_set().contains(st)
    except Exception:
        return False


def is_checked(n) -> bool:
    return _state(n, Atspi.StateType.CHECKED)


def is_showing(n) -> bool:
    return _state(n, Atspi.StateType.SHOWING)


def is_enabled(n) -> bool:
    return _state(n, Atspi.StateType.ENABLED)


def is_visible(n) -> bool:
    return _state(n, Atspi.StateType.VISIBLE)


def is_focused(n) -> bool:
    return _state(n, Atspi.StateType.FOCUSED)


def get_text(n) -> str:
    try:
        return Atspi.Text.get_text(n, 0, Atspi.Text.get_character_count(n))
    except Exception:
        try:
            return n.get_name() or ""
        except Exception:
            return ""


# --------------------------------------------------------------------------- #
# Actions
# --------------------------------------------------------------------------- #
def _action_iface(n):
    try:
        return n.get_action_iface()
    except Exception:
        return None


def action_names(n) -> list[str]:
    ai = _action_iface(n)
    if ai is None:
        return []
    try:
        return [ai.get_action_name(i) for i in range(ai.get_n_actions())]
    except Exception:
        return []


def do_action(n, want: str) -> bool:
    ai = _action_iface(n)
    if ai is None:
        return False
    try:
        for i in range(ai.get_n_actions()):
            if (ai.get_action_name(i) or "").lower() == want.lower():
                ai.do_action(i)
                return True
    except Exception:
        return False
    return False


def do_action_safe(n, want: str) -> bool:
    """Fire an AT-SPI action, tolerating a modal-opener. do_action on an item that opens
    a modal blocks in the app's nested event loop; Atspi.set_timeout (module init) now
    bounds that to ~1.5s, after which the call raises and we swallow it. PREFER
    open_modal()/click_node() (async xdotool) for anything that opens a dialog/menu —
    this is only the fallback. Returns True if the action was issued."""
    ai = _action_iface(n)
    if ai is None:
        return False
    idx = None
    try:
        for i in range(ai.get_n_actions()):
            if (ai.get_action_name(i) or "").lower() == want.lower():
                idx = i
                break
    except Exception:
        return False
    if idx is None:
        return False
    try:
        ai.do_action(idx)
    except Exception:
        pass
    return True


def press(n) -> bool:
    return do_action(n, "Press") or do_action(n, "click")


def toggle(n) -> bool:
    return do_action(n, "Toggle") or press(n)


def show_menu(n) -> bool:
    """Open a menu WITHOUT blocking. A menu-open can enter a grab/nested loop, so drive
    it with a synthetic mouse click (xdotool, async — returns immediately) rather than a
    synchronous do_action. Falls back to the (now timeout-bounded) do_action_safe."""
    if click_node(n) is not None:
        return True
    return do_action_safe(n, "ShowMenu") or do_action_safe(n, "click")


def open_modal(n) -> bool:
    """Trigger something that may spawn a MODAL dialog (File>Open, a menu item that
    opens a dialog) WITHOUT hanging. Uses a synthetic xdotool click (async) so the app
    can enter its modal nested loop while the test proceeds to read/dismiss the new
    window. NEVER use do_action for a modal-opener: do_action runs the handler
    synchronously and blocks in the nested loop until the modal closes (see the
    Atspi.set_timeout note at module top). After open_modal(), read the dialog via
    AT-SPI (bounded reads) and dismiss with press_escape()/key()."""
    return click_node(n) is not None


# --------------------------------------------------------------------------- #
# Real input via xdotool (needed to SELECT rows / reach webviews)
# --------------------------------------------------------------------------- #
def xdo(*args) -> bool:
    try:
        subprocess.run(
            ["xdotool", *[str(a) for a in args]],
            timeout=8,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
        )
        return True
    except Exception:
        return False


def center(n):
    try:
        ext = n.get_extents(Atspi.CoordType.SCREEN)
        if ext.width <= 0 or ext.height <= 0:
            return None
        return (ext.x + ext.width // 2, ext.y + ext.height // 2)
    except Exception:
        return None


def click_node(n, button: int = 1):
    """Real mouse click at the node's on-screen center (selects rows, focuses
    webviews — synthetic AT-SPI focus often won't)."""
    c = center(n)
    if c is None:
        return None
    xdo("mousemove", c[0], c[1], "click", button)
    return c


def key(*keys) -> bool:
    return xdo("key", *keys)


def press_escape() -> None:
    key("Escape")


def type_text(text: str, delay: int = 20) -> bool:
    return xdo("type", "--delay", str(delay), text)


def close_all_dialogs(rounds: int = 3) -> None:
    for _ in range(rounds):
        press_escape()
        time.sleep(0.15)


def focus_app_window(app=None, settle: float = 0.4) -> bool:
    """Raise + keyboard-focus the app's top-level X11 window so xdotool clicks/typing
    reliably land in it. A freshly-relaunched window is frequently NOT window-manager
    focused yet — synthetic input then goes nowhere or to the wrong window, which is the
    cold-baseline flakiness (the warm run_live instance was focused long ago, so it hid
    this). Called once by the ``app`` fixture when the app is acquired, so a cold
    run_baseline behaves like the warm run_live. Best-effort — never raises, never fails a
    test; activating the already-mapped main window before any modal is opened is benign.
    """
    pid = None
    try:
        if app is None:
            app = get_app()
        if app is not None:
            pid = app.get_process_id()
    except Exception:
        pid = None

    def _search(*args) -> str | None:
        try:
            r = subprocess.run(
                ["xdotool", "search", "--onlyvisible", *args],
                capture_output=True,
                text=True,
                timeout=5,
            )
            wids = [w for w in r.stdout.split() if w.strip()]
            return wids[-1] if wids else None
        except Exception:
            return None

    wid = _search("--pid", str(pid)) if pid else None
    if (
        wid is None
    ):  # pid-owned window not found (e.g. window owned by a child); fall back to title
        name = os.environ.get("RB_APP_NAME", "")
        wid = _search("--name", name) if name else None
    if wid is None:
        return False
    try:
        subprocess.run(
            ["xdotool", "windowactivate", "--sync", wid, "windowfocus", wid],
            timeout=6,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
        )
        time.sleep(settle)
        return True
    except Exception:
        return False


# --------------------------------------------------------------------------- #
# Waits (replaces time.sleep spam — poll for the observation instead)
# --------------------------------------------------------------------------- #
def wait_for(predicate, timeout: float = 6.0, interval: float = 0.25) -> bool:
    deadline = time.time() + timeout
    while time.time() < deadline:
        try:
            if predicate():
                return True
        except Exception:
            pass
        time.sleep(interval)
    return False


def wait_node(root_fn, timeout: float = 6.0, **find_kw):
    """Poll until a node matching find_kw appears; return it or None."""
    out = [None]

    def _p():
        root = root_fn() if callable(root_fn) else root_fn
        n = find_first(root, **find_kw)
        out[0] = n
        return n is not None

    wait_for(_p, timeout=timeout)
    return out[0]


# --------------------------------------------------------------------------- #
# VLM screenshot assertion (opaque/visual cores: WebKit/QtWebEngine/canvas)
# --------------------------------------------------------------------------- #
def _results_dir() -> str:
    return os.environ.get("RB_RESULTS_DIR") or os.environ.get("RESULTS_DIR") or "."


def screenshot_assert(
    test_name: str, description: str, results_dir: str | None = None, window=None
):
    """Capture a PNG (optionally cropped to ``window``'s extents) and record a
    natural-language assertion for the downstream VLM judge. Writes to both the
    append-only jsonl (authoritative key set, survives per-module truncation) and
    the tolerant assertions.json dict — exactly the contract phase-2 consumes.
    """
    rd = results_dir or _results_dir()
    ss_dir = os.path.join(rd, "screenshots")
    os.makedirs(ss_dir, exist_ok=True)
    fname = f"{test_name}.png"
    path = os.path.join(ss_dir, fname)
    ok = False
    for cmd in (
        ["import", "-window", "root", path],
        ["scrot", "-o", path],
        ["gnome-screenshot", "-f", path],
    ):
        try:
            subprocess.run(
                cmd, timeout=15, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
            )
            if os.path.exists(path) and os.path.getsize(path) > 0:
                ok = True
                break
        except Exception:
            continue
    if ok and window is not None:
        try:
            ext = window.get_extents(Atspi.CoordType.SCREEN)
            if ext.width > 0 and ext.height > 0:
                subprocess.run(
                    [
                        "convert",
                        path,
                        "-crop",
                        f"{ext.width}x{ext.height}+{ext.x}+{ext.y}",
                        path,
                    ],
                    timeout=15,
                    stdout=subprocess.DEVNULL,
                    stderr=subprocess.DEVNULL,
                )
        except Exception:
            pass
    if not ok:
        return False
    try:
        with open(os.path.join(ss_dir, "screenshot_asserts.jsonl"), "a") as f:
            f.write(
                json.dumps({"screenshot": fname, "description": description}) + "\n"
            )
    except Exception:
        pass
    try:
        aj = os.path.join(ss_dir, "assertions.json")
        data = {}
        if os.path.exists(aj):
            try:
                data = json.load(open(aj))
            except Exception:
                data = {}
        data[test_name] = {"screenshot": fname, "description": description}
        json.dump(data, open(aj, "w"))
    except Exception:
        pass
    return True