Project Granite aims to provide blueprints for adding animation to SWT applications using the Trident animation engine. Granite is an SWT RIA that connects to Amazon E-commerce backend and shows a list of albums for a specific performer. It is a pure SWT application with three dependencies – Trident, classes generated by the wsimport tool from the Amazon E-commerce WSDL and Eclipse Jobs library for performing networking tasks on background threads.

Over the next few entries i’m going to show code snippets that illustrate how Trident can be used to add simple and complex animations to your SWT applications. The full code is in the SVN repository, and here are two videos that show the different parts of Granite in action.

Asynchronously connecting to Amazon to fetch and display the list of albums, with fading and looping load progress animation, smooth album scrolling, showing bigger album art / track listing in a separate window and switching between different albums:

Looping scrolling of the album track listing, pausing at the end of each cycle to allow easier reading:

Timeline scenarios in the Trident animation library allow combining multiple timeline scenario actors in a parallel, sequential or custom order. Out of the box, Trident supports timelines, extensions of Runnable class and extensions of SwingWorker class, but the applications can easily create a custom implementation of the TimelineScenarioActor interface.

SwingWorker is an indispensable tool in the arsenal of a Swing programmer, and allows separating the long-running tasks that run on background threads from updating the UI components that must happen on the Event Dispatch Thread. While SWT does not have a direct counterpart, Eclipse core libraries have a very similar concept in Eclipse Jobs. And while the full functionality of Eclipse Jobs allows arbitrary dependencies and fine grained scheduling of interrelated jobs, you can wrap an Eclipse Job as a custom Trident timeline scenario actor and use the TimelineScenario APIs to seamlessly integrate an Eclipse Job in your Trident-powered SWT application.

Here is the complete source code to do this:

import org.eclipse.core.runtime.jobs.*;
import org.pushingpixels.trident.TimelineScenario.TimelineScenarioActor;

public abstract class EclipseJobTimelineScenarioActor extends Job implements
      TimelineScenarioActor {
   volatile transient boolean isDone = false;

   public EclipseJobTimelineScenarioActor(String name) {
      super(name);
      this.addJobChangeListener(new JobChangeAdapter() {
         @Override
         public void done(IJobChangeEvent event) {
            isDone = true;
         }
      });
   }

   @Override
   public boolean isDone() {
      return isDone && (this.getState() == Job.NONE);
   }

   @Override
   public void play() {
      this.schedule();
   }

   @Override
   public void resetDoneFlag() {
      throw new UnsupportedOperationException();
   }

   @Override
   public boolean supportsReplay() {
      return false;
   }
}

The play() method calls Job.schedule(), scheduling it for immediate execution. The isDone() method is called internally by the Trident engine on every pulse. The implementation registers a JobChangeListener to track the state of the job, and returns the relevant boolean value. Just as with SwingWorkers, the supportsReplay() returns false, and resetDoneFlag() throws an exception.

The timeline scenario below has the following steps which run in a sequential fashion:

  1. Load an image from the specified URL.
  2. Scale it to fit the specified area
  3. Fade it in on the screen

The first step is done using our EclipseJobTimelineScenarioActor (which would be done with a TimelineSwingWorker in a Swing application):

   private TimelineScenario getLoadImageScenario(final Item albumItem) {
      TimelineScenario loadScenario = new TimelineScenario.Sequence();

      // load the image
      EclipseJobTimelineScenarioActor imageLoadWorker = new EclipseJobTimelineScenarioActor(
            "Load image") {
         @Override
         protected IStatus run(IProgressMonitor monitor) {
            try {
               URL url = new URL(albumItem.getMediumImage().getURL());
               image = new Image(Display.getDefault(), url.openStream());
               return Status.OK_STATUS;
            } catch (Throwable t) {
               t.printStackTrace();
               return Status.CANCEL_STATUS;
            }
         }
      };
      loadScenario.addScenarioActor(imageLoadWorker);

      // scale if necessary
      TimelineRunnable scaler = new TimelineRunnable() {
         @Override
         public void run() {
            if (image != null) {
               float vFactor = (float) OVERVIEW_IMAGE_DIM
                     / (float) image.getImageData().height;
               float hFactor = (float) OVERVIEW_IMAGE_DIM
                     / (float) image.getImageData().width;
               float factor = Math.min(1.0f, Math.min(vFactor, hFactor));
               if (factor < 1.0f) {
                  // scaled to fit available area
                  image = GraniteUtils.getScaledInstance(image,
                        (int) (factor * image.getImageData().width),
                        (int) (factor * image.getImageData().height));
               }

               imageLoadedDone = true;
            }
         }
      };
      loadScenario.addScenarioActor(scaler);

      // and fade it in
      Timeline imageFadeInTimeline = new Timeline(AlbumOverviewComponent.this);
      imageFadeInTimeline.addPropertyToInterpolate("imageAlpha", 0.0f, 1.0f);
      imageFadeInTimeline.addCallback(new SWTRepaintCallback(
            AlbumOverviewComponent.this));
      imageFadeInTimeline.setDuration(500);
      loadScenario.addScenarioActor(imageFadeInTimeline);

      return loadScenario;
   }

