Datasets:
File size: 20,691 Bytes
41dfd8d | 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 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 | """Shared navigation / observation helpers for the tmpNote AX test suite.
tmpNote is an LSUIElement (menu-bar / status-item) app: it has NO window at launch.
Every surface is reached from a status-bar icon, so each lane needs the same reveal
and read primitives. They live here so all six test modules agree on them and so a
recreation that wires the SAME feature slightly differently still gets found.
Portability contract (this module is scanned by rb_lint_sources):
* never spawns the app, never hardcodes an install path or bundle id
* only talks to the AXHelper instance handed in by the `ax` pytest fixture
* every locator is tolerant (AXDescription -> AXHelp -> AXTitle keyword match)
Navigation entry points are deliberately named `rb_enter_*` / `rb_reach_*` so
rb_audit_depth() can see that a declared depth>=1 is backed by a real surface
crossing.
"""
import os
import re
import subprocess
import time
import Foundation
from ApplicationServices import (
AXUIElementCopyParameterizedAttributeValue,
AXValueCreate,
kAXValueCFRangeType,
)
import rb_testgen_kit as kit
import verifier_helpers as helpers
# ── timing ────────────────────────────────────────────────────────────────────
T_CLICK = 0.35 # after a plain button press
T_SURFACE = 1.3 # after a press that opens/closes a surface
T_MODE = 1.3 # after a content-mode switch (rebuilds the text view)
# ── canonical AXDescription of every popover control (official app) ───────────
BTN_LOCK = "Lock app on screen button"
BTN_WINDOW = "Open in a separate window"
BTN_SHARE = "Share button"
BTN_MENU = "Menu button"
BTN_CLEAR = "Clear button"
VIEW_BUTTONS = ["View 1", "View 2", "View 3", "View 4", "View 5"]
# AXHelp of the three content-mode segments of the mode radio group
MODE_TEXT = "Plain text mode"
MODE_MARKDOWN = "Markdown preview mode"
MODE_DRAWING = "Drawing mode"
# Keyword fallbacks, so a recreation that labels things a little differently
# is still located rather than scored 0 for a naming difference.
_KW = {
BTN_LOCK: ("lock", "hide on deactivate", "pin"),
BTN_WINDOW: ("separate window", "window", "detach", "panel"),
BTN_SHARE: ("share",),
BTN_MENU: ("menu", "settings", "preferences", "gear"),
BTN_CLEAR: ("clear", "trash", "erase"),
}
_MODE_KW = {
MODE_TEXT: ("plain", "text box", "text"),
MODE_MARKDOWN: ("markdown", "quick look", "preview"),
MODE_DRAWING: ("draw", "sketch"),
}
# ── low level reads ──────────────────────────────────────────────────────────
def attrs(ax, el_id, names=("AXDescription", "AXHelp", "AXTitle", "AXValue", "AXEnabled")):
"""Read several attributes at once, tolerating a dead element id."""
try:
return ax.get(el_id, list(names)) or {}
except Exception:
return {}
def _label_blob(ax, el_id):
a = attrs(ax, el_id, ("AXDescription", "AXHelp", "AXTitle"))
return " ".join(str(a.get(k) or "") for k in ("AXDescription", "AXHelp", "AXTitle")).lower()
def find_button(ax, desc, root_id=None):
"""Locate a popover button by exact AXDescription, then by keyword."""
buttons = ax.find(role="button", root_id=root_id, max_results=40, max_depth=14)
for b in buttons:
if (attrs(ax, b.id, ("AXDescription",)).get("AXDescription") or "") == desc:
return b
for kw in _KW.get(desc, ()):
for b in buttons:
if kw in _label_blob(ax, b.id):
return b
return None
def find_button_by_title(ax, title, root_id=None):
"""Locate a button by AXTitle (alert buttons carry their label in AXTitle)."""
want = title.strip().lower()
for b in ax.find(role="button", root_id=root_id, max_results=40, max_depth=14):
got = (attrs(ax, b.id, ("AXTitle",)).get("AXTitle") or "").strip().lower()
if got == want:
return b
return None
def mode_radios(ax):
"""The three content-mode segments, in tree order."""
groups = ax.find(role="radiogroup", max_results=3, max_depth=14)
for g in groups:
radios = ax.find(role="radio", root_id=g.id, max_results=8)
if len(radios) >= 2:
return radios
return []
def find_mode_radio(ax, mode_help):
"""Locate one content-mode segment by AXHelp, then by keyword, then by index."""
radios = mode_radios(ax)
for r in radios:
if (attrs(ax, r.id, ("AXHelp",)).get("AXHelp") or "") == mode_help:
return r
for kw in _MODE_KW.get(mode_help, ()):
for r in radios:
if kw in _label_blob(ax, r.id):
return r
order = [MODE_TEXT, MODE_MARKDOWN, MODE_DRAWING]
if mode_help in order and len(radios) > order.index(mode_help):
return radios[order.index(mode_help)]
return None
def mode_values(ax):
"""AXValue of each mode segment -> [1, 0, 0] means plain-text is selected."""
out = []
for r in mode_radios(ax):
v = attrs(ax, r.id, ("AXValue",)).get("AXValue")
try:
out.append(int(v))
except (TypeError, ValueError):
out.append(0)
return out
def selected_mode_index(ax):
vals = mode_values(ax)
for i, v in enumerate(vals):
if v:
return i
return -1
def text_area(ax):
"""The note's editable text surface."""
found = ax.find(role="text_area", max_results=3, max_depth=14)
return found[0] if found else None
def note_text(ax):
ta = text_area(ax)
if ta is None:
return None
return attrs(ax, ta.id, ("AXValue",)).get("AXValue")
def set_note_text(ax, value):
"""Write the note body. NSTextView accepts an AXValue write and, unlike a
blind keystroke, it does not depend on which app is frontmost."""
ta = text_area(ax)
if ta is None:
return False
ok = bool(ax.set_value(ta.id, value))
time.sleep(0.45)
return ok
def note_is_editable(ax):
"""True when the note text can be typed into (plain-text mode)."""
ta = text_area(ax)
if ta is None:
return False
try:
return bool(ax.is_attribute_settable(ta.id, "AXValue"))
except Exception:
return False
def glyph_bounds(ax, length=10):
"""(width, height) in points of the first `length` characters of the note.
The only AX-visible consequence of a font-size change: NSTextView reports the
rendered rect of a character range, and that rect grows/shrinks with the font.
Returns None when the surface does not implement AXBoundsForRange.
"""
ta = text_area(ax)
if ta is None:
return None
try:
ref = ax._get_ref(ta.id)
rng = AXValueCreate(kAXValueCFRangeType, Foundation.NSRange(0, length))
err, val = AXUIElementCopyParameterizedAttributeValue(
ref, "AXBoundsForRange", rng, None)
if err != 0 or val is None:
return None
m = re.search(r"w:([0-9.]+)\s+h:([0-9.]+)", str(val))
return (float(m.group(1)), float(m.group(2))) if m else None
except Exception:
return None
def popover(ax):
found = ax.find(role="popover", max_results=5, max_depth=12)
return found[0] if found else None
def note_surface(ax):
"""The container currently holding the note UI: popover, or the detached window."""
p = popover(ax)
if p is not None:
return p
for w in ax.find(role="window", max_results=8, max_depth=3):
if find_button(ax, BTN_CLEAR, root_id=w.id) is not None:
return w
return None
def window_titled(ax, title):
want = title.strip().lower()
for w in ax.find(role="window", max_results=8, max_depth=3):
got = (w.name or attrs(ax, w.id, ("AXTitle",)).get("AXTitle") or "").strip().lower()
if got == want:
return w
return None
def sheet(ax):
found = ax.find(role="sheet", max_results=4, max_depth=12)
if found:
return found[0]
found = ax.find(role="dialog", max_results=4, max_depth=12)
return found[0] if found else None
def surface_texts(ax, root_id=None):
"""Every static-text / label value on a surface."""
out = []
for role in ("label", "static_text", "text"):
for t in ax.find(role=role, root_id=root_id, max_results=60, max_depth=14):
v = attrs(ax, t.id, ("AXValue", "AXTitle")).get("AXValue")
if v is None:
v = t.name
if v not in (None, ""):
out.append(str(v))
if out:
break
return out
def menu_items_of(ax, *required):
"""Find an open menu that contains all of `required` items; return its items.
Used to identify a specific popped-up menu among the many menus a Cocoa app
exposes (the whole main menu bar is always in the tree).
"""
want = [r.lower() for r in required]
for m in ax.find(role="menu", max_results=80, max_depth=14):
kids = ax.find(role="menu_item", root_id=m.id, max_results=25)
names = [(k.name or "").lower() for k in kids]
if all(any(w in n for n in names) for w in want):
return kids
return []
def menu_item_named(items, name):
want = name.strip().lower().rstrip(".…")
for k in items:
got = (k.name or "").strip().lower().rstrip(".…")
if got == want:
return k
for k in items:
if want and want in (k.name or "").strip().lower():
return k
return None
# ── navigation: reveal / enter surfaces ──────────────────────────────────────
def _status_items(ax):
"""Menu-bar items that are NOT the app's own main menus.
A status item has no title; the main menus (Apple/tmpNote/File/…) all do.
Unnamed items are returned last-first because the extras menu bar is walked
after the main menu bar.
"""
items = ax.find(role="menu_bar_item", max_results=25, max_depth=6)
blank = [m for m in items if not (m.name or "").strip()]
return list(reversed(blank))
def rb_reach_popover(ax, timeout=12.0):
"""Reveal the note surface from the status-bar icon. Returns the container.
Fast path: press the unnamed status item directly (the app's own main menus
never open the popover, so pressing them is pure latency). Falls back to the
generic ensure_panel_open() reveal ladder for a recreation whose status item
is exposed differently.
"""
existing = note_surface(ax)
if existing is not None:
return existing
deadline = time.time() + timeout
for si in _status_items(ax):
try:
ax.action(si.id, "AXPress")
except Exception:
continue
time.sleep(T_SURFACE)
surface = note_surface(ax)
if surface is not None:
return surface
try:
ax.click_element_cg(si.id)
except Exception:
pass
time.sleep(T_SURFACE)
surface = note_surface(ax)
if surface is not None:
return surface
if time.time() > deadline:
break
helpers.ensure_panel_open(ax)
time.sleep(0.4)
return note_surface(ax)
# `ensure_note_surface` reads better at call sites that only need the container.
ensure_note_surface = rb_reach_popover
def rb_enter_app_menu(ax):
"""Open the popover's own gear menu (Preferences / font size / quit).
The gear button pops an NSMenu via `NSMenu.popUp(positioning:at:in:)`; an
AXPress does not run that nested tracking loop, so a real CGEvent click is
required. Returns the menu's items.
"""
rb_reach_popover(ax)
btn = find_button(ax, BTN_MENU)
if btn is None:
return []
try:
ax.click_element_cg(btn.id)
except Exception:
return []
time.sleep(T_SURFACE)
items = menu_items_of(ax, "font size")
if not items:
items = menu_items_of(ax, "preferences")
return items
def rb_enter_preferences(ax):
"""Open the Preferences window (gear menu -> "Preferences..."). Returns the window."""
existing = window_titled(ax, "tmpNote")
items = rb_enter_app_menu(ax)
target = menu_item_named(items, "Preferences") if items else None
if target is not None:
try:
ax.action(target.id, "AXPress")
except Exception:
pass
time.sleep(1.8)
win = window_titled(ax, "Preferences")
if win is None:
# A recreation may put settings behind the standard ⌘, instead.
dismiss_open_menu(ax)
_keystroke(",", "command")
time.sleep(1.5)
win = window_titled(ax, "Preferences")
if win is None:
for w in ax.find(role="window", max_results=8, max_depth=3):
if existing is not None and w.id == existing.id:
continue
if ax.find(role="checkbox", root_id=w.id, max_results=4):
return w
return win
def rb_enter_clear_dialog(ax):
"""Press Clear and return the confirmation sheet (or None)."""
rb_reach_popover(ax)
btn = find_button(ax, BTN_CLEAR)
if btn is None:
return None
try:
ax.action(btn.id, "AXPress")
except Exception:
return None
time.sleep(1.7)
return sheet(ax)
def _button_labels(ax):
names = set()
for b in ax.find(role="button", max_results=70, max_depth=14):
title = (attrs(ax, b.id, ("AXTitle",)).get("AXTitle") or "").strip()
if not title:
title = (b.name or "").strip()
if title:
names.add(title)
return names
def rb_enter_share_picker(ax):
"""Press Share and return only the service buttons the picker ADDED.
Diffed against the buttons already on the note surface, so the result is the
share picker's own contents rather than the popover's toolbar.
"""
rb_reach_popover(ax)
btn = find_button(ax, BTN_SHARE)
if btn is None:
return []
before = _button_labels(ax)
try:
ax.action(btn.id, "AXPress")
except Exception:
return []
time.sleep(2.0)
return sorted(_button_labels(ax) - before)
def close_note_surface(ax, timeout=6.0):
"""Hide the note surface so a reveal test can prove a real surface jump.
Escape is the app's documented dismiss (cancelOperation); pressing the status
item again is the toggle. Returns True once no note surface is exposed.
"""
deadline = time.time() + timeout
while time.time() < deadline:
if note_surface(ax) is None:
return True
dismiss_open_menu(ax)
time.sleep(0.7)
if note_surface(ax) is None:
return True
items = _status_items(ax)
if items:
try:
ax.action(items[0].id, "AXPress")
except Exception:
pass
time.sleep(T_SURFACE)
return note_surface(ax) is None
def rb_enter_detached_window(ax):
"""Press "Open in a separate window" and return the detached window."""
rb_reach_popover(ax)
btn = find_button(ax, BTN_WINDOW)
if btn is None:
return None
try:
ax.action(btn.id, "AXPress")
except Exception:
return None
time.sleep(2.2)
win = window_titled(ax, "tmpNote")
if win is not None:
return win
for w in ax.find(role="window", max_results=8, max_depth=3):
if find_button(ax, BTN_CLEAR, root_id=w.id) is not None:
return w
return None
def rb_enter_view_menu(ax):
"""Open the main menu bar's View menu; return its items."""
for m in ax.find(role="menu_bar_item", max_results=25, max_depth=6):
if (m.name or "").strip().lower() == "view":
try:
ax.action(m.id, "AXPress")
except Exception:
return []
time.sleep(T_SURFACE)
return ax.find(role="menu_item", root_id=m.id, max_results=30, max_depth=3)
return []
def rb_reach_mode(ax, mode_help):
"""Switch content mode via the popover's mode segments. Returns True on success."""
rb_reach_popover(ax)
r = find_mode_radio(ax, mode_help)
if r is None:
return False
try:
ax.action(r.id, "AXPress")
except Exception:
return False
time.sleep(T_MODE)
return True
def press_button(ax, desc):
"""Press a popover button by description. Returns True when it was pressed."""
btn = find_button(ax, desc)
if btn is None:
return False
try:
ax.action(btn.id, "AXPress")
except Exception:
return False
time.sleep(T_CLICK)
return True
# ── teardown ─────────────────────────────────────────────────────────────────
def _keystroke(key, modifier=None):
script = f'tell application "System Events" to keystroke "{key}"'
if modifier:
script += f" using {modifier} down"
try:
subprocess.run(["osascript", "-e", script], capture_output=True, timeout=5)
except Exception:
pass
def dismiss_open_menu(ax):
"""Close a popped-up menu without closing the note surface, best effort."""
try:
helpers.send_key(helpers.KC_ESCAPE)
except Exception:
pass
time.sleep(0.4)
def reset_ui(ax):
"""Return the app to its default surface state: no dialog, no menu, no
detached window, plain-text mode, empty note. Called at the top of a test so
the previous test's leftovers cannot decide this one's verdict."""
for _ in range(3):
s = sheet(ax)
if s is None:
break
cancel = find_button_by_title(ax, "Cancel", root_id=s.id)
if cancel is not None:
try:
ax.action(cancel.id, "AXPress")
except Exception:
pass
else:
dismiss_open_menu(ax)
time.sleep(0.9)
dismiss_open_menu(ax)
prefs = window_titled(ax, "Preferences")
if prefs is not None:
_close_window(ax, prefs)
surface = note_surface(ax)
if surface is None:
surface = rb_reach_popover(ax)
if surface is None:
return None
# A detached window is a different surface than the popover; fold it back.
if window_titled(ax, "tmpNote") is not None and popover(ax) is None:
if press_button(ax, BTN_WINDOW):
time.sleep(2.0)
if popover(ax) is None:
rb_reach_popover(ax)
if selected_mode_index(ax) != 0:
rb_reach_mode(ax, MODE_TEXT)
if note_is_editable(ax):
set_note_text(ax, "")
return note_surface(ax)
def _close_window(ax, win):
for b in ax.find(role="button", root_id=win.id, max_results=20):
if (attrs(ax, b.id, ("AXSubrole",)).get("AXSubrole")) == "AXCloseButton":
try:
ax.action(b.id, "AXPress")
except Exception:
pass
time.sleep(1.0)
return True
dismiss_open_menu(ax)
return False
# ── screenshots for the VLM judge ────────────────────────────────────────────
def results_dir():
return (os.environ.get("RESULTS_DIR")
or os.environ.get("AX_RESULTS_DIR")
or os.path.join(os.path.dirname(os.path.abspath(__file__)), "baseline_results"))
def screenshot_assert(test_name, description, out_dir=None):
"""Capture the screen and record what a VLM should see in it."""
import json
base = out_dir or results_dir()
ss_dir = os.path.join(base, "screenshots")
try:
os.makedirs(ss_dir, exist_ok=True)
subprocess.run(["screencapture", "-x", os.path.join(ss_dir, f"{test_name}.png")],
timeout=8, capture_output=True)
path = os.path.join(ss_dir, "assertions.json")
data = {}
if os.path.exists(path):
try:
with open(path) as fh:
data = json.load(fh)
except Exception:
data = {}
data[f"{test_name}.png"] = description
with open(path, "w") as fh:
json.dump(data, fh, indent=2)
except Exception:
pass
# Re-export so lanes need a single import for the verdict primitives.
rb_showing = kit.rb_showing
rb_reach = kit.rb_reach
rb_flip = kit.rb_flip
rb_value = kit.rb_value
|