(OS X) Prevent keyobard during programmatic mouse click - macos

I'm trying to port keynav to OS X. It is basically working, but I'm facing a problem due to the inability to change (global) monitored events.
Is it possible to suppress a keyboard modifier during a mouse click event? Maybe using a sequence, for example creating a keyboard event with "control key up" + mouse click?
This is my mouse click method:
- (void)clickMouseAtPoint:(CGPoint)point
{
CGEventRef move = CGEventCreateMouseEvent(
NULL, kCGEventMouseMoved,
point,
kCGMouseButtonLeft // ignored
);
CGEventRef click1_down = CGEventCreateMouseEvent(
NULL, kCGEventLeftMouseDown,
point,
kCGMouseButtonLeft
);
CGEventRef click1_up = CGEventCreateMouseEvent(
NULL, kCGEventLeftMouseUp,
point,
kCGMouseButtonLeft
);
CGEventPost(kCGHIDEventTap, move);
CGEventPost(kCGHIDEventTap, click1_down);
CGEventPost(kCGHIDEventTap, click1_up);
CFRelease(click1_up);
CFRelease(click1_down);
CFRelease(move1);
}

So this is what I ended up with. Background to what is done here in particular: The keynav is overlayed to the whole desktop when pressing ctrl+comma, a user may navigate the cross-hair using holding ctrl+SomeKeys, and simulate a mouse click at the cross-hait position by a second ctrl+comma (awaitClick is set when the second click is awaited in the code snippet below).
Now, before the click is done the control key modifier is removed from the keyboard event. Also, while keynav is shown all keyboard input is swapped with keycode -1. I found this by experimenting that this suppresses a key press.
If this is a good way or not, I can't tell. But it works reliably so far.
CGEventRef
myCGEventCallback(CGEventTapProxy proxy, CGEventType type,
CGEventRef event, void *refcon)
{
if ((type != kCGEventKeyDown) && (type != kCGEventKeyUp))
return event;
CGKeyCode keycode = (CGKeyCode)CGEventGetIntegerValueField(event, kCGKeyboardEventKeycode);
EWAppDelegate *appInstance = [NSApplication sharedApplication].delegate;
CGEventFlags flags = CGEventGetFlags(event);
if (_awaitClick && keycode == (CGKeyCode)43 && type == kCGEventKeyDown)
{
flags = flags & ~kCGEventFlagMaskControl;
CGEventSetFlags(event, flags);
NSLog(#"suppressed control key");
}
BOOL didHandle = NO;
if (type == kCGEventKeyDown)
{
didHandle = [appInstance handleNavKey:keycode flags:flags];
}
NSLog(#"pressed keycode %d", keycode);
if (didHandle || _navIsSHowing) {
CGEventSetIntegerValueField(event, kCGKeyboardEventKeycode, (int64_t)-1);
NSLog(#"nav");
}
return event;
}
- (BOOL)registerGlobalKeyBoardModifier
{
CFMachPortRef eventTap;
CGEventMask eventMask;
CFRunLoopSourceRef runLoopSource;
eventMask = ((1 << kCGEventKeyDown) | (1 << kCGEventKeyUp));
eventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0,
eventMask, myCGEventCallback, NULL);
if (!eventTap) {
fprintf(stderr, "failed to create event tap\n");
return NO;
}
runLoopSource = CFMachPortCreateRunLoopSource(
kCFAllocatorDefault, eventTap, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource,
kCFRunLoopCommonModes);
CGEventTapEnable(eventTap, true);
return YES;
}

Related

How to read mouse delta in Quartz events?

In a Quartz application, I am trying to freeze the mouse pointer on the screen but continue to register mouse mouvements from the user. I have found how to freeze the pointer:
CGAssociateMouseAndMouseCursorPosition(false);
I am following the documentation but don't know how to get and read events that contain mouse delta (change in X and Y) data.
I found the solution. I am now getting the mouse movements like this:
CGEventMask eventMask = CGEventMaskBit(kCGEventMouseMoved);
CFMachPortRef tap = CGEventTapCreate( kCGAnnotatedSessionEventTap,
kCGHeadInsertEventTap,
kCGEventTapOptionListenOnly,
eventMask,
eventOccurred,
NULL);
CFRunLoopSourceRef rl = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, tap, 0);
CFRunLoopAddSource(CFRunLoopGetMain(), rl, kCFRunLoopCommonModes);
CGEventTapEnable(tap, true);
where the callback is:
CGEventRef eventOccurred(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void* refcon) {
if (type == kCGEventMouseMoved) {
d_x = CGEventGetIntegerValueField(event, kCGMouseEventDeltaX);
d_y = CGEventGetIntegerValueField(event, kCGMouseEventDeltaY);
}
return event;
}
Note: d_xand d_y are globally defined int that store the mouse movement between each event.

Remap `fn` to left mouse button on OSX

I get bad tendinitis from clicking the mouse all day.
In the past I used Karabiner to remap the fn key to simulate a left mouse button. However it doesn't work with Sierra.
I tried to accomplish this in Cocoa, and it correctly performs mouse-down/up when I press and release fn.
However it doesn't handle double-click / triple-click.
Also when dragging, (e.g. dragging a window, or selecting some text) nothing happens visually until I key-up, whereupon it completes.
How can I adapt my code to implement this?
First I create an event tap:
- (BOOL)tapEvents
{
_modifiers = [NSEvent modifierFlags];
if ( ! _eventTap ) {
NSLog( #"Initializing an event tap." );
// kCGHeadInsertEventTap -- new event tap should be inserted before
// any pre-existing event taps at the same location,
_eventTap = CGEventTapCreate( kCGHIDEventTap, // kCGSessionEventTap,
kCGHeadInsertEventTap,
kCGEventTapOptionDefault,
CGEventMaskBit( kCGEventKeyDown )
| CGEventMaskBit( kCGEventFlagsChanged )
| CGEventMaskBit( NSSystemDefined )
,
(CGEventTapCallBack)_tapCallback,
(__bridge void *)(self));
if ( ! _eventTap ) {
NSLog(#"unable to create event tap. must run as root or "
"add privlidges for assistive devices to this app.");
return NO;
}
}
CGEventTapEnable( _eventTap, YES );
return [self isTapActive];
}
Now I implement the callback:
CGEventRef _tapCallback(
CGEventTapProxy proxy,
CGEventType type,
CGEventRef event,
Intercept* listener
)
{
//Do not make the NSEvent here.
//NSEvent will throw an exception if we try to make an event from the tap timout type
#autoreleasepool {
if( type == kCGEventTapDisabledByTimeout ) {
NSLog(#"event tap has timed out, re-enabling tap");
[listener tapEvents];
return nil;
}
if( type != kCGEventTapDisabledByUserInput ) {
return [listener processEvent:event];
}
}
return event;
}
Finally I implement a processEvent that will pass through any event apart from fn key up/down, which will get converted to left mouse up/down:
- (CGEventRef)processEvent:(CGEventRef)cgEvent
{
//NSLog( #"- - - - - - -" );
NSEvent* event = [NSEvent eventWithCGEvent:cgEvent];
//NSLog(#"%d,%d", event.data1, event.data2);
//NSEventType type = [event type];
NSUInteger m = event.modifierFlags &
( NSCommandKeyMask | NSAlternateKeyMask | NSShiftKeyMask | NSControlKeyMask | NSAlphaShiftKeyMask | NSFunctionKeyMask );
NSUInteger flags_changed = _modifiers ^ m;
_modifiers = m;
switch( event.type ) {
case NSFlagsChanged:
{
assert(flags_changed);
//NSLog(#"NSFlagsChanged: %d, event.modifierFlags: %lx", event.keyCode, event.modifierFlags);
if( flags_changed & NSFunctionKeyMask ) {
bool isDown = _modifiers & NSFunctionKeyMask;
CGEventType evType = isDown ? kCGEventLeftMouseDown : kCGEventLeftMouseUp;
CGPoint pt = [NSEvent mouseLocation];
CGPoint mousePoint = CGPointMake(pt.x, [NSScreen mainScreen].frame.size.height - pt.y);
CGEventRef theEvent = CGEventCreateMouseEvent(NULL, evType, mousePoint, kCGMouseButtonLeft);
CGEventSetType(theEvent, evType);
CGEventPost(kCGHIDEventTap, theEvent);
CFRelease(theEvent);
//return theEvent;
}
break;
}
}
_lastEvent = [event CGEvent];
CFRetain(_lastEvent); // must retain the event. will be released by the system
return _lastEvent;
}
EDIT: Performing a double click using CGEventCreateMouseEvent()
EDIT: OSX assign left mouse click to a keyboard key
Karabiner now works on macOS 10.12 and later.

how to disable keys in OS X?

I've an application that needs disable some keys while the application in running (i.e: A, option, command, shift).
how can I do that?
the language or method used does not matter.
You can inspect, modify, and block keyboard events with a CGEventTap.
The user will need to grant your app assistive privileges via the Security pane of System Preferences for events to be disabled before posting.
Something like this:
- (void)setKeyBlocker {
// You should filter this better than kCGEventMaskForAllEvents, depending on your needs.
CFMachPortRef eventTap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault, kCGEventMaskForAllEvents, cgEventCallback, NULL);
CFRunLoopSourceRef runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes);
CGEventTapEnable(eventTap, true);
CFRelease(eventTap);
CFRelease(runLoopSource);
}
CGEventRef callback(CGEventTapProxy proxy, CGEventType type, CGEventRef cgEvent, void *refcon) {
NSEvent *event = [NSEvent eventWithCGEvent:cgEvent];
if (event.type == kCGEventKeyDown) {
if ([event.characters isEqualToString:#"a"]) {
// Kill event
return NULL;
}
}
return cgEvent;
}

cocoa global watch for modifier key press

Using addGlobalMonitorForEventsMatchingMask, I can check for keys being pressed. And when an event is fired, I can check the modifier flags to see if any modifiers were used in conjunction.
But I need to know if a modifier is pressed without another key being pressed.
How would I do this?
You're looking for events of type kCGEventFlagsChanged:
CGEventMask eventMask = (1 << kCGEventFlagsChanged);
CFMachPortRef eventTap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault, eventMask, cgEventCallback, NULL);
...
CGEventRef cgEventCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef cgEvent, void *refcon)
{
NSEvent *event = [NSEvent eventWithCGEvent:cgEvent];
if (event.type == kCGEventFlagsChanged) {
NSLog(#"modifier key!");
}
}

How to trap global keydown/keyup events in cocoa

I want to trap, modify and divert all the keydown/keyup events in the system within my cocoa app. I know about CGEventTapCreate but, didn't found any working code from net.
Thanks
Found Solution:
self.machPortRef = CGEventTapCreate(kCGSessionEventTap,
kCGTailAppendEventTap,
kCGEventTapOptionDefault,
CGEventMaskBit(kCGEventKeyDown),
(CGEventTapCallBack)eventTapFunction,
self);
if (self.machPortRef == NULL)
{
printf("CGEventTapCreate failed!\n");
} else {
self.eventSrc = CFMachPortCreateRunLoopSource(NULL, self.machPortRef, 0);
if ( self.eventSrc == NULL )
{
printf( "No event run loop src?\n" );
}else {
CFRunLoopRef runLoop = CFRunLoopGetCurrent(); //GetCFRunLoopFromEventLoop(GetMainEventLoop ());
// Get the CFRunLoop primitive for the Carbon Main Event Loop, and add the new event souce
CFRunLoopAddSource(runLoop, self.eventSrc, kCFRunLoopDefaultMode);
}
}
Properties :
CFMachPortRef machPortRef;
CFRunLoopSourceRef eventSrc;
Event Handler:
CGEventRef eventTapFunction(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon)
{
//printf("eventTap triggered\n");
return event;
}

Resources