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