1use crate::{
2 geometry::vector::vec2f,
3 keymap::Keystroke,
4 platform::{Event, NavigationDirection},
5 KeyDownEvent, KeyUpEvent, Modifiers, ModifiersChangedEvent, MouseButton, MouseButtonEvent,
6 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 _ => None,
225 }
226 }
227}
228
229unsafe fn parse_keystroke(native_event: id) -> Keystroke {
230 use cocoa::appkit::*;
231
232 let mut chars_ignoring_modifiers =
233 CStr::from_ptr(native_event.charactersIgnoringModifiers().UTF8String() as *mut c_char)
234 .to_str()
235 .unwrap()
236 .to_string();
237 let first_char = chars_ignoring_modifiers.chars().next().map(|ch| ch as u16);
238 let modifiers = native_event.modifierFlags();
239
240 let ctrl = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
241 let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
242 let mut shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
243 let cmd = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
244 let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask)
245 && first_char.map_or(true, |ch| {
246 !(NSUpArrowFunctionKey..=NSModeSwitchFunctionKey).contains(&ch)
247 });
248
249 #[allow(non_upper_case_globals)]
250 let key = match first_char {
251 Some(SPACE_KEY) => "space".to_string(),
252 Some(BACKSPACE_KEY) => "backspace".to_string(),
253 Some(ENTER_KEY) | Some(NUMPAD_ENTER_KEY) => "enter".to_string(),
254 Some(ESCAPE_KEY) => "escape".to_string(),
255 Some(TAB_KEY) => "tab".to_string(),
256 Some(SHIFT_TAB_KEY) => "tab".to_string(),
257 Some(NSUpArrowFunctionKey) => "up".to_string(),
258 Some(NSDownArrowFunctionKey) => "down".to_string(),
259 Some(NSLeftArrowFunctionKey) => "left".to_string(),
260 Some(NSRightArrowFunctionKey) => "right".to_string(),
261 Some(NSPageUpFunctionKey) => "pageup".to_string(),
262 Some(NSPageDownFunctionKey) => "pagedown".to_string(),
263 Some(NSHomeFunctionKey) => "home".to_string(),
264 Some(NSEndFunctionKey) => "end".to_string(),
265 Some(NSDeleteFunctionKey) => "delete".to_string(),
266 Some(NSF1FunctionKey) => "f1".to_string(),
267 Some(NSF2FunctionKey) => "f2".to_string(),
268 Some(NSF3FunctionKey) => "f3".to_string(),
269 Some(NSF4FunctionKey) => "f4".to_string(),
270 Some(NSF5FunctionKey) => "f5".to_string(),
271 Some(NSF6FunctionKey) => "f6".to_string(),
272 Some(NSF7FunctionKey) => "f7".to_string(),
273 Some(NSF8FunctionKey) => "f8".to_string(),
274 Some(NSF9FunctionKey) => "f9".to_string(),
275 Some(NSF10FunctionKey) => "f10".to_string(),
276 Some(NSF11FunctionKey) => "f11".to_string(),
277 Some(NSF12FunctionKey) => "f12".to_string(),
278 _ => {
279 let mut chars_ignoring_modifiers_and_shift =
280 chars_for_modified_key(native_event.keyCode(), false, false);
281
282 // Honor ⌘ when Dvorak-QWERTY is used.
283 let chars_with_cmd = chars_for_modified_key(native_event.keyCode(), true, false);
284 if cmd && chars_ignoring_modifiers_and_shift != chars_with_cmd {
285 chars_ignoring_modifiers =
286 chars_for_modified_key(native_event.keyCode(), true, shift);
287 chars_ignoring_modifiers_and_shift = chars_with_cmd;
288 }
289
290 if shift {
291 if chars_ignoring_modifiers_and_shift
292 == chars_ignoring_modifiers.to_ascii_lowercase()
293 {
294 chars_ignoring_modifiers_and_shift
295 } else if chars_ignoring_modifiers_and_shift != chars_ignoring_modifiers {
296 shift = false;
297 chars_ignoring_modifiers
298 } else {
299 chars_ignoring_modifiers
300 }
301 } else {
302 chars_ignoring_modifiers
303 }
304 }
305 };
306
307 Keystroke {
308 ctrl,
309 alt,
310 shift,
311 cmd,
312 function,
313 key,
314 }
315}
316
317fn chars_for_modified_key(code: CGKeyCode, cmd: bool, shift: bool) -> String {
318 // Ideally, we would use `[NSEvent charactersByApplyingModifiers]` but that
319 // always returns an empty string with certain keyboards, e.g. Japanese. Synthesizing
320 // an event with the given flags instead lets us access `characters`, which always
321 // returns a valid string.
322 let source = unsafe { core_graphics::event_source::CGEventSource::from_ptr(EVENT_SOURCE) };
323 let event = CGEvent::new_keyboard_event(source.clone(), code, true).unwrap();
324 mem::forget(source);
325
326 let mut flags = CGEventFlags::empty();
327 if cmd {
328 flags |= CGEventFlags::CGEventFlagCommand;
329 }
330 if shift {
331 flags |= CGEventFlags::CGEventFlagShift;
332 }
333 event.set_flags(flags);
334
335 unsafe {
336 let event: id = msg_send![class!(NSEvent), eventWithCGEvent: &*event];
337 CStr::from_ptr(event.characters().UTF8String())
338 .to_str()
339 .unwrap()
340 .to_string()
341 }
342}