Monday, 13 July 2015

HTML5 Browser Apps with Java - TeaVM part 2

I took an initial look at TeaVM - a technology for developing HTML5/Javascript web applications using Java as the development language. The first signs were promising - it was easy to get started, and the learning curve looked to be a fairly shallow one for any developers who are already familiar with Java.

The next task was to determine how easy it would be to develop real applications. That means knowing how to implement commonly needed application features: creating a user interface, responding to user actions, loading data, and manipulating on-screen elements. To that end, here are some of code examples to illustrate how to do common tasks...

1. Handling user interface events
<button id="myButton">Click Me</button>
HTMLButtonElement myButton = (HTMLButtonElement) 
    myButton.addEventListener("click", new EventListener<Event>() {
    public void handleEvent(Event evt) {
        //button was clicked
2. Loading an image
HTMLImageElement imgElt = (HTMLImageElement)
imgElt.addEventListener("load", new EventListener<Event>() {
    public void handleEvent(Event evt) {
        //loaded image successfully
imgElt.addEventListener("error", new EventListener<Event>() {
    public void handleEvent(Event evt) {
        //failed to load image
3. Displaying an image
HTMLCanvasElement canvasElement = (HTMLCanvasElement)
CanvasRenderingContext2D context = (CanvasRenderingContext2D)canvasElement.getContext("2d");
context.drawImage(imgElt, posx, posy, width, height);

For a web application, the user interface is of course defined in HTML, so in the Java code we simply need to get handles of the existing elements (Example 1), or create them on the fly (Example 2). The classes HTMLButtonElement, EventListener, HTMLCanvasElement, CanvasRenderingContext2D and HTMLImageElement are all provided by TeaVM. If you are familiar with Javascript, you'll recognise the similarity. But of course being Java, you get the benefit of strongly-typed classes, which aid with clarity and help reduce bugs.

Another elegant feature of TeaVM is the ability to extend it if you need to use Javascript features that may be missing or not yet implemented. For example, I wanted to make use of Javascript's toFixed() method to format decimal numbers. TeaVM does not provide direct access to this function via its own APIs, but does however provide a method to access arbitrary Javascript using a mechanism called JSO. It works using Java annotations to declare Javascript references, like this:
import org.teavm.jso.JSBody;

public class JSFormatter {
    @JSBody(params = { "f", "n" }, script = "return f.toFixed(n);")
    public static native String toFixed(float f, int n);
I'll write up my conclusions on TeaVM in the next article.

Thursday, 18 June 2015

HTML5 Browser Apps with Java - TeaVM part 1

Let's take a moment reminisce about the late 1990s... Probably the first thing you thought of wasn't Java Applets! But there was a brief period back then where Java was the new and exciting language and one of the cool things you could do was create Java Applets - self contained programs that could be embedded in a web page.

But the glory days of Applets are long gone. While Java went from strength to strength for server-side development, the technology acquired a bad reputation on the client-side - especially for browser-based applets. Problems of perceived slowness, the need to download the large Java plugin, numerous security concerns, and competition from competing technologies such as Flash, saw Java Applets quickly fall into technological obscurity.

These days the preferred way of creating browser-based apps is using HTML5 and the associated goodies - JavaScript and canvas element. While this means a better and more secure user experience, it does present a problem if you want to develop such apps as a Java developer. If you are used to Java with its strong Object Orientation, static types, and excellent development environments, programming in JavaScript seems by comparison awkward and developer-unfriendly.

In an ideal world there would be a convenient way of developing in Java, but produce code that runs as client-side, HTML5 browser applications. The good news is: Now at last there is.

There are now several Java-to-JavaScript compilers on the scene, and so recently I started to take a look at them. The one I am particularly impressed with is TeaVM. Another interesting one is Back2Brwsr.

Google Web Toolkit, a similar technology in some respects, has been around for a while. But my experience with it was disappointing. It was awkward to use - requiring source code of any Java libraries you need to use, additional configuration for your included classes, and is slow to compile. The big benefit of these new generation of tools, is they work on compiled Java bytecode rather than source code, which makes them more convenient and easy to use, and faster to run too!

I decided to try out TeaVM a little, and to subjected it to the "10 minute test" - is it possible to create something trivial but which demonstrates its basic capabilities, just within a 10 minute period? Making use of the provided maven archetype, I created a project template and loaded it into my IDE. No problems there. Then it became very easy to make use of TeaVM's intuitive system for Java code to HTML elements. I ended up with something like this:

HTML source
    <title>TeaVM Test</title>
    <script charset="utf-8" src="teavm/runtime.js" type="text/javascript"></script>
    <script charset="utf-8" src="teavm/classes.js" type="text/javascript"></script>
<body onload="main()">
    <canvas width="400" height="400" id="canvas" tabindex="0">

Java source
    private static Window window = (Window) JS.getGlobal();
    private static HTMLDocument document = window.getDocument();
    private static HTMLCanvasElement canvas = 
    public static void main(String[] args) {
         CanvasRenderingContext2D context = 
         context.fillText("Hello World!", 20, 20);

Using the provided maven tasks, TeaVM converts the compiled Java bytecode into JavaScript (the two files runtime.js and classes.js), and hey presto, a simple canvas "Hello World" program.

The ease with which it was possible to get started, combined with the simple, intuitive way to deal with HTML elements, including canvas, makes TeaVM look very promising. I'll look at it in more detail in the next article.

Saturday, 4 October 2014

Top 3 tips for an improved typing experience - part 3

In this final part of my 3 keyboard improvement tips, let's look at an idea which is designed to allow the hands to adopt a more comfortable typing position when using standard keyboard hardware.

Tip #3: Use a Wide Keyboard Modification.

This tip is based on the Colemak Wide layout, but in fact will work well regardless of the layout being used. When I first heard of this idea, I was sceptical. But now, having tried it out for a while, it has become one of my favourite keyboard mods. Below are examples for both the Qwerty and Colemak layouts. There are Microsoft Keyboard Layout Creator files available if you want to try it out - these particular examples assume a UK keyboard.

The Qwerty-wide layout introduces greater separation between the hands and allows easier access to keys on the right-hand side, such as Return.
The design of most standard keyboards cause the hands to be unduly cramped together. This is especially the case with many smaller laptop keyboards. This modification addresses this design flaw by moving all the letter keys on the right-hand side of the keyboard by one space to the right. As a result, it introduces a greater separation between the two hands, as the home position of the right hand is now further to the right.

My laptop keyboard, using the Colemak layout combined with the Wide modification.

This change also provides the additional benefit that the commonly pressed keys on the right edge of the keyboard, such as Return, Backspace and Right Shift, become more accessible, and require a much reduced movement away from the home position.

The possible drawback though, is that to make room for the moved letters, the keys [ ] / = need to move to the central column of the keyboard, which may look strange at first sight. Despite the unusual aesthetics, in reality these keys are rarely typed, and if necessary can always be remapped to more convenient positions e.g. by using something like my AltGr Programmers mod.

A difference of one key-width may not seem like a huge difference, and in an ideal world it would be better yet to have an even greater separation. But nevertheless, having tried if for myself, I have found it does make a noticeable difference. For those who are touch-typists and have control over the equipment they use, and I am now convinced of its merits as a worthwhile change.

Download: Example scripts for all three tips are available from my keyboard-tweaks GitHub repository.