Bluish Coder

Programming Languages, Martials Arts and Computers. The Weblog of Chris Double.


Cells style gadget updating in Factor

Factor has a Cells like mechanism for propogating changes in models to their GUI representation (called Gadgets). It's like a lightweight functional reactive programming system. Using the latest darcs Factor code, which includes a Calendar library, you can quite easily get a gadget displaying with a dynamically updated date.

To have a gadget dynamically updated it must reference a 'model' which wraps the value to be displayed. Whenever the data wrapped by the model is changed, the gadget displaying it automatically updates.

In this example I create a global value called 'time' that holds a model wrapping the current date and time:

SYMBOL: time
f <model> time set-global

The model here wraps the value 'f' which is false indicating no value currently set. To have the value change regularly I start a background thread which sets the value every second:

: update-time ( -- )
  now time get set-model 1000 sleep update-time ;

[ update-time ] in-thread

The 'update-time' words gets the current date and time (using 'now') and sets the model's value to it. It does this every 1,000 milliseconds.

We can confirm that this value is updating by doing a 'get' of the 'time' variable and see that it changes between calls:

time get model-value . 
  => T{ timestamp f 2006 8 7 12 52 8.98 -12 }

time get model-value . 
  => T{ timestamp f 2006 8 7 12 52 49.14 -12 }

A label gadget that displays this value, and is updated as it changes, can be created and displayed with:

time get [ timestamp>http-string ] <filter> <label-control> gadget.

The <filter> object takes a model (retrieved with 'time get') and quotation that it will call on the model when its value changes to get a string to display. In this case I'm using the calendar libraries 'timestamp>http-string' word to convert the timestamp held by the model into a string representation. A label gadget is created using this filter as the displayed text.

The 'gadget.' word is what displays the gadget in the GUI. There should appear a date that is updated every second. You can display multiple gadgets on the same model, scroll the window, etc and it will be updated. You can see a screenshot here. You'll have to imagine the seconds value in the screenshot updating every second!


This site is accessable over tor as hidden service 6vp5u25g4izec5c37wv52skvecikld6kysvsivnl6sdg6q7wy25lixad.onion, or Freenet using key: