Friday, November 1, 2013

Where no diagram editor has ever gone before...

I should have been more suspicious about the Ferengi salesman I bought my LCARS system from. Ferengi have always been skeptical towards JavaFX. I should have known that this device had been tampered with in order to bring my system down in the middle of my demo at EclipseCon Europe. Ferengi petaq!

Nevertheless, I could organize a new working LCARS terminal now and here is my demo. It demonstrates JavaFX's flexibility to create a diagram editor that does neither look like nor behave like a dull lines and boxes editor.

I extracted the data from the StarTrek fansite Memory Alpha and stored it in a local mongoDB. The font is from GTJLCARS. SVG export extends some code from the JFXtras project initially written by Gerrit Grunwald. Thanks to all of you, guys.

EclipseCon Europe was once again big fun: I attended a number of cool presentations, met a lot of old friends and got acquainted with a bunch of new people. Thanks for the organizers to provide such a fine event. But without any further delay, here's the demo:

Tuesday, October 22, 2013

Eclipse Diagram Editors From A User's Perspective

I believe that the Eclipse's diagram editing frameworks have a lot to catch up when it comes to usability. For illustration I've created a screencast on how a typical Eclipse graphical editor appears to a user. I have used the Ecore Tools editor as an example, but most issues presented are caused by defaults of GMF or GEF which are pretty hard to change. So don't be surprised if you re-encounter these or similar issues in Graphiti, Sirius etc. The screencast doesn't even cover the rendering errors described in my previous blog post.

So what has gone wrong?

In my opinion, diagram editor behavior and editing metaphors haven't really changed since the first commits on the GEF project in 2002. Advances in UI design and usability have had almost no priority on Eclipse's graphical frameworks since then. They were built from a pure developer's perspective. So a lot of effort has been spent on:
  • Facilitating the development of new editors. This usually causes a restriction to very specific use cases. 
  • Establishing weird processes to implement new diagram editors. 
  • Repeatedly putting new abstraction layers on top of the existing ones. Hide the seemingly ugly or incomprehensible concepts of a base framework. The problem is to find better abstractions that don't leak. In the end you often have to learn both (or more) frameworks in order to use them. 
  • Building on top of existing frameworks with serious limitations, like integer coordinates, missing alpha channel, no hardware acceleration etc. 
  • Supporting very large diagrams. Yes, there are very big models. But diagrams with hundreds of nodes and connections only make good wallpapers.
  • Creating new compatibility APIs, e.g. to replace the rendering engine. These will limit the available functionality to the common minimum set of features of all backends. 
  • Changing a model graphically. Note the difference between editing a diagram – e.g. to make it look nicer – and changing the underlying model. Did you ever wonder why GEF Zest is the only Eclipse diagram framework with its own diagram layout algorithms and basic support for multi-touch gestures? 
Computers don't need diagrams. Diagrams are for humans. Their strength is to explain a part of a model in a very suggestive way. Taking the human user into focus changes the requirements for a graphical framework drastically. Issues like the following must have top priority:
  • Appealing visual design, 
  • Intuitive editing metaphors, 
  • Snappy behavior, 
  • Support for modern input devices, and 
  • The possibility for individual customization. 
How do we get there? Attend my talk Eclipse Diagram Editors - An Endangered Species at EclipseCon Europe for some propositions and an extensive demo.

EclipseCon Europe 2013

Friday, October 11, 2013

Multi-touch Gestures For JavaFX Apps Running in SWT

EclipseCon Europe 2013 I am currently preparing a demo for my talk at EclipseCon Europe 2013. Embedding my JavaFX based graphical editor into Eclipse went smoothly thanks to the FXCanvas that bridges SWT and JavaFX. But I realized that multi-touch gestures did no longer work.

I filed a bug for that, but I could not resist trying to find out what's wrong myself. You may not know that the sources of JavaFX are open now. So after cloning their mercurial repo and browsing a couple of classes I found out that SWT's GestureEvents are neither converted to JavaFX GestureEvents nor transferred to an embedded JavaFX canvas. The implementation was simply missing.

So with some help by Tom Schindl and Steve Northover (thanks a lot, guys!) I hacked a solution that works fine for me, as you can see in the screencast below. If you're interested you can download my the code from github.

