SWT Matrix

SWT Matrix

SWT Matrix is a tabular widget for SWT Java GUI toolkit. What makes it different from other grid components is unlimited capacity and instant rendering.
It also focuses on developer productivity by clean design with minimal learning curve.

Unlimited Capacity

SWT Matrix can handle an unlimited number of rows and columns. Integer.MAX_VALUE (2 147 483 647) is not a limit, neither is Long.MAX_VALUE (9 223 372 036 854 775 807). And still it performs block selection, moving, resizing scrolling and setting of various properties of cells, rows and columns. More then 2147483647 items is a rare case, but it can happen. It’s better to be safe then sorry.

Instant Rendering

It is assumed by convention that instant for GUI applications means responding in less then 0.1 sec. Now consider scrolling a content of a table with 1 million rows and columns in a full screen mode with 1680 x 1050 screen resolution. It’s around 2000 visible cells of size 50×16. Components that don’t support virtual display choke completely. BTW don’t be misled by SWT.VIRTUAL constructor flag of those widgets. Scroll to the end and you will see that it is lazy initialization rather then virtualization. None of the popular tabular components tested on Windows XP 2GHz are consistent to provide instant response for basic operations like navigation. SWT Matrix paints itself in about 50 ms, which is at least 8x better then the other grid/table widgets. And not all identified optimizations have been implemented yet.

Clean design

Total of 6 classes in the public API does not sound like an over-complicated design for the amount of supported features and compared to hundreds of classes in other solutions. Symmetry is also a measure of a clean design. Thus there is no such a thing that works for columns, but does not work for rows and vice versa, or works for one section and does not for another. For example since columns can be resized why not resize the row header? Even freezing is symetric. If the head of an axis can be frozen why not the tail? A frozen footer may come handy.

The current major limitations are for instance lack of cell merging, column/row grouping and hierarchy. But they are coming in the next releases. Here is the detail feature list.

The component is released under commercial licence but is free of charge for non commercial use.

The current stage is alpha release to allow evaluation and early user feedback. Your opinion would be highly appreciated!

Lazy Runner Pattern

The guideline to execute a long running operation in a separate thread is well known, especially for GUI triggered stuff. However I did not come across any best practice to deal with lengthy operations creeping. For example scrolling faster then the content refresh rate will cause a series of content updates going on and on long after the user has finished scrolling. This post is to provide a reference solution to handle such a case.

The LazyRunner, I think I can call it a pattern, guarantees that only the latest Runnable submitted to the execute() method will actually run (unless external disruption such as thread interruption or system error happens). All the Runnables submitted while some other Runnable is being executed are ignored.

In result the maximum time to finish processing after last execution request is equal to
2 * <single runnable time> instead of
<number of requests> * <single runnable time>.

public class LazyRunner  {
	private volatile Runnable running;
	private volatile Runnable latest;
	
	public final void execute(final Runnable r) {
		latest = r;
		if (running == null) {
			running = latest;
			new Thread("lazy runner") {
				@Override
				public void run() {
					do {
						running = latest;
						running.run();
					}
					while (running != latest);
					running = null;
				};
			}.start();
		}
	}
}

An example of usage:

static class LongOperation implements Runnable {
	String s;
	public LongOperation(String s) { this.s = s; }

	@Override
	public void run() {
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {}
		System.out.println(s);
	}
}

public static void main(String[] args) throws InterruptedException {
	LazyRunner runner = new LazyRunner();
	
	runner.execute(new LongOperation("a"));
	runner.execute(new LongOperation("b"));
	Thread.sleep(100);
	runner.execute(new LongOperation("c"));
	Thread.sleep(100);
	runner.execute(new LongOperation("d"));
	Thread.sleep(100);
	runner.execute(new LongOperation("e"));
}

The output should print “b” and “e”.

A special case is slow SWT operations, for instance drawing text in GTK2 on Linux, which causes a noticeable rendering delay for StyledText with a few dozen of lines. A LazyRunnable in such scenario has to mingle with display.asyncExec() method to execute the Runnable in the GUI thread. It can be implemented as follows:

public class SwtLazyRunner  {
	private final Display display;
	private volatile Runnable running;
	private volatile Runnable latest;
	
	public SwtLazyRunner(Display display) {
		this.display = display;
	}

	public final void execute(final Runnable r) {
		latest = r;
		if (running == null) {
			running = latest;
			if (!display.isDisposed()) {
				display.asyncExec(new Runnable() {
					@Override
					public void run() {
						do {
							running = latest;
							running.run();
						}
						while (running != latest);
						running = null;
					}
				});
			}
		}
	}
}

I hope you find it useful.

Null-safe method invocation in Java 7

There has been some discussion on null-safe method invocation in Java 7. Briefly there is a proposal to introduce a new ?. operator that would allow to call a method on a null object without throwing a NullPointerException (NPE). For instance:

List list = null;   
System.out.println(list?.isEmpty()); // prints: false

The most obtrusive part in the current state of proposals is assumption that the invocation on null object should always return null or a default value in case of primitives. In our example of list?.isEmpty() returning true would make much more sense then false, because semantically the null list does not have any elements so it is empty. The bottom line is that what the method returns when called on a null object is an implementation detail of that method, so it should be specified in the method’s body. The rest of this post proposes a way to do it.

If the method’s body starts with if (this == null) statement, e.g.

class List {
    public boolean isEmpty() {
    if (this == null) return true;
        return data.length == 0;
    }
}

then Java 7 compiler could compile it to both the traditional method:

public boolean isEmpty() {
    // the if (this == null) ... block is removed     
    return data.length == 0;
}

as well as to a static wrapper method:

private static boolean isEmptyNullSafe(List _this) {
    if (_this == null) return true;
    return _this.isEmpty();
}

(The name of the wrapper method must be generated by the compiler to prevent name clashes with methods already existing in the source code)

This way the isEmpty() method would work the same way if called normally:

list.isEmpty()

, throwing NPE.

But the null safe call:

list?.isEmpty()

would compile to:

List.isEmptyNullSafe(list);

and return true, if the list is null