events.rs

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