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