Tutorials

Hello, World!

The GUI version of the 'Hello, World!' program:

ui = require "tek.ui"
ui.Application:new
{
  Children =
  {
    ui.Window:new
    {
      Title = "Hello",
      Children =
      {
        ui.Text:new
        {
          Text = "Hello, World!",
          Class = "button",
          Mode = "button",
        }
      }
    }
  }
}:run()

As can be seen, tekUI allows a fully functional application to be written in a single nested expression. The UI library comes with an on-demand class loader, so whenever a class (like Application, Window or Text) is accessed for the first time, it will be loaded from tek/ui/class/ in the file system.

Note that a button class is not strictly needed: a button is just a Text element behaving like a button with a frame giving it the appearance of a button. We will later explain how you can write a button class yourself, to save you some typing.

To quit, click the window's close button. Closing the Application's last open window will cause the run method to return to its caller.

Reacting on input

There are different ways for reacting to presses on the 'Hello, World' button. The simplest form is to place an onClick function into the Text object:

ui = require "tek.ui"
ui.Application:new
{
  Children =
  {
    ui.Window:new
    {
      Title = "Hello",
      Children =
      {
        ui.Text:new
        {
          Text = "Hello, World!",
          Class = "button",
          Mode = "button",
          onClick = function(self)
            print "Hello, World!"
          end
        }
      }
    }
  }
}:run()

But onClick is just a convenient shortcut for the most trivial of all cases. To catch more events, you can override handler functions which react on changes to an element's state variables, like Pressed and Selected, to name but a few. They contain booleans and are indicative of the Element's state, such as: Is it in selected state, is it pressed down, is it hovered by the mouse, is it receiving the input? The onPress handler receives the current state of the Pressed variable as an argument, so it can be used to catch not only releases, but also presses of the mouse button:

ui = require "tek.ui"
ui.Application:new
{
  Children =
  {
    ui.Window:new
    {
      Title = "Hello",
      Children =
      {
        ui.Text:new
        {
          Text = "Hello, World!",
          Class = "button",
          Mode = "button",
          onPress = function(self, pressed)
            ui.Text.onPress(self, pressed)
            print("Pressed:", pressed)
          end
        }
      }
    }
  }
}:run()

When you overwrite a handler, you should forward the call to the original implementation of the same method, as seen in the example.

For regular applications it is normally sufficient to stick to overwriting the available handlers as in the previous example. But the underlying mechanism to register a notification handler can be interesting as well, especially if you plan on writing new GUI classes yourself:

ui = require "tek.ui"
app = ui.Application:new()
win = ui.Window:new { Title = "Hello", HideOnEscape = true }
text = ui.Text:new {
  KeyCode = true,
  Text = "_Hello, World!",
  Class = "button",
  Mode = "button"
}
text:addNotify("Pressed", false, {
  ui.NOTIFY_SELF,
  ui.NOTIFY_FUNCTION,
  function(self)
    print "Hello, World!"
  end
})
win:addMember(text)
app:addMember(win)
app:run()

In this example we have also set the HideOnEscape attribute for the application to quit on pressing the Escape key, and the KeyCode attribute, so that a shortcut for the element is created by placing an underscore in front of a letter in its caption.

See also Object:addNotify for all the hairy details on notification handlers, and the Area and Widget classes for the most important state variables.

List of predefined handlers

Name Base Class Cause
Widget:onActivate() Widget change of the Active attribute¹
Window:onChangeStatus() Window change of Status attribute¹
Widget:onClick() Widget caused when Pressed changes to false¹
Widget:onDisable() Widget change of the Disabled attribute¹
Widget:onDblClick() Widget change of the DblClick attribute¹
TextInput:onEnter() TextInput change of Enter attribute¹
Widget:onFocus() Widget change of the Focus attribute¹
Window:onHide() Window window close button, Escape key
Widget:onHilite() Widget change of the Hilite attribute¹
Widget:onHold() Widget change of the Hold attribute¹
Widget:onHover() Widget change of the Hover attribute¹
Widget:onPress() Widget change of the Pressed attribute¹
Widget:onSelect() Widget change of the Selected attribute¹
DirList:onSelectEntry() DirList item selected by the user
Lister:onSelectLine() Lister change of the SelectedLine attribute¹
PopList:onSelectLine() PopList change of the SelectedLine attribute¹
Canvas:onSetChild() Canvas change of the Child attribute¹
Element:onSetClass() Element change of the Class attribute¹
Lister:onSetCursor() Lister change of the CursorLine attribute¹
Numeric:onSetMax() Numeric change of the Max attribute¹
Numeric:onSetMin() Numeric change of the Min attribute¹
PageGroup:onSetPageNumber() PageGroup change of the PageNumber attribute¹
Slider:onSetRange() Slider change of the Range attribute¹
Element:onSetStyle() Element change of the Style attribute¹
Text:onSetText() Text change of Text attribute¹
FloatText:onSetText() FloatText change of Text attribute¹
Numeric:onSetValue() Numeric change of the Value attribute¹

¹ using Object:setValue() and the notification mechanism

Ad-hoc setup of classes

