Skip to main content

ferrokit_core/
keys.rs

1//! Keyboard focus and shortcuts across the boundary (risk 4).
2//!
3//! One local `NSEvent` monitor sees every key-down and mouse-down first:
4//! - Tab / Shift-Tab become [`Event::FocusStep`]: the host owns the focus order
5//!   across both worlds. A view registered with [`set_accepts_tab`] keeps plain
6//!   Tab (a text editor inserts it); Ctrl-Tab still moves on.
7//! - ⌘A/C/V/X/Z/⇧⌘Z go to the focused native view's responder chain. With the
8//!   host focused and the Edit menu installed, they go straight to the host's
9//!   view, so the menu's key equivalents don't swallow them.
10//! - A click outside every native view hands focus back to the host view.
11
12use crate::kept::{UiCell, UiLocal};
13use std::cell::Cell;
14use std::collections::HashSet;
15
16use block2::RcBlock;
17use objc2::rc::Retained;
18use objc2::runtime::{AnyObject, NSObject, Sel};
19use objc2::{MainThreadOnly, define_class, msg_send, sel};
20use objc2_app_kit::{
21    NSApplication, NSControl, NSEvent, NSEventMask, NSEventModifierFlags, NSEventType, NSMenu, NSMenuItem, NSView,
22};
23use objc2_core_foundation::{CFRunLoop, kCFRunLoopCommonModes};
24use objc2_foundation::{NSPoint, NSString};
25
26use crate::events::{Event, emit};
27use crate::host::{focus_target, mtm, with_host};
28use crate::ViewId;
29
30const TAB: u16 = 48;
31
32thread_local! {
33    static MONITOR: UiCell<Option<Retained<AnyObject>>> = const { UiCell::new(None) };
34    static ACCEPTS_TAB: UiCell<HashSet<ViewId>> = UiCell::new(HashSet::new());
35    static LAST_FOCUS: Cell<Option<ViewId>> = const { Cell::new(None) };
36    static CHECK_QUEUED: Cell<bool> = const { Cell::new(false) };
37    static EDIT_MENU: Cell<bool> = const { Cell::new(false) };
38    static TARGET: UiCell<Option<Retained<Target>>> = const { UiCell::new(None) };
39}
40
41/// Lets a view keep plain Tab (e.g. a text editor). Ctrl-Tab leaves it.
42pub fn set_accepts_tab(id: ViewId, accepts: bool) {
43    // `try_with`: editors are also dropped while thread-locals are torn
44    // down at exit, when this one may already be gone.
45    let _ = ACCEPTS_TAB.try_with(|s| {
46        let mut s = s.borrow_mut();
47        if accepts { s.insert(id) } else { s.remove(&id) }
48    });
49}
50
51/// Makes a mounted view the first responder.
52pub fn focus(id: ViewId) -> bool {
53    let done = with_host(|h| {
54        let (Some(m), Some(window)) = (h.views.get(&id), h.content.window()) else { return false };
55        window.makeFirstResponder(Some(&focus_target(&m.view)))
56    })
57    .unwrap_or(false);
58    queue_focus_check();
59    done
60}
61
62/// Gives keyboard focus back to the host's view.
63pub fn focus_host() -> bool {
64    let done = with_host(|h| h.content.window().is_some_and(|w| w.makeFirstResponder(Some(&h.content)))).unwrap_or(false);
65    queue_focus_check();
66    done
67}
68
69/// The mounted view containing the first responder, if any.
70pub fn focused_view() -> Option<ViewId> {
71    with_host(|h| {
72        let responder = h.content.window()?.firstResponder()?;
73        let view = responder.downcast::<NSView>().ok()?;
74        h.views.iter().find(|(_, m)| view.isDescendantOf(&m.view)).map(|(id, _)| *id)
75    })
76    .flatten()
77}
78
79/// Emits `FocusChanged` once the current event has been handled, if focus moved.
80fn queue_focus_check() {
81    if CHECK_QUEUED.with(|q| q.replace(true)) {
82        return;
83    }
84    let block = RcBlock::new(|| {
85        CHECK_QUEUED.with(|q| q.set(false));
86        let now = focused_view();
87        if LAST_FOCUS.with(|l| l.replace(now)) != now {
88            emit(Event::FocusChanged(now));
89        }
90    });
91    let main = CFRunLoop::main().expect("main run loop");
92    // SAFETY: runs on the main run loop; touches main-thread state only.
93    unsafe { main.perform_block(kCFRunLoopCommonModes.map(|m| m.as_ref()), Some(&block)) };
94    main.wake_up();
95}
96
97pub(crate) fn install() {
98    if MONITOR.with_borrow(Option::is_some) {
99        return;
100    }
101    let block = RcBlock::new(|event: std::ptr::NonNull<NSEvent>| -> *mut NSEvent {
102        // SAFETY: AppKit passes a valid event for the duration of the call.
103        let e = unsafe { event.as_ref() };
104        let keep = match e.r#type() {
105            NSEventType::KeyDown => on_key(e),
106            NSEventType::LeftMouseDown | NSEventType::RightMouseDown => {
107                on_mouse_down(e);
108                true
109            }
110            _ => true,
111        };
112        if keep { event.as_ptr() } else { std::ptr::null_mut() }
113    });
114    // SAFETY: the handler returns the event or nil, as the API requires.
115    let monitor = unsafe {
116        NSEvent::addLocalMonitorForEventsMatchingMask_handler(
117            NSEventMask::KeyDown | NSEventMask::LeftMouseDown | NSEventMask::RightMouseDown,
118            &block,
119        )
120    };
121    MONITOR.with_borrow_mut(|m| *m = monitor);
122}
123
124/// Returns false to consume the event.
125fn on_key(e: &NSEvent) -> bool {
126    let flags = e.modifierFlags();
127    let focused = focused_view();
128    if e.keyCode() == TAB && !flags.contains(NSEventModifierFlags::Command) {
129        let ctrl = flags.contains(NSEventModifierFlags::Control);
130        if !ctrl && focused.is_some_and(|id| ACCEPTS_TAB.with_borrow(|s| s.contains(&id))) {
131            return true;
132        }
133        emit(Event::FocusStep { forward: !flags.contains(NSEventModifierFlags::Shift) });
134        return false;
135    }
136    let command = flags.contains(NSEventModifierFlags::Command);
137    let Some(action) = command.then(|| edit_action(e.keyCode(), flags.contains(NSEventModifierFlags::Shift))).flatten() else {
138        return true;
139    };
140    if focused.is_some() {
141        return !perform_on_first_responder(action);
142    }
143    if EDIT_MENU.with(Cell::get) {
144        // Host focused: deliver to the host's view before the menu's key
145        // equivalent can take it.
146        with_host(|h| h.content.keyDown(e));
147        return false;
148    }
149    true
150}
151
152fn on_mouse_down(e: &NSEvent) {
153    // A click outside every native view gives focus back to the host's view
154    // (AppKit leaves the old first responder in place otherwise).
155    let outside = with_host(|h| {
156        let Some(window) = h.content.window() else { return false };
157        if e.window(mtm()).is_none_or(|w| w != window) {
158            return false;
159        }
160        // hitTest: takes a point in the receiver's superview coordinates.
161        let p = e.locationInWindow();
162        // SAFETY: the content view is in a window, so its superview is valid.
163        let p = unsafe { h.content.superview() }.map_or(p, |s| s.convertPoint_fromView(p, None));
164        let hit = h.content.hitTest(p);
165        !h.views.values().any(|m| hit.as_ref().is_some_and(|v| v.isDescendantOf(&m.view)))
166    })
167    .unwrap_or(false);
168    if outside && focused_view().is_some() {
169        focus_host();
170    }
171    queue_focus_check();
172}
173
174fn edit_action(key_code: u16, shift: bool) -> Option<Sel> {
175    Some(match (key_code, shift) {
176        (0, false) => sel!(selectAll:),
177        (7, false) => sel!(cut:),
178        (8, false) => sel!(copy:),
179        (9, false) => sel!(paste:),
180        (6, false) => sel!(undo:),
181        (6, true) => sel!(redo:),
182        _ => return None,
183    })
184}
185
186fn key_for(action: Sel) -> Option<(&'static str, u16, bool)> {
187    [
188        (sel!(selectAll:), ("a", 0, false)),
189        (sel!(cut:), ("x", 7, false)),
190        (sel!(copy:), ("c", 8, false)),
191        (sel!(paste:), ("v", 9, false)),
192        (sel!(undo:), ("z", 6, false)),
193        (sel!(redo:), ("z", 6, true)),
194    ]
195    .into_iter()
196    .find(|(s, _)| *s == action)
197    .map(|(_, k)| k)
198}
199
200fn perform_on_first_responder(action: Sel) -> bool {
201    with_host(|h| h.content.window()?.firstResponder())
202        .flatten()
203        // SAFETY: a standard responder action with a nil sender.
204        .is_some_and(|r| unsafe { r.tryToPerform_with(action, None) })
205}
206
207define_class!(
208    // Target for the Edit menu and for native controls' actions.
209    #[unsafe(super(NSObject))]
210    #[thread_kind = MainThreadOnly]
211    #[name = "FerrokitCoreTarget"]
212    struct Target;
213
214    impl Target {
215        #[unsafe(method(editAction:))]
216        fn edit_action(&self, sender: &NSMenuItem) {
217            let Some(action) = EDIT_ACTIONS.get(sender.tag() as usize).copied() else { return };
218            if focused_view().is_some() {
219                perform_on_first_responder(action());
220            } else if let Some((chars, code, shift)) = key_for(action()) {
221                // Chosen with the mouse while the host has focus: send the
222                // host the shortcut it would have received from the keyboard.
223                post_key_down(chars, code, true, shift);
224            }
225        }
226
227        #[unsafe(method(controlAction:))]
228        fn control_action(&self, sender: &AnyObject) {
229            // SAFETY: senders are NSControls and NSMenuItems, which both have -tag.
230            let tag: isize = unsafe { msg_send![sender, tag] };
231            emit(Event::Action(ViewId(tag as u64)));
232        }
233
234        #[unsafe(method(validateMenuItem:))]
235        fn validate(&self, _item: &NSMenuItem) -> bool {
236            true
237        }
238    }
239);
240
241const EDIT_ACTIONS: [fn() -> Sel; 6] =
242    [|| sel!(undo:), || sel!(redo:), || sel!(cut:), || sel!(copy:), || sel!(paste:), || sel!(selectAll:)];
243
244fn target() -> Retained<Target> {
245    TARGET.with_borrow_mut(|t| {
246        t.get_or_insert_with(|| {
247            let this = Target::alloc(mtm()).set_ivars(());
248            unsafe { msg_send![super(this), init] }
249        })
250        .clone()
251    })
252}
253
254/// Sends `control`'s action to the event sink as `Event::Action(id)`.
255pub fn set_action(control: &NSControl, id: ViewId) {
256    let target = target();
257    control.setTag(id.0 as isize);
258    // SAFETY: the target lives for the rest of the program (kept in TARGET).
259    unsafe {
260        control.setTarget(Some(&target));
261        control.setAction(Some(sel!(controlAction:)));
262    }
263}
264
265/// Sends a menu item's action to the event sink as `Event::Action(id)`.
266pub fn set_menu_action(item: &NSMenuItem, id: ViewId) {
267    let target = target();
268    item.setTag(id.0 as isize);
269    // SAFETY: the target lives for the rest of the program (kept in TARGET).
270    unsafe {
271        item.setTarget(Some(&target));
272        item.setAction(Some(sel!(controlAction:)));
273    }
274}
275
276/// Adds a standard Edit menu (Undo, Redo, Cut, Copy, Paste, Select All) with
277/// the usual shortcuts, routed to whichever side has focus.
278pub fn install_edit_menu() {
279    if EDIT_MENU.with(|e| e.replace(true)) {
280        return;
281    }
282    let mtm = mtm();
283    let app = NSApplication::sharedApplication(mtm);
284    let Some(main_menu) = app.mainMenu() else { return };
285    let menu = NSMenu::initWithTitle(NSMenu::alloc(mtm), &NSString::from_str("Edit"));
286    let target = target();
287    for (tag, (title, key)) in
288        [("Undo", "z"), ("Redo", "Z"), ("Cut", "x"), ("Copy", "c"), ("Paste", "v"), ("Select All", "a")].into_iter().enumerate()
289    {
290        // SAFETY: plain menu item construction; target kept alive in TARGET.
291        let item = unsafe {
292            NSMenuItem::initWithTitle_action_keyEquivalent(
293                NSMenuItem::alloc(mtm),
294                &NSString::from_str(title),
295                Some(sel!(editAction:)),
296                &NSString::from_str(key),
297            )
298        };
299        item.setTag(tag as isize);
300        unsafe { item.setTarget(Some(&target)) };
301        menu.addItem(&item);
302        if tag == 1 {
303            menu.addItem(&NSMenuItem::separatorItem(mtm));
304        }
305    }
306    let top = NSMenuItem::new(mtm);
307    top.setSubmenu(Some(&menu));
308    main_menu.insertItem_atIndex(&top, 1.min(main_menu.numberOfItems()));
309}
310
311pub(crate) fn post_key_down(chars: &str, key_code: u16, command: bool, shift: bool) {
312    let mtm = mtm();
313    let Some(window_number) = with_host(|h| h.content.window().map(|w| w.windowNumber())).flatten() else { return };
314    let mut flags = NSEventModifierFlags::empty();
315    if command {
316        flags |= NSEventModifierFlags::Command;
317    }
318    if shift {
319        flags |= NSEventModifierFlags::Shift;
320    }
321    let chars = NSString::from_str(chars);
322    let event = NSEvent::keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode(
323        NSEventType::KeyDown, NSPoint::ZERO, flags, 0.0, window_number, None, &chars, &chars, false, key_code,
324    );
325    if let Some(event) = event {
326        NSApplication::sharedApplication(mtm).postEvent_atStart(&event, false);
327    }
328}