Skip to main content

xa11y_linux/
atspi.rs

1//! Real AT-SPI2 backend implementation using zbus D-Bus bindings.
2
3use std::collections::{HashMap, HashSet, VecDeque};
4use std::sync::atomic::{AtomicU64, Ordering};
5use std::sync::Mutex;
6
7use rayon::prelude::*;
8use xa11y_core::{
9    ElementData, Error, Provider, Rect, Result, Role, StateSet, Subscription, Toggled,
10};
11use zbus::blocking::{Connection, Proxy};
12
13/// Global handle counter for mapping ElementData back to AccessibleRefs.
14static NEXT_HANDLE: AtomicU64 = AtomicU64::new(1);
15
16/// Format a normalized state attribute as the same string `xa11y_core::selector::resolve_attr`
17/// would produce, so fast-path matching agrees byte-for-byte with the slow path.
18fn state_attr_to_string(name: &str, s: &StateSet) -> Option<String> {
19    match name {
20        "enabled" => Some(s.enabled.to_string()),
21        "visible" => Some(s.visible.to_string()),
22        "focused" => Some(s.focused.to_string()),
23        "focusable" => Some(s.focusable.to_string()),
24        "selected" => Some(s.selected.to_string()),
25        "editable" => Some(s.editable.to_string()),
26        "modal" => Some(s.modal.to_string()),
27        "required" => Some(s.required.to_string()),
28        "busy" => Some(s.busy.to_string()),
29        "expanded" => s.expanded.map(|b| b.to_string()),
30        "checked" => s.checked.map(|c| {
31            match c {
32                Toggled::On => "on",
33                Toggled::Off => "off",
34                Toggled::Mixed => "mixed",
35            }
36            .to_string()
37        }),
38        _ => None,
39    }
40}
41
42/// Linux accessibility provider using AT-SPI2 over D-Bus.
43pub struct LinuxProvider {
44    a11y_bus: Connection,
45    /// Cached AT-SPI accessible refs keyed by handle ID.
46    handle_cache: Mutex<HashMap<u64, AccessibleRef>>,
47    /// Cached AT-SPI2 action indices keyed by element handle.
48    /// Maps each action name (snake_case) to the integer index used by `DoAction(i)`.
49    action_indices: Mutex<HashMap<u64, HashMap<String, i32>>>,
50}
51
52/// AT-SPI2 accessible reference: (bus_name, object_path).
53#[derive(Debug, Clone)]
54pub(crate) struct AccessibleRef {
55    pub(crate) bus_name: String,
56    pub(crate) path: String,
57}
58
59impl LinuxProvider {
60    /// Create a new Linux accessibility provider.
61    ///
62    /// Connects to the AT-SPI2 bus. Falls back to the session bus
63    /// if the dedicated AT-SPI bus is unavailable.
64    pub fn new() -> Result<Self> {
65        let a11y_bus = Self::connect_a11y_bus()?;
66        Ok(Self {
67            a11y_bus,
68            handle_cache: Mutex::new(HashMap::new()),
69            action_indices: Mutex::new(HashMap::new()),
70        })
71    }
72
73    pub(crate) fn connect_a11y_bus() -> Result<Connection> {
74        // Try getting the AT-SPI bus address from the a11y bus launcher,
75        // then connect to it. If that fails, fall back to the session bus
76        // (AT-SPI2 may use the session bus directly).
77        if let Ok(session) = Connection::session() {
78            let proxy = Proxy::new(&session, "org.a11y.Bus", "/org/a11y/bus", "org.a11y.Bus")
79                .map_err(|e| Error::Platform {
80                    code: -1,
81                    message: format!("Failed to create a11y bus proxy: {}", e),
82                })?;
83
84            if let Ok(addr_reply) = proxy.call_method("GetAddress", &()) {
85                if let Ok(address) = addr_reply.body().deserialize::<String>() {
86                    if let Ok(addr) = zbus::Address::try_from(address.as_str()) {
87                        if let Ok(Ok(conn)) =
88                            zbus::blocking::connection::Builder::address(addr).map(|b| b.build())
89                        {
90                            return Ok(conn);
91                        }
92                    }
93                }
94            }
95
96            // Fall back to session bus
97            return Ok(session);
98        }
99
100        Connection::session().map_err(|e| Error::Platform {
101            code: -1,
102            message: format!("Failed to connect to D-Bus session bus: {}", e),
103        })
104    }
105
106    fn make_proxy(&self, bus_name: &str, path: &str, interface: &str) -> Result<Proxy<'_>> {
107        // Use uncached proxy to avoid GetAll calls — Qt's AT-SPI adaptor
108        // doesn't support GetAll on all objects, causing spurious errors.
109        zbus::blocking::proxy::Builder::<Proxy>::new(&self.a11y_bus)
110            .destination(bus_name.to_owned())
111            .map_err(|e| Error::Platform {
112                code: -1,
113                message: format!("Failed to set proxy destination: {}", e),
114            })?
115            .path(path.to_owned())
116            .map_err(|e| Error::Platform {
117                code: -1,
118                message: format!("Failed to set proxy path: {}", e),
119            })?
120            .interface(interface.to_owned())
121            .map_err(|e| Error::Platform {
122                code: -1,
123                message: format!("Failed to set proxy interface: {}", e),
124            })?
125            .cache_properties(zbus::proxy::CacheProperties::No)
126            .build()
127            .map_err(|e| Error::Platform {
128                code: -1,
129                message: format!("Failed to create proxy: {}", e),
130            })
131    }
132
133    /// Check whether an accessible object implements a given interface.
134    /// Queries the AT-SPI GetInterfaces method on the Accessible interface.
135    fn has_interface(&self, aref: &AccessibleRef, iface: &str) -> bool {
136        let proxy = match self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Accessible") {
137            Ok(p) => p,
138            Err(_) => return false,
139        };
140        let reply = match proxy.call_method("GetInterfaces", &()) {
141            Ok(r) => r,
142            Err(_) => return false,
143        };
144        let interfaces: Vec<String> = match reply.body().deserialize() {
145            Ok(v) => v,
146            Err(_) => return false,
147        };
148        interfaces.iter().any(|i| i.contains(iface))
149    }
150
151    /// Get the numeric AT-SPI role via GetRole method.
152    fn get_role_number(&self, aref: &AccessibleRef) -> Result<u32> {
153        let proxy = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Accessible")?;
154        let reply = proxy
155            .call_method("GetRole", &())
156            .map_err(|e| Error::Platform {
157                code: -1,
158                message: format!("GetRole failed: {}", e),
159            })?;
160        reply
161            .body()
162            .deserialize::<u32>()
163            .map_err(|e| Error::Platform {
164                code: -1,
165                message: format!("GetRole deserialize failed: {}", e),
166            })
167    }
168
169    /// Get the AT-SPI role name string.
170    fn get_role_name(&self, aref: &AccessibleRef) -> Result<String> {
171        let proxy = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Accessible")?;
172        let reply = proxy
173            .call_method("GetRoleName", &())
174            .map_err(|e| Error::Platform {
175                code: -1,
176                message: format!("GetRoleName failed: {}", e),
177            })?;
178        reply
179            .body()
180            .deserialize::<String>()
181            .map_err(|e| Error::Platform {
182                code: -1,
183                message: format!("GetRoleName deserialize failed: {}", e),
184            })
185    }
186
187    /// Detect Chromium/Electron's "accessibility bridge disabled" signature.
188    ///
189    /// On Linux, Chromium-based apps (Electron, Chrome, VS Code, …) register
190    /// with AT-SPI but expose only an `application → frame` skeleton — the
191    /// frame's children list is empty (just the `/org/a11y/atspi/null`
192    /// sentinel) — unless the process was launched with the
193    /// `--force-renderer-accessibility` flag. Without this detection, callers
194    /// see zero results and assume their selector is wrong.
195    ///
196    /// Call this after observing an empty filtered children list. Returns an
197    /// error only when the parent is a window/frame whose AT-SPI bus reports
198    /// `Application.ToolkitName == "Chromium"`; otherwise returns `Ok(())` so
199    /// genuinely empty windows in other toolkits stay valid.
200    ///
201    /// `role_hint` lets callers that already know the role skip a `GetRole`
202    /// round-trip.
203    fn check_chromium_a11y_enabled(
204        &self,
205        parent: &AccessibleRef,
206        role_hint: Option<Role>,
207    ) -> Result<()> {
208        let app_root = AccessibleRef {
209            bus_name: parent.bus_name.clone(),
210            path: "/org/a11y/atspi/accessible/root".to_string(),
211        };
212        let toolkit = match self
213            .make_proxy(
214                &app_root.bus_name,
215                &app_root.path,
216                "org.a11y.atspi.Application",
217            )
218            .ok()
219            .and_then(|proxy| proxy.get_property::<String>("ToolkitName").ok())
220        {
221            Some(t) => t,
222            None => return Ok(()),
223        };
224        if !toolkit.eq_ignore_ascii_case("Chromium") {
225            return Ok(());
226        }
227        let role = role_hint.unwrap_or_else(|| self.resolve_role(parent));
228        if role != Role::Window {
229            return Ok(());
230        }
231        let app_name = self.get_name(&app_root).unwrap_or_default();
232        Err(Error::AccessibilityNotEnabled {
233            app: app_name,
234            instructions: "Chromium/Electron app exposes an empty accessibility tree on Linux. \
235                Relaunch with `--force-renderer-accessibility` (or set the env var \
236                `ACCESSIBILITY_ENABLED=1`) so the renderer accessibility bridge is initialised."
237                .to_string(),
238        })
239    }
240
241    /// Get the name of an accessible element.
242    fn get_name(&self, aref: &AccessibleRef) -> Result<String> {
243        let proxy = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Accessible")?;
244        proxy
245            .get_property::<String>("Name")
246            .map_err(|e| Error::Platform {
247                code: -1,
248                message: format!("Get Name property failed: {}", e),
249            })
250    }
251
252    /// Get the description of an accessible element.
253    fn get_description(&self, aref: &AccessibleRef) -> Result<String> {
254        let proxy = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Accessible")?;
255        proxy
256            .get_property::<String>("Description")
257            .map_err(|e| Error::Platform {
258                code: -1,
259                message: format!("Get Description property failed: {}", e),
260            })
261    }
262
263    /// Get children via the GetChildren method.
264    /// AT-SPI registryd doesn't always implement standard D-Bus Properties,
265    /// so we use GetChildren which is more reliable.
266    fn get_atspi_children(&self, aref: &AccessibleRef) -> Result<Vec<AccessibleRef>> {
267        let proxy = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Accessible")?;
268        let reply = proxy
269            .call_method("GetChildren", &())
270            .map_err(|e| Error::Platform {
271                code: -1,
272                message: format!("GetChildren failed: {}", e),
273            })?;
274        let children: Vec<(String, zbus::zvariant::OwnedObjectPath)> =
275            reply.body().deserialize().map_err(|e| Error::Platform {
276                code: -1,
277                message: format!("GetChildren deserialize failed: {}", e),
278            })?;
279        Ok(children
280            .into_iter()
281            .map(|(bus_name, path)| AccessibleRef {
282                bus_name,
283                path: path.to_string(),
284            })
285            .collect())
286    }
287
288    /// Get the state set as raw u32 values.
289    fn get_state(&self, aref: &AccessibleRef) -> Result<Vec<u32>> {
290        let proxy = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Accessible")?;
291        let reply = proxy
292            .call_method("GetState", &())
293            .map_err(|e| Error::Platform {
294                code: -1,
295                message: format!("GetState failed: {}", e),
296            })?;
297        reply
298            .body()
299            .deserialize::<Vec<u32>>()
300            .map_err(|e| Error::Platform {
301                code: -1,
302                message: format!("GetState deserialize failed: {}", e),
303            })
304    }
305
306    /// Return true if the element reports the AT-SPI MULTI_LINE state.
307    /// Used to distinguish multi-line text areas (TextArea) from single-line
308    /// text inputs (TextField), since both use the AT-SPI "text" role name.
309    /// Note: Qt's AT-SPI bridge does not reliably set SINGLE_LINE, so we
310    /// check MULTI_LINE and default to TextField when neither is set.
311    fn is_multi_line(&self, aref: &AccessibleRef) -> bool {
312        let state_bits = self.get_state(aref).unwrap_or_default();
313        let bits: u64 = if state_bits.len() >= 2 {
314            (state_bits[0] as u64) | ((state_bits[1] as u64) << 32)
315        } else if state_bits.len() == 1 {
316            state_bits[0] as u64
317        } else {
318            0
319        };
320        // ATSPI_STATE_MULTI_LINE = 17 in AtspiStateType enum
321        const MULTI_LINE: u64 = 1 << 17;
322        (bits & MULTI_LINE) != 0
323    }
324
325    /// Resolve TextField vs TextArea using the MULTI_LINE state, regardless of
326    /// the coarse role we started with. Different toolkits expose text inputs
327    /// under different AT-SPI roles ("text", "textbox", "entry", "embedded",
328    /// numeric 61/78/79), and WebKitGTK has changed mapping between versions
329    /// (e.g. 2.50 → 2.52 swapped what role textarea reports). MULTI_LINE is
330    /// the cross-toolkit invariant, so we let it decide.
331    ///
332    /// For any other coarse role, returns it unchanged.
333    fn refine_text_role(&self, coarse: Role, aref: &AccessibleRef) -> Role {
334        match coarse {
335            Role::TextArea | Role::TextField => {
336                if self.is_multi_line(aref) {
337                    Role::TextArea
338                } else {
339                    Role::TextField
340                }
341            }
342            other => other,
343        }
344    }
345
346    /// Get bounds via Component interface.
347    /// Checks for Component support first to avoid GTK CRITICAL warnings
348    /// on objects (e.g. TreeView cell renderers) that don't implement it.
349    fn get_extents(&self, aref: &AccessibleRef) -> Option<Rect> {
350        if !self.has_interface(aref, "Component") {
351            return None;
352        }
353        let proxy = self
354            .make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Component")
355            .ok()?;
356        // GetExtents(coord_type: u32) -> (x, y, width, height)
357        // coord_type 0 = screen coordinates
358        let reply = proxy.call_method("GetExtents", &(0u32,)).ok()?;
359        let (x, y, w, h): (i32, i32, i32, i32) = reply.body().deserialize().ok()?;
360        if w <= 0 && h <= 0 {
361            return None;
362        }
363        Some(Rect {
364            x,
365            y,
366            width: w.max(0) as u32,
367            height: h.max(0) as u32,
368        })
369    }
370
371    /// Get available actions via Action interface, returning both the action list
372    /// and a map of each action name to its AT-SPI2 integer index for direct `DoAction(i)`.
373    ///
374    /// Probes the interface directly rather than relying on the Interfaces property,
375    /// which some AT-SPI adapters (e.g. AccessKit) don't expose.
376    fn get_actions(&self, aref: &AccessibleRef) -> (Vec<String>, HashMap<String, i32>) {
377        let mut actions = Vec::new();
378        let mut indices = HashMap::new();
379
380        // Try Action interface directly
381        if let Ok(proxy) = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Action") {
382            // NActions may be returned as i32 or u32 depending on AT-SPI implementation.
383            let n_actions = proxy
384                .get_property::<i32>("NActions")
385                .or_else(|_| proxy.get_property::<u32>("NActions").map(|n| n as i32))
386                .unwrap_or(0);
387            for i in 0..n_actions {
388                if let Ok(reply) = proxy.call_method("GetName", &(i,)) {
389                    if let Ok(name) = reply.body().deserialize::<String>() {
390                        if let Some(action_name) = map_atspi_action_name(&name) {
391                            if !actions.contains(&action_name) {
392                                indices.insert(action_name.clone(), i);
393                                actions.push(action_name);
394                            }
395                        }
396                    }
397                }
398            }
399        }
400
401        // NOTE: We do NOT add implicit "focus" based on Component interface existence.
402        // On GTK4, GrabFocus() often returns false even when Component interface exists,
403        // violating design tenet 3 ("if action is listed, calling it must work").
404        // Only report "focus" if it's explicitly in the AT-SPI Action interface with a
405        // proper index. This ensures focus() will work when reported.
406        // Fixes GitHub issue #98.
407
408        (actions, indices)
409    }
410
411    /// Return true when the accessible's application identifies itself as GTK
412    /// via `org.a11y.atspi.Application.ToolkitName`.
413    ///
414    /// Used to scope the press-fallback heuristic for the
415    /// AdwMenuButton/GtkMenuButton wrapper pattern; other toolkits are
416    /// unaffected.
417    fn is_gtk_toolkit(&self, aref: &AccessibleRef) -> bool {
418        let app_root = AccessibleRef {
419            bus_name: aref.bus_name.clone(),
420            path: "/org/a11y/atspi/accessible/root".to_string(),
421        };
422        self.make_proxy(
423            &app_root.bus_name,
424            &app_root.path,
425            "org.a11y.atspi.Application",
426        )
427        .ok()
428        .and_then(|proxy| proxy.get_property::<String>("ToolkitName").ok())
429        .map(|t| t.eq_ignore_ascii_case("GTK"))
430        .unwrap_or(false)
431    }
432
433    /// GTK press-fallback resolver.
434    ///
435    /// Walks the accessible's descendants (BFS, depth-capped) looking for a
436    /// single activatable child that shares the outer widget's name. Returns
437    /// the (ref, action_index) pair when exactly one suitable candidate
438    /// exists at the shallowest matching depth. Returns `None` when the
439    /// subtree contains nothing suitable or multiple equally plausible
440    /// candidates — refusing to guess.
441    ///
442    /// Empirically fixes the `GtkMenuButton` / `AdwMenuButton` wrappers that
443    /// ship in every stock GNOME app (Calculator, Text Editor, Logs, Clocks,
444    /// Characters, …).
445    fn find_gtk_press_fallback(
446        &self,
447        outer: &AccessibleRef,
448        outer_name: &str,
449    ) -> Option<(AccessibleRef, i32)> {
450        let mut queue: VecDeque<(AccessibleRef, u32)> = VecDeque::new();
451        queue.push_back((outer.clone(), 0));
452        let mut visited: usize = 0;
453        let mut shallowest_depth: Option<u32> = None;
454        let mut hits: Vec<(AccessibleRef, i32)> = Vec::new();
455
456        while let Some((node, depth)) = queue.pop_front() {
457            // Once we've found the shallowest level with hits, don't look deeper.
458            if let Some(best) = shallowest_depth {
459                if depth > best {
460                    continue;
461                }
462            }
463            if visited > GTK_FALLBACK_MAX_NODES {
464                break;
465            }
466
467            let role_name = if depth == 0 {
468                String::new()
469            } else {
470                visited += 1;
471                self.get_role_name(&node).unwrap_or_default().to_lowercase()
472            };
473
474            if depth > 0 && is_actionable_atspi_role(&role_name) {
475                if let Some(idx) = self.gtk_fallback_pick(&node, outer_name) {
476                    match shallowest_depth {
477                        Some(d) if depth < d => {
478                            shallowest_depth = Some(depth);
479                            hits.clear();
480                            hits.push((node.clone(), idx));
481                        }
482                        Some(d) if depth == d => hits.push((node.clone(), idx)),
483                        Some(_) => {}
484                        None => {
485                            shallowest_depth = Some(depth);
486                            hits.push((node.clone(), idx));
487                        }
488                    }
489                }
490            }
491
492            // Do not descend into static/decorative roles. Descend through
493            // containers and actionable roles alike (actionable roles may
494            // themselves wrap an inner actionable — e.g. an AdwSplitButton's
495            // primary button inside a toggle-button shell).
496            let stop_descending = depth >= GTK_FALLBACK_MAX_DEPTH
497                || (depth > 0 && is_never_descend_atspi_role(&role_name));
498            if stop_descending {
499                continue;
500            }
501            if let Ok(children) = self.get_atspi_children(&node) {
502                for c in children {
503                    queue.push_back((c, depth + 1));
504                }
505            }
506        }
507
508        if hits.len() == 1 {
509            Some(hits.into_iter().next().unwrap())
510        } else {
511            None
512        }
513    }
514
515    /// Per-node filter for `find_gtk_press_fallback`. Returns the AT-SPI
516    /// action index to invoke when `aref` is a valid fallback candidate.
517    fn gtk_fallback_pick(&self, aref: &AccessibleRef, outer_name: &str) -> Option<i32> {
518        let (_, index_map) = self.get_actions(aref);
519        let idx = *index_map.get("press")?;
520        if !self.is_showing_visible_sensitive(aref) {
521            return None;
522        }
523        // If the outer has a name, require the candidate to share it. Rules
524        // out unrelated suffix widgets (e.g. a switch inside an AdwActionRow
525        // that happens to expose `click`).
526        if !outer_name.is_empty() {
527            let inner_name = self.get_name(aref).unwrap_or_default();
528            if !inner_name.is_empty() && inner_name != outer_name {
529                return None;
530            }
531        }
532        Some(idx)
533    }
534
535    /// True when the accessible's state has SHOWING, VISIBLE, and SENSITIVE
536    /// set. ENABLED is deliberately excluded: in GTK4 it reflects "has an
537    /// enabled GAction bound", which is false for the exact widgets we
538    /// rescue.
539    fn is_showing_visible_sensitive(&self, aref: &AccessibleRef) -> bool {
540        let raw = self.get_state(aref).unwrap_or_default();
541        let bits: u64 = if raw.len() >= 2 {
542            (raw[0] as u64) | ((raw[1] as u64) << 32)
543        } else if raw.len() == 1 {
544            raw[0] as u64
545        } else {
546            0
547        };
548        const SENSITIVE: u64 = 1 << 24;
549        const SHOWING: u64 = 1 << 25;
550        const VISIBLE: u64 = 1 << 30;
551        (bits & (SHOWING | VISIBLE | SENSITIVE)) == (SHOWING | VISIBLE | SENSITIVE)
552    }
553
554    /// Get value via Value or Text interface.
555    /// Probes interfaces directly rather than relying on the Interfaces property.
556    fn get_value(&self, aref: &AccessibleRef) -> Option<String> {
557        // Try Text interface first for text content (text fields, labels, combo boxes).
558        // This must come before Value because some AT-SPI adapters (e.g. AccessKit)
559        // may expose both interfaces, and Value.CurrentValue returns 0.0 for text elements.
560        let text_value = self.get_text_content(aref);
561        if text_value.is_some() {
562            return text_value;
563        }
564        // Try Value interface (sliders, progress bars, scroll bars, spinners)
565        if let Ok(proxy) = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Value") {
566            if let Ok(val) = proxy.get_property::<f64>("CurrentValue") {
567                return Some(val.to_string());
568            }
569        }
570        None
571    }
572
573    /// Read text content via the AT-SPI Text interface.
574    fn get_text_content(&self, aref: &AccessibleRef) -> Option<String> {
575        let proxy = self
576            .make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Text")
577            .ok()?;
578        let char_count: i32 = proxy.get_property("CharacterCount").ok()?;
579        if char_count > 0 {
580            let reply = proxy.call_method("GetText", &(0i32, char_count)).ok()?;
581            let text: String = reply.body().deserialize().ok()?;
582            if !text.is_empty() {
583                return Some(text);
584            }
585        }
586        None
587    }
588
589    /// Cache an AccessibleRef and return a new handle ID.
590    fn cache_element(&self, aref: AccessibleRef) -> u64 {
591        let handle = NEXT_HANDLE.fetch_add(1, Ordering::Relaxed);
592        self.handle_cache
593            .lock()
594            .unwrap_or_else(|e| e.into_inner())
595            .insert(handle, aref);
596        handle
597    }
598
599    /// Look up a cached AccessibleRef by handle.
600    fn get_cached(&self, handle: u64) -> Result<AccessibleRef> {
601        self.handle_cache
602            .lock()
603            .unwrap_or_else(|e| e.into_inner())
604            .get(&handle)
605            .cloned()
606            .ok_or(Error::ElementStale {
607                selector: format!("handle:{}", handle),
608            })
609    }
610
611    /// Build an ElementData from an AccessibleRef, caching the ref for later lookup.
612    ///
613    /// After resolving the role (1-3 sequential D-Bus calls), all remaining
614    /// property fetches are independent and run in parallel via rayon::join.
615    fn build_element_data(&self, aref: &AccessibleRef, pid: Option<u32>) -> ElementData {
616        let role_name = self.get_role_name(aref).unwrap_or_default();
617        let role_num = self.get_role_number(aref).unwrap_or(0);
618        let role = {
619            let by_name = if !role_name.is_empty() {
620                map_atspi_role(&role_name)
621            } else {
622                Role::Unknown
623            };
624            let coarse = if by_name != Role::Unknown {
625                by_name
626            } else {
627                map_atspi_role_number(role_num)
628            };
629            self.refine_text_role(coarse, aref)
630        };
631
632        // Fetch all independent properties in parallel.
633        // Left tree: (name+value, description)
634        // Right tree: ((states, bounds), (actions, numeric_values))
635        let (
636            ((mut name, value), description),
637            (
638                (states, bounds),
639                ((actions, action_index_map), (numeric_value, min_value, max_value)),
640            ),
641        ) = rayon::join(
642            || {
643                rayon::join(
644                    || {
645                        let name = self.get_name(aref).ok().filter(|s| !s.is_empty());
646                        let value = if role_has_value(role) {
647                            self.get_value(aref)
648                        } else {
649                            None
650                        };
651                        (name, value)
652                    },
653                    || self.get_description(aref).ok().filter(|s| !s.is_empty()),
654                )
655            },
656            || {
657                rayon::join(
658                    || {
659                        rayon::join(
660                            || self.parse_states(aref, role),
661                            || {
662                                if role != Role::Application {
663                                    self.get_extents(aref)
664                                } else {
665                                    None
666                                }
667                            },
668                        )
669                    },
670                    || {
671                        rayon::join(
672                            || {
673                                if role_has_actions(role) {
674                                    self.get_actions(aref)
675                                } else {
676                                    (vec![], HashMap::new())
677                                }
678                            },
679                            || {
680                                if matches!(
681                                    role,
682                                    Role::Slider
683                                        | Role::ProgressBar
684                                        | Role::ScrollBar
685                                        | Role::SpinButton
686                                ) {
687                                    if let Ok(proxy) = self.make_proxy(
688                                        &aref.bus_name,
689                                        &aref.path,
690                                        "org.a11y.atspi.Value",
691                                    ) {
692                                        (
693                                            proxy.get_property::<f64>("CurrentValue").ok(),
694                                            proxy.get_property::<f64>("MinimumValue").ok(),
695                                            proxy.get_property::<f64>("MaximumValue").ok(),
696                                        )
697                                    } else {
698                                        (None, None, None)
699                                    }
700                                } else {
701                                    (None, None, None)
702                                }
703                            },
704                        )
705                    },
706                )
707            },
708        );
709
710        // For label/static text elements, AT-SPI may put content in the Text
711        // interface (returned as value) rather than the Name property.
712        if name.is_none() && role == Role::StaticText {
713            if let Some(ref v) = value {
714                name = Some(v.clone());
715            }
716        }
717
718        let raw = {
719            let raw_role = if role_name.is_empty() {
720                format!("role_num:{}", role_num)
721            } else {
722                role_name
723            };
724            let mut raw = HashMap::new();
725            raw.insert("atspi_role".into(), serde_json::Value::String(raw_role));
726            raw.insert(
727                "bus_name".into(),
728                serde_json::Value::String(aref.bus_name.clone()),
729            );
730            raw.insert(
731                "object_path".into(),
732                serde_json::Value::String(aref.path.clone()),
733            );
734            // Preserve unstripped originals so callers who need bidi marks can
735            // recover them after the strip below.
736            if let Some(ref n) = name {
737                raw.insert("atspi_name".into(), serde_json::Value::String(n.clone()));
738            }
739            if let Some(ref v) = value {
740                raw.insert("atspi_value".into(), serde_json::Value::String(v.clone()));
741            }
742            if let Some(ref d) = description {
743                raw.insert(
744                    "atspi_description".into(),
745                    serde_json::Value::String(d.clone()),
746                );
747            }
748            raw
749        };
750
751        // Strip Unicode bidi format controls. RTL apps on Linux embed LRM/RLM
752        // marks into reported strings; the originals are preserved in `raw`.
753        let name = xa11y_core::text::strip_bidi_opt(name);
754        let value = xa11y_core::text::strip_bidi_opt(value);
755        let description = xa11y_core::text::strip_bidi_opt(description);
756
757        let handle = self.cache_element(aref.clone());
758        if !action_index_map.is_empty() {
759            self.action_indices
760                .lock()
761                .unwrap_or_else(|e| e.into_inner())
762                .insert(handle, action_index_map);
763        }
764
765        ElementData {
766            role,
767            name,
768            value,
769            description,
770            bounds,
771            actions,
772            states,
773            numeric_value,
774            min_value,
775            max_value,
776            pid,
777            stable_id: Some(aref.path.clone()),
778            raw,
779            handle,
780        }
781    }
782
783    /// Get the AT-SPI parent of an accessible ref.
784    fn get_atspi_parent(&self, aref: &AccessibleRef) -> Result<Option<AccessibleRef>> {
785        // Read the Parent property via the D-Bus Properties interface.
786        let proxy = self.make_proxy(
787            &aref.bus_name,
788            &aref.path,
789            "org.freedesktop.DBus.Properties",
790        )?;
791        let reply = proxy
792            .call_method("Get", &("org.a11y.atspi.Accessible", "Parent"))
793            .map_err(|e| Error::Platform {
794                code: -1,
795                message: format!("Get Parent property failed: {}", e),
796            })?;
797        // The reply is a Variant containing (so) — a struct of (bus_name, object_path)
798        let variant: zbus::zvariant::OwnedValue =
799            reply.body().deserialize().map_err(|e| Error::Platform {
800                code: -1,
801                message: format!("Parent deserialize variant failed: {}", e),
802            })?;
803        let (bus, path): (String, zbus::zvariant::OwnedObjectPath) =
804            zbus::zvariant::Value::from(variant).try_into().map_err(
805                |e: zbus::zvariant::Error| Error::Platform {
806                    code: -1,
807                    message: format!("Parent deserialize struct failed: {}", e),
808                },
809            )?;
810        let path_str = path.as_str();
811        if path_str == "/org/a11y/atspi/null" || bus.is_empty() || path_str.is_empty() {
812            return Ok(None);
813        }
814        // If the parent is the registry root, this is a top-level app — no parent
815        if path_str == "/org/a11y/atspi/accessible/root" {
816            return Ok(None);
817        }
818        Ok(Some(AccessibleRef {
819            bus_name: bus,
820            path: path_str.to_string(),
821        }))
822    }
823
824    /// Parse AT-SPI2 state bitfield into xa11y StateSet.
825    fn parse_states(&self, aref: &AccessibleRef, role: Role) -> StateSet {
826        let state_bits = self.get_state(aref).unwrap_or_default();
827
828        // AT-SPI2 states are a bitfield across two u32s
829        let bits: u64 = if state_bits.len() >= 2 {
830            (state_bits[0] as u64) | ((state_bits[1] as u64) << 32)
831        } else if state_bits.len() == 1 {
832            state_bits[0] as u64
833        } else {
834            0
835        };
836
837        // AT-SPI2 state bit positions (AtspiStateType enum values)
838        const BUSY: u64 = 1 << 3;
839        const CHECKED: u64 = 1 << 4;
840        const EDITABLE: u64 = 1 << 7;
841        const ENABLED: u64 = 1 << 8;
842        const EXPANDABLE: u64 = 1 << 9;
843        const EXPANDED: u64 = 1 << 10;
844        const FOCUSABLE: u64 = 1 << 11;
845        const FOCUSED: u64 = 1 << 12;
846        const MODAL: u64 = 1 << 16;
847        const SELECTED: u64 = 1 << 23;
848        const SENSITIVE: u64 = 1 << 24;
849        const SHOWING: u64 = 1 << 25;
850        const VISIBLE: u64 = 1 << 30;
851        const INDETERMINATE: u64 = 1 << 32;
852        const REQUIRED: u64 = 1 << 33;
853
854        let enabled = (bits & ENABLED) != 0 || (bits & SENSITIVE) != 0;
855        let visible = (bits & VISIBLE) != 0 || (bits & SHOWING) != 0;
856
857        let checked = match role {
858            Role::CheckBox | Role::RadioButton | Role::MenuItem | Role::Switch => {
859                if (bits & INDETERMINATE) != 0 {
860                    Some(Toggled::Mixed)
861                } else if (bits & CHECKED) != 0 {
862                    Some(Toggled::On)
863                } else {
864                    Some(Toggled::Off)
865                }
866            }
867            _ => None,
868        };
869
870        let expanded = if (bits & EXPANDABLE) != 0 {
871            Some((bits & EXPANDED) != 0)
872        } else {
873            None
874        };
875
876        StateSet {
877            enabled,
878            visible,
879            focused: (bits & FOCUSED) != 0,
880            checked,
881            selected: (bits & SELECTED) != 0,
882            expanded,
883            editable: (bits & EDITABLE) != 0,
884            focusable: (bits & FOCUSABLE) != 0,
885            modal: (bits & MODAL) != 0,
886            required: (bits & REQUIRED) != 0,
887            busy: (bits & BUSY) != 0,
888        }
889    }
890
891    /// Find an application by PID.
892    ///
893    /// Used by `subscribe` to resolve the target app's D-Bus sender name so
894    /// signal match rules can be scoped to it.
895    pub(crate) fn find_app_by_pid(&self, pid: u32) -> Result<AccessibleRef> {
896        let registry = AccessibleRef {
897            bus_name: "org.a11y.atspi.Registry".to_string(),
898            path: "/org/a11y/atspi/accessible/root".to_string(),
899        };
900        let children = self.get_atspi_children(&registry)?;
901
902        for child in &children {
903            if child.path == "/org/a11y/atspi/null" {
904                continue;
905            }
906            // Prefer D-Bus connection PID — it's authoritative for the
907            // process owning the bus connection. Application.Id is *not* a
908            // process pid: AT-SPI assigns it as a registry-local index
909            // (1, 2, 3, …) for some bridges (notably GTK4), so matching
910            // against Application.Id alone misses real processes.
911            if let Some(app_pid) = self.get_dbus_pid(&child.bus_name) {
912                if app_pid == pid {
913                    return Ok(child.clone());
914                }
915            }
916            // Fall back to Application.Id for adapters that do set it to pid.
917            if let Ok(proxy) =
918                self.make_proxy(&child.bus_name, &child.path, "org.a11y.atspi.Application")
919            {
920                if let Ok(app_pid) = proxy.get_property::<i32>("Id") {
921                    if app_pid as u32 == pid {
922                        return Ok(child.clone());
923                    }
924                }
925            }
926        }
927
928        Err(Error::Platform {
929            code: -1,
930            message: format!("No application found with PID {}", pid),
931        })
932    }
933
934    /// Get PID via D-Bus GetConnectionUnixProcessID.
935    fn get_dbus_pid(&self, bus_name: &str) -> Option<u32> {
936        let proxy = self
937            .make_proxy(
938                "org.freedesktop.DBus",
939                "/org/freedesktop/DBus",
940                "org.freedesktop.DBus",
941            )
942            .ok()?;
943        let reply = proxy
944            .call_method("GetConnectionUnixProcessID", &(bus_name,))
945            .ok()?;
946        let pid: u32 = reply.body().deserialize().ok()?;
947        if pid > 0 {
948            Some(pid)
949        } else {
950            None
951        }
952    }
953
954    /// Perform an AT-SPI2 action by its integer index (from discovery).
955    fn do_atspi_action_by_index(&self, aref: &AccessibleRef, index: i32) -> Result<()> {
956        let proxy = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Action")?;
957        proxy
958            .call_method("DoAction", &(index,))
959            .map_err(|e| Error::Platform {
960                code: -1,
961                message: format!("DoAction({}) failed: {}", index, e),
962            })?;
963        Ok(())
964    }
965
966    /// Look up the stored AT-SPI2 action index for the given element and action.
967    fn get_action_index(&self, handle: u64, action: &str) -> Result<i32> {
968        self.action_indices
969            .lock()
970            .unwrap_or_else(|e| e.into_inner())
971            .get(&handle)
972            .and_then(|map| map.get(action).copied())
973            .ok_or_else(|| Error::ActionNotSupported {
974                action: action.to_string(),
975                role: Role::Unknown, // caller will provide better context
976            })
977    }
978
979    /// Get the process PID for an AT-SPI accessible. Prefers the D-Bus
980    /// connection PID over `Application.Id`: the latter is a registry-local
981    /// index (1, 2, 3, …) on some bridges (e.g. GTK4), not a real pid, so
982    /// reading it first produces apps whose `pid` property doesn't match the
983    /// process the user launched.
984    fn get_app_pid(&self, aref: &AccessibleRef) -> Option<u32> {
985        if let Some(pid) = self.get_dbus_pid(&aref.bus_name) {
986            return Some(pid);
987        }
988
989        // Fall back to Application.Id for adapters that set it to pid.
990        // Require that a process with that id actually exists — a registry
991        // index from a misbehaving bridge usually names a long-dead or absurd
992        // pid. This is only a cheap sanity filter: a low index can still
993        // collide with a real process (1 = init), which is why the D-Bus
994        // connection pid above is authoritative whenever available.
995        if let Ok(proxy) = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Application")
996        {
997            if let Ok(pid) = proxy.get_property::<i32>("Id") {
998                if pid > 0 && std::path::Path::new(&format!("/proc/{pid}")).exists() {
999                    return Some(pid as u32);
1000                }
1001            }
1002        }
1003
1004        None
1005    }
1006
1007    /// Resolve the mapped Role for an accessible ref (1-3 D-Bus calls).
1008    fn resolve_role(&self, aref: &AccessibleRef) -> Role {
1009        let role_name = self.get_role_name(aref).unwrap_or_default();
1010        let by_name = if !role_name.is_empty() {
1011            map_atspi_role(&role_name)
1012        } else {
1013            Role::Unknown
1014        };
1015        let coarse = if by_name != Role::Unknown {
1016            by_name
1017        } else {
1018            // Unmapped or missing role name — fall back to numeric role.
1019            let role_num = self.get_role_number(aref).unwrap_or(0);
1020            map_atspi_role_number(role_num)
1021        };
1022        self.refine_text_role(coarse, aref)
1023    }
1024
1025    /// Check if an accessible ref matches a simple selector, fetching only the
1026    /// attributes the selector actually requires.
1027    ///
1028    /// Filter routing (cheapest first):
1029    ///   * `role` / `name` / `value` / `description` — single targeted D-Bus
1030    ///     call against this accessible.
1031    ///   * Normalized state attrs (`enabled`, `checked`, `focused`, …) —
1032    ///     one shared `GetState` call, cached for the rest of this match.
1033    ///   * Anything else (custom `raw` keys, `bounds`, numeric values) — fall
1034    ///     through to building a full `ElementData` and delegating to
1035    ///     [`xa11y_core::selector::matches_simple`]. This is slower but keeps
1036    ///     selectors with rare attribute filters semantically equivalent to
1037    ///     the default tree-traversal path.
1038    fn matches_ref(
1039        &self,
1040        aref: &AccessibleRef,
1041        simple: &xa11y_core::selector::SimpleSelector,
1042    ) -> bool {
1043        // Resolve role only if the selector needs it (for either the role
1044        // segment or any role/checked filter — checked depends on role).
1045        let needs_role = simple.role.is_some()
1046            || simple
1047                .filters
1048                .iter()
1049                .any(|f| matches!(f.attr.as_str(), "role" | "checked"));
1050        let role = if needs_role {
1051            Some(self.resolve_role(aref))
1052        } else {
1053            None
1054        };
1055
1056        if let Some(ref role_match) = simple.role {
1057            match role_match {
1058                xa11y_core::selector::RoleMatch::Normalized(expected) => {
1059                    if role != Some(*expected) {
1060                        return false;
1061                    }
1062                }
1063                xa11y_core::selector::RoleMatch::Platform(platform_role) => {
1064                    let raw_role = self.get_role_name(aref).unwrap_or_default();
1065                    if raw_role != *platform_role {
1066                        return false;
1067                    }
1068                }
1069            }
1070        }
1071
1072        let mut state_set: Option<StateSet> = None;
1073
1074        for filter in &simple.filters {
1075            let attr = filter.attr.as_str();
1076            let resolved: Option<Option<String>> = match attr {
1077                "role" => Some(role.map(|r| r.to_snake_case().to_string())),
1078                "name" => {
1079                    let name = self.get_name(aref).ok().filter(|s| !s.is_empty());
1080                    // Mirror build_element_data: StaticText carries its name
1081                    // in the Text interface's Value when Name is empty.
1082                    let resolved = if name.is_none() && role == Some(Role::StaticText) {
1083                        self.get_value(aref)
1084                    } else {
1085                        name
1086                    };
1087                    Some(resolved)
1088                }
1089                "value" => Some(self.get_value(aref)),
1090                "description" => Some(self.get_description(aref).ok().filter(|s| !s.is_empty())),
1091                "enabled" | "visible" | "focused" | "focusable" | "selected" | "editable"
1092                | "modal" | "required" | "busy" | "expanded" | "checked" => {
1093                    let s = state_set.get_or_insert_with(|| {
1094                        // `parse_states` reads `checked` based on role; pass
1095                        // whatever we already resolved (Unknown is a no-op for
1096                        // the role-gated `checked` mapping).
1097                        self.parse_states(aref, role.unwrap_or(Role::Unknown))
1098                    });
1099                    Some(state_attr_to_string(attr, s))
1100                }
1101                _ => None, // Routed through full ElementData below.
1102            };
1103
1104            match resolved {
1105                Some(value) => {
1106                    if !xa11y_core::selector::match_op(&filter.op, &filter.value, value.as_deref())
1107                    {
1108                        return false;
1109                    }
1110                }
1111                None => {
1112                    // Filter targets an attribute the fast path doesn't know
1113                    // (e.g. `bounds`, `numeric_value`, a custom `raw` key).
1114                    // Build the full ElementData once and let the shared
1115                    // matcher handle every remaining filter — it dispatches
1116                    // to `ElementData` fields and the `raw` map identically
1117                    // to the default tree-traversal path.
1118                    let pid = None; // pid isn't selector-addressable
1119                    let data = self.build_element_data(aref, pid);
1120                    return xa11y_core::selector::matches_simple(&data, simple);
1121                }
1122            }
1123        }
1124
1125        true
1126    }
1127
1128    /// ONE DFS over the subtree, evaluating each clause's first SimpleSelector
1129    /// against every visited node. Emits `(clause_idx, AccessibleRef)` pairs
1130    /// in document order; a node that matches multiple clauses is emitted
1131    /// once per matching clause (the merge step in `find_elements_group`
1132    /// collapses these by `(bus_name, path)` identity).
1133    ///
1134    /// This is the "push-down to the platform query per group" core: a
1135    /// selector group like `button, text_field` traverses the AT-SPI tree
1136    /// exactly once regardless of clause count, instead of N separate walks.
1137    fn collect_matching_refs_group(
1138        &self,
1139        parent: &AccessibleRef,
1140        clauses: &[&xa11y_core::selector::SimpleSelector],
1141        depth: u32,
1142        max_depth: u32,
1143        limit: Option<usize>,
1144    ) -> Result<Vec<(usize, AccessibleRef)>> {
1145        if depth > max_depth {
1146            return Ok(vec![]);
1147        }
1148
1149        let children = self.get_atspi_children(parent)?;
1150
1151        // Filter invalid refs. Application-node flattening (collapsing a
1152        // redundant `application` accessible into its grandchildren) is only
1153        // valid when the parent is itself an application — i.e. we have already
1154        // descended past the registry. At the registry root, the children *are*
1155        // the applications and must not be collapsed, otherwise selectors like
1156        // `application` (used by `App::list` / `App::by_name`) match nothing
1157        // because the app accessibles get dissolved into their windows.
1158        let parent_is_registry = parent.bus_name == "org.a11y.atspi.Registry";
1159        let mut to_search: Vec<AccessibleRef> = Vec::new();
1160        for child in children {
1161            if child.path == "/org/a11y/atspi/null"
1162                || child.bus_name.is_empty()
1163                || child.path.is_empty()
1164            {
1165                continue;
1166            }
1167
1168            if !parent_is_registry {
1169                let child_role = self.get_role_name(&child).unwrap_or_default();
1170                if child_role == "application" {
1171                    let grandchildren = self.get_atspi_children(&child).unwrap_or_default();
1172                    for gc in grandchildren {
1173                        if gc.path == "/org/a11y/atspi/null"
1174                            || gc.bus_name.is_empty()
1175                            || gc.path.is_empty()
1176                        {
1177                            continue;
1178                        }
1179                        let gc_role = self.get_role_name(&gc).unwrap_or_default();
1180                        if gc_role == "application" {
1181                            continue;
1182                        }
1183                        to_search.push(gc);
1184                    }
1185                    continue;
1186                }
1187            }
1188            to_search.push(child);
1189        }
1190
1191        // Detect Chromium/Electron's empty-tree signature whenever we
1192        // descend into a parent and find no real children.
1193        if to_search.is_empty() {
1194            self.check_chromium_a11y_enabled(parent, None)?;
1195        }
1196
1197        // Process each child subtree in parallel: check match against every
1198        // clause + recurse. Tagging each match with `clause_idx` lets the
1199        // caller route phase-2 narrowing to the right clause without
1200        // re-running the first-segment match.
1201        //
1202        // We deliberately swallow transient sibling errors here — a single
1203        // flaky D-Bus call on one child shouldn't fail the whole locator
1204        // query (the rest of this file is similarly tolerant via
1205        // `unwrap_or_default()`). But `AccessibilityNotEnabled` is *not* a
1206        // transient error: it's the signal that a Chromium renderer bridge
1207        // isn't initialised, and callers need to see it. So we propagate
1208        // that variant specifically and keep tolerating everything else.
1209        // Per-child batches: matches collected during that child's subtree
1210        // walk, plus the first AccessibilityNotEnabled error (if any).
1211        type ChildBatch = (Vec<(usize, AccessibleRef)>, Option<Error>);
1212        let per_child: Vec<ChildBatch> = to_search
1213            .par_iter()
1214            .map(|child| {
1215                let mut child_results: Vec<(usize, AccessibleRef)> = Vec::new();
1216                for (idx, simple) in clauses.iter().enumerate() {
1217                    if self.matches_ref(child, simple) {
1218                        child_results.push((idx, child.clone()));
1219                    }
1220                }
1221                match self.collect_matching_refs_group(child, clauses, depth + 1, max_depth, limit)
1222                {
1223                    Ok(sub) => {
1224                        child_results.extend(sub);
1225                        (child_results, None)
1226                    }
1227                    Err(e @ Error::AccessibilityNotEnabled { .. }) => (Vec::new(), Some(e)),
1228                    Err(_) => (child_results, None),
1229                }
1230            })
1231            .collect();
1232
1233        // Merge results, respecting limit. The first AccessibilityNotEnabled
1234        // error seen wins — any child subtree raising it means the whole
1235        // query is untrustworthy, so surface it rather than return partial
1236        // data.
1237        //
1238        // Note: `limit` is the *caller's* outer limit; for a multi-clause
1239        // group it must not be applied per-clause (a low-priority clause's
1240        // hit could come before a high-priority clause's in doc order, so
1241        // truncating mid-walk would drop legitimate matches). Callers pass
1242        // `None` for multi-clause queries and apply the limit after the
1243        // cross-clause merge.
1244        let mut results = Vec::new();
1245        for (batch, maybe_err) in per_child {
1246            if let Some(err) = maybe_err {
1247                return Err(err);
1248            }
1249            for r in batch {
1250                results.push(r);
1251                if let Some(limit) = limit {
1252                    if results.len() >= limit {
1253                        return Ok(results);
1254                    }
1255                }
1256            }
1257        }
1258        Ok(results)
1259    }
1260}
1261
1262impl Provider for LinuxProvider {
1263    fn get_children(&self, element: Option<&ElementData>) -> Result<Vec<ElementData>> {
1264        match element {
1265            None => {
1266                // Top-level: delegate to `list_apps()`, the canonical
1267                // discovery primitive.
1268                self.list_apps()
1269            }
1270            Some(element_data) => {
1271                let aref = self.get_cached(element_data.handle)?;
1272                let children = self.get_atspi_children(&aref).unwrap_or_default();
1273                let pid = element_data.pid;
1274
1275                // Pre-filter invalid refs and flatten nested application nodes,
1276                // collecting the concrete refs to build in parallel.
1277                let mut to_build: Vec<AccessibleRef> = Vec::new();
1278                for child_ref in &children {
1279                    if child_ref.path == "/org/a11y/atspi/null"
1280                        || child_ref.bus_name.is_empty()
1281                        || child_ref.path.is_empty()
1282                    {
1283                        continue;
1284                    }
1285                    let child_role = self.get_role_name(child_ref).unwrap_or_default();
1286                    if child_role == "application" {
1287                        let grandchildren = self.get_atspi_children(child_ref).unwrap_or_default();
1288                        for gc_ref in grandchildren {
1289                            if gc_ref.path == "/org/a11y/atspi/null"
1290                                || gc_ref.bus_name.is_empty()
1291                                || gc_ref.path.is_empty()
1292                            {
1293                                continue;
1294                            }
1295                            let gc_role = self.get_role_name(&gc_ref).unwrap_or_default();
1296                            if gc_role == "application" {
1297                                continue;
1298                            }
1299                            to_build.push(gc_ref);
1300                        }
1301                        continue;
1302                    }
1303                    to_build.push(child_ref.clone());
1304                }
1305
1306                if to_build.is_empty() {
1307                    self.check_chromium_a11y_enabled(&aref, Some(element_data.role))?;
1308                }
1309
1310                let results: Vec<ElementData> = to_build
1311                    .par_iter()
1312                    .map(|r| self.build_element_data(r, pid))
1313                    .collect();
1314
1315                Ok(results)
1316            }
1317        }
1318    }
1319
1320    fn find_elements_group(
1321        &self,
1322        root: &ElementData,
1323        group: &xa11y_core::selector::SelectorGroup,
1324        limit: Option<usize>,
1325        max_depth: Option<u32>,
1326    ) -> Result<Vec<ElementData>> {
1327        if group.clauses.is_empty() {
1328            return Ok(vec![]);
1329        }
1330        // Reject any clause with zero segments early — `clause.segments[0]`
1331        // below would otherwise panic.
1332        if group.clauses.iter().any(|c| c.segments.is_empty()) {
1333            return Ok(vec![]);
1334        }
1335
1336        // ONE AT-SPI walk that evaluates every clause's first SimpleSelector
1337        // against each visited node, then per-clause phase-2 narrowing on
1338        // the small candidate sets that fall out. Dedup uses
1339        // `(bus_name, path)` — the only AT-SPI identifier that's stable
1340        // across the per-clause narrowings (handles are minted fresh on
1341        // each `build_element_data` call).
1342        //
1343        // App discovery is handled separately by `list_apps()` — `root` is
1344        // always present here.
1345        let max_depth_val = max_depth.unwrap_or(xa11y_core::MAX_TREE_DEPTH);
1346
1347        let firsts: Vec<&xa11y_core::selector::SimpleSelector> = group
1348            .clauses
1349            .iter()
1350            .map(|c| &c.segments[0].simple)
1351            .collect();
1352
1353        let start_ref = self.get_cached(root.handle)?;
1354
1355        // ── Phase-1 limit short-circuit ───────────────────────────
1356        // When there's exactly one clause, propagate the user's `limit`
1357        // (adjusted for `:nth`) to the AT-SPI walk so e.g.
1358        // `app.locator("button").first()` stops at the first match. With
1359        // multiple clauses, phase-1 hits for clause N might come before
1360        // clause M's in doc order, so we need the union before truncating.
1361        // (Critical on Electron-scale apps where this prevents 50k-node
1362        // walks.)
1363        let phase1_limit = if group.clauses.len() == 1 {
1364            let clause = &group.clauses[0];
1365            let first = firsts[0];
1366            let outer = if clause.segments.len() == 1 {
1367                limit
1368            } else {
1369                None
1370            };
1371            match (outer, first.nth) {
1372                (Some(l), Some(n)) => Some(l.max(n)),
1373                (_, Some(n)) => Some(n),
1374                (l, None) => l,
1375            }
1376        } else {
1377            None
1378        };
1379
1380        let phase1: Vec<(usize, AccessibleRef)> =
1381            self.collect_matching_refs_group(&start_ref, &firsts, 0, max_depth_val, phase1_limit)?;
1382
1383        let pid_from_root = root.pid;
1384
1385        // Bucket phase-1 hits by clause so each clause's tail can narrow
1386        // independently. `walk_pos` preserves the doc-order rank from the
1387        // single walk for the final merge.
1388        let mut by_clause: Vec<Vec<(usize, AccessibleRef)>> =
1389            (0..group.clauses.len()).map(|_| Vec::new()).collect();
1390        for (walk_pos, (clause_idx, aref)) in phase1.into_iter().enumerate() {
1391            by_clause[clause_idx].push((walk_pos, aref));
1392        }
1393
1394        // For each clause, build ElementData for its phase-1 hits, then
1395        // narrow through any trailing segments. Single-segment clauses
1396        // skip phase 2 entirely.
1397        //
1398        // Each narrowed result keeps a (walk_pos, ElementData) pair: the
1399        // walk_pos of its phase-1 ancestor is the doc-order anchor we use
1400        // to merge across clauses at the end.
1401        let mut merged: Vec<(usize, ElementData)> = Vec::new();
1402        for (clause_idx, hits) in by_clause.into_iter().enumerate() {
1403            if hits.is_empty() {
1404                continue;
1405            }
1406            let clause = &group.clauses[clause_idx];
1407            // Build ElementData for this clause's phase-1 hits in parallel.
1408            let phase1_data: Vec<(usize, ElementData)> = hits
1409                .par_iter()
1410                .map(|(pos, aref)| {
1411                    // `root` is always present now, so the PID comes from
1412                    // the root element. No need to re-resolve via
1413                    // `get_app_pid` / `get_dbus_pid`.
1414                    (*pos, self.build_element_data(aref, pid_from_root))
1415                })
1416                .collect();
1417
1418            if clause.segments.len() == 1 {
1419                // Apply :nth on the first segment (per-clause, then merged).
1420                let mut candidates = phase1_data;
1421                if let Some(nth) = clause.segments[0].simple.nth {
1422                    if nth <= candidates.len() {
1423                        let kept = candidates.remove(nth - 1);
1424                        candidates.clear();
1425                        candidates.push(kept);
1426                    } else {
1427                        candidates.clear();
1428                    }
1429                }
1430                merged.extend(candidates);
1431                continue;
1432            }
1433
1434            // Multi-segment narrowing: re-use the trait helper. Each
1435            // narrowed result is anchored at the phase-1 ancestor's
1436            // walk_pos so the final sort puts it in doc order against
1437            // other clauses.
1438            for (anchor_pos, head) in phase1_data {
1439                let narrowed = self.narrow_multi_segment(
1440                    vec![head],
1441                    &clause.segments[1..],
1442                    max_depth_val,
1443                    None,
1444                )?;
1445                for n in narrowed {
1446                    merged.push((anchor_pos, n));
1447                }
1448            }
1449        }
1450
1451        // Doc-order merge: stable sort by walk position. Within the same
1452        // walk position multiple clauses can have emitted the same node —
1453        // dedup by AT-SPI identity (`(bus_name, path)`) keeps the first.
1454        merged.sort_by_key(|(pos, _)| *pos);
1455        let mut seen: HashSet<(String, String)> = HashSet::new();
1456        let mut out: Vec<ElementData> = Vec::with_capacity(merged.len());
1457        for (_, data) in merged {
1458            // Use the cached AccessibleRef for identity, not the (handle).
1459            // Handle is freshly minted per `build_element_data` call so it
1460            // would never collide here.
1461            if let Ok(aref) = self.get_cached(data.handle) {
1462                if !seen.insert((aref.bus_name.clone(), aref.path.clone())) {
1463                    continue;
1464                }
1465            }
1466            out.push(data);
1467        }
1468        if let Some(l) = limit {
1469            out.truncate(l);
1470        }
1471        Ok(out)
1472    }
1473
1474    fn get_parent(&self, element: &ElementData) -> Result<Option<ElementData>> {
1475        let aref = self.get_cached(element.handle)?;
1476        match self.get_atspi_parent(&aref)? {
1477            Some(parent_ref) => {
1478                let data = self.build_element_data(&parent_ref, element.pid);
1479                Ok(Some(data))
1480            }
1481            None => Ok(None),
1482        }
1483    }
1484
1485    /// Enumerate top-level applications by listing direct children of the
1486    /// AT-SPI registry root — every running accessibility-enabled app
1487    /// registers a child accessible there. Apps with empty names are
1488    /// filtered out (toolkits sometimes register transient/system
1489    /// accessibles before the real app appears). PID resolution uses the
1490    /// AT-SPI `Application` interface, falling back to the D-Bus owner.
1491    fn list_apps(&self) -> Result<Vec<ElementData>> {
1492        let registry = AccessibleRef {
1493            bus_name: "org.a11y.atspi.Registry".to_string(),
1494            path: "/org/a11y/atspi/accessible/root".to_string(),
1495        };
1496        let children = self.get_atspi_children(&registry)?;
1497
1498        // Filter valid children first, then build in parallel
1499        let valid: Vec<(&AccessibleRef, String)> = children
1500            .iter()
1501            .filter(|c| c.path != "/org/a11y/atspi/null")
1502            .filter_map(|c| {
1503                let name = self.get_name(c).unwrap_or_default();
1504                if name.is_empty() {
1505                    None
1506                } else {
1507                    Some((c, name))
1508                }
1509            })
1510            .collect();
1511
1512        let results: Vec<ElementData> = valid
1513            .par_iter()
1514            .map(|(child, app_name)| {
1515                let pid = self.get_app_pid(child);
1516                let mut data = self.build_element_data(child, pid);
1517                data.name = Some(app_name.clone());
1518                data
1519            })
1520            .collect();
1521
1522        Ok(results)
1523    }
1524
1525    /// Find an application by pid directly against the AT-SPI registry.
1526    ///
1527    /// Differs from filtering `list_apps()` in two ways that matter for a
1528    /// freshly launched process:
1529    ///
1530    /// * No empty-name filter — toolkits can register on the bus before the
1531    ///   app name is set, and a pid match is precise enough on its own.
1532    /// * The not-matched error reports how many registry entries were
1533    ///   examined and how many had no resolvable pid (the misreported-pid
1534    ///   bridge quirk `get_app_pid` documents), so a timeout on CI says why
1535    ///   the app was invisible instead of just "not found".
1536    fn app_by_pid(&self, pid: u32) -> Result<ElementData> {
1537        let registry = AccessibleRef {
1538            bus_name: "org.a11y.atspi.Registry".to_string(),
1539            path: "/org/a11y/atspi/accessible/root".to_string(),
1540        };
1541        let children = self.get_atspi_children(&registry)?;
1542
1543        let mut total = 0usize;
1544        let mut unresolved = 0usize;
1545        for child in children.iter().filter(|c| c.path != "/org/a11y/atspi/null") {
1546            total += 1;
1547            match self.get_app_pid(child) {
1548                Some(p) if p == pid => {
1549                    let mut data = self.build_element_data(child, Some(p));
1550                    // Mirror list_apps: prefer the registry-reported name.
1551                    let name = self.get_name(child).unwrap_or_default();
1552                    if !name.is_empty() {
1553                        data.name = Some(name);
1554                    }
1555                    return Ok(data);
1556                }
1557                Some(_) => {}
1558                None => unresolved += 1,
1559            }
1560        }
1561        Err(
1562            Error::selector_not_matched(format!("application[pid={pid}]")).diagnose(
1563                xa11y_core::Diagnosis {
1564                    last_observed: Some(format!(
1565                        "{total} AT-SPI registry entries examined, {unresolved} without a \
1566                         resolvable pid"
1567                    )),
1568                    ..Default::default()
1569                },
1570            ),
1571        )
1572    }
1573
1574    fn press(&self, element: &ElementData) -> Result<()> {
1575        let target = self.get_cached(element.handle)?;
1576        // Fast path: the widget exposes `press` on its own Action interface.
1577        if let Ok(index) = self.get_action_index(element.handle, "press") {
1578            return self.do_atspi_action_by_index(&target, index);
1579        }
1580        // TENET-BREAK(1): substitute target. Human approval granted for this
1581        // break (see batch B6 / PR #125 / commit daeaf59). Justification: GTK4
1582        // menu-button widgets (GtkMenuButton, AdwMenuButton, AdwSplitButton)
1583        // expose their AT-SPI Action interface on an *inner* toggle-button
1584        // child, not the outer push-button accessible the app author addresses
1585        // by name. Without this workaround, `press()` silently does nothing on
1586        // every GtkMenuButton in every stock GNOME app (Calculator, Text
1587        // Editor, Logs, …). Alternatives considered and rejected:
1588        //   1. Expose the inner widget in the tree — breaks AT-SPI tree
1589        //      fidelity and leaks a GTK implementation detail into every
1590        //      consumer.
1591        //   2. Return ActionNotSupported — every GTK consumer would have to
1592        //      reimplement the same subtree search to work around it.
1593        // The break is narrowly scoped: gated on (a) the owning toolkit being
1594        // GTK and (b) the outer role being Role::Button (push-button, which is
1595        // what all three menu-button variants present as). Non-GtkMenuButton
1596        // roles and non-GTK toolkits continue to fail-fast with
1597        // ActionNotSupported.
1598        if element.role == Role::Button && self.is_gtk_toolkit(&target) {
1599            let outer_name = self.get_name(&target).unwrap_or_default();
1600            if let Some((inner, index)) = self.find_gtk_press_fallback(&target, &outer_name) {
1601                return self.do_atspi_action_by_index(&inner, index);
1602            }
1603        }
1604        Err(Error::ActionNotSupported {
1605            action: "press".to_string(),
1606            role: element.role,
1607        })
1608    }
1609
1610    fn focus(&self, element: &ElementData) -> Result<()> {
1611        let target = self.get_cached(element.handle)?;
1612        // Try Component.GrabFocus first, then fall back to stored action index.
1613        // GrabFocus returns a boolean indicating success — we must check it.
1614        // Fixes GitHub issue #98.
1615        if let Ok(proxy) =
1616            self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Component")
1617        {
1618            if let Ok(reply) = proxy.call_method("GrabFocus", &()) {
1619                // GrabFocus returns boolean: true if focus was grabbed, false otherwise
1620                if let Ok(true) = reply.body().deserialize::<bool>() {
1621                    return Ok(());
1622                }
1623                // GrabFocus returned false — fall through to action index fallback
1624            }
1625        }
1626        if let Ok(index) = self.get_action_index(element.handle, "focus") {
1627            return self.do_atspi_action_by_index(&target, index);
1628        }
1629        Err(Error::ActionNotSupported {
1630            action: "focus".to_string(),
1631            role: element.role,
1632        })
1633    }
1634
1635    fn blur(&self, element: &ElementData) -> Result<()> {
1636        let target = self.get_cached(element.handle)?;
1637        // Grab focus on parent element to blur the current one. We propagate
1638        // every failure — no silent fallbacks (tenet 1): callers need to see
1639        // when blur can't do anything useful.
1640        if let Some(parent_ref) = self.get_atspi_parent(&target)? {
1641            if parent_ref.path != "/org/a11y/atspi/null" {
1642                let p = self.make_proxy(
1643                    &parent_ref.bus_name,
1644                    &parent_ref.path,
1645                    "org.a11y.atspi.Component",
1646                )?;
1647                p.call_method("GrabFocus", &())
1648                    .map_err(|e| Error::Platform {
1649                        code: -1,
1650                        message: format!("Component.GrabFocus on parent failed: {}", e),
1651                    })?;
1652                return Ok(());
1653            }
1654        }
1655        Err(Error::ActionNotSupported {
1656            action: "blur".to_string(),
1657            role: element.role,
1658        })
1659    }
1660
1661    fn toggle(&self, element: &ElementData) -> Result<()> {
1662        let target = self.get_cached(element.handle)?;
1663        // Fast path: the widget exposes the literal AT-SPI action name "toggle"
1664        // (or one of its toolkit aliases — "check" / "uncheck" — both
1665        // canonicalised to "toggle" by map_atspi_action_name during cache
1666        // population).
1667        if let Ok(index) = self.get_action_index(element.handle, "toggle") {
1668            return self.do_atspi_action_by_index(&target, index);
1669        }
1670        // Fallback for AccessKit-backed apps. accesskit_unix's AT-SPI bridge
1671        // hard-codes the action name as "click" for every clickable node
1672        // regardless of role — see platforms/atspi-common/src/node.rs in
1673        // AccessKit. That means egui, eframe, winit-based apps, Bevy, Tauri
1674        // (when using AccessKit) and any other AccessKit consumer never
1675        // advertise "toggle" for CheckBox/RadioButton/Switch, even though
1676        // activating those widgets via "click" is functionally a toggle on
1677        // every platform. Without this fallback, xa11y.toggle() is
1678        // unreachable on every AccessKit-on-Linux widget.
1679        //
1680        // This is tenet-3-consistent: the semantic verb `toggle` on a
1681        // toggleable role means "activate this toggleable element," and on
1682        // Linux the canonical AccessKit implementation of that is the same
1683        // action node entry we'd dispatch for press(). It's the mirror image
1684        // of the Windows `press` dispatch (uia.rs) which fans out to Invoke,
1685        // Toggle, SelectionItem.Select, or ExpandCollapse depending on the
1686        // element's primary-activation pattern.
1687        //
1688        // Narrowly scoped: only fires for toggleable primary-activation
1689        // roles. Other roles still fail-fast with ActionNotSupported so a
1690        // misuse of toggle() on, e.g., a Button does not silently dispatch
1691        // press().
1692        if matches!(
1693            element.role,
1694            Role::CheckBox | Role::RadioButton | Role::Switch
1695        ) {
1696            if let Ok(index) = self.get_action_index(element.handle, "press") {
1697                return self.do_atspi_action_by_index(&target, index);
1698            }
1699        }
1700        Err(Error::ActionNotSupported {
1701            action: "toggle".to_string(),
1702            role: element.role,
1703        })
1704    }
1705
1706    fn select(&self, element: &ElementData) -> Result<()> {
1707        let target = self.get_cached(element.handle)?;
1708        let index = self
1709            .get_action_index(element.handle, "select")
1710            .map_err(|_| Error::ActionNotSupported {
1711                action: "select".to_string(),
1712                role: element.role,
1713            })?;
1714        self.do_atspi_action_by_index(&target, index)
1715    }
1716
1717    fn expand(&self, element: &ElementData) -> Result<()> {
1718        let target = self.get_cached(element.handle)?;
1719        let index = self
1720            .get_action_index(element.handle, "expand")
1721            .map_err(|_| Error::ActionNotSupported {
1722                action: "expand".to_string(),
1723                role: element.role,
1724            })?;
1725        self.do_atspi_action_by_index(&target, index)
1726    }
1727
1728    fn collapse(&self, element: &ElementData) -> Result<()> {
1729        let target = self.get_cached(element.handle)?;
1730        let index = self
1731            .get_action_index(element.handle, "collapse")
1732            .map_err(|_| Error::ActionNotSupported {
1733                action: "collapse".to_string(),
1734                role: element.role,
1735            })?;
1736        self.do_atspi_action_by_index(&target, index)
1737    }
1738
1739    fn show_menu(&self, element: &ElementData) -> Result<()> {
1740        let target = self.get_cached(element.handle)?;
1741        let index = self
1742            .get_action_index(element.handle, "show_menu")
1743            .map_err(|_| Error::ActionNotSupported {
1744                action: "show_menu".to_string(),
1745                role: element.role,
1746            })?;
1747        self.do_atspi_action_by_index(&target, index)
1748    }
1749
1750    fn increment(&self, element: &ElementData) -> Result<()> {
1751        let target = self.get_cached(element.handle)?;
1752        // Try stored AT-SPI2 action index first, fall back to Value interface
1753        if let Ok(index) = self.get_action_index(element.handle, "increment") {
1754            return self.do_atspi_action_by_index(&target, index);
1755        }
1756        let proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Value")?;
1757        let current: f64 = proxy
1758            .get_property("CurrentValue")
1759            .map_err(|e| Error::Platform {
1760                code: -1,
1761                message: format!("Value.CurrentValue failed: {}", e),
1762            })?;
1763        let step: f64 = proxy.get_property("MinimumIncrement").unwrap_or(1.0);
1764        let step = if step <= 0.0 { 1.0 } else { step };
1765        proxy
1766            .set_property("CurrentValue", current + step)
1767            .map_err(|e| Error::Platform {
1768                code: -1,
1769                message: format!("Value.SetCurrentValue failed: {}", e),
1770            })
1771    }
1772
1773    fn decrement(&self, element: &ElementData) -> Result<()> {
1774        let target = self.get_cached(element.handle)?;
1775        if let Ok(index) = self.get_action_index(element.handle, "decrement") {
1776            return self.do_atspi_action_by_index(&target, index);
1777        }
1778        let proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Value")?;
1779        let current: f64 = proxy
1780            .get_property("CurrentValue")
1781            .map_err(|e| Error::Platform {
1782                code: -1,
1783                message: format!("Value.CurrentValue failed: {}", e),
1784            })?;
1785        let step: f64 = proxy.get_property("MinimumIncrement").unwrap_or(1.0);
1786        let step = if step <= 0.0 { 1.0 } else { step };
1787        proxy
1788            .set_property("CurrentValue", current - step)
1789            .map_err(|e| Error::Platform {
1790                code: -1,
1791                message: format!("Value.SetCurrentValue failed: {}", e),
1792            })
1793    }
1794
1795    fn scroll_into_view(&self, element: &ElementData) -> Result<()> {
1796        let target = self.get_cached(element.handle)?;
1797        let proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Component")?;
1798        proxy
1799            .call_method("ScrollTo", &(0u32,))
1800            .map_err(|e| Error::Platform {
1801                code: -1,
1802                message: format!("ScrollTo failed: {}", e),
1803            })?;
1804        Ok(())
1805    }
1806
1807    fn set_value(&self, element: &ElementData, value: &str) -> Result<()> {
1808        let target = self.get_cached(element.handle)?;
1809        let proxy = self
1810            .make_proxy(
1811                &target.bus_name,
1812                &target.path,
1813                "org.a11y.atspi.EditableText",
1814            )
1815            .map_err(|_| Error::TextValueNotSupported)?;
1816        // Try SetTextContents first (WebKit2GTK exposes this but not InsertText).
1817        if proxy.call_method("SetTextContents", &(value,)).is_ok() {
1818            return Ok(());
1819        }
1820        // Fall back to delete-then-insert for other AT-SPI2 implementations.
1821        // Capture the underlying D-Bus error so callers can distinguish an
1822        // absent `EditableText` interface (common on Chromium — the Chrome
1823        // URL bar only exposes read-only `Text`; see issue #101) from other
1824        // failures. Collapsing to `TextValueNotSupported` hides the reason.
1825        let classify_editable_text_error = |op: &str, e: zbus::Error| -> Error {
1826            let msg = e.to_string();
1827            if msg.contains("UnknownMethod") || msg.contains("UnknownInterface") {
1828                Error::TextValueNotSupported
1829            } else {
1830                Error::Platform {
1831                    code: -1,
1832                    message: format!("EditableText.{} failed: {}", op, msg),
1833                }
1834            }
1835        };
1836        if let Err(e) = proxy.call_method("DeleteText", &(0i32, i32::MAX)) {
1837            return Err(classify_editable_text_error("DeleteText", e));
1838        }
1839        if let Err(e) = proxy.call_method("InsertText", &(0i32, value, value.len() as i32)) {
1840            return Err(classify_editable_text_error("InsertText", e));
1841        }
1842        Ok(())
1843    }
1844
1845    fn set_numeric_value(&self, element: &ElementData, value: f64) -> Result<()> {
1846        let target = self.get_cached(element.handle)?;
1847        let proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Value")?;
1848        proxy
1849            .set_property("CurrentValue", value)
1850            .map_err(|e| Error::Platform {
1851                code: -1,
1852                message: format!("SetValue failed: {}", e),
1853            })
1854    }
1855
1856    fn type_text(&self, element: &ElementData, text: &str) -> Result<()> {
1857        let target = self.get_cached(element.handle)?;
1858        // Insert text via EditableText interface (accessibility API, not input simulation).
1859        // Get cursor position from Text interface, then insert at that position.
1860        let text_proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Text");
1861        let insert_pos = text_proxy
1862            .as_ref()
1863            .ok()
1864            .and_then(|p| p.get_property::<i32>("CaretOffset").ok())
1865            .unwrap_or(-1); // -1 = append at end
1866
1867        let proxy = self
1868            .make_proxy(
1869                &target.bus_name,
1870                &target.path,
1871                "org.a11y.atspi.EditableText",
1872            )
1873            .map_err(|_| Error::TextValueNotSupported)?;
1874        let pos = if insert_pos >= 0 {
1875            insert_pos
1876        } else {
1877            i32::MAX
1878        };
1879        proxy
1880            .call_method("InsertText", &(pos, text, text.len() as i32))
1881            .map_err(|e| Error::Platform {
1882                code: -1,
1883                message: format!("EditableText.InsertText failed: {}", e),
1884            })?;
1885        Ok(())
1886    }
1887
1888    fn set_text_selection(&self, element: &ElementData, start: u32, end: u32) -> Result<()> {
1889        let target = self.get_cached(element.handle)?;
1890        let proxy = self.make_proxy(&target.bus_name, &target.path, "org.a11y.atspi.Text")?;
1891        proxy
1892            .call_method("SetSelection", &(0i32, start as i32, end as i32))
1893            .map_err(|e| Error::Platform {
1894                code: -1,
1895                message: format!("Text.SetSelection failed: {}", e),
1896            })?;
1897        Ok(())
1898    }
1899
1900    fn perform_action(&self, element: &ElementData, action: &str) -> Result<()> {
1901        match action {
1902            "press" => self.press(element),
1903            "focus" => self.focus(element),
1904            "blur" => self.blur(element),
1905            "toggle" => self.toggle(element),
1906            "select" => self.select(element),
1907            "expand" => self.expand(element),
1908            "collapse" => self.collapse(element),
1909            "show_menu" => self.show_menu(element),
1910            "increment" => self.increment(element),
1911            "decrement" => self.decrement(element),
1912            "scroll_into_view" => self.scroll_into_view(element),
1913            _ => Err(Error::ActionNotSupported {
1914                action: action.to_string(),
1915                role: element.role,
1916            }),
1917        }
1918    }
1919
1920    fn subscribe(&self, element: &ElementData) -> Result<Subscription> {
1921        let pid = element.pid.ok_or(Error::Platform {
1922            code: -1,
1923            message: "Element has no PID for subscribe".to_string(),
1924        })?;
1925        let app_name = element.name.clone().unwrap_or_default();
1926        crate::events::subscribe_for_pid(self, pid, app_name)
1927    }
1928}
1929
1930/// Whether a role typically has text or Value interface content.
1931/// Container/structural roles are skipped to save D-Bus round-trips.
1932fn role_has_value(role: Role) -> bool {
1933    !matches!(
1934        role,
1935        Role::Application
1936            | Role::Window
1937            | Role::Dialog
1938            | Role::Group
1939            | Role::MenuBar
1940            | Role::Toolbar
1941            | Role::TabGroup
1942            | Role::SplitGroup
1943            | Role::Table
1944            | Role::TableRow
1945            | Role::Separator
1946    )
1947}
1948
1949/// Whether a role typically supports actions via the Action interface.
1950/// Container and display-only roles are skipped to save D-Bus round-trips.
1951fn role_has_actions(role: Role) -> bool {
1952    matches!(
1953        role,
1954        Role::Button
1955            | Role::CheckBox
1956            | Role::RadioButton
1957            | Role::MenuItem
1958            | Role::Link
1959            | Role::ComboBox
1960            | Role::TextField
1961            | Role::TextArea
1962            | Role::SpinButton
1963            | Role::Tab
1964            | Role::TreeItem
1965            | Role::ListItem
1966            | Role::ScrollBar
1967            | Role::Slider
1968            | Role::Menu
1969            | Role::Image
1970            | Role::Unknown
1971    )
1972}
1973
1974/// Map AT-SPI2 role name to xa11y Role.
1975pub(crate) fn map_atspi_role(role_name: &str) -> Role {
1976    match role_name.to_lowercase().as_str() {
1977        "application" => Role::Application,
1978        "window" | "frame" => Role::Window,
1979        "dialog" | "file chooser" => Role::Dialog,
1980        "alert" | "notification" => Role::Alert,
1981        "push button" | "push button menu" => Role::Button,
1982        "toggle button" => Role::Switch,
1983        "check box" | "check menu item" => Role::CheckBox,
1984        "radio button" | "radio menu item" => Role::RadioButton,
1985        "entry" | "password text" => Role::TextField,
1986        "spin button" | "spinbutton" => Role::SpinButton,
1987        // "textbox" is the ARIA role name returned by WebKit2GTK for both
1988        // <input type="text"> and <textarea>.  Map to TextArea here so the
1989        // multi-line refinement below can downgrade single-line ones to TextField.
1990        "text" | "textbox" => Role::TextArea,
1991        "label" | "static" | "caption" => Role::StaticText,
1992        "combo box" | "combobox" => Role::ComboBox,
1993        // "listbox" is the ARIA role name returned by WebKit2GTK for role="listbox".
1994        "list" | "list box" | "listbox" => Role::List,
1995        "list item" => Role::ListItem,
1996        "menu" => Role::Menu,
1997        "menu item" | "tearoff menu item" => Role::MenuItem,
1998        "menu bar" => Role::MenuBar,
1999        "page tab" => Role::Tab,
2000        "page tab list" => Role::TabGroup,
2001        "table" | "tree table" => Role::Table,
2002        "table row" => Role::TableRow,
2003        "table cell" | "table column header" | "table row header" => Role::TableCell,
2004        "tool bar" => Role::Toolbar,
2005        "scroll bar" => Role::ScrollBar,
2006        "slider" => Role::Slider,
2007        "image" | "icon" | "desktop icon" => Role::Image,
2008        "link" => Role::Link,
2009        "panel" | "section" | "form" | "filler" | "viewport" | "scroll pane" => Role::Group,
2010        "progress bar" => Role::ProgressBar,
2011        "tree item" => Role::TreeItem,
2012        "document web" | "document frame" => Role::WebArea,
2013        "heading" => Role::Heading,
2014        "separator" => Role::Separator,
2015        "split pane" => Role::SplitGroup,
2016        "tooltip" | "tool tip" => Role::Tooltip,
2017        "status bar" | "statusbar" => Role::Status,
2018        "landmark" | "navigation" => Role::Navigation,
2019        _ => xa11y_core::unknown_role(role_name),
2020    }
2021}
2022
2023/// Map AT-SPI2 numeric role (AtspiRole enum) to xa11y Role.
2024/// Values from atspi-common Role enum (repr(u32)).
2025pub(crate) fn map_atspi_role_number(role: u32) -> Role {
2026    match role {
2027        2 => Role::Alert,        // Alert
2028        7 => Role::CheckBox,     // CheckBox
2029        8 => Role::CheckBox,     // CheckMenuItem
2030        11 => Role::ComboBox,    // ComboBox
2031        16 => Role::Dialog,      // Dialog
2032        19 => Role::Dialog,      // FileChooser
2033        20 => Role::Group,       // Filler
2034        23 => Role::Window,      // Frame
2035        26 => Role::Image,       // Icon
2036        27 => Role::Image,       // Image
2037        29 => Role::StaticText,  // Label
2038        31 => Role::List,        // List
2039        32 => Role::ListItem,    // ListItem
2040        33 => Role::Menu,        // Menu
2041        34 => Role::MenuBar,     // MenuBar
2042        35 => Role::MenuItem,    // MenuItem
2043        37 => Role::Tab,         // PageTab
2044        38 => Role::TabGroup,    // PageTabList
2045        39 => Role::Group,       // Panel
2046        40 => Role::TextField,   // PasswordText
2047        42 => Role::ProgressBar, // ProgressBar
2048        43 => Role::Button,      // Button (push button)
2049        44 => Role::RadioButton, // RadioButton
2050        45 => Role::RadioButton, // RadioMenuItem
2051        48 => Role::ScrollBar,   // ScrollBar
2052        49 => Role::Group,       // ScrollPane
2053        50 => Role::Separator,   // Separator
2054        51 => Role::Slider,      // Slider
2055        52 => Role::SpinButton,  // SpinButton
2056        53 => Role::SplitGroup,  // SplitPane
2057        55 => Role::Table,       // Table
2058        56 => Role::TableCell,   // TableCell
2059        57 => Role::TableCell,   // TableColumnHeader
2060        58 => Role::TableCell,   // TableRowHeader
2061        61 => Role::TextArea,    // Text
2062        62 => Role::Switch,      // ToggleButton
2063        63 => Role::Toolbar,     // ToolBar
2064        65 => Role::Group,       // Tree
2065        66 => Role::Table,       // TreeTable
2066        67 => Role::Unknown,     // Unknown
2067        68 => Role::Group,       // Viewport
2068        69 => Role::Window,      // Window
2069        75 => Role::Application, // Application
2070        78 => Role::TextArea, // Embedded — WebKit2GTK uses this for <input type="text"> and <textarea>;
2071        // multi-line refinement below downgrades single-line ones to TextField
2072        79 => Role::TextField,   // Entry
2073        82 => Role::WebArea,     // DocumentFrame
2074        83 => Role::Heading,     // Heading
2075        85 => Role::Group,       // Section
2076        86 => Role::Group,       // RedundantObject
2077        87 => Role::Group,       // Form
2078        88 => Role::Link,        // Link
2079        90 => Role::TableRow,    // TableRow
2080        91 => Role::TreeItem,    // TreeItem
2081        95 => Role::WebArea,     // DocumentWeb
2082        97 => Role::List,        // WebKit2GTK uses this for <ul role="listbox">
2083        98 => Role::List,        // ListBox
2084        93 => Role::Tooltip,     // Tooltip
2085        101 => Role::Alert,      // Notification
2086        116 => Role::StaticText, // Static
2087        129 => Role::Button,     // PushButtonMenu
2088        _ => xa11y_core::unknown_role(&format!("AT-SPI role number {role}")),
2089    }
2090}
2091
2092/// Depth cap for the GTK press-fallback BFS. Wrapper patterns nest at most
2093/// two levels (e.g. `AdwSplitButton` → inner toggle-button → inner label);
2094/// depth 3 covers them with headroom without letting the walk wander.
2095const GTK_FALLBACK_MAX_DEPTH: u32 = 3;
2096
2097/// Hard cap on visited accessibles per fallback resolution. Defensive — the
2098/// depth cap already bounds typical cases to ≤ 20 nodes.
2099const GTK_FALLBACK_MAX_NODES: usize = 200;
2100
2101/// Whether an AT-SPI2 role name represents an activatable widget we are
2102/// willing to invoke via the fallback path. Deliberately narrow: roles that
2103/// could carry destructive or misleading semantics (e.g. `label` with the
2104/// synthesised clipboard/selection actions) are excluded.
2105fn is_actionable_atspi_role(role: &str) -> bool {
2106    matches!(
2107        role,
2108        "push button"
2109            | "toggle button"
2110            | "check box"
2111            | "radio button"
2112            | "menu item"
2113            | "check menu item"
2114            | "radio menu item"
2115            | "link"
2116            | "page tab"
2117            | "tab"
2118            | "list item"
2119            | "tree item"
2120    )
2121}
2122
2123/// Roles the BFS refuses to descend into. Static and decorative roles never
2124/// lead anywhere useful, and `label` in particular carries a fan-out of
2125/// text-editing actions (`clipboard.copy`, `selection.delete`, …) that we
2126/// must never reach via a press heuristic.
2127fn is_never_descend_atspi_role(role: &str) -> bool {
2128    matches!(
2129        role,
2130        "label" | "separator" | "image" | "icon" | "static" | "caption"
2131    )
2132}
2133
2134/// Map an AT-SPI2 action name to its canonical `snake_case` xa11y action name.
2135///
2136/// Toolkit-specific aliases are normalised to the single canonical name:
2137///   "click" / "activate" / "press" / "invoke" / "dodefault" → "press"
2138///   "toggle" / "check" / "uncheck"            → "toggle"
2139///   "expand" / "open"                          → "expand"
2140///   "collapse" / "close"                       → "collapse"
2141///   "menu" / "showmenu" / "showcontextmenu" / "popup" / "show menu" → "show_menu"
2142///   "select"                                    → "select"
2143///   "increment"                                 → "increment"
2144///   "decrement"                                 → "decrement"
2145///
2146/// Returns `None` for unrecognised names.
2147fn map_atspi_action_name(action_name: &str) -> Option<String> {
2148    // Normalise by lowercasing and stripping underscores/spaces so that
2149    // "show_menu", "show menu", "showMenu" and "showContextMenu" all collapse
2150    // to the same canonical form. Chromium is the main motivator: it uses
2151    // `doDefault` as the default activation action on ~190 elements per
2152    // window (Back/Forward buttons, toolbar icons, menu items, sliders,
2153    // notifications) and `showContextMenu` as the context-menu action. The
2154    // previous table dropped both, leaving those elements with no `press`
2155    // mapping at all. See issue #101.
2156    let lower = action_name.to_lowercase();
2157    let collapsed: String = lower.chars().filter(|c| !matches!(c, '_' | ' ')).collect();
2158    let canonical = match collapsed.as_str() {
2159        "click" | "activate" | "press" | "invoke" | "dodefault" => "press",
2160        "toggle" | "check" | "uncheck" => "toggle",
2161        "expand" | "open" => "expand",
2162        "collapse" | "close" => "collapse",
2163        "select" => "select",
2164        "menu" | "showmenu" | "showcontextmenu" | "contextmenu" | "popup" => "show_menu",
2165        "increment" => "increment",
2166        "decrement" => "decrement",
2167        _ => return None,
2168    };
2169    Some(canonical.to_string())
2170}
2171
2172#[cfg(test)]
2173mod tests {
2174    use super::*;
2175
2176    #[test]
2177    fn test_role_mapping() {
2178        assert_eq!(map_atspi_role("push button"), Role::Button);
2179        assert_eq!(map_atspi_role("toggle button"), Role::Switch);
2180        assert_eq!(map_atspi_role("check box"), Role::CheckBox);
2181        assert_eq!(map_atspi_role("entry"), Role::TextField);
2182        assert_eq!(map_atspi_role("label"), Role::StaticText);
2183        assert_eq!(map_atspi_role("window"), Role::Window);
2184        assert_eq!(map_atspi_role("frame"), Role::Window);
2185        assert_eq!(map_atspi_role("dialog"), Role::Dialog);
2186        assert_eq!(map_atspi_role("combo box"), Role::ComboBox);
2187        assert_eq!(map_atspi_role("slider"), Role::Slider);
2188        assert_eq!(map_atspi_role("panel"), Role::Group);
2189        assert_eq!(map_atspi_role("unknown_thing"), Role::Unknown);
2190    }
2191
2192    #[test]
2193    fn test_numeric_role_mapping() {
2194        // ToggleButton (62) must map to Switch, not Button.
2195        // GTK4's Gtk.Switch and Gtk.ToggleButton both report numeric role 62.
2196        assert_eq!(map_atspi_role_number(62), Role::Switch);
2197        // Sanity-check a few well-established numeric mappings.
2198        assert_eq!(map_atspi_role_number(43), Role::Button); // PushButton
2199        assert_eq!(map_atspi_role_number(7), Role::CheckBox);
2200        assert_eq!(map_atspi_role_number(67), Role::Unknown); // AT-SPI Unknown
2201    }
2202
2203    #[test]
2204    fn test_action_name_mapping() {
2205        assert_eq!(map_atspi_action_name("click"), Some("press".to_string()));
2206        assert_eq!(map_atspi_action_name("activate"), Some("press".to_string()));
2207        assert_eq!(map_atspi_action_name("press"), Some("press".to_string()));
2208        assert_eq!(map_atspi_action_name("invoke"), Some("press".to_string()));
2209        // Chromium uses `doDefault` for default activation on ~190 elements.
2210        assert_eq!(
2211            map_atspi_action_name("doDefault"),
2212            Some("press".to_string())
2213        );
2214        assert_eq!(
2215            map_atspi_action_name("do_default"),
2216            Some("press".to_string())
2217        );
2218        assert_eq!(map_atspi_action_name("toggle"), Some("toggle".to_string()));
2219        assert_eq!(map_atspi_action_name("check"), Some("toggle".to_string()));
2220        assert_eq!(map_atspi_action_name("uncheck"), Some("toggle".to_string()));
2221        assert_eq!(map_atspi_action_name("expand"), Some("expand".to_string()));
2222        assert_eq!(map_atspi_action_name("open"), Some("expand".to_string()));
2223        assert_eq!(
2224            map_atspi_action_name("collapse"),
2225            Some("collapse".to_string())
2226        );
2227        assert_eq!(map_atspi_action_name("close"), Some("collapse".to_string()));
2228        assert_eq!(map_atspi_action_name("select"), Some("select".to_string()));
2229        assert_eq!(map_atspi_action_name("menu"), Some("show_menu".to_string()));
2230        assert_eq!(
2231            map_atspi_action_name("showmenu"),
2232            Some("show_menu".to_string())
2233        );
2234        assert_eq!(
2235            map_atspi_action_name("popup"),
2236            Some("show_menu".to_string())
2237        );
2238        assert_eq!(
2239            map_atspi_action_name("show menu"),
2240            Some("show_menu".to_string())
2241        );
2242        // Chrome / Chromium expose the URL-bar context-menu action as
2243        // `showContextMenu`; the previous table missed both spellings.
2244        assert_eq!(
2245            map_atspi_action_name("showContextMenu"),
2246            Some("show_menu".to_string())
2247        );
2248        assert_eq!(
2249            map_atspi_action_name("show_context_menu"),
2250            Some("show_menu".to_string())
2251        );
2252        assert_eq!(
2253            map_atspi_action_name("increment"),
2254            Some("increment".to_string())
2255        );
2256        assert_eq!(
2257            map_atspi_action_name("decrement"),
2258            Some("decrement".to_string())
2259        );
2260        assert_eq!(map_atspi_action_name("foobar"), None);
2261    }
2262
2263    /// All known AT-SPI2 aliases map to one of the well-known action names,
2264    /// and re-mapping the canonical name produces the same canonical name.
2265    #[test]
2266    fn test_action_name_aliases_roundtrip() {
2267        let atspi_names = [
2268            "click",
2269            "activate",
2270            "press",
2271            "invoke",
2272            "doDefault",
2273            "do_default",
2274            "toggle",
2275            "check",
2276            "uncheck",
2277            "expand",
2278            "open",
2279            "collapse",
2280            "close",
2281            "select",
2282            "menu",
2283            "showmenu",
2284            "showContextMenu",
2285            "show_context_menu",
2286            "popup",
2287            "show menu",
2288            "increment",
2289            "decrement",
2290        ];
2291        for name in atspi_names {
2292            let canonical = map_atspi_action_name(name).unwrap_or_else(|| {
2293                panic!("AT-SPI2 name {:?} should map to a canonical name", name)
2294            });
2295            // Re-mapping the canonical name must produce itself.
2296            let back = map_atspi_action_name(&canonical)
2297                .unwrap_or_else(|| panic!("canonical {:?} should map back to itself", canonical));
2298            assert_eq!(
2299                canonical, back,
2300                "AT-SPI2 {:?} -> {:?} -> {:?} (expected {:?})",
2301                name, canonical, back, canonical
2302            );
2303        }
2304    }
2305
2306    /// Case-insensitive mapping works.
2307    #[test]
2308    fn test_action_name_case_insensitive() {
2309        assert_eq!(map_atspi_action_name("Click"), Some("press".to_string()));
2310        assert_eq!(map_atspi_action_name("TOGGLE"), Some("toggle".to_string()));
2311        assert_eq!(
2312            map_atspi_action_name("Increment"),
2313            Some("increment".to_string())
2314        );
2315    }
2316
2317    /// The GTK press-fallback's actionable-role set must include the inner
2318    /// toggle-button pattern used by `GtkMenuButton` / `AdwMenuButton`, plus
2319    /// the other standard activatable roles we're willing to synthesise a
2320    /// click for.
2321    #[test]
2322    fn test_gtk_fallback_actionable_roles() {
2323        for role in [
2324            "push button",
2325            "toggle button",
2326            "check box",
2327            "radio button",
2328            "menu item",
2329            "link",
2330            "tab",
2331            "list item",
2332            "tree item",
2333        ] {
2334            assert!(
2335                is_actionable_atspi_role(role),
2336                "{role:?} should be actionable"
2337            );
2338        }
2339    }
2340
2341    /// Never treat static / decorative accessibles as fallback candidates.
2342    /// Particularly important for `label`, whose synthesised text-editing
2343    /// actions (`clipboard.copy`, `selection.delete`) must never be invoked
2344    /// by a press heuristic.
2345    #[test]
2346    fn test_gtk_fallback_non_actionable_roles() {
2347        for role in [
2348            "label",
2349            "panel",
2350            "filler",
2351            "section",
2352            "group",
2353            "image",
2354            "separator",
2355            "static",
2356            "frame",
2357            "window",
2358        ] {
2359            assert!(
2360                !is_actionable_atspi_role(role),
2361                "{role:?} must not be treated as actionable"
2362            );
2363        }
2364    }
2365
2366    /// The BFS stops at static/decorative roles. `label` in particular must
2367    /// never be descended into — its children are text spans with bogus
2368    /// actions.
2369    #[test]
2370    fn test_gtk_fallback_never_descend_roles() {
2371        for role in ["label", "separator", "image", "icon", "static", "caption"] {
2372            assert!(
2373                is_never_descend_atspi_role(role),
2374                "{role:?} must block BFS descent"
2375            );
2376        }
2377        // Containers — panel / filler / section / group / frame — stay
2378        // walkable so the BFS can reach a wrapped inner actionable.
2379        for role in ["panel", "filler", "section", "group", "frame"] {
2380            assert!(
2381                !is_never_descend_atspi_role(role),
2382                "container role {role:?} must remain descendable"
2383            );
2384        }
2385    }
2386}