events.rs

  1use crate::{
  2    Capslock, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, ModifiersChangedEvent, MouseButton,
  3    MouseDownEvent, MouseExitEvent, MouseMoveEvent, MouseUpEvent, NavigationDirection, Pixels,
  4    PlatformInput, ScrollDelta, ScrollWheelEvent, TouchPhase,
  5    platform::mac::{
  6        LMGetKbdType, NSStringExt, TISCopyCurrentKeyboardLayoutInputSource,
  7        TISGetInputSourceProperty, UCKeyTranslate, kTISPropertyUnicodeKeyLayoutData,
  8    },
  9    point, px,
 10};
 11use cocoa::{
 12    appkit::{NSEvent, NSEventModifierFlags, NSEventPhase, NSEventType},
 13    base::{YES, id},
 14};
 15use core_foundation::data::{CFDataGetBytePtr, CFDataRef};
 16use core_graphics::event::CGKeyCode;
 17use objc::{msg_send, sel, sel_impl};
 18use std::{borrow::Cow, ffi::c_void};
 19
 20const BACKSPACE_KEY: u16 = 0x7f;
 21const SPACE_KEY: u16 = b' ' as u16;
 22const ENTER_KEY: u16 = 0x0d;
 23const NUMPAD_ENTER_KEY: u16 = 0x03;
 24pub(crate) const ESCAPE_KEY: u16 = 0x1b;
 25const TAB_KEY: u16 = 0x09;
 26const SHIFT_TAB_KEY: u16 = 0x19;
 27
 28pub fn key_to_native(key: &str) -> Cow<'_, str> {
 29    use cocoa::appkit::*;
 30    let code = match key {
 31        "space" => SPACE_KEY,
 32        "backspace" => BACKSPACE_KEY,
 33        "escape" => ESCAPE_KEY,
 34        "up" => NSUpArrowFunctionKey,
 35        "down" => NSDownArrowFunctionKey,
 36        "left" => NSLeftArrowFunctionKey,
 37        "right" => NSRightArrowFunctionKey,
 38        "pageup" => NSPageUpFunctionKey,
 39        "pagedown" => NSPageDownFunctionKey,
 40        "home" => NSHomeFunctionKey,
 41        "end" => NSEndFunctionKey,
 42        "delete" => NSDeleteFunctionKey,
 43        "insert" => NSHelpFunctionKey,
 44        "f1" => NSF1FunctionKey,
 45        "f2" => NSF2FunctionKey,
 46        "f3" => NSF3FunctionKey,
 47        "f4" => NSF4FunctionKey,
 48        "f5" => NSF5FunctionKey,
 49        "f6" => NSF6FunctionKey,
 50        "f7" => NSF7FunctionKey,
 51        "f8" => NSF8FunctionKey,
 52        "f9" => NSF9FunctionKey,
 53        "f10" => NSF10FunctionKey,
 54        "f11" => NSF11FunctionKey,
 55        "f12" => NSF12FunctionKey,
 56        "f13" => NSF13FunctionKey,
 57        "f14" => NSF14FunctionKey,
 58        "f15" => NSF15FunctionKey,
 59        "f16" => NSF16FunctionKey,
 60        "f17" => NSF17FunctionKey,
 61        "f18" => NSF18FunctionKey,
 62        "f19" => NSF19FunctionKey,
 63        "f20" => NSF20FunctionKey,
 64        "f21" => NSF21FunctionKey,
 65        "f22" => NSF22FunctionKey,
 66        "f23" => NSF23FunctionKey,
 67        "f24" => NSF24FunctionKey,
 68        "f25" => NSF25FunctionKey,
 69        "f26" => NSF26FunctionKey,
 70        "f27" => NSF27FunctionKey,
 71        "f28" => NSF28FunctionKey,
 72        "f29" => NSF29FunctionKey,
 73        "f30" => NSF30FunctionKey,
 74        "f31" => NSF31FunctionKey,
 75        "f32" => NSF32FunctionKey,
 76        "f33" => NSF33FunctionKey,
 77        "f34" => NSF34FunctionKey,
 78        "f35" => NSF35FunctionKey,
 79        _ => return Cow::Borrowed(key),
 80    };
 81    Cow::Owned(String::from_utf16(&[code]).unwrap())
 82}
 83
 84unsafe fn read_modifiers(native_event: id) -> Modifiers {
 85    unsafe {
 86        let modifiers = native_event.modifierFlags();
 87        let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
 88        let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
 89        let shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
 90        let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
 91        let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask);
 92
 93        Modifiers {
 94            control,
 95            alt,
 96            shift,
 97            platform: command,
 98            function,
 99        }
100    }
101}
102
103impl PlatformInput {
104    pub(crate) unsafe fn from_native(
105        native_event: id,
106        window_height: Option<Pixels>,
107    ) -> Option<Self> {
108        unsafe {
109            let event_type = native_event.eventType();
110
111            // Filter out event types that aren't in the NSEventType enum.
112            // See https://github.com/servo/cocoa-rs/issues/155#issuecomment-323482792 for details.
113            match event_type as u64 {
114                0 | 21 | 32 | 33 | 35 | 36 | 37 => {
115                    return None;
116                }
117                _ => {}
118            }
119
120            match event_type {
121                NSEventType::NSFlagsChanged => {
122                    Some(Self::ModifiersChanged(ModifiersChangedEvent {
123                        modifiers: read_modifiers(native_event),
124                        capslock: Capslock {
125                            on: native_event
126                                .modifierFlags()
127                                .contains(NSEventModifierFlags::NSAlphaShiftKeyMask),
128                        },
129                    }))
130                }
131                NSEventType::NSKeyDown => Some(Self::KeyDown(KeyDownEvent {
132                    keystroke: parse_keystroke(native_event),
133                    is_held: native_event.isARepeat() == YES,
134                    prefer_character_input: false,
135                })),
136                NSEventType::NSKeyUp => Some(Self::KeyUp(KeyUpEvent {
137                    keystroke: parse_keystroke(native_event),
138                })),
139                NSEventType::NSLeftMouseDown
140                | NSEventType::NSRightMouseDown
141                | NSEventType::NSOtherMouseDown => {
142                    let button = match native_event.buttonNumber() {
143                        0 => MouseButton::Left,
144                        1 => MouseButton::Right,
145                        2 => MouseButton::Middle,
146                        3 => MouseButton::Navigate(NavigationDirection::Back),
147                        4 => MouseButton::Navigate(NavigationDirection::Forward),
148                        // Other mouse buttons aren't tracked currently
149                        _ => return None,
150                    };
151                    window_height.map(|window_height| {
152                        Self::MouseDown(MouseDownEvent {
153                            button,
154                            position: point(
155                                px(native_event.locationInWindow().x as f32),
156                                // MacOS screen coordinates are relative to bottom left
157                                window_height - px(native_event.locationInWindow().y as f32),
158                            ),
159                            modifiers: read_modifiers(native_event),
160                            click_count: native_event.clickCount() as usize,
161                            first_mouse: false,
162                        })
163                    })
164                }
165                NSEventType::NSLeftMouseUp
166                | NSEventType::NSRightMouseUp
167                | NSEventType::NSOtherMouseUp => {
168                    let button = match native_event.buttonNumber() {
169                        0 => MouseButton::Left,
170                        1 => MouseButton::Right,
171                        2 => MouseButton::Middle,
172                        3 => MouseButton::Navigate(NavigationDirection::Back),
173                        4 => MouseButton::Navigate(NavigationDirection::Forward),
174                        // Other mouse buttons aren't tracked currently
175                        _ => return None,
176                    };
177
178                    window_height.map(|window_height| {
179                        Self::MouseUp(MouseUpEvent {
180                            button,
181                            position: point(
182                                px(native_event.locationInWindow().x as f32),
183                                window_height - px(native_event.locationInWindow().y as f32),
184                            ),
185                            modifiers: read_modifiers(native_event),
186                            click_count: native_event.clickCount() as usize,
187                        })
188                    })
189                }
190                // Some mice (like Logitech MX Master) send navigation buttons as swipe events
191                NSEventType::NSEventTypeSwipe => {
192                    let navigation_direction = match native_event.phase() {
193                        NSEventPhase::NSEventPhaseEnded => match native_event.deltaX() {
194                            x if x > 0.0 => Some(NavigationDirection::Back),
195                            x if x < 0.0 => Some(NavigationDirection::Forward),
196                            _ => return None,
197                        },
198                        _ => return None,
199                    };
200
201                    match navigation_direction {
202                        Some(direction) => window_height.map(|window_height| {
203                            Self::MouseDown(MouseDownEvent {
204                                button: MouseButton::Navigate(direction),
205                                position: point(
206                                    px(native_event.locationInWindow().x as f32),
207                                    window_height - px(native_event.locationInWindow().y as f32),
208                                ),
209                                modifiers: read_modifiers(native_event),
210                                click_count: 1,
211                                first_mouse: false,
212                            })
213                        }),
214                        _ => None,
215                    }
216                }
217                NSEventType::NSScrollWheel => window_height.map(|window_height| {
218                    let phase = match native_event.phase() {
219                        NSEventPhase::NSEventPhaseMayBegin | NSEventPhase::NSEventPhaseBegan => {
220                            TouchPhase::Started
221                        }
222                        NSEventPhase::NSEventPhaseEnded => TouchPhase::Ended,
223                        _ => TouchPhase::Moved,
224                    };
225
226                    let raw_data = point(
227                        native_event.scrollingDeltaX() as f32,
228                        native_event.scrollingDeltaY() as f32,
229                    );
230
231                    let delta = if native_event.hasPreciseScrollingDeltas() == YES {
232                        ScrollDelta::Pixels(raw_data.map(px))
233                    } else {
234                        ScrollDelta::Lines(raw_data)
235                    };
236
237                    Self::ScrollWheel(ScrollWheelEvent {
238                        position: point(
239                            px(native_event.locationInWindow().x as f32),
240                            window_height - px(native_event.locationInWindow().y as f32),
241                        ),
242                        delta,
243                        touch_phase: phase,
244                        modifiers: read_modifiers(native_event),
245                    })
246                }),
247                NSEventType::NSLeftMouseDragged
248                | NSEventType::NSRightMouseDragged
249                | NSEventType::NSOtherMouseDragged => {
250                    let pressed_button = match native_event.buttonNumber() {
251                        0 => MouseButton::Left,
252                        1 => MouseButton::Right,
253                        2 => MouseButton::Middle,
254                        3 => MouseButton::Navigate(NavigationDirection::Back),
255                        4 => MouseButton::Navigate(NavigationDirection::Forward),
256                        // Other mouse buttons aren't tracked currently
257                        _ => return None,
258                    };
259
260                    window_height.map(|window_height| {
261                        Self::MouseMove(MouseMoveEvent {
262                            pressed_button: Some(pressed_button),
263                            position: point(
264                                px(native_event.locationInWindow().x as f32),
265                                window_height - px(native_event.locationInWindow().y as f32),
266                            ),
267                            modifiers: read_modifiers(native_event),
268                        })
269                    })
270                }
271                NSEventType::NSMouseMoved => window_height.map(|window_height| {
272                    Self::MouseMove(MouseMoveEvent {
273                        position: point(
274                            px(native_event.locationInWindow().x as f32),
275                            window_height - px(native_event.locationInWindow().y as f32),
276                        ),
277                        pressed_button: None,
278                        modifiers: read_modifiers(native_event),
279                    })
280                }),
281                NSEventType::NSMouseExited => window_height.map(|window_height| {
282                    Self::MouseExited(MouseExitEvent {
283                        position: point(
284                            px(native_event.locationInWindow().x as f32),
285                            window_height - px(native_event.locationInWindow().y as f32),
286                        ),
287
288                        pressed_button: None,
289                        modifiers: read_modifiers(native_event),
290                    })
291                }),
292                _ => None,
293            }
294        }
295    }
296}
297
298unsafe fn parse_keystroke(native_event: id) -> Keystroke {
299    unsafe {
300        use cocoa::appkit::*;
301
302        let mut characters = native_event
303            .charactersIgnoringModifiers()
304            .to_str()
305            .to_string();
306        let mut key_char = None;
307        let first_char = characters.chars().next().map(|ch| ch as u16);
308        let modifiers = native_event.modifierFlags();
309
310        let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
311        let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
312        let mut shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
313        let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
314        let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask)
315            && first_char
316                .is_none_or(|ch| !(NSUpArrowFunctionKey..=NSModeSwitchFunctionKey).contains(&ch));
317
318        #[allow(non_upper_case_globals)]
319        let key = match first_char {
320            Some(SPACE_KEY) => {
321                key_char = Some(" ".to_string());
322                "space".to_string()
323            }
324            Some(TAB_KEY) => {
325                key_char = Some("\t".to_string());
326                "tab".to_string()
327            }
328            Some(ENTER_KEY) | Some(NUMPAD_ENTER_KEY) => {
329                key_char = Some("\n".to_string());
330                "enter".to_string()
331            }
332            Some(BACKSPACE_KEY) => "backspace".to_string(),
333            Some(ESCAPE_KEY) => "escape".to_string(),
334            Some(SHIFT_TAB_KEY) => "tab".to_string(),
335            Some(NSUpArrowFunctionKey) => "up".to_string(),
336            Some(NSDownArrowFunctionKey) => "down".to_string(),
337            Some(NSLeftArrowFunctionKey) => "left".to_string(),
338            Some(NSRightArrowFunctionKey) => "right".to_string(),
339            Some(NSPageUpFunctionKey) => "pageup".to_string(),
340            Some(NSPageDownFunctionKey) => "pagedown".to_string(),
341            Some(NSHomeFunctionKey) => "home".to_string(),
342            Some(NSEndFunctionKey) => "end".to_string(),
343            Some(NSDeleteFunctionKey) => "delete".to_string(),
344            // Observed Insert==NSHelpFunctionKey not NSInsertFunctionKey.
345            Some(NSHelpFunctionKey) => "insert".to_string(),
346            Some(NSF1FunctionKey) => "f1".to_string(),
347            Some(NSF2FunctionKey) => "f2".to_string(),
348            Some(NSF3FunctionKey) => "f3".to_string(),
349            Some(NSF4FunctionKey) => "f4".to_string(),
350            Some(NSF5FunctionKey) => "f5".to_string(),
351            Some(NSF6FunctionKey) => "f6".to_string(),
352            Some(NSF7FunctionKey) => "f7".to_string(),
353            Some(NSF8FunctionKey) => "f8".to_string(),
354            Some(NSF9FunctionKey) => "f9".to_string(),
355            Some(NSF10FunctionKey) => "f10".to_string(),
356            Some(NSF11FunctionKey) => "f11".to_string(),
357            Some(NSF12FunctionKey) => "f12".to_string(),
358            Some(NSF13FunctionKey) => "f13".to_string(),
359            Some(NSF14FunctionKey) => "f14".to_string(),
360            Some(NSF15FunctionKey) => "f15".to_string(),
361            Some(NSF16FunctionKey) => "f16".to_string(),
362            Some(NSF17FunctionKey) => "f17".to_string(),
363            Some(NSF18FunctionKey) => "f18".to_string(),
364            Some(NSF19FunctionKey) => "f19".to_string(),
365            Some(NSF20FunctionKey) => "f20".to_string(),
366            Some(NSF21FunctionKey) => "f21".to_string(),
367            Some(NSF22FunctionKey) => "f22".to_string(),
368            Some(NSF23FunctionKey) => "f23".to_string(),
369            Some(NSF24FunctionKey) => "f24".to_string(),
370            Some(NSF25FunctionKey) => "f25".to_string(),
371            Some(NSF26FunctionKey) => "f26".to_string(),
372            Some(NSF27FunctionKey) => "f27".to_string(),
373            Some(NSF28FunctionKey) => "f28".to_string(),
374            Some(NSF29FunctionKey) => "f29".to_string(),
375            Some(NSF30FunctionKey) => "f30".to_string(),
376            Some(NSF31FunctionKey) => "f31".to_string(),
377            Some(NSF32FunctionKey) => "f32".to_string(),
378            Some(NSF33FunctionKey) => "f33".to_string(),
379            Some(NSF34FunctionKey) => "f34".to_string(),
380            Some(NSF35FunctionKey) => "f35".to_string(),
381            _ => {
382                // Cases to test when modifying this:
383                //
384                //           qwerty key | none | cmd   | cmd-shift
385                // * Armenian         s | ս    | cmd-s | cmd-shift-s  (layout is non-ASCII, so we use cmd layout)
386                // * Dvorak+QWERTY    s | o    | cmd-s | cmd-shift-s  (layout switches on cmd)
387                // * Ukrainian+QWERTY s | с    | cmd-s | cmd-shift-s  (macOS reports cmd-s instead of cmd-S)
388                // * Czech            7 | ý    | cmd-ý | cmd-7        (layout has shifted numbers)
389                // * Norwegian        7 | 7    | cmd-7 | cmd-/        (macOS reports cmd-shift-7 instead of cmd-/)
390                // * Russian          7 | 7    | cmd-7 | cmd-&        (shift-7 is . but when cmd is down, should use cmd layout)
391                // * German QWERTZ    ; | ö    | cmd-ö | cmd-Ö        (Zed's shift special case only applies to a-z)
392                //
393                let mut chars_ignoring_modifiers =
394                    chars_for_modified_key(native_event.keyCode(), NO_MOD);
395                let mut chars_with_shift =
396                    chars_for_modified_key(native_event.keyCode(), SHIFT_MOD);
397                let always_use_cmd_layout = always_use_command_layout();
398
399                // Handle Dvorak+QWERTY / Russian / Armenian
400                if command || always_use_cmd_layout {
401                    let chars_with_cmd = chars_for_modified_key(native_event.keyCode(), CMD_MOD);
402                    let chars_with_both =
403                        chars_for_modified_key(native_event.keyCode(), CMD_MOD | SHIFT_MOD);
404
405                    // We don't do this in the case that the shifted command key generates
406                    // the same character as the unshifted command key (Norwegian, e.g.)
407                    if chars_with_both != chars_with_cmd {
408                        chars_with_shift = chars_with_both;
409
410                    // Handle edge-case where cmd-shift-s reports cmd-s instead of
411                    // cmd-shift-s (Ukrainian, etc.)
412                    } else if chars_with_cmd.to_ascii_uppercase() != chars_with_cmd {
413                        chars_with_shift = chars_with_cmd.to_ascii_uppercase();
414                    }
415                    chars_ignoring_modifiers = chars_with_cmd;
416                }
417
418                if !control && !command && !function {
419                    let mut mods = NO_MOD;
420                    if shift {
421                        mods |= SHIFT_MOD;
422                    }
423                    if alt {
424                        mods |= OPTION_MOD;
425                    }
426
427                    key_char = Some(chars_for_modified_key(native_event.keyCode(), mods));
428                }
429
430                if shift
431                    && chars_ignoring_modifiers
432                        .chars()
433                        .all(|c| c.is_ascii_lowercase())
434                {
435                    chars_ignoring_modifiers
436                } else if shift {
437                    shift = false;
438                    chars_with_shift
439                } else {
440                    chars_ignoring_modifiers
441                }
442            }
443        };
444
445        Keystroke {
446            modifiers: Modifiers {
447                control,
448                alt,
449                shift,
450                platform: command,
451                function,
452            },
453            key,
454            key_char,
455        }
456    }
457}
458
459fn always_use_command_layout() -> bool {
460    if chars_for_modified_key(0, NO_MOD).is_ascii() {
461        return false;
462    }
463
464    chars_for_modified_key(0, CMD_MOD).is_ascii()
465}
466
467const NO_MOD: u32 = 0;
468const CMD_MOD: u32 = 1;
469const SHIFT_MOD: u32 = 2;
470const OPTION_MOD: u32 = 8;
471
472fn chars_for_modified_key(code: CGKeyCode, modifiers: u32) -> String {
473    // Values from: https://github.com/phracker/MacOSX-SDKs/blob/master/MacOSX10.6.sdk/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h#L126
474    // shifted >> 8 for UCKeyTranslate
475    const CG_SPACE_KEY: u16 = 49;
476    // https://github.com/phracker/MacOSX-SDKs/blob/master/MacOSX10.6.sdk/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/CarbonCore.framework/Versions/A/Headers/UnicodeUtilities.h#L278
477    #[allow(non_upper_case_globals)]
478    const kUCKeyActionDown: u16 = 0;
479    #[allow(non_upper_case_globals)]
480    const kUCKeyTranslateNoDeadKeysMask: u32 = 0;
481
482    let keyboard_type = unsafe { LMGetKbdType() as u32 };
483    const BUFFER_SIZE: usize = 4;
484    let mut dead_key_state = 0;
485    let mut buffer: [u16; BUFFER_SIZE] = [0; BUFFER_SIZE];
486    let mut buffer_size: usize = 0;
487
488    let keyboard = unsafe { TISCopyCurrentKeyboardLayoutInputSource() };
489    if keyboard.is_null() {
490        return "".to_string();
491    }
492    let layout_data = unsafe {
493        TISGetInputSourceProperty(keyboard, kTISPropertyUnicodeKeyLayoutData as *const c_void)
494            as CFDataRef
495    };
496    if layout_data.is_null() {
497        unsafe {
498            let _: () = msg_send![keyboard, release];
499        }
500        return "".to_string();
501    }
502    let keyboard_layout = unsafe { CFDataGetBytePtr(layout_data) };
503
504    unsafe {
505        UCKeyTranslate(
506            keyboard_layout as *const c_void,
507            code,
508            kUCKeyActionDown,
509            modifiers,
510            keyboard_type,
511            kUCKeyTranslateNoDeadKeysMask,
512            &mut dead_key_state,
513            BUFFER_SIZE,
514            &mut buffer_size as *mut usize,
515            &mut buffer as *mut u16,
516        );
517        if dead_key_state != 0 {
518            UCKeyTranslate(
519                keyboard_layout as *const c_void,
520                CG_SPACE_KEY,
521                kUCKeyActionDown,
522                modifiers,
523                keyboard_type,
524                kUCKeyTranslateNoDeadKeysMask,
525                &mut dead_key_state,
526                BUFFER_SIZE,
527                &mut buffer_size as *mut usize,
528                &mut buffer as *mut u16,
529            );
530        }
531        let _: () = msg_send![keyboard, release];
532    }
533    String::from_utf16(&buffer[..buffer_size]).unwrap_or_default()
534}