Skip to content

Commit 785b0cf

Browse files
committed
CGEventTap: Allow dropping events from callback
1 parent f58166d commit 785b0cf

File tree

1 file changed

+16
-10
lines changed

1 file changed

+16
-10
lines changed

core-graphics/src/event.rs

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use foreign_types::ForeignType;
88
use geometry::CGPoint;
99
use libc::c_void;
1010
use std::mem::ManuallyDrop;
11+
use std::ptr;
1112

1213
pub type CGEventField = u32;
1314
pub type CGKeyCode = u16;
@@ -414,8 +415,13 @@ macro_rules! CGEventMaskBit {
414415
}
415416

416417
pub type CGEventTapProxy = *const c_void;
418+
pub enum CGEventTapCallbackResult {
419+
Replace(CGEvent),
420+
Keep,
421+
Drop,
422+
}
417423
pub type CGEventTapCallBackFn<'tap_life> =
418-
Box<dyn Fn(CGEventTapProxy, CGEventType, &CGEvent) -> Option<CGEvent> + 'tap_life>;
424+
Box<dyn Fn(CGEventTapProxy, CGEventType, &CGEvent) -> CGEventTapCallbackResult + 'tap_life>;
419425
type CGEventTapCallBackInternal = unsafe extern "C" fn(
420426
proxy: CGEventTapProxy,
421427
etype: CGEventType,
@@ -431,13 +437,14 @@ unsafe extern "C" fn cg_event_tap_callback_internal(
431437
_user_info: *const c_void,
432438
) -> ::sys::CGEventRef {
433439
let callback = _user_info as *mut CGEventTapCallBackFn;
434-
let event = CGEvent::from_ptr(_event);
440+
let event = ManuallyDrop::new(CGEvent::from_ptr(_event));
435441
let new_event = (*callback)(_proxy, _etype, &event);
436-
let event = match new_event {
437-
Some(new_event) => new_event,
438-
None => event,
439-
};
440-
ManuallyDrop::new(event).as_ptr()
442+
use self::CGEventTapCallbackResult::*;
443+
match new_event {
444+
Replace(new_event) => ManuallyDrop::new(new_event).as_ptr(),
445+
Keep => _event,
446+
Drop => ptr::null_mut(),
447+
}
441448
}
442449

443450

@@ -470,12 +477,11 @@ unsafe extern "C" fn cg_event_tap_callback_internal(
470477
/// ```
471478
pub struct CGEventTap<'tap_life> {
472479
pub mach_port: CFMachPort,
473-
pub callback_ref:
474-
Box<dyn Fn(CGEventTapProxy, CGEventType, &CGEvent) -> Option<CGEvent> + 'tap_life>,
480+
pub callback_ref: CGEventTapCallBackFn<'tap_life>,
475481
}
476482

477483
impl<'tap_life> CGEventTap<'tap_life> {
478-
pub fn new<F: Fn(CGEventTapProxy, CGEventType, &CGEvent) -> Option<CGEvent> + 'tap_life>(
484+
pub fn new<F: Fn(CGEventTapProxy, CGEventType, &CGEvent) -> CGEventTapCallbackResult + 'tap_life>(
479485
tap: CGEventTapLocation,
480486
place: CGEventTapPlacement,
481487
options: CGEventTapOptions,

0 commit comments

Comments
 (0)