hex/src/accessibility.rs
Dax 3434eb5f35
Rename voice-control to hex everywhere, without migrations (#293)
* Rename voice-control to hex everywhere, without migrations

The Cargo package and binary are now hex, every OS keeps its data in a
hex folder, and VOICE_CONTROL_* variables are HEX_*. Hex is a fresh
app: the macOS voice-control rename, its symlink, and the Windows and
Linux beta settings imports are gone. The Windows installer gets a new
AppId so it never takes over an old voice-control install's entry.

* Format

* Drop the Windows paste-last default only the beta import used
2026-10-28 13:08:44 -04:00

146 lines
4.7 KiB
Rust

use std::ffi::{CStr, c_char, c_void};
use std::ptr;
type CfTypeRef = *const c_void;
type CfStringRef = *const c_void;
type AxUiElementRef = *const c_void;
const CF_STRING_ENCODING_UTF8: u32 = 0x0800_0100;
const MAX_SELECTED_TEXT_BYTES: usize = 64 * 1024;
const MESSAGING_TIMEOUT_SECS: f32 = 0.25;
#[link(name = "ApplicationServices", kind = "framework")]
unsafe extern "C" {
fn AXUIElementCreateApplication(pid: i32) -> AxUiElementRef;
fn AXUIElementCreateSystemWide() -> AxUiElementRef;
fn AXUIElementCopyAttributeValue(
element: AxUiElementRef,
attribute: CfStringRef,
value: *mut CfTypeRef,
) -> i32;
fn AXUIElementSetMessagingTimeout(element: AxUiElementRef, timeout_in_seconds: f32) -> i32;
}
#[link(name = "CoreFoundation", kind = "framework")]
unsafe extern "C" {
fn CFGetTypeID(value: CfTypeRef) -> usize;
fn CFStringGetTypeID() -> usize;
fn CFStringGetLength(value: CfStringRef) -> isize;
fn CFStringGetMaximumSizeForEncoding(length: isize, encoding: u32) -> isize;
fn CFStringGetCString(
value: CfStringRef,
buffer: *mut c_char,
buffer_size: isize,
encoding: u32,
) -> bool;
fn CFStringCreateWithCString(
allocator: *const c_void,
string: *const c_char,
encoding: u32,
) -> CfStringRef;
fn CFRelease(value: CfTypeRef);
}
pub fn capture_optional() -> Option<String> {
// SAFETY: AXUIElementCreateSystemWide returns a retained Core Foundation object.
let system = bounded_element(unsafe { AXUIElementCreateSystemWide() })?;
let focused = copy_element(&system, c"AXFocusedUIElement")?;
copy_string(&focused, c"AXSelectedText")
.filter(|text| !text.is_empty() && text.len() <= MAX_SELECTED_TEXT_BYTES)
}
pub fn focused_window_title(pid: i32) -> Option<String> {
// SAFETY: AXUIElementCreateApplication returns a retained Core Foundation object.
let application = bounded_element(unsafe { AXUIElementCreateApplication(pid) })?;
let window = copy_element(&application, c"AXFocusedWindow")?;
copy_string(&window, c"AXTitle").filter(|title| !title.is_empty())
}
struct CfObject(CfTypeRef);
impl Drop for CfObject {
fn drop(&mut self) {
unsafe { CFRelease(self.0) };
}
}
fn bounded_element(element: AxUiElementRef) -> Option<CfObject> {
if element.is_null() {
return None;
}
let element = CfObject(element);
(unsafe { AXUIElementSetMessagingTimeout(element.0, MESSAGING_TIMEOUT_SECS) } == 0)
.then_some(element)
}
fn copy_attribute(element: &CfObject, name: &CStr) -> Option<CfObject> {
let attribute = CfObject(cf_string_literal(name)?);
let mut value = ptr::null();
let status = unsafe { AXUIElementCopyAttributeValue(element.0, attribute.0, &mut value) };
// `then`, not `then_some`: dropping a `CfObject(null)` would CFRelease(NULL).
(status == 0 && !value.is_null()).then(|| CfObject(value))
}
fn copy_element(element: &CfObject, name: &CStr) -> Option<CfObject> {
let child = copy_attribute(element, name)?;
(unsafe { AXUIElementSetMessagingTimeout(child.0, MESSAGING_TIMEOUT_SECS) } == 0)
.then_some(child)
}
fn copy_string(element: &CfObject, name: &CStr) -> Option<String> {
let value = copy_attribute(element, name)?;
cf_string(value.0)
}
fn cf_string_literal(value: &CStr) -> Option<CfStringRef> {
let string =
unsafe { CFStringCreateWithCString(ptr::null(), value.as_ptr(), CF_STRING_ENCODING_UTF8) };
(!string.is_null()).then_some(string)
}
fn cf_string(value: CfTypeRef) -> Option<String> {
if unsafe { CFGetTypeID(value) } != unsafe { CFStringGetTypeID() } {
return None;
}
let value = value.cast();
let length = unsafe { CFStringGetLength(value) };
let capacity = unsafe { CFStringGetMaximumSizeForEncoding(length, CF_STRING_ENCODING_UTF8) }
.saturating_add(1);
let mut bytes = vec![0_u8; capacity as usize];
if !unsafe {
CFStringGetCString(
value,
bytes.as_mut_ptr().cast(),
capacity,
CF_STRING_ENCODING_UTF8,
)
} {
return None;
}
let length = bytes
.iter()
.position(|byte| *byte == 0)
.unwrap_or(bytes.len());
bytes.truncate(length);
String::from_utf8(bytes).ok()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_missing_attribute_is_none() {
assert_eq!(focused_window_title(i32::MAX), None);
}
#[test]
#[ignore = "requires a trusted signed process and a focused selected text fixture"]
fn captures_the_focused_accessibility_selection() {
std::thread::sleep(std::time::Duration::from_secs(2));
assert_eq!(
capture_optional().as_deref(),
Some("Hex selected text fixture")
);
}
}