event.rs

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