This documentation is copyrighted by Sergey Kozlovich.
It may be distributed under the terms of GNU public licence
(see file COPYING).

I should apologise to all who speak Russian. Russian is my
native language but this doc is written in English. This is because
of many Russian code-pages which produce many problems with different
OSes and because of international audience :).

The next text is in "pseudo-Crazy-Russian":
                 
                               '       '
    y 4 u T e      a H I^ JI u u c k u u !!!

Thank you.

I should also apologise to all other people because of possible
errors in English. If you find some grammar or logical errors,
please, mail to me.

Thank you, too.

How to use GUI-programs?
========================

    See documentation for any graphical operating system like Windows.
    All items are selectable by mouse and keyboard.
    To go to the next item, press TAB.
    To go to the previous item, press SHIFT+TAB.
    To select RadioButtons, use UP and DOWN arrows.

Let's begin.

How to use GUI library?
=======================

This GUI is implemented by object-oriented programming tools.
So, if you don't know what is OOP and dynamic memory, please,
try to learn it somewhere. After that you can continue reading. :)

First of all, some definitions:
  BP - Borland Pascal (commercial).
       This can be Turbo Pascal or Borland Pascal with Objects v7.0,
       7.01 or 7.1.
       I haven't tested GUI in earlier versions of BP because BP 7.0
       is antique now (released in 1992/1993). Commercial.
  FP - FreePascal (freeware, GNU licence, www.freepascal.org).
       A good cross-platform PASCAL compiler.
       I have tested GUI with v1.0.6.
       At the moment FP can compile to different OSes.
       I compiled GUI under GO32v2 (DOS) and Win32.
  VP - Virtual Pascal (Some components are freeware)
  OPP - Object-oriented programming.
  ifdefs - compiler directive sets including
             {$DEFINE SOMETHING}   // - defines SOMETHING
             {$IFDEF SOMETHING}
                 the next code is compiled if SOMETHING is defined
             {$ELSE}
                 the next code is compiled if SOMETHING is NOT defined
                 this $ELSE section may be omitted
             {$ENDIF}               // - the end of $IFDEF directive
           We use platform.inc include file to find out the information
           about compiler and OS. This file sets up appropriate
           definitions using $DEFINE's.
  [USER] - this section in this doc should be read by all GUI programmers
  [PROF] - this section may be omitted if you are not interested in
           internal structure of GUI


NAMES AND UNITS.
=[USER]=========

Well, every item is an object (we don't use classes for compatibility
with Borland Pascal and portability).

Object types begin with the letter "T", e.g. TObject.
Pointers to object types begin with the letter "P", e.g. PObject.

All the objects are dynamic, so you don't need to use TObjects
but you will need to use PObjects.

I recomment to use BIG_LETTERS_WITH_UNDERLINE_SIGN for constant
names. I use that kind of identifiers for once-initialized
variables, too. It comes from C++ where this is an unofficial(?) standart.

All the objects have constructors named Init and virtual destructors
named Done like in Borland's TurboVision. I thought about naming
them like Create and Destroy (like in Delphi), but this is no so
important. In the last case, we can make two constructors and two
destructors with the different names, if you can't live without them.

We use a standart "Objects" unit that comes in (almost?) all
Pascal compilers. There is a TObject defined in this unit which
has two things that we use:
  constuctor Init (it fills the object data with zeroes!!!)
  destructor Done (it is virtual, so we can correctly free
                   memory of ANY object that is a descendant of TObject).
Unit "Objects" has also a TCollection object which is used as
an object container (see the online-help or a Borland's reference
how to use it; if you are not interested in details
you may know nothing about it; it is used only in internal purposes).

Each GUI unit begins with the letter g, e.g.
  gItems,
  gImages,
  gDrivers...

