Академический Документы
Профессиональный Документы
Культура Документы
FreePascal + Lazarus
asousa@fe.up.pt
--- 1 ---
ndice
Introduo POE
Soluo FPC/Lazarus
Resenha Histrica
Componentes adicionais
asousa@fe.up.pt
--- 2 ---
Introduo
asousa@fe.up.pt
--- 3 ---
asousa@fe.up.pt
--- 4 ---
asousa@fe.up.pt
--- 5 ---
Loops de espera
Operaes de polling
asousa@fe.up.pt
--- 6 ---
Funcionalidades acrescidas
Independncia de SO e ao hardware
--- 7 ---
Estrutura de camadas
Maiores
Funcionalidades
Hardware
VCL Delphi
Funcionalidades
Cross-Platform custa de
diversas camadas de software
Footprint grande
asousa@fe.up.pt
--- 8 ---
FPC/Lazarus
asousa@fe.up.pt
--- 9 ---
Cross Platform
asousa@fe.up.pt
--- 10 ---
Lazarus cross-platform
Processadores:
asousa@fe.up.pt
--- 11 ---
Histrico
asousa@fe.up.pt
--- 12 ---
Histria do Lzarus
Borland:
Turbo Pascal / B. Pascal + Delphi + Kylix
Internet:
Free Pascal + Lazarus
asousa@fe.up.pt
--- 13 ---
Histria do Lzarus
Pascal (1971):
Simplificao do Algol (1960)
Genrica
Educativa (ponteiros, := vs ==,... )
Strong Typed
Case Insensitive
Statically Linked
Rpida
Inicializaes/Finalizaes
asousa@fe.up.pt
--- 14 ---
Borland Delphi
Windows RAD - 1993
Borland Kylix
Linux - RAD - 2001
Actualmente clssico da Borland
asousa@fe.up.pt
--- 15 ---
Lazarus TimeLine
asousa@fe.up.pt
--- 16 ---
Cascata de criaes/libertaes
Excepes
asousa@fe.up.pt
--- 17 ---
asousa@fe.up.pt
--- 18 ---
http://wiki.lazarus.freepascal.org/index.php/Multithreaded_Application_Tutorial
asousa@fe.up.pt
--- 19 ---
Introduo ao Pascal
EBooks gratuitos
Essential Pascal e Essential Delphi
No URL:
http://www.marcocantu.com
asousa@fe.up.pt
--- 20 ---
FreePascal
FPC
asousa@fe.up.pt
--- 21 ---
asousa@fe.up.pt
--- 22 ---
Estrutura do Cdigo
Program Elementar;
begin
// ...
end. // termina com ponto final
asousa@fe.up.pt
--- 23 ---
Atribuies :=
Comparaes =
Case Insensitive
Inicializaes/Finalizaes
asousa@fe.up.pt
--- 24 ---
Estrutura do Cdigo
Program Elementar;
const
csAVOG : real = 6.02; // constante global
var
UmInteiro : integer;
// var global
begin
// ...
UmInteiro:=Trunc(csAVOG);
// ...
end.
asousa@fe.up.pt
--- 25 ---
Estrutura do Cdigo
Program elementar;
Uses Forms {sistema}, MyUnit;
begin
// ...
Application.Run;
end.
asousa@fe.up.pt
--- 26 ---
Estrutura do Cdigo
A poro de cdigo
Interface conhecida
pelos mdulos exteriores
unit
A poro implementation
local e inacessvel do
exterior
unit MyUnit;
interface
// definies e declaraes
// a exportar
implementation
// cdigo local unit
end.
asousa@fe.up.pt
--- 27 ---
Estrutura do Cdigo
unit MyUnit;
interface
uses A, B, C;
Program elementar;
Uses
Forms, MyUnit;
/// ...
asousa@fe.up.pt
--- 28 ---
Estrutura do Cdigo
// ...
implementation
uses
// outras units a importar/utilizar
D, E;
var // varivel local (no ser exportada)
UmInteiro : Integer;
procedure MyProcedure;
begin
// ...
end;
initialization
// Inicializao da unidade (opcional)
finalization
// Finalizao da unidade (opcional)
end.
asousa@fe.up.pt
--- 29 ---
IDE Lazarus
asousa@fe.up.pt
--- 30 ---
File,
New Application
Gere um Projecto
que inclui:
Programa
Unit (Forms)
Unit
2 Way !!!
Editor grfico
encontra cdigo
adequado (...)
Mudar nome de
componente muda
cdigo todo (...)
asousa@fe.up.pt
--- 31 ---
asousa@fe.up.pt
--- 32 ---
asousa@fe.up.pt
--- 33 ---
asousa@fe.up.pt
--- 34 ---
asousa@fe.up.pt
--- 35 ---
asousa@fe.up.pt
--- 36 ---
asousa@fe.up.pt
--- 37 ---
asousa@fe.up.pt
--- 38 ---
asousa@fe.up.pt
--- 39 ---
IDE Avanado
asousa@fe.up.pt
--- 40 ---
for | :=
to
do
begin
end;
asousa@fe.up.pt
--- 41 ---
asousa@fe.up.pt
--- 42 ---
asousa@fe.up.pt
--- 43 ---
asousa@fe.up.pt
--- 44 ---
asousa@fe.up.pt
--- 45 ---
Debugging
asousa@fe.up.pt
--- 46 ---
Debugging
Breakpoint
asousa@fe.up.pt
--- 47 ---
Debugging
asousa@fe.up.pt
--- 48 ---
Help de contexto
asousa@fe.up.pt
--- 49 ---
Dvidas Frequentes
asousa@fe.up.pt
--- 50 ---
Funes
--- 51 ---
asousa@fe.up.pt
--- 52 ---
asousa@fe.up.pt
--- 53 ---
ShowMessage
asousa@fe.up.pt
--- 54 ---
Pascal Avanado
asousa@fe.up.pt
--- 55 ---
Referncia
Prioridades:
unrios[@,not,-]
*,/,div,mod,and,shl,shr
+,-,or,xor,=,<>,<,>,<=,>=, in/is
Tipos bsicos
string / Pchar, integer, boolean, char,
TDateTime, Set, Pointer, variant...
high(vector)/low(vector)/sizeof(varivel)
Ord(...)+Chr(...)
asousa@fe.up.pt
--- 56 ---
program Project1;
()
uses
() Unit1;
begin
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;
end.
no necessrio
alterar nada !
asousa@fe.up.pt
--- 57 ---
Unidade e Form
unit Unit1;
interface
()
type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(());
()
end;
var
Form1: TForm1;
Na interface da Unit1
definida a TForm1 e a
varivel Form1
Neste caso a Form1 tem um
boto e um procedimento
Button1Click(...)
o programa (no a
unidade) que d instrues
ao S.O. para efectivamente
abrir a janela e execut-la
Adicionando componentes
form, o cdigo da definio
do tipo da form alterado
automaticamente
--- 58 ---
Unidade e Form
A descrio completa da
form estar no ficheiro .lfm
No alterar nada !
asousa@fe.up.pt
--- 59 ---
Tipos
Type
// Comear os tipos por 'T'
TUpCaseLetters = 'A'..'Z';
TDaysOfMonth
// subrange
TMyDate = record
Month : Byte;
Day
: Byte;
Year : Integer;
end;
asousa@fe.up.pt
--- 60 ---
Tipos
type
// tipo enumerado
TColors = ( ColorRed, ColorGreen, ColorBlue ); // RGB
// set, isto , conjunto !!!
TSetOfLetters = set of Char;
var
AnArray: array [10..24] of Byte;
ColorCode: array [ColorRed .. ColorGreen] of Word;
Palette: set of TColors;
asousa@fe.up.pt
--- 61 ---
type
TSetOfLetters = set of Char;
var
Letters1, Letters2 : TConjLetras;
begin
Letters1 := ['A', 'B', 'C'];
Letters2 := [];
if ('A' in Letters1)
then ShowMessage('A');
if (['A','B'] <= Letters1) then ShowMessage('A,B');
if (['E'] <= Letters1)
then ShowMessage('Falso');
if (Letters2 = [])
then ShowMessage('Vazio');
end;
asousa@fe.up.pt
--- 62 ---
Range Check
type
TDozen = array [1..12] of Integer;
var
UmMes : TDozen;
procedure WorkSomethingOnADozen;
begin
UmMes[1] := 10;
UmMes[2] := 12;
UmMes[0] := 18; // erro compile-time
UmMes[25] := 18; // erro compile-time
end;
asousa@fe.up.pt
--- 63 ---
type
TBiDimVector = array [1..12, 1..12] of Integer;
var
ABiDimVector : TBiDimVector;
asousa@fe.up.pt
--- 64 ---
Apontadores
type
PointerToInt = ^Integer;
var
P: ^Integer;
X : Integer;
begin
P := @X;
// Muda varivel de duas formas diferentes
X := 10;
P^ := 20;
end;
asousa@fe.up.pt
--- 65 ---
Apontadores
var
P: ^Integer;
begin
New (P);
// criar / iniciar
P^ := 20;
// atribuir
asousa@fe.up.pt
--- 66 ---
asousa@fe.up.pt
--- 67 ---
IFs
asousa@fe.up.pt
--- 68 ---
Case
case MyChar of
'+'
: Text := 'Soma';
'-'
: Text := 'Subtraco';
'*', '/' : Text := 'Multiplicao ou diviso';
'0'..'9' : Text := 'Algarismo';
'a'..'z' : Text := 'Minscula';
'A'..'Z' : Text := 'Maiscula';
else
Text := 'Outro Caracter';
end;
asousa@fe.up.pt
--- 69 ---
Ciclo for
...
Soma := 0;
for i := 1 to 10 do
Soma := Soma + i;
...
A varivel do ciclo
pode ser qualquer
ordinal, incluindo
tipos enumerados
Ciclos for so muito
mais restritivos em
Pascal que em C
Tal como em qualquer
outro ciclo for, o corpo
do ciclo pode ser no
executado nunca
...
Soma := 0;
for i := 10 downto 1 do
begin
Soma := Soma + i;
end;
...
asousa@fe.up.pt
--- 70 ---
repeat
...
I := I + 1;
J := J + 1;
until (I > 100) or (J > 100);
asousa@fe.up.pt
--- 71 ---
Procedimentos e funes
asousa@fe.up.pt
--- 72 ---
Vectores Dinmicos
asousa@fe.up.pt
--- 73 ---
Formatao de Strings
TYPE SPECIFIER
d (decimal)
x (hexadecimal)
p (pointer)
s (string)
e (exponential)
DESCRIPTION
The corresponding integer value is converted to a string of
decimal digits.
The corresponding integer value is converted to a string of
hexadecimal digits.
The corresponding pointer value is converted to a string expressed
with hexadecimal digits.
The corresponding string, character, or PChar value is copied to
the output string.
The corresponding floating-point value is converted to a string
based on exponential notation.
asousa@fe.up.pt
--- 74 ---
Formatao de Strings
f (floating point)
g (general)
n (number)
m (money)
asousa@fe.up.pt
--- 75 ---
Ciclos Prolongados
asousa@fe.up.pt
--- 76 ---
Excepes (i)
var
n2, n1, n0 : integer;
begin
try
n0 := 0;
n1 := 1;
n2 := n1 div n0;
ShowMessage('1 / 0 = '+IntToStr(n2));
except
on E : Exception do
begin
ShowMessage('Nome da classe = '+E.ClassName);
ShowMessage('Mensagem da excepo = '+E.Message);
end;
end;
end;
asousa@fe.up.pt
--- 77 ---
Excepes (ii)
...
except
// IO error
on E : EInOutError do
ShowMessage('IO error : '+E.Message);
// Dibision by zero
on E : EDivByZero do
ShowMessage('Div by zero error : '+E.Message);
// Catch other errors
else
ShowMessage('Unknown error');
end;
asousa@fe.up.pt
--- 78 ---
Excepes (iii)
var
number, zero : Integer;
begin
// Try to divide an integer by zero - to raise an exception
number := -1;
Try
zero
:= 0;
number := 1 div zero;
ShowMessage('number / zero = '+IntToStr(number));
finally
if number = -1 then
begin
ShowMessage('Not assigned - using default');
number := 0;
end;
end;
end;
asousa@fe.up.pt
--- 79 ---
Excepes (iv)
...
int2:=2;int1:=1;int0:=0;
vf2:=2.0;vf1:=1.0;vf0:=0.0;
try
case RadioGroup.ItemIndex of
0 : int2 := int1 div int0;
1 : vf2 := vf1 / vf0;
2 : assert(False,'Just Testing');
end;
Memo.Append('Sem erro:='+FloatToStr(vf2)+';'+ IntToStr(int2));
except
on E : EDivByZero do
Memo.Append('Div int por 0:'+e.ClassName+': '+e.Message);
on E : EZeroDivide do
Memo.Append('Div Virg Flt 0:'+e.ClassName+':'+e.Message);
on E : Exception
do Memo.Append('outro erro -- '+
e.ClassName+': '+e.Message);
end;
Memo.Append('Continua, Normal');
...
asousa@fe.up.pt
--- 80 ---
Variants
procedure TFormMain.Button1Click(Sender: TObject);
var
V : Variant;
I : Integer;
begin
V:='100';
I:=V;
Button1.Caption:='I = ' + IntToStr(I); // OK
V:='Something else';
I:=V;
Button1.Caption:='I = ' + IntToStr(I); // NOK
end;
asousa@fe.up.pt
--- 81 ---
{$IFDEF LINUX}
// Cdigo para Linux
{$ELSE}
// Cdigo para outras plataformas
{$ENDIF}
asousa@fe.up.pt
--- 82 ---
Para acrescentar
funcionalidades, qualquer
programador pode criar
componentes
Package graph
asousa@fe.up.pt
--- 83 ---
Mais Controlos
Visuais Padro
asousa@fe.up.pt
--- 84 ---
Botes
TButton
TBitButton
TSpeedButton
asousa@fe.up.pt
--- 85 ---
TLabel
TEdit
TStatusBar
asousa@fe.up.pt
--- 86 ---
TMemo
asousa@fe.up.pt
--- 87 ---
TMemo
Lines.SaveToFile('c:\memo.txt'); // windows
Memo.Lines.LoadFromFile('~/memo.txt'); // linux
... end;
...
--- 88 ---
CheckBox / Group
TCheckBox
TCheckGroup
asousa@fe.up.pt
--- 89 ---
RadioGroup
TRadioGroup
asousa@fe.up.pt
--- 90 ---
ListBox e ComboBox
asousa@fe.up.pt
--- 91 ---
TImage (.Picture)
TPaintBox (.Canvas)
TShape (.Canvas)
asousa@fe.up.pt
--- 92 ---
asousa@fe.up.pt
--- 93 ---
Temporizador
Tempo em milisegundos
Dificuldades em cumprir
restries de tempos curtos
asousa@fe.up.pt
--- 94 ---
Grficos
TBarChart
asousa@fe.up.pt
--- 95 ---
Menus
TMainMenu
Fazendo double click abre-se o editor de menus
possvel acrescentar diversas opes:
check box
cone
Tecla atalho
...
asousa@fe.up.pt
--- 96 ---
Componente de persistncia
TXMLPropStorage
(Separdor Misc)
(depois utilizar a propriedade da form.SessionProperties)
--- 97 ---
--- 98 ---
Componentes
Externos teis
asousa@fe.up.pt
--- 99 ---
Componentes a utilizar
ZeosLib -
http://sourceforge.net/projects/zeoslib/
asousa@fe.up.pt
Sdpo Serial
asousa@fe.up.pt
Lazarus FAQs
After I installed a component, Lazarus crashes with the following message:
Threading has been used before cthreads was initialized. Make cthreads one of the first units in
your uses clause. Runtime error 211
How can I fix this?
Your freshly installed component is using threads. Fpc on *nix doesn't automatically include threading
support, but it must be intialized. This initialization is done in the cthreads unit. Every application
using the component needs to add this unit to the uses clause of the main program. Lazarus itself is
no exception. This can be done in two ways:
1) Change the source of ide/lazarus.pp: add the cthreads as first unit to the uses clause, so that is looks
like this:
uses
cthreads,
{$IFDEF IDE_MEM_CHECK}
...
and rebuild lazarus.
asousa@fe.up.pt
Lazarus FAQs
2) In order to avoid modifying lazarus.pp file, a fpc compiler option could be used. Once package that
uses threads has been compiled, open menu Tools->Configure "build Lazarus". Configure "build
Lazarus" dialog will be shown, in field "Options:" type -Facthreads and then press "OK" button. The
next step is to install the package. Lazarus will be built with option -Facthreads which means that it
will treat main program as if unit cthreads where first in uses clause.
Hint:
Maybe your old (non-crashing) lazarus executable is stored as lazarus.old in the same directory as
the crashing lazarus executable.
asousa@fe.up.pt
Receber:
Evento OnRxData tem cadncia imprevisvel algumas vezes pode-se receber byte a byte, outras no,
obrigatrio o programa lidar com este facto !!!
Exemplo de recepo:
SdpoSerial.SynSer.RecvPacket(0);
asousa@fe.up.pt
Propriedades ACID:
Atomicity-Consistency-Isolation-Durability
asousa@fe.up.pt
SGBD
Query/
/Dataset
DataSource
asousa@fe.up.pt
DBGrid
DBEdit
DBLabel
...
asousa@fe.up.pt
asousa@fe.up.pt
...
dbGrid.ReadOnly:= ... (sempre!!!)
...
SQLQuery.Post;
...
asousa@fe.up.pt
...
begin
enter:=chr(13)+chr(10);
s:='update copias set nalugueres=nalugueres+1 where'+
'codcopia='+IntToStr(EstaCopia); // string de cdigo SQL
try
PQConChange.Connected:=True;
PQConChange.ExecuteDirect('Begin Work;');
PQConChange.ExecuteDirect(s);
PQConChange.ExecuteDirect('Commit Work;');
PQConChange.Connected:=False;
except
on E : EDatabaseError do
MemoLog.Append('ERROBD:'+enter+
E.ClassName+enter+E.Message);
on E : Exception do
MemoLog.Append('ERRO:'+enter+
E.ClassName+enter+E.Message);
end;
end;
asousa@fe.up.pt
asousa@fe.up.pt
asousa@fe.up.pt
lnet/visual/examples/tcpudp
...
FNet: TLNetComponent;
...
// TCP ou UDP
asousa@fe.up.pt
lnet/visual/examples/tcpudp
asousa@fe.up.pt
lnet/visual/examples/tcpudp
asousa@fe.up.pt
lnet/visual/examples/tcpudp
procedure TForm1.SendEditKeyPress
(Sender: TObject; var Key: char);
begin
if Key = #13 then
SendButtonClick(Sender);
end;
asousa@fe.up.pt
TAChart
asousa@fe.up.pt
Operator Overloading
type
complex = record
re : real;
im : real;
end;
// ...
Z2:=Z1;
//...
//
//
//
//
//
//
Atribuio de
record's do
mesmo tipo
Z2:=Z1
a atribuio de
todos os campos
type
complex = record
re : real;
im : real;
end;
var
R1
: real;
Z1,Z2 : complex;
// Operator Overloading
operator := (r : real) z : complex;
begin
z.re:=r;
z.im:=0.0;
end;
asousa@fe.up.pt
Ligaes interessantes
Todos os Wiki's:
http://wiki.lazarus.freepascal.org/Special:Allpages
Bases de dados:http://wiki.lazarus.freepascal.org/index.php/Lazarus_Database_Tutorial
http://wiki.lazarus.freepascal.org/TPSQL
RXLib:
http://wiki.lazarus.freepascal.org/RXfpc
http://www.alexs75.narod.ru/fpc/rxfpc/index.html
asousa@fe.up.pt
Ligaes interessantes
http://wiki.lazarus.freepascal.org/Lazarus_Faq
http://wiki.lazarus.freepascal.org/Installing_Lazarus
http://wiki.lazarus.freepascal.org/LCL_Defines
http://wiki.lazarus.freepascal.org/Getting_Lazarus
http://wiki.lazarus.freepascal.org/Icon_Editor
http://wiki.lazarus.freepascal.org/GLScene
http://wiki.lazarus.freepascal.org/Multiplatform_Programming_Guide
http://wiki.lazarus.freepascal.org/Multithreaded_Application_Tutorial
http://wiki.lazarus.freepascal.org/lNet
http://wiki.lazarus.freepascal.org/Pascal_Script
asousa@fe.up.pt
asousa@fe.up.pt