Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

JVM Languages

Java and the Waba Toolkit


Feb01: Java and the Waba Toolkit

Java in the palm of your hand

Al teaches courses on various web-related technologies through Wintellect (http://www.wintellect.com/). He can be contacted at [email protected].


If you own a PalmPilot or a Windows CE-based handheld, chances are you've thought of programs you'd like to write for it. Unfortunately, programming these small machines can turn into a big job. However, if you know Java and have ordinary Java development tools, you can develop a wide range of programs that run on the Palm or Windows CE with a development kit known as "Waba" (http://www.wabasoft.com/). Waba is a freely available software kit released under a license similar to Linux. It provides a subset of Java that will run on either handheld device (CE or Palm), or any machine that runs Java — you can even embed a Waba applet in a web page. In this article, I'll show how you can simply write a Waba Reverse Polish Notation (RPN) calculator that will run on a handheld device. The complete source for the calculator is available electronically; see "Resource Center," page 5.

Unlike some tools, Waba doesn't include a compiler, debugger, or much else in the way of tools. Instead, it uses your existing Java development tools. Of course, you can download the basic JDK from Sun for free, but you might find an IDE from one of the major tool vendors more to your liking. Waba doesn't care which tools you use.

To run a Waba program on a handheld device, you need a small download (40-60 KB depending on platform). This Waba run time installs on the handheld and executes the Waba programs you create. The Waba developer's kit is in a ZIP file that is around 360 KB — very lean compared to most development tools. This is especially true if you consider a great deal of the development kit is documentation and examples. You can also get the Waba source code in another 160 KB download. Of course, you don't really need the source code unless you like to tinker. If you are using a nonWindows PC, you'll also need to download the binary tools for your platform (you can download them for Linux, Solaris, BeOS, MacOS, AmigaOS, and OS/2). There is also a third-party set of tools written in Java that should run practically anywhere.

The Basic Idea

Writing a Waba program is much like writing a Java program. However, Waba provides a complete class hierarchy that replaces the standard Java classes. Many of these classes mimic the normal classes (for example, String or Graphics). Others are unique to Waba. For example, MainWindow is similar (but different) from the usual Java Applet object.

Waba provides the following packages:

  • waba.lang. Object, String, and StringBuffer classes.
  • waba.sys. Classes for time, date, type conversion, and access to machine resources.

  • waba.util. The Vector class.

  • waba.ui. Classes that provide user- interface elements (buttons and labels). It also provides support for timers and events (including pen events).

  • waba.io. Access to databases, files (the Palm has no files), serial port, and network sockets.

  • waba.fx. Classes for colors, fonts, images, and sounds.

You can also add some extra classes that are available from other authors, including several enhanced user-interface packages.

Once you generate your class file, you'll use special tools to create a Waba executable that can run on the handheld device. One tool (warp) creates special files tailored for the CE or Palm environment. The other tool (exegen) creates icons for both systems that can start the program. The exegen program also sets the window size, memory allocation, icons, and other details.

Anatomy of a Waba Program

A Waba program typically extends MainWindow, the class that represents the Waba program and its primary window. From this object's onStart function, you can create controls and perform other initialization. The onEvent function is the main clearinghouse for events (keystrokes, button press, and pen events).

Many useful Waba programs won't need more than a MainWindow-derived class that contains an onStart and an onEvent function, along with whatever custom functions you need to do the actual work.

A Waba Example

As a long-time user of HP calculators, I've often wanted a simple Windows CE RPN calculator. Why not use Waba to make a calculator that will run on CE or the Palm? You'd even be able to put the calculator in a web page or use it on any Java-enabled platform. Figure 1 and Listing One present the complete calculator.

When you design a Waba program, you must be aware of the limitations of Waba when compared to ordinary Java. For example, it is important to realize that Waba does not support the double data type. That means the calculator will use the float data type (and accept the resulting loss of precision). Initially, you might consider reading numbers as a string and then converting the string into a float. This would be easy to do with Java, but Waba handles conversions a bit differently.

The waba.sys.Convert object has many static functions (for example, toString) that converts basic types to strings and vice versa. However, the object lacks a function that converts a string to a float. Therefore, the calculator program has to provide code to convert key presses into a floating-point number. Of course, the inherent lack of precision in the float class means that entering, for example, 1.2345 might actually display 1.2344999.

Another problem with the lack of double support is constants. When you write a floating-point constant (like 3.141) in Java, it has an implicit type of double. When the Waba interpreter tries to load the constant, it will generate an invalid op code error. The answer to this problem is to use the f suffix on constants to force their type to float (as in 3.141f).

Inside the Calculator

In Listing One, notice that the alcalc class begins with a few simple member variables. Instead of using a separate variable for each button, the calculator uses an array. A label control (led) serves as the calculator's display.

Another array (stack) serves as the calculator's stack (four deep in this example). There are a few other simple variables to track input state and the stack's current status. The final two variables in this section, wid and hi, store the dimensions for normal-sized buttons.

Since the calculator's stack is circular, the addsp function handles incrementing and decrementing the stack pointer (sp). The function simply wraps the stack pointer around when it falls past zero or increases beyond the end of the stack.

To simplify the user-interface setup, the setBtn function handles the population of the button array. The calling code supplies the row and column number for the button as well as the button's caption and relative width. A width of one is the normal width, but some buttons occupy twice the space (a width of two). The size and actual location of the buttons depend on the host device's screen size. The onStart routine begins by finding the screen size and setting the wid and hi variables to appropriate values. Then it is a simple matter to call setBtn to populate the calculator's face with buttons.

Most of the real work occurs in the onEvent function. This is where the calculator processes events that Waba generates. The first order of business in this function is to detect KEY_PRESS events. These events occur when users enter characters via the keyboard or a pen input method (like Jot or Graffiti).

To keep the code simple, the calculator effectively converts key events into a corresponding button index. In the case of a real button push (a PRESSED event), the code searches the button array and determines the index. Either way, the remaining code handles a button index, not the actual event.

Like most event-handling code, onEvent's main section uses a switch statement. Variables control the state of the input, as follows:

  • lift. This variable is 1 if there is a new number being entered.
  • dp. If 0, users are entering the whole part of a number. If dp is not 0, it indicates the scale of the fractional input. For example, if dp is 100, this indicates the second digit beyond the decimal point.

  • neg. The algorithm used to build the number assumes that the input number is positive. This variable remembers if the number is negative so it can restore the correct sign if necessary.

All the numbers use the same routine. Each function key (the "+" key, for example) has a small piece of separate code that performs the correct operation.

Debugging Waba

One of the nice features of Waba is that you can get your program operating on your workstation using Java. Simply compile your program with the javac program as usual to produce class files. To run the alcalc program, run:

java waba.applet.Applet alcalc

When you are running on the workstation you can even use System.out.println to display messages on the console. Remember, the library you are using is not exactly the Waba library in this case. For example, the standard run time doesn't support the serial port. The Waba Extras package does have a replacement library that supports the serial port, but I had trouble with a large program like alcalc receiving key events when using the Extras package (a simple test program worked, though).

However, you can get most, if not all, of your program working before you bother downloading to the handheld computer. If you've used any calls to println, you'll want to remove them before you do a final build.

Building the Calculator

You can't download class files directly to the handheld device. Instead, you must run the warp utility to generate a wrp file (for Windows CE) and a pdb file for the Palm. In addition to these files, you'll also want to run exegen to create icons for both platforms (either an lnk file or a prc file). You can wrap these commands up in a batch file (see Listing Two).

The Waba documentation explains how to install files on each platform. For Windows CE, it is simply a matter of copying files to the correct locations. For the Palm, you'll run the Palm's installation program. Either way, you'll wind up with an icon that will run the program. Of course, you'll also have to install the Waba run time once on the handheld machine.

What's not in Waba?

Waba does not currently support long and double data types. It also does not support exceptions or threads. However, for many applications this is not a serious problem. Of course, the source code for Waba is available, so if you are particularly intrepid, you could add support for what you wanted yourself.

For example, if you tried to add more scientific functions to the calculator, you'd find that Waba doesn't support many more math functions. However, someone has written a replacement math library (see the resources). There's no reason you couldn't do the same.

Acknowledgment

Thanks to Justin Kerr of the Johnson Space Center for testing this program on the PalmPilot.

DDJ

Listing One

// RPN calculator for CE or Palm
// Al Williams


import waba.ui.*;
import waba.fx.*;
import waba.util.*;


public class alcalc extends MainWindow
{
 final int stacksize=4;  // Set stack depth


// Buttons and display
 Button btns[] = new Button[18];
 Label led = new Label("0.0",Label.RIGHT);


// This is the stack
 float stack[] = new float[stacksize];
 float dp=0.0f;  // decimal point scaling


 int sp=0;  // stack pointer
 int lift=0; // stack lift (new entry) flag


// Scale factors for the current window
 int hi;  
 int wid;


// Set incr==1 to increment; -1 to decrement
// circularizes based on stacksize
 int addsp(int sp,int incr) 
  {
  if (incr==-1 && sp==0) return stacksize-1;
  if (incr==1 && sp==stacksize-1) return 0;
  return sp+incr;
  }


// set up a button
// x,y are row and column NOT pixels
// width is 1 for single-width, 2 for double width
 void setBtn(int i,String lbl,int x,int y, int width)
  {
  btns[i]=new Button(lbl);
  btns[i].setRect(x*(wid+5),y*(hi+5),width*wid,hi);
  add(btns[i]);
  }
// Set up all the work
 public void onStart()
  {
  Rect r;
  r=getRect();


  hi=r.height/7;
  wid=r.width/5;
  stack[sp]=0;
// display
  led.setRect(0,0,r.width-10,hi);
  add(led);
// set up all buttons
  setBtn(0,"0",1,4,1);
  setBtn(1,"1",0,3,1);
  setBtn(2,"2",1,3,1);
  setBtn(3,"3",2,3,1);
  setBtn(4,"4",0,2,1);
  setBtn(5,"5",1,2,1);
  setBtn(6,"6",2,2,1);
  setBtn(7,"7",0,1,1);
  setBtn(8,"8",1,1,1);
  setBtn(9,"9",2,1,1);
  setBtn(10,"Enter",0,5,2);
  setBtn(11,"+",3,1,1);
  setBtn(12,"-",3,2,1);
  setBtn(13,"*",3,3,1);
  setBtn(14,"/",3,4,1);
  setBtn(15,"+/-",0,4,1);
  setBtn(16,".",2,4,1);
  setBtn(17,"x<>y",2,5,2);
  }
// display number at top of stack
void disp(int newlift)
  {
     led.setText(waba.sys.Convert.toString(stack[sp]));
     lift=newlift;
  } 
// Handle key pressses
public void onEvent(Event event)
  {
  int i=-1;
  int leaddp=0;  // leading decimal point?
  int neg=1;  // 1 means positive number
  if (event.type==KeyEvent.KEY_PRESS)
    {
    KeyEvent kevent = (KeyEvent)event;
    if (kevent.key==IKeys.ENTER) kevent.key='\n';  // Enter key
// convert key to button #
    String keys="0123456789\n+-*/ .";  
    for (i=0;i<keys.length();i++)
    if (keys.charAt(i)==kevent.key) break;
    if (i==keys.length()) return;
    }
  else if (event.type == ControlEvent.PRESSED) // button
    {
    for (i=0;btns[i]!=event.target;i++); // scan for button
    }
  if (i!=-1)
    {
    switch (i)


      {
case 16:   // decimal point
      leaddp=1;
      if (dp==0.0f) dp=10.0f;
      if (lift==0) break;  // if not first entry, nothing special
      i=0;    // otherwise, treat like a 0 key
// fall into 0 case
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:  // digits
    if (lift==1)  // new number?
      {
      sp=addsp(sp,1);
      stack[sp]=0;
      lift=0;
      dp=0.0f;
      }
    else
      leaddp=0;  // ignore lead dp flag if old number
    

    if (stack[sp]<0)  // get absolute value of tos
      {
      neg=-1;
      stack[sp]=-stack[sp];
      }
    if (dp==0.0f)   // whole number
      {
      stack[sp]=stack[sp]*10+i;
      }
    else  // fractional number
      {
      stack[sp]=stack[sp]+i/dp;
      dp*=10;
      }
// if number was negative, make it negative again
    stack[sp]=stack[sp]*neg;
    disp(0);
    if (leaddp==1) dp=10.0f;
        break;
// enter key
case 10:
    i=addsp(sp,1);
    stack[i]=stack[sp];
    sp=i;
        lift=1;
    break;
// +
case 11:
   i=sp;
    sp=addsp(sp,-1);
    stack[sp]=stack[sp]+stack[i];
    disp(1);
    break;
// -
case 12:
    i=sp;
    sp=addsp(sp,-1);
    stack[sp]=stack[sp]-stack[i];
    disp(1);
    break;
// *
case 13:
    i=sp;
    sp=addsp(sp,-1);
    stack[sp]=stack[sp]*stack[i];
    disp(1);
    break;
// /
case 14:
    i=sp;
    sp=addsp(sp,-1);
    stack[sp]=stack[sp]/stack[i];
    disp(1);
    break;
// +/-
case 15:
      stack[sp]=-stack[sp];
      disp(lift);
      break;
// x<>y
case 17:
    float tmp;
    i=addsp(sp,-1);
    tmp=stack[sp];
    stack[sp]=stack[i];
    stack[i]=tmp;
    disp(1);
    break;
      }
    }
  }
}


Back to Article

Listing Two

@echo off


rem compile program, build warp files and launchers
javac *.java
warp c /q alcalc *.class
exegen /q /i icon.bmp alcalc alcalc alcalc
echo To test program:
echo java waba.applet.Applet alcalc








Back to Article


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.