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