What do the files contain?
==========================
    Each GUI filename starts with the letter "g".
    gImages.pas - unit containing classes for working with images and canvas
      gIma_cur.pas - unit for reading *.CUR and *.ANI cursor files
      gIma_bmp.pas - unit for reading *.BMP files
      gIma_gif.pas - unit for reading (not all) *.GIF files
      _gImages.pas - a test program for gImages unit
    gCursors.pas - working with *.CUR and *.ANI mouse cursors
    gDrivers.pas - unit containing classes for working with different
                   graphic drivers, mouse drivers and keyboard
      SCANCODE.PAS - unit for getting keyboard codes
      gBGI.pas - graphic driver for Borland/Turbo Pascal with Graph unit
                    (tested with BP version 7.0)
      .\GRAPH\ - a directory with some useful units for BP Graph unit
      gGrafX.pas - graphic driver for Borland/Turbo Pascal with GrafX unit
                    (tested with BP version 7.0, GrafX version 1.42)
      .\GRAFX\ - a directory with GrafX library for BP
      gGraph.pas - graphic driver for FreePascal (GO32V2) with Graph unit
      .\graphix\ - a directory with GraphiX library for FP
      gGraphiX.pas - graphic driver for FreePascal (GO32V2) with GraphiX library
    gMemory.pas - platform independent memory management
      _gMemory.pas - a test program for gMemory unit
      .\XMS\ - a directory with units for XMS memory support in Real mode
    gFonts.pas - unit for working with fonts (*.f, *.ttf)
      _gFonts.pas - a test program for gFonts unit
      .\FREETYPE\ - a directory with FreeType library for Pascal
    gThemes.pas - unit to load themes for the elements (items)
      DOSINI.PAS - unit to read *.INI files (like in Windows)
      .\winxp.thm\ - a directory containing WindowsXP theme for GUI
      .\linux.thm\ - a directory containing Linux theme for GUI
    gItems.pas - classes for GUI elements (items)
      gStandar.pas - gStandartItems (TButton, TForm, etc. like in Delphi)
      gWin32It.pas - gWin32Items (TProgressBar like in Delphi)
      gDialogs.pas - MessageBox, Abort/Retry/Ignore box, etc.

    qsystem\
      qsystem.pas - a useful unit

Some files for easy compiling are included, too:
  make_tp.bat   - compiles demos under Turbo Pascal (tpc.exe) for Real Mode
  make_bp.bat   - compiles demos under Borland Pascal With Objects
                (bpc.exe) for DPMI (Protected Mode)
  make_dos.bat  - compiles demos under FreePascal (fpc.exe) for GO32V2
  make_w32.bat  - compiles demos under FreePascal (fpc.exe) for Win32
  make_lnx.sh   - compiles demos under FreePascal (fpc) for Linux

OBJECTS.
=[USER]=
Every object in GUI is a descendant of TObject.

Each visible item (button, form, input-line (edit))
is a descendant of TItem (unit gItems).
This object is the main in GUI and declared in gItems.pas.
It has such methods:
  constructor Init (each object has its own one)
  destructor Done; virtual;

To create an object, use
  ObjectPointerTypeVariable := New( PObjectType, Init(constructor-parameters));
To destroy the object, use
  Dispose(ObjectPointerTypeVariable, Done).

There is also the descendant of TItem - TItemGroup for containing
and controlling several items. In each TItemGroup there may be
not more than one active item. 

Each group is a descendant of TItemGroup (unit gItems), and TItemGroup
is a descendant of TItem. So, we can manipulate visible objects
in the same way.

TItemGroup implements these usable methods:
  constructor Init (parameters are different is different objects)
  destructor Done; virtual;
    destroys all the items inserted to TItemGroup and not deleted from it;
    so it correctly releases memory.

OBJECTS.
=[PROF]=
    Each item (TItem) can't activate itself
    without informing about it to the owner (TItemGroup) because there
    could appear more than one active items. So, TItem calls
      Owner^.SetActiveItem
    to activate itself. Owner deactivates previous active item and
    make a new item active.

INITIALIZING AND FINALIZING GUI.
=[USER]=========================
  For these purposes I've created a unit "gInit" which has
two procedures and a variable Desktop: PDesktop.
 
  procedure InitGUI( GraphResolutionByX, GraphResolutionByY: Integer;
                     BitsPerPixel: Word );
  procedure DoneGUI;

The first one must be called BEFORE ANY use of GUI. It uses the
best included drivers for the compiler you use. Drivers are defined
using ifdef's.
The last one must be called to free GUI's memory and destroy a
graphic mode.

Unit gInit initialized graphic mode using standart (unit Graph) or
non-standart free available graphic units included in this distribution.

