Saturday, June 4, 2011

Punch Clock 0.2.1 and clickable edit button for SWT tables

After the release of Punch Clock 0.2.0 I observed a few issues that needed to be solved. I've just posted a new version, Punch Clock 0.2.1 which has these minor fixes and a new dialog to view the "audit" data in the UI.

One of the new features I added since 0.2.0 which I wanted to write about is the "Fix Session" button I have added to each row of the main table of data in PunchClock. This lets you go back after the fact and modify the times or other details for a record that has been saved. This was a true life-saver for me in practice as you often forget to start the timer at the right time, or want to put clarifying comments in later, etc. I implemented this with a click-able SWT button on every row with a wrench style icon.
Clicking on that button brings up a simple form in a dialog for editing the data in that row. Since I couldn't find an example that was exactly like this, I came up with an approach, still not sure if this is the most efficient way to do it. Here is how this was accomplished.

Using TableEditor to add the Buttons
I started from Snippet126 from the Eclipse SWT snippets site: "Table example snippet: place arbitrary controls in a table".

Using a class called org.eclipse.swt.custom.TableEditor which you construct with your Table, you specify a new control and place it against a particular TableItem in that Table, and even specify which column that control should be over. One way to picture this is that the TableEditor as floating above the Table as an invisible layer which you can put controls on that overlap your Table.

For example in my case, where table is an instance of org.eclipse.swt.widgets.Table


//get all the current items (rows) from your SWT table
TableItem [] items = table.getItems ();
for (int i=0; i<items.length; i++) {

//create the editor
TableEditor editor = new TableEditor(table);

//get the row
TableItem item = items[i];
//create my button
Button button = new Button (table, SWT.PUSH);
//my code to set the button icon image from an JFace ImageRegistry
button.setImage(Resources.getImageRegistry().get(Resources.IMAGES_EDIT_PNG));
button.setSize(16, 16);
button.setToolTipText("Fix this session");
button.pack();

//not sure if necessary, prevent the editor from being smaller than button
editor.minimumWidth = button.getSize ().x;
editor.horizontalAlignment = SWT.RIGHT;
//set the button to float over column 5 for this item
editor.setEditor (button, item, 5);
}


And that is it for the set up. Note regarding the JFace ImageRegistry, I have begun to use an excellent tutorial/article called Using the Eclipse GUI outside the Eclipse Workbench which has three parts. Part 2: Using the JFace image registry, describes the approach to creating an org.eclipse.jface.resource.ImageRegistry that is then referred to whenever you need to display the same image repeatedly in the UI, as I do in the case for the little wrench icon.

Handling Button Clicks
While the above code drops the buttons on the tables, I need to then hook them up to display the edit dialog. This is done through adding a Selection Listener to the button being added to each row.

Again, I am not sure if this is the greatest way to implement this code, but I created a class called EditButtonListener which implemented the org.eclipse.swt.widgets.Listener interface, specifically calling my new dialog from the handleEvent() method. Something like this (with my form logic simplified to pseudo code).


