Repository navigation
Expand file tree
/
Copy pathax.rs
More file actions
3339 lines (3056 loc) · 126 KB
/
Copy pathax.rs
File metadata and controls
3339 lines (3056 loc) · 126 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
//! macOS AXUIElement-based accessibility provider.
use std::collections::{HashMap, HashSet};
use std::ffi::c_void;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Mutex;
use std::time::{Duration, Instant};
use core_foundation::base::TCFType;
use core_foundation::number::CFNumber;
use core_foundation::string::CFString;
use rayon::prelude::*;
#[cfg(test)]
use xa11y_core::Selector;
use xa11y_core::{
CancelHandle, ElementData, Error, Event, EventKind, EventReceiver, Provider, Rect, Result,
Role, StateFlag, StateSet, Subscription, Toggled,
};
// ── FFI Declarations ──────────────────────────────────────────────────────────
type AXUIElementRef = *const c_void;
type CFTypeRef = *const c_void;
type CFStringRef = *const c_void;
type CFArrayRef = *const c_void;
type CFIndex = isize;
const AX_ERROR_SUCCESS: i32 = 0;
const AX_ERROR_INVALID_UI_ELEMENT: i32 = -25202;
const AX_ERROR_CANNOT_COMPLETE: i32 = -25204;
const AX_ERROR_ACTION_UNSUPPORTED: i32 = -25206;
const AX_ERROR_NOT_IMPLEMENTED: i32 = -25208;
const AX_ERROR_NO_VALUE: i32 = -25212;
const AX_VALUE_CGPOINT: i32 = 1;
const AX_VALUE_CGSIZE: i32 = 2;
const CF_NUMBER_FLOAT64: i32 = 13;
const CF_NUMBER_SINT32: i32 = 3;
#[allow(dead_code)]
const CF_NUMBER_SINT64: i32 = 4;
#[repr(C)]
#[derive(Default)]
struct CGPoint {
x: f64,
y: f64,
}
#[repr(C)]
#[derive(Default)]
struct CGSize {
width: f64,
height: f64,
}
// All CF / AX interop in this file goes through the `safe_*` wrappers defined
// in `exception_safe.m`. Each wrapper runs its underlying call inside an
// Objective-C `@try`/`@catch` so a misbehaving AX value's `-release` /
// `-getTypeID` can't unwind through `extern "C"` frames and abort the
// process. Raw CF / AX symbols (CFRelease, CFRetain, CFGetTypeID,
// CFNumberGetValue, CFBooleanGetValue, CFArrayGetCount,
// CFArrayGetValueAtIndex, CFDictionaryGetValue, CFArrayCreate,
// CFStringGetTypeID, CFNumberGetTypeID, CFBooleanGetTypeID,
// CFArrayGetTypeID, AXIsProcessTrusted) are intentionally NOT declared here
// - if you need a new one, add a `safe_*` wrapper to `exception_safe.m`.
// Enforced by `cargo xtask check-macos-ffi`.
extern "C" {
fn safe_ax_copy_attribute_value(
element: AXUIElementRef,
attribute: CFStringRef,
value: *mut CFTypeRef,
) -> i32;
fn safe_ax_copy_multiple_attribute_values(
element: AXUIElementRef,
attributes: CFArrayRef,
values: *mut CFArrayRef,
) -> i32;
fn safe_ax_copy_action_names(element: AXUIElementRef, names: *mut CFArrayRef) -> i32;
fn safe_ax_perform_action(element: AXUIElementRef, action: CFStringRef) -> i32;
fn safe_ax_set_attribute_value(
element: AXUIElementRef,
attribute: CFStringRef,
value: CFTypeRef,
) -> i32;
fn safe_ax_is_attribute_settable(
element: AXUIElementRef,
attribute: CFStringRef,
settable: *mut bool,
) -> i32;
fn safe_ax_create_application(pid: i32) -> AXUIElementRef;
fn safe_ax_create_system_wide() -> AXUIElementRef;
fn safe_ax_get_pid(element: AXUIElementRef, out_pid: *mut i32) -> i32;
fn safe_ax_value_get_value(value: CFTypeRef, the_type: i32, value_ptr: *mut c_void) -> bool;
fn safe_cg_window_list_copy(option: u32, relative_to: u32) -> CFArrayRef;
fn safe_ax_observer_create(
pid: i32,
callback: unsafe extern "C" fn(CFTypeRef, AXUIElementRef, CFTypeRef, *mut c_void),
observer: *mut CFTypeRef,
) -> i32;
fn safe_ax_observer_add_notification(
observer: CFTypeRef,
element: AXUIElementRef,
notification: CFStringRef,
refcon: *mut c_void,
) -> i32;
fn safe_ax_observer_remove_notification(
observer: CFTypeRef,
element: AXUIElementRef,
notification: CFStringRef,
) -> i32;
fn safe_ax_observer_get_run_loop_source(observer: CFTypeRef) -> CFTypeRef;
fn safe_cf_run_loop_add_source(source: CFTypeRef);
fn safe_cf_run_loop_get_current() -> CFTypeRef;
fn safe_cf_run_loop_run();
fn safe_cf_run_loop_stop(run_loop: CFTypeRef);
fn safe_ax_value_create_cf_range(location: isize, length: isize) -> CFTypeRef;
// CoreFoundation helpers - all calls from ax.rs go through these.
fn safe_cf_retain(cf: CFTypeRef) -> CFTypeRef;
fn safe_cf_release(cf: CFTypeRef);
fn safe_cf_get_type_id(cf: CFTypeRef) -> u64;
fn safe_cf_array_get_count(arr: CFArrayRef) -> CFIndex;
fn safe_cf_array_get_value(arr: CFArrayRef, idx: CFIndex) -> CFTypeRef;
fn safe_cf_boolean_get_value(b: CFTypeRef) -> bool;
fn safe_cf_equal(a: CFTypeRef, b: CFTypeRef) -> bool;
fn safe_cf_number_get_value(num: CFTypeRef, the_type: i32, value_ptr: *mut c_void) -> bool;
fn safe_cf_dict_get_value(dict: CFTypeRef, key: CFTypeRef) -> CFTypeRef;
fn safe_cf_array_create(values: *const CFTypeRef, num_values: CFIndex) -> CFArrayRef;
fn safe_cf_string_get_type_id() -> u64;
fn safe_cf_number_get_type_id() -> u64;
fn safe_cf_boolean_get_type_id() -> u64;
fn safe_cf_array_get_type_id() -> u64;
fn safe_ax_is_process_trusted() -> bool;
#[cfg(test)]
fn test_throw_and_catch_nsexception() -> i32;
}
// ── AXElement RAII Wrapper ────────────────────────────────────────────────────
struct AXElement(AXUIElementRef);
unsafe impl Send for AXElement {}
unsafe impl Sync for AXElement {}
impl AXElement {
fn from_owned(ptr: AXUIElementRef) -> Self {
Self(ptr)
}
fn from_borrowed(ptr: AXUIElementRef) -> Self {
if !ptr.is_null() {
unsafe { safe_cf_retain(ptr) };
}
Self(ptr)
}
fn as_ptr(&self) -> AXUIElementRef {
self.0
}
fn is_null(&self) -> bool {
self.0.is_null()
}
}
impl Clone for AXElement {
fn clone(&self) -> Self {
Self::from_borrowed(self.0)
}
}
impl Drop for AXElement {
fn drop(&mut self) {
if !self.0.is_null() {
unsafe { safe_cf_release(self.0) };
}
}
}
// ── AX Call Counters (test-only) ──────────────────────────────────────────────
/// Atomic counters tracking AX IPC calls. Only compiled in test builds.
/// Used by integration tests to assert that selector optimizations don't
/// regress — call counts should only go down over time.
#[cfg(test)]
pub mod ax_counters {
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Mutex;
/// Individual attribute fetch (AXUIElementCopyAttributeValue).
pub static COPY_ATTR: AtomicU64 = AtomicU64::new(0);
/// Batch attribute fetch (AXUIElementCopyMultipleAttributeValues).
pub static COPY_MULTI_ATTR: AtomicU64 = AtomicU64::new(0);
/// Action names fetch (AXUIElementCopyActionNames).
pub static COPY_ACTIONS: AtomicU64 = AtomicU64::new(0);
/// Serializes counter-based tests (global counters are shared state).
pub static LOCK: Mutex<()> = Mutex::new(());
pub fn reset_all() {
COPY_ATTR.store(0, Ordering::SeqCst);
COPY_MULTI_ATTR.store(0, Ordering::SeqCst);
COPY_ACTIONS.store(0, Ordering::SeqCst);
}
pub fn total() -> u64 {
COPY_ATTR.load(Ordering::SeqCst)
+ COPY_MULTI_ATTR.load(Ordering::SeqCst)
+ COPY_ACTIONS.load(Ordering::SeqCst)
}
pub fn snapshot() -> (u64, u64, u64) {
(
COPY_ATTR.load(Ordering::SeqCst),
COPY_MULTI_ATTR.load(Ordering::SeqCst),
COPY_ACTIONS.load(Ordering::SeqCst),
)
}
}
// ── FFI Wrappers (instrumented in test builds) ──────────────────────────────
#[inline(always)]
fn ffi_copy_attribute_value(
element: AXUIElementRef,
attribute: CFStringRef,
value: *mut CFTypeRef,
) -> i32 {
#[cfg(test)]
ax_counters::COPY_ATTR.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
unsafe { safe_ax_copy_attribute_value(element, attribute, value) }
}
#[inline(always)]
fn ffi_copy_multiple_attribute_values(
element: AXUIElementRef,
attributes: CFArrayRef,
values: *mut CFArrayRef,
) -> i32 {
#[cfg(test)]
ax_counters::COPY_MULTI_ATTR.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
unsafe { safe_ax_copy_multiple_attribute_values(element, attributes, values) }
}
#[inline(always)]
fn ffi_copy_action_names(element: AXUIElementRef, names: *mut CFArrayRef) -> i32 {
#[cfg(test)]
ax_counters::COPY_ACTIONS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
unsafe { safe_ax_copy_action_names(element, names) }
}
// ── Attribute Helpers ─────────────────────────────────────────────────────────
fn ax_attr(element: AXUIElementRef, attribute: &str) -> Option<CFTypeRef> {
let attr = CFString::new(attribute);
let mut value: CFTypeRef = std::ptr::null();
let err =
ffi_copy_attribute_value(element, attr.as_concrete_TypeRef() as CFTypeRef, &mut value);
if err == AX_ERROR_SUCCESS && !value.is_null() {
Some(value)
} else {
None
}
}
fn ax_string(element: AXUIElementRef, attribute: &str) -> Option<String> {
let value = ax_attr(element, attribute)?;
unsafe {
if safe_cf_get_type_id(value) == safe_cf_string_get_type_id() {
let s = CFString::wrap_under_create_rule(value as *const _);
Some(s.to_string())
} else {
safe_cf_release(value);
None
}
}
}
fn ax_bool(element: AXUIElementRef, attribute: &str) -> Option<bool> {
let value = ax_attr(element, attribute)?;
unsafe {
if safe_cf_get_type_id(value) == safe_cf_boolean_get_type_id() {
let b = safe_cf_boolean_get_value(value);
safe_cf_release(value);
Some(b)
} else {
safe_cf_release(value);
None
}
}
}
fn ax_number_f64(element: AXUIElementRef, attribute: &str) -> Option<f64> {
let value = ax_attr(element, attribute)?;
unsafe {
let type_id = safe_cf_get_type_id(value);
// Each branch owns the CFRelease of `value` exactly once: the number
// path releases explicitly after the copy; the string path transfers
// ownership to `CFString::wrap_under_create_rule`, which releases on
// drop; the fall-through releases before returning `None`. The
// previous control flow released in the number branch and then read
// `value` again in the string branch (use-after-free) and released
// it a second time on the fall-through path (double-release).
if type_id == safe_cf_number_get_type_id() {
let mut result: f64 = 0.0;
let ok = safe_cf_number_get_value(
value,
CF_NUMBER_FLOAT64,
&mut result as *mut _ as *mut c_void,
);
safe_cf_release(value);
return if ok { Some(result) } else { None };
}
if type_id == safe_cf_string_get_type_id() {
// `wrap_under_create_rule` adopts the existing +1 retain; the
// resulting `CFString` releases on drop.
let s = CFString::wrap_under_create_rule(value as *const _);
return s.to_string().trim().parse::<f64>().ok();
}
safe_cf_release(value);
None
}
}
#[allow(dead_code)]
fn ax_number_i32(element: AXUIElementRef, attribute: &str) -> Option<i32> {
let value = ax_attr(element, attribute)?;
unsafe {
if safe_cf_get_type_id(value) == safe_cf_number_get_type_id() {
let mut result: i32 = 0;
let ok = safe_cf_number_get_value(
value,
CF_NUMBER_SINT32,
&mut result as *mut _ as *mut c_void,
);
safe_cf_release(value);
if ok {
Some(result)
} else {
None
}
} else {
safe_cf_release(value);
None
}
}
}
#[allow(dead_code)]
fn ax_number_i64(element: AXUIElementRef, attribute: &str) -> Option<i64> {
let value = ax_attr(element, attribute)?;
unsafe {
if safe_cf_get_type_id(value) == safe_cf_number_get_type_id() {
let mut result: i64 = 0;
let ok = safe_cf_number_get_value(
value,
CF_NUMBER_SINT64,
&mut result as *mut _ as *mut c_void,
);
safe_cf_release(value);
if ok {
Some(result)
} else {
None
}
} else {
safe_cf_release(value);
None
}
}
}
fn ax_children(element: AXUIElementRef) -> Vec<AXElement> {
let value = match ax_attr(element, "AXChildren") {
Some(v) => v,
None => return vec![],
};
unsafe {
if safe_cf_get_type_id(value) != safe_cf_array_get_type_id() {
safe_cf_release(value);
return vec![];
}
let count = safe_cf_array_get_count(value);
let mut children = Vec::with_capacity(count as usize);
for i in 0..count {
let child = safe_cf_array_get_value(value, i);
if !child.is_null() {
children.push(AXElement::from_borrowed(child));
}
}
safe_cf_release(value);
children
}
}
fn ax_parent(element: AXUIElementRef) -> Option<AXElement> {
let value = ax_attr(element, "AXParent")?;
// AXParent returns an AXUIElement, which we own via copy attribute
Some(AXElement::from_owned(value as AXUIElementRef))
}
/// Roles whose selection state may live on the container rather than on the
/// element itself. Kept narrow so the container probe never fires for
/// elements that simply have no selection concept.
fn selection_can_come_from_container(role: Role) -> bool {
matches!(role, Role::TableCell | Role::TableRow | Role::ListItem)
}
/// Resolve selection for an element with no `AXSelected` attribute by
/// membership in the nearest ancestor's `AXSelectedChildren`.
///
/// AppKit sets `AXSelected` directly on rows/cells, but some bridges expose
/// selection only container-side: Qt's Cocoa bridge implements no
/// per-element `AXSelected` at all and surfaces `QAccessibleSelectionInterface`
/// as `AXSelectedChildren` on the table — two hops above a cell
/// (cell → row → table). Membership is the platform's canonical reading of
/// per-item selection in that case, not a substitute for it.
///
/// Walks at most `max_hops` ancestors and stops at the first that exposes
/// `AXSelectedChildren`; an empty list there is a definitive "not selected".
/// A chain with no such container yields `false`, matching how the other
/// state attributes degrade when absent.
fn container_selection_contains(element: AXUIElementRef, max_hops: usize) -> bool {
let mut current = match ax_parent(element) {
Some(p) => p,
None => return false,
};
for _ in 0..max_hops {
if let Some(list) = ax_attr(current.as_ptr(), "AXSelectedChildren") {
let contained = unsafe {
if safe_cf_get_type_id(list) == safe_cf_array_get_type_id() {
let count = safe_cf_array_get_count(list);
(0..count).any(|i| {
let item = safe_cf_array_get_value(list, i);
safe_cf_equal(item, element as CFTypeRef)
})
} else {
false
}
};
unsafe { safe_cf_release(list) };
return contained;
}
current = match ax_parent(current.as_ptr()) {
Some(p) => p,
None => return false,
};
}
false
}
fn ax_action_names(element: AXUIElementRef) -> Vec<String> {
let mut names: CFArrayRef = std::ptr::null();
let err = ffi_copy_action_names(element, &mut names);
if err != AX_ERROR_SUCCESS || names.is_null() {
return vec![];
}
unsafe {
let count = safe_cf_array_get_count(names);
let mut result = Vec::with_capacity(count as usize);
for i in 0..count {
let name = safe_cf_array_get_value(names, i);
if !name.is_null() && safe_cf_get_type_id(name) == safe_cf_string_get_type_id() {
let s = CFString::wrap_under_get_rule(name as *const _);
result.push(s.to_string());
}
}
safe_cf_release(names);
result
}
}
fn ax_position(element: AXUIElementRef) -> Option<(f64, f64)> {
let value = ax_attr(element, "AXPosition")?;
let mut point = CGPoint::default();
let ok = unsafe {
safe_ax_value_get_value(value, AX_VALUE_CGPOINT, &mut point as *mut _ as *mut c_void)
};
unsafe { safe_cf_release(value) };
if ok {
Some((point.x, point.y))
} else {
None
}
}
fn ax_size(element: AXUIElementRef) -> Option<(f64, f64)> {
let value = ax_attr(element, "AXSize")?;
let mut size = CGSize::default();
let ok = unsafe {
safe_ax_value_get_value(value, AX_VALUE_CGSIZE, &mut size as *mut _ as *mut c_void)
};
unsafe { safe_cf_release(value) };
if ok {
Some((size.width, size.height))
} else {
None
}
}
fn ax_value_string(element: AXUIElementRef) -> Option<String> {
let value = ax_attr(element, "AXValue")?;
unsafe {
let tid = safe_cf_get_type_id(value);
if tid == safe_cf_string_get_type_id() {
let s = CFString::wrap_under_create_rule(value as *const _);
return Some(s.to_string());
}
if tid == safe_cf_number_get_type_id() {
let mut f: f64 = 0.0;
if safe_cf_number_get_value(value, CF_NUMBER_FLOAT64, &mut f as *mut _ as *mut c_void) {
safe_cf_release(value);
return Some(f.to_string());
}
}
safe_cf_release(value);
None
}
}
fn ax_value_number(element: AXUIElementRef) -> Option<f64> {
let value = ax_attr(element, "AXValue")?;
unsafe {
if safe_cf_get_type_id(value) == safe_cf_number_get_type_id() {
let mut f: f64 = 0.0;
let ok =
safe_cf_number_get_value(value, CF_NUMBER_FLOAT64, &mut f as *mut _ as *mut c_void);
safe_cf_release(value);
if ok {
return Some(f);
}
}
if safe_cf_get_type_id(value) == safe_cf_string_get_type_id() {
let s = CFString::wrap_under_create_rule(value as *const _);
return s.to_string().trim().parse::<f64>().ok();
}
safe_cf_release(value);
None
}
}
fn ax_value_int(element: AXUIElementRef) -> Option<i32> {
let value = ax_attr(element, "AXValue")?;
unsafe {
if safe_cf_get_type_id(value) == safe_cf_number_get_type_id() {
let mut i: i32 = 0;
let ok =
safe_cf_number_get_value(value, CF_NUMBER_SINT32, &mut i as *mut _ as *mut c_void);
safe_cf_release(value);
if ok {
return Some(i);
}
}
safe_cf_release(value);
None
}
}
// ── Batch Attribute Fetch ────────────────────────────────────────────────────
/// Attribute indices into the batch fetch result array.
/// Order must match `BATCH_ATTRS` below.
mod attr_idx {
pub const ROLE: usize = 0;
pub const SUBROLE: usize = 1;
pub const TITLE: usize = 2;
pub const DESCRIPTION: usize = 3;
pub const HELP: usize = 4;
pub const VALUE: usize = 5;
pub const ENABLED: usize = 6;
pub const FOCUSED: usize = 7;
pub const SELECTED: usize = 8;
pub const HIDDEN: usize = 9;
pub const EXPANDED: usize = 10;
pub const MODAL: usize = 11;
pub const POSITION: usize = 12;
pub const SIZE: usize = 13;
pub const IDENTIFIER: usize = 14;
pub const COUNT: usize = 15;
}
/// Raw values returned by a single batch AX fetch. Values are borrowed
/// CFTypeRefs (owned by the CFArray) — valid only while `_values_array`
/// is alive.
struct BatchAttrs {
/// Owning CFArray — values are only valid while this is alive.
_values_array: CFArrayRef,
/// Borrowed pointers into the array (may be null or AXValueIllegalType).
vals: [CFTypeRef; attr_idx::COUNT],
}
impl BatchAttrs {
/// Fetch all element attributes in a single Mach IPC round-trip.
fn fetch(element: AXUIElementRef) -> Option<Self> {
// Build CFArray of attribute name CFStrings.
let attr_names: [CFString; attr_idx::COUNT] = [
CFString::new("AXRole"),
CFString::new("AXSubrole"),
CFString::new("AXTitle"),
CFString::new("AXDescription"),
CFString::new("AXHelp"),
CFString::new("AXValue"),
CFString::new("AXEnabled"),
CFString::new("AXFocused"),
CFString::new("AXSelected"),
CFString::new("AXHidden"),
CFString::new("AXExpanded"),
CFString::new("AXModal"),
CFString::new("AXPosition"),
CFString::new("AXSize"),
CFString::new("AXIdentifier"),
];
let ptrs: Vec<CFTypeRef> = attr_names
.iter()
.map(|s| s.as_concrete_TypeRef() as CFTypeRef)
.collect();
let cf_attrs = unsafe { safe_cf_array_create(ptrs.as_ptr(), ptrs.len() as CFIndex) };
if cf_attrs.is_null() {
return None;
}
let mut values: CFArrayRef = std::ptr::null();
let err = ffi_copy_multiple_attribute_values(element, cf_attrs, &mut values);
unsafe { safe_cf_release(cf_attrs) };
if err != AX_ERROR_SUCCESS || values.is_null() {
return None;
}
let count = unsafe { safe_cf_array_get_count(values) } as usize;
let mut vals = [std::ptr::null(); attr_idx::COUNT];
for (i, slot) in vals.iter_mut().enumerate().take(count.min(attr_idx::COUNT)) {
let v = unsafe { safe_cf_array_get_value(values, i as CFIndex) };
*slot = v;
}
Some(BatchAttrs {
_values_array: values,
vals,
})
}
/// Read a value as a String (CFString).
fn string(&self, idx: usize) -> Option<String> {
let v = self.vals[idx];
if v.is_null() {
return None;
}
unsafe {
if safe_cf_get_type_id(v) == safe_cf_string_get_type_id() {
let s = CFString::wrap_under_get_rule(v as *const _);
Some(s.to_string())
} else {
None
}
}
}
/// Read a value as a bool (CFBoolean).
fn boolean(&self, idx: usize) -> Option<bool> {
let v = self.vals[idx];
if v.is_null() {
return None;
}
unsafe {
if safe_cf_get_type_id(v) == safe_cf_boolean_get_type_id() {
Some(safe_cf_boolean_get_value(v))
} else {
None
}
}
}
/// Read AXValue as a string (handles CFString and CFNumber).
fn value_string(&self) -> Option<String> {
let v = self.vals[attr_idx::VALUE];
if v.is_null() {
return None;
}
unsafe {
let tid = safe_cf_get_type_id(v);
if tid == safe_cf_string_get_type_id() {
let s = CFString::wrap_under_get_rule(v as *const _);
return Some(s.to_string());
}
if tid == safe_cf_number_get_type_id() {
let mut f: f64 = 0.0;
if safe_cf_number_get_value(v, CF_NUMBER_FLOAT64, &mut f as *mut _ as *mut c_void) {
return Some(f.to_string());
}
}
None
}
}
/// Read AXValue as an f64 number.
fn value_number(&self) -> Option<f64> {
let v = self.vals[attr_idx::VALUE];
if v.is_null() {
return None;
}
unsafe {
if safe_cf_get_type_id(v) == safe_cf_number_get_type_id() {
let mut f: f64 = 0.0;
if safe_cf_number_get_value(v, CF_NUMBER_FLOAT64, &mut f as *mut _ as *mut c_void) {
return Some(f);
}
}
if safe_cf_get_type_id(v) == safe_cf_string_get_type_id() {
let s = CFString::wrap_under_get_rule(v as *const _);
return s.to_string().trim().parse::<f64>().ok();
}
None
}
}
/// Read AXValue as an i32 integer.
fn value_int(&self) -> Option<i32> {
let v = self.vals[attr_idx::VALUE];
if v.is_null() {
return None;
}
unsafe {
if safe_cf_get_type_id(v) == safe_cf_number_get_type_id() {
let mut i: i32 = 0;
if safe_cf_number_get_value(v, CF_NUMBER_SINT32, &mut i as *mut _ as *mut c_void) {
return Some(i);
}
}
None
}
}
/// Read AXPosition as (x, y).
fn position(&self) -> Option<(f64, f64)> {
let v = self.vals[attr_idx::POSITION];
if v.is_null() {
return None;
}
let mut point = CGPoint::default();
let ok = unsafe {
safe_ax_value_get_value(v, AX_VALUE_CGPOINT, &mut point as *mut _ as *mut c_void)
};
if ok {
Some((point.x, point.y))
} else {
None
}
}
/// Read AXSize as (width, height).
fn size(&self) -> Option<(f64, f64)> {
let v = self.vals[attr_idx::SIZE];
if v.is_null() {
return None;
}
let mut size = CGSize::default();
let ok = unsafe {
safe_ax_value_get_value(v, AX_VALUE_CGSIZE, &mut size as *mut _ as *mut c_void)
};
if ok {
Some((size.width, size.height))
} else {
None
}
}
}
impl Drop for BatchAttrs {
fn drop(&mut self) {
if !self._values_array.is_null() {
unsafe { safe_cf_release(self._values_array) };
}
}
}
// ── Resolved Attributes ──────────────────────────────────────────────────────
/// Platform-independent snapshot of all AX attributes needed to build an
/// ElementData. Populated either from a BatchAttrs (1 IPC call) or from
/// individual ax_* helpers (fallback path).
struct ResolvedAttrs {
role_str: String,
subrole_str: Option<String>,
ax_title: Option<String>,
ax_description: Option<String>,
ax_help: Option<String>,
value_string: Option<String>,
value_int: Option<i32>,
value_number: Option<f64>,
/// Is the raw AXValue a CFBoolean? Used for checkbox toggle fallback.
value_is_bool: Option<bool>,
enabled: Option<bool>,
focused: Option<bool>,
selected: Option<bool>,
hidden: Option<bool>,
expanded: Option<bool>,
modal: Option<bool>,
position: Option<(f64, f64)>,
size: Option<(f64, f64)>,
identifier: Option<String>,
}
impl ResolvedAttrs {
/// Populate from a BatchAttrs (1 Mach IPC round-trip).
fn from_batch(batch: &BatchAttrs) -> Self {
let value_is_bool = {
let v = batch.vals[attr_idx::VALUE];
if v.is_null() {
None
} else {
unsafe {
if safe_cf_get_type_id(v) == safe_cf_boolean_get_type_id() {
Some(safe_cf_boolean_get_value(v))
} else {
None
}
}
}
};
Self {
role_str: batch.string(attr_idx::ROLE).unwrap_or_default(),
subrole_str: batch.string(attr_idx::SUBROLE),
ax_title: batch.string(attr_idx::TITLE),
ax_description: batch.string(attr_idx::DESCRIPTION),
ax_help: batch.string(attr_idx::HELP),
value_string: batch.value_string(),
value_int: batch.value_int(),
value_number: batch.value_number(),
value_is_bool,
enabled: batch.boolean(attr_idx::ENABLED),
focused: batch.boolean(attr_idx::FOCUSED),
selected: batch.boolean(attr_idx::SELECTED),
hidden: batch.boolean(attr_idx::HIDDEN),
expanded: batch.boolean(attr_idx::EXPANDED),
modal: batch.boolean(attr_idx::MODAL),
position: batch.position(),
size: batch.size(),
identifier: batch.string(attr_idx::IDENTIFIER),
}
}
/// Populate from individual AX API calls (fallback path).
fn from_individual(element: AXUIElementRef) -> Self {
Self {
role_str: ax_string(element, "AXRole").unwrap_or_default(),
subrole_str: ax_string(element, "AXSubrole"),
ax_title: ax_string(element, "AXTitle"),
ax_description: ax_string(element, "AXDescription"),
ax_help: ax_string(element, "AXHelp"),
value_string: ax_value_string(element),
value_int: ax_value_int(element),
value_number: ax_value_number(element),
value_is_bool: ax_bool(element, "AXValue"),
enabled: ax_bool(element, "AXEnabled"),
focused: ax_bool(element, "AXFocused"),
selected: ax_bool(element, "AXSelected"),
hidden: ax_bool(element, "AXHidden"),
expanded: ax_bool(element, "AXExpanded"),
modal: ax_bool(element, "AXModal"),
position: ax_position(element),
size: ax_size(element),
identifier: ax_string(element, "AXIdentifier"),
}
}
}
// ── Safe FFI Wrappers ────────────────────────────────────────────────────────
fn do_perform_action(element: AXUIElementRef, action: &CFString) -> i32 {
unsafe { safe_ax_perform_action(element, action.as_concrete_TypeRef() as CFTypeRef) }
}
fn do_set_attribute(element: AXUIElementRef, attribute: &CFString, value: CFTypeRef) -> i32 {
unsafe {
safe_ax_set_attribute_value(element, attribute.as_concrete_TypeRef() as CFTypeRef, value)
}
}
/// Convert an AX error code from `do_perform_action` into an appropriate
/// `Error`. Returns `ActionNotSupported` for -25206 (kAXErrorActionUnsupported)
/// so callers get a clear, structured error instead of a raw platform code.
fn action_error(err: i32, action: &str, role: Role, fallback_msg: &str) -> Error {
if err == AX_ERROR_ACTION_UNSUPPORTED {
Error::ActionNotSupported {
action: action.to_string(),
role,
}
} else {
Error::Platform {
code: err as i64,
message: fallback_msg.to_string(),
}
}
}
// ── Action Helpers ──────────────────────────────────────────────────────────
//
// Small functions that reduce repetition in `perform_action`. Each wraps a
// single AX API call pattern and converts the result to `Result<()>`.
/// Invoke an AX action by name. Used for Press, ShowMenu, Increment, Decrement.
fn perform_ax_action(
el_ptr: AXUIElementRef,
ax_name: &str,
action: &str,
role: Role,
) -> Result<()> {
let cf = CFString::new(ax_name);
let err = do_perform_action(el_ptr, &cf);
if err != AX_ERROR_SUCCESS {
return Err(action_error(
err,
action,
role,
&format!("{ax_name} failed"),
));
}
Ok(())
}
/// Set a boolean attribute. Used for Focus, Blur, Select, Expand, Collapse.
/// Check whether `attr_name` is settable on the element.
///
/// Used to surface `ActionNotSupported` for attribute-backed semantic verbs
/// (`expand` / `collapse`): every AX bridge (AppKit, AccessKit, Qt) accepts
/// `AXUIElementSetAttributeValue` for an attribute the element does not
/// support and silently no-ops, so a plain "set and check the error code"
/// can never report unsupported. Matches the AT-SPI2 backend (missing action
/// index) and the UIA backend (missing ExpandCollapse pattern).
fn is_attr_settable(el_ptr: AXUIElementRef, attr_name: &str) -> Result<bool> {
let attr = CFString::new(attr_name);
let mut settable = false;
let err = unsafe {
safe_ax_is_attribute_settable(
el_ptr,
attr.as_concrete_TypeRef() as CFTypeRef,
&mut settable,
)
};
if err != AX_ERROR_SUCCESS {
return Err(Error::Platform {
code: err as i64,
message: format!("IsAttributeSettable({attr_name}) failed"),
});
}
Ok(settable)
}
fn set_bool_attr(
el_ptr: AXUIElementRef,
attr_name: &str,
value: bool,
action: &str,
role: Role,
) -> Result<()> {
let attr = CFString::new(attr_name);
let val = if value {
core_foundation::boolean::CFBoolean::true_value()
} else {
core_foundation::boolean::CFBoolean::false_value()
};
let err = do_set_attribute(el_ptr, &attr, val.as_CFTypeRef());
if err != AX_ERROR_SUCCESS {
return Err(action_error(
err,
action,
role,
&format!("Set {attr_name}={value} failed"),
));
}
Ok(())
}
// ── Role Mapping ──────────────────────────────────────────────────────────────
fn map_ax_role(role: &str, subrole: Option<&str>) -> Role {
match subrole {
Some("AXDialog") => return Role::Dialog,
Some("AXApplicationAlert") | Some("AXSystemAlert") => return Role::Alert,
Some("AXTabButton") => return Role::Tab,
Some("AXOutlineRow") => return Role::TreeItem,
Some("AXHeading") => return Role::Heading,
Some("AXSwitch") => return Role::Switch,
// WebKit exposes <nav>/role="navigation" as AXGroup with this
// subrole; matches AT-SPI's "navigation" landmark mapping.
Some("AXLandmarkNavigation") => return Role::Navigation,
_ => {}
}
match role {
"AXApplication" => Role::Application,
"AXWindow" | "AXSheet" | "AXDrawer" => {
if role == "AXSheet" {
Role::Dialog
} else {