Debian Codegraph @

tools/dump-tree.py

raw
1 #!/usr/bin/python
2 # dump-tree.py
3 #
4 # Command-line tool to dump the tree of accessible objects for a given application.
5 # Usage: dump-tree.py <APP_NAME>
6 #
7 # Copyright 2025 Igalia, S.L.
8 # Author: Joanmarie Diggs <[email protected]>
9 #
10 # This library is free software; you can redistribute it and/or
11 # modify it under the terms of the GNU Lesser General Public
12 # License as published by the Free Software Foundation; either
13 # version 2.1 of the License, or (at your option) any later version.
14 #
15 # This library is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 # Lesser General Public License for more details.
19 #
20 # You should have received a copy of the GNU Lesser General Public
21 # License along with this library; if not, write to the
22 # Free Software Foundation, Inc., Franklin Street, Fifth Floor,
23 # Boston MA 02110-1301 USA.
24
25 # pylint: disable=invalid-name
26 # pylint: disable=wrong-import-position
27
28 """Command-line tool to dump the tree of accessible objects for a given application."""
29
30 import sys
31
32 import gi
33
34 gi.require_version("Atspi", "2.0")
35 from gi.repository import Atspi, GLib
36
37
38 def as_string(
39 obj: Atspi.Accessible, prefix: str, expected_parent: Atspi.Accessible | None = None
40 ) -> str:
41 "Convert an accessible object to a string representation."
42
43 indent = " " * (len(prefix) + 1)
44 result = (
45 f"{prefix} "
46 f"{get_role_as_string(obj)} "
47 f"NAME: '{get_name(obj)}' "
48 f"DESCRIPTION: '{get_description(obj)}' "
49 f"ACCESSIBLE ID: '{get_accessible_id(obj)}'"
50 )
51
52 parent_info = get_parent_info(obj, expected_parent)
53 if parent_info:
54 result += f"\n{indent}{parent_info}"
55
56 result += (
57 f"\n{indent}INTERFACES: {get_interfaces_as_string(obj)}"
58 f"\n{indent}STATES: {get_states_as_string(obj)}"
59 f"\n{indent}ATTRIBUTES: {get_attributes_as_string(obj)}"
60 f"\n{indent}LOCALE: '{get_locale(obj)}'"
61 f"\n{indent}RECT: {get_rect_as_string(obj)}"
62 )
63
64 relations = get_relations_as_string(obj)
65 if relations:
66 result += f"\n{indent}RELATIONS: {relations}"
67
68 selection_info = get_selection_info(obj, indent)
69 if selection_info:
70 result += f"\n{indent}{selection_info}"
71
72 if supports_interface(obj, Atspi.Accessible.get_text_iface):
73 result += f"\n{indent}TEXT: {get_text(obj)}"
74 text_attrs = get_text_attributes(obj, indent)
75 if text_attrs:
76 result += f"\n{indent}{text_attrs}"
77
78 table_info = get_table_info(obj, indent)
79 if table_info:
80 result += f"\n{indent}{table_info}"
81
82 table_cell_info = get_table_cell_info(obj, indent)
83 if table_cell_info:
84 result += f"\n{indent}{table_cell_info}"
85
86 return result
87
88
89 def supports_interface(obj: Atspi.Accessible, getter) -> bool:
90 "Check if an accessible object supports a specific interface."
91
92 try:
93 iface = getter(obj)
94 except GLib.GError:
95 return False
96 return iface is not None
97
98
99 INTERFACE_CHECKS = [
100 (Atspi.Accessible.get_action_iface, "Action"),
101 (Atspi.Accessible.get_collection_iface, "Collection"),
102 (Atspi.Accessible.get_component_iface, "Component"),
103 (Atspi.Accessible.get_document_iface, "Document"),
104 (Atspi.Accessible.get_editable_text_iface, "EditableText"),
105 (Atspi.Accessible.get_hyperlink, "Hyperlink"),
106 (Atspi.Accessible.get_hypertext_iface, "Hypertext"),
107 (Atspi.Accessible.get_image_iface, "Image"),
108 (Atspi.Accessible.get_selection_iface, "Selection"),
109 (Atspi.Accessible.get_table_iface, "Table"),
110 (Atspi.Accessible.get_table_cell, "TableCell"),
111 (Atspi.Accessible.get_text_iface, "Text"),
112 (Atspi.Accessible.get_value_iface, "Value"),
113 ]
114
115
116 def get_interfaces_as_string(obj: Atspi.Accessible) -> str:
117 "Get the supported interfaces of an accessible object as a string."
118
119 ifaces = [name for getter, name in INTERFACE_CHECKS if supports_interface(obj, getter)]
120 return ", ".join(ifaces) or "(none)"
121
122
123 def get_selection_info(obj: Atspi.Accessible, indent: str) -> str:
124 "Get selection interface details if the selection interface is supported."
125
126 if not supports_interface(obj, Atspi.Accessible.get_selection_iface):
127 return ""
128
129 try:
130 count = Atspi.Selection.get_n_selected_children(obj)
131 except GLib.GError as error:
132 return f"SELECTION: Exception in get_n_selected_children: {error}"
133
134 result = f"SELECTION: SELECTED CHILD COUNT: {count}"
135
136 def format_selected_child(index: int) -> str:
137 try:
138 child = Atspi.Selection.get_selected_child(obj, index)
139 except GLib.GError as error:
140 return f"SELECTED CHILD [{index}]: Exception: {error}"
141 if child is None:
142 return f"SELECTED CHILD [{index}]: (null)"
143 return f"SELECTED CHILD [{index}]: {get_role_as_string(child)} NAME: '{get_name(child)}'"
144
145 if count <= 10:
146 indices = range(count)
147 else:
148 indices = list(range(5)) + list(range(count - 5, count))
149
150 for i in indices:
151 if i == count - 5 and count > 10:
152 result += f"\n{indent} ... ({count - 10} selected children omitted) ..."
153 result += f"\n{indent} {format_selected_child(i)}"
154
155 return result
156
157
158 def get_table_info(obj: Atspi.Accessible, _indent: str) -> str:
159 "Get table interface details if the table interface is supported."
160
161 if not supports_interface(obj, Atspi.Accessible.get_table_iface):
162 return ""
163
164 try:
165 n_rows = Atspi.Table.get_n_rows(obj)
166 except GLib.GError as error:
167 return f"TABLE: Exception in get_n_rows: {error}"
168
169 try:
170 n_cols = Atspi.Table.get_n_columns(obj)
171 except GLib.GError as error:
172 return f"TABLE: ROWS: {n_rows}, Exception in get_n_columns: {error}"
173
174 return f"TABLE: ROWS: {n_rows}, COLUMNS: {n_cols}"
175
176
177 def get_table_cell_info(obj: Atspi.Accessible, _indent: str) -> str:
178 "Get table cell interface details if the table cell interface is supported."
179
180 if not supports_interface(obj, Atspi.Accessible.get_table_cell):
181 return ""
182
183 try:
184 success, row, column = Atspi.TableCell.get_position(obj)
185 except GLib.GError as error:
186 return f"TABLE CELL: Exception in get_position: {error}"
187
188 if not success:
189 return "TABLE CELL: ROW: (unknown), COLUMN: (unknown)"
190
191 result = f"TABLE CELL: ROW: {row}, COLUMN: {column}"
192
193 try:
194 row_span = Atspi.TableCell.get_row_span(obj)
195 col_span = Atspi.TableCell.get_column_span(obj)
196 except GLib.GError as error:
197 return f"{result}, Exception in get_span: {error}"
198
199 if row_span != 1 or col_span != 1:
200 result += f", ROW SPAN: {row_span}, COLUMN SPAN: {col_span}"
201
202 return result
203
204
205 def get_rect_as_string(obj: Atspi.Accessible) -> str:
206 "Get the rectangle dimensions of an accessible object as a string."
207
208 try:
209 if Atspi.Accessible.get_role(obj) == Atspi.Role.APPLICATION:
210 return ""
211 except GLib.GError as error:
212 print(f"Exception in get_role: {error}")
213 return ""
214
215 try:
216 rect = Atspi.Component.get_extents(obj, Atspi.CoordType.WINDOW)
217 except GLib.GError as error:
218 print(f"Exception in get_extents: {error}")
219 return ""
220 return f"X:{rect.x}, Y:{rect.y}, WIDTH:{rect.width}, HEIGHT:{rect.height}"
221
222
223 def get_relations_as_string(obj: Atspi.Accessible) -> str:
224 "Get the relations of an accessible object as a string."
225
226 try:
227 relations = Atspi.Accessible.get_relation_set(obj)
228 except GLib.GError as error:
229 print(f"Exception in get_relation_set: {error}")
230 return ""
231
232 result = []
233 for relation in relations:
234 if relation.get_n_targets() == 0:
235 continue
236 targets = [relation.get_target(i) for i in range(relation.get_n_targets())]
237 target_addresses = ", ".join(
238 [f"{get_role_as_string(target)} NAME: '{get_name(target)}'" for target in targets]
239 )
240 result.append(f"{relation.get_relation_type().value_nick}: {target_addresses}")
241
242 return " ".join(result)
243
244
245 def get_states_as_string(obj: Atspi.Accessible) -> str:
246 "Get the states of an accessible object as a string."
247
248 try:
249 state_set = Atspi.Accessible.get_state_set(obj)
250 except GLib.GError as error:
251 print(f"Exception in get_state_set: {error}")
252 return ""
253 return " ".join([s.value_nick for s in state_set.get_states()]) or "(none)"
254
255
256 def get_name(obj: Atspi.Accessible, fallback_on_labelled_by: bool = True) -> str:
257 "Get the name of an accessible object."
258
259 try:
260 name = Atspi.Accessible.get_name(obj)
261 except GLib.GError as error:
262 print(f"Exception in get_name: {error}")
263 return ""
264
265 if name:
266 return name
267
268 result = "(none)"
269 if not fallback_on_labelled_by:
270 return result
271
272 try:
273 relations = Atspi.Accessible.get_relation_set(obj)
274 except GLib.GError as error:
275 print(f"Exception in get_relation_set: {error}")
276 return ""
277
278 for relation in relations:
279 if relation.get_relation_type() != Atspi.RelationType.LABELLED_BY:
280 continue
281 targets = [relation.get_target(i) for i in range(relation.get_n_targets())]
282 result = " ".join([get_name(target, False) for target in targets])
283 if result:
284 result += " (from labelled-by relation)"
285
286 return result
287
288
289 def get_description(obj: Atspi.Accessible, fallback_on_described_by: bool = True) -> str:
290 "Get the description of an accessible object."
291
292 try:
293 description = Atspi.Accessible.get_description(obj)
294 except GLib.GError as error:
295 print(f"Exception in get_description: {error}")
296 return ""
297 if description:
298 return description
299
300 result = "(none)"
301 if not fallback_on_described_by:
302 return result
303
304 try:
305 relations = Atspi.Accessible.get_relation_set(obj)
306 except GLib.GError as error:
307 print(f"Exception in get_relation_set: {error}")
308 return ""
309
310 for relation in relations:
311 if relation.get_relation_type() != Atspi.RelationType.DESCRIBED_BY:
312 continue
313 targets = [relation.get_target(i) for i in range(relation.get_n_targets())]
314 result = " ".join([get_name(target, False) for target in targets])
315 if result:
316 result += " (from described-by relation)"
317
318 return result
319
320
321 def get_accessible_id(obj: Atspi.Accessible) -> str:
322 """Get the accessible id of obj"""
323
324 try:
325 result = Atspi.Accessible.get_accessible_id(obj)
326 except GLib.GError as error:
327 print(f"Exception in get_accessible_id: {error}")
328 return ""
329
330 return result
331
332
333 def get_attributes_as_string(obj: Atspi.Accessible) -> str:
334 "Get the attributes of an accessible object as a string."
335
336 try:
337 attributes = Atspi.Accessible.get_attributes(obj)
338 except GLib.GError as error:
339 print(f"Exception in get_attributes: {error}")
340 return ""
341
342 if not attributes:
343 return "(none)"
344
345 result = []
346 for key, value in attributes.items():
347 result.append(f"{key}={value if value is not None else '(null)'}")
348
349 return ", ".join(result)
350
351
352 def get_role_as_string(obj: Atspi.Accessible) -> str:
353 "Get the role of an accessible object."
354
355 try:
356 return Atspi.Accessible.get_role(obj).value_name
357 except GLib.GError as error:
358 print(f"Exception in get_role: {error}")
359 return "(unknown role)"
360
361
362 def get_locale(obj: Atspi.Accessible) -> str:
363 """Returns the locale of obj"""
364
365 try:
366 locale = Atspi.Accessible.get_object_locale(obj)
367 except GLib.GError as error:
368 print(f"Exception in get_object_locale: {error}")
369 return ""
370
371 return locale
372
373
374 def get_text(obj: Atspi.Accessible) -> str:
375 "Get the text of an accessible object."
376
377 length = Atspi.Text.get_character_count(obj)
378 result = Atspi.Text.get_text(obj, 0, length)
379 result = result.replace("\ufffc", "[OBJ]")
380 result = result.replace("\n", "\\n")
381 if len(result) > 80:
382 result = result[:80] + "[...]"
383 return f"'{result}'"
384
385
386 def get_text_attributes(obj: Atspi.Accessible, indent: str) -> str:
387 "Get the text attribute runs for an accessible object."
388
389 try:
390 length = Atspi.Text.get_character_count(obj)
391 except GLib.GError:
392 return ""
393
394 if length <= 0:
395 return ""
396
397 runs = []
398 offset = 0
399 while offset < length:
400 try:
401 attrs, start, end = Atspi.Text.get_attribute_run(obj, offset, True)
402 except GLib.GError as error:
403 runs.append(f"Exception at offset {offset}: {error}")
404 break
405
406 if end <= offset:
407 break
408
409 if attrs:
410 formatted = ", ".join(f"{k}={v}" for k, v in attrs.items())
411 runs.append(f"[{start}-{end}] {formatted}")
412
413 offset = end
414
415 if not runs:
416 return ""
417
418 result = f"TEXT ATTRIBUTES: {len(runs)} run(s)"
419 for run in runs:
420 result += f"\n{indent} {run}"
421 return result
422
423
424 def get_parent(obj: Atspi.Accessible) -> Atspi.Accessible:
425 "Get the parent of an accessible object."
426
427 try:
428 if Atspi.Accessible.get_role(obj) == Atspi.Role.APPLICATION:
429 return None
430 except GLib.GError as error:
431 print(f"Exception in get_role: {error}")
432 return None
433
434 try:
435 return Atspi.Accessible.get_parent(obj)
436 except GLib.GError as error:
437 print(f"Exception in get_parent: {error}")
438 return None
439
440
441 def get_parent_info(obj: Atspi.Accessible, expected_parent: Atspi.Accessible | None) -> str:
442 "Get parent info, only if the parent is unexpected or missing."
443
444 parent = get_parent(obj)
445 if parent is None and expected_parent is None:
446 return ""
447
448 if parent is None:
449 return "**NO PARENT** (expected one)"
450
451 if expected_parent is None:
452 return f"PARENT: {get_role_as_string(parent)} (unexpected; object has no expected parent)"
453
454 if parent == expected_parent:
455 return ""
456
457 return f"**UNEXPECTED PARENT**: {get_role_as_string(parent)} NAME: '{get_name(parent)}'"
458
459
460 def get_children(obj: Atspi.Accessible) -> list[Atspi.Accessible]:
461 "Get the children of an accessible object."
462
463 children = []
464 try:
465 count = Atspi.Accessible.get_child_count(obj)
466 except GLib.GError as error:
467 print(f"Exception in get_child_count: {error}")
468 return []
469
470 for i in range(count):
471 try:
472 children.append(Atspi.Accessible.get_child_at_index(obj, i))
473 except GLib.GError as error:
474 print(f"Exception in get_child_at_index: {error}")
475 return children
476
477 return children
478
479
480 def clear_cache_single(obj: Atspi.Accessible) -> None:
481 "Clear the cache for a single accessible object."
482
483 try:
484 Atspi.Accessible.clear_cache_single(obj)
485 except GLib.GError as error:
486 print(f"Exception in clear_cache_single: {error}")
487
488
489 def print_tree(
490 root: Atspi.Accessible,
491 indent: int = 0,
492 expected_parent: Atspi.Accessible | None = None,
493 ) -> None:
494 "Print the tree structure of accessible objects."
495
496 clear_cache_single(root)
497 prefix = f"{' ' * indent}-->"
498 print(f"{as_string(root, prefix, expected_parent)}")
499 for child in get_children(root):
500 print_tree(child, indent + 1, root)
501
502
503 def get_desktop_apps() -> list[Atspi.Accessible]:
504 "Get all accessible applications from the desktop."
505
506 try:
507 desktop = Atspi.get_desktop(0)
508 except GLib.GError as error:
509 print(f"Exception getting desktop from Atspi: {error}")
510 return []
511
512 return get_children(desktop)
513
514
515 def print_available_apps(apps: list[Atspi.Accessible]) -> None:
516 "Print the list of available accessible applications."
517
518 print(f"Desktop has {len(apps)} accessible application(s):")
519 for i, app in enumerate(apps):
520 print(f" {i + 1}. {get_name(app, False)}")
521
522
523 def find_application_with_name(app_name: str) -> Atspi.Accessible:
524 "Find the accessible application with the specified name."
525
526 apps = get_desktop_apps()
527 for app in apps:
528 if get_name(app, False) == app_name:
529 return app
530
531 print(f"Application '{app_name}' not found.")
532 print_available_apps(apps)
533 return None
534
535
536 def main():
537 """Starts the tree dumper and waits for events."""
538
539 if len(sys.argv) != 2:
540 print("Usage: dump-tree.py <APP_NAME>")
541 print()
542 print_available_apps(get_desktop_apps())
543 sys.exit(1)
544
545 app = find_application_with_name(sys.argv[1])
546 if not app:
547 sys.exit(1)
548
549 print_tree(app)
550 print("Tree dump complete.")
551
552
553 if __name__ == "__main__":
554 main()