Remap `fn` to left mouse button on OSX - macos

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.

Related

(OS X) Prevent keyobard during programmatic mouse click

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;
}

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;
}

Reverse engineering an NSMenu for a Status Bar Item

I'm want to create a menu for a status bar item like the one seen in Tapbot's PastebotSync application:
Does anyone have any ideas how to achieve the custom area at the top of the menu which is flush with the top?
I've tried/thought of a few potential ways of doing it:
Standard NSMenuItem with a view - isn't flush with the top of the menu
Some hack-ish code to place an NSWindow over the area at the top of the menu - not great as it doesn't fade out nicely with the menu when it closes
Abandoning an NSMenu entirely and using an NSView instead - haven't tried this yet but I don't really want to have to make some fake buttons or something that act as NSMenuItems
Anyone have any better ideas or suggestions?
Thanks!
In case anyone comes looking, I posted a solution to this at Gap above NSMenuItem custom view
Here's the code:
#interface FullMenuItemView : NSView
#end
#implementation FullMenuItemView
- (void) drawRect:(NSRect)dirtyRect
{
NSRect fullBounds = [self bounds];
fullBounds.size.height += 4;
[[NSBezierPath bezierPathWithRect:fullBounds] setClip];
// Then do your drawing, for example...
[[NSColor blueColor] set];
NSRectFill( fullBounds );
}
#end
Use it like this:
CGFloat menuItemHeight = 32;
NSRect viewRect = NSMakeRect(0, 0, /* width autoresizes */ 1, menuItemHeight);
NSView *menuItemView = [[[FullMenuItemView alloc] initWithFrame:viewRect] autorelease];
menuItemView.autoresizingMask = NSViewWidthSizable;
yourMenuItem.view = menuItemView;
I had the same need in early versions of HoudahSpot 2. I did get it working with one limitation: my code leaves the menu with square corners at the bottom.
I have since abandonned this setup, as the BlitzSearch feature in HoudahSpot grew to need a complexer UI, I ran into other limitations with using NSViews in a NSMenu.
Anyway, here is the original code taking care of those extra 3 pixels:
- (void)awakeFromNib
{
HIViewRef contentView;
MenuRef menuRef = [statusMenu carbonMenuRef];
HIMenuGetContentView (menuRef, kThemeMenuTypePullDown, &contentView);
EventTypeSpec hsEventSpec[1] = {
{ kEventClassMenu, kEventMenuCreateFrameView }
};
HIViewInstallEventHandler(contentView,
NewEventHandlerUPP((EventHandlerProcPtr)hsMenuCreationEventHandler),
GetEventTypeCount(hsEventSpec),
hsEventSpec,
NULL,
NULL);
}
#pragma mark -
#pragma mark Carbon handlers
static OSStatus hsMenuContentEventHandler( EventHandlerCallRef caller, EventRef event, void* refcon )
{
OSStatus err;
check( GetEventClass( event ) == kEventClassControl );
check( GetEventKind( event ) == kEventControlGetFrameMetrics );
err = CallNextEventHandler( caller, event );
if ( err == noErr )
{
HIViewFrameMetrics metrics;
verify_noerr( GetEventParameter( event, kEventParamControlFrameMetrics, typeControlFrameMetrics, NULL,
sizeof( metrics ), NULL, &metrics ) );
metrics.top = 0;
verify_noerr( SetEventParameter( event, kEventParamControlFrameMetrics, typeControlFrameMetrics,
sizeof( metrics ), &metrics ) );
}
return err;
}
static OSStatus hsMenuCreationEventHandler( EventHandlerCallRef caller, EventRef event, void* refcon )
{
OSStatus err = eventNotHandledErr;
if ( GetEventKind( event ) == kEventMenuCreateFrameView)
{
err = CallNextEventHandler( caller, event );
if ( err == noErr )
{
static const EventTypeSpec kContentEvents[] =
{
{ kEventClassControl, kEventControlGetFrameMetrics }
};
HIViewRef frame;
HIViewRef content;
verify_noerr( GetEventParameter( event, kEventParamMenuFrameView, typeControlRef, NULL,
sizeof( frame ), NULL, &frame ) );
verify_noerr( HIViewFindByID( frame, kHIViewWindowContentID, &content ) );
HIViewInstallEventHandler( content, hsMenuContentEventHandler, GetEventTypeCount( kContentEvents ),
kContentEvents, 0, NULL );
}
}
return err;
}
Sorry, I forgot that bit:
- (MenuRef) carbonMenuRef
{
MenuRef carbonMenuRef = NULL;
if (carbonMenuRef == NULL) {
extern MenuRef _NSGetCarbonMenu(NSMenu *);
carbonMenuRef = _NSGetCarbonMenu(self);
if (carbonMenuRef == NULL) {
NSMenu *theMainMenu = [NSApp mainMenu];
NSMenuItem *theDummyMenuItem = [theMainMenu addItemWithTitle: #"sub" action: NULL keyEquivalent: #""];
if (theDummyMenuItem != nil) {
[theDummyMenuItem setSubmenu:self];
[theDummyMenuItem setSubmenu:nil];
[theMainMenu removeItem:theDummyMenuItem];
carbonMenuRef = _NSGetCarbonMenu(self);
}
}
}
if (carbonMenuRef == NULL) {
extern MenuRef _NSGetCarbonMenu2(NSMenu *);
carbonMenuRef = _NSGetCarbonMenu2(self);
}
return carbonMenuRef;
}

How to Capture / Post system-wide Keyboard / Mouse events under Mac OS X?

For a scripting utility I need to be able to record a series of keyboard and mouse events that occur when an application has focus. The second part is being able to later send those events to the active window.
I do not need to worry about menus or tracking the identifier of which window receives input.
I know how to do this under Windows but have no idea about Mac OS X.
The first thing i will tell you is that you CAN'T do this without the user enabling support for assitive devices in the accessability control panel. It's some kind of security built into OSX.
Here is a code snippit I am using in one of my applications to do this:
//this method calls a carbon method to attach a global event handler
- (void)attachEventHandlers
{
//create our event type spec for the keyup
EventTypeSpec eventType;
eventType.eventClass = kEventClassKeyboard;
eventType.eventKind = kEventRawKeyUp;
//create a callback for our event to fire in
EventHandlerUPP handlerFunction = NewEventHandlerUPP(globalKeyPress);
//install the event handler
OSStatus err = InstallEventHandler(GetEventMonitorTarget(), handlerFunction, 1, &eventType, self, NULL);
//error checking
if( err )
{
//TODO: need an alert sheet here
NSLog(#"Error registering keyboard handler...%d", err);
}
//create our event type spec for the mouse events
EventTypeSpec eventTypeM;
eventTypeM.eventClass = kEventClassMouse;
eventTypeM.eventKind = kEventMouseUp;
//create a callback for our event to fire in
EventHandlerUPP handlerFunctionM = NewEventHandlerUPP(globalMousePress);
//install the event handler
OSStatus errM = InstallEventHandler(GetEventMonitorTarget(), handlerFunctionM, 1, &eventTypeM, self, NULL);
//error checking
if( errM )
{
//TODO: need an alert sheet here
NSLog(#"Error registering mouse handler...%d", err);
}
}
Here is an example of the callback method i am using:
OSStatus globalKeyPress(EventHandlerCallRef nextHandler, EventRef theEvent, void *userData)
{
NSEvent *anEvent = [NSEvent eventWithEventRef:theEvent];
NSEventType type = [anEvent type];
WarStrokerApplication *application = (WarStrokerApplication*)userData;
//is it a key up event?
if( type == NSKeyUp)
{
//which key is it?
switch( [anEvent keyCode] )
{
case NUMERIC_KEYPAD_PLUS:
//this is the character we are using for our toggle
//call the handler function
[application toggleKeyPressed];
break;
//Comment this line back in to figure out the keykode for a particular character
default:
NSLog(#"Keypressed: %d, **%#**", [anEvent keyCode], [anEvent characters]);
break;
}
}
return CallNextEventHandler(nextHandler, theEvent);
}
For the latter part, posting events, use the CGEvent methods provided in ApplicationServices/ApplicationServices.h
Here's an example function to move the mouse to a specified absolute location:
#include <ApplicationServices/ApplicationServices.h>
int to(int x, int y)
{
CGPoint newloc;
CGEventRef eventRef;
newloc.x = x;
newloc.y = y;
eventRef = CGEventCreateMouseEvent(NULL, kCGEventMouseMoved, newloc,
kCGMouseButtonCenter);
//Apparently, a bug in xcode requires this next line
CGEventSetType(eventRef, kCGEventMouseMoved);
CGEventPost(kCGSessionEventTap, eventRef);
CFRelease(eventRef);
return 0;
}
For tapping mouse events, see Link
I haven't checked this under 10.5 Leopard but on 10.4 it works.

Resources