You are on page 1of 20

BLAISE

BLAISE PASCAL
PASCAL MAGAZINE
MAGAZINE
27
27
D E L P H I,

L A Z A R U S,

OXYGEN

(P R I S M), A N D

PASCAL

RELATED

LANGUAGES

Introduction to thread programming in Lazarus


By Michal Van Canneyt
Introduction to Databases Part 11:
DataSnap Filters and Security
By Cary Jensen
Electronic document processing tools
for Delphi made by Gnostice
By Grish Patil
Use of the "absolute" function abs(..)
By David Dirkse

Development for lazarus


By Joost van der Sluis

What is polymorphism?
By Vsevolod Leonov
Creating and using kbmMW as an Ajax back-end server
By Benno Evers

1 / 2013
Publisher: Foundation for Supporting the Pascal Programming Language
in collaboration with the Dutch Pascal User Group (Pascal Gebruikers Groep)
Stichting Ondersteuning Programmeertaal Pascal

27
BLAISE
BLAISE PASCAL
PASCAL MAGAZINE
MAGAZINE 27
D E L P H I,

L A Z A R U S,

OXYGEN

(P R I S M), A N D

PASCAL

RELATED

CONTENTS

V O L U M E 2 7,

I S S N 1 8 7 6-0 5 8 9

Editor - in - chief
Detlef D. Overbeek, Netherlands
Tel.: +31 (0)30 890.66.44 / Mobile: +31 (0)6
21.23.62.68

Articles
Introduction to thread programming in
Lazarus
By Michal Van Canneyt
Page
Introduction to Databases Part 11:
DataSnap Filters and Security
By Cary Jensen
Page
Electronic document processing tools
for Delphi made by Gnostice
By Grish Patil
Page
Use of the "absolute" function abs(..)
By David Dirkse
Page
.iOS Development for lazarus
By Joost van der Sluis
Page
What is polymorphism?
By Vsevolod Leonov
Page
Creating and using kbmMW
as an Ajax back-end server
By Benno Evers
Page

13

23
36
41
48

News and Press Releases


email only to editor@blaisepascal.eu
Authors
A
B
C
D
F
G
H
J
L
M
N
O
P
S

Alexander Alexeev
Peter Bijlsma,
Michal Van Canneyt, Marco Cant,
David Dirkse, Daniele Teti
Bruno Fierens
Primo Gabrijeli,
Fikret Hasovic
Cary Jensen
Wagner R. Landgraf, Sergey Lyubeznyy
KIm Madsen, Felipe Monteiro de Cavalho
Jeremy North,
Tim Opsteeg, Inoussa Ouedraogo
Howard Page-Clark,
Henk Schreij, Rik Smit, Bob Swart,

Editors
Peter Bijlsma, W. (Wim) van Ingen Schenau,
Rik Smit

52

Correctors
Howard Page-Clark, James D. Duff
Copyright Page 118
Trademarks All trademarks used are
acknowledged as the property of their respective
owners.
Caveat Whilst we endeavour to ensure that what is
published in the magazine is correct, we cannot
accept responsibility for any errors or omissions.
If you notice something which may be incorrect,
please contact the Editor and we will publish a
correction where relevant.
Subscriptions ( 2013 prices )
1: Printed version: subscription 60.-(including code, programs and printed magazine,
6 issues per year including postage).
2: Non printed subscription 40.-Incl. VAT 21% (including code, programs and
download magazine)
Subscriptions can be taken out online at

Advertisers

www.blaisepascal.eu

Barnsten
BetterOffice
Components 4 Developers
Delphi Developer Days
FastReport
Learn to program using Lazarus
Lazarus the complete guide
Parallel Programming
with Omnithread Library
Smart Mobile Studio

page
page
page
Page
Page
page
page

47
12
60
3
40
39 / 51
51

page 22
page 24

Copyright notice
All material published in Blaise Pascal is copyright SOPP Stichting
Ondersteuning Programeertaal Pascal unless otherwise noted and
may not be copied, distributed or republished without written
permission. Authors agree that code associated with their articles will
be made available to subscribers after publication by placing it on the
website of the PGG for download, and that articles and code will be
placed on distributable data storage media. Use of program listings
by subscribers for research and study purposes is allowed, but not for
commercial purposes. Commercial use of program listings and code
is prohibited without the written permission of the author.

LANGUAGES

COMPONENTS
DEVELOPERS

or by written order, or by sending an email to

office@blaisepascal.eu
Subscriptions can start at any date. All issues
published in the calendar year of the subscription will
be sent as well.

Subscriptions run 365 days.


Subscriptions will not be prolonged without notice.
Receipt of payment will be sent by email.
Subscriptions can be paid by sending the payment to:
ABN AMRO Bank Account no. 44 19 60 863
or by credit card: Paypal or TakeTwo
Name: Pro Pascal Foundation-Foundation for
Supporting the Pascal Programming Language
(Stichting Ondersteuning Programeertaal Pascal)
IBAN: NL82 ABNA 0441960863
BIC ABNANL2A VAT no.: 81 42 54 147
(Stichting Programmeertaal Pascal)

Subscription department
Edelstenenbaan 21 / 3402 XA IJsselstein,
The Netherlands / Tel.: + 31 (0) 30 890.66.44 /
Mobile: + 31 (0) 6 21.23.62.68

office@blaisepascal.eu

Nr 1 / 2013 BLAISE PASCAL MAGAZINE

Don't Miss! Delphi Developer Days 2013

