GUI User's Manual


Please use the supplied GUI.TPH (Turbo Pascal Help) file for declaration reference.

Content


1. Theory

1.1. What is GUI for?
1.2. How does a GUI application work?
1.3. The GUI units
1.4. Views and ViewGroups
1.5. Canvas and Surfaces
1.6. Bitmaps
1.7. Message types and flow
1.8. Modality, focus and event caption

2. GUI programming

2.1. A minimal application
2.2. Centralized message handling
2.3. View initialization

3. View programming

3.1. Modifying an existing view type
3.2. View messages
3.3. View shapes

4. Driver programming

4.1. Minimal driver requirements
4.2. The driver screen
4.3. The driver canvas
4.4. Driver canvas acceleration
4.5. Acceleration of non-Direct methods
4.6. The driver mouse
4.7. Some thoughts about reentrancy
4.8. The driver timer
4.9. The driver itself

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

1.1. What is GUI for?


The GUI (Graphical User Interface) is designed to provide any type of
application with a professional look and usage behaviour as well as many
benefits for the programmer. It's interface design is similar to use to
Windows and other popular GUIs.

Since GUI is designed to work with a very flexible driver model it can be used
with virtually any existing in- and output libraries (if a driver exists or is
created for that specific library).

Because GUI natively supports many drawing primitives and bitmaps it is able
to handle most or even all types of application where a GUI is needed. Some
applications may be: Modelling, File management, Games, ...

1.2. How does a GUI application work?


A GUI application is in fact only an object that basically provides four
methods to be modified. These are initialisation, finalization, idle handler
and the message handler.

In the initialisation, the application must set up all the views and variables
that will be used at the program start. This usually includes setting up a
menu and maybe some windows; this is also the place to read and process an
initialization file.

The finalization should undo all memory assignments that were done. The GUI
will take care to release all the memory that it has allocated itself and it
will free all components that have been inserted on the screen. The latter
allows the programmer to create components and "forget" about them, that is
the components will generate events when used and they will be freed by the
GUI when the application closes.

The idle handler is the ideal place to do background actions. Note that some
background actions such as a clock will better be handled using a timer. Idle
means that currently no messages are waiting to be processed, so if your
application has lots of messages to handle idle will be called less. It is
suggested to free the time slice of the OS in the idle proc. By doing this
your application will use only very little CPU time in a multitasking
environment when idle.

Depending of the set-up of your application, the application object will
receive messages to be processed. These messages will usually be redirected
commands or broadcasts. For instance, the application should halt when it
receives a cmClose command, no matter if a menu or a button created the event.

It is important to understand that a GUI application is event-driven and
cooperative. The event handler should be as firm as possible to allow the
application to continue working smoothly. This means that the programmer
should avoid using basic CRT features such as ReadKey, ReadLn, KeyPressed or
Delay. In fact, the CRT unit is not needed when writing GUI applications. For
more details on the internal message flow read chapter 1.7.

1.3. The GUI units


The GUI is built out of several units (alphabetically):

BITMAPS:  Provides generic bitmaps with file loader, as well as a bitmap
					canvas. Bitmaps	are described in 1.6.

CANVAS:   Canvas are drawing surfaces. There are different kinds of canvas,
					while some draw on the screen there are also canvas available to
					draw on bitmaps (1.6) and surfaces (1.5). The canvas chapter is 1.5.

DIALOGS:  Pre-defined GUI dialogs. Currently a file selector is available.

ELEMENTS: Pre-defined GUI views. This includes panels, labels, buttons, lists,
					edit fields, checkboxes, comboboxes, scrollboxes, dialogs, windows
					and some more.

EVENTS:   Event declarations and common event codes for event kinds and also
					keyboard messages.

FONTS:    Fonts for the usage with canvases. Currently 8*8 bitmap fonts and
					TrueType fonts are supported (through FreeType, thanks!).

GUI:      The most important unit, providing views, groups, screens and other
					common types such as the driver frame.

GUIUTILS: Some allround utility functions written in assembly. Currently this
					is the only GUI part that is not fully Pascal.

MENUS:    Drop-down and pop-up menu views.

SURFACES: Surfaces are some kind of boolean bitmaps organized as list of
					rectangles. They are used for views (shape) and canvases (clipping)
					but you will most likely never have to use them directly.

Note that in addition you will always need to include at least one driver
unit, but the driver itself is not one of the integral GUI units; changing the
used driver does not force a recompilation of the GUI.

