Share

Building Native MacOS Apps with Java

Some Time ago, Java and MacOS were friends. You could just open XCode choose “Java Application” and start coding your app. But since the last version of Xcode 3 and finally with the release of Xcode 4 all the nice Cocoa/Java Bindings were gone. The normal way of Apple to cleanup their System and make space for the support of new Features.

But sometimes you have this great Java Library. Or you just want to create a nice UI for your CLI Java App, and the common SWING UI won’t work and other UI Libraries like macwidgets just lack support for a decent UI Designer and will just add some more graphics to your plain Java UI.

There is a solution for that kind of Problem. It is called rococoa and offers Java a native Binding to your Cocoa Libs. There is also one famous Application that uses this Library and doing very well: Cyberduck.
This App also managed to get into the _AppStore_ by Bundling its own JDK to the App Bundle. You can see the source of Cyberduck here.

So What is an App Bundle?

An App Bundle is basically just a folder with an .app in its nahe. It contains some common Folders:

– a Content Folder with
-> a plist File
-> a Resources Folder

App Bundle Structure

 

 

 

 

 

 

 

There is an old Project called JarBundler to create MacOS App Bundles from your Java Project.
But for this example we are using the maven plugin “osxappbundle-maven-plugin”, for creating the App Bundle and a DMG File for Installation. We also adding the necessary Files for ROCOCOA.

The first Step is to create the necessary NIB File for our Application. In Xcode 3 you could just create a basic NIB with Interface Builder and then add the Outlets and Actions to the NSObject Class (that is the default First Responder). In Xcode 4+ you need to create a dummy controller Class first. Then you can add your Outlets to this class and the the first Responder to this Class.

XCode 4+ NIB and Dummy Class

 

 

 

 

 

 

 

 

You can now create your ViewController Class in Java:

  
// we re-using some of the work done by the cyberduck developer.
import ch.cyberduck.ui.cocoa.application.NSTextField;
import ch.cyberduck.ui.cocoa.application.NSWindow;
import ch.cyberduck.ui.cocoa.foundation.NSBundle;
import ch.cyberduck.ui.cocoa.foundation.NSObject;

import org.rococoa.ID;
import org.rococoa.Rococoa;

public class WindowController {

    public WindowController() {
        String bundleName = "HelloWorld";
        // Load the NIB file and pass it our Rococoa proxy as the file owner.
        if (!NSBundle.loadNibNamed(bundleName, this.id())) {
            System.err.println("Couldn't load " + bundleName + ".nib");
            return;
        }
    }
    // Injected outlet from NIB
    private NSWindow mainWindow;

    private NSTextField textField;

    // Called when loading NIB using NSBundle. NIB has a mainWindow outlet defined.
    public void setMainWindow(NSWindow mainWindow) {
        System.out.println("Outlet set to: " + mainWindow.title());
    }

    // bind the Outlet to the Class Attribute.
    public void setTextField(NSTextField textField){
        this.textField = textField;
    }

    // NSButton in NIB has an action to the file owner named buttonClicked:
    public void buttonClicked(ID sender) {
        textField.setStringValue("Hello World from: " + sender);
    }

    /**
     * You need to keep a reference to the returned value for as long as it is
     * active. When it is GCd, it will release the Objective-C proxy.
     */
    private NSObject proxy;
    private ID id;

    public NSObject proxy() {
        return this.proxy(NSObject.class);
    }

    public NSObject proxy(Class type) {
        if (null == proxy) {
            proxy = Rococoa.proxy(this, type);
        }
        return proxy;
    }

    // Getter for ID for Rococoa Binding
    public org.rococoa.ID id() {
        return this.id(NSObject.class);
    }

    // Setter for ID for Rococoa Binding
    public org.rococoa.ID id(Class type) {
        if (null == id) {
            id = this.proxy(type).id();
        }
        return id;
    }
}

Your main methode is very simple. It just calls the ViewController and creates the AutoreleasePool for your App:

import ch.cyberduck.ui.cocoa.application.NSApplication;
import ch.cyberduck.ui.cocoa.foundation.NSAutoreleasePool;

/**
 * Hello world!
 *
 */
