Saturday, March 24, 2007

Documenting user interfaces the smart way

One thing that was always painful with jEdit was keeping the code and documentation in sync. For example, take keyboard shortcuts. For every command that I documented, I would manually enter the shortcut in the documentation, and before every release, I'd have to go through documentation by hand and ensure the shortcuts were up to date. Extremely tedious busy-work. At the time, I wasn't smart enough to understand what Emacs really meant by "self-documenting", but now that I've been exposed to more development tools and language paradigms, I'm starting to come around.

For a while now the Factor UI has had "commands", which are a concept found in many other UI toolkits, as well as jEdit, Emacs, etc. A command is an abstraction over an operation which can be performed by the user, and is often associated with a keyboard shortcut, can be added to toolbars and menus, and so on. in Factor 0.89, I refactored things so that commands are just words with some properties set.

Consider the article on the UI walker. For a long time now, the shortcut/command table there is automatically generated, with a markup element which refers to a command map by name, like the following:
{ $commands walker-gadget "toolbar" }
However the keyboard shortcut "C+A+w" is hard-coded there, and in fact as of Factor 0.88, it is out of date; it is just "C+w" now. The problem was that while command maps were "well-known" and were easy to identify by name, commands were not, they were just tuples floating around in hashtables (with no obvious "primary key" for you database people). Now that commands are words, I defined a new markup element which is rendered as the shortcut associated to a given command in a specific command map. For example,
{ $command interactor "quotation" walk }
The result looks exactly the same, but it is kept up to date when command maps change.

This is just the beginning. I want the Factor UI to feel like an extension of the language. This quality is hard to put in words, but perhaps CLIM comes closest to achieving this goal.

Wednesday, March 21, 2007

New inspector

There is a new inspector tool in the UI which can edit slot values now.

It is useful for debugging, as well as prototyping -- you can build a very ad-hoc GUI this way.

For example, consider the following interactive session:

We set variable to a hashtable holding prices of various foodstuffs, then we define a word which takes a list of foodstuffs, computes the total cost, and prints it.

Unfortunately, the price of sausages has gone up, so the prices have to be adjusted accordingly. No problem. First, print out the hashtable holding the prices; when printed it becomes a clickable presentation:

Now, click it, which opens the inspector tool. The ellipsis to the left of every slot is a button which opens the slot editor:

Here we are in the slot editor:

After clicking 'Commit' and returning to the listener, we see the price has gone up:

The inspector can edit sequences, tuples, strings... you can also input complex structures (the slot editor text area is parsed in the parser, it can take a lot more than just numbers).

One limitation is that so far you cannot add new elements to objects which allow that (eg, hashtables, resizable sequences). However the listener-based inspector supports this feature now, and it won't be long before the UI inspector does too.

Mmmmm, hot dogs.

Number of unit tests

The Factor core consists of 34,000 lines of Factor code. The test suite used to test the core is just a dozen or so unit tests shy of 2000. I don't know if this is considered enough tests or not, but it sure seems like a lot. Lately I've been working on the UI and trying to unit test every new feature and fix I apply. This is a bit difficult and has required some refactoring, but I think it is worth it.

Thursday, March 15, 2007

Improved unit testing framework

I noticed a time-waster in my workflow recently. After making changes to code, I run unit tests. The old test framework would run all tests, collecting errors, printing a report at the end. However this report was not granular enough. It would only print which file failed and what the error was, not the specific test that failed. And there was no way to get a traceback after the fact. So I would often invoke test-modules, wait for the tests to finish, look at the report of failed files, and run each one individually to see what test failed, and where it failed, by using :c.

The situation is better now. More detailed information is collected at the end of a test run -- here I intentionally broke the ^ word to return incorrect results, it throws an error when the exponent is zero, otherwise always returns 3:

Now I click "Traceback", which is a presentation of a continuation. The UI presents the continuation in a window:

The code to display a continuation in this manner was taken from the UI single stepper tool. It is a generic gadget now, used by both the single stepper and for presenting continuations.

The best part? The entire unit test framework is 59 lines of code. The gadget to present a continuation (keep in mind this gadget is reusable) is 31 lines. So in total, it only takes 90 lines of code to build a useful unit testing tool in Factor.

Despite the small size, I can't think of many ways I could improve it. Some unit test frameworks out there can generate fancy HTML reports, but if I wanted that, all I have to do is HTTP server module and wrapping the call to test-modules in with-html-stream. Then I'd get clickable links for browsing word definitions in the output.

Tuesday, March 13, 2007

Topological sort

