axuielement 0.9.1

Safe Rust bindings for Apple's AXUIElement — drive other apps' UIs (read attributes, perform actions) on macOS
Documentation
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
//! Safe wrapper for `AXUIElement`.

use core::ffi::c_void;
use core::fmt;

use crate::ax_error::{AXError, K_AX_ERROR_NO_VALUE, K_AX_ERROR_SUCCESS};
use crate::ax_text_marker::{AXTextMarker, AXTextMarkerRange};
use crate::ax_value::{AXPoint, AXRange, AXRect, AXSize, AXValue};
use crate::{bridge, internal};

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
/// Bitflags mirroring `ApplicationServices` `AXCopyMultipleAttributeOptions`.
pub struct AXCopyMultipleAttributeOptions(u32);

impl AXCopyMultipleAttributeOptions {
    /// Matches the default `AXCopyMultipleAttributeOptions` value.
    pub const NONE: Self = Self(0);
    /// Matches `kAXCopyMultipleAttributeOptionStopOnError`.
    pub const STOP_ON_ERROR: Self = Self(1);

    #[must_use]
    /// Returns the raw `AXCopyMultipleAttributeOptions` bit pattern.
    pub const fn bits(self) -> u32 {
        self.0
    }
}

impl core::ops::BitOr for AXCopyMultipleAttributeOptions {
    type Output = Self;

    fn bitor(self, rhs: Self) -> Self::Output {
        Self(self.0 | rhs.0)
    }
}

#[repr(transparent)]
/// Safe owner of an `ApplicationServices` `AXUIElementRef`.
pub struct AXUIElement {
    raw: *mut c_void,
}

/// Compatibility alias for `AXUIElement`.
pub type AXElement = AXUIElement;

unsafe impl Send for AXUIElement {}
unsafe impl Sync for AXUIElement {}

impl Clone for AXUIElement {
    fn clone(&self) -> Self {
        // SAFETY: ax_ui_element_retain returns a valid CFTypeRef that must be released in Drop.
        // SAFETY: FFI call with valid arguments
        let raw = unsafe { bridge::ax_ui_element::ax_ui_element_retain(self.raw) };
        // SAFETY: raw is guaranteed valid from ax_ui_element_retain; from_raw takes ownership.
        // SAFETY: pointer is guaranteed valid from the bridge
        unsafe { Self::from_raw(raw) }
    }
}

impl Drop for AXUIElement {
    fn drop(&mut self) {
        if !self.raw.is_null() {
            // SAFETY: self.raw is a valid CFTypeRef created by the bridge; release is the inverse of retain.
            // SAFETY: FFI boundary with properly validated inputs
            unsafe { bridge::ax_ui_element::ax_ui_element_release(self.raw) };
            self.raw = core::ptr::null_mut();
        }
    }
}

impl fmt::Debug for AXUIElement {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AXUIElement")
            .field("pid", &self.pid())
            .finish()
    }
}

impl AXUIElement {
    #[must_use]
    /// Wraps `AXUIElementGetTypeID`.
    pub fn type_id() -> usize {
        // SAFETY: ax_ui_element_get_type_id is a pure function returning a CFTypeID.
        // SAFETY: FFI boundary with properly validated inputs
        unsafe { bridge::ax_ui_element::ax_ui_element_get_type_id() }
    }

    #[must_use]
    /// Wraps `AXUIElementCreateApplication`.
    pub fn from_pid(pid: i32) -> Option<Self> {
        // SAFETY: ax_ui_element_create_application returns either null or a valid CFTypeRef.
        // SAFETY: FFI call with valid arguments
        let raw = unsafe { bridge::ax_ui_element::ax_ui_element_create_application(pid) };
        // SAFETY: null-check; if non-null, raw is a valid CFTypeRef from the bridge.
        // SAFETY: pointer is guaranteed valid from the bridge
        (!raw.is_null()).then(|| unsafe { Self::from_raw(raw) })
    }

