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