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