KLib.API.rtf         Klib tutorial by Seppe Sol
__________________________________________________________

This document is an API reference and tutorial for the Klib library for Kolibri.
Fasm is used to compile the many example applications.
It is assumed that the reader knows the Fasm syntax.
__________________________________________________________

For a quick evaluation of Klib, just run the examples in the Klibex_apps folder.
The source and the description of all the examples is given in this document.
__________________________________________________________

The source files are available in the Klibex_asm folder for you to experiment. 
For the experienced readers: insert int3 in the sources to invoke MtDbg. 
__________________________________________________________

Latest revision of Klib : version 2, 10.09.2014

Download the Klib folder on a USB flash drive or a hard drive to use on your KolibriOS system.
In this version, the Klib folder contains these subfolders: 

The Klib_apps folder contains the KbTool1 application.
The Klib_fonts folder contains the unicode rasterfont files used by Klib.
The Klib_world folder contains the keyboard and other files used by Klib.
The Klibex_apps folder contains the executables of the examples is this tutorial (compiled with Fasm).
The Klibex_asm folder contains the sources of the examples in this tutorial + Klib_o2i + Klib.inc.
__________________________________________________________

klibex:	Kolibri library example application

Please look at the source of the "Klib example 01" below. 
To begin, every example application includes a klib.inc and calls the "klib" macro. 
The Klib.inc file defines the macro's that are used by FASM to call the Klib routines.
The Klib.inc file also defines several 32-bit variables to exchange information with the library.
The macro's and the predefined variables are explained in the examples.
The "Klib" macro defines the application header, and includes the Klib_o2i object file (explained later).

sax:	create a default sandbox window to experiment

The Klib examples use the "sax" routine to create a simple window as sandbox to experiment.
The sax routine must be called repeatedly (mainloop).
The skinned window can be moved and minimized, but not resized.
A Klib example application terminates when the window is closed or the "Esc" key is pressed.

; Klibex01 - 22/07/2014
;
include 'klib.inc'                      ; Includes the kolibri library
klib                                    ; klib is the macro to get started
idle:   sax                             ; show the default sandbox window
        jmp idle                        ; loop until closed
I_END:                                  ; obligatory label: end of our application

The application shows a simple empty skinned window, and uses the application name as title.
The window location is x=50, y=60; the size is w=600, h=400; and the background  color is white.

As an exercise: rename the source file, compile and run, and check the new application name in the window header. 

Create a default sandbox window with a specified background color

The background color (RGB) used by the window can be set in the predefined variable "bgc".
As an exercise, modify and run your Klibex01 example as shown below.

include 'klib.inc'                      ; Includes the kolibri library
klib                                    ; klib is the macro to get started
idle:   mov bgc,0xFFFF00                ; background color is yellow
        sax                             ; show the default sandbox
        jmp idle                        ; loop until closed
I_END:                                  ; obligatory label: end of our application

Sand:	Create a sandbox

The "sand" routine is a variation of the "sax" routine, using comma separated parameters.
In the Klib API, input parameters are written like >a,>b,>c, . . .
Unless noted otherwise, all Klib variables are 32 bit (big endian).

>a	screenlocation x
>b	screenlocation y
>c	window width
>d	window height
>e	bg color (default 0 = white)
>f	title (ascii zstring or zero)

; Klibex02 - 22/07/2014
;
include 'klib.inc'                      ; Includes the kolibri library
klib                                    ; klib is the macro to get started
idle:   sand 10,60,200,100,0xC7D7E7,0   ; display the sandbox window
        jmp idle                        ; loop until closed
I_END:                                  ; obligatory label: end of our application

The Klibex02 application shows a small blue window.
Because the title is not specified (f=0), the application name is used as window title.
As an exercise, modify and run your Klibex02 example with a different title as shown below.

include 'klib.inc'                      ; Includes the kolibri library
klib                                    ; klib is the macro to get started
idle:   sand 10,60,200,100,0xC7D7E7,tit ; display the sandbox window
        jmp idle                        ; loop until closed
tit:    db 'My lovely window',0         ; window title
I_END:                                  ; obligatory label: end of our application

mt:	moveto

Klib routines use variables "xc" and "yc" to specify the x and y coordinates (screen pixels).
These coordinates apply to the user_area inside the borders of the window.
You can set each of these variables using a move operation, or use the mt macro to set them both.
In the Klib API, output parameters are written like <xc, . . .

>a	x coordinate
>b	y coordinate
<xc	x coordinate (from a)
<yc	y coordinate (from b)

Parameters can be predefined variables, such as >xc on input, or <xc on output.

lt:	lineto
>a	x coordinate of endpoint
>b	y coordinate of endpoint
>fgc	foreground color (RGB) used to color the line
<xc/yc	coordinates of the endpoint (from a,b)

Pixels are drawn from the current pen position (xc,yc) up to the specified endpoint.
The routine updates xc and yc to the endpoint.