    #[must_use]
    /// Wraps `AXUIElementCreateSystemWide`.
    pub fn system_wide() -> Option<Self> {
        // SAFETY: ax_system_wide_create returns either null or a valid AXUIElement CFTypeRef.
        // SAFETY: FFI call with valid arguments
        let raw = unsafe { bridge::system_wide::ax_system_wide_create() };
        // SAFETY: null-check; if non-null, raw is a valid CFTypeRef from the bridge.
        // SAFETY: pointer is guaranteed valid from the bridge
        (!raw.is_null()).then(|| unsafe { Self::from_raw(raw) })
    }

    /// Wraps `AXUIElementGetPid`.
    pub fn pid(&self) -> Result<i32, AXError> {
        let mut pid = 0_i32;
        // SAFETY: self.raw is a valid AXUIElement; pid is a valid mutable output parameter.
        // SAFETY: FFI call with valid arguments
        let status = unsafe { bridge::ax_ui_element::ax_ui_element_get_pid(self.raw, &mut pid) };
        if status == K_AX_ERROR_SUCCESS {
            Ok(pid)
        } else {
            Err(AXError::from_status(status, "AXUIElementGetPid"))
        }
    }

    /// Wraps `AXUIElementSetMessagingTimeout`.
    pub fn set_timeout(&self, timeout_seconds: f32) -> Result<(), AXError> {
        // SAFETY: self.raw is a valid AXUIElement; timeout_seconds is a float primitive.
        // SAFETY: FFI call with valid arguments
        let status = unsafe {
            bridge::ax_ui_element::ax_ui_element_set_messaging_timeout(self.raw, timeout_seconds)
        };
        if status == K_AX_ERROR_SUCCESS {
            Ok(())
        } else {
            Err(AXError::from_status(status, "set_timeout"))
        }
    }

    /// Wraps `AXUIElementCopyAttributeNames`.
    pub fn attribute_names(&self) -> Result<Vec<String>, AXError> {
        let mut raw = core::ptr::null_mut();
        // SAFETY: FFI call with valid arguments
        let status = unsafe { bridge::ax_attribute::ax_attribute_copy_names(self.raw, &mut raw) };
        if status != K_AX_ERROR_SUCCESS {
            return Err(AXError::from_status(status, "attribute_names"));
        }
        Ok(raw_to_string_vec(raw))
    }

    /// Wraps `AXUIElementIsAttributeSettable`.
    pub fn is_attribute_settable(&self, name: &str) -> Result<bool, AXError> {
        let name = internal::make_cstring(name)?;
        let mut settable = false;
        // SAFETY: FFI call with valid arguments
        let status = unsafe {
            bridge::ax_attribute::ax_attribute_is_settable(self.raw, name.as_ptr(), &mut settable)
        };
        if status == K_AX_ERROR_SUCCESS {
            Ok(settable)
        } else if status == K_AX_ERROR_NO_VALUE {
            Ok(false)
        } else {
            Err(AXError::from_status(
                status,
                name.to_string_lossy().as_ref(),
            ))
        }
    }

    /// Wraps `AXUIElementGetAttributeValueCount`.
    pub fn attribute_value_count(&self, name: &str) -> Result<usize, AXError> {
        let name = internal::make_cstring(name)?;
        let mut count = 0_isize;
        // SAFETY: FFI call with valid arguments
        let status = unsafe {
            bridge::ax_attribute::ax_attribute_get_value_count(self.raw, name.as_ptr(), &mut count)
        };
        if status == K_AX_ERROR_SUCCESS {
            usize::try_from(count).map_err(|_| {
                AXError::IllegalArgument(format!("count overflow for {}", name.to_string_lossy()))
            })
        } else if status == K_AX_ERROR_NO_VALUE {
            Ok(0)
        } else {
            Err(AXError::from_status(
                status,
                name.to_string_lossy().as_ref(),
            ))
        }
    }

