Wednesday, September 09, 2009

Griffon Tip: Mac Look and Feel on Snow Leopard

If you upgraded your Mac to Snow Leopard recently, you may have noticed that your Griffon apps no longer look the same as they used to on Leopard.  Aside from a few color differences, the biggest giveaway will be that your app no longer uses the standard top menubar.  Fortunately there is a simple fix if you want to use the more native look and feel.  Change your griffon-app/lifecycle/Initialize.groovy file to include the 'mac' look and feel first:
import groovy.swing.SwingBuilder
import griffon.util.GriffonPlatformHelper

GriffonPlatformHelper.tweakForNativePlatform(app)
SwingBuilder.lookAndFeel('mac', 'nimbus', 'gtk', ['metal', [boldFonts: false]])

The crux of the problem is SwingBuilder tries various L&Fs in the order you specify them and stops when it finds one that works.  Nimbus is the L&F for Java 6 but previous versions of Mac OS X shipped with Java 5.  So SwingBuilder would try Nimbus and it would fail then it would try the Mac look and feel which would work.  Snow Leopard ships with Java 6 so when SwingBuilder tried Nimbus, it worked and it never tried to set the Mac L&F.

EDIT: This will be the default behavior in the upcoming Griffon 0.2 release.  So you will only need this fix if you have Griffon apps from pre-0.2 days.

Tuesday, September 01, 2009

Griffon Tip: Intercepting Window Closing Events

When building an editor of sorts, it is often useful to intercept the window closing event so that you can prompt the user to save if the editor has unsaved changes.  To do this in Griffon, we first need to change the defaultCloseOperation and define a windowClosing event handler on our application node in the view:

application(title:'Editor', size:[800,600], locationByPlatform: true,
    defaultCloseOperation: WindowConstants.DO_NOTHING_ON_CLOSE, 
    windowClosing: { evt -> 
        // check if the editor needs saving
    }) {
// the rest of your view code here
}

If we run our application now, we should notice that...the windowClosing event handler never runs.  Turns out that there's one more step--we need to tell Griffon that we want to explicitly handle shutting down the application.  We do this by setting autoShutdown=false in griffon-app/conf/Application.groovy Once this is set, we should notice that our windowClosing event handler runs.  Since Griffon is no longer responsible for automatically shutting down our application, we must make sure to call app.shutdown() somewhere in our closing logic or the user won't be able to exit the app.

Wednesday, August 19, 2009

Building your Griffon app with Gradle

In this post, I'm going to show how to build your Griffon apps with Gradle. Griffon already comes with a command line tool to build and interact with your app, so why would you want to do this? I can think of a few reasons:
  • you have an existing Gradle build you want to integrate with
  • you have a complex build or packaging scenario
  • you want to take advantage of Gradle's dependency management for your app
Prerequisites
  1. Griffon
  2. Gradle
The build.gradle file
Below is a generic Gradle build file for Griffon applications. Either copy and paste the code below or download it and place it in a build.gradle in your Griffon application folder.
// standard configuration
project.captureStandardOutput(LogLevel.INFO)
configurations { compile }

// add additional repositories here if you need them
repositories {
//mavenRepo(urls:'http://download.java.net/maven/2/')
mavenCentral()
}

// add any dependencies you want downloaded as part of the bootstrap process
dependencies {
//compile 'com.google.collections:google-collections:1.0-rc2'
}

// this should be run once for the project
createTask('bootstrap') << {
// download any dependencies and put them in lib/
configurations['compile']?.files?.findAll { it.absolutePath.indexOf('unspecified') < 0 }.each { dep ->
ant.copy(toDir: new File('lib'), file: dep)
}

// try to install any plugins
new File('application.properties').eachLine { line ->
if (line.startsWith("plugins")) {
def plugin = line[8..-1].split('=')
griffon "install-plugin ${plugin[0]} ${plugin[1]}"
}
}
}

// mimic the tasks provided by the Java plugin
createTask('clean') << { griffon 'clean' }
createTask('compile') << { griffon 'compile' }
createTask('libs') << { griffon 'package' }
createTask('test') << { griffon 'test-app' }
createTask('dists') << { griffon 'prod package' }

// additional run-related tasks
createTask('run-app') << { griffon 'run-app' }
createTask('debug-app') << { griffon 'run-app -debug' }
createTask('run-webstart') << { griffon 'run-webstart' }
createTask('run-applet') << { griffon 'run-applet' }