; Klibex03 - 22/07/2014     Move to, Line to
;
include 'klib.inc'                     ; Includes the kolibri library
klib                                   ; klib is the macro to get started
idle:   mov bgc,0C7D7E7h               ; set bg color
        sax                            ; display the sandbox window
        mov fgc,0                      ; black
        mt  10,20                      ; move to
        lt  50,50                      ; line to
        mov fgc,0FF0000h               ; Red
        lt  150,180                    ; line to
        jmp idle                       ; loop until closed
I_END:                                 ; obligatory label: end of our application

FRt:	Fill Rectangle
>a	Rectangle (XYwh)
>b	fill color (RGB)
The specified rectangle is filled with the specified color. (Fgc and Bgc are not used nor affected).
In Klib, rectangles are structures with four 32-bit coordinate values: x=left, y=top, w=width, h=height.

; Klibex04 - 22/07/2014     Fill Rectangle
;
include 'klib.inc'                     ; Includes the kolibri library
klib                                   ; klib is the macro to get started
idle:   sax                            ; display the sandbox window
        FRt Rt1,0                      ; black rectangle
        FRt Rt2,0xFF                   ; blue rectangle
        jmp idle                       ; loop until closed
Rt1:    dd 40,120,300,220              ; X Y w h
Rt2:    dd 0,160,270,150               ; X Y w h
I_END:                                 ; obligatory label: end of our application

FrRt:	Frame Rectangle
>a	Rect (XYwh)
>b	RGB color
<xc/yc	at the top/left coordinate (preserved)
<fgc	taken from b
The specified rectangle is framed (inside) with the specified color.

; Klibex05 - 22/07/2014     Frame Rectangle
;
include 'klib.inc'                     ; Includes the kolibri library
klib                                   ; klib is the macro to get started
idle:   sax                            ; display the sandbox window
        FrRt Rt1,0                     ; black frame
        FrRt Rt2,0xFF                  ; blue frame
        jmp idle                       ; loop until closed
Rt1:    dd 40,120,300,220              ; L T w h
Rt2:    dd 0,160,270,150               ; L T w h
I_END:                                 ; obligatory label: end of our application

oRt:	Outline a Rectangle
>a	Rect (XYwh)
>b	RGB color
>c	inset (positive:inwards, negative:outwards)
<xc/yc	set at the top/left coordinate (preserved)
<fgc	taken from b
The specified rectangle is framed (inside + inset) with the specified color.

; Klibex06 - 22/07/2014     Outline Rectangle
;
include 'klib.inc'                     ; Includes the kolibri library
klib                                   ; klib is the macro to get started
idle:   sax                            ; display the sandbox window
        FrRt Rt1,0                     ; black frame
        oRt  Rt1,0xFF,3                ; blue inline
        oRt  Rt1,0xFF0000,-3           ; red outline
        jmp idle                       ; loop until closed
Rt1:    dd 60,160,300,220              ; L T w h
I_END:                                 ; obligatory label: end of our application

baw:	black and white : set fgc=black and bgc=white
wab:	white and black : set fgc=white and bgc=black
These simple macro's without parameters are used to simplify the setting of the colors.
The baw macro is used by the next example.

dc:	Draw ascii char at Xc,Yc
>a	ascii char (0x20 to 0xFF)
>xc/yc	coordinates
>fgc	alpha + text color RGB (transparent if alpha channel is none zero)
>bgc	bg color (RGB) (ignored if alpha channel is none zero)
>cpa	code page (1=CP866, 2=CP1252)

The routine draws or overdraws a single ascii character on screen at the current xc/yc location.
Charactervalues below 0x20 are not drawn.
The fonts have a 6-pixel wide glyph, and one pixel is added in front to display a caret.
Note: At this moment, the alpha byte in the foreground color is just a transparency on/off specifier.

; Klibex07 - 22/07/2014     Draw ascii character
;
include 'klib.inc'                     ; Includes the kolibri library
klib                                   ; klib is the macro to get started
idle:   mov bgc,0xFFFF00               ; background color = yellow
        sax                            ; display the sandbox window
        mt 50,60                       ; set draw location (x,y)
        baw                            ; choose black on white
        dc 'X'                         ; draw letter X on white background
        add xc,20                      ; set draw location
        mov fgc,0xFFFF0000             ; color = transparent red
        dc 'Y'                         ; draw letter Y on the background color
        jmp idle                       ; loop until closed
I_END:                                 ; obligatory label: end of our application

Draw the ascii table in CP1252 and in CP866.
As an example, we draw the ascii table (0x20 to 0xFF) in 7 rows of 32 characters.
Predefined variable cpa is set to zero for the CP1252 codepage, and to one for the Russian "CP866" code page.
Klib defines 9 variables you can freely use to work with, named w1 to w9.
In this example we use predefined variable 'w1' and 'w2'.

