1use crate::{
2 KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, ModifiersChangedEvent, MouseButton,
3 MouseDownEvent, MouseExitEvent, MouseMoveEvent, MouseUpEvent, NavigationDirection, Pixels,
4 PlatformInput, ScrollDelta, ScrollWheelEvent, TouchPhase,
5 platform::mac::{
6 LMGetKbdType, NSStringExt, TISCopyCurrentKeyboardLayoutInputSource,
7 TISGetInputSourceProperty, UCKeyTranslate, kTISPropertyUnicodeKeyLayoutData,
8 },
9 point, px,
10};
11use cocoa::{
12 appkit::{NSEvent, NSEventModifierFlags, NSEventPhase, NSEventType},
13 base::{YES, id},
14};
15use core_foundation::data::{CFDataGetBytePtr, CFDataRef};
16use core_graphics::event::CGKeyCode;
17use objc::{msg_send, sel, sel_impl};
18use std::{borrow::Cow, ffi::c_void};
19
20const BACKSPACE_KEY: u16 = 0x7f;
21const SPACE_KEY: u16 = b' ' as u16;
22const ENTER_KEY: u16 = 0x0d;
23const NUMPAD_ENTER_KEY: u16 = 0x03;
24pub(crate) const 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 "escape" => ESCAPE_KEY,
34 "up" => NSUpArrowFunctionKey,
35 "down" => NSDownArrowFunctionKey,
36 "left" => NSLeftArrowFunctionKey,
37 "right" => NSRightArrowFunctionKey,
38 "pageup" => NSPageUpFunctionKey,
39 "pagedown" => NSPageDownFunctionKey,
40 "home" => NSHomeFunctionKey,
41 "end" => NSEndFunctionKey,
42 "delete" => NSDeleteFunctionKey,
43 "insert" => NSHelpFunctionKey,
44 "f1" => NSF1FunctionKey,
45 "f2" => NSF2FunctionKey,
46 "f3" => NSF3FunctionKey,
47 "f4" => NSF4FunctionKey,
48 "f5" => NSF5FunctionKey,
49 "f6" => NSF6FunctionKey,
50 "f7" => NSF7FunctionKey,
51 "f8" => NSF8FunctionKey,
52 "f9" => NSF9FunctionKey,
53 "f10" => NSF10FunctionKey,
54 "f11" => NSF11FunctionKey,
55 "f12" => NSF12FunctionKey,
56 "f13" => NSF13FunctionKey,
57 "f14" => NSF14FunctionKey,
58 "f15" => NSF15FunctionKey,
59 "f16" => NSF16FunctionKey,
60 "f17" => NSF17FunctionKey,
61 "f18" => NSF18FunctionKey,
62 "f19" => NSF19FunctionKey,
63 "f20" => NSF20FunctionKey,
64 "f21" => NSF21FunctionKey,
65 "f22" => NSF22FunctionKey,
66 "f23" => NSF23FunctionKey,
67 "f24" => NSF24FunctionKey,
68 "f25" => NSF25FunctionKey,
69 "f26" => NSF26FunctionKey,
70 "f27" => NSF27FunctionKey,
71 "f28" => NSF28FunctionKey,
72 "f29" => NSF29FunctionKey,
73 "f30" => NSF30FunctionKey,
74 "f31" => NSF31FunctionKey,
75 "f32" => NSF32FunctionKey,
76 "f33" => NSF33FunctionKey,
77 "f34" => NSF34FunctionKey,
78 "f35" => NSF35FunctionKey,
79 _ => return Cow::Borrowed(key),
80 };
81 Cow::Owned(String::from_utf16(&[code]).unwrap())
82}
83
84unsafe fn read_modifiers(native_event: id) -> Modifiers {
85 unsafe {
86 let modifiers = native_event.modifierFlags();
87 let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
88 let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
89 let shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
90 let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
91 let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask);
92
93 Modifiers {
94 control,
95 alt,
96 shift,
97 platform: command,
98 function,
99 }
100 }
101}
102
103impl PlatformInput {
104 pub(crate) unsafe fn from_native(
105 native_event: id,
106 window_height: Option<Pixels>,
107 ) -> Option<Self> {
108 unsafe {
109 let event_type = native_event.eventType();
110
111 // Filter out event types that aren't in the NSEventType enum.
112 // See https://github.com/servo/cocoa-rs/issues/155#issuecomment-323482792 for details.
113 match event_type as u64 {
114 0 | 21 | 32 | 33 | 35 | 36 | 37 => {
115 return None;
116 }
117 _ => {}
118 }
119
120 match event_type {
121 NSEventType::NSFlagsChanged => {
122 Some(Self::ModifiersChanged(ModifiersChangedEvent {
123 modifiers: read_modifiers(native_event),
124 }))
125 }
126 NSEventType::NSKeyDown => Some(Self::KeyDown(KeyDownEvent {
127 keystroke: parse_keystroke(native_event),
128 is_held: native_event.isARepeat() == YES,
129 })),
130 NSEventType::NSKeyUp => Some(Self::KeyUp(KeyUpEvent {
131 keystroke: parse_keystroke(native_event),
132 })),
133 NSEventType::NSLeftMouseDown
134 | NSEventType::NSRightMouseDown
135 | NSEventType::NSOtherMouseDown => {
136 let button = match native_event.buttonNumber() {
137 0 => MouseButton::Left,
138 1 => MouseButton::Right,
139 2 => MouseButton::Middle,
140 3 => MouseButton::Navigate(NavigationDirection::Back),
141 4 => MouseButton::Navigate(NavigationDirection::Forward),
142 // Other mouse buttons aren't tracked currently
143 _ => return None,
144 };
145 window_height.map(|window_height| {
146 Self::MouseDown(MouseDownEvent {
147 button,
148 position: point(
149 px(native_event.locationInWindow().x as f32),
150 // MacOS screen coordinates are relative to bottom left
151 window_height - px(native_event.locationInWindow().y as f32),
152 ),
153 modifiers: read_modifiers(native_event),
154 click_count: native_event.clickCount() as usize,
155 first_mouse: false,
156 })
157 })
158 }
159 NSEventType::NSLeftMouseUp
160 | NSEventType::NSRightMouseUp
161 | NSEventType::NSOtherMouseUp => {
162 let button = match native_event.buttonNumber() {
163 0 => MouseButton::Left,
164 1 => MouseButton::Right,
165 2 => MouseButton::Middle,
166 3 => MouseButton::Navigate(NavigationDirection::Back),
167 4 => MouseButton::Navigate(NavigationDirection::Forward),
168 // Other mouse buttons aren't tracked currently
169 _ => return None,
170 };
171
172 window_height.map(|window_height| {
173 Self::MouseUp(MouseUpEvent {
174 button,
175 position: point(
176 px(native_event.locationInWindow().x as f32),
177 window_height - px(native_event.locationInWindow().y as f32),
178 ),
179 modifiers: read_modifiers(native_event),
180 click_count: native_event.clickCount() as usize,
181 })
182 })
183 }
184 // Some mice (like Logitech MX Master) send navigation buttons as swipe events
185 NSEventType::NSEventTypeSwipe => {
186 let navigation_direction = match native_event.phase() {
187 NSEventPhase::NSEventPhaseEnded => match native_event.deltaX() {
188 x if x > 0.0 => Some(NavigationDirection::Back),
189 x if x < 0.0 => Some(NavigationDirection::Forward),
190 _ => return None,
191 },
192 _ => return None,
193 };
194
195 match navigation_direction {
196 Some(direction) => window_height.map(|window_height| {
197 Self::MouseDown(MouseDownEvent {
198 button: MouseButton::Navigate(direction),
199 position: point(
200 px(native_event.locationInWindow().x as f32),
201 window_height - px(native_event.locationInWindow().y as f32),
202 ),
203 modifiers: read_modifiers(native_event),
204 click_count: 1,
205 first_mouse: false,
206 })
207 }),
208 _ => None,
209 }
210 }
211 NSEventType::NSScrollWheel => window_height.map(|window_height| {
212 let phase = match native_event.phase() {
213 NSEventPhase::NSEventPhaseMayBegin | NSEventPhase::NSEventPhaseBegan => {
214 TouchPhase::Started
215 }
216 NSEventPhase::NSEventPhaseEnded => TouchPhase::Ended,
217 _ => TouchPhase::Moved,
218 };
219
220 let raw_data = point(
221 native_event.scrollingDeltaX() as f32,
222 native_event.scrollingDeltaY() as f32,
223 );
224
225 let delta = if native_event.hasPreciseScrollingDeltas() == YES {
226 ScrollDelta::Pixels(raw_data.map(px))
227 } else {
228 ScrollDelta::Lines(raw_data)
229 };
230
231 Self::ScrollWheel(ScrollWheelEvent {
232 position: point(
233 px(native_event.locationInWindow().x as f32),
234 window_height - px(native_event.locationInWindow().y as f32),
235 ),
236 delta,
237 touch_phase: phase,
238 modifiers: read_modifiers(native_event),
239 })
240 }),
241 NSEventType::NSLeftMouseDragged
242 | NSEventType::NSRightMouseDragged
243 | NSEventType::NSOtherMouseDragged => {
244 let pressed_button = match native_event.buttonNumber() {
245 0 => MouseButton::Left,
246 1 => MouseButton::Right,
247 2 => MouseButton::Middle,
248 3 => MouseButton::Navigate(NavigationDirection::Back),
249 4 => MouseButton::Navigate(NavigationDirection::Forward),
250 // Other mouse buttons aren't tracked currently
251 _ => return None,
252 };
253
254 window_height.map(|window_height| {
255 Self::MouseMove(MouseMoveEvent {
256 pressed_button: Some(pressed_button),
257 position: point(
258 px(native_event.locationInWindow().x as f32),
259 window_height - px(native_event.locationInWindow().y as f32),
260 ),
261 modifiers: read_modifiers(native_event),
262 })
263 })
264 }
265 NSEventType::NSMouseMoved => window_height.map(|window_height| {
266 Self::MouseMove(MouseMoveEvent {
267 position: point(
268 px(native_event.locationInWindow().x as f32),
269 window_height - px(native_event.locationInWindow().y as f32),
270 ),
271 pressed_button: None,
272 modifiers: read_modifiers(native_event),
273 })
274 }),
275 NSEventType::NSMouseExited => window_height.map(|window_height| {
276 Self::MouseExited(MouseExitEvent {
277 position: point(
278 px(native_event.locationInWindow().x as f32),
279 window_height - px(native_event.locationInWindow().y as f32),
280 ),
281
282 pressed_button: None,
283 modifiers: read_modifiers(native_event),
284 })
285 }),
286 _ => None,
287 }
288 }
289 }
290}
291
292unsafe fn parse_keystroke(native_event: id) -> Keystroke {
293 unsafe {
294 use cocoa::appkit::*;
295
296 let mut characters = native_event
297 .charactersIgnoringModifiers()
298 .to_str()
299 .to_string();
300 let mut key_char = None;
301 let first_char = characters.chars().next().map(|ch| ch as u16);
302 let modifiers = native_event.modifierFlags();
303
304 let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
305 let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
306 let mut shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
307 let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
308 let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask)
309 && first_char.map_or(true, |ch| {
310 !(NSUpArrowFunctionKey..=NSModeSwitchFunctionKey).contains(&ch)
311 });
312
313 #[allow(non_upper_case_globals)]
314 let key = match first_char {
315 Some(SPACE_KEY) => {
316 key_char = Some(" ".to_string());
317 "space".to_string()
318 }
319 Some(TAB_KEY) => {
320 key_char = Some("\t".to_string());
321 "tab".to_string()
322 }
323 Some(ENTER_KEY) | Some(NUMPAD_ENTER_KEY) => {
324 key_char = Some("\n".to_string());
325 "enter".to_string()
326 }
327 Some(BACKSPACE_KEY) => "backspace".to_string(),
328 Some(ESCAPE_KEY) => "escape".to_string(),
329 Some(SHIFT_TAB_KEY) => "tab".to_string(),
330 Some(NSUpArrowFunctionKey) => "up".to_string(),
331 Some(NSDownArrowFunctionKey) => "down".to_string(),
332 Some(NSLeftArrowFunctionKey) => "left".to_string(),
333 Some(NSRightArrowFunctionKey) => "right".to_string(),
334 Some(NSPageUpFunctionKey) => "pageup".to_string(),
335 Some(NSPageDownFunctionKey) => "pagedown".to_string(),
336 Some(NSHomeFunctionKey) => "home".to_string(),
337 Some(NSEndFunctionKey) => "end".to_string(),
338 Some(NSDeleteFunctionKey) => "delete".to_string(),
339 // Observed Insert==NSHelpFunctionKey not NSInsertFunctionKey.
340 Some(NSHelpFunctionKey) => "insert".to_string(),
341 Some(NSF1FunctionKey) => "f1".to_string(),
342 Some(NSF2FunctionKey) => "f2".to_string(),
343 Some(NSF3FunctionKey) => "f3".to_string(),
344 Some(NSF4FunctionKey) => "f4".to_string(),
345 Some(NSF5FunctionKey) => "f5".to_string(),
346 Some(NSF6FunctionKey) => "f6".to_string(),
347 Some(NSF7FunctionKey) => "f7".to_string(),
348 Some(NSF8FunctionKey) => "f8".to_string(),
349 Some(NSF9FunctionKey) => "f9".to_string(),
350 Some(NSF10FunctionKey) => "f10".to_string(),
351 Some(NSF11FunctionKey) => "f11".to_string(),
352 Some(NSF12FunctionKey) => "f12".to_string(),
353 Some(NSF13FunctionKey) => "f13".to_string(),
354 Some(NSF14FunctionKey) => "f14".to_string(),
355 Some(NSF15FunctionKey) => "f15".to_string(),
356 Some(NSF16FunctionKey) => "f16".to_string(),
357 Some(NSF17FunctionKey) => "f17".to_string(),
358 Some(NSF18FunctionKey) => "f18".to_string(),
359 Some(NSF19FunctionKey) => "f19".to_string(),
360 Some(NSF20FunctionKey) => "f20".to_string(),
361 Some(NSF21FunctionKey) => "f21".to_string(),
362 Some(NSF22FunctionKey) => "f22".to_string(),
363 Some(NSF23FunctionKey) => "f23".to_string(),
364 Some(NSF24FunctionKey) => "f24".to_string(),
365 Some(NSF25FunctionKey) => "f25".to_string(),
366 Some(NSF26FunctionKey) => "f26".to_string(),
367 Some(NSF27FunctionKey) => "f27".to_string(),
368 Some(NSF28FunctionKey) => "f28".to_string(),
369 Some(NSF29FunctionKey) => "f29".to_string(),
370 Some(NSF30FunctionKey) => "f30".to_string(),
371 Some(NSF31FunctionKey) => "f31".to_string(),
372 Some(NSF32FunctionKey) => "f32".to_string(),
373 Some(NSF33FunctionKey) => "f33".to_string(),
374 Some(NSF34FunctionKey) => "f34".to_string(),
375 Some(NSF35FunctionKey) => "f35".to_string(),
376 _ => {
377 // Cases to test when modifying this:
378 //
379 // qwerty key | none | cmd | cmd-shift
380 // * Armenian s | ս | cmd-s | cmd-shift-s (layout is non-ASCII, so we use cmd layout)
381 // * Dvorak+QWERTY s | o | cmd-s | cmd-shift-s (layout switches on cmd)
382 // * Ukrainian+QWERTY s | с | cmd-s | cmd-shift-s (macOS reports cmd-s instead of cmd-S)
383 // * Czech 7 | ý | cmd-ý | cmd-7 (layout has shifted numbers)
384 // * Norwegian 7 | 7 | cmd-7 | cmd-/ (macOS reports cmd-shift-7 instead of cmd-/)
385 // * Russian 7 | 7 | cmd-7 | cmd-& (shift-7 is . but when cmd is down, should use cmd layout)
386 // * German QWERTZ ; | ö | cmd-ö | cmd-Ö (Zed's shift special case only applies to a-z)
387 //
388 let mut chars_ignoring_modifiers =
389 chars_for_modified_key(native_event.keyCode(), NO_MOD);
390 let mut chars_with_shift =
391 chars_for_modified_key(native_event.keyCode(), SHIFT_MOD);
392 let always_use_cmd_layout = always_use_command_layout();
393
394 // Handle Dvorak+QWERTY / Russian / Armenian
395 if command || always_use_cmd_layout {
396 let chars_with_cmd = chars_for_modified_key(native_event.keyCode(), CMD_MOD);
397 let chars_with_both =
398 chars_for_modified_key(native_event.keyCode(), CMD_MOD | SHIFT_MOD);
399
400 // We don't do this in the case that the shifted command key generates
401 // the same character as the unshifted command key (Norwegian, e.g.)
402 if chars_with_both != chars_with_cmd {
403 chars_with_shift = chars_with_both;
404
405 // Handle edge-case where cmd-shift-s reports cmd-s instead of
406 // cmd-shift-s (Ukrainian, etc.)
407 } else if chars_with_cmd.to_ascii_uppercase() != chars_with_cmd {
408 chars_with_shift = chars_with_cmd.to_ascii_uppercase();
409 }
410 chars_ignoring_modifiers = chars_with_cmd;
411 }
412
413 if !control && !command && !function {
414 let mut mods = NO_MOD;
415 if shift {
416 mods |= SHIFT_MOD;
417 }
418 if alt {
419 mods |= OPTION_MOD;
420 }
421
422 key_char = Some(chars_for_modified_key(native_event.keyCode(), mods));
423 }
424
425 let mut key = if shift
426 && chars_ignoring_modifiers
427 .chars()
428 .all(|c| c.is_ascii_lowercase())
429 {
430 chars_ignoring_modifiers
431 } else if shift {
432 shift = false;
433 chars_with_shift
434 } else {
435 chars_ignoring_modifiers
436 };
437
438 key
439 }
440 };
441
442 Keystroke {
443 modifiers: Modifiers {
444 control,
445 alt,
446 shift,
447 platform: command,
448 function,
449 },
450 key,
451 key_char,
452 }
453 }
454}
455
456fn always_use_command_layout() -> bool {
457 if chars_for_modified_key(0, NO_MOD).is_ascii() {
458 return false;
459 }
460
461 chars_for_modified_key(0, CMD_MOD).is_ascii()
462}
463
464const NO_MOD: u32 = 0;
465const CMD_MOD: u32 = 1;
466const SHIFT_MOD: u32 = 2;
467const OPTION_MOD: u32 = 8;
468
469fn chars_for_modified_key(code: CGKeyCode, modifiers: u32) -> String {
470 // Values from: https://github.com/phracker/MacOSX-SDKs/blob/master/MacOSX10.6.sdk/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h#L126
471 // shifted >> 8 for UCKeyTranslate
472 const CG_SPACE_KEY: u16 = 49;
473 // https://github.com/phracker/MacOSX-SDKs/blob/master/MacOSX10.6.sdk/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/CarbonCore.framework/Versions/A/Headers/UnicodeUtilities.h#L278
474 #[allow(non_upper_case_globals)]
475 const kUCKeyActionDown: u16 = 0;
476 #[allow(non_upper_case_globals)]
477 const kUCKeyTranslateNoDeadKeysMask: u32 = 0;
478
479 let keyboard_type = unsafe { LMGetKbdType() as u32 };
480 const BUFFER_SIZE: usize = 4;
481 let mut dead_key_state = 0;
482 let mut buffer: [u16; BUFFER_SIZE] = [0; BUFFER_SIZE];
483 let mut buffer_size: usize = 0;
484
485 let keyboard = unsafe { TISCopyCurrentKeyboardLayoutInputSource() };
486 if keyboard.is_null() {
487 return "".to_string();
488 }
489 let layout_data = unsafe {
490 TISGetInputSourceProperty(keyboard, kTISPropertyUnicodeKeyLayoutData as *const c_void)
491 as CFDataRef
492 };
493 if layout_data.is_null() {
494 unsafe {
495 let _: () = msg_send![keyboard, release];
496 }
497 return "".to_string();
498 }
499 let keyboard_layout = unsafe { CFDataGetBytePtr(layout_data) };
500
501 unsafe {
502 UCKeyTranslate(
503 keyboard_layout as *const c_void,
504 code,
505 kUCKeyActionDown,
506 modifiers,
507 keyboard_type,
508 kUCKeyTranslateNoDeadKeysMask,
509 &mut dead_key_state,
510 BUFFER_SIZE,
511 &mut buffer_size as *mut usize,
512 &mut buffer as *mut u16,
513 );
514 if dead_key_state != 0 {
515 UCKeyTranslate(
516 keyboard_layout as *const c_void,
517 CG_SPACE_KEY,
518 kUCKeyActionDown,
519 modifiers,
520 keyboard_type,
521 kUCKeyTranslateNoDeadKeysMask,
522 &mut dead_key_state,
523 BUFFER_SIZE,
524 &mut buffer_size as *mut usize,
525 &mut buffer as *mut u16,
526 );
527 }
528 let _: () = msg_send![keyboard, release];
529 }
530 String::from_utf16(&buffer[..buffer_size]).unwrap_or_default()
531}