public class EditButtonListener implements Listener {

private TableItem _tableItem;

/**
* @param tableItem - dependency injection, keeps track of the row
*/
public EditButtonListener(TableItem tableItem) {
_tableItem = tableItem;
}

/* (non-Javadoc)
* @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
*/
@Override
public void handleEvent(Event event) {
//get the parent shell for my table, needed to launch my new SWT dialog
Shell lShell = _tableItem.getParent().getShell();
//in my table the first column is a unique id
String sessionIdString = _tableItem.getText(0);
System.out.println("Button click for session id: "+sessionIdString);

final TimeSession selectedSession;
try{
//retrieve the selected time session from the back end
//...
}catch(Exception e){
throw new IllegalStateException(e);
}

// create new dialog where user enters the project name
final Shell dialog = new Shell(lShell, SWT.DIALOG_TRIM
| SWT.APPLICATION_MODAL);
dialog.setText("Fix this session");
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = 10;
formLayout.marginHeight = 10;
formLayout.spacing = 10;
dialog.setLayout(formLayout);
// position near parent window location
dialog.setLocation(lShell.getLocation().x + 10,
lShell.getLocation().y + 10);
dialog.setSize(400, 400);
// text displayed in dialog i.e. field labels
//...

// create combo box drop down selection
//final Combo combo = new Combo(dialog, SWT.NONE);
//combo.setItems (options);
//set current value to selected session's value
//...
// text displayed in dialog i.e. field labels
//...
//next text box field
//final Text startTimeBox = new Text(dialog, SWT.SINGLE | SWTSWT.BORDER );
//...
//etc...

//create cancel button
//Button cancel = new Button(dialog, SWT.PUSH);
//cancel.setText("Cancel");
//layout stuff...
//add listener for when cancel is pressed:
//cancel.addSelectionListener(new SelectionAdapter() {
// public void widgetSelected(SelectionEvent e) {
// System.out.println("User cancelled dialog");
// dialog.close();
// }
//});

//creates ok button
//Button ok = new Button(dialog, SWT.PUSH);
//ok.setText("OK");
//layout stuff...
//add listener when OK button pressed
//ok.addSelectionListener(
// nested anonymous inner class for listener, could be separate class too
//new SelectionAdapter() {

/*
* (non-Javadoc)
*
* @see org.eclipse.swt.events.SelectionAdapter
* #widgetSelected (org.eclipse.swt.events.SelectionEvent)
*/
//public void widgetSelected(SelectionEvent e) {

//when OK is pressed save the current changes to the backend
//...

// close the message dialog
//dialog.close();

//}

//});

//finish set up of dialog and call open()
//...
//dialog.setDefaultButton(ok);
//dialog.pack();
//dialog.open();
}

}



To link the EditButtonListener back to the button I created above you would modify the button creation above slightly to include adding the Listener:

button.addListener(SWT.Selection, new EditButtonListener(item));

Now when clicked the form pops up



Improvements
One way that I would like to try to improve on this design is to be able to reuse the same EditButtonListener, so instead of creating a new listener instance for each TableEditor button, I would reuse the same instance and it would determine which button was pressed from the event.item passed in to handleEvent(). I also want to remove all the dialog code from the EditButtonListener and implement that using a JFace dialog in its own class.

Sunday, May 15, 2011

Giant Sequoia, Dawn Redwood in downtown Boston

Recently had a chance to spend an afternoon with family in Boston Public Gardens. I recently read online that there was a Giant Sequoia (Sequoiadendron giganteum) growing in the Public Gardens. I have lived in the region for a long time, and never had any idea.

After walking in the park, keeping a lookout at the various conifer trees, dodging the crowds of tourists on a chilly Spring day we were surprised to first come across a Dawn Redwood (Metasequoia glyptostroboides), a relative of the Sequoia and Redwoods native to China. Close up the needles are tightly packed and arranged flatly, almost giving the appearance of a broadleaf. I don't think I have ever seen a Dawn Redwood, it was probably 4' in diameter, hard to give a good height, maybe 50' tall. There was a faded, old, plaque identifying the tree. The tree is located on the Arlington St. side of the swan boats pond, North of the George Washington statue along a path.

A little further around the North side of the pond we found the Giant Sequoia. It was a spotted red with a very fibrous bark that looked like bleached mulch. From a distance it didn't look like a normal pine or spruce, so in that sense it stood out, it looked a bit sparser and irregular, without much of conical shape.

Of course we hung around to take some pictures. This is the first sequoia I've seen outside of California in person, and it was good to confirm that they do grow outdoors out here. However, the "giant sequoia", or Sequoiadendron are not to be confused with the Coastal Redwood which I have been trying to grow here indoors. I have never seen anywhere that the Coastal Redwood, which are adapted to the foggy Pacific coastline, can survive our winters. The Sequoiadendron is native to the Sierra Nevada mountains, so it can tolerate cold better. The Dawn Sequoia, being deciduous also apparently can grow here in this climate zone.

Up close I was amazed by how spikey the branches and needles were, it wasn't like my redwood seadlings which have fairly smooth bark on the branches with softer needles. The sequoia's branches were much denser with pretty short, sharp and stiff needles. There were a few fallen twigs around and we were able to get a good whiff of the tree's odor, which smelled nice, like a Christmas tree or wreath. It is amazing these are growing right in the center of city like this.