; Klibex08 - 29/08/2014     Draw ascii tabel cp1252 and cp866
;
include 'klib.inc'                     ; Includes the kolibri library
klib                                   ; klib is the macro to get started
idle:   sax                            ; display the sandbox window
        mov cpa,2                      ; choose CP1252
        mov yc,20                      ; set y location
     A: mov w1,0x20                    ; start with space
     B: mov xc,20                      ; set x location
        mov w2,32                      ; 32 chars per row
     C: dc  w1                         ; draw one char
        add xc,12                      ; advance horizontal
        inc w1                         ; next ascii code
        dec w2                         ; 32 chars
        jne C                          ; loop next char
        add yc,18                      ; set y at the next row
        cmp w1,255                     ; until 0xFF
        jl  B                          ; next row
        add yc,40                      ; lower on the screen
        dec cpa                        ; cpa = russion code page
        je  idle                       ; stop if russian table is already displayed
        jmp A                          ; go to display the russion ascii table
I_END:                                 ; obligatory label: end of our application

PrTx:	Print Text
>a	text (ascii or utf8 coded)
>b	nb. chars (0=unlimited)
>xc/yc	screen coordinates
>fgc	alpha + text color RGB (transparent if alpha is none zero)
>bgc	bg color (RGB) (ignored if alpha is none zero)
>cpa	code page (0=unicode, 1=cp866, 2=cp1252)
<xc	behind the last drawn char.
The routine draws or overdraws the textline on screen starting at the current xc/yc location.
Drawing stops at the occurance of a zero, lf, cr, or a crlf. The routine does not wrap.
As an example, we draw the text "Hello World!" in cp1252. A unicode example follows later.

; Klibex09 - 22/07/2014     Hello World
;
include 'klib.inc'                     ; Includes the kolibri library
klib                                   ; klib is the macro to get started
idle:   sax                            ; display the sandbox window
        mov cpa,2                      ; choose Western latin
        mt 4,10                        ; set draw location (x,y)
        PrTx hello,0                   ; display "Hello World!"
        jmp idle                       ; loop until closed
hello:  db 'Hello World!',0            ; finally
I_END:                                 ; obligatory label: end of our application

PrTl:	Print Textline
>a	string of ascii or unicode chars
>b	width of the field in pixels (>0)
>xc/yc	coordinates of the first character
>fgc	alpha + text color RGB (transparent if alpha is none zero)
>bgc	bg color (RGB) (ignored if alpha is none zero)
>cpa	code page address (font bitmap) (inited to CP1252 if zero)
<xc	behind the last drawn char.
<Rt1	Rect of the textfield
This routine fills the textline with the background color before drawing one textline using PrTx.
The routine preserves registers c,d,e,f.

; Klibex10 - 29/07/2014     Print textline
;
include 'klib.inc'                     ; Includes the kolibri library
klib                                   ; klib is the macro to get started
idle:   mov bgc,0xFF                   ; blue window
        sax                            ; display the sandbox window
        baw                            ; black and white
        mt 10,5                        ; set draw location (x,y)
        PrTl hello,200                 ; display "Hello World!"
        jmp idle                       ; loop until closed
hello:  db 'Hello World!',0            ; finally
I_END:                                 ; obligatory label: end of our application

PrFrTl:	Print and Frame a Textline
>a	zstring (ascii or unicode)
>b	pixelwidth of the field (>0)
>c	pixelwidth of the left text margin
>d	frame color (no frame if transparency is 0xFF)
>e	inset of the frame (pixels +inwards -outwards)
>xc/yc	coordinates of the first character
>fgc	alpha + text color RGB (transparent if alpha is none zero)
>bgc	bg color (RGB) (ignored if alpha is none zero)
>cpa	code page
<xc	behind the last drawn char.
First, the routine calls PrTl to print the textline with the specified width and text with left margin.
Then, the routine calls oRt to frame the textline using the specified color and inset.

; Klibex11 - 02/09/2014     Print and frame a textline
;
include 'klib.inc'                     ; Includes the kolibri library
klib                                   ; klib is the macro to get started
idle:   mov bgc,0xFF                   ; blue window
        sax                            ; display the sandbox window
        cmp evc,1                      ; on draw request
        jne idle                       ;
        mt 15,5                        ; set draw location (x,y)
        mov fgc,0xFFFF00               ; yellow
        mov bgc,0xFF0000               ; on red
        PrFrTl tx1,400,5,0xFF00,-2     ; display in a green frame
        mt 15,30                       ; set draw location
        mov fgc,-1                     ; transparent white
        PrFrTl tx1,400,20,0xFF0000,-3  ; display in a red frame
        jmp idle                       ; loop until closed
tx1:    db 'Test of the Print and Frame a textline routine',0
I_END:                                 ; obligatory label: end of our application

DtBt:	Draw Button with centered text
>a	ascii zstring with the caption text (unicode not yet implemented in this Klib version).
>b	max.Nb.chars in caption (determines the width of the btn)
>c	Btn ID (1 is reserved for the close window button)
>d	RGB color for the button
>e	RGB color for the text (always transparent)
>xc/yc	topleft corner
<fgc	text color from e