www.DelphiDeveloperDays.com

Delphi Developer Days 2013


Featuring Bob Swart & Cary Jensen
Bob Swart and Cary Jensen present Delphi Developer Days 2013, a Delphi training tour in the
United State and Europe. Delphi Developer Days is an intense two-day live event where you
will experience both joint sessions, presented by Bob and Cary together, as well as
simultaneous tracks. Some of the topics covered include browser-based clients, essential
through advanced database development, from VCL to FireMonkey, mobile development and
Delphi's NextGen Compiler, data access components, DataSnap, REST versus DBX, XML
and JSON, SOAP, debugging applications, writing Windows services, and gestures and touch
in Delphi applications. There's also an Embarcadero keynote, plus a session by a guest
speaker.

Delphi Developer Days 2013 Dates and Cities


Date

City

Location

6-7 May 2013

Chicago, USA

Holiday Inn Express NW O'Hare

30-31 May 2013

Frankfurt, Germany

Holiday Inn Express Frankfurt

3-4 June 2013

Amsterdam, NL

Park Plaza Victoria Amsterdam

Seating is limited to 42 people per city.

Attendees Receive:
An extensive course book (several hundred pages) written by Bob and Cary
that includes material covered in their joint and individual sessions
Source code examples from all of their sessions
A chance to win valuable prizes from our sponsors
Lunch on both days

Register early for an additional discount. Previous attendee and group discounts are available.

Register Now to Reserve Your Space!

www.DelphiDeveloperDays.com
Nr 1 / 2013 BLAISE PASCAL MAGAZINE

Introduction to thread programming in Lazarus


By Michal Van Canneyt
starter

TThreadList

expert Lazarus 1

This is a special list which can be locked for exclusive


access by a thread. It is declared in the classes unit.

Because of the complexity of the subject we have asked


The Author (Michael van Canneyt) on behalf of showing
and making Delphi and Lazarus more compattible to help
demonstrating the processes.

This class can be used to make sure a particular piece of


code is executed only by one thread at a time. It is declared
in the syncobjs unit.

Abstract

3 The TThread class

Thread support in Free Pascal has received an update,


so it is compatible to thread support in Delphi XE3. Time
to re-visit the subject of threads, and look at the
possibilities for those not familiar with thread
programming.

1 Introduction
Recently, FPC received a substantial upgrade in its
threading code. It has been made compatible with the
Delphi XE3 threading possibilities. Time for a refreshment
on how to do threading in Lazarus/Free Pascal.
Threading means writing the code of an application so that
several parts of the code are executed simultaneously, in
parallel. Each part of the code forms a thread of execution.
Threading requires support by the hardware: several
processors or a processor with various cores. If the
hardware does not allow it, the operating system mimics
simultaneous execution by giving the various parts of the
program time to execute in an intertwined fashion,
much like it allows multiple programs to execute
simultaneously. The scheduling of threads and programs
by the operating system is a huge subject in itself, and is
done differently by each OS.
The difference between threads and multiple programs
is of course that all threads in a program all have access to
the same data and memory space. Programs can share
some memory by using shared memory and special
operating system calls. Access to the shared memory by the
various threads must be carefully designed, or strange
things may happen: As long as one thread only writes and
another thread only reads from a shared memory location,
things will usually progress without problems. However, if
threads will try to update the same memory location,
strange things may happen. To prevent
this, special programming is required. In this article, well
show how this is done.

TCriticalSection

From the classes presented above, the most important class is


TThread. It has at least the following public methods:
Start
this will start execution of the thread if it was created in a
suspended state.
Terminate
Tells the thread to stop executing at the earliest possible time.
WaitFor
This waits for the thread to end, and returns the exit code of
the thread.
And some properties:

FreeOnTerminate
This property is described in detail below.
Handle
An operating system handle for the thread.
ThreadID
An operating system ID for the thread.
ExternalThread
A boolean indicating whether this thread was started outside
the RTL.
Priority
An indicator of the threads priority.
Suspended
A Boolean indicating whether the thread is currently
executing or not.
Finished
A Boolean indicating whether the thread has finished
executing.
OnTerminate
An event handler that is calledwhen the thread has finished
executing.
FatalException
If an exception is raised during the execution of the thread,
but is not caught by user code, then it is caught and held here
for inspection.

2 Thread support classes in Free Pascal


There are also some protected methods, only available inside
the TThread class and its descencents:
Execute
A virtual abstract method that must be overridden.
Synchronize
Allows to schedule a procedure for execution in the main
TThread
This is the heart of the threading system:
thread. The thread waits till it has finished executing.
This class encapsulates a thread in a program. It is declared Queue
Allows to schedule a procedure for execution in the main
in the classes unit.
threadvar
thread. The thread does not wait till it has finished executing,
This is a special kind of variable:
but continues at once.
global variables are normally accessible by all threads in a
And 2 protected properties:
ReturnValue
program. When they are declared as threadvar instead of
This is an integer value that can be set to report back at the
var, each thread in the program will receive its own copy
end of the thread.
of the global variable.
TMultiReadExclusiveWriteSynchronizer
It is the value that is reported when WaitFor is used.
Terminated
This class serves to protect access to a piece
This is a flag that must be regularly checked during
of data such that it can be read simultaneously by various
execution of the thread: when it is set to True, the thread
threads, but can be written
should stop executing. It is set by the Terminate method.
only by one thread. It is declared in the sysutils unit.
The threading support of Free Pascal makes it relatively
simple to create multi-threaded programs. FPC provides
several classes and a language construct to deal with
multiple threads in a program:

