Files
eepp/projects/scripts/benchmark_accessibility_dormant.py
T
Martín Lucas Golini 67660d4c13 Add accessible text, relations and live regions; keep dormant a11y free
Text:
- Ranged text access in code points (length, range, line bounds) that
  never copies more than requested, plus a text revision (document UUID
  and modification) so UIA and macOS cache their UTF-16 copies.
- Report document edits as exact change records, up to four per widget
  and frame, then collapse to one whole-text change. Resets, loads and
  document swaps report a whole-text change.
- The removed text is available only while an edit is being notified
  (TextDocument::getNotifiedRemovedText()); DocumentContentChange stays
  { range, text }, so queued records (LSP) copy nothing extra.
- Suppressed text changes are keyed by node ref, so a document shared
  with another window still reports its edits.
- UITextView reports NameChanged; UITextInput overrides onTextChanged()
  to report ValueChanged.

Relations, live regions and shortcuts:
- aria-labelledby, aria-describedby and aria-live (API and CSS). Ids a
  client has read are remembered; renaming, adding or removing their
  widgets notifies the dependents. setId() copies the old id only when
  it is remembered.
- Live regions and UISceneNode::announceForAccessibility(). A newer
  change from the same widget replaces its pending announcement, and
  hidden sources are dropped.
- Menu item shortcuts (std::string text and key) exposed as AT-SPI key
  bindings, the UIA accelerator key and macOS command characters.
- ScrollTo for anything inside a scroll view
  (UIScrollView::scrollIntoView()). Icon-only buttons are named from
  their tooltip.

Dormant path (no client attached):
- Widget notifications are inline: one relaxed atomic load of a
  process-wide count of active root scenes, no call.
- Scene destruction and scene or host changes never create a manager.
  Without a client, notify() queues nothing and widget deletion does
  not register parents to announce it. While only the root has an
  identity, deletion skips the ancestor walk unless a remembered
  relation target may be affected.
- When the last client disconnects, model-view sources release their
  queried rows. Persistent handles count their registrations, so
  handles held elsewhere survive (PersistentModelIndex::release()).
- Spin boxes no longer hide their input explicitly, and
  AccessibilityProperties shrinks from 144 to 136 bytes.

Backends:
- AT-SPI: object:announcement, word and line granularity, ranged
  reads, SetTextContents reported as its minimal diff. Watch
  disconnects per client (NameOwnerChanged arg0 plus a non-blocking
  NameHasOwner check) instead of for every bus name. Without a scene
  thread pool, initialize on a detached thread that shares ownership,
  so teardown never waits on D-Bus timeouts.
- UIA: notification events (resolved at runtime, Windows 10 1709+),
  text ranges served from the revision cache, and a per-frame provider
  drain that skips the lock when nothing is queued.
- macOS: announcements, a UTF-16 text cache per revision, and command
  key attributes.
- EEPP_ACCESSIBILITY_TRACE=1 logs client activity transitions.

Fixes:
- UICodeEditor::isType() no longer dispatches to a subclass's
  getType(), so a UITextEdit is a code editor again.
- ecode: dropped files open only in document editors, not in other
  code editors such as a commit message box.

Tools, tests and docs:
- Widget inspector: role names, shortcut, relation and live rows, and
  an accessibility audit (unnamed controls, broken relations).
- Accessibility example: live status, an icon-only button, and edit and
  reset actions that test_atspi.py checks end to end.
- Regression tests for text records, relations, live regions,
  disconnect and reconnect, scene lifecycle and id changes.
- Add the AccessibilityDormant benchmark (C++ new/new[] counted on the
  measuring thread) and benchmark_accessibility_dormant.py, which fails
  on missing measurements and compares against other builds with
  --compare LABEL=PATH.
- Document the dormant-path rules, what survives a disconnection, and
  the remaining platform limitations.
2026-10-10 02:01:52 -03:00

165 lines
6.3 KiB
Python