1.4. Views and ViewGroups


Everything that can be seen on the screen is a view. Viewgroups are views that
can carry views inside. Every view can have any user defined shape, no matter
what it is. The normal shape is a rectangle of the views size, but rounded
edges, triangles, holes etc. are also possible.

A view has many properties. It can be inserted to a viewgroup during it's
initalization or later using InsertToGroup. To change the Z position of the
view (that's the "layer" of the view, making it be over or under other views)
one can use the MoveToTop, MoveToBottom, MoveUp and MoveDown methods.
Depending on the AlwaysOnTop-flag, the view will not be moved under or over
other views. One of the views on the screen can have the focus. The focused
view is "active" and will receive keyboard messages.

When a view has to be drawn or redrawn, the Draw method is called. The
clipping of the view will be limited to the affected area in the case of a
redraw, so that these is basically no diffenrece for the view in drawing or
redrawing. Views can be shown or hidden of the display.

A view can be enabled or disabled. This only affects views that accept mouse
and keyboard events.

1.5. Canvas and Surfaces


Every drawing action, no matter if on the screen, on a bitmap or on a surface,
will take place by the use of a canvas. The canvas offers all the GUIs drawing
methods, such as lines, rectangles, circles, ellipses and polygons, as well as
methods for text output and bitmap drawing.

The canvas manages all the clipping issues of it's owner (usually a view). To
do this, it holds a list of rectangles where it can draw to. Such a list is
implementes as surface in the GUI. Drawing on a surface means modifying its
list of rectangles.

The shapes of views are also defined by surfaces. To modify any surface you
can use the TSurfaceCanvas which gives you access to all canvas drawing
primitives on the surface. Look a the TestGUI demo aplication at the end of
the init to see how the screen's rounded edges are created.

1.6. Bitmaps


The GUI offers support for both device independent (generic) and device
dependend bitmaps. While the latter are not yet used in any driver, the device
independend bitmaps are accessible through the bitmaps unit. Such a bitmap
will be accessed in lines, that means if you want to directly modify or read
bitmap data you can do this by requiring the memory address of a line for
modification.

Bitmaps can be color-keyed (e.g. one color will be transparent) or have an
alpha mask, thus making them transparent. Bitmaps can be drawn on the screen
using PutImage and retrieved from the screen using GetImage. Note that
PutImage will require the bitmap to be in the correct screen format. The
screen provides a method to convert any bitmap to the screen format.

1.7. Message types and flow


A message is the key component for any action in the GUI. Moving the mouse,
typing a key or a timer will all create an event that is handled by the GUI's
components. Aside from the events created by input devices there are commands
and broadcasts. Such commands will be issued as a result of another action.
For instance, when the mouse leaves or enters a view's area, this view will
be informed with a cmMouseEnter or cmMouseLeave command.

If a message has been handled, it should be marked as handled to prevent
further actions as a result of the message. For instance, a keyboard event
that is not handled will be broadcasted. If the focused component handles
the key, it should mark the message so that the broadcast is not emitted.

Broadcasts willbe sent to a view and from there to all it's subviews. Since
this can make the message "travel" through all views one should be careful
not to abuse broadcats and to start the broadcast at the right place to
minimize the views that handle the boradcast.

A view has an EventHandler property. If the event handler is assigned, any
command or broadcast message received and not handled will be resent to the
event handler as a command. This allows for instance to redirect commands to
the application object or any other TEventObject descendant.

1.8. Modality, focus and event caption


Views on the screen can have the focus. The focus should make then look
"active" and they will get the keyboard events. Views may, however, also
choose not to accept the focus if they don't want to get focused. This is done
by the use of the AcceptFocus property and will mekr the focus being given to
it's owner.

If a view is shown modal, it will always stay in the focus and also prevent
other views of getting mouse or keyboard messages. Usually modal dialogs are
used for settings or when loading/saving a file etc. - you know them from
other OS's like windows when you cannot activate the main window because of an
opened dialog. The modality state is undone as soon as the view is hidden.

Some times a viwe needs to capture the mouse and keyboard events in order to
complete an action. Such a situation is the dragging or resizing of a window,
where the mouse must inform the view of actions even if it isn't currently
under the mode and in focus. The capture must be released in order to release
the mouse and keyboard so that they again generate events for other views.

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

2.1. A minimal application


 uses
	GUI,Events,Elements,Canvas,Drv_VBE; {replace XXXX with the driver name}

 type
	TMyApp=object(TApplication)
	 constructor Init;
	 procedure HandleEvent(var Event: TEvent); virtual;
	end;

 constructor TMyApp.Init;
 begin
	inherited Init(@Driver); {Initialize using our driver}
	Screen^.EventHandler:=@self;
	with PLabel(New(PLabel,Init(Screen)))^ do begin
		Resize(Screen^.Width,10);
		SetCaption('Press ALT-X to quit');
		Canvas^.SetColor(clWhite);
		Show;
	end;
 end;

 procedure TMyApp.HandleEvent(var Event: TEvent);
 begin
	if Event.What=evCommand then
	 case Event.Command of
	 cmHandleKey: if Event.KeyCode=kbAltX then begin
		 Halt;
		 EventHandled(Event);
		end;
	 end;
 end;

 var
	MyApp: TMyApp;

 begin
	MyApp.Init;
	MyApp.Run;
	MyApp.Done;
 end.

This application will do nothing but display a black screen with some text and
the mouse and wait for Alt-X to be pressed...

As you can see, the programmer does not have to check himself for the state
of keys, mouse or views, but he gets informed by the means of a message when
something happens. This allows the programer to forget everything related to
mouse position checks and clipping.

You may add some more stuff to this application, like a button that issues a
command:
In MyApp.Init:
	with PButton(New(PButton,Init(Screen)))^ do begin
		Resize(200,30);
		Move(30,30);
		SetCaption('Quit');
		Command:=cmClose;
		EventHandler:=@self;
		AcceptFocus:=False;
		Hover:=True;
		Show;
	end;
In MyApp.HandleEvent:
	 cmClose: begin
		 Halt;
		 EventHandled(Event);
		end;

2.2. Centralized message handling


As seen in the minimal application, a button for instance does not have to
handle its actions itself. By the use of the EventHandler property, commands
can be sent to another evenbt handling object (see 1.7).

By assigning unique command numbers and setting all the event handler of a
certain group of views to the same object, you can make a central point where
all the issued messages are to be handled. The advantage of this method is
that no broadcast or even view inheritance is necessary to handle the issued
event.

I suggest to make strategic event handling points, like the application object
for global events (Alt-X, ...) and separated handling points for dialogs and
windows which are inherited usually anyways (so adding a HandleEvent is not a
problem). By doing this you can implement Delphi-like events for forms (done
by calling procedures on ever case statement of your window event handler).

2.3. View initialization


Since views have a lot of properties they need a couple of lines to be
initialized properly. That's because one has to set up position, size, event
handler, visibility, command to issue, display text and all the other
properties available to you.

A specific shortcut initialization for elements that are often used is in
discussion and may be implmented in a future GUI version.

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

3.1. Modifying an existing view type


A view is designed to be enhanced or omdified in behaviour by means of
inherited methods. Four methods are specially important: Init, Done, Draw
and HandleEvent. The first two should be self-explaining, why the latter two
may need some more detailed description.

Draw will always be called when the component needs to draw itself on the
screen. This is, however, not directly dependant of Show and Hide. When a view
is shown but there is nothing to draw on the screen because it's off-bounds,
has no size or is hidden by other views, so no draw will be issued. On the
other side, everytime that a redraw is needed due to movement, sizing or
hiding of views Draw will be called also.

Technical note: Don't worry about bad performance because every Redraw will
trigger a Draw that draws the whole view. Clipping will be restricted to the
area to be redrawn so that all the drawing operations outside of the clipping
will just be ignored.

Draw may be called at any time to ask the component to refresh itself. For
instance, when a Label's SetCaption is called, a Draw is issued to reflect the
changes. Note that you should use CanDraw prior to calling Draw when you're
unsure of the View's state.

HandleEvent has already been quickly described in 1.7 and 2.2. There are some
important things to think about when dealing with messages. First you will
have to decide wether you want to process a message before or after the
original message handler. If you handle it afterwards, the Event may already
have been cleared. You can use EventHandled to mark a normal event as handled,
thus preventing it of being processed further. Broadcasts are not affected by
EventHandled. Remember that an unhandled command or broadcast will be sent to
the EventHandler if assigned.

3.2. View messages


A view receives several messages to process. While it will most likely ignore
most of them, you can use them to reflect state changes.
 Mouse events: (evMouseMove,evMouseDown,evMouseUp,evMouseDouble)
	The view under the mouse receives all mouse events for processing.
 Keyboard events: (evKeyboard)
	The view with the focus receives keyboard messages.
 Commands & Broadcasts (evCommand,evBroadcast)
	cmMouseEnter,cmMouseLeave: issued to every view when the mouse moves over
	 it's border, thus entering or leaving a view's area.
	cmFocusChanged: Broadcast to all views that were or are in the focus chain.
	cmHandleKey: Broadcast to all views when a key message wasn't handled. You
	 use this to process keyboard combinations like Alt-X globally.

By intercepting these events the view can react to the most important actions.
A view can also start a timer:
 Application^.Post.Timer(@self,TimeInMS,Command,Tag);
will send the Command to the view (@self) with the InfoLong Tag after TimeInMS
milliseconds have elapsed. (Note that the timer may be late due to driver
limitations or bad cooperation of your application).

3.3. View shapes


Every view is allowed to have its own shape. While every spae is possible, the
use of very complex shapes (in the means of rectangles) may affect your
applications performance. To change a view's shape, use code similar to the
following:
 with PSurfaceCanvas(New(PSurfaceCanvas,Init(ViewToBeShaped)))^ do begin
	SetColor(0); {remove shape parts}
	{Add any canvas drawing operation here}
	SetColor(1); {add shape parts}
	{Add any canvas drawing operation here}
	Free;
 end;

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

4.1. Minimal driver requirements


A driver must provide the following methods:
 Timer: Function to return milliseconds, start value is unimportant.
 TDriver.Open: Setup (create) Timer, Screen and Mouse objects.
 TMouse.Show: Display mouse
 TMouse.Hide: Hide mouse
 TMouse.Limit: Limit mouse movement area
 TMouse.Move: Set mouse position
 TScreen.NewCanvas: Create new screen canvas
 TCanvas.SetColor: Setup the canvas's color
 TCanvas.DirectHLine: Draw a horizontal line
 TCanvas.DirectReadHLine: Copy a horizontal line from screen to memory
 TCanvas.DirectWriteHLineKey: Copy from memory to screen with color keying

4.2. The driver screen


The screen should be able to initialize and close. A mode selection, init
file or any other method may be used to specify the exact mode to use.

4.3. The driver canvas


The canvas will only need four basic functions to be replaced to receive full
functionality. It is suggested to implement as may DirectXxx functions as
needed to achieve the highest speed of a driver. Note that a color key of -1
is not equal to clWhite and should be handled as such.

4.4. Driver canvas acceleration


By replacing more fucntions of the canvas you can accelerate your driver. All
methods that are not directly implemented will be executed by calling other
graphical functions. For instance, a VLine will use PutPixel, and PutPixel
will call HLine. So replacing PutPixel or even VLine will speed up the
graphics output. All the DirectXxx functions are very basic and should be no
problem on implementation. All DirectXxx functions are already clipped and in
absolute screen coordinates.

4.5. Acceleration of non-Direct methods


If you want to replace any of the more specialized function, such as discs,
filled polygons and others, you will have to take care of the following:
 * Call BeginUpdate and EndUpdate to make sure you don't overdraw the mouse
 * Clip around the given canvas surface
 * Add Offset.X and Offset.Y to get absolute screen coordinates
While this sounds pretty easy the clipping part can be very demanding, since
the drawn figure has to be identical every time it is drawn.

4.6. The driver mouse


The mouse is quite straightforward to implement. You can use the Update or
IntUpdate methods inside an interrupt or handler, but be warned that this may
also generate a collection of events that cannot be processed so quickly. In
the reference drivers, mouse keys trigger an update from within the handler,
thuis guaranteeing that no click is lost or processed on the wrong spot. All
movements are handled inside the driver poll.

4.7. Some thoughts about reentrancy


I have tried to make the GUI as reentrant as possible where it did make sense.
However, you should be careful when accessing surfaces from outside an
interrupt; may be a synchronization to the main application must be used:
by posting (not sending) a message into the application queue you can trigger
an action by interrupt but it will be handled later (by an event) inside the
main application.

4.8. The driver timer


The timer is very simple, the start value does not matter. Note that the
accuracy of the timer will directly affect timer messages, thus you should
try to get a quick and exact MS timing.

4.9. The driver itself


The driver has, apart from initialisation and finalization, a method called
Check that will be called to poll for new driver events (mouse, keyboard) to
be posted to the application. If you handle everything be interrupt or
handler you can ignore the Check procedure.

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(C) 1999 by A. von Wyss