The DtBt routine defines and draws a button with transparent centered text.
Note: When clicked, the variable btn has the ID, and eventcode is 3. This will be documented later.

; Klibex12 - 25/07/2014     Draw button with centered text
;
include 'klib.inc'                     ; Includes the kolibri library
klib                                   ; klib is the macro to get started
idle:   sax                            ; display the sandbox window
        mt 40,15                       ; set draw location (x,y)
        DtBt tx1,40,2,0xFF8899,-1      ; Btn 2 with white transp. text
        jmp idle                       ; loop until closed
tx1:    db 'Test of the DtBt routine',0
I_END:                                 ; obligatory label: end of our application

About the Thread information record (Tir)

Klib uses a 1K memory block to hold information about the current thread, window, font, and more.
The predefined variable "Tir" points to this record.
Some of its fields, named Tir-vars, are usefull by the application. They are explained in the examples that follow.
At offset 0x58, Tir has a rectangle that represents the area inside the inner borders of the current front window.
In this example, we use this rectangle to fill the entire window with a different color each time a button is pressed.
Notice that the button must be drawn (DtBt) on each redraw request (evc = 1).

; Klibex13 - 26/08/2014  Tir
;
include 'klib.inc'                  ; Include the klib library
        klib                        ; and start it up
        mov bgc,0x7799BB            ; set window color
idle:   sax                         ; display the sandbox window
        cmp  evc,1                  ; on redraw request
        je   A                      ; redraw the screen
        cmp  evc,3                  ; on click in button
        jne  idle                   ;
        mov  ecx,bgc                ; ecx = RGB
        shl  ecx,8                  ; ecx = B--
        shr  bgc,8                  ; bgc = -RG
        or   bgc,ecx                ; bgc = BRG
        mov  eax,Tir                ; eax = thread info record
        add  eax,0x58               ; eax = window rectangle
        FRt  eax,bgc                ; color the window
     A: mt   40,15                  ; position x,y
        DtBt Btx,10,2,150,-1        ; Draw the button
        jmp  idle                   ;
Btx:    db   'Hit me!',0            ; Button text       
I_END:                              ; over and out

About fn, sz, na, key,fp

Klib reserves a few small buffers to be used by some of it's routines or by the application.
When Klib starts, these buffers are all clear.
The predefined vars "fn", "sz", "na", "key", "wz" and "fp" point to them:
fn	filename (128 bytes)
sz	scrap zone (128 bytes)
na	number array (128 bytes)
key	key (128 bytes)
wz	work zone (0x500 = 1280 bytes)
fp	filepath (0x400 = 1024 bytes)

T$z:	convert a binary value to a zero terminated decimal numberstring
>a	value to convert
>b	address of the resulting zstring
The example shows the width of the screen as a decimal number.
The pixel-size of the screen is present in the Tir at offset 0x68 (width) and 0x6C (height).
Note: negative numbers get a leading minus sign.

; Klibex14 - 25/08/2014     Show a decimal number
;
include 'klib.inc'                  ; Include kolibri library
klib                                ; get started
idle:   sax                         ; show the sandbox
        mov  eax,Tir                ; eax = thread info record
        add  eax,0x68               ;
        mov  eax,[eax]              ; eax = screen width
        T$z  eax,sz                 ; make it an asciiz string in sz
        mt   20,10                  ; set x,y on screen
        PrTx sz,0                   ; print the screenwidth
        jmp  idle                   ;
I_END:                              ; over and out

Tir90 : The search path.

At this moment, the kernel expects filenames to be coded in CP866, case insensitive.
A filepath is considered an absolute full path when it starts with a "/". example "/usbhd0/1/folder1/file1".
Otherwise, a filepath is considered relative to the path of the current directory. (explained later).
A "/" behind a trailing foldername is not mandatory, but it avoids file/folder conflicts.
In addition, in Klib, a filepath is considered relative to a searchpath when it starts with a "^".
This means that Klib will search for the given filepath in the search path and all it's parent folders up to it's root.
When not found, the routine will try again by dropping the topmost parent in the given path (if any).  
The address of the searchpath (a zstring) is kept in Tir90.
During it's initialization, Klib initializes the searchstring to be the full path of the application.

Finfo:	file/folder info
>a	path (zstring)
>Tir90	searchpath
eax	error code (5 = file not found)
sz	the scrap zone is used as parameterblock
na	the number array is used as informationblock (see syscall 70):
na00	1=read-only, 2=hidden, 4=system, 8=volume-label, 10h=folder, 20h=un-archived
na08	creation time&date
na10	access time&date
na18	modification time&date
na20	file size (zero for a folder)
fp	full path after resolving a searchpath (unaffected otherwise)
The routine returns info about the specified file or folder.
In this example we display the full path of the font file "K1r.urf".
To succeed, the fontfile "K1r.urf" must exist in the application search path.

