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) => "space".to_string(),
264 Some(BACKSPACE_KEY) => "backspace".to_string(),
265 Some(ENTER_KEY) | Some(NUMPAD_ENTER_KEY) => "enter".to_string(),
266 Some(ESCAPE_KEY) => "escape".to_string(),
267 Some(TAB_KEY) => "tab".to_string(),
268 Some(SHIFT_TAB_KEY) => "tab".to_string(),
269 Some(NSUpArrowFunctionKey) => "up".to_string(),
270 Some(NSDownArrowFunctionKey) => "down".to_string(),
271 Some(NSLeftArrowFunctionKey) => "left".to_string(),
272 Some(NSRightArrowFunctionKey) => "right".to_string(),
273 Some(NSPageUpFunctionKey) => "pageup".to_string(),
274 Some(NSPageDownFunctionKey) => "pagedown".to_string(),
275 Some(NSHomeFunctionKey) => "home".to_string(),
276 Some(NSEndFunctionKey) => "end".to_string(),
277 Some(NSDeleteFunctionKey) => "delete".to_string(),
278 // Observed Insert==NSHelpFunctionKey not NSInsertFunctionKey.
279 Some(NSHelpFunctionKey) => "insert".to_string(),
280 Some(NSF1FunctionKey) => "f1".to_string(),
281 Some(NSF2FunctionKey) => "f2".to_string(),
282 Some(NSF3FunctionKey) => "f3".to_string(),
283 Some(NSF4FunctionKey) => "f4".to_string(),
284 Some(NSF5FunctionKey) => "f5".to_string(),
285 Some(NSF6FunctionKey) => "f6".to_string(),
286 Some(NSF7FunctionKey) => "f7".to_string(),
287 Some(NSF8FunctionKey) => "f8".to_string(),
288 Some(NSF9FunctionKey) => "f9".to_string(),
289 Some(NSF10FunctionKey) => "f10".to_string(),
290 Some(NSF11FunctionKey) => "f11".to_string(),
291 Some(NSF12FunctionKey) => "f12".to_string(),
292 Some(NSF13FunctionKey) => "f13".to_string(),
293 Some(NSF14FunctionKey) => "f14".to_string(),
294 Some(NSF15FunctionKey) => "f15".to_string(),
295 Some(NSF16FunctionKey) => "f16".to_string(),
296 Some(NSF17FunctionKey) => "f17".to_string(),
297 Some(NSF18FunctionKey) => "f18".to_string(),
298 Some(NSF19FunctionKey) => "f19".to_string(),
299 _ => {
300 // Cases to test when modifying this:
301 //
302 // qwerty key | none | cmd | cmd-shift
303 // * Armenian s | ս | cmd-s | cmd-shift-s (layout is non-ASCII, so we use cmd layout)
304 // * Dvorak+QWERTY s | o | cmd-s | cmd-shift-s (layout switches on cmd)
305 // * Ukrainian+QWERTY s | с | cmd-s | cmd-shift-s (macOS reports cmd-s instead of cmd-S)
306 // * Czech 7 | ý | cmd-ý | cmd-7 (layout has shifted numbers)
307 // * Norwegian 7 | 7 | cmd-7 | cmd-/ (macOS reports cmd-shift-7 instead of cmd-/)
308 // * Russian 7 | 7 | cmd-7 | cmd-& (shift-7 is . but when cmd is down, should use cmd layout)
309 // * German QWERTZ ; | ö | cmd-ö | cmd-Ö (Zed's shift special case only applies to a-z)
310 //
311 let mut chars_ignoring_modifiers =
312 chars_for_modified_key(native_event.keyCode(), NO_MOD);
313 let mut chars_with_shift = chars_for_modified_key(native_event.keyCode(), SHIFT_MOD);
314 let always_use_cmd_layout = always_use_command_layout();
315
316 // Handle Dvorak+QWERTY / Russian / Armeniam
317 if command || always_use_cmd_layout {
318 let chars_with_cmd = chars_for_modified_key(native_event.keyCode(), CMD_MOD);
319 let chars_with_both =
320 chars_for_modified_key(native_event.keyCode(), CMD_MOD | SHIFT_MOD);
321
322 // We don't do this in the case that the shifted command key generates
323 // the same character as the unshifted command key (Norwegian, e.g.)
324 if chars_with_both != chars_with_cmd {
325 chars_with_shift = chars_with_both;
326
327 // Handle edge-case where cmd-shift-s reports cmd-s instead of
328 // cmd-shift-s (Ukrainian, etc.)
329 } else if chars_with_cmd.to_ascii_uppercase() != chars_with_cmd {
330 chars_with_shift = chars_with_cmd.to_ascii_uppercase();
331 }
332 chars_ignoring_modifiers = chars_with_cmd;
333 }
334
335 let mut key = if shift
336 && chars_ignoring_modifiers
337 .chars()
338 .all(|c| c.is_ascii_lowercase())
339 {
340 chars_ignoring_modifiers
341 } else if shift {
342 shift = false;
343 chars_with_shift
344 } else {
345 chars_ignoring_modifiers
346 };
347
348 if always_use_cmd_layout || alt {
349 let mut mods = NO_MOD;
350 if shift {
351 mods |= SHIFT_MOD;
352 }
353 if alt {
354 mods |= OPTION_MOD;
355 }
356 let alt_key = chars_for_modified_key(native_event.keyCode(), mods);
357 if alt_key != key {
358 ime_key = Some(alt_key);
359 }
360 };
361
362 key
363 }
364 };
365
366 Keystroke {
367 modifiers: Modifiers {
368 control,
369 alt,
370 shift,
371 platform: command,
372 function,
373 },
374 key,
375 ime_key,
376 }
377}
378
379fn always_use_command_layout() -> bool {
380 if chars_for_modified_key(0, NO_MOD).is_ascii() {
381 return false;
382 }
383
384 chars_for_modified_key(0, CMD_MOD).is_ascii()
385}
386
387const NO_MOD: u32 = 0;
388const CMD_MOD: u32 = 1;
389const SHIFT_MOD: u32 = 2;
390const OPTION_MOD: u32 = 8;
391
392fn chars_for_modified_key(code: CGKeyCode, modifiers: u32) -> String {
393 // 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
394 // shifted >> 8 for UCKeyTranslate
395 const CG_SPACE_KEY: u16 = 49;
396 // 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
397 #[allow(non_upper_case_globals)]
398 const kUCKeyActionDown: u16 = 0;
399 #[allow(non_upper_case_globals)]
400 const kUCKeyTranslateNoDeadKeysMask: u32 = 0;
401
402 let keyboard_type = unsafe { LMGetKbdType() as u32 };
403 const BUFFER_SIZE: usize = 4;
404 let mut dead_key_state = 0;
405 let mut buffer: [u16; BUFFER_SIZE] = [0; BUFFER_SIZE];
406 let mut buffer_size: usize = 0;
407
408 let keyboard = unsafe { TISCopyCurrentKeyboardLayoutInputSource() };
409 if keyboard.is_null() {
410 return "".to_string();
411 }
412 let layout_data = unsafe {
413 TISGetInputSourceProperty(keyboard, kTISPropertyUnicodeKeyLayoutData as *const c_void)
414 as CFDataRef
415 };
416 if layout_data.is_null() {
417 unsafe {
418 let _: () = msg_send![keyboard, release];
419 }
420 return "".to_string();
421 }
422 let keyboard_layout = unsafe { CFDataGetBytePtr(layout_data) };
423
424 unsafe {
425 UCKeyTranslate(
426 keyboard_layout as *const c_void,
427 code,
428 kUCKeyActionDown,
429 modifiers,
430 keyboard_type,
431 kUCKeyTranslateNoDeadKeysMask,
432 &mut dead_key_state,
433 BUFFER_SIZE,
434 &mut buffer_size as *mut usize,
435 &mut buffer as *mut u16,
436 );
437 if dead_key_state != 0 {
438 UCKeyTranslate(
439 keyboard_layout as *const c_void,
440 CG_SPACE_KEY,
441 kUCKeyActionDown,
442 modifiers,
443 keyboard_type,
444 kUCKeyTranslateNoDeadKeysMask,
445 &mut dead_key_state,
446 BUFFER_SIZE,
447 &mut buffer_size as *mut usize,
448 &mut buffer as *mut u16,
449 );
450 }
451 let _: () = msg_send![keyboard, release];
452 }
453 String::from_utf16(&buffer[..buffer_size]).unwrap_or_default()
454}