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}
140
141impl<T> BoundedTraversal<T> {
142    fn new(max_items: usize) -> Self {
143        Self {
144            queue: VecDeque::new(),
145            attempted: 0,
146            max_items,
147        }
148    }
149
150    fn enqueue(&mut self, items: impl IntoIterator<Item = T>) {
151        self.queue
152            .extend(items.into_iter().take(self.remaining_capacity()));
153    }
154
155    fn pop(&mut self) -> Option<T> {
156        if self.attempted >= self.max_items {
157            return None;
158        }
159        let item = self.queue.pop_front()?;
160        self.attempted += 1;
161        Some(item)
162    }
163
164    fn remaining_capacity(&self) -> usize {
165        self.max_items
166            .saturating_sub(self.attempted.saturating_add(self.queue.len()))
167    }
168}
169
170fn bounded_child_count(reported: i32, limit: usize) -> usize {
171    usize::try_from(reported).unwrap_or_default().min(limit)
172}
173
174struct IndexedReadBatch<T> {
175    items: Vec<T>,
176    attempted: usize,
177}
178
179impl<T> IndexedReadBatch<T> {
180    fn all_failed(&self) -> bool {
181        self.attempted > 0 && self.items.is_empty()
182    }
183}
184
185async fn fetch_indexed_up_to<T, E, F, Fut>(
186    reported: i32,
187    limit: usize,
188    remaining_attempts: &mut usize,
189    fetch: F,
190) -> IndexedReadBatch<T>
191where
192    F: Fn(i32) -> Fut,
193    Fut: Future<Output = std::result::Result<T, E>>,
194{
195    let attempt_count = bounded_child_count(reported, limit).min(*remaining_attempts);
196    *remaining_attempts = (*remaining_attempts).saturating_sub(attempt_count);
197    let end_index = i32::try_from(attempt_count).unwrap_or(i32::MAX);
198
199    let items = stream::iter(0..end_index)
200        .map(fetch)
201        .buffered(CHILD_READ_CONCURRENCY)
202        .filter_map(|result| async move { result.ok() })
203        .collect()
204        .await;
205
206    IndexedReadBatch {
207        items,
208        attempted: attempt_count,
209    }
210}
211
212async fn children_up_to(
213    proxy: &AccessibleProxy<'_>,
214    limit: usize,
215    remaining_attempts: &mut usize,
216) -> zbus::Result<IndexedReadBatch<ObjectRefOwned>> {
217    if limit == 0 || *remaining_attempts == 0 {
218        return Ok(IndexedReadBatch {
219            items: Vec::new(),
220            attempted: 0,
221        });
222    }
223
224    let child_count = proxy.child_count().await?;
225    Ok(
226        fetch_indexed_up_to(child_count, limit, remaining_attempts, |index| {
227            proxy.get_child_at_index(index)
228        })
229        .await,
230    )
231}
232
233pub async fn list_accessible_apps(limit: usize) -> Result<Vec<AccessibleAppSummary>> {
234    let conn = connect().await?;
235    let mut remaining_child_reads = limit;
236    let roots = registry_children(&conn, limit, &mut remaining_child_reads).await?;
237    let dbus = DBusProxy::new(conn.connection()).await.ok();
238    let mut apps = Vec::new();
239
240    for object_ref in roots.into_iter().take(limit) {
241        if let Ok(proxy) = open_accessible(&conn, &object_ref).await {
242            apps.push(read_app_summary(&proxy, &object_ref, dbus.as_ref()).await);
243        }
244    }
245
246    Ok(apps)
247}
248
249pub async fn snapshot_tree(
250    app_name_or_bundle_identifier: Option<&str>,
251    target_pid: Option<u32>,
252    max_nodes: usize,
253    max_depth: u32,
254) -> Result<Vec<AccessibilityNode>> {
255    let (max_nodes, max_depth) = snapshot_limits(Some(max_nodes), Some(max_depth));
256    timeout(
257        SNAPSHOT_TIMEOUT,
258        snapshot_tree_inner(
259            app_name_or_bundle_identifier,
260            target_pid,
261            max_nodes,
262            max_depth,
263        ),
264    )
265    .await
266    .context("AT-SPI snapshot exceeded its 10-second deadline")?
267}
268
269async fn snapshot_tree_inner(
270    app_name_or_bundle_identifier: Option<&str>,
271    target_pid: Option<u32>,
272    max_nodes: usize,
273    max_depth: u32,
274) -> Result<Vec<AccessibilityNode>> {
275    let conn = connect().await?;
276    // App discovery is bounded independently so a tiny requested tree still
277    // finds a target registered after the first accessibility root.
278    let (mut remaining_registry_reads, mut remaining_filter_reads, mut remaining_traversal_reads) =
279        snapshot_child_read_budgets(max_nodes);
280    let roots =
281        registry_children(&conn, MAX_DISCOVERY_ROOTS, &mut remaining_registry_reads).await?;
282    let selected_roots = select_roots(
283        &conn,
284        roots,
285        app_name_or_bundle_identifier,
286        target_pid,
287        &mut remaining_filter_reads,
288    )
289    .await;
290    let mut nodes = Vec::new();
291    let mut traversal = BoundedTraversal::new(max_nodes);
292
293    traversal.enqueue(
294        selected_roots
295            .into_iter()
296            .map(|object_ref| (object_ref, 0_u32, None)),
297    );
298
299    while let Some((object_ref, depth, parent_index)) = traversal.pop() {
300        let Ok(proxy) = open_accessible(&conn, &object_ref).await else {
301            continue;
302        };
303        let index = nodes.len() as u32;
304        let remaining = traversal.remaining_capacity();
305        let child_refs = if depth < max_depth && remaining > 0 {
306            children_up_to(&proxy, remaining, &mut remaining_traversal_reads)
307                .await
308                .map(|batch| batch.items)
309                .unwrap_or_default()
310        } else {
311            Vec::new()
312        };
313
314        nodes.push(read_node(&proxy, &object_ref, index, parent_index, depth).await);
315
316        traversal.enqueue(
317            child_refs
318                .into_iter()
319                .map(|child| (child, depth + 1, Some(index))),
320        );
321    }
322
323    Ok(nodes)
324}
325
326/// Compact description of the AT-SPI element that currently holds keyboard
327/// focus, used as post-input feedback for type_text/press_key.
328#[derive(Debug, Clone, Serialize, JsonSchema)]
329pub struct FocusedElementSummary {
330    pub role: String,
331    pub name: Option<String>,
332    pub editable: bool,
333    pub states: Vec<String>,
334}
335
336const FOCUS_PROBE_MAX_NODES: usize = 400;
337const FOCUS_PROBE_MAX_DEPTH: u32 = 16;
338
339/// Find the element with the `focused` state inside the target app (by pid) or
340/// across all apps. Best-effort and bounded: returns Ok(None) when no focused
341/// element is reachable through AT-SPI (common for apps without accessibility
342/// support, e.g. Electron without --force-renderer-accessibility).
343pub async fn focused_element_summary(
344    target_pid: Option<u32>,
345) -> Result<Option<FocusedElementSummary>> {
346    let conn = connect().await?;
347    let mut remaining_registry_reads = MAX_DISCOVERY_ROOTS;
348    let roots =
349        registry_children(&conn, MAX_DISCOVERY_ROOTS, &mut remaining_registry_reads).await?;
350    let mut remaining_filter_reads = MAX_DISCOVERY_CHILD_READS;
351    let selected_roots =
352        select_roots(&conn, roots, None, target_pid, &mut remaining_filter_reads).await;
353    let mut traversal = BoundedTraversal::new(FOCUS_PROBE_MAX_NODES);
354    let mut remaining_traversal_reads = FOCUS_PROBE_MAX_NODES;
355
356    traversal.enqueue(
357        selected_roots
358            .into_iter()
359            .map(|object_ref| (object_ref, 0_u32)),
360    );
361
362    while let Some((object_ref, depth)) = traversal.pop() {
363        let Ok(proxy) = open_accessible(&conn, &object_ref).await else {
364            continue;
365        };
366        let Ok(state) = proxy.get_state().await else {
367            continue;
368        };
369        if state.contains(atspi::State::Focused) {
370            let proxies = proxy.proxies().await.ok();
371            return Ok(Some(FocusedElementSummary {
372                role: role_name(&proxy).await,
373                name: optional_string(proxy.name().await.ok()),
374                editable: supports_editable_text(proxies.as_ref()).await,
375                states: state_labels(state),
376            }));
377        }
378        if depth < FOCUS_PROBE_MAX_DEPTH {
379            let remaining = traversal.remaining_capacity();
380            let children = children_up_to(&proxy, remaining, &mut remaining_traversal_reads)
381                .await
382                .map(|batch| batch.items)
383                .unwrap_or_default();
384            traversal.enqueue(children.into_iter().map(|child| (child, depth + 1)));
385        }
386    }
387
388    Ok(None)
389}
390
391pub async fn perform_action(
392    object_ref_id: &str,
393    requested_action: Option<&str>,
394) -> Result<ActionInvocation> {
395    let conn = connect().await?;
396    let object_ref = object_ref_from_id(object_ref_id)?;
397    let proxy = open_accessible(&conn, &object_ref)
398        .await
399        .with_context(|| format!("failed to open AT-SPI object {object_ref_id}"))?;
400    let action = proxy
401        .proxies()
402        .await?
403        .action()
404        .await
405        .context("element does not expose the AT-SPI Action interface")?;
406    let actions = action.get_actions().await.unwrap_or_default();
407    let action_index = select_action_index(&actions, requested_action)?;
408    let action_name = actions
409        .get(action_index as usize)
410        .map(|action| action.name.clone());
411    let ok = action
412        .do_action(action_index)
413        .await
414        .with_context(|| format!("failed to invoke AT-SPI action {action_index}"))?;
415
416    Ok(ActionInvocation {
417        action_index,
418        action_name,
419        ok,
420    })
421}
422
423pub async fn set_element_value(object_ref_id: &str, value: &str) -> Result<ValueSetInvocation> {
424    let conn = connect().await?;
425    let object_ref = object_ref_from_id(object_ref_id)?;
426    let proxy = open_accessible(&conn, &object_ref)
427        .await
428        .with_context(|| format!("failed to open AT-SPI object {object_ref_id}"))?;
429    let proxies = proxy.proxies().await?;
430
431    if let Ok(numeric_value) = value.parse::<f64>() {
432        if let Ok(value_proxy) = proxies.value().await {
433            value_proxy
434                .set_current_value(numeric_value)
435                .await
436                .with_context(|| {
437                    format!("failed to set AT-SPI numeric value to {numeric_value}")
438                })?;
439            return Ok(ValueSetInvocation::Numeric {
440                value: numeric_value,
441            });
442        }
443    }
444
445    if let Ok(editable_text) = proxies.editable_text().await {
446        let ok = editable_text
447            .set_text_contents(value)
448            .await
449            .context("failed to set AT-SPI editable text contents")?;
450        if ok {
451            return Ok(ValueSetInvocation::EditableText);
452        }
453        return Err(anyhow!("AT-SPI EditableText rejected the new contents"));
454    }
455
456    if value.parse::<f64>().is_err() && proxies.value().await.is_ok() {
457        return Err(anyhow!(
458            "element exposes the AT-SPI Value interface, but the requested value is not numeric"
459        ));
460    }
461
462    Err(anyhow!(
463        "element does not expose AT-SPI Value or EditableText interfaces"
464    ))
465}
466
467async fn connect() -> Result<AccessibilityConnection> {
468    hydrate_session_bus_env();
469    AccessibilityConnection::new()
470        .await
471        .context("failed to connect to AT-SPI bus")
472}
473
474/// Open an `AccessibleProxy` for an object on the a11y bus.
475///
476/// We deliberately avoid `AccessibilityConnection::object_as_accessible` (the
477/// `P2P` trait). For apps that advertise a peer-to-peer bus address it routes
478/// reads over that socket, but for apps that don't (notably GTK4 apps such as
479/// Nautilus / Text Editor / baobab, which don't implement the legacy
480/// `GetApplicationBusAddress`) it falls back to a proxy built with only a path
481/// and *no destination*. On the shared a11y bus that proxy can't address the
482/// app and every call fails with `ServiceUnknown`, which surfaces as an empty
483/// tree (`role: "unknown"`, `child_count: 0`). `as_accessible_proxy` always
484/// pins the destination to the object's bus name, so it works for every app
485/// regardless of P2P support. See issue #31.
486async fn open_accessible<'r>(
487    conn: &AccessibilityConnection,
488    object_ref: &'r ObjectRefOwned,
489) -> Result<AccessibleProxy<'r>, atspi::AtspiError> {
490    object_ref.as_accessible_proxy(conn.connection()).await
491}
492
493async fn registry_children(
494    conn: &AccessibilityConnection,
495    limit: usize,
496    remaining_child_reads: &mut usize,
497) -> Result<Vec<ObjectRefOwned>> {
498    let root = conn
499        .root_accessible_on_registry()
500        .await
501        .context("failed to open AT-SPI registry root")?;
502    let batch = children_up_to(&root, limit, remaining_child_reads)
503        .await
504        .context("failed to read AT-SPI registry children")?;
505    if batch.all_failed() {
506        return Err(anyhow!(
507            "AT-SPI registry reported children, but every indexed child read failed"
508        ));
509    }
510    Ok(batch.items)
511}
512
513async fn select_roots(
514    conn: &AccessibilityConnection,
515    roots: Vec<ObjectRefOwned>,
516    app_name_or_bundle_identifier: Option<&str>,
517    target_pid: Option<u32>,
518    remaining_child_reads: &mut usize,
519) -> Vec<ObjectRefOwned> {
520    let needle = app_name_or_bundle_identifier
521        .map(str::trim)
522        .filter(|value| !value.is_empty())
523        .map(|value| value.to_ascii_lowercase());
524    let dbus = DBusProxy::new(conn.connection()).await.ok();
525    let mut remaining = roots;
526
527    if let Some(target_pid) = target_pid {
528        let mut pid_and_filter_matches = Vec::new();
529        let mut pid_matches = Vec::new();
530        let mut non_pid_matches = Vec::new();
531
532        for object_ref in remaining {
533            if object_ref_pid(dbus.as_ref(), &object_ref).await == Some(target_pid) {
534                if let Some(needle) = needle.as_deref() {
535                    if root_matches(conn, &object_ref, needle, remaining_child_reads).await {
536                        pid_and_filter_matches.push(object_ref);
537                    } else {
538                        pid_matches.push(object_ref);
539                    }
540                } else {
541                    pid_matches.push(object_ref);
542                }
543            } else {
544                non_pid_matches.push(object_ref);
545            }
546        }
547
548        if !pid_and_filter_matches.is_empty() {
549            return pid_and_filter_matches;
550        }
551        if !pid_matches.is_empty() {
552            return pid_matches;
553        }
554
555        remaining = non_pid_matches;
556    }
557
558    let Some(needle) = needle.as_deref() else {
559        return remaining;
560    };
561
562    let mut selected = Vec::new();
563    for object_ref in remaining {
564        if root_matches(conn, &object_ref, needle, remaining_child_reads).await {
565            selected.push(object_ref);
566        }
567    }
568
569    selected
570}
571
572async fn root_matches(
573    conn: &AccessibilityConnection,
574    object_ref: &ObjectRefOwned,
575    needle: &str,
576    remaining_child_reads: &mut usize,
577) -> bool {
578    let Ok(proxy) = open_accessible(conn, object_ref).await else {
579        return object_ref_id(object_ref)
580            .to_ascii_lowercase()
581            .contains(needle);
582    };
583
584    if proxy_matches(&proxy, object_ref, needle).await {
585        return true;
586    }
587
588    for child_ref in children_up_to(&proxy, ROOT_MATCH_CHILD_LIMIT, remaining_child_reads)
589        .await
590        .map(|batch| batch.items)
591        .unwrap_or_default()
592    {
593        let Ok(child_proxy) = open_accessible(conn, &child_ref).await else {
594            continue;
595        };
596        if proxy_matches(&child_proxy, &child_ref, needle).await {
597            return true;
598        }
599    }
600
601    false
602}
603
604async fn proxy_matches(
605    proxy: &AccessibleProxy<'_>,
606    object_ref: &ObjectRefOwned,
607    needle: &str,
608) -> bool {
609    let name = proxy.name().await.unwrap_or_default();
610    let role = proxy.get_role_name().await.unwrap_or_default();
611    format!("{} {} {}", object_ref_id(object_ref), name, role)
612        .to_ascii_lowercase()
613        .contains(needle)
614}
615
616async fn read_app_summary(
617    proxy: &AccessibleProxy<'_>,
618    object_ref: &ObjectRefOwned,
619    dbus: Option<&DBusProxy<'_>>,
620) -> AccessibleAppSummary {
621    AccessibleAppSummary {
622        object_ref: object_ref_id(object_ref),
623        name: optional_string(proxy.name().await.ok()),
624        pid: object_ref_pid(dbus, object_ref).await,
625        role: role_name(proxy).await,
626        child_count: proxy.child_count().await.unwrap_or_default(),
627        bounds: bounds(proxy).await,
628    }
629}
630
631async fn read_node(
632    proxy: &AccessibleProxy<'_>,
633    object_ref: &ObjectRefOwned,
634    index: u32,
635    parent_index: Option<u32>,
636    depth: u32,
637) -> AccessibilityNode {
638    let proxies = proxy.proxies().await.ok();
639
640    AccessibilityNode {
641        index,
642        parent_index,
643        depth,
644        object_ref: object_ref_id(object_ref),
645        role: role_name(proxy).await,
646        name: optional_string(proxy.name().await.ok()),
647        description: optional_string(proxy.description().await.ok()),
648        child_count: proxy.child_count().await.unwrap_or_default(),
649        bounds: bounds_from_proxies(proxies.as_ref(), proxy).await,
650        states: states_from_proxy(proxy).await,
651        actions: actions_from_proxies(proxies.as_ref()).await,
652        value: value_from_proxies(proxies.as_ref()).await,
653        text: text_from_proxies(proxies.as_ref()).await,
654        supports_editable_text: supports_editable_text(proxies.as_ref()).await,
655    }
656}
657
658async fn role_name(proxy: &AccessibleProxy<'_>) -> String {
659    if let Ok(role) = proxy.get_role_name().await {
660        if !role.trim().is_empty() {
661            return role;
662        }
663    }
664    proxy
665        .get_role()
666        .await
667        .map(|role| format!("{role:?}"))
668        .unwrap_or_else(|_| "unknown".to_string())
669}
670
671async fn bounds(proxy: &AccessibleProxy<'_>) -> Option<Bounds> {
672    bounds_from_proxies(proxy.proxies().await.ok().as_ref(), proxy).await
673}
674
675async fn object_ref_pid(dbus: Option<&DBusProxy<'_>>, object_ref: &ObjectRefOwned) -> Option<u32> {
676    let dbus = dbus?;
677    let bus_name = BusName::try_from(object_ref.name_as_str()?.to_string()).ok()?;
678    dbus.get_connection_unix_process_id(bus_name).await.ok()
679}
680
681async fn bounds_from_proxies(
682    proxies: Option<&atspi::proxy::proxy_ext::Proxies<'_>>,
683    proxy: &AccessibleProxy<'_>,
684) -> Option<Bounds> {
685    let owned_proxies;
686    let proxies = if let Some(proxies) = proxies {
687        proxies
688    } else {
689        owned_proxies = proxy.proxies().await.ok()?;
690        &owned_proxies
691    };
692    let component = proxies.component().await.ok()?;
693    let (x, y, width, height) = component.get_extents(CoordType::Screen).await.ok()?;
694    normalize_bounds(Bounds {
695        x,
696        y,
697        width,
698        height,
699    })
700}
701
702fn normalize_bounds(bounds: Bounds) -> Option<Bounds> {
703    if bounds.width <= 0 || bounds.height <= 0 {
704        return None;
705    }
706    if bounds.x <= i32::MIN / 2 || bounds.y <= i32::MIN / 2 {
707        return None;
708    }
709    Some(bounds)
710}
711
712async fn actions_from_proxies(
713    proxies: Option<&atspi::proxy::proxy_ext::Proxies<'_>>,
714) -> Vec<AccessibilityAction> {
715    let Some(proxies) = proxies else {
716        return Vec::new();
717    };
718    let Ok(action_proxy) = proxies.action().await else {
719        return Vec::new();
720    };
721
722    action_proxy
723        .get_actions()
724        .await
725        .unwrap_or_default()
726        .into_iter()
727        .enumerate()
728        .map(|(index, action)| AccessibilityAction {
729            index: index as i32,
730            name: action.name,
731            description: action.description,
732            keybinding: action.keybinding,
733        })
734        .collect()
735}
736
737async fn states_from_proxy(proxy: &AccessibleProxy<'_>) -> Vec<String> {
738    proxy
739        .get_state()
740        .await
741        .map(state_labels)
742        .unwrap_or_default()
743}
744
745async fn value_from_proxies(
746    proxies: Option<&atspi::proxy::proxy_ext::Proxies<'_>>,
747) -> Option<AccessibilityValue> {
748    let value = proxies?.value().await.ok()?;
749    Some(AccessibilityValue {
750        current: value.current_value().await.ok()?,
751        minimum: value.minimum_value().await.ok()?,
752        maximum: value.maximum_value().await.ok()?,
753        minimum_increment: value.minimum_increment().await.ok()?,
754        text: optional_string(value.text().await.ok()),
755    })
756}
757
758async fn text_from_proxies(
759    proxies: Option<&atspi::proxy::proxy_ext::Proxies<'_>>,
760) -> Option<AccessibilityText> {
761    let text = proxies?.text().await.ok()?;
762    let character_count = text.character_count().await.ok()?.max(0);
763    let caret_offset = text.caret_offset().await.ok();
764    let capped_count = character_count.min(MAX_TEXT_READBACK_CHARS);
765    let content = if capped_count > 0 {
766        optional_string(text.get_text(0, capped_count).await.ok())
767    } else {
768        None
769    };
770    let selection_count = text
771        .get_nselections()
772        .await
773        .unwrap_or_default()
774        .clamp(0, MAX_TEXT_SELECTIONS);
775    let mut selections = Vec::new();
776    for index in 0..selection_count {
777        if let Ok((start_offset, end_offset)) = text.get_selection(index).await {
778            selections.push(AccessibilityTextSelection {
779                start_offset,
780                end_offset,
781            });
782        }
783    }
784
785    Some(AccessibilityText {
786        character_count,
787        caret_offset,
788        content,
789        truncated: character_count > MAX_TEXT_READBACK_CHARS,
790        selections,
791    })
792}
793
794async fn supports_editable_text(proxies: Option<&atspi::proxy::proxy_ext::Proxies<'_>>) -> bool {
795    let Some(proxies) = proxies else {
796        return false;
797    };
798    proxies.editable_text().await.is_ok()
799}
800
801fn state_labels(state_set: StateSet) -> Vec<String> {
802    state_set.iter().map(|state| state.to_string()).collect()
803}
804
805fn select_action_index(actions: &[atspi::Action], requested_action: Option<&str>) -> Result<i32> {
806    if actions.is_empty() {
807        return Err(anyhow!("element exposes no AT-SPI actions"));
808    }
809
810    if let Some(requested_action) = requested_action
811        .map(str::trim)
812        .filter(|value| !value.is_empty())
813    {
814        let requested_action = requested_action.to_ascii_lowercase();
815        if let Some((index, _)) = actions.iter().enumerate().find(|(_, action)| {
816            action.name.to_ascii_lowercase() == requested_action
817                || action.description.to_ascii_lowercase() == requested_action
818        }) {
819            return Ok(index as i32);
820        }
821
822        if let Ok(index) = requested_action.parse::<usize>() {
823            if index < actions.len() {
824                return Ok(index as i32);
825            }
826        }
827
828        return Err(anyhow!(
829            "requested AT-SPI action was not found; available actions: {}",
830            actions
831                .iter()
832                .map(|action| action.name.as_str())
833                .collect::<Vec<_>>()
834                .join(", ")
835        ));
836    }
837
838    Ok(if actions.len() > 1 { 1 } else { 0 })
839}
840
841fn optional_string(value: Option<String>) -> Option<String> {
842    value
843        .map(|value| value.trim().to_string())
844        .filter(|value| !value.is_empty())
845}
846
847fn object_ref_from_id(object_ref_id: &str) -> Result<ObjectRefOwned> {
848    let (name, path) = split_object_ref_id(object_ref_id)?;
849    let name = UniqueName::try_from(name.to_string())
850        .with_context(|| format!("invalid AT-SPI bus name in object ref {object_ref_id}"))?;
851    let path = ObjectPath::try_from(path.to_string())
852        .with_context(|| format!("invalid AT-SPI object path in object ref {object_ref_id}"))?;
853    Ok(ObjectRef::new_owned(name, path))
854}
855
856fn split_object_ref_id(object_ref_id: &str) -> Result<(&str, &str)> {
857    let Some(path_start) = object_ref_id.find('/') else {
858        return Err(anyhow!(
859            "invalid AT-SPI object ref '{object_ref_id}'; expected ':bus/path'"
860        ));
861    };
862    let (name, path) = object_ref_id.split_at(path_start);
863    if name.is_empty() || path.is_empty() {
864        return Err(anyhow!(
865            "invalid AT-SPI object ref '{object_ref_id}'; expected ':bus/path'"
866        ));
867    }
868    Ok((name, path))
869}
870
871fn object_ref_id(object_ref: &ObjectRefOwned) -> String {
872    format!(
873        "{}{}",
874        object_ref.name_as_str().unwrap_or(""),
875        object_ref.path_as_str()
876    )
877}
878
879#[cfg(test)]
880mod tests {
881    use super::*;
882
883    #[test]
884    fn split_object_ref_id_separates_bus_name_and_path() {
885        let (name, path) = split_object_ref_id(":1.42/org/a11y/atspi/accessible/7").unwrap();
886
887        assert_eq!(name, ":1.42");
888        assert_eq!(path, "/org/a11y/atspi/accessible/7");
889    }
890
891    #[test]
892    fn select_action_index_uses_named_action() {
893        let actions = vec![
894            atspi::Action {
895                name: "click".to_string(),
896                description: "Clicks".to_string(),
897                keybinding: String::new(),
898            },
899            atspi::Action {
900                name: "show-menu".to_string(),
901                description: "Shows menu".to_string(),
902                keybinding: String::new(),
903            },
904        ];
905
906        assert_eq!(select_action_index(&actions, Some("show-menu")).unwrap(), 1);
907    }
908
909    #[test]
910    fn select_action_index_defaults_to_secondary_when_available() {
911        let actions = vec![
912            atspi::Action {
913                name: "click".to_string(),
914                description: String::new(),
915                keybinding: String::new(),
916            },
917            atspi::Action {
918                name: "show-menu".to_string(),
919                description: String::new(),
920                keybinding: String::new(),
921            },
922        ];
923
924        assert_eq!(select_action_index(&actions, None).unwrap(), 1);
925    }
926
927    #[test]
928    fn state_labels_serialize_in_bit_order() {
929        let labels = state_labels(StateSet::new(atspi::State::Focused | atspi::State::Checked));
930
931        assert_eq!(labels, vec!["checked".to_string(), "focused".to_string()]);
932    }
933
934    #[test]
935    fn default_snapshot_limits_cover_deep_gtk4_trees() {
936        // Nautilus 50 places file-list cells below depth 20 and can expose
937        // more than 850 raw nodes. Keep the defaults above that known shape.
938        assert_eq!(snapshot_limits(None, None), (1_000, 32));
939    }
940
941    #[test]
942    fn requested_snapshot_limits_remain_bounded() {
943        assert_eq!(snapshot_limits(Some(0), Some(0)), (1, 0));
944        assert_eq!(snapshot_limits(Some(10_000), Some(128)), (2_000, 64));
945    }
946
947    #[test]
948    fn app_discovery_budget_is_independent_of_requested_tree_size() {
949        assert_eq!(snapshot_child_read_budgets(1), (256, 2_048, 1));
950    }
951
952    #[test]
953    fn traversal_attempts_and_queue_share_one_work_budget() {
954        let mut traversal = BoundedTraversal::new(4);
955        traversal.enqueue([1]);
956
957        assert_eq!(traversal.pop(), Some(1));
958        traversal.enqueue(2..=10_000);
959        assert_eq!(traversal.queue, VecDeque::from([2, 3, 4]));
960
961        assert_eq!(traversal.pop(), Some(2));
962        traversal.enqueue(5..=10_000);
963        assert_eq!(traversal.queue, VecDeque::from([3, 4]));
964        assert_eq!(traversal.pop(), Some(3));
965        assert_eq!(traversal.pop(), Some(4));
966        assert_eq!(traversal.pop(), None);
967        assert_eq!(traversal.attempted, 4);
968    }
969
970    #[test]
971    fn child_count_is_clamped_before_indexed_reads() {
972        assert_eq!(bounded_child_count(-1, 4), 0);
973        assert_eq!(bounded_child_count(3, 4), 3);
974        assert_eq!(bounded_child_count(i32::MAX, 4), 4);
975    }
976
977    #[tokio::test]
978    async fn indexed_child_reads_consume_attempts_even_when_one_fails() {
979        let calls = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
980        let mut remaining_attempts = 3;
981        let batch = fetch_indexed_up_to(100, 10, &mut remaining_attempts, {
982            let calls = calls.clone();
983            move |index| {
984                let calls = calls.clone();
985                async move {
986                    calls.lock().unwrap().push(index);
987                    if index == 1 {
988                        Err(())
989                    } else {
990                        Ok(index)
991                    }
992                }
993            }
994        })
995        .await;
996
997        assert_eq!(batch.items, vec![0, 2]);
998        assert_eq!(batch.attempted, 3);
999        assert!(!batch.all_failed());
1000        assert_eq!(*calls.lock().unwrap(), vec![0, 1, 2]);
1001        assert_eq!(remaining_attempts, 0);
1002
1003        let no_children = fetch_indexed_up_to(100, 10, &mut remaining_attempts, |_| async {
1004            Ok::<_, ()>(99)
1005        })
1006        .await;
1007        assert!(no_children.items.is_empty());
1008        assert_eq!(no_children.attempted, 0);
1009        assert!(!no_children.all_failed());
1010
1011        let mut failed_attempts = 2;
1012        let all_failed =
1013            fetch_indexed_up_to(2, 2, &mut failed_attempts, |_| async { Err::<i32, _>(()) }).await;
1014        assert!(all_failed.all_failed());
1015    }
1016}