; Klibex15 - 28/08/2014   Display the fullpath of a fontfile
;
include 'klib.inc'                  ; Include kolibri library
klib                                ; get started
	 Finfo pat                   ; get file info
idle:   sax                         ; show the sandbox
        mt   20,10                  ; set x,y on screen
        PrTx fp,0                   ; print the fullpath
        jmp  idle                   ;
pat:    db   '^Klib_fonts/K1r.urf',0  ; a file on the appl.path
I_END:

Rac:	Read and Close a file (fn,bp,max.size) => bp,bs,fl
>a	filepath (z-string)
>b	bufferpointer or zero
>c	buffersize or Max.size or zero
eax	last error (zero if ok) (5=file not found, ...)
<bp	buffer pointer (specified in b, or allocated)
<bs	size of the buffer (from c or filelength)
<fl	file length (wathever the buffersize)
sz	the scrap zone is used as parameterblock (syscall 70)
na	the number array is used as informationblock (syscall 70).
The routine tries to locate and read the specified file in memory.
If no  buffer is given, then the routine will allocate a buffer asuring 8 trailing zero bytes.
When reading in a specified buffer, the data in the unread portion of the buffer is preserved.
In this example we read a small .asm file and display the first text line in ascii.
This example asumes that there is a file Klibex01.asm in a folder "Klibex_asm" in the application path.

; Klibex16 - 28/08/2014   read file
;
include 'klib.inc'
        klib
        Rac pat,0,0                 ; read a file
idle:   sax                         ; show the sandbox
        cmp evc,1                   ; when redraw requested
        jne  idle                   ;
        mt   4,10                   ; position on screen
        PrTx bp,0                   ; print the first ascii textline        
        jmp  idle
pat:    db   '^Klibex_asm/Klibex01.asm',0
I_END:

About unicode

Klib uses unicode rasterfont files (.urf) to display unicode characters.
In the urf files, the unicode values vary from 0x20 (space) to 0xFB1D. 
You can find the official unicode character charts on the internet.
There is no need for code pages when working with unicode, but you need to select a unicode font file. 
This version of KLib works with unicode rasterfonts named "K1r.urf", "K1b.urf" and "K1i.urf". (regular, bold, italic)
The Klib examples asume that these files exist in the folder "Klib/Klib_fonts" on the application path.
If you dont specify a font, then Klib will use the default K1 regular 12 font.

sfont:	Set Font and size
>a	name of the rasterfont file (0=currently choosen font)
>b	fontsize (min. 12, max. 48, 0=smallest available)
<Tir74>	font queue (queued URF tables)
>Tir78	the selected font
>Tir7C	currently chosen fontsize (copy from b or smallest size)
>Tir84	glyph margins (reset to zero)
>Tir88	default missing char (0x25A1 = square)
eax	0 when not found, copy of Tir78 otherwise

Unless already loaded, the routine loads the specified rasterfont file and adds it to the font queue.
The routine then stores the font information in the Tir vars as shown above.
If the exact font/size combination can not be found, then the routine returns without affecting the Tir vars.
If fontsize zero is specified, then the routine will choose the smallest available fontsize for that font face.
In this example, we specify the K1 regular font and display its smallest size (which is 12).
If the displayed size is zero, that means that the font could not be loaded properly.

; Klibex21 - 25/08/2014     Set font
;
include 'klib.inc'
        klib
        Sfont k1r,0                    ; choose K1 regular
idle:   sax                            ; show the sandbox
        mov edx,Tir                    ; edx = tir
        add edx,0x7C                   ;
        mov eax,[edx]                  ; eax = fontsize
        T$z eax,sz                     ; make it ascii
        mt 20,10                       ; set screen x,y
        PrTx sz,0                      ; show the result
        jmp idle                       ; loop
I_END:

duc:	Draw unicode char at Xc,Yc
>a	unicode char
>xc/yc	screen coordinates
>fgc	alpha + text color RGB (transparent if alpha channel is none zero)
>bgc	bg color (RGB) (ignored if alpha channel is none zero)

The routine draws or overdraws a single unicode character on screen at the current xc/yc location in the current face and style.
Charactervalues below 0x20 are not drawn. Unknown characters are drawn with the missing character symbol.
In this example we draw the letters "X", and "ὡ".

; Klibex22 - 29/08/2014     Draw unicode character
;
include 'klib.inc'                     ; Includes the kolibri library
        klib                           ; klib is the macro to get started
        Sfont k1r,22                   ; choose K1 regular 22
idle:   mov bgc,0xFFFF00               ; background color = yellow
        sax                            ; display the sandbox window
        mt 50,60                       ; set draw location (x,y)
        baw                            ; choose black on white
        duc 'X'                        ; draw letter X on white background
        add xc,20                      ; set draw location
        mov fgc,0xFFFF0000             ; color = transparent red
        duc 0x1F61                        ; draw letter ὡ on the background color
        jmp idle                       ; loop until closed