Later on I was browsing around various sites trying to find some more data on these trees, the Public Garden website had zero information and I haven't found anything else official about them. I came across a crowd-sourced site iNaturalist.org where users post pictures of wildlife and try to identify them. A user has posted a number of trees from the Public Garden. Apparently there are two Dawn Redwoods, as well as the one Giant Sequoia. There is a project dedicated to people making observations of "Redwoods", including the Sequoia and Dawn Redwood species, it is called RedwoodWatch organized by the Save the Redwoods League who aim to document the "in what climates redwoods can survive and track the redwood forests' migration over time.". I like the idea of the site and hope to contribute some of my own observations some day. However, at this point, not sure what merits being "observed". Also while interesting that there are Redwood tree species growing here, it is a somewhat artificial environment, I am sure there is a lot of care given to those trees in Public Gardens or in the nearby Arnold Arboretum.


Saturday, May 14, 2011

Punch Clock new release

This is a cross-post from the PunchClockSWT Project Updates. Version 0.2.0 of PunchClock has now been posted.

Major changes:

  • "Fix this row" button on every row, which brings up a dialog to edit the fields for that row and save them.
  • All updates to rows are now audited in a table. This table can currently be dumped to the console through Options > Audit menu item.
  • Rounding errors in the Elapsed time calculation have been fixed. Now 5 digits of precision and a max of two digits after the decimal place.
I learned a few new things in this process. For the fix button I involved more SWT widgets such as TableEditor and explored further the FormLayout options to make a custom dialog for manually inputing data.

On the Derby side, I created additional tables, and had a chance to implement some database Triggers, which was new.

I may write up some of the details of the techniques I used.

Sunday, April 10, 2011

 when Reading a text file in Java

If you have code that processes text files using InputStreamReader, you may be puzzled why there are certain garbage characters  at the start of your resulting String data if you output that the contents of the file.

This is due to a Reader processing your input file in ASCII encoding when the data is stored in UTF-8.

While I came across this in Java, the ASCII/UTF-8 solution was actually in this aptly named blog post "Three little characters  designed to make your life hell" by Martyn at the Ventrino Blog.

The solution proposed in the post is basically "if your text file is saved as UTF-8, that is the problem, save as ASCII encoding instead". I think this isn't really a best practice, probably as UTF-8 is better for internationalization, the developer should probably change his/her code to support that format rather than restrict a program to the limited set of US/Western ASCII characters.

Here is an example of code that when reading a UTF-8 encoded file, say a .HTML file will display the 

//stores the html text, in my case I needed to pass it in to an SWT Browser.setText() method.
StringBuffer buffer = new StringBuffer();
//read the HTML to display from a resource
InputStream htmlInStream = Resources.getResourceAsStream(Resources.HTML_ABOUT_HTML);

BufferedReader bufInpStream = new BufferedReader(new InputStreamReader(htmlInStream));
String line = "";

while(line != null){
line = bufInpStream.readLine();
//System.out.println(line);
if(line!= null){
buffer.append(line);
}
}


The key seems to be the InputStreamReader conversion of the underlying InputStream to the HTML file. Readers are by design for processing text, while Streams are more concerned with binary data. So when converting from the Stream, we have to tell it what encoding to use. This correction will solve the problem.

//if we didn't specify char-encoding as UTF-8, it would show these strange chars: 
BufferedReader bufInpStream = new BufferedReader(new InputStreamReader(htmlInStream,"UTF-8"));


Punch Clock has gone live

I have wrapped up development of a beta version of my side-project "Punch Clock". I've created a launch page on Google Sites, and linked from the side bar.

https://sites.google.com/site/punchclockswt/

The released version is basically a public beta, free for anyone to download. Right now I support Windows and Linux.

The feature set is rudimentary but I am adding features as I have time. It has been a good project to learn the ins and outs of SWT for a basic app. I would like to explore refactoring more the UI to use more of the JFace patterns on top of SWT, I was just beginning to use this with the About dialog and the persistent settings modules. From the beginning this was a learning project, where I picked up Apache Derby, SWT, and created a build process in ANT, launched an entire release site with actual documentation, specified a license for the work etc...

