event.rs

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