#!/usr/bin/env python3
"""Dormant-path accessibility benchmark: allocations, bytes and time with no client attached.
Runs the AccessibilityDormant benchmarks from eepp-benchmarks (a Release build) several times and
reports the median of each measurement. Each --compare LABEL=PATH runs the same benchmark source
built against another tree as well (for example an exported develop or merge-base revision,
compiled with -DEE_BENCH_NO_ACCESSIBILITY), and prints the current build's differences from it.
Allocation counts and bytes cover ordinary C++ new/new[] on the measuring thread only (not malloc,
other threads or background work) and are deterministic; times are indicative only. A run passes
only when every sample exits cleanly and reports every expected measurement, guarded scenarios
included. A compared build whose run fails still reports its measurements.
"""
import argparse
import json
import re
import statistics
import subprocess
import sys
LINE = re.compile(r"^ACCESSIBILITY_DORMANT (\S+) ?(.*)$")
FIELD = re.compile(r"(\w+)=([-\d.]+)")
# Every build must report these; a run missing any of them did not measure what it claims.
COMMON = {
"typing": ("allocations", "bytes", "ms"),
"deleting_characters": ("allocations", "bytes", "ms"),
"large_deletion": ("allocations", "bytes", "ms"),
"large_deletion_removed_text_bytes": ("value", "allocated_bytes_per_removed_byte"),
"spinbox_construction": ("allocations", "bytes", "ms"),
"spinbox_destruction": ("allocations", "bytes", "ms"),
"deep_hierarchy_lifecycle": ("allocations", "bytes", "ms"),
"nested_scene_lifecycle": ("allocations", "bytes", "ms"),
"list_scroll_updates": ("allocations", "bytes", "ms"),
"list_model_mutations": ("allocations", "bytes", "ms"),
"widget_notifications": ("allocations", "bytes", "ms"),
}
# Only builds with accessibility support (not EE_BENCH_NO_ACCESSIBILITY) report these, including
# the guarded after-disconnect and unreferenced id scenarios.
ACCESSIBILITY = {
"first_update_without_thread_pool": ("allocations", "bytes", "ms"),
"later_update_without_thread_pool": ("allocations", "bytes", "ms"),
"readiness_ms": ("value", "backend_available"),
"model_mutations_never_queried": ("allocations", "bytes", "ms"),
"model_mutations_after_disconnect": ("allocations", "bytes", "ms"),
"set_id_no_client": ("allocations", "bytes", "ms"),
"set_id_active_unreferenced": ("allocations", "bytes", "ms"),
"set_id_active_referenced": ("allocations", "bytes", "ms"),
}
def parse(stdout):
sample = {}
for line in stdout.splitlines():
match = LINE.match(line)
if not match:
continue
name, rest = match.groups()
fields = {}
# Single-value lines ("name=value ...") carry the measurement in the name itself.
if "=" in name:
name, value = name.split("=", 1)
fields["value"] = float(value)
for key, value in FIELD.findall(rest):
fields[key] = float(value)
sample[name] = fields
return sample
def missing(sample, expected):
return sorted(
f"{name}.{key}" if name in sample else name
for name, keys in expected.items()
for key in (keys if name in sample else keys[:1])
if name not in sample or key not in sample[name]
)
def run(executable, samples, timeout, expected):
"""Returns the median of every measurement and the reasons the run did not pass, if any."""
results = {}
failures = []
for index in range(samples):
completed = subprocess.run(
[executable, "--filter=AccessibilityDormant.*"],
capture_output=True,
text=True,
timeout=timeout,
)
if completed.returncode != 0:
failures.append(f"sample {index + 1}: exit code {completed.returncode}")
sample = parse(completed.stdout)
absent = missing(sample, expected)
if absent:
failures.append(f"sample {index + 1}: missing {', '.join(absent)}")
for name, fields in sample.items():
for key, value in fields.items():
results.setdefault(name, {}).setdefault(key, []).append(value)
medians = {
name: {key: statistics.median(values) for key, values in fields.items()}
for name, fields in results.items()
}
return medians, failures
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--executable", default="bin/benchmarks/eepp-benchmarks")
parser.add_argument("--compare", action="append", default=[], metavar="LABEL=PATH",
help="the same benchmark built against another tree")
parser.add_argument("--samples", type=int, default=3)
parser.add_argument("--timeout", type=float, default=300)
parser.add_argument("--json", action="store_true")
args = parser.parse_args()
if args.samples < 1:
parser.error("--samples must be at least 1")
builds = [("current", args.executable)]
for entry in args.compare:
label, _, path = entry.partition("=")
if not label or not path:
parser.error(f"--compare expects LABEL=PATH, got {entry!r}")
if any(label == existing for existing, _ in builds):
# Results are keyed by label: a repeated one would replace another build's results.
reason = "is reserved for --executable" if label == "current" else "is already used"
parser.error(f"--compare label {label!r} {reason}")
builds.append((label, path))
output = {}
failures = {}
for label, path in builds:
# The current build must measure everything; a compared tree may lack accessibility.
expected = {**COMMON, **ACCESSIBILITY} if label == "current" else COMMON
output[label], failures[label] = run(path, args.samples, args.timeout, expected)
passed = {label: not failures[label] for label in failures}
if args.json:
print(json.dumps({"results": output, "guards_passed": passed, "failures": failures},
indent=1, sort_keys=True))
sys.exit(0 if passed["current"] else 1)
current = output["current"]
labels = [label for label, _ in builds]
for key in ("allocations", "bytes", "ms"):
print(f"\n{key} (median of {args.samples})")
print(f"{'measurement':42}" + "".join(f" {label:>16}" for label in labels))
for name in sorted(current):
if key not in current[name]:
continue
row = f"{name:42}"
for label in labels:
value = output[label].get(name, {}).get(key)
if value is None:
row += f" {'-':>16}"
else:
row += f" {value:>16.3f}" if key == "ms" else f" {value:>16.0f}"
print(row)
for label in labels:
for failure in failures[label]:
print(f"\n{label}: {failure} (measurements above are still reported)")
sys.exit(0 if passed["current"] else 1)
if __name__ == "__main__":
main()