GUI uses so called "graphic drivers" to work with graphic, so you may
define a driver for your favourite unit not included in this GUI.
In that case you might have to change unit gInit to initialize
a graphic mode using YOUR driver. If you use a good unit or a good driver,
plase, let me know. I may include it to GUI distribution.

CREATING FORMS AND ITEMS. TDESKTOP.
=[USER]============================
How to write GUI programs?

  The interface is similar to TurboVision,
but the names of the objects are like in Delphi.

  It's better to see test (demo) programs for GUI that
are included in this package:
  _gDemo?.pas
  This is a template for GUI applications (may be changed):
_GAPP.PAS

  The first logical step is to create a form, like this:

    Form := New(PForm, Init(
      10,10,   { coordinates of the left top corner }
      400,300, { width & height }
      'Form1', { caption }
      False,   { we don't want to save image under the form }
      DRAG_RECTANGLE { how we want to Drag&Drop window;
                       available constants:
                       DRAG_NONE        - no drag
                       DRAG_RECTANGLE   - a dotted rectangle will be visible
                                          while dragging
                       DRAG_SHOW        - window will be redrawn while dragging
                     }
    ));
  where Form is PForm - the pointer to TForm object defined in unit
  gStandartItems. After that you can insert items to this form like this:

    Form^.Insert(New(PEdit, Init(100,150,0,0,'Edit1',50 {maximal string length})));

  or (the same)
    Edit := New(PEdit, Init(100,150,0,0,'Edit1',50 {maximal string length}));
    { Edit is a variable of type PEdit defined in gStandartItems }
    Form^.Insert( Edit );

  Almost all the objects have a constructor with the first four parameters
describing relative (to the owner - in our case to the form) coordinates
of the left top corner (first two integer parameters) followed by
width and height (the next two integer parameters). In the example above,
we initialize an Edit line (input line) which can be used to enter strings
with the Left=100 and Top=150 coordinates of the left top corner but
Width and Height are equal to 0. This means, that the width and the height
will be initialized by default values with the best look at the screen
(like in Microsoft (R) Windows).

  TEdit can't close the form because it is used only to enter strings.
But there are some items which can inform its form to be closed because
the user had pressed on them. The example is a simple button (TButton).
When a button is pressed, the dialog ends and returns the ID of the button
to find out which one was pressed. Please, use different IDs for different
buttons :) It is recommended to use IDs bigger than 99 because I'd like
to reserve IDs from 0 to 99 for GUIs purposes. Some of the reserved IDs
you may use, e.g.
  ID_NONE = 0;  { no identifier for the object }
  ID_CLOSE = 1; { for the Close button }
They are defined in unit gItems.
  So, when you insert a button to the Form, you should pass the button's
ID as the parameter to its constructor:
  B := New(PButton, Init(50,50,0,0,'B&utton1',
    1 { this is an ID (must be positive);
        this ID will be returned by Desktop^.Execute
        if the button is pressed
      }
    ));

You can make a button default, so if user presses ENTER,
this button will be pressed:
  B^.Default := True; { if user presses ENTER, this button will be pressed }
  Form^.Insert(B);

or you can make a cancel button:

  B := New(PButton, Init(150,50,0,0,'&Button2',2));
  B^.Cancel := True;  { if user presses ESC, this button will be pressed }
  Form^.Insert(B);

If you want to make an item active (item will get the input focus), you
may do it like this:
  B := New(PButton, Init(150,50,0,0,'&Button2',2));
  B^.Active := True; {!!! we are making this item active;
                      there may be no more than ONE item active
                      at the same time!!!}
  Form^.Insert(B);

The "&" sign allows to set the "hot key" to some objects. The hotkey
is ALT+Symbol. The button above has a hotkey ALT+"B". Pressing
this hotkey makes the button pressed.

If you want to make a hotkey to some other objects, you may
:= a char to the field HotKey, e.g.
  Edit:=New(PEdit,
    Init(90,35,100,21,            { <= coordinates }
      '',                         { <= default text in the input line }
      50                          { <= max length of the text }
  ));
  Edit^.HotKey := 'N'; 
  Form^.Insert(Edit);

  When the user press ALT+"N" the item above is activated (because it
- TEdit - cannot be pressed :).