COMPONENTS
DEVELOPERS

Nr 1 / 2013 BLAISE PASCAL MAGAZINE

Introduction to thread programming in Lazarus (Continuation 8 End)


Note that the main form does not use the critical section
when reading the data. The result can be seen in figure 4
on page 18. It is left as an exercise to the reader to find out
why it would be more correct to update the display in a
critical section as well.

9 Conclusion
Threads can be very useful when performing lengthy
tasks in the background. The thread support in Free
Pascal makes it very easy to do. Having multiple threads
perform tasks in the background while accessing and
modyfing the same shared data is a bit more tricky, but
can be done as well with standard classes provided by
Free Pascal.

12

COMPONENTS
DEVELOPERS

About the Author


Michael van Canneijt
is one of our important authors. He writes several
books and articles, yet an other to come:
The Pascal Bible a book we will present later
this year.
He is the main author behind our legendary first
book over Lazarus: Lazarus the complet guide.
He nowadays is working for MailJet in Paris.
He is the main man behind FPC Pascal and has an
enormous knowledge of Pascal, Delphi Free pascal
and Lazrus in many ways.

Nr 1 / 2013 BLAISE PASCAL MAGAZINE

Introduction to Databases Part 11: By Cary Jensen


DataSnap Filters and Security
starter

expert

Delphi 10 and later

In the preceding article in this series I walked you through the creation of a
simple IP-based DataSnap Server, which Embarcadero refers to as a
DataSnap DBX Server (as opposed to DataSnap REST). In this article I am
going to go into greater depth, and discuss the use of server class lifecycle,
authorization, authentication, and filters. I will begin this discussion by
exploring the various classes that are involved in the creation of a DataSnap
server (these apply to both DBX and RESTful DataSnap servers).

Figure 1. Page 2 of the DataSnap Server wizard.


DataSnap Server Components
Let's begin by creating a new DataSnap server. However, unlike the simple server that
we created in the preceding article in this series, this time we will ask the DataSnap
Server wizard to add additional capabilities to our server.
1.
2.
3.
4.

Close any open projects. Then, select


File | New | Other from Delphi's main menu.
Select the DataSnap Server tab under the
Delphi Projects tab.
Double-click the DataSnap Server icon to launch
the DataSnap Server wizard
For convenience, select the VCL Forms Application option from page 1 of the
DataSnap Server wizard. This option makes it easy to create and debug your
DataSnap server, though as I mentioned in the preceding article, you will eventually
want to convert this application to a Windows service before you deploy it. Click
Next to advance to page 2 of the DataSnap Server wizard, shown in Figure 1.

Nr 1 / 2013 BLAISE PASCAL MAGAZINE

COMPONENTS
DEVELOPERS

13

m
ra 0
g
o
Pr us 1.
o
n t ar
ar Laz
e
L g
in
us

Primo
A Smart Book Gabrijeli

Primo
Gabrijeli

Parallel Programming
with OmnithreadLibrary

Pa

SMART MOBILE
STUDIO

ar
ow

ar

Cl

ge

o i
im l
Prrije
ab

OO

B
RT

MA

AS

T
EN
PM
LO TH
VE L WI
E
B D CA
WE PAS
IN

IO

UD

T
ES

BI

O
TM

AR

SM

i
jel org
barmimer.
a
G r

rog
mortp
Pwrwi.sma
w

AL
SC
A
P
SE
AI
L
B

NE
ZI
A
G
MA

BLAISE PASCAL MAGAZINE


publishes two new books, written in English

Author Primo Gabrijeli

Parallel Programming
with Omnithread
Library,
and

Smart Mobile Studio


http://www.blaisepascal.eu/index.php?
actie=./subscribers/UK_Book_Department

Electronic document processing tools for Delphi By Grish Patil


made by Gnostice
The Gnostice document-processing components
for Delphi have been devloped to their present
high-performance level simply to meet the needs
of their customers - indeed necessity is the
mother of invention.
This article charts their development detailing
their present technical capabilities, and looks to
future development as well.
History
A classmate and I were working as software
consultants in the late 90s, when a customer
requested inclusion of a particular feature in
software we had developed for him: he wanted the
application to generate reports that could be
distributed easily, and viewed in any web browser.
We had developed the application using
QuickReport which, at that time, generated textonly HTML output and did not handle deeply nested
report sub-detail. We had created a separate
QuickReport report viewer app that had to be
distributed to his employees, which was really
cumbersome to deploy. So we then developed a
WYSIWYG HTML export filter for QuickReport,
based on TQRExportFilter.
TGPQRHTMLExportFilter = class(TQRExportFilter)
// Public content-creation methods were overridden
procedure BeginDoc; override;
procedure TextOut(X, Y: Integer;
Text: string); override;
Figure 1: The HTML filter was derived from
procedure EndDoc; override;
the generic QuickReport export filter:
// Missing content-creation methods were introduced
procedure DrawImage(X, Y: Integer; Image: TGraphic);
procedure DrawShape (X, Y: Integer;...);

Custom controls were derived from all the QuickReport


controls (content elements) so we could send more report
content information to the new HTML filter. This enabled
the filter to generate WYSIWYG HTML output internally:

Evolution to the present day

We had started supporting multiple reporting tools.


