1use std::collections::{HashMap, HashSet, VecDeque};
4use std::sync::atomic::{AtomicU64, Ordering};
5use std::sync::Mutex;
6
7use rayon::prelude::*;
8use xa11y_core::selector::{Combinator, SelectorSegment};
9use xa11y_core::{
10 ElementData, Error, Provider, Rect, Result, Role, Selector, StateSet, Subscription, Toggled,
11};
12use zbus::blocking::{Connection, Proxy};
13
14static NEXT_HANDLE: AtomicU64 = AtomicU64::new(1);
16
17fn state_attr_to_string(name: &str, s: &StateSet) -> Option<String> {
20 match name {
21 "enabled" => Some(s.enabled.to_string()),
22 "visible" => Some(s.visible.to_string()),
23 "focused" => Some(s.focused.to_string()),
24 "focusable" => Some(s.focusable.to_string()),
25 "selected" => Some(s.selected.to_string()),
26 "editable" => Some(s.editable.to_string()),
27 "modal" => Some(s.modal.to_string()),
28 "required" => Some(s.required.to_string()),
29 "busy" => Some(s.busy.to_string()),
30 "expanded" => s.expanded.map(|b| b.to_string()),
31 "checked" => s.checked.map(|c| {
32 match c {
33 Toggled::On => "on",
34 Toggled::Off => "off",
35 Toggled::Mixed => "mixed",
36 }
37 .to_string()
38 }),
39 _ => None,
40 }
41}
42
43pub struct LinuxProvider {
45 a11y_bus: Connection,
46 handle_cache: Mutex<HashMap<u64, AccessibleRef>>,
48 action_indices: Mutex<HashMap<u64, HashMap<String, i32>>>,
51}
52
53#[derive(Debug, Clone)]
55pub(crate) struct AccessibleRef {
56 pub(crate) bus_name: String,
57 pub(crate) path: String,
58}
59
60impl LinuxProvider {
61 pub fn new() -> Result<Self> {
66 let a11y_bus = Self::connect_a11y_bus()?;
67 Ok(Self {
68 a11y_bus,
69 handle_cache: Mutex::new(HashMap::new()),
70 action_indices: Mutex::new(HashMap::new()),
71 })
72 }
73
74 pub(crate) fn connect_a11y_bus() -> Result<Connection> {
75 if let Ok(session) = Connection::session() {
79 let proxy = Proxy::new(&session, "org.a11y.Bus", "/org/a11y/bus", "org.a11y.Bus")
80 .map_err(|e| Error::Platform {
81 code: -1,
82 message: format!("Failed to create a11y bus proxy: {}", e),
83 })?;
84
85 if let Ok(addr_reply) = proxy.call_method("GetAddress", &()) {
86 if let Ok(address) = addr_reply.body().deserialize::<String>() {
87 if let Ok(addr) = zbus::Address::try_from(address.as_str()) {
88 if let Ok(Ok(conn)) =
89 zbus::blocking::connection::Builder::address(addr).map(|b| b.build())
90 {
91 return Ok(conn);
92 }
93 }
94 }
95 }
96
97 return Ok(session);
99 }
100
101 Connection::session().map_err(|e| Error::Platform {
102 code: -1,
103 message: format!("Failed to connect to D-Bus session bus: {}", e),
104 })
105 }
106
107 fn make_proxy(&self, bus_name: &str, path: &str, interface: &str) -> Result<Proxy<'_>> {
108 zbus::blocking::proxy::Builder::<Proxy>::new(&self.a11y_bus)
111 .destination(bus_name.to_owned())
112 .map_err(|e| Error::Platform {
113 code: -1,
114 message: format!("Failed to set proxy destination: {}", e),
115 })?
116 .path(path.to_owned())
117 .map_err(|e| Error::Platform {
118 code: -1,
119 message: format!("Failed to set proxy path: {}", e),
120 })?
121 .interface(interface.to_owned())
122 .map_err(|e| Error::Platform {
123 code: -1,
124 message: format!("Failed to set proxy interface: {}", e),
125 })?
126 .cache_properties(zbus::proxy::CacheProperties::No)
127 .build()
128 .map_err(|e| Error::Platform {
129 code: -1,
130 message: format!("Failed to create proxy: {}", e),
131 })
132 }
133
134 fn has_interface(&self, aref: &AccessibleRef, iface: &str) -> bool {
137 let proxy = match self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Accessible") {
138 Ok(p) => p,
139 Err(_) => return false,
140 };
141 let reply = match proxy.call_method("GetInterfaces", &()) {
142 Ok(r) => r,
143 Err(_) => return false,
144 };
145 let interfaces: Vec<String> = match reply.body().deserialize() {
146 Ok(v) => v,
147 Err(_) => return false,
148 };
149 interfaces.iter().any(|i| i.contains(iface))
150 }
151
152 fn get_role_number(&self, aref: &AccessibleRef) -> Result<u32> {
154 let proxy = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Accessible")?;
155 let reply = proxy
156 .call_method("GetRole", &())
157 .map_err(|e| Error::Platform {
158 code: -1,
159 message: format!("GetRole failed: {}", e),
160 })?;
161 reply
162 .body()
163 .deserialize::<u32>()
164 .map_err(|e| Error::Platform {
165 code: -1,
166 message: format!("GetRole deserialize failed: {}", e),
167 })
168 }
169
170 fn get_role_name(&self, aref: &AccessibleRef) -> Result<String> {
172 let proxy = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Accessible")?;
173 let reply = proxy
174 .call_method("GetRoleName", &())
175 .map_err(|e| Error::Platform {
176 code: -1,
177 message: format!("GetRoleName failed: {}", e),
178 })?;
179 reply
180 .body()
181 .deserialize::<String>()
182 .map_err(|e| Error::Platform {
183 code: -1,
184 message: format!("GetRoleName deserialize failed: {}", e),
185 })
186 }
187
188 fn check_chromium_a11y_enabled(
205 &self,
206 parent: &AccessibleRef,
207 role_hint: Option<Role>,
208 ) -> Result<()> {
209 let app_root = AccessibleRef {
210 bus_name: parent.bus_name.clone(),
211 path: "/org/a11y/atspi/accessible/root".to_string(),
212 };
213 let toolkit = match self
214 .make_proxy(
215 &app_root.bus_name,
216 &app_root.path,
217 "org.a11y.atspi.Application",
218 )
219 .ok()
220 .and_then(|proxy| proxy.get_property::<String>("ToolkitName").ok())
221 {
222 Some(t) => t,
223 None => return Ok(()),
224 };
225 if !toolkit.eq_ignore_ascii_case("Chromium") {
226 return Ok(());
227 }
228 let role = role_hint.unwrap_or_else(|| self.resolve_role(parent));
229 if role != Role::Window {
230 return Ok(());
231 }
232 let app_name = self.get_name(&app_root).unwrap_or_default();
233 Err(Error::AccessibilityNotEnabled {
234 app: app_name,
235 instructions: "Chromium/Electron app exposes an empty accessibility tree on Linux. \
236 Relaunch with `--force-renderer-accessibility` (or set the env var \
237 `ACCESSIBILITY_ENABLED=1`) so the renderer accessibility bridge is initialised."
238 .to_string(),
239 })
240 }
241
242 fn get_name(&self, aref: &AccessibleRef) -> Result<String> {
244 let proxy = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Accessible")?;
245 proxy
246 .get_property::<String>("Name")
247 .map_err(|e| Error::Platform {
248 code: -1,
249 message: format!("Get Name property failed: {}", e),
250 })
251 }
252
253 fn get_description(&self, aref: &AccessibleRef) -> Result<String> {
255 let proxy = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Accessible")?;
256 proxy
257 .get_property::<String>("Description")
258 .map_err(|e| Error::Platform {
259 code: -1,
260 message: format!("Get Description property failed: {}", e),
261 })
262 }
263
264 fn get_atspi_children(&self, aref: &AccessibleRef) -> Result<Vec<AccessibleRef>> {
268 let proxy = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Accessible")?;
269 let reply = proxy
270 .call_method("GetChildren", &())
271 .map_err(|e| Error::Platform {
272 code: -1,
273 message: format!("GetChildren failed: {}", e),
274 })?;
275 let children: Vec<(String, zbus::zvariant::OwnedObjectPath)> =
276 reply.body().deserialize().map_err(|e| Error::Platform {
277 code: -1,
278 message: format!("GetChildren deserialize failed: {}", e),
279 })?;
280 Ok(children
281 .into_iter()
282 .map(|(bus_name, path)| AccessibleRef {
283 bus_name,
284 path: path.to_string(),
285 })
286 .collect())
287 }
288
289 fn get_state(&self, aref: &AccessibleRef) -> Result<Vec<u32>> {
291 let proxy = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Accessible")?;
292 let reply = proxy
293 .call_method("GetState", &())
294 .map_err(|e| Error::Platform {
295 code: -1,
296 message: format!("GetState failed: {}", e),
297 })?;
298 reply
299 .body()
300 .deserialize::<Vec<u32>>()
301 .map_err(|e| Error::Platform {
302 code: -1,
303 message: format!("GetState deserialize failed: {}", e),
304 })
305 }
306
307 fn is_multi_line(&self, aref: &AccessibleRef) -> bool {
313 let state_bits = self.get_state(aref).unwrap_or_default();
314 let bits: u64 = if state_bits.len() >= 2 {
315 (state_bits[0] as u64) | ((state_bits[1] as u64) << 32)
316 } else if state_bits.len() == 1 {
317 state_bits[0] as u64
318 } else {
319 0
320 };
321 const MULTI_LINE: u64 = 1 << 17;
323 (bits & MULTI_LINE) != 0
324 }
325
326 fn get_extents(&self, aref: &AccessibleRef) -> Option<Rect> {
330 if !self.has_interface(aref, "Component") {
331 return None;
332 }
333 let proxy = self
334 .make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Component")
335 .ok()?;
336 let reply = proxy.call_method("GetExtents", &(0u32,)).ok()?;
339 let (x, y, w, h): (i32, i32, i32, i32) = reply.body().deserialize().ok()?;
340 if w <= 0 && h <= 0 {
341 return None;
342 }
343 Some(Rect {
344 x,
345 y,
346 width: w.max(0) as u32,
347 height: h.max(0) as u32,
348 })
349 }
350
351 fn get_actions(&self, aref: &AccessibleRef) -> (Vec<String>, HashMap<String, i32>) {
357 let mut actions = Vec::new();
358 let mut indices = HashMap::new();
359
360 if let Ok(proxy) = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Action") {
362 let n_actions = proxy
364 .get_property::<i32>("NActions")
365 .or_else(|_| proxy.get_property::<u32>("NActions").map(|n| n as i32))
366 .unwrap_or(0);
367 for i in 0..n_actions {
368 if let Ok(reply) = proxy.call_method("GetName", &(i,)) {
369 if let Ok(name) = reply.body().deserialize::<String>() {
370 if let Some(action_name) = map_atspi_action_name(&name) {
371 if !actions.contains(&action_name) {
372 indices.insert(action_name.clone(), i);
373 actions.push(action_name);
374 }
375 }
376 }
377 }
378 }
379 }
380
381 (actions, indices)
389 }
390
391 fn is_gtk_toolkit(&self, aref: &AccessibleRef) -> bool {
398 let app_root = AccessibleRef {
399 bus_name: aref.bus_name.clone(),
400 path: "/org/a11y/atspi/accessible/root".to_string(),
401 };
402 self.make_proxy(
403 &app_root.bus_name,
404 &app_root.path,
405 "org.a11y.atspi.Application",
406 )
407 .ok()
408 .and_then(|proxy| proxy.get_property::<String>("ToolkitName").ok())
409 .map(|t| t.eq_ignore_ascii_case("GTK"))
410 .unwrap_or(false)
411 }
412
413 fn find_gtk_press_fallback(
426 &self,
427 outer: &AccessibleRef,
428 outer_name: &str,
429 ) -> Option<(AccessibleRef, i32)> {
430 let mut queue: VecDeque<(AccessibleRef, u32)> = VecDeque::new();
431 queue.push_back((outer.clone(), 0));
432 let mut visited: usize = 0;
433 let mut shallowest_depth: Option<u32> = None;
434 let mut hits: Vec<(AccessibleRef, i32)> = Vec::new();
435
436 while let Some((node, depth)) = queue.pop_front() {
437 if let Some(best) = shallowest_depth {
439 if depth > best {
440 continue;
441 }
442 }
443 if visited > GTK_FALLBACK_MAX_NODES {
444 break;
445 }
446
447 let role_name = if depth == 0 {
448 String::new()
449 } else {
450 visited += 1;
451 self.get_role_name(&node).unwrap_or_default().to_lowercase()
452 };
453
454 if depth > 0 && is_actionable_atspi_role(&role_name) {
455 if let Some(idx) = self.gtk_fallback_pick(&node, outer_name) {
456 match shallowest_depth {
457 Some(d) if depth < d => {
458 shallowest_depth = Some(depth);
459 hits.clear();
460 hits.push((node.clone(), idx));
461 }
462 Some(d) if depth == d => hits.push((node.clone(), idx)),
463 Some(_) => {}
464 None => {
465 shallowest_depth = Some(depth);
466 hits.push((node.clone(), idx));
467 }
468 }
469 }
470 }
471
472 let stop_descending = depth >= GTK_FALLBACK_MAX_DEPTH
477 || (depth > 0 && is_never_descend_atspi_role(&role_name));
478 if stop_descending {
479 continue;
480 }
481 if let Ok(children) = self.get_atspi_children(&node) {
482 for c in children {
483 queue.push_back((c, depth + 1));
484 }
485 }
486 }
487
488 if hits.len() == 1 {
489 Some(hits.into_iter().next().unwrap())
490 } else {
491 None
492 }
493 }
494
495 fn gtk_fallback_pick(&self, aref: &AccessibleRef, outer_name: &str) -> Option<i32> {
498 let (_, index_map) = self.get_actions(aref);
499 let idx = *index_map.get("press")?;
500 if !self.is_showing_visible_sensitive(aref) {
501 return None;
502 }
503 if !outer_name.is_empty() {
507 let inner_name = self.get_name(aref).unwrap_or_default();
508 if !inner_name.is_empty() && inner_name != outer_name {
509 return None;
510 }
511 }
512 Some(idx)
513 }
514
515 fn is_showing_visible_sensitive(&self, aref: &AccessibleRef) -> bool {
520 let raw = self.get_state(aref).unwrap_or_default();
521 let bits: u64 = if raw.len() >= 2 {
522 (raw[0] as u64) | ((raw[1] as u64) << 32)
523 } else if raw.len() == 1 {
524 raw[0] as u64
525 } else {
526 0
527 };
528 const SENSITIVE: u64 = 1 << 24;
529 const SHOWING: u64 = 1 << 25;
530 const VISIBLE: u64 = 1 << 30;
531 (bits & (SHOWING | VISIBLE | SENSITIVE)) == (SHOWING | VISIBLE | SENSITIVE)
532 }
533
534 fn get_value(&self, aref: &AccessibleRef) -> Option<String> {
537 let text_value = self.get_text_content(aref);
541 if text_value.is_some() {
542 return text_value;
543 }
544 if let Ok(proxy) = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Value") {
546 if let Ok(val) = proxy.get_property::<f64>("CurrentValue") {
547 return Some(val.to_string());
548 }
549 }
550 None
551 }
552
553 fn get_text_content(&self, aref: &AccessibleRef) -> Option<String> {
555 let proxy = self
556 .make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Text")
557 .ok()?;
558 let char_count: i32 = proxy.get_property("CharacterCount").ok()?;
559 if char_count > 0 {
560 let reply = proxy.call_method("GetText", &(0i32, char_count)).ok()?;
561 let text: String = reply.body().deserialize().ok()?;
562 if !text.is_empty() {
563 return Some(text);
564 }
565 }
566 None
567 }
568
569 fn cache_element(&self, aref: AccessibleRef) -> u64 {
571 let handle = NEXT_HANDLE.fetch_add(1, Ordering::Relaxed);
572 self.handle_cache
573 .lock()
574 .unwrap_or_else(|e| e.into_inner())
575 .insert(handle, aref);
576 handle
577 }
578
579 fn get_cached(&self, handle: u64) -> Result<AccessibleRef> {
581 self.handle_cache
582 .lock()
583 .unwrap_or_else(|e| e.into_inner())
584 .get(&handle)
585 .cloned()
586 .ok_or(Error::ElementStale {
587 selector: format!("handle:{}", handle),
588 })
589 }
590
591 fn build_element_data(&self, aref: &AccessibleRef, pid: Option<u32>) -> ElementData {
596 let role_name = self.get_role_name(aref).unwrap_or_default();
597 let role_num = self.get_role_number(aref).unwrap_or(0);
598 let role = {
599 let by_name = if !role_name.is_empty() {
600 map_atspi_role(&role_name)
601 } else {
602 Role::Unknown
603 };
604 let coarse = if by_name != Role::Unknown {
605 by_name
606 } else {
607 map_atspi_role_number(role_num)
608 };
609 if coarse == Role::TextArea && !self.is_multi_line(aref) {
610 Role::TextField
611 } else {
612 coarse
613 }
614 };
615
616 let (
620 ((mut name, value), description),
621 (
622 (states, bounds),
623 ((actions, action_index_map), (numeric_value, min_value, max_value)),
624 ),
625 ) = rayon::join(
626 || {
627 rayon::join(
628 || {
629 let name = self.get_name(aref).ok().filter(|s| !s.is_empty());
630 let value = if role_has_value(role) {
631 self.get_value(aref)
632 } else {
633 None
634 };
635 (name, value)
636 },
637 || self.get_description(aref).ok().filter(|s| !s.is_empty()),
638 )
639 },
640 || {
641 rayon::join(
642 || {
643 rayon::join(
644 || self.parse_states(aref, role),
645 || {
646 if role != Role::Application {
647 self.get_extents(aref)
648 } else {
649 None
650 }
651 },
652 )
653 },
654 || {
655 rayon::join(
656 || {
657 if role_has_actions(role) {
658 self.get_actions(aref)
659 } else {
660 (vec![], HashMap::new())
661 }
662 },
663 || {
664 if matches!(
665 role,
666 Role::Slider
667 | Role::ProgressBar
668 | Role::ScrollBar
669 | Role::SpinButton
670 ) {
671 if let Ok(proxy) = self.make_proxy(
672 &aref.bus_name,
673 &aref.path,
674 "org.a11y.atspi.Value",
675 ) {
676 (
677 proxy.get_property::<f64>("CurrentValue").ok(),
678 proxy.get_property::<f64>("MinimumValue").ok(),
679 proxy.get_property::<f64>("MaximumValue").ok(),
680 )
681 } else {
682 (None, None, None)
683 }
684 } else {
685 (None, None, None)
686 }
687 },
688 )
689 },
690 )
691 },
692 );
693
694 if name.is_none() && role == Role::StaticText {
697 if let Some(ref v) = value {
698 name = Some(v.clone());
699 }
700 }
701
702 let raw = {
703 let raw_role = if role_name.is_empty() {
704 format!("role_num:{}", role_num)
705 } else {
706 role_name
707 };
708 {
709 let mut raw = HashMap::new();
710 raw.insert("atspi_role".into(), serde_json::Value::String(raw_role));
711 raw.insert(
712 "bus_name".into(),
713 serde_json::Value::String(aref.bus_name.clone()),
714 );
715 raw.insert(
716 "object_path".into(),
717 serde_json::Value::String(aref.path.clone()),
718 );
719 raw
720 }
721 };
722
723 let handle = self.cache_element(aref.clone());
724 if !action_index_map.is_empty() {
725 self.action_indices
726 .lock()
727 .unwrap_or_else(|e| e.into_inner())
728 .insert(handle, action_index_map);
729 }
730
731 ElementData {
732 role,
733 name,
734 value,
735 description,
736 bounds,
737 actions,
738 states,
739 numeric_value,
740 min_value,
741 max_value,
742 pid,
743 stable_id: Some(aref.path.clone()),
744 raw,
745 handle,
746 }
747 }
748
749 fn get_atspi_parent(&self, aref: &AccessibleRef) -> Result<Option<AccessibleRef>> {
751 let proxy = self.make_proxy(
753 &aref.bus_name,
754 &aref.path,
755 "org.freedesktop.DBus.Properties",
756 )?;
757 let reply = proxy
758 .call_method("Get", &("org.a11y.atspi.Accessible", "Parent"))
759 .map_err(|e| Error::Platform {
760 code: -1,
761 message: format!("Get Parent property failed: {}", e),
762 })?;
763 let variant: zbus::zvariant::OwnedValue =
765 reply.body().deserialize().map_err(|e| Error::Platform {
766 code: -1,
767 message: format!("Parent deserialize variant failed: {}", e),
768 })?;
769 let (bus, path): (String, zbus::zvariant::OwnedObjectPath) =
770 zbus::zvariant::Value::from(variant).try_into().map_err(
771 |e: zbus::zvariant::Error| Error::Platform {
772 code: -1,
773 message: format!("Parent deserialize struct failed: {}", e),
774 },
775 )?;
776 let path_str = path.as_str();
777 if path_str == "/org/a11y/atspi/null" || bus.is_empty() || path_str.is_empty() {
778 return Ok(None);
779 }
780 if path_str == "/org/a11y/atspi/accessible/root" {
782 return Ok(None);
783 }
784 Ok(Some(AccessibleRef {
785 bus_name: bus,
786 path: path_str.to_string(),
787 }))
788 }
789
790 fn parse_states(&self, aref: &AccessibleRef, role: Role) -> StateSet {
792 let state_bits = self.get_state(aref).unwrap_or_default();
793
794 let bits: u64 = if state_bits.len() >= 2 {
796 (state_bits[0] as u64) | ((state_bits[1] as u64) << 32)
797 } else if state_bits.len() == 1 {
798 state_bits[0] as u64
799 } else {
800 0
801 };
802
803 const BUSY: u64 = 1 << 3;
805 const CHECKED: u64 = 1 << 4;
806 const EDITABLE: u64 = 1 << 7;
807 const ENABLED: u64 = 1 << 8;
808 const EXPANDABLE: u64 = 1 << 9;
809 const EXPANDED: u64 = 1 << 10;
810 const FOCUSABLE: u64 = 1 << 11;
811 const FOCUSED: u64 = 1 << 12;
812 const MODAL: u64 = 1 << 16;
813 const SELECTED: u64 = 1 << 23;
814 const SENSITIVE: u64 = 1 << 24;
815 const SHOWING: u64 = 1 << 25;
816 const VISIBLE: u64 = 1 << 30;
817 const INDETERMINATE: u64 = 1 << 32;
818 const REQUIRED: u64 = 1 << 33;
819
820 let enabled = (bits & ENABLED) != 0 || (bits & SENSITIVE) != 0;
821 let visible = (bits & VISIBLE) != 0 || (bits & SHOWING) != 0;
822
823 let checked = match role {
824 Role::CheckBox | Role::RadioButton | Role::MenuItem | Role::Switch => {
825 if (bits & INDETERMINATE) != 0 {
826 Some(Toggled::Mixed)
827 } else if (bits & CHECKED) != 0 {
828 Some(Toggled::On)
829 } else {
830 Some(Toggled::Off)
831 }
832 }
833 _ => None,
834 };
835
836 let expanded = if (bits & EXPANDABLE) != 0 {
837 Some((bits & EXPANDED) != 0)
838 } else {
839 None
840 };
841
842 StateSet {
843 enabled,
844 visible,
845 focused: (bits & FOCUSED) != 0,
846 checked,
847 selected: (bits & SELECTED) != 0,
848 expanded,
849 editable: (bits & EDITABLE) != 0,
850 focusable: (bits & FOCUSABLE) != 0,
851 modal: (bits & MODAL) != 0,
852 required: (bits & REQUIRED) != 0,
853 busy: (bits & BUSY) != 0,
854 }
855 }
856
857 pub(crate) fn find_app_by_pid(&self, pid: u32) -> Result<AccessibleRef> {
862 let registry = AccessibleRef {
863 bus_name: "org.a11y.atspi.Registry".to_string(),
864 path: "/org/a11y/atspi/accessible/root".to_string(),
865 };
866 let children = self.get_atspi_children(®istry)?;
867
868 for child in &children {
869 if child.path == "/org/a11y/atspi/null" {
870 continue;
871 }
872 if let Some(app_pid) = self.get_dbus_pid(&child.bus_name) {
878 if app_pid == pid {
879 return Ok(child.clone());
880 }
881 }
882 if let Ok(proxy) =
884 self.make_proxy(&child.bus_name, &child.path, "org.a11y.atspi.Application")
885 {
886 if let Ok(app_pid) = proxy.get_property::<i32>("Id") {
887 if app_pid as u32 == pid {
888 return Ok(child.clone());
889 }
890 }
891 }
892 }
893
894 Err(Error::Platform {
895 code: -1,
896 message: format!("No application found with PID {}", pid),
897 })
898 }
899
900 fn get_dbus_pid(&self, bus_name: &str) -> Option<u32> {
902 let proxy = self
903 .make_proxy(
904 "org.freedesktop.DBus",
905 "/org/freedesktop/DBus",
906 "org.freedesktop.DBus",
907 )
908 .ok()?;
909 let reply = proxy
910 .call_method("GetConnectionUnixProcessID", &(bus_name,))
911 .ok()?;
912 let pid: u32 = reply.body().deserialize().ok()?;
913 if pid > 0 {
914 Some(pid)
915 } else {
916 None
917 }
918 }
919
920 fn do_atspi_action_by_index(&self, aref: &AccessibleRef, index: i32) -> Result<()> {
922 let proxy = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Action")?;
923 proxy
924 .call_method("DoAction", &(index,))
925 .map_err(|e| Error::Platform {
926 code: -1,
927 message: format!("DoAction({}) failed: {}", index, e),
928 })?;
929 Ok(())
930 }
931
932 fn get_action_index(&self, handle: u64, action: &str) -> Result<i32> {
934 self.action_indices
935 .lock()
936 .unwrap_or_else(|e| e.into_inner())
937 .get(&handle)
938 .and_then(|map| map.get(action).copied())
939 .ok_or_else(|| Error::ActionNotSupported {
940 action: action.to_string(),
941 role: Role::Unknown, })
943 }
944
945 fn get_app_pid(&self, aref: &AccessibleRef) -> Option<u32> {
951 if let Some(pid) = self.get_dbus_pid(&aref.bus_name) {
952 return Some(pid);
953 }
954
955 if let Ok(proxy) = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Application")
957 {
958 if let Ok(pid) = proxy.get_property::<i32>("Id") {
959 if pid > 0 {
960 return Some(pid as u32);
961 }
962 }
963 }
964
965 None
966 }
967
968 fn resolve_role(&self, aref: &AccessibleRef) -> Role {
970 let role_name = self.get_role_name(aref).unwrap_or_default();
971 let by_name = if !role_name.is_empty() {
972 map_atspi_role(&role_name)
973 } else {
974 Role::Unknown
975 };
976 let coarse = if by_name != Role::Unknown {
977 by_name
978 } else {
979 let role_num = self.get_role_number(aref).unwrap_or(0);
981 map_atspi_role_number(role_num)
982 };
983 if coarse == Role::TextArea && !self.is_multi_line(aref) {
985 Role::TextField
986 } else {
987 coarse
988 }
989 }
990
991 fn matches_ref(
1005 &self,
1006 aref: &AccessibleRef,
1007 simple: &xa11y_core::selector::SimpleSelector,
1008 ) -> bool {
1009 let needs_role = simple.role.is_some()
1012 || simple
1013 .filters
1014 .iter()
1015 .any(|f| matches!(f.attr.as_str(), "role" | "checked"));
1016 let role = if needs_role {
1017 Some(self.resolve_role(aref))
1018 } else {
1019 None
1020 };
1021
1022 if let Some(ref role_match) = simple.role {
1023 match role_match {
1024 xa11y_core::selector::RoleMatch::Normalized(expected) => {
1025 if role != Some(*expected) {
1026 return false;
1027 }
1028 }
1029 xa11y_core::selector::RoleMatch::Platform(platform_role) => {
1030 let raw_role = self.get_role_name(aref).unwrap_or_default();
1031 if raw_role != *platform_role {
1032 return false;
1033 }
1034 }
1035 }
1036 }
1037
1038 let mut state_set: Option<StateSet> = None;
1039
1040 for filter in &simple.filters {
1041 let attr = filter.attr.as_str();
1042 let resolved: Option<Option<String>> = match attr {
1043 "role" => Some(role.map(|r| r.to_snake_case().to_string())),
1044 "name" => {
1045 let name = self.get_name(aref).ok().filter(|s| !s.is_empty());
1046 let resolved = if name.is_none() && role == Some(Role::StaticText) {
1049 self.get_value(aref)
1050 } else {
1051 name
1052 };
1053 Some(resolved)
1054 }
1055 "value" => Some(self.get_value(aref)),
1056 "description" => Some(self.get_description(aref).ok().filter(|s| !s.is_empty())),
1057 "enabled" | "visible" | "focused" | "focusable" | "selected" | "editable"
1058 | "modal" | "required" | "busy" | "expanded" | "checked" => {
1059 let s = state_set.get_or_insert_with(|| {
1060 self.parse_states(aref, role.unwrap_or(Role::Unknown))
1064 });
1065 Some(state_attr_to_string(attr, s))
1066 }
1067 _ => None, };
1069
1070 match resolved {
1071 Some(value) => {
1072 if !xa11y_core::selector::match_op(&filter.op, &filter.value, value.as_deref())
1073 {
1074 return false;
1075 }
1076 }
1077 None => {
1078 let pid = None; let data = self.build_element_data(aref, pid);
1086 return xa11y_core::selector::matches_simple(&data, simple);
1087 }
1088 }
1089 }
1090
1091 true
1092 }
1093
1094 fn collect_matching_refs(
1100 &self,
1101 parent: &AccessibleRef,
1102 simple: &xa11y_core::selector::SimpleSelector,
1103 depth: u32,
1104 max_depth: u32,
1105 limit: Option<usize>,
1106 ) -> Result<Vec<AccessibleRef>> {
1107 if depth > max_depth {
1108 return Ok(vec![]);
1109 }
1110
1111 let children = self.get_atspi_children(parent)?;
1112
1113 let parent_is_registry = parent.bus_name == "org.a11y.atspi.Registry";
1121 let mut to_search: Vec<AccessibleRef> = Vec::new();
1122 for child in children {
1123 if child.path == "/org/a11y/atspi/null"
1124 || child.bus_name.is_empty()
1125 || child.path.is_empty()
1126 {
1127 continue;
1128 }
1129
1130 if !parent_is_registry {
1131 let child_role = self.get_role_name(&child).unwrap_or_default();
1132 if child_role == "application" {
1133 let grandchildren = self.get_atspi_children(&child).unwrap_or_default();
1134 for gc in grandchildren {
1135 if gc.path == "/org/a11y/atspi/null"
1136 || gc.bus_name.is_empty()
1137 || gc.path.is_empty()
1138 {
1139 continue;
1140 }
1141 let gc_role = self.get_role_name(&gc).unwrap_or_default();
1142 if gc_role == "application" {
1143 continue;
1144 }
1145 to_search.push(gc);
1146 }
1147 continue;
1148 }
1149 }
1150 to_search.push(child);
1151 }
1152
1153 if to_search.is_empty() {
1156 self.check_chromium_a11y_enabled(parent, None)?;
1157 }
1158
1159 let per_child: Vec<(Vec<AccessibleRef>, Option<Error>)> = to_search
1168 .par_iter()
1169 .map(|child| {
1170 let mut child_results = Vec::new();
1171 if self.matches_ref(child, simple) {
1172 child_results.push(child.clone());
1173 }
1174 match self.collect_matching_refs(child, simple, depth + 1, max_depth, limit) {
1175 Ok(sub) => {
1176 child_results.extend(sub);
1177 (child_results, None)
1178 }
1179 Err(e @ Error::AccessibilityNotEnabled { .. }) => (Vec::new(), Some(e)),
1180 Err(_) => (child_results, None),
1181 }
1182 })
1183 .collect();
1184
1185 let mut results = Vec::new();
1190 for (batch, maybe_err) in per_child {
1191 if let Some(err) = maybe_err {
1192 return Err(err);
1193 }
1194 for r in batch {
1195 results.push(r);
1196 if let Some(limit) = limit {
1197 if results.len() >= limit {
1198 return Ok(results);
1199 }
1200 }
1201 }
1202 }
1203 Ok(results)
1204 }
1205}
1206
1207impl Provider for LinuxProvider {
1208 fn get_children(&self, element: Option<&ElementData>) -> Result<Vec<ElementData>> {
1209 match element {
1210 None => {
1211 let registry = AccessibleRef {
1213 bus_name: "org.a11y.atspi.Registry".to_string(),
1214 path: "/org/a11y/atspi/accessible/root".to_string(),
1215 };
1216 let children = self.get_atspi_children(®istry)?;
1217
1218 let valid: Vec<(&AccessibleRef, String)> = children
1220 .iter()
1221 .filter(|c| c.path != "/org/a11y/atspi/null")
1222 .filter_map(|c| {
1223 let name = self.get_name(c).unwrap_or_default();
1224 if name.is_empty() {
1225 None
1226 } else {
1227 Some((c, name))
1228 }
1229 })
1230 .collect();
1231
1232 let results: Vec<ElementData> = valid
1233 .par_iter()
1234 .map(|(child, app_name)| {
1235 let pid = self.get_app_pid(child);
1236 let mut data = self.build_element_data(child, pid);
1237 data.name = Some(app_name.clone());
1238 data
1239 })
1240 .collect();
1241
1242 Ok(results)
1243 }
1244 Some(element_data) => {
1245 let aref = self.get_cached(element_data.handle)?;
1246 let children = self.get_atspi_children(&aref).unwrap_or_default();
1247 let pid = element_data.pid;
1248
1249 let mut to_build: Vec<AccessibleRef> = Vec::new();
1252 for child_ref in &children {
1253 if child_ref.path == "/org/a11y/atspi/null"
1254 || child_ref.bus_name.is_empty()
1255 || child_ref.path.is_empty()
1256 {
1257 continue;
1258 }
1259 let child_role = self.get_role_name(child_ref).unwrap_or_default();
1260 if child_role == "application" {
1261 let grandchildren = self.get_atspi_children(child_ref).unwrap_or_default();
1262 for gc_ref in grandchildren {
1263 if gc_ref.path == "/org/a11y/atspi/null"
1264 || gc_ref.bus_name.is_empty()
1265 || gc_ref.path.is_empty()
1266 {
1267 continue;
1268 }
1269 let gc_role = self.get_role_name(&gc_ref).unwrap_or_default();
1270 if gc_role == "application" {
1271 continue;
1272 }
1273 to_build.push(gc_ref);
1274 }
1275 continue;
1276 }
1277 to_build.push(child_ref.clone());
1278 }
1279
1280 if to_build.is_empty() {
1281 self.check_chromium_a11y_enabled(&aref, Some(element_data.role))?;
1282 }
1283
1284 let results: Vec<ElementData> = to_build
1285 .par_iter()
1286 .map(|r| self.build_element_data(r, pid))
1287 .collect();
1288
1289 Ok(results)
1290 }
1291 }
1292 }
1293
1294 fn find_elements(
1295 &self,
1296 root: Option<&ElementData>,
1297 selector: &Selector,
1298 limit: Option<usize>,
1299 max_depth: Option<u32>,
1300 ) -> Result<Vec<ElementData>> {
1301 if selector.segments.is_empty() {
1302 return Ok(vec![]);
1303 }
1304
1305 let max_depth_val = max_depth.unwrap_or(xa11y_core::MAX_TREE_DEPTH);
1306
1307 let first = &selector.segments[0].simple;
1310
1311 let phase1_limit = if selector.segments.len() == 1 {
1312 limit
1313 } else {
1314 None
1315 };
1316 let phase1_limit = match (phase1_limit, first.nth) {
1317 (Some(l), Some(n)) => Some(l.max(n)),
1318 (_, Some(n)) => Some(n),
1319 (l, None) => l,
1320 };
1321
1322 let phase1_depth = if root.is_none()
1324 && matches!(
1325 first.role,
1326 Some(xa11y_core::selector::RoleMatch::Normalized(
1327 Role::Application
1328 ))
1329 ) {
1330 0
1331 } else {
1332 max_depth_val
1333 };
1334
1335 let start_ref = match root {
1336 None => AccessibleRef {
1337 bus_name: "org.a11y.atspi.Registry".to_string(),
1338 path: "/org/a11y/atspi/accessible/root".to_string(),
1339 },
1340 Some(el) => self.get_cached(el.handle)?,
1341 };
1342
1343 let mut matching_refs =
1344 self.collect_matching_refs(&start_ref, first, 0, phase1_depth, phase1_limit)?;
1345
1346 let pid_from_root = root.and_then(|r| r.pid);
1347
1348 if selector.segments.len() == 1 {
1350 if let Some(nth) = first.nth {
1351 if nth <= matching_refs.len() {
1352 let aref = &matching_refs[nth - 1];
1353 let pid = if root.is_none() {
1354 self.get_app_pid(aref)
1355 .or_else(|| self.get_dbus_pid(&aref.bus_name))
1356 } else {
1357 pid_from_root
1358 };
1359 return Ok(vec![self.build_element_data(aref, pid)]);
1360 } else {
1361 return Ok(vec![]);
1362 }
1363 }
1364
1365 if let Some(limit) = limit {
1366 matching_refs.truncate(limit);
1367 }
1368
1369 let is_root_search = root.is_none();
1370 return Ok(matching_refs
1371 .par_iter()
1372 .map(|aref| {
1373 let pid = if is_root_search {
1374 self.get_app_pid(aref)
1375 .or_else(|| self.get_dbus_pid(&aref.bus_name))
1376 } else {
1377 pid_from_root
1378 };
1379 self.build_element_data(aref, pid)
1380 })
1381 .collect());
1382 }
1383
1384 let is_root_search = root.is_none();
1387 let mut candidates: Vec<ElementData> = matching_refs
1388 .par_iter()
1389 .map(|aref| {
1390 let pid = if is_root_search {
1391 self.get_app_pid(aref)
1392 .or_else(|| self.get_dbus_pid(&aref.bus_name))
1393 } else {
1394 pid_from_root
1395 };
1396 self.build_element_data(aref, pid)
1397 })
1398 .collect();
1399
1400 for segment in &selector.segments[1..] {
1401 let mut next_candidates = Vec::new();
1402 for candidate in &candidates {
1403 match segment.combinator {
1404 Combinator::Child => {
1405 let children = self.get_children(Some(candidate))?;
1406 for child in children {
1407 if xa11y_core::selector::matches_simple(&child, &segment.simple) {
1408 next_candidates.push(child);
1409 }
1410 }
1411 }
1412 Combinator::Descendant => {
1413 let sub_selector = Selector {
1414 segments: vec![SelectorSegment {
1415 combinator: Combinator::Root,
1416 simple: segment.simple.clone(),
1417 }],
1418 };
1419 let mut sub_results = xa11y_core::selector::find_elements_in_tree(
1420 |el| self.get_children(el),
1421 Some(candidate),
1422 &sub_selector,
1423 None,
1424 Some(max_depth_val),
1425 )?;
1426 next_candidates.append(&mut sub_results);
1427 }
1428 Combinator::Root => unreachable!(),
1429 }
1430 }
1431 let mut seen = HashSet::new();
1432 next_candidates.retain(|e| seen.insert(e.handle));
1433 candidates = next_candidates;
1434 }
1435
1436 if let Some(nth) = selector.segments.last().and_then(|s| s.simple.nth) {
1438 if nth <= candidates.len() {
1439 candidates = vec![candidates.remove(nth - 1)];
1440 } else {
1441 candidates.clear();
1442 }
1443 }
1444
1445 if let Some(limit) = limit {
1446 candidates.truncate(limit);
1447 }
1448
1449 Ok(candidates)
1450 }
1451
1452 fn get_parent(&self, element: &ElementData) -> Result<Option<ElementData>> {
1453 let aref = self.get_cached(element.handle)?;
1454 match self.get_atspi_parent(&aref)? {
1455 Some(parent_ref) => {
1456 let data = self.build_element_data(&parent_ref, element.pid);
1457 Ok(Some(data))
1458 }
1459 None => Ok(None),
1460 }
1461 }
1462
1463 fn press(&self, element: &ElementData) -> Result<()> {
1464 let target = self.get_cached(element.handle)?;
1465 if let Ok(index) = self.get_action_index(element.handle, "press") {
1467 return self.do_atspi_action_by_index(&target, index);
1468 }
1469 if element.role == Role::Button && self.is_gtk_toolkit(&target) {
1488 let outer_name = self.get_name(&target).unwrap_or_default();
1489 if let Some((inner, index)) = self.find_gtk_press_fallback(&target, &outer_name) {
1490 return self.do_atspi_action_by_index(&inner, index);
1491 }
1492 }
1493 Err(Error::ActionNotSupported {
1494 action: "press".to_string(),
1495 role: element.role,
1496 })
1497 }
1498
1499 fn focus(&self, element: &ElementData) -> Result<()> {
1500 let target = self.get_cached(element.handle)?;
1501 if let Ok(proxy) =
1505 self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Component")
1506 {
1507 if let Ok(reply) = proxy.call_method("GrabFocus", &()) {
1508 if let Ok(true) = reply.body().deserialize::<bool>() {
1510 return Ok(());
1511 }
1512 }
1514 }
1515 if let Ok(index) = self.get_action_index(element.handle, "focus") {
1516 return self.do_atspi_action_by_index(&target, index);
1517 }
1518 Err(Error::ActionNotSupported {
1519 action: "focus".to_string(),
1520 role: element.role,
1521 })
1522 }
1523
1524 fn blur(&self, element: &ElementData) -> Result<()> {
1525 let target = self.get_cached(element.handle)?;
1526 if let Some(parent_ref) = self.get_atspi_parent(&target)? {
1530 if parent_ref.path != "/org/a11y/atspi/null" {
1531 let p = self.make_proxy(
1532 &parent_ref.bus_name,
1533 &parent_ref.path,
1534 "org.a11y.atspi.Component",
1535 )?;
1536 p.call_method("GrabFocus", &())
1537 .map_err(|e| Error::Platform {
1538 code: -1,
1539 message: format!("Component.GrabFocus on parent failed: {}", e),
1540 })?;
1541 return Ok(());
1542 }
1543 }
1544 Err(Error::ActionNotSupported {
1545 action: "blur".to_string(),
1546 role: element.role,
1547 })
1548 }
1549
1550 fn toggle(&self, element: &ElementData) -> Result<()> {
1551 let target = self.get_cached(element.handle)?;
1552 let index = self
1553 .get_action_index(element.handle, "toggle")
1554 .map_err(|_| Error::ActionNotSupported {
1555 action: "toggle".to_string(),
1556 role: element.role,
1557 })?;
1558 self.do_atspi_action_by_index(&target, index)
1559 }
1560
1561 fn select(&self, element: &ElementData) -> Result<()> {
1562 let target = self.get_cached(element.handle)?;
1563 let index = self
1564 .get_action_index(element.handle, "select")
1565 .map_err(|_| Error::ActionNotSupported {
1566 action: "select".to_string(),
1567 role: element.role,
1568 })?;
1569 self.do_atspi_action_by_index(&target, index)
1570 }
1571
1572 fn expand(&self, element: &ElementData) -> Result<()> {
1573 let target = self.get_cached(element.handle)?;
1574 let index = self
1575 .get_action_index(element.handle, "expand")
1576 .map_err(|_| Error::ActionNotSupported {
1577 action: "expand".to_string(),
1578 role: element.role,
1579 })?;
1580 self.do_atspi_action_by_index(&target, index)
1581 }
1582
1583 fn collapse(&self, element: &ElementData) -> Result<()> {
1584 let target = self.get_cached(element.handle)?;
1585 let index = self
1586 .get_action_index(element.handle, "collapse")
1587 .map_err(|_| Error::ActionNotSupported {
1588 action: "collapse".to_string(),
1589 role: element.role,
1590 })?;
1591 self.do_atspi_action_by_index(&target, index)
1592 }
1593
1594 fn show_menu(&self, element: &ElementData) -> Result<()> {
1595 let target = self.get_cached(element.handle)?;
1596 let index = self
1597 .get_action_index(element.handle, "show_menu")
1598 .map_err(|_| Error::ActionNotSupported {
1599 action: "show_menu".to_string(),
1600 role: element.role,
1601 })?;
1602 self.do_atspi_action_by_index(&target, index)
1603 }
1604
1605 fn increment(&self, element: &ElementData) -> Result<()> {
1606 let target = self.get_cached(element.handle)?;
1607 if let Ok(index) = self.get_action_index(element.handle, "increment") {
1609 return self.do_atspi_action_by_index(&target, index);
1610 }
1611 let proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Value")?;
1612 let current: f64 = proxy
1613 .get_property("CurrentValue")
1614 .map_err(|e| Error::Platform {
1615 code: -1,
1616 message: format!("Value.CurrentValue failed: {}", e),
1617 })?;
1618 let step: f64 = proxy.get_property("MinimumIncrement").unwrap_or(1.0);
1619 let step = if step <= 0.0 { 1.0 } else { step };
1620 proxy
1621 .set_property("CurrentValue", current + step)
1622 .map_err(|e| Error::Platform {
1623 code: -1,
1624 message: format!("Value.SetCurrentValue failed: {}", e),
1625 })
1626 }
1627
1628 fn decrement(&self, element: &ElementData) -> Result<()> {
1629 let target = self.get_cached(element.handle)?;
1630 if let Ok(index) = self.get_action_index(element.handle, "decrement") {
1631 return self.do_atspi_action_by_index(&target, index);
1632 }
1633 let proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Value")?;
1634 let current: f64 = proxy
1635 .get_property("CurrentValue")
1636 .map_err(|e| Error::Platform {
1637 code: -1,
1638 message: format!("Value.CurrentValue failed: {}", e),
1639 })?;
1640 let step: f64 = proxy.get_property("MinimumIncrement").unwrap_or(1.0);
1641 let step = if step <= 0.0 { 1.0 } else { step };
1642 proxy
1643 .set_property("CurrentValue", current - step)
1644 .map_err(|e| Error::Platform {
1645 code: -1,
1646 message: format!("Value.SetCurrentValue failed: {}", e),
1647 })
1648 }
1649
1650 fn scroll_into_view(&self, element: &ElementData) -> Result<()> {
1651 let target = self.get_cached(element.handle)?;
1652 let proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Component")?;
1653 proxy
1654 .call_method("ScrollTo", &(0u32,))
1655 .map_err(|e| Error::Platform {
1656 code: -1,
1657 message: format!("ScrollTo failed: {}", e),
1658 })?;
1659 Ok(())
1660 }
1661
1662 fn set_value(&self, element: &ElementData, value: &str) -> Result<()> {
1663 let target = self.get_cached(element.handle)?;
1664 let proxy = self
1665 .make_proxy(
1666 &target.bus_name,
1667 &target.path,
1668 "org.a11y.atspi.EditableText",
1669 )
1670 .map_err(|_| Error::TextValueNotSupported)?;
1671 if proxy.call_method("SetTextContents", &(value,)).is_ok() {
1673 return Ok(());
1674 }
1675 let classify_editable_text_error = |op: &str, e: zbus::Error| -> Error {
1681 let msg = e.to_string();
1682 if msg.contains("UnknownMethod") || msg.contains("UnknownInterface") {
1683 Error::TextValueNotSupported
1684 } else {
1685 Error::Platform {
1686 code: -1,
1687 message: format!("EditableText.{} failed: {}", op, msg),
1688 }
1689 }
1690 };
1691 if let Err(e) = proxy.call_method("DeleteText", &(0i32, i32::MAX)) {
1692 return Err(classify_editable_text_error("DeleteText", e));
1693 }
1694 if let Err(e) = proxy.call_method("InsertText", &(0i32, value, value.len() as i32)) {
1695 return Err(classify_editable_text_error("InsertText", e));
1696 }
1697 Ok(())
1698 }
1699
1700 fn set_numeric_value(&self, element: &ElementData, value: f64) -> Result<()> {
1701 let target = self.get_cached(element.handle)?;
1702 let proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Value")?;
1703 proxy
1704 .set_property("CurrentValue", value)
1705 .map_err(|e| Error::Platform {
1706 code: -1,
1707 message: format!("SetValue failed: {}", e),
1708 })
1709 }
1710
1711 fn type_text(&self, element: &ElementData, text: &str) -> Result<()> {
1712 let target = self.get_cached(element.handle)?;
1713 let text_proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Text");
1716 let insert_pos = text_proxy
1717 .as_ref()
1718 .ok()
1719 .and_then(|p| p.get_property::<i32>("CaretOffset").ok())
1720 .unwrap_or(-1); let proxy = self
1723 .make_proxy(
1724 &target.bus_name,
1725 &target.path,
1726 "org.a11y.atspi.EditableText",
1727 )
1728 .map_err(|_| Error::TextValueNotSupported)?;
1729 let pos = if insert_pos >= 0 {
1730 insert_pos
1731 } else {
1732 i32::MAX
1733 };
1734 proxy
1735 .call_method("InsertText", &(pos, text, text.len() as i32))
1736 .map_err(|e| Error::Platform {
1737 code: -1,
1738 message: format!("EditableText.InsertText failed: {}", e),
1739 })?;
1740 Ok(())
1741 }
1742
1743 fn set_text_selection(&self, element: &ElementData, start: u32, end: u32) -> Result<()> {
1744 let target = self.get_cached(element.handle)?;
1745 let proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Text")?;
1746 proxy
1747 .call_method("SetSelection", &(0i32, start as i32, end as i32))
1748 .map_err(|e| Error::Platform {
1749 code: -1,
1750 message: format!("Text.SetSelection failed: {}", e),
1751 })?;
1752 Ok(())
1753 }
1754
1755 fn perform_action(&self, element: &ElementData, action: &str) -> Result<()> {
1756 match action {
1757 "press" => self.press(element),
1758 "focus" => self.focus(element),
1759 "blur" => self.blur(element),
1760 "toggle" => self.toggle(element),
1761 "select" => self.select(element),
1762 "expand" => self.expand(element),
1763 "collapse" => self.collapse(element),
1764 "show_menu" => self.show_menu(element),
1765 "increment" => self.increment(element),
1766 "decrement" => self.decrement(element),
1767 "scroll_into_view" => self.scroll_into_view(element),
1768 _ => Err(Error::ActionNotSupported {
1769 action: action.to_string(),
1770 role: element.role,
1771 }),
1772 }
1773 }
1774
1775 fn subscribe(&self, element: &ElementData) -> Result<Subscription> {
1776 let pid = element.pid.ok_or(Error::Platform {
1777 code: -1,
1778 message: "Element has no PID for subscribe".to_string(),
1779 })?;
1780 let app_name = element.name.clone().unwrap_or_default();
1781 crate::events::subscribe_for_pid(self, pid, app_name)
1782 }
1783}
1784
1785fn role_has_value(role: Role) -> bool {
1788 !matches!(
1789 role,
1790 Role::Application
1791 | Role::Window
1792 | Role::Dialog
1793 | Role::Group
1794 | Role::MenuBar
1795 | Role::Toolbar
1796 | Role::TabGroup
1797 | Role::SplitGroup
1798 | Role::Table
1799 | Role::TableRow
1800 | Role::Separator
1801 )
1802}
1803
1804fn role_has_actions(role: Role) -> bool {
1807 matches!(
1808 role,
1809 Role::Button
1810 | Role::CheckBox
1811 | Role::RadioButton
1812 | Role::MenuItem
1813 | Role::Link
1814 | Role::ComboBox
1815 | Role::TextField
1816 | Role::TextArea
1817 | Role::SpinButton
1818 | Role::Tab
1819 | Role::TreeItem
1820 | Role::ListItem
1821 | Role::ScrollBar
1822 | Role::Slider
1823 | Role::Menu
1824 | Role::Image
1825 | Role::Unknown
1826 )
1827}
1828
1829pub(crate) fn map_atspi_role(role_name: &str) -> Role {
1831 match role_name.to_lowercase().as_str() {
1832 "application" => Role::Application,
1833 "window" | "frame" => Role::Window,
1834 "dialog" | "file chooser" => Role::Dialog,
1835 "alert" | "notification" => Role::Alert,
1836 "push button" | "push button menu" => Role::Button,
1837 "toggle button" => Role::Switch,
1838 "check box" | "check menu item" => Role::CheckBox,
1839 "radio button" | "radio menu item" => Role::RadioButton,
1840 "entry" | "password text" => Role::TextField,
1841 "spin button" | "spinbutton" => Role::SpinButton,
1842 "text" | "textbox" => Role::TextArea,
1846 "label" | "static" | "caption" => Role::StaticText,
1847 "combo box" | "combobox" => Role::ComboBox,
1848 "list" | "list box" | "listbox" => Role::List,
1850 "list item" => Role::ListItem,
1851 "menu" => Role::Menu,
1852 "menu item" | "tearoff menu item" => Role::MenuItem,
1853 "menu bar" => Role::MenuBar,
1854 "page tab" => Role::Tab,
1855 "page tab list" => Role::TabGroup,
1856 "table" | "tree table" => Role::Table,
1857 "table row" => Role::TableRow,
1858 "table cell" | "table column header" | "table row header" => Role::TableCell,
1859 "tool bar" => Role::Toolbar,
1860 "scroll bar" => Role::ScrollBar,
1861 "slider" => Role::Slider,
1862 "image" | "icon" | "desktop icon" => Role::Image,
1863 "link" => Role::Link,
1864 "panel" | "section" | "form" | "filler" | "viewport" | "scroll pane" => Role::Group,
1865 "progress bar" => Role::ProgressBar,
1866 "tree item" => Role::TreeItem,
1867 "document web" | "document frame" => Role::WebArea,
1868 "heading" => Role::Heading,
1869 "separator" => Role::Separator,
1870 "split pane" => Role::SplitGroup,
1871 "tooltip" | "tool tip" => Role::Tooltip,
1872 "status bar" | "statusbar" => Role::Status,
1873 "landmark" | "navigation" => Role::Navigation,
1874 _ => xa11y_core::unknown_role(role_name),
1875 }
1876}
1877
1878pub(crate) fn map_atspi_role_number(role: u32) -> Role {
1881 match role {
1882 2 => Role::Alert, 7 => Role::CheckBox, 8 => Role::CheckBox, 11 => Role::ComboBox, 16 => Role::Dialog, 19 => Role::Dialog, 20 => Role::Group, 23 => Role::Window, 26 => Role::Image, 27 => Role::Image, 29 => Role::StaticText, 31 => Role::List, 32 => Role::ListItem, 33 => Role::Menu, 34 => Role::MenuBar, 35 => Role::MenuItem, 37 => Role::Tab, 38 => Role::TabGroup, 39 => Role::Group, 40 => Role::TextField, 42 => Role::ProgressBar, 43 => Role::Button, 44 => Role::RadioButton, 45 => Role::RadioButton, 48 => Role::ScrollBar, 49 => Role::Group, 50 => Role::Separator, 51 => Role::Slider, 52 => Role::SpinButton, 53 => Role::SplitGroup, 55 => Role::Table, 56 => Role::TableCell, 57 => Role::TableCell, 58 => Role::TableCell, 61 => Role::TextArea, 62 => Role::Switch, 63 => Role::Toolbar, 65 => Role::Group, 66 => Role::Table, 67 => Role::Unknown, 68 => Role::Group, 69 => Role::Window, 75 => Role::Application, 78 => Role::TextArea, 79 => Role::TextField, 82 => Role::WebArea, 83 => Role::Heading, 85 => Role::Group, 86 => Role::Group, 87 => Role::Group, 88 => Role::Link, 90 => Role::TableRow, 91 => Role::TreeItem, 95 => Role::WebArea, 97 => Role::List, 98 => Role::List, 93 => Role::Tooltip, 101 => Role::Alert, 116 => Role::StaticText, 129 => Role::Button, _ => xa11y_core::unknown_role(&format!("AT-SPI role number {role}")),
1944 }
1945}
1946
1947const GTK_FALLBACK_MAX_DEPTH: u32 = 3;
1951
1952const GTK_FALLBACK_MAX_NODES: usize = 200;
1955
1956fn is_actionable_atspi_role(role: &str) -> bool {
1961 matches!(
1962 role,
1963 "push button"
1964 | "toggle button"
1965 | "check box"
1966 | "radio button"
1967 | "menu item"
1968 | "check menu item"
1969 | "radio menu item"
1970 | "link"
1971 | "page tab"
1972 | "tab"
1973 | "list item"
1974 | "tree item"
1975 )
1976}
1977
1978fn is_never_descend_atspi_role(role: &str) -> bool {
1983 matches!(
1984 role,
1985 "label" | "separator" | "image" | "icon" | "static" | "caption"
1986 )
1987}
1988
1989fn map_atspi_action_name(action_name: &str) -> Option<String> {
2003 let lower = action_name.to_lowercase();
2012 let collapsed: String = lower.chars().filter(|c| !matches!(c, '_' | ' ')).collect();
2013 let canonical = match collapsed.as_str() {
2014 "click" | "activate" | "press" | "invoke" | "dodefault" => "press",
2015 "toggle" | "check" | "uncheck" => "toggle",
2016 "expand" | "open" => "expand",
2017 "collapse" | "close" => "collapse",
2018 "select" => "select",
2019 "menu" | "showmenu" | "showcontextmenu" | "contextmenu" | "popup" => "show_menu",
2020 "increment" => "increment",
2021 "decrement" => "decrement",
2022 _ => return None,
2023 };
2024 Some(canonical.to_string())
2025}
2026
2027#[cfg(test)]
2028mod tests {
2029 use super::*;
2030
2031 #[test]
2032 fn test_role_mapping() {
2033 assert_eq!(map_atspi_role("push button"), Role::Button);
2034 assert_eq!(map_atspi_role("toggle button"), Role::Switch);
2035 assert_eq!(map_atspi_role("check box"), Role::CheckBox);
2036 assert_eq!(map_atspi_role("entry"), Role::TextField);
2037 assert_eq!(map_atspi_role("label"), Role::StaticText);
2038 assert_eq!(map_atspi_role("window"), Role::Window);
2039 assert_eq!(map_atspi_role("frame"), Role::Window);
2040 assert_eq!(map_atspi_role("dialog"), Role::Dialog);
2041 assert_eq!(map_atspi_role("combo box"), Role::ComboBox);
2042 assert_eq!(map_atspi_role("slider"), Role::Slider);
2043 assert_eq!(map_atspi_role("panel"), Role::Group);
2044 assert_eq!(map_atspi_role("unknown_thing"), Role::Unknown);
2045 }
2046
2047 #[test]
2048 fn test_numeric_role_mapping() {
2049 assert_eq!(map_atspi_role_number(62), Role::Switch);
2052 assert_eq!(map_atspi_role_number(43), Role::Button); assert_eq!(map_atspi_role_number(7), Role::CheckBox);
2055 assert_eq!(map_atspi_role_number(67), Role::Unknown); }
2057
2058 #[test]
2059 fn test_action_name_mapping() {
2060 assert_eq!(map_atspi_action_name("click"), Some("press".to_string()));
2061 assert_eq!(map_atspi_action_name("activate"), Some("press".to_string()));
2062 assert_eq!(map_atspi_action_name("press"), Some("press".to_string()));
2063 assert_eq!(map_atspi_action_name("invoke"), Some("press".to_string()));
2064 assert_eq!(
2066 map_atspi_action_name("doDefault"),
2067 Some("press".to_string())
2068 );
2069 assert_eq!(
2070 map_atspi_action_name("do_default"),
2071 Some("press".to_string())
2072 );
2073 assert_eq!(map_atspi_action_name("toggle"), Some("toggle".to_string()));
2074 assert_eq!(map_atspi_action_name("check"), Some("toggle".to_string()));
2075 assert_eq!(map_atspi_action_name("uncheck"), Some("toggle".to_string()));
2076 assert_eq!(map_atspi_action_name("expand"), Some("expand".to_string()));
2077 assert_eq!(map_atspi_action_name("open"), Some("expand".to_string()));
2078 assert_eq!(
2079 map_atspi_action_name("collapse"),
2080 Some("collapse".to_string())
2081 );
2082 assert_eq!(map_atspi_action_name("close"), Some("collapse".to_string()));
2083 assert_eq!(map_atspi_action_name("select"), Some("select".to_string()));
2084 assert_eq!(map_atspi_action_name("menu"), Some("show_menu".to_string()));
2085 assert_eq!(
2086 map_atspi_action_name("showmenu"),
2087 Some("show_menu".to_string())
2088 );
2089 assert_eq!(
2090 map_atspi_action_name("popup"),
2091 Some("show_menu".to_string())
2092 );
2093 assert_eq!(
2094 map_atspi_action_name("show menu"),
2095 Some("show_menu".to_string())
2096 );
2097 assert_eq!(
2100 map_atspi_action_name("showContextMenu"),
2101 Some("show_menu".to_string())
2102 );
2103 assert_eq!(
2104 map_atspi_action_name("show_context_menu"),
2105 Some("show_menu".to_string())
2106 );
2107 assert_eq!(
2108 map_atspi_action_name("increment"),
2109 Some("increment".to_string())
2110 );
2111 assert_eq!(
2112 map_atspi_action_name("decrement"),
2113 Some("decrement".to_string())
2114 );
2115 assert_eq!(map_atspi_action_name("foobar"), None);
2116 }
2117
2118 #[test]
2121 fn test_action_name_aliases_roundtrip() {
2122 let atspi_names = [
2123 "click",
2124 "activate",
2125 "press",
2126 "invoke",
2127 "doDefault",
2128 "do_default",
2129 "toggle",
2130 "check",
2131 "uncheck",
2132 "expand",
2133 "open",
2134 "collapse",
2135 "close",
2136 "select",
2137 "menu",
2138 "showmenu",
2139 "showContextMenu",
2140 "show_context_menu",
2141 "popup",
2142 "show menu",
2143 "increment",
2144 "decrement",
2145 ];
2146 for name in atspi_names {
2147 let canonical = map_atspi_action_name(name).unwrap_or_else(|| {
2148 panic!("AT-SPI2 name {:?} should map to a canonical name", name)
2149 });
2150 let back = map_atspi_action_name(&canonical)
2152 .unwrap_or_else(|| panic!("canonical {:?} should map back to itself", canonical));
2153 assert_eq!(
2154 canonical, back,
2155 "AT-SPI2 {:?} -> {:?} -> {:?} (expected {:?})",
2156 name, canonical, back, canonical
2157 );
2158 }
2159 }
2160
2161 #[test]
2163 fn test_action_name_case_insensitive() {
2164 assert_eq!(map_atspi_action_name("Click"), Some("press".to_string()));
2165 assert_eq!(map_atspi_action_name("TOGGLE"), Some("toggle".to_string()));
2166 assert_eq!(
2167 map_atspi_action_name("Increment"),
2168 Some("increment".to_string())
2169 );
2170 }
2171
2172 #[test]
2177 fn test_gtk_fallback_actionable_roles() {
2178 for role in [
2179 "push button",
2180 "toggle button",
2181 "check box",
2182 "radio button",
2183 "menu item",
2184 "link",
2185 "tab",
2186 "list item",
2187 "tree item",
2188 ] {
2189 assert!(
2190 is_actionable_atspi_role(role),
2191 "{role:?} should be actionable"
2192 );
2193 }
2194 }
2195
2196 #[test]
2201 fn test_gtk_fallback_non_actionable_roles() {
2202 for role in [
2203 "label",
2204 "panel",
2205 "filler",
2206 "section",
2207 "group",
2208 "image",
2209 "separator",
2210 "static",
2211 "frame",
2212 "window",
2213 ] {
2214 assert!(
2215 !is_actionable_atspi_role(role),
2216 "{role:?} must not be treated as actionable"
2217 );
2218 }
2219 }
2220
2221 #[test]
2225 fn test_gtk_fallback_never_descend_roles() {
2226 for role in ["label", "separator", "image", "icon", "static", "caption"] {
2227 assert!(
2228 is_never_descend_atspi_role(role),
2229 "{role:?} must block BFS descent"
2230 );
2231 }
2232 for role in ["panel", "filler", "section", "group", "frame"] {
2235 assert!(
2236 !is_never_descend_atspi_role(role),
2237 "container role {role:?} must remain descendable"
2238 );
2239 }
2240 }
2241}