You may also insert a radiobutton to the Form:
  RB := New(PRadioButton, Init(100,240,0,0,'This is a radiobutton1'));
  RB^.Selected := True;  { and select the radiobutton }
  Form^.Insert(RB);

Or you may want to add a checkbox:
  CB := New(PCheckBox, Init(100,220,0,0,'This is a checkbox'));
  CB^.Checked := True; { with the checked tick }
  Form^.Insert(CB);

EXECUTING DIALOGS.
=[USER]===========
  The Desktop variable (of type PDesktop) is initialized during
InitGUI. Desktop is a descendant of TItemGroup, so you can insert items to
it. I recommend to insert only forms to it. Then call method (function)
Desktop^.Execute which executes all the forms inserted to it and returns
the ID of pressed item.
Desktop^.Execute waits until the command is passed to it via the Event
variable (until the event which is command appears). This usually happens
when a button is pressed (keyboard or visual button like "Ok" or "Cancel") and
passed the ID via the event.

Note: if no item which can return the ID is inserted to the Desktop,
Desktop will wait infinitely.

If you don't want to insert a form to the Desktop, you may
call Form^.ShowModal which acts similar to Desktop^.Execute.
The difference is that Form^.ShowModal handles events by itself and
Desktop^.Execute allows to handle events for every item inserted to it.
If Desktop has only one form inserted then Form^.ShowModal works
the same as Desktop^.Execute.

  Desctructo Desktop^.Done is called during DoneGUI so you don't have to
Dispose the items inserted to the desktop or the items inserted to the
items (forms) inserted to the Desktop :) They are automatically destroyed
because all those items are descendants of TItem and TItem is a descendant
of TObject with an virtual destructor.

COMPILING.
=[USER]===
NOTE.
When compiling under BP add these paths to directories:
  include directories:  freetype\lib;
  unit directories:   GRAPH;GRAFX;freetype\lib;QSYSTEM;QSYSTEM\XMS;
  object directories: GRAPH;GRAFX;

  turbo.tpl and tpp.tpl files are libraries for BP
  with the corrected bug in unit CRT (Runtime Error 200 bug).

When compiling under FP add these paths to directories:
  include directories:  freetype\lib;
  unit directories: freetype\lib;graphix;graphix\directdraw\lib;graphix\svgalib;qsystem;

graph\ and xms\ are the directories containing files for BP to
                work comfortly with graphics and memory
freetype\lib is a directory containing library for working with TrueType fonts
             for BP and FP
graphix\ is a GraphiX library v 4.00 for FP
         it requires svgalib (for Linux or Windows) and DirectDraw (Windows).
	 
If you compile under Linux, replace "\" characters with "/" :)

You will need to install these libraries for compiling in Linux:
  svgalib (needs device /dev/svga)
  ncurses
(?) maybe others

WRITING YOUR OWN DRIVER (usually, it is not necessary).
=[PROF]================================================

Each graphic driver is an object, descendant from TCanvas (see unit gDrivers).
If you want to implement a new driver, you must implement AT LEAST
four its methods:
  constructor Init,
  procedure PutPixel,
  function GetPixel,
and
  destructor Done.
If you think you can implement some others methods, override them too.
For example, you can see units
  gGraphiX
  gGraph
  gBGI
  gGrafX...                              (*)

You should know, that you should also implement a new mouse driver,
if your graphic unit can't work with an existing mouse driver from one
of the units above (see *).
A mouse driver is a descendant of TMouseDriver defined in unit gDrivers.

To write a mouse driver, you must implement AT LEAST three methods:
  Init
  Done
  GetState

FORGET ABOUT CRT.
=[USER]==========
There are some "graphic drivers" that have its own keypressed/readkey
functions. So, it was decided to put procedure-variables called
  KeyPressed
  ReadKey
  GetScanCode
and
  Delay    (**)
to the unit gDrivers.
It is recommended to use KeyPressed/ReadKey/GetScanCode and Delay
from unit gDrivers instead of CRT. You may override these procedures.

OVERRIDING PROCEDURES LISTED ABOVE (see **).
=[PROF]=====================================

These procedures are initialized as a CRT's functions by default
and GetScanCode is a function from ScanCode.pas which returns a WORD (16-bit)
keyboard scancode.