I_END:                                 ; obligatory label: end of our application

Example: draw Greek, Coptic, and Cyrillic glyphs
As an example, we draw the unicodes (0x400 to 0x520) in rows of 32 chars in "K1 regular 18"
; Klibex23 - 29/08/2014     Draw Greek, Coptic, Cyrillic
;
include 'klib.inc'                     ; Includes the kolibri library
        klib                           ; klib is the macro to get started
        Sfont k1r,18                   ; choose K1 regular 18
idle:   mov bgc,0xFFFF80               ; background color = yellow
        sax                            ; display the sandbox window
        cmp evc,1                      ;
        jne idle                       ; when requested
        mov yc,20                      ; top margin
        mov w1,0x400                   ; w1 = unicode
     A: mov xc,20                      ; left margin
     B: duc w1                         ; draw the unicode
        inc eax                        ; widen the text
        add xc,eax                     ; apply character spacing
        inc w1                         ; next unicode
        mov eax,w1                     ;
        and eax,0x1F                   ; every 32 chars
        jne B                          ;
        mov ebx,Tir                    ;
        mov eax,[ebx+0x80]             ; get lineheight
        add yc,eax                     ; next line
        cmp w1,0x520                   ; until 0x520
        jne A                          ;
        jmp idle                       ; loop
I_END:

Example: border clipping
A similar example is given here to illustrate clipping wihtin the borders of the window.
; Klibex24 - 29/08/2014     Illustrate window border clipping
;
include 'klib.inc'                     ; Includes the kolibri library
        klib                           ; klib is the macro to get started
        Sfont k1r,22                   ; choose K1 regular
idle:   mov bgc,0xFFFFA0               ; background color = yellow
        sax                            ; display the sandbox window
        cmp evc,1                      ;
        jne idle                       ; when requested
        mov yc,-12                     ; negative top margin
        mov w1,0x40                    ; w1 = unicode
     A: mov xc,-5                      ; negative left margin
     B: duc w1                         ; draw the unicode
        inc eax                        ; widen the text
        add xc,eax                     ; apply character spacing
        inc w1                         ; next unicode
        mov eax,w1                     ;
        and eax,0x3F                   ; every 64 chars
        jne B                          ;
        mov ebx,Tir                    ;
        mov eax,[ebx+0x80]             ; get lineheight
        add yc,eax                     ; next line
        cmp w1,0x600                   ; until 0x600
        jne A                          ;
        jmp idle                       ; loop
I_END:

Example: draw text in various sizes and styles
As an example, we draw the alphabet in different sizes and styles:
; Klibex25 - 29/08/2014     Draw in various sizes and styles
;
include 'klib.inc'                     ; Includes the kolibri library
        klib                           ; klib is the macro to get started
idle:   sax                            ; display the sandbox window
        cmp evc,1                      ;
        jne idle                       ; when requested
        mov yc,20                      ; set top margin
        Sfont k1r,0                    ; choose K1 regular
        call R                         ; 12,14,16,18,22
        Sfont k1b,0                    ; choose K1 bold
        call R                         ; 12,14,16,18,22
        Sfont k1i,0                    ; choose K1 italic
        mov w0,16                      ; 16
        call P                         ;
        mov w0,18                      ; 18
        call P                         ;
        jmp idle                       ; loop
     R: mov w0,12                      ; 12
        call P                         ;
        mov w0,14                      ; 14
        call P                         ;
        mov w0,16                      ; 16
        call P                         ;
        mov w0,18                      ; 18
        call P                         ;
        mov w0,22                      ; 22
        call P                         ;
        add yc,20                      ; a little lower
        ret                            ;
     P: Sfont 0,w0                     ; set fontsize
        mov w1,"A"                     ; w1 = unicode char
        mov xc,4                       ; left margin
     Q: duc w1                         ; display
        inc eax                        ; extra spacing
        add xc,eax                     ; char.spacing
        inc w1                         ; next unicode
        cmp w1,"z"                     ;
        jle Q                          ; A-z
        mov ebx,Tir                    ;
        mov eax,[ebx+0x80]             ; get lineheight
        add yc,eax                     ; next line
        ret                            ;
I_END:

Example: print embedded text in cp866, cp1252, and unicode.

This example illustrates the use of the PrTx routine using code pages and utf8 coded unicode.
>cpa	code page (0=unicode, 1=cp866, 2=cp1252)

; Klibex26 - 30/08/2014    display an utf-8 coded text file
;
include 'klib.inc'
        klib
idle:   sax                            ; display the sandbox window
        cmp evc,1                      ;
        jne idle                       ; when requested
        mt  10,5                       ; set origin
        mov cpa,2                      ;
        PrTx tx1,0                     ; Western Latin
        add xc,20                      ;
        mov cpa,1                      ;
        PrTx tx2,16                    ; 16 cp866 chars
        add xc,20                      ;
        mov cpa,0                      ;
        PrTx tx3,0                     ; utf8-coded unicode
        jmp idle                       ;