More to follow I am sure.

Saturday, April 9, 2011

Seedling update

"J2"


Our Redwood seedlings have survived the long dark New England winter and are starting to grow new shoots and widen their branches. Of the two J2 seems to have done a little better, on B2 there are some needles turning brown on an upper branch. The crown area of J2 has filled out better. Supposedly redwood seedlings can grow several feet per year, but we haven't seen growth like that yet. It could be the indoors, the pots, or even the lower levels of sunlight during our winters here. To make measuring easier I printed off some some color square rules, one inch squares and taped it to a wall as a background. As you can see the heights are about 15" for J2 and around 12" for B2, which has more of a curve. The length of the lower branches is really amazing now, the longest I've measured is around 9" and each of those has several 3-4" offshoots


"B2"
I was partly inspired to write this after watching a great National Geographic documentary Climbing Redwood Giants (2009) on Netflix. The quality was great in HD, seeing the fully grown giants was impressive. The two main focuses of the documentary were researcher Steve Sillett who using a crossbow(!), ropes and pulleys pulls himself up the giants in order to climb into the canopy and measure them. The other story a pair of researches, Micheal Fay and Lindsey Holm, transecting the known extent of the Coastal Redwood range. While a big focus was on trumpeting successes in stopping old-growth logging of Redwoods and conservation, the sheer size of the trees was the big show. I have had the opportunity to see redwoods in Muir Woods, but nothing like the 350 foot giants in the movie.

The trees ecosystem supposedly supports more biomass than any other ecosystem on Earth, including the tropical rain forests. It was interesting to see the mulberry bushes and other plants growing from the branches of some of the trees, hundreds of feet up. Another star was the Wandering Salamander that may spend its life in the tree canopy. They didn't really mention much about birds or insects nesting in the tree, which I would have assumed to be a big part of the ecosystem, although the tannins in the Redwood bark are supposed to deter insects.


Finally here are a few more pictures of the seedlings, and some of their new growths.
 
"B2" new growth shoot
Another shot of both trees.
Two's company



Sunday, April 3, 2011

Collapsible SWT Text Area Snippet

A little sample code showing how you can have a Java SWT button that can collapse other Controls like a toggle switch. This also will show how to resize the container after "collapsing" your control.

I went this route after not finding the SWT ExpandBar widget suiting this purpose.

Screenshots from Windows 7

Source Code

/*
*
*/
package swt.snippet;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.FontMetrics;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import com.brianl.timetrack.controller.TimeSession;
import com.brianl.timetrack.view.CollapseButtonListener;

