Thursday, December 11, 2008

Middle Click on a Mac code

Paste the following code into a file called click.m, then compile using gcc -o click click.m -framework ApplicationServices -framework Foundation


// click.m
//
// Compile with:
// gcc -o click click.m -framework ApplicationServices -framework Foundation
//
// Usage:
// ./click -i 1
// It will command-click the mouse wherever the mouse is.


#import <foundation foundation.h>
#import <applicationservices applicationservices.h>


int main(int argc, char *argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSUserDefaults *args = [NSUserDefaults standardUserDefaults];


// grabs command line argument -i
// i: 0 to not middle click, 1 to middle click
int i = [args integerForKey:@"i"];
// get the current pointer location
CGEventRef ourEvent = CGEventCreate(NULL);
// middle click at the current location
// command keycode is 55
if (i==1) {
CGPostKeyboardEvent( (CGCharCode)0, (CGKeyCode)55, true );
CGPostMouseEvent( ourLoc, 1, 1, 1);
CGPostMouseEvent( ourLoc, 1, 1, 0);
CGPostKeyboardEvent( (CGCharCode)0, (CGKeyCode)55, false );
}
[pool release];
return 0;
}

After it's compiled, place it somewhere out of the way, preferably in a bin directory. Then write a quick java program, like this:

public class Main {
public static void main(String[] args) {
try {
Runtime rt = Runtime.getRuntime();
rt.exec("/Path/To/click -i 1");
} catch (Throwable t) {
t.printStackTrace();
}
}

}

replacing /Path/To/click with the UNIX path to click. then package it up in a jar and use jar builder to make a mac java app. Place the app in a place quicksilver will find it.
Open QS and hit command-' to get to the triggers. Add a new trigger with the java app as the program to run. give it a shortcut like command-option-shift-/ (this makes it very unlikely that it will collide with another program's shortcut). Now open the multiclutch prefpane and add a new gesture with your shortcut(above) as the shortcut.
Done. Pat yourself on the back, you've just made a middle-click gesture!