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