Debian Codegraph @

third_party/rust/core-graphics/src/event.rs

raw
1 #![allow(non_upper_case_globals)]
2 use core_foundation::{
3 base::{CFRelease, CFRetain, CFTypeID, TCFType},
4 mach_port::{CFMachPort, CFMachPortRef},
5 };
6 use event_source::CGEventSource;
7 use foreign_types::ForeignType;
8 use geometry::CGPoint;
9 use libc::c_void;
10 use std::mem::ManuallyDrop;
11
12 pub type CGEventField = u32;
13 pub type CGKeyCode = u16;
14 pub type CGScrollEventUnit = u32;
15
16 bitflags! {
17 /// Flags for events
18 ///
19 /// [Ref](http://opensource.apple.com/source/IOHIDFamily/IOHIDFamily-700/IOHIDSystem/IOKit/hidsystem/IOLLEvent.h)
20 #[repr(C)]
21 pub struct CGEventFlags: u64 {
22 const CGEventFlagNull = 0;
23
24 // Device-independent modifier key bits.
25 const CGEventFlagAlphaShift = 0x00010000;
26 const CGEventFlagShift = 0x00020000;
27 const CGEventFlagControl = 0x00040000;
28 const CGEventFlagAlternate = 0x00080000;
29 const CGEventFlagCommand = 0x00100000;
30
31 // Special key identifiers.
32 const CGEventFlagHelp = 0x00400000;
33 const CGEventFlagSecondaryFn = 0x00800000;
34
35 // Identifies key events from numeric keypad area on extended keyboards.
36 const CGEventFlagNumericPad = 0x00200000;
37
38 // Indicates if mouse/pen movement events are not being coalesced
39 const CGEventFlagNonCoalesced = 0x00000100;
40 }
41 }
42
43 /// Key codes for keys that are independent of keyboard layout.
44 ///
45 /// [Ref](https://github.com/phracker/MacOSX-SDKs/blob/master/MacOSX10.13.sdk/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h)
46 #[repr(C)]
47 pub struct KeyCode;
48 impl KeyCode {
49 pub const RETURN: CGKeyCode = 0x24;
50 pub const TAB: CGKeyCode = 0x30;
51 pub const SPACE: CGKeyCode = 0x31;
52 pub const DELETE: CGKeyCode = 0x33;
53 pub const ESCAPE: CGKeyCode = 0x35;
54 pub const COMMAND: CGKeyCode = 0x37;
55 pub const SHIFT: CGKeyCode = 0x38;
56 pub const CAPS_LOCK: CGKeyCode = 0x39;
57 pub const OPTION: CGKeyCode = 0x3A;
58 pub const CONTROL: CGKeyCode = 0x3B;
59 pub const RIGHT_COMMAND: CGKeyCode = 0x36;
60 pub const RIGHT_SHIFT: CGKeyCode = 0x3C;
61 pub const RIGHT_OPTION: CGKeyCode = 0x3D;
62 pub const RIGHT_CONTROL: CGKeyCode = 0x3E;
63 pub const FUNCTION: CGKeyCode = 0x3F;
64 pub const VOLUME_UP: CGKeyCode = 0x48;
65 pub const VOLUME_DOWN: CGKeyCode = 0x49;
66 pub const MUTE: CGKeyCode = 0x4A;
67 pub const F1: CGKeyCode = 0x7A;
68 pub const F2: CGKeyCode = 0x78;
69 pub const F3: CGKeyCode = 0x63;
70 pub const F4: CGKeyCode = 0x76;
71 pub const F5: CGKeyCode = 0x60;
72 pub const F6: CGKeyCode = 0x61;
73 pub const F7: CGKeyCode = 0x62;
74 pub const F8: CGKeyCode = 0x64;
75 pub const F9: CGKeyCode = 0x65;
76 pub const F10: CGKeyCode = 0x6D;
77 pub const F11: CGKeyCode = 0x67;
78 pub const F12: CGKeyCode = 0x6F;
79 pub const F13: CGKeyCode = 0x69;
80 pub const F14: CGKeyCode = 0x6B;
81 pub const F15: CGKeyCode = 0x71;
82 pub const F16: CGKeyCode = 0x6A;
83 pub const F17: CGKeyCode = 0x40;
84 pub const F18: CGKeyCode = 0x4F;
85 pub const F19: CGKeyCode = 0x50;
86 pub const F20: CGKeyCode = 0x5A;
87 pub const HELP: CGKeyCode = 0x72;
88 pub const HOME: CGKeyCode = 0x73;
89 pub const PAGE_UP: CGKeyCode = 0x74;
90 pub const FORWARD_DELETE: CGKeyCode = 0x75;
91 pub const END: CGKeyCode = 0x77;
92 pub const PAGE_DOWN: CGKeyCode = 0x79;
93 pub const LEFT_ARROW: CGKeyCode = 0x7B;
94 pub const RIGHT_ARROW: CGKeyCode = 0x7C;
95 pub const DOWN_ARROW: CGKeyCode = 0x7D;
96 pub const UP_ARROW: CGKeyCode = 0x7E;
97 }
98
99 #[repr(C)]
100 pub struct ScrollEventUnit {}
101 impl ScrollEventUnit {
102 pub const PIXEL: CGScrollEventUnit = 0;
103 pub const LINE: CGScrollEventUnit = 1;
104 }
105
106 /// Constants that specify the different types of input events.
107 ///
108 /// [Ref](http://opensource.apple.com/source/IOHIDFamily/IOHIDFamily-700/IOHIDSystem/IOKit/hidsystem/IOLLEvent.h)
109 #[repr(u32)]
110 #[derive(Clone, Copy, Debug)]
111 pub enum CGEventType {
112 Null = 0,
113
114 // Mouse events.
115 LeftMouseDown = 1,
116 LeftMouseUp = 2,
117 RightMouseDown = 3,
118 RightMouseUp = 4,
119 MouseMoved = 5,
120 LeftMouseDragged = 6,
121 RightMouseDragged = 7,
122
123 // Keyboard events.
124 KeyDown = 10,
125 KeyUp = 11,
126 FlagsChanged = 12,
127
128 // Specialized control devices.
129 ScrollWheel = 22,
130 TabletPointer = 23,
131 TabletProximity = 24,
132 OtherMouseDown = 25,
133 OtherMouseUp = 26,
134 OtherMouseDragged = 27,
135
136 // Out of band event types. These are delivered to the event tap callback
137 // to notify it of unusual conditions that disable the event tap.
138 TapDisabledByTimeout = 0xFFFFFFFE,
139 TapDisabledByUserInput = 0xFFFFFFFF,
140 }
141
142 /// Constants used as keys to access specialized fields in low-level events.
143 ///
144 /// [Ref](https://developer.apple.com/documentation/coregraphics/cgeventfield)
145 pub struct EventField;
146 impl EventField {
147 /// Key to access an integer field that contains the mouse button event
148 /// number. Matching mouse-down and mouse-up events will have the same
149 /// event number.
150 pub const MOUSE_EVENT_NUMBER: CGEventField = 0;
151
152 /// Key to access an integer field that contains the mouse button click
153 /// state. A click state of 1 represents a single click. A click state of
154 /// 2 represents a double-click. A click state of 3 represents a
155 /// triple-click.
156 pub const MOUSE_EVENT_CLICK_STATE: CGEventField = 1;
157
158 /// Key to access a double field that contains the mouse button pressure.
159 /// The pressure value may range from 0 to 1, with 0 representing the
160 /// mouse being up. This value is commonly set by tablet pens mimicking a
161 /// mouse.
162 pub const MOUSE_EVENT_PRESSURE: CGEventField = 2;
163
164 /// Key to access an integer field that contains the mouse button number.
165 pub const MOUSE_EVENT_BUTTON_NUMBER: CGEventField = 3;
166
167 /// Key to access an integer field that contains the horizontal mouse
168 /// delta since the last mouse movement event.
169 pub const MOUSE_EVENT_DELTA_X: CGEventField = 4;
170
171 /// Key to access an integer field that contains the vertical mouse delta
172 /// since the last mouse movement event.
173 pub const MOUSE_EVENT_DELTA_Y: CGEventField = 5;
174
175 /// Key to access an integer field. The value is non-zero if the event
176 /// should be ignored by the Inkwell subsystem.
177 pub const MOUSE_EVENT_INSTANT_MOUSER: CGEventField = 6;
178
179 /// Key to access an integer field that encodes the mouse event subtype as
180 /// a `kCFNumberIntType'.
181 pub const MOUSE_EVENT_SUB_TYPE: CGEventField = 7;
182
183 /// Key to access an integer field, non-zero when this is an autorepeat of
184 /// a key-down, and zero otherwise.
185 pub const KEYBOARD_EVENT_AUTOREPEAT: CGEventField = 8;
186
187 /// Key to access an integer field that contains the virtual keycode of the
188 /// key-down or key-up event.
189 pub const KEYBOARD_EVENT_KEYCODE: CGEventField = 9;
190
191 /// Key to access an integer field that contains the keyboard type
192 /// identifier.
193 pub const KEYBOARD_EVENT_KEYBOARD_TYPE: CGEventField = 10;
194
195 /// Key to access an integer field that contains scrolling data. This field
196 /// typically contains the change in vertical position since the last
197 /// scrolling event from a Mighty Mouse scroller or a single-wheel mouse
198 /// scroller.
199 pub const SCROLL_WHEEL_EVENT_DELTA_AXIS_1: CGEventField = 11;
200
201 /// Key to access an integer field that contains scrolling data. This field
202 /// typically contains the change in horizontal position since the last
203 /// scrolling event from a Mighty Mouse scroller.
204 pub const SCROLL_WHEEL_EVENT_DELTA_AXIS_2: CGEventField = 12;
205
206 /// Key to access a field that contains scrolling data. The scrolling data
207 /// represents a line-based or pixel-based change in vertical position
208 /// since the last scrolling event from a Mighty Mouse scroller or a
209 /// single-wheel mouse scroller. The scrolling data uses a fixed-point
210 /// 16.16 signed integer format. If this key is passed to
211 /// `CGEventGetDoubleValueField', the fixed-point value is converted to a
212 /// double value.
213 pub const SCROLL_WHEEL_EVENT_FIXED_POINT_DELTA_AXIS_1: CGEventField = 93;
214
215 /// Key to access a field that contains scrolling data. The scrolling data
216 /// represents a line-based or pixel-based change in horizontal position
217 /// since the last scrolling event from a Mighty Mouse scroller. The
218 /// scrolling data uses a fixed-point 16.16 signed integer format. If this
219 /// key is passed to `CGEventGetDoubleValueField', the fixed-point value is
220 /// converted to a double value.
221 pub const SCROLL_WHEEL_EVENT_FIXED_POINT_DELTA_AXIS_2: CGEventField = 94;
222
223 /// Key to access an integer field that contains pixel-based scrolling
224 /// data. The scrolling data represents the change in vertical position
225 /// since the last scrolling event from a Mighty Mouse scroller or a
226 /// single-wheel mouse scroller.
227 pub const SCROLL_WHEEL_EVENT_POINT_DELTA_AXIS_1: CGEventField = 96;
228
229 /// Key to access an integer field that contains pixel-based scrolling
230 /// data. The scrolling data represents the change in horizontal position
231 /// since the last scrolling event from a Mighty Mouse scroller.
232 pub const SCROLL_WHEEL_EVENT_POINT_DELTA_AXIS_2: CGEventField = 97;
233
234 /// Key to access an integer field that indicates whether the event should
235 /// be ignored by the Inkwell subsystem. If the value is non-zero, the
236 /// event should be ignored.
237 pub const SCROLL_WHEEL_EVENT_INSTANT_MOUSER: CGEventField = 14;
238
239 /// Key to access an integer field that contains the absolute X coordinate
240 /// in tablet space at full tablet resolution.
241 pub const TABLET_EVENT_POINT_X: CGEventField = 15;
242
243 /// Key to access an integer field that contains the absolute Y coordinate
244 /// in tablet space at full tablet resolution.
245 pub const TABLET_EVENT_POINT_Y: CGEventField = 16;
246
247 /// Key to access an integer field that contains the absolute Z coordinate
248 /// in tablet space at full tablet resolution.
249 pub const TABLET_EVENT_POINT_Z: CGEventField = 17;
250
251 /// Key to access an integer field that contains the tablet button state.
252 /// Bit 0 is the first button, and a set bit represents a closed or pressed
253 /// button. Up to 16 buttons are supported.
254 pub const TABLET_EVENT_POINT_BUTTONS: CGEventField = 18;
255
256 /// Key to access a double field that contains the tablet pen pressure. A
257 /// value of 0.0 represents no pressure, and 1.0 represents maximum
258 /// pressure.
259 pub const TABLET_EVENT_POINT_PRESSURE: CGEventField = 19;
260
261 /// Key to access a double field that contains the horizontal tablet pen
262 /// tilt. A value of 0 represents no tilt, and 1 represents maximum tilt.
263 pub const TABLET_EVENT_TILT_X: CGEventField = 20;
264
265 /// Key to access a double field that contains the vertical tablet pen
266 /// tilt. A value of 0 represents no tilt, and 1 represents maximum tilt.
267 pub const TABLET_EVENT_TILT_Y: CGEventField = 21;
268
269 /// Key to access a double field that contains the tablet pen rotation.
270 pub const TABLET_EVENT_ROTATION: CGEventField = 22;
271
272 /// Key to access a double field that contains the tangential pressure on
273 /// the device. A value of 0.0 represents no pressure, and 1.0 represents
274 /// maximum pressure.
275 pub const TABLET_EVENT_TANGENTIAL_PRESSURE: CGEventField = 23;
276
277 /// Key to access an integer field that contains the system-assigned unique
278 /// device ID.
279 pub const TABLET_EVENT_DEVICE_ID: CGEventField = 24;
280
281 /// Key to access an integer field that contains a vendor-specified value.
282 pub const TABLET_EVENT_VENDOR_1: CGEventField = 25;
283
284 /// Key to access an integer field that contains a vendor-specified value.
285 pub const TABLET_EVENT_VENDOR_2: CGEventField = 26;
286
287 /// Key to access an integer field that contains a vendor-specified value.
288 pub const TABLET_EVENT_VENDOR_3: CGEventField = 27;
289
290 /// Key to access an integer field that contains the vendor-defined ID,
291 /// typically the USB vendor ID.
292 pub const TABLET_PROXIMITY_EVENT_VENDOR_ID: CGEventField = 28;
293
294 /// Key to access an integer field that contains the vendor-defined tablet
295 /// ID, typically the USB product ID.
296 pub const TABLET_PROXIMITY_EVENT_TABLET_ID: CGEventField = 29;
297
298 /// Key to access an integer field that contains the vendor-defined ID of
299 /// the pointing device.
300 pub const TABLET_PROXIMITY_EVENT_POINTER_ID: CGEventField = 30;
301
302 /// Key to access an integer field that contains the system-assigned
303 /// device ID.
304 pub const TABLET_PROXIMITY_EVENT_DEVICE_ID: CGEventField = 31;
305
306 /// Key to access an integer field that contains the system-assigned
307 /// unique tablet ID.
308 pub const TABLET_PROXIMITY_EVENT_SYSTEM_TABLET_ID: CGEventField = 32;
309
310 /// Key to access an integer field that contains the vendor-assigned
311 /// pointer type.
312 pub const TABLET_PROXIMITY_EVENT_VENDOR_POINTER_TYPE: CGEventField = 33;
313
314 /// Key to access an integer field that contains the vendor-defined
315 /// pointer serial number.
316 pub const TABLET_PROXIMITY_EVENT_VENDOR_POINTER_SERIAL_NUMBER: CGEventField = 34;
317
318 /// Key to access an integer field that contains the vendor-defined unique
319 /// ID.
320 pub const TABLET_PROXIMITY_EVENT_VENDOR_UNIQUE_ID: CGEventField = 35;
321
322 /// Key to access an integer field that contains the device capabilities
323 /// mask.
324 pub const TABLET_PROXIMITY_EVENT_CAPABILITY_MASK: CGEventField = 36;
325
326 /// Key to access an integer field that contains the pointer type.
327 pub const TABLET_PROXIMITY_EVENT_POINTER_TYPE: CGEventField = 37;
328
329 /// Key to access an integer field that indicates whether the pen is in
330 /// proximity to the tablet. The value is non-zero if the pen is in
331 /// proximity to the tablet and zero when leaving the tablet.
332 pub const TABLET_PROXIMITY_EVENT_ENTER_PROXIMITY: CGEventField = 38;
333
334 /// Key to access a field that contains the event target process serial
335 /// number. The value is a 64-bit value.
336 pub const EVENT_TARGET_PROCESS_SERIAL_NUMBER: CGEventField = 39;
337
338 /// Key to access a field that contains the event target Unix process ID.
339 pub const EVENT_TARGET_UNIX_PROCESS_ID: CGEventField = 40;
340
341 /// Key to access a field that contains the event source Unix process ID.
342 pub const EVENT_SOURCE_UNIX_PROCESS_ID: CGEventField = 41;
343
344 /// Key to access a field that contains the event source user-supplied
345 /// data, up to 64 bits.
346 pub const EVENT_SOURCE_USER_DATA: CGEventField = 42;
347
348 /// Key to access a field that contains the event source Unix effective UID.
349 pub const EVENT_SOURCE_USER_ID: CGEventField = 43;
350
351 /// Key to access a field that contains the event source Unix effective
352 /// GID.
353 pub const EVENT_SOURCE_GROUP_ID: CGEventField = 44;
354
355 /// Key to access a field that contains the event source state ID used to
356 /// create this event.
357 pub const EVENT_SOURCE_STATE_ID: CGEventField = 45;
358
359 /// Key to access an integer field that indicates whether a scrolling event
360 /// contains continuous, pixel-based scrolling data. The value is non-zero
361 /// when the scrolling data is pixel-based and zero when the scrolling data
362 /// is line-based.
363 pub const SCROLL_WHEEL_EVENT_IS_CONTINUOUS: CGEventField = 88;
364
365 /// Added in 10.5; made public in 10.7.
366 pub const MOUSE_EVENT_WINDOW_UNDER_MOUSE_POINTER: CGEventField = 91;
367 pub const MOUSE_EVENT_WINDOW_UNDER_MOUSE_POINTER_THAT_CAN_HANDLE_THIS_EVENT: CGEventField = 92;
368 }
369
370 // Constants that specify buttons on a one, two, or three-button mouse.
371 #[repr(C)]
372 #[derive(Clone, Copy, Debug)]
373 pub enum CGMouseButton {
374 Left,
375 Right,
376 Center,
377 }
378
379 /// Possible tapping points for events.
380 #[repr(C)]
381 #[derive(Clone, Copy, Debug)]
382 pub enum CGEventTapLocation {
383 HID,
384 Session,
385 AnnotatedSession,
386 }
387
388 // The next three enums are taken from:
389 // [Ref](https://github.com/phracker/MacOSX-SDKs/blob/ef9fe35d5691b6dd383c8c46d867a499817a01b6/MacOSX10.15.sdk/System/Library/Frameworks/CoreGraphics.framework/Versions/A/Headers/CGEventTypes.h)
390 /* Constants that specify where a new event tap is inserted into the list of
391 active event taps. */
392 #[repr(u32)]
393 #[derive(Clone, Copy, Debug)]
394 pub enum CGEventTapPlacement {
395 HeadInsertEventTap = 0,
396 TailAppendEventTap,
397 }
398
399 /* Constants that specify whether a new event tap is an active filter or a
400 passive listener. */
401 #[repr(u32)]
402 #[derive(Clone, Copy, Debug)]
403 pub enum CGEventTapOptions {
404 Default = 0x00000000,
405 ListenOnly = 0x00000001,
406 }
407
408 pub type CGEventMask = u64;
409 /* Generate an event mask for a single type of event. */
410 macro_rules! CGEventMaskBit {
411 ($eventType:expr) => {
412 1 << $eventType as CGEventMask
413 };
414 }
415
416 pub type CGEventTapProxy = *const c_void;
417 pub type CGEventTapCallBackFn<'tap_life> =
418 Box<dyn Fn(CGEventTapProxy, CGEventType, &CGEvent) -> Option<CGEvent> + 'tap_life>;
419 type CGEventTapCallBackInternal = unsafe extern "C" fn(
420 proxy: CGEventTapProxy,
421 etype: CGEventType,
422 event: ::sys::CGEventRef,
423 user_info: *const c_void,
424 ) -> ::sys::CGEventRef;
425
426 unsafe extern "C" fn cg_event_tap_callback_internal(
427 _proxy: CGEventTapProxy,
428 _etype: CGEventType,
429 _event: ::sys::CGEventRef,
430 _user_info: *const c_void,
431 ) -> ::sys::CGEventRef {
432 let callback = _user_info as *mut CGEventTapCallBackFn;
433 let event = CGEvent::from_ptr(_event);
434 let new_event = (*callback)(_proxy, _etype, &event);
435 let event = match new_event {
436 Some(new_event) => new_event,
437 None => event,
438 };
439 ManuallyDrop::new(event).as_ptr()
440 }
441
442
443 /// ```no_run
444 ///extern crate core_foundation;
445 ///use core_foundation::runloop::{kCFRunLoopCommonModes, CFRunLoop};
446 ///use core_graphics::event::{CGEventTap, CGEventTapLocation, CGEventTapPlacement, CGEventTapOptions, CGEventType};
447 ///let current = CFRunLoop::get_current();
448 ///match CGEventTap::new(
449 /// CGEventTapLocation::HID,
450 /// CGEventTapPlacement::HeadInsertEventTap,
451 /// CGEventTapOptions::Default,
452 /// vec![CGEventType::MouseMoved],
453 /// |_a, _b, d| {
454 /// println!("{:?}", d.location());
455 /// None
456 /// },
457 /// ) {
458 /// Ok(tap) => unsafe {
459 /// let loop_source = tap
460 /// .mach_port
461 /// .create_runloop_source(0)
462 /// .expect("Somethings is bad ");
463 /// current.add_source(&loop_source, kCFRunLoopCommonModes);
464 /// tap.enable();
465 /// CFRunLoop::run_current();
466 /// },
467 /// Err(_) => (assert!(false)),
468 /// }
469 /// ```
470 pub struct CGEventTap<'tap_life> {
471 pub mach_port: CFMachPort,
472 pub callback_ref:
473 Box<dyn Fn(CGEventTapProxy, CGEventType, &CGEvent) -> Option<CGEvent> + 'tap_life>,
474 }
475
476 impl<'tap_life> CGEventTap<'tap_life> {
477 pub fn new<F: Fn(CGEventTapProxy, CGEventType, &CGEvent) -> Option<CGEvent> + 'tap_life>(
478 tap: CGEventTapLocation,
479 place: CGEventTapPlacement,
480 options: CGEventTapOptions,
481 events_of_interest: std::vec::Vec<CGEventType>,
482 callback: F,
483 ) -> Result<CGEventTap<'tap_life>, ()> {
484 let event_mask: CGEventMask = events_of_interest
485 .iter()
486 .fold(CGEventType::Null as CGEventMask, |mask, &etype| {
487 mask | CGEventMaskBit!(etype)
488 });
489 let cb = Box::new(Box::new(callback) as CGEventTapCallBackFn);
490 let cbr = Box::into_raw(cb);
491 unsafe {
492 let event_tap_ref = CGEventTapCreate(
493 tap,
494 place,
495 options,
496 event_mask,
497 cg_event_tap_callback_internal,
498 cbr as *const c_void,
499 );
500
501 if !event_tap_ref.is_null() {
502 Ok(Self {
503 mach_port: (CFMachPort::wrap_under_create_rule(event_tap_ref)),
504 callback_ref: Box::from_raw(cbr),
505 })
506 } else {
507 let _ = Box::from_raw(cbr);
508 Err(())
509 }
510 }
511 }
512
513 pub fn enable(&self) {
514 unsafe { CGEventTapEnable(self.mach_port.as_concrete_TypeRef(), true) }
515 }
516 }
517
518 foreign_type! {
519 #[doc(hidden)]
520 pub unsafe type CGEvent {
521 type CType = ::sys::CGEvent;
522 fn drop = |p| CFRelease(p as *mut _);
523 fn clone = |p| CFRetain(p as *const _) as *mut _;
524 }
525 }
526
527 impl CGEvent {
528 pub fn type_id() -> CFTypeID {
529 unsafe {
530 CGEventGetTypeID()
531 }
532 }
533
534 pub fn new(source: CGEventSource) -> Result<CGEvent, ()> {
535 unsafe {
536 let event_ref = CGEventCreate(source.as_ptr());
537 if !event_ref.is_null() {
538 Ok(Self::from_ptr(event_ref))
539 } else {
540 Err(())
541 }
542 }
543 }
544
545 pub fn new_keyboard_event(
546 source: CGEventSource,
547 keycode: CGKeyCode,
548 keydown: bool
549 ) -> Result<CGEvent, ()> {
550 unsafe {
551 let event_ref = CGEventCreateKeyboardEvent(source.as_ptr(), keycode, keydown);
552 if !event_ref.is_null() {
553 Ok(Self::from_ptr(event_ref))
554 } else {
555 Err(())
556 }
557 }
558 }
559
560 pub fn new_mouse_event(
561 source: CGEventSource,
562 mouse_type: CGEventType,
563 mouse_cursor_position: CGPoint,
564 mouse_button: CGMouseButton
565 ) -> Result<CGEvent, ()> {
566 unsafe {
567 let event_ref = CGEventCreateMouseEvent(source.as_ptr(), mouse_type,
568 mouse_cursor_position, mouse_button);
569 if !event_ref.is_null() {
570 Ok(Self::from_ptr(event_ref))
571 } else {
572 Err(())
573 }
574 }
575 }
576
577 #[cfg(feature = "highsierra")]
578 pub fn new_scroll_event(
579 source: CGEventSource,
580 units: CGScrollEventUnit,
581 wheel_count: u32,
582 wheel1: i32,
583 wheel2: i32,
584 wheel3: i32,
585 ) -> Result<CGEvent, ()> {
586 unsafe {
587 let event_ref = CGEventCreateScrollWheelEvent2(
588 source.as_ptr(),
589 units,
590 wheel_count,
591 wheel1,
592 wheel2,
593 wheel3,
594 );
595 if !event_ref.is_null() {
596 Ok(Self::from_ptr(event_ref))
597 } else {
598 Err(())
599 }
600 }
601 }
602
603 pub fn post(&self, tap_location: CGEventTapLocation) {
604 unsafe {
605 CGEventPost(tap_location, self.as_ptr());
606 }
607 }
608
609 pub fn post_from_tap(&self, tap_proxy: CGEventTapProxy) {
610 unsafe {
611 CGEventTapPostEvent(tap_proxy, self.as_ptr());
612 }
613 }
614
615 pub fn location(&self) -> CGPoint {
616 unsafe { CGEventGetLocation(self.as_ptr()) }
617 }
618
619 #[cfg(feature = "elcapitan")]
620 pub fn post_to_pid(&self, pid: libc::pid_t) {
621 unsafe {
622 CGEventPostToPid(pid, self.as_ptr());
623 }
624 }
625
626 pub fn set_flags(&self, flags: CGEventFlags) {
627 unsafe {
628 CGEventSetFlags(self.as_ptr(), flags);
629 }
630 }
631
632 pub fn get_flags(&self) -> CGEventFlags {
633 unsafe {
634 CGEventGetFlags(self.as_ptr())
635 }
636 }
637
638 pub fn set_type(&self, event_type: CGEventType) {
639 unsafe {
640 CGEventSetType(self.as_ptr(), event_type);
641 }
642 }
643
644 pub fn get_type(&self) -> CGEventType {
645 unsafe {
646 CGEventGetType(self.as_ptr())
647 }
648 }
649
650 pub fn set_string_from_utf16_unchecked(&self, buf: &[u16]) {
651 let buflen = buf.len() as libc::c_ulong;
652 unsafe {
653 CGEventKeyboardSetUnicodeString(self.as_ptr(), buflen, buf.as_ptr());
654 }
655 }
656
657 pub fn set_string(&self, string: &str) {
658 let buf: Vec<u16> = string.encode_utf16().collect();
659 self.set_string_from_utf16_unchecked(&buf);
660 }
661
662 pub fn get_integer_value_field(&self, field: CGEventField) -> i64 {
663 unsafe { CGEventGetIntegerValueField(self.as_ptr(), field) }
664 }
665
666 pub fn set_integer_value_field(&self, field: CGEventField, value: i64) {
667 unsafe { CGEventSetIntegerValueField(self.as_ptr(), field, value) }
668 }
669
670 pub fn get_double_value_field(&self, field: CGEventField) -> f64 {
671 unsafe { CGEventGetDoubleValueField(self.as_ptr(), field) }
672 }
673
674 pub fn set_double_value_field(&self, field: CGEventField, value: f64) {
675 unsafe { CGEventSetDoubleValueField(self.as_ptr(), field, value) }
676 }
677 }
678
679 #[link(name = "CoreGraphics", kind = "framework")]
680 extern {
681 /// Return the type identifier for the opaque type `CGEventRef'.
682 fn CGEventGetTypeID() -> CFTypeID;
683
684 /// Return a new event using the event source `source'. If `source' is NULL,
685 /// the default source is used.
686 fn CGEventCreate(source: ::sys::CGEventSourceRef) -> ::sys::CGEventRef;
687
688 /// Return a new keyboard event.
689 ///
690 /// The event source may be taken from another event, or may be NULL. Based
691 /// on the virtual key code values entered, the appropriate key down, key up,
692 /// or flags changed events are generated.
693 ///
694 /// All keystrokes needed to generate a character must be entered, including
695 /// SHIFT, CONTROL, OPTION, and COMMAND keys. For example, to produce a 'Z',
696 /// the SHIFT key must be down, the 'z' key must go down, and then the SHIFT
697 /// and 'z' key must be released:
698 fn CGEventCreateKeyboardEvent(source: ::sys::CGEventSourceRef, keycode: CGKeyCode,
699 keydown: bool) -> ::sys::CGEventRef;
700
701 /// Return a new mouse event.
702 ///
703 /// The event source may be taken from another event, or may be NULL.
704 /// `mouseType' should be one of the mouse event types. `mouseCursorPosition'
705 /// should be the position of the mouse cursor in global coordinates.
706 /// `mouseButton' should be the button that's changing state; `mouseButton'
707 /// is ignored unless `mouseType' is one of `kCGEventOtherMouseDown',
708 /// `kCGEventOtherMouseDragged', or `kCGEventOtherMouseUp'.
709 ///
710 /// The current implementation of the event system supports a maximum of
711 /// thirty-two buttons. Mouse button 0 is the primary button on the mouse.
712 /// Mouse button 1 is the secondary mouse button (right). Mouse button 2 is
713 /// the center button, and the remaining buttons are in USB device order.
714 fn CGEventCreateMouseEvent(source: ::sys::CGEventSourceRef, mouseType: CGEventType,
715 mouseCursorPosition: CGPoint, mouseButton: CGMouseButton) -> ::sys::CGEventRef;
716
717 /// A non-variadic variant version of CGEventCreateScrollWheelEvent.
718 ///
719 /// Returns a new Quartz scrolling event.
720 ///
721 /// This function allows you to create a scrolling event and customize the
722 /// event before posting it to the event system.
723 #[cfg(feature = "highsierra")]
724 fn CGEventCreateScrollWheelEvent2(
725 source: ::sys::CGEventSourceRef,
726 units: CGScrollEventUnit,
727 wheelCount: u32,
728 wheel1: i32,
729 wheel2: i32,
730 wheel3: i32,
731 ) -> ::sys::CGEventRef;
732
733 /// Post an event into the event stream at a specified location.
734 ///
735 /// This function posts the specified event immediately before any event taps
736 /// instantiated for that location, and the event passes through any such
737 /// taps.
738 fn CGEventPost(tapLocation: CGEventTapLocation, event: ::sys::CGEventRef);
739
740 fn CGEventTapPostEvent(tapProxy: CGEventTapProxy, event: ::sys::CGEventRef);
741
742 #[cfg(feature = "elcapitan")]
743 /// Post an event to a specified process ID
744 fn CGEventPostToPid(pid: libc::pid_t, event: ::sys::CGEventRef);
745
746 /// Set the event flags of an event.
747 fn CGEventSetFlags(event: ::sys::CGEventRef, flags: CGEventFlags);
748
749 /// Return the event flags of an event.
750 fn CGEventGetFlags(event: ::sys::CGEventRef) -> CGEventFlags;
751
752 /// Return the location of an event in global display coordinates.
753 /// CGPointZero is returned if event is not a valid ::sys::CGEventRef.
754 fn CGEventGetLocation(event: ::sys::CGEventRef) -> CGPoint;
755
756 /// Set the event type of an event.
757 fn CGEventSetType(event: ::sys::CGEventRef, eventType: CGEventType);
758
759 /// Return the event type of an event (left mouse down, for example).
760 fn CGEventGetType(event: ::sys::CGEventRef) -> CGEventType;
761
762 /// Set the Unicode string associated with a keyboard event.
763 ///
764 /// By default, the system translates the virtual key code in a keyboard
765 /// event into a Unicode string based on the keyboard ID in the event
766 /// source. This function allows you to manually override this string.
767 /// Note that application frameworks may ignore the Unicode string in a
768 /// keyboard event and do their own translation based on the virtual
769 /// keycode and perceived event state.
770 fn CGEventKeyboardSetUnicodeString(event: ::sys::CGEventRef,
771 length: libc::c_ulong,
772 string: *const u16);
773
774 /// Return the integer value of a field in an event.
775 fn CGEventGetIntegerValueField(event: ::sys::CGEventRef, field: CGEventField) -> i64;
776
777 /// Set the integer value of a field in an event.
778 ///
779 /// Before calling this function, the event type must be set using a typed
780 /// event creation function such as `CGEventCreateMouseEvent', or by
781 /// calling `CGEventSetType'.
782 ///
783 /// If you are creating a mouse event generated by a tablet, call this
784 /// function and specify the field `kCGMouseEventSubtype' with a value of
785 /// `kCGEventMouseSubtypeTabletPoint' or
786 /// `kCGEventMouseSubtypeTabletProximity' before setting other parameters.
787 fn CGEventSetIntegerValueField(event: ::sys::CGEventRef, field: CGEventField, value: i64);
788
789 /// Return the floating-point value of a field in an event.
790 ///
791 /// In cases where the field value is represented within the event by a fixed
792 /// point number or an integer, the result is scaled to the appropriate range
793 /// as part of creating the floating-point representation.
794 fn CGEventGetDoubleValueField(event: ::sys::CGEventRef, field: CGEventField) -> f64;
795
796 /// Set the floating-point value of a field in an event.
797 ///
798 /// Before calling this function, the event type must be set using a typed
799 /// event creation function such as `CGEventCreateMouseEvent', or by calling
800 /// `CGEventSetType'.
801 ///
802 /// In cases where the field’s value is represented within the event by a
803 /// fixed point number or integer, the value parameter is scaled as needed
804 /// and converted to the appropriate type.
805 fn CGEventSetDoubleValueField(event: ::sys::CGEventRef, field: CGEventField, value: f64);
806
807 // ::sys::CGEventTapRef is actually an CFMachPortRef
808 fn CGEventTapCreate(
809 tap: CGEventTapLocation,
810 place: CGEventTapPlacement,
811 options: CGEventTapOptions,
812 eventsOfInterest: CGEventMask,
813 callback: CGEventTapCallBackInternal,
814 userInfo: *const c_void,
815 ) -> CFMachPortRef;
816
817 fn CGEventTapEnable(tap: CFMachPortRef, enable: bool);
818
819 }