Today I had to implement a topological sort for arrays of classes under the partial order of class inclusion. Since the arrays in question are never large I used a rather naive algorithm. I think it looks nice:

: largest-class ( seq -- n elt )
dup [ swap [ class< ] subset-with length 1 = ] find-with ;

: (sort-classes) ( vec -- )
dup empty?
[ drop ]
[ dup largest-class , over delete-nth (sort-classes) ] if ;

: sort-classes ( seq -- newseq )
[ >vector (sort-classes) ] { } make ;

The first word takes a sequence and finds a class which is only a subclass of itself. Such a class always exists, since classes form a lattice.

The second word is the main iterative loop here. It repeatedly removes the largest class and tucks it away by calling , - then deletes it from the sequence. The recursion stops when the sequence is empty.

The last word does the setup and teardown for the algorithm. It copies the input sequence into a fresh mutable vector, and wraps the whole thing in a make so that objects passed to , are collected into a new sequence which is returned at the end.

Multimedia library bindings

Adam Wendt is working on a binding to libMAD, an MP3 decoder. He is also working on a library to parse ID3 tags. Chris Double is working on Ogg Vorbis and Ogg Theora bindings. Cool stuff.

Prettier prettyprinting

So what have I been working on for the last few days? The prettyprinter, which is invoked any time you use a word such as . or see.

This concept does not even exist in many languages, but it is central to Factor. The idea is that given an object, you can print it in a form which can then be parsed back in. Doing this is easy enough. The hard part is formatting the result nicely so that it is useful for human as well as machine consumption.

The prettyprinter is still not as good as a human programmer, but my goal is to make it as close as possible -- when the structure editor is implemented, it will use the prettyprinter to display the definitions being edited. There are more improvements I plan on making, but at some point any the only word definitions which are still formatted badly will be the longer ones, and they can be factored and cleaned up.

Now I will describe some of the improvements I have made.

Keeping quotations together
A very common idiom is to push a pair of quotations and then pass them to a combinator, for example if. The old prettyprinter didn't do anything special in this case, it would just insert line breaks wherever it had to so that the whole thing would fit within the margin:
IN: sequences : head? ( seq begin -- ? ) 
2dup [ length ] 2apply < [ 2drop f ]
[ [ length head-slice ] keep sequence= ] if ;

Now it tries to avoid leaving a quotation at the end of the line:
IN: sequences
: head? ( seq begin -- ? )
2dup [ length ] 2apply <
[ 2drop f ] [ [ length head-slice ] keep sequence= ] if ;


Grouping lines by stack flow
While well-factored definitions tend to be short, sometimes a longer one crops up. This happens often in the compiler backend, where you have words which emit a series of assembly instructions, with no good way of splitting this up into several words. The old prettyprinter would turn everything into a big soup:
\ (%dispatch) see
IN: generator : (%dispatch) ( word-table# -- )
"n" operand dup 1 SRAWI 0 "scratch" operand LOAD32
rc-absolute-ppc-2/2 rel-dispatch "n" operand dup "scratch"
operand ADD "n" operand dup 0 LWZ ;

The new prettyprinter looks at word stack effects and tries to lay things out using a variety of heuristics:
IN: generator
: (%dispatch) ( word-table# -- )
"n" operand dup 1 SRAWI 0 "scratch" operand LOAD32
rc-absolute-ppc-2/2 rel-dispatch
"n" operand dup "scratch" operand ADD
"n" operand dup 0 LWZ ;


Support for C:
The prettyprinter used to display tuple constructors in their internal, expanded form:
IN: parser : <parse-error> ( msg -- error ) 
\ parse-error 6 <tuple> file get over set-parse-error-file
line-number get over set-parse-error-line column-number get
over set-parse-error-col line-text get over
set-parse-error-text [ set-delegate ] keep ;

This confused a few people in the last (what is the <tuple> word? What does that number mean? etc). Now, the prettyprinter knows what is a constructor and displays it properly; also note the improved layout:
IN: parser
C: parse-error ( msg -- error )
file get over set-parse-error-file
line-number get over set-parse-error-line
column-number get over set-parse-error-col
line-text over set-parse-error-text
[ set-delegate ] keep ;


Better display of >r / r>
The prettyprinter now tries to place a block enclosed in >r and r> on one line if possible.

Before:
M: live-search handle-gesture* 
drop over search-gesture dup [
over find-workspace hide-popup >r live-search-list
list-value r> invoke-command f
] [ 2drop t ] if ;

After:
M: live-search handle-gesture*
drop over search-gesture dup [
over find-workspace hide-popup
>r live-search-list list-value r>
invoke-command f
] [ 2drop t ] if ;