// call out to the griffon command
def griffon(target) {
if (System.getProperty("os.name").toLowerCase().startsWith("win")) {
ant.exec(executable: 'griffon.bat', dir: projectDir, failonerror: true) {
arg(value: target)
}
} else {
ant.exec(executable: 'griffon', dir: projectDir, failonerror: true) {
arg(value: target)
}
}
}

// if you want to use the gradle wrapper
createTask('wrapper', type: Wrapper).configure {
gradleVersion = '0.7'
}
To verify that everything is working, let's try running our app from Gradle (substitute gradle.bat if you are on Windows):
gradle run-app

Your Griffon app should run. If it doesn't, try invoking the Gradle command with the '-i' flag:
gradle -i run-app
to see what the problem is.

Multi-project Builds
So far it may seem like "What's the point?" We could already run our Griffon app with the griffon command. Where Gradle really starts to shine is when you start wanting to perform complex builds, such as building multiple Griffon apps at once or integrating with an existing build.

Gradle has good support for multi-project builds. Assuming you are using a directory layout like this:
settings.gradle
griffonapp1/
build.gradle
...
griffonapp2/
build.gradle
...
Building these multiple Griffon apps is as simple as listing them in the settings.gradle file:
include 'griffonapp1', 'griffonapp2'
Similarly, integrating with an existing build should be as simple as adding the name of your Griffon app to your existing settings.gradle file.

Complex Build/Packaging Scenarios
Griffon offers several packaging options with the Installer plugin. Sometimes you need more flexibility. For my PSICAT build, I wanted to package two Griffon apps together in a specific directory structure. The nice thing about Gradle build files is that they are just Groovy code and offer great integration with Ant. Below is a snippet from the PSICAT build that illustrates using Ant within Gradle:
// griffon create-all-launchers for PSICAT and SchemeEditor
griffon(psicat, 'create-all-launchers')
griffon(schemeEditor, 'create-all-launchers')

