BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-base / src / macos_accessibility.rs

macos_accessibility.rs

eef6c0a4 History
macos_accessibility.rs 2.3 KiB Download Raw
1use std::{ffi::CString, ptr::null_mut};
2
3use gpui::Window;
4use objc2::{
5 Message,
6 encode::{Encode, EncodeArguments, EncodeReturn, Encoding},
7 ffi::{class_addMethod, object_getClass},
8 msg_send,
9 runtime::{AnyClass, AnyObject, MethodImplementation, Sel},
10 sel,
11};
12use objc2_app_kit::{NSView, NSWindow};
13use objc2_foundation::NSPoint;
14use raw_window_handle::{HasWindowHandle, RawWindowHandle};
15
16pub fn install_window_hit_test_forwarder(window: &Window) {
17 let Some(view) = ns_view(window) else {
18 return;
19 };
20 let Some(window) = view.window() else {
21 return;
22 };
23
24 unsafe {
25 let class = object_getClass((&*window as *const NSWindow).cast::<AnyObject>());
26 if !class.is_null() {
27 add_method(
28 class.cast_mut(),
29 sel!(accessibilityHitTest:),
30 hit_test_forwarder as extern "C" fn(_, _, _) -> _,
31 );
32 }
33 }
34}
35
36extern "C" fn hit_test_forwarder(this: &NSWindow, _cmd: Sel, point: NSPoint) -> *mut AnyObject {
37 this.contentView().map_or_else(null_mut, |view| unsafe {
38 msg_send![&*view, accessibilityHitTest: point]
39 })
40}
41
42fn ns_view(window: &Window) -> Option<&NSView> {
43 let handle = HasWindowHandle::window_handle(window).ok()?;
44 let RawWindowHandle::AppKit(handle) = handle.as_raw() else {
45 return None;
46 };
47 unsafe { (handle.ns_view.as_ptr() as *const NSView).as_ref() }
48}
49
50unsafe fn add_method<T, F>(class: *mut AnyClass, sel: Sel, func: F)
51where
52 T: Message + ?Sized,
53 F: MethodImplementation<Callee = T>,
54{
55 let encs = F::Arguments::ENCODINGS;
56 debug_assert_eq!(
57 count_args(sel),
58 encs.len(),
59 "selector {sel:?} argument count does not match method implementation"
60 );
61
62 let types = method_type_encoding(&F::Return::ENCODING_RETURN, encs);
63 let success = unsafe { class_addMethod(class, sel, func.__imp(), types.as_ptr()) };
64 let _ = success.as_bool();
65}
66
67fn count_args(sel: Sel) -> usize {
68 sel.name().to_bytes().iter().filter(|&&c| c == b':').count()
69}
70
71fn method_type_encoding(ret: &Encoding, args: &[Encoding]) -> CString {
72 let mut types = format!("{ret}{}{}", <*mut AnyObject>::ENCODING, Sel::ENCODING);
73 for enc in args {
74 use core::fmt::Write;
75 write!(&mut types, "{enc}").unwrap();
76 }
77 CString::new(types).unwrap()
78}