You will need the following Eclipse libraries in your classpath:

  • org.eclipse.core.jobs
  • org.eclipse.equinox.common
  • org.eclipse.osgi

As you can see, it is quite easy to extend the existing functionality of Trident scenarios by wrapping external modules as custom timeline scenario actors.

Trident animation library allows adding a short fade-out sequence to a Swing / SWT window that is being closed. This can provide an unobtrusive visual feedback to the user, confirming his action and smoothly guiding his eye to the new application state.

Here is a utility method to add a fade-out sequence to disposing a Swing window – this code requires the latest builds of JDK7 that added the Window.setAlpha(float) method:

public static void fadeOutAndDispose(final Window window,
      int fadeOutDuration) {
   Timeline dispose = new Timeline(window);
   dispose.addPropertyToInterpolate("opacity", 1.0f, 0.0f);
   dispose.addCallback(new UIThreadTimelineCallbackAdapter() {
      @Override
      public void onTimelineStateChanged(TimelineState oldState,
            TimelineState newState, float durationFraction,
            float timelinePosition) {
         if (newState == TimelineState.DONE) {
            window.dispose();
         }
      }
   });
   dispose.setDuration(fadeOutDuration);
   dispose.play();
}

and the matching method for disposing an SWT shell with a fade-out sequence, which requires SWT 3.4 to run:

public static void fadeOutAndDispose(final Shell shell, int fadeOutDuration) {
   Timeline dispose = new Timeline(shell);
   dispose.addPropertyToInterpolate("alpha", 255, 0);
   dispose.addCallback(new UIThreadTimelineCallbackAdapter() {
      @Override
      public void onTimelineStateChanged(TimelineState oldState,
            TimelineState newState, float durationFraction,
            float timelinePosition) {
         if (newState == TimelineState.DONE) {
            shell.dispose();
         }
      }
   });
   dispose.setDuration(fadeOutDuration);
   dispose.play();
}

Instead of calling Shell.dispose() or Window.dispose(), call the fadeOutAndDispose() method, passing the duration of the fade-out sequence in milliseconds. A previous entry has discussed another option – overriding the Window.dispose() method in your custom Swing class. While this works in Swing, SWT does not allow extending the Shell class outside the org.eclipse.swt.widgets package.

I am thrilled today to announce the availability of the final release for version 1.0 of Trident animation library for Java applications (code-named Acumen).  Trident aims to simplify the development of rich animation effects in Java based UI applications, addressing both simple and complex scenarios – and you can read the available documentation in the project Wiki.

The current published API set follows the “simplicity before generality” approach. Trident is a continuation of the internal animation engine that has been part of the Substance look-and-feel for the last two years. Extracting it to a standalone library was accompanied by a significant overhaul of the API facets to:

  • Provide a shallow learning curve
  • Address real world use cases

It is very easy to start with Trident. To add animations to your application, simply create a timeline, configure it to change a value of some property and play it. From here, you can go progressively deeper towards the more powerful – and the more complex – Trident APIs:

At each level you get more control over the animations – as you get more comfortable with what Trident can do to address the animation requirements of your application.

During the development of this version i have created a number of simple and more advanced examples using Trident. These examples have driven the current shape of Trident APIs. The simple examples include animating the foreground color of a button, showing an indeterminate progress indication, emulating fireworks and Matrix rain. In addition, Amber and Onyx are more complicated applications that integrate animation scenarios into UIs that fetch and display information from the web-based backend services – such as Digg, Twitter and Amazon. These examples strive to be the blueprints for using Trident in Java applications.

If i had to choose three features that bring the most functionality to interested applications, those would be:

  • Timeline scenarios that allow creating progressively complex dependency graphs of timelines, runnables, swing workers and custom application actors
  • Support for threading rules of UI toolkits that frees the application code from creating convoluted nested inner classes and prevents it from deadlocking and freezing the UI
  • The extensibility layer that allows application to extend the existing core functionality to additional property classes and UI toolkits

Going forward, i intend to evolve Trident, and i already have a couple of post-1.0 features in the pipeline. The next major release of Substance will be rewritten to use Trident – further testing the published APIs for usage in real-world scenarios. In addition, the next major release of Flamingo ribbon will add Trident-based animations – where applicable.

Finally, no project is complete without the users trying the different features, pushing the existing APIs, reporting bugs and asking to support additional requirements. Subscribe to the mailing lists and let me know what is missing, and how the existing APIs can be improved. If you find a bug, report it in the issue tracker. If you want to take a look at the code, check out the SVN repository and subscribe to the “commits” mailing list.