    /// Wraps `AXUIElementCopyAttributeValue`.
    pub fn attribute(&self, name: &str) -> Result<Option<AXValue>, AXError> {
        let name = internal::make_cstring(name)?;
        let mut raw = core::ptr::null_mut();
        // SAFETY: FFI call with valid arguments
        let status = unsafe {
            bridge::ax_attribute::ax_attribute_copy_value(self.raw, name.as_ptr(), &mut raw)
        };
        if status == K_AX_ERROR_SUCCESS {
            // SAFETY: pointer is guaranteed valid from the bridge
            Ok((!raw.is_null()).then(|| unsafe { AXValue::from_raw(raw) }))
        } else if status == K_AX_ERROR_NO_VALUE {
            Ok(None)
        } else {
            Err(AXError::from_status(
                status,
                name.to_string_lossy().as_ref(),
            ))
        }
    }

    /// Convenience wrapper over `AXUIElementCopyAttributeValue` that decodes a string payload.
    pub fn string_attribute(&self, name: &str) -> Result<Option<String>, AXError> {
        Ok(self.attribute(name)?.and_then(|value| value.as_string()))
    }

    /// Convenience wrapper over `AXUIElementCopyAttributeValue` that decodes a boolean payload.
    pub fn bool_attribute(&self, name: &str) -> Result<Option<bool>, AXError> {
        Ok(self.attribute(name)?.and_then(|value| value.as_bool()))
    }

    /// Convenience wrapper over `AXUIElementCopyAttributeValue` that decodes an integer payload.
    pub fn i64_attribute(&self, name: &str) -> Result<Option<i64>, AXError> {
        Ok(self.attribute(name)?.and_then(|value| value.as_i64()))
    }

    /// Convenience wrapper over `AXUIElementCopyAttributeValue` that decodes a floating-point payload.
    pub fn f64_attribute(&self, name: &str) -> Result<Option<f64>, AXError> {
        Ok(self.attribute(name)?.and_then(|value| value.as_f64()))
    }

    /// Convenience wrapper over `AXUIElementCopyAttributeValue` that decodes a `CGPoint` payload.
    pub fn point_attribute(&self, name: &str) -> Result<Option<AXPoint>, AXError> {
        Ok(self.attribute(name)?.and_then(|value| value.as_point()))
    }

    /// Convenience wrapper over `AXUIElementCopyAttributeValue` that decodes a `CGSize` payload.
    pub fn size_attribute(&self, name: &str) -> Result<Option<AXSize>, AXError> {
        Ok(self.attribute(name)?.and_then(|value| value.as_size()))
    }

    /// Convenience wrapper over `AXUIElementCopyAttributeValue` that decodes a `CGRect` payload.
    pub fn rect_attribute(&self, name: &str) -> Result<Option<AXRect>, AXError> {
        Ok(self.attribute(name)?.and_then(|value| value.as_rect()))
    }

    /// Convenience wrapper over `AXUIElementCopyAttributeValue` that decodes a `CFRange` payload.
    pub fn range_attribute(&self, name: &str) -> Result<Option<AXRange>, AXError> {
        Ok(self.attribute(name)?.and_then(|value| value.as_range()))
    }

    /// Convenience wrapper over `AXUIElementCopyAttributeValue` that decodes an `AXUIElementRef` payload.
    pub fn element_attribute(&self, name: &str) -> Result<Option<Self>, AXError> {
        Ok(self.attribute(name)?.and_then(|value| value.as_element()))
    }

    /// Convenience wrapper over `AXUIElementCopyAttributeValue` that decodes an `AXTextMarkerRef` payload.
    pub fn text_marker_attribute(&self, name: &str) -> Result<Option<AXTextMarker>, AXError> {
        Ok(self
            .attribute(name)?
            .and_then(|value| value.as_text_marker()))
    }

    /// Convenience wrapper over `AXUIElementCopyAttributeValue` that decodes an `AXTextMarkerRangeRef` payload.
    pub fn text_marker_range_attribute(
        &self,
        name: &str,
    ) -> Result<Option<AXTextMarkerRange>, AXError> {
        Ok(self
            .attribute(name)?
            .and_then(|value| value.as_text_marker_range()))
    }

