Repository navigation
Expand file tree
/
Copy pathatspi.rs
More file actions
2668 lines (2523 loc) · 108 KB
/
Copy pathatspi.rs
File metadata and controls
2668 lines (2523 loc) · 108 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Real AT-SPI2 backend implementation using zbus D-Bus bindings.
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Mutex;
use rayon::prelude::*;
use xa11y_core::{
ElementData, Error, Provider, Rect, Result, Role, StateSet, Subscription, Toggled,
};
use zbus::blocking::{Connection, Proxy};
/// Global handle counter for mapping ElementData back to AccessibleRefs.
static NEXT_HANDLE: AtomicU64 = AtomicU64::new(1);
/// Format a normalized state attribute as the same string `xa11y_core::selector::resolve_attr`
/// would produce, so fast-path matching agrees byte-for-byte with the slow path.
fn state_attr_to_string(name: &str, s: &StateSet) -> Option<String> {
match name {
"enabled" => Some(s.enabled.to_string()),
"visible" => Some(s.visible.to_string()),
"focused" => Some(s.focused.to_string()),
"active" => Some(s.active.to_string()),
"focusable" => Some(s.focusable.to_string()),
"selected" => Some(s.selected.to_string()),
"editable" => Some(s.editable.to_string()),
"modal" => Some(s.modal.to_string()),
"required" => Some(s.required.to_string()),
"busy" => Some(s.busy.to_string()),
"expanded" => s.expanded.map(|b| b.to_string()),
"checked" => s.checked.map(|c| {
match c {
Toggled::On => "on",
Toggled::Off => "off",
Toggled::Mixed => "mixed",
}
.to_string()
}),
_ => None,
}
}
/// Linux accessibility provider using AT-SPI2 over D-Bus.
pub struct LinuxProvider {
a11y_bus: Connection,
/// Cached AT-SPI accessible refs keyed by handle ID.
handle_cache: Mutex<HashMap<u64, AccessibleRef>>,
/// Cached AT-SPI2 action indices keyed by element handle.
/// Maps each action name (snake_case) to the integer index used by `DoAction(i)`.
action_indices: Mutex<HashMap<u64, HashMap<String, i32>>>,
}
/// AT-SPI2 accessible reference: (bus_name, object_path).
#[derive(Debug, Clone)]
pub(crate) struct AccessibleRef {
pub(crate) bus_name: String,
pub(crate) path: String,
}
impl LinuxProvider {
/// Create a new Linux accessibility provider.
///
/// Connects to the AT-SPI2 bus. Falls back to the session bus
/// if the dedicated AT-SPI bus is unavailable.
pub fn new() -> Result<Self> {
let a11y_bus = Self::connect_a11y_bus()?;
Ok(Self {
a11y_bus,
handle_cache: Mutex::new(HashMap::new()),
action_indices: Mutex::new(HashMap::new()),
})
}
pub(crate) fn connect_a11y_bus() -> Result<Connection> {
// Try getting the AT-SPI bus address from the a11y bus launcher,
// then connect to it. If that fails, fall back to the session bus
// (AT-SPI2 may use the session bus directly).
if let Ok(session) = Connection::session() {
let proxy = Proxy::new(&session, "org.a11y.Bus", "/org/a11y/bus", "org.a11y.Bus")
.map_err(|e| Error::Platform {
code: -1,
message: format!("Failed to create a11y bus proxy: {}", e),
})?;
if let Ok(addr_reply) = proxy.call_method("GetAddress", &()) {
if let Ok(address) = addr_reply.body().deserialize::<String>() {
if let Ok(addr) = zbus::Address::try_from(address.as_str()) {
if let Ok(Ok(conn)) =
zbus::blocking::connection::Builder::address(addr).map(|b| b.build())
{
return Ok(conn);
}
}
}
}
// Fall back to session bus
return Ok(session);
}
Connection::session().map_err(|e| Error::Platform {
code: -1,
message: format!("Failed to connect to D-Bus session bus: {}", e),
})
}
fn make_proxy(&self, bus_name: &str, path: &str, interface: &str) -> Result<Proxy<'_>> {
// Use uncached proxy to avoid GetAll calls — Qt's AT-SPI adaptor
// doesn't support GetAll on all objects, causing spurious errors.
zbus::blocking::proxy::Builder::<Proxy>::new(&self.a11y_bus)
.destination(bus_name.to_owned())
.map_err(|e| Error::Platform {
code: -1,
message: format!("Failed to set proxy destination: {}", e),
})?
.path(path.to_owned())
.map_err(|e| Error::Platform {
code: -1,
message: format!("Failed to set proxy path: {}", e),
})?
.interface(interface.to_owned())
.map_err(|e| Error::Platform {
code: -1,
message: format!("Failed to set proxy interface: {}", e),
})?
.cache_properties(zbus::proxy::CacheProperties::No)
.build()
.map_err(|e| Error::Platform {
code: -1,
message: format!("Failed to create proxy: {}", e),
})
}
/// Check whether an accessible object implements a given interface.
/// Queries the AT-SPI GetInterfaces method on the Accessible interface.
fn has_interface(&self, aref: &AccessibleRef, iface: &str) -> bool {
let proxy = match self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Accessible") {
Ok(p) => p,
Err(_) => return false,
};
let reply = match proxy.call_method("GetInterfaces", &()) {
Ok(r) => r,
Err(_) => return false,
};
let interfaces: Vec<String> = match reply.body().deserialize() {
Ok(v) => v,
Err(_) => return false,
};
interfaces.iter().any(|i| i.contains(iface))
}
/// Get the numeric AT-SPI role via GetRole method.
fn get_role_number(&self, aref: &AccessibleRef) -> Result<u32> {
let proxy = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Accessible")?;
let reply = proxy
.call_method("GetRole", &())
.map_err(|e| Error::Platform {
code: -1,
message: format!("GetRole failed: {}", e),
})?;
reply
.body()
.deserialize::<u32>()
.map_err(|e| Error::Platform {
code: -1,
message: format!("GetRole deserialize failed: {}", e),
})
}
/// Get the AT-SPI role name string.
fn get_role_name(&self, aref: &AccessibleRef) -> Result<String> {
let proxy = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Accessible")?;
let reply = proxy
.call_method("GetRoleName", &())
.map_err(|e| Error::Platform {
code: -1,
message: format!("GetRoleName failed: {}", e),
})?;
reply
.body()
.deserialize::<String>()
.map_err(|e| Error::Platform {
code: -1,
message: format!("GetRoleName deserialize failed: {}", e),
})
}
/// Detect Chromium/Electron's "accessibility bridge disabled" signature.
///
/// On Linux, Chromium-based apps (Electron, Chrome, VS Code, …) register
/// with AT-SPI but expose only an `application → frame` skeleton — the
/// frame's children list is empty (just the `/org/a11y/atspi/null`
/// sentinel) — unless the process was launched with the
/// `--force-renderer-accessibility` flag. Without this detection, callers
/// see zero results and assume their selector is wrong.
///
/// Call this after observing an empty filtered children list. Returns an
/// error only when the parent is a window/frame whose AT-SPI bus reports
/// `Application.ToolkitName == "Chromium"`; otherwise returns `Ok(())` so
/// genuinely empty windows in other toolkits stay valid.
///
/// `role_hint` lets callers that already know the role skip a `GetRole`
/// round-trip.
fn check_chromium_a11y_enabled(
&self,
parent: &AccessibleRef,
role_hint: Option<Role>,
) -> Result<()> {
let app_root = AccessibleRef {
bus_name: parent.bus_name.clone(),
path: "/org/a11y/atspi/accessible/root".to_string(),
};
let toolkit = match self
.make_proxy(
&app_root.bus_name,
&app_root.path,
"org.a11y.atspi.Application",
)
.ok()
.and_then(|proxy| proxy.get_property::<String>("ToolkitName").ok())
{
Some(t) => t,
None => return Ok(()),
};
if !toolkit.eq_ignore_ascii_case("Chromium") {
return Ok(());
}
let role = role_hint.unwrap_or_else(|| self.resolve_role(parent));
if role != Role::Window {
return Ok(());
}
let app_name = self.get_name(&app_root).unwrap_or_default();
Err(Error::AccessibilityNotEnabled {
app: app_name,
instructions: "Chromium/Electron app exposes an empty accessibility tree on Linux. \
Relaunch with `--force-renderer-accessibility` (or set the env var \
`ACCESSIBILITY_ENABLED=1`) so the renderer accessibility bridge is initialised."
.to_string(),
})
}
/// Get the name of an accessible element.
fn get_name(&self, aref: &AccessibleRef) -> Result<String> {
let proxy = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Accessible")?;
proxy
.get_property::<String>("Name")
.map_err(|e| Error::Platform {
code: -1,
message: format!("Get Name property failed: {}", e),
})
}
/// Get the description of an accessible element.
fn get_description(&self, aref: &AccessibleRef) -> Result<String> {
let proxy = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Accessible")?;
proxy
.get_property::<String>("Description")
.map_err(|e| Error::Platform {
code: -1,
message: format!("Get Description property failed: {}", e),
})
}
/// Get children via the GetChildren method.
/// AT-SPI registryd doesn't always implement standard D-Bus Properties,
/// so we use GetChildren which is more reliable.
fn get_atspi_children(&self, aref: &AccessibleRef) -> Result<Vec<AccessibleRef>> {
let proxy = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Accessible")?;
let reply = proxy
.call_method("GetChildren", &())
.map_err(|e| Error::Platform {
code: -1,
message: format!("GetChildren failed: {}", e),
})?;
let children: Vec<(String, zbus::zvariant::OwnedObjectPath)> =
reply.body().deserialize().map_err(|e| Error::Platform {
code: -1,
message: format!("GetChildren deserialize failed: {}", e),
})?;
Ok(children
.into_iter()
.map(|(bus_name, path)| AccessibleRef {
bus_name,
path: path.to_string(),
})
.collect())
}
/// Get the state set as raw u32 values.
fn get_state(&self, aref: &AccessibleRef) -> Result<Vec<u32>> {
let proxy = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Accessible")?;
let reply = proxy
.call_method("GetState", &())
.map_err(|e| Error::Platform {
code: -1,
message: format!("GetState failed: {}", e),
})?;
reply
.body()
.deserialize::<Vec<u32>>()
.map_err(|e| Error::Platform {
code: -1,
message: format!("GetState deserialize failed: {}", e),
})
}
/// Return true if the element reports the AT-SPI MULTI_LINE state.
/// Used to distinguish multi-line text areas (TextArea) from single-line
/// text inputs (TextField), since both use the AT-SPI "text" role name.
/// Note: Qt's AT-SPI bridge does not reliably set SINGLE_LINE, so we
/// check MULTI_LINE and default to TextField when neither is set.
fn is_multi_line(&self, aref: &AccessibleRef) -> bool {
let state_bits = self.get_state(aref).unwrap_or_default();
let bits: u64 = if state_bits.len() >= 2 {
(state_bits[0] as u64) | ((state_bits[1] as u64) << 32)
} else if state_bits.len() == 1 {
state_bits[0] as u64
} else {
0
};
// ATSPI_STATE_MULTI_LINE = 17 in AtspiStateType enum
const MULTI_LINE: u64 = 1 << 17;
(bits & MULTI_LINE) != 0
}
/// Resolve TextField vs TextArea using the MULTI_LINE state, regardless of
/// the coarse role we started with. Different toolkits expose text inputs
/// under different AT-SPI roles ("text", "textbox", "entry", "embedded",
/// numeric 61/78/79), and WebKitGTK has changed mapping between versions
/// (e.g. 2.50 → 2.52 swapped what role textarea reports). MULTI_LINE is
/// the cross-toolkit invariant, so we let it decide.
///
/// For any other coarse role, returns it unchanged.
fn refine_text_role(&self, coarse: Role, aref: &AccessibleRef) -> Role {
match coarse {
Role::TextArea | Role::TextField => {
if self.is_multi_line(aref) {
Role::TextArea
} else {
Role::TextField
}
}
other => other,
}
}
/// Get bounds via Component interface.
/// Checks for Component support first to avoid GTK CRITICAL warnings
/// on objects (e.g. TreeView cell renderers) that don't implement it.
fn get_extents(&self, aref: &AccessibleRef) -> Option<Rect> {
if !self.has_interface(aref, "Component") {
return None;
}
let proxy = self
.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Component")
.ok()?;
// GetExtents(coord_type: u32) -> (x, y, width, height)
// coord_type 0 = screen coordinates
let reply = proxy.call_method("GetExtents", &(0u32,)).ok()?;
let (x, y, w, h): (i32, i32, i32, i32) = reply.body().deserialize().ok()?;
if w <= 0 && h <= 0 {
return None;
}
// AT-SPI screen extents are physical device pixels. Convert to logical
// coordinates (the cross-platform contract, same space as the
// screenshot/input layers) using the detected display scale. On the
// common 1.0 case this is a no-op. See `crate::scale`.
Some(
Rect {
x,
y,
width: w.max(0) as u32,
height: h.max(0) as u32,
}
.to_logical(crate::scale::coordinate_scale()),
)
}
/// Get available actions via Action interface, returning both the action list
/// and a map of each action name to its AT-SPI2 integer index for direct `DoAction(i)`.
///
/// Probes the interface directly rather than relying on the Interfaces property,
/// which some AT-SPI adapters (e.g. AccessKit) don't expose.
fn get_actions(&self, aref: &AccessibleRef) -> (Vec<String>, HashMap<String, i32>) {
let mut actions = Vec::new();
let mut indices = HashMap::new();
// Try Action interface directly
if let Ok(proxy) = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Action") {
// NActions may be returned as i32 or u32 depending on AT-SPI implementation.
let n_actions = proxy
.get_property::<i32>("NActions")
.or_else(|_| proxy.get_property::<u32>("NActions").map(|n| n as i32))
.unwrap_or(0);
for i in 0..n_actions {
if let Ok(reply) = proxy.call_method("GetName", &(i,)) {
if let Ok(name) = reply.body().deserialize::<String>() {
if let Some(action_name) = map_atspi_action_name(&name) {
if !actions.contains(&action_name) {
indices.insert(action_name.clone(), i);
actions.push(action_name);
}
}
}
}
}
}
// NOTE: We do NOT add implicit "focus" based on Component interface existence.
// On GTK4, GrabFocus() often returns false even when Component interface exists,
// violating design tenet 3 ("if action is listed, calling it must work").
// Only report "focus" if it's explicitly in the AT-SPI Action interface with a
// proper index. This ensures focus() will work when reported.
// Fixes GitHub issue #98.
(actions, indices)
}
/// Return true when the accessible's application identifies itself as GTK
/// via `org.a11y.atspi.Application.ToolkitName`.
///
/// Used to scope the press-fallback heuristic for the
/// AdwMenuButton/GtkMenuButton wrapper pattern; other toolkits are
/// unaffected.
fn is_gtk_toolkit(&self, aref: &AccessibleRef) -> bool {
let app_root = AccessibleRef {
bus_name: aref.bus_name.clone(),
path: "/org/a11y/atspi/accessible/root".to_string(),
};
self.make_proxy(
&app_root.bus_name,
&app_root.path,
"org.a11y.atspi.Application",
)
.ok()
.and_then(|proxy| proxy.get_property::<String>("ToolkitName").ok())
.map(|t| t.eq_ignore_ascii_case("GTK"))
.unwrap_or(false)
}
/// GTK press-fallback resolver.
///
/// Walks the accessible's descendants (BFS, depth-capped) looking for a
/// single activatable child that shares the outer widget's name. Returns
/// the (ref, action_index) pair when exactly one suitable candidate
/// exists at the shallowest matching depth. Returns `None` when the
/// subtree contains nothing suitable or multiple equally plausible
/// candidates — refusing to guess.
///
/// Empirically fixes the `GtkMenuButton` / `AdwMenuButton` wrappers that
/// ship in every stock GNOME app (Calculator, Text Editor, Logs, Clocks,
/// Characters, …).
fn find_gtk_press_fallback(
&self,
outer: &AccessibleRef,
outer_name: &str,
) -> Option<(AccessibleRef, i32)> {
let mut queue: VecDeque<(AccessibleRef, u32)> = VecDeque::new();
queue.push_back((outer.clone(), 0));
let mut visited: usize = 0;
let mut shallowest_depth: Option<u32> = None;
let mut hits: Vec<(AccessibleRef, i32)> = Vec::new();
while let Some((node, depth)) = queue.pop_front() {
// Once we've found the shallowest level with hits, don't look deeper.
if let Some(best) = shallowest_depth {
if depth > best {
continue;
}
}
if visited > GTK_FALLBACK_MAX_NODES {
break;
}
let role_name = if depth == 0 {
String::new()
} else {
visited += 1;
self.get_role_name(&node).unwrap_or_default().to_lowercase()
};
if depth > 0 && is_actionable_atspi_role(&role_name) {
if let Some(idx) = self.gtk_fallback_pick(&node, outer_name) {
match shallowest_depth {
Some(d) if depth < d => {
shallowest_depth = Some(depth);
hits.clear();
hits.push((node.clone(), idx));
}
Some(d) if depth == d => hits.push((node.clone(), idx)),
Some(_) => {}
None => {
shallowest_depth = Some(depth);
hits.push((node.clone(), idx));
}
}
}
}
// Do not descend into static/decorative roles. Descend through
// containers and actionable roles alike (actionable roles may
// themselves wrap an inner actionable — e.g. an AdwSplitButton's
// primary button inside a toggle-button shell).
let stop_descending = depth >= GTK_FALLBACK_MAX_DEPTH
|| (depth > 0 && is_never_descend_atspi_role(&role_name));
if stop_descending {
continue;
}
if let Ok(children) = self.get_atspi_children(&node) {
for c in children {
queue.push_back((c, depth + 1));
}
}
}
if hits.len() == 1 {
Some(hits.into_iter().next().unwrap())
} else {
None
}
}
/// Per-node filter for `find_gtk_press_fallback`. Returns the AT-SPI
/// action index to invoke when `aref` is a valid fallback candidate.
fn gtk_fallback_pick(&self, aref: &AccessibleRef, outer_name: &str) -> Option<i32> {
let (_, index_map) = self.get_actions(aref);
let idx = *index_map.get("press")?;
if !self.is_showing_visible_sensitive(aref) {
return None;
}
// If the outer has a name, require the candidate to share it. Rules
// out unrelated suffix widgets (e.g. a switch inside an AdwActionRow
// that happens to expose `click`).
if !outer_name.is_empty() {
let inner_name = self.get_name(aref).unwrap_or_default();
if !inner_name.is_empty() && inner_name != outer_name {
return None;
}
}
Some(idx)
}
/// True when the accessible's state has SHOWING, VISIBLE, and SENSITIVE
/// set. ENABLED is deliberately excluded: in GTK4 it reflects "has an
/// enabled GAction bound", which is false for the exact widgets we
/// rescue.
fn is_showing_visible_sensitive(&self, aref: &AccessibleRef) -> bool {
let raw = self.get_state(aref).unwrap_or_default();
let bits: u64 = if raw.len() >= 2 {
(raw[0] as u64) | ((raw[1] as u64) << 32)
} else if raw.len() == 1 {
raw[0] as u64
} else {
0
};
const SENSITIVE: u64 = 1 << 24;
const SHOWING: u64 = 1 << 25;
const VISIBLE: u64 = 1 << 30;
(bits & (SHOWING | VISIBLE | SENSITIVE)) == (SHOWING | VISIBLE | SENSITIVE)
}
/// Get value via Value or Text interface.
/// Probes interfaces directly rather than relying on the Interfaces property.
fn get_value(&self, aref: &AccessibleRef) -> Option<String> {
// Try Text interface first for text content (text fields, labels, combo boxes).
// This must come before Value because some AT-SPI adapters (e.g. AccessKit)
// may expose both interfaces, and Value.CurrentValue returns 0.0 for text elements.
let text_value = self.get_text_content(aref);
if text_value.is_some() {
return text_value;
}
// Try Value interface (sliders, progress bars, scroll bars, spinners)
if let Ok(proxy) = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Value") {
if let Ok(val) = proxy.get_property::<f64>("CurrentValue") {
return Some(val.to_string());
}
}
None
}
/// Read text content via the AT-SPI Text interface.
fn get_text_content(&self, aref: &AccessibleRef) -> Option<String> {
let proxy = self
.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Text")
.ok()?;
let char_count: i32 = proxy.get_property("CharacterCount").ok()?;
if char_count > 0 {
let reply = proxy.call_method("GetText", &(0i32, char_count)).ok()?;
let text: String = reply.body().deserialize().ok()?;
if !text.is_empty() {
return Some(text);
}
}
None
}
/// Cache an AccessibleRef and return a new handle ID.
fn cache_element(&self, aref: AccessibleRef) -> u64 {
let handle = NEXT_HANDLE.fetch_add(1, Ordering::Relaxed);
self.handle_cache
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(handle, aref);
handle
}
/// Look up a cached AccessibleRef by handle.
fn get_cached(&self, handle: u64) -> Result<AccessibleRef> {
self.handle_cache
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(&handle)
.cloned()
.ok_or(Error::ElementStale {
selector: format!("handle:{}", handle),
})
}
/// Build an ElementData from an AccessibleRef, caching the ref for later lookup.
///
/// After resolving the role (1-3 sequential D-Bus calls), all remaining
/// property fetches are independent and run in parallel via rayon::join.
fn build_element_data(&self, aref: &AccessibleRef, pid: Option<u32>) -> ElementData {
let role_name = self.get_role_name(aref).unwrap_or_default();
let role_num = self.get_role_number(aref).unwrap_or(0);
let role = {
let by_name = if !role_name.is_empty() {
map_atspi_role(&role_name)
} else {
Role::Unknown
};
let coarse = if by_name != Role::Unknown {
by_name
} else {
map_atspi_role_number(role_num)
};
self.refine_text_role(coarse, aref)
};
// Fetch all independent properties in parallel.
// Left tree: (name+value, description)
// Right tree: ((states, bounds), (actions, numeric_values))
let (
((mut name, value), description),
(
((states, state_bits), bounds),
((actions, action_index_map), (numeric_value, min_value, max_value)),
),
) = rayon::join(
|| {
rayon::join(
|| {
let name = self.get_name(aref).ok().filter(|s| !s.is_empty());
let value = if role_has_value(role) {
self.get_value(aref)
} else {
None
};
(name, value)
},
|| self.get_description(aref).ok().filter(|s| !s.is_empty()),
)
},
|| {
rayon::join(
|| {
rayon::join(
|| self.parse_states_with_bits(aref, role),
|| {
if role != Role::Application {
self.get_extents(aref)
} else {
None
}
},
)
},
|| {
rayon::join(
|| {
if role_has_actions(role) {
self.get_actions(aref)
} else {
(vec![], HashMap::new())
}
},
|| {
if matches!(
role,
Role::Slider
| Role::ProgressBar
| Role::ScrollBar
| Role::SpinButton
) {
if let Ok(proxy) = self.make_proxy(
&aref.bus_name,
&aref.path,
"org.a11y.atspi.Value",
) {
(
proxy.get_property::<f64>("CurrentValue").ok(),
proxy.get_property::<f64>("MinimumValue").ok(),
proxy.get_property::<f64>("MaximumValue").ok(),
)
} else {
(None, None, None)
}
} else {
(None, None, None)
}
},
)
},
)
},
);
// For label/static text elements, AT-SPI may put content in the Text
// interface (returned as value) rather than the Name property.
if name.is_none() && role == Role::StaticText {
if let Some(ref v) = value {
name = Some(v.clone());
}
}
let raw = {
let raw_role = if role_name.is_empty() {
format!("role_num:{}", role_num)
} else {
role_name
};
let mut raw = HashMap::new();
raw.insert("atspi_role".into(), serde_json::Value::String(raw_role));
raw.insert(
"bus_name".into(),
serde_json::Value::String(aref.bus_name.clone()),
);
raw.insert(
"object_path".into(),
serde_json::Value::String(aref.path.clone()),
);
// Preserve unstripped originals so callers who need bidi marks can
// recover them after the strip below.
if let Some(ref n) = name {
raw.insert("atspi_name".into(), serde_json::Value::String(n.clone()));
}
if let Some(ref v) = value {
raw.insert("atspi_value".into(), serde_json::Value::String(v.clone()));
}
if let Some(ref d) = description {
raw.insert(
"atspi_description".into(),
serde_json::Value::String(d.clone()),
);
}
// DEFUNCT (bit 6) marks a dead accessible — the object was
// destroyed provider-side but a reference still resolves. It has
// no cross-platform StateSet field, but it's the key diagnostic
// for stale-reference bugs (e.g. a churning WebKit tree), so
// surface it whenever set.
if (state_bits & (1 << 6)) != 0 {
raw.insert("atspi_defunct".into(), serde_json::Value::Bool(true));
}
raw
};
// Strip Unicode bidi format controls. RTL apps on Linux embed LRM/RLM
// marks into reported strings; the originals are preserved in `raw`.
let name = xa11y_core::text::strip_bidi_opt(name);
let value = xa11y_core::text::strip_bidi_opt(value);
let description = xa11y_core::text::strip_bidi_opt(description);
let handle = self.cache_element(aref.clone());
if !action_index_map.is_empty() {
self.action_indices
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(handle, action_index_map);
}
ElementData {
role,
name,
value,
description,
bounds,
actions,
states,
numeric_value,
min_value,
max_value,
pid,
stable_id: Some(aref.path.clone()),
raw,
handle,
}
}
/// Get the AT-SPI parent of an accessible ref.
fn get_atspi_parent(&self, aref: &AccessibleRef) -> Result<Option<AccessibleRef>> {
// Read the Parent property via the D-Bus Properties interface.
let proxy = self.make_proxy(
&aref.bus_name,
&aref.path,
"org.freedesktop.DBus.Properties",
)?;
let reply = proxy
.call_method("Get", &("org.a11y.atspi.Accessible", "Parent"))
.map_err(|e| Error::Platform {
code: -1,
message: format!("Get Parent property failed: {}", e),
})?;
// The reply is a Variant containing (so) — a struct of (bus_name, object_path)
let variant: zbus::zvariant::OwnedValue =
reply.body().deserialize().map_err(|e| Error::Platform {
code: -1,
message: format!("Parent deserialize variant failed: {}", e),
})?;
let (bus, path): (String, zbus::zvariant::OwnedObjectPath) =
zbus::zvariant::Value::from(variant).try_into().map_err(
|e: zbus::zvariant::Error| Error::Platform {
code: -1,
message: format!("Parent deserialize struct failed: {}", e),
},
)?;
let path_str = path.as_str();
if path_str == "/org/a11y/atspi/null" || bus.is_empty() || path_str.is_empty() {
return Ok(None);
}
// If the parent is the registry root, this is a top-level app — no parent
if path_str == "/org/a11y/atspi/accessible/root" {
return Ok(None);
}
Ok(Some(AccessibleRef {
bus_name: bus,
path: path_str.to_string(),
}))
}
/// Fetch an accessible's AT-SPI2 state bitfield as a single `u64`.
///
/// AT-SPI2 returns states as two `u32`s (low/high words); collapse them
/// into one mask so callers can test bit positions directly.
fn state_bits(&self, aref: &AccessibleRef) -> u64 {
let state_bits = self.get_state(aref).unwrap_or_default();
if state_bits.len() >= 2 {
(state_bits[0] as u64) | ((state_bits[1] as u64) << 32)
} else if state_bits.len() == 1 {
state_bits[0] as u64
} else {
0
}
}
/// Parse AT-SPI2 state bitfield into xa11y StateSet.
fn parse_states(&self, aref: &AccessibleRef, role: Role) -> StateSet {
self.parse_states_with_bits(aref, role).0
}
/// Like [`parse_states`], but also returns the raw AT-SPI state bitset so
/// callers can surface provider-only facts (notably DEFUNCT) that have no
/// cross-platform `StateSet` field.
fn parse_states_with_bits(&self, aref: &AccessibleRef, role: Role) -> (StateSet, u64) {
let bits = self.state_bits(aref);
// AT-SPI2 state bit positions (AtspiStateType enum values)
const ACTIVE: u64 = 1 << 1;
const BUSY: u64 = 1 << 3;
const CHECKED: u64 = 1 << 4;
const EDITABLE: u64 = 1 << 7;
const ENABLED: u64 = 1 << 8;
const EXPANDABLE: u64 = 1 << 9;
const EXPANDED: u64 = 1 << 10;
const FOCUSABLE: u64 = 1 << 11;
const FOCUSED: u64 = 1 << 12;
const MODAL: u64 = 1 << 16;
const SELECTED: u64 = 1 << 23;
const SENSITIVE: u64 = 1 << 24;
const SHOWING: u64 = 1 << 25;
const VISIBLE: u64 = 1 << 30;
const INDETERMINATE: u64 = 1 << 32;
const REQUIRED: u64 = 1 << 33;
let enabled = (bits & ENABLED) != 0 || (bits & SENSITIVE) != 0;
let visible = (bits & VISIBLE) != 0 || (bits & SHOWING) != 0;
let checked = match role {
Role::CheckBox | Role::RadioButton | Role::MenuItem | Role::Switch => {
if (bits & INDETERMINATE) != 0 {
Some(Toggled::Mixed)
} else if (bits & CHECKED) != 0 {
Some(Toggled::On)
} else {
Some(Toggled::Off)
}
}
_ => None,
};
let expanded = if (bits & EXPANDABLE) != 0 {
Some((bits & EXPANDED) != 0)
} else {
None
};
let mut states = StateSet::default();
states.enabled = enabled;
states.visible = visible;
states.focused = (bits & FOCUSED) != 0;
// AT-SPI `ACTIVE` marks the foreground window/frame (see
// `focused_app`, which relies on the same bit).
states.active = (bits & ACTIVE) != 0;
states.checked = checked;
states.selected = (bits & SELECTED) != 0;
states.expanded = expanded;
states.editable = (bits & EDITABLE) != 0;
states.focusable = (bits & FOCUSABLE) != 0;
states.modal = (bits & MODAL) != 0;
states.required = (bits & REQUIRED) != 0;
states.busy = (bits & BUSY) != 0;
(states, bits)
}
/// Find an application by PID.
///
/// Used by `subscribe` to resolve the target app's D-Bus sender name so
/// signal match rules can be scoped to it.
pub(crate) fn find_app_by_pid(&self, pid: u32) -> Result<AccessibleRef> {
let registry = AccessibleRef {
bus_name: "org.a11y.atspi.Registry".to_string(),
path: "/org/a11y/atspi/accessible/root".to_string(),
};
let children = self.get_atspi_children(®istry)?;
for child in &children {
if child.path == "/org/a11y/atspi/null" {
continue;
}
// Prefer D-Bus connection PID — it's authoritative for the
// process owning the bus connection. Application.Id is *not* a
// process pid: AT-SPI assigns it as a registry-local index
// (1, 2, 3, …) for some bridges (notably GTK4), so matching
// against Application.Id alone misses real processes.
if let Some(app_pid) = self.get_dbus_pid(&child.bus_name) {
if app_pid == pid {
return Ok(child.clone());
}
}
// Fall back to Application.Id for adapters that do set it to pid.
if let Ok(proxy) =
self.make_proxy(&child.bus_name, &child.path, "org.a11y.atspi.Application")
{
if let Ok(app_pid) = proxy.get_property::<i32>("Id") {
if app_pid as u32 == pid {
return Ok(child.clone());
}
}
}
}
Err(Error::Platform {
code: -1,
message: format!("No application found with PID {}", pid),
})
}
/// Get PID via D-Bus GetConnectionUnixProcessID.
fn get_dbus_pid(&self, bus_name: &str) -> Option<u32> {
let proxy = self
.make_proxy(
"org.freedesktop.DBus",
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
)
.ok()?;
let reply = proxy
.call_method("GetConnectionUnixProcessID", &(bus_name,))
.ok()?;
let pid: u32 = reply.body().deserialize().ok()?;
if pid > 0 {
Some(pid)
} else {
None
}
}
/// Perform an AT-SPI2 action by its integer index (from discovery).
fn do_atspi_action_by_index(&self, aref: &AccessibleRef, index: i32) -> Result<()> {
let proxy = self.make_proxy(&aref.bus_name, &aref.path, "org.a11y.atspi.Action")?;
proxy
.call_method("DoAction", &(index,))
.map_err(|e| Error::Platform {
code: -1,
message: format!("DoAction({}) failed: {}", index, e),
})?;
Ok(())
}
/// Look up the stored AT-SPI2 action index for the given element and action.
fn get_action_index(&self, handle: u64, action: &str) -> Result<i32> {