#!/usr/bin/env python3 """Dump an application's AT-SPI tree as plain text, for comparing the Wine Access publisher against native Linux Chromium on the same fixture. Usage: atspi_dump.py --app-name NAME [--wait SECONDS] [--max-nodes N] Waits for an application whose name contains NAME (case ignored) and a document-web descendant with children, then prints the tree. Never prints the text of password-text objects. """ import argparse import sys import time import warnings import gi gi.require_version("Atspi", "2.0") from gi.repository import Atspi # noqa: E402 # get_action_name is deprecated, but its replacement fails through PyGObject. warnings.filterwarnings("ignore", category=DeprecationWarning, message=".*get_action_name.*") nodeCount = 0 showBoundaries = False GRANULARITIES = (("word", Atspi.TextGranularity.WORD), ("sentence", Atspi.TextGranularity.SENTENCE), ("line", Atspi.TextGranularity.LINE), ("paragraph", Atspi.TextGranularity.PARAGRAPH)) def boundary_segments(accessible, characterCount, granularity): """Distinct (start, end) segments reported at every offset.""" segments = [] for offset in range(characterCount + 1): segment = safe(lambda: Atspi.Text.get_string_at_offset(accessible, offset, granularity)) if segment is None: entry = "error" else: entry = f"{segment.start_offset}-{segment.end_offset}" if not segments or segments[-1] != entry: segments.append(entry) return segments def safe(call, default=None): try: return call() except Exception: # AT-SPI raises GLib.Error for defunct objects return default def short(text, limit=100): if text is None: return "(null)" cleaned = text.replace("", "[obj]").replace("\n", "\\n") if len(cleaned) > limit: cleaned = cleaned[:limit] + "..." return f'"{cleaned}" len={len(text)}' def state_names(accessible): stateSet = safe(lambda: accessible.get_state_set()) if stateSet is None: return "?" names = [Atspi.StateType(state).value_nick for state in stateSet.get_states()] return ",".join(sorted(names)) or "-" def interface_names(accessible): return ",".join(sorted(safe(lambda: accessible.get_interfaces(), []) or [])) or "-" def find_document(accessible, depth=0): if depth > 40: return None if safe(lambda: accessible.get_role()) == Atspi.Role.DOCUMENT_WEB: if (safe(lambda: accessible.get_child_count(), 0) or 0) > 0: return accessible for index in range(safe(lambda: accessible.get_child_count(), 0) or 0): child = safe(lambda: accessible.get_child_at_index(index)) if child is not None: found = find_document(child, depth + 1) if found is not None: return found return None def describe(accessible, depth, maxNodes): global nodeCount if nodeCount >= maxNodes: return nodeCount += 1 indent = " " * depth role = safe(lambda: accessible.get_role_name(), "?") name = safe(lambda: accessible.get_name(), "") states = state_names(accessible) childCount = safe(lambda: accessible.get_child_count(), 0) or 0 print(f"{indent}- {role} name={short(name, 60)} children={childCount}") print(f"{indent} states: {states}") print(f"{indent} interfaces: {interface_names(accessible)}") attributes = safe(lambda: accessible.get_attributes(), {}) or {} if attributes: joined = ";".join(f"{key}:{value}" for key, value in sorted(attributes.items())) print(f"{indent} attrs: {short(joined, 240)}") relations = safe(lambda: accessible.get_relation_set(), []) or [] if relations: parts = [f"{relation.get_relation_type().value_nick}({relation.get_n_targets()})" for relation in relations] print(f"{indent} relations: {' '.join(parts)}") text = safe(lambda: accessible.get_text_iface()) if text is not None: characterCount = safe(lambda: text.get_character_count(), 0) or 0 if role == "password text": print(f"{indent} text: n={characterCount} (password, content not read)") else: content = safe(lambda: Atspi.Text.get_text(accessible, 0, characterCount), "") caret = safe(lambda: text.get_caret_offset(), -1) print(f"{indent} text: n={characterCount} {short(content)} caret={caret}") if showBoundaries and characterCount: for label, granularity in GRANULARITIES: print(f"{indent} {label}s: {' '.join(boundary_segments(accessible, characterCount, granularity))}") hypertext = safe(lambda: accessible.get_hypertext_iface()) if hypertext is not None: linkCount = safe(lambda: hypertext.get_n_links(), 0) or 0 if linkCount: ranges = [] for index in range(min(linkCount, 6)): link = safe(lambda: hypertext.get_link(index)) if link is not None: ranges.append(f"[{safe(lambda: link.get_start_index())}-{safe(lambda: link.get_end_index())}]") print(f"{indent} hyperlinks: {linkCount} {' '.join(ranges)}") action = safe(lambda: accessible.get_action_iface()) if action is not None: actionCount = safe(lambda: action.get_n_actions(), 0) or 0 if actionCount: names = [safe(lambda: Atspi.Action.get_action_name(accessible, index), "?") for index in range(actionCount)] print(f"{indent} actions: {','.join(names)}") table = safe(lambda: accessible.get_table_iface()) if table is not None: print(f"{indent} table: {safe(lambda: table.get_n_rows())}x{safe(lambda: table.get_n_columns())}") cell = safe(lambda: accessible.get_table_cell()) if cell is not None: position = safe(lambda: Atspi.TableCell.get_position(accessible), None) if isinstance(position, tuple): position = "r{} c{}".format(*position[-2:]) span = safe(lambda: Atspi.TableCell.get_row_column_span(accessible), None) if isinstance(span, tuple): span = "{}x{}".format(*span[-2:]) columnHeaders = safe(lambda: Atspi.TableCell.get_column_header_cells(accessible), []) or [] rowHeaders = safe(lambda: Atspi.TableCell.get_row_header_cells(accessible), []) or [] print(f"{indent} cell: position={position} span={span} columnHeaders={len(columnHeaders)} " f"rowHeaders={len(rowHeaders)}") for index in range(childCount): child = safe(lambda: accessible.get_child_at_index(index)) if child is not None: describe(child, depth + 1, maxNodes) def main(): parser = argparse.ArgumentParser() parser.add_argument("--app-name", required=True) parser.add_argument("--wait", type=float, default=30) parser.add_argument("--max-nodes", type=int, default=3000) parser.add_argument("--whole-app", action="store_true", help="dump the application, not just the document") parser.add_argument("--boundaries", action="store_true", help="also dump word/sentence/line/paragraph segments") options = parser.parse_args() global showBoundaries showBoundaries = options.boundaries deadline = time.monotonic() + options.wait application = None document = None while time.monotonic() < deadline: desktop = Atspi.get_desktop(0) for index in range(desktop.get_child_count()): candidate = safe(lambda: desktop.get_child_at_index(index)) candidateName = safe(lambda: candidate.get_name(), "") if candidate else "" if candidate is not None and options.app_name.lower() in (candidateName or "").lower(): application = candidate document = find_document(candidate) if document is not None: break if document is not None: break time.sleep(0.5) if application is None: print(f"No application matching {options.app_name}") return 3 print(f"application: name={short(safe(lambda: application.get_name()))} " f"toolkit={safe(lambda: application.get_toolkit_name())} " f"version={safe(lambda: application.get_toolkit_version())} " f"pid={safe(lambda: application.get_process_id())}") if document is None: print("No document-web with children found") return 4 describe(application if options.whole_app else document, 0, options.max_nodes) print(f"nodes={nodeCount}") return 0 if __name__ == "__main__": sys.exit(main())