/**
* Simple SWT Shell that contains a Group with some controls. An arrow button is
* used to toggle the Text area widget as collapsed or not.
*
* @author ammianus http://librixxxi.blogspot.com/
*
*/
public class CollapsibleTextBox {

private static final int NUMBER_GRID_COLUMNS = 1;

private Display _display;

private Shell _shell;

CollapsibleTextBox() {
_display = new Display();
_shell = new Shell(_display);
_shell.setSize(300, 250);
// Collapsible Group
_shell.setText("Collapsible Group Example");
// format shell as single column grid layout
_shell.setLayout(new GridLayout(NUMBER_GRID_COLUMNS, true));

// create the group
Group collapseGroup = new Group(_shell, SWT.NONE);
GridData groupGrid = new GridData(SWT.TOP, SWT.LEFT, false, false);
groupGrid.horizontalSpan = 1;
collapseGroup.setLayoutData(groupGrid);
collapseGroup.setText("Control Group");

// create a Label and Button inside the Group
GridData labelGridData = new GridData(GridData.VERTICAL_ALIGN_END);
labelGridData.horizontalSpan = 1;
String labelText = "Pressing button toggles Text. ";
final Label instructionLabel = new Label(collapseGroup, SWT.NONE);
instructionLabel.setText(labelText);
instructionLabel.setLayoutData(labelGridData);
instructionLabel.pack();

final Button collapseButton = new Button(collapseGroup, SWT.ARROW
| SWT.UP);

// multi-row Text area with word-wrap
final Text textArea = new Text(collapseGroup, SWT.MULTI | SWT.LEAD
| SWT.BORDER | SWT.WRAP);

// set height and width of Text area
GC gc = new GC(textArea);
FontMetrics fm = gc.getFontMetrics();
final int textBoxWidth = 50 * fm.getAverageCharWidth();
final int textBoxHeight = 4 * fm.getHeight();
gc.dispose();
textArea.setSize(textArea.computeSize(textBoxWidth, textBoxHeight));
GridData textBoxGrid = new GridData(SWT.TOP, SWT.LEFT, false, false);
textBoxGrid.horizontalSpan = NUMBER_GRID_COLUMNS;
textBoxGrid.heightHint = textBoxHeight;
textBoxGrid.widthHint = textBoxWidth;
textArea.setLayoutData(textBoxGrid);

// set the layout for the items contained by the Group as a two column
// grid
collapseGroup.setLayout(new GridLayout(2, false));
collapseGroup.layout(true);

// create a listener that waits for button press
collapseButton.addListener(SWT.Selection, new CollapseButtonListener(
textArea, textBoxWidth, textBoxHeight, collapseGroup,
textBoxGrid));

// open the shell and run UI loop
_shell.pack();
_shell.open();
while (!_shell.isDisposed()) {
if (!_display.readAndDispatch())
_display.sleep();
}
_display.dispose();
}

/**
* Runs the demo
*
* @param args
*/
public static void main(String[] args) {
new CollapsibleTextBox();
}

/**
* inner class handles button click events for arrow button
*
*/
public class CollapseButtonListener implements Listener {

private Text _timeNotesBox;
private int _textBoxHeight;
private int _textBoxWidth;
private Group _container;
private GridData _textBoxGrid;

/**
* @param timeNotesBox
* @param textBoxHeight
* @param textBoxWidth
* @param container
* @param textBoxGrid
*/
public CollapseButtonListener(Text timeNotesBox, int textBoxWidth,
int textBoxHeight, Group container, GridData textBoxGrid) {
super();
// save references to the various controls to update
this._timeNotesBox = timeNotesBox;
this._textBoxHeight = textBoxHeight;
this._textBoxWidth = textBoxWidth;
this._container = container;
this._textBoxGrid = textBoxGrid;
}

/*
* (non-Javadoc)
*
* @see
* org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets
* .Event)
*/
@Override
public void handleEvent(Event event) {
// toggles the Text Area as visible or not.
// When Text Area is collapsed, resize the parent group
if (_timeNotesBox.getVisible()) {
// collapse the text area
_timeNotesBox.setSize(_timeNotesBox.computeSize(1, 1));
_textBoxGrid.heightHint = 1;
_textBoxGrid.widthHint = 1;
_timeNotesBox.setLayoutData(_textBoxGrid);
_timeNotesBox.setVisible(false);
_timeNotesBox.pack(true);
System.out.println("Hiding textbox");
} else {
// expand text area back to original sizing
_timeNotesBox.setSize(_timeNotesBox.computeSize(_textBoxWidth,
_textBoxHeight));
_textBoxGrid.heightHint = _textBoxHeight;
_textBoxGrid.widthHint = _textBoxWidth;
_timeNotesBox.setLayoutData(_textBoxGrid);
_timeNotesBox.setVisible(true);
_timeNotesBox.pack(true);
System.out.println("Showing textbox");
}

// in this case the container is the Group
_container.pack(true);

// resize the parent shell too
_container.getParent().pack(true);
}

}
}


Built with:
swt-3.6.1-win32-win32-x86
Java 1.6.0_17
Eclipse 3.4.1

Built on the model of the snippets from java2s and the SWT snippets site.

I came up with this approach as I am trying to have an optional text box in my "Time Track" program. I really didn't see any other way to have this kind of dynamic visual behavior that is pretty common on websites these days. The only prebuilt widget that seemed similar was the ExpandBar, but what that did was create a large pane with expandable widgets within it. These all had a very non-native look and feel and was bit complex to set up when I had a single text box to expand/collapse.