See gGraphiX.pas for an example, where we use DirectDraw (Win32)
routines to get the information from a keyboard.

If you re-define KeyPressed and ReadKey functions you must also
re-define a function GetScanCode.

If you have only a KeyPressed and ReadKey functions, you may
not write a function GetScanCode, but simply := to it
function GetScanCodeFromReadKey that is implemented in unit gDrivers
(see GraphiX.pas). Is returns Scan Code by calling a ReadKey function
(that may be changed) from unit gDrivers.

MORE ABOUT UNIT GDRIVERS.
=[USER]==================

Unit gDrivers contains keyboard scan code definitions. It constains also
a function Ticks, which is defined from unit "SysTimer.pas". This function
returns DOS ticks which change every 55 ms (~18.2 times per second).
This function is implemented for all supported platforms. Remember:
Ticks is a function in contract to Borland's variable in order
to be portable.

GDrivers contains also constants for mouse cursors. These constants
have different names for the same cursors, so you may use any you like.

const
  crDefault = 0;
  crArrow = crDefault;
    CURSOR_DEFAULT = crDefault;
    CURSOR_ARROW = crDefault;
    CURSOR_STANDART = crDefault;
  crHandPoint = 1;
  crHand = crHandPoint;
    CURSOR_HANDPOINT = crHandPoint;
    CURSOR_HAND = crHandPoint;
  crHourGlass = 2;
  crWait = crHourGlass;
    CURSOR_HOURGLASS = crHourGlass;
    CURSOR_WAIT = crWait;
  crText = 3;
    CURSOR_TEXT = crText;

GDrivers contains also some color-variables which are initialized
during GraphDriver's initialization. Standart color names are
compatible with unit CRT. So, this is another reason not to use
CRT - not to mistmatch the names.

var
{ STANDART COLORS }
  Black,Blue,Green,Cyan,Red,Magenta,Brown,LightGray,
  DarkGray,LightBlue,LightGreen,LightCyan,
  LightRed,LightMagenta,Yellow,White: LongInt;

{ COLORS USED BY GUI ITEMS }
  {0} col_transparent,
  {1} col_light1,
  {2} col_dark1,
  {3} col_light2,
  {4} col_dark2,
  {5} col_3d_bg,
  {6} col_3d_text,
  {7} col_bar_bg,
  {8} col_bar_bg2,
  {9} col_bar_text,
  {A} col_desktop: LongInt; {??? may be these col_XXX names will be changed ???}

Unit GDrivers contains variables
  Mouse: PMouseDriver
and
  Screen: PScreen { = PCanvas }.
These GLOBAL variables are used by GUI. They are initialized in
unit gInit by descendats of TMouseDriver and TCanvas.

  Screen is used to put/get something to the screen and Mouse
is used to provide mouse support. By default TMouseDriver already
provides support for *.CUR and *.ANI mouse cursors. You can
preload them using unit gCursors and then change cursors
using Mouse^.SetCursor().

MORE ABOUT UNIT GDRIVERS.
=[PROF]==================

Unit gDrivers contains some features like Borland's Drivers unit.

procedure InitEvents; 
procedure DoneEvents; { are called in gInit, they only clear buffer
                        used for compatibility only }

procedure GetMouseEvent(var Event: TEvent);
procedure GetKeyEvent(var Event: TEvent);
function GetShiftState: Byte;

procedure CheckEvent(var Event: TEvent);
procedure ClearEvent(var Event: TEvent);

{ Keyboard support routines }

function GetAltChar(KeyCode: Word): Char;
function GetAltCode(Ch: Char): Word;
function GetCtrlChar(KeyCode: Word): Char;
function GetCtrlCode(Ch: Char): Word;
function CtrlToArrow(KeyCode: Word): Word;

TEvent record was a bit changed.


**********************
IMPLEMENTATION SECRETS
**********************

