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