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