tx1:    db 'Bonjour Maître Valère.',0  ; cp1252
tx2:    db 80h,81h,82h,83h,84h,85h,86h,87h  ; cp866
tx3:    db 0E2h,95h,90h,0E2h,95h,91h   ; utf8-coded unicode
        db 0E2h,95h,92h,0E2h,95h,94h
        db 0E2h,95h,95h,0E2h,95h,96h
        db 0E2h,95h,98h,0E2h,95h,9Eh
        db 0E2h,95h,0A3h,0
I_END:

TBox:	Draw text in a box
>a	text(utf8-coded or ascii text)
>b	address of a bounding rectangle (L,T,w,h in windowcoordinates) or zero
>c	Alignment (0=left, 1=right, 2=center, 3=justified, + flags)
>fgc	alpha + text color RGB (transparent if alpha is none zero)
>bgc	bg color (RGB) (ignored if alpha is none zero)
>cpa	code page (0=unicode, 1=cp866, 2=cp1252)
>Tir7C	selected font (considered only for unicode)
<xc/yc	behind the last drawn char.
The routine draws or overdraws the text on screen in the specified rectangle.
Drawing stops on a nul char, or when reaching the edge of the rectangle.
In this version of Klib, the alignment is left, monospaced, and wrapping and clipping is not yet implemented.
Other functions (alignment, tabstops, wrapping, spacing . . .) will be implemented in a later version.

In this example we print the source of Klibex01.asm in cp1252.

; Klibex27 - 01/09/2014    display text in a box
;
include 'klib.inc'
        klib
        mov cpa,2                      ; cp1252
        Rac fina,0,2000                ; read the file
idle:   sax                            ; display the sandbox window
        cmp evc,1                      ;
        jne idle                       ; when requested
        TBox bp,box,0                  ; draw the text
        oRt box,0xFF0000,-2            ; outline the rectangle
        jmp idle                       ; that's it
box:    dd 10,5,500,100                ; box to draw in
fina:   db '^Klib/Klibex_asm/Klibex01.asm',0
I_END:

Example: draw the text from a cp866, cp1252, and unicode testfile

; Klibex28 - 01/09/2014    display testfiles cp866, cp1252, utf8
;
include 'klib.inc'
        klib
        Rac tf1,0,2000                 ; read file 1 in w1
        push bp
        pop w1
        Rac tf2,0,2000                 ; read file 1 in w2
        push bp
        pop w2
        Rac tf3,0,2000                 ; read file 1 in w3
        push bp
        pop w3
idle:   sax                            ; display the sandbox window
        cmp evc,1                      ;
        jne idle                       ; on draw request
        mov cpa,1                      ; cp866
        mov dword[box+4],10            ; reset top
        TBox w1,box,0                  ; draw w1 in box
        mov eax,yc                     ;
        add eax,20                     ; a little lower
        mov [box+4],eax                ; set as top
        mov cpa,2                      ; cp1252
        TBox w2,box,0                  ; draw w2 in box
        mov eax,yc                     ;
        add eax,20                     ; a little lower
        mov [box+4],eax                ; set as top
        mov cpa,0                      ; unicode
        TBox w3,box,0                  ; draw w3 in box
        jmp idle                       ; that's it        
box:    dd 10,5,500,100                ; box to draw in
tf1:	 db '^Klib/Klibex_testfiles/Cp866.txt',0   ; cp866
tf2:	 db '^Klib/Klibex_Testfiles/Cp1252.txt',0  ; cp1252
tf3:	 db '^Klib/Klibex_testfiles/Utf8.txt',0    ; utf8-coded unicode
I_END:

Example: print textline with bold and italic

; Klibex29 - 01/09/2014    print textline
;
include 'klib.inc'
        klib
idle:   mov bgc,0xFF                   ; blue window
        sax                            ; display the sandbox window
        cmp evc,1                      ;
        jne idle                       ; on draw request
        Sfont k1r,12                   ; regular 12
        mt  20,5                       ; here
        baw                            ; black on white
        PrTl tx1,300                   ; show it
        Sfont k1b,14                   ; bold 14
        mt  20,25                      ; here
        mov fgc,-1                     ; tranparent white
        PrTl tx1,300                   ; show it
        Sfont k1i,18                   ; Italic 18
        mt  20,45                      ; here
        mov fgc,0xFF                   ; blue text
        mov bgc,0xFFFF00               ; yellow canvas
        PrTl tx1,400                   ; show it
        jmp idle
tx1:	 db 'A test of the Print Textline routine.',0
I_END:

Keyboard activity

The sand routine reports keyboard activity via predefined variables.
evc :	event code 2 = a key with printable caption has been pressed (key-down)
	event code 4 = a key has been released or a key with none-printable caption has been pressed. 
