1use std::collections::{HashMap, HashSet, VecDeque};
4use std::sync::atomic::{AtomicU64, Ordering};
5use std::sync::Mutex;
6
7use rayon::prelude::*;
8use xa11y_core::{
9 ElementData, Error, Provider, Rect, Result, Role, StateSet, Subscription, Toggled,
10};
11use zbus::blocking::{Connection, Proxy};
12
13static NEXT_HANDLE: AtomicU64 = AtomicU64::new(1);
15
16fn state_attr_to_string(name: &str, s: &StateSet) -> Option<String> {
19 match name {
20 "enabled" => Some(s.enabled.to_string()),
21 "visible" => Some(s.visible.to_string()),
22 "focused" => Some(s.focused.to_string()),
23 "focusable" => Some(s.focusable.to_string()),
24 "selected" => Some(s.selected.to_string()),
25 "editable" => Some(s.editable.to_string()),
26 "modal" => Some(s.modal.to_string()),
27 "required" => Some(s.required.to_string()),
28 "busy" => Some(s.busy.to_string()),
29 "expanded" => s.expanded.map(|b| b.to_string()),
30 "checked" => s.checked.map(|c| {
31 match c {
32 Toggled::On => "on",
33 Toggled::Off => "off",
34 Toggled::Mixed => "mixed",
35 }
36 .to_string()
37 }),
38 _ => None,
39 }
40}
41
42pub struct LinuxProvider {
44 a11y_bus: Connection,
45 handle_cache: Mutex<HashMap<u64, AccessibleRef>>,
47 action_indices: Mutex<HashMap<u64, HashMap<String, i32>>>,
50}
51
52#[derive(Debug, Clone)]
54pub(crate) struct AccessibleRef {
55 pub(crate) bus_name: String,
56 pub(crate) path: String,
57}
58
59impl LinuxProvider {
60 pub fn new() -> Result<Self> {
65 let a11y_bus = Self::connect_a11y_bus()?;
66 Ok(Self {
67 a11y_bus,
68 handle_cache: Mutex::new(HashMap::new()),
69 action_indices: Mutex::new(HashMap::new()),
70 })
71 }
72
73 pub(crate) fn connect_a11y_bus() -> Result<Connection> {
74 if let Ok(session) = Connection::session() {
78 let proxy = Proxy::new(&session, "org.a11y.Bus", "/org/a11y/bus", "org.a11y.Bus")
79 .map_err(|e| Error::Platform {
80 code: -1,
81 message: format!("Failed to create a11y bus proxy: {}", e),
82 })?;
83
84 if let Ok(addr_reply) = proxy.call_method("GetAddress", &()) {
85 if let Ok(address) = addr_reply.body().deserialize::<String>() {
86 if let Ok(addr) = zbus::Address::try_from(address.as_str()) {
87 if let Ok(Ok(conn)) =
88 zbus::blocking::connection::Builder::address(addr).map(|b| b.build())
89 {
90 return Ok(conn);
91 }
92 }
93 }
94 }
95
96 return Ok(session);
98 }
99
100 Connection::session().map_err(|e| Error::Platform {
101 code: -1,
102 message: format!("Failed to connect to D-Bus session bus: {}", e),
103 })
104 }
105
106 fn make_proxy(&self, bus_name: &str, path: &str, interface: &str) -> Result<Proxy<'_>> {
107 zbus::blocking::proxy::Builder::<Proxy>::new(&self.a11y_bus)
110 .destination(bus_name.to_owned())
111 .map_err(|e| Error::Platform {
112 code: -1,
113 message: format!("Failed to set proxy destination: {}", e),
114 })?
115 .path(path.to_owned())
116 .map_err(|e| Error::Platform {
117 code: -1,
118 message: format!("Failed to set proxy path: {}", e),
119 })?
120 .interface(interface.to_owned())
121 .map_err(|e| Error::Platform {
122 code: -1,
123 message: format!("Failed to set proxy interface: {}", e),
124 })?
125 .cache_properties(zbus::proxy::CacheProperties::No)
126 .build()
127 .map_err(|e| Error::Platform {
128 code: -1,
129 message: format!("Failed to create proxy: {}", e),
130 })
131 }
132
133 fn has_interface(&self, aref: &AccessibleRef, iface: &str) -> bool {
136 let proxy = match self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Accessible") {
137 Ok(p) => p,
138 Err(_) => return false,
139 };
140 let reply = match proxy.call_method("GetInterfaces", &()) {
141 Ok(r) => r,
142 Err(_) => return false,
143 };
144 let interfaces: Vec<String> = match reply.body().deserialize() {
145 Ok(v) => v,
146 Err(_) => return false,
147 };
148 interfaces.iter().any(|i| i.contains(iface))
149 }
150
151 fn get_role_number(&self, aref: &AccessibleRef) -> Result<u32> {
153 let proxy = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Accessible")?;
154 let reply = proxy
155 .call_method("GetRole", &())
156 .map_err(|e| Error::Platform {
157 code: -1,
158 message: format!("GetRole failed: {}", e),
159 })?;
160 reply
161 .body()
162 .deserialize::<u32>()
163 .map_err(|e| Error::Platform {
164 code: -1,
165 message: format!("GetRole deserialize failed: {}", e),
166 })
167 }
168
169 fn get_role_name(&self, aref: &AccessibleRef) -> Result<String> {
171 let proxy = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Accessible")?;
172 let reply = proxy
173 .call_method("GetRoleName", &())
174 .map_err(|e| Error::Platform {
175 code: -1,
176 message: format!("GetRoleName failed: {}", e),
177 })?;
178 reply
179 .body()
180 .deserialize::<String>()
181 .map_err(|e| Error::Platform {
182 code: -1,
183 message: format!("GetRoleName deserialize failed: {}", e),
184 })
185 }
186
187 fn check_chromium_a11y_enabled(
204 &self,
205 parent: &AccessibleRef,
206 role_hint: Option<Role>,
207 ) -> Result<()> {
208 let app_root = AccessibleRef {
209 bus_name: parent.bus_name.clone(),
210 path: "/org/a11y/atspi/accessible/root".to_string(),
211 };
212 let toolkit = match self
213 .make_proxy(
214 &app_root.bus_name,
215 &app_root.path,
216 "org.a11y.atspi.Application",
217 )
218 .ok()
219 .and_then(|proxy| proxy.get_property::<String>("ToolkitName").ok())
220 {
221 Some(t) => t,
222 None => return Ok(()),
223 };
224 if !toolkit.eq_ignore_ascii_case("Chromium") {
225 return Ok(());
226 }
227 let role = role_hint.unwrap_or_else(|| self.resolve_role(parent));
228 if role != Role::Window {
229 return Ok(());
230 }
231 let app_name = self.get_name(&app_root).unwrap_or_default();
232 Err(Error::AccessibilityNotEnabled {
233 app: app_name,
234 instructions: "Chromium/Electron app exposes an empty accessibility tree on Linux. \
235 Relaunch with `--force-renderer-accessibility` (or set the env var \
236 `ACCESSIBILITY_ENABLED=1`) so the renderer accessibility bridge is initialised."
237 .to_string(),
238 })
239 }
240
241 fn get_name(&self, aref: &AccessibleRef) -> Result<String> {
243 let proxy = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Accessible")?;
244 proxy
245 .get_property::<String>("Name")
246 .map_err(|e| Error::Platform {
247 code: -1,
248 message: format!("Get Name property failed: {}", e),
249 })
250 }
251
252 fn get_description(&self, aref: &AccessibleRef) -> Result<String> {
254 let proxy = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Accessible")?;
255 proxy
256 .get_property::<String>("Description")
257 .map_err(|e| Error::Platform {
258 code: -1,
259 message: format!("Get Description property failed: {}", e),
260 })
261 }
262
263 fn get_atspi_children(&self, aref: &AccessibleRef) -> Result<Vec<AccessibleRef>> {
267 let proxy = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Accessible")?;
268 let reply = proxy
269 .call_method("GetChildren", &())
270 .map_err(|e| Error::Platform {
271 code: -1,
272 message: format!("GetChildren failed: {}", e),
273 })?;
274 let children: Vec<(String, zbus::zvariant::OwnedObjectPath)> =
275 reply.body().deserialize().map_err(|e| Error::Platform {
276 code: -1,
277 message: format!("GetChildren deserialize failed: {}", e),
278 })?;
279 Ok(children
280 .into_iter()
281 .map(|(bus_name, path)| AccessibleRef {
282 bus_name,
283 path: path.to_string(),
284 })
285 .collect())
286 }
287
288 fn get_state(&self, aref: &AccessibleRef) -> Result<Vec<u32>> {
290 let proxy = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Accessible")?;
291 let reply = proxy
292 .call_method("GetState", &())
293 .map_err(|e| Error::Platform {
294 code: -1,
295 message: format!("GetState failed: {}", e),
296 })?;
297 reply
298 .body()
299 .deserialize::<Vec<u32>>()
300 .map_err(|e| Error::Platform {
301 code: -1,
302 message: format!("GetState deserialize failed: {}", e),
303 })
304 }
305
306 fn is_multi_line(&self, aref: &AccessibleRef) -> bool {
312 let state_bits = self.get_state(aref).unwrap_or_default();
313 let bits: u64 = if state_bits.len() >= 2 {
314 (state_bits[0] as u64) | ((state_bits[1] as u64) << 32)
315 } else if state_bits.len() == 1 {
316 state_bits[0] as u64
317 } else {
318 0
319 };
320 const MULTI_LINE: u64 = 1 << 17;
322 (bits & MULTI_LINE) != 0
323 }
324
325 fn refine_text_role(&self, coarse: Role, aref: &AccessibleRef) -> Role {
334 match coarse {
335 Role::TextArea | Role::TextField => {
336 if self.is_multi_line(aref) {
337 Role::TextArea
338 } else {
339 Role::TextField
340 }
341 }
342 other => other,
343 }
344 }
345
346 fn get_extents(&self, aref: &AccessibleRef) -> Option<Rect> {
350 if !self.has_interface(aref, "Component") {
351 return None;
352 }
353 let proxy = self
354 .make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Component")
355 .ok()?;
356 let reply = proxy.call_method("GetExtents", &(0u32,)).ok()?;
359 let (x, y, w, h): (i32, i32, i32, i32) = reply.body().deserialize().ok()?;
360 if w <= 0 && h <= 0 {
361 return None;
362 }
363 Some(Rect {
364 x,
365 y,
366 width: w.max(0) as u32,
367 height: h.max(0) as u32,
368 })
369 }
370
371 fn get_actions(&self, aref: &AccessibleRef) -> (Vec<String>, HashMap<String, i32>) {
377 let mut actions = Vec::new();
378 let mut indices = HashMap::new();
379
380 if let Ok(proxy) = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Action") {
382 let n_actions = proxy
384 .get_property::<i32>("NActions")
385 .or_else(|_| proxy.get_property::<u32>("NActions").map(|n| n as i32))
386 .unwrap_or(0);
387 for i in 0..n_actions {
388 if let Ok(reply) = proxy.call_method("GetName", &(i,)) {
389 if let Ok(name) = reply.body().deserialize::<String>() {
390 if let Some(action_name) = map_atspi_action_name(&name) {
391 if !actions.contains(&action_name) {
392 indices.insert(action_name.clone(), i);
393 actions.push(action_name);
394 }
395 }
396 }
397 }
398 }
399 }
400
401 (actions, indices)
409 }
410
411 fn is_gtk_toolkit(&self, aref: &AccessibleRef) -> bool {
418 let app_root = AccessibleRef {
419 bus_name: aref.bus_name.clone(),
420 path: "/org/a11y/atspi/accessible/root".to_string(),
421 };
422 self.make_proxy(
423 &app_root.bus_name,
424 &app_root.path,
425 "org.a11y.atspi.Application",
426 )
427 .ok()
428 .and_then(|proxy| proxy.get_property::<String>("ToolkitName").ok())
429 .map(|t| t.eq_ignore_ascii_case("GTK"))
430 .unwrap_or(false)
431 }
432
433 fn find_gtk_press_fallback(
446 &self,
447 outer: &AccessibleRef,
448 outer_name: &str,
449 ) -> Option<(AccessibleRef, i32)> {
450 let mut queue: VecDeque<(AccessibleRef, u32)> = VecDeque::new();
451 queue.push_back((outer.clone(), 0));
452 let mut visited: usize = 0;
453 let mut shallowest_depth: Option<u32> = None;
454 let mut hits: Vec<(AccessibleRef, i32)> = Vec::new();
455
456 while let Some((node, depth)) = queue.pop_front() {
457 if let Some(best) = shallowest_depth {
459 if depth > best {
460 continue;
461 }
462 }
463 if visited > GTK_FALLBACK_MAX_NODES {
464 break;
465 }
466
467 let role_name = if depth == 0 {
468 String::new()
469 } else {
470 visited += 1;
471 self.get_role_name(&node).unwrap_or_default().to_lowercase()
472 };
473
474 if depth > 0 && is_actionable_atspi_role(&role_name) {
475 if let Some(idx) = self.gtk_fallback_pick(&node, outer_name) {
476 match shallowest_depth {
477 Some(d) if depth < d => {
478 shallowest_depth = Some(depth);
479 hits.clear();
480 hits.push((node.clone(), idx));
481 }
482 Some(d) if depth == d => hits.push((node.clone(), idx)),
483 Some(_) => {}
484 None => {
485 shallowest_depth = Some(depth);
486 hits.push((node.clone(), idx));
487 }
488 }
489 }
490 }
491
492 let stop_descending = depth >= GTK_FALLBACK_MAX_DEPTH
497 || (depth > 0 && is_never_descend_atspi_role(&role_name));
498 if stop_descending {
499 continue;
500 }
501 if let Ok(children) = self.get_atspi_children(&node) {
502 for c in children {
503 queue.push_back((c, depth + 1));
504 }
505 }
506 }
507
508 if hits.len() == 1 {
509 Some(hits.into_iter().next().unwrap())
510 } else {
511 None
512 }
513 }
514
515 fn gtk_fallback_pick(&self, aref: &AccessibleRef, outer_name: &str) -> Option<i32> {
518 let (_, index_map) = self.get_actions(aref);
519 let idx = *index_map.get("press")?;
520 if !self.is_showing_visible_sensitive(aref) {
521 return None;
522 }
523 if !outer_name.is_empty() {
527 let inner_name = self.get_name(aref).unwrap_or_default();
528 if !inner_name.is_empty() && inner_name != outer_name {
529 return None;
530 }
531 }
532 Some(idx)
533 }
534
535 fn is_showing_visible_sensitive(&self, aref: &AccessibleRef) -> bool {
540 let raw = self.get_state(aref).unwrap_or_default();
541 let bits: u64 = if raw.len() >= 2 {
542 (raw[0] as u64) | ((raw[1] as u64) << 32)
543 } else if raw.len() == 1 {
544 raw[0] as u64
545 } else {
546 0
547 };
548 const SENSITIVE: u64 = 1 << 24;
549 const SHOWING: u64 = 1 << 25;
550 const VISIBLE: u64 = 1 << 30;
551 (bits & (SHOWING | VISIBLE | SENSITIVE)) == (SHOWING | VISIBLE | SENSITIVE)
552 }
553
554 fn get_value(&self, aref: &AccessibleRef) -> Option<String> {
557 let text_value = self.get_text_content(aref);
561 if text_value.is_some() {
562 return text_value;
563 }
564 if let Ok(proxy) = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Value") {
566 if let Ok(val) = proxy.get_property::<f64>("CurrentValue") {
567 return Some(val.to_string());
568 }
569 }
570 None
571 }
572
573 fn get_text_content(&self, aref: &AccessibleRef) -> Option<String> {
575 let proxy = self
576 .make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Text")
577 .ok()?;
578 let char_count: i32 = proxy.get_property("CharacterCount").ok()?;
579 if char_count > 0 {
580 let reply = proxy.call_method("GetText", &(0i32, char_count)).ok()?;
581 let text: String = reply.body().deserialize().ok()?;
582 if !text.is_empty() {
583 return Some(text);
584 }
585 }
586 None
587 }
588
589 fn cache_element(&self, aref: AccessibleRef) -> u64 {
591 let handle = NEXT_HANDLE.fetch_add(1, Ordering::Relaxed);
592 self.handle_cache
593 .lock()
594 .unwrap_or_else(|e| e.into_inner())
595 .insert(handle, aref);
596 handle
597 }
598
599 fn get_cached(&self, handle: u64) -> Result<AccessibleRef> {
601 self.handle_cache
602 .lock()
603 .unwrap_or_else(|e| e.into_inner())
604 .get(&handle)
605 .cloned()
606 .ok_or(Error::ElementStale {
607 selector: format!("handle:{}", handle),
608 })
609 }
610
611 fn build_element_data(&self, aref: &AccessibleRef, pid: Option<u32>) -> ElementData {
616 let role_name = self.get_role_name(aref).unwrap_or_default();
617 let role_num = self.get_role_number(aref).unwrap_or(0);
618 let role = {
619 let by_name = if !role_name.is_empty() {
620 map_atspi_role(&role_name)
621 } else {
622 Role::Unknown
623 };
624 let coarse = if by_name != Role::Unknown {
625 by_name
626 } else {
627 map_atspi_role_number(role_num)
628 };
629 self.refine_text_role(coarse, aref)
630 };
631
632 let (
636 ((mut name, value), description),
637 (
638 (states, bounds),
639 ((actions, action_index_map), (numeric_value, min_value, max_value)),
640 ),
641 ) = rayon::join(
642 || {
643 rayon::join(
644 || {
645 let name = self.get_name(aref).ok().filter(|s| !s.is_empty());
646 let value = if role_has_value(role) {
647 self.get_value(aref)
648 } else {
649 None
650 };
651 (name, value)
652 },
653 || self.get_description(aref).ok().filter(|s| !s.is_empty()),
654 )
655 },
656 || {
657 rayon::join(
658 || {
659 rayon::join(
660 || self.parse_states(aref, role),
661 || {
662 if role != Role::Application {
663 self.get_extents(aref)
664 } else {
665 None
666 }
667 },
668 )
669 },
670 || {
671 rayon::join(
672 || {
673 if role_has_actions(role) {
674 self.get_actions(aref)
675 } else {
676 (vec![], HashMap::new())
677 }
678 },
679 || {
680 if matches!(
681 role,
682 Role::Slider
683 | Role::ProgressBar
684 | Role::ScrollBar
685 | Role::SpinButton
686 ) {
687 if let Ok(proxy) = self.make_proxy(
688 &aref.bus_name,
689 &aref.path,
690 "org.a11y.atspi.Value",
691 ) {
692 (
693 proxy.get_property::<f64>("CurrentValue").ok(),
694 proxy.get_property::<f64>("MinimumValue").ok(),
695 proxy.get_property::<f64>("MaximumValue").ok(),
696 )
697 } else {
698 (None, None, None)
699 }
700 } else {
701 (None, None, None)
702 }
703 },
704 )
705 },
706 )
707 },
708 );
709
710 if name.is_none() && role == Role::StaticText {
713 if let Some(ref v) = value {
714 name = Some(v.clone());
715 }
716 }
717
718 let raw = {
719 let raw_role = if role_name.is_empty() {
720 format!("role_num:{}", role_num)
721 } else {
722 role_name
723 };
724 let mut raw = HashMap::new();
725 raw.insert("atspi_role".into(), serde_json::Value::String(raw_role));
726 raw.insert(
727 "bus_name".into(),
728 serde_json::Value::String(aref.bus_name.clone()),
729 );
730 raw.insert(
731 "object_path".into(),
732 serde_json::Value::String(aref.path.clone()),
733 );
734 if let Some(ref n) = name {
737 raw.insert("atspi_name".into(), serde_json::Value::String(n.clone()));
738 }
739 if let Some(ref v) = value {
740 raw.insert("atspi_value".into(), serde_json::Value::String(v.clone()));
741 }
742 if let Some(ref d) = description {
743 raw.insert(
744 "atspi_description".into(),
745 serde_json::Value::String(d.clone()),
746 );
747 }
748 raw
749 };
750
751 let name = xa11y_core::text::strip_bidi_opt(name);
754 let value = xa11y_core::text::strip_bidi_opt(value);
755 let description = xa11y_core::text::strip_bidi_opt(description);
756
757 let handle = self.cache_element(aref.clone());
758 if !action_index_map.is_empty() {
759 self.action_indices
760 .lock()
761 .unwrap_or_else(|e| e.into_inner())
762 .insert(handle, action_index_map);
763 }
764
765 ElementData {
766 role,
767 name,
768 value,
769 description,
770 bounds,
771 actions,
772 states,
773 numeric_value,
774 min_value,
775 max_value,
776 pid,
777 stable_id: Some(aref.path.clone()),
778 raw,
779 handle,
780 }
781 }
782
783 fn get_atspi_parent(&self, aref: &AccessibleRef) -> Result<Option<AccessibleRef>> {
785 let proxy = self.make_proxy(
787 &aref.bus_name,
788 &aref.path,
789 "org.freedesktop.DBus.Properties",
790 )?;
791 let reply = proxy
792 .call_method("Get", &("org.a11y.atspi.Accessible", "Parent"))
793 .map_err(|e| Error::Platform {
794 code: -1,
795 message: format!("Get Parent property failed: {}", e),
796 })?;
797 let variant: zbus::zvariant::OwnedValue =
799 reply.body().deserialize().map_err(|e| Error::Platform {
800 code: -1,
801 message: format!("Parent deserialize variant failed: {}", e),
802 })?;
803 let (bus, path): (String, zbus::zvariant::OwnedObjectPath) =
804 zbus::zvariant::Value::from(variant).try_into().map_err(
805 |e: zbus::zvariant::Error| Error::Platform {
806 code: -1,
807 message: format!("Parent deserialize struct failed: {}", e),
808 },
809 )?;
810 let path_str = path.as_str();
811 if path_str == "/org/a11y/atspi/null" || bus.is_empty() || path_str.is_empty() {
812 return Ok(None);
813 }
814 if path_str == "/org/a11y/atspi/accessible/root" {
816 return Ok(None);
817 }
818 Ok(Some(AccessibleRef {
819 bus_name: bus,
820 path: path_str.to_string(),
821 }))
822 }
823
824 fn parse_states(&self, aref: &AccessibleRef, role: Role) -> StateSet {
826 let state_bits = self.get_state(aref).unwrap_or_default();
827
828 let bits: u64 = if state_bits.len() >= 2 {
830 (state_bits[0] as u64) | ((state_bits[1] as u64) << 32)
831 } else if state_bits.len() == 1 {
832 state_bits[0] as u64
833 } else {
834 0
835 };
836
837 const BUSY: u64 = 1 << 3;
839 const CHECKED: u64 = 1 << 4;
840 const EDITABLE: u64 = 1 << 7;
841 const ENABLED: u64 = 1 << 8;
842 const EXPANDABLE: u64 = 1 << 9;
843 const EXPANDED: u64 = 1 << 10;
844 const FOCUSABLE: u64 = 1 << 11;
845 const FOCUSED: u64 = 1 << 12;
846 const MODAL: u64 = 1 << 16;
847 const SELECTED: u64 = 1 << 23;
848 const SENSITIVE: u64 = 1 << 24;
849 const SHOWING: u64 = 1 << 25;
850 const VISIBLE: u64 = 1 << 30;
851 const INDETERMINATE: u64 = 1 << 32;
852 const REQUIRED: u64 = 1 << 33;
853
854 let enabled = (bits & ENABLED) != 0 || (bits & SENSITIVE) != 0;
855 let visible = (bits & VISIBLE) != 0 || (bits & SHOWING) != 0;
856
857 let checked = match role {
858 Role::CheckBox | Role::RadioButton | Role::MenuItem | Role::Switch => {
859 if (bits & INDETERMINATE) != 0 {
860 Some(Toggled::Mixed)
861 } else if (bits & CHECKED) != 0 {
862 Some(Toggled::On)
863 } else {
864 Some(Toggled::Off)
865 }
866 }
867 _ => None,
868 };
869
870 let expanded = if (bits & EXPANDABLE) != 0 {
871 Some((bits & EXPANDED) != 0)
872 } else {
873 None
874 };
875
876 StateSet {
877 enabled,
878 visible,
879 focused: (bits & FOCUSED) != 0,
880 checked,
881 selected: (bits & SELECTED) != 0,
882 expanded,
883 editable: (bits & EDITABLE) != 0,
884 focusable: (bits & FOCUSABLE) != 0,
885 modal: (bits & MODAL) != 0,
886 required: (bits & REQUIRED) != 0,
887 busy: (bits & BUSY) != 0,
888 }
889 }
890
891 pub(crate) fn find_app_by_pid(&self, pid: u32) -> Result<AccessibleRef> {
896 let registry = AccessibleRef {
897 bus_name: "org.a11y.atspi.Registry".to_string(),
898 path: "/org/a11y/atspi/accessible/root".to_string(),
899 };
900 let children = self.get_atspi_children(®istry)?;
901
902 for child in &children {
903 if child.path == "/org/a11y/atspi/null" {
904 continue;
905 }
906 if let Some(app_pid) = self.get_dbus_pid(&child.bus_name) {
912 if app_pid == pid {
913 return Ok(child.clone());
914 }
915 }
916 if let Ok(proxy) =
918 self.make_proxy(&child.bus_name, &child.path, "org.a11y.atspi.Application")
919 {
920 if let Ok(app_pid) = proxy.get_property::<i32>("Id") {
921 if app_pid as u32 == pid {
922 return Ok(child.clone());
923 }
924 }
925 }
926 }
927
928 Err(Error::Platform {
929 code: -1,
930 message: format!("No application found with PID {}", pid),
931 })
932 }
933
934 fn get_dbus_pid(&self, bus_name: &str) -> Option<u32> {
936 let proxy = self
937 .make_proxy(
938 "org.freedesktop.DBus",
939 "/org/freedesktop/DBus",
940 "org.freedesktop.DBus",
941 )
942 .ok()?;
943 let reply = proxy
944 .call_method("GetConnectionUnixProcessID", &(bus_name,))
945 .ok()?;
946 let pid: u32 = reply.body().deserialize().ok()?;
947 if pid > 0 {
948 Some(pid)
949 } else {
950 None
951 }
952 }
953
954 fn do_atspi_action_by_index(&self, aref: &AccessibleRef, index: i32) -> Result<()> {
956 let proxy = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Action")?;
957 proxy
958 .call_method("DoAction", &(index,))
959 .map_err(|e| Error::Platform {
960 code: -1,
961 message: format!("DoAction({}) failed: {}", index, e),
962 })?;
963 Ok(())
964 }
965
966 fn get_action_index(&self, handle: u64, action: &str) -> Result<i32> {
968 self.action_indices
969 .lock()
970 .unwrap_or_else(|e| e.into_inner())
971 .get(&handle)
972 .and_then(|map| map.get(action).copied())
973 .ok_or_else(|| Error::ActionNotSupported {
974 action: action.to_string(),
975 role: Role::Unknown, })
977 }
978
979 fn get_app_pid(&self, aref: &AccessibleRef) -> Option<u32> {
985 if let Some(pid) = self.get_dbus_pid(&aref.bus_name) {
986 return Some(pid);
987 }
988
989 if let Ok(proxy) = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Application")
996 {
997 if let Ok(pid) = proxy.get_property::<i32>("Id") {
998 if pid > 0 && std::path::Path::new(&format!("/proc/{pid}")).exists() {
999 return Some(pid as u32);
1000 }
1001 }
1002 }
1003
1004 None
1005 }
1006
1007 fn resolve_role(&self, aref: &AccessibleRef) -> Role {
1009 let role_name = self.get_role_name(aref).unwrap_or_default();
1010 let by_name = if !role_name.is_empty() {
1011 map_atspi_role(&role_name)
1012 } else {
1013 Role::Unknown
1014 };
1015 let coarse = if by_name != Role::Unknown {
1016 by_name
1017 } else {
1018 let role_num = self.get_role_number(aref).unwrap_or(0);
1020 map_atspi_role_number(role_num)
1021 };
1022 self.refine_text_role(coarse, aref)
1023 }
1024
1025 fn matches_ref(
1039 &self,
1040 aref: &AccessibleRef,
1041 simple: &xa11y_core::selector::SimpleSelector,
1042 ) -> bool {
1043 let needs_role = simple.role.is_some()
1046 || simple
1047 .filters
1048 .iter()
1049 .any(|f| matches!(f.attr.as_str(), "role" | "checked"));
1050 let role = if needs_role {
1051 Some(self.resolve_role(aref))
1052 } else {
1053 None
1054 };
1055
1056 if let Some(ref role_match) = simple.role {
1057 match role_match {
1058 xa11y_core::selector::RoleMatch::Normalized(expected) => {
1059 if role != Some(*expected) {
1060 return false;
1061 }
1062 }
1063 xa11y_core::selector::RoleMatch::Platform(platform_role) => {
1064 let raw_role = self.get_role_name(aref).unwrap_or_default();
1065 if raw_role != *platform_role {
1066 return false;
1067 }
1068 }
1069 }
1070 }
1071
1072 let mut state_set: Option<StateSet> = None;
1073
1074 for filter in &simple.filters {
1075 let attr = filter.attr.as_str();
1076 let resolved: Option<Option<String>> = match attr {
1077 "role" => Some(role.map(|r| r.to_snake_case().to_string())),
1078 "name" => {
1079 let name = self.get_name(aref).ok().filter(|s| !s.is_empty());
1080 let resolved = if name.is_none() && role == Some(Role::StaticText) {
1083 self.get_value(aref)
1084 } else {
1085 name
1086 };
1087 Some(resolved)
1088 }
1089 "value" => Some(self.get_value(aref)),
1090 "description" => Some(self.get_description(aref).ok().filter(|s| !s.is_empty())),
1091 "enabled" | "visible" | "focused" | "focusable" | "selected" | "editable"
1092 | "modal" | "required" | "busy" | "expanded" | "checked" => {
1093 let s = state_set.get_or_insert_with(|| {
1094 self.parse_states(aref, role.unwrap_or(Role::Unknown))
1098 });
1099 Some(state_attr_to_string(attr, s))
1100 }
1101 _ => None, };
1103
1104 match resolved {
1105 Some(value) => {
1106 if !xa11y_core::selector::match_op(&filter.op, &filter.value, value.as_deref())
1107 {
1108 return false;
1109 }
1110 }
1111 None => {
1112 let pid = None; let data = self.build_element_data(aref, pid);
1120 return xa11y_core::selector::matches_simple(&data, simple);
1121 }
1122 }
1123 }
1124
1125 true
1126 }
1127
1128 fn collect_matching_refs_group(
1138 &self,
1139 parent: &AccessibleRef,
1140 clauses: &[&xa11y_core::selector::SimpleSelector],
1141 depth: u32,
1142 max_depth: u32,
1143 limit: Option<usize>,
1144 ) -> Result<Vec<(usize, AccessibleRef)>> {
1145 if depth > max_depth {
1146 return Ok(vec![]);
1147 }
1148
1149 let children = self.get_atspi_children(parent)?;
1150
1151 let parent_is_registry = parent.bus_name == "org.a11y.atspi.Registry";
1159 let mut to_search: Vec<AccessibleRef> = Vec::new();
1160 for child in children {
1161 if child.path == "/org/a11y/atspi/null"
1162 || child.bus_name.is_empty()
1163 || child.path.is_empty()
1164 {
1165 continue;
1166 }
1167
1168 if !parent_is_registry {
1169 let child_role = self.get_role_name(&child).unwrap_or_default();
1170 if child_role == "application" {
1171 let grandchildren = self.get_atspi_children(&child).unwrap_or_default();
1172 for gc in grandchildren {
1173 if gc.path == "/org/a11y/atspi/null"
1174 || gc.bus_name.is_empty()
1175 || gc.path.is_empty()
1176 {
1177 continue;
1178 }
1179 let gc_role = self.get_role_name(&gc).unwrap_or_default();
1180 if gc_role == "application" {
1181 continue;
1182 }
1183 to_search.push(gc);
1184 }
1185 continue;
1186 }
1187 }
1188 to_search.push(child);
1189 }
1190
1191 if to_search.is_empty() {
1194 self.check_chromium_a11y_enabled(parent, None)?;
1195 }
1196
1197 type ChildBatch = (Vec<(usize, AccessibleRef)>, Option<Error>);
1212 let per_child: Vec<ChildBatch> = to_search
1213 .par_iter()
1214 .map(|child| {
1215 let mut child_results: Vec<(usize, AccessibleRef)> = Vec::new();
1216 for (idx, simple) in clauses.iter().enumerate() {
1217 if self.matches_ref(child, simple) {
1218 child_results.push((idx, child.clone()));
1219 }
1220 }
1221 match self.collect_matching_refs_group(child, clauses, depth + 1, max_depth, limit)
1222 {
1223 Ok(sub) => {
1224 child_results.extend(sub);
1225 (child_results, None)
1226 }
1227 Err(e @ Error::AccessibilityNotEnabled { .. }) => (Vec::new(), Some(e)),
1228 Err(_) => (child_results, None),
1229 }
1230 })
1231 .collect();
1232
1233 let mut results = Vec::new();
1245 for (batch, maybe_err) in per_child {
1246 if let Some(err) = maybe_err {
1247 return Err(err);
1248 }
1249 for r in batch {
1250 results.push(r);
1251 if let Some(limit) = limit {
1252 if results.len() >= limit {
1253 return Ok(results);
1254 }
1255 }
1256 }
1257 }
1258 Ok(results)
1259 }
1260}
1261
1262impl Provider for LinuxProvider {
1263 fn get_children(&self, element: Option<&ElementData>) -> Result<Vec<ElementData>> {
1264 match element {
1265 None => {
1266 self.list_apps()
1269 }
1270 Some(element_data) => {
1271 let aref = self.get_cached(element_data.handle)?;
1272 let children = self.get_atspi_children(&aref).unwrap_or_default();
1273 let pid = element_data.pid;
1274
1275 let mut to_build: Vec<AccessibleRef> = Vec::new();
1278 for child_ref in &children {
1279 if child_ref.path == "/org/a11y/atspi/null"
1280 || child_ref.bus_name.is_empty()
1281 || child_ref.path.is_empty()
1282 {
1283 continue;
1284 }
1285 let child_role = self.get_role_name(child_ref).unwrap_or_default();
1286 if child_role == "application" {
1287 let grandchildren = self.get_atspi_children(child_ref).unwrap_or_default();
1288 for gc_ref in grandchildren {
1289 if gc_ref.path == "/org/a11y/atspi/null"
1290 || gc_ref.bus_name.is_empty()
1291 || gc_ref.path.is_empty()
1292 {
1293 continue;
1294 }
1295 let gc_role = self.get_role_name(&gc_ref).unwrap_or_default();
1296 if gc_role == "application" {
1297 continue;
1298 }
1299 to_build.push(gc_ref);
1300 }
1301 continue;
1302 }
1303 to_build.push(child_ref.clone());
1304 }
1305
1306 if to_build.is_empty() {
1307 self.check_chromium_a11y_enabled(&aref, Some(element_data.role))?;
1308 }
1309
1310 let results: Vec<ElementData> = to_build
1311 .par_iter()
1312 .map(|r| self.build_element_data(r, pid))
1313 .collect();
1314
1315 Ok(results)
1316 }
1317 }
1318 }
1319
1320 fn find_elements_group(
1321 &self,
1322 root: &ElementData,
1323 group: &xa11y_core::selector::SelectorGroup,
1324 limit: Option<usize>,
1325 max_depth: Option<u32>,
1326 ) -> Result<Vec<ElementData>> {
1327 if group.clauses.is_empty() {
1328 return Ok(vec![]);
1329 }
1330 if group.clauses.iter().any(|c| c.segments.is_empty()) {
1333 return Ok(vec![]);
1334 }
1335
1336 let max_depth_val = max_depth.unwrap_or(xa11y_core::MAX_TREE_DEPTH);
1346
1347 let firsts: Vec<&xa11y_core::selector::SimpleSelector> = group
1348 .clauses
1349 .iter()
1350 .map(|c| &c.segments[0].simple)
1351 .collect();
1352
1353 let start_ref = self.get_cached(root.handle)?;
1354
1355 let phase1_limit = if group.clauses.len() == 1 {
1364 let clause = &group.clauses[0];
1365 let first = firsts[0];
1366 let outer = if clause.segments.len() == 1 {
1367 limit
1368 } else {
1369 None
1370 };
1371 match (outer, first.nth) {
1372 (Some(l), Some(n)) => Some(l.max(n)),
1373 (_, Some(n)) => Some(n),
1374 (l, None) => l,
1375 }
1376 } else {
1377 None
1378 };
1379
1380 let phase1: Vec<(usize, AccessibleRef)> =
1381 self.collect_matching_refs_group(&start_ref, &firsts, 0, max_depth_val, phase1_limit)?;
1382
1383 let pid_from_root = root.pid;
1384
1385 let mut by_clause: Vec<Vec<(usize, AccessibleRef)>> =
1389 (0..group.clauses.len()).map(|_| Vec::new()).collect();
1390 for (walk_pos, (clause_idx, aref)) in phase1.into_iter().enumerate() {
1391 by_clause[clause_idx].push((walk_pos, aref));
1392 }
1393
1394 let mut merged: Vec<(usize, ElementData)> = Vec::new();
1402 for (clause_idx, hits) in by_clause.into_iter().enumerate() {
1403 if hits.is_empty() {
1404 continue;
1405 }
1406 let clause = &group.clauses[clause_idx];
1407 let phase1_data: Vec<(usize, ElementData)> = hits
1409 .par_iter()
1410 .map(|(pos, aref)| {
1411 (*pos, self.build_element_data(aref, pid_from_root))
1415 })
1416 .collect();
1417
1418 if clause.segments.len() == 1 {
1419 let mut candidates = phase1_data;
1421 if let Some(nth) = clause.segments[0].simple.nth {
1422 if nth <= candidates.len() {
1423 let kept = candidates.remove(nth - 1);
1424 candidates.clear();
1425 candidates.push(kept);
1426 } else {
1427 candidates.clear();
1428 }
1429 }
1430 merged.extend(candidates);
1431 continue;
1432 }
1433
1434 for (anchor_pos, head) in phase1_data {
1439 let narrowed = self.narrow_multi_segment(
1440 vec![head],
1441 &clause.segments[1..],
1442 max_depth_val,
1443 None,
1444 )?;
1445 for n in narrowed {
1446 merged.push((anchor_pos, n));
1447 }
1448 }
1449 }
1450
1451 merged.sort_by_key(|(pos, _)| *pos);
1455 let mut seen: HashSet<(String, String)> = HashSet::new();
1456 let mut out: Vec<ElementData> = Vec::with_capacity(merged.len());
1457 for (_, data) in merged {
1458 if let Ok(aref) = self.get_cached(data.handle) {
1462 if !seen.insert((aref.bus_name.clone(), aref.path.clone())) {
1463 continue;
1464 }
1465 }
1466 out.push(data);
1467 }
1468 if let Some(l) = limit {
1469 out.truncate(l);
1470 }
1471 Ok(out)
1472 }
1473
1474 fn get_parent(&self, element: &ElementData) -> Result<Option<ElementData>> {
1475 let aref = self.get_cached(element.handle)?;
1476 match self.get_atspi_parent(&aref)? {
1477 Some(parent_ref) => {
1478 let data = self.build_element_data(&parent_ref, element.pid);
1479 Ok(Some(data))
1480 }
1481 None => Ok(None),
1482 }
1483 }
1484
1485 fn list_apps(&self) -> Result<Vec<ElementData>> {
1492 let registry = AccessibleRef {
1493 bus_name: "org.a11y.atspi.Registry".to_string(),
1494 path: "/org/a11y/atspi/accessible/root".to_string(),
1495 };
1496 let children = self.get_atspi_children(®istry)?;
1497
1498 let valid: Vec<(&AccessibleRef, String)> = children
1500 .iter()
1501 .filter(|c| c.path != "/org/a11y/atspi/null")
1502 .filter_map(|c| {
1503 let name = self.get_name(c).unwrap_or_default();
1504 if name.is_empty() {
1505 None
1506 } else {
1507 Some((c, name))
1508 }
1509 })
1510 .collect();
1511
1512 let results: Vec<ElementData> = valid
1513 .par_iter()
1514 .map(|(child, app_name)| {
1515 let pid = self.get_app_pid(child);
1516 let mut data = self.build_element_data(child, pid);
1517 data.name = Some(app_name.clone());
1518 data
1519 })
1520 .collect();
1521
1522 Ok(results)
1523 }
1524
1525 fn app_by_pid(&self, pid: u32) -> Result<ElementData> {
1537 let registry = AccessibleRef {
1538 bus_name: "org.a11y.atspi.Registry".to_string(),
1539 path: "/org/a11y/atspi/accessible/root".to_string(),
1540 };
1541 let children = self.get_atspi_children(®istry)?;
1542
1543 let mut total = 0usize;
1544 let mut unresolved = 0usize;
1545 for child in children.iter().filter(|c| c.path != "/org/a11y/atspi/null") {
1546 total += 1;
1547 match self.get_app_pid(child) {
1548 Some(p) if p == pid => {
1549 let mut data = self.build_element_data(child, Some(p));
1550 let name = self.get_name(child).unwrap_or_default();
1552 if !name.is_empty() {
1553 data.name = Some(name);
1554 }
1555 return Ok(data);
1556 }
1557 Some(_) => {}
1558 None => unresolved += 1,
1559 }
1560 }
1561 Err(
1562 Error::selector_not_matched(format!("application[pid={pid}]")).diagnose(
1563 xa11y_core::Diagnosis {
1564 last_observed: Some(format!(
1565 "{total} AT-SPI registry entries examined, {unresolved} without a \
1566 resolvable pid"
1567 )),
1568 ..Default::default()
1569 },
1570 ),
1571 )
1572 }
1573
1574 fn press(&self, element: &ElementData) -> Result<()> {
1575 let target = self.get_cached(element.handle)?;
1576 if let Ok(index) = self.get_action_index(element.handle, "press") {
1578 return self.do_atspi_action_by_index(&target, index);
1579 }
1580 if element.role == Role::Button && self.is_gtk_toolkit(&target) {
1599 let outer_name = self.get_name(&target).unwrap_or_default();
1600 if let Some((inner, index)) = self.find_gtk_press_fallback(&target, &outer_name) {
1601 return self.do_atspi_action_by_index(&inner, index);
1602 }
1603 }
1604 Err(Error::ActionNotSupported {
1605 action: "press".to_string(),
1606 role: element.role,
1607 })
1608 }
1609
1610 fn focus(&self, element: &ElementData) -> Result<()> {
1611 let target = self.get_cached(element.handle)?;
1612 if let Ok(proxy) =
1616 self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Component")
1617 {
1618 if let Ok(reply) = proxy.call_method("GrabFocus", &()) {
1619 if let Ok(true) = reply.body().deserialize::<bool>() {
1621 return Ok(());
1622 }
1623 }
1625 }
1626 if let Ok(index) = self.get_action_index(element.handle, "focus") {
1627 return self.do_atspi_action_by_index(&target, index);
1628 }
1629 Err(Error::ActionNotSupported {
1630 action: "focus".to_string(),
1631 role: element.role,
1632 })
1633 }
1634
1635 fn blur(&self, element: &ElementData) -> Result<()> {
1636 let target = self.get_cached(element.handle)?;
1637 if let Some(parent_ref) = self.get_atspi_parent(&target)? {
1641 if parent_ref.path != "/org/a11y/atspi/null" {
1642 let p = self.make_proxy(
1643 &parent_ref.bus_name,
1644 &parent_ref.path,
1645 "org.a11y.atspi.Component",
1646 )?;
1647 p.call_method("GrabFocus", &())
1648 .map_err(|e| Error::Platform {
1649 code: -1,
1650 message: format!("Component.GrabFocus on parent failed: {}", e),
1651 })?;
1652 return Ok(());
1653 }
1654 }
1655 Err(Error::ActionNotSupported {
1656 action: "blur".to_string(),
1657 role: element.role,
1658 })
1659 }
1660
1661 fn toggle(&self, element: &ElementData) -> Result<()> {
1662 let target = self.get_cached(element.handle)?;
1663 if let Ok(index) = self.get_action_index(element.handle, "toggle") {
1668 return self.do_atspi_action_by_index(&target, index);
1669 }
1670 if matches!(
1693 element.role,
1694 Role::CheckBox | Role::RadioButton | Role::Switch
1695 ) {
1696 if let Ok(index) = self.get_action_index(element.handle, "press") {
1697 return self.do_atspi_action_by_index(&target, index);
1698 }
1699 }
1700 Err(Error::ActionNotSupported {
1701 action: "toggle".to_string(),
1702 role: element.role,
1703 })
1704 }
1705
1706 fn select(&self, element: &ElementData) -> Result<()> {
1707 let target = self.get_cached(element.handle)?;
1708 let index = self
1709 .get_action_index(element.handle, "select")
1710 .map_err(|_| Error::ActionNotSupported {
1711 action: "select".to_string(),
1712 role: element.role,
1713 })?;
1714 self.do_atspi_action_by_index(&target, index)
1715 }
1716
1717 fn expand(&self, element: &ElementData) -> Result<()> {
1718 let target = self.get_cached(element.handle)?;
1719 let index = self
1720 .get_action_index(element.handle, "expand")
1721 .map_err(|_| Error::ActionNotSupported {
1722 action: "expand".to_string(),
1723 role: element.role,
1724 })?;
1725 self.do_atspi_action_by_index(&target, index)
1726 }
1727
1728 fn collapse(&self, element: &ElementData) -> Result<()> {
1729 let target = self.get_cached(element.handle)?;
1730 let index = self
1731 .get_action_index(element.handle, "collapse")
1732 .map_err(|_| Error::ActionNotSupported {
1733 action: "collapse".to_string(),
1734 role: element.role,
1735 })?;
1736 self.do_atspi_action_by_index(&target, index)
1737 }
1738
1739 fn show_menu(&self, element: &ElementData) -> Result<()> {
1740 let target = self.get_cached(element.handle)?;
1741 let index = self
1742 .get_action_index(element.handle, "show_menu")
1743 .map_err(|_| Error::ActionNotSupported {
1744 action: "show_menu".to_string(),
1745 role: element.role,
1746 })?;
1747 self.do_atspi_action_by_index(&target, index)
1748 }
1749
1750 fn increment(&self, element: &ElementData) -> Result<()> {
1751 let target = self.get_cached(element.handle)?;
1752 if let Ok(index) = self.get_action_index(element.handle, "increment") {
1754 return self.do_atspi_action_by_index(&target, index);
1755 }
1756 let proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Value")?;
1757 let current: f64 = proxy
1758 .get_property("CurrentValue")
1759 .map_err(|e| Error::Platform {
1760 code: -1,
1761 message: format!("Value.CurrentValue failed: {}", e),
1762 })?;
1763 let step: f64 = proxy.get_property("MinimumIncrement").unwrap_or(1.0);
1764 let step = if step <= 0.0 { 1.0 } else { step };
1765 proxy
1766 .set_property("CurrentValue", current + step)
1767 .map_err(|e| Error::Platform {
1768 code: -1,
1769 message: format!("Value.SetCurrentValue failed: {}", e),
1770 })
1771 }
1772
1773 fn decrement(&self, element: &ElementData) -> Result<()> {
1774 let target = self.get_cached(element.handle)?;
1775 if let Ok(index) = self.get_action_index(element.handle, "decrement") {
1776 return self.do_atspi_action_by_index(&target, index);
1777 }
1778 let proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Value")?;
1779 let current: f64 = proxy
1780 .get_property("CurrentValue")
1781 .map_err(|e| Error::Platform {
1782 code: -1,
1783 message: format!("Value.CurrentValue failed: {}", e),
1784 })?;
1785 let step: f64 = proxy.get_property("MinimumIncrement").unwrap_or(1.0);
1786 let step = if step <= 0.0 { 1.0 } else { step };
1787 proxy
1788 .set_property("CurrentValue", current - step)
1789 .map_err(|e| Error::Platform {
1790 code: -1,
1791 message: format!("Value.SetCurrentValue failed: {}", e),
1792 })
1793 }
1794
1795 fn scroll_into_view(&self, element: &ElementData) -> Result<()> {
1796 let target = self.get_cached(element.handle)?;
1797 let proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Component")?;
1798 proxy
1799 .call_method("ScrollTo", &(0u32,))
1800 .map_err(|e| Error::Platform {
1801 code: -1,
1802 message: format!("ScrollTo failed: {}", e),
1803 })?;
1804 Ok(())
1805 }
1806
1807 fn set_value(&self, element: &ElementData, value: &str) -> Result<()> {
1808 let target = self.get_cached(element.handle)?;
1809 let proxy = self
1810 .make_proxy(
1811 &target.bus_name,
1812 &target.path,
1813 "org.a11y.atspi.EditableText",
1814 )
1815 .map_err(|_| Error::TextValueNotSupported)?;
1816 if proxy.call_method("SetTextContents", &(value,)).is_ok() {
1818 return Ok(());
1819 }
1820 let classify_editable_text_error = |op: &str, e: zbus::Error| -> Error {
1826 let msg = e.to_string();
1827 if msg.contains("UnknownMethod") || msg.contains("UnknownInterface") {
1828 Error::TextValueNotSupported
1829 } else {
1830 Error::Platform {
1831 code: -1,
1832 message: format!("EditableText.{} failed: {}", op, msg),
1833 }
1834 }
1835 };
1836 if let Err(e) = proxy.call_method("DeleteText", &(0i32, i32::MAX)) {
1837 return Err(classify_editable_text_error("DeleteText", e));
1838 }
1839 if let Err(e) = proxy.call_method("InsertText", &(0i32, value, value.len() as i32)) {
1840 return Err(classify_editable_text_error("InsertText", e));
1841 }
1842 Ok(())
1843 }
1844
1845 fn set_numeric_value(&self, element: &ElementData, value: f64) -> Result<()> {
1846 let target = self.get_cached(element.handle)?;
1847 let proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Value")?;
1848 proxy
1849 .set_property("CurrentValue", value)
1850 .map_err(|e| Error::Platform {
1851 code: -1,
1852 message: format!("SetValue failed: {}", e),
1853 })
1854 }
1855
1856 fn type_text(&self, element: &ElementData, text: &str) -> Result<()> {
1857 let target = self.get_cached(element.handle)?;
1858 let text_proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Text");
1861 let insert_pos = text_proxy
1862 .as_ref()
1863 .ok()
1864 .and_then(|p| p.get_property::<i32>("CaretOffset").ok())
1865 .unwrap_or(-1); let proxy = self
1868 .make_proxy(
1869 &target.bus_name,
1870 &target.path,
1871 "org.a11y.atspi.EditableText",
1872 )
1873 .map_err(|_| Error::TextValueNotSupported)?;
1874 let pos = if insert_pos >= 0 {
1875 insert_pos
1876 } else {
1877 i32::MAX
1878 };
1879 proxy
1880 .call_method("InsertText", &(pos, text, text.len() as i32))
1881 .map_err(|e| Error::Platform {
1882 code: -1,
1883 message: format!("EditableText.InsertText failed: {}", e),
1884 })?;
1885 Ok(())
1886 }
1887
1888 fn set_text_selection(&self, element: &ElementData, start: u32, end: u32) -> Result<()> {
1889 let target = self.get_cached(element.handle)?;
1890 let proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Text")?;
1891 proxy
1892 .call_method("SetSelection", &(0i32, start as i32, end as i32))
1893 .map_err(|e| Error::Platform {
1894 code: -1,
1895 message: format!("Text.SetSelection failed: {}", e),
1896 })?;
1897 Ok(())
1898 }
1899
1900 fn perform_action(&self, element: &ElementData, action: &str) -> Result<()> {
1901 match action {
1902 "press" => self.press(element),
1903 "focus" => self.focus(element),
1904 "blur" => self.blur(element),
1905 "toggle" => self.toggle(element),
1906 "select" => self.select(element),
1907 "expand" => self.expand(element),
1908 "collapse" => self.collapse(element),
1909 "show_menu" => self.show_menu(element),
1910 "increment" => self.increment(element),
1911 "decrement" => self.decrement(element),
1912 "scroll_into_view" => self.scroll_into_view(element),
1913 _ => Err(Error::ActionNotSupported {
1914 action: action.to_string(),
1915 role: element.role,
1916 }),
1917 }
1918 }
1919
1920 fn subscribe(&self, element: &ElementData) -> Result<Subscription> {
1921 let pid = element.pid.ok_or(Error::Platform {
1922 code: -1,
1923 message: "Element has no PID for subscribe".to_string(),
1924 })?;
1925 let app_name = element.name.clone().unwrap_or_default();
1926 crate::events::subscribe_for_pid(self, pid, app_name)
1927 }
1928}
1929
1930fn role_has_value(role: Role) -> bool {
1933 !matches!(
1934 role,
1935 Role::Application
1936 | Role::Window
1937 | Role::Dialog
1938 | Role::Group
1939 | Role::MenuBar
1940 | Role::Toolbar
1941 | Role::TabGroup
1942 | Role::SplitGroup
1943 | Role::Table
1944 | Role::TableRow
1945 | Role::Separator
1946 )
1947}
1948
1949fn role_has_actions(role: Role) -> bool {
1952 matches!(
1953 role,
1954 Role::Button
1955 | Role::CheckBox
1956 | Role::RadioButton
1957 | Role::MenuItem
1958 | Role::Link
1959 | Role::ComboBox
1960 | Role::TextField
1961 | Role::TextArea
1962 | Role::SpinButton
1963 | Role::Tab
1964 | Role::TreeItem
1965 | Role::ListItem
1966 | Role::ScrollBar
1967 | Role::Slider
1968 | Role::Menu
1969 | Role::Image
1970 | Role::Unknown
1971 )
1972}
1973
1974pub(crate) fn map_atspi_role(role_name: &str) -> Role {
1976 match role_name.to_lowercase().as_str() {
1977 "application" => Role::Application,
1978 "window" | "frame" => Role::Window,
1979 "dialog" | "file chooser" => Role::Dialog,
1980 "alert" | "notification" => Role::Alert,
1981 "push button" | "push button menu" => Role::Button,
1982 "toggle button" => Role::Switch,
1983 "check box" | "check menu item" => Role::CheckBox,
1984 "radio button" | "radio menu item" => Role::RadioButton,
1985 "entry" | "password text" => Role::TextField,
1986 "spin button" | "spinbutton" => Role::SpinButton,
1987 "text" | "textbox" => Role::TextArea,
1991 "label" | "static" | "caption" => Role::StaticText,
1992 "combo box" | "combobox" => Role::ComboBox,
1993 "list" | "list box" | "listbox" => Role::List,
1995 "list item" => Role::ListItem,
1996 "menu" => Role::Menu,
1997 "menu item" | "tearoff menu item" => Role::MenuItem,
1998 "menu bar" => Role::MenuBar,
1999 "page tab" => Role::Tab,
2000 "page tab list" => Role::TabGroup,
2001 "table" | "tree table" => Role::Table,
2002 "table row" => Role::TableRow,
2003 "table cell" | "table column header" | "table row header" => Role::TableCell,
2004 "tool bar" => Role::Toolbar,
2005 "scroll bar" => Role::ScrollBar,
2006 "slider" => Role::Slider,
2007 "image" | "icon" | "desktop icon" => Role::Image,
2008 "link" => Role::Link,
2009 "panel" | "section" | "form" | "filler" | "viewport" | "scroll pane" => Role::Group,
2010 "progress bar" => Role::ProgressBar,
2011 "tree item" => Role::TreeItem,
2012 "document web" | "document frame" => Role::WebArea,
2013 "heading" => Role::Heading,
2014 "separator" => Role::Separator,
2015 "split pane" => Role::SplitGroup,
2016 "tooltip" | "tool tip" => Role::Tooltip,
2017 "status bar" | "statusbar" => Role::Status,
2018 "landmark" | "navigation" => Role::Navigation,
2019 _ => xa11y_core::unknown_role(role_name),
2020 }
2021}
2022
2023pub(crate) fn map_atspi_role_number(role: u32) -> Role {
2026 match role {
2027 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}")),
2089 }
2090}
2091
2092const GTK_FALLBACK_MAX_DEPTH: u32 = 3;
2096
2097const GTK_FALLBACK_MAX_NODES: usize = 200;
2100
2101fn is_actionable_atspi_role(role: &str) -> bool {
2106 matches!(
2107 role,
2108 "push button"
2109 | "toggle button"
2110 | "check box"
2111 | "radio button"
2112 | "menu item"
2113 | "check menu item"
2114 | "radio menu item"
2115 | "link"
2116 | "page tab"
2117 | "tab"
2118 | "list item"
2119 | "tree item"
2120 )
2121}
2122
2123fn is_never_descend_atspi_role(role: &str) -> bool {
2128 matches!(
2129 role,
2130 "label" | "separator" | "image" | "icon" | "static" | "caption"
2131 )
2132}
2133
2134fn map_atspi_action_name(action_name: &str) -> Option<String> {
2148 let lower = action_name.to_lowercase();
2157 let collapsed: String = lower.chars().filter(|c| !matches!(c, '_' | ' ')).collect();
2158 let canonical = match collapsed.as_str() {
2159 "click" | "activate" | "press" | "invoke" | "dodefault" => "press",
2160 "toggle" | "check" | "uncheck" => "toggle",
2161 "expand" | "open" => "expand",
2162 "collapse" | "close" => "collapse",
2163 "select" => "select",
2164 "menu" | "showmenu" | "showcontextmenu" | "contextmenu" | "popup" => "show_menu",
2165 "increment" => "increment",
2166 "decrement" => "decrement",
2167 _ => return None,
2168 };
2169 Some(canonical.to_string())
2170}
2171
2172#[cfg(test)]
2173mod tests {
2174 use super::*;
2175
2176 #[test]
2177 fn test_role_mapping() {
2178 assert_eq!(map_atspi_role("push button"), Role::Button);
2179 assert_eq!(map_atspi_role("toggle button"), Role::Switch);
2180 assert_eq!(map_atspi_role("check box"), Role::CheckBox);
2181 assert_eq!(map_atspi_role("entry"), Role::TextField);
2182 assert_eq!(map_atspi_role("label"), Role::StaticText);
2183 assert_eq!(map_atspi_role("window"), Role::Window);
2184 assert_eq!(map_atspi_role("frame"), Role::Window);
2185 assert_eq!(map_atspi_role("dialog"), Role::Dialog);
2186 assert_eq!(map_atspi_role("combo box"), Role::ComboBox);
2187 assert_eq!(map_atspi_role("slider"), Role::Slider);
2188 assert_eq!(map_atspi_role("panel"), Role::Group);
2189 assert_eq!(map_atspi_role("unknown_thing"), Role::Unknown);
2190 }
2191
2192 #[test]
2193 fn test_numeric_role_mapping() {
2194 assert_eq!(map_atspi_role_number(62), Role::Switch);
2197 assert_eq!(map_atspi_role_number(43), Role::Button); assert_eq!(map_atspi_role_number(7), Role::CheckBox);
2200 assert_eq!(map_atspi_role_number(67), Role::Unknown); }
2202
2203 #[test]
2204 fn test_action_name_mapping() {
2205 assert_eq!(map_atspi_action_name("click"), Some("press".to_string()));
2206 assert_eq!(map_atspi_action_name("activate"), Some("press".to_string()));
2207 assert_eq!(map_atspi_action_name("press"), Some("press".to_string()));
2208 assert_eq!(map_atspi_action_name("invoke"), Some("press".to_string()));
2209 assert_eq!(
2211 map_atspi_action_name("doDefault"),
2212 Some("press".to_string())
2213 );
2214 assert_eq!(
2215 map_atspi_action_name("do_default"),
2216 Some("press".to_string())
2217 );
2218 assert_eq!(map_atspi_action_name("toggle"), Some("toggle".to_string()));
2219 assert_eq!(map_atspi_action_name("check"), Some("toggle".to_string()));
2220 assert_eq!(map_atspi_action_name("uncheck"), Some("toggle".to_string()));
2221 assert_eq!(map_atspi_action_name("expand"), Some("expand".to_string()));
2222 assert_eq!(map_atspi_action_name("open"), Some("expand".to_string()));
2223 assert_eq!(
2224 map_atspi_action_name("collapse"),
2225 Some("collapse".to_string())
2226 );
2227 assert_eq!(map_atspi_action_name("close"), Some("collapse".to_string()));
2228 assert_eq!(map_atspi_action_name("select"), Some("select".to_string()));
2229 assert_eq!(map_atspi_action_name("menu"), Some("show_menu".to_string()));
2230 assert_eq!(
2231 map_atspi_action_name("showmenu"),
2232 Some("show_menu".to_string())
2233 );
2234 assert_eq!(
2235 map_atspi_action_name("popup"),
2236 Some("show_menu".to_string())
2237 );
2238 assert_eq!(
2239 map_atspi_action_name("show menu"),
2240 Some("show_menu".to_string())
2241 );
2242 assert_eq!(
2245 map_atspi_action_name("showContextMenu"),
2246 Some("show_menu".to_string())
2247 );
2248 assert_eq!(
2249 map_atspi_action_name("show_context_menu"),
2250 Some("show_menu".to_string())
2251 );
2252 assert_eq!(
2253 map_atspi_action_name("increment"),
2254 Some("increment".to_string())
2255 );
2256 assert_eq!(
2257 map_atspi_action_name("decrement"),
2258 Some("decrement".to_string())
2259 );
2260 assert_eq!(map_atspi_action_name("foobar"), None);
2261 }
2262
2263 #[test]
2266 fn test_action_name_aliases_roundtrip() {
2267 let atspi_names = [
2268 "click",
2269 "activate",
2270 "press",
2271 "invoke",
2272 "doDefault",
2273 "do_default",
2274 "toggle",
2275 "check",
2276 "uncheck",
2277 "expand",
2278 "open",
2279 "collapse",
2280 "close",
2281 "select",
2282 "menu",
2283 "showmenu",
2284 "showContextMenu",
2285 "show_context_menu",
2286 "popup",
2287 "show menu",
2288 "increment",
2289 "decrement",
2290 ];
2291 for name in atspi_names {
2292 let canonical = map_atspi_action_name(name).unwrap_or_else(|| {
2293 panic!("AT-SPI2 name {:?} should map to a canonical name", name)
2294 });
2295 let back = map_atspi_action_name(&canonical)
2297 .unwrap_or_else(|| panic!("canonical {:?} should map back to itself", canonical));
2298 assert_eq!(
2299 canonical, back,
2300 "AT-SPI2 {:?} -> {:?} -> {:?} (expected {:?})",
2301 name, canonical, back, canonical
2302 );
2303 }
2304 }
2305
2306 #[test]
2308 fn test_action_name_case_insensitive() {
2309 assert_eq!(map_atspi_action_name("Click"), Some("press".to_string()));
2310 assert_eq!(map_atspi_action_name("TOGGLE"), Some("toggle".to_string()));
2311 assert_eq!(
2312 map_atspi_action_name("Increment"),
2313 Some("increment".to_string())
2314 );
2315 }
2316
2317 #[test]
2322 fn test_gtk_fallback_actionable_roles() {
2323 for role in [
2324 "push button",
2325 "toggle button",
2326 "check box",
2327 "radio button",
2328 "menu item",
2329 "link",
2330 "tab",
2331 "list item",
2332 "tree item",
2333 ] {
2334 assert!(
2335 is_actionable_atspi_role(role),
2336 "{role:?} should be actionable"
2337 );
2338 }
2339 }
2340
2341 #[test]
2346 fn test_gtk_fallback_non_actionable_roles() {
2347 for role in [
2348 "label",
2349 "panel",
2350 "filler",
2351 "section",
2352 "group",
2353 "image",
2354 "separator",
2355 "static",
2356 "frame",
2357 "window",
2358 ] {
2359 assert!(
2360 !is_actionable_atspi_role(role),
2361 "{role:?} must not be treated as actionable"
2362 );
2363 }
2364 }
2365
2366 #[test]
2370 fn test_gtk_fallback_never_descend_roles() {
2371 for role in ["label", "separator", "image", "icon", "static", "caption"] {
2372 assert!(
2373 is_never_descend_atspi_role(role),
2374 "{role:?} must block BFS descent"
2375 );
2376 }
2377 for role in ["panel", "filler", "section", "group", "frame"] {
2380 assert!(
2381 !is_never_descend_atspi_role(role),
2382 "container role {role:?} must remain descendable"
2383 );
2384 }
2385 }
2386}