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 "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 let raw_data = vec2f(
168 native_event.scrollingDeltaX() as f32,
169 native_event.scrollingDeltaY() as f32,
170 );
171
172 let delta = if native_event.hasPreciseScrollingDeltas() == YES {
173 ScrollDelta::Pixels(raw_data)
174 } else {
175 ScrollDelta::Lines(raw_data)
176 };
177
178 Self::ScrollWheel(ScrollWheelEvent {
179 position: vec2f(
180 native_event.locationInWindow().x as f32,
181 window_height - native_event.locationInWindow().y as f32,
182 ),
183 delta,
184 phase,
185 modifiers: read_modifiers(native_event),
186 })
187 }),
188 NSEventType::NSLeftMouseDragged
189 | NSEventType::NSRightMouseDragged
190 | NSEventType::NSOtherMouseDragged => {
191 let pressed_button = match native_event.buttonNumber() {
192 0 => MouseButton::Left,
193 1 => MouseButton::Right,
194 2 => MouseButton::Middle,
195 3 => MouseButton::Navigate(NavigationDirection::Back),
196 4 => MouseButton::Navigate(NavigationDirection::Forward),
197 // Other mouse buttons aren't tracked currently
198 _ => return None,
199 };
200
201 window_height.map(|window_height| {
202 Self::MouseMoved(MouseMovedEvent {
203 pressed_button: Some(pressed_button),
204 position: vec2f(
205 native_event.locationInWindow().x as f32,
206 window_height - native_event.locationInWindow().y as f32,
207 ),
208 modifiers: read_modifiers(native_event),
209 })
210 })
211 }
212 NSEventType::NSMouseMoved => window_height.map(|window_height| {
213 Self::MouseMoved(MouseMovedEvent {
214 position: vec2f(
215 native_event.locationInWindow().x as f32,
216 window_height - native_event.locationInWindow().y as f32,
217 ),
218 pressed_button: None,
219 modifiers: read_modifiers(native_event),
220 })
221 }),
222 _ => None,
223 }
224 }
225}
226
227unsafe fn parse_keystroke(native_event: id) -> Keystroke {
228 use cocoa::appkit::*;
229
230 let mut chars_ignoring_modifiers =
231 CStr::from_ptr(native_event.charactersIgnoringModifiers().UTF8String() as *mut c_char)
232 .to_str()
233 .unwrap()
234 .to_string();
235 let first_char = chars_ignoring_modifiers.chars().next().map(|ch| ch as u16);
236 let modifiers = native_event.modifierFlags();
237
238 let ctrl = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
239 let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
240 let mut shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
241 let cmd = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
242 let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask)
243 && first_char.map_or(true, |ch| {
244 !(NSUpArrowFunctionKey..=NSModeSwitchFunctionKey).contains(&ch)
245 });
246
247 #[allow(non_upper_case_globals)]
248 let key = match first_char {
249 Some(SPACE_KEY) => "space".to_string(),
250 Some(BACKSPACE_KEY) => "backspace".to_string(),
251 Some(ENTER_KEY) | Some(NUMPAD_ENTER_KEY) => "enter".to_string(),
252 Some(ESCAPE_KEY) => "escape".to_string(),
253 Some(TAB_KEY) => "tab".to_string(),
254 Some(SHIFT_TAB_KEY) => "tab".to_string(),
255 Some(NSUpArrowFunctionKey) => "up".to_string(),
256 Some(NSDownArrowFunctionKey) => "down".to_string(),
257 Some(NSLeftArrowFunctionKey) => "left".to_string(),
258 Some(NSRightArrowFunctionKey) => "right".to_string(),
259 Some(NSPageUpFunctionKey) => "pageup".to_string(),
260 Some(NSPageDownFunctionKey) => "pagedown".to_string(),
261 Some(NSDeleteFunctionKey) => "delete".to_string(),
262 Some(NSF1FunctionKey) => "f1".to_string(),
263 Some(NSF2FunctionKey) => "f2".to_string(),
264 Some(NSF3FunctionKey) => "f3".to_string(),
265 Some(NSF4FunctionKey) => "f4".to_string(),
266 Some(NSF5FunctionKey) => "f5".to_string(),
267 Some(NSF6FunctionKey) => "f6".to_string(),
268 Some(NSF7FunctionKey) => "f7".to_string(),
269 Some(NSF8FunctionKey) => "f8".to_string(),
270 Some(NSF9FunctionKey) => "f9".to_string(),
271 Some(NSF10FunctionKey) => "f10".to_string(),
272 Some(NSF11FunctionKey) => "f11".to_string(),
273 Some(NSF12FunctionKey) => "f12".to_string(),
274 _ => {
275 let mut chars_ignoring_modifiers_and_shift =
276 chars_for_modified_key(native_event.keyCode(), false, false);
277
278 // Honor ⌘ when Dvorak-QWERTY is used.
279 let chars_with_cmd = chars_for_modified_key(native_event.keyCode(), true, false);
280 if cmd && chars_ignoring_modifiers_and_shift != chars_with_cmd {
281 chars_ignoring_modifiers =
282 chars_for_modified_key(native_event.keyCode(), true, shift);
283 chars_ignoring_modifiers_and_shift = chars_with_cmd;
284 }
285
286 if shift {
287 if chars_ignoring_modifiers_and_shift
288 == chars_ignoring_modifiers.to_ascii_lowercase()
289 {
290 chars_ignoring_modifiers_and_shift
291 } else if chars_ignoring_modifiers_and_shift != chars_ignoring_modifiers {
292 shift = false;
293 chars_ignoring_modifiers
294 } else {
295 chars_ignoring_modifiers
296 }
297 } else {
298 chars_ignoring_modifiers
299 }
300 }
301 };
302
303 Keystroke {
304 ctrl,
305 alt,
306 shift,
307 cmd,
308 function,
309 key,
310 }
311}
312
313fn chars_for_modified_key(code: CGKeyCode, cmd: bool, shift: bool) -> String {
314 // Ideally, we would use `[NSEvent charactersByApplyingModifiers]` but that
315 // always returns an empty string with certain keyboards, e.g. Japanese. Synthesizing
316 // an event with the given flags instead lets us access `characters`, which always
317 // returns a valid string.
318 let source = unsafe { core_graphics::event_source::CGEventSource::from_ptr(EVENT_SOURCE) };
319 let event = CGEvent::new_keyboard_event(source.clone(), code, true).unwrap();
320 mem::forget(source);
321
322 let mut flags = CGEventFlags::empty();
323 if cmd {
324 flags |= CGEventFlags::CGEventFlagCommand;
325 }
326 if shift {
327 flags |= CGEventFlags::CGEventFlagShift;
328 }
329 event.set_flags(flags);
330
331 unsafe {
332 let event: id = msg_send![class!(NSEvent), eventWithCGEvent: &*event];
333 CStr::from_ptr(event.characters().UTF8String())
334 .to_str()
335 .unwrap()
336 .to_string()
337 }
338}