1use crate::{
2 point, px, InputEvent, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, ModifiersChangedEvent,
3 MouseButton, MouseDownEvent, MouseExitEvent, MouseMoveEvent, MouseUpEvent, NavigationDirection,
4 Pixels, 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 foreign_types::ForeignType;
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
37// todo!
38#[allow(unused)]
39pub fn key_to_native(key: &str) -> Cow<str> {
40 use cocoa::appkit::*;
41 let code = match key {
42 "space" => SPACE_KEY,
43 "backspace" => BACKSPACE_KEY,
44 "up" => NSUpArrowFunctionKey,
45 "down" => NSDownArrowFunctionKey,
46 "left" => NSLeftArrowFunctionKey,
47 "right" => NSRightArrowFunctionKey,
48 "pageup" => NSPageUpFunctionKey,
49 "pagedown" => NSPageDownFunctionKey,
50 "home" => NSHomeFunctionKey,
51 "end" => NSEndFunctionKey,
52 "delete" => NSDeleteFunctionKey,
53 "f1" => NSF1FunctionKey,
54 "f2" => NSF2FunctionKey,
55 "f3" => NSF3FunctionKey,
56 "f4" => NSF4FunctionKey,
57 "f5" => NSF5FunctionKey,
58 "f6" => NSF6FunctionKey,
59 "f7" => NSF7FunctionKey,
60 "f8" => NSF8FunctionKey,
61 "f9" => NSF9FunctionKey,
62 "f10" => NSF10FunctionKey,
63 "f11" => NSF11FunctionKey,
64 "f12" => NSF12FunctionKey,
65 _ => return Cow::Borrowed(key),
66 };
67 Cow::Owned(String::from_utf16(&[code]).unwrap())
68}
69
70unsafe fn read_modifiers(native_event: id) -> Modifiers {
71 let modifiers = native_event.modifierFlags();
72 let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
73 let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
74 let shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
75 let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
76 let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask);
77
78 Modifiers {
79 control,
80 alt,
81 shift,
82 command,
83 function,
84 }
85}
86
87impl InputEvent {
88 pub unsafe fn from_native(native_event: id, window_height: Option<Pixels>) -> Option<Self> {
89 let event_type = native_event.eventType();
90
91 // Filter out event types that aren't in the NSEventType enum.
92 // See https://github.com/servo/cocoa-rs/issues/155#issuecomment-323482792 for details.
93 match event_type as u64 {
94 0 | 21 | 32 | 33 | 35 | 36 | 37 => {
95 return None;
96 }
97 _ => {}
98 }
99
100 match event_type {
101 NSEventType::NSFlagsChanged => Some(Self::ModifiersChanged(ModifiersChangedEvent {
102 modifiers: read_modifiers(native_event),
103 })),
104 NSEventType::NSKeyDown => Some(Self::KeyDown(KeyDownEvent {
105 keystroke: parse_keystroke(native_event),
106 is_held: native_event.isARepeat() == YES,
107 })),
108 NSEventType::NSKeyUp => Some(Self::KeyUp(KeyUpEvent {
109 keystroke: parse_keystroke(native_event),
110 })),
111 NSEventType::NSLeftMouseDown
112 | NSEventType::NSRightMouseDown
113 | NSEventType::NSOtherMouseDown => {
114 let button = match native_event.buttonNumber() {
115 0 => MouseButton::Left,
116 1 => MouseButton::Right,
117 2 => MouseButton::Middle,
118 3 => MouseButton::Navigate(NavigationDirection::Back),
119 4 => MouseButton::Navigate(NavigationDirection::Forward),
120 // Other mouse buttons aren't tracked currently
121 _ => return None,
122 };
123 window_height.map(|window_height| {
124 Self::MouseDown(MouseDownEvent {
125 button,
126 position: point(
127 px(native_event.locationInWindow().x as f32),
128 // MacOS screen coordinates are relative to bottom left
129 window_height - px(native_event.locationInWindow().y as f32),
130 ),
131 modifiers: read_modifiers(native_event),
132 click_count: native_event.clickCount() as usize,
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 chars_ignoring_modifiers =
245 CStr::from_ptr(native_event.charactersIgnoringModifiers().UTF8String() as *mut c_char)
246 .to_str()
247 .unwrap()
248 .to_string();
249 let first_char = chars_ignoring_modifiers.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 Some(NSF1FunctionKey) => "f1".to_string(),
279 Some(NSF2FunctionKey) => "f2".to_string(),
280 Some(NSF3FunctionKey) => "f3".to_string(),
281 Some(NSF4FunctionKey) => "f4".to_string(),
282 Some(NSF5FunctionKey) => "f5".to_string(),
283 Some(NSF6FunctionKey) => "f6".to_string(),
284 Some(NSF7FunctionKey) => "f7".to_string(),
285 Some(NSF8FunctionKey) => "f8".to_string(),
286 Some(NSF9FunctionKey) => "f9".to_string(),
287 Some(NSF10FunctionKey) => "f10".to_string(),
288 Some(NSF11FunctionKey) => "f11".to_string(),
289 Some(NSF12FunctionKey) => "f12".to_string(),
290 _ => {
291 let mut chars_ignoring_modifiers_and_shift =
292 chars_for_modified_key(native_event.keyCode(), false, false);
293
294 // Honor ⌘ when Dvorak-QWERTY is used.
295 let chars_with_cmd = chars_for_modified_key(native_event.keyCode(), true, false);
296 if command && chars_ignoring_modifiers_and_shift != chars_with_cmd {
297 chars_ignoring_modifiers =
298 chars_for_modified_key(native_event.keyCode(), true, shift);
299 chars_ignoring_modifiers_and_shift = chars_with_cmd;
300 }
301
302 if shift {
303 if chars_ignoring_modifiers_and_shift
304 == chars_ignoring_modifiers.to_ascii_lowercase()
305 {
306 chars_ignoring_modifiers_and_shift
307 } else if chars_ignoring_modifiers_and_shift != chars_ignoring_modifiers {
308 shift = false;
309 chars_ignoring_modifiers
310 } else {
311 chars_ignoring_modifiers
312 }
313 } else {
314 chars_ignoring_modifiers
315 }
316 }
317 };
318
319 Keystroke {
320 modifiers: Modifiers {
321 control,
322 alt,
323 shift,
324 command,
325 function,
326 },
327 key,
328 ime_key: None,
329 }
330}
331
332fn chars_for_modified_key(code: CGKeyCode, cmd: bool, shift: bool) -> String {
333 // Ideally, we would use `[NSEvent charactersByApplyingModifiers]` but that
334 // always returns an empty string with certain keyboards, e.g. Japanese. Synthesizing
335 // an event with the given flags instead lets us access `characters`, which always
336 // returns a valid string.
337 let source = unsafe { core_graphics::event_source::CGEventSource::from_ptr(EVENT_SOURCE) };
338 let event = CGEvent::new_keyboard_event(source.clone(), code, true).unwrap();
339 mem::forget(source);
340
341 let mut flags = CGEventFlags::empty();
342 if cmd {
343 flags |= CGEventFlags::CGEventFlagCommand;
344 }
345 if shift {
346 flags |= CGEventFlags::CGEventFlagShift;
347 }
348 event.set_flags(flags);
349
350 unsafe {
351 let event: id = msg_send![class!(NSEvent), eventWithCGEvent: &*event];
352 CStr::from_ptr(event.characters().UTF8String())
353 .to_str()
354 .unwrap()
355 .to_string()
356 }
357}