2009-05-05

kelvSYC on Cocoa and Java

One of the more interesting exercises is how to program a Mac program
using the Cocoa framework while keeping all of your core program logic
in Java. It used to be trivial, but has gotten much less with the
deprecation of the Cocoa Java bridge (people are simply told to "use
JNI", which is still quite vague).

Now Cocoa relies on MVC - the model-view-controller paradigm. The
model (core program logic) would be in Java, and the view is basically
your Cocoa nib. The controller is pretty much where you use JNI. The
basic idea is that your controller object (in Objective-C) would be
associated with a Java object, and any IBActions that you write in
your controller effectively result in method calls on the Java object
(then, the Java object further interacts with the model).

Seems like a bunch of boilerplate, and there has to be a way to
automate this. My first thought is to write an annotation processor.
Given the Java source to the object's class file, could it be possible
to annotate this source in such a way so that the annotation processor
can write the necessary Objective-C classes and headers?

My idea is basically to have something like

@Controller
public class MyController {
@IBOutlet NSButton button;
@IBAction public void action(ID sender);
}

and have the annotation processor create a MyController.h which might
look something like this

@interface MyController {
IBOutlet NSButton* button;
}
- (IBAction) action:(id) sender;
@end

and a MyController.m with the necessary glue code (which is pretty
much changing the Objective-C message to a Java method call - I'm
going to go under the assumption that the generated code will also
create the association between Objective-C and Java objects by, say,
creating the Java object in -init). ID and NSButton in Java would be
interfaces/abstract classes standing in for their Objective-C
counterparts, using something like Rococoa[1].

Clearly, this idea hasn't been fully fleshed out (in particular, I
probably haven't properly dealt with "ID and NSButton in Java" part).
If anyone can pitch in with their input, that would be great.

[1] http://rococoa.dev.java.net