Skip to main content

computer_use_linux/
atspi_tree.rs

1use crate::diagnostics::hydrate_session_bus_env;
2use anyhow::{anyhow, Context, Result};
3use atspi::{
4    proxy::{
5        accessible::{AccessibleProxy, ObjectRefExt},
6        action::ActionProxy,
7        editable_text::EditableTextProxy,
8        proxy_ext::{Proxies, ProxyExt},
9        text::TextProxy,
10    },
11    CoordType, ObjectRef, ObjectRefOwned, StateSet,
12};
13// Direct dependency (p2p feature off) — see Cargo.toml for why we bypass
14// atspi's "connection" re-export.
15use atspi_connection::AccessibilityConnection;
16use futures_util::{stream, StreamExt};
17use schemars::JsonSchema;
18use serde::Serialize;
19use std::{collections::VecDeque, future::Future, time::Duration};
20use tokio::time::{sleep_until, timeout, timeout_at, Instant};
21use zbus::{
22    fdo::DBusProxy,
23    names::{BusName, UniqueName},
24    zvariant::{ObjectPath, OwnedObjectPath},
25};
26
27#[derive(Debug, Clone, Serialize, JsonSchema)]
28pub struct AccessibleAppSummary {
29    pub object_ref: String,
30    pub name: Option<String>,
31    pub pid: Option<u32>,
32    pub role: String,
33    pub child_count: i32,
34    pub bounds: Option<Bounds>,
35}
36
37#[derive(Debug, Clone, Serialize, JsonSchema)]
38pub struct AccessibilityNode {
39    pub index: u32,
40    pub parent_index: Option<u32>,
41    pub depth: u32,
42    pub object_ref: String,
43    pub role: String,
44    pub name: Option<String>,
45    pub description: Option<String>,
46    pub child_count: i32,
47    pub bounds: Option<Bounds>,
48    pub states: Vec<String>,
49    pub actions: Vec<AccessibilityAction>,
50    pub value: Option<AccessibilityValue>,
51    pub text: Option<AccessibilityText>,
52    pub supports_editable_text: bool,
53}
54
55#[derive(Debug, Clone, Serialize, JsonSchema)]
56pub struct Bounds {
57    pub x: i32,
58    pub y: i32,
59    pub width: i32,
60    pub height: i32,
61}
62
63#[derive(Debug, Clone, Serialize, JsonSchema)]
64pub struct AccessibilityAction {
65    pub index: i32,
66    pub name: String,
67    pub description: String,
68    pub keybinding: String,
69}
70
71#[derive(Debug, Clone, Serialize, JsonSchema)]
72pub struct AccessibilityValue {
73    pub current: f64,
74    pub minimum: f64,
75    pub maximum: f64,
76    pub minimum_increment: f64,
77    pub text: Option<String>,
78}
79
80#[derive(Debug, Clone, Serialize, JsonSchema)]
81pub struct AccessibilityText {
82    pub character_count: i32,
83    pub caret_offset: Option<i32>,
84    pub content: Option<String>,
85    pub truncated: bool,
86    pub selections: Vec<AccessibilityTextSelection>,
87}
88
89#[derive(Debug, Clone, Serialize, JsonSchema)]
90pub struct AccessibilityTextSelection {
91    pub start_offset: i32,
92    pub end_offset: i32,
93}
94
95#[derive(Debug, Clone)]
96pub struct ActionInvocation {
97    pub action_index: i32,
98    pub action_name: Option<String>,
99    pub ok: bool,
100}
101
102#[derive(Debug, Clone)]
103pub enum ValueSetInvocation {
104    Numeric { value: f64 },
105    EditableText { outcome: EditableTextSetOutcome },
106}
107
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109pub enum EditableTextSetOutcome {
110    Verified,
111    MismatchAfterDeadline,
112    ReadbackFailed,
113    ReadbackTimedOut,
114    PasswordUnverifiable,
115}
116
117const MAX_TEXT_READBACK_CHARS: i32 = 4096;
118const EDITABLE_TEXT_READ_CHUNK_UNITS: usize = 4096;
119const EDITABLE_TEXT_VERIFY_TIMEOUT: Duration = Duration::from_secs(1);
120const EDITABLE_TEXT_VERIFY_INTERVAL: Duration = Duration::from_millis(50);
121const MAX_TEXT_SELECTIONS: i32 = 8;
122const DEFAULT_SNAPSHOT_MAX_NODES: usize = 1_000;
123// Larger trees are opt-in; the default and the 10-second deadline stay unchanged.
124const HARD_SNAPSHOT_MAX_NODES: usize = 10_000;
125const DEFAULT_SNAPSHOT_MAX_DEPTH: u32 = 32;
126const HARD_SNAPSHOT_MAX_DEPTH: u32 = 64;
127const CHILD_READ_CONCURRENCY: usize = 16;
128const SNAPSHOT_TIMEOUT: Duration = Duration::from_secs(10);
129/// Time past `SNAPSHOT_TIMEOUT` for the node being read to finish; a node still
130/// reading after it is dropped and the tree is returned truncated.
131const SNAPSHOT_HARD_GRACE: Duration = Duration::from_secs(2);
132const MAX_ACTIONS_PER_OBJECT: i32 = 64;
133const ACTION_QUERY_TIMEOUT: Duration = Duration::from_secs(5);
134const MAX_DISCOVERY_ROOTS: usize = 256;
135const ROOT_MATCH_CHILD_LIMIT: usize = 8;
136const MAX_DISCOVERY_CHILD_READS: usize = MAX_DISCOVERY_ROOTS * ROOT_MATCH_CHILD_LIMIT;
137
138fn snapshot_child_read_budgets(max_nodes: usize) -> (usize, usize, usize) {
139    (MAX_DISCOVERY_ROOTS, MAX_DISCOVERY_CHILD_READS, max_nodes)
140}
141
142pub(crate) fn snapshot_limits(
143    requested_max_nodes: Option<usize>,
144    requested_max_depth: Option<u32>,
145) -> (usize, u32) {
146    (
147        requested_max_nodes
148            .unwrap_or(DEFAULT_SNAPSHOT_MAX_NODES)
149            .clamp(1, HARD_SNAPSHOT_MAX_NODES),
150        requested_max_depth
151            .unwrap_or(DEFAULT_SNAPSHOT_MAX_DEPTH)
152            .min(HARD_SNAPSHOT_MAX_DEPTH),
153    )
154}
155
156struct BoundedTraversal<T> {
157    queue: VecDeque<T>,
158    attempted: usize,
159    max_items: usize,
160    /// Set once an enqueue had to drop offered items for lack of capacity.
161    dropped: bool,
162}
163
164impl<T> BoundedTraversal<T> {
165    fn new(max_items: usize) -> Self {
166        Self {
167            queue: VecDeque::new(),
168            attempted: 0,
169            max_items,
170            dropped: false,
171        }
172    }
173
174    fn enqueue(&mut self, items: impl IntoIterator<Item = T>) {
175        let capacity = self.remaining_capacity();
176        let mut items = items.into_iter();
177        self.queue.extend(items.by_ref().take(capacity));
178        if items.next().is_some() {
179            self.dropped = true;
180        }
181    }
182
183    fn pop(&mut self) -> Option<T> {
184        if self.attempted >= self.max_items {
185            return None;
186        }
187        let item = self.queue.pop_front()?;
188        self.attempted += 1;
189        Some(item)
190    }
191
192    fn remaining_capacity(&self) -> usize {
193        self.max_items
194            .saturating_sub(self.attempted.saturating_add(self.queue.len()))
195    }
196
197    /// Drop pending and earlier dropped work, keeping the spent budget, so the
198    /// rest of the budget goes to the subtree enqueued next.
199    fn narrow(&mut self) {
200        self.queue.clear();
201        self.dropped = false;
202    }
203
204    /// True when the budget stopped work that was actually offered. `enqueue`
205    /// is the only gate: it never exceeds `remaining_capacity`, so
206    /// `attempted + queue.len() <= max_items` always holds and the queue can
207    /// never be non-empty at the attempt cap. Dropped items are the whole story.
208    fn truncated(&self) -> bool {
209        self.dropped
210    }
211}
212
213fn bounded_child_count(reported: i32, limit: usize) -> usize {
214    usize::try_from(reported).unwrap_or_default().min(limit)
215}
216
217struct IndexedReadBatch<T> {
218    items: Vec<T>,
219    attempted: usize,
220    /// True when fewer children were attempted than the parent reported, because
221    /// the caller's limit or the shared read budget ran out. Failed reads do not
222    /// count; they were attempted.
223    incomplete: bool,
224}
225
226impl<T> IndexedReadBatch<T> {
227    fn all_failed(&self) -> bool {
228        self.attempted > 0 && self.items.is_empty()
229    }
230}
231
232async fn fetch_indexed_up_to<T, E, F, Fut>(
233    reported: i32,
234    limit: usize,
235    remaining_attempts: &mut usize,
236    fetch: F,
237) -> IndexedReadBatch<T>
238where
239    F: Fn(i32) -> Fut,
240    Fut: Future<Output = std::result::Result<T, E>>,
241{
242    let attempt_count = bounded_child_count(reported, limit).min(*remaining_attempts);
243    *remaining_attempts = (*remaining_attempts).saturating_sub(attempt_count);
244    let end_index = i32::try_from(attempt_count).unwrap_or(i32::MAX);
245
246    let items = stream::iter(0..end_index)
247        .map(fetch)
248        .buffered(CHILD_READ_CONCURRENCY)
249        .filter_map(|result| async move { result.ok() })
250        .collect()
251        .await;
252
253    IndexedReadBatch {
254        items,
255        attempted: attempt_count,
256        incomplete: attempt_count < usize::try_from(reported).unwrap_or_default(),
257    }
258}
259
260async fn children_up_to(
261    proxy: &AccessibleProxy<'_>,
262    limit: usize,
263    remaining_attempts: &mut usize,
264) -> zbus::Result<IndexedReadBatch<ObjectRefOwned>> {
265    if limit == 0 || *remaining_attempts == 0 {
266        // Budget already spent: stay I/O-free. `incomplete` is false here because
267        // nothing was asked of the parent; callers that already hold the node's
268        // child_count (snapshot_tree_inner) derive truncation from that instead.
269        return Ok(IndexedReadBatch {
270            items: Vec::new(),
271            attempted: 0,
272            incomplete: false,
273        });
274    }
275
276    let child_count = proxy.child_count().await?;
277    Ok(
278        fetch_indexed_up_to(child_count, limit, remaining_attempts, |index| {
279            child_at_index(proxy, index)
280        })
281        .await,
282    )
283}
284
285async fn child_at_index(proxy: &AccessibleProxy<'_>, index: i32) -> zbus::Result<ObjectRefOwned> {
286    // WebKit sockets return a well-known bus name. atspi's ObjectRef decoder
287    // only accepts unique names, so resolve the wire reference before using it.
288    let (name, path): (String, OwnedObjectPath) =
289        proxy.inner().call("GetChildAtIndex", &(index,)).await?;
290    if path.as_str() == "/org/a11y/atspi/null" {
291        return Ok(ObjectRef::Null.into());
292    }
293    match BusName::try_from(name)? {
294        BusName::Unique(name) => Ok(ObjectRef::new_owned(name, path)),
295        name => {
296            let owner = DBusProxy::new(proxy.inner().connection())
297                .await?
298                .get_name_owner(name)
299                .await?;
300            Ok(ObjectRef::new_owned(owner, path))
301        }
302    }
303}
304
305pub async fn list_accessible_apps(limit: usize) -> Result<Vec<AccessibleAppSummary>> {
306    let conn = connect().await?;
307    let mut remaining_child_reads = limit;
308    let roots = registry_children(&conn, limit, &mut remaining_child_reads).await?;
309    let dbus = DBusProxy::new(conn.connection()).await.ok();
310    let mut apps = Vec::new();
311
312    for object_ref in roots.into_iter().take(limit) {
313        if let Ok(proxy) = open_accessible(&conn, &object_ref).await {
314            apps.push(read_app_summary(&proxy, &object_ref, dbus.as_ref()).await);
315        }
316    }
317
318    Ok(apps)
319}
320
321#[derive(Debug, Clone)]
322pub(crate) struct AccessibilitySnapshot {
323    pub nodes: Vec<AccessibilityNode>,
324    /// True when registry roots were filtered to an app name and/or pid.
325    pub scoped: bool,
326    /// The pid every root belongs to, when roots were matched by pid. None
327    /// when they were matched by app name alone or not filtered at all: those
328    /// roots can belong to any app, so no single pid describes the tree.
329    pub root_pid: Option<u32>,
330    /// True when selected roots satisfy the supplied app/name filter, or no
331    /// filter was supplied. Normal snapshots retain their PID-only fallback;
332    /// action recovery requires this evidence before invoking a fresh node.
333    pub app_filter_matched: bool,
334    /// True when max_nodes, max_depth, the child read budget, or the deadline stopped
335    /// traversal with unread elements left. Failed element reads do not count.
336    pub truncated: bool,
337    /// Name of the AT-SPI window the tree was narrowed to, when an app root
338    /// exposed several windows and exactly one matched the window title.
339    pub window_scope: Option<String>,
340}
341
342pub async fn snapshot_tree(
343    app_name_or_bundle_identifier: Option<&str>,
344    target_pid: Option<u32>,
345    max_nodes: usize,
346    max_depth: u32,
347) -> Result<Vec<AccessibilityNode>> {
348    Ok(snapshot_accessibility_tree(
349        app_name_or_bundle_identifier,
350        target_pid,
351        None,
352        max_nodes,
353        max_depth,
354    )
355    .await?
356    .nodes)
357}
358
359/// Read the accessibility tree of the matching app roots. With
360/// `window_title`, an app root that exposes several windows (Chromium puts
361/// every browser window under one application) is read only through the
362/// window whose name matches it; its other children stay.
363pub(crate) async fn snapshot_accessibility_tree(
364    app_name_or_bundle_identifier: Option<&str>,
365    target_pid: Option<u32>,
366    window_title: Option<&str>,
367    max_nodes: usize,
368    max_depth: u32,
369) -> Result<AccessibilitySnapshot> {
370    let (max_nodes, max_depth) = snapshot_limits(Some(max_nodes), Some(max_depth));
371    // Traversal stops at the deadline and returns what it read, marked truncated.
372    // The outer timeout only bounds app discovery, which runs before any node
373    // is read; the traversal itself ends by `stop_reading` plus the grace.
374    let stop_reading = Instant::now() + SNAPSHOT_TIMEOUT;
375    timeout(
376        SNAPSHOT_TIMEOUT + SNAPSHOT_HARD_GRACE + SNAPSHOT_HARD_GRACE,
377        snapshot_tree_inner(
378            app_name_or_bundle_identifier,
379            target_pid,
380            window_title
381                .map(str::trim)
382                .filter(|title| !title.is_empty()),
383            max_nodes,
384            max_depth,
385            stop_reading,
386        ),
387    )
388    .await
389    .context("AT-SPI snapshot could not find its target before the deadline")?
390}
391
392async fn snapshot_tree_inner(
393    app_name_or_bundle_identifier: Option<&str>,
394    target_pid: Option<u32>,
395    window_title: Option<&str>,
396    max_nodes: usize,
397    max_depth: u32,
398    stop_reading: Instant,
399) -> Result<AccessibilitySnapshot> {
400    let conn = connect().await?;
401    // App discovery is bounded independently so a tiny requested tree still
402    // finds a target registered after the first accessibility root.
403    let (mut remaining_registry_reads, mut remaining_filter_reads, mut remaining_traversal_reads) =
404        snapshot_child_read_budgets(max_nodes);
405    let roots =
406        registry_children(&conn, MAX_DISCOVERY_ROOTS, &mut remaining_registry_reads).await?;
407    let selected_roots = select_roots(
408        &conn,
409        roots,
410        app_name_or_bundle_identifier,
411        target_pid,
412        &mut remaining_filter_reads,
413    )
414    .await;
415    let scoped = selected_roots.scoped;
416    let root_pid = selected_roots.pid;
417    let app_filter_matched = selected_roots.app_filter_matched;
418    let mut nodes = Vec::new();
419    let mut truncated = false;
420    let mut window_scope = None;
421    let mut traversal = BoundedTraversal::new(max_nodes);
422
423    traversal.enqueue(
424        selected_roots
425            .roots
426            .into_iter()
427            .map(|object_ref| (object_ref, 0_u32, None)),
428    );
429
430    // Each node's reads may run past `stop_reading` by the grace, never more: a
431    // slow action query (up to ACTION_QUERY_TIMEOUT) near the deadline cuts the
432    // tree there instead of losing it to the outer timeout.
433    let node_cutoff = stop_reading + SNAPSHOT_HARD_GRACE;
434    while let Some((object_ref, depth, parent_index)) = traversal.pop() {
435        if Instant::now() >= stop_reading {
436            truncated = true;
437            break;
438        }
439        let index = nodes.len() as u32;
440        let remaining = traversal.remaining_capacity();
441        let read = timeout_at(node_cutoff, async {
442            let Ok(proxy) = open_accessible(&conn, &object_ref).await else {
443                return None;
444            };
445            let node = read_node(&proxy, &object_ref, index, parent_index, depth).await;
446            let mut cut = false;
447            let mut scope = None;
448            let child_refs = if depth < max_depth && remaining > 0 {
449                match children_up_to(&proxy, remaining, &mut remaining_traversal_reads).await {
450                    Ok(batch) => {
451                        // A read-budget cut inside the fetch reports `incomplete`; an
452                        // already-exhausted budget returns the I/O-free empty batch, so
453                        // fall back to the child_count read_node already fetched.
454                        cut = batch.incomplete || (batch.attempted == 0 && node.child_count > 0);
455                        match window_title.filter(|_| depth == 0) {
456                            Some(title) => {
457                                let (children, matched) =
458                                    scope_to_window(&conn, batch.items, title).await;
459                                scope = matched;
460                                children
461                            }
462                            None => batch.items,
463                        }
464                    }
465                    Err(_) => Vec::new(),
466                }
467            } else {
468                // Depth or node cap reached: any child this node reports is unread.
469                cut = node.child_count > 0;
470                Vec::new()
471            };
472            Some((node, child_refs, cut, scope))
473        })
474        .await;
475        let Ok(read) = read else {
476            truncated = true;
477            break;
478        };
479        let Some((node, child_refs, cut, scope)) = read else {
480            continue;
481        };
482        truncated |= cut;
483        if scope.is_some() {
484            window_scope = scope;
485        }
486        nodes.push(node);
487
488        traversal.enqueue(
489            child_refs
490                .into_iter()
491                .map(|child| (child, depth + 1, Some(index))),
492        );
493    }
494    truncated |= traversal.truncated();
495
496    Ok(AccessibilitySnapshot {
497        nodes,
498        scoped,
499        root_pid,
500        app_filter_matched,
501        truncated,
502        window_scope,
503    })
504}
505
506/// Children of an app root, narrowed to the window named `title` when the root
507/// holds several windows. Returns the children to read and the matched window
508/// name. Only the other named frames are dropped: popups, menus, dialogs and
509/// unnamed windows are kept, since Chromium puts a window's popups and dialogs
510/// beside it under the app root.
511async fn scope_to_window(
512    conn: &AccessibilityConnection,
513    children: Vec<ObjectRefOwned>,
514    title: &str,
515) -> (Vec<ObjectRefOwned>, Option<String>) {
516    // An app root has a handful of windows; read them in order.
517    let mut labels = Vec::with_capacity(children.len());
518    for child in &children {
519        labels.push(match open_accessible(conn, child).await {
520            Ok(proxy) => (
521                role_name(&proxy).await,
522                optional_string(proxy.name().await.ok()),
523            ),
524            Err(_) => (String::new(), None),
525        });
526    }
527    let Some(chosen) = matching_window(&labels, title) else {
528        return (children, None);
529    };
530    let name = labels[chosen].1.clone();
531    let keep = kept_beside_window(&labels, chosen);
532    let kept = children
533        .into_iter()
534        .zip(keep)
535        .filter_map(|(child, keep)| keep.then_some(child))
536        .collect();
537    (kept, name)
538}
539
540/// Which app root children (`(role, name)`) stay when `chosen` is the targeted
541/// window: it, and every child that is not another named frame.
542fn kept_beside_window(children: &[(String, Option<String>)], chosen: usize) -> Vec<bool> {
543    children
544        .iter()
545        .enumerate()
546        .map(|(index, (role, name))| {
547            index == chosen
548                || role != "frame"
549                || name.as_deref().is_none_or(|name| name.trim().is_empty())
550        })
551        .collect()
552}
553
554pub(crate) fn is_window_role(role: &str) -> bool {
555    matches!(role, "frame" | "window" | "dialog" | "file chooser")
556}
557
558/// Index of the one window among an app root's children (`(role, name)`)
559/// that `title` names, when the root has at least two windows. An exact name
560/// wins, then a case-insensitive one, then the one name that contains
561/// `title`, ignoring case. A tie at the first rule that matches returns
562/// `None`, which keeps every window. With no match at all, the longest name
563/// that `title` starts with, followed by a decoration (` (...)` or
564/// ` - ...`), wins: a compositor title such as Chromium's
565/// "PlanetScale - Chromium (Profile 1)" decorates the AT-SPI frame name
566/// "PlanetScale - Chromium".
567fn matching_window(children: &[(String, Option<String>)], title: &str) -> Option<usize> {
568    let windows: Vec<(usize, &str)> = children
569        .iter()
570        .enumerate()
571        .filter(|(_, (role, _))| is_window_role(role))
572        .map(|(index, (_, name))| (index, name.as_deref().unwrap_or_default().trim()))
573        .collect();
574    if windows.len() < 2 {
575        return None;
576    }
577    let title = title.trim();
578    let lowered = title.to_lowercase();
579    let rules: [&dyn Fn(&str) -> bool; 3] = [
580        &|name| name == title,
581        &|name| name.to_lowercase() == lowered,
582        &|name| name.to_lowercase().contains(&lowered),
583    ];
584    for rule in rules {
585        let mut matches = windows.iter().filter(|(_, name)| rule(name));
586        if let Some((index, _)) = matches.next() {
587            return matches.next().is_none().then_some(*index);
588        }
589    }
590    let decorated = |name: &str| {
591        let name = name.to_lowercase();
592        !name.is_empty()
593            && lowered.strip_prefix(&name).is_some_and(|rest| {
594                rest.starts_with(" (") || rest.starts_with(" - ") || rest.starts_with(" \u{2014} ")
595            })
596    };
597    let decorated_matches = windows.iter().filter(|(_, name)| decorated(name));
598    let longest = decorated_matches
599        .clone()
600        .map(|(_, name)| name.len())
601        .max()?;
602    let mut longest_matches = decorated_matches.filter(|(_, name)| name.len() == longest);
603    let (index, _) = longest_matches.next()?;
604    longest_matches.next().is_none().then_some(*index)
605}
606
607/// Compact description of the AT-SPI element that currently holds keyboard
608/// focus, used as post-input feedback for type_text/press_key.
609#[derive(Debug, Clone, Serialize, JsonSchema)]
610pub struct FocusedElementSummary {
611    pub role: String,
612    pub name: Option<String>,
613    pub editable: bool,
614    pub states: Vec<String>,
615    /// AT-SPI `Role::Terminal`, read from the role enum rather than the
616    /// localized role name. Internal routing only; not part of the output.
617    #[serde(skip)]
618    #[schemars(skip)]
619    pub is_terminal: bool,
620}
621
622impl FocusedElementSummary {
623    /// A field that takes typed text: editable, or a text-entry role.
624    pub(crate) fn accepts_text(&self) -> bool {
625        self.editable
626            || self.states.iter().any(|state| state == "editable")
627            || matches!(
628                self.role.as_str(),
629                "text" | "entry" | "password text" | "combo box"
630            )
631    }
632}
633
634const FOCUS_PROBE_MAX_NODES: usize = 400;
635const FOCUS_PROBE_MAX_DEPTH: u32 = 16;
636
637/// Find the element with the `focused` state inside the target app (by pid) or
638/// across all apps. Best-effort and bounded: returns Ok(None) when no focused
639/// element is reachable through AT-SPI (common for apps without accessibility
640/// support, e.g. Electron without --force-renderer-accessibility).
641/// Outcome of the bounded focused-element search.
642#[derive(Debug, Clone)]
643pub(crate) enum FocusProbe {
644    Found(FocusedElementSummary),
645    /// The search covered the target's whole tree and nothing holds focus.
646    NoneFocused,
647    /// A complete scoped search saw only window/menu chrome, no content.
648    ShellOnly,
649    /// A node, depth, or read limit stopped the search before it finished, so
650    /// the focused element may exist past the limit.
651    Incomplete,
652    /// A pid was given but no AT-SPI app belongs to it (xterm, or Electron
653    /// without --force-renderer-accessibility), so focus cannot be read.
654    NoAccessibleApp,
655}
656
657/// Focused element in the app owning `target_pid`, or across all apps when no
658/// pid is given. With a pid, only that app's tree is searched: falling back to
659/// every other app would report some unrelated widget as the focus.
660pub(crate) async fn probe_focused_element(target_pid: Option<u32>) -> Result<FocusProbe> {
661    focused_element_probe(target_pid, target_pid.is_some()).await
662}
663
664/// The focused element in the app that owns `target_pid`, for callers that
665/// only need an answer when one exists. Every non-`Found` probe result maps to
666/// `None`; see [`probe_focused_element`] for the distinctions.
667pub(crate) async fn focused_element_summary_in_app(
668    target_pid: u32,
669) -> Result<Option<FocusedElementSummary>> {
670    Ok(match focused_element_probe(Some(target_pid), true).await? {
671        FocusProbe::Found(summary) => Some(summary),
672        _ => None,
673    })
674}
675
676async fn focused_element_probe(
677    target_pid: Option<u32>,
678    require_scoped: bool,
679) -> Result<FocusProbe> {
680    let conn = connect().await?;
681    let mut remaining_registry_reads = MAX_DISCOVERY_ROOTS;
682    let roots =
683        registry_children(&conn, MAX_DISCOVERY_ROOTS, &mut remaining_registry_reads).await?;
684    let mut remaining_filter_reads = MAX_DISCOVERY_CHILD_READS;
685    let selected_roots =
686        select_roots(&conn, roots, None, target_pid, &mut remaining_filter_reads).await;
687    if require_scoped && !selected_roots.scoped {
688        return Ok(FocusProbe::NoAccessibleApp);
689    }
690    let mut traversal = BoundedTraversal::new(FOCUS_PROBE_MAX_NODES);
691    let mut remaining_traversal_reads = FOCUS_PROBE_MAX_NODES;
692    let mut incomplete = false;
693    let mut shell_only = true;
694    let mut observed_nodes = 0;
695    let mut focused_container = None;
696    let mut depth_base = 0_u32;
697
698    traversal.enqueue(
699        selected_roots
700            .roots
701            .into_iter()
702            .map(|object_ref| (object_ref, 0_u32, false)),
703    );
704
705    while let Some((object_ref, depth, in_menu)) = traversal.pop() {
706        let Ok(proxy) = open_accessible(&conn, &object_ref).await else {
707            incomplete = true;
708            continue;
709        };
710        let Ok(state) = proxy.get_state().await else {
711            incomplete = true;
712            continue;
713        };
714        observed_nodes += 1;
715        let mut child_menu = false;
716        if shell_only {
717            match accessibility_chrome_context(&role_name(&proxy).await, in_menu) {
718                Some(menu) => child_menu = menu,
719                None => shell_only = false,
720            }
721        }
722        if state.contains(atspi::State::Focused) {
723            let proxies = proxy.proxies().await.ok();
724            let is_terminal = matches!(proxy.get_role().await, Ok(atspi::Role::Terminal));
725            let summary = FocusedElementSummary {
726                role: role_name(&proxy).await,
727                name: optional_string(proxy.name().await.ok()),
728                editable: supports_editable_text(proxies.as_ref()).await,
729                states: state_labels(state),
730                is_terminal,
731            };
732            // Chromium can mark both a document and its contenteditable entry
733            // focused. Do not stop at the ancestor before visiting the editor:
734            // the focus is inside it, so the rest of the budget searches only
735            // its subtree, and nodes left unread elsewhere no longer matter.
736            if focus_is_container(&summary) {
737                focused_container = Some(summary);
738                // Only within one app: across apps a stale focused document in
739                // another app must not hide the real focus.
740                if require_scoped {
741                    traversal.narrow();
742                    // The discarded queue had spent its child reads; the subtree
743                    // gets the rest of the node budget, and its depth counts from
744                    // the container.
745                    remaining_traversal_reads = traversal.remaining_capacity();
746                    depth_base = depth;
747                    incomplete = false;
748                }
749            } else {
750                return Ok(FocusProbe::Found(summary));
751            }
752        }
753        let remaining = traversal.remaining_capacity();
754        if depth - depth_base < FOCUS_PROBE_MAX_DEPTH && remaining > 0 {
755            if let Ok(batch) =
756                children_up_to(&proxy, remaining, &mut remaining_traversal_reads).await
757            {
758                incomplete |= batch.incomplete;
759                // An exhausted shared read budget takes children_up_to's
760                // I/O-free path (attempted 0, incomplete false), so the node's
761                // own child count has to say whether children went unread.
762                // With budget left, attempted 0 just means a leaf: no read.
763                if batch.attempted == 0 && remaining_traversal_reads == 0 && !incomplete {
764                    incomplete = proxy.child_count().await.map_or(true, |count| count > 0);
765                }
766                traversal.enqueue(
767                    batch
768                        .items
769                        .into_iter()
770                        .map(|child| (child, depth + 1, child_menu)),
771                );
772            } else {
773                incomplete = true;
774            }
775        } else if !incomplete {
776            // Depth or node cap: any child this node reports goes unread. One
777            // child-count read settles it, and only until the first cut is seen.
778            incomplete = proxy.child_count().await.map_or(true, |count| count > 0);
779        }
780    }
781    Ok(finish_focus_probe(
782        incomplete || traversal.truncated(),
783        require_scoped && shell_only && observed_nodes > 0,
784        focused_container,
785    ))
786}
787
788pub(crate) fn focus_is_container(element: &FocusedElementSummary) -> bool {
789    !element.editable
790        && !element.states.iter().any(|state| state == "editable")
791        && !element.is_terminal
792        && matches!(
793            element.role.as_str(),
794            "application"
795                | "frame"
796                | "window"
797                | "panel"
798                | "filler"
799                | "section"
800                | "document web"
801                | "document frame"
802                | "document text"
803        )
804}
805
806fn finish_focus_probe(
807    incomplete: bool,
808    shell_only: bool,
809    focused_container: Option<FocusedElementSummary>,
810) -> FocusProbe {
811    // A focused container is not a definitive recipient if descendants were
812    // unread. Preserve uncertainty rather than reporting a non-editable field.
813    if incomplete {
814        FocusProbe::Incomplete
815    } else if let Some(container) = focused_container {
816        FocusProbe::Found(container)
817    } else if shell_only {
818        FocusProbe::ShellOnly
819    } else {
820        FocusProbe::NoneFocused
821    }
822}
823
824/// Window and native menu chrome can exist without Electron renderer content.
825/// This is evidence about tree coverage, not positive Electron detection.
826pub(crate) fn accessibility_chrome_context(role: &str, in_menu: bool) -> Option<bool> {
827    match role {
828        "application" | "frame" | "window" | "panel" | "filler" | "separator" => Some(in_menu),
829        "menu bar" | "menu" | "menu item" | "check menu item" | "radio menu item"
830        | "tearoff menu item" => Some(true),
831        // Electron's native menu buttons are exposed as buttons, not menu items.
832        "button" | "push button" | "label" | "static" | "image" | "icon" if in_menu => Some(true),
833        _ => None,
834    }
835}
836
837pub async fn perform_action(
838    object_ref_id: &str,
839    requested_action: Option<&str>,
840) -> Result<ActionInvocation> {
841    perform_action_inner(object_ref_id, requested_action, false).await
842}
843
844pub(crate) async fn perform_named_action(
845    object_ref_id: &str,
846    name: &str,
847) -> Result<ActionInvocation> {
848    perform_action_inner(object_ref_id, Some(name), true).await
849}
850
851async fn perform_action_inner(
852    object_ref_id: &str,
853    requested_action: Option<&str>,
854    name_only: bool,
855) -> Result<ActionInvocation> {
856    let object_ref = object_ref_from_id(object_ref_id)?;
857    let (action, action_index, action_name) = timeout(ACTION_QUERY_TIMEOUT, async {
858        let conn = connect().await?;
859        let proxy = open_accessible(&conn, &object_ref)
860            .await
861            .with_context(|| format!("failed to open AT-SPI object {object_ref_id}"))?;
862        let action = proxy
863            .proxies()
864            .await?
865            .action()
866            .await
867            .context("element does not expose the AT-SPI Action interface")?;
868        let actions = read_actions(&action).await?;
869        let action_index = if name_only {
870            select_named_action_index(&actions, requested_action.unwrap_or_default())?
871        } else {
872            select_action_index(&actions, requested_action)?
873        };
874        let action_name = actions
875            .get(action_index as usize)
876            .map(|action| action.name.clone());
877        Ok::<_, anyhow::Error>((action, action_index, action_name))
878    })
879    .await
880    .context("AT-SPI action revalidation exceeded its 5-second deadline")??;
881    // Only time out the reads: once DoAction is sent, it may already have acted.
882    let ok = action
883        .do_action(action_index)
884        .await
885        .with_context(|| format!("failed to invoke AT-SPI action {action_index}"))?;
886
887    Ok(ActionInvocation {
888        action_index,
889        action_name,
890        ok,
891    })
892}
893
894pub async fn set_element_value(object_ref_id: &str, value: &str) -> Result<ValueSetInvocation> {
895    let conn = connect().await?;
896    let object_ref = object_ref_from_id(object_ref_id)?;
897    let proxy = open_accessible(&conn, &object_ref)
898        .await
899        .with_context(|| format!("failed to open AT-SPI object {object_ref_id}"))?;
900    let proxies = proxy.proxies().await?;
901    set_element_value_with_proxies(&proxy, &proxies, value).await
902}
903
904async fn set_element_value_with_proxies(
905    proxy: &AccessibleProxy<'_>,
906    proxies: &Proxies<'_>,
907    value: &str,
908) -> Result<ValueSetInvocation> {
909    if let Ok(numeric_value) = value.parse::<f64>() {
910        if let Ok(value_proxy) = proxies.value().await {
911            value_proxy
912                .set_current_value(numeric_value)
913                .await
914                .with_context(|| {
915                    format!("failed to set AT-SPI numeric value to {numeric_value}")
916                })?;
917            return Ok(ValueSetInvocation::Numeric {
918                value: numeric_value,
919            });
920        }
921    }
922
923    if let Ok(editable_text) = proxies.editable_text().await {
924        return set_editable_text_contents(proxy, proxies, &editable_text, value).await;
925    }
926
927    if value.parse::<f64>().is_err() && proxies.value().await.is_ok() {
928        return Err(anyhow!(
929            "element exposes the AT-SPI Value interface, but the requested value is not numeric"
930        ));
931    }
932
933    Err(anyhow!(
934        "element does not expose AT-SPI Value or EditableText interfaces"
935    ))
936}
937
938async fn set_editable_text_contents(
939    proxy: &AccessibleProxy<'_>,
940    proxies: &Proxies<'_>,
941    editable_text: &EditableTextProxy<'_>,
942    value: &str,
943) -> Result<ValueSetInvocation> {
944    let ok = editable_text
945        .set_text_contents(value)
946        .await
947        .context("failed to set AT-SPI editable text contents")?;
948    if !ok {
949        return Err(anyhow!("AT-SPI EditableText rejected the new contents"));
950    }
951
952    let outcome = verify_editable_text_contents(proxy, proxies, value).await;
953    Ok(ValueSetInvocation::EditableText { outcome })
954}
955
956#[derive(Debug, Clone, Copy, PartialEq, Eq)]
957enum EditableTextReadbackError {
958    Failed,
959    TimedOut,
960}
961
962async fn readback_within<T, E>(
963    deadline: Instant,
964    read: impl Future<Output = std::result::Result<T, E>>,
965) -> std::result::Result<T, EditableTextReadbackError> {
966    timeout_at(deadline, read)
967        .await
968        .map_err(|_| EditableTextReadbackError::TimedOut)?
969        .map_err(|_| EditableTextReadbackError::Failed)
970}
971
972async fn text_readback_matches(
973    text: &TextProxy<'_>,
974    requested: &str,
975    deadline: Instant,
976) -> std::result::Result<bool, EditableTextReadbackError> {
977    let character_count = readback_within(deadline, text.character_count()).await?;
978    if character_count < 0 {
979        return Err(EditableTextReadbackError::Failed);
980    }
981    if character_count as usize == requested.chars().count() {
982        return unicode_scalar_text_readback_matches(text, requested, deadline).await;
983    }
984
985    let requested_utf16 = requested.encode_utf16().collect::<Vec<_>>();
986    if character_count as usize != requested_utf16.len() {
987        return Ok(false);
988    }
989    utf16_text_readback_matches(text, &requested_utf16, deadline).await
990}
991
992async fn unicode_scalar_text_readback_matches(
993    text: &TextProxy<'_>,
994    requested: &str,
995    deadline: Instant,
996) -> std::result::Result<bool, EditableTextReadbackError> {
997    let requested_chars = requested.chars().collect::<Vec<_>>();
998    let mut offset = 0;
999    while offset < requested_chars.len() {
1000        let end = offset
1001            .saturating_add(EDITABLE_TEXT_READ_CHUNK_UNITS)
1002            .min(requested_chars.len());
1003        let chunk = readback_within(deadline, text.get_text(offset as i32, end as i32)).await?;
1004        if !chunk
1005            .chars()
1006            .eq(requested_chars[offset..end].iter().copied())
1007        {
1008            return Ok(false);
1009        }
1010        offset = end;
1011    }
1012
1013    Ok(true)
1014}
1015
1016async fn utf16_text_readback_matches(
1017    text: &TextProxy<'_>,
1018    requested: &[u16],
1019    deadline: Instant,
1020) -> std::result::Result<bool, EditableTextReadbackError> {
1021    let mut offset = 0;
1022    while offset < requested.len() {
1023        let mut end = offset
1024            .saturating_add(EDITABLE_TEXT_READ_CHUNK_UNITS)
1025            .min(requested.len());
1026        if end < requested.len() && (0xD800..=0xDBFF).contains(&requested[end - 1]) {
1027            end -= 1;
1028        }
1029        let chunk = readback_within(deadline, text.get_text(offset as i32, end as i32)).await?;
1030        if !chunk
1031            .encode_utf16()
1032            .eq(requested[offset..end].iter().copied())
1033        {
1034            return Ok(false);
1035        }
1036        offset = end;
1037    }
1038
1039    Ok(true)
1040}
1041
1042async fn verify_editable_text_contents(
1043    proxy: &AccessibleProxy<'_>,
1044    proxies: &Proxies<'_>,
1045    requested: &str,
1046) -> EditableTextSetOutcome {
1047    let deadline = Instant::now() + EDITABLE_TEXT_VERIFY_TIMEOUT;
1048    match readback_within(deadline, proxy.get_role()).await {
1049        Ok(atspi::Role::PasswordText) => return EditableTextSetOutcome::PasswordUnverifiable,
1050        Ok(_) => {}
1051        Err(EditableTextReadbackError::Failed) => {
1052            return EditableTextSetOutcome::ReadbackFailed;
1053        }
1054        Err(EditableTextReadbackError::TimedOut) => {
1055            return EditableTextSetOutcome::ReadbackTimedOut;
1056        }
1057    }
1058    let text = match readback_within(deadline, proxies.text()).await {
1059        Ok(text) => text,
1060        Err(EditableTextReadbackError::Failed) => {
1061            return EditableTextSetOutcome::ReadbackFailed;
1062        }
1063        Err(EditableTextReadbackError::TimedOut) => {
1064            return EditableTextSetOutcome::ReadbackTimedOut;
1065        }
1066    };
1067
1068    loop {
1069        match text_readback_matches(&text, requested, deadline).await {
1070            Ok(true) => return EditableTextSetOutcome::Verified,
1071            Ok(false) => {}
1072            Err(EditableTextReadbackError::Failed) => {
1073                return EditableTextSetOutcome::ReadbackFailed;
1074            }
1075            Err(EditableTextReadbackError::TimedOut) => {
1076                return EditableTextSetOutcome::ReadbackTimedOut;
1077            }
1078        }
1079
1080        let now = Instant::now();
1081        if now >= deadline {
1082            return EditableTextSetOutcome::MismatchAfterDeadline;
1083        }
1084        sleep_until((now + EDITABLE_TEXT_VERIFY_INTERVAL).min(deadline)).await;
1085        if Instant::now() >= deadline {
1086            return EditableTextSetOutcome::MismatchAfterDeadline;
1087        }
1088    }
1089}
1090
1091async fn connect() -> Result<AccessibilityConnection> {
1092    hydrate_session_bus_env();
1093    AccessibilityConnection::new()
1094        .await
1095        .context("failed to connect to AT-SPI bus")
1096}
1097
1098/// Open an `AccessibleProxy` for an object on the a11y bus.
1099///
1100/// We deliberately avoid `AccessibilityConnection::object_as_accessible` (the
1101/// `P2P` trait). For apps that advertise a peer-to-peer bus address it routes
1102/// reads over that socket, but for apps that don't (notably GTK4 apps such as
1103/// Nautilus / Text Editor / baobab, which don't implement the legacy
1104/// `GetApplicationBusAddress`) it falls back to a proxy built with only a path
1105/// and *no destination*. On the shared a11y bus that proxy can't address the
1106/// app and every call fails with `ServiceUnknown`, which surfaces as an empty
1107/// tree (`role: "unknown"`, `child_count: 0`). `as_accessible_proxy` always
1108/// pins the destination to the object's bus name, so it works for every app
1109/// regardless of P2P support. See issue #31.
1110async fn open_accessible<'r>(
1111    conn: &AccessibilityConnection,
1112    object_ref: &'r ObjectRefOwned,
1113) -> Result<AccessibleProxy<'r>, atspi::AtspiError> {
1114    object_ref.as_accessible_proxy(conn.connection()).await
1115}
1116
1117async fn registry_children(
1118    conn: &AccessibilityConnection,
1119    limit: usize,
1120    remaining_child_reads: &mut usize,
1121) -> Result<Vec<ObjectRefOwned>> {
1122    let root = conn
1123        .root_accessible_on_registry()
1124        .await
1125        .context("failed to open AT-SPI registry root")?;
1126    let batch = children_up_to(&root, limit, remaining_child_reads)
1127        .await
1128        .context("failed to read AT-SPI registry children")?;
1129    if batch.all_failed() {
1130        return Err(anyhow!(
1131            "AT-SPI registry reported children, but every indexed child read failed"
1132        ));
1133    }
1134    Ok(batch.items)
1135}
1136
1137struct SelectedRoots {
1138    roots: Vec<ObjectRefOwned>,
1139    scoped: bool,
1140    /// Set only when the roots were chosen because they belong to this pid.
1141    pid: Option<u32>,
1142    app_filter_matched: bool,
1143}
1144
1145/// Normalized app-name filter, or `None` when the caller passed nothing usable.
1146/// A `None` needle with no pid match means the snapshot covers the whole desktop.
1147fn app_name_needle(app_name_or_bundle_identifier: Option<&str>) -> Option<String> {
1148    app_name_or_bundle_identifier
1149        .map(str::trim)
1150        .filter(|value| !value.is_empty())
1151        .map(|value| value.to_ascii_lowercase())
1152}
1153
1154async fn select_roots(
1155    conn: &AccessibilityConnection,
1156    roots: Vec<ObjectRefOwned>,
1157    app_name_or_bundle_identifier: Option<&str>,
1158    target_pid: Option<u32>,
1159    remaining_child_reads: &mut usize,
1160) -> SelectedRoots {
1161    let needle = app_name_needle(app_name_or_bundle_identifier);
1162    let dbus = DBusProxy::new(conn.connection()).await.ok();
1163    let mut remaining = roots;
1164
1165    if let Some(target_pid) = target_pid {
1166        let mut pid_and_filter_matches = Vec::new();
1167        let mut pid_matches = Vec::new();
1168        let mut non_pid_matches = Vec::new();
1169
1170        for object_ref in remaining {
1171            if object_ref_pid(dbus.as_ref(), &object_ref).await == Some(target_pid) {
1172                if let Some(needle) = needle.as_deref() {
1173                    if root_matches(conn, &object_ref, needle, remaining_child_reads).await {
1174                        pid_and_filter_matches.push(object_ref);
1175                    } else {
1176                        pid_matches.push(object_ref);
1177                    }
1178                } else {
1179                    pid_matches.push(object_ref);
1180                }
1181            } else {
1182                non_pid_matches.push(object_ref);
1183            }
1184        }
1185
1186        if !pid_and_filter_matches.is_empty() {
1187            return SelectedRoots {
1188                roots: pid_and_filter_matches,
1189                scoped: true,
1190                pid: Some(target_pid),
1191                app_filter_matched: true,
1192            };
1193        }
1194        if !pid_matches.is_empty() {
1195            return SelectedRoots {
1196                roots: pid_matches,
1197                scoped: true,
1198                pid: Some(target_pid),
1199                app_filter_matched: needle.is_none(),
1200            };
1201        }
1202
1203        remaining = non_pid_matches;
1204    }
1205
1206    let Some(needle) = needle.as_deref() else {
1207        return SelectedRoots {
1208            roots: remaining,
1209            scoped: false,
1210            pid: None,
1211            app_filter_matched: true,
1212        };
1213    };
1214
1215    let mut selected = Vec::new();
1216    for object_ref in remaining {
1217        if root_matches(conn, &object_ref, needle, remaining_child_reads).await {
1218            selected.push(object_ref);
1219        }
1220    }
1221
1222    let app_filter_matched = !selected.is_empty();
1223    SelectedRoots {
1224        roots: selected,
1225        scoped: true,
1226        pid: None,
1227        app_filter_matched,
1228    }
1229}
1230
1231async fn root_matches(
1232    conn: &AccessibilityConnection,
1233    object_ref: &ObjectRefOwned,
1234    needle: &str,
1235    remaining_child_reads: &mut usize,
1236) -> bool {
1237    let Ok(proxy) = open_accessible(conn, object_ref).await else {
1238        return object_ref_id(object_ref)
1239            .to_ascii_lowercase()
1240            .contains(needle);
1241    };
1242
1243    if proxy_matches(&proxy, object_ref, needle).await {
1244        return true;
1245    }
1246
1247    for child_ref in children_up_to(&proxy, ROOT_MATCH_CHILD_LIMIT, remaining_child_reads)
1248        .await
1249        .map(|batch| batch.items)
1250        .unwrap_or_default()
1251    {
1252        let Ok(child_proxy) = open_accessible(conn, &child_ref).await else {
1253            continue;
1254        };
1255        if proxy_matches(&child_proxy, &child_ref, needle).await {
1256            return true;
1257        }
1258    }
1259
1260    false
1261}
1262
1263async fn proxy_matches(
1264    proxy: &AccessibleProxy<'_>,
1265    object_ref: &ObjectRefOwned,
1266    needle: &str,
1267) -> bool {
1268    let name = proxy.name().await.unwrap_or_default();
1269    let role = proxy.get_role_name().await.unwrap_or_default();
1270    format!("{} {} {}", object_ref_id(object_ref), name, role)
1271        .to_ascii_lowercase()
1272        .contains(needle)
1273}
1274
1275async fn read_app_summary(
1276    proxy: &AccessibleProxy<'_>,
1277    object_ref: &ObjectRefOwned,
1278    dbus: Option<&DBusProxy<'_>>,
1279) -> AccessibleAppSummary {
1280    AccessibleAppSummary {
1281        object_ref: object_ref_id(object_ref),
1282        name: optional_string(proxy.name().await.ok()),
1283        pid: object_ref_pid(dbus, object_ref).await,
1284        role: role_name(proxy).await,
1285        child_count: proxy.child_count().await.unwrap_or_default(),
1286        bounds: bounds(proxy).await,
1287    }
1288}
1289
1290async fn read_node(
1291    proxy: &AccessibleProxy<'_>,
1292    object_ref: &ObjectRefOwned,
1293    index: u32,
1294    parent_index: Option<u32>,
1295    depth: u32,
1296) -> AccessibilityNode {
1297    let proxies = proxy.proxies().await.ok();
1298
1299    AccessibilityNode {
1300        index,
1301        parent_index,
1302        depth,
1303        object_ref: object_ref_id(object_ref),
1304        role: role_name(proxy).await,
1305        name: optional_string(proxy.name().await.ok()),
1306        description: optional_string(proxy.description().await.ok()),
1307        child_count: proxy.child_count().await.unwrap_or_default(),
1308        bounds: bounds_from_proxies(proxies.as_ref(), proxy).await,
1309        states: states_from_proxy(proxy).await,
1310        actions: actions_from_proxies(proxies.as_ref()).await,
1311        value: value_from_proxies(proxies.as_ref()).await,
1312        text: text_from_proxies(proxies.as_ref()).await,
1313        supports_editable_text: supports_editable_text(proxies.as_ref()).await,
1314    }
1315}
1316
1317/// Role reported when neither AT-SPI role read succeeds.
1318pub(crate) const UNKNOWN_ROLE: &str = "unknown";
1319
1320async fn role_name(proxy: &AccessibleProxy<'_>) -> String {
1321    if let Ok(role) = proxy.get_role_name().await {
1322        if !role.trim().is_empty() {
1323            return role;
1324        }
1325    }
1326    proxy
1327        .get_role()
1328        .await
1329        .map(|role| format!("{role:?}"))
1330        .unwrap_or_else(|_| UNKNOWN_ROLE.to_string())
1331}
1332
1333async fn bounds(proxy: &AccessibleProxy<'_>) -> Option<Bounds> {
1334    bounds_from_proxies(proxy.proxies().await.ok().as_ref(), proxy).await
1335}
1336
1337/// Pid of the process that owns an AT-SPI object ref (`:bus/path`), from the
1338/// accessibility bus. `None` when the owner is gone or the bus cannot say.
1339pub(crate) async fn object_ref_owner_pid(object_ref_id: &str) -> Result<Option<u32>> {
1340    let object_ref = object_ref_from_id(object_ref_id)?;
1341    let conn = connect().await?;
1342    let dbus = DBusProxy::new(conn.connection()).await.ok();
1343    Ok(object_ref_pid(dbus.as_ref(), &object_ref).await)
1344}
1345
1346async fn object_ref_pid(dbus: Option<&DBusProxy<'_>>, object_ref: &ObjectRefOwned) -> Option<u32> {
1347    let dbus = dbus?;
1348    let bus_name = BusName::try_from(object_ref.name_as_str()?.to_string()).ok()?;
1349    dbus.get_connection_unix_process_id(bus_name).await.ok()
1350}
1351
1352async fn bounds_from_proxies(
1353    proxies: Option<&atspi::proxy::proxy_ext::Proxies<'_>>,
1354    proxy: &AccessibleProxy<'_>,
1355) -> Option<Bounds> {
1356    let owned_proxies;
1357    let proxies = if let Some(proxies) = proxies {
1358        proxies
1359    } else {
1360        owned_proxies = proxy.proxies().await.ok()?;
1361        &owned_proxies
1362    };
1363    let component = proxies.component().await.ok()?;
1364    let (x, y, width, height) = component.get_extents(CoordType::Screen).await.ok()?;
1365    normalize_bounds(Bounds {
1366        x,
1367        y,
1368        width,
1369        height,
1370    })
1371}
1372
1373fn normalize_bounds(bounds: Bounds) -> Option<Bounds> {
1374    if bounds.width <= 0 || bounds.height <= 0 {
1375        return None;
1376    }
1377    if bounds.x <= i32::MIN / 2 || bounds.y <= i32::MIN / 2 {
1378        return None;
1379    }
1380    Some(bounds)
1381}
1382
1383async fn actions_from_proxies(
1384    proxies: Option<&atspi::proxy::proxy_ext::Proxies<'_>>,
1385) -> Vec<AccessibilityAction> {
1386    let Some(proxies) = proxies else {
1387        return Vec::new();
1388    };
1389    let Ok(action_proxy) = proxies.action().await else {
1390        return Vec::new();
1391    };
1392
1393    read_actions(&action_proxy)
1394        .await
1395        .unwrap_or_default()
1396        .into_iter()
1397        .enumerate()
1398        .map(|(index, action)| AccessibilityAction {
1399            index: index as i32,
1400            name: action.name,
1401            description: action.description,
1402            keybinding: action.keybinding,
1403        })
1404        .collect()
1405}
1406
1407async fn read_actions(proxy: &ActionProxy<'_>) -> Result<Vec<atspi::Action>> {
1408    // WebKit can advertise GetActions without replying to it. The indexed
1409    // methods work, and must also be used when revalidating a cached action.
1410    // Keep the wire spelling: the current atspi binding asks for "Nactions".
1411    timeout(ACTION_QUERY_TIMEOUT, async {
1412        let count = proxy
1413            .inner()
1414            .get_property::<i32>("NActions")
1415            .await
1416            .context("failed to read AT-SPI action count")?;
1417        if count > MAX_ACTIONS_PER_OBJECT {
1418            return Err(anyhow!(
1419                "AT-SPI action count {count} exceeds the {MAX_ACTIONS_PER_OBJECT}-action read budget"
1420            ));
1421        }
1422        if count < 0 {
1423            return Err(anyhow!("invalid negative AT-SPI action count {count}"));
1424        }
1425        Ok(stream::iter(0..count)
1426            .map(|index| async move {
1427                let (name, description, keybinding) = tokio::join!(
1428                    proxy.get_name(index),
1429                    proxy.get_description(index),
1430                    proxy.get_key_binding(index),
1431                );
1432                atspi::Action {
1433                    name: name.unwrap_or_default(),
1434                    description: description.unwrap_or_default(),
1435                    keybinding: keybinding.unwrap_or_default(),
1436                }
1437            })
1438            .buffered(CHILD_READ_CONCURRENCY)
1439            .collect()
1440            .await)
1441    })
1442    .await
1443    .context("AT-SPI action reads exceeded their 5-second deadline")?
1444}
1445
1446async fn states_from_proxy(proxy: &AccessibleProxy<'_>) -> Vec<String> {
1447    proxy
1448        .get_state()
1449        .await
1450        .map(state_labels)
1451        .unwrap_or_default()
1452}
1453
1454async fn value_from_proxies(
1455    proxies: Option<&atspi::proxy::proxy_ext::Proxies<'_>>,
1456) -> Option<AccessibilityValue> {
1457    let value = proxies?.value().await.ok()?;
1458    Some(AccessibilityValue {
1459        current: value.current_value().await.ok()?,
1460        minimum: value.minimum_value().await.ok()?,
1461        maximum: value.maximum_value().await.ok()?,
1462        minimum_increment: value.minimum_increment().await.ok()?,
1463        text: optional_string(value.text().await.ok()),
1464    })
1465}
1466
1467async fn text_from_proxies(
1468    proxies: Option<&atspi::proxy::proxy_ext::Proxies<'_>>,
1469) -> Option<AccessibilityText> {
1470    let text = proxies?.text().await.ok()?;
1471    let character_count = text.character_count().await.ok()?.max(0);
1472    let caret_offset = text.caret_offset().await.ok();
1473    let capped_count = character_count.min(MAX_TEXT_READBACK_CHARS);
1474    let content = if capped_count > 0 {
1475        optional_string(text.get_text(0, capped_count).await.ok())
1476    } else {
1477        None
1478    };
1479    let selection_count = text
1480        .get_nselections()
1481        .await
1482        .unwrap_or_default()
1483        .clamp(0, MAX_TEXT_SELECTIONS);
1484    let mut selections = Vec::new();
1485    for index in 0..selection_count {
1486        if let Ok((start_offset, end_offset)) = text.get_selection(index).await {
1487            selections.push(AccessibilityTextSelection {
1488                start_offset,
1489                end_offset,
1490            });
1491        }
1492    }
1493
1494    Some(AccessibilityText {
1495        character_count,
1496        caret_offset,
1497        content,
1498        truncated: character_count > MAX_TEXT_READBACK_CHARS,
1499        selections,
1500    })
1501}
1502
1503async fn supports_editable_text(proxies: Option<&atspi::proxy::proxy_ext::Proxies<'_>>) -> bool {
1504    let Some(proxies) = proxies else {
1505        return false;
1506    };
1507    proxies.editable_text().await.is_ok()
1508}
1509
1510fn state_labels(state_set: StateSet) -> Vec<String> {
1511    state_set.iter().map(|state| state.to_string()).collect()
1512}
1513
1514fn select_action_index(actions: &[atspi::Action], requested_action: Option<&str>) -> Result<i32> {
1515    if actions.is_empty() {
1516        return Err(anyhow!("element exposes no AT-SPI actions"));
1517    }
1518
1519    if let Some(requested_action) = requested_action
1520        .map(str::trim)
1521        .filter(|value| !value.is_empty())
1522    {
1523        let requested_action = requested_action.to_ascii_lowercase();
1524        if let Some((index, _)) = actions.iter().enumerate().find(|(_, action)| {
1525            action.name.to_ascii_lowercase() == requested_action
1526                || action.description.to_ascii_lowercase() == requested_action
1527        }) {
1528            return Ok(index as i32);
1529        }
1530
1531        if let Ok(index) = requested_action.parse::<usize>() {
1532            if index < actions.len() {
1533                return Ok(index as i32);
1534            }
1535        }
1536
1537        return Err(anyhow!(
1538            "requested AT-SPI action was not found; available actions: {}",
1539            actions
1540                .iter()
1541                .map(|action| action.name.as_str())
1542                .collect::<Vec<_>>()
1543                .join(", ")
1544        ));
1545    }
1546
1547    Ok(if actions.len() > 1 { 1 } else { 0 })
1548}
1549
1550fn select_named_action_index(actions: &[atspi::Action], name: &str) -> Result<i32> {
1551    actions
1552        .iter()
1553        .position(|action| action.name.eq_ignore_ascii_case(name))
1554        .map(|index| index as i32)
1555        .ok_or_else(|| {
1556            anyhow!("cached AT-SPI action name is no longer available; refresh get_app_state")
1557        })
1558}
1559
1560fn optional_string(value: Option<String>) -> Option<String> {
1561    value
1562        .map(|value| value.trim().to_string())
1563        .filter(|value| !value.is_empty())
1564}
1565
1566fn object_ref_from_id(object_ref_id: &str) -> Result<ObjectRefOwned> {
1567    let (name, path) = split_object_ref_id(object_ref_id)?;
1568    let name = UniqueName::try_from(name.to_string())
1569        .with_context(|| format!("invalid AT-SPI bus name in object ref {object_ref_id}"))?;
1570    let path = ObjectPath::try_from(path.to_string())
1571        .with_context(|| format!("invalid AT-SPI object path in object ref {object_ref_id}"))?;
1572    Ok(ObjectRef::new_owned(name, path))
1573}
1574
1575fn split_object_ref_id(object_ref_id: &str) -> Result<(&str, &str)> {
1576    let Some(path_start) = object_ref_id.find('/') else {
1577        return Err(anyhow!(
1578            "invalid AT-SPI object ref '{object_ref_id}'; expected ':bus/path'"
1579        ));
1580    };
1581    let (name, path) = object_ref_id.split_at(path_start);
1582    if name.is_empty() || path.is_empty() {
1583        return Err(anyhow!(
1584            "invalid AT-SPI object ref '{object_ref_id}'; expected ':bus/path'"
1585        ));
1586    }
1587    Ok((name, path))
1588}
1589
1590fn object_ref_id(object_ref: &ObjectRefOwned) -> String {
1591    format!(
1592        "{}{}",
1593        object_ref.name_as_str().unwrap_or(""),
1594        object_ref.path_as_str()
1595    )
1596}
1597
1598#[cfg(test)]
1599mod tests {
1600    use super::*;
1601    use crate::test_sockets::PrivateBus;
1602    use std::sync::{
1603        atomic::{AtomicUsize, Ordering},
1604        Arc, Mutex,
1605    };
1606
1607    const EDITABLE_FIXTURE_PATH: &str = "/editable";
1608
1609    #[derive(Default)]
1610    struct FakeEditableState {
1611        contents: String,
1612        mutations: usize,
1613        character_count_reads: usize,
1614        get_text_reads: usize,
1615        numeric_value: f64,
1616        numeric_writes: usize,
1617    }
1618
1619    #[derive(Clone, Copy)]
1620    enum FakeMutation {
1621        Apply,
1622        NoOp,
1623        Delayed,
1624        Normalize,
1625        Mask,
1626        Reject,
1627        Fail,
1628    }
1629
1630    #[derive(Clone, Copy, Debug)]
1631    enum FakeTextOffsetModel {
1632        UnicodeScalars,
1633        Utf16CodeUnits,
1634    }
1635
1636    #[derive(Clone, Copy)]
1637    enum FakeTextBehavior {
1638        Normal,
1639        CharacterCountError,
1640        GetTextError,
1641        NegativeCount,
1642        StallCharacterCount,
1643    }
1644
1645    #[derive(Clone, Copy)]
1646    struct FakeEditableConfig {
1647        mutation: FakeMutation,
1648        text: FakeTextBehavior,
1649        text_offset_model: FakeTextOffsetModel,
1650        role: atspi::Role,
1651        has_text: bool,
1652        has_value: bool,
1653    }
1654
1655    impl Default for FakeEditableConfig {
1656        fn default() -> Self {
1657            Self {
1658                mutation: FakeMutation::Apply,
1659                text: FakeTextBehavior::Normal,
1660                text_offset_model: FakeTextOffsetModel::Utf16CodeUnits,
1661                role: atspi::Role::Text,
1662                has_text: true,
1663                has_value: false,
1664            }
1665        }
1666    }
1667
1668    struct FakeEditableAccessible(FakeEditableConfig);
1669
1670    #[zbus::interface(name = "org.a11y.atspi.Accessible")]
1671    impl FakeEditableAccessible {
1672        #[zbus(property)]
1673        fn child_count(&self) -> i32 {
1674            0
1675        }
1676
1677        fn get_interfaces(&self) -> Vec<&str> {
1678            let mut interfaces = vec!["org.a11y.atspi.Accessible", "org.a11y.atspi.EditableText"];
1679            if self.0.has_text {
1680                interfaces.push("org.a11y.atspi.Text");
1681            }
1682            if self.0.has_value {
1683                interfaces.push("org.a11y.atspi.Value");
1684            }
1685            interfaces
1686        }
1687
1688        fn get_role(&self) -> atspi::Role {
1689            self.0.role
1690        }
1691    }
1692
1693    struct FakeEditableText {
1694        state: Arc<Mutex<FakeEditableState>>,
1695        mutation: FakeMutation,
1696    }
1697
1698    #[zbus::interface(name = "org.a11y.atspi.EditableText")]
1699    impl FakeEditableText {
1700        fn set_text_contents(&self, new_contents: &str) -> zbus::fdo::Result<bool> {
1701            self.state.lock().unwrap().mutations += 1;
1702            match self.mutation {
1703                FakeMutation::Apply => {
1704                    self.state.lock().unwrap().contents = new_contents.to_string();
1705                }
1706                FakeMutation::NoOp => {}
1707                FakeMutation::Delayed => {
1708                    let state = Arc::clone(&self.state);
1709                    let new_contents = new_contents.to_string();
1710                    tokio::spawn(async move {
1711                        tokio::time::sleep(Duration::from_millis(150)).await;
1712                        state.lock().unwrap().contents = new_contents;
1713                    });
1714                }
1715                FakeMutation::Normalize => {
1716                    self.state.lock().unwrap().contents = new_contents.replace("\r\n", "\n");
1717                }
1718                FakeMutation::Mask => {
1719                    self.state.lock().unwrap().contents = "•".repeat(new_contents.chars().count());
1720                }
1721                FakeMutation::Reject => return Ok(false),
1722                FakeMutation::Fail => {
1723                    return Err(zbus::fdo::Error::Failed(
1724                        "injected SetTextContents failure".into(),
1725                    ));
1726                }
1727            }
1728            Ok(true)
1729        }
1730    }
1731
1732    fn unicode_scalar_offset_to_byte_index(contents: &str, offset: usize) -> Option<usize> {
1733        contents
1734            .char_indices()
1735            .map(|(byte_index, _)| byte_index)
1736            .chain(std::iter::once(contents.len()))
1737            .nth(offset)
1738    }
1739
1740    fn utf16_offset_to_byte_index(contents: &str, offset: usize) -> Option<usize> {
1741        let mut utf16_offset = 0;
1742        for (byte_index, character) in contents.char_indices() {
1743            if utf16_offset == offset {
1744                return Some(byte_index);
1745            }
1746            utf16_offset += character.len_utf16();
1747        }
1748        (utf16_offset == offset).then_some(contents.len())
1749    }
1750
1751    struct FakeText {
1752        state: Arc<Mutex<FakeEditableState>>,
1753        behavior: FakeTextBehavior,
1754        text_offset_model: FakeTextOffsetModel,
1755    }
1756
1757    #[zbus::interface(name = "org.a11y.atspi.Text")]
1758    impl FakeText {
1759        #[zbus(property)]
1760        async fn character_count(&self) -> zbus::fdo::Result<i32> {
1761            self.state.lock().unwrap().character_count_reads += 1;
1762            match self.behavior {
1763                FakeTextBehavior::CharacterCountError => Err(zbus::fdo::Error::Failed(
1764                    "injected CharacterCount failure".into(),
1765                )),
1766                FakeTextBehavior::NegativeCount => Ok(-1),
1767                FakeTextBehavior::StallCharacterCount => std::future::pending().await,
1768                _ => {
1769                    let state = self.state.lock().unwrap();
1770                    let count = match self.text_offset_model {
1771                        FakeTextOffsetModel::UnicodeScalars => state.contents.chars().count(),
1772                        FakeTextOffsetModel::Utf16CodeUnits => {
1773                            state.contents.encode_utf16().count()
1774                        }
1775                    };
1776                    Ok(count as i32)
1777                }
1778            }
1779        }
1780
1781        fn get_text(&self, start_offset: i32, end_offset: i32) -> zbus::fdo::Result<String> {
1782            let mut state = self.state.lock().unwrap();
1783            state.get_text_reads += 1;
1784            if matches!(self.behavior, FakeTextBehavior::GetTextError) {
1785                return Err(zbus::fdo::Error::Failed("injected GetText failure".into()));
1786            }
1787            if start_offset < 0 || end_offset < start_offset {
1788                return Err(zbus::fdo::Error::InvalidArgs("invalid text offsets".into()));
1789            }
1790            let offset_to_byte_index = match self.text_offset_model {
1791                FakeTextOffsetModel::UnicodeScalars => unicode_scalar_offset_to_byte_index,
1792                FakeTextOffsetModel::Utf16CodeUnits => utf16_offset_to_byte_index,
1793            };
1794            let start = offset_to_byte_index(&state.contents, start_offset as usize)
1795                .ok_or_else(|| zbus::fdo::Error::InvalidArgs("invalid text offsets".into()))?;
1796            let end = offset_to_byte_index(&state.contents, end_offset as usize)
1797                .ok_or_else(|| zbus::fdo::Error::InvalidArgs("invalid text offsets".into()))?;
1798            Ok(state.contents[start..end].to_string())
1799        }
1800    }
1801
1802    struct FakeValue(Arc<Mutex<FakeEditableState>>);
1803
1804    #[zbus::interface(name = "org.a11y.atspi.Value")]
1805    impl FakeValue {
1806        #[zbus(property)]
1807        fn current_value(&self) -> f64 {
1808            self.0.lock().unwrap().numeric_value
1809        }
1810
1811        #[zbus(property)]
1812        fn set_current_value(&self, value: f64) {
1813            let mut state = self.0.lock().unwrap();
1814            state.numeric_value = value;
1815            state.numeric_writes += 1;
1816        }
1817    }
1818
1819    async fn start_editable_fixture(
1820        initial_contents: &str,
1821        config: FakeEditableConfig,
1822    ) -> (
1823        PrivateBus,
1824        zbus::Connection,
1825        zbus::Connection,
1826        Arc<Mutex<FakeEditableState>>,
1827    ) {
1828        let bus = PrivateBus::start("cul-atspi-bus");
1829        let address = bus.address();
1830        let state = Arc::new(Mutex::new(FakeEditableState {
1831            contents: initial_contents.to_string(),
1832            ..Default::default()
1833        }));
1834        let mut builder = zbus::connection::Builder::address(address)
1835            .unwrap()
1836            .serve_at(EDITABLE_FIXTURE_PATH, FakeEditableAccessible(config))
1837            .unwrap()
1838            .serve_at(
1839                EDITABLE_FIXTURE_PATH,
1840                FakeEditableText {
1841                    state: Arc::clone(&state),
1842                    mutation: config.mutation,
1843                },
1844            )
1845            .unwrap();
1846        if config.has_text {
1847            builder = builder
1848                .serve_at(
1849                    EDITABLE_FIXTURE_PATH,
1850                    FakeText {
1851                        state: Arc::clone(&state),
1852                        behavior: config.text,
1853                        text_offset_model: config.text_offset_model,
1854                    },
1855                )
1856                .unwrap();
1857        }
1858        if config.has_value {
1859            builder = builder
1860                .serve_at(EDITABLE_FIXTURE_PATH, FakeValue(Arc::clone(&state)))
1861                .unwrap();
1862        }
1863        let peer = builder.build().await.unwrap();
1864        let client = zbus::connection::Builder::address(address)
1865            .unwrap()
1866            .build()
1867            .await
1868            .unwrap();
1869        (bus, peer, client, state)
1870    }
1871
1872    async fn dispatch_editable_fixture(
1873        client: &zbus::Connection,
1874        peer: &zbus::Connection,
1875        value: &str,
1876    ) -> Result<ValueSetInvocation> {
1877        let proxy = AccessibleProxy::builder(client)
1878            .destination(peer.unique_name().unwrap().clone())
1879            .unwrap()
1880            .path(EDITABLE_FIXTURE_PATH)
1881            .unwrap()
1882            .cache_properties(zbus::proxy::CacheProperties::No)
1883            .build()
1884            .await
1885            .unwrap();
1886        let proxies = proxy.proxies().await.unwrap();
1887        set_element_value_with_proxies(&proxy, &proxies, value).await
1888    }
1889
1890    fn editable_outcome(invocation: ValueSetInvocation) -> EditableTextSetOutcome {
1891        match invocation {
1892            ValueSetInvocation::EditableText { outcome } => outcome,
1893            ValueSetInvocation::Numeric { .. } => panic!("expected editable-text dispatch"),
1894        }
1895    }
1896
1897    struct FakeAccessible {
1898        name: String,
1899        children: Vec<(String, OwnedObjectPath)>,
1900        has_action: bool,
1901    }
1902
1903    #[zbus::interface(name = "org.a11y.atspi.Accessible")]
1904    impl FakeAccessible {
1905        #[zbus(property)]
1906        fn child_count(&self) -> i32 {
1907            self.children.len() as i32
1908        }
1909
1910        #[zbus(property)]
1911        fn name(&self) -> &str {
1912            &self.name
1913        }
1914
1915        fn get_interfaces(&self) -> Vec<&str> {
1916            let mut interfaces = vec!["org.a11y.atspi.Accessible"];
1917            if self.has_action {
1918                interfaces.push("org.a11y.atspi.Action");
1919            }
1920            interfaces
1921        }
1922
1923        fn get_child_at_index(
1924            &self,
1925            index: i32,
1926        ) -> zbus::fdo::Result<((String, OwnedObjectPath),)> {
1927            self.children
1928                .get(index as usize)
1929                .cloned()
1930                .map(|child| (child,))
1931                .ok_or_else(|| zbus::fdo::Error::InvalidArgs("invalid child index".into()))
1932        }
1933    }
1934
1935    struct FakeWebKitAction {
1936        count: i32,
1937        stall_indexed_reads: bool,
1938        name_reads: Arc<AtomicUsize>,
1939    }
1940
1941    impl Default for FakeWebKitAction {
1942        fn default() -> Self {
1943            Self {
1944                count: 1,
1945                stall_indexed_reads: false,
1946                name_reads: Arc::default(),
1947            }
1948        }
1949    }
1950
1951    #[zbus::interface(name = "org.a11y.atspi.Action")]
1952    impl FakeWebKitAction {
1953        async fn get_actions(&self) -> Vec<atspi::Action> {
1954            std::future::pending().await
1955        }
1956
1957        #[zbus(property, name = "NActions")]
1958        fn nactions(&self) -> i32 {
1959            self.count
1960        }
1961
1962        async fn get_name(&self, index: i32) -> &str {
1963            assert!((0..self.count).contains(&index));
1964            self.name_reads.fetch_add(1, Ordering::SeqCst);
1965            if self.stall_indexed_reads {
1966                std::future::pending::<()>().await;
1967            }
1968            "click"
1969        }
1970
1971        async fn get_localized_name(&self, index: i32) -> &str {
1972            assert!((0..self.count).contains(&index));
1973            "Activate"
1974        }
1975
1976        fn get_description(&self, index: i32) -> &str {
1977            assert!((0..self.count).contains(&index));
1978            "Activate the control"
1979        }
1980
1981        fn get_key_binding(&self, index: i32) -> &str {
1982            assert!((0..self.count).contains(&index));
1983            "Return"
1984        }
1985
1986        fn do_action(&self, index: i32) -> bool {
1987            index == 0
1988        }
1989    }
1990
1991    struct FakeQtAction;
1992
1993    #[zbus::interface(name = "org.a11y.atspi.Action")]
1994    impl FakeQtAction {
1995        #[zbus(property, name = "NActions")]
1996        fn nactions(&self) -> i32 {
1997            2
1998        }
1999
2000        fn get_name(&self, index: i32) -> &str {
2001            match index {
2002                0 => "Press",
2003                1 => "Set Focus",
2004                _ => panic!("invalid action index"),
2005            }
2006        }
2007
2008        fn get_description(&self, index: i32) -> &str {
2009            match index {
2010                0 => "Eylemi tetikler",
2011                1 => "Odağı ayarlar",
2012                _ => panic!("invalid action index"),
2013            }
2014        }
2015
2016        fn get_key_binding(&self, _index: i32) -> &str {
2017            ""
2018        }
2019    }
2020
2021    #[tokio::test]
2022    async fn editable_text_true_without_publication_is_mismatch_and_mutates_once() {
2023        let (_bus, peer, client, state) = start_editable_fixture(
2024            "original",
2025            FakeEditableConfig {
2026                mutation: FakeMutation::NoOp,
2027                ..Default::default()
2028            },
2029        )
2030        .await;
2031
2032        let outcome = editable_outcome(
2033            dispatch_editable_fixture(&client, &peer, "modified")
2034                .await
2035                .unwrap(),
2036        );
2037
2038        // A last poll can cross the same fixed deadline. Both outcomes mean
2039        // an unverified write; neither permits verification or replay.
2040        assert!(
2041            matches!(
2042                outcome,
2043                EditableTextSetOutcome::MismatchAfterDeadline
2044                    | EditableTextSetOutcome::ReadbackTimedOut
2045            ),
2046            "{outcome:?}"
2047        );
2048        let state = state.lock().unwrap();
2049        assert_eq!(state.mutations, 1);
2050        assert!(state.character_count_reads > 1);
2051        assert!(state.get_text_reads > 1);
2052        assert_eq!(state.contents, "original");
2053    }
2054
2055    #[tokio::test]
2056    async fn editable_text_exact_readback_accepts_empty_whitespace_and_trailing_newline() {
2057        let (_bus, peer, client, state) =
2058            start_editable_fixture("initial", FakeEditableConfig::default()).await;
2059        let values = [
2060            "",
2061            " \t\n",
2062            "  leading and trailing\t \n",
2063            "trailing newline\n",
2064            "Case and unicode € 内容 😀🦀𐐷",
2065        ];
2066
2067        for value in values {
2068            let outcome = editable_outcome(
2069                dispatch_editable_fixture(&client, &peer, value)
2070                    .await
2071                    .unwrap(),
2072            );
2073            assert_eq!(outcome, EditableTextSetOutcome::Verified);
2074            assert_eq!(state.lock().unwrap().contents, value);
2075        }
2076        assert_eq!(state.lock().unwrap().mutations, values.len());
2077    }
2078
2079    #[tokio::test]
2080    async fn editable_text_non_bmp_readback_supports_scalar_and_utf16_peers() {
2081        let requested = "🦀 GTK verified ";
2082        for text_offset_model in [
2083            FakeTextOffsetModel::UnicodeScalars,
2084            FakeTextOffsetModel::Utf16CodeUnits,
2085        ] {
2086            let (_bus, peer, client, state) = start_editable_fixture(
2087                "",
2088                FakeEditableConfig {
2089                    text_offset_model,
2090                    ..Default::default()
2091                },
2092            )
2093            .await;
2094
2095            let outcome = editable_outcome(
2096                dispatch_editable_fixture(&client, &peer, requested)
2097                    .await
2098                    .unwrap(),
2099            );
2100
2101            assert_eq!(
2102                outcome,
2103                EditableTextSetOutcome::Verified,
2104                "{text_offset_model:?}"
2105            );
2106            let state = state.lock().unwrap();
2107            assert_eq!(state.mutations, 1);
2108            assert_eq!(state.contents, requested);
2109        }
2110    }
2111
2112    #[tokio::test]
2113    async fn editable_text_non_bmp_matching_count_does_not_accept_different_content() {
2114        let requested = "🦀 GTK verified ";
2115        let published = "🦀 GTK verified!";
2116        assert_eq!(requested.chars().count(), published.chars().count());
2117        assert_eq!(
2118            requested.encode_utf16().count(),
2119            published.encode_utf16().count()
2120        );
2121        for text_offset_model in [
2122            FakeTextOffsetModel::UnicodeScalars,
2123            FakeTextOffsetModel::Utf16CodeUnits,
2124        ] {
2125            let (_bus, peer, client, state) = start_editable_fixture(
2126                published,
2127                FakeEditableConfig {
2128                    mutation: FakeMutation::NoOp,
2129                    text_offset_model,
2130                    ..Default::default()
2131                },
2132            )
2133            .await;
2134
2135            let outcome = editable_outcome(
2136                dispatch_editable_fixture(&client, &peer, requested)
2137                    .await
2138                    .unwrap(),
2139            );
2140
2141            // A last poll can cross the same fixed deadline. Both outcomes
2142            // leave the write unverified without extending its deadline.
2143            assert!(
2144                matches!(
2145                    outcome,
2146                    EditableTextSetOutcome::MismatchAfterDeadline
2147                        | EditableTextSetOutcome::ReadbackTimedOut
2148                ),
2149                "{text_offset_model:?}: {outcome:?}"
2150            );
2151            let state = state.lock().unwrap();
2152            assert_eq!(state.mutations, 1);
2153            assert!(state.get_text_reads > 0, "{text_offset_model:?}");
2154            assert_eq!(state.contents, published);
2155        }
2156    }
2157
2158    #[tokio::test]
2159    async fn editable_text_readback_chunks_utf16_without_splitting_non_bmp() {
2160        let (_bus, peer, client, state) = start_editable_fixture(
2161            "",
2162            FakeEditableConfig {
2163                text_offset_model: FakeTextOffsetModel::Utf16CodeUnits,
2164                ..Default::default()
2165            },
2166        )
2167        .await;
2168        let mut expected = "a".repeat(EDITABLE_TEXT_READ_CHUNK_UNITS - 1);
2169        // The crab's surrogate pair straddles the first 4096-unit read boundary.
2170        expected.push_str("🦀é");
2171        expected.push_str(&"内容\n".repeat(1_200));
2172        assert!(expected.encode_utf16().count() > MAX_TEXT_READBACK_CHARS as usize);
2173
2174        let outcome = editable_outcome(
2175            dispatch_editable_fixture(&client, &peer, &expected)
2176                .await
2177                .unwrap(),
2178        );
2179
2180        assert_eq!(outcome, EditableTextSetOutcome::Verified);
2181        let state = state.lock().unwrap();
2182        assert_eq!(state.mutations, 1);
2183        assert!(state.get_text_reads >= 2);
2184        assert_eq!(state.contents, expected);
2185    }
2186
2187    #[tokio::test]
2188    async fn editable_text_readback_waits_for_async_publication() {
2189        let (_bus, peer, client, state) = start_editable_fixture(
2190            "pending",
2191            FakeEditableConfig {
2192                mutation: FakeMutation::Delayed,
2193                ..Default::default()
2194            },
2195        )
2196        .await;
2197
2198        let outcome = editable_outcome(
2199            dispatch_editable_fixture(&client, &peer, "published asynchronously")
2200                .await
2201                .unwrap(),
2202        );
2203
2204        assert_eq!(outcome, EditableTextSetOutcome::Verified);
2205        let state = state.lock().unwrap();
2206        assert_eq!(state.mutations, 1);
2207        assert!(state.character_count_reads > 1);
2208        assert_eq!(state.contents, "published asynchronously");
2209    }
2210
2211    #[tokio::test]
2212    async fn editable_text_normalization_mismatch_is_not_verified() {
2213        let (_bus, peer, client, state) = start_editable_fixture(
2214            "",
2215            FakeEditableConfig {
2216                mutation: FakeMutation::Normalize,
2217                ..Default::default()
2218            },
2219        )
2220        .await;
2221
2222        let outcome = editable_outcome(
2223            dispatch_editable_fixture(&client, &peer, "first\r\nsecond\n")
2224                .await
2225                .unwrap(),
2226        );
2227
2228        // A last poll can cross the same fixed deadline. Both outcomes mean
2229        // an unverified write; neither permits verification or replay.
2230        assert!(
2231            matches!(
2232                outcome,
2233                EditableTextSetOutcome::MismatchAfterDeadline
2234                    | EditableTextSetOutcome::ReadbackTimedOut
2235            ),
2236            "{outcome:?}"
2237        );
2238        let state = state.lock().unwrap();
2239        assert_eq!(state.mutations, 1);
2240        assert!(state.character_count_reads > 1);
2241        assert_eq!(state.contents, "first\nsecond\n");
2242    }
2243
2244    #[tokio::test]
2245    async fn password_text_is_unverifiable_even_when_requested_text_is_bullets() {
2246        let (_bus, peer, client, state) = start_editable_fixture(
2247            "",
2248            FakeEditableConfig {
2249                mutation: FakeMutation::Mask,
2250                role: atspi::Role::PasswordText,
2251                ..Default::default()
2252            },
2253        )
2254        .await;
2255
2256        let outcome = editable_outcome(
2257            dispatch_editable_fixture(&client, &peer, "••••••••")
2258                .await
2259                .unwrap(),
2260        );
2261
2262        assert_eq!(outcome, EditableTextSetOutcome::PasswordUnverifiable);
2263        let state = state.lock().unwrap();
2264        assert_eq!(state.mutations, 1);
2265        assert_eq!(state.character_count_reads, 0);
2266        assert_eq!(state.contents, "••••••••");
2267    }
2268
2269    #[tokio::test]
2270    async fn editable_text_missing_text_and_read_errors_are_structured_outcomes() {
2271        let configs = [
2272            FakeEditableConfig {
2273                has_text: false,
2274                ..Default::default()
2275            },
2276            FakeEditableConfig {
2277                text: FakeTextBehavior::CharacterCountError,
2278                ..Default::default()
2279            },
2280            FakeEditableConfig {
2281                text: FakeTextBehavior::GetTextError,
2282                ..Default::default()
2283            },
2284        ];
2285
2286        for config in configs {
2287            let (_bus, peer, client, state) = start_editable_fixture("before", config).await;
2288            let outcome = editable_outcome(
2289                dispatch_editable_fixture(&client, &peer, "readback may have changed")
2290                    .await
2291                    .unwrap(),
2292            );
2293            assert_eq!(outcome, EditableTextSetOutcome::ReadbackFailed);
2294            assert_eq!(state.lock().unwrap().mutations, 1);
2295        }
2296    }
2297
2298    #[tokio::test]
2299    async fn editable_text_negative_counts_and_stalled_readback_are_structured_outcomes() {
2300        let cases = [
2301            (
2302                FakeTextBehavior::NegativeCount,
2303                EditableTextSetOutcome::ReadbackFailed,
2304            ),
2305            (
2306                FakeTextBehavior::StallCharacterCount,
2307                EditableTextSetOutcome::ReadbackTimedOut,
2308            ),
2309        ];
2310
2311        for (text, expected) in cases {
2312            let (_bus, peer, client, state) = start_editable_fixture(
2313                "before",
2314                FakeEditableConfig {
2315                    text,
2316                    ..Default::default()
2317                },
2318            )
2319            .await;
2320            let outcome = editable_outcome(
2321                dispatch_editable_fixture(&client, &peer, "after")
2322                    .await
2323                    .unwrap(),
2324            );
2325            assert_eq!(outcome, expected);
2326            let state = state.lock().unwrap();
2327            assert_eq!(state.mutations, 1);
2328            assert_eq!(state.get_text_reads, 0);
2329        }
2330    }
2331
2332    #[tokio::test]
2333    async fn editable_text_rejection_and_mutation_errors_remain_errors() {
2334        let cases = [
2335            (FakeMutation::Reject, "rejected"),
2336            (FakeMutation::Fail, "failed to set"),
2337        ];
2338
2339        for (mutation, expected_error) in cases {
2340            let (_bus, peer, client, state) = start_editable_fixture(
2341                "before",
2342                FakeEditableConfig {
2343                    mutation,
2344                    ..Default::default()
2345                },
2346            )
2347            .await;
2348            let error = dispatch_editable_fixture(&client, &peer, "after")
2349                .await
2350                .unwrap_err();
2351            assert!(error.to_string().contains(expected_error));
2352            let state = state.lock().unwrap();
2353            assert_eq!(state.mutations, 1);
2354            assert_eq!(state.character_count_reads, 0);
2355        }
2356    }
2357
2358    #[tokio::test]
2359    async fn numeric_value_dispatch_remains_isolated_from_editable_text() {
2360        let (_bus, peer, client, state) = start_editable_fixture(
2361            "unchanged",
2362            FakeEditableConfig {
2363                has_value: true,
2364                ..Default::default()
2365            },
2366        )
2367        .await;
2368
2369        let invocation = dispatch_editable_fixture(&client, &peer, "42.5")
2370            .await
2371            .unwrap();
2372
2373        match invocation {
2374            ValueSetInvocation::Numeric { value } => assert_eq!(value, 42.5),
2375            ValueSetInvocation::EditableText { .. } => panic!("expected numeric dispatch"),
2376        }
2377        let state = state.lock().unwrap();
2378        assert_eq!(state.numeric_value, 42.5);
2379        assert_eq!(state.numeric_writes, 1);
2380        assert_eq!(state.mutations, 0);
2381        assert_eq!(state.character_count_reads, 0);
2382        assert_eq!(state.contents, "unchanged");
2383    }
2384
2385    #[tokio::test]
2386    async fn qt_action_names_do_not_depend_on_localized_names() {
2387        let bus = PrivateBus::start("cul-atspi-bus");
2388        let address = bus.address();
2389        let peer = zbus::connection::Builder::address(address)
2390            .unwrap()
2391            .serve_at("/actions/qt", FakeQtAction)
2392            .unwrap()
2393            .build()
2394            .await
2395            .unwrap();
2396        let client = zbus::connection::Builder::address(address)
2397            .unwrap()
2398            .build()
2399            .await
2400            .unwrap();
2401        let action = ActionProxy::builder(&client)
2402            .destination(peer.unique_name().unwrap().clone())
2403            .unwrap()
2404            .path("/actions/qt")
2405            .unwrap()
2406            .cache_properties(zbus::proxy::CacheProperties::No)
2407            .build()
2408            .await
2409            .unwrap();
2410
2411        let actions = timeout(Duration::from_secs(1), read_actions(&action))
2412            .await
2413            .expect("Qt action reads must not require GetLocalizedName")
2414            .unwrap();
2415
2416        assert_eq!(actions.len(), 2);
2417        assert_eq!(actions[0].name, "Press");
2418        assert_eq!(actions[0].description, "Eylemi tetikler");
2419        assert_eq!(actions[1].name, "Set Focus");
2420        assert_eq!(actions[1].description, "Odağı ayarlar");
2421        assert_eq!(select_named_action_index(&actions, "press").unwrap(), 0);
2422    }
2423
2424    #[tokio::test]
2425    async fn indexed_children_resolve_webkit_names_on_the_accessibility_bus() {
2426        let bus = PrivateBus::start("cul-atspi-bus");
2427        let address = bus.address();
2428
2429        let webkit_name = "org.webkit.MockWebProcess";
2430        let child_path = "/org/a11y/webkit/accessible/child";
2431        let webkit = zbus::connection::Builder::address(address)
2432            .unwrap()
2433            .name(webkit_name)
2434            .unwrap()
2435            .serve_at(
2436                child_path,
2437                FakeAccessible {
2438                    name: "WebKit page".into(),
2439                    children: Vec::new(),
2440                    has_action: true,
2441                },
2442            )
2443            .unwrap()
2444            .serve_at(child_path, FakeWebKitAction::default())
2445            .unwrap()
2446            .build()
2447            .await
2448            .unwrap();
2449        let owner = webkit.unique_name().unwrap().to_string();
2450        let gtk = zbus::connection::Builder::address(address)
2451            .unwrap()
2452            .serve_at(
2453                "/org/a11y/atspi/accessible/root",
2454                FakeAccessible {
2455                    name: "GTK socket".into(),
2456                    has_action: false,
2457                    children: vec![
2458                        (webkit_name.into(), child_path.try_into().unwrap()),
2459                        (owner.clone(), child_path.try_into().unwrap()),
2460                        (String::new(), "/org/a11y/atspi/null".try_into().unwrap()),
2461                        (
2462                            "org.webkit.UnownedWebProcess".into(),
2463                            child_path.try_into().unwrap(),
2464                        ),
2465                    ],
2466                },
2467            )
2468            .unwrap()
2469            .build()
2470            .await
2471            .unwrap();
2472        let client = zbus::connection::Builder::address(address)
2473            .unwrap()
2474            .build()
2475            .await
2476            .unwrap();
2477        let proxy = AccessibleProxy::builder(&client)
2478            .destination(gtk.unique_name().unwrap().clone())
2479            .unwrap()
2480            .path("/org/a11y/atspi/accessible/root")
2481            .unwrap()
2482            .build()
2483            .await
2484            .unwrap();
2485        let mut remaining = 4;
2486        let reply = proxy
2487            .inner()
2488            .call_method("GetChildAtIndex", &(0_i32,))
2489            .await
2490            .unwrap();
2491        assert_eq!(reply.body().signature().to_string(), "(so)");
2492        let batch = children_up_to(&proxy, 4, &mut remaining).await.unwrap();
2493
2494        assert_eq!(batch.attempted, 4);
2495        assert_eq!(remaining, 0);
2496        assert!(!batch.incomplete);
2497        assert_eq!(batch.items.len(), 3, "only the unowned name should fail");
2498        assert_eq!(batch.items[0].name_as_str(), Some(owner.as_str()));
2499        assert_eq!(batch.items[0].path_as_str(), child_path);
2500        assert_eq!(batch.items[0], batch.items[1]);
2501        assert!(batch.items[2].is_null());
2502
2503        // The canonical reference remains usable by the normal read/action path.
2504        let child = batch.items[0].as_accessible_proxy(&client).await.unwrap();
2505        assert_eq!(child.name().await.unwrap(), "WebKit page");
2506        assert_eq!(
2507            object_ref_from_id(&object_ref_id(&batch.items[0])).unwrap(),
2508            batch.items[0]
2509        );
2510        let action = child.proxies().await.unwrap().action().await.unwrap();
2511        let actions = timeout(Duration::from_secs(1), read_actions(&action))
2512            .await
2513            .expect("indexed action reads must not wait for GetActions")
2514            .unwrap();
2515        assert_eq!(actions.len(), 1);
2516        assert_eq!(actions[0].name, "click");
2517        assert_eq!(actions[0].description, "Activate the control");
2518        assert_eq!(actions[0].keybinding, "Return");
2519        assert_eq!(select_named_action_index(&actions, "click").unwrap(), 0);
2520        assert!(action.do_action(0).await.unwrap());
2521    }
2522
2523    #[tokio::test]
2524    async fn indexed_actions_bound_untrusted_counts_before_reading_indices() {
2525        let bus = PrivateBus::start("cul-atspi-bus");
2526        let address = bus.address();
2527        let name_reads = Arc::new(AtomicUsize::new(0));
2528        let counts = [
2529            -1,
2530            MAX_ACTIONS_PER_OBJECT + 1,
2531            i32::MAX,
2532            0,
2533            MAX_ACTIONS_PER_OBJECT,
2534        ];
2535        let mut builder = zbus::connection::Builder::address(address).unwrap();
2536        for (index, count) in counts.iter().enumerate() {
2537            builder = builder
2538                .serve_at(
2539                    format!("/actions/{index}"),
2540                    FakeWebKitAction {
2541                        count: *count,
2542                        name_reads: Arc::clone(&name_reads),
2543                        ..Default::default()
2544                    },
2545                )
2546                .unwrap();
2547        }
2548        let peer = builder.build().await.unwrap();
2549        let client = zbus::connection::Builder::address(address)
2550            .unwrap()
2551            .build()
2552            .await
2553            .unwrap();
2554
2555        for (index, count) in counts.iter().enumerate() {
2556            let action = ActionProxy::builder(&client)
2557                .destination(peer.unique_name().unwrap().clone())
2558                .unwrap()
2559                .path(format!("/actions/{index}"))
2560                .unwrap()
2561                .cache_properties(zbus::proxy::CacheProperties::No)
2562                .build()
2563                .await
2564                .unwrap();
2565            let result = timeout(Duration::from_secs(1), read_actions(&action))
2566                .await
2567                .expect("untrusted counts must not cause unbounded work");
2568            if (0..=MAX_ACTIONS_PER_OBJECT).contains(count) {
2569                assert_eq!(result.unwrap().len(), *count as usize);
2570            } else {
2571                let error = result.unwrap_err().to_string();
2572                assert!(error.contains("action count"), "{error}");
2573                assert_eq!(name_reads.load(Ordering::SeqCst), 0);
2574            }
2575        }
2576        assert_eq!(
2577            name_reads.load(Ordering::SeqCst),
2578            MAX_ACTIONS_PER_OBJECT as usize
2579        );
2580    }
2581
2582    #[tokio::test]
2583    async fn indexed_actions_time_out_the_entire_read() {
2584        let bus = PrivateBus::start("cul-atspi-bus");
2585        let address = bus.address();
2586        let name_reads = Arc::new(AtomicUsize::new(0));
2587        let peer = zbus::connection::Builder::address(address)
2588            .unwrap()
2589            .serve_at(
2590                "/actions/stalled",
2591                FakeWebKitAction {
2592                    stall_indexed_reads: true,
2593                    name_reads: Arc::clone(&name_reads),
2594                    ..Default::default()
2595                },
2596            )
2597            .unwrap()
2598            .build()
2599            .await
2600            .unwrap();
2601        let client = zbus::connection::Builder::address(address)
2602            .unwrap()
2603            .build()
2604            .await
2605            .unwrap();
2606        let action = ActionProxy::builder(&client)
2607            .destination(peer.unique_name().unwrap().clone())
2608            .unwrap()
2609            .path("/actions/stalled")
2610            .unwrap()
2611            .cache_properties(zbus::proxy::CacheProperties::No)
2612            .build()
2613            .await
2614            .unwrap();
2615
2616        let error = timeout(
2617            ACTION_QUERY_TIMEOUT + Duration::from_secs(1),
2618            read_actions(&action),
2619        )
2620        .await
2621        .expect("indexed reads must have an overall deadline")
2622        .unwrap_err();
2623        assert!(error.to_string().contains("5-second deadline"));
2624        assert_eq!(name_reads.load(Ordering::SeqCst), 1);
2625    }
2626
2627    fn app_children(children: &[(&str, &str)]) -> Vec<(String, Option<String>)> {
2628        children
2629            .iter()
2630            .map(|(role, name)| (role.to_string(), Some(name.to_string())))
2631            .collect()
2632    }
2633
2634    #[test]
2635    fn a_window_title_picks_one_of_several_app_windows() {
2636        let chromium = app_children(&[
2637            ("frame", "GitHub - Chromium"),
2638            ("frame", "PlanetScale - Chromium"),
2639            ("menu", ""),
2640        ]);
2641        assert_eq!(
2642            matching_window(&chromium, "PlanetScale - Chromium"),
2643            Some(1)
2644        );
2645        assert_eq!(
2646            matching_window(&chromium, "planetscale - chromium"),
2647            Some(1)
2648        );
2649        // A title substring, as a caller passes it.
2650        assert_eq!(matching_window(&chromium, "PlanetScale"), Some(1));
2651        // Matches every window: keep them all.
2652        assert_eq!(matching_window(&chromium, "Chromium"), None);
2653        assert_eq!(matching_window(&chromium, "Gmail"), None);
2654    }
2655
2656    #[test]
2657    fn a_decorated_compositor_title_picks_the_frame_it_decorates() {
2658        let chromium = app_children(&[
2659            ("frame", "GitHub - Chromium"),
2660            ("frame", "PlanetScale - Chromium"),
2661        ]);
2662        assert_eq!(
2663            matching_window(&chromium, "PlanetScale - Chromium (Profile 1)"),
2664            Some(1)
2665        );
2666        // Both names are decorated prefixes: the longest wins.
2667        let nested = app_children(&[("frame", "Docs"), ("frame", "Docs - Settings")]);
2668        assert_eq!(
2669            matching_window(&nested, "Docs - Settings (Profile 1)"),
2670            Some(1)
2671        );
2672        // A name inside the title but not its prefix is not a decoration.
2673        let generic = app_children(&[("frame", "Settings"), ("frame", "Mail")]);
2674        assert_eq!(
2675            matching_window(&generic, "Docs - Settings (Profile 1)"),
2676            None
2677        );
2678        assert_eq!(matching_window(&generic, "Mailbox"), None);
2679    }
2680
2681    #[test]
2682    fn an_exact_window_name_wins_over_a_substring_match() {
2683        let windows = app_children(&[("frame", "Docs"), ("frame", "Docs - Settings")]);
2684        assert_eq!(matching_window(&windows, "Docs"), Some(0));
2685    }
2686
2687    #[test]
2688    fn narrowing_keeps_popups_and_dialogs_beside_the_window() {
2689        let chromium = app_children(&[
2690            ("frame", "GitHub - Chromium"),
2691            ("frame", "PlanetScale - Chromium"),
2692            ("window", ""),
2693            ("dialog", "Open File"),
2694            ("menu", ""),
2695        ]);
2696        let chosen = matching_window(&chromium, "PlanetScale").unwrap();
2697        assert_eq!(
2698            kept_beside_window(&chromium, chosen),
2699            [false, true, true, true, true]
2700        );
2701    }
2702
2703    #[test]
2704    fn one_window_is_never_narrowed() {
2705        let single = app_children(&[("frame", "PlanetScale - Chromium"), ("menu", "")]);
2706        assert_eq!(matching_window(&single, "PlanetScale"), None);
2707    }
2708
2709    #[test]
2710    fn split_object_ref_id_separates_bus_name_and_path() {
2711        let (name, path) = split_object_ref_id(":1.42/org/a11y/atspi/accessible/7").unwrap();
2712
2713        assert_eq!(name, ":1.42");
2714        assert_eq!(path, "/org/a11y/atspi/accessible/7");
2715    }
2716
2717    #[test]
2718    fn select_action_index_uses_named_action() {
2719        let actions = vec![
2720            atspi::Action {
2721                name: "click".to_string(),
2722                description: "Clicks".to_string(),
2723                keybinding: String::new(),
2724            },
2725            atspi::Action {
2726                name: "show-menu".to_string(),
2727                description: "Shows menu".to_string(),
2728                keybinding: String::new(),
2729            },
2730        ];
2731
2732        assert_eq!(select_action_index(&actions, Some("show-menu")).unwrap(), 1);
2733    }
2734
2735    #[test]
2736    fn cached_action_name_is_revalidated_against_current_actions() {
2737        let mut actions = vec![atspi::Action {
2738            name: "show-menu".into(),
2739            description: "Click".into(),
2740            keybinding: String::new(),
2741        }];
2742        // Neither a stale index nor a matching description may invoke another action.
2743        assert!(select_named_action_index(&actions, "Click").is_err());
2744        actions.push(atspi::Action {
2745            name: "click".into(),
2746            description: String::new(),
2747            keybinding: String::new(),
2748        });
2749        assert_eq!(select_named_action_index(&actions, "Click").unwrap(), 1);
2750    }
2751
2752    #[test]
2753    fn select_action_index_defaults_to_secondary_when_available() {
2754        let actions = vec![
2755            atspi::Action {
2756                name: "click".to_string(),
2757                description: String::new(),
2758                keybinding: String::new(),
2759            },
2760            atspi::Action {
2761                name: "show-menu".to_string(),
2762                description: String::new(),
2763                keybinding: String::new(),
2764            },
2765        ];
2766
2767        assert_eq!(select_action_index(&actions, None).unwrap(), 1);
2768    }
2769
2770    #[test]
2771    fn state_labels_serialize_in_bit_order() {
2772        let labels = state_labels(StateSet::new(atspi::State::Focused | atspi::State::Checked));
2773
2774        assert_eq!(labels, vec!["checked".to_string(), "focused".to_string()]);
2775    }
2776
2777    #[test]
2778    fn default_snapshot_limits_cover_deep_gtk4_trees() {
2779        // Nautilus 50 places file-list cells below depth 20 and can expose
2780        // more than 850 raw nodes. Keep the defaults above that known shape.
2781        assert_eq!(snapshot_limits(None, None), (1_000, 32));
2782    }
2783
2784    #[test]
2785    fn app_name_needle_ignores_blank_values_and_normalizes_the_rest() {
2786        assert_eq!(app_name_needle(None), None);
2787        assert_eq!(app_name_needle(Some("")), None);
2788        assert_eq!(app_name_needle(Some("   ")), None);
2789        assert_eq!(
2790            app_name_needle(Some("Calculator")).as_deref(),
2791            Some("calculator")
2792        );
2793        assert_eq!(
2794            app_name_needle(Some(" :1.64/org/a11y/atspi/accessible/root ")).as_deref(),
2795            Some(":1.64/org/a11y/atspi/accessible/root")
2796        );
2797    }
2798
2799    #[test]
2800    fn requested_snapshot_limits_remain_bounded() {
2801        assert_eq!(snapshot_limits(Some(0), Some(0)), (1, 0));
2802        assert_eq!(snapshot_limits(Some(100_000), Some(128)), (10_000, 64));
2803    }
2804
2805    #[test]
2806    fn app_discovery_budget_is_independent_of_requested_tree_size() {
2807        assert_eq!(snapshot_child_read_budgets(1), (256, 2_048, 1));
2808    }
2809
2810    #[test]
2811    fn traversal_attempts_and_queue_share_one_work_budget() {
2812        let mut traversal = BoundedTraversal::new(4);
2813        traversal.enqueue([1]);
2814
2815        assert_eq!(traversal.pop(), Some(1));
2816        traversal.enqueue(2..=10_000);
2817        assert_eq!(traversal.queue, VecDeque::from([2, 3, 4]));
2818
2819        assert_eq!(traversal.pop(), Some(2));
2820        traversal.enqueue(5..=10_000);
2821        assert_eq!(traversal.queue, VecDeque::from([3, 4]));
2822        assert_eq!(traversal.pop(), Some(3));
2823        assert_eq!(traversal.pop(), Some(4));
2824        assert_eq!(traversal.pop(), None);
2825        assert_eq!(traversal.attempted, 4);
2826        assert!(
2827            traversal.truncated(),
2828            "dropped enqueue items must be reported"
2829        );
2830    }
2831
2832    #[test]
2833    fn traversal_that_drains_within_budget_is_not_truncated() {
2834        let mut traversal = BoundedTraversal::new(3);
2835        traversal.enqueue([1, 2, 3]);
2836        assert_eq!(traversal.pop(), Some(1));
2837        assert_eq!(traversal.pop(), Some(2));
2838        assert_eq!(traversal.pop(), Some(3));
2839        assert_eq!(traversal.pop(), None);
2840        assert!(
2841            !traversal.truncated(),
2842            "exactly max_items real nodes is complete"
2843        );
2844    }
2845
2846    #[test]
2847    fn enqueue_at_zero_capacity_marks_the_traversal_truncated() {
2848        let mut traversal = BoundedTraversal::new(2);
2849        traversal.enqueue([1, 2]);
2850        assert_eq!(traversal.pop(), Some(1));
2851        assert_eq!(traversal.pop(), Some(2));
2852        assert!(!traversal.truncated(), "nothing dropped yet");
2853        // Capacity is zero; the offered item is dropped, which is the only
2854        // path that can mark truncation.
2855        traversal.enqueue([3]);
2856        assert!(traversal.queue.is_empty());
2857        assert_eq!(traversal.pop(), None);
2858        assert!(traversal.truncated());
2859    }
2860
2861    #[test]
2862    fn child_count_is_clamped_before_indexed_reads() {
2863        assert_eq!(bounded_child_count(-1, 4), 0);
2864        assert_eq!(bounded_child_count(3, 4), 3);
2865        assert_eq!(bounded_child_count(i32::MAX, 4), 4);
2866    }
2867
2868    #[tokio::test]
2869    async fn indexed_child_reads_consume_attempts_even_when_one_fails() {
2870        let calls = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
2871        let mut remaining_attempts = 3;
2872        let batch = fetch_indexed_up_to(100, 10, &mut remaining_attempts, {
2873            let calls = calls.clone();
2874            move |index| {
2875                let calls = calls.clone();
2876                async move {
2877                    calls.lock().unwrap().push(index);
2878                    if index == 1 {
2879                        Err(())
2880                    } else {
2881                        Ok(index)
2882                    }
2883                }
2884            }
2885        })
2886        .await;
2887
2888        assert_eq!(batch.items, vec![0, 2]);
2889        assert_eq!(batch.attempted, 3);
2890        assert!(
2891            batch.incomplete,
2892            "100 reported children, 3 attempted: budget cut must be reported"
2893        );
2894        assert!(!batch.all_failed());
2895        assert_eq!(*calls.lock().unwrap(), vec![0, 1, 2]);
2896        assert_eq!(remaining_attempts, 0);
2897
2898        let no_children = fetch_indexed_up_to(100, 10, &mut remaining_attempts, |_| async {
2899            Ok::<_, ()>(99)
2900        })
2901        .await;
2902        assert!(no_children.items.is_empty());
2903        assert_eq!(no_children.attempted, 0);
2904        assert!(!no_children.all_failed());
2905
2906        let mut failed_attempts = 2;
2907        let all_failed =
2908            fetch_indexed_up_to(2, 2, &mut failed_attempts, |_| async { Err::<i32, _>(()) }).await;
2909        assert!(all_failed.all_failed());
2910    }
2911
2912    fn document() -> FocusedElementSummary {
2913        FocusedElementSummary {
2914            role: "document web".into(),
2915            name: Some("Synthetic editor host".into()),
2916            editable: false,
2917            states: vec!["focused".into()],
2918            is_terminal: false,
2919        }
2920    }
2921
2922    #[test]
2923    fn focused_document_does_not_end_the_search_before_contenteditable() {
2924        assert!(focus_is_container(&document()));
2925        let mut entry = document();
2926        entry.role = "entry".into();
2927        entry.states.push("editable".into());
2928        // Chromium need not implement EditableText for keyboard input.
2929        assert!(!entry.editable);
2930        assert!(!focus_is_container(&entry));
2931    }
2932
2933    #[test]
2934    fn incomplete_descendants_do_not_make_the_document_a_definitive_recipient() {
2935        assert!(matches!(
2936            finish_focus_probe(true, false, Some(document())),
2937            FocusProbe::Incomplete
2938        ));
2939        assert!(matches!(
2940            finish_focus_probe(false, false, Some(document())),
2941            FocusProbe::Found(_)
2942        ));
2943    }
2944
2945    #[test]
2946    fn opt_in_snapshot_budget_reaches_controls_after_embedded_browser_content() {
2947        let (limit, _) = snapshot_limits(Some(4_000), None);
2948        assert_eq!(limit, 4_000);
2949        let mut traversal = BoundedTraversal::new(limit);
2950        traversal.enqueue(0..3_000);
2951        let mut reached_editor = false;
2952        while let Some(node) = traversal.pop() {
2953            reached_editor |= node == 2_500;
2954        }
2955        assert!(reached_editor);
2956        assert!(!traversal.truncated());
2957        let (default, _) = snapshot_limits(None, None);
2958        assert_eq!(default, 1_000);
2959    }
2960
2961    #[test]
2962    fn narrowing_keeps_the_spent_budget_and_forgets_dropped_work() {
2963        let mut traversal = BoundedTraversal::new(4);
2964        traversal.enqueue(0..6);
2965        assert!(traversal.truncated());
2966        assert_eq!(traversal.pop(), Some(0));
2967        traversal.narrow();
2968        assert!(
2969            !traversal.truncated(),
2970            "work dropped outside the subtree no longer counts"
2971        );
2972        assert_eq!(traversal.pop(), None);
2973        traversal.enqueue([10, 11, 12, 13]);
2974        assert_eq!(traversal.pop(), Some(10));
2975        assert_eq!(traversal.pop(), Some(11));
2976        assert_eq!(traversal.pop(), Some(12));
2977        assert_eq!(
2978            traversal.pop(),
2979            None,
2980            "the budget spent before narrowing still counts"
2981        );
2982        assert!(traversal.truncated());
2983    }
2984}