import os import re import time import warnings import subprocess from dataclasses import dataclass, field from typing import Optional from collections import Counter, deque from ApplicationServices import ( AXUIElementCreateApplication, AXUIElementCreateSystemWide, AXUIElementCopyAttributeNames, AXUIElementCopyAttributeValue, AXUIElementGetAttributeValueCount, AXUIElementCopyAttributeValues, AXUIElementIsAttributeSettable, AXUIElementSetAttributeValue, AXUIElementCopyMultipleAttributeValues, AXUIElementCopyParameterizedAttributeNames, AXUIElementCopyParameterizedAttributeValue, AXUIElementCopyActionNames, AXUIElementCopyActionDescription, AXUIElementPerformAction, AXUIElementCopyElementAtPosition, AXUIElementGetPid, AXUIElementSetMessagingTimeout, kAXValueCGPointType, kAXValueCGSizeType, AXValueGetValue, ) import Quartz ROLE_MAP = { "AXButton": "button", "AXStaticText": "label", "AXTextField": "text_field", "AXTextArea": "text_area", "AXCheckBox": "checkbox", "AXRadioButton": "radio", "AXPopUpButton": "popup", "AXComboBox": "combobox", "AXSlider": "slider", "AXImage": "image", "AXGroup": "group", "AXList": "list", "AXTable": "table", "AXGrid": "grid", "AXCell": "cell", "AXRow": "row", "AXColumn": "column", "AXOutline": "outline", "AXToolbar": "toolbar", "AXTabGroup": "tab_group", "AXTab": "tab", "AXScrollArea": "scroll_area", "AXScrollBar": "scroll_bar", "AXWindow": "window", "AXSheet": "sheet", "AXDialog": "dialog", "AXPopover": "popover", "AXMenu": "menu", "AXMenuBar": "menu_bar", "AXMenuBarItem": "menu_bar_item", "AXMenuItem": "menu_item", "AXSplitGroup": "split_group", "AXSplitter": "splitter", "AXProgressIndicator": "progress", "AXBusyIndicator": "busy", "AXValueIndicator": "value_indicator", "AXLink": "link", "AXDisclosureTriangle": "disclosure", } @dataclass class AXElement: id: str role: str name: Optional[str] = None value: Optional[str] = None text: Optional[str] = None enabled: bool = True actions: list = field(default_factory=list) ref: object = field(default=None, repr=False) _DYNAMIC_TEXT_PATTERNS = [ re.compile(r"^\d{1,2}:\d{2}(:\d{2})?(\s*[AP]M)?$"), re.compile(r"^\d{4}-\d{2}-\d{2}"), re.compile(r"^\d{1,2}/\d{1,2}/\d{2,4}$"), ] def _bundle_for_pid(pid): """Best-effort .app bundle path for a running pid (via its executable path).""" try: out = subprocess.run( ["ps", "-o", "comm=", "-p", str(int(pid))], capture_output=True, text=True, ).stdout.strip() except Exception: return "" marker = "/Contents/MacOS/" return out.split(marker)[0] if marker in out else "" def is_electron_app(pid): """True if the app for `pid` is a Chromium-based app (Electron or CEF) whose web content AX tree stays empty unless launched with --force-renderer-accessibility. Detected by the presence of the Electron/CEF framework — precise, and does NOT false-positive on a native app that merely bundles a "* Helper.app" (XPC helper).""" bundle = _bundle_for_pid(pid) if not bundle: return False fw = bundle + "/Contents/Frameworks" return (os.path.isdir(fw + "/Electron Framework.framework") or os.path.isdir(fw + "/Chromium Embedded Framework.framework")) def wait_for_web_ax(pid, timeout=8.0): """For Electron apps launched with --force-renderer-accessibility, the Chromium AXWebArea appears a few seconds after launch (async). Poll until it shows up so a read right after launch doesn't capture an empty window. Fast no-op for non-Electron apps (native/Gecko already expose AX). Best-effort; returns True when settled or when the app isn't Electron.""" try: if not is_electron_app(pid): return True app = AXUIElementCreateApplication(int(pid)) except Exception: return True try: AXUIElementSetMessagingTimeout(app, 5.0) except Exception: pass deadline = time.time() + timeout while time.time() < deadline: dq = deque([app]) seen = 0 while dq and seen < 8000: el = dq.popleft() seen += 1 err, role = AXUIElementCopyAttributeValue(el, "AXRole", None) if err == 0 and str(role) == "AXWebArea": return True # Chromium web content is built err, kids = AXUIElementCopyAttributeValue(el, "AXChildren", None) if err == 0 and kids: for k in kids: dq.append(k) time.sleep(0.5) return True class AXHelper: def __init__(self, app_name_or_pid, wait_for_ready=True, ready_timeout=10, prime=True): if isinstance(app_name_or_pid, int): self._pid = app_name_or_pid else: self._pid = self._find_pid_by_name(app_name_or_pid) self._app_ref = AXUIElementCreateApplication(self._pid) self._element_cache = {} # Electron apps launched with --force-renderer-accessibility build their # Chromium AXWebArea a few seconds after launch (async). Wait for it here so # the first real read sees full web content, not an empty window. Runs even # when wait_for_ready=False (e.g. the pytest `ax` fixture). Fast no-op for # non-Electron apps (native/Gecko already expose AX). if prime: wait_for_web_ax(self._pid) if wait_for_ready: self._wait_until_ready(ready_timeout) def _wait_until_ready(self, timeout): deadline = time.time() + timeout while time.time() < deadline: try: err, role = AXUIElementCopyAttributeValue(self._app_ref, "AXRole", None) if err == 0 and role: err, children = AXUIElementCopyAttributeValue( self._app_ref, "AXChildren", None ) if err == 0 and children and len(children) > 0: return except Exception: pass time.sleep(0.3) warnings.warn(f"AX tree for PID {self._pid} not ready after {timeout}s") def _find_pid_by_name(self, name): search_name = name[:15] result = subprocess.run( ["pgrep", "-x", search_name], capture_output=True, text=True ) if result.returncode != 0: result = subprocess.run( ["pgrep", "-f", search_name], capture_output=True, text=True ) if result.returncode != 0: raise RuntimeError(f"Process '{name}' not found") return int(result.stdout.strip().split("\n")[0]) # ── Core API ── def find( self, role=None, name=None, name_contains=None, value=None, enabled=None, max_results=50, root_id=None, max_depth=None, ): root_ref = self._get_ref(root_id) if root_id else self._app_ref results = [] def _recurse(ref, depth): if max_depth is not None and depth > max_depth: return if len(results) >= max_results: return el = self._ref_to_element(ref) if self._matches(el, role, name, name_contains, value, enabled): results.append(el) err, children = AXUIElementCopyAttributeValue(ref, "AXChildren", None) if err == 0 and children: for child in children: _recurse(child, depth + 1) if len(results) >= max_results: return _recurse(root_ref, 0) return results def action(self, element_id, action_name): ref = self._get_ref(element_id) if ref is None: return False try: err = AXUIElementPerformAction(ref, action_name) return err == 0 except Exception: return False def action_checked(self, element_id, action_name): success = self.action(element_id, action_name) if not success: warnings.warn(f"Action '{action_name}' failed on {element_id}") return success def click_element_cg(self, element_id): """Simulate a real mouse click at the element's screen position using CGEvent. Use this when AXPress doesn't work — e.g. menu bar apps that use NSEvent.addLocalMonitorForEvents instead of button target-action. """ ref = self._get_ref(element_id) if ref is None: return False center = self._get_element_center(ref) if center is None: return False point = Quartz.CGPointMake(center[0], center[1]) event_down = Quartz.CGEventCreateMouseEvent( None, Quartz.kCGEventLeftMouseDown, point, Quartz.kCGMouseButtonLeft ) Quartz.CGEventPost(Quartz.kCGHIDEventTap, event_down) time.sleep(0.05) event_up = Quartz.CGEventCreateMouseEvent( None, Quartz.kCGEventLeftMouseUp, point, Quartz.kCGMouseButtonLeft ) Quartz.CGEventPost(Quartz.kCGHIDEventTap, event_up) return True def get(self, element_id, attributes): # element_id=None 表示 APPLICATION 元素,与 find(root_id=None)/attribute_names(None) 一致。 # 否则 ax.get(None, ["AXTitle"]) 走不进元素缓存、返回 {},读 app 自身标题的 test 拿到 None。 ref = self._get_ref(element_id) if element_id else self._app_ref if ref is None: return {} result = {} for attr in attributes: try: err, val = AXUIElementCopyAttributeValue(ref, attr, None) if err == 0: result[attr] = self._serialize_value(val) else: result[attr] = None except Exception: result[attr] = None return result def activate(self): """把本 helper 绑定的 app 提到前台,返回是否成功。 有些 toolkit 只在进程被 ACTIVATED 时才装原生菜单栏:olive(Qt)启动后 90s 仍只有 ['Apple','Olive'];zotero(Gecko/XUL)一直只有 ['Apple','Zotero','File','Window'], 且搜索框会吞掉合成键。一次激活即补齐。用 AX API 设 AXFrontmost 会返回成功但无效, 所以走 NSRunningApplication。 """ try: from AppKit import NSRunningApplication except Exception: return False try: app = NSRunningApplication.runningApplicationWithProcessIdentifier_(int(self._pid)) if app is None: return False return bool(app.activateWithOptions_(1 << 1)) # IgnoringOtherApps except Exception: return False def set_value(self, element_id, value): ref = self._get_ref(element_id) if ref is None: return False try: err = AXUIElementSetAttributeValue(ref, "AXValue", value) return err == 0 except Exception: return False # ── Attribute Introspection ── def attribute_names(self, element_id=None): ref = self._get_ref(element_id) if element_id else self._app_ref if ref is None: return [] try: err, names = AXUIElementCopyAttributeNames(ref, None) if err == 0 and names: return list(names) except Exception: pass return [] def is_attribute_settable(self, element_id, attribute): ref = self._get_ref(element_id) if ref is None: return False try: err, settable = AXUIElementIsAttributeSettable(ref, attribute, None) return err == 0 and bool(settable) except Exception: return False def attribute_value_count(self, element_id, attribute): ref = self._get_ref(element_id) if ref is None: return 0 try: err, count = AXUIElementGetAttributeValueCount(ref, attribute, None) return count if err == 0 else 0 except Exception: return 0 def attribute_values_range(self, element_id, attribute, index, count): ref = self._get_ref(element_id) if ref is None: return [] try: err, values = AXUIElementCopyAttributeValues(ref, attribute, index, count, None) if err == 0 and values: return [self._serialize_value(v) for v in values] except Exception: pass return [] def get_multiple(self, element_id, attributes): ref = self._get_ref(element_id) if ref is None: return {} try: err, values, errors = AXUIElementCopyMultipleAttributeValues( ref, attributes, 0, None, None ) if err == 0 and values: result = {} for i, attr in enumerate(attributes): if i < len(values): result[attr] = self._serialize_value(values[i]) else: result[attr] = None return result except Exception: pass return self.get(element_id, attributes) # ── Parameterized Attributes ── def parameterized_attribute_names(self, element_id=None): ref = self._get_ref(element_id) if element_id else self._app_ref if ref is None: return [] try: err, names = AXUIElementCopyParameterizedAttributeNames(ref, None) if err == 0 and names: return list(names) except Exception: pass return [] def parameterized_attribute_value(self, element_id, attribute, parameter): ref = self._get_ref(element_id) if ref is None: return None try: err, value = AXUIElementCopyParameterizedAttributeValue( ref, attribute, parameter, None ) if err == 0: return self._serialize_value(value) except Exception: pass return None # ── Action Introspection ── def action_description(self, element_id, action_name): ref = self._get_ref(element_id) if ref is None: return "" try: err, desc = AXUIElementCopyActionDescription(ref, action_name, None) if err == 0 and desc: return str(desc) except Exception: pass return "" # ── Position / PID / Timeout ── def element_at_position(self, x, y): try: sys_ref = AXUIElementCreateSystemWide() err, el_ref = AXUIElementCopyElementAtPosition(sys_ref, float(x), float(y), None) if err == 0 and el_ref: element = self._ref_to_element(el_ref) return element except Exception: pass return None def get_pid(self, element_id=None): ref = self._get_ref(element_id) if element_id else self._app_ref if ref is None: return -1 try: err, pid = AXUIElementGetPid(ref, None) return pid if err == 0 else -1 except Exception: return -1 def set_messaging_timeout(self, element_id, timeout_seconds): ref = self._get_ref(element_id) if element_id else self._app_ref if ref is None: return False try: err = AXUIElementSetMessagingTimeout(ref, float(timeout_seconds)) return err == 0 except Exception: return False @staticmethod def create_system_wide(): return AXUIElementCreateSystemWide() def tree(self, max_depth=5, root_id=None): root_ref = self._get_ref(root_id) if root_id else self._app_ref def _build(ref, depth): el = self._ref_to_element(ref) node = { "role": el.role, "name": el.name, "id": el.id, "actions": el.actions, } if el.value: node["value"] = str(el.value)[:100] if depth < max_depth: err, children = AXUIElementCopyAttributeValue(ref, "AXChildren", None) if err == 0 and children: node["children"] = [_build(c, depth + 1) for c in children] return node return _build(root_ref, 0) def list_apps(self): from AppKit import NSWorkspace apps = NSWorkspace.sharedWorkspace().runningApplications() return [ { "name": app.localizedName(), "pid": app.processIdentifier(), "bundle_id": app.bundleIdentifier() or "", "type": "regular" if app.activationPolicy() == 0 else "accessory", } for app in apps if app.activationPolicy() in (0, 1) ] # ── Capability-based Search ── def find_clickable(self, root_id=None, max_results=50): all_elements = self._walk_tree(root_id, max_results * 3) clickable = [] for el in all_elements: if "AXPress" in el.actions or "AXConfirm" in el.actions: subrole = self._get_attr(el.ref, "AXSubrole", "") if subrole in ( "AXCloseButton", "AXMinimizeButton", "AXZoomButton", "AXFullScreenButton", ): continue clickable.append(el) if len(clickable) >= max_results: break return clickable def find_text_elements(self, root_id=None, max_results=100): all_elements = self._walk_tree(root_id, max_results * 3) text_elements = [] for el in all_elements: text = ( self._get_attr(el.ref, "AXValue", "") or self._get_attr(el.ref, "AXTitle", "") or self._get_attr(el.ref, "AXDescription", "") or el.name or "" ) if isinstance(text, str) and text.strip(): el.text = text.strip() text_elements.append(el) if len(text_elements) >= max_results: break return text_elements def find_value_settable(self, root_id=None, max_results=20): all_elements = self._walk_tree(root_id, max_results * 3) settable = [] for el in all_elements: try: err, is_settable = AXUIElementIsAttributeSettable( el.ref, "AXValue", None ) if err == 0 and is_settable: settable.append(el) if len(settable) >= max_results: break except Exception: continue return settable def find_togglable(self, root_id=None, max_results=20): all_elements = self._walk_tree(root_id, max_results * 3) togglable = [] for el in all_elements: if "AXPress" in el.actions: value = self._get_attr(el.ref, "AXValue", None) if value in (0, 1, True, False, "0", "1"): togglable.append(el) if len(togglable) >= max_results: break return togglable # ── Text Snapshot ── def snapshot_all_text(self, exclude_dynamic=True): text_elements = self.find_text_elements(max_results=200) texts = [] for el in text_elements: text = el.text if exclude_dynamic and any( p.match(text) for p in _DYNAMIC_TEXT_PATTERNS ): continue texts.append(text) return Counter(texts) def wait_for_text_change(self, original_text, timeout=3.0): deadline = time.time() + timeout while time.time() < deadline: current = self.snapshot_all_text() if current != original_text: return current time.sleep(0.2) return self.snapshot_all_text() def wait_for(self, role=None, name=None, timeout=5.0, max_results=1): deadline = time.time() + timeout while time.time() < deadline: results = self.find(role=role, name=name, max_results=max_results) if results: return results time.sleep(0.3) return [] # ── Verifier Helpers ── def find_safe_buttons(self, max_results=20): clickable = self.find_clickable(max_results=max_results * 2) safe = [] for el in clickable: name_lower = (el.name or "").lower() if any( kw in name_lower for kw in [ "quit", "delete", "remove", "erase", "reset", "clear all", "uninstall", ] ): continue safe.append(el) if len(safe) >= max_results: break return safe def ensure_ui_visible(self): _CONTAINER_ROLES = ["window", "popover", "group", "sheet"] # Menu-item labels that reveal the main UI via a Settings/Preferences # window (EN + ZH). Kept deliberately narrow and high-signal: broader # verbs like "open"/"show" risk pressing File-menu items such as # "Open…" that pop a file dialog instead of revealing the main UI. _REVEAL_KW = ("preference", "settings", "偏好", "设置") def _visible(): # max_depth=12 (was 3): status-item / menu-bar popovers sit ~7-8 levels # deep in the AX tree, so a depth-3 check reported "not visible" even # after the popover opened -> reveal loops gave up / tests saw no UI. for role in _CONTAINER_ROLES: if self.find(role=role, max_results=1, max_depth=12): return True return False if _visible(): return True menu_items = self.find(role="menu_bar_item", max_results=8, max_depth=3) for item in menu_items: self.action(item.id, "AXPress") time.sleep(0.5) if _visible(): return True # Two-level reveal: pressing the status/menu-bar item may open a MENU # (not the window). A valid recreation can wire it as # icon -> menu -> "Preferences…" -> window. Click a reveal item. for mi in self.find(role="menu_item", max_results=40, max_depth=6): name = (mi.name or "").lower() if name and any(k in name for k in _REVEAL_KW): self.action(mi.id, "AXPress") time.sleep(0.5) if _visible(): return True # AXPress may not work for apps using NSEvent mouse monitoring; # fall back to a real CGEvent click at the element's position. self.click_element_cg(item.id) time.sleep(1.0) if _visible(): return True # Preferences hotkey (⌘,) — standard macOS "show settings" trigger. # Guarded so this method preserves its contract of never raising # (osascript can hit the subprocess timeout). try: subprocess.run( [ "osascript", "-e", 'tell application "System Events" to ' 'keystroke "," using command down', ], capture_output=True, timeout=3, ) time.sleep(0.5) except Exception: pass return _visible() def dismiss_any_dialog(self): for role in ["sheet", "dialog"]: dialogs = self.find(role=role, max_results=3, max_depth=3) for dlg in dialogs: buttons = self.find(role="button", root_id=dlg.id, max_results=10) for btn in buttons: name_lower = (btn.name or "").lower() if name_lower in ( "cancel", "ok", "close", "dismiss", "don't save", ): self.action(btn.id, "AXPress") time.sleep(0.3) return True subprocess.run( [ "osascript", "-e", 'tell application "System Events" to key code 53', ], capture_output=True, timeout=2, ) time.sleep(0.3) return True return False def get_main_window(self): windows = self.find(role="window", max_results=10, max_depth=1) if not windows: return None if len(windows) == 1: return windows[0].id for w in windows: attrs = self.get(w.id, ["AXMain"]) if attrs.get("AXMain"): return w.id best, best_area = None, 0 for w in windows: attrs = self.get(w.id, ["AXSize"]) size = attrs.get("AXSize") if size is not None: area = getattr(size, "width", 0) * getattr(size, "height", 0) else: area = 0 if area > best_area: best_area = area best = w.id return best # ── Internal ── def _walk_tree(self, root_id, max_count): root_ref = self._get_ref(root_id) if root_id else self._app_ref results = [] def _recurse(ref): if len(results) >= max_count: return el = self._ref_to_element(ref) results.append(el) err, children = AXUIElementCopyAttributeValue(ref, "AXChildren", None) if err == 0 and children: for child in children: _recurse(child) if len(results) >= max_count: return _recurse(root_ref) return results def _ref_to_element(self, ref): el_id = str(hash(ref)) self._element_cache[el_id] = ref role_raw = self._get_attr(ref, "AXRole", "") role = ROLE_MAP.get( role_raw, role_raw.replace("AX", "").lower() if role_raw else "unknown", ) name = self._get_attr(ref, "AXTitle", "") or self._get_attr( ref, "AXDescription", "" ) value = self._get_attr(ref, "AXValue", "") enabled = self._get_attr(ref, "AXEnabled", True) actions = [] try: err, action_names = AXUIElementCopyActionNames(ref, None) if err == 0 and action_names: actions = list(action_names) except Exception: pass return AXElement( id=el_id, role=role, name=name, value=value, enabled=enabled, actions=actions, ref=ref, ) def _get_ref(self, element_id): return self._element_cache.get(element_id) def _get_element_center(self, ref): """Return (x, y) screen coordinates of the element's center, or None.""" pos_val = self._get_attr(ref, "AXPosition", None) size_val = self._get_attr(ref, "AXSize", None) if pos_val is None or size_val is None: return None pos_str = str(pos_val) size_str = str(size_val) pos_nums = re.findall(r"[-\d.]+", pos_str) size_nums = re.findall(r"[-\d.]+", size_str) if len(pos_nums) < 2 or len(size_nums) < 2: return None px, py = float(pos_nums[-2]), float(pos_nums[-1]) sw, sh = float(size_nums[-2]), float(size_nums[-1]) return (px + sw / 2, py + sh / 2) def _get_attr(self, ref, attr_name, default=None): try: err, val = AXUIElementCopyAttributeValue(ref, attr_name, None) return val if err == 0 else default except Exception: return default def _matches(self, el, role, name, name_contains, value, enabled): if role and el.role != role: return False if name and el.name != name: return False if name_contains and (not el.name or name_contains not in el.name): return False if value is not None and el.value != value: return False if enabled is not None and el.enabled != enabled: return False return True def _serialize_value(self, val): if val is None: return None if isinstance(val, (str, int, float, bool)): return val if hasattr(val, "width") and hasattr(val, "height"): return {"width": val.width, "height": val.height} if hasattr(val, "x") and hasattr(val, "y"): return {"x": val.x, "y": val.y} return str(val) def _pid_by_name(name): """Resolve a pid from a process name using the same MAXCOMLEN(15)/pgrep logic the stage shells use.""" s = name[:15] r = subprocess.run(["pgrep", "-x", s], capture_output=True, text=True) if r.returncode != 0: r = subprocess.run(["pgrep", "-f", s], capture_output=True, text=True) if r.returncode != 0: return None out = r.stdout.strip() return int(out.split("\n")[0]) if out else None