use std::{
cell::{Cell, RefCell},
ptr::NonNull,
};
use block2::RcBlock;
use gpui::{App, Window, WindowHandle};
use objc2::{
rc::Retained,
runtime::{AnyObject, ProtocolObject},
};
use objc2_app_kit::{NSEvent, NSEventMask, NSEventModifierFlags, NSEventType, NSWindow};
use objc2_foundation::{NSNotificationCenter, NSObjectProtocol};
use crate::floating_menu::{Menu, Signal, Typed, typed};
use crate::keyboard::Key;
use super::{event_in, ns_window_of};
pub const KEYLESS: bool = true;
pub struct Watch {
monitor: Option<Retained<AnyObject>>,
resign: Retained<ProtocolObject<dyn NSObjectProtocol>>,
ns_window: usize,
}
impl Drop for Watch {
fn drop(&mut self) {
if let Some(monitor) = self.monitor.take() {
unsafe { NSEvent::removeMonitor(&monitor) };
}
unsafe {
NSNotificationCenter::defaultCenter()
.removeObserver(ProtocolObject::as_ref(&*self.resign))
};
allow_key(self.ns_window);
}
}
fn key_for_code(code: u16) -> Option<Key> {
Some(match code {
53 => Key::Dismiss,
36 | 76 | 49 => Key::Activate,
125 => Key::Down,
126 => Key::Up,
123 => Key::Left,
124 => Key::Right,
115 => Key::Home,
119 => Key::End,
116 => Key::PageUp,
121 => Key::PageDown,
_ => return None,
})
}
pub fn watch<I: Clone + 'static>(
window: &Window,
menu: WindowHandle<Menu<I>>,
cx: &App,
) -> Option<Watch> {
let (ns_window, _) = ns_window_of(window);
if ns_window == 0 {
return None;
}
let done = std::rc::Rc::new(Cell::new(false));
let deliver: std::rc::Rc<dyn Fn(Signal)> = {
let done = done.clone();
let cx = RefCell::new(cx.to_async());
std::rc::Rc::new(move |signal: Signal| {
if done.get() {
return;
}
if matches!(signal, Signal::Close) {
done.set(true);
}
let mut cx = cx.borrow_mut();
let _ = menu.update(&mut *cx, |menu, window, cx| menu.signal(signal, window, cx));
})
};
let on_resign = deliver.clone();
let handler = RcBlock::new(move |event: NonNull<NSEvent>| -> *mut NSEvent {
let event_ref = unsafe { event.as_ref() };
if done.get() {
return event.as_ptr();
}
if event_ref.r#type() == NSEventType::KeyDown {
let flags = event_ref.modifierFlags();
let text = event_ref.characters().map(|text| text.to_string());
return match typed(
key_for_code(event_ref.keyCode()),
text.as_deref(),
flags.contains(NSEventModifierFlags::Command)
|| flags.contains(NSEventModifierFlags::Control),
) {
Typed::Key(key) => {
deliver(Signal::Key(key));
std::ptr::null_mut()
}
Typed::Text(text) => {
deliver(Signal::Text(text));
std::ptr::null_mut()
}
Typed::Other => {
deliver(Signal::Close);
event.as_ptr()
}
};
}
if event_in(event_ref, ns_window) {
return event.as_ptr();
}
deliver(Signal::Close);
std::ptr::null_mut()
});
let monitor = unsafe {
NSEvent::addLocalMonitorForEventsMatchingMask_handler(
NSEventMask::LeftMouseDown
| NSEventMask::RightMouseDown
| NSEventMask::OtherMouseDown
| NSEventMask::KeyDown,
&handler,
)
};
let block = RcBlock::new(move |_| on_resign(Signal::Close));
let resign = unsafe {
NSNotificationCenter::defaultCenter().addObserverForName_object_queue_usingBlock(
Some(objc2_app_kit::NSApplicationDidResignActiveNotification),
None,
None,
&block,
)
};
Some(Watch {
monitor,
resign,
ns_window,
})
}
pub fn shown(window: &mut Window, cx: &mut App) {
let (ns_window, _) = ns_window_of(window);
if ns_window == 0 {
return;
}
let ns_window = unsafe { &*(ns_window as *const NSWindow) };
ns_window.setHasShadow(false);
never_key(ns_window);
window.draw(cx).clear(cx);
ns_window.orderFront(None);
}
pub fn hide(window: &Window) {
let (ns_window, _) = ns_window_of(window);
if ns_window == 0 {
return;
}
let ns_window = unsafe { &*(ns_window as *const NSWindow) };
ns_window.orderOut(None);
}
fn never_key(window: &NSWindow) {
use objc2::runtime::{AnyObject, Bool, Sel};
type CanBecomeKey = unsafe extern "C-unwind" fn(&AnyObject, Sel) -> Bool;
unsafe extern "C-unwind" fn can_become_key(this: &AnyObject, sel: Sel) -> Bool {
let this_ptr = this as *const AnyObject as usize;
if KEYLESS_WINDOWS.with(|set| set.borrow().contains(&this_ptr)) {
return Bool::NO;
}
let Some(original) = ORIGINAL_CAN_BECOME_KEY.with(Cell::get) else {
return Bool::YES;
};
let original: CanBecomeKey = unsafe { std::mem::transmute(original) };
unsafe { original(this, sel) }
}
KEYLESS_WINDOWS.with(|set| set.borrow_mut().insert(window as *const NSWindow as usize));
if ORIGINAL_CAN_BECOME_KEY.with(Cell::get).is_some() {
return;
}
let Some(method) = window
.class()
.instance_method(objc2::sel!(canBecomeKeyWindow))
else {
return;
};
let replacement: CanBecomeKey = can_become_key;
let original = unsafe {
method.set_implementation(std::mem::transmute::<CanBecomeKey, objc2::runtime::Imp>(
replacement,
))
};
ORIGINAL_CAN_BECOME_KEY.with(|slot| slot.set(Some(original)));
}
fn allow_key(ns_window: usize) {
KEYLESS_WINDOWS.with(|set| set.borrow_mut().remove(&ns_window));
}
thread_local! {
static KEYLESS_WINDOWS: RefCell<std::collections::HashSet<usize>> =
RefCell::new(std::collections::HashSet::new());
static ORIGINAL_CAN_BECOME_KEY: Cell<Option<objc2::runtime::Imp>> = const { Cell::new(None) };
}