1use crate::{
2 geometry::vector::vec2f,
3 keymap_matcher::Keystroke,
4 platform::{
5 Event, KeyDownEvent, KeyUpEvent, Modifiers, ModifiersChangedEvent, MouseButton,
6 MouseButtonEvent, MouseExitedEvent, MouseMovedEvent, NavigationDirection, ScrollDelta,
7 ScrollWheelEvent, TouchPhase,
8 },
9};
10use cocoa::{
11 appkit::{NSEvent, NSEventModifierFlags, NSEventPhase, NSEventType},
12 base::{id, YES},
13 foundation::NSString as _,
14};
15use core_graphics::{
16 event::{CGEvent, CGEventFlags, CGKeyCode},
17 event_source::{CGEventSource, CGEventSourceStateID},
18};
19use ctor::ctor;
20use foreign_types::ForeignType;
21use objc::{class, msg_send, sel, sel_impl};
22use std::{borrow::Cow, ffi::CStr, mem, os::raw::c_char, ptr};
23
24const BACKSPACE_KEY: u16 = 0x7f;
25const SPACE_KEY: u16 = b' ' as u16;
26const ENTER_KEY: u16 = 0x0d;
27const NUMPAD_ENTER_KEY: u16 = 0x03;
28const ESCAPE_KEY: u16 = 0x1b;
29const TAB_KEY: u16 = 0x09;
30const SHIFT_TAB_KEY: u16 = 0x19;
31
32static mut EVENT_SOURCE: core_graphics::sys::CGEventSourceRef = ptr::null_mut();
33
34#[ctor]
35unsafe fn build_event_source() {
36 let source = CGEventSource::new(CGEventSourceStateID::Private).unwrap();
37 EVENT_SOURCE = source.as_ptr();
38 mem::forget(source);
39}
40
41pub fn key_to_native(key: &str) -> Cow<str> {
42 use cocoa::appkit::*;
43 let code = match key {
44 "space" => SPACE_KEY,
45 "backspace" => BACKSPACE_KEY,
46 "up" => NSUpArrowFunctionKey,
47 "down" => NSDownArrowFunctionKey,
48 "left" => NSLeftArrowFunctionKey,
49 "right" => NSRightArrowFunctionKey,
50 "pageup" => NSPageUpFunctionKey,
51 "pagedown" => NSPageDownFunctionKey,
52 "home" => NSHomeFunctionKey,
53 "end" => NSEndFunctionKey,
54 "delete" => NSDeleteFunctionKey,
55 "f1" => NSF1FunctionKey,
56 "f2" => NSF2FunctionKey,
57 "f3" => NSF3FunctionKey,
58 "f4" => NSF4FunctionKey,
59 "f5" => NSF5FunctionKey,
60 "f6" => NSF6FunctionKey,
61 "f7" => NSF7FunctionKey,
62 "f8" => NSF8FunctionKey,
63 "f9" => NSF9FunctionKey,
64 "f10" => NSF10FunctionKey,
65 "f11" => NSF11FunctionKey,
66 "f12" => NSF12FunctionKey,
67 _ => return Cow::Borrowed(key),
68 };
69 Cow::Owned(String::from_utf16(&[code]).unwrap())
70}
71
72unsafe fn read_modifiers(native_event: id) -> Modifiers {
73 let modifiers = native_event.modifierFlags();
74 let ctrl = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
75 let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
76 let shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
77 let cmd = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
78 let fun = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask);
79
80 Modifiers {
81 ctrl,
82 alt,
83 shift,
84 cmd,
85 fun,
86 }
87}
88
89impl Event {
90 pub unsafe fn from_native(native_event: id, window_height: Option<f32>) -> Option<Self> {
91 let event_type = native_event.eventType();
92
93 // Filter out event types that aren't in the NSEventType enum.
94 // See https://github.com/servo/cocoa-rs/issues/155#issuecomment-323482792 for details.
95 match event_type as u64 {
96 0 | 21 | 32 | 33 | 35 | 36 | 37 => {
97 return None;
98 }
99 _ => {}
100 }
101
102 match event_type {
103 NSEventType::NSFlagsChanged => Some(Self::ModifiersChanged(ModifiersChangedEvent {
104 modifiers: read_modifiers(native_event),
105 })),
106 NSEventType::NSKeyDown => Some(Self::KeyDown(KeyDownEvent {
107 keystroke: parse_keystroke(native_event),
108 is_held: native_event.isARepeat() == YES,
109 })),
110 NSEventType::NSKeyUp => Some(Self::KeyUp(KeyUpEvent {
111 keystroke: parse_keystroke(native_event),
112 })),
113 NSEventType::NSLeftMouseDown
114 | NSEventType::NSRightMouseDown
115 | NSEventType::NSOtherMouseDown => {
116 let button = match native_event.buttonNumber() {
117 0 => MouseButton::Left,
118 1 => MouseButton::Right,
119 2 => MouseButton::Middle,
120 3 => MouseButton::Navigate(NavigationDirection::Back),
121 4 => MouseButton::Navigate(NavigationDirection::Forward),
122 // Other mouse buttons aren't tracked currently
123 _ => return None,
124 };
125 window_height.map(|window_height| {
126 Self::MouseDown(MouseButtonEvent {
127 button,
128 position: vec2f(
129 native_event.locationInWindow().x as f32,
130 // MacOS screen coordinates are relative to bottom left
131 window_height - native_event.locationInWindow().y as f32,
132 ),
133 modifiers: read_modifiers(native_event),
134 click_count: native_event.clickCount() as usize,
135 is_down: true,
136 })
137 })
138 }
139 NSEventType::NSLeftMouseUp
140 | NSEventType::NSRightMouseUp
141 | NSEventType::NSOtherMouseUp => {
142 let button = match native_event.buttonNumber() {
143 0 => MouseButton::Left,
144 1 => MouseButton::Right,
145 2 => MouseButton::Middle,
146 3 => MouseButton::Navigate(NavigationDirection::Back),
147 4 => MouseButton::Navigate(NavigationDirection::Forward),
148 // Other mouse buttons aren't tracked currently
149 _ => return None,
150 };
151
152 window_height.map(|window_height| {
153 Self::MouseUp(MouseButtonEvent {
154 button,
155 position: vec2f(
156 native_event.locationInWindow().x as f32,
157 // MacOS view coordinates are relative to bottom left
158 window_height - native_event.locationInWindow().y as f32,
159 ),
160 modifiers: read_modifiers(native_event),
161 click_count: native_event.clickCount() as usize,
162 is_down: false,
163 })
164 })
165 }
166 NSEventType::NSScrollWheel => window_height.map(|window_height| {
167 let phase = match native_event.phase() {
168 NSEventPhase::NSEventPhaseMayBegin | NSEventPhase::NSEventPhaseBegan => {
169 Some(TouchPhase::Started)
170 }
171 NSEventPhase::NSEventPhaseEnded => Some(TouchPhase::Ended),
172 _ => Some(TouchPhase::Moved),
173 };
174
175 let raw_data = vec2f(
176 native_event.scrollingDeltaX() as f32,
177 native_event.scrollingDeltaY() as f32,
178 );
179
180 let delta = if native_event.hasPreciseScrollingDeltas() == YES {
181 ScrollDelta::Pixels(raw_data)
182 } else {
183 ScrollDelta::Lines(raw_data)
184 };
185
186 Self::ScrollWheel(ScrollWheelEvent {
187 position: vec2f(
188 native_event.locationInWindow().x as f32,
189 window_height - native_event.locationInWindow().y as f32,
190 ),
191 delta,
192 phase,
193 modifiers: read_modifiers(native_event),
194 })
195 }),
196 NSEventType::NSLeftMouseDragged
197 | NSEventType::NSRightMouseDragged
198 | NSEventType::NSOtherMouseDragged => {
199 let pressed_button = match native_event.buttonNumber() {
200 0 => MouseButton::Left,
201 1 => MouseButton::Right,
202 2 => MouseButton::Middle,
203 3 => MouseButton::Navigate(NavigationDirection::Back),
204 4 => MouseButton::Navigate(NavigationDirection::Forward),
205 // Other mouse buttons aren't tracked currently
206 _ => return None,
207 };
208
209 window_height.map(|window_height| {
210 Self::MouseMoved(MouseMovedEvent {
211 pressed_button: Some(pressed_button),
212 position: vec2f(
213 native_event.locationInWindow().x as f32,
214 window_height - native_event.locationInWindow().y as f32,
215 ),
216 modifiers: read_modifiers(native_event),
217 })
218 })
219 }
220 NSEventType::NSMouseMoved => window_height.map(|window_height| {
221 Self::MouseMoved(MouseMovedEvent {
222 position: vec2f(
223 native_event.locationInWindow().x as f32,
224 window_height - native_event.locationInWindow().y as f32,
225 ),
226 pressed_button: None,
227 modifiers: read_modifiers(native_event),
228 })
229 }),
230 NSEventType::NSMouseExited => window_height.map(|window_height| {
231 Self::MouseExited(MouseExitedEvent {
232 position: vec2f(
233 native_event.locationInWindow().x as f32,
234 window_height - native_event.locationInWindow().y as f32,
235 ),
236 pressed_button: None,
237 modifiers: read_modifiers(native_event),
238 })
239 }),
240 _ => None,
241 }
242 }
243}
244
245unsafe fn parse_keystroke(native_event: id) -> Keystroke {
246 use cocoa::appkit::*;
247
248 let mut chars_ignoring_modifiers =
249 CStr::from_ptr(native_event.charactersIgnoringModifiers().UTF8String() as *mut c_char)
250 .to_str()
251 .unwrap()
252 .to_string();
253 let first_char = chars_ignoring_modifiers.chars().next().map(|ch| ch as u16);
254 let modifiers = native_event.modifierFlags();
255
256 let ctrl = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
257 let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
258 let mut shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
259 let cmd = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
260 let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask)
261 && first_char.map_or(true, |ch| {
262 !(NSUpArrowFunctionKey..=NSModeSwitchFunctionKey).contains(&ch)
263 });
264
265 #[allow(non_upper_case_globals)]
266 let key = match first_char {
267 Some(SPACE_KEY) => "space".to_string(),
268 Some(BACKSPACE_KEY) => "backspace".to_string(),
269 Some(ENTER_KEY) | Some(NUMPAD_ENTER_KEY) => "enter".to_string(),
270 Some(ESCAPE_KEY) => "escape".to_string(),
271 Some(TAB_KEY) => "tab".to_string(),
272 Some(SHIFT_TAB_KEY) => "tab".to_string(),
273 Some(NSUpArrowFunctionKey) => "up".to_string(),
274 Some(NSDownArrowFunctionKey) => "down".to_string(),
275 Some(NSLeftArrowFunctionKey) => "left".to_string(),
276 Some(NSRightArrowFunctionKey) => "right".to_string(),
277 Some(NSPageUpFunctionKey) => "pageup".to_string(),
278 Some(NSPageDownFunctionKey) => "pagedown".to_string(),
279 Some(NSHomeFunctionKey) => "home".to_string(),
280 Some(NSEndFunctionKey) => "end".to_string(),
281 Some(NSDeleteFunctionKey) => "delete".to_string(),
282 Some(NSF1FunctionKey) => "f1".to_string(),
283 Some(NSF2FunctionKey) => "f2".to_string(),
284 Some(NSF3FunctionKey) => "f3".to_string(),
285 Some(NSF4FunctionKey) => "f4".to_string(),
286 Some(NSF5FunctionKey) => "f5".to_string(),
287 Some(NSF6FunctionKey) => "f6".to_string(),
288 Some(NSF7FunctionKey) => "f7".to_string(),
289 Some(NSF8FunctionKey) => "f8".to_string(),
290 Some(NSF9FunctionKey) => "f9".to_string(),
291 Some(NSF10FunctionKey) => "f10".to_string(),
292 Some(NSF11FunctionKey) => "f11".to_string(),
293 Some(NSF12FunctionKey) => "f12".to_string(),
294 _ => {
295 let mut chars_ignoring_modifiers_and_shift =
296 chars_for_modified_key(native_event.keyCode(), false, false);
297
298 // Honor ⌘ when Dvorak-QWERTY is used.
299 let chars_with_cmd = chars_for_modified_key(native_event.keyCode(), true, false);
300 if cmd && chars_ignoring_modifiers_and_shift != chars_with_cmd {
301 chars_ignoring_modifiers =
302 chars_for_modified_key(native_event.keyCode(), true, shift);
303 chars_ignoring_modifiers_and_shift = chars_with_cmd;
304 }
305
306 if shift {
307 if chars_ignoring_modifiers_and_shift
308 == chars_ignoring_modifiers.to_ascii_lowercase()
309 {
310 chars_ignoring_modifiers_and_shift
311 } else if chars_ignoring_modifiers_and_shift != chars_ignoring_modifiers {
312 shift = false;
313 chars_ignoring_modifiers
314 } else {
315 chars_ignoring_modifiers
316 }
317 } else {
318 chars_ignoring_modifiers
319 }
320 }
321 };
322
323 Keystroke {
324 ctrl,
325 alt,
326 shift,
327 cmd,
328 function,
329 key,
330 ime_key: None,
331 }
332}
333
334fn chars_for_modified_key(code: CGKeyCode, cmd: bool, shift: bool) -> String {
335 // Ideally, we would use `[NSEvent charactersByApplyingModifiers]` but that
336 // always returns an empty string with certain keyboards, e.g. Japanese. Synthesizing
337 // an event with the given flags instead lets us access `characters`, which always
338 // returns a valid string.
339 let source = unsafe { core_graphics::event_source::CGEventSource::from_ptr(EVENT_SOURCE) };
340 let event = CGEvent::new_keyboard_event(source.clone(), code, true).unwrap();
341 mem::forget(source);
342
343 let mut flags = CGEventFlags::empty();
344 if cmd {
345 flags |= CGEventFlags::CGEventFlagCommand;
346 }
347 if shift {
348 flags |= CGEventFlags::CGEventFlagShift;
349 }
350 event.set_flags(flags);
351
352 unsafe {
353 let event: id = msg_send![class!(NSEvent), eventWithCGEvent: &*event];
354 CStr::from_ptr(event.characters().UTF8String())
355 .to_str()
356 .unwrap()
357 .to_string()
358 }
359}