The export component for each tool was a separate product
and the code was tightly coupled with it.
TGPQRImage = class(TQRImage)
We felt the need to have a single codebase and wanted to
procedure Draw(...); override;
decouple the logic of the format-generation engine from
Our new custom controls' overridden Draw methods could that of report-specific code. Necessity was again driving
invention.
call our new content-creation methods introduced in the
We also wanted to be able to adapt to any possible
TGPQRHTMLExportFilter:
future document-creation requirement, and this was
procedure TGPQRImage.Draw(...);
achieved by supporting standard printing and Windows
if Report.Exporting and (Report.ExportFilter
graphics-drawing mechanisms. Our truly multi-talented
is TGPQRHTMLFilter) then
TGPQRHTMLFilter(Report.ExportFilter).Draw eDocEngine was born out of this refactoring, offering many
ways to create report content. eDocEngine has remained a
Image(...);
cutting-edge multi-format document-creation engine.
The HTML filter was a big hit with our customer and was
quickly followed by filters for other formats including
WYSIWYG filters for PDF and RTF.
Since the customer's reports had to use these custom
report controls, I created an application that went through
any reporting project and upgraded it to use the new
controls. With just a few clicks, his existing report projects
were upgraded to generate WYSIWYG HTML, PDF (and
other format) reports.
Other customers loved this product too.
It soon came to define our company's main product line.
The company we had envisioned long before Gnostice
was founded in 2002 to concentrate on developing
electronic document processing tools.

Nr 1 / 2013 BLAISE PASCAL MAGAZINE

COMPONENTS
DEVELOPERS

23

Electronic document processing tools for Delphi (Continuation 1)


HTML, RTF
metafile viewer
exporter
components

Delphi
Reporting
Tools

Your GDI or
TCanvas Drawing
code

Metafiles, RTF,
text, images

eDocEngine
Content-Creation
API (pages,
paragraph, tables,
headers, footers
from fields,
annotation, etc.)

eDocEngine VCL
Document - Creation
Components

Report - Export Interface


Components

PDF

RTF

HTML

XLS

CSV

BMP

PNG

JPG

SVG

EMF

WMF

Figure 2: Schematic overview of the overall system


eDocEngine can create content in:
PDF, RTF, HTML, XHTML, EXCEL, TEXT, CSV,
Quattro Pro, LOTUS 1-2-3, DIF, SYLK, TIFF,
PNG, SVG, JPEG, GIF, BMP, EMF and WMF formats.
Also included are report-export adapters
(we call them Export Interfaces) for many popular Delphi
reporting tools:
AceReporter,
DevExpress Printing System,
FastReport,
GmPrintSuite,
QuickReport,
Rave Reports,
ReportBuilder,
ScaleRichView,
ThtmlViewer,
TMS Grid,
TRichView,
WPRichText,
WPTools

Here's how:
1. Drop a format engine component (say PDFEngine)
TgtPDFEngine - to export to PDF
2. Drop the appropriate report export interface (say
FrExportInterface)
TgtFRExportInterface - to connect with FastReport
3. Wire the export interface to the format engine
Select PDFEngine as the value for FREExportInterface
object's Engine property
Now, when we run the application and preview the report,
the option to save to PDF magically appears in the report.
(See the next page top)
eDocEngine's document-creation engines are really mature
and include many of the advanced features that you
usually find only in specialized tools. For example, the PDF
engine includes support for on-the-fly digital signing

Figure 3: The Toolpalette


With these report-export interfaces, users can export
reports without writing any code. This lets you add
high-quality report-export capability to existing
applications in just three simple steps.

24

COMPONENTS
DEVELOPERS

Figure 4: It offers export of charts as vector graphics


and RichText content as rich text to retain hi-fidelity

Nr 1 / 2013 BLAISE PASCAL MAGAZINE

Electronic document processing tools for Delphi (Continuation 12)


Future plans, continuing Present
Increasingly demanding requirements need ever smarter solutions! As our insight into document creation, rendering and
analysis has deepened we have struck out in fresh directions with our product technology. Our goal now is to provide a
single toolset that enables developers to perform any kind of document-processing operation in any format. Our
customers will not have to be concerned about using different toolkits for different operations on documents. They will
also be writing much less code.
This is not just an integration of all the products we have created thus far, but a fresh start and a brand-new extensible
and seamless architecture. We call this product XtremeDocumentStudio
The first area we decided to tackle was viewing of DOCX
and PDF formats. Our engineers have already done a great
job on the .NET version and we are working on the Delphi
version. For now, let us see a sample from the .NET version
using Delphi Prism. We will be creating a DocX/PDF viewer
application.

Figure 19: Graphic depicting some of the major


document processing functions that
XtremeDocumentStudio will enable.

1. Create a new Windows Form project.


2. Drop a Gnostice DocumentViewer control on the form.
3. Drop other controls such as an Open File Dialog,
a toolstrip for the toolbar button and the required buttons.
4. Program event handlers of the buttons with
DocumentViewer methods such as the NextPage and
PreviousPage.
5. Program the Open button to load the selected document
into the DocumentViewer using the LoadDocument
method.
That's it! We are ready to run the multi-format document
viewer.

Figure 20: A multi-format document viewer created using XtremeDocumentStudio.

We know from experience that the Delphi developer community is a great adopter of tools and components. However
we were still surprised at the overwhelmingly positive response to our new tools presentation at the 2012 Delphi Tage
conference in Germany. We are very excited about the future and the upcoming releases of next-generation documentprocessing toolsets both for Delphi and Delphi Prism developers.