    /// Wraps `AXUIElementCopyAttributeValues` and decodes the returned range as `AXValue` items.
    pub fn value_array_attribute_range(
        &self,
        name: &str,
        index: usize,
        max_values: usize,
    ) -> Result<Vec<AXValue>, AXError> {
        let name = internal::make_cstring(name)?;
        let index = isize::try_from(index).map_err(|_| {
            AXError::IllegalArgument(format!("index overflow for {}", name.to_string_lossy()))
        })?;
        let max_values = isize::try_from(max_values).map_err(|_| {
            AXError::IllegalArgument(format!(
                "max_values overflow for {}",
                name.to_string_lossy()
            ))
        })?;
        let mut raw = core::ptr::null_mut();
        // SAFETY: FFI call with valid arguments
        let status = unsafe {
            bridge::ax_attribute::ax_attribute_copy_values(
                self.raw,
                name.as_ptr(),
                index,
                max_values,
                &mut raw,
            )
        };
        if status == K_AX_ERROR_SUCCESS {
            Ok(raw_to_value_vec(raw))
        } else if status == K_AX_ERROR_NO_VALUE {
            Ok(Vec::new())
        } else {
            Err(AXError::from_status(
                status,
                name.to_string_lossy().as_ref(),
            ))
        }
    }

    /// Wraps `AXUIElementCopyAttributeValues` and keeps only `AXUIElementRef` items.
    pub fn element_array_attribute_range(
        &self,
        name: &str,
        index: usize,
        max_values: usize,
    ) -> Result<Vec<Self>, AXError> {
        Ok(self
            .value_array_attribute_range(name, index, max_values)?
            .into_iter()
            .filter_map(|value| value.as_element())
            .collect())
    }

    /// Builds on `AXUIElementGetAttributeValueCount` plus `AXUIElementCopyAttributeValues` to fetch an entire element array attribute.
    pub fn element_array_attribute(&self, name: &str) -> Result<Vec<Self>, AXError> {
        let count = self.attribute_value_count(name)?;
        if count == 0 {
            return Ok(Vec::new());
        }
        self.element_array_attribute_range(name, 0, count)
    }

    /// Convenience wrapper for the `kAXChildrenAttribute` element array.
    pub fn children(&self) -> Result<Vec<Self>, AXError> {
        self.element_array_attribute("AXChildren")
    }

    /// Wraps `AXUIElementSetAttributeValue`.
    pub fn set_attribute(&self, name: &str, value: &AXValue) -> Result<(), AXError> {
        let name = internal::make_cstring(name)?;
        // SAFETY: FFI call with valid arguments
        let status = unsafe {
            bridge::ax_attribute::ax_attribute_set_value(self.raw, name.as_ptr(), value.as_ptr())
        };
        if status == K_AX_ERROR_SUCCESS {
            Ok(())
        } else {
            Err(AXError::from_status(
                status,
                name.to_string_lossy().as_ref(),
            ))
        }
    }

    /// Convenience wrapper over `AXUIElementSetAttributeValue` for string payloads.
    pub fn set_string_attribute(&self, name: &str, value: &str) -> Result<(), AXError> {
        let value = AXValue::from_string(value)?;
        self.set_attribute(name, &value)
    }

    /// Convenience wrapper over `AXUIElementSetAttributeValue` for boolean payloads.
    pub fn set_bool_attribute(&self, name: &str, value: bool) -> Result<(), AXError> {
        let value = AXValue::from_bool(value);
        self.set_attribute(name, &value)
    }

    /// Convenience wrapper over `AXUIElementSetAttributeValue` for integer payloads.
    pub fn set_i64_attribute(&self, name: &str, value: i64) -> Result<(), AXError> {
        let value = AXValue::from_i64(value);
        self.set_attribute(name, &value)
    }

    /// Convenience wrapper over `AXUIElementSetAttributeValue` for floating-point payloads.
    pub fn set_f64_attribute(&self, name: &str, value: f64) -> Result<(), AXError> {
        let value = AXValue::from_f64(value);
        self.set_attribute(name, &value)
    }

