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        proxy_ext::ProxyExt,
7    },
8    CoordType, ObjectRef, ObjectRefOwned, StateSet,
9};
10// Direct dependency (p2p feature off) — see Cargo.toml for why we bypass
11// atspi's "connection" re-export.
12use atspi_connection::AccessibilityConnection;
13use futures_util::{stream, StreamExt};
14use schemars::JsonSchema;
15use serde::Serialize;
16use std::{collections::VecDeque, future::Future, time::Duration};
17use tokio::time::timeout;
18use zbus::{
19    fdo::DBusProxy,
20    names::{BusName, UniqueName},
21    zvariant::ObjectPath,
22};
23
24#[derive(Debug, Clone, Serialize, JsonSchema)]
25pub struct AccessibleAppSummary {
26    pub object_ref: String,
27    pub name: Option<String>,
28    pub pid: Option<u32>,
29    pub role: String,
30    pub child_count: i32,
31    pub bounds: Option<Bounds>,
32}
33
34#[derive(Debug, Clone, Serialize, JsonSchema)]
35pub struct AccessibilityNode {
36    pub index: u32,
37    pub parent_index: Option<u32>,
38    pub depth: u32,
39    pub object_ref: String,
40    pub role: String,
41    pub name: Option<String>,
42    pub description: Option<String>,
43    pub child_count: i32,
44    pub bounds: Option<Bounds>,
45    pub states: Vec<String>,
46    pub actions: Vec<AccessibilityAction>,
47    pub value: Option<AccessibilityValue>,
48    pub text: Option<AccessibilityText>,
49    pub supports_editable_text: bool,
50}
51
52#[derive(Debug, Clone, Serialize, JsonSchema)]
53pub struct Bounds {
54    pub x: i32,
55    pub y: i32,
56    pub width: i32,
57    pub height: i32,
58}
59
60#[derive(Debug, Clone, Serialize, JsonSchema)]
61pub struct AccessibilityAction {
62    pub index: i32,
63    pub name: String,
64    pub description: String,
65    pub keybinding: String,
66}
67
68#[derive(Debug, Clone, Serialize, JsonSchema)]
69pub struct AccessibilityValue {
70    pub current: f64,
71    pub minimum: f64,
72    pub maximum: f64,
73    pub minimum_increment: f64,
74    pub text: Option<String>,
75}
76
77#[derive(Debug, Clone, Serialize, JsonSchema)]
78pub struct AccessibilityText {
79    pub character_count: i32,
80    pub caret_offset: Option<i32>,
81    pub content: Option<String>,
82    pub truncated: bool,
83    pub selections: Vec<AccessibilityTextSelection>,
84}
85
86#[derive(Debug, Clone, Serialize, JsonSchema)]
87pub struct AccessibilityTextSelection {
88    pub start_offset: i32,
89    pub end_offset: i32,
90}
91
92#[derive(Debug, Clone)]
93pub struct ActionInvocation {
94    pub action_index: i32,
95    pub action_name: Option<String>,
96    pub ok: bool,
97}
98
99#[derive(Debug, Clone)]
100pub enum ValueSetInvocation {
101    Numeric { value: f64 },
102    EditableText,
103}
104
105const MAX_TEXT_READBACK_CHARS: i32 = 4096;
106const MAX_TEXT_SELECTIONS: i32 = 8;
107const DEFAULT_SNAPSHOT_MAX_NODES: usize = 1_000;
108const HARD_SNAPSHOT_MAX_NODES: usize = 2_000;
109const DEFAULT_SNAPSHOT_MAX_DEPTH: u32 = 32;
110const HARD_SNAPSHOT_MAX_DEPTH: u32 = 64;
111const CHILD_READ_CONCURRENCY: usize = 16;
112const SNAPSHOT_TIMEOUT: Duration = Duration::from_secs(10);
113const MAX_DISCOVERY_ROOTS: usize = 256;
114const ROOT_MATCH_CHILD_LIMIT: usize = 8;
115const MAX_DISCOVERY_CHILD_READS: usize = MAX_DISCOVERY_ROOTS * ROOT_MATCH_CHILD_LIMIT;
116
117fn snapshot_child_read_budgets(max_nodes: usize) -> (usize, usize, usize) {
118    (MAX_DISCOVERY_ROOTS, MAX_DISCOVERY_CHILD_READS, max_nodes)
119}
120
121pub(crate) fn snapshot_limits(
122    requested_max_nodes: Option<usize>,
123    requested_max_depth: Option<u32>,
124) -> (usize, u32) {
125    (
126        requested_max_nodes
127            .unwrap_or(DEFAULT_SNAPSHOT_MAX_NODES)
128            .clamp(1, HARD_SNAPSHOT_MAX_NODES),
129        requested_max_depth
130            .unwrap_or(DEFAULT_SNAPSHOT_MAX_DEPTH)
131            .min(HARD_SNAPSHOT_MAX_DEPTH),
132    )
133}
134
135struct BoundedTraversal<T> {
136    queue: VecDeque<T>,
137    attempted: usize,
138    max_items: usize,
139    /// Set once an enqueue had to drop offered items for lack of capacity.
140    dropped: bool,
141}
142
143impl<T> BoundedTraversal<T> {
144    fn new(max_items: usize) -> Self {
145        Self {
146            queue: VecDeque::new(),
147            attempted: 0,
148            max_items,
149            dropped: false,
150        }
151    }
152
153    fn enqueue(&mut self, items: impl IntoIterator<Item = T>) {
154        let capacity = self.remaining_capacity();
155        let mut items = items.into_iter();
156        self.queue.extend(items.by_ref().take(capacity));
157        if items.next().is_some() {
158            self.dropped = true;
159        }
160    }
161
162    fn pop(&mut self) -> Option<T> {
163        if self.attempted >= self.max_items {
164            return None;
165        }
166        let item = self.queue.pop_front()?;
167        self.attempted += 1;
168        Some(item)
169    }
170
171    fn remaining_capacity(&self) -> usize {
172        self.max_items
173            .saturating_sub(self.attempted.saturating_add(self.queue.len()))
174    }
175
176    /// True when the budget stopped work that was actually offered. `enqueue`
177    /// is the only gate: it never exceeds `remaining_capacity`, so
178    /// `attempted + queue.len() <= max_items` always holds and the queue can
179    /// never be non-empty at the attempt cap. Dropped items are the whole story.
180    fn truncated(&self) -> bool {
181        self.dropped
182    }
183}
184
185fn bounded_child_count(reported: i32, limit: usize) -> usize {
186    usize::try_from(reported).unwrap_or_default().min(limit)
187}
188
189struct IndexedReadBatch<T> {
190    items: Vec<T>,
191    attempted: usize,
192    /// True when fewer children were attempted than the parent reported, because
193    /// the caller's limit or the shared read budget ran out. Failed reads do not
194    /// count; they were attempted.
195    incomplete: bool,
196}
197
198impl<T> IndexedReadBatch<T> {
199    fn all_failed(&self) -> bool {
200        self.attempted > 0 && self.items.is_empty()
201    }
202}
203
204async fn fetch_indexed_up_to<T, E, F, Fut>(
205    reported: i32,
206    limit: usize,
207    remaining_attempts: &mut usize,
208    fetch: F,
209) -> IndexedReadBatch<T>
210where
211    F: Fn(i32) -> Fut,
212    Fut: Future<Output = std::result::Result<T, E>>,
213{
214    let attempt_count = bounded_child_count(reported, limit).min(*remaining_attempts);
215    *remaining_attempts = (*remaining_attempts).saturating_sub(attempt_count);
216    let end_index = i32::try_from(attempt_count).unwrap_or(i32::MAX);
217
218    let items = stream::iter(0..end_index)
219        .map(fetch)
220        .buffered(CHILD_READ_CONCURRENCY)
221        .filter_map(|result| async move { result.ok() })
222        .collect()
223        .await;
224
225    IndexedReadBatch {
226        items,
227        attempted: attempt_count,
228        incomplete: attempt_count < usize::try_from(reported).unwrap_or_default(),
229    }
230}
231
232async fn children_up_to(
233    proxy: &AccessibleProxy<'_>,
234    limit: usize,
235    remaining_attempts: &mut usize,
236) -> zbus::Result<IndexedReadBatch<ObjectRefOwned>> {
237    if limit == 0 || *remaining_attempts == 0 {
238        // Budget already spent: stay I/O-free. `incomplete` is false here because
239        // nothing was asked of the parent; callers that already hold the node's
240        // child_count (snapshot_tree_inner) derive truncation from that instead.
241        return Ok(IndexedReadBatch {
242            items: Vec::new(),
243            attempted: 0,
244            incomplete: false,
245        });
246    }
247
248    let child_count = proxy.child_count().await?;
249    Ok(
250        fetch_indexed_up_to(child_count, limit, remaining_attempts, |index| {
251            proxy.get_child_at_index(index)
252        })
253        .await,
254    )
255}
256
257pub async fn list_accessible_apps(limit: usize) -> Result<Vec<AccessibleAppSummary>> {
258    let conn = connect().await?;
259    let mut remaining_child_reads = limit;
260    let roots = registry_children(&conn, limit, &mut remaining_child_reads).await?;
261    let dbus = DBusProxy::new(conn.connection()).await.ok();
262    let mut apps = Vec::new();
263
264    for object_ref in roots.into_iter().take(limit) {
265        if let Ok(proxy) = open_accessible(&conn, &object_ref).await {
266            apps.push(read_app_summary(&proxy, &object_ref, dbus.as_ref()).await);
267        }
268    }
269
270    Ok(apps)
271}
272
273#[derive(Debug, Clone)]
274pub(crate) struct AccessibilitySnapshot {
275    pub nodes: Vec<AccessibilityNode>,
276    /// True when registry roots were filtered to an app name and/or pid.
277    pub scoped: bool,
278    /// True when max_nodes, max_depth, or the child read budget stopped
279    /// traversal with unread elements left. Failed element reads do not count.
280    pub truncated: bool,
281}
282
283pub async fn snapshot_tree(
284    app_name_or_bundle_identifier: Option<&str>,
285    target_pid: Option<u32>,
286    max_nodes: usize,
287    max_depth: u32,
288) -> Result<Vec<AccessibilityNode>> {
289    Ok(snapshot_accessibility_tree(
290        app_name_or_bundle_identifier,
291        target_pid,
292        max_nodes,
293        max_depth,
294    )
295    .await?
296    .nodes)
297}
298
299pub(crate) async fn snapshot_accessibility_tree(
300    app_name_or_bundle_identifier: Option<&str>,
301    target_pid: Option<u32>,
302    max_nodes: usize,
303    max_depth: u32,
304) -> Result<AccessibilitySnapshot> {
305    let (max_nodes, max_depth) = snapshot_limits(Some(max_nodes), Some(max_depth));
306    timeout(
307        SNAPSHOT_TIMEOUT,
308        snapshot_tree_inner(
309            app_name_or_bundle_identifier,
310            target_pid,
311            max_nodes,
312            max_depth,
313        ),
314    )
315    .await
316    .context("AT-SPI snapshot exceeded its 10-second deadline")?
317}
318
319async fn snapshot_tree_inner(
320    app_name_or_bundle_identifier: Option<&str>,
321    target_pid: Option<u32>,
322    max_nodes: usize,
323    max_depth: u32,
324) -> Result<AccessibilitySnapshot> {
325    let conn = connect().await?;
326    // App discovery is bounded independently so a tiny requested tree still
327    // finds a target registered after the first accessibility root.
328    let (mut remaining_registry_reads, mut remaining_filter_reads, mut remaining_traversal_reads) =
329        snapshot_child_read_budgets(max_nodes);
330    let roots =
331        registry_children(&conn, MAX_DISCOVERY_ROOTS, &mut remaining_registry_reads).await?;
332    let selected_roots = select_roots(
333        &conn,
334        roots,
335        app_name_or_bundle_identifier,
336        target_pid,
337        &mut remaining_filter_reads,
338    )
339    .await;
340    let scoped = selected_roots.scoped;
341    let mut nodes = Vec::new();
342    let mut truncated = false;
343    let mut traversal = BoundedTraversal::new(max_nodes);
344
345    traversal.enqueue(
346        selected_roots
347            .roots
348            .into_iter()
349            .map(|object_ref| (object_ref, 0_u32, None)),
350    );
351
352    while let Some((object_ref, depth, parent_index)) = traversal.pop() {
353        let Ok(proxy) = open_accessible(&conn, &object_ref).await else {
354            continue;
355        };
356        let index = nodes.len() as u32;
357        let remaining = traversal.remaining_capacity();
358        let node = read_node(&proxy, &object_ref, index, parent_index, depth).await;
359        let child_refs = if depth < max_depth && remaining > 0 {
360            match children_up_to(&proxy, remaining, &mut remaining_traversal_reads).await {
361                Ok(batch) => {
362                    // A read-budget cut inside the fetch reports `incomplete`; an
363                    // already-exhausted budget returns the I/O-free empty batch, so
364                    // fall back to the child_count read_node already fetched.
365                    truncated |= batch.incomplete || (batch.attempted == 0 && node.child_count > 0);
366                    batch.items
367                }
368                Err(_) => Vec::new(),
369            }
370        } else {
371            // Depth or node cap reached: any child this node reports is unread.
372            truncated |= node.child_count > 0;
373            Vec::new()
374        };
375
376        nodes.push(node);
377
378        traversal.enqueue(
379            child_refs
380                .into_iter()
381                .map(|child| (child, depth + 1, Some(index))),
382        );
383    }
384    truncated |= traversal.truncated();
385
386    Ok(AccessibilitySnapshot {
387        nodes,
388        scoped,
389        truncated,
390    })
391}
392
393/// Compact description of the AT-SPI element that currently holds keyboard
394/// focus, used as post-input feedback for type_text/press_key.
395#[derive(Debug, Clone, Serialize, JsonSchema)]
396pub struct FocusedElementSummary {
397    pub role: String,
398    pub name: Option<String>,
399    pub editable: bool,
400    pub states: Vec<String>,
401    /// AT-SPI `Role::Terminal`, read from the role enum rather than the
402    /// localized role name. Internal routing only; not part of the output.
403    #[serde(skip)]
404    #[schemars(skip)]
405    pub is_terminal: bool,
406}
407
408const FOCUS_PROBE_MAX_NODES: usize = 400;
409const FOCUS_PROBE_MAX_DEPTH: u32 = 16;
410
411/// Find the element with the `focused` state inside the target app (by pid) or
412/// across all apps. Best-effort and bounded: returns Ok(None) when no focused
413/// element is reachable through AT-SPI (common for apps without accessibility
414/// support, e.g. Electron without --force-renderer-accessibility).
415/// Outcome of the bounded focused-element search.
416#[derive(Debug, Clone)]
417pub(crate) enum FocusProbe {
418    Found(FocusedElementSummary),
419    /// The search covered the target's whole tree and nothing holds focus.
420    NoneFocused,
421    /// A node, depth, or read limit stopped the search before it finished, so
422    /// the focused element may exist past the limit.
423    Incomplete,
424    /// A pid was given but no AT-SPI app belongs to it (xterm, or Electron
425    /// without --force-renderer-accessibility), so focus cannot be read.
426    NoAccessibleApp,
427}
428
429/// Focused element in the app owning `target_pid`, or across all apps when no
430/// pid is given. With a pid, only that app's tree is searched: falling back to
431/// every other app would report some unrelated widget as the focus.
432pub(crate) async fn probe_focused_element(target_pid: Option<u32>) -> Result<FocusProbe> {
433    focused_element_probe(target_pid, target_pid.is_some()).await
434}
435
436/// The focused element in the app that owns `target_pid`, for callers that
437/// only need an answer when one exists. Every non-`Found` probe result maps to
438/// `None`; see [`probe_focused_element`] for the distinctions.
439pub(crate) async fn focused_element_summary_in_app(
440    target_pid: u32,
441) -> Result<Option<FocusedElementSummary>> {
442    Ok(match focused_element_probe(Some(target_pid), true).await? {
443        FocusProbe::Found(summary) => Some(summary),
444        _ => None,
445    })
446}
447
448async fn focused_element_probe(
449    target_pid: Option<u32>,
450    require_scoped: bool,
451) -> Result<FocusProbe> {
452    let conn = connect().await?;
453    let mut remaining_registry_reads = MAX_DISCOVERY_ROOTS;
454    let roots =
455        registry_children(&conn, MAX_DISCOVERY_ROOTS, &mut remaining_registry_reads).await?;
456    let mut remaining_filter_reads = MAX_DISCOVERY_CHILD_READS;
457    let selected_roots =
458        select_roots(&conn, roots, None, target_pid, &mut remaining_filter_reads).await;
459    if require_scoped && !selected_roots.scoped {
460        return Ok(FocusProbe::NoAccessibleApp);
461    }
462    let mut traversal = BoundedTraversal::new(FOCUS_PROBE_MAX_NODES);
463    let mut remaining_traversal_reads = FOCUS_PROBE_MAX_NODES;
464    let mut incomplete = false;
465
466    traversal.enqueue(
467        selected_roots
468            .roots
469            .into_iter()
470            .map(|object_ref| (object_ref, 0_u32)),
471    );
472
473    while let Some((object_ref, depth)) = traversal.pop() {
474        let Ok(proxy) = open_accessible(&conn, &object_ref).await else {
475            continue;
476        };
477        let Ok(state) = proxy.get_state().await else {
478            continue;
479        };
480        if state.contains(atspi::State::Focused) {
481            let proxies = proxy.proxies().await.ok();
482            let is_terminal = matches!(proxy.get_role().await, Ok(atspi::Role::Terminal));
483            return Ok(FocusProbe::Found(FocusedElementSummary {
484                role: role_name(&proxy).await,
485                name: optional_string(proxy.name().await.ok()),
486                editable: supports_editable_text(proxies.as_ref()).await,
487                states: state_labels(state),
488                is_terminal,
489            }));
490        }
491        let remaining = traversal.remaining_capacity();
492        if depth < FOCUS_PROBE_MAX_DEPTH && remaining > 0 {
493            if let Ok(batch) =
494                children_up_to(&proxy, remaining, &mut remaining_traversal_reads).await
495            {
496                incomplete |= batch.incomplete;
497                // An exhausted shared read budget takes children_up_to's
498                // I/O-free path (attempted 0, incomplete false), so the node's
499                // own child count has to say whether children went unread.
500                // With budget left, attempted 0 just means a leaf: no read.
501                if batch.attempted == 0 && remaining_traversal_reads == 0 && !incomplete {
502                    incomplete = proxy.child_count().await.is_ok_and(|count| count > 0);
503                }
504                traversal.enqueue(batch.items.into_iter().map(|child| (child, depth + 1)));
505            }
506        } else if !incomplete {
507            // Depth or node cap: any child this node reports goes unread. One
508            // child-count read settles it, and only until the first cut is seen.
509            incomplete = proxy.child_count().await.is_ok_and(|count| count > 0);
510        }
511    }
512    if incomplete || traversal.truncated() {
513        return Ok(FocusProbe::Incomplete);
514    }
515
516    Ok(FocusProbe::NoneFocused)
517}
518
519pub async fn perform_action(
520    object_ref_id: &str,
521    requested_action: Option<&str>,
522) -> Result<ActionInvocation> {
523    perform_action_inner(object_ref_id, requested_action, false).await
524}
525
526pub(crate) async fn perform_named_action(
527    object_ref_id: &str,
528    name: &str,
529) -> Result<ActionInvocation> {
530    perform_action_inner(object_ref_id, Some(name), true).await
531}
532
533async fn perform_action_inner(
534    object_ref_id: &str,
535    requested_action: Option<&str>,
536    name_only: bool,
537) -> Result<ActionInvocation> {
538    let conn = connect().await?;
539    let object_ref = object_ref_from_id(object_ref_id)?;
540    let proxy = open_accessible(&conn, &object_ref)
541        .await
542        .with_context(|| format!("failed to open AT-SPI object {object_ref_id}"))?;
543    let action = proxy
544        .proxies()
545        .await?
546        .action()
547        .await
548        .context("element does not expose the AT-SPI Action interface")?;
549    let actions = action.get_actions().await.unwrap_or_default();
550    let action_index = if name_only {
551        select_named_action_index(&actions, requested_action.unwrap_or_default())?
552    } else {
553        select_action_index(&actions, requested_action)?
554    };
555    let action_name = actions
556        .get(action_index as usize)
557        .map(|action| action.name.clone());
558    let ok = action
559        .do_action(action_index)
560        .await
561        .with_context(|| format!("failed to invoke AT-SPI action {action_index}"))?;
562
563    Ok(ActionInvocation {
564        action_index,
565        action_name,
566        ok,
567    })
568}
569
570pub async fn set_element_value(object_ref_id: &str, value: &str) -> Result<ValueSetInvocation> {
571    let conn = connect().await?;
572    let object_ref = object_ref_from_id(object_ref_id)?;
573    let proxy = open_accessible(&conn, &object_ref)
574        .await
575        .with_context(|| format!("failed to open AT-SPI object {object_ref_id}"))?;
576    let proxies = proxy.proxies().await?;
577
578    if let Ok(numeric_value) = value.parse::<f64>() {
579        if let Ok(value_proxy) = proxies.value().await {
580            value_proxy
581                .set_current_value(numeric_value)
582                .await
583                .with_context(|| {
584                    format!("failed to set AT-SPI numeric value to {numeric_value}")
585                })?;
586            return Ok(ValueSetInvocation::Numeric {
587                value: numeric_value,
588            });
589        }
590    }
591
592    if let Ok(editable_text) = proxies.editable_text().await {
593        let ok = editable_text
594            .set_text_contents(value)
595            .await
596            .context("failed to set AT-SPI editable text contents")?;
597        if ok {
598            return Ok(ValueSetInvocation::EditableText);
599        }
600        return Err(anyhow!("AT-SPI EditableText rejected the new contents"));
601    }
602
603    if value.parse::<f64>().is_err() && proxies.value().await.is_ok() {
604        return Err(anyhow!(
605            "element exposes the AT-SPI Value interface, but the requested value is not numeric"
606        ));
607    }
608
609    Err(anyhow!(
610        "element does not expose AT-SPI Value or EditableText interfaces"
611    ))
612}
613
614async fn connect() -> Result<AccessibilityConnection> {
615    hydrate_session_bus_env();
616    AccessibilityConnection::new()
617        .await
618        .context("failed to connect to AT-SPI bus")
619}
620
621/// Open an `AccessibleProxy` for an object on the a11y bus.
622///
623/// We deliberately avoid `AccessibilityConnection::object_as_accessible` (the
624/// `P2P` trait). For apps that advertise a peer-to-peer bus address it routes
625/// reads over that socket, but for apps that don't (notably GTK4 apps such as
626/// Nautilus / Text Editor / baobab, which don't implement the legacy
627/// `GetApplicationBusAddress`) it falls back to a proxy built with only a path
628/// and *no destination*. On the shared a11y bus that proxy can't address the
629/// app and every call fails with `ServiceUnknown`, which surfaces as an empty
630/// tree (`role: "unknown"`, `child_count: 0`). `as_accessible_proxy` always
631/// pins the destination to the object's bus name, so it works for every app
632/// regardless of P2P support. See issue #31.
633async fn open_accessible<'r>(
634    conn: &AccessibilityConnection,
635    object_ref: &'r ObjectRefOwned,
636) -> Result<AccessibleProxy<'r>, atspi::AtspiError> {
637    object_ref.as_accessible_proxy(conn.connection()).await
638}
639
640async fn registry_children(
641    conn: &AccessibilityConnection,
642    limit: usize,
643    remaining_child_reads: &mut usize,
644) -> Result<Vec<ObjectRefOwned>> {
645    let root = conn
646        .root_accessible_on_registry()
647        .await
648        .context("failed to open AT-SPI registry root")?;
649    let batch = children_up_to(&root, limit, remaining_child_reads)
650        .await
651        .context("failed to read AT-SPI registry children")?;
652    if batch.all_failed() {
653        return Err(anyhow!(
654            "AT-SPI registry reported children, but every indexed child read failed"
655        ));
656    }
657    Ok(batch.items)
658}
659
660struct SelectedRoots {
661    roots: Vec<ObjectRefOwned>,
662    scoped: bool,
663}
664
665/// Normalized app-name filter, or `None` when the caller passed nothing usable.
666/// A `None` needle with no pid match means the snapshot covers the whole desktop.
667fn app_name_needle(app_name_or_bundle_identifier: Option<&str>) -> Option<String> {
668    app_name_or_bundle_identifier
669        .map(str::trim)
670        .filter(|value| !value.is_empty())
671        .map(|value| value.to_ascii_lowercase())
672}
673
674async fn select_roots(
675    conn: &AccessibilityConnection,
676    roots: Vec<ObjectRefOwned>,
677    app_name_or_bundle_identifier: Option<&str>,
678    target_pid: Option<u32>,
679    remaining_child_reads: &mut usize,
680) -> SelectedRoots {
681    let needle = app_name_needle(app_name_or_bundle_identifier);
682    let dbus = DBusProxy::new(conn.connection()).await.ok();
683    let mut remaining = roots;
684
685    if let Some(target_pid) = target_pid {
686        let mut pid_and_filter_matches = Vec::new();
687        let mut pid_matches = Vec::new();
688        let mut non_pid_matches = Vec::new();
689
690        for object_ref in remaining {
691            if object_ref_pid(dbus.as_ref(), &object_ref).await == Some(target_pid) {
692                if let Some(needle) = needle.as_deref() {
693                    if root_matches(conn, &object_ref, needle, remaining_child_reads).await {
694                        pid_and_filter_matches.push(object_ref);
695                    } else {
696                        pid_matches.push(object_ref);
697                    }
698                } else {
699                    pid_matches.push(object_ref);
700                }
701            } else {
702                non_pid_matches.push(object_ref);
703            }
704        }
705
706        if !pid_and_filter_matches.is_empty() {
707            return SelectedRoots {
708                roots: pid_and_filter_matches,
709                scoped: true,
710            };
711        }
712        if !pid_matches.is_empty() {
713            return SelectedRoots {
714                roots: pid_matches,
715                scoped: true,
716            };
717        }
718
719        remaining = non_pid_matches;
720    }
721
722    let Some(needle) = needle.as_deref() else {
723        return SelectedRoots {
724            roots: remaining,
725            scoped: false,
726        };
727    };
728
729    let mut selected = Vec::new();
730    for object_ref in remaining {
731        if root_matches(conn, &object_ref, needle, remaining_child_reads).await {
732            selected.push(object_ref);
733        }
734    }
735
736    SelectedRoots {
737        roots: selected,
738        scoped: true,
739    }
740}
741
742async fn root_matches(
743    conn: &AccessibilityConnection,
744    object_ref: &ObjectRefOwned,
745    needle: &str,
746    remaining_child_reads: &mut usize,
747) -> bool {
748    let Ok(proxy) = open_accessible(conn, object_ref).await else {
749        return object_ref_id(object_ref)
750            .to_ascii_lowercase()
751            .contains(needle);
752    };
753
754    if proxy_matches(&proxy, object_ref, needle).await {
755        return true;
756    }
757
758    for child_ref in children_up_to(&proxy, ROOT_MATCH_CHILD_LIMIT, remaining_child_reads)
759        .await
760        .map(|batch| batch.items)
761        .unwrap_or_default()
762    {
763        let Ok(child_proxy) = open_accessible(conn, &child_ref).await else {
764            continue;
765        };
766        if proxy_matches(&child_proxy, &child_ref, needle).await {
767            return true;
768        }
769    }
770
771    false
772}
773
774async fn proxy_matches(
775    proxy: &AccessibleProxy<'_>,
776    object_ref: &ObjectRefOwned,
777    needle: &str,
778) -> bool {
779    let name = proxy.name().await.unwrap_or_default();
780    let role = proxy.get_role_name().await.unwrap_or_default();
781    format!("{} {} {}", object_ref_id(object_ref), name, role)
782        .to_ascii_lowercase()
783        .contains(needle)
784}
785
786async fn read_app_summary(
787    proxy: &AccessibleProxy<'_>,
788    object_ref: &ObjectRefOwned,
789    dbus: Option<&DBusProxy<'_>>,
790) -> AccessibleAppSummary {
791    AccessibleAppSummary {
792        object_ref: object_ref_id(object_ref),
793        name: optional_string(proxy.name().await.ok()),
794        pid: object_ref_pid(dbus, object_ref).await,
795        role: role_name(proxy).await,
796        child_count: proxy.child_count().await.unwrap_or_default(),
797        bounds: bounds(proxy).await,
798    }
799}
800
801async fn read_node(
802    proxy: &AccessibleProxy<'_>,
803    object_ref: &ObjectRefOwned,
804    index: u32,
805    parent_index: Option<u32>,
806    depth: u32,
807) -> AccessibilityNode {
808    let proxies = proxy.proxies().await.ok();
809
810    AccessibilityNode {
811        index,
812        parent_index,
813        depth,
814        object_ref: object_ref_id(object_ref),
815        role: role_name(proxy).await,
816        name: optional_string(proxy.name().await.ok()),
817        description: optional_string(proxy.description().await.ok()),
818        child_count: proxy.child_count().await.unwrap_or_default(),
819        bounds: bounds_from_proxies(proxies.as_ref(), proxy).await,
820        states: states_from_proxy(proxy).await,
821        actions: actions_from_proxies(proxies.as_ref()).await,
822        value: value_from_proxies(proxies.as_ref()).await,
823        text: text_from_proxies(proxies.as_ref()).await,
824        supports_editable_text: supports_editable_text(proxies.as_ref()).await,
825    }
826}
827
828async fn role_name(proxy: &AccessibleProxy<'_>) -> String {
829    if let Ok(role) = proxy.get_role_name().await {
830        if !role.trim().is_empty() {
831            return role;
832        }
833    }
834    proxy
835        .get_role()
836        .await
837        .map(|role| format!("{role:?}"))
838        .unwrap_or_else(|_| "unknown".to_string())
839}
840
841async fn bounds(proxy: &AccessibleProxy<'_>) -> Option<Bounds> {
842    bounds_from_proxies(proxy.proxies().await.ok().as_ref(), proxy).await
843}
844
845/// Pid of the process that owns an AT-SPI object ref (`:bus/path`), from the
846/// accessibility bus. `None` when the owner is gone or the bus cannot say.
847pub(crate) async fn object_ref_owner_pid(object_ref_id: &str) -> Result<Option<u32>> {
848    let object_ref = object_ref_from_id(object_ref_id)?;
849    let conn = connect().await?;
850    let dbus = DBusProxy::new(conn.connection()).await.ok();
851    Ok(object_ref_pid(dbus.as_ref(), &object_ref).await)
852}
853
854async fn object_ref_pid(dbus: Option<&DBusProxy<'_>>, object_ref: &ObjectRefOwned) -> Option<u32> {
855    let dbus = dbus?;
856    let bus_name = BusName::try_from(object_ref.name_as_str()?.to_string()).ok()?;
857    dbus.get_connection_unix_process_id(bus_name).await.ok()
858}
859
860async fn bounds_from_proxies(
861    proxies: Option<&atspi::proxy::proxy_ext::Proxies<'_>>,
862    proxy: &AccessibleProxy<'_>,
863) -> Option<Bounds> {
864    let owned_proxies;
865    let proxies = if let Some(proxies) = proxies {
866        proxies
867    } else {
868        owned_proxies = proxy.proxies().await.ok()?;
869        &owned_proxies
870    };
871    let component = proxies.component().await.ok()?;
872    let (x, y, width, height) = component.get_extents(CoordType::Screen).await.ok()?;
873    normalize_bounds(Bounds {
874        x,
875        y,
876        width,
877        height,
878    })
879}
880
881fn normalize_bounds(bounds: Bounds) -> Option<Bounds> {
882    if bounds.width <= 0 || bounds.height <= 0 {
883        return None;
884    }
885    if bounds.x <= i32::MIN / 2 || bounds.y <= i32::MIN / 2 {
886        return None;
887    }
888    Some(bounds)
889}
890
891async fn actions_from_proxies(
892    proxies: Option<&atspi::proxy::proxy_ext::Proxies<'_>>,
893) -> Vec<AccessibilityAction> {
894    let Some(proxies) = proxies else {
895        return Vec::new();
896    };
897    let Ok(action_proxy) = proxies.action().await else {
898        return Vec::new();
899    };
900
901    action_proxy
902        .get_actions()
903        .await
904        .unwrap_or_default()
905        .into_iter()
906        .enumerate()
907        .map(|(index, action)| AccessibilityAction {
908            index: index as i32,
909            name: action.name,
910            description: action.description,
911            keybinding: action.keybinding,
912        })
913        .collect()
914}
915
916async fn states_from_proxy(proxy: &AccessibleProxy<'_>) -> Vec<String> {
917    proxy
918        .get_state()
919        .await
920        .map(state_labels)
921        .unwrap_or_default()
922}
923
924async fn value_from_proxies(
925    proxies: Option<&atspi::proxy::proxy_ext::Proxies<'_>>,
926) -> Option<AccessibilityValue> {
927    let value = proxies?.value().await.ok()?;
928    Some(AccessibilityValue {
929        current: value.current_value().await.ok()?,
930        minimum: value.minimum_value().await.ok()?,
931        maximum: value.maximum_value().await.ok()?,
932        minimum_increment: value.minimum_increment().await.ok()?,
933        text: optional_string(value.text().await.ok()),
934    })
935}
936
937async fn text_from_proxies(
938    proxies: Option<&atspi::proxy::proxy_ext::Proxies<'_>>,
939) -> Option<AccessibilityText> {
940    let text = proxies?.text().await.ok()?;
941    let character_count = text.character_count().await.ok()?.max(0);
942    let caret_offset = text.caret_offset().await.ok();
943    let capped_count = character_count.min(MAX_TEXT_READBACK_CHARS);
944    let content = if capped_count > 0 {
945        optional_string(text.get_text(0, capped_count).await.ok())
946    } else {
947        None
948    };
949    let selection_count = text
950        .get_nselections()
951        .await
952        .unwrap_or_default()
953        .clamp(0, MAX_TEXT_SELECTIONS);
954    let mut selections = Vec::new();
955    for index in 0..selection_count {
956        if let Ok((start_offset, end_offset)) = text.get_selection(index).await {
957            selections.push(AccessibilityTextSelection {
958                start_offset,
959                end_offset,
960            });
961        }
962    }
963
964    Some(AccessibilityText {
965        character_count,
966        caret_offset,
967        content,
968        truncated: character_count > MAX_TEXT_READBACK_CHARS,
969        selections,
970    })
971}
972
973async fn supports_editable_text(proxies: Option<&atspi::proxy::proxy_ext::Proxies<'_>>) -> bool {
974    let Some(proxies) = proxies else {
975        return false;
976    };
977    proxies.editable_text().await.is_ok()
978}
979
980fn state_labels(state_set: StateSet) -> Vec<String> {
981    state_set.iter().map(|state| state.to_string()).collect()
982}
983
984fn select_action_index(actions: &[atspi::Action], requested_action: Option<&str>) -> Result<i32> {
985    if actions.is_empty() {
986        return Err(anyhow!("element exposes no AT-SPI actions"));
987    }
988
989    if let Some(requested_action) = requested_action
990        .map(str::trim)
991        .filter(|value| !value.is_empty())
992    {
993        let requested_action = requested_action.to_ascii_lowercase();
994        if let Some((index, _)) = actions.iter().enumerate().find(|(_, action)| {
995            action.name.to_ascii_lowercase() == requested_action
996                || action.description.to_ascii_lowercase() == requested_action
997        }) {
998            return Ok(index as i32);
999        }
1000
1001        if let Ok(index) = requested_action.parse::<usize>() {
1002            if index < actions.len() {
1003                return Ok(index as i32);
1004            }
1005        }
1006
1007        return Err(anyhow!(
1008            "requested AT-SPI action was not found; available actions: {}",
1009            actions
1010                .iter()
1011                .map(|action| action.name.as_str())
1012                .collect::<Vec<_>>()
1013                .join(", ")
1014        ));
1015    }
1016
1017    Ok(if actions.len() > 1 { 1 } else { 0 })
1018}
1019
1020fn select_named_action_index(actions: &[atspi::Action], name: &str) -> Result<i32> {
1021    actions
1022        .iter()
1023        .position(|action| action.name.eq_ignore_ascii_case(name))
1024        .map(|index| index as i32)
1025        .ok_or_else(|| {
1026            anyhow!("cached AT-SPI action name is no longer available; refresh get_app_state")
1027        })
1028}
1029
1030fn optional_string(value: Option<String>) -> Option<String> {
1031    value
1032        .map(|value| value.trim().to_string())
1033        .filter(|value| !value.is_empty())
1034}
1035
1036fn object_ref_from_id(object_ref_id: &str) -> Result<ObjectRefOwned> {
1037    let (name, path) = split_object_ref_id(object_ref_id)?;
1038    let name = UniqueName::try_from(name.to_string())
1039        .with_context(|| format!("invalid AT-SPI bus name in object ref {object_ref_id}"))?;
1040    let path = ObjectPath::try_from(path.to_string())
1041        .with_context(|| format!("invalid AT-SPI object path in object ref {object_ref_id}"))?;
1042    Ok(ObjectRef::new_owned(name, path))
1043}
1044
1045fn split_object_ref_id(object_ref_id: &str) -> Result<(&str, &str)> {
1046    let Some(path_start) = object_ref_id.find('/') else {
1047        return Err(anyhow!(
1048            "invalid AT-SPI object ref '{object_ref_id}'; expected ':bus/path'"
1049        ));
1050    };
1051    let (name, path) = object_ref_id.split_at(path_start);
1052    if name.is_empty() || path.is_empty() {
1053        return Err(anyhow!(
1054            "invalid AT-SPI object ref '{object_ref_id}'; expected ':bus/path'"
1055        ));
1056    }
1057    Ok((name, path))
1058}
1059
1060fn object_ref_id(object_ref: &ObjectRefOwned) -> String {
1061    format!(
1062        "{}{}",
1063        object_ref.name_as_str().unwrap_or(""),
1064        object_ref.path_as_str()
1065    )
1066}
1067
1068#[cfg(test)]
1069mod tests {
1070    use super::*;
1071
1072    #[test]
1073    fn split_object_ref_id_separates_bus_name_and_path() {
1074        let (name, path) = split_object_ref_id(":1.42/org/a11y/atspi/accessible/7").unwrap();
1075
1076        assert_eq!(name, ":1.42");
1077        assert_eq!(path, "/org/a11y/atspi/accessible/7");
1078    }
1079
1080    #[test]
1081    fn select_action_index_uses_named_action() {
1082        let actions = vec![
1083            atspi::Action {
1084                name: "click".to_string(),
1085                description: "Clicks".to_string(),
1086                keybinding: String::new(),
1087            },
1088            atspi::Action {
1089                name: "show-menu".to_string(),
1090                description: "Shows menu".to_string(),
1091                keybinding: String::new(),
1092            },
1093        ];
1094
1095        assert_eq!(select_action_index(&actions, Some("show-menu")).unwrap(), 1);
1096    }
1097
1098    #[test]
1099    fn cached_action_name_is_revalidated_against_current_actions() {
1100        let mut actions = vec![atspi::Action {
1101            name: "show-menu".into(),
1102            description: "Click".into(),
1103            keybinding: String::new(),
1104        }];
1105        // Neither a stale index nor a matching description may invoke another action.
1106        assert!(select_named_action_index(&actions, "Click").is_err());
1107        actions.push(atspi::Action {
1108            name: "click".into(),
1109            description: String::new(),
1110            keybinding: String::new(),
1111        });
1112        assert_eq!(select_named_action_index(&actions, "Click").unwrap(), 1);
1113    }
1114
1115    #[test]
1116    fn select_action_index_defaults_to_secondary_when_available() {
1117        let actions = vec![
1118            atspi::Action {
1119                name: "click".to_string(),
1120                description: String::new(),
1121                keybinding: String::new(),
1122            },
1123            atspi::Action {
1124                name: "show-menu".to_string(),
1125                description: String::new(),
1126                keybinding: String::new(),
1127            },
1128        ];
1129
1130        assert_eq!(select_action_index(&actions, None).unwrap(), 1);
1131    }
1132
1133    #[test]
1134    fn state_labels_serialize_in_bit_order() {
1135        let labels = state_labels(StateSet::new(atspi::State::Focused | atspi::State::Checked));
1136
1137        assert_eq!(labels, vec!["checked".to_string(), "focused".to_string()]);
1138    }
1139
1140    #[test]
1141    fn default_snapshot_limits_cover_deep_gtk4_trees() {
1142        // Nautilus 50 places file-list cells below depth 20 and can expose
1143        // more than 850 raw nodes. Keep the defaults above that known shape.
1144        assert_eq!(snapshot_limits(None, None), (1_000, 32));
1145    }
1146
1147    #[test]
1148    fn app_name_needle_ignores_blank_values_and_normalizes_the_rest() {
1149        assert_eq!(app_name_needle(None), None);
1150        assert_eq!(app_name_needle(Some("")), None);
1151        assert_eq!(app_name_needle(Some("   ")), None);
1152        assert_eq!(
1153            app_name_needle(Some("Calculator")).as_deref(),
1154            Some("calculator")
1155        );
1156        assert_eq!(
1157            app_name_needle(Some(" :1.64/org/a11y/atspi/accessible/root ")).as_deref(),
1158            Some(":1.64/org/a11y/atspi/accessible/root")
1159        );
1160    }
1161
1162    #[test]
1163    fn requested_snapshot_limits_remain_bounded() {
1164        assert_eq!(snapshot_limits(Some(0), Some(0)), (1, 0));
1165        assert_eq!(snapshot_limits(Some(10_000), Some(128)), (2_000, 64));
1166    }
1167
1168    #[test]
1169    fn app_discovery_budget_is_independent_of_requested_tree_size() {
1170        assert_eq!(snapshot_child_read_budgets(1), (256, 2_048, 1));
1171    }
1172
1173    #[test]
1174    fn traversal_attempts_and_queue_share_one_work_budget() {
1175        let mut traversal = BoundedTraversal::new(4);
1176        traversal.enqueue([1]);
1177
1178        assert_eq!(traversal.pop(), Some(1));
1179        traversal.enqueue(2..=10_000);
1180        assert_eq!(traversal.queue, VecDeque::from([2, 3, 4]));
1181
1182        assert_eq!(traversal.pop(), Some(2));
1183        traversal.enqueue(5..=10_000);
1184        assert_eq!(traversal.queue, VecDeque::from([3, 4]));
1185        assert_eq!(traversal.pop(), Some(3));
1186        assert_eq!(traversal.pop(), Some(4));
1187        assert_eq!(traversal.pop(), None);
1188        assert_eq!(traversal.attempted, 4);
1189        assert!(
1190            traversal.truncated(),
1191            "dropped enqueue items must be reported"
1192        );
1193    }
1194
1195    #[test]
1196    fn traversal_that_drains_within_budget_is_not_truncated() {
1197        let mut traversal = BoundedTraversal::new(3);
1198        traversal.enqueue([1, 2, 3]);
1199        assert_eq!(traversal.pop(), Some(1));
1200        assert_eq!(traversal.pop(), Some(2));
1201        assert_eq!(traversal.pop(), Some(3));
1202        assert_eq!(traversal.pop(), None);
1203        assert!(
1204            !traversal.truncated(),
1205            "exactly max_items real nodes is complete"
1206        );
1207    }
1208
1209    #[test]
1210    fn enqueue_at_zero_capacity_marks_the_traversal_truncated() {
1211        let mut traversal = BoundedTraversal::new(2);
1212        traversal.enqueue([1, 2]);
1213        assert_eq!(traversal.pop(), Some(1));
1214        assert_eq!(traversal.pop(), Some(2));
1215        assert!(!traversal.truncated(), "nothing dropped yet");
1216        // Capacity is zero; the offered item is dropped, which is the only
1217        // path that can mark truncation.
1218        traversal.enqueue([3]);
1219        assert!(traversal.queue.is_empty());
1220        assert_eq!(traversal.pop(), None);
1221        assert!(traversal.truncated());
1222    }
1223
1224    #[test]
1225    fn child_count_is_clamped_before_indexed_reads() {
1226        assert_eq!(bounded_child_count(-1, 4), 0);
1227        assert_eq!(bounded_child_count(3, 4), 3);
1228        assert_eq!(bounded_child_count(i32::MAX, 4), 4);
1229    }
1230
1231    #[tokio::test]
1232    async fn indexed_child_reads_consume_attempts_even_when_one_fails() {
1233        let calls = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
1234        let mut remaining_attempts = 3;
1235        let batch = fetch_indexed_up_to(100, 10, &mut remaining_attempts, {
1236            let calls = calls.clone();
1237            move |index| {
1238                let calls = calls.clone();
1239                async move {
1240                    calls.lock().unwrap().push(index);
1241                    if index == 1 {
1242                        Err(())
1243                    } else {
1244                        Ok(index)
1245                    }
1246                }
1247            }
1248        })
1249        .await;
1250
1251        assert_eq!(batch.items, vec![0, 2]);
1252        assert_eq!(batch.attempted, 3);
1253        assert!(
1254            batch.incomplete,
1255            "100 reported children, 3 attempted: budget cut must be reported"
1256        );
1257        assert!(!batch.all_failed());
1258        assert_eq!(*calls.lock().unwrap(), vec![0, 1, 2]);
1259        assert_eq!(remaining_attempts, 0);
1260
1261        let no_children = fetch_indexed_up_to(100, 10, &mut remaining_attempts, |_| async {
1262            Ok::<_, ()>(99)
1263        })
1264        .await;
1265        assert!(no_children.items.is_empty());
1266        assert_eq!(no_children.attempted, 0);
1267        assert!(!no_children.all_failed());
1268
1269        let mut failed_attempts = 2;
1270        let all_failed =
1271            fetch_indexed_up_to(2, 2, &mut failed_attempts, |_| async { Err::<i32, _>(()) }).await;
1272        assert!(all_failed.all_failed());
1273    }
1274}