events.rs

  1use crate::{
  2    point, px, InputEvent, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, ModifiersChangedEvent,
  3    MouseButton, MouseDownEvent, MouseExitEvent, MouseMoveEvent, MouseUpEvent, NavigationDirection,
  4    Pixels, ScrollDelta, ScrollWheelEvent, TouchPhase,
  5};
  6use cocoa::{
  7    appkit::{NSEvent, NSEventModifierFlags, NSEventPhase, NSEventType},
  8    base::{id, YES},
  9    foundation::NSString as _,
 10};
 11use core_graphics::{
 12    event::{CGEvent, CGEventFlags, CGKeyCode},
 13    event_source::{CGEventSource, CGEventSourceStateID},
 14};
 15use ctor::ctor;
 16use foreign_types::ForeignType;
 17use objc::{class, msg_send, sel, sel_impl};
 18use std::{borrow::Cow, ffi::CStr, mem, os::raw::c_char, 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        command,
 81        function,
 82    }
 83}
 84
 85impl InputEvent {
 86    pub unsafe fn from_native(native_event: id, window_height: Option<Pixels>) -> 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(MouseDownEvent {
123                        button,
124                        position: point(
125                            px(native_event.locationInWindow().x as f32),
126                            // MacOS screen coordinates are relative to bottom left
127                            window_height - px(native_event.locationInWindow().y as f32),
128                        ),
129                        modifiers: read_modifiers(native_event),
130                        click_count: native_event.clickCount() as usize,
131                    })
132                })
133            }
134            NSEventType::NSLeftMouseUp
135            | NSEventType::NSRightMouseUp
136            | NSEventType::NSOtherMouseUp => {
137                let button = match native_event.buttonNumber() {
138                    0 => MouseButton::Left,
139                    1 => MouseButton::Right,
140                    2 => MouseButton::Middle,
141                    3 => MouseButton::Navigate(NavigationDirection::Back),
142                    4 => MouseButton::Navigate(NavigationDirection::Forward),
143                    // Other mouse buttons aren't tracked currently
144                    _ => return None,
145                };
146
147                window_height.map(|window_height| {
148                    Self::MouseUp(MouseUpEvent {
149                        button,
150                        position: point(
151                            px(native_event.locationInWindow().x as f32),
152                            window_height - px(native_event.locationInWindow().y as f32),
153                        ),
154                        modifiers: read_modifiers(native_event),
155                        click_count: native_event.clickCount() as usize,
156                    })
157                })
158            }
159            NSEventType::NSScrollWheel => window_height.map(|window_height| {
160                let phase = match native_event.phase() {
161                    NSEventPhase::NSEventPhaseMayBegin | NSEventPhase::NSEventPhaseBegan => {
162                        TouchPhase::Started
163                    }
164                    NSEventPhase::NSEventPhaseEnded => TouchPhase::Ended,
165                    _ => TouchPhase::Moved,
166                };
167
168                let raw_data = point(
169                    native_event.scrollingDeltaX() as f32,
170                    native_event.scrollingDeltaY() as f32,
171                );
172
173                let delta = if native_event.hasPreciseScrollingDeltas() == YES {
174                    ScrollDelta::Pixels(raw_data.map(px))
175                } else {
176                    ScrollDelta::Lines(raw_data)
177                };
178
179                Self::ScrollWheel(ScrollWheelEvent {
180                    position: point(
181                        px(native_event.locationInWindow().x as f32),
182                        window_height - px(native_event.locationInWindow().y as f32),
183                    ),
184                    delta,
185                    touch_phase: phase,
186                    modifiers: read_modifiers(native_event),
187                })
188            }),
189            NSEventType::NSLeftMouseDragged
190            | NSEventType::NSRightMouseDragged
191            | NSEventType::NSOtherMouseDragged => {
192                let pressed_button = match native_event.buttonNumber() {
193                    0 => MouseButton::Left,
194                    1 => MouseButton::Right,
195                    2 => MouseButton::Middle,
196                    3 => MouseButton::Navigate(NavigationDirection::Back),
197                    4 => MouseButton::Navigate(NavigationDirection::Forward),
198                    // Other mouse buttons aren't tracked currently
199                    _ => return None,
200                };
201
202                window_height.map(|window_height| {
203                    Self::MouseMove(MouseMoveEvent {
204                        pressed_button: Some(pressed_button),
205                        position: point(
206                            px(native_event.locationInWindow().x as f32),
207                            window_height - px(native_event.locationInWindow().y as f32),
208                        ),
209                        modifiers: read_modifiers(native_event),
210                    })
211                })
212            }
213            NSEventType::NSMouseMoved => window_height.map(|window_height| {
214                Self::MouseMove(MouseMoveEvent {
215                    position: point(
216                        px(native_event.locationInWindow().x as f32),
217                        window_height - px(native_event.locationInWindow().y as f32),
218                    ),
219                    pressed_button: None,
220                    modifiers: read_modifiers(native_event),
221                })
222            }),
223            NSEventType::NSMouseExited => window_height.map(|window_height| {
224                Self::MouseExited(MouseExitEvent {
225                    position: point(
226                        px(native_event.locationInWindow().x as f32),
227                        window_height - px(native_event.locationInWindow().y as f32),
228                    ),
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 control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
251    let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
252    let mut shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
253    let command = 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 command && 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        modifiers: Modifiers {
319            control,
320            alt,
321            shift,
322            command,
323            function,
324        },
325        key,
326        ime_key: None,
327    }
328}
329
330fn chars_for_modified_key(code: CGKeyCode, cmd: bool, shift: bool) -> String {
331    // Ideally, we would use `[NSEvent charactersByApplyingModifiers]` but that
332    // always returns an empty string with certain keyboards, e.g. Japanese. Synthesizing
333    // an event with the given flags instead lets us access `characters`, which always
334    // returns a valid string.
335    let source = unsafe { core_graphics::event_source::CGEventSource::from_ptr(EVENT_SOURCE) };
336    let event = CGEvent::new_keyboard_event(source.clone(), code, true).unwrap();
337    mem::forget(source);
338
339    let mut flags = CGEventFlags::empty();
340    if cmd {
341        flags |= CGEventFlags::CGEventFlagCommand;
342    }
343    if shift {
344        flags |= CGEventFlags::CGEventFlagShift;
345    }
346    event.set_flags(flags);
347
348    unsafe {
349        let event: id = msg_send![class!(NSEvent), eventWithCGEvent: &*event];
350        CStr::from_ptr(event.characters().UTF8String())
351            .to_str()
352            .unwrap()
353            .to_string()
354    }
355}