Nr 1 / 2013 BLAISE PASCAL MAGAZINE

COMPONENTS
DEVELOPERS

35

Use of the "absolute" function abs(..) By David Dirkse


starter

expert

Delphi 3 and later, and Lazarus

The Delphi "system" unit contains a function


abs(x) which returns the absolute value of
variable x. The parameter x can be either an
integer or a real value.
So,
abs(+15) = 15
abs(-15) = 15
Note that the abs function actually combines two functions
because:

In the plot above the scale of a rectangle is 0.2


Point (0,0) is positioned at an acute angle in the line. This is
a unique property of the abs function. All other functions
like log, sin, cos, tan or polynomials produce smooth
curves.
All results in this article build on the plot of the abs
function. Of course, the discontinuity will not always be
nicely positioned at (0,0).
Therefore, before continuing, we will discuss several
general ways to manipulate graphs of functions: how the
plots can be shifted, reflected, or scaled.

if x < 0 then abs(x) = -x


if x > 0 then abs(x) = x

If we replace x by (x-1) in an arbitrary function, the


plot will shift 1 scale unit to the right.
This article demonstrates several useful applications for the To understand this, notice that the plot of y = f(x) is the
abs() function.
collection of points (x,y) that satisfy the equation y =
f(x). Say point (p,q) is part of the plot, so, q = f(p).
1. Calculating Distances
But if x is replaced by x-1 we no longer have p = x, but
Suppose your application paints a line using mouse-clicks
we have p = x -1, so x = p + 1.
to specify the two end points. Successive clicks yield the
P has changed to p + 1, so , (q,p+1) is now part of the
points (x1,y1) and (x2,y2). You store horizontal and vertical plot which means that the plot has shifted 1 scale unit to
offsets in the variables dx and dy.
the right.
The following assignments will calculate these offsets:
Similarly we can deduce that changing y into (y-1) shifts
the plot 1 scale unit upwards.
dx := abs(x1 - x2)
Replacing x by (x+1) shifts the plot 1 scale unit to the left;
dy := abs(y1 - y2)
and replacing y by (y+1) shifts the plot 1 scale unit
downwards.
Note that there is no difference between abs(x1 - x2)
If x is replaced by x/2 in any function y = f(x), then the
and abs(x2 - x1).
plot is multiplied by 2 in horizontal direction (relative to the
y-axis).
Replacing y by y/2 multiplies the plot by 2 in
To avoid negative distances we could have used if
vertical direction (relative to the x-axis).
statements. However, this approach is slower because
processors use pipelines for code execution, and an if
If x is replaced by -x in any function y = f(x), then the
statement forces a restart of the pipeline, which interrupts
plot is reflected relative to the y-axis. Replacing y by -y
the instruction streaming.
reflects the plot around the x-axis.
2. Calculating a lower limit
Say we have a variable x which is not allowed to take a
negative value. This means that if x drops below zero it
then has to be reset to zero.
Again, we might use an if statement but the abs() function
is equally suitable.
To appreciate why, it may help to look at the plot of the
function y=abs(x) first.

Bearing the above transformations in mind, enables us to


move the angle at (0,0) of y = abs(x) to any other position.
Consider the following function:
y - 2 = abs(x - 3) which means
y = abs(x - 3) + 2
The point of discontinuity is moved from (0,0) to (3,2)

Figure 2:
Figure 1:

36

COMPONENTS
DEVELOPERS

Nr 1 / 2013 BLAISE PASCAL MAGAZINE

Use of the "absolute" function abs(..) Continuation 1


Back to our initial objective: finding a function that
automatically establishes a lower limit to a variable.
For this we combine two functions: y=abs(x) and y=x.
We plot y = abs(x) + x

-y = 0.5(abs(x) -x) or
y = -0.5(abs(x) -x) or
y = 0.5(x - abs(x))
Now for x > 0 the upper limit is 0 and for x < 0
we get y = x.
The angle may now be shifted to any position.
The slope is adjusted to 1 by the factor 0.5

Figure 3:

For x < 0 the function delivers a lower limit of zero,


however for x > 0 the slope is too steep. We need y =
x, but get y = 2x.
Therefore, we replace y by 2y to multiply the plot by a
factor 0.5 in the vertical direction.
The function changes to
2y = abs(x) + x

or

y = 0.5(abs(x) + x)

Figure 5:

Say we want an upper limit of 100. Point (0,0) must be


shifted to (100,100) in this case,
so we replace x by (x-100) and y by (y-100)
y - 100 = 0.5((x-100) - abs(x-100))
y = 0.5(x - abs(x-100)) + 50

4. Providing both upper and lower limits


We plot the function y = 0.5(abs(x+1) - abs(x-1))
Note: the scale below is 0.2
Below x = -1 the function has a lower limit of -1 and
above x = 1 the upper limit is 1

Figure 4:

Say we want a lower limit of 10.


