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