| 1 | use std::{ffi::CString, ptr::null_mut}; |
| 2 | |
| 3 | use gpui::Window; |
| 4 | use 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 | }; |
| 12 | use objc2_app_kit::{NSView, NSWindow}; |
| 13 | use objc2_foundation::NSPoint; |
| 14 | use raw_window_handle::{HasWindowHandle, RawWindowHandle}; |
| 15 | |
| 16 | pub 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 | |
| 36 | extern "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 | |
| 42 | fn 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 | |
| 50 | unsafe fn add_method<T, F>(class: *mut AnyClass, sel: Sel, func: F) |
| 51 | where |
| 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 | |
| 67 | fn count_args(sel: Sel) -> usize { |
| 68 | sel.name().to_bytes().iter().filter(|&&c| c == b':').count() |
| 69 | } |
| 70 | |
| 71 | fn 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 | } |