Saturday, September 7, 2013

Obi-Wan at the Edge

There are two hard problems in computer science: cache validation, variable substitution, and off-by-one errors.      (unknown source)
The uncounted latter is often referred to as OBOE or, with a geek sense of humor, "Obi-Wan error".

Obi-Wan In Eclipse Diagram Editors

In an older post, I already mentioned one major weakness of GEF (3.x): All coordinates are integers. One problem with that is that it can easily result in off-by-one rendering bugs. That unfortunately holds for many frameworks built on top of GEF. Have a close look at the gradient fill, anchor points (where connections are touching the nodes), clipping bounds and the arrow head in the following screenshots from the standard examples:

Integer vs. double coordinates is comparable to raster vs. vector images. While in integer coordinates a point usually means a pixel, in double coordinates a point has no area and a line can be infinitesimally thin. In a world of double precision it is obvious that we need some rendering. We are forced to think about things like line width, stroke type, line caps, line joins, miters, etc. There are excellent explanatory pictures on these in the JavaDocs of JavaFX's Shape class.

"Smooth" Curves

You have to take round-off errors into account when approximating smooth curves (splines) with integer polylines. Otherwise your allegedly smooth curve will go zigzag. This might be the reason why GEF does not have any curves. GMF does:


Arrow Heads

I'd expect an edges arrow head them to be aligned with the tangent of the edge at the anchor point. For polylines this is the line connecting the anchor with the last bendpoint. Same for Bézier curves, but apparently not for splines like these:

It is also a good idea to prohibit bendpoints too close to the anchor: The inclination of the curve may become too steep:

The last screenshot also shows that the line cap style plays a role at the tip of the arrow head.


Use the Force

GEF 4 will have double coordinates and Bézier curves. But at the time of writing this blogpost, there hasn't been an official release yet. It is not clear either whether and when it will be adopted by downstream projects.

I came across all this when trying to calculate edges and arrow heads for my sparetime JavaFX diagram editor project. Luckily, JavaFX uses double coordinates only. JavaFX also includes quadratic and cubic Bézier curves. These curves are really smooth and drawn fast, though I must admit I'd  have expected B-Splines at least.

I am going to demonstrate this at EclipseCon Europe 2013. Stay tuned for more.

Wednesday, June 12, 2013

Using Xcore in Xtext

With Xtext you can easily create your own textual language. The structure of the language is defined in an Ecore model. This model can be automatically derived from the grammar, which allows quick turnarounds in the beginning. But in the long run, this model becomes an increasingly important API to the language. You want to fix it and make it a first class artifact: You are switching from an inferred Ecore model to an imported one in the grammar.

Traditionally, you use EMF's tree editors to edit Ecore models. That can be cumbersome as the tooling is not the nicest to use. Furthermore, the Ecore model only describes the declarative part. Behavior, such as the body of EOperations or the code for derived EStructuralFeatures has to be woven in either from additional models or directly in the generated code. These and more issues are addressed by Xcore. Xcore allows to specify Ecore models textually, including the behavioral parts and the code generation parameters. Having a single source of information facilitates the maintanance of such a model drastically. Xcore is shipped with EMF.