kbc :	keyboard code (last inkeyed printable unicode 0x20 up to 0xFFFF)
kbs :	keyboard scan code 0x01 to 0x5F, (+ 0x80 for key-up)
kcc:	keyboard control key bits reflect the status of the controlkeys (shift, ctrl, Alt, ...) at the moment of the stroke.

Klib enters the key translation and dead-key data from external files.
The name of the files is "Keymaps.txt" and "DeadKeys.txt". 
Both files must be in the Klib_world folder on the application path.
The alt-numkey option allows the entry of numbers up to 64K.
Use the KbTool application to see the scancodes for your keyboard.

Print printable keystrokes

The sand routine reports keyboard activity via predefined variables.
evc :	event code. 2 = a key with printable caption has been pressed (key-down)
kbc :	keyboard code (last inkeyed printable unicode 0x20 up to 0xFFFF)
The sand routine stores the unicode of the last printable keystroke in predefined variable kbc.
The unicodes are generated according the keyboard layout choosen by the user (country code).
The sand routine takes care of dead key handling as specified by the keyboard map for the chosen country.
The  sand routine implements the AltNumkey method to produce any unicode above 0x20, using the left Alt key.
In this example we draw the last inkeyed character on screen, overdrawing the previous character.
Use the KbTool1 application to select another keyboard in order to view different code sets.

; Klibex30 - 25/07/2014     Print the printable keystrokes
;
include 'klib.inc'                     ; Includes the kolibri library
klib                                   ; and start it up
idle:   sax                            ; display the sandbox window
        mt  5,15                       ; set draw location (x,y)
	 PrTx tx1,0                     ; Type here:
        cmp evc,2                      ; has a printable char been typed?
        jne idle                       ; if so, 
        duc kbc                        ; draw the inkeyed character
        jmp idle                       ; loop until closed
tx1:    db 'Type here: ',0             ;
I_END:                                 ; obligatory label: end of our application

Sland:	Select keyboard layout for a country
>a	country code (two ascii letters) or "next" for next marked layout
>b	if set to "umor" : unmark all other records
TirA4	table with keymap records (loaded from the keymaps.txt file)
TirA8	pointer to the selected kb record (inside TirA4 table)
The sland routine selects the keyboard layout for the specified country.
More then one keyboard layout can be selected.
In future, Klib will allow circling through the layouts using a special key combination (???).
Unless already loaded, the routine loads the Keymaps.txt and deadkeys.txt files in memory (TirA4).
If "next" is specified in a (the b parameter is ignored): 
If TirA8 is zero, then the routine sets TirA8 to  the first marked record.
I no record is marked, then the routine uses the kernel setting.
If TirA8 is not zero, then the routine sets TirA8 to the next marked record, ring around if needed.
If there is no next record marked, then the routine simply exits without modification.
If a country code is specified:
The routine scans the keymaps and sets TirA8 to the record for the specified country.
If b specifies "umor", then the routine unmarks all other country records.

The routine updates the keymaps.txt file to remember the setting (unless read-only).
In future, the sand routine will show the selected country code in the status bar of the desktop.
On error, the routine exits without changing the Tir vars.
Note: the routine does not affect the kernel keyboard selection.
Note: See the file structure in keymaps.jpg, view the contents with Notepad.

In this example we select keyboard layout 'Pr' with funny unicode characters. 
Use KbTool1 to restore the setting.
As an exercise: modify the source to preserve the keyboard selection.

; Klibex31 - 10/09/2014     Select a keyboard layout
;
include 'klib.inc'                     ; Includes the kolibri library
klib                                   ; and start it up
        Sland 'Pr'                     ; select keyboard
idle:   sax                            ; display the sandbox window
        mt  5,5                        ; set draw location (x,y)
	 PrTx tx0,0                     ; The . . . is selected
        mt  5,25                       ; set draw location (x,y)
	 PrTx tx1,0                     ; Type unicode here:
        cmp evc,2                      ; has a printable char been typed?
        jne idle                       ; if so, 
        duc kbc                        ; draw the inkeyed character
        jmp idle                       ; loop until closed
tx0:    db 'The Private Personal keyboard is selected',0
tx1:    db 'Type here: ',0             ;
I_END:                                 ; obligatory label: end of our application

Textfield edit

The textfield edit routines are not yet unicode ready and are left out of this Klib version.
TEnew:	Create a new Text Edit record
DrFld:	Draw a field
TEkey:	Handle a printable keystroke for an editable field
TEhkc:	Handle keyboard control keys for a field

Epilog:

Missing details about structures and the internals of the KLib library will be published In next versions of this tutorial.
Note that Klib is an object included library. Klib is not a shared library! I did not qualify the routine names.
A missing or changed Klib library will not affect your applications until you compile them again.
Klib itself is written in Mas (Modern assembly).
I will publish the source of Klib as soon as the "Mas" IDE is implemented on Kolibri.