events.rs

  1use crate::{
  2    platform::mac::NSStringExt, point, px, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers,
  3    ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseExitEvent, MouseMoveEvent,
  4    MouseUpEvent, NavigationDirection, Pixels, PlatformInput, ScrollDelta, ScrollWheelEvent,
  5    TouchPhase,
  6};
  7use cocoa::{
  8    appkit::{NSEvent, NSEventModifierFlags, NSEventPhase, NSEventType},
  9    base::{id, YES},
 10};
 11use core_graphics::{
 12    event::{CGEvent, CGEventFlags, CGKeyCode},
 13    event_source::{CGEventSource, CGEventSourceStateID},
 14};
 15use metal::foreign_types::ForeignType as _;
 16use objc::{class, msg_send, sel, sel_impl};
 17use std::{borrow::Cow, mem, ptr, sync::Once};
 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
 27fn synthesize_keyboard_event(code: CGKeyCode) -> CGEvent {
 28    static mut EVENT_SOURCE: core_graphics::sys::CGEventSourceRef = ptr::null_mut();
 29    static INIT_EVENT_SOURCE: Once = Once::new();
 30
 31    INIT_EVENT_SOURCE.call_once(|| {
 32        let source = CGEventSource::new(CGEventSourceStateID::Private).unwrap();
 33        unsafe {
 34            EVENT_SOURCE = source.as_ptr();
 35        };
 36        mem::forget(source);
 37    });
 38
 39    let source = unsafe { core_graphics::event_source::CGEventSource::from_ptr(EVENT_SOURCE) };
 40    let event = CGEvent::new_keyboard_event(source.clone(), code, true).unwrap();
 41    mem::forget(source);
 42    event
 43}
 44
 45pub fn key_to_native(key: &str) -> Cow<str> {
 46    use cocoa::appkit::*;
 47    let code = match key {
 48        "space" => SPACE_KEY,
 49        "backspace" => BACKSPACE_KEY,
 50        "up" => NSUpArrowFunctionKey,
 51        "down" => NSDownArrowFunctionKey,
 52        "left" => NSLeftArrowFunctionKey,
 53        "right" => NSRightArrowFunctionKey,
 54        "pageup" => NSPageUpFunctionKey,
 55        "pagedown" => NSPageDownFunctionKey,
 56        "home" => NSHomeFunctionKey,
 57        "end" => NSEndFunctionKey,
 58        "delete" => NSDeleteFunctionKey,
 59        "f1" => NSF1FunctionKey,
 60        "f2" => NSF2FunctionKey,
 61        "f3" => NSF3FunctionKey,
 62        "f4" => NSF4FunctionKey,
 63        "f5" => NSF5FunctionKey,
 64        "f6" => NSF6FunctionKey,
 65        "f7" => NSF7FunctionKey,
 66        "f8" => NSF8FunctionKey,
 67        "f9" => NSF9FunctionKey,
 68        "f10" => NSF10FunctionKey,
 69        "f11" => NSF11FunctionKey,
 70        "f12" => NSF12FunctionKey,
 71        _ => return Cow::Borrowed(key),
 72    };
 73    Cow::Owned(String::from_utf16(&[code]).unwrap())
 74}
 75
 76unsafe fn read_modifiers(native_event: id) -> Modifiers {
 77    let modifiers = native_event.modifierFlags();
 78    let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
 79    let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
 80    let shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
 81    let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
 82    let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask);
 83
 84    Modifiers {
 85        control,
 86        alt,
 87        shift,
 88        platform: command,
 89        function,
 90    }
 91}
 92
 93impl PlatformInput {
 94    pub(crate) unsafe fn from_native(
 95        native_event: id,
 96        window_height: Option<Pixels>,
 97    ) -> Option<Self> {
 98        let event_type = native_event.eventType();
 99
100        // Filter out event types that aren't in the NSEventType enum.
101        // See https://github.com/servo/cocoa-rs/issues/155#issuecomment-323482792 for details.
102        match event_type as u64 {
103            0 | 21 | 32 | 33 | 35 | 36 | 37 => {
104                return None;
105            }
106            _ => {}
107        }
108
109        match event_type {
110            NSEventType::NSFlagsChanged => Some(Self::ModifiersChanged(ModifiersChangedEvent {
111                modifiers: read_modifiers(native_event),
112            })),
113            NSEventType::NSKeyDown => Some(Self::KeyDown(KeyDownEvent {
114                keystroke: parse_keystroke(native_event),
115                is_held: native_event.isARepeat() == YES,
116            })),
117            NSEventType::NSKeyUp => Some(Self::KeyUp(KeyUpEvent {
118                keystroke: parse_keystroke(native_event),
119            })),
120            NSEventType::NSLeftMouseDown
121            | NSEventType::NSRightMouseDown
122            | NSEventType::NSOtherMouseDown => {
123                let button = match native_event.buttonNumber() {
124                    0 => MouseButton::Left,
125                    1 => MouseButton::Right,
126                    2 => MouseButton::Middle,
127                    3 => MouseButton::Navigate(NavigationDirection::Back),
128                    4 => MouseButton::Navigate(NavigationDirection::Forward),
129                    // Other mouse buttons aren't tracked currently
130                    _ => return None,
131                };
132                window_height.map(|window_height| {
133                    Self::MouseDown(MouseDownEvent {
134                        button,
135                        position: point(
136                            px(native_event.locationInWindow().x as f32),
137                            // MacOS screen coordinates are relative to bottom left
138                            window_height - px(native_event.locationInWindow().y as f32),
139                        ),
140                        modifiers: read_modifiers(native_event),
141                        click_count: native_event.clickCount() as usize,
142                        first_mouse: false,
143                    })
144                })
145            }
146            NSEventType::NSLeftMouseUp
147            | NSEventType::NSRightMouseUp
148            | NSEventType::NSOtherMouseUp => {
149                let button = match native_event.buttonNumber() {
150                    0 => MouseButton::Left,
151                    1 => MouseButton::Right,
152                    2 => MouseButton::Middle,
153                    3 => MouseButton::Navigate(NavigationDirection::Back),
154                    4 => MouseButton::Navigate(NavigationDirection::Forward),
155                    // Other mouse buttons aren't tracked currently
156                    _ => return None,
157                };
158
159                window_height.map(|window_height| {
160                    Self::MouseUp(MouseUpEvent {
161                        button,
162                        position: point(
163                            px(native_event.locationInWindow().x as f32),
164                            window_height - px(native_event.locationInWindow().y as f32),
165                        ),
166                        modifiers: read_modifiers(native_event),
167                        click_count: native_event.clickCount() as usize,
168                    })
169                })
170            }
171            NSEventType::NSScrollWheel => window_height.map(|window_height| {
172                let phase = match native_event.phase() {
173                    NSEventPhase::NSEventPhaseMayBegin | NSEventPhase::NSEventPhaseBegan => {
174                        TouchPhase::Started
175                    }
176                    NSEventPhase::NSEventPhaseEnded => TouchPhase::Ended,
177                    _ => TouchPhase::Moved,
178                };
179
180                let raw_data = point(
181                    native_event.scrollingDeltaX() as f32,
182                    native_event.scrollingDeltaY() as f32,
183                );
184
185                let delta = if native_event.hasPreciseScrollingDeltas() == YES {
186                    ScrollDelta::Pixels(raw_data.map(px))
187                } else {
188                    ScrollDelta::Lines(raw_data)
189                };
190
191                Self::ScrollWheel(ScrollWheelEvent {
192                    position: point(
193                        px(native_event.locationInWindow().x as f32),
194                        window_height - px(native_event.locationInWindow().y as f32),
195                    ),
196                    delta,
197                    touch_phase: phase,
198                    modifiers: read_modifiers(native_event),
199                })
200            }),
201            NSEventType::NSLeftMouseDragged
202            | NSEventType::NSRightMouseDragged
203            | NSEventType::NSOtherMouseDragged => {
204                let pressed_button = match native_event.buttonNumber() {
205                    0 => MouseButton::Left,
206                    1 => MouseButton::Right,
207                    2 => MouseButton::Middle,
208                    3 => MouseButton::Navigate(NavigationDirection::Back),
209                    4 => MouseButton::Navigate(NavigationDirection::Forward),
210                    // Other mouse buttons aren't tracked currently
211                    _ => return None,
212                };
213
214                window_height.map(|window_height| {
215                    Self::MouseMove(MouseMoveEvent {
216                        pressed_button: Some(pressed_button),
217                        position: point(
218                            px(native_event.locationInWindow().x as f32),
219                            window_height - px(native_event.locationInWindow().y as f32),
220                        ),
221                        modifiers: read_modifiers(native_event),
222                    })
223                })
224            }
225            NSEventType::NSMouseMoved => window_height.map(|window_height| {
226                Self::MouseMove(MouseMoveEvent {
227                    position: point(
228                        px(native_event.locationInWindow().x as f32),
229                        window_height - px(native_event.locationInWindow().y as f32),
230                    ),
231                    pressed_button: None,
232                    modifiers: read_modifiers(native_event),
233                })
234            }),
235            NSEventType::NSMouseExited => window_height.map(|window_height| {
236                Self::MouseExited(MouseExitEvent {
237                    position: point(
238                        px(native_event.locationInWindow().x as f32),
239                        window_height - px(native_event.locationInWindow().y as f32),
240                    ),
241
242                    pressed_button: None,
243                    modifiers: read_modifiers(native_event),
244                })
245            }),
246            _ => None,
247        }
248    }
249}
250
251unsafe fn parse_keystroke(native_event: id) -> Keystroke {
252    use cocoa::appkit::*;
253
254    let mut chars_ignoring_modifiers = native_event
255        .charactersIgnoringModifiers()
256        .to_str()
257        .to_string();
258    let first_char = chars_ignoring_modifiers.chars().next().map(|ch| ch as u16);
259    let modifiers = native_event.modifierFlags();
260
261    let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
262    let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
263    let mut shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
264    let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
265    let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask)
266        && first_char.map_or(true, |ch| {
267            !(NSUpArrowFunctionKey..=NSModeSwitchFunctionKey).contains(&ch)
268        });
269
270    #[allow(non_upper_case_globals)]
271    let key = match first_char {
272        Some(SPACE_KEY) => "space".to_string(),
273        Some(BACKSPACE_KEY) => "backspace".to_string(),
274        Some(ENTER_KEY) | Some(NUMPAD_ENTER_KEY) => "enter".to_string(),
275        Some(ESCAPE_KEY) => "escape".to_string(),
276        Some(TAB_KEY) => "tab".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        Some(NSF1FunctionKey) => "f1".to_string(),
288        Some(NSF2FunctionKey) => "f2".to_string(),
289        Some(NSF3FunctionKey) => "f3".to_string(),
290        Some(NSF4FunctionKey) => "f4".to_string(),
291        Some(NSF5FunctionKey) => "f5".to_string(),
292        Some(NSF6FunctionKey) => "f6".to_string(),
293        Some(NSF7FunctionKey) => "f7".to_string(),
294        Some(NSF8FunctionKey) => "f8".to_string(),
295        Some(NSF9FunctionKey) => "f9".to_string(),
296        Some(NSF10FunctionKey) => "f10".to_string(),
297        Some(NSF11FunctionKey) => "f11".to_string(),
298        Some(NSF12FunctionKey) => "f12".to_string(),
299        _ => {
300            let mut chars_ignoring_modifiers_and_shift =
301                chars_for_modified_key(native_event.keyCode(), false, false);
302
303            // Honor ⌘ when Dvorak-QWERTY is used.
304            let chars_with_cmd = chars_for_modified_key(native_event.keyCode(), true, false);
305            if command && chars_ignoring_modifiers_and_shift != chars_with_cmd {
306                chars_ignoring_modifiers =
307                    chars_for_modified_key(native_event.keyCode(), true, shift);
308                chars_ignoring_modifiers_and_shift = chars_with_cmd;
309            }
310
311            if shift {
312                if chars_ignoring_modifiers_and_shift
313                    == chars_ignoring_modifiers.to_ascii_lowercase()
314                {
315                    chars_ignoring_modifiers_and_shift
316                } else if chars_ignoring_modifiers_and_shift != chars_ignoring_modifiers {
317                    shift = false;
318                    chars_ignoring_modifiers
319                } else {
320                    chars_ignoring_modifiers
321                }
322            } else {
323                chars_ignoring_modifiers
324            }
325        }
326    };
327
328    Keystroke {
329        modifiers: Modifiers {
330            control,
331            alt,
332            shift,
333            platform: command,
334            function,
335        },
336        key,
337        ime_key: None,
338    }
339}
340
341fn chars_for_modified_key(code: CGKeyCode, cmd: bool, shift: bool) -> String {
342    // Ideally, we would use `[NSEvent charactersByApplyingModifiers]` but that
343    // always returns an empty string with certain keyboards, e.g. Japanese. Synthesizing
344    // an event with the given flags instead lets us access `characters`, which always
345    // returns a valid string.
346    let event = synthesize_keyboard_event(code);
347
348    let mut flags = CGEventFlags::empty();
349    if cmd {
350        flags |= CGEventFlags::CGEventFlagCommand;
351    }
352    if shift {
353        flags |= CGEventFlags::CGEventFlagShift;
354    }
355    event.set_flags(flags);
356
357    unsafe {
358        let event: id = msg_send![class!(NSEvent), eventWithCGEvent: &*event];
359        event.characters().to_str().to_string()
360    }
361}