How is the fade effect implemented when the Form is arriving?
=============================================================

   Task: Output the image like ghost - semi-transparent,
         when the transparency factor (from 0 to 1) is given.
   Solution: Function ConvertToGhost from unit gImages.

   Inside:
      In order to find out the (r,g,b) color which must
      contain old color (that was at the screen) and
      new color (that we want to output like ghost),
      we may use this formula for Red, Green and Blue
      components separately:

        WantedColorComponent := OldColorComponent*(1-Factor) + NewColorComponent*Factor;
      For each of the components (r,g,b) we have a formula.
      Total - 3 formulas.

      OldColor disappeares with the coeficient, "opposite" Factor,
      and the NewColor appeares with the coeficient = Factor.

   Task: We want to programme fade effect.
   Solution: TCanvas.PutImage(....., SHOW_FADE);

   Inside:
     The image appears on the screen in FADE_STEPS steps
     with the coefficients i/FADE_STEPS,
     where i from [1, 2, 3,... FADE_STEPS].

     Really, the situation when i = FADE_STEPS we can handle without
     any transparency - simply output the image as is. This will be
     more quickly.

     When i = 1, all is OK. We calculate all new colors
     using formulas above with the factor = i/FADE_STEPS = 1/FADE_STEPS.
     But when i = 2, we can't use the same factor, because the
     colors at the screen were a little changed. Now we have a job
     with a new colors at the screen (not those, that were before
     the 1st FADE step). So, the Factor relatively to the current
     screen will be distict from i/FADE_STEPS, but relatively to
     the start screen (before 1st FADE step) it will be equal to i/FADE_STEPS.

     So, we've spoiled the screen!? But not at all. Each spoiled pixel
     contains some useful information.

     Let's solve this problem:
       At the screen pixels are with the Factor = k accordingly to the
       start screen.
       We want to calucate the new Factor in order all the pixels at
       the screen become with the Factor = l acocordingly to the start
       screen.

       Let
         c1 = (1-k)*OldColorComponent + k*NewColorComponent
         c2 = (1-x)*c1 + x*NewColorComponent
       and at the same time
         c2 = (1-l)*OldColorComponent + l*NewColorComponent

       where OldColorComponent is the color component on non-spoiled screen,
       and NewColorComponent - that we want to see finally, after FADE.
       c1 is a color component at the screen
       c2 is a color component that we want to see at the next fade step

       We want to find such factor x.
       Ok.

       c2 = (1-l)*OldColorComponent + l*NewColorComponent =
          = (1-x)*c1 + x*NewColorComponent =
          = (1-x)*((1-k)*OldColorComponent + k*NewColorComponent) + x*NewColorComponent =
          = ... =
          = (1-(k+x-k*x))*OldColorComponent + (k+x-k*x)*NewColorComponent

       Look at the 1st and the last row.
       We can see, that l = k+x-k*x,
       so   x = (l-k)*(1-k).

       In our case
         k = (i-1)/FADE_STEPS
         l = i/FADE_STEPS,

       so   x = (l-k)*(1-k) = .... = 1/(FADE_STEPS-i+1)
       at the i-th step of fade.
     Simple, isn't it?


How to make universal 256-color palette (and easy find out
==========================================================
the number of a color by known Red-Green-Blue values)?
======================================================
  We divide palette into 216 colors (from 16 to 231).
  Some start colors (e.g. 0-15) are standart and we leave them
  as is.
  We assume that each of three main colors (Red-Green-Blue) could be
  one of the 6 values - 0, 51, 102, 153, 204, 255.
  So, for 3 main colors we need 6^3 = 216 palette entries.

  How to find out the color number if Red/Green/Blue values are given:
    r := round(r/51);
    g := round(g/51);
    b := round(b/51);
    ColorIndex := r * 6*6 + g * 6 + b  + 16;
      { this 16 means that the first 16 colors we save for system
        purposes }

  How to get Red/Green/Blue values if the color number is given:
    ColorIndex := ColorIndex - 16;
    b := (ColorIndex mod 6) * 51; ColorIndex := ColorIndex div 6;
    g := (ColorIndex mod 6) * 51; ColorIndex := ColorIndex div 6;
    r := ColorIndex;

Copyright (c) 2003  Sergey Kozlovich.

English isn't my native language.
I know Russian (native) and Latvian (free).
Also, PASCAL and C.
I live in Latvia (Riga), GMT+2.
E-mail:
  kozlovichREMOVE_THIS@inbox.lv
  nospamsergey_kozlovich@hotmail.com 
  (remove REMOVE_THIS or nospam from the address).

