Skip to main content

xa11y_linux/
atspi.rs

1//! Real AT-SPI2 backend implementation using zbus D-Bus bindings.
2
3use 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
13/// Global handle counter for mapping ElementData back to AccessibleRefs.
14static NEXT_HANDLE: AtomicU64 = AtomicU64::new(1);
15
16/// Format a normalized state attribute as the same string `xa11y_core::selector::resolve_attr`
17/// would produce, so fast-path matching agrees byte-for-byte with the slow path.
18fn 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
42/// Linux accessibility provider using AT-SPI2 over D-Bus.
43pub struct LinuxProvider {
44    a11y_bus: Connection,
45    /// Cached AT-SPI accessible refs keyed by handle ID.
46    handle_cache: Mutex<HashMap<u64, AccessibleRef>>,
47    /// Cached AT-SPI2 action indices keyed by element handle.
48    /// Maps each action name (snake_case) to the integer index used by `DoAction(i)`.
49    action_indices: Mutex<HashMap<u64, HashMap<String, i32>>>,
50}
51
52/// AT-SPI2 accessible reference: (bus_name, object_path).
53#[derive(Debug, Clone)]
54pub(crate) struct AccessibleRef {
55    pub(crate) bus_name: String,
56    pub(crate) path: String,
57}
58
59impl LinuxProvider {
60    /// Create a new Linux accessibility provider.
61    ///
62    /// Connects to the AT-SPI2 bus. Falls back to the session bus
63    /// if the dedicated AT-SPI bus is unavailable.
64    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        // Try getting the AT-SPI bus address from the a11y bus launcher,
75        // then connect to it. If that fails, fall back to the session bus
76        // (AT-SPI2 may use the session bus directly).
77        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            // Fall back to session bus
97            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        // Use uncached proxy to avoid GetAll calls — Qt's AT-SPI adaptor
108        // doesn't support GetAll on all objects, causing spurious errors.
109        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    /// Check whether an accessible object implements a given interface.
134    /// Queries the AT-SPI GetInterfaces method on the Accessible interface.
135    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    /// Get the numeric AT-SPI role via GetRole method.
152    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    /// Get the AT-SPI role name string.
170    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    /// Detect Chromium/Electron's "accessibility bridge disabled" signature.
188    ///
189    /// On Linux, Chromium-based apps (Electron, Chrome, VS Code, …) register
190    /// with AT-SPI but expose only an `application → frame` skeleton — the
191    /// frame's children list is empty (just the `/org/a11y/atspi/null`
192    /// sentinel) — unless the process was launched with the
193    /// `--force-renderer-accessibility` flag. Without this detection, callers
194    /// see zero results and assume their selector is wrong.
195    ///
196    /// Call this after observing an empty filtered children list. Returns an
197    /// error only when the parent is a window/frame whose AT-SPI bus reports
198    /// `Application.ToolkitName == "Chromium"`; otherwise returns `Ok(())` so
199    /// genuinely empty windows in other toolkits stay valid.
200    ///
201    /// `role_hint` lets callers that already know the role skip a `GetRole`
202    /// round-trip.
203    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    /// Get the name of an accessible element.
242    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    /// Get the description of an accessible element.
253    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    /// Get children via the GetChildren method.
264    /// AT-SPI registryd doesn't always implement standard D-Bus Properties,
265    /// so we use GetChildren which is more reliable.
266    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    /// Get the state set as raw u32 values.
289    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    /// Return true if the element reports the AT-SPI MULTI_LINE state.
307    /// Used to distinguish multi-line text areas (TextArea) from single-line
308    /// text inputs (TextField), since both use the AT-SPI "text" role name.
309    /// Note: Qt's AT-SPI bridge does not reliably set SINGLE_LINE, so we
310    /// check MULTI_LINE and default to TextField when neither is set.
311    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        // ATSPI_STATE_MULTI_LINE = 17 in AtspiStateType enum
321        const MULTI_LINE: u64 = 1 << 17;
322        (bits & MULTI_LINE) != 0
323    }
324
325    /// Resolve TextField vs TextArea using the MULTI_LINE state, regardless of
326    /// the coarse role we started with. Different toolkits expose text inputs
327    /// under different AT-SPI roles ("text", "textbox", "entry", "embedded",
328    /// numeric 61/78/79), and WebKitGTK has changed mapping between versions
329    /// (e.g. 2.50 → 2.52 swapped what role textarea reports). MULTI_LINE is
330    /// the cross-toolkit invariant, so we let it decide.
331    ///
332    /// For any other coarse role, returns it unchanged.
333    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    /// Get bounds via Component interface.
347    /// Checks for Component support first to avoid GTK CRITICAL warnings
348    /// on objects (e.g. TreeView cell renderers) that don't implement it.
349    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        // GetExtents(coord_type: u32) -> (x, y, width, height)
357        // coord_type 0 = screen coordinates
358        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    /// Get available actions via Action interface, returning both the action list
372    /// and a map of each action name to its AT-SPI2 integer index for direct `DoAction(i)`.
373    ///
374    /// Probes the interface directly rather than relying on the Interfaces property,
375    /// which some AT-SPI adapters (e.g. AccessKit) don't expose.
376    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        // Try Action interface directly
381        if let Ok(proxy) = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Action") {
382            // NActions may be returned as i32 or u32 depending on AT-SPI implementation.
383            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        // NOTE: We do NOT add implicit "focus" based on Component interface existence.
402        // On GTK4, GrabFocus() often returns false even when Component interface exists,
403        // violating design tenet 3 ("if action is listed, calling it must work").
404        // Only report "focus" if it's explicitly in the AT-SPI Action interface with a
405        // proper index. This ensures focus() will work when reported.
406        // Fixes GitHub issue #98.
407
408        (actions, indices)
409    }
410
411    /// Return true when the accessible's application identifies itself as GTK
412    /// via `org.a11y.atspi.Application.ToolkitName`.
413    ///
414    /// Used to scope the press-fallback heuristic for the
415    /// AdwMenuButton/GtkMenuButton wrapper pattern; other toolkits are
416    /// unaffected.
417    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    /// GTK press-fallback resolver.
434    ///
435    /// Walks the accessible's descendants (BFS, depth-capped) looking for a
436    /// single activatable child that shares the outer widget's name. Returns
437    /// the (ref, action_index) pair when exactly one suitable candidate
438    /// exists at the shallowest matching depth. Returns `None` when the
439    /// subtree contains nothing suitable or multiple equally plausible
440    /// candidates — refusing to guess.
441    ///
442    /// Empirically fixes the `GtkMenuButton` / `AdwMenuButton` wrappers that
443    /// ship in every stock GNOME app (Calculator, Text Editor, Logs, Clocks,
444    /// Characters, …).
445    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            // Once we've found the shallowest level with hits, don't look deeper.
458            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            // Do not descend into static/decorative roles. Descend through
493            // containers and actionable roles alike (actionable roles may
494            // themselves wrap an inner actionable — e.g. an AdwSplitButton's
495            // primary button inside a toggle-button shell).
496            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    /// Per-node filter for `find_gtk_press_fallback`. Returns the AT-SPI
516    /// action index to invoke when `aref` is a valid fallback candidate.
517    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 the outer has a name, require the candidate to share it. Rules
524        // out unrelated suffix widgets (e.g. a switch inside an AdwActionRow
525        // that happens to expose `click`).
526        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    /// True when the accessible's state has SHOWING, VISIBLE, and SENSITIVE
536    /// set. ENABLED is deliberately excluded: in GTK4 it reflects "has an
537    /// enabled GAction bound", which is false for the exact widgets we
538    /// rescue.
539    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    /// Get value via Value or Text interface.
555    /// Probes interfaces directly rather than relying on the Interfaces property.
556    fn get_value(&self, aref: &AccessibleRef) -> Option<String> {
557        // Try Text interface first for text content (text fields, labels, combo boxes).
558        // This must come before Value because some AT-SPI adapters (e.g. AccessKit)
559        // may expose both interfaces, and Value.CurrentValue returns 0.0 for text elements.
560        let text_value = self.get_text_content(aref);
561        if text_value.is_some() {
562            return text_value;
563        }
564        // Try Value interface (sliders, progress bars, scroll bars, spinners)
565        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    /// Read text content via the AT-SPI Text interface.
574    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    /// Cache an AccessibleRef and return a new handle ID.
590    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    /// Look up a cached AccessibleRef by handle.
600    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    /// Build an ElementData from an AccessibleRef, caching the ref for later lookup.
612    ///
613    /// After resolving the role (1-3 sequential D-Bus calls), all remaining
614    /// property fetches are independent and run in parallel via rayon::join.
615    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        // Fetch all independent properties in parallel.
633        // Left tree: (name+value, description)
634        // Right tree: ((states, bounds), (actions, numeric_values))
635        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        // For label/static text elements, AT-SPI may put content in the Text
711        // interface (returned as value) rather than the Name property.
712        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            // Preserve unstripped originals so callers who need bidi marks can
735            // recover them after the strip below.
736            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        // Strip Unicode bidi format controls. RTL apps on Linux embed LRM/RLM
752        // marks into reported strings; the originals are preserved in `raw`.
753        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    /// Get the AT-SPI parent of an accessible ref.
784    fn get_atspi_parent(&self, aref: &AccessibleRef) -> Result<Option<AccessibleRef>> {
785        // Read the Parent property via the D-Bus Properties interface.
786        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        // The reply is a Variant containing (so) — a struct of (bus_name, object_path)
798        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 the parent is the registry root, this is a top-level app — no parent
815        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    /// Parse AT-SPI2 state bitfield into xa11y StateSet.
825    fn parse_states(&self, aref: &AccessibleRef, role: Role) -> StateSet {
826        let state_bits = self.get_state(aref).unwrap_or_default();
827
828        // AT-SPI2 states are a bitfield across two u32s
829        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        // AT-SPI2 state bit positions (AtspiStateType enum values)
838        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    /// Find an application by PID.
892    ///
893    /// Used by `subscribe` to resolve the target app's D-Bus sender name so
894    /// signal match rules can be scoped to it.
895    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(&registry)?;
901
902        for child in &children {
903            if child.path == "/org/a11y/atspi/null" {
904                continue;
905            }
906            // Prefer D-Bus connection PID — it's authoritative for the
907            // process owning the bus connection. Application.Id is *not* a
908            // process pid: AT-SPI assigns it as a registry-local index
909            // (1, 2, 3, …) for some bridges (notably GTK4), so matching
910            // against Application.Id alone misses real processes.
911            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            // Fall back to Application.Id for adapters that do set it to pid.
917            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    /// Get PID via D-Bus GetConnectionUnixProcessID.
935    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    /// Perform an AT-SPI2 action by its integer index (from discovery).
955    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    /// Look up the stored AT-SPI2 action index for the given element and action.
967    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, // caller will provide better context
976            })
977    }
978
979    /// Get the process PID for an AT-SPI accessible. Prefers the D-Bus
980    /// connection PID over `Application.Id`: the latter is a registry-local
981    /// index (1, 2, 3, …) on some bridges (e.g. GTK4), not a real pid, so
982    /// reading it first produces apps whose `pid` property doesn't match the
983    /// process the user launched.
984    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        // Fall back to Application.Id for adapters that set it to pid.
990        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    /// Resolve the mapped Role for an accessible ref (1-3 D-Bus calls).
1003    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            // Unmapped or missing role name — fall back to numeric role.
1014            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    /// Check if an accessible ref matches a simple selector, fetching only the
1021    /// attributes the selector actually requires.
1022    ///
1023    /// Filter routing (cheapest first):
1024    ///   * `role` / `name` / `value` / `description` — single targeted D-Bus
1025    ///     call against this accessible.
1026    ///   * Normalized state attrs (`enabled`, `checked`, `focused`, …) —
1027    ///     one shared `GetState` call, cached for the rest of this match.
1028    ///   * Anything else (custom `raw` keys, `bounds`, numeric values) — fall
1029    ///     through to building a full `ElementData` and delegating to
1030    ///     [`xa11y_core::selector::matches_simple`]. This is slower but keeps
1031    ///     selectors with rare attribute filters semantically equivalent to
1032    ///     the default tree-traversal path.
1033    fn matches_ref(
1034        &self,
1035        aref: &AccessibleRef,
1036        simple: &xa11y_core::selector::SimpleSelector,
1037    ) -> bool {
1038        // Resolve role only if the selector needs it (for either the role
1039        // segment or any role/checked filter — checked depends on role).
1040        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                    // Mirror build_element_data: StaticText carries its name
1076                    // in the Text interface's Value when Name is empty.
1077                    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                        // `parse_states` reads `checked` based on role; pass
1090                        // whatever we already resolved (Unknown is a no-op for
1091                        // the role-gated `checked` mapping).
1092                        self.parse_states(aref, role.unwrap_or(Role::Unknown))
1093                    });
1094                    Some(state_attr_to_string(attr, s))
1095                }
1096                _ => None, // Routed through full ElementData below.
1097            };
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                    // Filter targets an attribute the fast path doesn't know
1108                    // (e.g. `bounds`, `numeric_value`, a custom `raw` key).
1109                    // Build the full ElementData once and let the shared
1110                    // matcher handle every remaining filter — it dispatches
1111                    // to `ElementData` fields and the `raw` map identically
1112                    // to the default tree-traversal path.
1113                    let pid = None; // pid isn't selector-addressable
1114                    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    /// ONE DFS over the subtree, evaluating each clause's first SimpleSelector
1124    /// against every visited node. Emits `(clause_idx, AccessibleRef)` pairs
1125    /// in document order; a node that matches multiple clauses is emitted
1126    /// once per matching clause (the merge step in `find_elements_group`
1127    /// collapses these by `(bus_name, path)` identity).
1128    ///
1129    /// This is the "push-down to the platform query per group" core: a
1130    /// selector group like `button, text_field` traverses the AT-SPI tree
1131    /// exactly once regardless of clause count, instead of N separate walks.
1132    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        // Filter invalid refs. Application-node flattening (collapsing a
1147        // redundant `application` accessible into its grandchildren) is only
1148        // valid when the parent is itself an application — i.e. we have already
1149        // descended past the registry. At the registry root, the children *are*
1150        // the applications and must not be collapsed, otherwise selectors like
1151        // `application` (used by `App::list` / `App::by_name`) match nothing
1152        // because the app accessibles get dissolved into their windows.
1153        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        // Detect Chromium/Electron's empty-tree signature whenever we
1187        // descend into a parent and find no real children.
1188        if to_search.is_empty() {
1189            self.check_chromium_a11y_enabled(parent, None)?;
1190        }
1191
1192        // Process each child subtree in parallel: check match against every
1193        // clause + recurse. Tagging each match with `clause_idx` lets the
1194        // caller route phase-2 narrowing to the right clause without
1195        // re-running the first-segment match.
1196        //
1197        // We deliberately swallow transient sibling errors here — a single
1198        // flaky D-Bus call on one child shouldn't fail the whole locator
1199        // query (the rest of this file is similarly tolerant via
1200        // `unwrap_or_default()`). But `AccessibilityNotEnabled` is *not* a
1201        // transient error: it's the signal that a Chromium renderer bridge
1202        // isn't initialised, and callers need to see it. So we propagate
1203        // that variant specifically and keep tolerating everything else.
1204        // Per-child batches: matches collected during that child's subtree
1205        // walk, plus the first AccessibilityNotEnabled error (if any).
1206        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        // Merge results, respecting limit. The first AccessibilityNotEnabled
1229        // error seen wins — any child subtree raising it means the whole
1230        // query is untrustworthy, so surface it rather than return partial
1231        // data.
1232        //
1233        // Note: `limit` is the *caller's* outer limit; for a multi-clause
1234        // group it must not be applied per-clause (a low-priority clause's
1235        // hit could come before a high-priority clause's in doc order, so
1236        // truncating mid-walk would drop legitimate matches). Callers pass
1237        // `None` for multi-clause queries and apply the limit after the
1238        // cross-clause merge.
1239        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                // Top-level: delegate to `list_apps()`, the canonical
1262                // discovery primitive.
1263                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                // Pre-filter invalid refs and flatten nested application nodes,
1271                // collecting the concrete refs to build in parallel.
1272                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        // Reject any clause with zero segments early — `clause.segments[0]`
1326        // below would otherwise panic.
1327        if group.clauses.iter().any(|c| c.segments.is_empty()) {
1328            return Ok(vec![]);
1329        }
1330
1331        // ONE AT-SPI walk that evaluates every clause's first SimpleSelector
1332        // against each visited node, then per-clause phase-2 narrowing on
1333        // the small candidate sets that fall out. Dedup uses
1334        // `(bus_name, path)` — the only AT-SPI identifier that's stable
1335        // across the per-clause narrowings (handles are minted fresh on
1336        // each `build_element_data` call).
1337        //
1338        // App discovery is handled separately by `list_apps()` — `root` is
1339        // always present here.
1340        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        // ── Phase-1 limit short-circuit ───────────────────────────
1351        // When there's exactly one clause, propagate the user's `limit`
1352        // (adjusted for `:nth`) to the AT-SPI walk so e.g.
1353        // `app.locator("button").first()` stops at the first match. With
1354        // multiple clauses, phase-1 hits for clause N might come before
1355        // clause M's in doc order, so we need the union before truncating.
1356        // (Critical on Electron-scale apps where this prevents 50k-node
1357        // walks.)
1358        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        // Bucket phase-1 hits by clause so each clause's tail can narrow
1381        // independently. `walk_pos` preserves the doc-order rank from the
1382        // single walk for the final merge.
1383        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        // For each clause, build ElementData for its phase-1 hits, then
1390        // narrow through any trailing segments. Single-segment clauses
1391        // skip phase 2 entirely.
1392        //
1393        // Each narrowed result keeps a (walk_pos, ElementData) pair: the
1394        // walk_pos of its phase-1 ancestor is the doc-order anchor we use
1395        // to merge across clauses at the end.
1396        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            // Build ElementData for this clause's phase-1 hits in parallel.
1403            let phase1_data: Vec<(usize, ElementData)> = hits
1404                .par_iter()
1405                .map(|(pos, aref)| {
1406                    // `root` is always present now, so the PID comes from
1407                    // the root element. No need to re-resolve via
1408                    // `get_app_pid` / `get_dbus_pid`.
1409                    (*pos, self.build_element_data(aref, pid_from_root))
1410                })
1411                .collect();
1412
1413            if clause.segments.len() == 1 {
1414                // Apply :nth on the first segment (per-clause, then merged).
1415                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            // Multi-segment narrowing: re-use the trait helper. Each
1430            // narrowed result is anchored at the phase-1 ancestor's
1431            // walk_pos so the final sort puts it in doc order against
1432            // other clauses.
1433            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        // Doc-order merge: stable sort by walk position. Within the same
1447        // walk position multiple clauses can have emitted the same node —
1448        // dedup by AT-SPI identity (`(bus_name, path)`) keeps the first.
1449        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            // Use the cached AccessibleRef for identity, not the (handle).
1454            // Handle is freshly minted per `build_element_data` call so it
1455            // would never collide here.
1456            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    /// Enumerate top-level applications by listing direct children of the
1481    /// AT-SPI registry root — every running accessibility-enabled app
1482    /// registers a child accessible there. Apps with empty names are
1483    /// filtered out (toolkits sometimes register transient/system
1484    /// accessibles before the real app appears). PID resolution uses the
1485    /// AT-SPI `Application` interface, falling back to the D-Bus owner.
1486    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(&registry)?;
1492
1493        // Filter valid children first, then build in parallel
1494        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        // Fast path: the widget exposes `press` on its own Action interface.
1523        if let Ok(index) = self.get_action_index(element.handle, "press") {
1524            return self.do_atspi_action_by_index(&target, index);
1525        }
1526        // TENET-BREAK(1): substitute target. Human approval granted for this
1527        // break (see batch B6 / PR #125 / commit daeaf59). Justification: GTK4
1528        // menu-button widgets (GtkMenuButton, AdwMenuButton, AdwSplitButton)
1529        // expose their AT-SPI Action interface on an *inner* toggle-button
1530        // child, not the outer push-button accessible the app author addresses
1531        // by name. Without this workaround, `press()` silently does nothing on
1532        // every GtkMenuButton in every stock GNOME app (Calculator, Text
1533        // Editor, Logs, …). Alternatives considered and rejected:
1534        //   1. Expose the inner widget in the tree — breaks AT-SPI tree
1535        //      fidelity and leaks a GTK implementation detail into every
1536        //      consumer.
1537        //   2. Return ActionNotSupported — every GTK consumer would have to
1538        //      reimplement the same subtree search to work around it.
1539        // The break is narrowly scoped: gated on (a) the owning toolkit being
1540        // GTK and (b) the outer role being Role::Button (push-button, which is
1541        // what all three menu-button variants present as). Non-GtkMenuButton
1542        // roles and non-GTK toolkits continue to fail-fast with
1543        // ActionNotSupported.
1544        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        // Try Component.GrabFocus first, then fall back to stored action index.
1559        // GrabFocus returns a boolean indicating success — we must check it.
1560        // Fixes GitHub issue #98.
1561        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                // GrabFocus returns boolean: true if focus was grabbed, false otherwise
1566                if let Ok(true) = reply.body().deserialize::<bool>() {
1567                    return Ok(());
1568                }
1569                // GrabFocus returned false — fall through to action index fallback
1570            }
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        // Grab focus on parent element to blur the current one. We propagate
1584        // every failure — no silent fallbacks (tenet 1): callers need to see
1585        // when blur can't do anything useful.
1586        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        // Fast path: the widget exposes the literal AT-SPI action name "toggle"
1610        // (or one of its toolkit aliases — "check" / "uncheck" — both
1611        // canonicalised to "toggle" by map_atspi_action_name during cache
1612        // population).
1613        if let Ok(index) = self.get_action_index(element.handle, "toggle") {
1614            return self.do_atspi_action_by_index(&target, index);
1615        }
1616        // Fallback for AccessKit-backed apps. accesskit_unix's AT-SPI bridge
1617        // hard-codes the action name as "click" for every clickable node
1618        // regardless of role — see platforms/atspi-common/src/node.rs in
1619        // AccessKit. That means egui, eframe, winit-based apps, Bevy, Tauri
1620        // (when using AccessKit) and any other AccessKit consumer never
1621        // advertise "toggle" for CheckBox/RadioButton/Switch, even though
1622        // activating those widgets via "click" is functionally a toggle on
1623        // every platform. Without this fallback, xa11y.toggle() is
1624        // unreachable on every AccessKit-on-Linux widget.
1625        //
1626        // This is tenet-3-consistent: the semantic verb `toggle` on a
1627        // toggleable role means "activate this toggleable element," and on
1628        // Linux the canonical AccessKit implementation of that is the same
1629        // action node entry we'd dispatch for press(). It's the mirror image
1630        // of the Windows `press` dispatch (uia.rs) which fans out to Invoke,
1631        // Toggle, SelectionItem.Select, or ExpandCollapse depending on the
1632        // element's primary-activation pattern.
1633        //
1634        // Narrowly scoped: only fires for toggleable primary-activation
1635        // roles. Other roles still fail-fast with ActionNotSupported so a
1636        // misuse of toggle() on, e.g., a Button does not silently dispatch
1637        // press().
1638        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        // Try stored AT-SPI2 action index first, fall back to Value interface
1699        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        // Try SetTextContents first (WebKit2GTK exposes this but not InsertText).
1763        if proxy.call_method("SetTextContents", &(value,)).is_ok() {
1764            return Ok(());
1765        }
1766        // Fall back to delete-then-insert for other AT-SPI2 implementations.
1767        // Capture the underlying D-Bus error so callers can distinguish an
1768        // absent `EditableText` interface (common on Chromium — the Chrome
1769        // URL bar only exposes read-only `Text`; see issue #101) from other
1770        // failures. Collapsing to `TextValueNotSupported` hides the reason.
1771        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        // Insert text via EditableText interface (accessibility API, not input simulation).
1805        // Get cursor position from Text interface, then insert at that position.
1806        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); // -1 = append at end
1812
1813        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
1876/// Whether a role typically has text or Value interface content.
1877/// Container/structural roles are skipped to save D-Bus round-trips.
1878fn 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
1895/// Whether a role typically supports actions via the Action interface.
1896/// Container and display-only roles are skipped to save D-Bus round-trips.
1897fn 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
1920/// Map AT-SPI2 role name to xa11y Role.
1921pub(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        // "textbox" is the ARIA role name returned by WebKit2GTK for both
1934        // <input type="text"> and <textarea>.  Map to TextArea here so the
1935        // multi-line refinement below can downgrade single-line ones to TextField.
1936        "text" | "textbox" => Role::TextArea,
1937        "label" | "static" | "caption" => Role::StaticText,
1938        "combo box" | "combobox" => Role::ComboBox,
1939        // "listbox" is the ARIA role name returned by WebKit2GTK for role="listbox".
1940        "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
1969/// Map AT-SPI2 numeric role (AtspiRole enum) to xa11y Role.
1970/// Values from atspi-common Role enum (repr(u32)).
1971pub(crate) fn map_atspi_role_number(role: u32) -> Role {
1972    match role {
1973        2 => Role::Alert,        // Alert
1974        7 => Role::CheckBox,     // CheckBox
1975        8 => Role::CheckBox,     // CheckMenuItem
1976        11 => Role::ComboBox,    // ComboBox
1977        16 => Role::Dialog,      // Dialog
1978        19 => Role::Dialog,      // FileChooser
1979        20 => Role::Group,       // Filler
1980        23 => Role::Window,      // Frame
1981        26 => Role::Image,       // Icon
1982        27 => Role::Image,       // Image
1983        29 => Role::StaticText,  // Label
1984        31 => Role::List,        // List
1985        32 => Role::ListItem,    // ListItem
1986        33 => Role::Menu,        // Menu
1987        34 => Role::MenuBar,     // MenuBar
1988        35 => Role::MenuItem,    // MenuItem
1989        37 => Role::Tab,         // PageTab
1990        38 => Role::TabGroup,    // PageTabList
1991        39 => Role::Group,       // Panel
1992        40 => Role::TextField,   // PasswordText
1993        42 => Role::ProgressBar, // ProgressBar
1994        43 => Role::Button,      // Button (push button)
1995        44 => Role::RadioButton, // RadioButton
1996        45 => Role::RadioButton, // RadioMenuItem
1997        48 => Role::ScrollBar,   // ScrollBar
1998        49 => Role::Group,       // ScrollPane
1999        50 => Role::Separator,   // Separator
2000        51 => Role::Slider,      // Slider
2001        52 => Role::SpinButton,  // SpinButton
2002        53 => Role::SplitGroup,  // SplitPane
2003        55 => Role::Table,       // Table
2004        56 => Role::TableCell,   // TableCell
2005        57 => Role::TableCell,   // TableColumnHeader
2006        58 => Role::TableCell,   // TableRowHeader
2007        61 => Role::TextArea,    // Text
2008        62 => Role::Switch,      // ToggleButton
2009        63 => Role::Toolbar,     // ToolBar
2010        65 => Role::Group,       // Tree
2011        66 => Role::Table,       // TreeTable
2012        67 => Role::Unknown,     // Unknown
2013        68 => Role::Group,       // Viewport
2014        69 => Role::Window,      // Window
2015        75 => Role::Application, // Application
2016        78 => Role::TextArea, // Embedded — WebKit2GTK uses this for <input type="text"> and <textarea>;
2017        // multi-line refinement below downgrades single-line ones to TextField
2018        79 => Role::TextField,   // Entry
2019        82 => Role::WebArea,     // DocumentFrame
2020        83 => Role::Heading,     // Heading
2021        85 => Role::Group,       // Section
2022        86 => Role::Group,       // RedundantObject
2023        87 => Role::Group,       // Form
2024        88 => Role::Link,        // Link
2025        90 => Role::TableRow,    // TableRow
2026        91 => Role::TreeItem,    // TreeItem
2027        95 => Role::WebArea,     // DocumentWeb
2028        97 => Role::List,        // WebKit2GTK uses this for <ul role="listbox">
2029        98 => Role::List,        // ListBox
2030        93 => Role::Tooltip,     // Tooltip
2031        101 => Role::Alert,      // Notification
2032        116 => Role::StaticText, // Static
2033        129 => Role::Button,     // PushButtonMenu
2034        _ => xa11y_core::unknown_role(&format!("AT-SPI role number {role}")),
2035    }
2036}
2037
2038/// Depth cap for the GTK press-fallback BFS. Wrapper patterns nest at most
2039/// two levels (e.g. `AdwSplitButton` → inner toggle-button → inner label);
2040/// depth 3 covers them with headroom without letting the walk wander.
2041const GTK_FALLBACK_MAX_DEPTH: u32 = 3;
2042
2043/// Hard cap on visited accessibles per fallback resolution. Defensive — the
2044/// depth cap already bounds typical cases to ≤ 20 nodes.
2045const GTK_FALLBACK_MAX_NODES: usize = 200;
2046
2047/// Whether an AT-SPI2 role name represents an activatable widget we are
2048/// willing to invoke via the fallback path. Deliberately narrow: roles that
2049/// could carry destructive or misleading semantics (e.g. `label` with the
2050/// synthesised clipboard/selection actions) are excluded.
2051fn 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
2069/// Roles the BFS refuses to descend into. Static and decorative roles never
2070/// lead anywhere useful, and `label` in particular carries a fan-out of
2071/// text-editing actions (`clipboard.copy`, `selection.delete`, …) that we
2072/// must never reach via a press heuristic.
2073fn is_never_descend_atspi_role(role: &str) -> bool {
2074    matches!(
2075        role,
2076        "label" | "separator" | "image" | "icon" | "static" | "caption"
2077    )
2078}
2079
2080/// Map an AT-SPI2 action name to its canonical `snake_case` xa11y action name.
2081///
2082/// Toolkit-specific aliases are normalised to the single canonical name:
2083///   "click" / "activate" / "press" / "invoke" / "dodefault" → "press"
2084///   "toggle" / "check" / "uncheck"            → "toggle"
2085///   "expand" / "open"                          → "expand"
2086///   "collapse" / "close"                       → "collapse"
2087///   "menu" / "showmenu" / "showcontextmenu" / "popup" / "show menu" → "show_menu"
2088///   "select"                                    → "select"
2089///   "increment"                                 → "increment"
2090///   "decrement"                                 → "decrement"
2091///
2092/// Returns `None` for unrecognised names.
2093fn map_atspi_action_name(action_name: &str) -> Option<String> {
2094    // Normalise by lowercasing and stripping underscores/spaces so that
2095    // "show_menu", "show menu", "showMenu" and "showContextMenu" all collapse
2096    // to the same canonical form. Chromium is the main motivator: it uses
2097    // `doDefault` as the default activation action on ~190 elements per
2098    // window (Back/Forward buttons, toolbar icons, menu items, sliders,
2099    // notifications) and `showContextMenu` as the context-menu action. The
2100    // previous table dropped both, leaving those elements with no `press`
2101    // mapping at all. See issue #101.
2102    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        // ToggleButton (62) must map to Switch, not Button.
2141        // GTK4's Gtk.Switch and Gtk.ToggleButton both report numeric role 62.
2142        assert_eq!(map_atspi_role_number(62), Role::Switch);
2143        // Sanity-check a few well-established numeric mappings.
2144        assert_eq!(map_atspi_role_number(43), Role::Button); // PushButton
2145        assert_eq!(map_atspi_role_number(7), Role::CheckBox);
2146        assert_eq!(map_atspi_role_number(67), Role::Unknown); // AT-SPI Unknown
2147    }
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        // Chromium uses `doDefault` for default activation on ~190 elements.
2156        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        // Chrome / Chromium expose the URL-bar context-menu action as
2189        // `showContextMenu`; the previous table missed both spellings.
2190        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    /// All known AT-SPI2 aliases map to one of the well-known action names,
2210    /// and re-mapping the canonical name produces the same canonical name.
2211    #[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            // Re-mapping the canonical name must produce itself.
2242            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    /// Case-insensitive mapping works.
2253    #[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    /// The GTK press-fallback's actionable-role set must include the inner
2264    /// toggle-button pattern used by `GtkMenuButton` / `AdwMenuButton`, plus
2265    /// the other standard activatable roles we're willing to synthesise a
2266    /// click for.
2267    #[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    /// Never treat static / decorative accessibles as fallback candidates.
2288    /// Particularly important for `label`, whose synthesised text-editing
2289    /// actions (`clipboard.copy`, `selection.delete`) must never be invoked
2290    /// by a press heuristic.
2291    #[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    /// The BFS stops at static/decorative roles. `label` in particular must
2313    /// never be descended into — its children are text spans with bogus
2314    /// actions.
2315    #[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        // Containers — panel / filler / section / group / frame — stay
2324        // walkable so the BFS can reach a wrapped inner actionable.
2325        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}