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                })),
135                NSEventType::NSKeyUp => Some(Self::KeyUp(KeyUpEvent {
136                    keystroke: parse_keystroke(native_event),
137                })),
138                NSEventType::NSLeftMouseDown
139                | NSEventType::NSRightMouseDown
140                | NSEventType::NSOtherMouseDown => {
141                    let button = match native_event.buttonNumber() {
142                        0 => MouseButton::Left,
143                        1 => MouseButton::Right,
144                        2 => MouseButton::Middle,
145                        3 => MouseButton::Navigate(NavigationDirection::Back),
146                        4 => MouseButton::Navigate(NavigationDirection::Forward),
147                        // Other mouse buttons aren't tracked currently
148                        _ => return None,
149                    };
150                    window_height.map(|window_height| {
151                        Self::MouseDown(MouseDownEvent {
152                            button,
153                            position: point(
154                                px(native_event.locationInWindow().x as f32),
155                                // MacOS screen coordinates are relative to bottom left
156                                window_height - px(native_event.locationInWindow().y as f32),
157                            ),
158                            modifiers: read_modifiers(native_event),
159                            click_count: native_event.clickCount() as usize,
160                            first_mouse: false,
161                        })
162                    })
163                }
164                NSEventType::NSLeftMouseUp
165                | NSEventType::NSRightMouseUp
166                | NSEventType::NSOtherMouseUp => {
167                    let button = match native_event.buttonNumber() {
168                        0 => MouseButton::Left,
169                        1 => MouseButton::Right,
170                        2 => MouseButton::Middle,
171                        3 => MouseButton::Navigate(NavigationDirection::Back),
172                        4 => MouseButton::Navigate(NavigationDirection::Forward),
173                        // Other mouse buttons aren't tracked currently
174                        _ => return None,
175                    };
176
177                    window_height.map(|window_height| {
178                        Self::MouseUp(MouseUpEvent {
179                            button,
180                            position: point(
181                                px(native_event.locationInWindow().x as f32),
182                                window_height - px(native_event.locationInWindow().y as f32),
183                            ),
184                            modifiers: read_modifiers(native_event),
185                            click_count: native_event.clickCount() as usize,
186                        })
187                    })
188                }
189                // Some mice (like Logitech MX Master) send navigation buttons as swipe events
190                NSEventType::NSEventTypeSwipe => {
191                    let navigation_direction = match native_event.phase() {
192                        NSEventPhase::NSEventPhaseEnded => match native_event.deltaX() {
193                            x if x > 0.0 => Some(NavigationDirection::Back),
194                            x if x < 0.0 => Some(NavigationDirection::Forward),
195                            _ => return None,
196                        },
197                        _ => return None,
198                    };
199
200                    match navigation_direction {
201                        Some(direction) => window_height.map(|window_height| {
202                            Self::MouseDown(MouseDownEvent {
203                                button: MouseButton::Navigate(direction),
204                                position: point(
205                                    px(native_event.locationInWindow().x as f32),
206                                    window_height - px(native_event.locationInWindow().y as f32),
207                                ),
208                                modifiers: read_modifiers(native_event),
209                                click_count: 1,
210                                first_mouse: false,
211                            })
212                        }),
213                        _ => None,
214                    }
215                }
216                NSEventType::NSScrollWheel => window_height.map(|window_height| {
217                    let phase = match native_event.phase() {
218                        NSEventPhase::NSEventPhaseMayBegin | NSEventPhase::NSEventPhaseBegan => {
219                            TouchPhase::Started
220                        }
221                        NSEventPhase::NSEventPhaseEnded => TouchPhase::Ended,
222                        _ => TouchPhase::Moved,
223                    };
224
225                    let raw_data = point(
226                        native_event.scrollingDeltaX() as f32,
227                        native_event.scrollingDeltaY() as f32,
228                    );
229
230                    let delta = if native_event.hasPreciseScrollingDeltas() == YES {
231                        ScrollDelta::Pixels(raw_data.map(px))
232                    } else {
233                        ScrollDelta::Lines(raw_data)
234                    };
235
236                    Self::ScrollWheel(ScrollWheelEvent {
237                        position: point(
238                            px(native_event.locationInWindow().x as f32),
239                            window_height - px(native_event.locationInWindow().y as f32),
240                        ),
241                        delta,
242                        touch_phase: phase,
243                        modifiers: read_modifiers(native_event),
244                    })
245                }),
246                NSEventType::NSLeftMouseDragged
247                | NSEventType::NSRightMouseDragged
248                | NSEventType::NSOtherMouseDragged => {
249                    let pressed_button = match native_event.buttonNumber() {
250                        0 => MouseButton::Left,
251                        1 => MouseButton::Right,
252                        2 => MouseButton::Middle,
253                        3 => MouseButton::Navigate(NavigationDirection::Back),
254                        4 => MouseButton::Navigate(NavigationDirection::Forward),
255                        // Other mouse buttons aren't tracked currently
256                        _ => return None,
257                    };
258
259                    window_height.map(|window_height| {
260                        Self::MouseMove(MouseMoveEvent {
261                            pressed_button: Some(pressed_button),
262                            position: point(
263                                px(native_event.locationInWindow().x as f32),
264                                window_height - px(native_event.locationInWindow().y as f32),
265                            ),
266                            modifiers: read_modifiers(native_event),
267                        })
268                    })
269                }
270                NSEventType::NSMouseMoved => window_height.map(|window_height| {
271                    Self::MouseMove(MouseMoveEvent {
272                        position: point(
273                            px(native_event.locationInWindow().x as f32),
274                            window_height - px(native_event.locationInWindow().y as f32),
275                        ),
276                        pressed_button: None,
277                        modifiers: read_modifiers(native_event),
278                    })
279                }),
280                NSEventType::NSMouseExited => window_height.map(|window_height| {
281                    Self::MouseExited(MouseExitEvent {
282                        position: point(
283                            px(native_event.locationInWindow().x as f32),
284                            window_height - px(native_event.locationInWindow().y as f32),
285                        ),
286
287                        pressed_button: None,
288                        modifiers: read_modifiers(native_event),
289                    })
290                }),
291                _ => None,
292            }
293        }
294    }
295}
296
297unsafe fn parse_keystroke(native_event: id) -> Keystroke {
298    unsafe {
299        use cocoa::appkit::*;
300
301        let mut characters = native_event
302            .charactersIgnoringModifiers()
303            .to_str()
304            .to_string();
305        let mut key_char = None;
306        let first_char = characters.chars().next().map(|ch| ch as u16);
307        let modifiers = native_event.modifierFlags();
308
309        let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
310        let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
311        let mut shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
312        let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
313        let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask)
314            && first_char.map_or(true, |ch| {
315                !(NSUpArrowFunctionKey..=NSModeSwitchFunctionKey).contains(&ch)
316            });
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                let mut key = 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                key
444            }
445        };
446
447        Keystroke {
448            modifiers: Modifiers {
449                control,
450                alt,
451                shift,
452                platform: command,
453                function,
454            },
455            key,
456            key_char,
457        }
458    }
459}
460
461fn always_use_command_layout() -> bool {
462    if chars_for_modified_key(0, NO_MOD).is_ascii() {
463        return false;
464    }
465
466    chars_for_modified_key(0, CMD_MOD).is_ascii()
467}
468
469const NO_MOD: u32 = 0;
470const CMD_MOD: u32 = 1;
471const SHIFT_MOD: u32 = 2;
472const OPTION_MOD: u32 = 8;
473
474fn chars_for_modified_key(code: CGKeyCode, modifiers: u32) -> String {
475    // 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
476    // shifted >> 8 for UCKeyTranslate
477    const CG_SPACE_KEY: u16 = 49;
478    // 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
479    #[allow(non_upper_case_globals)]
480    const kUCKeyActionDown: u16 = 0;
481    #[allow(non_upper_case_globals)]
482    const kUCKeyTranslateNoDeadKeysMask: u32 = 0;
483
484    let keyboard_type = unsafe { LMGetKbdType() as u32 };
485    const BUFFER_SIZE: usize = 4;
486    let mut dead_key_state = 0;
487    let mut buffer: [u16; BUFFER_SIZE] = [0; BUFFER_SIZE];
488    let mut buffer_size: usize = 0;
489
490    let keyboard = unsafe { TISCopyCurrentKeyboardLayoutInputSource() };
491    if keyboard.is_null() {
492        return "".to_string();
493    }
494    let layout_data = unsafe {
495        TISGetInputSourceProperty(keyboard, kTISPropertyUnicodeKeyLayoutData as *const c_void)
496            as CFDataRef
497    };
498    if layout_data.is_null() {
499        unsafe {
500            let _: () = msg_send![keyboard, release];
501        }
502        return "".to_string();
503    }
504    let keyboard_layout = unsafe { CFDataGetBytePtr(layout_data) };
505
506    unsafe {
507        UCKeyTranslate(
508            keyboard_layout as *const c_void,
509            code,
510            kUCKeyActionDown,
511            modifiers,
512            keyboard_type,
513            kUCKeyTranslateNoDeadKeysMask,
514            &mut dead_key_state,
515            BUFFER_SIZE,
516            &mut buffer_size as *mut usize,
517            &mut buffer as *mut u16,
518        );
519        if dead_key_state != 0 {
520            UCKeyTranslate(
521                keyboard_layout as *const c_void,
522                CG_SPACE_KEY,
523                kUCKeyActionDown,
524                modifiers,
525                keyboard_type,
526                kUCKeyTranslateNoDeadKeysMask,
527                &mut dead_key_state,
528                BUFFER_SIZE,
529                &mut buffer_size as *mut usize,
530                &mut buffer as *mut u16,
531            );
532        }
533        let _: () = msg_send![keyboard, release];
534    }
535    String::from_utf16(&buffer[..buffer_size]).unwrap_or_default()
536}