// build linux package
ant.copy(toDir: new File(linux, 'PSICAT')) {
fileset(dir: new File(psicat, 'installer/linux/dist')) {
include(name: 'bin/**')
include(name: 'lib/**')
}
}
ant.copy(toDir: new File(linux, 'PSICAT/tools/SchemeEditor')) {
fileset(dir: new File(schemeEditor, 'installer/linux/dist')) {
include(name: 'bin/**')
include(name: 'lib/**')
}
}
ant.chmod(perm: "+x", dir: new File(linux, 'PSICAT/bin'), includes: '*')
ant.chmod(perm: "+x", dir: new File(linux, 'PSICAT/tools/SchemeEditor/bin'), includes: '*')
ant.tar(destFile: new File(linux, "PSICAT-linux-${version}.tar.gz"), compression: 'gzip', basedir: linux, includes: 'PSICAT/**')
...
(if you're curious, the whole build.gradle file is here)

Cool Gradle Tricks
One cool feature of Gradle is that you can generate a 'wrapper' script that will download and bootstrap Gradle itself so that developers who download your source don't have to have Gradle installed to build your project.
The build.gradle file above is already setup to create this wrapper. You simply have to run the command:
gradle wrapper
and it will create four files in your project:
gradle-wrapper.jar
gradle-wrapper.properties
gradlew
gradlew.bat
If you include these files when you send someone your project, they can use the gradlew or gradlew.bat scripts as if they had Gradle installed:
./gradlew run-app

The other neat trick with Gradle is you can use its ability to pull from Maven repositories to bootstrap the dependencies of your Griffon app. This means you don't need to send someone your Griffon app with a bunch of JARs in the lib directory. Instead you can send them a Gradle-ized version of your app and tell them to run the command:
./gradlew bootstrap

This will download all of the dependencies you've listed in the build.gradle file and put them in the lib directory of your Griffon app. Specifying dependencies is as simple as adding a few lines to the dependencies section of the build file:
dependencies {
compile 'com.google.collections:google-collections:1.0-rc2'
compile 'org.slf4j:slf4j-api:1.5.8'
}
Conclusion
Hopefully this has given you a taste of using Gradle with Griffon. Both are awesome tools that really show off the power of the Groovy language. If there's enough interest in using Gradle with Griffon, we can make build.gradle a standard artifact created by the griffon create-app task.

Saturday, August 15, 2009

Are Groovy Stacktraces a Showstopper?

I've been part of an interesting debate on the merits of Groovy via Twitter this week. I'm reproducing it here because I think it's an interesting take on what potential users feel are make or break issues for a language, and to give others who may not have seen it the chance to weigh in without the 140 character limit. :)

(Sorry in advance. Reproducing a Twitter convo in a blog is kind of hideous)

[@philswenson] if you want to know why groovy sucks, click here: http://pastie.org/583115
[@joshareed] @philswenson It took me a second to diagnose your problem. Did you want Groovy to say: "Hey joker, actually import the classes you're using"
[@joshareed] @philswenson Apparently Ruby has some magical mind-reading interpreter/compiler that saves you from yourself?

[@philswenson] @joshareed why the extra 500 lines of crap? in java or jruby that stacktrace would have been 1/50 the size. that's my point
[@joshareed] @philswenson re: Java guess that's the trade off for Groovy dynamics. Ruby's (http://bit.ly/IagLJ) is not any better [Note: Nambu mangled the original link]

[@philswenson] @joshareed Ruby's stack dump = 67 lines. Groovy's = 222 lines. Not as different as I said, but still...
[@joshareed] @philswenson # of lines doesn't matter when you see the cause of the prob in the first 10 lines, does it? You don't have to keep reading...
[@joshareed] @philswenson and was the 67 vs 222 equivalent programs in each? I'd be interested in comparing the source of each

[@philswenson] @joshareed this was a case where the cause was obvious (it usually isn't). isn't groovy in large part about succinctness over java?
[@joshareed] @philswenson how much time do you spend looking at stacktraces that this is hang up for you? Write a 3 line .findAll{} to filter traces
[@joshareed] @philswenson and if you want to stick with stacktrace length as your argument then you won't be plain old Java traces with JRuby

From my perspective, this isn't a JRuby vs Groovy debate even though both languages were brought up in the conversation. Both are two different ways to skin a cat but they ultimately get you to the same place. Which you choose to use is more a matter of personal preference than the actual merits of the language.

What I'm more interested in is how important/serious is the stacktrace issue that Phil Swenson argues? I've been writing Groovy for a couple years now and can't remember (off the top of my head) a stacktrace from Groovy that was so confusing I couldn't figure out the problem. I'm sure there are some, especially when you start getting deep into the Groovy innards, but I'm guessing that's also the case with other languages on the JVM, like JRuby.

All dynamic languages built on the JVM introduce a certain level of indirection (by necessity), so are Groovy's stacktraces that much more hideous than JRuby's? What qualifies as hideous? I think length is a naive measure because the cause of the problem is likely to show up in the first dozen lines. Who cares if it goes on for another 200 lines? Length is also easily manipulated. You could write a simple findAll closure that sanitizes the stacktrace by removing all the lines that start with 'sun.reflect' or 'org.codehaus.groovy.runtime'. I have never once run into a problem that could be tracked to one of those lines in the stacktrace. So now does that make Groovy better than JRuby because the stacktrace is shorter?

I'm sure this is just a case of me being used to seeing Groovy stacktraces, so I'm used to feel of them and can quickly hone in on the cause of the problem. Likewise I'm sure Phil is used to [J]Ruby errors which probably look much different than Groovy's. I say probably because the two example put forth didn't look all that dissimilar IMO but were not from the same problem so it was an apples to oranges comparison.

Anyways, how important are stacktraces when making the decision to use a particular language? Are they important enough to declare one language's superiority over another? Are they worth focusing on to improve Groovy's ease-of-use?

Wednesday, August 12, 2009

Griffon Installer Plugin

Last week Andres Almiray and I released a new version of the Griffon Installer plugin. This version adds support for creating native Mac app bundles for your Griffon application, as well a few refactorings to make the generated artifacts more consistent. In this post, I'm going to walk you through the process of creating a set of native launchers for your application. A future post will explain the process of creating installers.

Getting started using the installer plugin is simple:
griffon install-plugin installer

This will fetch the plugin and install it into your Griffon app. The plugin adds several new targets. All of the launcher-related targets are broken into two steps: a prepare step that copies all of the configuration files for that particular launcher into your application, and a create step that actually generates the native launcher. The prepare targets only need to be run once for your project. They give you a chance to tweak the launcher configuration files. The create targets are run every time you want to make a release.

The plugin provides launchers for the following platforms:
  • Linux
  • Mac
  • Windows
  • Executable Jar
The plugin also provides two other convenient targets, prepare-all-launchers and create-all-launchers which invoke the prepare- and create- targets for the four platforms above.

We'll use these convenience targets to create launchers for all platforms:
griffon prepare-all-launchers

This will create several new files for you:
  • installer/jar - the executable JAR launcher directory
  • installer/jsmooth - the Windows launcher directory
  • installer/linux - the Linux launcher directory
  • installer/mac - the Mac launcher directory
  • installer/jar/MANIFEST.MF - customize the manifest of the executable JAR
  • installer/jsmooth/$appName-icon.png - customize the .exe icon
  • installer/jsmooth/$appName.jsmooth - customize the .exe options
  • installer/mac/$appName.icns - customize the Mac icon
Once you are done customizing the configuration files, invoke the
griffon create-all-launchers target to actually create the launchers. This will create all of the launchers in the installer/$platform/dist directories and create archives of the launchers:
  • installer/jar/dist/$appName-$version.jar - the executable jar
  • installer/linux/dist/bin/$appName - the Linux launcher shell script
  • installer/linux/dist/$appName-linux-$version.zip - a zip of the Linux launcher
  • installer/mac/dist/$appName-$version.dmg - a disk image of the Mac launcher [only created if on a Mac]
  • installer/mac/dist/$appName.app - the Mac application bundle
  • installer/jsmooth/dist/$appName-windows-$version.zip - a zip of the Windows launcher
  • installer/jsmooth/dist/$appName.exe - the Windows launcher
  • installer/windows/dist/$appName-windows-$version.zip - copied from the JSmooth directory
  • installer/windows/dist/$appName.exe - copied from the JSmooth directory
As you make changes to your code, simply invoke griffon create-all-launchers and your latest changes will be packaged up. If you increment the version number of your app, the created artifacts will be updated to match.

Hopefully the Installer plugin makes it easy to distribute your Griffon applications to users on various platforms. In a future blog post, I'll cover creating installers for when a simple zip file is not enough.

Tuesday, July 14, 2009

Griffon Plugin Development

I finally got to the point in my Griffon application development that I was ready to release my app. Griffon has a plugin for creating installers and platform-specific launchers, but it didn't generate a proper Mac .app bundle. Being a Mac user myself, I really wanted to be able to deploy my app natively on Macs, so I decided to scratch my itch and add support to the plugin. I learned a fair bit about Griffon plugin development, so keep reading if you're interested in tweaking existing plugins or creating new plugins.

First off, Griffon plugins are simply Griffon applications with a few extra bits not normally used in a standard application—scripts for providing command line targets e.g., griffon create-mac-launcher, and interception of Griffon events like eventCleanEnd. To get started with plugin development, you'll want to decide whether you want to create a new plugin or edit an existing one.

Setting up your Griffon plugin development environment is fairly straightforward. If you want to edit an existing plugin:

cd MyExistingApplication
griffon install-plugin installer


If you want to create a new plugin and install it in an existing application:

griffon create-plugin MyNewPlugin
cd MyExistingApplication
{edit application.properties to include a line 'plugin.my-new-plugin=0.1'}



The real trick for both of these scenarios is to link the plugin source to somewhere where you can edit it live. This makes testing a whole lot easier. I had to pull a few strings to get this tip, but I'm going to share it with you for free:
Go into your ~/.griffon/{griffon version}/projects/MyExistingApplication/plugins/ and either edit the plugin directly or symlink it to something more convenient:

cd ~/.griffon/{griffon version}/projects/MyExistingApplication/plugins/
rm -rf installer-0.3
ln -s ~/Workspace/griffon/griffon-installer installer-0.3

You just have to make sure the name and the version match what is in your MyExistingApplication/application.properties file. If you installed an existing plugin, you should be good to go. If you're creating a new plugin, it defaults to 0.1.

Once you have your plugin development environment setup, you're ready to go to town. Below are a few things I learned along the way. Most have to do with Gant scripting, which I wasn't very familiar with before this but is easy to pick up.

If you want to create a new command line option, e.g. griffon say-hello-world you need to create a new script in your plugin. You can do this by creating a SayHelloWorld.groovy file in the $plugin/scripts. Or as Andres points out in the comments a simple griffon create-script SayHelloWorld works as well. Even better! You also have to define a sayHelloWorld target in your script and make it the default target:

target(sayHelloWorld:"Says 'Hello World'") {
// any Groovy is valid here
println "Hello World!"
}
setDefaultTarget(sayHelloWorld)


Another useful feature is the ability to invoke targets in other strips, such as if you wanted to make sure the Griffon app was built before your task was executed. You can accomplish this by including the targets of other scripts in your script:

includeTargets << griffonScript("_GriffonPackage") // script name minus the .groovy

target(doAfterBuild: "Build and then run me") {
depends(checkVersion, packageApp, classpath) // defined by _GriffonPackage.groovy
packageApp() // calls the packageApp target in _GriffonPackage.groovy
println "The JARs in $basedir/staging should be fresh!"
}

setDefaultTarget(doAfterBuild)


Finally, before this post gets too long-winded, I'll cover the topic of events. Events are fired by the Griffon core runtime and by plugins in response to actions in the workflow. They provide an extension mechanism for plugins who wish to respond to various actions. Your plugin can intercept events by providing a $plugin/scripts/_Events.groovy file which declares interest in specific events:

eventCleanEnd = {
// jar
ant.delete(dir:"${basedir}/installer/jar/dist", failonerror:false)
ant.delete(dir:"${basedir}/installer/jar/classes", failonerror:false)

// jsmooth
ant.delete(dir:"${basedir}/installer/jsmooth/dist", failonerror:false)

// linux
ant.delete(dir:"${basedir}/installer/linux/dist", failonerror:false)

// mac
ant.delete(dir:"${basedir}/installer/mac/dist", failonerror:false)

// windows
ant.delete(dir:"${basedir}/installer/windows/dist", failonerror:false)
}


If you are developing your own plugin, you should consider publishing events so that other plugins can hook into your workflow. You can do this by including the _GriffonEvents targets in your script, or by including any script that itself includes _GriffonEvents:

includeTargets << griffonScript("_GriffonEvents")

target(myPluginTask: "") {
event("MyPluginTaskStart", [])
println "My Plugin Task!"
event("MyPluginTaskEnd", [])
}

setDefaultTarget(myPluginTask)


Thanks for following along. Any suggestions or questions are greatly appreciated!

Oh and if you're interested in the installer plugin stuff, check out: http://dev.psicat.org/ for some example outputs. These are not the exact outputs as I am bundling two Griffon apps--the main PSICAT one and a second one in tools/--but you get the idea.

Thursday, July 02, 2009

Griffon Action Patterns

I've been working on a decent-sized Griffon app recently and hit upon a pattern for managing actions that I thought might be useful to others. I began by following SwingPad's lead and declaring my actions separate (PSICATActions.groovy) from my view (PSICATView.groovy):

actions {
action(id: 'exitAction', name: 'Exit', closure: controller.exit)
action(id: 'openAction', name: 'Open', closure: controller.open)
...
}


which I import into my view:

// build actions
build(PSICATActions)

application(title:'PSICAT', size:[800,600], locationByPlatform: true, layout: new MigLayout('fill')) {
...
}


This is nice because it keeps all of your action definitions in one place and doesn't clutter your view code with them. When implementing the actions, the common pattern seems to define closures on your controller:

class PSICATController {
def model
def view

void mvcGroupInit(Map args) {
...
}

def exit = { evt = null ->
...
}

def open = { evt = null ->
...
}
}


This is fine but when you start getting many actions your controller becomes cluttered and it is difficult to tell what is an action implementation and what is regular controller logic. You also have to be careful with naming:

actions {
action(id: 'exitAction', name: 'Exit', closure: controller.exit)
action(id: 'openAction', name: 'Open', closure: controller.open)
action(id: 'newAction', name: 'New', closure: controller.new) // ERROR
}


We are forced to break with our naming convention because 'new' is a reserved keyword. To combat the clutter and avoid naming issues, I've taken to declaring my action implementations in a map on the controller:

class PSICATController {
def model
def view

void mvcGroupInit(Map args) {
...
}

def actions = [
'exit': { evt = null -> ... },
'open': { evt = null -> ... },
'new': { evt = null -> ... } // no issues here
]
}


Using the map makes it easy to tell what is an action and what is not, and linking the action definitions to the implementations becomes elegant and intuitive:

actions {
action(id: 'exitAction', name: 'Exit', closure: controller.actions['exit'])
action(id: 'openAction', name: 'Open', closure: controller.actions['open'])
action(id: 'newAction', name: 'New', closure: controller.actions['new'])
}


So far I have been pretty happy with this approach. What do other Griffon developers out there think?