In the upcoming Eclipse release 4.3 (Kepler) Xcore and Xtext can be used together. Here is a step-by-step example how to do this with Xtext's "Greetings" language:
  1. Create an Xtext project File > New > Project > Xtext Project. The defaults are fine. This will create the usual four projects for your Xtext language in your workspace.
  2. By default, Xcore generates its code to the folder src-gen. The same folder is used by Xtext and will be wiped each time you regenerate the language from the grammar. To avoid loosing data, choose a separate output folder for Xcore: Eclipse/Window > Preferences > Xcore > Compiler > Output Folder > Directory > ./emf-gen

  3. Create a new folder model in the root of org.xtext.example.mydsl and file Greetings.xcore inside that folder. Our Ecore model consists of an EPackage org.xtext.example.mydsl, two EClasses Model and Greetings, a containment EReference greetings and an EAttribute name. In Xcore, this looks like

  4. Open the grammar MyDsl.xtext. By default, the Ecore model myDsl is generated from the grammar rules. We want to replace this with the Ecore model specified in the Xcore file:

  5. We have to load the Xcore model in the workflow GenerateMyDsl.mwe2 of the language generator. Add an appropriate loadedResource entry to the language section:

    module org.xtext.example.mydsl.GenerateMyDsl
    Workflow {
      component = Generator {
        language = auto-inject {
          loadedResource =
          uri = ...
  6. You have to add a dependency to org.eclipse.emf.xcore in the MANIFEST.MF of the project.
  7. Now generate the language infrastructure Run As > MWE2 Workflow. There should not be any error.
  8. Make sure that all folders will be correctly deployed. Your file should look like this
  9. Launch a new Eclipse workbench Run > Run Configurations > Eclipse Application > Launch Runtime Eclipse and enjoy your language in action.
For the geeky fun of it: As Xcore is itself implemented in Xtext with an imported Ecore model, this lays the foundation to replace Xcore.ecore with Xcore.xcore and thereby bootstraping it.
Sorry, I couldn't resist ;-)

Monday, May 20, 2013

Another Xtend and JavaFX Story

For my spare time JavaFX project, I was looking for a way to export a scene to SVG. Googling a bit I stumbled over a blog entry by Gerrit Grunwald who implemented an JavaFX shape to SVG path converter class for the JFXtras project. It looked good so I decided to give it a try.


Java to Xtend

The class is of course written in Java. Even though there is no technical reason - Java and Xtend classes can coexist in the same project without any problems - I wanted to convert it to Xtend as well. I am a lazy guy. Luckily Krzysztof Rzymkowski had recently posted on the Xtend group that he had started to implement a Java to Xtend converter. It even has a web interface, and except for one slight issue with a for-loop it worked like a charm. Great work, Krzysztof!

Of course the resulting code is pretty Java-like, so I wanted to improve on it using more of the cool Xtend features. I found quite a few spots to do so, reducing the amount of code significantly and enhancing readability a lot. The remainder of this post is about this ongoing love of JavaFX and Xtend. The complete source code will likely be made open-source soon.


Dispatch Methods

The class starts with a method that only contains an instanceof-cascade to delegate to the conversion method for the specific subclass of Shape the parameter has:
public static String shapeToSvgString(final Shape SHAPE) {
   final StringBuilder fxPath = new StringBuilder();
   if (Line.class.equals(SHAPE.getClass())) {
      fxPath.append(convertLine((Line) SHAPE));
   } else if (Arc.class.equals(SHAPE.getClass())) { 
      fxPath.append(convertArc((Arc) SHAPE)); 
   } else if (QuadCurve.class.equals(SHAPE.getClass())) {
      fxPath.append(convertQuadCurve((QuadCurve) SHAPE));
   } ... 
In Xtend I can use dispatch methods to realize this: They must have the same method and number of parameters, but different parameter types. The Xtend compiler then generates the dispatcher method with the instanceof-cascade automatically. So renaming the delegate methods and marking them as dispatch made the dispatcher method obsolete.
def dispatch String toSvgString(Line line) ...
def dispatch String toSvgString(Arc arc) ...
def dispatch String toSvgString(QuadCurve quadCurve) ...
Tip: If you want to delegate from one dispatch case to another, the original methods are available with an underscore preceeding their name.


An SVG path is kind of a cryptic string. In the Java code it is assembled using a StringBuilder, e.g.
final StringBuilder fxPath = new StringBuilder();
fxPath.append("M ").append(CENTER_X).append(" ")
   .append(CENTER_Y - RADIUS).append(" ");
fxPath.append("C ")
   .append(" ").append(CENTER_Y - RADIUS).append(" ")
   .append(CENTER_X + RADIUS).append(" ")
   .append(" ")
   .append(CENTER_X + RADIUS).append(" ")
   .append(CENTER_Y).append(" ");
That's the best you can do with Java. In Xtend we have template expressions - multiline strings which can be interrupted with values from expressions. Even IF-conditions and FOR-loops are supported. With carefully chosen regular expressions for find/replace and some manual fine-tuning the above becomes nicely readable
'''M «centerX» «centerY - radius»
   C «centerX + controlDistance» «centerY - radius» 
   «centerX + radius» «centerY - controlDistance» 
   «centerX + radius» «centerY»

Switch Expression

I found another finer-grained instanceof-cascade in the convertPath method:
final StringBuilder fxPath = new StringBuilder();
for (PathElement element : PATH.getElements()) {
   if (MoveTo.class.equals(element.getClass())) {
      fxPath.append("M ")
         .append(((MoveTo) element).getX()).append(" ")
         .append(((MoveTo) element).getY()).append(" ");
   } else if (LineTo.class.equals(element.getClass())) {
      fxPath.append("L ")
         .append(((LineTo) element).getX()).append(" ")
         .append(((LineTo) element).getY()).append(" ");
   } else if (CubicCurveTo.class.equals(element.getClass())) { 
      fxPath.append("C ")
As the bodies of the if-statements are so simple, I decided to use Xtend's switch instead. It allows to use type guards for the cases and automatically cast the switch variable to that type inside the case's body:
val it = new StringBuilder
for (element : path.elements) {
   switch element {
      MoveTo: append('''M «element.x» «element.y» ''')
      LineTo: append('''L «element.x» «element.y» ''')
      CubicCurveTo: append('''C «element.controlX1»...
I could further use the operator => instead of the Builder class and the operator <=> replacing

Extension Import (Client Side)

From a client side, the shapeToSvgString method is a utility method for Shapes. In Xtend, you can import such methods using a static extension import. That makes them callable in extension syntax, as if the method was defined in the class of the first parameter. To further improve readability, I renamed the methods to toSvgString such that I can now write
import static extension ...ShapeConverter.*
new Rectangle.toSvgString

Wednesday, April 3, 2013

'X' Is For Abstraction

We at itemis have created a bunch of projects with an ‘X‘ during the last years: Xtext, Xtend and Xbase. In this blog post I am trying to elaborate the different use cases for each of them.

It all starts with Java...

...which is a nice language understood by many programmers worldwide. A giant ecosystem and a vivid community as well as great IDEs are keys to its success.

But Java has a couple of crucial problems: Its syntax is inflexible and very verbose, making fluent APIs the closest you can get to domain-specific languages. Design patterns and structural conventions as JavaBeans have to be manually implemented over and over again with lot of error-prone boiler plate code. Frameworks require a big deal of XML pointing to Java classes, often ignored by the static analysis at compile time. IDEs can help us here, but they are usually limited to scaffolding or a single way of using a framework. The diagnosis is: Java is lacking the right means of abstraction.

All technologies presented in the following enable you to define your own set of abstractions on top of Java. The solutions differ in syntactic flexibility, turnaround times, required user skills and multi-platform coverage.

External DSLs (Xtext)

Xtext is a framework for external, textual, domain-specific languages. Xtext makes it easy to build an entire IDE for a completely new language, including your own code generators or interpreters to execute it. The Xtext homepage lists a lot of example projects.

When should you use Xtext? First of all, when you need a maximum of syntactical freedom. As Xtext DSLs are external they are defined by their own grammar, thus not constrained by the syntax of a host language.

Second, use plain Xtext if your language has no correspondence to Java or if you want to avoid dependencies on JDT at all cost. Languages that target different platforms at the same time are most likely based on a plain Xtext-based language, too. The technical skills needed to work with a Xtext-based language IDE is relatively low. I personally do not believe in "programming business men". But Xtext has been successfully used for non-technical, purely domain-oriented languages.
As the generated IDE is already very powerful by default and can be customized easily, some people even use Xtext to build the IDE front end for an existing language with an existing compiler.

If you change the grammar, you have to regenerate the language infrastructure and redeploy the language's plug-ins to the user's machines. The latter can be a challenge in some scenarios.

Mostly structural languages with simple expressions only will go smoothly. A few complicated expressions can pragmatically be integrated using the common integration techniques (generation gap pattern, black-box literals, protected regions, etc.). But all of these raise the complexity, break the abstraction, and are hard to maintain. If expressions are the rule and not the exception, consider

Java DSLs (Xtext with Xbase)

Under the codename Xbase, we have developed a rich expression language, that you can embed in your Xtext-based DSLs. It reuses Java's typesystem, can express everything that Java expressions can do and adds even more features like type inference, operator overloading, lambda expressions etc.

The default way of using Xbase is to define a transformation from your language to a structural Java model and embed the expressions in the appropriate Java contexts. A generic code generator builds Java code from this model, so no need to build your own. As we generate plain Java code, these Xbase languages integrate seamlessly with hand-written Java code and work for platforms that are sensitive to bytecode manipulation, like Android.

Java DSLs are the way to go for languages that compile to Java and need rich behavior or expressions. These are probably much more than you'd probably expect. Have a look at our seven languages for some examples. There is also an interpreter for Xbase allowing to skip the compilation step on the language user's side.

We have only implemented an execution environment for Java, so it's up to you if you need another. Restricting the available expressions is easy and could help here significantly. You can also add new expressions to the expression language, but the syntactic space is already quite crowded.

Non-technical users are usually ruled out here. You don't want to teach them managers about closures, do you? You still have complete syntactical freedom for your language. But you still have to regenerate the plug-ins and redeploy them on grammar changes as before.

Internal DSLs (Xtend)

Just because Java doesn't offer the means of abstraction you need doesn't mean you have to define a new language yourself. We have created Xtend, a general purpose language (GPL) based on Java but adding a lot of fancy stuff like type inference, operator overloading, lambda expressions, etc. You guessed it: Xtend is based on the Xbase expression library, but also defines the structural parts (types, fields, methods, annotations etc.), adds extension methods, multi-dispatch methods, template expressions, and offers an even better IDE.

This is already a mighty toolset and can bring you pretty close to internal DSLs in other languages. Look at our examples from EclipseCon 2012 (especially the SWT, Distances and HTML Builder examples).

One additional leap ahead are Active Annotations (new in 2.4, beta). These annotations allow you to participate in the Xtend to Java compilation. They are particularly useful for implementing patterns,  but can be surprisingly powerful in other scenarios, too. Have a look at a few cool examples: Observer pattern, Vistors, JSON classes, a simple REST API, micro benchmarking...

Having everything you need in the language itself gives you short turnarounds as no more regeneration and redeployment is needed. The toolstack stays nicely low. But you're restricted to generating Java and use the syntactical elements of the Xtend language. I would never recommend Xtend to non-programmers, but to everyone fighting with Java.

Sunday, January 6, 2013

Accumulating JavaFX Transforms With Xtend

I was a bit vague in my last post on JavaFX's transformation API, so I decided to write a separate post on this topic.

In JavaFX, each node in the scenegraph can be translated, rotated, scaled or sheared relative to its parent. In mathematical terms, each node maintains a transformation describing its own local coordinate system. This transformation can be defined with a matrix represented as a Transform object in JavaFX.

The JavaFX API offers some convenience methods to manipulate this transformation. E.g., you can scale a node in x-direction and translate it by 42 units in y-direction by calling
Unfortunately, these convenience methods do not accumulate as one would expect. Instead of multiplying the matrices for subsequent transformations, the only set specific entries in the matrix. As a result, translating an object before rotating yields the same result as applying these transformations in reverse order. This is mathematically wrong and does also not match the users expectations.

In my diagram editor application, I want to scroll (translate), zoom (scale) and rotate the canvas using mouse gestures. From the user's point of view it's imperative that each transformation builds on the previous state. The convenience methods don't match this usecase.

The correct solution to this problem is to multiply the transformation matrices. Unfortunately, JavaFX lacks any kind of calculation API for Transform and its subclasses.

Once again, this is where Xtend comes to our aid. An extension method in Xtend can be used to define functions for existing (closed) types, which syntactically look like being methods of the type on the caller's side. Affine is a subtype of Transform that allows its matrix entries to change. So I wrote extension methods to translate, rotate, scale and shear an existing Affine by multiplying the respective transformation matrix, e.g.
class TransformExtensions {
  def static scale(Affine it, double x, double y) {
    // left multiply a scale matrix to it
    // highly optimized as there are many zeros in the scale matrix
    mxx = x * mxx 
    xy = x * mxy 
    mxz = x * mxz
    tx = x * tx // take existing translation into account 

    myx = y * myx
    myy = y * myy
    myz = y * myz
    ty = y * ty 
Importing these as extensions
import static extension ...TransformExtensions.*
now allows to accumulate the transformations, e.g.
val diagram = scene.root
val diagramTransform = new Affine
diagram.transforms += diagramTransform

val EventHandler scrollHandler = [
  diagramTransform.translate(deltaX, deltaY)
scene.onScrollStarted = scrollHandler 
scene.onScroll = scrollHandler
scene.onScrollFinished = scrollHandler
val EventHandler rotateHandler = [
  diagramTransform.rotate(angle, sceneX, sceneY)
scene.onRotationStarted = rotateHandler
scene.onRotate = rotateHandler
scene.onRotationFinished = rotateHandler
The resulting behavior looks like the following screenshot. Note that the mouse position is the pivot for rotations and zoom. 


The same mechanism can be used to properly place labels along connections:

PS: I went for mutable transformation matrices, but the same mechnism will hold for immutable matrices. The extension methods then return a new Affine instead of modifying the receiver.

Tuesday, January 1, 2013

JavaFX Loves Xtend

Inspired by a talk by Gerrit Grunwald and the work of Tom Schindl I started to dig a bit deeper into JavaFX. Being one of the committers of the Xtend language, it was a matter of honour to use Xtend in my experiments. The result: JavaFX and Xtend seem to be made for each other.

If you know me a bit, you won't be surprised that I tried implementing a simple graph editor first. I will blog on that particular application in a separate post. Even though JavaFX is not primarily a graphical editing framework, it offers a lot of the required features, e.g.
  • State of the art rendering and CSS styling
  • A life scene-graph with affine transformations in all nodes
  • An easy way to do data-binding and event propagation
  • Easy to use APIs for effects and animations
  • Built-in support for tablets and touch-aware devices
The developers of JavaFX did a pretty good job in creating a clear Java API, but sometimes Java's rigid syntax was a bit in their way. This is where Xtend comes into play. The resulting code is astonishingly short and easy to read.

Lambda Expressions For Event Listeners

Each JavaFX Node has a couple of convenience methods to react on on UI events, such as mouse clicks, key strokes or multi-touch gestures. A mouse click can for example be handled as
Node node = new Rectangle();
node.setOnMouseClicked(new EventHandler<MouseEvent>() {
   public void handle(MouseEvent event) {
      System.out.println(event.getButton() + " button clicked");  
Xtend's lambda expressions (aka closures) are automatically coerced to interfaces with a single method. Using the implicit parameter it and the shortcut syntax for property access the above becomes
val node = new Rectangle
node.onMouseClicked = [
   println(button + " button clicked")

The With Operator => Obsoletes Builders

JavaFX has a couple of objects that need quite a few parameters to be customized. Instead of implementing a new constructor with a huge number of parameters for each use case, the JavaFX developers generated fluent builder APIs, e.g.
Rectangle rectangle = RectangleBuilder.create()
In Xtend, we have the with operator '=>' that binds the preceding argument to the parameter of a lambda expression and executes the latter. So we can achieve the same as above with an even shorter syntax and without the need for an accompanying builder class:
val rectangle = new Rectangle => [
   width = 80
   height = 30
   fill = Color::BLUE
   stroke = Color::RED
   strokeWidth = 1.2
   arcWidth = 12
   arcHeight = 12
The with operator also facilitates the creation of object trees, e.g. subtrees of JavaFX's scenegraph.

Extension Methods For High-Level Property Binding

In JavaFX, properties can be derived from other properties by means of another fluent API for the calculation. The result is the best you can achieve with pure Java, e.g. given two DoubleProperties a and b, you can bind a mean value property which will be automatically updated when a or be change:
If these calculations get more difficult and you do a lot of them it will get quite unreadable. This is the right moment to think about overloaded operator extensions for DoubleProperties. With these, the last line can become as simple as
mean << a + b / 2
Extension methods and operator overloading can also be used to add the missing APIs for geometry calculation, e.g. to apply a Transform to a Point3D or to accumulate Transforms.