To inherit properties and functionality from existing classes and to reuse existing code consequently, it is often desirable to create new classes yourself. There are different scopes in which new classes can be useful:

  • Global classes are written as separate source files, located in the system-wide installation path under tek/ui/class and set up using a procedure as described in the class setup section.
  • Application classes are created in the same way, but they are located in tek/ui/class relative to the application's local program directory.
  • Another scope is inside a running application or module. We call this the ad-hoc style, because new classes are often created out of a spontaneous need.

For the ad-hoc style, it is not necessary to create a new source file or module. For example, a Button class can be derived from the Text class whereever you see fit:

local Button = ui.Text:newClass { _NAME = "_button" }

ad-hoc classes may be named arbitrarily, but their names should be prefixed with an underscore to distinguish them from global classes. You can even do without a name, as tekUI will create one for you if necessary (but you will find it difficult to reference such a class in a style sheet).

From this point, the new class can be extended, e.g. for initializations which turn a Text into a Button:

function Button.init(self)
  self.Class = "button"
  self.Mode = self.Mode or "button"
  self.KeyCode = true
  return ui.Text.init(self)
end

As shown in the example, we also passed the call on to our super class, which we expect to perform the missing initializations.

Finally, a new object from our new class can be created:

button = Button:new { Text = "_Hello, World!" }

Also refer to the Class reference and the Class setup section for further information.


The lifecycle of an element

A GUI element is set up in several stages, all of which are initiated by the tekUI framework. Normally, you do not call any of these methods yourself (aside from passing a call on to the same method in your super class):

Drawing an element

In the drawing method, the control flow is roughly as follows:

function ElementClass:draw()
  if SuperClass.draw(self) then
    -- your rendering here
    return true
  end
end

There are rare cases in which a class modifies the drawing context, e.g. by setting a coordinate displacement. Such modifications must be performed in Area:drawBegin() and reverted in Area:drawEnd(), and the control flow looks like this:

function ElementClass:draw()
  if SuperClass.draw(self) then
    if self:drawBegin() then
      -- your rendering here
      self:drawEnd()
    end
    return true
  end
end

Debug library

The debug library used throughout tekUI is tek.lib.debug. The default debug level is 10 (ERROR). To increase verbosity, set level to a lower value, either by modifying tek/lib/debug.lua, or by setting it after including the module:

db = require "tek.lib.debug"
db.level = db.INFO

See also the module's documentation for redirecting the output.

Proxied object model

If you plan on extending existing classes or develop your own, you are advised to set the following configurable parameters in tek.class, the base class of all tekUI classes:

local PROXY = true
local DEBUG = true

The PROXY option allows for intercepting read/write accesses to objects, which will be harnessed by the DEBUG option for tracking accesses to uninitialized class members. So whenever a nil value is read from or written to an object, this causes tek.class to bail out with an error and a meaningful message.

As a result, all member variables must be initialized during new() or init() – or more specifically, before the class metatable is attached and an object is becoming fully functional. This will assist in keeping variables neatly together, and you won't end up in a fluff of variables of limited scope and significance, getting initialized at random places. This also means that you cannot assign a distinct meaning to nil for a class member – you will have to use false instead, or find another arrangement. (This convention of not using nil for class variables is found throughout the whole tekUI framework.)

Once your application is tested and ready for deployment, you can disable PROXY, as this will improve performance and reduce memory consumption.

Class setup

A class is usually set up in a prologue like this:

local Widget = require "tek.ui.class.widget"
module("tek.ui.class.button", tek.ui.class.widget)
_VERSION = "Button Widget 1.0"
local Button = _M

The second argument to module is the super class to derive the new class from (see also tek.class for details on how this is supposed to work). By convention, we then put the module table (the class) into a local variable.

Finally, methods in the newly created class may look like this (note that, thanks to the Button variable, the second example provides an implicit self):

function Button.new(class, self)
  ...
  return Widget.new(class, self)
end

function Button:method()
  ...
  Widget.method(self)
end

Also, don't forget to add a _VERSION variable, as it will be used by the documentation system – see also the next section.

Class documentation system

Don't stray off too far from the class setup described in the previous section, as it contains valuable informations for tekUI's documentation generator.

Most notably, the second argument to module should be written out in full – in the example above, one might be tempted to use Widget instead of tek.ui.class.widget; but then, the path information would be lost for the source code parser, which tries to assemble a self-contained class hierarchy from individual class / child class relations.

Tokens for markup

Aside from the aforementioned module and _VERSION keys (see section Class setup), the source code parser reacts on the following tokens.

Long lines of dashes signify the beginnings and endings of comment blocks that are subject to processing markup notation, e.g.

----------------------------------------------------------------
--  OVERVIEW::
--    Area - implements margins, layouting and drawing
----------------------------------------------------------------

The other condition that must be met for the following text to appear in the documentation is the recognition of either a definition (as seen in the example) or function marker inside such a comment block. The template for a definition is this:

DEFINITION::

And the function template:

ret1, ret2, ... = function(arg1, arg2, ...): ...

The marker and the following text will then become part of the documentation. (In other words, by avoiding these markers, it is also possible to write comment blocks that do not show up in the documentation.)

Functions inside classes will automatically receive a symbolic name as their class prefix (from assigning the module table _M to a local variable, see Class setup). Hereinafter, they can be cross-referenced using the following notations:

Class:function()
Class.function()

For further information, consult the sources in the class hierarchy as examples, and the source code containing the markup notation reference, which can be found in tek.class.markup.