1use gpui::{
2 Capslock, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, ModifiersChangedEvent, MouseButton,
3 MouseDownEvent, MouseExitEvent, MouseMoveEvent, MousePressureEvent, MouseUpEvent,
4 NavigationDirection, Pixels, PlatformInput, PressureStage, ScrollDelta, ScrollWheelEvent,
5 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::NSScrollWheel => 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 raw_data = point(
247 native_event.scrollingDeltaX() as f32,
248 native_event.scrollingDeltaY() as f32,
249 );
250
251 let delta = if native_event.hasPreciseScrollingDeltas() == YES {
252 ScrollDelta::Pixels(raw_data.map(px))
253 } else {
254 ScrollDelta::Lines(raw_data)
255 };
256
257 PlatformInput::ScrollWheel(ScrollWheelEvent {
258 position: point(
259 px(native_event.locationInWindow().x as f32),
260 window_height - px(native_event.locationInWindow().y as f32),
261 ),
262 delta,
263 touch_phase: phase,
264 modifiers: read_modifiers(native_event),
265 })
266 }),
267 NSEventType::NSLeftMouseDragged
268 | NSEventType::NSRightMouseDragged
269 | NSEventType::NSOtherMouseDragged => {
270 let pressed_button = match native_event.buttonNumber() {
271 0 => MouseButton::Left,
272 1 => MouseButton::Right,
273 2 => MouseButton::Middle,
274 3 => MouseButton::Navigate(NavigationDirection::Back),
275 4 => MouseButton::Navigate(NavigationDirection::Forward),
276 // Other mouse buttons aren't tracked currently
277 _ => return None,
278 };
279
280 window_height.map(|window_height| {
281 PlatformInput::MouseMove(MouseMoveEvent {
282 pressed_button: Some(pressed_button),
283 position: point(
284 px(native_event.locationInWindow().x as f32),
285 window_height - px(native_event.locationInWindow().y as f32),
286 ),
287 modifiers: read_modifiers(native_event),
288 })
289 })
290 }
291 NSEventType::NSMouseMoved => window_height.map(|window_height| {
292 PlatformInput::MouseMove(MouseMoveEvent {
293 position: point(
294 px(native_event.locationInWindow().x as f32),
295 window_height - px(native_event.locationInWindow().y as f32),
296 ),
297 pressed_button: None,
298 modifiers: read_modifiers(native_event),
299 })
300 }),
301 NSEventType::NSMouseExited => window_height.map(|window_height| {
302 PlatformInput::MouseExited(MouseExitEvent {
303 position: point(
304 px(native_event.locationInWindow().x as f32),
305 window_height - px(native_event.locationInWindow().y as f32),
306 ),
307
308 pressed_button: None,
309 modifiers: read_modifiers(native_event),
310 })
311 }),
312 _ => None,
313 }
314 }
315}
316
317unsafe fn parse_keystroke(native_event: id) -> Keystroke {
318 unsafe {
319 use cocoa::appkit::*;
320
321 let characters = native_event
322 .charactersIgnoringModifiers()
323 .to_str()
324 .to_string();
325 let mut key_char = None;
326 let first_char = characters.chars().next().map(|ch| ch as u16);
327 let modifiers = native_event.modifierFlags();
328
329 let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
330 let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
331 let mut shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
332 let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
333 let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask)
334 && first_char
335 .is_none_or(|ch| !(NSUpArrowFunctionKey..=NSModeSwitchFunctionKey).contains(&ch));
336
337 #[allow(non_upper_case_globals)]
338 let key = match first_char {
339 Some(SPACE_KEY) => {
340 key_char = Some(" ".to_string());
341 "space".to_string()
342 }
343 Some(TAB_KEY) => {
344 key_char = Some("\t".to_string());
345 "tab".to_string()
346 }
347 Some(ENTER_KEY) | Some(NUMPAD_ENTER_KEY) => {
348 key_char = Some("\n".to_string());
349 "enter".to_string()
350 }
351 Some(BACKSPACE_KEY) => "backspace".to_string(),
352 Some(ESCAPE_KEY) => "escape".to_string(),
353 Some(SHIFT_TAB_KEY) => "tab".to_string(),
354 Some(NSUpArrowFunctionKey) => "up".to_string(),
355 Some(NSDownArrowFunctionKey) => "down".to_string(),
356 Some(NSLeftArrowFunctionKey) => "left".to_string(),
357 Some(NSRightArrowFunctionKey) => "right".to_string(),
358 Some(NSPageUpFunctionKey) => "pageup".to_string(),
359 Some(NSPageDownFunctionKey) => "pagedown".to_string(),
360 Some(NSHomeFunctionKey) => "home".to_string(),
361 Some(NSEndFunctionKey) => "end".to_string(),
362 Some(NSDeleteFunctionKey) => "delete".to_string(),
363 // Observed Insert==NSHelpFunctionKey not NSInsertFunctionKey.
364 Some(NSHelpFunctionKey) => "insert".to_string(),
365 Some(NSF1FunctionKey) => "f1".to_string(),
366 Some(NSF2FunctionKey) => "f2".to_string(),
367 Some(NSF3FunctionKey) => "f3".to_string(),
368 Some(NSF4FunctionKey) => "f4".to_string(),
369 Some(NSF5FunctionKey) => "f5".to_string(),
370 Some(NSF6FunctionKey) => "f6".to_string(),
371 Some(NSF7FunctionKey) => "f7".to_string(),
372 Some(NSF8FunctionKey) => "f8".to_string(),
373 Some(NSF9FunctionKey) => "f9".to_string(),
374 Some(NSF10FunctionKey) => "f10".to_string(),
375 Some(NSF11FunctionKey) => "f11".to_string(),
376 Some(NSF12FunctionKey) => "f12".to_string(),
377 Some(NSF13FunctionKey) => "f13".to_string(),
378 Some(NSF14FunctionKey) => "f14".to_string(),
379 Some(NSF15FunctionKey) => "f15".to_string(),
380 Some(NSF16FunctionKey) => "f16".to_string(),
381 Some(NSF17FunctionKey) => "f17".to_string(),
382 Some(NSF18FunctionKey) => "f18".to_string(),
383 Some(NSF19FunctionKey) => "f19".to_string(),
384 Some(NSF20FunctionKey) => "f20".to_string(),
385 Some(NSF21FunctionKey) => "f21".to_string(),
386 Some(NSF22FunctionKey) => "f22".to_string(),
387 Some(NSF23FunctionKey) => "f23".to_string(),
388 Some(NSF24FunctionKey) => "f24".to_string(),
389 Some(NSF25FunctionKey) => "f25".to_string(),
390 Some(NSF26FunctionKey) => "f26".to_string(),
391 Some(NSF27FunctionKey) => "f27".to_string(),
392 Some(NSF28FunctionKey) => "f28".to_string(),
393 Some(NSF29FunctionKey) => "f29".to_string(),
394 Some(NSF30FunctionKey) => "f30".to_string(),
395 Some(NSF31FunctionKey) => "f31".to_string(),
396 Some(NSF32FunctionKey) => "f32".to_string(),
397 Some(NSF33FunctionKey) => "f33".to_string(),
398 Some(NSF34FunctionKey) => "f34".to_string(),
399 Some(NSF35FunctionKey) => "f35".to_string(),
400 _ => {
401 // Cases to test when modifying this:
402 //
403 // qwerty key | none | cmd | cmd-shift
404 // * Armenian s | ս | cmd-s | cmd-shift-s (layout is non-ASCII, so we use cmd layout)
405 // * Dvorak+QWERTY s | o | cmd-s | cmd-shift-s (layout switches on cmd)
406 // * Ukrainian+QWERTY s | с | cmd-s | cmd-shift-s (macOS reports cmd-s instead of cmd-S)
407 // * Czech 7 | ý | cmd-ý | cmd-7 (layout has shifted numbers)
408 // * Norwegian 7 | 7 | cmd-7 | cmd-/ (macOS reports cmd-shift-7 instead of cmd-/)
409 // * Russian 7 | 7 | cmd-7 | cmd-& (shift-7 is . but when cmd is down, should use cmd layout)
410 // * German QWERTZ ; | ö | cmd-ö | cmd-Ö (Zed's shift special case only applies to a-z)
411 //
412 let mut chars_ignoring_modifiers =
413 chars_for_modified_key(native_event.keyCode(), NO_MOD);
414 let mut chars_with_shift =
415 chars_for_modified_key(native_event.keyCode(), SHIFT_MOD);
416 let always_use_cmd_layout = always_use_command_layout();
417
418 // Handle Dvorak+QWERTY / Russian / Armenian
419 if command || always_use_cmd_layout {
420 let chars_with_cmd = chars_for_modified_key(native_event.keyCode(), CMD_MOD);
421 let chars_with_both =
422 chars_for_modified_key(native_event.keyCode(), CMD_MOD | SHIFT_MOD);
423
424 // We don't do this in the case that the shifted command key generates
425 // the same character as the unshifted command key (Norwegian, e.g.)
426 if chars_with_both != chars_with_cmd {
427 chars_with_shift = chars_with_both;
428
429 // Handle edge-case where cmd-shift-s reports cmd-s instead of
430 // cmd-shift-s (Ukrainian, etc.)
431 } else if chars_with_cmd.to_ascii_uppercase() != chars_with_cmd {
432 chars_with_shift = chars_with_cmd.to_ascii_uppercase();
433 }
434 chars_ignoring_modifiers = chars_with_cmd;
435 }
436
437 if !control && !command && !function {
438 let mut mods = NO_MOD;
439 if shift {
440 mods |= SHIFT_MOD;
441 }
442 if alt {
443 mods |= OPTION_MOD;
444 }
445
446 key_char = Some(chars_for_modified_key(native_event.keyCode(), mods));
447 }
448
449 if shift
450 && chars_ignoring_modifiers
451 .chars()
452 .all(|c| c.is_ascii_lowercase())
453 {
454 chars_ignoring_modifiers
455 } else if shift {
456 shift = false;
457 chars_with_shift
458 } else {
459 chars_ignoring_modifiers
460 }
461 }
462 };
463
464 Keystroke {
465 modifiers: Modifiers {
466 control,
467 alt,
468 shift,
469 platform: command,
470 function,
471 },
472 key,
473 key_char,
474 }
475 }
476}
477
478fn always_use_command_layout() -> bool {
479 if chars_for_modified_key(0, NO_MOD).is_ascii() {
480 return false;
481 }
482
483 chars_for_modified_key(0, CMD_MOD).is_ascii()
484}
485
486const NO_MOD: u32 = 0;
487const CMD_MOD: u32 = 1;
488const SHIFT_MOD: u32 = 2;
489const OPTION_MOD: u32 = 8;
490
491fn chars_for_modified_key(code: CGKeyCode, modifiers: u32) -> String {
492 // 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
493 // shifted >> 8 for UCKeyTranslate
494 const CG_SPACE_KEY: u16 = 49;
495 // 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
496 #[allow(non_upper_case_globals)]
497 const kUCKeyActionDown: u16 = 0;
498 #[allow(non_upper_case_globals)]
499 const kUCKeyTranslateNoDeadKeysMask: u32 = 0;
500
501 let keyboard_type = unsafe { LMGetKbdType() as u32 };
502 const BUFFER_SIZE: usize = 4;
503 let mut dead_key_state = 0;
504 let mut buffer: [u16; BUFFER_SIZE] = [0; BUFFER_SIZE];
505 let mut buffer_size: usize = 0;
506
507 let keyboard = unsafe { TISCopyCurrentKeyboardLayoutInputSource() };
508 if keyboard.is_null() {
509 return "".to_string();
510 }
511 let layout_data = unsafe {
512 TISGetInputSourceProperty(keyboard, kTISPropertyUnicodeKeyLayoutData as *const c_void)
513 as CFDataRef
514 };
515 if layout_data.is_null() {
516 unsafe {
517 let _: () = msg_send![keyboard, release];
518 }
519 return "".to_string();
520 }
521 let keyboard_layout = unsafe { CFDataGetBytePtr(layout_data) };
522
523 unsafe {
524 UCKeyTranslate(
525 keyboard_layout as *const c_void,
526 code,
527 kUCKeyActionDown,
528 modifiers,
529 keyboard_type,
530 kUCKeyTranslateNoDeadKeysMask,
531 &mut dead_key_state,
532 BUFFER_SIZE,
533 &mut buffer_size as *mut usize,
534 &mut buffer as *mut u16,
535 );
536 if dead_key_state != 0 {
537 UCKeyTranslate(
538 keyboard_layout as *const c_void,
539 CG_SPACE_KEY,
540 kUCKeyActionDown,
541 modifiers,
542 keyboard_type,
543 kUCKeyTranslateNoDeadKeysMask,
544 &mut dead_key_state,
545 BUFFER_SIZE,
546 &mut buffer_size as *mut usize,
547 &mut buffer as *mut u16,
548 );
549 }
550 let _: () = msg_send![keyboard, release];
551 }
552 String::from_utf16(&buffer[..buffer_size]).unwrap_or_default()
553}