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")
991 {
992 if let Ok(pid) = proxy.get_property::<i32>("Id") {
993 if pid > 0 {
994 return Some(pid as u32);
995 }
996 }
997 }
998
999 None
1000 }
1001
1002 fn resolve_role(&self, aref: &AccessibleRef) -> Role {
1004 let role_name = self.get_role_name(aref).unwrap_or_default();
1005 let by_name = if !role_name.is_empty() {
1006 map_atspi_role(&role_name)
1007 } else {
1008 Role::Unknown
1009 };
1010 let coarse = if by_name != Role::Unknown {
1011 by_name
1012 } else {
1013 let role_num = self.get_role_number(aref).unwrap_or(0);
1015 map_atspi_role_number(role_num)
1016 };
1017 self.refine_text_role(coarse, aref)
1018 }
1019
1020 fn matches_ref(
1034 &self,
1035 aref: &AccessibleRef,
1036 simple: &xa11y_core::selector::SimpleSelector,
1037 ) -> bool {
1038 let needs_role = simple.role.is_some()
1041 || simple
1042 .filters
1043 .iter()
1044 .any(|f| matches!(f.attr.as_str(), "role" | "checked"));
1045 let role = if needs_role {
1046 Some(self.resolve_role(aref))
1047 } else {
1048 None
1049 };
1050
1051 if let Some(ref role_match) = simple.role {
1052 match role_match {
1053 xa11y_core::selector::RoleMatch::Normalized(expected) => {
1054 if role != Some(*expected) {
1055 return false;
1056 }
1057 }
1058 xa11y_core::selector::RoleMatch::Platform(platform_role) => {
1059 let raw_role = self.get_role_name(aref).unwrap_or_default();
1060 if raw_role != *platform_role {
1061 return false;
1062 }
1063 }
1064 }
1065 }
1066
1067 let mut state_set: Option<StateSet> = None;
1068
1069 for filter in &simple.filters {
1070 let attr = filter.attr.as_str();
1071 let resolved: Option<Option<String>> = match attr {
1072 "role" => Some(role.map(|r| r.to_snake_case().to_string())),
1073 "name" => {
1074 let name = self.get_name(aref).ok().filter(|s| !s.is_empty());
1075 let resolved = if name.is_none() && role == Some(Role::StaticText) {
1078 self.get_value(aref)
1079 } else {
1080 name
1081 };
1082 Some(resolved)
1083 }
1084 "value" => Some(self.get_value(aref)),
1085 "description" => Some(self.get_description(aref).ok().filter(|s| !s.is_empty())),
1086 "enabled" | "visible" | "focused" | "focusable" | "selected" | "editable"
1087 | "modal" | "required" | "busy" | "expanded" | "checked" => {
1088 let s = state_set.get_or_insert_with(|| {
1089 self.parse_states(aref, role.unwrap_or(Role::Unknown))
1093 });
1094 Some(state_attr_to_string(attr, s))
1095 }
1096 _ => None, };
1098
1099 match resolved {
1100 Some(value) => {
1101 if !xa11y_core::selector::match_op(&filter.op, &filter.value, value.as_deref())
1102 {
1103 return false;
1104 }
1105 }
1106 None => {
1107 let pid = None; let data = self.build_element_data(aref, pid);
1115 return xa11y_core::selector::matches_simple(&data, simple);
1116 }
1117 }
1118 }
1119
1120 true
1121 }
1122
1123 fn collect_matching_refs_group(
1133 &self,
1134 parent: &AccessibleRef,
1135 clauses: &[&xa11y_core::selector::SimpleSelector],
1136 depth: u32,
1137 max_depth: u32,
1138 limit: Option<usize>,
1139 ) -> Result<Vec<(usize, AccessibleRef)>> {
1140 if depth > max_depth {
1141 return Ok(vec![]);
1142 }
1143
1144 let children = self.get_atspi_children(parent)?;
1145
1146 let parent_is_registry = parent.bus_name == "org.a11y.atspi.Registry";
1154 let mut to_search: Vec<AccessibleRef> = Vec::new();
1155 for child in children {
1156 if child.path == "/org/a11y/atspi/null"
1157 || child.bus_name.is_empty()
1158 || child.path.is_empty()
1159 {
1160 continue;
1161 }
1162
1163 if !parent_is_registry {
1164 let child_role = self.get_role_name(&child).unwrap_or_default();
1165 if child_role == "application" {
1166 let grandchildren = self.get_atspi_children(&child).unwrap_or_default();
1167 for gc in grandchildren {
1168 if gc.path == "/org/a11y/atspi/null"
1169 || gc.bus_name.is_empty()
1170 || gc.path.is_empty()
1171 {
1172 continue;
1173 }
1174 let gc_role = self.get_role_name(&gc).unwrap_or_default();
1175 if gc_role == "application" {
1176 continue;
1177 }
1178 to_search.push(gc);
1179 }
1180 continue;
1181 }
1182 }
1183 to_search.push(child);
1184 }
1185
1186 if to_search.is_empty() {
1189 self.check_chromium_a11y_enabled(parent, None)?;
1190 }
1191
1192 type ChildBatch = (Vec<(usize, AccessibleRef)>, Option<Error>);
1207 let per_child: Vec<ChildBatch> = to_search
1208 .par_iter()
1209 .map(|child| {
1210 let mut child_results: Vec<(usize, AccessibleRef)> = Vec::new();
1211 for (idx, simple) in clauses.iter().enumerate() {
1212 if self.matches_ref(child, simple) {
1213 child_results.push((idx, child.clone()));
1214 }
1215 }
1216 match self.collect_matching_refs_group(child, clauses, depth + 1, max_depth, limit)
1217 {
1218 Ok(sub) => {
1219 child_results.extend(sub);
1220 (child_results, None)
1221 }
1222 Err(e @ Error::AccessibilityNotEnabled { .. }) => (Vec::new(), Some(e)),
1223 Err(_) => (child_results, None),
1224 }
1225 })
1226 .collect();
1227
1228 let mut results = Vec::new();
1240 for (batch, maybe_err) in per_child {
1241 if let Some(err) = maybe_err {
1242 return Err(err);
1243 }
1244 for r in batch {
1245 results.push(r);
1246 if let Some(limit) = limit {
1247 if results.len() >= limit {
1248 return Ok(results);
1249 }
1250 }
1251 }
1252 }
1253 Ok(results)
1254 }
1255}
1256
1257impl Provider for LinuxProvider {
1258 fn get_children(&self, element: Option<&ElementData>) -> Result<Vec<ElementData>> {
1259 match element {
1260 None => {
1261 self.list_apps()
1264 }
1265 Some(element_data) => {
1266 let aref = self.get_cached(element_data.handle)?;
1267 let children = self.get_atspi_children(&aref).unwrap_or_default();
1268 let pid = element_data.pid;
1269
1270 let mut to_build: Vec<AccessibleRef> = Vec::new();
1273 for child_ref in &children {
1274 if child_ref.path == "/org/a11y/atspi/null"
1275 || child_ref.bus_name.is_empty()
1276 || child_ref.path.is_empty()
1277 {
1278 continue;
1279 }
1280 let child_role = self.get_role_name(child_ref).unwrap_or_default();
1281 if child_role == "application" {
1282 let grandchildren = self.get_atspi_children(child_ref).unwrap_or_default();
1283 for gc_ref in grandchildren {
1284 if gc_ref.path == "/org/a11y/atspi/null"
1285 || gc_ref.bus_name.is_empty()
1286 || gc_ref.path.is_empty()
1287 {
1288 continue;
1289 }
1290 let gc_role = self.get_role_name(&gc_ref).unwrap_or_default();
1291 if gc_role == "application" {
1292 continue;
1293 }
1294 to_build.push(gc_ref);
1295 }
1296 continue;
1297 }
1298 to_build.push(child_ref.clone());
1299 }
1300
1301 if to_build.is_empty() {
1302 self.check_chromium_a11y_enabled(&aref, Some(element_data.role))?;
1303 }
1304
1305 let results: Vec<ElementData> = to_build
1306 .par_iter()
1307 .map(|r| self.build_element_data(r, pid))
1308 .collect();
1309
1310 Ok(results)
1311 }
1312 }
1313 }
1314
1315 fn find_elements_group(
1316 &self,
1317 root: &ElementData,
1318 group: &xa11y_core::selector::SelectorGroup,
1319 limit: Option<usize>,
1320 max_depth: Option<u32>,
1321 ) -> Result<Vec<ElementData>> {
1322 if group.clauses.is_empty() {
1323 return Ok(vec![]);
1324 }
1325 if group.clauses.iter().any(|c| c.segments.is_empty()) {
1328 return Ok(vec![]);
1329 }
1330
1331 let max_depth_val = max_depth.unwrap_or(xa11y_core::MAX_TREE_DEPTH);
1341
1342 let firsts: Vec<&xa11y_core::selector::SimpleSelector> = group
1343 .clauses
1344 .iter()
1345 .map(|c| &c.segments[0].simple)
1346 .collect();
1347
1348 let start_ref = self.get_cached(root.handle)?;
1349
1350 let phase1_limit = if group.clauses.len() == 1 {
1359 let clause = &group.clauses[0];
1360 let first = firsts[0];
1361 let outer = if clause.segments.len() == 1 {
1362 limit
1363 } else {
1364 None
1365 };
1366 match (outer, first.nth) {
1367 (Some(l), Some(n)) => Some(l.max(n)),
1368 (_, Some(n)) => Some(n),
1369 (l, None) => l,
1370 }
1371 } else {
1372 None
1373 };
1374
1375 let phase1: Vec<(usize, AccessibleRef)> =
1376 self.collect_matching_refs_group(&start_ref, &firsts, 0, max_depth_val, phase1_limit)?;
1377
1378 let pid_from_root = root.pid;
1379
1380 let mut by_clause: Vec<Vec<(usize, AccessibleRef)>> =
1384 (0..group.clauses.len()).map(|_| Vec::new()).collect();
1385 for (walk_pos, (clause_idx, aref)) in phase1.into_iter().enumerate() {
1386 by_clause[clause_idx].push((walk_pos, aref));
1387 }
1388
1389 let mut merged: Vec<(usize, ElementData)> = Vec::new();
1397 for (clause_idx, hits) in by_clause.into_iter().enumerate() {
1398 if hits.is_empty() {
1399 continue;
1400 }
1401 let clause = &group.clauses[clause_idx];
1402 let phase1_data: Vec<(usize, ElementData)> = hits
1404 .par_iter()
1405 .map(|(pos, aref)| {
1406 (*pos, self.build_element_data(aref, pid_from_root))
1410 })
1411 .collect();
1412
1413 if clause.segments.len() == 1 {
1414 let mut candidates = phase1_data;
1416 if let Some(nth) = clause.segments[0].simple.nth {
1417 if nth <= candidates.len() {
1418 let kept = candidates.remove(nth - 1);
1419 candidates.clear();
1420 candidates.push(kept);
1421 } else {
1422 candidates.clear();
1423 }
1424 }
1425 merged.extend(candidates);
1426 continue;
1427 }
1428
1429 for (anchor_pos, head) in phase1_data {
1434 let narrowed = self.narrow_multi_segment(
1435 vec![head],
1436 &clause.segments[1..],
1437 max_depth_val,
1438 None,
1439 )?;
1440 for n in narrowed {
1441 merged.push((anchor_pos, n));
1442 }
1443 }
1444 }
1445
1446 merged.sort_by_key(|(pos, _)| *pos);
1450 let mut seen: HashSet<(String, String)> = HashSet::new();
1451 let mut out: Vec<ElementData> = Vec::with_capacity(merged.len());
1452 for (_, data) in merged {
1453 if let Ok(aref) = self.get_cached(data.handle) {
1457 if !seen.insert((aref.bus_name.clone(), aref.path.clone())) {
1458 continue;
1459 }
1460 }
1461 out.push(data);
1462 }
1463 if let Some(l) = limit {
1464 out.truncate(l);
1465 }
1466 Ok(out)
1467 }
1468
1469 fn get_parent(&self, element: &ElementData) -> Result<Option<ElementData>> {
1470 let aref = self.get_cached(element.handle)?;
1471 match self.get_atspi_parent(&aref)? {
1472 Some(parent_ref) => {
1473 let data = self.build_element_data(&parent_ref, element.pid);
1474 Ok(Some(data))
1475 }
1476 None => Ok(None),
1477 }
1478 }
1479
1480 fn list_apps(&self) -> Result<Vec<ElementData>> {
1487 let registry = AccessibleRef {
1488 bus_name: "org.a11y.atspi.Registry".to_string(),
1489 path: "/org/a11y/atspi/accessible/root".to_string(),
1490 };
1491 let children = self.get_atspi_children(®istry)?;
1492
1493 let valid: Vec<(&AccessibleRef, String)> = children
1495 .iter()
1496 .filter(|c| c.path != "/org/a11y/atspi/null")
1497 .filter_map(|c| {
1498 let name = self.get_name(c).unwrap_or_default();
1499 if name.is_empty() {
1500 None
1501 } else {
1502 Some((c, name))
1503 }
1504 })
1505 .collect();
1506
1507 let results: Vec<ElementData> = valid
1508 .par_iter()
1509 .map(|(child, app_name)| {
1510 let pid = self.get_app_pid(child);
1511 let mut data = self.build_element_data(child, pid);
1512 data.name = Some(app_name.clone());
1513 data
1514 })
1515 .collect();
1516
1517 Ok(results)
1518 }
1519
1520 fn press(&self, element: &ElementData) -> Result<()> {
1521 let target = self.get_cached(element.handle)?;
1522 if let Ok(index) = self.get_action_index(element.handle, "press") {
1524 return self.do_atspi_action_by_index(&target, index);
1525 }
1526 if element.role == Role::Button && self.is_gtk_toolkit(&target) {
1545 let outer_name = self.get_name(&target).unwrap_or_default();
1546 if let Some((inner, index)) = self.find_gtk_press_fallback(&target, &outer_name) {
1547 return self.do_atspi_action_by_index(&inner, index);
1548 }
1549 }
1550 Err(Error::ActionNotSupported {
1551 action: "press".to_string(),
1552 role: element.role,
1553 })
1554 }
1555
1556 fn focus(&self, element: &ElementData) -> Result<()> {
1557 let target = self.get_cached(element.handle)?;
1558 if let Ok(proxy) =
1562 self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Component")
1563 {
1564 if let Ok(reply) = proxy.call_method("GrabFocus", &()) {
1565 if let Ok(true) = reply.body().deserialize::<bool>() {
1567 return Ok(());
1568 }
1569 }
1571 }
1572 if let Ok(index) = self.get_action_index(element.handle, "focus") {
1573 return self.do_atspi_action_by_index(&target, index);
1574 }
1575 Err(Error::ActionNotSupported {
1576 action: "focus".to_string(),
1577 role: element.role,
1578 })
1579 }
1580
1581 fn blur(&self, element: &ElementData) -> Result<()> {
1582 let target = self.get_cached(element.handle)?;
1583 if let Some(parent_ref) = self.get_atspi_parent(&target)? {
1587 if parent_ref.path != "/org/a11y/atspi/null" {
1588 let p = self.make_proxy(
1589 &parent_ref.bus_name,
1590 &parent_ref.path,
1591 "org.a11y.atspi.Component",
1592 )?;
1593 p.call_method("GrabFocus", &())
1594 .map_err(|e| Error::Platform {
1595 code: -1,
1596 message: format!("Component.GrabFocus on parent failed: {}", e),
1597 })?;
1598 return Ok(());
1599 }
1600 }
1601 Err(Error::ActionNotSupported {
1602 action: "blur".to_string(),
1603 role: element.role,
1604 })
1605 }
1606
1607 fn toggle(&self, element: &ElementData) -> Result<()> {
1608 let target = self.get_cached(element.handle)?;
1609 if let Ok(index) = self.get_action_index(element.handle, "toggle") {
1614 return self.do_atspi_action_by_index(&target, index);
1615 }
1616 if matches!(
1639 element.role,
1640 Role::CheckBox | Role::RadioButton | Role::Switch
1641 ) {
1642 if let Ok(index) = self.get_action_index(element.handle, "press") {
1643 return self.do_atspi_action_by_index(&target, index);
1644 }
1645 }
1646 Err(Error::ActionNotSupported {
1647 action: "toggle".to_string(),
1648 role: element.role,
1649 })
1650 }
1651
1652 fn select(&self, element: &ElementData) -> Result<()> {
1653 let target = self.get_cached(element.handle)?;
1654 let index = self
1655 .get_action_index(element.handle, "select")
1656 .map_err(|_| Error::ActionNotSupported {
1657 action: "select".to_string(),
1658 role: element.role,
1659 })?;
1660 self.do_atspi_action_by_index(&target, index)
1661 }
1662
1663 fn expand(&self, element: &ElementData) -> Result<()> {
1664 let target = self.get_cached(element.handle)?;
1665 let index = self
1666 .get_action_index(element.handle, "expand")
1667 .map_err(|_| Error::ActionNotSupported {
1668 action: "expand".to_string(),
1669 role: element.role,
1670 })?;
1671 self.do_atspi_action_by_index(&target, index)
1672 }
1673
1674 fn collapse(&self, element: &ElementData) -> Result<()> {
1675 let target = self.get_cached(element.handle)?;
1676 let index = self
1677 .get_action_index(element.handle, "collapse")
1678 .map_err(|_| Error::ActionNotSupported {
1679 action: "collapse".to_string(),
1680 role: element.role,
1681 })?;
1682 self.do_atspi_action_by_index(&target, index)
1683 }
1684
1685 fn show_menu(&self, element: &ElementData) -> Result<()> {
1686 let target = self.get_cached(element.handle)?;
1687 let index = self
1688 .get_action_index(element.handle, "show_menu")
1689 .map_err(|_| Error::ActionNotSupported {
1690 action: "show_menu".to_string(),
1691 role: element.role,
1692 })?;
1693 self.do_atspi_action_by_index(&target, index)
1694 }
1695
1696 fn increment(&self, element: &ElementData) -> Result<()> {
1697 let target = self.get_cached(element.handle)?;
1698 if let Ok(index) = self.get_action_index(element.handle, "increment") {
1700 return self.do_atspi_action_by_index(&target, index);
1701 }
1702 let proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Value")?;
1703 let current: f64 = proxy
1704 .get_property("CurrentValue")
1705 .map_err(|e| Error::Platform {
1706 code: -1,
1707 message: format!("Value.CurrentValue failed: {}", e),
1708 })?;
1709 let step: f64 = proxy.get_property("MinimumIncrement").unwrap_or(1.0);
1710 let step = if step <= 0.0 { 1.0 } else { step };
1711 proxy
1712 .set_property("CurrentValue", current + step)
1713 .map_err(|e| Error::Platform {
1714 code: -1,
1715 message: format!("Value.SetCurrentValue failed: {}", e),
1716 })
1717 }
1718
1719 fn decrement(&self, element: &ElementData) -> Result<()> {
1720 let target = self.get_cached(element.handle)?;
1721 if let Ok(index) = self.get_action_index(element.handle, "decrement") {
1722 return self.do_atspi_action_by_index(&target, index);
1723 }
1724 let proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Value")?;
1725 let current: f64 = proxy
1726 .get_property("CurrentValue")
1727 .map_err(|e| Error::Platform {
1728 code: -1,
1729 message: format!("Value.CurrentValue failed: {}", e),
1730 })?;
1731 let step: f64 = proxy.get_property("MinimumIncrement").unwrap_or(1.0);
1732 let step = if step <= 0.0 { 1.0 } else { step };
1733 proxy
1734 .set_property("CurrentValue", current - step)
1735 .map_err(|e| Error::Platform {
1736 code: -1,
1737 message: format!("Value.SetCurrentValue failed: {}", e),
1738 })
1739 }
1740
1741 fn scroll_into_view(&self, element: &ElementData) -> Result<()> {
1742 let target = self.get_cached(element.handle)?;
1743 let proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Component")?;
1744 proxy
1745 .call_method("ScrollTo", &(0u32,))
1746 .map_err(|e| Error::Platform {
1747 code: -1,
1748 message: format!("ScrollTo failed: {}", e),
1749 })?;
1750 Ok(())
1751 }
1752
1753 fn set_value(&self, element: &ElementData, value: &str) -> Result<()> {
1754 let target = self.get_cached(element.handle)?;
1755 let proxy = self
1756 .make_proxy(
1757 &target.bus_name,
1758 &target.path,
1759 "org.a11y.atspi.EditableText",
1760 )
1761 .map_err(|_| Error::TextValueNotSupported)?;
1762 if proxy.call_method("SetTextContents", &(value,)).is_ok() {
1764 return Ok(());
1765 }
1766 let classify_editable_text_error = |op: &str, e: zbus::Error| -> Error {
1772 let msg = e.to_string();
1773 if msg.contains("UnknownMethod") || msg.contains("UnknownInterface") {
1774 Error::TextValueNotSupported
1775 } else {
1776 Error::Platform {
1777 code: -1,
1778 message: format!("EditableText.{} failed: {}", op, msg),
1779 }
1780 }
1781 };
1782 if let Err(e) = proxy.call_method("DeleteText", &(0i32, i32::MAX)) {
1783 return Err(classify_editable_text_error("DeleteText", e));
1784 }
1785 if let Err(e) = proxy.call_method("InsertText", &(0i32, value, value.len() as i32)) {
1786 return Err(classify_editable_text_error("InsertText", e));
1787 }
1788 Ok(())
1789 }
1790
1791 fn set_numeric_value(&self, element: &ElementData, value: f64) -> Result<()> {
1792 let target = self.get_cached(element.handle)?;
1793 let proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Value")?;
1794 proxy
1795 .set_property("CurrentValue", value)
1796 .map_err(|e| Error::Platform {
1797 code: -1,
1798 message: format!("SetValue failed: {}", e),
1799 })
1800 }
1801
1802 fn type_text(&self, element: &ElementData, text: &str) -> Result<()> {
1803 let target = self.get_cached(element.handle)?;
1804 let text_proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Text");
1807 let insert_pos = text_proxy
1808 .as_ref()
1809 .ok()
1810 .and_then(|p| p.get_property::<i32>("CaretOffset").ok())
1811 .unwrap_or(-1); let proxy = self
1814 .make_proxy(
1815 &target.bus_name,
1816 &target.path,
1817 "org.a11y.atspi.EditableText",
1818 )
1819 .map_err(|_| Error::TextValueNotSupported)?;
1820 let pos = if insert_pos >= 0 {
1821 insert_pos
1822 } else {
1823 i32::MAX
1824 };
1825 proxy
1826 .call_method("InsertText", &(pos, text, text.len() as i32))
1827 .map_err(|e| Error::Platform {
1828 code: -1,
1829 message: format!("EditableText.InsertText failed: {}", e),
1830 })?;
1831 Ok(())
1832 }
1833
1834 fn set_text_selection(&self, element: &ElementData, start: u32, end: u32) -> Result<()> {
1835 let target = self.get_cached(element.handle)?;
1836 let proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Text")?;
1837 proxy
1838 .call_method("SetSelection", &(0i32, start as i32, end as i32))
1839 .map_err(|e| Error::Platform {
1840 code: -1,
1841 message: format!("Text.SetSelection failed: {}", e),
1842 })?;
1843 Ok(())
1844 }
1845
1846 fn perform_action(&self, element: &ElementData, action: &str) -> Result<()> {
1847 match action {
1848 "press" => self.press(element),
1849 "focus" => self.focus(element),
1850 "blur" => self.blur(element),
1851 "toggle" => self.toggle(element),
1852 "select" => self.select(element),
1853 "expand" => self.expand(element),
1854 "collapse" => self.collapse(element),
1855 "show_menu" => self.show_menu(element),
1856 "increment" => self.increment(element),
1857 "decrement" => self.decrement(element),
1858 "scroll_into_view" => self.scroll_into_view(element),
1859 _ => Err(Error::ActionNotSupported {
1860 action: action.to_string(),
1861 role: element.role,
1862 }),
1863 }
1864 }
1865
1866 fn subscribe(&self, element: &ElementData) -> Result<Subscription> {
1867 let pid = element.pid.ok_or(Error::Platform {
1868 code: -1,
1869 message: "Element has no PID for subscribe".to_string(),
1870 })?;
1871 let app_name = element.name.clone().unwrap_or_default();
1872 crate::events::subscribe_for_pid(self, pid, app_name)
1873 }
1874}
1875
1876fn role_has_value(role: Role) -> bool {
1879 !matches!(
1880 role,
1881 Role::Application
1882 | Role::Window
1883 | Role::Dialog
1884 | Role::Group
1885 | Role::MenuBar
1886 | Role::Toolbar
1887 | Role::TabGroup
1888 | Role::SplitGroup
1889 | Role::Table
1890 | Role::TableRow
1891 | Role::Separator
1892 )
1893}
1894
1895fn role_has_actions(role: Role) -> bool {
1898 matches!(
1899 role,
1900 Role::Button
1901 | Role::CheckBox
1902 | Role::RadioButton
1903 | Role::MenuItem
1904 | Role::Link
1905 | Role::ComboBox
1906 | Role::TextField
1907 | Role::TextArea
1908 | Role::SpinButton
1909 | Role::Tab
1910 | Role::TreeItem
1911 | Role::ListItem
1912 | Role::ScrollBar
1913 | Role::Slider
1914 | Role::Menu
1915 | Role::Image
1916 | Role::Unknown
1917 )
1918}
1919
1920pub(crate) fn map_atspi_role(role_name: &str) -> Role {
1922 match role_name.to_lowercase().as_str() {
1923 "application" => Role::Application,
1924 "window" | "frame" => Role::Window,
1925 "dialog" | "file chooser" => Role::Dialog,
1926 "alert" | "notification" => Role::Alert,
1927 "push button" | "push button menu" => Role::Button,
1928 "toggle button" => Role::Switch,
1929 "check box" | "check menu item" => Role::CheckBox,
1930 "radio button" | "radio menu item" => Role::RadioButton,
1931 "entry" | "password text" => Role::TextField,
1932 "spin button" | "spinbutton" => Role::SpinButton,
1933 "text" | "textbox" => Role::TextArea,
1937 "label" | "static" | "caption" => Role::StaticText,
1938 "combo box" | "combobox" => Role::ComboBox,
1939 "list" | "list box" | "listbox" => Role::List,
1941 "list item" => Role::ListItem,
1942 "menu" => Role::Menu,
1943 "menu item" | "tearoff menu item" => Role::MenuItem,
1944 "menu bar" => Role::MenuBar,
1945 "page tab" => Role::Tab,
1946 "page tab list" => Role::TabGroup,
1947 "table" | "tree table" => Role::Table,
1948 "table row" => Role::TableRow,
1949 "table cell" | "table column header" | "table row header" => Role::TableCell,
1950 "tool bar" => Role::Toolbar,
1951 "scroll bar" => Role::ScrollBar,
1952 "slider" => Role::Slider,
1953 "image" | "icon" | "desktop icon" => Role::Image,
1954 "link" => Role::Link,
1955 "panel" | "section" | "form" | "filler" | "viewport" | "scroll pane" => Role::Group,
1956 "progress bar" => Role::ProgressBar,
1957 "tree item" => Role::TreeItem,
1958 "document web" | "document frame" => Role::WebArea,
1959 "heading" => Role::Heading,
1960 "separator" => Role::Separator,
1961 "split pane" => Role::SplitGroup,
1962 "tooltip" | "tool tip" => Role::Tooltip,
1963 "status bar" | "statusbar" => Role::Status,
1964 "landmark" | "navigation" => Role::Navigation,
1965 _ => xa11y_core::unknown_role(role_name),
1966 }
1967}
1968
1969pub(crate) fn map_atspi_role_number(role: u32) -> Role {
1972 match role {
1973 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}")),
2035 }
2036}
2037
2038const GTK_FALLBACK_MAX_DEPTH: u32 = 3;
2042
2043const GTK_FALLBACK_MAX_NODES: usize = 200;
2046
2047fn is_actionable_atspi_role(role: &str) -> bool {
2052 matches!(
2053 role,
2054 "push button"
2055 | "toggle button"
2056 | "check box"
2057 | "radio button"
2058 | "menu item"
2059 | "check menu item"
2060 | "radio menu item"
2061 | "link"
2062 | "page tab"
2063 | "tab"
2064 | "list item"
2065 | "tree item"
2066 )
2067}
2068
2069fn is_never_descend_atspi_role(role: &str) -> bool {
2074 matches!(
2075 role,
2076 "label" | "separator" | "image" | "icon" | "static" | "caption"
2077 )
2078}
2079
2080fn map_atspi_action_name(action_name: &str) -> Option<String> {
2094 let lower = action_name.to_lowercase();
2103 let collapsed: String = lower.chars().filter(|c| !matches!(c, '_' | ' ')).collect();
2104 let canonical = match collapsed.as_str() {
2105 "click" | "activate" | "press" | "invoke" | "dodefault" => "press",
2106 "toggle" | "check" | "uncheck" => "toggle",
2107 "expand" | "open" => "expand",
2108 "collapse" | "close" => "collapse",
2109 "select" => "select",
2110 "menu" | "showmenu" | "showcontextmenu" | "contextmenu" | "popup" => "show_menu",
2111 "increment" => "increment",
2112 "decrement" => "decrement",
2113 _ => return None,
2114 };
2115 Some(canonical.to_string())
2116}
2117
2118#[cfg(test)]
2119mod tests {
2120 use super::*;
2121
2122 #[test]
2123 fn test_role_mapping() {
2124 assert_eq!(map_atspi_role("push button"), Role::Button);
2125 assert_eq!(map_atspi_role("toggle button"), Role::Switch);
2126 assert_eq!(map_atspi_role("check box"), Role::CheckBox);
2127 assert_eq!(map_atspi_role("entry"), Role::TextField);
2128 assert_eq!(map_atspi_role("label"), Role::StaticText);
2129 assert_eq!(map_atspi_role("window"), Role::Window);
2130 assert_eq!(map_atspi_role("frame"), Role::Window);
2131 assert_eq!(map_atspi_role("dialog"), Role::Dialog);
2132 assert_eq!(map_atspi_role("combo box"), Role::ComboBox);
2133 assert_eq!(map_atspi_role("slider"), Role::Slider);
2134 assert_eq!(map_atspi_role("panel"), Role::Group);
2135 assert_eq!(map_atspi_role("unknown_thing"), Role::Unknown);
2136 }
2137
2138 #[test]
2139 fn test_numeric_role_mapping() {
2140 assert_eq!(map_atspi_role_number(62), Role::Switch);
2143 assert_eq!(map_atspi_role_number(43), Role::Button); assert_eq!(map_atspi_role_number(7), Role::CheckBox);
2146 assert_eq!(map_atspi_role_number(67), Role::Unknown); }
2148
2149 #[test]
2150 fn test_action_name_mapping() {
2151 assert_eq!(map_atspi_action_name("click"), Some("press".to_string()));
2152 assert_eq!(map_atspi_action_name("activate"), Some("press".to_string()));
2153 assert_eq!(map_atspi_action_name("press"), Some("press".to_string()));
2154 assert_eq!(map_atspi_action_name("invoke"), Some("press".to_string()));
2155 assert_eq!(
2157 map_atspi_action_name("doDefault"),
2158 Some("press".to_string())
2159 );
2160 assert_eq!(
2161 map_atspi_action_name("do_default"),
2162 Some("press".to_string())
2163 );
2164 assert_eq!(map_atspi_action_name("toggle"), Some("toggle".to_string()));
2165 assert_eq!(map_atspi_action_name("check"), Some("toggle".to_string()));
2166 assert_eq!(map_atspi_action_name("uncheck"), Some("toggle".to_string()));
2167 assert_eq!(map_atspi_action_name("expand"), Some("expand".to_string()));
2168 assert_eq!(map_atspi_action_name("open"), Some("expand".to_string()));
2169 assert_eq!(
2170 map_atspi_action_name("collapse"),
2171 Some("collapse".to_string())
2172 );
2173 assert_eq!(map_atspi_action_name("close"), Some("collapse".to_string()));
2174 assert_eq!(map_atspi_action_name("select"), Some("select".to_string()));
2175 assert_eq!(map_atspi_action_name("menu"), Some("show_menu".to_string()));
2176 assert_eq!(
2177 map_atspi_action_name("showmenu"),
2178 Some("show_menu".to_string())
2179 );
2180 assert_eq!(
2181 map_atspi_action_name("popup"),
2182 Some("show_menu".to_string())
2183 );
2184 assert_eq!(
2185 map_atspi_action_name("show menu"),
2186 Some("show_menu".to_string())
2187 );
2188 assert_eq!(
2191 map_atspi_action_name("showContextMenu"),
2192 Some("show_menu".to_string())
2193 );
2194 assert_eq!(
2195 map_atspi_action_name("show_context_menu"),
2196 Some("show_menu".to_string())
2197 );
2198 assert_eq!(
2199 map_atspi_action_name("increment"),
2200 Some("increment".to_string())
2201 );
2202 assert_eq!(
2203 map_atspi_action_name("decrement"),
2204 Some("decrement".to_string())
2205 );
2206 assert_eq!(map_atspi_action_name("foobar"), None);
2207 }
2208
2209 #[test]
2212 fn test_action_name_aliases_roundtrip() {
2213 let atspi_names = [
2214 "click",
2215 "activate",
2216 "press",
2217 "invoke",
2218 "doDefault",
2219 "do_default",
2220 "toggle",
2221 "check",
2222 "uncheck",
2223 "expand",
2224 "open",
2225 "collapse",
2226 "close",
2227 "select",
2228 "menu",
2229 "showmenu",
2230 "showContextMenu",
2231 "show_context_menu",
2232 "popup",
2233 "show menu",
2234 "increment",
2235 "decrement",
2236 ];
2237 for name in atspi_names {
2238 let canonical = map_atspi_action_name(name).unwrap_or_else(|| {
2239 panic!("AT-SPI2 name {:?} should map to a canonical name", name)
2240 });
2241 let back = map_atspi_action_name(&canonical)
2243 .unwrap_or_else(|| panic!("canonical {:?} should map back to itself", canonical));
2244 assert_eq!(
2245 canonical, back,
2246 "AT-SPI2 {:?} -> {:?} -> {:?} (expected {:?})",
2247 name, canonical, back, canonical
2248 );
2249 }
2250 }
2251
2252 #[test]
2254 fn test_action_name_case_insensitive() {
2255 assert_eq!(map_atspi_action_name("Click"), Some("press".to_string()));
2256 assert_eq!(map_atspi_action_name("TOGGLE"), Some("toggle".to_string()));
2257 assert_eq!(
2258 map_atspi_action_name("Increment"),
2259 Some("increment".to_string())
2260 );
2261 }
2262
2263 #[test]
2268 fn test_gtk_fallback_actionable_roles() {
2269 for role in [
2270 "push button",
2271 "toggle button",
2272 "check box",
2273 "radio button",
2274 "menu item",
2275 "link",
2276 "tab",
2277 "list item",
2278 "tree item",
2279 ] {
2280 assert!(
2281 is_actionable_atspi_role(role),
2282 "{role:?} should be actionable"
2283 );
2284 }
2285 }
2286
2287 #[test]
2292 fn test_gtk_fallback_non_actionable_roles() {
2293 for role in [
2294 "label",
2295 "panel",
2296 "filler",
2297 "section",
2298 "group",
2299 "image",
2300 "separator",
2301 "static",
2302 "frame",
2303 "window",
2304 ] {
2305 assert!(
2306 !is_actionable_atspi_role(role),
2307 "{role:?} must not be treated as actionable"
2308 );
2309 }
2310 }
2311
2312 #[test]
2316 fn test_gtk_fallback_never_descend_roles() {
2317 for role in ["label", "separator", "image", "icon", "static", "caption"] {
2318 assert!(
2319 is_never_descend_atspi_role(role),
2320 "{role:?} must block BFS descent"
2321 );
2322 }
2323 for role in ["panel", "filler", "section", "group", "frame"] {
2326 assert!(
2327 !is_never_descend_atspi_role(role),
2328 "container role {role:?} must remain descendable"
2329 );
2330 }
2331 }
2332}