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};
13use 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;
123const 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);
129const 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 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 fn narrow(&mut self) {
200 self.queue.clear();
201 self.dropped = false;
202 }
203
204 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 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 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 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 pub scoped: bool,
326 pub root_pid: Option<u32>,
330 pub app_filter_matched: bool,
334 pub truncated: bool,
337 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
359pub(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 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 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 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 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 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
506async fn scope_to_window(
512 conn: &AccessibilityConnection,
513 children: Vec<ObjectRefOwned>,
514 title: &str,
515) -> (Vec<ObjectRefOwned>, Option<String>) {
516 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
540fn 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
558fn 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#[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 #[serde(skip)]
618 #[schemars(skip)]
619 pub is_terminal: bool,
620}
621
622impl FocusedElementSummary {
623 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#[derive(Debug, Clone)]
643pub(crate) enum FocusProbe {
644 Found(FocusedElementSummary),
645 NoneFocused,
647 ShellOnly,
649 Incomplete,
652 NoAccessibleApp,
655}
656
657pub(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
664pub(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 if focus_is_container(&summary) {
737 focused_container = Some(summary);
738 if require_scoped {
741 traversal.narrow();
742 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 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 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 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
824pub(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 "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 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
1098async 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 pid: Option<u32>,
1142 app_filter_matched: bool,
1143}
1144
1145fn 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
1317pub(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
1337pub(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 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 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 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 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 assert_eq!(outcome, EditableTextSetOutcome::MismatchAfterDeadline);
2229 let state = state.lock().unwrap();
2230 assert_eq!(state.mutations, 1);
2231 assert!(state.character_count_reads > 1);
2232 assert_eq!(state.contents, "first\nsecond\n");
2233 }
2234
2235 #[tokio::test]
2236 async fn password_text_is_unverifiable_even_when_requested_text_is_bullets() {
2237 let (_bus, peer, client, state) = start_editable_fixture(
2238 "",
2239 FakeEditableConfig {
2240 mutation: FakeMutation::Mask,
2241 role: atspi::Role::PasswordText,
2242 ..Default::default()
2243 },
2244 )
2245 .await;
2246
2247 let outcome = editable_outcome(
2248 dispatch_editable_fixture(&client, &peer, "••••••••")
2249 .await
2250 .unwrap(),
2251 );
2252
2253 assert_eq!(outcome, EditableTextSetOutcome::PasswordUnverifiable);
2254 let state = state.lock().unwrap();
2255 assert_eq!(state.mutations, 1);
2256 assert_eq!(state.character_count_reads, 0);
2257 assert_eq!(state.contents, "••••••••");
2258 }
2259
2260 #[tokio::test]
2261 async fn editable_text_missing_text_and_read_errors_are_structured_outcomes() {
2262 let configs = [
2263 FakeEditableConfig {
2264 has_text: false,
2265 ..Default::default()
2266 },
2267 FakeEditableConfig {
2268 text: FakeTextBehavior::CharacterCountError,
2269 ..Default::default()
2270 },
2271 FakeEditableConfig {
2272 text: FakeTextBehavior::GetTextError,
2273 ..Default::default()
2274 },
2275 ];
2276
2277 for config in configs {
2278 let (_bus, peer, client, state) = start_editable_fixture("before", config).await;
2279 let outcome = editable_outcome(
2280 dispatch_editable_fixture(&client, &peer, "readback may have changed")
2281 .await
2282 .unwrap(),
2283 );
2284 assert_eq!(outcome, EditableTextSetOutcome::ReadbackFailed);
2285 assert_eq!(state.lock().unwrap().mutations, 1);
2286 }
2287 }
2288
2289 #[tokio::test]
2290 async fn editable_text_negative_counts_and_stalled_readback_are_structured_outcomes() {
2291 let cases = [
2292 (
2293 FakeTextBehavior::NegativeCount,
2294 EditableTextSetOutcome::ReadbackFailed,
2295 ),
2296 (
2297 FakeTextBehavior::StallCharacterCount,
2298 EditableTextSetOutcome::ReadbackTimedOut,
2299 ),
2300 ];
2301
2302 for (text, expected) in cases {
2303 let (_bus, peer, client, state) = start_editable_fixture(
2304 "before",
2305 FakeEditableConfig {
2306 text,
2307 ..Default::default()
2308 },
2309 )
2310 .await;
2311 let outcome = editable_outcome(
2312 dispatch_editable_fixture(&client, &peer, "after")
2313 .await
2314 .unwrap(),
2315 );
2316 assert_eq!(outcome, expected);
2317 let state = state.lock().unwrap();
2318 assert_eq!(state.mutations, 1);
2319 assert_eq!(state.get_text_reads, 0);
2320 }
2321 }
2322
2323 #[tokio::test]
2324 async fn editable_text_rejection_and_mutation_errors_remain_errors() {
2325 let cases = [
2326 (FakeMutation::Reject, "rejected"),
2327 (FakeMutation::Fail, "failed to set"),
2328 ];
2329
2330 for (mutation, expected_error) in cases {
2331 let (_bus, peer, client, state) = start_editable_fixture(
2332 "before",
2333 FakeEditableConfig {
2334 mutation,
2335 ..Default::default()
2336 },
2337 )
2338 .await;
2339 let error = dispatch_editable_fixture(&client, &peer, "after")
2340 .await
2341 .unwrap_err();
2342 assert!(error.to_string().contains(expected_error));
2343 let state = state.lock().unwrap();
2344 assert_eq!(state.mutations, 1);
2345 assert_eq!(state.character_count_reads, 0);
2346 }
2347 }
2348
2349 #[tokio::test]
2350 async fn numeric_value_dispatch_remains_isolated_from_editable_text() {
2351 let (_bus, peer, client, state) = start_editable_fixture(
2352 "unchanged",
2353 FakeEditableConfig {
2354 has_value: true,
2355 ..Default::default()
2356 },
2357 )
2358 .await;
2359
2360 let invocation = dispatch_editable_fixture(&client, &peer, "42.5")
2361 .await
2362 .unwrap();
2363
2364 match invocation {
2365 ValueSetInvocation::Numeric { value } => assert_eq!(value, 42.5),
2366 ValueSetInvocation::EditableText { .. } => panic!("expected numeric dispatch"),
2367 }
2368 let state = state.lock().unwrap();
2369 assert_eq!(state.numeric_value, 42.5);
2370 assert_eq!(state.numeric_writes, 1);
2371 assert_eq!(state.mutations, 0);
2372 assert_eq!(state.character_count_reads, 0);
2373 assert_eq!(state.contents, "unchanged");
2374 }
2375
2376 #[tokio::test]
2377 async fn qt_action_names_do_not_depend_on_localized_names() {
2378 let bus = PrivateBus::start("cul-atspi-bus");
2379 let address = bus.address();
2380 let peer = zbus::connection::Builder::address(address)
2381 .unwrap()
2382 .serve_at("/actions/qt", FakeQtAction)
2383 .unwrap()
2384 .build()
2385 .await
2386 .unwrap();
2387 let client = zbus::connection::Builder::address(address)
2388 .unwrap()
2389 .build()
2390 .await
2391 .unwrap();
2392 let action = ActionProxy::builder(&client)
2393 .destination(peer.unique_name().unwrap().clone())
2394 .unwrap()
2395 .path("/actions/qt")
2396 .unwrap()
2397 .cache_properties(zbus::proxy::CacheProperties::No)
2398 .build()
2399 .await
2400 .unwrap();
2401
2402 let actions = timeout(Duration::from_secs(1), read_actions(&action))
2403 .await
2404 .expect("Qt action reads must not require GetLocalizedName")
2405 .unwrap();
2406
2407 assert_eq!(actions.len(), 2);
2408 assert_eq!(actions[0].name, "Press");
2409 assert_eq!(actions[0].description, "Eylemi tetikler");
2410 assert_eq!(actions[1].name, "Set Focus");
2411 assert_eq!(actions[1].description, "Odağı ayarlar");
2412 assert_eq!(select_named_action_index(&actions, "press").unwrap(), 0);
2413 }
2414
2415 #[tokio::test]
2416 async fn indexed_children_resolve_webkit_names_on_the_accessibility_bus() {
2417 let bus = PrivateBus::start("cul-atspi-bus");
2418 let address = bus.address();
2419
2420 let webkit_name = "org.webkit.MockWebProcess";
2421 let child_path = "/org/a11y/webkit/accessible/child";
2422 let webkit = zbus::connection::Builder::address(address)
2423 .unwrap()
2424 .name(webkit_name)
2425 .unwrap()
2426 .serve_at(
2427 child_path,
2428 FakeAccessible {
2429 name: "WebKit page".into(),
2430 children: Vec::new(),
2431 has_action: true,
2432 },
2433 )
2434 .unwrap()
2435 .serve_at(child_path, FakeWebKitAction::default())
2436 .unwrap()
2437 .build()
2438 .await
2439 .unwrap();
2440 let owner = webkit.unique_name().unwrap().to_string();
2441 let gtk = zbus::connection::Builder::address(address)
2442 .unwrap()
2443 .serve_at(
2444 "/org/a11y/atspi/accessible/root",
2445 FakeAccessible {
2446 name: "GTK socket".into(),
2447 has_action: false,
2448 children: vec![
2449 (webkit_name.into(), child_path.try_into().unwrap()),
2450 (owner.clone(), child_path.try_into().unwrap()),
2451 (String::new(), "/org/a11y/atspi/null".try_into().unwrap()),
2452 (
2453 "org.webkit.UnownedWebProcess".into(),
2454 child_path.try_into().unwrap(),
2455 ),
2456 ],
2457 },
2458 )
2459 .unwrap()
2460 .build()
2461 .await
2462 .unwrap();
2463 let client = zbus::connection::Builder::address(address)
2464 .unwrap()
2465 .build()
2466 .await
2467 .unwrap();
2468 let proxy = AccessibleProxy::builder(&client)
2469 .destination(gtk.unique_name().unwrap().clone())
2470 .unwrap()
2471 .path("/org/a11y/atspi/accessible/root")
2472 .unwrap()
2473 .build()
2474 .await
2475 .unwrap();
2476 let mut remaining = 4;
2477 let reply = proxy
2478 .inner()
2479 .call_method("GetChildAtIndex", &(0_i32,))
2480 .await
2481 .unwrap();
2482 assert_eq!(reply.body().signature().to_string(), "(so)");
2483 let batch = children_up_to(&proxy, 4, &mut remaining).await.unwrap();
2484
2485 assert_eq!(batch.attempted, 4);
2486 assert_eq!(remaining, 0);
2487 assert!(!batch.incomplete);
2488 assert_eq!(batch.items.len(), 3, "only the unowned name should fail");
2489 assert_eq!(batch.items[0].name_as_str(), Some(owner.as_str()));
2490 assert_eq!(batch.items[0].path_as_str(), child_path);
2491 assert_eq!(batch.items[0], batch.items[1]);
2492 assert!(batch.items[2].is_null());
2493
2494 let child = batch.items[0].as_accessible_proxy(&client).await.unwrap();
2496 assert_eq!(child.name().await.unwrap(), "WebKit page");
2497 assert_eq!(
2498 object_ref_from_id(&object_ref_id(&batch.items[0])).unwrap(),
2499 batch.items[0]
2500 );
2501 let action = child.proxies().await.unwrap().action().await.unwrap();
2502 let actions = timeout(Duration::from_secs(1), read_actions(&action))
2503 .await
2504 .expect("indexed action reads must not wait for GetActions")
2505 .unwrap();
2506 assert_eq!(actions.len(), 1);
2507 assert_eq!(actions[0].name, "click");
2508 assert_eq!(actions[0].description, "Activate the control");
2509 assert_eq!(actions[0].keybinding, "Return");
2510 assert_eq!(select_named_action_index(&actions, "click").unwrap(), 0);
2511 assert!(action.do_action(0).await.unwrap());
2512 }
2513
2514 #[tokio::test]
2515 async fn indexed_actions_bound_untrusted_counts_before_reading_indices() {
2516 let bus = PrivateBus::start("cul-atspi-bus");
2517 let address = bus.address();
2518 let name_reads = Arc::new(AtomicUsize::new(0));
2519 let counts = [
2520 -1,
2521 MAX_ACTIONS_PER_OBJECT + 1,
2522 i32::MAX,
2523 0,
2524 MAX_ACTIONS_PER_OBJECT,
2525 ];
2526 let mut builder = zbus::connection::Builder::address(address).unwrap();
2527 for (index, count) in counts.iter().enumerate() {
2528 builder = builder
2529 .serve_at(
2530 format!("/actions/{index}"),
2531 FakeWebKitAction {
2532 count: *count,
2533 name_reads: Arc::clone(&name_reads),
2534 ..Default::default()
2535 },
2536 )
2537 .unwrap();
2538 }
2539 let peer = builder.build().await.unwrap();
2540 let client = zbus::connection::Builder::address(address)
2541 .unwrap()
2542 .build()
2543 .await
2544 .unwrap();
2545
2546 for (index, count) in counts.iter().enumerate() {
2547 let action = ActionProxy::builder(&client)
2548 .destination(peer.unique_name().unwrap().clone())
2549 .unwrap()
2550 .path(format!("/actions/{index}"))
2551 .unwrap()
2552 .cache_properties(zbus::proxy::CacheProperties::No)
2553 .build()
2554 .await
2555 .unwrap();
2556 let result = timeout(Duration::from_secs(1), read_actions(&action))
2557 .await
2558 .expect("untrusted counts must not cause unbounded work");
2559 if (0..=MAX_ACTIONS_PER_OBJECT).contains(count) {
2560 assert_eq!(result.unwrap().len(), *count as usize);
2561 } else {
2562 let error = result.unwrap_err().to_string();
2563 assert!(error.contains("action count"), "{error}");
2564 assert_eq!(name_reads.load(Ordering::SeqCst), 0);
2565 }
2566 }
2567 assert_eq!(
2568 name_reads.load(Ordering::SeqCst),
2569 MAX_ACTIONS_PER_OBJECT as usize
2570 );
2571 }
2572
2573 #[tokio::test]
2574 async fn indexed_actions_time_out_the_entire_read() {
2575 let bus = PrivateBus::start("cul-atspi-bus");
2576 let address = bus.address();
2577 let name_reads = Arc::new(AtomicUsize::new(0));
2578 let peer = zbus::connection::Builder::address(address)
2579 .unwrap()
2580 .serve_at(
2581 "/actions/stalled",
2582 FakeWebKitAction {
2583 stall_indexed_reads: true,
2584 name_reads: Arc::clone(&name_reads),
2585 ..Default::default()
2586 },
2587 )
2588 .unwrap()
2589 .build()
2590 .await
2591 .unwrap();
2592 let client = zbus::connection::Builder::address(address)
2593 .unwrap()
2594 .build()
2595 .await
2596 .unwrap();
2597 let action = ActionProxy::builder(&client)
2598 .destination(peer.unique_name().unwrap().clone())
2599 .unwrap()
2600 .path("/actions/stalled")
2601 .unwrap()
2602 .cache_properties(zbus::proxy::CacheProperties::No)
2603 .build()
2604 .await
2605 .unwrap();
2606
2607 let error = timeout(
2608 ACTION_QUERY_TIMEOUT + Duration::from_secs(1),
2609 read_actions(&action),
2610 )
2611 .await
2612 .expect("indexed reads must have an overall deadline")
2613 .unwrap_err();
2614 assert!(error.to_string().contains("5-second deadline"));
2615 assert_eq!(name_reads.load(Ordering::SeqCst), 1);
2616 }
2617
2618 fn app_children(children: &[(&str, &str)]) -> Vec<(String, Option<String>)> {
2619 children
2620 .iter()
2621 .map(|(role, name)| (role.to_string(), Some(name.to_string())))
2622 .collect()
2623 }
2624
2625 #[test]
2626 fn a_window_title_picks_one_of_several_app_windows() {
2627 let chromium = app_children(&[
2628 ("frame", "GitHub - Chromium"),
2629 ("frame", "PlanetScale - Chromium"),
2630 ("menu", ""),
2631 ]);
2632 assert_eq!(
2633 matching_window(&chromium, "PlanetScale - Chromium"),
2634 Some(1)
2635 );
2636 assert_eq!(
2637 matching_window(&chromium, "planetscale - chromium"),
2638 Some(1)
2639 );
2640 assert_eq!(matching_window(&chromium, "PlanetScale"), Some(1));
2642 assert_eq!(matching_window(&chromium, "Chromium"), None);
2644 assert_eq!(matching_window(&chromium, "Gmail"), None);
2645 }
2646
2647 #[test]
2648 fn a_decorated_compositor_title_picks_the_frame_it_decorates() {
2649 let chromium = app_children(&[
2650 ("frame", "GitHub - Chromium"),
2651 ("frame", "PlanetScale - Chromium"),
2652 ]);
2653 assert_eq!(
2654 matching_window(&chromium, "PlanetScale - Chromium (Profile 1)"),
2655 Some(1)
2656 );
2657 let nested = app_children(&[("frame", "Docs"), ("frame", "Docs - Settings")]);
2659 assert_eq!(
2660 matching_window(&nested, "Docs - Settings (Profile 1)"),
2661 Some(1)
2662 );
2663 let generic = app_children(&[("frame", "Settings"), ("frame", "Mail")]);
2665 assert_eq!(
2666 matching_window(&generic, "Docs - Settings (Profile 1)"),
2667 None
2668 );
2669 assert_eq!(matching_window(&generic, "Mailbox"), None);
2670 }
2671
2672 #[test]
2673 fn an_exact_window_name_wins_over_a_substring_match() {
2674 let windows = app_children(&[("frame", "Docs"), ("frame", "Docs - Settings")]);
2675 assert_eq!(matching_window(&windows, "Docs"), Some(0));
2676 }
2677
2678 #[test]
2679 fn narrowing_keeps_popups_and_dialogs_beside_the_window() {
2680 let chromium = app_children(&[
2681 ("frame", "GitHub - Chromium"),
2682 ("frame", "PlanetScale - Chromium"),
2683 ("window", ""),
2684 ("dialog", "Open File"),
2685 ("menu", ""),
2686 ]);
2687 let chosen = matching_window(&chromium, "PlanetScale").unwrap();
2688 assert_eq!(
2689 kept_beside_window(&chromium, chosen),
2690 [false, true, true, true, true]
2691 );
2692 }
2693
2694 #[test]
2695 fn one_window_is_never_narrowed() {
2696 let single = app_children(&[("frame", "PlanetScale - Chromium"), ("menu", "")]);
2697 assert_eq!(matching_window(&single, "PlanetScale"), None);
2698 }
2699
2700 #[test]
2701 fn split_object_ref_id_separates_bus_name_and_path() {
2702 let (name, path) = split_object_ref_id(":1.42/org/a11y/atspi/accessible/7").unwrap();
2703
2704 assert_eq!(name, ":1.42");
2705 assert_eq!(path, "/org/a11y/atspi/accessible/7");
2706 }
2707
2708 #[test]
2709 fn select_action_index_uses_named_action() {
2710 let actions = vec![
2711 atspi::Action {
2712 name: "click".to_string(),
2713 description: "Clicks".to_string(),
2714 keybinding: String::new(),
2715 },
2716 atspi::Action {
2717 name: "show-menu".to_string(),
2718 description: "Shows menu".to_string(),
2719 keybinding: String::new(),
2720 },
2721 ];
2722
2723 assert_eq!(select_action_index(&actions, Some("show-menu")).unwrap(), 1);
2724 }
2725
2726 #[test]
2727 fn cached_action_name_is_revalidated_against_current_actions() {
2728 let mut actions = vec![atspi::Action {
2729 name: "show-menu".into(),
2730 description: "Click".into(),
2731 keybinding: String::new(),
2732 }];
2733 assert!(select_named_action_index(&actions, "Click").is_err());
2735 actions.push(atspi::Action {
2736 name: "click".into(),
2737 description: String::new(),
2738 keybinding: String::new(),
2739 });
2740 assert_eq!(select_named_action_index(&actions, "Click").unwrap(), 1);
2741 }
2742
2743 #[test]
2744 fn select_action_index_defaults_to_secondary_when_available() {
2745 let actions = vec![
2746 atspi::Action {
2747 name: "click".to_string(),
2748 description: String::new(),
2749 keybinding: String::new(),
2750 },
2751 atspi::Action {
2752 name: "show-menu".to_string(),
2753 description: String::new(),
2754 keybinding: String::new(),
2755 },
2756 ];
2757
2758 assert_eq!(select_action_index(&actions, None).unwrap(), 1);
2759 }
2760
2761 #[test]
2762 fn state_labels_serialize_in_bit_order() {
2763 let labels = state_labels(StateSet::new(atspi::State::Focused | atspi::State::Checked));
2764
2765 assert_eq!(labels, vec!["checked".to_string(), "focused".to_string()]);
2766 }
2767
2768 #[test]
2769 fn default_snapshot_limits_cover_deep_gtk4_trees() {
2770 assert_eq!(snapshot_limits(None, None), (1_000, 32));
2773 }
2774
2775 #[test]
2776 fn app_name_needle_ignores_blank_values_and_normalizes_the_rest() {
2777 assert_eq!(app_name_needle(None), None);
2778 assert_eq!(app_name_needle(Some("")), None);
2779 assert_eq!(app_name_needle(Some(" ")), None);
2780 assert_eq!(
2781 app_name_needle(Some("Calculator")).as_deref(),
2782 Some("calculator")
2783 );
2784 assert_eq!(
2785 app_name_needle(Some(" :1.64/org/a11y/atspi/accessible/root ")).as_deref(),
2786 Some(":1.64/org/a11y/atspi/accessible/root")
2787 );
2788 }
2789
2790 #[test]
2791 fn requested_snapshot_limits_remain_bounded() {
2792 assert_eq!(snapshot_limits(Some(0), Some(0)), (1, 0));
2793 assert_eq!(snapshot_limits(Some(100_000), Some(128)), (10_000, 64));
2794 }
2795
2796 #[test]
2797 fn app_discovery_budget_is_independent_of_requested_tree_size() {
2798 assert_eq!(snapshot_child_read_budgets(1), (256, 2_048, 1));
2799 }
2800
2801 #[test]
2802 fn traversal_attempts_and_queue_share_one_work_budget() {
2803 let mut traversal = BoundedTraversal::new(4);
2804 traversal.enqueue([1]);
2805
2806 assert_eq!(traversal.pop(), Some(1));
2807 traversal.enqueue(2..=10_000);
2808 assert_eq!(traversal.queue, VecDeque::from([2, 3, 4]));
2809
2810 assert_eq!(traversal.pop(), Some(2));
2811 traversal.enqueue(5..=10_000);
2812 assert_eq!(traversal.queue, VecDeque::from([3, 4]));
2813 assert_eq!(traversal.pop(), Some(3));
2814 assert_eq!(traversal.pop(), Some(4));
2815 assert_eq!(traversal.pop(), None);
2816 assert_eq!(traversal.attempted, 4);
2817 assert!(
2818 traversal.truncated(),
2819 "dropped enqueue items must be reported"
2820 );
2821 }
2822
2823 #[test]
2824 fn traversal_that_drains_within_budget_is_not_truncated() {
2825 let mut traversal = BoundedTraversal::new(3);
2826 traversal.enqueue([1, 2, 3]);
2827 assert_eq!(traversal.pop(), Some(1));
2828 assert_eq!(traversal.pop(), Some(2));
2829 assert_eq!(traversal.pop(), Some(3));
2830 assert_eq!(traversal.pop(), None);
2831 assert!(
2832 !traversal.truncated(),
2833 "exactly max_items real nodes is complete"
2834 );
2835 }
2836
2837 #[test]
2838 fn enqueue_at_zero_capacity_marks_the_traversal_truncated() {
2839 let mut traversal = BoundedTraversal::new(2);
2840 traversal.enqueue([1, 2]);
2841 assert_eq!(traversal.pop(), Some(1));
2842 assert_eq!(traversal.pop(), Some(2));
2843 assert!(!traversal.truncated(), "nothing dropped yet");
2844 traversal.enqueue([3]);
2847 assert!(traversal.queue.is_empty());
2848 assert_eq!(traversal.pop(), None);
2849 assert!(traversal.truncated());
2850 }
2851
2852 #[test]
2853 fn child_count_is_clamped_before_indexed_reads() {
2854 assert_eq!(bounded_child_count(-1, 4), 0);
2855 assert_eq!(bounded_child_count(3, 4), 3);
2856 assert_eq!(bounded_child_count(i32::MAX, 4), 4);
2857 }
2858
2859 #[tokio::test]
2860 async fn indexed_child_reads_consume_attempts_even_when_one_fails() {
2861 let calls = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
2862 let mut remaining_attempts = 3;
2863 let batch = fetch_indexed_up_to(100, 10, &mut remaining_attempts, {
2864 let calls = calls.clone();
2865 move |index| {
2866 let calls = calls.clone();
2867 async move {
2868 calls.lock().unwrap().push(index);
2869 if index == 1 {
2870 Err(())
2871 } else {
2872 Ok(index)
2873 }
2874 }
2875 }
2876 })
2877 .await;
2878
2879 assert_eq!(batch.items, vec![0, 2]);
2880 assert_eq!(batch.attempted, 3);
2881 assert!(
2882 batch.incomplete,
2883 "100 reported children, 3 attempted: budget cut must be reported"
2884 );
2885 assert!(!batch.all_failed());
2886 assert_eq!(*calls.lock().unwrap(), vec![0, 1, 2]);
2887 assert_eq!(remaining_attempts, 0);
2888
2889 let no_children = fetch_indexed_up_to(100, 10, &mut remaining_attempts, |_| async {
2890 Ok::<_, ()>(99)
2891 })
2892 .await;
2893 assert!(no_children.items.is_empty());
2894 assert_eq!(no_children.attempted, 0);
2895 assert!(!no_children.all_failed());
2896
2897 let mut failed_attempts = 2;
2898 let all_failed =
2899 fetch_indexed_up_to(2, 2, &mut failed_attempts, |_| async { Err::<i32, _>(()) }).await;
2900 assert!(all_failed.all_failed());
2901 }
2902
2903 fn document() -> FocusedElementSummary {
2904 FocusedElementSummary {
2905 role: "document web".into(),
2906 name: Some("Synthetic editor host".into()),
2907 editable: false,
2908 states: vec!["focused".into()],
2909 is_terminal: false,
2910 }
2911 }
2912
2913 #[test]
2914 fn focused_document_does_not_end_the_search_before_contenteditable() {
2915 assert!(focus_is_container(&document()));
2916 let mut entry = document();
2917 entry.role = "entry".into();
2918 entry.states.push("editable".into());
2919 assert!(!entry.editable);
2921 assert!(!focus_is_container(&entry));
2922 }
2923
2924 #[test]
2925 fn incomplete_descendants_do_not_make_the_document_a_definitive_recipient() {
2926 assert!(matches!(
2927 finish_focus_probe(true, false, Some(document())),
2928 FocusProbe::Incomplete
2929 ));
2930 assert!(matches!(
2931 finish_focus_probe(false, false, Some(document())),
2932 FocusProbe::Found(_)
2933 ));
2934 }
2935
2936 #[test]
2937 fn opt_in_snapshot_budget_reaches_controls_after_embedded_browser_content() {
2938 let (limit, _) = snapshot_limits(Some(4_000), None);
2939 assert_eq!(limit, 4_000);
2940 let mut traversal = BoundedTraversal::new(limit);
2941 traversal.enqueue(0..3_000);
2942 let mut reached_editor = false;
2943 while let Some(node) = traversal.pop() {
2944 reached_editor |= node == 2_500;
2945 }
2946 assert!(reached_editor);
2947 assert!(!traversal.truncated());
2948 let (default, _) = snapshot_limits(None, None);
2949 assert_eq!(default, 1_000);
2950 }
2951
2952 #[test]
2953 fn narrowing_keeps_the_spent_budget_and_forgets_dropped_work() {
2954 let mut traversal = BoundedTraversal::new(4);
2955 traversal.enqueue(0..6);
2956 assert!(traversal.truncated());
2957 assert_eq!(traversal.pop(), Some(0));
2958 traversal.narrow();
2959 assert!(
2960 !traversal.truncated(),
2961 "work dropped outside the subtree no longer counts"
2962 );
2963 assert_eq!(traversal.pop(), None);
2964 traversal.enqueue([10, 11, 12, 13]);
2965 assert_eq!(traversal.pop(), Some(10));
2966 assert_eq!(traversal.pop(), Some(11));
2967 assert_eq!(traversal.pop(), Some(12));
2968 assert_eq!(
2969 traversal.pop(),
2970 None,
2971 "the budget spent before narrowing still counts"
2972 );
2973 assert!(traversal.truncated());
2974 }
2975}