    /// Convenience wrapper over `AXUIElementSetAttributeValue` for `CGPoint` payloads.
    pub fn set_point_attribute(&self, name: &str, value: AXPoint) -> Result<(), AXError> {
        let value = AXValue::from_point(value).ok_or(AXError::Failure)?;
        self.set_attribute(name, &value)
    }

    /// Convenience wrapper over `AXUIElementSetAttributeValue` for `CGSize` payloads.
    pub fn set_size_attribute(&self, name: &str, value: AXSize) -> Result<(), AXError> {
        let value = AXValue::from_size(value).ok_or(AXError::Failure)?;
        self.set_attribute(name, &value)
    }

    /// Convenience wrapper over `AXUIElementSetAttributeValue` for `CGRect` payloads.
    pub fn set_rect_attribute(&self, name: &str, value: AXRect) -> Result<(), AXError> {
        let value = AXValue::from_rect(value).ok_or(AXError::Failure)?;
        self.set_attribute(name, &value)
    }

    /// Convenience wrapper over `AXUIElementSetAttributeValue` for `CFRange` payloads.
    pub fn set_range_attribute(&self, name: &str, value: AXRange) -> Result<(), AXError> {
        let value = AXValue::from_range(value).ok_or(AXError::Failure)?;
        self.set_attribute(name, &value)
    }

    /// Convenience wrapper over `AXUIElementSetAttributeValue` for `AXUIElementRef` payloads.
    pub fn set_element_attribute(&self, name: &str, value: &Self) -> Result<(), AXError> {
        let value = AXValue::from_element(value).ok_or(AXError::Failure)?;
        self.set_attribute(name, &value)
    }

    /// Wraps `AXUIElementCopyMultipleAttributeValues`.
    pub fn copy_multiple_attribute_values(
        &self,
        names: &[&str],
        options: AXCopyMultipleAttributeOptions,
    ) -> Result<Vec<AXValue>, AXError> {
        let (names_storage, raw_names) = internal::make_cstring_vec(names)?;
        let _storage = names_storage;
        let mut raw = core::ptr::null_mut();
        // SAFETY: FFI call with valid arguments
        let status = unsafe {
            bridge::ax_attribute::ax_attribute_copy_multiple_values(
                self.raw,
                raw_names.as_ptr(),
                raw_names.len(),
                options.bits(),
                &mut raw,
            )
        };
        if status == K_AX_ERROR_SUCCESS {
            Ok(raw_to_value_vec(raw))
        } else {
            Err(AXError::from_status(
                status,
                "copy_multiple_attribute_values",
            ))
        }
    }

    /// Wraps `AXUIElementCopyParameterizedAttributeNames`.
    pub fn parameterized_attribute_names(&self) -> Result<Vec<String>, AXError> {
        let mut raw = core::ptr::null_mut();
        // SAFETY: FFI call with valid arguments
        let status = unsafe {
            bridge::ax_attribute::ax_attribute_copy_parameterized_names(self.raw, &mut raw)
        };
        if status != K_AX_ERROR_SUCCESS {
            return Err(AXError::from_status(
                status,
                "parameterized_attribute_names",
            ));
        }
        Ok(raw_to_string_vec(raw))
    }

    /// Wraps `AXUIElementCopyParameterizedAttributeValue`.
    pub fn parameterized_attribute(
        &self,
        name: &str,
        parameter: &AXValue,
    ) -> Result<Option<AXValue>, AXError> {
        let name = internal::make_cstring(name)?;
        let mut raw = core::ptr::null_mut();
        // SAFETY: FFI call with valid arguments
        let status = unsafe {
            bridge::ax_attribute::ax_attribute_copy_parameterized_value(
                self.raw,
                name.as_ptr(),
                parameter.as_ptr(),
                &mut raw,
            )
        };
        if status == K_AX_ERROR_SUCCESS {
            // SAFETY: pointer is guaranteed valid from the bridge
            Ok((!raw.is_null()).then(|| unsafe { AXValue::from_raw(raw) }))
        } else if status == K_AX_ERROR_NO_VALUE {
            Ok(None)
        } else {
            Err(AXError::from_status(
                status,
                name.to_string_lossy().as_ref(),
            ))
        }
    }