public class App {
    public static void main(String[] args) {
        final NSAutoreleasePool pool = NSAutoreleasePool.push();
        try {
            // This method also makes a connection to the window server and completes other initialization.
            // Your program should invoke this method as one of the first statements in main();
            // The NSApplication class sets up autorelease pools (instances of the NSAutoreleasePool class)
            // during initialization and inside the event loop—specifically, within its initialization
            // (or sharedApplication) and run methods.
            final NSApplication app = NSApplication.sharedApplication();
            WindowController w = new WindowController();
            // Starts the main event loop. The loop continues until a stop: or terminate: message is
            // received. Upon each iteration through the loop, the next available event
            // from the window server is stored and then dispatched by sending it to NSApp using sendEvent:.
            // The global application object uses autorelease pools in its run method.
            app.run();
        } finally {
            pool.drain();
        }
    }
}

I am using an updated version of this example from the rococoa Project Page.

Finally you have to put all the things together; Compiling your Java Files, adding your native Libs, Creating your App-Bundle and your DMG.
I updated the Plugin to be able to add non Java Dependencies to Your App Bundle (like dylibs and NIB Files). You can find the updated version here. I am currently working on creating patch files for upstreaming my changes to the codehaus project.

The important Call of the Maven-Plugins reads like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>de.javastream.rococoa</groupId>
    <artifactId>helloworld</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>Hello World</name>
    <url>https://github.com/phaus/rococoa-tests/helloworld</url>
    <build>
        <plugins>
...
 <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>osxappbundle-maven-plugin</artifactId>
                <version>1.0-SNAPSHOT</version>
                <configuration>
                    <!-- PLIST Settings -->
                    <workingDirectory>$APP_PACKAGE/Contents/Resources/Java</workingDirectory>
                    <vmOptions>-Xmx512m -Djava.library.path=$APP_PACKAGE/Contents/Resources/Java/lib -Djna.boot.library.path=$APP_PACKAGE/Contents/Resources/Java/lib -Djna.library.path=$APP_PACKAGE/Contents/Resources/Java/lib -Djna.nounpack=true -Djava.awt.headless=true -Dsun.jnu.encoding=utf-8 -Dfile.encoding=utf-8 -XX:-UsePerfData -XX:+ReduceSignalUsage -Xincgc -XX:-UseLoopPredicate -XX:-OptimizeStringConcat</vmOptions>
                    <mainClass>de.javastream.rococoa.apptest.App</mainClass>
                    <dictionaryFile>${basedir}/src/main/resources/Info.plist</dictionaryFile>
                    <iconFile>${basedir}/src/main/resources/helloworld.icns</iconFile>
                    <!-- adding additional files to the DMG -->
                    <additionalArchiveFiles>
                        <fileSet>
                            <directory>${basedir}/src/main/doc</directory>
                            <includes>
                                <include>COPYING</include>
                                <include>COPYING.LESSER</include>
                                <include>release-notes.txt</include>
                            </includes>
                        </fileSet>
                    </additionalArchiveFiles>
                    <!-- Adding additional Resources (like NIBs) -->
                    <additionalResources>
                        <fileSet>
                            <directory>${basedir}/xcode</directory>
                            <includes>
                                <include>*.lproj/**</include>
                            </includes>
                        </fileSet>
                    </additionalResources>
                    <!-- Adding Native Java Libs -->
                    <additionalBundledClasspathResources>
                        <fileSet>
                            <directory>${basedir}/src/main/lib</directory>
                            <includes>
                                <include>libjnidispatch.dylib</include>
                            </includes>
                        </fileSet>
                        <fileSet>
                            <directory>${basedir}/target</directory>
                            <includes>
                                <include>librococoa.dylib</include>
                            </includes>
                        </fileSet>
                    </additionalBundledClasspathResources>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>bundle</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            
            ...
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.rococoa</groupId>
            <artifactId>rococoa-core</artifactId>
            <version>0.5</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.4</version>
        </dependency>
        <dependency>
            <groupId>net.java.dev.jna</groupId>
            <artifactId>jna</artifactId>
            <version>3.3.0</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2.2</version>
        </dependency>
    </dependencies>
    
    ...
   <repositories>
        <repository>
            <id>maven.javastream.de</id>
            <name>javastream Repository</name>
            <url>http://maven.javastream.de</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>maven.javastream.de</id>
            <url>http://maven.javastream.de</url>
        </pluginRepository>
    </pluginRepositories>
    
...
</project>

 

You can find the whole project on Github. It is a very simple Hello World Programm. As soon as you click the Button the Labels text changes to “Hello World from: #CALLER-ID”.

App Window

 

 

 

 

 

 

 

 

The next step is to do further updates to the Plugin, for Bundling a JDK to your App Bundle for creating a real Standalone Application.

You may also like...

Leave a Reply