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            NSEventType::NSScrollWheel => window_height.map(|window_height| {
162                let phase = match native_event.phase() {
163                    NSEventPhase::NSEventPhaseMayBegin | NSEventPhase::NSEventPhaseBegan => {
164                        TouchPhase::Started
165                    }
166                    NSEventPhase::NSEventPhaseEnded => TouchPhase::Ended,
167                    _ => TouchPhase::Moved,
168                };
169
170                let raw_data = point(
171                    native_event.scrollingDeltaX() as f32,
172                    native_event.scrollingDeltaY() as f32,
173                );
174
175                let delta = if native_event.hasPreciseScrollingDeltas() == YES {
176                    ScrollDelta::Pixels(raw_data.map(px))
177                } else {
178                    ScrollDelta::Lines(raw_data)
179                };
180
181                Self::ScrollWheel(ScrollWheelEvent {
182                    position: point(
183                        px(native_event.locationInWindow().x as f32),
184                        window_height - px(native_event.locationInWindow().y as f32),
185                    ),
186                    delta,
187                    touch_phase: phase,
188                    modifiers: read_modifiers(native_event),
189                })
190            }),
191            NSEventType::NSLeftMouseDragged
192            | NSEventType::NSRightMouseDragged
193            | NSEventType::NSOtherMouseDragged => {
194                let pressed_button = match native_event.buttonNumber() {
195                    0 => MouseButton::Left,
196                    1 => MouseButton::Right,
197                    2 => MouseButton::Middle,
198                    3 => MouseButton::Navigate(NavigationDirection::Back),
199                    4 => MouseButton::Navigate(NavigationDirection::Forward),
200                    // Other mouse buttons aren't tracked currently
201                    _ => return None,
202                };
203
204                window_height.map(|window_height| {
205                    Self::MouseMove(MouseMoveEvent {
206                        pressed_button: Some(pressed_button),
207                        position: point(
208                            px(native_event.locationInWindow().x as f32),
209                            window_height - px(native_event.locationInWindow().y as f32),
210                        ),
211                        modifiers: read_modifiers(native_event),
212                    })
213                })
214            }
215            NSEventType::NSMouseMoved => window_height.map(|window_height| {
216                Self::MouseMove(MouseMoveEvent {
217                    position: point(
218                        px(native_event.locationInWindow().x as f32),
219                        window_height - px(native_event.locationInWindow().y as f32),
220                    ),
221                    pressed_button: None,
222                    modifiers: read_modifiers(native_event),
223                })
224            }),
225            NSEventType::NSMouseExited => window_height.map(|window_height| {
226                Self::MouseExited(MouseExitEvent {
227                    position: point(
228                        px(native_event.locationInWindow().x as f32),
229                        window_height - px(native_event.locationInWindow().y as f32),
230                    ),
231
232                    pressed_button: None,
233                    modifiers: read_modifiers(native_event),
234                })
235            }),
236            _ => None,
237        }
238    }
239}
240
241unsafe fn parse_keystroke(native_event: id) -> Keystroke {
242    use cocoa::appkit::*;
243
244    let mut characters = native_event
245        .charactersIgnoringModifiers()
246        .to_str()
247        .to_string();
248    let mut key_char = None;
249    let first_char = characters.chars().next().map(|ch| ch as u16);
250    let modifiers = native_event.modifierFlags();
251
252    let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
253    let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
254    let mut shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
255    let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
256    let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask)
257        && first_char.map_or(true, |ch| {
258            !(NSUpArrowFunctionKey..=NSModeSwitchFunctionKey).contains(&ch)
259        });
260
261    #[allow(non_upper_case_globals)]
262    let key = match first_char {
263        Some(SPACE_KEY) => {
264            key_char = Some(" ".to_string());
265            "space".to_string()
266        }
267        Some(TAB_KEY) => {
268            key_char = Some("\t".to_string());
269            "tab".to_string()
270        }
271        Some(ENTER_KEY) | Some(NUMPAD_ENTER_KEY) => {
272            key_char = Some("\n".to_string());
273            "enter".to_string()
274        }
275        Some(BACKSPACE_KEY) => "backspace".to_string(),
276        Some(ESCAPE_KEY) => "escape".to_string(),
277        Some(SHIFT_TAB_KEY) => "tab".to_string(),
278        Some(NSUpArrowFunctionKey) => "up".to_string(),
279        Some(NSDownArrowFunctionKey) => "down".to_string(),
280        Some(NSLeftArrowFunctionKey) => "left".to_string(),
281        Some(NSRightArrowFunctionKey) => "right".to_string(),
282        Some(NSPageUpFunctionKey) => "pageup".to_string(),
283        Some(NSPageDownFunctionKey) => "pagedown".to_string(),
284        Some(NSHomeFunctionKey) => "home".to_string(),
285        Some(NSEndFunctionKey) => "end".to_string(),
286        Some(NSDeleteFunctionKey) => "delete".to_string(),
287        // Observed Insert==NSHelpFunctionKey not NSInsertFunctionKey.
288        Some(NSHelpFunctionKey) => "insert".to_string(),
289        Some(NSF1FunctionKey) => "f1".to_string(),
290        Some(NSF2FunctionKey) => "f2".to_string(),
291        Some(NSF3FunctionKey) => "f3".to_string(),
292        Some(NSF4FunctionKey) => "f4".to_string(),
293        Some(NSF5FunctionKey) => "f5".to_string(),
294        Some(NSF6FunctionKey) => "f6".to_string(),
295        Some(NSF7FunctionKey) => "f7".to_string(),
296        Some(NSF8FunctionKey) => "f8".to_string(),
297        Some(NSF9FunctionKey) => "f9".to_string(),
298        Some(NSF10FunctionKey) => "f10".to_string(),
299        Some(NSF11FunctionKey) => "f11".to_string(),
300        Some(NSF12FunctionKey) => "f12".to_string(),
301        Some(NSF13FunctionKey) => "f13".to_string(),
302        Some(NSF14FunctionKey) => "f14".to_string(),
303        Some(NSF15FunctionKey) => "f15".to_string(),
304        Some(NSF16FunctionKey) => "f16".to_string(),
305        Some(NSF17FunctionKey) => "f17".to_string(),
306        Some(NSF18FunctionKey) => "f18".to_string(),
307        Some(NSF19FunctionKey) => "f19".to_string(),
308        _ => {
309            // Cases to test when modifying this:
310            //
311            //           qwerty key | none | cmd   | cmd-shift
312            // * Armenian         s | ս    | cmd-s | cmd-shift-s  (layout is non-ASCII, so we use cmd layout)
313            // * Dvorak+QWERTY    s | o    | cmd-s | cmd-shift-s  (layout switches on cmd)
314            // * Ukrainian+QWERTY s | с    | cmd-s | cmd-shift-s  (macOS reports cmd-s instead of cmd-S)
315            // * Czech            7 | ý    | cmd-ý | cmd-7        (layout has shifted numbers)
316            // * Norwegian        7 | 7    | cmd-7 | cmd-/        (macOS reports cmd-shift-7 instead of cmd-/)
317            // * Russian          7 | 7    | cmd-7 | cmd-&        (shift-7 is . but when cmd is down, should use cmd layout)
318            // * German QWERTZ    ; | ö    | cmd-ö | cmd-Ö        (Zed's shift special case only applies to a-z)
319            //
320            let mut chars_ignoring_modifiers =
321                chars_for_modified_key(native_event.keyCode(), NO_MOD);
322            let mut chars_with_shift = chars_for_modified_key(native_event.keyCode(), SHIFT_MOD);
323            let always_use_cmd_layout = always_use_command_layout();
324
325            // Handle Dvorak+QWERTY / Russian / Armeniam
326            if command || always_use_cmd_layout {
327                let chars_with_cmd = chars_for_modified_key(native_event.keyCode(), CMD_MOD);
328                let chars_with_both =
329                    chars_for_modified_key(native_event.keyCode(), CMD_MOD | SHIFT_MOD);
330
331                // We don't do this in the case that the shifted command key generates
332                // the same character as the unshifted command key (Norwegian, e.g.)
333                if chars_with_both != chars_with_cmd {
334                    chars_with_shift = chars_with_both;
335
336                // Handle edge-case where cmd-shift-s reports cmd-s instead of
337                // cmd-shift-s (Ukrainian, etc.)
338                } else if chars_with_cmd.to_ascii_uppercase() != chars_with_cmd {
339                    chars_with_shift = chars_with_cmd.to_ascii_uppercase();
340                }
341                chars_ignoring_modifiers = chars_with_cmd;
342            }
343
344            if !control && !command && !function {
345                let mut mods = NO_MOD;
346                if shift {
347                    mods |= SHIFT_MOD;
348                }
349                if alt {
350                    mods |= OPTION_MOD;
351                }
352
353                key_char = Some(chars_for_modified_key(native_event.keyCode(), mods));
354            }
355
356            let mut key = if shift
357                && chars_ignoring_modifiers
358                    .chars()
359                    .all(|c| c.is_ascii_lowercase())
360            {
361                chars_ignoring_modifiers
362            } else if shift {
363                shift = false;
364                chars_with_shift
365            } else {
366                chars_ignoring_modifiers
367            };
368
369            key
370        }
371    };
372
373    Keystroke {
374        modifiers: Modifiers {
375            control,
376            alt,
377            shift,
378            platform: command,
379            function,
380        },
381        key,
382        key_char,
383    }
384}
385
386fn always_use_command_layout() -> bool {
387    if chars_for_modified_key(0, NO_MOD).is_ascii() {
388        return false;
389    }
390
391    chars_for_modified_key(0, CMD_MOD).is_ascii()
392}
393
394const NO_MOD: u32 = 0;
395const CMD_MOD: u32 = 1;
396const SHIFT_MOD: u32 = 2;
397const OPTION_MOD: u32 = 8;
398
399fn chars_for_modified_key(code: CGKeyCode, modifiers: u32) -> String {
400    // 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
401    // shifted >> 8 for UCKeyTranslate
402    const CG_SPACE_KEY: u16 = 49;
403    // 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
404    #[allow(non_upper_case_globals)]
405    const kUCKeyActionDown: u16 = 0;
406    #[allow(non_upper_case_globals)]
407    const kUCKeyTranslateNoDeadKeysMask: u32 = 0;
408
409    let keyboard_type = unsafe { LMGetKbdType() as u32 };
410    const BUFFER_SIZE: usize = 4;
411    let mut dead_key_state = 0;
412    let mut buffer: [u16; BUFFER_SIZE] = [0; BUFFER_SIZE];
413    let mut buffer_size: usize = 0;
414
415    let keyboard = unsafe { TISCopyCurrentKeyboardLayoutInputSource() };
416    if keyboard.is_null() {
417        return "".to_string();
418    }
419    let layout_data = unsafe {
420        TISGetInputSourceProperty(keyboard, kTISPropertyUnicodeKeyLayoutData as *const c_void)
421            as CFDataRef
422    };
423    if layout_data.is_null() {
424        unsafe {
425            let _: () = msg_send![keyboard, release];
426        }
427        return "".to_string();
428    }
429    let keyboard_layout = unsafe { CFDataGetBytePtr(layout_data) };
430
431    unsafe {
432        UCKeyTranslate(
433            keyboard_layout as *const c_void,
434            code,
435            kUCKeyActionDown,
436            modifiers,
437            keyboard_type,
438            kUCKeyTranslateNoDeadKeysMask,
439            &mut dead_key_state,
440            BUFFER_SIZE,
441            &mut buffer_size as *mut usize,
442            &mut buffer as *mut u16,
443        );
444        if dead_key_state != 0 {
445            UCKeyTranslate(
446                keyboard_layout as *const c_void,
447                CG_SPACE_KEY,
448                kUCKeyActionDown,
449                modifiers,
450                keyboard_type,
451                kUCKeyTranslateNoDeadKeysMask,
452                &mut dead_key_state,
453                BUFFER_SIZE,
454                &mut buffer_size as *mut usize,
455                &mut buffer as *mut u16,
456            );
457        }
458        let _: () = msg_send![keyboard, release];
459    }
460    String::from_utf16(&buffer[..buffer_size]).unwrap_or_default()
461}