    /// Wraps `AXUIElementCopyActionNames`.
    pub fn action_names(&self) -> Result<Vec<String>, AXError> {
        let mut raw = core::ptr::null_mut();
        // SAFETY: FFI call with valid arguments
        let status = unsafe { bridge::ax_action::ax_action_copy_names(self.raw, &mut raw) };
        if status != K_AX_ERROR_SUCCESS {
            return Err(AXError::from_status(status, "action_names"));
        }
        Ok(raw_to_string_vec(raw))
    }

    /// Wraps `AXUIElementCopyActionDescription`.
    pub fn action_description(&self, action: &str) -> Result<Option<String>, AXError> {
        let action = internal::make_cstring(action)?;
        let mut raw = core::ptr::null_mut();
        // SAFETY: FFI call with valid arguments
        let status = unsafe {
            bridge::ax_action::ax_action_copy_description(self.raw, action.as_ptr(), &mut raw)
        };
        if status == K_AX_ERROR_SUCCESS {
            // SAFETY: FFI boundary with properly validated inputs
            Ok(unsafe { internal::string_from_handle(raw) })
        } else if status == K_AX_ERROR_NO_VALUE {
            Ok(None)
        } else {
            Err(AXError::from_status(
                status,
                action.to_string_lossy().as_ref(),
            ))
        }
    }

    /// Wraps `AXUIElementPerformAction`.
    pub fn perform_action(&self, action: &str) -> Result<(), AXError> {
        let action = internal::make_cstring(action)?;
        // SAFETY: FFI call with valid arguments
        let status = unsafe { bridge::ax_action::ax_action_perform(self.raw, action.as_ptr()) };
        if status == K_AX_ERROR_SUCCESS {
            Ok(())
        } else {
            Err(AXError::from_status(
                status,
                action.to_string_lossy().as_ref(),
            ))
        }
    }

    /// Wraps `AXUIElementCopyElementAtPosition`.
    pub fn element_at_position(&self, x: f32, y: f32) -> Result<Option<Self>, AXError> {
        let mut raw = core::ptr::null_mut();
        // SAFETY: FFI call with valid arguments
        let status = unsafe {
            bridge::ax_ui_element::ax_ui_element_copy_element_at_position(self.raw, x, y, &mut raw)
        };
        if status == K_AX_ERROR_SUCCESS {
            // SAFETY: pointer is guaranteed valid from the bridge
            Ok((!raw.is_null()).then(|| unsafe { Self::from_raw(raw) }))
        } else if status == K_AX_ERROR_NO_VALUE {
            Ok(None)
        } else {
            Err(AXError::from_status(status, "element_at_position"))
        }
    }

    /// Wraps deprecated `AXUIElementPostKeyboardEvent`.
    pub fn post_keyboard_event(
        &self,
        key_char: u16,
        virtual_key: u16,
        key_down: bool,
    ) -> Result<(), AXError> {
        // SAFETY: FFI call with valid arguments
        let status = unsafe {
            bridge::ax_ui_element::ax_ui_element_post_keyboard_event(
                self.raw,
                key_char,
                virtual_key,
                key_down,
            )
        };
        if status == K_AX_ERROR_SUCCESS {
            Ok(())
        } else {
            Err(AXError::from_status(status, "post_keyboard_event"))
        }
    }

    pub(crate) unsafe fn from_raw(raw: *mut c_void) -> Self {
        Self { raw }
    }

    pub(crate) const fn as_ptr(&self) -> *mut c_void {
        self.raw
    }
}

fn raw_to_value_vec(raw: *mut c_void) -> Vec<AXValue> {
    if raw.is_null() {
        return Vec::new();
    }
    // SAFETY: pointer is guaranteed valid from the bridge
    let value = unsafe { AXValue::from_raw(raw) };
    value.as_array().unwrap_or_default()
}

fn raw_to_string_vec(raw: *mut c_void) -> Vec<String> {
    raw_to_value_vec(raw)
        .into_iter()
        .filter_map(|value| value.as_string())
        .collect()
}