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    /// Fetch an accessible's AT-SPI2 state bitfield as a single `u64`.
825    ///
826    /// AT-SPI2 returns states as two `u32`s (low/high words); collapse them
827    /// into one mask so callers can test bit positions directly.
828    fn state_bits(&self, aref: &AccessibleRef) -> u64 {
829        let state_bits = self.get_state(aref).unwrap_or_default();
830        if state_bits.len() >= 2 {
831            (state_bits[0] as u64) | ((state_bits[1] as u64) << 32)
832        } else if state_bits.len() == 1 {
833            state_bits[0] as u64
834        } else {
835            0
836        }
837    }
838
839    /// Parse AT-SPI2 state bitfield into xa11y StateSet.
840    fn parse_states(&self, aref: &AccessibleRef, role: Role) -> StateSet {
841        let bits = self.state_bits(aref);
842
843        // AT-SPI2 state bit positions (AtspiStateType enum values)
844        const BUSY: u64 = 1 << 3;
845        const CHECKED: u64 = 1 << 4;
846        const EDITABLE: u64 = 1 << 7;
847        const ENABLED: u64 = 1 << 8;
848        const EXPANDABLE: u64 = 1 << 9;
849        const EXPANDED: u64 = 1 << 10;
850        const FOCUSABLE: u64 = 1 << 11;
851        const FOCUSED: u64 = 1 << 12;
852        const MODAL: u64 = 1 << 16;
853        const SELECTED: u64 = 1 << 23;
854        const SENSITIVE: u64 = 1 << 24;
855        const SHOWING: u64 = 1 << 25;
856        const VISIBLE: u64 = 1 << 30;
857        const INDETERMINATE: u64 = 1 << 32;
858        const REQUIRED: u64 = 1 << 33;
859
860        let enabled = (bits & ENABLED) != 0 || (bits & SENSITIVE) != 0;
861        let visible = (bits & VISIBLE) != 0 || (bits & SHOWING) != 0;
862
863        let checked = match role {
864            Role::CheckBox | Role::RadioButton | Role::MenuItem | Role::Switch => {
865                if (bits & INDETERMINATE) != 0 {
866                    Some(Toggled::Mixed)
867                } else if (bits & CHECKED) != 0 {
868                    Some(Toggled::On)
869                } else {
870                    Some(Toggled::Off)
871                }
872            }
873            _ => None,
874        };
875
876        let expanded = if (bits & EXPANDABLE) != 0 {
877            Some((bits & EXPANDED) != 0)
878        } else {
879            None
880        };
881
882        StateSet {
883            enabled,
884            visible,
885            focused: (bits & FOCUSED) != 0,
886            checked,
887            selected: (bits & SELECTED) != 0,
888            expanded,
889            editable: (bits & EDITABLE) != 0,
890            focusable: (bits & FOCUSABLE) != 0,
891            modal: (bits & MODAL) != 0,
892            required: (bits & REQUIRED) != 0,
893            busy: (bits & BUSY) != 0,
894        }
895    }
896
897    /// Find an application by PID.
898    ///
899    /// Used by `subscribe` to resolve the target app's D-Bus sender name so
900    /// signal match rules can be scoped to it.
901    pub(crate) fn find_app_by_pid(&self, pid: u32) -> Result<AccessibleRef> {
902        let registry = AccessibleRef {
903            bus_name: "org.a11y.atspi.Registry".to_string(),
904            path: "/org/a11y/atspi/accessible/root".to_string(),
905        };
906        let children = self.get_atspi_children(&registry)?;
907
908        for child in &children {
909            if child.path == "/org/a11y/atspi/null" {
910                continue;
911            }
912            // Prefer D-Bus connection PID — it's authoritative for the
913            // process owning the bus connection. Application.Id is *not* a
914            // process pid: AT-SPI assigns it as a registry-local index
915            // (1, 2, 3, …) for some bridges (notably GTK4), so matching
916            // against Application.Id alone misses real processes.
917            if let Some(app_pid) = self.get_dbus_pid(&child.bus_name) {
918                if app_pid == pid {
919                    return Ok(child.clone());
920                }
921            }
922            // Fall back to Application.Id for adapters that do set it to pid.
923            if let Ok(proxy) =
924                self.make_proxy(&child.bus_name, &child.path, "org.a11y.atspi.Application")
925            {
926                if let Ok(app_pid) = proxy.get_property::<i32>("Id") {
927                    if app_pid as u32 == pid {
928                        return Ok(child.clone());
929                    }
930                }
931            }
932        }
933
934        Err(Error::Platform {
935            code: -1,
936            message: format!("No application found with PID {}", pid),
937        })
938    }
939
940    /// Get PID via D-Bus GetConnectionUnixProcessID.
941    fn get_dbus_pid(&self, bus_name: &str) -> Option<u32> {
942        let proxy = self
943            .make_proxy(
944                "org.freedesktop.DBus",
945                "/org/freedesktop/DBus",
946                "org.freedesktop.DBus",
947            )
948            .ok()?;
949        let reply = proxy
950            .call_method("GetConnectionUnixProcessID", &(bus_name,))
951            .ok()?;
952        let pid: u32 = reply.body().deserialize().ok()?;
953        if pid > 0 {
954            Some(pid)
955        } else {
956            None
957        }
958    }
959
960    /// Perform an AT-SPI2 action by its integer index (from discovery).
961    fn do_atspi_action_by_index(&self, aref: &AccessibleRef, index: i32) -> Result<()> {
962        let proxy = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Action")?;
963        proxy
964            .call_method("DoAction", &(index,))
965            .map_err(|e| Error::Platform {
966                code: -1,
967                message: format!("DoAction({}) failed: {}", index, e),
968            })?;
969        Ok(())
970    }
971
972    /// Look up the stored AT-SPI2 action index for the given element and action.
973    fn get_action_index(&self, handle: u64, action: &str) -> Result<i32> {
974        self.action_indices
975            .lock()
976            .unwrap_or_else(|e| e.into_inner())
977            .get(&handle)
978            .and_then(|map| map.get(action).copied())
979            .ok_or_else(|| Error::ActionNotSupported {
980                action: action.to_string(),
981                role: Role::Unknown, // caller will provide better context
982            })
983    }
984
985    /// Get the process PID for an AT-SPI accessible. Prefers the D-Bus
986    /// connection PID over `Application.Id`: the latter is a registry-local
987    /// index (1, 2, 3, …) on some bridges (e.g. GTK4), not a real pid, so
988    /// reading it first produces apps whose `pid` property doesn't match the
989    /// process the user launched.
990    fn get_app_pid(&self, aref: &AccessibleRef) -> Option<u32> {
991        if let Some(pid) = self.get_dbus_pid(&aref.bus_name) {
992            return Some(pid);
993        }
994
995        // Fall back to Application.Id for adapters that set it to pid.
996        // Require that a process with that id actually exists — a registry
997        // index from a misbehaving bridge usually names a long-dead or absurd
998        // pid. This is only a cheap sanity filter: a low index can still
999        // collide with a real process (1 = init), which is why the D-Bus
1000        // connection pid above is authoritative whenever available.
1001        if let Ok(proxy) = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Application")
1002        {
1003            if let Ok(pid) = proxy.get_property::<i32>("Id") {
1004                if pid > 0 && std::path::Path::new(&format!("/proc/{pid}")).exists() {
1005                    return Some(pid as u32);
1006                }
1007            }
1008        }
1009
1010        None
1011    }
1012
1013    /// Resolve the mapped Role for an accessible ref (1-3 D-Bus calls).
1014    fn resolve_role(&self, aref: &AccessibleRef) -> Role {
1015        let role_name = self.get_role_name(aref).unwrap_or_default();
1016        let by_name = if !role_name.is_empty() {
1017            map_atspi_role(&role_name)
1018        } else {
1019            Role::Unknown
1020        };
1021        let coarse = if by_name != Role::Unknown {
1022            by_name
1023        } else {
1024            // Unmapped or missing role name — fall back to numeric role.
1025            let role_num = self.get_role_number(aref).unwrap_or(0);
1026            map_atspi_role_number(role_num)
1027        };
1028        self.refine_text_role(coarse, aref)
1029    }
1030
1031    /// Check if an accessible ref matches a simple selector, fetching only the
1032    /// attributes the selector actually requires.
1033    ///
1034    /// Filter routing (cheapest first):
1035    ///   * `role` / `name` / `value` / `description` — single targeted D-Bus
1036    ///     call against this accessible.
1037    ///   * Normalized state attrs (`enabled`, `checked`, `focused`, …) —
1038    ///     one shared `GetState` call, cached for the rest of this match.
1039    ///   * Anything else (custom `raw` keys, `bounds`, numeric values) — fall
1040    ///     through to building a full `ElementData` and delegating to
1041    ///     [`xa11y_core::selector::matches_simple`]. This is slower but keeps
1042    ///     selectors with rare attribute filters semantically equivalent to
1043    ///     the default tree-traversal path.
1044    fn matches_ref(
1045        &self,
1046        aref: &AccessibleRef,
1047        simple: &xa11y_core::selector::SimpleSelector,
1048    ) -> bool {
1049        // Resolve role only if the selector needs it (for either the role
1050        // segment or any role/checked filter — checked depends on role).
1051        let needs_role = simple.role.is_some()
1052            || simple
1053                .filters
1054                .iter()
1055                .any(|f| matches!(f.attr.as_str(), "role" | "checked"));
1056        let role = if needs_role {
1057            Some(self.resolve_role(aref))
1058        } else {
1059            None
1060        };
1061
1062        if let Some(ref role_match) = simple.role {
1063            match role_match {
1064                xa11y_core::selector::RoleMatch::Normalized(expected) => {
1065                    if role != Some(*expected) {
1066                        return false;
1067                    }
1068                }
1069                xa11y_core::selector::RoleMatch::Platform(platform_role) => {
1070                    let raw_role = self.get_role_name(aref).unwrap_or_default();
1071                    if raw_role != *platform_role {
1072                        return false;
1073                    }
1074                }
1075            }
1076        }
1077
1078        let mut state_set: Option<StateSet> = None;
1079
1080        for filter in &simple.filters {
1081            let attr = filter.attr.as_str();
1082            let resolved: Option<Option<String>> = match attr {
1083                "role" => Some(role.map(|r| r.to_snake_case().to_string())),
1084                "name" => {
1085                    let name = self.get_name(aref).ok().filter(|s| !s.is_empty());
1086                    // Mirror build_element_data: StaticText carries its name
1087                    // in the Text interface's Value when Name is empty.
1088                    let resolved = if name.is_none() && role == Some(Role::StaticText) {
1089                        self.get_value(aref)
1090                    } else {
1091                        name
1092                    };
1093                    Some(resolved)
1094                }
1095                "value" => Some(self.get_value(aref)),
1096                "description" => Some(self.get_description(aref).ok().filter(|s| !s.is_empty())),
1097                "enabled" | "visible" | "focused" | "focusable" | "selected" | "editable"
1098                | "modal" | "required" | "busy" | "expanded" | "checked" => {
1099                    let s = state_set.get_or_insert_with(|| {
1100                        // `parse_states` reads `checked` based on role; pass
1101                        // whatever we already resolved (Unknown is a no-op for
1102                        // the role-gated `checked` mapping).
1103                        self.parse_states(aref, role.unwrap_or(Role::Unknown))
1104                    });
1105                    Some(state_attr_to_string(attr, s))
1106                }
1107                _ => None, // Routed through full ElementData below.
1108            };
1109
1110            match resolved {
1111                Some(value) => {
1112                    if !xa11y_core::selector::match_op(&filter.op, &filter.value, value.as_deref())
1113                    {
1114                        return false;
1115                    }
1116                }
1117                None => {
1118                    // Filter targets an attribute the fast path doesn't know
1119                    // (e.g. `bounds`, `numeric_value`, a custom `raw` key).
1120                    // Build the full ElementData once and let the shared
1121                    // matcher handle every remaining filter — it dispatches
1122                    // to `ElementData` fields and the `raw` map identically
1123                    // to the default tree-traversal path.
1124                    let pid = None; // pid isn't selector-addressable
1125                    let data = self.build_element_data(aref, pid);
1126                    return xa11y_core::selector::matches_simple(&data, simple);
1127                }
1128            }
1129        }
1130
1131        true
1132    }
1133
1134    /// ONE DFS over the subtree, evaluating each clause's first SimpleSelector
1135    /// against every visited node. Emits `(clause_idx, AccessibleRef)` pairs
1136    /// in document order; a node that matches multiple clauses is emitted
1137    /// once per matching clause (the merge step in `find_elements_group`
1138    /// collapses these by `(bus_name, path)` identity).
1139    ///
1140    /// This is the "push-down to the platform query per group" core: a
1141    /// selector group like `button, text_field` traverses the AT-SPI tree
1142    /// exactly once regardless of clause count, instead of N separate walks.
1143    fn collect_matching_refs_group(
1144        &self,
1145        parent: &AccessibleRef,
1146        clauses: &[&xa11y_core::selector::SimpleSelector],
1147        depth: u32,
1148        max_depth: u32,
1149        limit: Option<usize>,
1150    ) -> Result<Vec<(usize, AccessibleRef)>> {
1151        if depth > max_depth {
1152            return Ok(vec![]);
1153        }
1154
1155        let children = self.get_atspi_children(parent)?;
1156
1157        // Filter invalid refs. Application-node flattening (collapsing a
1158        // redundant `application` accessible into its grandchildren) is only
1159        // valid when the parent is itself an application — i.e. we have already
1160        // descended past the registry. At the registry root, the children *are*
1161        // the applications and must not be collapsed, otherwise selectors like
1162        // `application` (used by `App::list` / `App::by_name`) match nothing
1163        // because the app accessibles get dissolved into their windows.
1164        let parent_is_registry = parent.bus_name == "org.a11y.atspi.Registry";
1165        let mut to_search: Vec<AccessibleRef> = Vec::new();
1166        for child in children {
1167            if child.path == "/org/a11y/atspi/null"
1168                || child.bus_name.is_empty()
1169                || child.path.is_empty()
1170            {
1171                continue;
1172            }
1173
1174            if !parent_is_registry {
1175                let child_role = self.get_role_name(&child).unwrap_or_default();
1176                if child_role == "application" {
1177                    let grandchildren = self.get_atspi_children(&child).unwrap_or_default();
1178                    for gc in grandchildren {
1179                        if gc.path == "/org/a11y/atspi/null"
1180                            || gc.bus_name.is_empty()
1181                            || gc.path.is_empty()
1182                        {
1183                            continue;
1184                        }
1185                        let gc_role = self.get_role_name(&gc).unwrap_or_default();
1186                        if gc_role == "application" {
1187                            continue;
1188                        }
1189                        to_search.push(gc);
1190                    }
1191                    continue;
1192                }
1193            }
1194            to_search.push(child);
1195        }
1196
1197        // Detect Chromium/Electron's empty-tree signature whenever we
1198        // descend into a parent and find no real children.
1199        if to_search.is_empty() {
1200            self.check_chromium_a11y_enabled(parent, None)?;
1201        }
1202
1203        // Process each child subtree in parallel: check match against every
1204        // clause + recurse. Tagging each match with `clause_idx` lets the
1205        // caller route phase-2 narrowing to the right clause without
1206        // re-running the first-segment match.
1207        //
1208        // We deliberately swallow transient sibling errors here — a single
1209        // flaky D-Bus call on one child shouldn't fail the whole locator
1210        // query (the rest of this file is similarly tolerant via
1211        // `unwrap_or_default()`). But `AccessibilityNotEnabled` is *not* a
1212        // transient error: it's the signal that a Chromium renderer bridge
1213        // isn't initialised, and callers need to see it. So we propagate
1214        // that variant specifically and keep tolerating everything else.
1215        // Per-child batches: matches collected during that child's subtree
1216        // walk, plus the first AccessibilityNotEnabled error (if any).
1217        type ChildBatch = (Vec<(usize, AccessibleRef)>, Option<Error>);
1218        let per_child: Vec<ChildBatch> = to_search
1219            .par_iter()
1220            .map(|child| {
1221                let mut child_results: Vec<(usize, AccessibleRef)> = Vec::new();
1222                for (idx, simple) in clauses.iter().enumerate() {
1223                    if self.matches_ref(child, simple) {
1224                        child_results.push((idx, child.clone()));
1225                    }
1226                }
1227                match self.collect_matching_refs_group(child, clauses, depth + 1, max_depth, limit)
1228                {
1229                    Ok(sub) => {
1230                        child_results.extend(sub);
1231                        (child_results, None)
1232                    }
1233                    Err(e @ Error::AccessibilityNotEnabled { .. }) => (Vec::new(), Some(e)),
1234                    Err(_) => (child_results, None),
1235                }
1236            })
1237            .collect();
1238
1239        // Merge results, respecting limit. The first AccessibilityNotEnabled
1240        // error seen wins — any child subtree raising it means the whole
1241        // query is untrustworthy, so surface it rather than return partial
1242        // data.
1243        //
1244        // Note: `limit` is the *caller's* outer limit; for a multi-clause
1245        // group it must not be applied per-clause (a low-priority clause's
1246        // hit could come before a high-priority clause's in doc order, so
1247        // truncating mid-walk would drop legitimate matches). Callers pass
1248        // `None` for multi-clause queries and apply the limit after the
1249        // cross-clause merge.
1250        let mut results = Vec::new();
1251        for (batch, maybe_err) in per_child {
1252            if let Some(err) = maybe_err {
1253                return Err(err);
1254            }
1255            for r in batch {
1256                results.push(r);
1257                if let Some(limit) = limit {
1258                    if results.len() >= limit {
1259                        return Ok(results);
1260                    }
1261                }
1262            }
1263        }
1264        Ok(results)
1265    }
1266}
1267
1268impl Provider for LinuxProvider {
1269    fn get_children(&self, element: Option<&ElementData>) -> Result<Vec<ElementData>> {
1270        match element {
1271            None => {
1272                // Top-level: delegate to `list_apps()`, the canonical
1273                // discovery primitive.
1274                self.list_apps()
1275            }
1276            Some(element_data) => {
1277                let aref = self.get_cached(element_data.handle)?;
1278                let children = self.get_atspi_children(&aref).unwrap_or_default();
1279                let pid = element_data.pid;
1280
1281                // Pre-filter invalid refs and flatten nested application nodes,
1282                // collecting the concrete refs to build in parallel.
1283                let mut to_build: Vec<AccessibleRef> = Vec::new();
1284                for child_ref in &children {
1285                    if child_ref.path == "/org/a11y/atspi/null"
1286                        || child_ref.bus_name.is_empty()
1287                        || child_ref.path.is_empty()
1288                    {
1289                        continue;
1290                    }
1291                    let child_role = self.get_role_name(child_ref).unwrap_or_default();
1292                    if child_role == "application" {
1293                        let grandchildren = self.get_atspi_children(child_ref).unwrap_or_default();
1294                        for gc_ref in grandchildren {
1295                            if gc_ref.path == "/org/a11y/atspi/null"
1296                                || gc_ref.bus_name.is_empty()
1297                                || gc_ref.path.is_empty()
1298                            {
1299                                continue;
1300                            }
1301                            let gc_role = self.get_role_name(&gc_ref).unwrap_or_default();
1302                            if gc_role == "application" {
1303                                continue;
1304                            }
1305                            to_build.push(gc_ref);
1306                        }
1307                        continue;
1308                    }
1309                    to_build.push(child_ref.clone());
1310                }
1311
1312                if to_build.is_empty() {
1313                    self.check_chromium_a11y_enabled(&aref, Some(element_data.role))?;
1314                }
1315
1316                let results: Vec<ElementData> = to_build
1317                    .par_iter()
1318                    .map(|r| self.build_element_data(r, pid))
1319                    .collect();
1320
1321                Ok(results)
1322            }
1323        }
1324    }
1325
1326    fn find_elements_group(
1327        &self,
1328        root: &ElementData,
1329        group: &xa11y_core::selector::SelectorGroup,
1330        limit: Option<usize>,
1331        max_depth: Option<u32>,
1332    ) -> Result<Vec<ElementData>> {
1333        if group.clauses.is_empty() {
1334            return Ok(vec![]);
1335        }
1336        // Reject any clause with zero segments early — `clause.segments[0]`
1337        // below would otherwise panic.
1338        if group.clauses.iter().any(|c| c.segments.is_empty()) {
1339            return Ok(vec![]);
1340        }
1341
1342        // ONE AT-SPI walk that evaluates every clause's first SimpleSelector
1343        // against each visited node, then per-clause phase-2 narrowing on
1344        // the small candidate sets that fall out. Dedup uses
1345        // `(bus_name, path)` — the only AT-SPI identifier that's stable
1346        // across the per-clause narrowings (handles are minted fresh on
1347        // each `build_element_data` call).
1348        //
1349        // App discovery is handled separately by `list_apps()` — `root` is
1350        // always present here.
1351        let max_depth_val = max_depth.unwrap_or(xa11y_core::MAX_TREE_DEPTH);
1352
1353        let firsts: Vec<&xa11y_core::selector::SimpleSelector> = group
1354            .clauses
1355            .iter()
1356            .map(|c| &c.segments[0].simple)
1357            .collect();
1358
1359        let start_ref = self.get_cached(root.handle)?;
1360
1361        // ── Phase-1 limit short-circuit ───────────────────────────
1362        // When there's exactly one clause, propagate the user's `limit`
1363        // (adjusted for `:nth`) to the AT-SPI walk so e.g.
1364        // `app.locator("button").first()` stops at the first match. With
1365        // multiple clauses, phase-1 hits for clause N might come before
1366        // clause M's in doc order, so we need the union before truncating.
1367        // (Critical on Electron-scale apps where this prevents 50k-node
1368        // walks.)
1369        let phase1_limit = if group.clauses.len() == 1 {
1370            let clause = &group.clauses[0];
1371            let first = firsts[0];
1372            let outer = if clause.segments.len() == 1 {
1373                limit
1374            } else {
1375                None
1376            };
1377            match (outer, first.nth) {
1378                (Some(l), Some(n)) => Some(l.max(n)),
1379                (_, Some(n)) => Some(n),
1380                (l, None) => l,
1381            }
1382        } else {
1383            None
1384        };
1385
1386        let phase1: Vec<(usize, AccessibleRef)> =
1387            self.collect_matching_refs_group(&start_ref, &firsts, 0, max_depth_val, phase1_limit)?;
1388
1389        let pid_from_root = root.pid;
1390
1391        // Bucket phase-1 hits by clause so each clause's tail can narrow
1392        // independently. `walk_pos` preserves the doc-order rank from the
1393        // single walk for the final merge.
1394        let mut by_clause: Vec<Vec<(usize, AccessibleRef)>> =
1395            (0..group.clauses.len()).map(|_| Vec::new()).collect();
1396        for (walk_pos, (clause_idx, aref)) in phase1.into_iter().enumerate() {
1397            by_clause[clause_idx].push((walk_pos, aref));
1398        }
1399
1400        // For each clause, build ElementData for its phase-1 hits, then
1401        // narrow through any trailing segments. Single-segment clauses
1402        // skip phase 2 entirely.
1403        //
1404        // Each narrowed result keeps a (walk_pos, ElementData) pair: the
1405        // walk_pos of its phase-1 ancestor is the doc-order anchor we use
1406        // to merge across clauses at the end.
1407        let mut merged: Vec<(usize, ElementData)> = Vec::new();
1408        for (clause_idx, hits) in by_clause.into_iter().enumerate() {
1409            if hits.is_empty() {
1410                continue;
1411            }
1412            let clause = &group.clauses[clause_idx];
1413            // Build ElementData for this clause's phase-1 hits in parallel.
1414            let phase1_data: Vec<(usize, ElementData)> = hits
1415                .par_iter()
1416                .map(|(pos, aref)| {
1417                    // `root` is always present now, so the PID comes from
1418                    // the root element. No need to re-resolve via
1419                    // `get_app_pid` / `get_dbus_pid`.
1420                    (*pos, self.build_element_data(aref, pid_from_root))
1421                })
1422                .collect();
1423
1424            if clause.segments.len() == 1 {
1425                // Apply :nth on the first segment (per-clause, then merged).
1426                let mut candidates = phase1_data;
1427                if let Some(nth) = clause.segments[0].simple.nth {
1428                    if nth <= candidates.len() {
1429                        let kept = candidates.remove(nth - 1);
1430                        candidates.clear();
1431                        candidates.push(kept);
1432                    } else {
1433                        candidates.clear();
1434                    }
1435                }
1436                merged.extend(candidates);
1437                continue;
1438            }
1439
1440            // Multi-segment narrowing: re-use the trait helper. Each
1441            // narrowed result is anchored at the phase-1 ancestor's
1442            // walk_pos so the final sort puts it in doc order against
1443            // other clauses.
1444            for (anchor_pos, head) in phase1_data {
1445                let narrowed = self.narrow_multi_segment(
1446                    vec![head],
1447                    &clause.segments[1..],
1448                    max_depth_val,
1449                    None,
1450                )?;
1451                for n in narrowed {
1452                    merged.push((anchor_pos, n));
1453                }
1454            }
1455        }
1456
1457        // Doc-order merge: stable sort by walk position. Within the same
1458        // walk position multiple clauses can have emitted the same node —
1459        // dedup by AT-SPI identity (`(bus_name, path)`) keeps the first.
1460        merged.sort_by_key(|(pos, _)| *pos);
1461        let mut seen: HashSet<(String, String)> = HashSet::new();
1462        let mut out: Vec<ElementData> = Vec::with_capacity(merged.len());
1463        for (_, data) in merged {
1464            // Use the cached AccessibleRef for identity, not the (handle).
1465            // Handle is freshly minted per `build_element_data` call so it
1466            // would never collide here.
1467            if let Ok(aref) = self.get_cached(data.handle) {
1468                if !seen.insert((aref.bus_name.clone(), aref.path.clone())) {
1469                    continue;
1470                }
1471            }
1472            out.push(data);
1473        }
1474        if let Some(l) = limit {
1475            out.truncate(l);
1476        }
1477        Ok(out)
1478    }
1479
1480    fn get_parent(&self, element: &ElementData) -> Result<Option<ElementData>> {
1481        let aref = self.get_cached(element.handle)?;
1482        match self.get_atspi_parent(&aref)? {
1483            Some(parent_ref) => {
1484                let data = self.build_element_data(&parent_ref, element.pid);
1485                Ok(Some(data))
1486            }
1487            None => Ok(None),
1488        }
1489    }
1490
1491    /// Enumerate top-level applications by listing direct children of the
1492    /// AT-SPI registry root — every running accessibility-enabled app
1493    /// registers a child accessible there. Apps with empty names are
1494    /// filtered out (toolkits sometimes register transient/system
1495    /// accessibles before the real app appears). PID resolution uses the
1496    /// AT-SPI `Application` interface, falling back to the D-Bus owner.
1497    fn list_apps(&self) -> Result<Vec<ElementData>> {
1498        let registry = AccessibleRef {
1499            bus_name: "org.a11y.atspi.Registry".to_string(),
1500            path: "/org/a11y/atspi/accessible/root".to_string(),
1501        };
1502        let children = self.get_atspi_children(&registry)?;
1503
1504        // Filter valid children first, then build in parallel
1505        let valid: Vec<(&AccessibleRef, String)> = children
1506            .iter()
1507            .filter(|c| c.path != "/org/a11y/atspi/null")
1508            .filter_map(|c| {
1509                let name = self.get_name(c).unwrap_or_default();
1510                if name.is_empty() {
1511                    None
1512                } else {
1513                    Some((c, name))
1514                }
1515            })
1516            .collect();
1517
1518        let results: Vec<ElementData> = valid
1519            .par_iter()
1520            .map(|(child, app_name)| {
1521                let pid = self.get_app_pid(child);
1522                let mut data = self.build_element_data(child, pid);
1523                data.name = Some(app_name.clone());
1524                data
1525            })
1526            .collect();
1527
1528        Ok(results)
1529    }
1530
1531    /// Find an application by pid directly against the AT-SPI registry.
1532    ///
1533    /// Differs from filtering `list_apps()` in two ways that matter for a
1534    /// freshly launched process:
1535    ///
1536    /// * No empty-name filter — toolkits can register on the bus before the
1537    ///   app name is set, and a pid match is precise enough on its own.
1538    /// * The not-matched error reports how many registry entries were
1539    ///   examined and how many had no resolvable pid (the misreported-pid
1540    ///   bridge quirk `get_app_pid` documents), so a timeout on CI says why
1541    ///   the app was invisible instead of just "not found".
1542    fn app_by_pid(&self, pid: u32) -> Result<ElementData> {
1543        let registry = AccessibleRef {
1544            bus_name: "org.a11y.atspi.Registry".to_string(),
1545            path: "/org/a11y/atspi/accessible/root".to_string(),
1546        };
1547        let children = self.get_atspi_children(&registry)?;
1548
1549        let mut total = 0usize;
1550        let mut unresolved = 0usize;
1551        for child in children.iter().filter(|c| c.path != "/org/a11y/atspi/null") {
1552            total += 1;
1553            match self.get_app_pid(child) {
1554                Some(p) if p == pid => {
1555                    let mut data = self.build_element_data(child, Some(p));
1556                    // Mirror list_apps: prefer the registry-reported name.
1557                    let name = self.get_name(child).unwrap_or_default();
1558                    if !name.is_empty() {
1559                        data.name = Some(name);
1560                    }
1561                    return Ok(data);
1562                }
1563                Some(_) => {}
1564                None => unresolved += 1,
1565            }
1566        }
1567        Err(
1568            Error::selector_not_matched(format!("application[pid={pid}]")).diagnose(
1569                xa11y_core::Diagnosis {
1570                    last_observed: Some(format!(
1571                        "{total} AT-SPI registry entries examined, {unresolved} without a \
1572                         resolvable pid"
1573                    )),
1574                    ..Default::default()
1575                },
1576            ),
1577        )
1578    }
1579
1580    /// Identify the foreground application via the active top-level window.
1581    ///
1582    /// AT-SPI has no registry-level "focused application" call, and the
1583    /// `Application` accessibles themselves don't carry an active/focused
1584    /// state across toolkits. The portable signal is the `ACTIVE` state
1585    /// (`AtspiStateType::ACTIVE`) set on the foreground *window* (frame): we
1586    /// enumerate each registered application's top-level children and return
1587    /// the first application that owns a window reporting `ACTIVE`.
1588    ///
1589    /// Returns [`Error::SelectorNotMatched`] when no window is active (no app
1590    /// has the foreground — e.g. focus is on the shell or a non-AT-SPI
1591    /// surface). The core reads that as "nothing focused", not a failure.
1592    fn focused_app(&self) -> Result<ElementData> {
1593        // AtspiStateType::ACTIVE = 1 → bit position 1.
1594        const ACTIVE: u64 = 1 << 1;
1595
1596        let registry = AccessibleRef {
1597            bus_name: "org.a11y.atspi.Registry".to_string(),
1598            path: "/org/a11y/atspi/accessible/root".to_string(),
1599        };
1600        let apps = self.get_atspi_children(&registry)?;
1601
1602        for app in apps.iter().filter(|c| c.path != "/org/a11y/atspi/null") {
1603            let windows = match self.get_atspi_children(app) {
1604                Ok(w) => w,
1605                // A single app failing to enumerate its windows shouldn't abort
1606                // the whole foreground probe — skip it and keep scanning.
1607                Err(_) => continue,
1608            };
1609            let has_active_window = windows
1610                .iter()
1611                .filter(|w| w.path != "/org/a11y/atspi/null")
1612                .any(|w| self.state_bits(w) & ACTIVE != 0);
1613            if has_active_window {
1614                let pid = self.get_app_pid(app);
1615                let mut data = self.build_element_data(app, pid);
1616                let name = self.get_name(app).unwrap_or_default();
1617                if !name.is_empty() {
1618                    data.name = Some(name);
1619                }
1620                return Ok(data);
1621            }
1622        }
1623
1624        Err(Error::selector_not_matched("focused application"))
1625    }
1626
1627    fn press(&self, element: &ElementData) -> Result<()> {
1628        let target = self.get_cached(element.handle)?;
1629        // Fast path: the widget exposes `press` on its own Action interface.
1630        if let Ok(index) = self.get_action_index(element.handle, "press") {
1631            return self.do_atspi_action_by_index(&target, index);
1632        }
1633        // TENET-BREAK(1): substitute target. Human approval granted for this
1634        // break (see batch B6 / PR #125 / commit daeaf59). Justification: GTK4
1635        // menu-button widgets (GtkMenuButton, AdwMenuButton, AdwSplitButton)
1636        // expose their AT-SPI Action interface on an *inner* toggle-button
1637        // child, not the outer push-button accessible the app author addresses
1638        // by name. Without this workaround, `press()` silently does nothing on
1639        // every GtkMenuButton in every stock GNOME app (Calculator, Text
1640        // Editor, Logs, …). Alternatives considered and rejected:
1641        //   1. Expose the inner widget in the tree — breaks AT-SPI tree
1642        //      fidelity and leaks a GTK implementation detail into every
1643        //      consumer.
1644        //   2. Return ActionNotSupported — every GTK consumer would have to
1645        //      reimplement the same subtree search to work around it.
1646        // The break is narrowly scoped: gated on (a) the owning toolkit being
1647        // GTK and (b) the outer role being Role::Button (push-button, which is
1648        // what all three menu-button variants present as). Non-GtkMenuButton
1649        // roles and non-GTK toolkits continue to fail-fast with
1650        // ActionNotSupported.
1651        if element.role == Role::Button && self.is_gtk_toolkit(&target) {
1652            let outer_name = self.get_name(&target).unwrap_or_default();
1653            if let Some((inner, index)) = self.find_gtk_press_fallback(&target, &outer_name) {
1654                return self.do_atspi_action_by_index(&inner, index);
1655            }
1656        }
1657        Err(Error::ActionNotSupported {
1658            action: "press".to_string(),
1659            role: element.role,
1660        })
1661    }
1662
1663    fn focus(&self, element: &ElementData) -> Result<()> {
1664        let target = self.get_cached(element.handle)?;
1665        // Try Component.GrabFocus first, then fall back to stored action index.
1666        // GrabFocus returns a boolean indicating success — we must check it.
1667        // Fixes GitHub issue #98.
1668        if let Ok(proxy) =
1669            self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Component")
1670        {
1671            if let Ok(reply) = proxy.call_method("GrabFocus", &()) {
1672                // GrabFocus returns boolean: true if focus was grabbed, false otherwise
1673                if let Ok(true) = reply.body().deserialize::<bool>() {
1674                    return Ok(());
1675                }
1676                // GrabFocus returned false — fall through to action index fallback
1677            }
1678        }
1679        if let Ok(index) = self.get_action_index(element.handle, "focus") {
1680            return self.do_atspi_action_by_index(&target, index);
1681        }
1682        Err(Error::ActionNotSupported {
1683            action: "focus".to_string(),
1684            role: element.role,
1685        })
1686    }
1687
1688    fn blur(&self, element: &ElementData) -> Result<()> {
1689        let target = self.get_cached(element.handle)?;
1690        // Grab focus on parent element to blur the current one. We propagate
1691        // every failure — no silent fallbacks (tenet 1): callers need to see
1692        // when blur can't do anything useful.
1693        if let Some(parent_ref) = self.get_atspi_parent(&target)? {
1694            if parent_ref.path != "/org/a11y/atspi/null" {
1695                let p = self.make_proxy(
1696                    &parent_ref.bus_name,
1697                    &parent_ref.path,
1698                    "org.a11y.atspi.Component",
1699                )?;
1700                p.call_method("GrabFocus", &())
1701                    .map_err(|e| Error::Platform {
1702                        code: -1,
1703                        message: format!("Component.GrabFocus on parent failed: {}", e),
1704                    })?;
1705                return Ok(());
1706            }
1707        }
1708        Err(Error::ActionNotSupported {
1709            action: "blur".to_string(),
1710            role: element.role,
1711        })
1712    }
1713
1714    fn toggle(&self, element: &ElementData) -> Result<()> {
1715        let target = self.get_cached(element.handle)?;
1716        // Fast path: the widget exposes the literal AT-SPI action name "toggle"
1717        // (or one of its toolkit aliases — "check" / "uncheck" — both
1718        // canonicalised to "toggle" by map_atspi_action_name during cache
1719        // population).
1720        if let Ok(index) = self.get_action_index(element.handle, "toggle") {
1721            return self.do_atspi_action_by_index(&target, index);
1722        }
1723        // Fallback for AccessKit-backed apps. accesskit_unix's AT-SPI bridge
1724        // hard-codes the action name as "click" for every clickable node
1725        // regardless of role — see platforms/atspi-common/src/node.rs in
1726        // AccessKit. That means egui, eframe, winit-based apps, Bevy, Tauri
1727        // (when using AccessKit) and any other AccessKit consumer never
1728        // advertise "toggle" for CheckBox/RadioButton/Switch, even though
1729        // activating those widgets via "click" is functionally a toggle on
1730        // every platform. Without this fallback, xa11y.toggle() is
1731        // unreachable on every AccessKit-on-Linux widget.
1732        //
1733        // This is tenet-3-consistent: the semantic verb `toggle` on a
1734        // toggleable role means "activate this toggleable element," and on
1735        // Linux the canonical AccessKit implementation of that is the same
1736        // action node entry we'd dispatch for press(). It's the mirror image
1737        // of the Windows `press` dispatch (uia.rs) which fans out to Invoke,
1738        // Toggle, SelectionItem.Select, or ExpandCollapse depending on the
1739        // element's primary-activation pattern.
1740        //
1741        // Narrowly scoped: only fires for toggleable primary-activation
1742        // roles. Other roles still fail-fast with ActionNotSupported so a
1743        // misuse of toggle() on, e.g., a Button does not silently dispatch
1744        // press().
1745        if matches!(
1746            element.role,
1747            Role::CheckBox | Role::RadioButton | Role::Switch
1748        ) {
1749            if let Ok(index) = self.get_action_index(element.handle, "press") {
1750                return self.do_atspi_action_by_index(&target, index);
1751            }
1752        }
1753        Err(Error::ActionNotSupported {
1754            action: "toggle".to_string(),
1755            role: element.role,
1756        })
1757    }
1758
1759    fn select(&self, element: &ElementData) -> Result<()> {
1760        let target = self.get_cached(element.handle)?;
1761        let index = self
1762            .get_action_index(element.handle, "select")
1763            .map_err(|_| Error::ActionNotSupported {
1764                action: "select".to_string(),
1765                role: element.role,
1766            })?;
1767        self.do_atspi_action_by_index(&target, index)
1768    }
1769
1770    fn expand(&self, element: &ElementData) -> Result<()> {
1771        let target = self.get_cached(element.handle)?;
1772        let index = self
1773            .get_action_index(element.handle, "expand")
1774            .map_err(|_| Error::ActionNotSupported {
1775                action: "expand".to_string(),
1776                role: element.role,
1777            })?;
1778        self.do_atspi_action_by_index(&target, index)
1779    }
1780
1781    fn collapse(&self, element: &ElementData) -> Result<()> {
1782        let target = self.get_cached(element.handle)?;
1783        let index = self
1784            .get_action_index(element.handle, "collapse")
1785            .map_err(|_| Error::ActionNotSupported {
1786                action: "collapse".to_string(),
1787                role: element.role,
1788            })?;
1789        self.do_atspi_action_by_index(&target, index)
1790    }
1791
1792    fn show_menu(&self, element: &ElementData) -> Result<()> {
1793        let target = self.get_cached(element.handle)?;
1794        let index = self
1795            .get_action_index(element.handle, "show_menu")
1796            .map_err(|_| Error::ActionNotSupported {
1797                action: "show_menu".to_string(),
1798                role: element.role,
1799            })?;
1800        self.do_atspi_action_by_index(&target, index)
1801    }
1802
1803    fn increment(&self, element: &ElementData) -> Result<()> {
1804        let target = self.get_cached(element.handle)?;
1805        // Try stored AT-SPI2 action index first, fall back to Value interface
1806        if let Ok(index) = self.get_action_index(element.handle, "increment") {
1807            return self.do_atspi_action_by_index(&target, index);
1808        }
1809        let proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Value")?;
1810        let current: f64 = proxy
1811            .get_property("CurrentValue")
1812            .map_err(|e| Error::Platform {
1813                code: -1,
1814                message: format!("Value.CurrentValue failed: {}", e),
1815            })?;
1816        let step: f64 = proxy.get_property("MinimumIncrement").unwrap_or(1.0);
1817        let step = if step <= 0.0 { 1.0 } else { step };
1818        proxy
1819            .set_property("CurrentValue", current + step)
1820            .map_err(|e| Error::Platform {
1821                code: -1,
1822                message: format!("Value.SetCurrentValue failed: {}", e),
1823            })
1824    }
1825
1826    fn decrement(&self, element: &ElementData) -> Result<()> {
1827        let target = self.get_cached(element.handle)?;
1828        if let Ok(index) = self.get_action_index(element.handle, "decrement") {
1829            return self.do_atspi_action_by_index(&target, index);
1830        }
1831        let proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Value")?;
1832        let current: f64 = proxy
1833            .get_property("CurrentValue")
1834            .map_err(|e| Error::Platform {
1835                code: -1,
1836                message: format!("Value.CurrentValue failed: {}", e),
1837            })?;
1838        let step: f64 = proxy.get_property("MinimumIncrement").unwrap_or(1.0);
1839        let step = if step <= 0.0 { 1.0 } else { step };
1840        proxy
1841            .set_property("CurrentValue", current - step)
1842            .map_err(|e| Error::Platform {
1843                code: -1,
1844                message: format!("Value.SetCurrentValue failed: {}", e),
1845            })
1846    }
1847
1848    fn scroll_into_view(&self, element: &ElementData) -> Result<()> {
1849        let target = self.get_cached(element.handle)?;
1850        let proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Component")?;
1851        proxy
1852            .call_method("ScrollTo", &(0u32,))
1853            .map_err(|e| Error::Platform {
1854                code: -1,
1855                message: format!("ScrollTo failed: {}", e),
1856            })?;
1857        Ok(())
1858    }
1859
1860    fn set_value(&self, element: &ElementData, value: &str) -> Result<()> {
1861        let target = self.get_cached(element.handle)?;
1862        let proxy = self
1863            .make_proxy(
1864                &target.bus_name,
1865                &target.path,
1866                "org.a11y.atspi.EditableText",
1867            )
1868            .map_err(|_| Error::TextValueNotSupported)?;
1869        // Try SetTextContents first (WebKit2GTK exposes this but not InsertText).
1870        if proxy.call_method("SetTextContents", &(value,)).is_ok() {
1871            return Ok(());
1872        }
1873        // Fall back to delete-then-insert for other AT-SPI2 implementations.
1874        // Capture the underlying D-Bus error so callers can distinguish an
1875        // absent `EditableText` interface (common on Chromium — the Chrome
1876        // URL bar only exposes read-only `Text`; see issue #101) from other
1877        // failures. Collapsing to `TextValueNotSupported` hides the reason.
1878        let classify_editable_text_error = |op: &str, e: zbus::Error| -> Error {
1879            let msg = e.to_string();
1880            if msg.contains("UnknownMethod") || msg.contains("UnknownInterface") {
1881                Error::TextValueNotSupported
1882            } else {
1883                Error::Platform {
1884                    code: -1,
1885                    message: format!("EditableText.{} failed: {}", op, msg),
1886                }
1887            }
1888        };
1889        if let Err(e) = proxy.call_method("DeleteText", &(0i32, i32::MAX)) {
1890            return Err(classify_editable_text_error("DeleteText", e));
1891        }
1892        if let Err(e) = proxy.call_method("InsertText", &(0i32, value, value.len() as i32)) {
1893            return Err(classify_editable_text_error("InsertText", e));
1894        }
1895        Ok(())
1896    }
1897
1898    fn set_numeric_value(&self, element: &ElementData, value: f64) -> Result<()> {
1899        let target = self.get_cached(element.handle)?;
1900        let proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Value")?;
1901        proxy
1902            .set_property("CurrentValue", value)
1903            .map_err(|e| Error::Platform {
1904                code: -1,
1905                message: format!("SetValue failed: {}", e),
1906            })
1907    }
1908
1909    fn type_text(&self, element: &ElementData, text: &str) -> Result<()> {
1910        let target = self.get_cached(element.handle)?;
1911        // Insert text via EditableText interface (accessibility API, not input simulation).
1912        // Get cursor position from Text interface, then insert at that position.
1913        let text_proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Text");
1914        let insert_pos = text_proxy
1915            .as_ref()
1916            .ok()
1917            .and_then(|p| p.get_property::<i32>("CaretOffset").ok())
1918            .unwrap_or(-1); // -1 = append at end
1919
1920        let proxy = self
1921            .make_proxy(
1922                &target.bus_name,
1923                &target.path,
1924                "org.a11y.atspi.EditableText",
1925            )
1926            .map_err(|_| Error::TextValueNotSupported)?;
1927        let pos = if insert_pos >= 0 {
1928            insert_pos
1929        } else {
1930            i32::MAX
1931        };
1932        proxy
1933            .call_method("InsertText", &(pos, text, text.len() as i32))
1934            .map_err(|e| Error::Platform {
1935                code: -1,
1936                message: format!("EditableText.InsertText failed: {}", e),
1937            })?;
1938        Ok(())
1939    }
1940
1941    fn set_text_selection(&self, element: &ElementData, start: u32, end: u32) -> Result<()> {
1942        let target = self.get_cached(element.handle)?;
1943        let proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Text")?;
1944        proxy
1945            .call_method("SetSelection", &(0i32, start as i32, end as i32))
1946            .map_err(|e| Error::Platform {
1947                code: -1,
1948                message: format!("Text.SetSelection failed: {}", e),
1949            })?;
1950        Ok(())
1951    }
1952
1953    fn perform_action(&self, element: &ElementData, action: &str) -> Result<()> {
1954        match action {
1955            "press" => self.press(element),
1956            "focus" => self.focus(element),
1957            "blur" => self.blur(element),
1958            "toggle" => self.toggle(element),
1959            "select" => self.select(element),
1960            "expand" => self.expand(element),
1961            "collapse" => self.collapse(element),
1962            "show_menu" => self.show_menu(element),
1963            "increment" => self.increment(element),
1964            "decrement" => self.decrement(element),
1965            "scroll_into_view" => self.scroll_into_view(element),
1966            _ => Err(Error::ActionNotSupported {
1967                action: action.to_string(),
1968                role: element.role,
1969            }),
1970        }
1971    }
1972
1973    fn subscribe(&self, element: &ElementData) -> Result<Subscription> {
1974        let pid = element.pid.ok_or(Error::Platform {
1975            code: -1,
1976            message: "Element has no PID for subscribe".to_string(),
1977        })?;
1978        let app_name = element.name.clone().unwrap_or_default();
1979        crate::events::subscribe_for_pid(self, pid, app_name)
1980    }
1981}
1982
1983/// Whether a role typically has text or Value interface content.
1984/// Container/structural roles are skipped to save D-Bus round-trips.
1985fn role_has_value(role: Role) -> bool {
1986    !matches!(
1987        role,
1988        Role::Application
1989            | Role::Window
1990            | Role::Dialog
1991            | Role::Group
1992            | Role::MenuBar
1993            | Role::Toolbar
1994            | Role::TabGroup
1995            | Role::SplitGroup
1996            | Role::Table
1997            | Role::TableRow
1998            | Role::Separator
1999    )
2000}
2001
2002/// Whether a role typically supports actions via the Action interface.
2003/// Container and display-only roles are skipped to save D-Bus round-trips.
2004fn role_has_actions(role: Role) -> bool {
2005    matches!(
2006        role,
2007        Role::Button
2008            | Role::CheckBox
2009            | Role::RadioButton
2010            | Role::MenuItem
2011            | Role::Link
2012            | Role::ComboBox
2013            | Role::TextField
2014            | Role::TextArea
2015            | Role::SpinButton
2016            | Role::Tab
2017            | Role::TreeItem
2018            | Role::ListItem
2019            | Role::ScrollBar
2020            | Role::Slider
2021            | Role::Menu
2022            | Role::Image
2023            | Role::Unknown
2024    )
2025}
2026
2027/// Map AT-SPI2 role name to xa11y Role.
2028pub(crate) fn map_atspi_role(role_name: &str) -> Role {
2029    match role_name.to_lowercase().as_str() {
2030        "application" => Role::Application,
2031        "window" | "frame" => Role::Window,
2032        "dialog" | "file chooser" => Role::Dialog,
2033        "alert" | "notification" => Role::Alert,
2034        "push button" | "push button menu" => Role::Button,
2035        "toggle button" => Role::Switch,
2036        "check box" | "check menu item" => Role::CheckBox,
2037        "radio button" | "radio menu item" => Role::RadioButton,
2038        "entry" | "password text" => Role::TextField,
2039        "spin button" | "spinbutton" => Role::SpinButton,
2040        // "textbox" is the ARIA role name returned by WebKit2GTK for both
2041        // <input type="text"> and <textarea>.  Map to TextArea here so the
2042        // multi-line refinement below can downgrade single-line ones to TextField.
2043        "text" | "textbox" => Role::TextArea,
2044        "label" | "static" | "caption" => Role::StaticText,
2045        "combo box" | "combobox" => Role::ComboBox,
2046        // "listbox" is the ARIA role name returned by WebKit2GTK for role="listbox".
2047        "list" | "list box" | "listbox" => Role::List,
2048        "list item" => Role::ListItem,
2049        "menu" => Role::Menu,
2050        "menu item" | "tearoff menu item" => Role::MenuItem,
2051        "menu bar" => Role::MenuBar,
2052        "page tab" => Role::Tab,
2053        "page tab list" => Role::TabGroup,
2054        "table" | "tree table" => Role::Table,
2055        "table row" => Role::TableRow,
2056        "table cell" | "table column header" | "table row header" => Role::TableCell,
2057        "tool bar" => Role::Toolbar,
2058        "scroll bar" => Role::ScrollBar,
2059        "slider" => Role::Slider,
2060        "image" | "icon" | "desktop icon" => Role::Image,
2061        "link" => Role::Link,
2062        "panel" | "section" | "form" | "filler" | "viewport" | "scroll pane" => Role::Group,
2063        "progress bar" => Role::ProgressBar,
2064        "tree item" => Role::TreeItem,
2065        "document web" | "document frame" => Role::WebArea,
2066        "heading" => Role::Heading,
2067        "separator" => Role::Separator,
2068        "split pane" => Role::SplitGroup,
2069        "tooltip" | "tool tip" => Role::Tooltip,
2070        "status bar" | "statusbar" => Role::Status,
2071        "landmark" | "navigation" => Role::Navigation,
2072        _ => xa11y_core::unknown_role(role_name),
2073    }
2074}
2075
2076/// Map AT-SPI2 numeric role (AtspiRole enum) to xa11y Role.
2077/// Values from atspi-common Role enum (repr(u32)).
2078pub(crate) fn map_atspi_role_number(role: u32) -> Role {
2079    match role {
2080        2 => Role::Alert,        // Alert
2081        7 => Role::CheckBox,     // CheckBox
2082        8 => Role::CheckBox,     // CheckMenuItem
2083        11 => Role::ComboBox,    // ComboBox
2084        16 => Role::Dialog,      // Dialog
2085        19 => Role::Dialog,      // FileChooser
2086        20 => Role::Group,       // Filler
2087        23 => Role::Window,      // Frame
2088        26 => Role::Image,       // Icon
2089        27 => Role::Image,       // Image
2090        29 => Role::StaticText,  // Label
2091        31 => Role::List,        // List
2092        32 => Role::ListItem,    // ListItem
2093        33 => Role::Menu,        // Menu
2094        34 => Role::MenuBar,     // MenuBar
2095        35 => Role::MenuItem,    // MenuItem
2096        37 => Role::Tab,         // PageTab
2097        38 => Role::TabGroup,    // PageTabList
2098        39 => Role::Group,       // Panel
2099        40 => Role::TextField,   // PasswordText
2100        42 => Role::ProgressBar, // ProgressBar
2101        43 => Role::Button,      // Button (push button)
2102        44 => Role::RadioButton, // RadioButton
2103        45 => Role::RadioButton, // RadioMenuItem
2104        48 => Role::ScrollBar,   // ScrollBar
2105        49 => Role::Group,       // ScrollPane
2106        50 => Role::Separator,   // Separator
2107        51 => Role::Slider,      // Slider
2108        52 => Role::SpinButton,  // SpinButton
2109        53 => Role::SplitGroup,  // SplitPane
2110        55 => Role::Table,       // Table
2111        56 => Role::TableCell,   // TableCell
2112        57 => Role::TableCell,   // TableColumnHeader
2113        58 => Role::TableCell,   // TableRowHeader
2114        61 => Role::TextArea,    // Text
2115        62 => Role::Switch,      // ToggleButton
2116        63 => Role::Toolbar,     // ToolBar
2117        65 => Role::Group,       // Tree
2118        66 => Role::Table,       // TreeTable
2119        67 => Role::Unknown,     // Unknown
2120        68 => Role::Group,       // Viewport
2121        69 => Role::Window,      // Window
2122        75 => Role::Application, // Application
2123        78 => Role::TextArea, // Embedded — WebKit2GTK uses this for <input type="text"> and <textarea>;
2124        // multi-line refinement below downgrades single-line ones to TextField
2125        79 => Role::TextField,   // Entry
2126        82 => Role::WebArea,     // DocumentFrame
2127        83 => Role::Heading,     // Heading
2128        85 => Role::Group,       // Section
2129        86 => Role::Group,       // RedundantObject
2130        87 => Role::Group,       // Form
2131        88 => Role::Link,        // Link
2132        90 => Role::TableRow,    // TableRow
2133        91 => Role::TreeItem,    // TreeItem
2134        95 => Role::WebArea,     // DocumentWeb
2135        97 => Role::List,        // WebKit2GTK uses this for <ul role="listbox">
2136        98 => Role::List,        // ListBox
2137        93 => Role::Tooltip,     // Tooltip
2138        101 => Role::Alert,      // Notification
2139        116 => Role::StaticText, // Static
2140        129 => Role::Button,     // PushButtonMenu
2141        _ => xa11y_core::unknown_role(&format!("AT-SPI role number {role}")),
2142    }
2143}
2144
2145/// Depth cap for the GTK press-fallback BFS. Wrapper patterns nest at most
2146/// two levels (e.g. `AdwSplitButton` → inner toggle-button → inner label);
2147/// depth 3 covers them with headroom without letting the walk wander.
2148const GTK_FALLBACK_MAX_DEPTH: u32 = 3;
2149
2150/// Hard cap on visited accessibles per fallback resolution. Defensive — the
2151/// depth cap already bounds typical cases to ≤ 20 nodes.
2152const GTK_FALLBACK_MAX_NODES: usize = 200;
2153
2154/// Whether an AT-SPI2 role name represents an activatable widget we are
2155/// willing to invoke via the fallback path. Deliberately narrow: roles that
2156/// could carry destructive or misleading semantics (e.g. `label` with the
2157/// synthesised clipboard/selection actions) are excluded.
2158fn is_actionable_atspi_role(role: &str) -> bool {
2159    matches!(
2160        role,
2161        "push button"
2162            | "toggle button"
2163            | "check box"
2164            | "radio button"
2165            | "menu item"
2166            | "check menu item"
2167            | "radio menu item"
2168            | "link"
2169            | "page tab"
2170            | "tab"
2171            | "list item"
2172            | "tree item"
2173    )
2174}
2175
2176/// Roles the BFS refuses to descend into. Static and decorative roles never
2177/// lead anywhere useful, and `label` in particular carries a fan-out of
2178/// text-editing actions (`clipboard.copy`, `selection.delete`, …) that we
2179/// must never reach via a press heuristic.
2180fn is_never_descend_atspi_role(role: &str) -> bool {
2181    matches!(
2182        role,
2183        "label" | "separator" | "image" | "icon" | "static" | "caption"
2184    )
2185}
2186
2187/// Map an AT-SPI2 action name to its canonical `snake_case` xa11y action name.
2188///
2189/// Toolkit-specific aliases are normalised to the single canonical name:
2190///   "click" / "activate" / "press" / "invoke" / "dodefault" → "press"
2191///   "toggle" / "check" / "uncheck"            → "toggle"
2192///   "expand" / "open"                          → "expand"
2193///   "collapse" / "close"                       → "collapse"
2194///   "menu" / "showmenu" / "showcontextmenu" / "popup" / "show menu" → "show_menu"
2195///   "select"                                    → "select"
2196///   "increment"                                 → "increment"
2197///   "decrement"                                 → "decrement"
2198///
2199/// Returns `None` for unrecognised names.
2200fn map_atspi_action_name(action_name: &str) -> Option<String> {
2201    // Normalise by lowercasing and stripping underscores/spaces so that
2202    // "show_menu", "show menu", "showMenu" and "showContextMenu" all collapse
2203    // to the same canonical form. Chromium is the main motivator: it uses
2204    // `doDefault` as the default activation action on ~190 elements per
2205    // window (Back/Forward buttons, toolbar icons, menu items, sliders,
2206    // notifications) and `showContextMenu` as the context-menu action. The
2207    // previous table dropped both, leaving those elements with no `press`
2208    // mapping at all. See issue #101.
2209    let lower = action_name.to_lowercase();
2210    let collapsed: String = lower.chars().filter(|c| !matches!(c, '_' | ' ')).collect();
2211    let canonical = match collapsed.as_str() {
2212        "click" | "activate" | "press" | "invoke" | "dodefault" => "press",
2213        "toggle" | "check" | "uncheck" => "toggle",
2214        "expand" | "open" => "expand",
2215        "collapse" | "close" => "collapse",
2216        "select" => "select",
2217        "menu" | "showmenu" | "showcontextmenu" | "contextmenu" | "popup" => "show_menu",
2218        "increment" => "increment",
2219        "decrement" => "decrement",
2220        _ => return None,
2221    };
2222    Some(canonical.to_string())
2223}
2224
2225#[cfg(test)]
2226mod tests {
2227    use super::*;
2228
2229    #[test]
2230    fn test_role_mapping() {
2231        assert_eq!(map_atspi_role("push button"), Role::Button);
2232        assert_eq!(map_atspi_role("toggle button"), Role::Switch);
2233        assert_eq!(map_atspi_role("check box"), Role::CheckBox);
2234        assert_eq!(map_atspi_role("entry"), Role::TextField);
2235        assert_eq!(map_atspi_role("label"), Role::StaticText);
2236        assert_eq!(map_atspi_role("window"), Role::Window);
2237        assert_eq!(map_atspi_role("frame"), Role::Window);
2238        assert_eq!(map_atspi_role("dialog"), Role::Dialog);
2239        assert_eq!(map_atspi_role("combo box"), Role::ComboBox);
2240        assert_eq!(map_atspi_role("slider"), Role::Slider);
2241        assert_eq!(map_atspi_role("panel"), Role::Group);
2242        assert_eq!(map_atspi_role("unknown_thing"), Role::Unknown);
2243    }
2244
2245    #[test]
2246    fn test_numeric_role_mapping() {
2247        // ToggleButton (62) must map to Switch, not Button.
2248        // GTK4's Gtk.Switch and Gtk.ToggleButton both report numeric role 62.
2249        assert_eq!(map_atspi_role_number(62), Role::Switch);
2250        // Sanity-check a few well-established numeric mappings.
2251        assert_eq!(map_atspi_role_number(43), Role::Button); // PushButton
2252        assert_eq!(map_atspi_role_number(7), Role::CheckBox);
2253        assert_eq!(map_atspi_role_number(67), Role::Unknown); // AT-SPI Unknown
2254    }
2255
2256    #[test]
2257    fn test_action_name_mapping() {
2258        assert_eq!(map_atspi_action_name("click"), Some("press".to_string()));
2259        assert_eq!(map_atspi_action_name("activate"), Some("press".to_string()));
2260        assert_eq!(map_atspi_action_name("press"), Some("press".to_string()));
2261        assert_eq!(map_atspi_action_name("invoke"), Some("press".to_string()));
2262        // Chromium uses `doDefault` for default activation on ~190 elements.
2263        assert_eq!(
2264            map_atspi_action_name("doDefault"),
2265            Some("press".to_string())
2266        );
2267        assert_eq!(
2268            map_atspi_action_name("do_default"),
2269            Some("press".to_string())
2270        );
2271        assert_eq!(map_atspi_action_name("toggle"), Some("toggle".to_string()));
2272        assert_eq!(map_atspi_action_name("check"), Some("toggle".to_string()));
2273        assert_eq!(map_atspi_action_name("uncheck"), Some("toggle".to_string()));
2274        assert_eq!(map_atspi_action_name("expand"), Some("expand".to_string()));
2275        assert_eq!(map_atspi_action_name("open"), Some("expand".to_string()));
2276        assert_eq!(
2277            map_atspi_action_name("collapse"),
2278            Some("collapse".to_string())
2279        );
2280        assert_eq!(map_atspi_action_name("close"), Some("collapse".to_string()));
2281        assert_eq!(map_atspi_action_name("select"), Some("select".to_string()));
2282        assert_eq!(map_atspi_action_name("menu"), Some("show_menu".to_string()));
2283        assert_eq!(
2284            map_atspi_action_name("showmenu"),
2285            Some("show_menu".to_string())
2286        );
2287        assert_eq!(
2288            map_atspi_action_name("popup"),
2289            Some("show_menu".to_string())
2290        );
2291        assert_eq!(
2292            map_atspi_action_name("show menu"),
2293            Some("show_menu".to_string())
2294        );
2295        // Chrome / Chromium expose the URL-bar context-menu action as
2296        // `showContextMenu`; the previous table missed both spellings.
2297        assert_eq!(
2298            map_atspi_action_name("showContextMenu"),
2299            Some("show_menu".to_string())
2300        );
2301        assert_eq!(
2302            map_atspi_action_name("show_context_menu"),
2303            Some("show_menu".to_string())
2304        );
2305        assert_eq!(
2306            map_atspi_action_name("increment"),
2307            Some("increment".to_string())
2308        );
2309        assert_eq!(
2310            map_atspi_action_name("decrement"),
2311            Some("decrement".to_string())
2312        );
2313        assert_eq!(map_atspi_action_name("foobar"), None);
2314    }
2315
2316    /// All known AT-SPI2 aliases map to one of the well-known action names,
2317    /// and re-mapping the canonical name produces the same canonical name.
2318    #[test]
2319    fn test_action_name_aliases_roundtrip() {
2320        let atspi_names = [
2321            "click",
2322            "activate",
2323            "press",
2324            "invoke",
2325            "doDefault",
2326            "do_default",
2327            "toggle",
2328            "check",
2329            "uncheck",
2330            "expand",
2331            "open",
2332            "collapse",
2333            "close",
2334            "select",
2335            "menu",
2336            "showmenu",
2337            "showContextMenu",
2338            "show_context_menu",
2339            "popup",
2340            "show menu",
2341            "increment",
2342            "decrement",
2343        ];
2344        for name in atspi_names {
2345            let canonical = map_atspi_action_name(name).unwrap_or_else(|| {
2346                panic!("AT-SPI2 name {:?} should map to a canonical name", name)
2347            });
2348            // Re-mapping the canonical name must produce itself.
2349            let back = map_atspi_action_name(&canonical)
2350                .unwrap_or_else(|| panic!("canonical {:?} should map back to itself", canonical));
2351            assert_eq!(
2352                canonical, back,
2353                "AT-SPI2 {:?} -> {:?} -> {:?} (expected {:?})",
2354                name, canonical, back, canonical
2355            );
2356        }
2357    }
2358
2359    /// Case-insensitive mapping works.
2360    #[test]
2361    fn test_action_name_case_insensitive() {
2362        assert_eq!(map_atspi_action_name("Click"), Some("press".to_string()));
2363        assert_eq!(map_atspi_action_name("TOGGLE"), Some("toggle".to_string()));
2364        assert_eq!(
2365            map_atspi_action_name("Increment"),
2366            Some("increment".to_string())
2367        );
2368    }
2369
2370    /// The GTK press-fallback's actionable-role set must include the inner
2371    /// toggle-button pattern used by `GtkMenuButton` / `AdwMenuButton`, plus
2372    /// the other standard activatable roles we're willing to synthesise a
2373    /// click for.
2374    #[test]
2375    fn test_gtk_fallback_actionable_roles() {
2376        for role in [
2377            "push button",
2378            "toggle button",
2379            "check box",
2380            "radio button",
2381            "menu item",
2382            "link",
2383            "tab",
2384            "list item",
2385            "tree item",
2386        ] {
2387            assert!(
2388                is_actionable_atspi_role(role),
2389                "{role:?} should be actionable"
2390            );
2391        }
2392    }
2393
2394    /// Never treat static / decorative accessibles as fallback candidates.
2395    /// Particularly important for `label`, whose synthesised text-editing
2396    /// actions (`clipboard.copy`, `selection.delete`) must never be invoked
2397    /// by a press heuristic.
2398    #[test]
2399    fn test_gtk_fallback_non_actionable_roles() {
2400        for role in [
2401            "label",
2402            "panel",
2403            "filler",
2404            "section",
2405            "group",
2406            "image",
2407            "separator",
2408            "static",
2409            "frame",
2410            "window",
2411        ] {
2412            assert!(
2413                !is_actionable_atspi_role(role),
2414                "{role:?} must not be treated as actionable"
2415            );
2416        }
2417    }
2418
2419    /// The BFS stops at static/decorative roles. `label` in particular must
2420    /// never be descended into — its children are text spans with bogus
2421    /// actions.
2422    #[test]
2423    fn test_gtk_fallback_never_descend_roles() {
2424        for role in ["label", "separator", "image", "icon", "static", "caption"] {
2425            assert!(
2426                is_never_descend_atspi_role(role),
2427                "{role:?} must block BFS descent"
2428            );
2429        }
2430        // Containers — panel / filler / section / group / frame — stay
2431        // walkable so the BFS can reach a wrapped inner actionable.
2432        for role in ["panel", "filler", "section", "group", "frame"] {
2433            assert!(
2434                !is_never_descend_atspi_role(role),
2435                "container role {role:?} must remain descendable"
2436            );
2437        }
2438    }
2439}