1use crate::{
2 point, px, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, ModifiersChangedEvent, MouseButton,
3 MouseDownEvent, MouseExitEvent, MouseMoveEvent, MouseUpEvent, NavigationDirection, Pixels,
4 PlatformInput, ScrollDelta, ScrollWheelEvent, TouchPhase,
5};
6use cocoa::{
7 appkit::{NSEvent, NSEventModifierFlags, NSEventPhase, NSEventType},
8 base::{id, YES},
9 foundation::NSString as _,
10};
11use core_graphics::{
12 event::{CGEvent, CGEventFlags, CGKeyCode},
13 event_source::{CGEventSource, CGEventSourceStateID},
14};
15use ctor::ctor;
16use metal::foreign_types::ForeignType as _;
17use objc::{class, msg_send, sel, sel_impl};
18use std::{borrow::Cow, ffi::CStr, mem, os::raw::c_char, ptr};
19
20const BACKSPACE_KEY: u16 = 0x7f;
21const SPACE_KEY: u16 = b' ' as u16;
22const ENTER_KEY: u16 = 0x0d;
23const NUMPAD_ENTER_KEY: u16 = 0x03;
24const ESCAPE_KEY: u16 = 0x1b;
25const TAB_KEY: u16 = 0x09;
26const SHIFT_TAB_KEY: u16 = 0x19;
27
28static mut EVENT_SOURCE: core_graphics::sys::CGEventSourceRef = ptr::null_mut();
29
30#[ctor]
31unsafe fn build_event_source() {
32 let source = CGEventSource::new(CGEventSourceStateID::Private).unwrap();
33 EVENT_SOURCE = source.as_ptr();
34 mem::forget(source);
35}
36
37pub fn key_to_native(key: &str) -> Cow<str> {
38 use cocoa::appkit::*;
39 let code = match key {
40 "space" => SPACE_KEY,
41 "backspace" => BACKSPACE_KEY,
42 "up" => NSUpArrowFunctionKey,
43 "down" => NSDownArrowFunctionKey,
44 "left" => NSLeftArrowFunctionKey,
45 "right" => NSRightArrowFunctionKey,
46 "pageup" => NSPageUpFunctionKey,
47 "pagedown" => NSPageDownFunctionKey,
48 "home" => NSHomeFunctionKey,
49 "end" => NSEndFunctionKey,
50 "delete" => NSDeleteFunctionKey,
51 "f1" => NSF1FunctionKey,
52 "f2" => NSF2FunctionKey,
53 "f3" => NSF3FunctionKey,
54 "f4" => NSF4FunctionKey,
55 "f5" => NSF5FunctionKey,
56 "f6" => NSF6FunctionKey,
57 "f7" => NSF7FunctionKey,
58 "f8" => NSF8FunctionKey,
59 "f9" => NSF9FunctionKey,
60 "f10" => NSF10FunctionKey,
61 "f11" => NSF11FunctionKey,
62 "f12" => NSF12FunctionKey,
63 _ => return Cow::Borrowed(key),
64 };
65 Cow::Owned(String::from_utf16(&[code]).unwrap())
66}
67
68unsafe fn read_modifiers(native_event: id) -> Modifiers {
69 let modifiers = native_event.modifierFlags();
70 let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
71 let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
72 let shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
73 let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
74 let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask);
75
76 Modifiers {
77 control,
78 alt,
79 shift,
80 command,
81 function,
82 }
83}
84
85impl PlatformInput {
86 pub(crate) unsafe fn from_native(
87 native_event: id,
88 window_height: Option<Pixels>,
89 ) -> Option<Self> {
90 let event_type = native_event.eventType();
91
92 // Filter out event types that aren't in the NSEventType enum.
93 // See https://github.com/servo/cocoa-rs/issues/155#issuecomment-323482792 for details.
94 match event_type as u64 {
95 0 | 21 | 32 | 33 | 35 | 36 | 37 => {
96 return None;
97 }
98 _ => {}
99 }
100
101 match event_type {
102 NSEventType::NSFlagsChanged => Some(Self::ModifiersChanged(ModifiersChangedEvent {
103 modifiers: read_modifiers(native_event),
104 })),
105 NSEventType::NSKeyDown => Some(Self::KeyDown(KeyDownEvent {
106 keystroke: parse_keystroke(native_event),
107 is_held: native_event.isARepeat() == YES,
108 })),
109 NSEventType::NSKeyUp => Some(Self::KeyUp(KeyUpEvent {
110 keystroke: parse_keystroke(native_event),
111 })),
112 NSEventType::NSLeftMouseDown
113 | NSEventType::NSRightMouseDown
114 | NSEventType::NSOtherMouseDown => {
115 let button = match native_event.buttonNumber() {
116 0 => MouseButton::Left,
117 1 => MouseButton::Right,
118 2 => MouseButton::Middle,
119 3 => MouseButton::Navigate(NavigationDirection::Back),
120 4 => MouseButton::Navigate(NavigationDirection::Forward),
121 // Other mouse buttons aren't tracked currently
122 _ => return None,
123 };
124 window_height.map(|window_height| {
125 Self::MouseDown(MouseDownEvent {
126 button,
127 position: point(
128 px(native_event.locationInWindow().x as f32),
129 // MacOS screen coordinates are relative to bottom left
130 window_height - px(native_event.locationInWindow().y as f32),
131 ),
132 modifiers: read_modifiers(native_event),
133 click_count: native_event.clickCount() as usize,
134 })
135 })
136 }
137 NSEventType::NSLeftMouseUp
138 | NSEventType::NSRightMouseUp
139 | NSEventType::NSOtherMouseUp => {
140 let button = match native_event.buttonNumber() {
141 0 => MouseButton::Left,
142 1 => MouseButton::Right,
143 2 => MouseButton::Middle,
144 3 => MouseButton::Navigate(NavigationDirection::Back),
145 4 => MouseButton::Navigate(NavigationDirection::Forward),
146 // Other mouse buttons aren't tracked currently
147 _ => return None,
148 };
149
150 window_height.map(|window_height| {
151 Self::MouseUp(MouseUpEvent {
152 button,
153 position: point(
154 px(native_event.locationInWindow().x as f32),
155 window_height - px(native_event.locationInWindow().y as f32),
156 ),
157 modifiers: read_modifiers(native_event),
158 click_count: native_event.clickCount() as usize,
159 })
160 })
161 }
162 NSEventType::NSScrollWheel => window_height.map(|window_height| {
163 let phase = match native_event.phase() {
164 NSEventPhase::NSEventPhaseMayBegin | NSEventPhase::NSEventPhaseBegan => {
165 TouchPhase::Started
166 }
167 NSEventPhase::NSEventPhaseEnded => TouchPhase::Ended,
168 _ => TouchPhase::Moved,
169 };
170
171 let raw_data = point(
172 native_event.scrollingDeltaX() as f32,
173 native_event.scrollingDeltaY() as f32,
174 );
175
176 let delta = if native_event.hasPreciseScrollingDeltas() == YES {
177 ScrollDelta::Pixels(raw_data.map(px))
178 } else {
179 ScrollDelta::Lines(raw_data)
180 };
181
182 Self::ScrollWheel(ScrollWheelEvent {
183 position: point(
184 px(native_event.locationInWindow().x as f32),
185 window_height - px(native_event.locationInWindow().y as f32),
186 ),
187 delta,
188 touch_phase: phase,
189 modifiers: read_modifiers(native_event),
190 })
191 }),
192 NSEventType::NSLeftMouseDragged
193 | NSEventType::NSRightMouseDragged
194 | NSEventType::NSOtherMouseDragged => {
195 let pressed_button = match native_event.buttonNumber() {
196 0 => MouseButton::Left,
197 1 => MouseButton::Right,
198 2 => MouseButton::Middle,
199 3 => MouseButton::Navigate(NavigationDirection::Back),
200 4 => MouseButton::Navigate(NavigationDirection::Forward),
201 // Other mouse buttons aren't tracked currently
202 _ => return None,
203 };
204
205 window_height.map(|window_height| {
206 Self::MouseMove(MouseMoveEvent {
207 pressed_button: Some(pressed_button),
208 position: point(
209 px(native_event.locationInWindow().x as f32),
210 window_height - px(native_event.locationInWindow().y as f32),
211 ),
212 modifiers: read_modifiers(native_event),
213 })
214 })
215 }
216 NSEventType::NSMouseMoved => window_height.map(|window_height| {
217 Self::MouseMove(MouseMoveEvent {
218 position: point(
219 px(native_event.locationInWindow().x as f32),
220 window_height - px(native_event.locationInWindow().y as f32),
221 ),
222 pressed_button: None,
223 modifiers: read_modifiers(native_event),
224 })
225 }),
226 NSEventType::NSMouseExited => window_height.map(|window_height| {
227 Self::MouseExited(MouseExitEvent {
228 position: point(
229 px(native_event.locationInWindow().x as f32),
230 window_height - px(native_event.locationInWindow().y as f32),
231 ),
232
233 pressed_button: None,
234 modifiers: read_modifiers(native_event),
235 })
236 }),
237 _ => None,
238 }
239 }
240}
241
242unsafe fn parse_keystroke(native_event: id) -> Keystroke {
243 use cocoa::appkit::*;
244
245 let mut chars_ignoring_modifiers =
246 CStr::from_ptr(native_event.charactersIgnoringModifiers().UTF8String() as *mut c_char)
247 .to_str()
248 .unwrap()
249 .to_string();
250 let first_char = chars_ignoring_modifiers.chars().next().map(|ch| ch as u16);
251 let modifiers = native_event.modifierFlags();
252
253 let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
254 let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
255 let mut shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
256 let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
257 let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask)
258 && first_char.map_or(true, |ch| {
259 !(NSUpArrowFunctionKey..=NSModeSwitchFunctionKey).contains(&ch)
260 });
261
262 #[allow(non_upper_case_globals)]
263 let key = match first_char {
264 Some(SPACE_KEY) => "space".to_string(),
265 Some(BACKSPACE_KEY) => "backspace".to_string(),
266 Some(ENTER_KEY) | Some(NUMPAD_ENTER_KEY) => "enter".to_string(),
267 Some(ESCAPE_KEY) => "escape".to_string(),
268 Some(TAB_KEY) => "tab".to_string(),
269 Some(SHIFT_TAB_KEY) => "tab".to_string(),
270 Some(NSUpArrowFunctionKey) => "up".to_string(),
271 Some(NSDownArrowFunctionKey) => "down".to_string(),
272 Some(NSLeftArrowFunctionKey) => "left".to_string(),
273 Some(NSRightArrowFunctionKey) => "right".to_string(),
274 Some(NSPageUpFunctionKey) => "pageup".to_string(),
275 Some(NSPageDownFunctionKey) => "pagedown".to_string(),
276 Some(NSHomeFunctionKey) => "home".to_string(),
277 Some(NSEndFunctionKey) => "end".to_string(),
278 Some(NSDeleteFunctionKey) => "delete".to_string(),
279 Some(NSF1FunctionKey) => "f1".to_string(),
280 Some(NSF2FunctionKey) => "f2".to_string(),
281 Some(NSF3FunctionKey) => "f3".to_string(),
282 Some(NSF4FunctionKey) => "f4".to_string(),
283 Some(NSF5FunctionKey) => "f5".to_string(),
284 Some(NSF6FunctionKey) => "f6".to_string(),
285 Some(NSF7FunctionKey) => "f7".to_string(),
286 Some(NSF8FunctionKey) => "f8".to_string(),
287 Some(NSF9FunctionKey) => "f9".to_string(),
288 Some(NSF10FunctionKey) => "f10".to_string(),
289 Some(NSF11FunctionKey) => "f11".to_string(),
290 Some(NSF12FunctionKey) => "f12".to_string(),
291 _ => {
292 let mut chars_ignoring_modifiers_and_shift =
293 chars_for_modified_key(native_event.keyCode(), false, false);
294
295 // Honor ⌘ when Dvorak-QWERTY is used.
296 let chars_with_cmd = chars_for_modified_key(native_event.keyCode(), true, false);
297 if command && chars_ignoring_modifiers_and_shift != chars_with_cmd {
298 chars_ignoring_modifiers =
299 chars_for_modified_key(native_event.keyCode(), true, shift);
300 chars_ignoring_modifiers_and_shift = chars_with_cmd;
301 }
302
303 if shift {
304 if chars_ignoring_modifiers_and_shift
305 == chars_ignoring_modifiers.to_ascii_lowercase()
306 {
307 chars_ignoring_modifiers_and_shift
308 } else if chars_ignoring_modifiers_and_shift != chars_ignoring_modifiers {
309 shift = false;
310 chars_ignoring_modifiers
311 } else {
312 chars_ignoring_modifiers
313 }
314 } else {
315 chars_ignoring_modifiers
316 }
317 }
318 };
319
320 Keystroke {
321 modifiers: Modifiers {
322 control,
323 alt,
324 shift,
325 command,
326 function,
327 },
328 key,
329 ime_key: None,
330 }
331}
332
333fn chars_for_modified_key(code: CGKeyCode, cmd: bool, shift: bool) -> String {
334 // Ideally, we would use `[NSEvent charactersByApplyingModifiers]` but that
335 // always returns an empty string with certain keyboards, e.g. Japanese. Synthesizing
336 // an event with the given flags instead lets us access `characters`, which always
337 // returns a valid string.
338 let source = unsafe { core_graphics::event_source::CGEventSource::from_ptr(EVENT_SOURCE) };
339 let event = CGEvent::new_keyboard_event(source.clone(), code, true).unwrap();
340 mem::forget(source);
341
342 let mut flags = CGEventFlags::empty();
343 if cmd {
344 flags |= CGEventFlags::CGEventFlagCommand;
345 }
346 if shift {
347 flags |= CGEventFlags::CGEventFlagShift;
348 }
349 event.set_flags(flags);
350
351 unsafe {
352 let event: id = msg_send![class!(NSEvent), eventWithCGEvent: &*event];
353 CStr::from_ptr(event.characters().UTF8String())
354 .to_str()
355 .unwrap()
356 .to_string()
357 }
358}