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