Point (0,0) must be shifted to point (10,10).
X is therefore replaced by (x-10) and y by (y-10) so,
y-10 = 0.5(abs(x-10) + (x-10) or
y = 0.5(abs(x-10) + x) + 5 does the job.
3. Calculating an upper limit
For an upper limit we mirror the plot around the y-axis by
changing x into -x:

Figure 6:

y = 0.5(abs(x) - x)
note : abs(-x) = abs(x)
The function returns 0 for x > 0 and abs(x) for x < 0,
which is not quite what we want.
Reflection again, now around the x- axis (replace y by -y):

Nr 1 / 2013 BLAISE PASCAL MAGAZINE

COMPONENTS
DEVELOPERS

37

Use of the "absolute" function abs(..) Continuation 2


Please note that
abs(lower limit) = abs(upper limit) = 1
But how can we establish different lower and upper limits?
We start with function
y = 0.5(abs(x+v) - abs(x-v))
For x < -v we may write:

5. Painting rectangles rotated by 45 degrees.


The figure below shows a rectangle rotated 45 degrees from
the horizontal.
We are looking for a simple way to draw this rectangle.

y = 0.5(-(x+v) - (v-x)) = -v ............lower limit


For x > v we may write
y = 0.5((x+v) - (x - v)) = v.............upper limit
And for x > -v

& x < v we get

y = 0.5((x+v) - (v-x)) = x .................no correction


Say, we want a lower limit of a and an upper limit of b.
The distance between the limits is b - a.
So, v = (b-a)/2 for the upper limit and the lower limit
is -v = (a-b)/2.
But the upper limit must be b, not (b-a)/2 so a shift is
needed of (end - start) :

Figure 7:

Let's give the top pixel coordinates (sx,sy).


See the figure below. The edges of the rectangle have
lengths h and v.
Painting is done by drawing horizontal lines from point x1
to x2 at distance y from the top of the bitmap.

b - (b-a)/2 = (a+b)/2 ,
a shift over the line y = x
so replace x by x-(a+b)/2 and y by y-(a+b)/2
so:
y = 0.5(abs(x+v) - abs(x-v))
which yields
y - (a+b)/2 = 0.5(abs(x-(a+b)/2
+ (b-a)/2) - abs(x-(a+b)/2 - (b-a)/2))
y - (a+b)/2 = 0.5(abs(x-a) - abs(x-b))
y = 0.5(abs(x-a) - abs(x-b) + a + b)
In this way a function can be constructed with any
arbitrary upper and lower limit, without the use of if
statements. The processor pipelines can stream
uninterruptedly.
My graphics program Graphics-Explorer may be used to
visualize the results.
Download the program from the web page
http://www.davdata.nl/math/grxpl.html
Type y = 0.5(abs(x-a) - abs(x-b) + a + b) and click "plot".
Select (right top) "replace" (not add) and "autoplot".
Now click (left or right) at the a and b windows to
increment or decrement constants a and b. The plot
immediately adjusts itself to the new values.
Below I summarize the results so far:
Variable x is assigned a
lower limit a using function
y = 0.5(abs(x - a) + x + a)
upper limit b using function
y = 0.5(x - abs(x - b) + b)
both limits a, b using function
y = 0.5(abs(x - a) - abs(x - b) + a + b)
Quite surprising, isn't it?

38

COMPONENTS
DEVELOPERS

Figure 8:

So, the program might look like this:


var

j : word;
h,v : word;
sx,sy : word;
bm : Tbitmap;

begin
.....
//creation of bitmap
//setting rectangle dimensions h and v
//setting position (sx,sy)
...
with bm.canvas do
begin
pen.color := 0;
pen.width := 1;
for j := 0 to h + v - 2
//from top to bottom of the rectangle
begin
y := sy + j;
x1 := ???;
x2 := ???;
moveto(x1,y);
lineto(x2,y)
//for j
end;
//with bm
end;
....
end;

Nr 1 / 2013 BLAISE PASCAL MAGAZINE

Use of the "absolute" function abs(..) Continuation 3


Let's look at the relation between x1 and j.
For the sake of simplicity, assume the top pixel has
coordinates (0,0).
j
0
1
2
3
4
5
6
7
x1 0
-1 -2 -3 -2 -1 0
1

the function becomes

8
2

x1 + 3 = abs(j - 3)
x1 = abs(j - 3) - 3

or

If the height is not 3 but v the function changes to

Figure 9:

From this table we draw a plot.


This plot appears to be bent, which reminds us of x1 =
abs(j) where (0,0) is shifted to position (3,-3) so

x1 = abs(j+v-1) - (v-1)
For the final result, sx has to be added to the horizontal
position so,
x1 = sx + abs(j+v-1) - (v-1)
Similarly we calculate that
x2 = sx - abs(j-h+1) + (h-1)
Note:
moveto(0,0) followed by lineto(10,0) draws a line from (0,0)
to (9,0).
Pixel (10,0) is not included.
Therefore, 1 has to be added to x2.
This concludes my article about ways you can usefully
apply the abs( ) function.

Figure 10:

Good news for startes


BLAISE PASCAL MAGAZINE
has publishd a book in English
aimed at people who are just setting
out to learn to code.
It is called

Learn to Program
using Lazarus 1.0,
and is written by Howard Page-Clark,
our editor, corrector
and writer of many articles
Among the many topics introduced are:
Pascal types, the Lazarus IDE,
Coding discipline,
GUI editing components,
Pascal files and streams,
Object oriented principles,
debugging techniques.

NEW:
As Loose Leaf Book
35 plus postage 17,50

As PDF File on USB STICK (8 GB) including


Lazarus Mobile Windows (Click and go)
version 1,07 on the stick and the three
Operating Sytems Linux Mac Windows
As PDF File
35 plus postage 3,50
25 no postage

Nr 1 / 2013 BLAISE PASCAL MAGAZINE

COMPONENTS
DEVELOPERS

39

.iOS Development

for lazarus

By Joost van der Sluis

The iOS Designer uses Lazarus functionality which is not


starter
expert Lazarus 1.1 or higher yet available in an official release. So you need to use a
development version of Lazarus (version number 1.1 or
This is a short introduction to developing iOS
higher). These versions can be downloaded from the
applications using Lazarus and the iOS Designer. For
Lazarus website (or mirror sites) or orderd from our
some time it has been possible to write applications for
Magazine. We will bring a special prenstalled version for
iOS using Free Pascal and you could use Lazarus as a
you in within some time, to make the use easy.
smart text editor.
Now it is also possible to use Lazarus to design iOS
screen layouts using the iOS Designer, which makes
layout design and use much easier. However this
additional functionality is rather new and is still being
developed. For instance the current installation and
settings need a lot of improvement; but for those who
are really interested in iOS development it's definitely
worth investing some time to learn about this new
capability.

The cross compiler for iOS devicesAn iOS device


(iPhone, iPad) makes use of an ARM processor. That's a
different type of processor from those based on the i386
architecture which you find in most desktop PCs. To create
applications which run on an ARM processor you need a
compiler which generates code for that type of processor.

Four resources are required in order to be able to develop


applications for iOS using Lazarus and the iOS Designer:
A Free Pascal cross-compiler for iOS devices or the iOS
Simulator.
The Pascal iOS header files.
Knowledge of the Objective Pascal language extensions
in Free Pascal.
The iOS Designer and iPhoneLazExt packages installed
in the Lazarus IDE (v1.1).

Because we want to create our iOS programs on a machine


running under OS/X, we need a 'cross compiler'. A cross
compiler runs on a different type of processor than the
type for which code is generated.
In our case the compiler runs under OS/X with an i386 (or
x86-64) architecture, but generates code for the ARM
architecture.
Such a cross compiler can be downloaded from the Free
Pascal website.

Nr 1 / 2013 BLAISE PASCAL MAGAZINE

http://www.blaisepascal.eu/index.php?actie=./subs
cribers/UK_Book_Department

COMPONENTS
DEVELOPERS

41

Barnsten has selected the best tools for the best developers
and is already for 20 years the expert for the Embarcadero products.
Each day we have contact with a lot of Delphi Developers to give advise,
trainings, consultancy and the use of components.
Barnsten has collected by now more then 600 components.
Here is an overview of the most used and wanted Delphi- and C++Builder
components:

Feature rich reusable PDF


Componens

Mida converter for FireMonkey


FireMonkey Components
for easily creating stunning apps!

Fast Report
Reporting must be fast

For building quick


powerfuul
multimedia applications

A collection of over
180 VCL Controls

Excellent Delphi Components


boosting your performance

The easiest way


to create unit test

Graphical components for


Win, Mac OS and iOS/iPhone

Build your own sophisticated


user interfaces in less
time with less effort
Embedded Database Engines
for database application developers

A Unique set of Universel


Data Access Components

Take a look at the components on


http://www.barnsten.com/default/components
Is the component you are looking for not available?
Then please make contact, so we will be able to help you.
The components are deliverd electronically.

http://www.barnsten.com/default/components

What is polymorphism? By Vsevolod Leonov


Good explanation leads to solid understanding
In the Russian-speaking world there are many printed
books about Delphi, as well as many digital books
about Delphi. I am holding a 1,024-page Delphi book
now. Yet it devotes only five lines to an explanation of
the term polymorphism. Whereas the TButton
component requires 96 lines of text and two
illustrations along with two source code examples. Is
understanding a button component twenty times more
important than understanding polymorphism?
As a RAD IDE Delphi is justifiably considered the best
programming environment from the point of view both
of beginners and professionals. However, critics of the
RAD paradigm often point to the fact that RAD
technology leads to a proliferation of bad programmers.
The previous paragraph shows why.

Aurora Borealis
Perhaps a good explanation of a new concept should begin
with a definition.
Polymorphism is derived from a Greek term which literally
means many forms. In the field of programming
polymorphism means that the calling of a conceptual
operation is isolated from its actual implementation. In
fact, at runtime, the implementation may vary
considerably, depending on the type of object that
performs the operation.
There is no redundancy in this three-sentence definition. A
beginner trying to understand a shorter definition would
be short-changed. We should not imagine that a supremely
crisp, succinct definition is one of the hallmarks of
polymorphism.
Try to read the above definition as you would understand
a description of the Northern lights, since polymorphism
likewise shines in the north. You can easily understand
what the Northern lights are simply by looking at
photographs. We will try to make up for the unfortunate
fact that you cannot photograph polymorphism.
Esoteric knowledge
Ask (a friend, a teacher, Google) about polymorphism and
you realize it is considered esoteric knowledge. You will be
told You need to work on polymorphic constructs for a
year and then maybe you'll understand.
A textbook explanation will conclude with:
polymorphism is a way of dealing with two or more
similar but technically different tasks. In fact, however,
programming is an engineering science. Its wonders and
creativity arise from easily explained concepts, with
nothing esoteric at all.
Mouse around
The ability to effortlessly 'mouse around' in a RAD IDE
is ultimately unhelpful if it detaches novices from the
code they are generating
You have to understand that syntax development in
programming languages (such as adding the new paradigm of
encapsulation, inheritance and polymorphism) is designed for
very specific needs that developers have. For instance you
are not interested in the philosophy (or spirituality) of a
car's automatic transmission. It was introduced to meet a
specific need. Polymorphism likewise solves a specific
problem.

48

COMPONENTS
DEVELOPERS

What problem does polymorphism solve?


What problems do developers face? Well, polymorphism
does not solve the salary problem (at least not directly).
However, polymorphism allows developers to create large
programs with minimal code complexity. Who needs
simple, yet powerful, code? Probably everyone! A
programmer is satisfied with high quality code. A user is
also satisfied, and will not have to curse developers for yet
another bug. The developer's employer also wants
polymorphism because simple, yet powerful, code is faster
and easier to maintain, modify and develop (i. e. cheaper).
If you try to answer the question Why is it bad to use
global variables? you'll find the answer is closely related
to the answer given to the question What problem does
polymorphism solve?
Polymorhpism is voluntary
Q: Can you avoid using polymorphism?
A: Sure! Before the invention of polymorphism as a
programming paradigm people got along without it.
However it makes no sense to ignore what has already
been well thought out, and is easy to understand.
Q: Can I use polymorphism without realizing it?
A: This is more than likely. However, more often you are
using object-oriented code written by someone else which
has polymorphism at its core. Delphi programmers do this
all the time.
Q: I asked my friend, who is a professional programmer, about
polymorphism. He answered me evasively. Does that mean he
does not understand it?
A: He knows about it, but it is hard to explain which is
the reason for this article. So you cannot have an excuse
any more for saying that Delphi multiplies ignoramusprogrammers.
I have already read a lot about this, so I don't
see the point of this article.
Well, you already know then that you should not be afraid
of polymorphism. Here are some pointers for writing high
quality code:
Don't use global variables; add comments; name variables
meaningfully; utilize polymorphism.
Certainly there is complexity in programming, but it is not
in polymorphism as such.
I'm tired of reading!
Well, I am tired of writing! But what else can we do if
Delphi books devote only a few lines to explaining
polymorphism, while devoting far more text to describing
the properties of the TLabel component? Sometimes you
must consider a topic comprehensively.

Nr 1 / 2013 BLAISE PASCAL MAGAZINE

http://www.barnsten.com/default/development-tools

LAZARUS
THE COMPLETE GUIDE

(ExtraPackage updated)

New Version 1.7


Complete Package 60,00 (Paperback)
will also include a free download subscription of
BLAISE PASCAL MAGAZINE for 1 year.
If you are a subscriber you can buy the simple pac it for just 35,00
(this excludes shipping costs).
Including Blaise Pascal Magazine it offers a complete package
The complete package contains
Lazarus the Complete Guide
1 a Windows installer for Lazarus Version 1.7
2 a Linux for Lazarus Version 1.7
3 a Mac for Lazarus Version 1.7
4 Lazarus Portable, a prenstalled copy Lazarus Version 1.7 on
a free 8 GB USB stick (Click and Go)
5 60 additional sample projects on installed CD and USB Stick
6 extra: additional prenstalled component suites on both:
DVD and USB Stick.
7 free Blaise Pascal Magazine Library on the USB Stick,

Completed up to all 26 issues, including code

BLAISE PASCAL MAGAZINE www.blaisepascal.eu


Extra Service: If you buy the complete package you will
have the book Learning to program using lazarus
for free as PDF file.
http://www.blaisepascal.eu/index.php?actie=./subscribers/UK_Book_Department

LINUX
LAZARUS V1
Pro Pascal Foundation

48

WINDOWS

WinXp/Vista/Win7

LAZARUS V1
Pro Pascal Foundation

MAC
LAZARUS V1
Pro Pascal Foundation

51
47
27

New V4.11.00 available


for DELPHI XE2 -32 and 64
On iPad and iPhone Full kbmMW support
The Delphi Starter Edition now also has the
ability to do multi tier development for no cost
at all.
Pro/Ent is available for Win32/Win64/OSX/FPC.
The CodeGear Edition is for Delphi XE2 / Win32
only and provides access to SQLite in addition
to the standard Delphi Starter Edition database
connectivity frameworks, BDE and IBExpress.
Delphi Starter Edition also lacks proper XML
support and the local TClientDataset, which is
also to be found as part of kbmMW Code
Gear Edition in the form of TkbmMWDOMXML
and the high performance TkbmMemTable.
In addition its possible to upgrade to kbmMem
Table Standard Edition for only US$30.
The upgrade includes full source for kbmMem
Table, and includes kbmSQL which provides a
SQL frontend to kbmMemTable.

(client and server)

For kbmMemtable now available: full XE2


support (32 / 64 / osx)
For kbmMW there are multiple new items:
Remote Desktop Client/Server/Proxy
Support, NEW JSON support, JSON
streaming of kbmMemTable datasets,
bugfixes and more.
Improved HTML template support,
improved Cookie Support etc. Lots of
improvements related to using kbmMW as a
web server producing dynamic
web pages. kbmMemTable on Win64.
Tests done:
10 million records in memory
with multiple fields and indexes...

COMPONENTS
DEVELOPERS

ESB, SOA,MoM, EAI TOOLS FOR INTELLIGENT SOLUTIONS.


kbmMW IS THE PREMIERE N-TIER PRODUCT
FOR DELPHI / C++BUILDER BDS DEVELOPMENT
FRAMEWORK FOR WIN 32
/ 64, .NET AND LINUX
WITH CLIENTS RESIDING ON WIN32 / 64, .NET, LINUX, UNIX MAINFRAMES, MINIS, EMBEDDED DEVICES, SMART
PHONES AND TABLETS.

You might also like