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