text stringlengths 14 6.51M |
|---|
{
Modelo de Negório: Regras encapsuladas
Recurso: CONTATO = associação com as classes TEmail e TTelefone
OBS: Quando se herda de um TComponent, a instancia/criação do objeto precisa
ter um Owner, senão, passa nil...
}
unit uContato;
interface
uses
System.Classes, System.Generics.Collections;
type
TEmail = class { Agregação }
private
FItemId: Integer;
FContatoId: Integer;
FEmail: string;
FTipo: string;
procedure SetItemId(const Value: Integer);
procedure SetContatoId(const Value: Integer);
procedure SetEmail(const Value: string);
procedure SetTipo(const Value: string);
public
property ItemId: Integer read FItemId write SetItemId;
property ContatoId: Integer read FContatoId write SetContatoId;
property Email: string read FEmail write SetEmail;
property Tipo: string read FTipo write SetTipo;
end;
TTelefone = class { Agregação }
private
FItemId: Integer;
FContatoIdo: Integer;
FDDD: string;
FNumero: string;
FTipo: string;
procedure SetItemId(const Value: Integer);
procedure SetContatoIdo(const Value: Integer);
procedure SetDDD(const Value: string);
procedure SetNumero(const Value: string);
procedure SetTipo(const Value: string);
public
property ItemId: Integer read FItemId write SetItemId;
property ContatoIdo: Integer read FContatoIdo write SetContatoIdo;
property DDD: string read FDDD write SetDDD;
property Numero: string read FNumero write SetNumero;
property Tipo: string read FTipo write SetTipo;
end;
TContato = class { Recurso }
private
FCodigo: Integer;
FEmpresa: string;
FNome: string;
FTelefones: TList<TTelefone>;
FEmails: TList<TEmail>;
procedure SetCodigo(const Value: Integer);
procedure SetEmpresa(const Value: string);
procedure SetNome(const Value: string);
public
{
Boa Prática: Sempre que declararmos Propriedades do Tipo de Outras classes,
devemos instancia-las no Construtor da Classe que recebe o objeto agregado,
que neste caso, é a classe TContato que recebe por agregação, as classes
TEmail e TTelefone via Listas/Tipadas, sempre lembrando de destruílas no
Destrutor da Classe.
}
constructor Create;
destructor Destroy; override;
property Codigo: Integer read FCodigo write SetCodigo;
property Nome: string read FNome write SetNome;
property Empresa: string read FEmpresa write SetEmpresa;
property Emails: TList<TEmail> read FEmails; { Lista Tipada/Generic = Email - somente leitura }
property Telefones: TList<TTelefone> read FTelefones; { Lista Tipada/Generic = Telefone - somente leitura }
procedure Validar();
end;
implementation
{ TContato }
constructor TContato.Create;
begin
FEmails := TList<TEmail>.Create;
FTelefones := TList<TTelefone>.Create;
end;
destructor TContato.Destroy;
begin
FEmails.Free;
FTelefones.Free;
inherited;
end;
procedure TContato.SetCodigo(const Value: Integer);
begin
FCodigo := Value;
end;
procedure TContato.SetEmpresa(const Value: string);
begin
FEmpresa := Value;
end;
procedure TContato.SetNome(const Value: string);
begin
FNome := Value;
end;
procedure TContato.Validar();
var
Str: string;
begin
Str := 'Validando...';
end;
{ TEmail }
procedure TEmail.SetContatoId(const Value: Integer);
begin
FContatoId := Value;
end;
procedure TEmail.SetEmail(const Value: string);
begin
FEmail := Value;
end;
procedure TEmail.SetItemId(const Value: Integer);
begin
FItemId := Value;
end;
procedure TEmail.SetTipo(const Value: string);
begin
FTipo := Value;
end;
{ TTelefone }
procedure TTelefone.SetContatoIdo(const Value: Integer);
begin
FContatoIdo := Value;
end;
procedure TTelefone.SetDDD(const Value: string);
begin
FDDD := Value;
end;
procedure TTelefone.SetItemId(const Value: Integer);
begin
FItemId := Value;
end;
procedure TTelefone.SetNumero(const Value: string);
begin
FNumero := Value;
end;
procedure TTelefone.SetTipo(const Value: string);
begin
FTipo := Value;
end;
end.
{ TODO -oCharles -c0 : Tratar exceção, Gestão de Memória (ReportMemoryLeakOnShootDown), etc... }
|
unit gsf_Xlat;
{-----------------------------------------------------------------------------
International Character Sets
gsf_Xlat Copyright (c) 1996 Griffin Solutions, Inc.
Date
4 Apr 1996
Programmer:
Richard F. Griffin tel: (912) 953-2680
Griffin Solutions, Inc. e-mail: grifsolu@hom.net
102 Molded Stone Pl
Warner Robins, GA 31088
Modified (m) 1997-2000 by Valery Votintsev 2:5021/22
--------------------------------------------------------------
This unit handles character conversion and comparison for
international character sets.
Description
This unit initializes country-specific information and character sets
for use in languages that use different alphabets than English. It is
designed to allow the developer to determine the character set for the
program by including an xxxxxxxx.NLS file that provides four different
256-byte tables--UpperCase, LowerCase, Dictionary, and Standard ASCII
character sets. The character set used is based on the country code
and code page as described in the MS-DOS manual in the chapter titled
"Customizing for International Use".
The xxxxxxxx.NLS files included have file names that are constructed
as CcccPppp.NLS, where ccc is the country code and ppp is the code
page. For example, file C001P437.NLS is the include file for the
United States (country code 001), and code page 437 (English); file
C049P850.NLS is for Germany (country code 049), and code page 850
(Multilingual (Latin I)). To include a file, it must replace the
$I C001P437.NLS directive at the beginning of the implementation
section. BE SURE THE FILE IS IN THE INCLUDE DIRECTORIES PATH.
The character tables are described below:
-----------------------------------------
UpperCase - This is a 256-byte table that is used to translate an
ASCII character to its uppercase equivalent. For example, the
table below is the UpperCase table from C001P437.NLS. If the
character 'a' used this translation table, it would retrieve the
value at $61 (ASCII value for 'a'), which is $41 (ASCII value for
'A'). This table is also valid for characters stored above the
first 128 bytes. These characters are often alphabetical codes
containing umlauts. Look at the character at $A0 (a lowercase 'a'
with an accent mark). This character also translates to an
uppercase 'A' ($41). There are also many lowercase characters in
this region whose uppercase equivalent is also in the upper 128
bytes. The character at location $81 is a lowercase 'u' with two
dots above the character. This translates to $9A, which is an
uppercase 'U' with two dots above the character.
0 1 2 3 4 5 6 7 8 9 A B C D E F
0 $00 $01 $02 $03 $04 $05 $06 $07 $08 $09 $0A $0B $0C $0D $0E $0F
1 $10 $11 $12 $13 $14 $15 $16 $17 $18 $19 $1A $1B $1C $1D $1E $1F
2 $20 $21 $22 $23 $24 $25 $26 $27 $28 $29 $2A $2B $2C $2D $2E $2F
3 $30 $31 $32 $33 $34 $35 $36 $37 $38 $39 $3A $3B $3C $3D $3E $3F
4 $40 $41 $42 $43 $44 $45 $46 $47 $48 $49 $4A $4B $4C $4D $4E $4F
5 $50 $51 $52 $53 $54 $55 $56 $57 $58 $59 $5A $5B $5C $5D $5E $5F
6 $60 $41 $42 $43 $44 $45 $46 $47 $48 $49 $4A $4B $4C $4D $4E $4F
7 $50 $51 $52 $53 $54 $55 $56 $57 $58 $59 $5A $7B $7C $7D $7E $7F
8 $80 $9A $45 $41 $8E $41 $8F $80 $45 $45 $45 $49 $49 $49 $8E $8F
9 $90 $92 $92 $4F $99 $4F $55 $55 $59 $99 $9A $9B $9C $9D $9E $9F
A $41 $49 $4F $55 $A5 $A5 $A6 $A7 $A8 $A9 $AA $AB $AC $AD $AE $AF
B $B0 $B1 $B2 $B3 $B4 $B5 $B6 $B7 $B8 $B9 $BA $BB $BC $BD $BE $BF
C $C0 $C1 $C2 $C3 $C4 $C5 $C6 $C7 $C8 $C9 $CA $CB $CC $CD $CE $CF
D $D0 $D1 $D2 $D3 $D4 $D5 $D6 $D7 $D8 $D9 $DA $DB $DC $DD $DE $DF
E $E0 $E1 $E2 $E3 $E4 $E5 $E6 $E7 $E8 $E9 $EA $EB $EC $ED $EE $EF
F $F0 $F1 $F2 $F3 $F4 $F5 $F6 $F7 $F8 $F9 $FA $FB $FC $FD $FE $FF
LowerCase - This is a 256-byte table used to translate an uppercase
character to its lowercase equivalent. The translation technique
is the same as for the UpperCase description above.
Dictionary - Initially set to UpperCase, but provides a pointer so
that the programmer may create a table with a custom sort sequence.
This 256-byte table provides a translation based on the
collation sequence of the character set. This provides more
than just setting uppercase for characters. It ensures that
punctuation symbols as well as alphabetical characters are
ordered in a sequence that makes sense. The values in the table
are the character weight of the ASCII value in that location.
This allows sorting of two characters by getting their character
weights from the table, and ordering based on the lowest weight
first. As you can see from the table below, several of the
characters have the character weight of $41 (ASCII 'A'). Just
as importantly, many currency symbols (pound, yen, franc, cent,
peseta) in the upper 128 bytes from $9B to $9F all have the
weight of $24 ('$').
The character weight is not required to translate to an existing
ASCII character index. For the letter 'A', if you wished that
it were the lowest possible weight, then the weight $00 would be
set at index $41 and all other locations that shared the same
character weight. Then 'B' would be assigned the weight $01,
'C' assigned $02, etc. The character weight simply reflects the
relative ranking of the character at the indexed position in the
table.
0 1 2 3 4 5 6 7 8 9 A B C D E F
0 $00 $01 $02 $03 $04 $05 $06 $07 $08 $09 $0A $0B $0C $0D $0E $0F
1 $10 $11 $12 $13 $14 $15 $16 $17 $18 $19 $1A $1B $1C $1D $1E $1F
2 $20 $21 $22 $23 $24 $25 $26 $27 $28 $29 $2A $2B $2C $2D $2E $2F
3 $30 $31 $32 $33 $34 $35 $36 $37 $38 $39 $3A $3B $3C $3D $3E $3F
4 $40 $41 $42 $43 $44 $45 $46 $47 $48 $49 $4A $4B $4C $4D $4E $4F
5 $50 $51 $52 $53 $54 $55 $56 $57 $58 $59 $5A $5B $5C $5D $5E $5F
6 $60 $41 $42 $43 $44 $45 $46 $47 $48 $49 $4A $4B $4C $4D $4E $4F
7 $50 $51 $52 $53 $54 $55 $56 $57 $58 $59 $5A $7B $7C $7D $7E $7F
8 $43 $55 $45 $41 $41 $41 $41 $43 $45 $45 $45 $49 $49 $49 $41 $41
9 $45 $41 $41 $4F $4F $4F $55 $55 $59 $4F $55 $24 $24 $24 $24 $24
A $41 $49 $4F $55 $4E $4E $A6 $A7 $3F $A9 $AA $AB $AC $21 $22 $22
B $B0 $B1 $B2 $B3 $B4 $B5 $B6 $B7 $B8 $B9 $BA $BB $BC $BD $BE $BF
C $C0 $C1 $C2 $C3 $C4 $C5 $C6 $C7 $C8 $C9 $CA $CB $CC $CD $CE $CF
D $D0 $D1 $D2 $D3 $D4 $D5 $D6 $D7 $D8 $D9 $DA $DB $DC $DD $DE $DF
E $E0 $53 $E2 $E3 $E4 $E5 $E6 $E7 $E8 $E9 $EA $EB $EC $ED $EE $EF
F $F0 $F1 $F2 $F3 $F4 $F5 $F6 $F7 $F8 $F9 $FA $FB $FC $FD $FE $FF
Standard - Initially set to nil to do a straight ASCII compare.
It may be assigned a table address if the programmer wants to
design a custom 'ASCII' sort. This table normally contains the
ASCII code for that index, which means you return with the same
value that was used as the index. The reason for having the table
is to provide a capability to modify the ASCII order by changing
the character weight. The table as provided will provide a 'pure'
ASCII sort.
Usage
-----
During initialization, the table addresses are assigned to
pointers pCtyUpperCase, pCtyLowerCase, pCtyDictionary, and
pCtyStandard. In addition, the pointer pCompareTbl is assigned
the address of pCtyStandard, and pCompareITbl is assigned the
address of pCtyUpperCase.
In Griffin Solutions routines, string comparisons that are case
sensitive will use the table pointed to by pCompareTbl. The
string comparisons that are case insensitive will use pCompareITbl.
Therefore. by assigning another table to these pointers, the
programmer could create any type of sort that was desired.
Changes:
07/19/97 - changed CaseOEMPChar() to have an additional argument to
protect for the maximum length. This clears undefined
errors where the byte just beyond the buffer might be
modified if the PChar did not end with a #0.
08/05/97 - changed CmprOEMBufr() to handle characters below #32
(space) when the other buffer is null-terminated.
!!RFG 090297 added argument to CmprOEMBufr() to define the substitute
character to use for unequal field length comparisons.
Numeric fields in CDX indexes could fail.
!!RFG 012198 added test in CmprOEMBufr to test for unequal field
comparisons where the comparison was 1 and the compare
position was greater than the length of the first key.
This happened on keys where characters < #32 were used.
For example, 'PAUL' and 'PAUL'#31 would determine that
'PAUL' was greater than 'PAUL'#31 because the default
#32 would be compared against the #31 in the second key.
------------------------------------------------------------------------------}
{$I gsf_FLAG.PAS}
interface
uses
gsf_Glbl;
var
ctyCountry : word;
ctyCodePage : word;
ctyDateFormat : word;
ctyDateSeparator : char;
ctyThousandsSeparator : char;
ctyDecimalSeparator : char;
ctyCurrencySymbol : array[0..4] of char;
ctyCurrencySymPos : byte;
ctyDecimalPlaces : byte;
ctyTimeFormat : byte;
ctyTimeSeparator : char;
ctyDataSeparator : char;
pCtyUpperCase : GSptrByteArray;
pCtyLowerCase : GSptrByteArray;
pCtyDictionary : GSptrByteArray;
pCtyStandard : GSptrByteArray;
pCompareTbl : GSptrByteArray;
pCompareITbl : GSptrByteArray;
procedure ConvertAnsiToNative(AnsiStr, NativeStr: PChar; MaxLen: longint);
procedure ConvertNativeToAnsi(NativeStr, AnsiStr: PChar; MaxLen: longint);
procedure CaseOEMPChar(stp: PChar; tbl: GSptrByteArray; Len: word);
function CmprOEMChar(ch1, ch2: char; tbl: GSptrByteArray): integer;
function CmprOEMBufr(st1, st2: pointer; tbl: GSptrByteArray;
var ix: longint; SubChar: char): integer;
function CmprOEMPChar(st1, st2: PChar; tbl: GSptrByteArray; var ix: integer): integer;
function CmprOEMString(const st1, st2: string; tbl: GSptrByteArray): integer;
{$IFDEF DUMY1234}
procedure NLSInit;
{$ENDIF}
implementation
uses vString;
{$I C007P866.NLS}
procedure ConvertAnsiToNative(AnsiStr, NativeStr: PChar; MaxLen: longint);
begin
if AnsiStr <> NativeStr then
Move(AnsiStr[0],NativeStr[0],MaxLen);
end;
procedure ConvertNativeToAnsi(NativeStr, AnsiStr: PChar; MaxLen: longint);
begin
if NativeStr <> AnsiStr then
Move(NativeStr[0],AnsiStr[0],MaxLen);
end;
procedure CaseOEMPChar(stp: PChar; tbl: GSptrByteArray; Len: word);
var
ix : word;
begin
if stp = nil then exit;
if tbl = nil then exit;
ix := 0;
while (ix < len) and (stp[ix] <> #0) do
begin
stp[ix] := chr(tbl^[ord(stp[ix])]);
inc(ix);
end;
end;
function CmprOEMChar(ch1, ch2: char; tbl: GSptrByteArray): integer;
var
flg : integer;
df: integer;
begin
if tbl = nil then
begin
if ch1 = ch2 then CmprOEMChar := 0
else if ch1 < ch2 then CmprOEMChar := -1
else CmprOEMChar := 1;
exit;
end;
flg := 0;
df := tbl^[ord(ch1)];
df := df - tbl^[ord(ch2)];
if df < 0 then
flg := -1
else
if df > 0 then flg := 1;
CmprOEMChar := flg;
end;
function CmprOEMPChar(st1, st2: PChar; tbl: GSptrByteArray; var ix: integer): integer;
var
df: integer;
c1: char;
c2: char;
xlat: boolean;
begin
ix := 0;
if (st1 = nil) or (st2 = nil) then
begin
df := 0;
if (st1 = nil) and (st2 <> nil) then dec(df)
else
if (st2 = nil) and (st1 <> nil) then inc(df);
CmprOEMPChar := df;
exit;
end;
xlat := tbl <> nil;
if xlat then
begin
repeat
c1 := st1[ix];
c2 := st2[ix];
if c1 <> c2 then
begin
df := tbl^[ord(c1)];
df := df - tbl^[ord(c2)];
end
else
df := 0;
inc(ix);
until (df <> 0) or (c1 = #0);
end
else
begin
repeat
c1 := st1[ix];
df := ord(c1) - ord(st2[ix]);
inc(ix);
until (df <> 0) or (c1 = #0);
end;
if df = 0 then
CmprOEMPChar := 0
else
if df < 0 then
CmprOEMPChar := -1
else
CmprOEMPChar := 1;
end;
function CmprOEMString(const st1, st2: string; tbl: GSptrByteArray): integer;
var
flg : integer;
len : word;
ix : word;
df: integer;
begin
if tbl = nil then
begin
if st1 = st2 then CmprOEMString := 0
else if st1 < st2 then CmprOEMString := -1
else CmprOEMString := 1;
exit;
end;
ix := 1;
flg := 0;
len := length(st1);
if len < length(st2) then flg := -1
else if len > length(st2) then
begin
flg := 1;
len := length(st2);
end;
while ix <= len do
begin
df := tbl^[ord(st1[ix])];
df := df - tbl^[ord(st2[ix])];
if df < 0 then
begin
flg := -1;
ix := len;
end
else
if df > 0 then
begin
flg := 1;
ix := len;
end;
inc(ix);
end;
CmprOEMString := flg;
end;
function CmprOEMBufr(st1, st2: pointer; tbl: GSptrByteArray;
var ix: longint; SubChar: char): integer;
var
df: longint;
c1: char;
c2: char;
xlat: boolean;
lm1: longint;
lm2: longint;
lmt: longint;
begin
lm1 := GSptrString(st1)^.SizeStr;
lm2 := GSptrString(st2)^.SizeStr;
xlat := tbl <> nil;
lmt := lm1;
if lm2 > lm1 then lmt := lm2;
ix := 0;
repeat
if lm1 <= ix then
c1 := SubChar
else
c1 := GSptrString(st1)^.CharStr^[ix];
if lm2 <= ix then
c2 := SubChar
else
c2 := GSptrString(st2)^.CharStr^[ix];
if xlat then begin
if c1 <> c2 then begin
df := tbl^[ord(c1)];
df := df - tbl^[ord(c2)];
end
else
df := 0;
end
else
begin
df := ord(c1) - ord(c2);
end;
inc(ix);
until (df <> 0) or (ix >= lmt);
CmprOEMBufr := df;
if df = 0 then begin
inc(ix);
df := lm1 - lm2;
end;
if df < 0 then
CmprOEMBufr := -1
else
if df > 0 then
if (ix > lm1) then {!!RFG 012198}
CmprOEMBufr := -1 {!!RFG 012198}
else {!!RFG 012198}
CmprOEMBufr := 1;
end;
procedure OEMInit;
begin
NLSInit;
pCompareTbl := pCtyStandard;
pCompareITbl := pCtyUpperCase;
end;
{------------------------------------------------------------------------------
Setup and Exit Routines
------------------------------------------------------------------------------}
begin
OEMInit;
end.
|
unit UnitBigImagesSize;
interface
uses
Windows,
Messages,
System.SysUtils,
System.Math,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.ComCtrls,
Vcl.StdCtrls,
Vcl.ExtCtrls,
Dmitry.Controls.Base,
Dmitry.Controls.WebLink,
UnitDBDeclare,
UnitDBCommon,
uGraphicUtils,
uDBForm,
uDBIcons,
uConstants;
type
TBigImagesSizeForm = class(TDBForm)
TrbImageSize: TTrackBar;
Panel1: TPanel;
RgPictureSize: TRadioGroup;
LnkClose: TWebLink;
TimerActivate: TTimer;
procedure LnkCloseClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure RgPictureSizeClick(Sender: TObject);
procedure TrbImageSizeChange(Sender: TObject);
procedure FormDeactivate(Sender: TObject);
procedure TimerActivateTimer(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
LockChange : boolean;
FCallBack: TCallBackBigSizeProc;
FOwner: TForm;
TimerActivated: Boolean;
procedure LoadLanguage;
protected
function GetFormID : string; override;
public
{ Public declarations }
BigThSize: Integer;
Destroying: Boolean;
procedure Execute(AOwner: TForm; APictureSize: Integer; CallBack: TCallBackBigSizeProc);
procedure SetRadioButtonSize;
end;
var
BigImagesSizeForm: TBigImagesSizeForm;
implementation
{$R *.dfm}
procedure TBigImagesSizeForm.LoadLanguage;
begin
BeginTranslate;
try
Caption := L('Thumbnails size');
RgPictureSize.Caption := L('Size') + ':';
LnkClose.Text := L('Close');
RgPictureSize.Items[0] := Format( L('%dx%d pixels'), [BigThSize,BigThSize]);
finally
EndTranslate;
end;
end;
procedure TBigImagesSizeForm.LnkCloseClick(Sender: TObject);
begin
if Destroying then
Exit;
Destroying := True;
Release;
end;
procedure TBigImagesSizeForm.FormCreate(Sender: TObject);
begin
FCallBack := nil;
LnkClose.LoadFromHIcon(Icons[DB_IC_DELETE_INFO]);
RgPictureSize.HandleNeeded;
RgPictureSize.DoubleBuffered := True;
RgPictureSize.Buttons[0].DoubleBuffered := True;
TimerActivated := False;
Destroying := False;
LoadLanguage;
LnkClose.LoadImage;
LnkClose.Left := ClientWidth - TrbImageSize.Width - LnkClose.Width - 5;
LockChange := False;
end;
procedure TBigImagesSizeForm.RgPictureSizeClick(Sender: TObject);
begin
if LockChange or (not Assigned(FCallBack)) then
Exit;
case RgPictureSize.ItemIndex of
0: BigThSize := TrbImageSize.Position * 10 + 40;
1: BigThSize := 300;
2: BigThSize := 250;
3: BigThSize := 200;
4: BigThSize := 150;
5: BigThSize := 100;
6: BigThSize := 85;
end;
FCallBack(Self, BigThSize, BigThSize);
LockChange := True;
TrbImageSize.Position := 50 - (BigThSize div 10 - 4);
LockChange := False;
end;
procedure TBigImagesSizeForm.SetRadioButtonSize;
begin
case BigThSize of
85: RgPictureSize.ItemIndex := 6;
100: RgPictureSize.ItemIndex := 5;
150: RgPictureSize.ItemIndex := 4;
200: RgPictureSize.ItemIndex := 3;
250: RgPictureSize.ItemIndex := 2;
300: RgPictureSize.ItemIndex := 1;
else
RgPictureSize.ItemIndex := 0;
end;
end;
procedure TBigImagesSizeForm.TrbImageSizeChange(Sender: TObject);
begin
BeginScreenUpdate(RgPictureSize.Buttons[0].Handle);
try
if LockChange then
Exit;
LockChange := True;
RgPictureSize.ItemIndex := 0;
BigThSize := Max((50 - TrbImageSize.Position) * 10 + 80, 85);
RgPictureSize.Buttons[0].Caption := Format(L('%dx%d pixels'), [BigThSize, BigThSize]);
FCallBack(Self, BigThSize, BigThSize);
finally
EndScreenUpdate(RgPictureSize.Buttons[0].Handle, False);
LockChange := False;
end;
end;
procedure TBigImagesSizeForm.Execute(aOwner: TForm; aPictureSize : integer;
CallBack: TCallBackBigSizeProc);
var
p: TPoint;
begin
GetCursorPos(p);
p.X := p.X - 12;
LockChange := True;
BigThSize := aPictureSize;
TrbImageSize.Position := 50 - (BigThSize div 10 - 8);
p.y := p.y - 10 - Round((TrbImageSize.Height - 20) * TrbImageSize.Position / TrbImageSize.Max);
if p.y < 0 then
begin
Left := p.X;
p.X := 10;
p.y := 10 + Round((TrbImageSize.Height - 20) * TrbImageSize.Position / TrbImageSize.Max);
Top := 0;
p := ClientToScreen(p);
SetCursorPos(p.X, p.y);
end else
begin
Left := p.X;
Top := p.y - GetSystemMetrics(SM_CYFRAME) - GetSystemMetrics(SM_CYCAPTION)
div 2;
end;
SetRadioButtonSize;
LockChange := False;
RgPictureSize.Items[0] := Format(L('%dx%d pixels'), [BigThSize, BigThSize]);
FCallBack := CallBack;
fOwner := aOwner;
Show;
end;
procedure TBigImagesSizeForm.FormDeactivate(Sender: TObject);
begin
if not TimerActivated then
Exit;
if Destroying then
Exit;
Destroying := True;
Release;
end;
procedure TBigImagesSizeForm.TimerActivateTimer(Sender: TObject);
begin
TimerActivate.Enabled := False;
TimerActivated := True;
end;
procedure TBigImagesSizeForm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_ESCAPE then
Deactivate;
end;
procedure TBigImagesSizeForm.FormShow(Sender: TObject);
var
p : TPoint;
begin
ActivateApplication(Self.Handle);
GetCursorPos(p);
TrbImageSize.SetFocus;
if GetAsyncKeystate(VK_MBUTTON) <> 0 then
Exit;
if GetAsyncKeystate(VK_LBUTTON) <> 0 then
mouse_event(MOUSEEVENTF_LEFTDOWN, P.X, P.Y, 0, 0);
end;
function TBigImagesSizeForm.GetFormID: string;
begin
Result := 'ThumbnailsSize';
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: RGBE<p>
<b>History : </b><font size=-1><ul>
<li>20/01/10 - Yar - Creation
</ul><p>
}
unit RGBE;
interface
{$I GLScene.inc}
uses
Classes, GLVectorTypes, GLVectorGeometry;
procedure float2rgbe(var rgbe: TVector4b; const red, green, blue: Single);
procedure rgbe2float(var red, green, blue: Single; const rgbe: TVector4b);
procedure LoadRLEpixels(stream : TStream; dst: PSingle;
scanline_width, num_scanlines: integer);
procedure LoadRGBEpixels(stream : TStream; dst: PSingle; numpixels: integer);
implementation
uses
SysUtils;
type
ERGBEexception = class(Exception);
{ Extract exponent and mantissa from X }
procedure Frexp(X: Extended; var Mantissa: Extended; var Exponent: Integer);
{ Mantissa ptr in EAX, Exponent ptr in EDX }
{$IFDEF GLS_NO_ASM}
begin
Exponent:=0;
if (X<>0) then
if (abs(X)<0.5) then
repeat
X:=X*2;
Dec(Exponent);
until (abs(X)>=0.5)
else
while (abs(X)>=1) do
begin
X:=X/2;
Inc(Exponent);
end;
Mantissa:=X;
{$ELSE}
asm
FLD X
PUSH EAX
MOV dword ptr [edx], 0 { if X = 0, return 0 }
FTST
FSTSW AX
FWAIT
SAHF
JZ @@Done
FXTRACT // ST(1) = exponent, (pushed) ST = fraction
FXCH
// The FXTRACT instruction normalizes the fraction 1 bit higher than
// wanted for the definition of frexp() so we need to tweak the result
// by scaling the fraction down and incrementing the exponent.
FISTP dword ptr [edx]
FLD1
FCHS
FXCH
FSCALE // scale fraction
INC dword ptr [edx] // exponent biased to match
FSTP ST(1) // discard -1, leave fraction as TOS
@@Done:
POP EAX
FSTP tbyte ptr [eax]
FWAIT
{$ENDIF}
end;
function Ldexp(X: Extended; const P: Integer): Extended;
{$IFDEF GLS_NO_ASM}
begin
ldexp:=x*intpower(2.0,p);
{$ELSE}
{ Result := X * (2^P) }
asm
PUSH EAX
FILD dword ptr [ESP]
FLD X
FSCALE
POP EAX
FSTP ST(1)
FWAIT
{$ENDIF}
end;
// standard conversion from float pixels to rgbe pixels
procedure float2rgbe(var rgbe: TVector4b; const red, green, blue: Single);
var
v, m: Extended;
e: integer;
begin
v := red;
if (green > v) then v := green;
if (blue > v) then v := blue;
if (v < 1e-32) then begin
rgbe[0] := 0;
rgbe[1] := 0;
rgbe[2] := 0;
rgbe[3] := 0;
end
else begin
FrExp(v, m, e);
m := m * 256/v;
rgbe[0] := Floor(red * v);
rgbe[1] := Floor(green * v);
rgbe[2] := Floor(blue * v);
rgbe[3] := Floor(e + 128);
end;
end;
// standard conversion from rgbe to float pixels
// note: Ward uses ldexp(col+0.5,exp-(128+8)). However we wanted pixels
// in the range [0,1] to map back into the range [0,1].
procedure rgbe2float(var red, green, blue: Single; const rgbe: TVector4b);
var
f: single;
begin
if rgbe[3]<>0 then //nonzero pixel
begin
f := ldexp(1.0, rgbe[3]-(128+8));
red := rgbe[0] * f;
green := rgbe[1] * f;
blue := rgbe[2] * f;
end
else begin
red := 0;
green := 0;
blue := 0;
end;
end;
procedure LoadRLEpixels(stream : TStream; dst: PSingle;
scanline_width, num_scanlines: Integer);
var
rgbeTemp: TVector4b;
buf: TVector2b;
rf, gf, bf: Single;
scanline_buffer: PByteArray;
ptr, ptr_end: PByte;
i, count: integer;
begin
if (scanline_width < 8) or (scanline_width > $7FFF) then begin
//run length encoding is not allowed so read flat
LoadRGBEPixels(stream, dst, scanline_width*num_scanlines);
Exit;
end;
scanline_buffer := nil;
while num_scanlines > 0 do
begin
stream.Read(rgbeTemp, SizeOf( TVector4b ));
if (rgbeTemp[0] <> 2)
or (rgbeTemp[1] <> 2)
or (rgbeTemp[2] and $80 <> 0) then
begin
// this file is not run length encoded
rgbe2float( rf, gf, bf, rgbeTemp);
dst^ := rf; Inc(dst);
dst^ := gf; Inc(dst);
dst^ := bf; Inc(dst);
if Assigned(scanline_buffer) then FreeMem( scanline_buffer );
LoadRGBEpixels(stream, dst, scanline_width*num_scanlines-1);
Exit;
end;
if ((Integer(rgbeTemp[2]) shl 8) or rgbeTemp[3]) <> scanline_width then begin
if Assigned(scanline_buffer) then FreeMem( scanline_buffer );
raise ERGBEexception.Create('Wrong scanline width.');
end;
if not Assigned(scanline_buffer) then ReallocMem(scanline_buffer, 4*scanline_width);
ptr := PByte( scanline_buffer );
// read each of the four channels for the scanline into the buffer
for i := 0 to 3 do
begin
ptr_end := @scanline_buffer[(i+1)*scanline_width];
while Integer(ptr) < Integer(ptr_end) do
begin
stream.Read(buf, SizeOf( TVector2b ));
if buf[0] > 128 then
begin //a run of the same value
count := buf[0]-128;
if (count = 0) or (count > Integer(ptr_end) - Integer(ptr)) then
begin
FreeMem( scanline_buffer );
raise ERGBEexception.Create('Bad HDR scanline data.');
end;
while count > 0 do
begin
ptr^ := buf[1];
Dec( count );
Inc( ptr );
end;
end
else begin //a non-run
count := buf[0];
if (count = 0) or (count > Integer(ptr_end) - Integer(ptr)) then
begin
FreeMem( scanline_buffer );
raise ERGBEexception.Create('Bad HDR scanline data.');
end;
ptr^ := buf[1];
Dec( count );
Inc( ptr );
if count>0 then stream.Read(ptr^, Count);
Inc( ptr, count);
end;
end;
end;
// now convert data from buffer into floats
for i := 0 to scanline_width-1 do
begin
rgbeTemp[0] := scanline_buffer[i];
rgbeTemp[1] := scanline_buffer[i+scanline_width];
rgbeTemp[2] := scanline_buffer[i+2*scanline_width];
rgbeTemp[3] := scanline_buffer[i+3*scanline_width];
rgbe2float( rf, gf, bf, rgbeTemp);
dst^ := rf; Inc(dst);
dst^ := gf; Inc(dst);
dst^ := bf; Inc(dst);
end;
Dec( num_scanlines );
end;
if Assigned(scanline_buffer) then FreeMem( scanline_buffer );
end;
procedure LoadRGBEpixels(stream : TStream; dst: PSingle; numpixels: integer);
var
rgbeTemp: TVector4b;
rf, gf, bf: Single;
begin
while numpixels>0 do
begin
stream.Read(rgbeTemp, SizeOf( TVector4b ));
rgbe2float( rf, gf, bf, rgbeTemp);
dst^ := rf; Inc(dst);
dst^ := gf; Inc(dst);
dst^ := bf; Inc(dst);
Dec( numpixels );
end;
end;
end.
|
unit UResults;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, UHistory, ComCtrls;
type
TfrmResults = class(TForm)
lvResults: TListView;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
FHistory: THistoryArray;
procedure outputHistory;
public
{ Public declarations }
end;
var
frmResults: TfrmResults;
implementation
uses UMenu;
{$R *.dfm}
procedure TfrmResults.FormCreate(Sender: TObject);
begin
Caption := Application.Title;
FHistory := returnHistory;
outputHistory;
end;
procedure TfrmResults.outputHistory;
var
i: Integer;
listItem: TListItem;
begin
for i := 0 to length(FHistory) - 1 do
begin
listItem := lvResults.Items.Add;
listItem.Caption := IntToStr(FHistory[i].score);
listItem.SubItems.Add(DateTimeToStr(FHistory[i].date));
listItem.SubItems.Add(IntToStr(FHistory[i].snakeLength));
listItem.SubItems.Add(IntToStr(FHistory[i].code));
end;
end;
procedure TfrmResults.FormClose(Sender: TObject; var Action: TCloseAction);
begin
frmMenu.Show;
end;
end.
|
unit SprDoh2DataModul;
interface
uses
SysUtils, Classes, DB, FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase,
frxClass, frxDBSet, frxDesgn, IBase, IniFiles, Forms, Dates, Variants,
Unit_SprSubs_Consts, ZProc,Dialogs, frxExportXLS, frxExportRTF,
frxExportHTML, FIBQuery, pFIBQuery, pFIBStoredProc, AccMGMT;
Type TFilterData = record
ID_man : integer;
TN:integer;
FIO: string;
Kod_setup1:integer;
Kod_setup2:integer;
PrUser:Boolean;
end;
type
TDM = class(TDataModule)
DB: TpFIBDatabase;
ReadTransaction: TpFIBTransaction;
DSet: TpFIBDataSet;
ReportDBDSet: TfrxDBDataset;
Designer: TfrxDesigner;
DSetFoundationData: TpFIBDataSet;
ReportDBDSetFoundationData: TfrxDBDataset;
DSource: TDataSource;
Report: TfrxReport;
XLSExport: TfrxXLSExport;
frxHTMLExport1: TfrxHTMLExport;
frxRTFExport1: TfrxRTFExport;
StoredProc: TpFIBStoredProc;
procedure ReportGetValue(const VarName: String; var Value: Variant);
procedure DataModuleDestroy(Sender: TObject);
procedure ReportAfterPrintReport(Sender: TObject);
private
PUser:Boolean;
CanEdit:Boolean;
public
function PrintSpr(ADb_Handle: TISC_DB_HANDLE; AParameter:TFilterData):variant;
end;
implementation
{$R *.dfm}
const Path_IniFile_Reports = 'Reports\Zarplata\Reports.ini';
const SectionOfIniFile = 'SprDoh';
const NameReport = 'Reports\Zarplata\SprDoh2.fr3';
function TDM.PrintSpr(ADb_Handle: TISC_DB_HANDLE; AParameter:TFilterData):variant;
var IniFile:TIniFile;
ViewMode:integer;
PathReport:string;
SummaDoh:Extended;
SummaNal:Extended;
SummaNar:Extended;
begin
PUser:=AParameter.PrUser;
CanEdit := fibCheckPermission('/ROOT/Zarplata/Z_Menu/Z_Menu_Reports/Z_Menu_DOXOD/CanEdit','Belong')=0;
CanEdit := True;
DSet.SQLs.SelectSQL.Text := 'SELECT * FROM Z_SPR_DOH2('+IntToStr(AParameter.Kod_setup1)+','
+IntToStr(AParameter.Kod_setup2)+','
+IntToStr(AParameter.ID_man)+')';
DSetFoundationData.SQLs.SelectSQL.Text := 'SELECT * FROM Z_FOUNDATION_DATA_SPR_DOH2('+IntToStr(AParameter.ID_man)+','+IntToStr(AParameter.Kod_setup2)+')';
DB.Handle:=ADb_Handle;
DSet.Open;
DSetFoundationData.Open;
SummaDoh:=0;
SummaNal:=0;
SummaNar:=0;
DSet.First;
while not DSet.Eof do
begin
SummaDoh:=SummaDoh+DSet['SUM_DOH'];
SummaNal:=SummaNal+DSet['SUM_NAL'];
SummaNar:=SummaNar+DSet['SUM_NAR'];
DSet.Next;
end;
IniFile:=TIniFile.Create(ExtractFilePath(Application.ExeName)+Path_IniFile_Reports);
ViewMode:=IniFile.ReadInteger(SectionOfIniFile,'ViewMode',1);
PathReport:=IniFile.ReadString(SectionOfIniFile,'NameReport',NameReport);
IniFile.Free;
Report.Clear;
Report.LoadFromFile(ExtractFilePath(Application.ExeName)+PathReport,True);
Report.Variables.Clear;
Report.Variables[' '+'User Category']:=NULL;
Report.Variables.AddVariable('User Category','PSex',
''''+IfThen(DSetFoundationData['ID_SEX']=1,TDM_RPSexMan_Text,TDM_RPSexWoMan_Text)+'''');
Report.Variables.AddVariable('User Category','PKodSet1',''''+KodSetupToPeriod(AParameter.Kod_setup1,1)+'''');
Report.Variables.AddVariable('User Category','PKodSet2',''''+KodSetupToPeriod(AParameter.Kod_setup2,1)+'''');
if SummaDoh=0 then
Report.Variables.AddVariable('User Category','PSumDoh','''----- ''')
else
Report.Variables.AddVariable('User Category','PSumDoh',''''+FloatToStrF(SummaDoh,ffFixed,16,2)+' ''');
if SummaNal=0 then
Report.Variables.AddVariable('User Category','PSumNal','''----- ''')
else
Report.Variables.AddVariable('User Category','PSumNal',''''+FloatToStrF(SummaNal,ffFixed,16,2)+' ''');
if SummaNar=0 then
Report.Variables.AddVariable('User Category','PSumNar','''----- ''')
else
Report.Variables.AddVariable('User Category','PSumNar',''''+FloatToStrF(SummaNar,ffFixed,16,2)+' ''');
Report.Variables.AddVariable('User Category','PWork',''''+TypeWorkReturn(DSetFoundationData['N_STUD'],DSetFoundationData['N_TYPEWORK'])+
' '+IfThen(VarIsNull(DSetFoundationData['KURS']),'',VarToStr(DSetFoundationData['KURS'])+' курс ')+
IfThen(VarIsNull(DSetFoundationData['NAME_DEPARTMENT']),'',VarToSTr(DSetFoundationData['NAME_DEPARTMENT']))+'''');
Report.Variables.AddVariable('User Category','SumLetters',''''+SumToString(SummaDoh,1,False)+'''');
case ViewMode of
1: Report.ShowReport;
2: Report.DesignReport;
end;
Report.Free;
end;
procedure TDM.ReportGetValue(const VarName: String; var Value: Variant);
begin
if (PUser=True) then
begin
if UpperCase(VarName)='USER' then
value:=AccMGMT.GetUserFIO;
end
else if UpperCase(VarName)='USER' then
value:=' ';
if UpperCase(VarName)='PKOD_SETUP' then
Value:=KodSetupToPeriod(DSet['KOD_SETUP'],4);
if UpperCase(VarName)='PSUM_DOH' then
begin
if (DSet['SUM_DOH']=NULL) or (DSet['SUM_DOH']=0) then
value:='----- '
else
Value:=FloatToStrF(DSet['SUM_DOH'],ffFixed,16,2)+' ';
end;
if UpperCase(VarName)='PSUM_NAL' then
begin
if (DSet['SUM_NAL']=NULL) or (DSet['SUM_NAL']=0) then
value:='----- '
else
Value:=FloatToStrF(DSet['SUM_NAL'],ffFixed,16,2)+' ';
end;
if UpperCase(VarName)='PSUM_NAR' then
begin
if (DSet['SUM_NAR']=NULL) or (DSet['SUM_NAR']=0) then
value:='----- '
else
Value:=FloatToStrF(DSet['SUM_NAR'],ffFixed,16,2)+' ';
end;
if UpperCase(VarName)='P_MONTH' then
begin
value:=MonthNumToName(IfThen((DateToKodSetup(Date) mod 12)=0,12,DateToKodSetup(Date) mod 12));
end;
if UpperCase(VarName)='CANEDIT' then
value:=CANEDIT;
end;
procedure TDM.DataModuleDestroy(Sender: TObject);
begin
if ReadTransaction.InTransaction then ReadTransaction.Commit;
end;
procedure TDM.ReportAfterPrintReport(Sender: TObject);
begin
StoredProc.StoredProcName:='Z_SPRAVKA_NUMBER_INC';
StoredProc.ExecProc;
end;
end.
|
unit UnitMain;
interface
uses
Windows, SysUtils, Classes, Controls, Forms, Dialogs, Graphics,
StdCtrls, UCrpe32, UCrpeDS, Db, UCrpeClasses;
type
TfrmMain = class(TForm)
btnSelect: TButton;
CrpeDS1: TCrpeDS;
Crpe1: TCrpe;
Memo1: TMemo;
cbGrow: TCheckBox;
procedure btnSelectClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure CrpeDS1GetRecordCount(Sender: TObject; DataSet: TDataSet;
var RecordCount: Integer);
procedure CrpeDS1GetFieldCount(Sender: TObject; DataSet: TDataSet;
var FieldCount: Smallint);
procedure CrpeDS1GetFieldName(Sender: TObject; DataSet: TDataSet;
FieldIndex: Smallint; var FieldName: WideString);
procedure CrpeDS1GetFieldType(Sender: TObject; DataSet: TDataSet;
FieldIndex: Smallint; var FieldType: Smallint);
procedure CrpeDS1GetBlobFieldValue(Sender: TObject; DataSet: TDataSet;
FieldIndex: Smallint; var BlobFieldValue: TMemoryStream);
procedure CrpeDS1MoveFirst(Sender: TObject; DataSet: TDataSet);
procedure CrpeDS1MoveNext(Sender: TObject; DataSet: TDataSet);
procedure CrpeDS1GetBookmark(Sender: TObject; DataSet: TDataSet;
var Bookmark: OleVariant);
procedure CrpeDS1SetBookmark(Sender: TObject; DataSet: TDataSet;
var Bookmark: OleVariant);
procedure CrpeDS1EOF(Sender: TObject; DataSet: TDataSet;
var EndOfFile: Boolean);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmMain : TfrmMain;
ExePath : string;
BmpPath : string;
BmpCount : integer;
BmpItem : integer;
Bkmark : string;
implementation
{$R *.DFM}
uses FileCtrl, UnitPath, Utilities;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
ExePath := AddBackSlash(ExtractFileDir(Application.ExeName));
BmpPath := ExePath;
end;
procedure TfrmMain.btnSelectClick(Sender: TObject);
var
n : integer;
function GetFileCount(SourceDir: string): integer;
var
fSearch : TSearchRec;
i : integer;
s : string;
begin
i := 0;
s := AddBackSlash(SourceDir) + '*.bmp';
if FindFirst(s, faAnyFile, fSearch) = 0 then
begin
{skip directories}
if (fSearch.Name <> '.') and (fSearch.Name <> '..') and
(fSearch.Attr and faDirectory = 0) then
Inc(i);
{Count the next files}
while FindNext(fSearch) = 0 do
begin
{skip directories}
if (fSearch.Name <> '.') and (fSearch.Name <> '..') and
(fSearch.Attr and faDirectory = 0) then
Inc(i);
end;
FindClose(fSearch);
end;
Result := i;
end;
begin
PathDlg := TPathDlg.Create(Self);
PathDlg.Caption := 'Select a Bitmap Directory';
PathDlg.rPath := BmpPath;
PathDlg.ShowModal;
if PathDlg.ModalResult = mrOk then
begin
if DirectoryExists(PathDlg.rPath) then
BmpPath := PathDlg.rPath;
BmpCount := GetFileCount(BmpPath);
Memo1.Lines.Clear;
Crpe1.ReportName := ExePath + 'PicViewer.rpt';
Crpe1.DiscardSavedData;
Crpe1.Tables[0].DataPointer := CrpeDS1.DataPointer;
for n := 0 to Crpe1.Pictures.Count-1 do
Crpe1.Pictures[n].CanGrow := cbGrow.Checked;
Crpe1.ReportOptions.ZoomMode := pwPageWidth;
Crpe1.WindowButtonBar.ToolbarTips := True;
Crpe1.WindowButtonBar.CancelBtn := True;
Crpe1.Show;
end;
end;
procedure TfrmMain.CrpeDS1GetRecordCount(Sender: TObject;
DataSet: TDataSet; var RecordCount: Integer);
begin
RecordCount := BmpCount div 8;
Memo1.Lines.Add('GetRecordCount: ' + IntToStr(RecordCount));
end;
procedure TfrmMain.CrpeDS1GetFieldCount(Sender: TObject; DataSet: TDataSet;
var FieldCount: Smallint);
begin
FieldCount := 8;
Memo1.Lines.Add('GetFieldCount: ' + IntToStr(FieldCount));
end;
procedure TfrmMain.CrpeDS1GetFieldName(Sender: TObject; DataSet: TDataSet;
FieldIndex: Smallint; var FieldName: WideString);
begin
case FieldIndex of
0: FieldName := 'Image1';
1: FieldName := 'Image2';
2: FieldName := 'Image3';
3: FieldName := 'Image4';
4: FieldName := 'Image5';
5: FieldName := 'Image6';
6: FieldName := 'Image7';
7: FieldName := 'Image8';
end;
Memo1.Lines.Add('GetFieldName: ' + FieldName);
end;
procedure TfrmMain.CrpeDS1GetFieldType(Sender: TObject; DataSet: TDataSet;
FieldIndex: Smallint; var FieldType: Smallint);
begin
FieldType := varArray or varByte;
Memo1.Lines.Add('GetFieldType: ' + IntToStr(FieldType));
end;
procedure TfrmMain.CrpeDS1GetBlobFieldValue(Sender: TObject;
DataSet: TDataSet; FieldIndex: Smallint;
var BlobFieldValue: TMemoryStream);
var
bitmap: TBitmap;
sFile : string;
function GetBmpItem(index: integer): string;
var
fSearch : TSearchRec;
i : integer;
s : string;
begin
i := 0;
Result := '';
s := AddBackSlash(BmpPath) + '*.bmp';
if FindFirst(s, faAnyFile, fSearch) = 0 then
begin
{skip directories}
if (fSearch.Name <> '.') and (fSearch.Name <> '..') and
(fSearch.Attr and faDirectory = 0) then
begin
Inc(i);
if i = index then
begin
Result := fSearch.Name;
Inc(BmpItem);
Exit;
end;
end;
{Count the next files}
while FindNext(fSearch) = 0 do
begin
{skip directories}
if (fSearch.Name <> '.') and (fSearch.Name <> '..') and
(fSearch.Attr and faDirectory = 0) then
begin
Inc(i);
if i = index then
begin
Result := fSearch.Name;
Inc(BmpItem);
Exit;
end;
end;
end;
end;
FindClose(fSearch);
end;
begin
bitmap := TBitmap.Create;
try
sFile := GetBmpItem(BmpItem);
Memo1.Lines.Add('GetBlob: ' + AddBackSlash(BmpPath) + sFile);
if FileExists(AddBackSlash(BmpPath) + sFile) then
begin
bitmap.LoadFromFile(AddBackSlash(BmpPath) + sFile);
bitmap.SaveToStream(BlobFieldValue);
end;
finally
bitmap.free;
end;
end;
procedure TfrmMain.CrpeDS1MoveFirst(Sender: TObject; DataSet: TDataSet);
begin
BmpItem := 1;
Memo1.Lines.Add('MoveFirst');
end;
procedure TfrmMain.CrpeDS1MoveNext(Sender: TObject; DataSet: TDataSet);
begin
Memo1.Lines.Add('MoveNext');
end;
procedure TfrmMain.CrpeDS1GetBookmark(Sender: TObject; DataSet: TDataSet;
var Bookmark: OleVariant);
begin
Bookmark := BkMark;
Memo1.Lines.Add('GetBookmark: ' + Bookmark);
end;
procedure TfrmMain.CrpeDS1SetBookmark(Sender: TObject; DataSet: TDataSet;
var Bookmark: OleVariant);
begin
BkMark := Bookmark;
Memo1.Lines.Add('SetBookmark: ' + Bookmark);
end;
procedure TfrmMain.CrpeDS1EOF(Sender: TObject; DataSet: TDataSet;
var EndOfFile: Boolean);
begin
EndOfFile := (BmpItem >= BmpCount) or (BmpCount = 0);
Memo1.Lines.Add('EndOfFile: ' + CrBooleanToStr(EndOfFile, False));
end;
end.
|
{: TGLMultiPolygon Sample, contributed by Uwe Raabe.<p>
Note: this sample has been partly obsoleted/superseded by the TGLExtrusionSolid
(by Uwe Raabe), which allows building such solids directly.
}
unit expolygon1;
interface
uses
SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
VectorGeometry, GLTexture, GLScene, GLObjects, GLGeomObjects, GLMultiPolygon,
GLViewer, GLCrossPlatform, GLMaterial, GLCoordinates;
type
TVektor = record
x,y,z : Double;
end;
TForm1 = class(TForm)
GLSceneViewer1: TGLSceneViewer;
GLScene1: TGLScene;
GLLightSource1: TGLLightSource;
GLLightSource2: TGLLightSource;
Container: TGLDummyCube;
CameraTarget: TGLDummyCube;
Camera: TGLCamera;
GLMaterialLibrary1: TGLMaterialLibrary;
procedure GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure FormShow(Sender: TObject);
private
mx,my : Integer;
FPlane : array[0..5] of TGLMultiPolygon;
FDY: Double;
FDX: Double;
FDZ: Double;
function GetPlane(Side: Integer): TGLMultiPolygon;
procedure SetDX(const Value: Double);
procedure SetDY(const Value: Double);
procedure SetDZ(const Value: Double);
procedure CreatePanel;
procedure AddMaterial(Obj:TGLSceneObject);
procedure ReDraw;
function TransformToPlane(Side:Integer; x,y,z:Double):TVektor; overload;
function TransformToPlane(Side:Integer; v:TVektor):TVektor; overload;
public
{ Public-Deklarationen }
procedure MakeHole(Side:Integer; X,Y,Z,D,T:Double; Phi:Double=0; Rho:Double=0);
property Plane[Side:Integer]:TGLMultiPolygon read GetPlane;
property DX:Double read FDX write SetDX;
property DY:Double read FDY write SetDY;
property DZ:Double read FDZ write SetDZ;
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
function Vektor(x,y,z:Double):TVektor;
begin
result.x := x;
result.y := y;
result.z := z;
end;
const
cOpposite : array[0..5] of Integer = (5,3,4,1,2,0);
procedure TForm1.MakeHole(Side: Integer; X, Y, Z, D, T, Phi, Rho: Double);
var
R : Double;
procedure AddPlane(I:Integer);
begin
with Plane[I] do begin
with TransformToPlane(I,X,Y,Z) do begin
Contours.Add.Nodes.AddXYArc(R/cos(Phi*c180divPi),R,0,360,16,AffineVectorMake(X,Y,0));
end;
end;
end;
var
Dum : TGLDummyCube;
Cyl : TGLCylinder;
through : Boolean;
begin
Dum := TGLDummyCube.Create(nil);
Dum.Position.x := X;
Dum.Position.y := Y;
Dum.Position.z := Z;
case Side of
0 : Dum.PitchAngle := -90;
1 : Dum.RollAngle := 90;
2 : Dum.RollAngle := 180;
3 : Dum.RollAngle := 270;
4 : Dum.RollAngle := 0;
5 : Dum.PitchAngle := 90;
end;
Dum.PitchAngle := Dum.PitchAngle + Rho;
Dum.RollAngle := Dum.RollAngle + Phi;
R := 0.5*D;
through := true;
case Side of
0 : if (Z-T)<=0 then T := Z else through := false;
1 : if (X+T)>=DX then T := DX-X else through := false;
2 : if (Y+T)>=DY then T := DY-Y else through := false;
3 : if (X-T)<=0 then T := X else through := false;
4 : if (Y-T)<=0 then T := Y else through := false;
5 : if (Z+T)>=DZ then T := DZ-Z else through := false;
end;
Cyl := TGLCylinder.Create(nil);
AddMaterial(Cyl);
Cyl.Position.x := 0;
Cyl.Position.y := - 0.5*T;
Cyl.Position.z := 0;
Cyl.Height := T;
Cyl.BottomRadius := R;
Cyl.TopRadius := R;
Cyl.NormalDirection := ndInside;
if through then Cyl.Parts := [cySides]
else Cyl.Parts := [cySides,cyBottom];
Dum.AddChild(Cyl);
Container.AddChild(Dum);
AddPlane(Side);
if through then AddPlane(cOpposite[Side]);
end;
procedure TForm1.CreatePanel;
var
I : Integer;
function MakePlane(X,Y,Z,P,T,W,H:Double):TGLMultiPolygon;
begin
result := TGLMultiPolygon.Create(nil);
result.Material.MaterialLibrary := GLMaterialLibrary1;
result.Material.LibMaterialName := 'MatSurface';
result.Parts := [ppTop];
result.AddNode(0,0,0,0);
result.AddNode(0,W,0,0);
result.AddNode(0,W,H,0);
result.AddNode(0,0,H,0);
result.Position.x := X;
result.Position.y := Y;
result.Position.z := Z;
result.PitchAngle := P;
result.TurnAngle := T;
end;
begin
Container.DeleteChildren;
FPlane[2] := MakePlane( 0, 0, 0, -90, 0,DX,DZ);
FPlane[3] := MakePlane(DX, 0, 0, -90, 90,DY,DZ);
FPlane[4] := MakePlane(DX,DY, 0, -90,180,DX,DZ);
FPlane[1] := MakePlane( 0,DY, 0, -90,270,DY,DZ);
FPlane[5] := MakePlane( 0,DY, 0,-180, 0,DX,DY);
FPlane[0] := MakePlane( 0, 0,DZ, 0, 0,DX,DY);
for I:=0 to 5 do Container.AddChild(FPlane[I]);
end;
function TForm1.GetPlane(Side: Integer): TGLMultiPolygon;
begin
result := FPlane[Side];
end;
procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
mx:=x; my:=y;
end;
procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
if Shift<>[] then
Camera.MoveAroundTarget(my-y, mx-x);
mx:=x; my:=y;
end;
procedure TForm1.SetDX(const Value: Double);
begin
FDX := Value;
Container.Position.X := -0.5*Value;
end;
procedure TForm1.SetDY(const Value: Double);
begin
FDY := Value;
Container.Position.y := -0.5*Value;
end;
procedure TForm1.SetDZ(const Value: Double);
begin
FDZ := Value;
Container.Position.z := -0.5*Value;
end;
procedure TForm1.AddMaterial(Obj: TGLSceneObject);
begin
Obj.Material.MaterialLibrary := GLMaterialLibrary1;
Obj.Material.LibMaterialName := 'MatInner';
end;
procedure TForm1.ReDraw;
begin
DX := 600;
DY := 400;
DZ := 19;
CreatePanel;
MakeHole(0,0.5*DX,0.5*DY,DZ,50,DZ);
end;
procedure TForm1.FormShow(Sender: TObject);
begin
Redraw;
end;
function TForm1.TransformToPlane(Side: Integer; x, y, z: Double): TVektor;
begin
case Side of
0 : result := Vektor(x,y,z-DZ);
1 : result := Vektor(DY-y,z,x);
2 : result := Vektor(x,z,-y);
3 : result := Vektor(y,z,DX-x);
4 : result := Vektor(DX-x,z,DY-y);
5 : result := Vektor(x,DY-y,z);
else result := Vektor(x,y,z);
end;
end;
function TForm1.TransformToPlane(Side: Integer; v: TVektor): TVektor;
begin
with v do result := TransformToPlane(Side,x,y,z);
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Core.Spec.Interfaces;
interface
uses
System.SysUtils,
System.Classes,
Spring.Collections,
DPM.Core.Types,
DPM.Core.Logging,
DPM.Core.TargetPlatform,
DPM.Core.Dependency.Version,
JsonDataObjects,
DPM.Core.Options.Spec;
type
ISpecNode = interface
['{AD47A3ED-591B-4E47-94F2-7EC136182202}']
function LoadFromJson(const jsonObject : TJsonObject) : boolean;
end;
ISpecDependency = interface(ISpecNode)
['{6CE14888-54A8-459C-865E-E4B4628DB8C6}']
function GetId : string;
function GetVersionRange : TVersionRange;
procedure SetVersionRange(const value : TVersionRange);
function GetVersionString : string;
function IsGroup : boolean;
function Clone : ISpecDependency;
property Id : string read GetId;
property Version : TVersionRange read GetVersionRange write SetVersionRange;
property VersionString : string read GetVersionString;
end;
ISpecDependencyGroup = interface(ISpecDependency)
['{98666E8B-0C15-4CEF-9C1C-18E90D86E378}']
function GetTargetPlatform : TTargetPlatform;
function GetDependencies : IList<ISpecDependency>;
property TargetPlatform : TTargetPlatform read GetTargetPlatform;
property Dependencies : IList<ISpecDependency>read GetDependencies;
end;
ISpecMetaData = interface(ISpecNode)
['{9972F2EA-4180-4D12-9193-13A55B927B81}']
function GetId : string;
function GetVersion : TPackageVersion;
function GetDescription : string;
function GetAuthors : string;
function GetProjectUrl : string;
function GetRepositoryUrl : string;
function GetRepositoryType : string;
function GetRepositoryBranch : string;
function GetRepositoryCommit : string;
function GetReleaseNotes : string;
function GetLicense : string;
function GetIcon : string;
function GetCopyright : string;
function GetTags : string;
function GetIsTrial : boolean;
function GetIsCommercial : boolean;
function GetReadMe : string;
function GetUIFrameworkType : TDPMUIFrameworkType;
procedure SetVersion(const value : TPackageVersion);
procedure SetId(const value : string);
procedure SetDescription(const value : string);
procedure SetAuthors(const value : string);
procedure SetProjectUrl(const value : string);
procedure SetRepositoryUrl(const value : string);
procedure SetRepositoryType(const value : string);
procedure SetRepositoryBranch(const value : string);
procedure SetRepositoryCommit(const value : string);
procedure SetReleaseNotes(const value : string);
procedure SetLicense(const value : string);
procedure SetIcon(const value : string);
procedure SetCopyright(const value : string);
procedure SetTags(const value : string);
procedure SetIsTrial(const value : boolean);
procedure SetIsCommercial(const value : boolean);
procedure SetReadMe(const value : string);
procedure SetUIFrameworkType(const value : TDPMUIFrameworkType);
property Id : string read GetId write SetId;
property Version : TPackageVersion read GetVersion write SetVersion;
property Description : string read GetDescription write SetDescription;
property Authors : string read GetAuthors write SetAuthors;
property ProjectUrl : string read GetProjectUrl write SetProjectUrl;
property RepositoryUrl : string read GetRepositoryUrl write SetRepositoryUrl;
property RepositoryType : string read GetRepositoryType write SetRepositoryType;
property RepositoryBranch : string read GetRepositoryBranch write SetRepositoryBranch;
property RepositoryCommit : string read GetRepositoryCommit write SetRepositoryCommit;
property ReleaseNotes : string read GetReleaseNotes write SetReleaseNotes;
property License : string read GetLicense write SetLicense;
property Icon : string read GetIcon write SetIcon;
property Copyright : string read GetCopyright write SetCopyright;
property Tags : string read GetTags write SetTags;
property IsTrial : boolean read GetIsTrial write SetIsTrial;
property IsCommercial : boolean read GetIsCommercial write SetIsCommercial;
property ReadMe : string read GetReadMe write SetReadMe;
property UIFrameworkType : TDPMUIFrameworkType read GetUIFrameworkType write SetUIFrameworkType;
end;
ISpecFileEntry = interface(ISpecNode)
['{2BE821AA-94C7-439C-B236-85D8901FFA81}']
function GetSource : string;
function GetDestination : string;
function GetExclude : IList<string>;
function GetFlatten : boolean;
procedure SetSource(const value : string);
procedure SetDestination(const value : string);
function GetIgnore : boolean;
function Clone : ISpecFileEntry;
property Source : string read GetSource write SetSource;
property Destination : string read GetDestination write SetDestination;
property Exclude : IList<string>read GetExclude;
property Flatten : boolean read GetFlatten;
property Ignore : boolean read GetIgnore;
end;
ISpecBPLEntry = interface(ISpecNode)
['{13723048-E2AA-45BE-A0F1-C446848F3936}']
function GetSource : string;
function GetCopyLocal : boolean;
function GetInstall : boolean;
function GetBuildId : string;
procedure SetSource(const value : string);
procedure SetBuildId(const value : string);
function Clone : ISpecBPLEntry;
property Source : string read GetSource write SetSource;
property CopyLocal : boolean read GetCopyLocal; //ignored for design
property Install : boolean read GetInstall; //ignored for runtime
property BuildId : string read GetBuildId write SetBuildId;
end;
ISpecSearchPath = interface(ISpecNode)
['{493371C5-CD82-49EF-9D2A-BA7C4CFA2550}']
function GetPath : string;
procedure SetPath(const value : string);
function IsGroup : boolean;
function Clone : ISpecSearchPath;
property Path : string read GetPath write SetPath;
end;
ISpecSearchPathGroup = interface(ISpecSearchPath)
['{B558E9C4-5B01-409F-AB59-5D8B71F0DCB1}']
function GetTargetPlatform : TTargetPlatform;
function GetSearchPaths : IList<ISpecSearchPath>;
property TargetPlatform : TTargetPlatform read GetTargetPlatform;
property SearchPaths : IList<ISpecSearchPath>read GetSearchPaths;
end;
//post build copy operations for res, dfm etc
ISpecCopyEntry = interface(ISpecNode)
['{F36D7156-0537-4BF4-9D51-E873B797FA27}']
function GetSource : string;
function GetFlatten : boolean;
function Clone : ISpecCopyEntry;
property Source : string read GetSource;
property Flatten : boolean read GetFlatten;
end;
ISpecBuildEntry = interface(ISpecNode)
['{9E1850EB-40C4-421F-A47F-03FDD6286573}']
function GetId : string;
function GetProject : string;
function GetConfig : string;
function GetBplOutputDir : string;
function GetLibOutputDir : string;
function GetDesignOnly : boolean;
function GetBuildForDesign : boolean;
function GetCopyFiles : IList<ISpecCopyEntry>;
procedure SetId(const value : string);
procedure SetProject(const value : string);
procedure SetBplOutputDir(const value : string);
procedure SetLibOutputDir(const value : string);
procedure SetDesignOnly(const value : boolean);
procedure SetBuildForDesign(const value : boolean);
function Clone : ISpecBuildEntry;
property Id : string read GetId write SetId;
property Project : string read GetProject write SetProject;
property Config : string read GetConfig;
property LibOutputDir : string read GetLibOutputDir write SetLibOutputDir;
property BplOutputDir : string read GetBplOutputDir write SetBplOutputDir;
property DesignOnly : boolean read GetDesignOnly write SetDesignOnly;
property BuildForDesign : boolean read GetBuildForDesign write SetBuildForDesign;
property CopyFiles : IList<ISpecCopyEntry> read GetCopyFiles;
end;
ISpecTemplateBase = interface(ISpecNode)
['{B4DE32F7-AE58-4519-B69D-2389F12EC63F}']
function GetLibFiles : IList<ISpecFileEntry>;
function GetSourceFiles : IList<ISpecFileEntry>;
function GetFiles : IList<ISpecFileEntry>;
function GetRuntimeFiles : IList<ISpecBPLEntry>;
function GetDesignFiles : IList<ISpecBPLEntry>;
function GetDependencies : IList<ISpecDependency>;
function GetSearchPaths : IList<ISpecSearchPath>;
function GetBuildEntries : IList<ISpecBuildEntry>;
function FindDependencyById(const id : string) : ISpecDependency;
function FindDependencyGroupByTargetPlatform(const targetPlatform : TTargetPlatform) : ISpecDependencyGroup;
function FindSearchPathByPath(const path : string) : ISpecSearchPath;
function FindRuntimeBplBySrc(const src : string) : ISpecBPLEntry;
function FindDesignBplBySrc(const src : string) : ISpecBPLEntry;
function FindLibFileBySrc(const src : string) : ISpecFileEntry;
function FindSourceFileBySrc(const src : string) : ISpecFileEntry;
function FindOtherFileBySrc(const src : string) : ISpecFileEntry;
function FindBuildEntryById(const id : string) : ISpecBuildEntry;
property LibFiles : IList<ISpecFileEntry>read GetLibFiles;
property SourceFiles : IList<ISpecFileEntry>read GetSourceFiles;
property Files : IList<ISpecFileEntry>read GetFiles;
property RuntimeFiles : IList<ISpecBPLEntry>read GetRuntimeFiles;
property DesignFiles : IList<ISpecBPLEntry>read GetDesignFiles;
property Dependencies : IList<ISpecDependency>read GetDependencies;
property SearchPaths : IList<ISpecSearchPath>read GetSearchPaths;
property BuildEntries : IList<ISpecBuildEntry>read GetBuildEntries;
end;
ISpecTemplate = interface(ISpecTemplateBase)
['{FB9EE9B8-E77B-4E45-A838-E1C9C9947CFB}']
function GetName : string;
property Name : string read GetName;
end;
ISpecTargetPlatform = interface(ISpecTemplateBase)
['{43BE69CA-0C29-4147-806B-460FFF402A68}']
function GetPlatforms : TArray<TDPMPlatform>;
function GetTemplateName : string;
function GetCompiler : TCompilerVersion;
function GetVariables : TStrings;
function CloneForPlatform(const platform : TDPMPlatform) : ISpecTargetPlatform;
property Compiler : TCompilerVersion read GetCompiler;
property Platforms : TArray<TDPMPlatform>read GetPlatforms;
property TemplateName : string read GetTemplateName;
property Variables : TStrings read GetVariables;
end;
IPackageSpec = interface(ISpecNode)
['{9F2BE15D-40DD-4263-925C-01E255D7BE03}']
function GetMetaData : ISpecMetaData;
function GetTargetPlatforms : IList<ISpecTargetPlatform>;
function GetTargetPlatform : ISpecTargetPlatform;
function GetTemplates : IList<ISpecTemplate>;
function GetIsValid : boolean;
function GetFileName : string;
//builds out the full spec
function PreProcess(const version : TPackageVersion; const properties : TStringList) : boolean;
function GenerateManifestJson(const version : TPackageVersion; const targetPlatform : ISpecTargetPlatform) : string;
property MetaData : ISpecMetaData read GetMetaData;
property TargetPlatforms : IList<ISpecTargetPlatform>read GetTargetPlatforms;
property TargetPlatform : ISpecTargetPlatform read GetTargetPlatform;
property Templates : IList<ISpecTemplate>read GetTemplates;
property IsValid : boolean read GetIsValid;
property FileName : string read GetFileName;
end;
IPackageSpecReader = interface
['{8A20F825-8DCA-4784-BDBD-8F91A651BA72}']
function ReadSpec(const fileName : string) : IPackageSpec;
function ReadSpecString(const specString : string) : IPackageSpec;
end;
IPackageSpecWriter = interface
['{F3370E25-2E9D-4353-9985-95C75D35D68E}']
function CreateSpecFile(const options : TSpecOptions) : boolean;
end;
implementation
end.
|
unit Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.AppEvnts;
type
TfMain = class(TForm)
btDatasetLoop: TButton;
btThreads: TButton;
btStreams: TButton;
ApplicationEvents1: TApplicationEvents;
procedure btDatasetLoopClick(Sender: TObject);
procedure btStreamsClick(Sender: TObject);
procedure ApplicationEvents1Exception(Sender: TObject; E: Exception);
procedure btThreadsClick(Sender: TObject);
private
public
end;
var
fMain: TfMain;
implementation
uses
DatasetLoop, ClienteServidor, Threads;
{$R *.dfm}
procedure TfMain.btDatasetLoopClick(Sender: TObject);
begin
fDatasetLoop.Show;
end;
procedure TfMain.btStreamsClick(Sender: TObject);
begin
fClienteServidor.Show;
end;
procedure TfMain.btThreadsClick(Sender: TObject);
begin
fThreads.Show;
end;
procedure TfMain.ApplicationEvents1Exception(Sender: TObject;
E: Exception);
var
vrLogFile: String;
begin
vrLogFile := ExtractFilePath(Application.ExeName) + 'log-exceptions.log';
with TStringList.Create do
begin
if FileExists(vrLogFile) then
LoadFromFile(vrLogFile);
Add('----');
Add('Exception Às ' + FormatDateTime('dd/mm/yyyy hh:nn:ss', now));
Add('Classe: ' + E.ClassName);
Add('Descrição: '+ E.Message);
SaveToFile(vrLogFile);
Free;
end;
raise E;
end;
end.
|
unit EasyListviewReg;
// Version 2.0.0
//
// The contents of this file are subject to the Mozilla Public License
// Version 1.1 (the "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
//
// Alternatively, you may redistribute this library, use and/or modify it under the terms of the
// GNU Lesser General Public License as published by the Free Software Foundation;
// either version 2.1 of the License, or (at your option) any later version.
// You may obtain a copy of the LGPL at http://www.gnu.org/copyleft/.
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the
// specific language governing rights and limitations under the License.
//
// The initial developer of this code is Jim Kueneman <jimdk@mindspring.com>
// Special thanks to the following in no particular order for their help/support/code
// Danijel Malik, Robert Lee, Werner Lehmann, Alexey Torgashin, Milan Vandrovec
//
//----------------------------------------------------------------------------
interface
{$I ..\Source\Compilers.inc}
uses
ToolsApi,
Classes,
{$IFDEF COMPILER_6_UP}
DesignIntf,
DesignEditors,
PropertyCategories,
{$ELSE}
DsgnIntf,
DsgnWnds,
{$ENDIF}
Forms,
{$IFDEF COMPILER_5_UP}
ColnEdit,
{$ENDIF COMPILER_5_UP}
SysUtils,
Controls,
EasyListview,
EasyScrollFrame,
MPCommonWizardHelpers,
MPCommonObjects,
EasyTaskPanelForm;
const
NEW_PAGE = 'New';
type
TEasyListviewEditor = class(TDefaultEditor)
public
procedure Edit; override;
end;
TEasyDelphiTaskFormWizard = class(TCommonWizardDelphiForm)
public
procedure InitializeWizard; override;
end;
// Only used in BDS 4.0 and up
TEasyBuilderTaskFormWizard = class(TCommonWizardBuilderForm)
public
procedure InitializeWizard; override;
end;
TEasyTaskPanelCreator = class(TCommonWizardEmptyFormCreator)
public
procedure InitializeCreator; override;
end;
{$IFDEF COMPILER_6_UP}
const
sELVColumnCategory = 'Column Objects';
sELVItemCategory = 'Item Objects';
sELVGroupCategory = 'Group Objects';
sELVIncrementalCategory = 'Incremental Search';
sELVMouseCategory = 'Mouse';
sELVHintCategory = 'Hint';
sELVOLECategory = 'OLE Drag Drop';
sImageListCategory = 'ImageLists';
sPaintInfoCategory = 'Paint Information';
sELVClipboardCategory = 'Clipboard';
sELVHeaderCategory = 'Header';
sELVPaintCategory = 'Paint and Drawing';
sAutoCategory = 'Auto';
sELVViewCategory = 'View';
sELVContextMenuCategory = 'ContextMenu';
{$ENDIF COMPILER_6_UP}
procedure Register;
implementation
uses
{$IFDEF COMPILER_5_UP}
EasyCollectionEditor;
{$ELSE}
EasyCollectionEditorD4;
{$ENDIF COMPILER_5_UP}
{$IFDEF COMPILER_8_UP}
var
DelphiCategory, BuilderCategory: IOTAGalleryCategory;
{$ENDIF}
procedure Register;
begin
RegisterComponents('MustangPeak', [TEasyListview, TEasyTaskBand, TEasyScrollButton, TEasyTaskPanelBand]);
RegisterPropertyEditor(TypeInfo(TEasyCollection), nil, '', TEasyCollectionEditor);
RegisterComponentEditor(TEasyListview, TEasyListviewEditor);
RegisterComponentEditor(TEasyTaskPanelBand, TEasyListviewEditor);
RegisterComponentEditor(TEasyTaskBand, TEasyListviewEditor);
RegisterCustomModule(TEasyTaskPanelForm, TCustomModule);
RegisterPackageWizard(TEasyDelphiTaskFormWizard.Create);
{$IFDEF COMPILER_10_UP}
RegisterPackageWizard(TEasyBuilderTaskFormWizard.Create);
{$ENDIF COMPILER_10_UP}
{$IFDEF COMPILER_6_UP}
RegisterPropertyEditor(TypeInfo(TCommonImageIndexInteger), nil, '', TCommonImageIndexProperty);
RegisterPropertiesInCategory(sELVColumnCategory, TCustomEasyListview,
['OnColumn*']);
RegisterPropertiesInCategory(sELVItemCategory, TCustomEasyListview,
['OnItem*']);
RegisterPropertiesInCategory(sELVGroupCategory, TCustomEasyListview,
['OnGroup*'] );
RegisterPropertiesInCategory(sELVHintCategory, TCustomEasyListview,
['*Hint*'] );
RegisterPropertiesInCategory(sELVOLECategory, TCustomEasyListview,
['*OLE*',
'OnGetDragImage'] );
RegisterPropertiesInCategory(sELVOLECategory, TCustomEasyListview,
['*PaintInfo*'] );
RegisterPropertiesInCategory(sELVClipboardCategory, TCustomEasyListview,
['*Clipboard*'] );
RegisterPropertiesInCategory(sELVHeaderCategory, TCustomEasyListview,
['*Header*'] );
RegisterPropertiesInCategory(sELVPaintCategory, TCustomEasyListview,
['OnAfterPaint',
'OnPaintHeaderBkGnd',
'OnPaintBkGnd'] );
RegisterPropertiesInCategory(sELVHeaderCategory, TCustomEasyListview,
['Header*'] );
RegisterPropertiesInCategory(sELVViewCategory, TCustomEasyListview,
['OnViewChange'] );
RegisterPropertiesInCategory(sInputCategoryName, TCustomEasyListview,
['OnDblClick'] );
RegisterPropertiesInCategory(sAutoCategory, TCustomEasyListview,
['OnAuto*'] );
RegisterPropertiesInCategory(sELVIncrementalCategory, TCustomEasyListview,
['*Incremental*'] );
RegisterPropertiesInCategory(sELVContextMenuCategory, TCustomEasyListview,
['OnContextMenu*'] );
{$ENDIF COMPILER_6_UP}
end;
{ TEasyListviewEditor }
procedure TEasyListviewEditor.Edit;
begin
// Show column collection editor on listview doubleclick.
if (Component is TEasyTaskPanelBand) or (Component is TEasyTaskBand) then
ShowEasyCollectionEditor(Designer, TEasyListview(Component).Groups)
else
ShowEasyCollectionEditor(Designer, TEasyListview(Component).Header.Columns);
end;
{ TEasyDelphiTaskForm }
procedure TEasyDelphiTaskFormWizard.InitializeWizard;
begin
inherited;
Caption := 'EasyListview TaskPanel';
Author := 'Mustangpeak';
Comment := 'Creates a task band panel for the EasyTaskPanelBand component';
GlyphResourceID := ''; // use the default icon
Page := NEW_PAGE; // use the New page for Forms
UniqueID := 'mustangpeak.easy.delphi.task.form';
State := [];
CreatorClass := TEasyTaskPanelCreator;
{$IFDEF COMPILER_8_UP}
GalleryCategory := DelphiCategory;
{$ENDIF COMPILER_8_UP}
end;
{ TEasyBuilderTaskForm }
procedure TEasyBuilderTaskFormWizard.InitializeWizard;
begin
inherited;
Caption := 'EasyTaskPanel C++Builder Form';
Author := 'Mustangpeak';
Comment := 'Creates a task band panel for the EasyTaskPanelBand component';
GlyphResourceID := ''; // use the default icon
Page := ''; // use the default page for Forms
UniqueID := 'mustangpeak.easy.builder.task.form';
State := [];
CreatorClass := TEasyTaskPanelCreator;
{$IFDEF COMPILER_8_UP}
GalleryCategory := BuilderCategory;
{$ENDIF COMPILER_8_UP}
end;
{ TEasyTaskPanelCreator }
procedure TEasyTaskPanelCreator.InitializeCreator;
begin
inherited;
AncestorName := 'EasyTaskPanelForm';
if IsDelphi then
IncludeIdent.Add('EasyTaskPanelForm')
else
IncludeIdent.Add('EasyTaskPanelForm.hpp')
end;
initialization
{$IFDEF COMPILER_8_UP}
DelphiCategory := AddDelphiCategory('mustangpeak.delphi.easylistview', 'EasyListview for Delphi');
BuilderCategory := AddBuilderCategory('mustangpeak.builder.easylistview', 'EasyListview for C++ Builder');
{$ENDIF COMPILER_8_UP}
finalization
{$IFDEF COMPILER_8_UP}
RemoveCategory(BuilderCategory);
RemoveCategory(DelphiCategory);
{$ENDIF COMPILER_8_UP}
end.
|
unit BCEditor.Editor.PopupWindow;
interface
uses
Winapi.Messages, System.Classes, System.Types, Vcl.Controls;
type
TBCEditorPopupWindow = class(TCustomControl)
private
FEditor: TWinControl;
procedure WMEraseBkgnd(var AMessage: TMessage); message WM_ERASEBKGND;
procedure WMMouseActivate(var AMessage: TMessage); message WM_MOUSEACTIVATE;
{$IFDEF USE_VCL_STYLES}
procedure WMNCPaint(var Message: TWMNCPaint); message WM_NCPAINT;
{$ENDIF}
protected
FActiveControl: TWinControl;
FIsFocusable: Boolean;
procedure CreateParams(var Params: TCreateParams); override;
procedure InvalidateEditor;
public
constructor Create(AOwner: TComponent); override;
procedure Hide;
procedure Show(Origin: TPoint); virtual;
property ActiveControl: TWinControl read FActiveControl;
property IsFocusable: Boolean read FIsFocusable;
end;
implementation
uses
Winapi.Windows, System.SysUtils{$IFDEF USE_VCL_STYLES}, Vcl.Themes{$ENDIF};
constructor TBCEditorPopupWindow.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FEditor := AOwner as TWinControl;
ControlStyle := ControlStyle + [csNoDesignVisible, csReplicatable];
if not(csDesigning in ComponentState) then
ControlStyle := ControlStyle + [csAcceptsControls];
Ctl3D := False;
ParentCtl3D := False;
Parent := FEditor;
Visible := False;
end;
procedure TBCEditorPopupWindow.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
Params.Style := WS_POPUP or WS_BORDER;
end;
procedure TBCEditorPopupWindow.Hide;
begin
SetWindowPos(Handle, 0, 0, 0, 0, 0, SWP_NOZORDER or SWP_NOMOVE or SWP_NOSIZE or SWP_NOACTIVATE or SWP_HIDEWINDOW);
Visible := False;
end;
procedure TBCEditorPopupWindow.InvalidateEditor;
var
R: TRect;
begin
R := FEditor.ClientRect;
Winapi.Windows.InvalidateRect(FEditor.Handle, @R, False);
UpdateWindow(FEditor.Handle);
end;
procedure TBCEditorPopupWindow.Show(Origin: TPoint);
begin
SetBounds(Origin.X, Origin.Y, Width, Height);
SetWindowPos(Handle, HWND_TOP, Origin.X, Origin.Y, 0, 0, SWP_NOACTIVATE or SWP_SHOWWINDOW or SWP_NOSIZE);
Visible := True;
end;
procedure TBCEditorPopupWindow.WMMouseActivate(var AMessage: TMessage);
begin
if FIsFocusable then
inherited
else
AMessage.Result := MA_NOACTIVATE;
end;
procedure TBCEditorPopupWindow.WMEraseBkgnd(var AMessage: TMessage);
begin
AMessage.Result := -1;
end;
{$IFDEF USE_VCL_STYLES}
procedure TBCEditorPopupWindow.WMNCPaint(var Message: TWMNCPaint);
var
LRect: TRect;
LExStyle: Integer;
LTempRgn: HRGN;
LBorderWidth, LBorderHeight: Integer;
begin
if StyleServices.Enabled then
begin
LExStyle := GetWindowLong(Handle, GWL_EXSTYLE);
if (LExStyle and WS_EX_CLIENTEDGE) <> 0 then
begin
GetWindowRect(Handle, LRect);
LBorderWidth := GetSystemMetrics(SM_CXEDGE);
LBorderHeight := GetSystemMetrics(SM_CYEDGE);
InflateRect(LRect, -LBorderWidth, -LBorderHeight);
LTempRgn := CreateRectRgnIndirect(LRect);
DefWindowProc(Handle, Message.Msg, wParam(LTempRgn), 0);
DeleteObject(LTempRgn);
end
else
DefaultHandler(Message);
end
else
DefaultHandler(Message);
if StyleServices.Enabled then
StyleServices.PaintBorder(Self, False);
end;
{$ENDIF}
end.
|
unit uDataBaseOperation;
{*
BACKUP RETORE MSSQL
APPLICATION NETWORK INC.
LOG ----------------------------
Created by Rodrigo Costa
05/17/02.
*}
interface
uses Db, ADODB;
const
BKP_APPEND_INIT = ' INIT ';
BKP_APPEND_NOINIT = ' NOINIT ';
RST_REPLACE_DB = ' REPLACE, ';
DEVICE_DISK = ' DISK=';
type
TDataBaseOperation = class
private
FADOConnection : TADOConnection; //Connection to the DB
FSQLText : String; //SQL to be executed
FDataBaseName : String; //DB name
FDevice : String; //Device available Disk, Tape, or Pipe.
function ExecOperarion : Integer; //Run SQL
public
property DataBaseName : String read FDataBaseName write FDataBaseName;
property Device : String read FDevice write FDevice;
property Connection : TADOConnection read FADOConnection write FADOConnection;
function SetSQLExecute : Integer; virtual; abstract; //Set SQL and execute
end;
TBackUpDataBase = class(TDataBaseOperation)
private
FFilePath : String; //Physical location on the HD
FAppendDataBase : String; //Append or Override backupfile
public
property AppendDB : String read FAppendDataBase write FAppendDataBase;
property FilePath : String read FFilePath write FFilePath;
function SetSQLExecute : Integer; override;
end;
TRestoreDataBase = class(TDataBaseOperation)
private
FLogicalDataName : String; //Logical database data name
FLogicalLogName : String; //Logical database log name
FNewDatePath : String; //Physical location of the Database data file
FNewLogPath : String; //Physical location of the Database log file
FForceRestore : String; //Force restore over an existent DB
public
property LogicalDataName : String read FLogicalDataName write FLogicalDataName;
property LogicalLogName : String read FLogicalLogName write FLogicalLogName;
property NewDataPath : String read FNewDatePath write FNewDatePath;
property NewLogPath : String read FNewLogPath write FNewLogPath;
property ForceRestore : String read FForceRestore write FForceRestore;
function SetSQLExecute : Integer; override;
end;
implementation
uses Sysutils;
{ TDataBaseOperation }
function TDataBaseOperation.ExecOperarion:integer;
var
cmd : TADOCommand;
begin
Result := -1;
cmd := nil;
try
cmd := TADOCommand.Create(nil);
cmd.Connection := FADOConnection;
cmd.CommandTimeout := 180;
cmd.CommandText := FSQLText;
try
cmd.Execute;
except
raise;
Result := 100; //Error
end;
finally
FreeAndNil(cmd);
end;
end;
{ TBackUpDataBase }
function TBackUpDataBase.SetSQLExecute:Integer;
begin
FSQLText := ' BACKUP TRANSACTION '+FDataBaseName+' WITH TRUNCATE_ONLY ' +
' BACKUP DATABASE '+FDataBaseName+' TO '+FDevice+' '+
' WITH ' + FAppendDataBase;
Result := ExecOperarion;
end;
{ TRestoreDataBase }
function TRestoreDataBase.SetSQLExecute:Integer;
begin
FSQLText := ' RESTORE DATABASE '+ FDataBaseName +' FROM ' + FDevice +
' WITH '+ FForceRestore +
' MOVE '+ FLogicalDataName + ' TO ' + FNewDatePath + ', ' +
' MOVE '+ FLogicalLogName + ' TO ' + FNewLogPath;
Result := ExecOperarion;
end;
end.
|
unit BsGetInput;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, cxLabel, cxControls,
cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit,
cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, DB, FIBDataSet,
pFIBDataSet, ExtCtrls, uConsts, uCommon_Messages, uCommon_Funcs, uCommon_Types,
iBase, uCommon_Loader;
type
TfrmGetInput = class(TForm)
InputBox: TcxLookupComboBox;
lblInput: TcxLabel;
btnOk: TcxButton;
btnCancel: TcxButton;
InputDSet: TpFIBDataSet;
InputDS: TDataSource;
TimerEnter: TTimer;
procedure TimerEnterTimer(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure InputBoxPropertiesInitPopup(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure lblInputMouseEnter(Sender: TObject);
procedure lblInputMouseLeave(Sender: TObject);
procedure lblInputClick(Sender: TObject);
private
{ Private declarations }
IsAdmin:Boolean;
public
{ Public declarations }
DbHandle:TISC_DB_HANDLE;
IdDisObject:Integer;
constructor Create(AOwner:TComponent; isAdm:Boolean);reintroduce;
end;
var
frmGetInput: TfrmGetInput;
implementation
{$R *.dfm}
uses BsClient, BsClientEdit;
constructor TfrmGetInput.Create(AOwner:TComponent; isAdm:boolean);
begin
inherited Create(AOwner);
IsAdmin:=isAdm;
end;
procedure TfrmGetInput.TimerEnterTimer(Sender: TObject);
begin
TimerEnter.Enabled:=True;
InputDSet.Close;
InputDSet.SQLs.SelectSQL.Text:='SELECT * FROM BS_GET_INPUT_BY_DIS_OBJECT(:KOD_INPUT_IN, :ID_DISCOUNT_OBJECT)';
InputDSet.ParamByName('KOD_INPUT_IN').AsString:=InputBox.EditText;
InputDSet.ParamByName('ID_DISCOUNT_OBJECT').AsInteger:=IdDisObject;
InputDSet.Open;
if not InputDSet.IsEmpty then
begin
InputBox.DroppedDown:=True;
end;
end;
procedure TfrmGetInput.FormCreate(Sender: TObject);
var b:Byte;
begin
b:=uCommon_Funcs.bsLanguageIndex();
btnOk.Caption:=uConsts.bs_Accept[b];
btnCancel.Caption:=uConsts.bs_Cancel[b];
end;
procedure TfrmGetInput.InputBoxPropertiesInitPopup(Sender: TObject);
begin
if InputBox.EditText='' then
begin
InputDSet.Close;
InputDSet.SQLs.SelectSQL.Text:='SELECT * FROM BS_GET_INPUT_BY_DIS_OBJECT(:KOD_INPUT_IN, :ID_DISCOUNT_OBJECT)';
InputDSet.ParamByName('KOD_INPUT_IN').AsString:=InputBox.EditText;
InputDSet.ParamByName('ID_DISCOUNT_OBJECT').AsInteger:=IdDisObject;
InputDSet.Open;
end;
end;
procedure TfrmGetInput.btnOkClick(Sender: TObject);
begin
if InputBox.EditText<>'' then
begin
ModalResult:=mrOk;
end;
end;
procedure TfrmGetInput.btnCancelClick(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TfrmGetInput.lblInputMouseEnter(Sender: TObject);
begin
Screen.Cursor:=crHandPoint;
end;
procedure TfrmGetInput.lblInputMouseLeave(Sender: TObject);
begin
Screen.Cursor:=crDefault;
end;
procedure TfrmGetInput.lblInputClick(Sender: TObject);
var
AParameter:TBsSimpleParams;
InPutRes:Variant;
begin
try
AParameter:= TBsSimpleParams.Create;
AParameter.Owner:=self;
AParameter.Db_Handle:= DbHandle;
AParameter.Formstyle:=fsNormal;
AParameter.WaitPakageOwner:=self;
AParameter.is_admin:=IsAdmin;
InPutRes:=RunFunctionFromPackage(AParameter, 'BillingSystem\bs_sp_inputs.bpl','ShowSPInputs');
AParameter.Free;
if VarArrayDimCount(InPutRes)>0 then
begin
if InputDSet.Active then InputDSet.Close;
InputDSet.SQLs.SelectSQL.Text:='SELECT DISTINCT * FROM BS_INPUT WHERE ID_INPUT=:ID_INPUT';
InputDSet.ParamByName('ID_INPUT').AsInteger:=InPutRes[0];
InputDSet.Open;
InputBox.EditValue:=IntToStr(InPutRes[0]);
end;
except on E:exception
do bsShowMessage('гтрур!', e.message, mtInformation, [mbOK]);
end;
end;
end.
|
function UNIXTimeInMilliseconds: Int64;
var
ST: SystemTime;
DT: TDateTime;
begin
Windows.GetSystemTime(ST);
DT := SysUtils.EncodeDate(ST.wYear, ST.wMonth, ST.wDay) +
SysUtils.EncodeTime(ST.wHour, ST.wMinute, ST.wSecond, ST.wMilliseconds);
Result := DateUtils.MilliSecondsBetween(DT, UnixDateDelta);
end; |
uses crt, graph,joystick;
type JoyType=record X,Y : integer;b1,b2,b3,b4:boolean;END;
var
x, y, z : array[ 1..2,1..24] of shortint;
no, e,b,kX,kY : byte; {Index}
xp1,xp2,yp1,yp2 :array[1..24] of integer;
const
g = 10 ; {g=VergrĒŠerung}
di = 100; {di=Distanz des Objektes}
f = 44.5; {Zoom}
xv = 320;
yv = 240; {xv, yv : Verschiebung}
(********************************************************************)
procedure center;
var Joy : JoyType;
BEGIN
clrscr;
writeln('Bitte zentrieren sie ihren Joystick und drĀcken sie einen Knopf.');
with joy do BEGIN
repeat
JoyButton(b1, b2, b3, b4);
until not b1 or not b2 or not b3 or not b4;
JoyKoor(X, Y);
END;
kX := Joy.X; kY := Joy.Y;
END;
procedure datlese;
var
er,aha : integer;
t : text;
a : string;
s,n,l: byte;
BEGIN
b:=0;
assign(t, 'c:\dosprg\tp\cobra2.dat');
reset(t);readln(t,a);readln(t,a);
repeat
b := b + 1;
readln(t, a);
val(a, aha, er);x[1,b]:=aha div 5;
readln(t, a);
val(a, aha, er);y[1,b]:=aha div 5;
readln(t, a);
val(a, aha, er);z[1,b]:=aha div 5;
readln(t, a);
val(a, aha, er);x[2,b]:=aha div 5;
readln(t, a);
val(a, aha, er);y[2,b]:=aha div 5;
readln(t, a);
val(a, aha, er);z[2,b]:=aha div 5;
readln(t, a);
until eof(t);
END;
procedure grafik;
var grDriver , grMode : Integer; {InitGraph (640*480*16)}
BEGIN
grDriver := Detect;
InitGraph(grDriver,grMode,'c:\tp');
END;
procedure rotate(rot,rot2,rot3: real);
var
zp1, zp2,srot,crot,srot2,crot2,srot3,crot3: real;
BEGIN
Srot:=Sin(rot); Crot:=Cos(rot);
Srot2:=Sin(rot2); Crot2:=Cos(rot2);
Srot3:=Sin(rot3); Crot3:=Cos(rot3); {Sin & Cos-Berechnungen}
for e := 1 to 24 do
BEGIN
setcolor(0); LINE (xp1[e],yp1[e],xp2[e],yp2[e]); {LĒschen}
zp1:=srot*x[1,e]-crot*(srot2*z[1,e]+crot2*y[1,e])+di;
xp1[e]:=trunc((f/zp1)*(Crot3*(crot*x[1,e]+srot*(srot2*y[1, e]-crot2*z[1, e]))-srot3*(crot2*y[1,e]+srot2*z[1,e]))*g)+xv;
yp1[e]:=yv-trunc((f/zp1)*(Crot3*((crot2*y[1,e]+srot2*z[1, e]))+srot3*(crot*x[1,e]+srot*(srot2*y[1,e]-crot2*z[1,e])))*g);
zp2:=srot*x[2,e]-crot*(srot2*z[2,e]+crot2*y[2,e])+di;
xp2[e]:=trunc((f/zp2)*(Crot3*(crot*x[2, e]+srot*(srot2*y[2,e]-crot2*z[2,e]))-srot3*(crot2*(y[2,e])+srot2*z[2,e]))*g)+xv;
yp2[e]:=yv-trunc((f/zp2)*(Crot3*(crot2*y[2, e]+srot2*z[2, e])+srot3*(crot*x[2,e]+srot*(srot2*y[2, e]-crot2*z[2,e])))*g);
setcolor(7);LINE (xp1[e],yp1[e],xp2[e],yp2[e]); {Zeichnen}
END;
END;
Procedure JoyAbfrage;
var Joy : joytype;
rot, rot2, rot3 : real;
BEGIN
rot :=0;rot2:=0;
repeat
with joy do
BEGIN
joykoor(x,y);
if (x - kX < -10) or (x - kX > 10) or (y - kY < -10) or (y - kY > 10) then
BEGIN
rot2:= rot2+ (y-kY)/1000;
joybutton(b1,b2,b3,b4);
if b2 = true then rot := rot + (x-kX)/1000 else rot3 := rot3 + (x-kX)/1000;
rotate(rot,rot2,rot3);
END;
END;
until keypressed;
END;
BEGIN {Main}
Datlese;
Center;
Grafik;
JoyAbfrage;
Closegraph;
END. |
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Console.Command.Why;
interface
//TODO : Why command to explain a dependency. Just use the graph to present a clear explaination
//https://theimowski.com/blog/2016/10-30-paket-why-command/index.html
uses
VSoft.CancellationToken,
DPM.Console.ExitCodes,
DPM.Console.Command,
DPM.Console.Command.Base;
type
TWhyCommand = class(TBaseCommand)
protected
function Execute(const cancellationToken : ICancellationToken) : TExitCode; override;
end;
implementation
{ TWhyCommand }
function TWhyCommand.Execute(const cancellationToken : ICancellationToken) : TExitCode;
begin
Logger.Error('Why command not implemented');
result := TExitCode.NotImplemented;
end;
end.
|
(*----------------------------------------------------------------------------*
* Direct3D sample from DirectX 9.0 SDK December 2006 *
* Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) *
* *
* Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 *
* *
* Latest version can be downloaded from: *
* http://www.clootie.ru *
* http://sourceforge.net/projects/delphi-dx9sdk *
*----------------------------------------------------------------------------*
* $Id: HDRCubeMapUnit.pas,v 1.11 2007/02/05 22:21:06 clootie Exp $
*----------------------------------------------------------------------------*)
//--------------------------------------------------------------------------------------
// File: HDRCubeMap.cpp
//
// This sample demonstrates a common shadow technique called shadow mapping.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
{$I DirectX.inc}
unit HDRCubeMapUnit;
interface
uses
Windows, Messages, SysUtils, Math,
DXTypes, Direct3D9, D3DX9,
DXUT, DXUTcore, DXUTenum, DXUTmisc, DXUTgui, DXUTMesh, DXUTSettingsDlg;
{.$DEFINE DEBUG_VS} // Uncomment this line to debug vertex shaders
{.$DEFINE DEBUG_PS} // Uncomment this line to debug pixel shaders
//--------------------------------------------------------------------------------------
// Defines, and constants
//--------------------------------------------------------------------------------------
const
ENVMAPSIZE = 256;
// Currently, 4 is the only number of lights supported.
NUM_LIGHTS = 4;
LIGHTMESH_RADIUS = 0.2;
HELPTEXTCOLOR: TD3DXColor = (r: 0.0; g: 1.0; b: 0.3; a: 1.0);
g_aVertDecl: array[0..3] of TD3DVertexElement9 =
(
(Stream: 0; Offset: 0; _Type: D3DDECLTYPE_FLOAT3; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_POSITION; UsageIndex: 0),
(Stream: 0; Offset: 12; _Type: D3DDECLTYPE_FLOAT3; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_NORMAL; UsageIndex: 0),
(Stream: 0; Offset: 24; _Type: D3DDECLTYPE_FLOAT2; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_TEXCOORD; UsageIndex: 0),
{D3DDECL_END()}(Stream:$FF; Offset:0; _Type:D3DDECLTYPE_UNUSED; Method:TD3DDeclMethod(0); Usage:TD3DDeclUsage(0); UsageIndex:0)
);
g_atszMeshFileName: array[0..2] of PWideChar =
(
'misc\teapot.x',
'misc\skullocc.x',
'misc\car.x'
);
NUM_MESHES = High(g_atszMeshFileName) + 1;
type
POrbutData = ^TOrbutData;
TOrbutData = record
tszXFile: PWideChar; // X file
vAxis: TD3DVector; // Axis of rotation
fRadius: Single; // Orbit radius
fSpeed: Single; // Orbit speed in radians per second
end;
const
// Mesh file to use for orbiter objects
// These don't have to use the same mesh file.
g_OrbitData: array [0..1] of TOrbutData =
(
(tszXFile: 'airplane\airplane 2.x'; vAxis: (x:-1.0; y: 0.0; z: 0.0); fRadius: 2.0; fSpeed: {D3DX_PI}3.141592654 * 1.0),
(tszXFile: 'airplane\airplane 2.x'; vAxis: (x: 0.3; y: 1.0; z: 0.3); fRadius: 2.5; fSpeed: {D3DX_PI}3.141592654 / 2.0)
);
function ComputeBoundingSphere(Mesh: CDXUTMesh; out pvCtr: TD3DXVector3; out pfRadius: Single): HRESULT;
type
//--------------------------------------------------------------------------------------
// Encapsulate an object in the scene with its world transformation
// matrix.
//--------------------------------------------------------------------------------------
CObj = class
m_mWorld: TD3DXMatrixA16; // World transformation
m_Mesh: CDXUTMesh; // Mesh object
public
constructor Create; { D3DXMatrixIdentity( &m_mWorld ); }
// destructor Destroy; override; {}
function WorldCenterAndScaleToRadius(fRadius: Single): HRESULT;
end;
//--------------------------------------------------------------------------------------
// Encapsulate an orbiter object in the scene with related data
//--------------------------------------------------------------------------------------
COrbiter = class(CObj)
public
m_vAxis: TD3DXVector3; // orbit axis
m_fRadius: Single; // orbit radius
m_fSpeed: Single; // Speed, angle in radian per second
public
constructor Create; // m_vAxis( 0.0f, 1.0f, 0.0f ), m_fRadius(1.0f), m_fSpeed( D3DX_PI )
procedure SetOrbit(const vAxis: TD3DXVector3; fRadius: Single; fSpeed: Single);
procedure Orbit(fElapsedTime: Single);
end;
PLight = ^TLight;
TLight = record
vPos: TD3DXVector4; // Position in world space
vMoveDir: TD3DXVector4; // Direction in which it moves
fMoveDist: Single; // Maximum distance it can move
mWorld: TD3DXMatrixA16; // World transform matrix for the light before animation
mWorking: TD3DXMatrixA16; // Working matrix (world transform after animation)
end;
PTechniqueGroup = ^TTechniqueGroup;
TTechniqueGroup = record
hRenderScene: TD3DXHandle;
hRenderLight: TD3DXHandle;
hRenderEnvMap: TD3DXHandle;
end;
PATechniqueGroup = ^ATechniqueGroup;
ATechniqueGroup = array[0..MaxInt div SizeOf(TTechniqueGroup) - 1] of TTechniqueGroup;
PAIDirect3DCubeTexture9 = ^AIDirect3DCubeTexture9;
AIDirect3DCubeTexture9 = array [0..999] of IDirect3DCubeTexture9;
//--------------------------------------------------------------------------------------
// Global variables
//--------------------------------------------------------------------------------------
var
g_pFont: ID3DXFont; // Font for drawing text
g_pTextSprite: ID3DXSprite; // Sprite for batching draw text calls
g_pEffect: ID3DXEffect; // D3DX effect interface
g_Camera: CModelViewerCamera; // A model viewing camera
g_bShowHelp: Boolean = True; // If true, it renders the UI control text
g_DialogResourceManager: CDXUTDialogResourceManager; // manager for shared resources of dialogs
g_SettingsDlg: CD3DSettingsDlg; // Device settings dialog
g_HUD: CDXUTDialog; // dialog for standard controls
g_aLights: array [0..NUM_LIGHTS-1] of TLight; // Parameters of light objects
g_vLightIntensity: TD3DXVector4; // Light intensity
g_EnvMesh: array [0..NUM_MESHES-1] of CObj; // Mesh to receive environment mapping
g_nCurrMesh: Integer = 0; // Index of the element in m_EnvMesh we are currently displaying
g_Room: CDXUTMesh; // Mesh representing room (wall, floor, ceiling)
g_Orbiter: array [0..High(g_OrbitData)] of COrbiter; // Orbiter meshes
g_LightMesh: CDXUTMesh; // Mesh for the light object
g_pVertDecl: IDirect3DVertexDeclaration9; // Vertex decl for the sample
g_apCubeMapFp: array [0..1] of IDirect3DCubeTexture9; // Floating point format cube map
g_pCubeMap32: IDirect3DCubeTexture9;// 32-bit cube map (for fallback)
g_pDepthCube: IDirect3DSurface9; // Depth-stencil buffer for rendering to cube texture
g_nNumFpCubeMap: Integer = 0; // Number of cube maps required for using floating point
g_aTechGroupFp: array [0..1] of TTechniqueGroup; // Group of techniques to use with floating pointcubemaps (2 cubes max)
g_TechGroup32: TTechniqueGroup; // Group of techniques to use with integer cubemaps
g_hWorldView: TD3DXHandle; // Handle for world+view matrix in effect
g_hProj: TD3DXHandle; // Handle for projection matrix in effect
g_ahtxCubeMap: array [0..1] of TD3DXHandle; // Handle for the cube texture in effect
g_htxScene: TD3DXHandle; // Handle for the scene texture in effect
g_hLightIntensity: TD3DXHandle; // Handle for the light intensity in effect
g_hLightPosView: TD3DXHandle; // Handle for view space light positions in effect
g_hReflectivity: TD3DXHandle; // Handle for reflectivity in effect
g_nNumCubes: Integer; // Number of cube maps used based on current cubemap format
g_apCubeMap: PAIDirect3DCubeTexture9 = @g_apCubeMapFp; // Cube map(s) to use based on current cubemap format
g_pTech: PATechniqueGroup = @g_aTechGroupFp; // Techniques to be used based on cubemap format
g_fWorldRotX: Single = 0.0; // World rotation state X-axis
g_fWorldRotY: Single = 0.0; // World rotation state Y-axis
g_bUseFloatCubeMap:Boolean; // Whether we use floating point format cube map
g_fReflectivity: Single; // Reflectivity value. Ranges from 0 to 1.
const
//--------------------------------------------------------------------------------------
// UI control IDs
//--------------------------------------------------------------------------------------
IDC_TOGGLEFULLSCREEN = 1;
IDC_TOGGLEREF = 3;
IDC_CHANGEDEVICE = 4;
IDC_CHANGEMESH = 5;
IDC_RESETPARAM = 6;
IDC_SLIDERLIGHTTEXT = 7;
IDC_SLIDERLIGHT = 8;
IDC_SLIDERREFLECTTEXT = 9;
IDC_SLIDERREFLECT = 10;
IDC_CHECKHDR = 11;
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
procedure OnLostDevice(pUserContext: Pointer); stdcall;
procedure OnDestroyDevice(pUserContext: Pointer); stdcall;
procedure InitApp;
function LoadMesh(pd3dDevice: IDirect3DDevice9; wszName: PWideChar; Mesh: CDXUTMesh): HRESULT;
procedure RenderText;
procedure ResetParameters;
procedure RenderSceneIntoCubeMap(const pd3dDevice: IDirect3DDevice9; fTime: Double);
procedure RenderScene(const pd3dDevice: IDirect3DDevice9; const pmView, pmProj: TD3DXMatrix; const pTechGroup: TTechniqueGroup; bRenderEnvMappedMesh: Boolean; fTime: Double);
procedure UpdateUiWithChanges;
procedure CreateCustomDXUTobjects;
procedure DestroyCustomDXUTobjects;
implementation
function ComputeBoundingSphere(Mesh: CDXUTMesh; out pvCtr: TD3DXVector3; out pfRadius: Single): HRESULT;
var
pMeshObj: ID3DXMesh;
decl: TFVFDeclaration; // D3DVERTEXELEMENT9 decl[MAX_FVF_DECL_SIZE];
pVB: Pointer; // LPprocedure
uStride: LongWord;
begin
// Obtain the bounding sphere
pMeshObj := Mesh.Mesh;
if (pMeshObj = nil) then
begin
Result:= E_FAIL;
Exit;
end;
// Obtain the declaration
Result := pMeshObj.GetDeclaration(decl);
if FAILED(Result) then Exit;
// Lock the vertex buffer
Result := pMeshObj.LockVertexBuffer(D3DLOCK_READONLY, pVB);
if FAILED(Result) then Exit;
// Compute the bounding sphere
uStride := D3DXGetDeclVertexSize(@decl, 0);
Result := D3DXComputeBoundingSphere(PD3DXVector3(pVB), pMeshObj.GetNumVertices,
uStride, pvCtr, pfRadius);
pMeshObj.UnlockVertexBuffer;
end;
//--------------------------------------------------------------------------------------
// Initialize the app
//--------------------------------------------------------------------------------------
procedure InitApp;
var
pElement: CDXUTElement;
iY: Integer;
begin
// Change CheckBox default visual style
pElement := g_HUD.GetDefaultElement(DXUT_CONTROL_CHECKBOX, 0);
if Assigned(pElement) then
begin
pElement.FontColor.States[DXUT_STATE_NORMAL] := D3DCOLOR_ARGB(255, 0, 255, 0);
end;
// Change Static default visual style
pElement := g_HUD.GetDefaultElement(DXUT_CONTROL_STATIC, 0);
if Assigned(pElement) then
begin
pElement.dwTextFormat := DT_LEFT or DT_VCENTER;
pElement.FontColor.States[DXUT_STATE_NORMAL] := D3DCOLOR_ARGB(255, 0, 255, 0);
end;
// Initialize dialogs
g_SettingsDlg.Init(g_DialogResourceManager);
g_HUD.Init(g_DialogResourceManager);
g_HUD.SetCallback(OnGUIEvent);
iY := 10; g_HUD.AddButton(IDC_TOGGLEFULLSCREEN, 'Toggle full screen', 35, iY, 125, 22);
Inc(iY, 24); g_HUD.AddButton(IDC_TOGGLEREF, 'Toggle REF (F3)', 35, iY, 125, 22 );
Inc(iY, 24); g_HUD.AddButton(IDC_CHANGEDEVICE, 'Change device (F2)', 35, iY, 125, 22 );
Inc(iY, 24); g_HUD.AddButton(IDC_CHANGEMESH, 'Change Mesh (N)', 35, iY, 125, 22, Ord('N'));
Inc(iY, 24); g_HUD.AddButton(IDC_RESETPARAM, 'Reset Parameters (R)', 35, iY, 125, 22, Ord('R'));
Inc(iY, 24); g_HUD.AddCheckBox(IDC_CHECKHDR, 'Use HDR Texture (F)', 35, iY, 130, 22, True, Ord('F'));
Inc(iY, 24); g_HUD.AddStatic(IDC_SLIDERLIGHTTEXT, 'Light Intensity', 35, iY, 125, 16);
Inc(iY, 17); g_HUD.AddSlider(IDC_SLIDERLIGHT, 35, iY, 125, 22, 0, 1500);
Inc(iY, 24); g_HUD.AddStatic(IDC_SLIDERREFLECTTEXT, 'Reflectivity', 35, iY, 125, 16);
Inc(iY, 17); g_HUD.AddSlider(IDC_SLIDERREFLECT, 35, iY, 125, 22, 0, 100);
ResetParameters();
// Initialize camera parameters
g_Camera.SetModelCenter(D3DXVector3(0.0, 0.0, 0.0));
g_Camera.SetRadius(3.0);
g_Camera.SetEnablePositionMovement(False);
// Set the light positions
g_aLights[0].vPos := D3DXVector4(-3.5, 2.3, -4.0, 1.0);
g_aLights[0].vMoveDir := D3DXVector4(0.0, 0.0, 1.0, 0.0);
g_aLights[0].fMoveDist := 8.0;
if NUM_LIGHTS > 1 then
begin
g_aLights[1].vPos := D3DXVector4(3.5, 2.3, 4.0, 1.0);
g_aLights[1].vMoveDir := D3DXVector4(0.0, 0.0, -1.0, 0.0);
g_aLights[1].fMoveDist := 8.0;
end;
if NUM_LIGHTS > 2 then
begin
g_aLights[2].vPos := D3DXVECTOR4( -3.5, 2.3, 4.0, 1.0);
g_aLights[2].vMoveDir := D3DXVECTOR4( 1.0, 0.0, 0.0, 0.0);
g_aLights[2].fMoveDist := 7.0;
end;
if NUM_LIGHTS > 3 then
begin
g_aLights[3].vPos := D3DXVECTOR4( 3.5, 2.3, -4.0, 1.0);
g_aLights[3].vMoveDir := D3DXVECTOR4( -1.0, 0.0, 0.0, 0.0);
g_aLights[3].fMoveDist := 7.0;
end;
end;
//--------------------------------------------------------------------------------------
// Called during device initialization, this code checks the device for some
// minimum set of capabilities, and rejects those that don't pass by returning false.
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
var
pD3D: IDirect3D9;
begin
Result:= False;
// Skip backbuffer formats that don't support alpha blending
pD3D := DXUTGetD3DObject;
if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,
AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING,
D3DRTYPE_TEXTURE, BackBufferFormat))
then Exit;
// Must support cube textures
if (pCaps.TextureCaps and D3DPTEXTURECAPS_CUBEMAP = 0) then Exit;
// Must support vertex shader 1.1
if (pCaps.VertexShaderVersion < D3DVS_VERSION(1, 1)) then Exit;
// Must support pixel shader 2.0
if (pCaps.PixelShaderVersion < D3DPS_VERSION(2, 0)) then Exit;
// need to support D3DFMT_A16B16G16R16F render target
if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,
AdapterFormat, D3DUSAGE_RENDERTARGET,
D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F)) then
begin
// If not, need to support D3DFMT_G16R16F render target as fallback
if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,
AdapterFormat, D3DUSAGE_RENDERTARGET,
D3DRTYPE_CUBETEXTURE, D3DFMT_G16R16F))
then Exit;
end;
// need to support D3DFMT_A8R8G8B8 render target
if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,
AdapterFormat, D3DUSAGE_RENDERTARGET,
D3DRTYPE_CUBETEXTURE, D3DFMT_A8R8G8B8))
then Exit;
Result:= True;
end;
//--------------------------------------------------------------------------------------
// This callback function is called immediately before a device is created to allow the
// application to modify the device settings. The supplied pDeviceSettings parameter
// contains the settings that the framework has selected for the new device, and the
// application can make any desired changes directly to this structure. Note however that
// DXUT will not correct invalid device settings so care must be taken
// to return valid device settings, otherwise IDirect3D9::CreateDevice() will fail.
//--------------------------------------------------------------------------------------
{static} var s_bFirstTime: Boolean = True;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
var
pD3D: IDirect3D9;
begin
// Initialize the number of cube maps required when using floating point format
pD3D := DXUTGetD3DObject;
if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,
pDeviceSettings.AdapterFormat, D3DUSAGE_RENDERTARGET,
D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F))
then g_nNumFpCubeMap := 2
else g_nNumFpCubeMap := 1;
g_nNumCubes := g_nNumFpCubeMap;
// If device doesn't support HW T&L or doesn't support 1.1 vertex shaders in HW
// then switch to SWVP.
if (pCaps.DevCaps and D3DDEVCAPS_HWTRANSFORMANDLIGHT = 0) or
(pCaps.VertexShaderVersion < D3DVS_VERSION(1,1))
then pDeviceSettings.BehaviorFlags := D3DCREATE_SOFTWARE_VERTEXPROCESSING;
// Debugging vertex shaders requires either REF or software vertex processing
// and debugging pixel shaders requires REF.
{$IFDEF DEBUG_VS}
if (pDeviceSettings.DeviceType <> D3DDEVTYPE_REF) then
with pDeviceSettings do
begin
BehaviorFlags := BehaviorFlags and not D3DCREATE_HARDWARE_VERTEXPROCESSING;
BehaviorFlags := BehaviorFlags and not D3DCREATE_PUREDEVICE;
BehaviorFlags := BehaviorFlags or D3DCREATE_SOFTWARE_VERTEXPROCESSING;
end;
{$ENDIF}
{$IFDEF DEBUG_PS}
pDeviceSettings.DeviceType := D3DDEVTYPE_REF;
{$ENDIF}
// For the first device created if its a REF device, optionally display a warning dialog box
if s_bFirstTime then
begin
s_bFirstTime := False;
if (pDeviceSettings.DeviceType = D3DDEVTYPE_REF) then DXUTDisplaySwitchingToREFWarning;
end;
Result:= True;
end;
//-----------------------------------------------------------------------------
// Reset light and material parameters to default values
//-----------------------------------------------------------------------------
procedure ResetParameters;
begin
g_bUseFloatCubeMap := True;
g_fReflectivity := 0.4;
g_vLightIntensity := D3DXVector4(24.0, 24.0, 24.0, 24.0);
if (g_pEffect <> nil) then
begin
V(g_pEffect.SetFloat(g_hReflectivity, g_fReflectivity));
V(g_pEffect.SetVector(g_hLightIntensity, g_vLightIntensity));
end;
UpdateUiWithChanges;
end;
//--------------------------------------------------------------------------------------
// Write the updated values to the static UI controls
procedure UpdateUiWithChanges;
var
pStatic: CDXUTStatic;
pSlider: CDXUTSlider;
pCheck: CDXUTCheckBox;
begin
pStatic := g_HUD.GetStatic(IDC_SLIDERLIGHTTEXT);
if (pStatic <> nil) then
begin
// swprintf( wszText, L"Light intensity: %0.2f", g_vLightIntensity.x);
pStatic.Text := PWideChar(WideFormat('Light intensity: %0.2f', [g_vLightIntensity.x]));
end;
pStatic := g_HUD.GetStatic(IDC_SLIDERREFLECTTEXT);
if (pStatic <> nil) then
begin
// swprintf( wszText, L"Reflectivity: %0.2f", g_fReflectivity);
pStatic.Text := PWideChar(WideFormat('Reflectivity: %0.2f', [g_fReflectivity]));
end;
pSlider := g_HUD.GetSlider(IDC_SLIDERLIGHT);
if (pSlider <> nil) then
begin
pSlider.Value := Trunc(g_vLightIntensity.x * 10.0 + 0.5);
end;
pSlider := g_HUD.GetSlider(IDC_SLIDERREFLECT);
if (pSlider <> nil) then
begin
pSlider.Value := Trunc(g_fReflectivity * 100.0 + 0.5);
end;
pCheck := g_HUD.GetCheckBox(IDC_CHECKHDR);
if (pCheck <> nil) then pCheck.Checked := g_bUseFloatCubeMap;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// created, which will happen during application initialization and windowed/full screen
// toggles. This is the best location to create D3DPOOL_MANAGED resources since these
// resources need to be reloaded whenever the device is destroyed. Resources created
// here should be released in the OnDestroyDevice callback.
//--------------------------------------------------------------------------------------
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
dwShaderFlags: DWORD;
str: array[0..MAX_PATH-1] of WideChar;
i: Integer;
vCtr: TD3DXVector3;
fRadius: Single;
mWorld, m: TD3DXMatrixA16;
vAxis: TD3DXVector3;
mIdent: TD3DXMatrixA16;
vFromPt: TD3DXVector3;
vLookatPt: TD3DXVector3;
begin
Result:= g_DialogResourceManager.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
// Initialize the font
Result:= D3DXCreateFont(pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE,
'Arial', g_pFont);
if V_Failed(Result) then Exit;
// Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the
// shader debugger. Debugging vertex shaders requires either REF or software vertex
// processing, and debugging pixel shaders requires REF. The
// D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug experience in the
// shader debugger. It enables source level debugging, prevents instruction
// reordering, prevents dead code elimination, and forces the compiler to compile
// against the next higher available software target, which ensures that the
// unoptimized shaders do not exceed the shader model limitations. Setting these
// flags will cause slower rendering since the shaders will be unoptimized and
// forced into software. See the DirectX documentation for more information about
// using the shader debugger.
dwShaderFlags := D3DXFX_NOT_CLONEABLE;
{$IFDEF DEBUG}
// Set the D3DXSHADER_DEBUG flag to embed debug information in the shaders.
// Setting this flag improves the shader debugging experience, but still allows
// the shaders to be optimized and to run exactly the way they will run in
// the release configuration of this program.
dwShaderFlags := dwShaderFlags or D3DXSHADER_DEBUG;
{$ENDIF}
{$IFDEF DEBUG_VS}
dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT;
{$ENDIF}
{$IFDEF DEBUG_PS}
dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT;
{$ENDIF}
// Read the D3DX effect file
Result := DXUTFindDXSDKMediaFile(str, MAX_PATH, 'HDRCubeMap.fx');
if V_Failed(Result) then Exit;
// If this fails, there should be debug output as to
// they the .fx file failed to compile
Result := D3DXCreateEffectFromFileW(pd3dDevice, str, nil, nil, dwShaderFlags,
nil, g_pEffect, nil);
if V_Failed(Result) then Exit;
g_hWorldView := g_pEffect.GetParameterByName(nil, 'g_mWorldView');
g_hProj := g_pEffect.GetParameterByName(nil, 'g_mProj');
g_ahtxCubeMap[0] := g_pEffect.GetParameterByName(nil, 'g_txCubeMap');
g_ahtxCubeMap[1] := g_pEffect.GetParameterByName(nil, 'g_txCubeMap2');
g_htxScene := g_pEffect.GetParameterByName(nil, 'g_txScene');
g_hLightIntensity := g_pEffect.GetParameterByName(nil, 'g_vLightIntensity');
g_hLightPosView := g_pEffect.GetParameterByName(nil, 'g_vLightPosView');
g_hReflectivity := g_pEffect.GetParameterByName(nil, 'g_fReflectivity');
// Determine the technique to render with
// Integer cube map
g_TechGroup32.hRenderScene := g_pEffect.GetTechniqueByName('RenderScene');
g_TechGroup32.hRenderLight := g_pEffect.GetTechniqueByName('RenderLight');
g_TechGroup32.hRenderEnvMap := g_pEffect.GetTechniqueByName('RenderHDREnvMap');
ZeroMemory(@g_aTechGroupFp, SizeOf(g_aTechGroupFp));
if (g_nNumFpCubeMap = 2) then
begin
// Two floating point G16R16F cube maps
g_aTechGroupFp[0].hRenderScene := g_pEffect.GetTechniqueByName('RenderSceneFirstHalf');
g_aTechGroupFp[0].hRenderLight := g_pEffect.GetTechniqueByName('RenderLightFirstHalf');
g_aTechGroupFp[0].hRenderEnvMap := g_pEffect.GetTechniqueByName('RenderHDREnvMap2Tex');
g_aTechGroupFp[1].hRenderScene := g_pEffect.GetTechniqueByName('RenderSceneSecondHalf');
g_aTechGroupFp[1].hRenderLight := g_pEffect.GetTechniqueByName('RenderLightSecondHalf');
g_aTechGroupFp[1].hRenderEnvMap := g_pEffect.GetTechniqueByName('RenderHDREnvMap2Tex');
end else
begin
// Single floating point cube map
g_aTechGroupFp[0].hRenderScene := g_pEffect.GetTechniqueByName('RenderScene');
g_aTechGroupFp[0].hRenderLight := g_pEffect.GetTechniqueByName('RenderLight');
g_aTechGroupFp[0].hRenderEnvMap := g_pEffect.GetTechniqueByName('RenderHDREnvMap');
end;
// Initialize reflectivity
Result := g_pEffect.SetFloat(g_hReflectivity, g_fReflectivity);
if V_Failed(Result) then Exit;
// Initialize light intensity
Result := g_pEffect.SetVector(g_hLightIntensity, g_vLightIntensity);
if V_Failed(Result) then Exit;
// Create vertex declaration
Result := pd3dDevice.CreateVertexDeclaration(@g_aVertDecl, g_pVertDecl);
if V_Failed(Result) then Exit;
Result:= DXUTERR_MEDIANOTFOUND;
// Load the mesh
for i := 0 to NUM_MESHES - 1 do
begin
if FAILED(LoadMesh(pd3dDevice, g_atszMeshFileName[i], g_EnvMesh[i].m_Mesh)) then Exit;
g_EnvMesh[i].WorldCenterAndScaleToRadius(1.0); // Scale to radius of 1
end;
// Load the room object
if FAILED(LoadMesh(pd3dDevice, 'room.x', g_Room)) then Exit;
// Load the light object
if FAILED(LoadMesh(pd3dDevice, 'misc\sphere0.x', g_LightMesh)) then Exit;
// Initialize the world matrix for the lights
if FAILED(ComputeBoundingSphere(g_LightMesh, vCtr, fRadius)) then
begin
Result:= E_FAIL;
Exit;
end;
D3DXMatrixTranslation(mWorld, -vCtr.x, -vCtr.y, -vCtr.z);
D3DXMatrixScaling(m, LIGHTMESH_RADIUS / fRadius,
LIGHTMESH_RADIUS / fRadius,
LIGHTMESH_RADIUS / fRadius);
D3DXMatrixMultiply(mWorld, mWorld, m);
for i := 0 to NUM_LIGHTS - 1 do
begin
D3DXMatrixTranslation(m, g_aLights[i].vPos.x,
g_aLights[i].vPos.y,
g_aLights[i].vPos.z);
D3DXMatrixMultiply(g_aLights[i].mWorld, mWorld, m);
end;
// Orbiter
for i := 0 to High(g_Orbiter) do
begin
if FAILED(LoadMesh(pd3dDevice, g_OrbitData[i].tszXFile, g_Orbiter[i].m_Mesh)) then Exit;
g_Orbiter[i].WorldCenterAndScaleToRadius(0.7);
vAxis := g_OrbitData[i].vAxis;
g_Orbiter[i].SetOrbit(vAxis, g_OrbitData[i].fRadius, g_OrbitData[i].fSpeed);
end;
// World transform to identity
D3DXMatrixIdentity(mIdent);
Result := pd3dDevice.SetTransform(D3DTS_WORLD, mIdent);
if V_Failed(Result) then Exit;
// Setup the camera's view parameters
vFromPt := D3DXVector3(0.0, 0.0, -2.5);
vLookatPt := D3DXVector3(0.0, 0.0, 0.0);
g_Camera.SetViewParams(vFromPt, vLookatPt);
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// Load mesh from file and convert vertices to our format
//--------------------------------------------------------------------------------------
function LoadMesh(pd3dDevice: IDirect3DDevice9; wszName: PWideChar; Mesh: CDXUTMesh): HRESULT;
begin
Result := Mesh.CreateMesh(pd3dDevice, wszName);
if Failed(Result) then Exit;
Result := Mesh.SetVertexDecl(pd3dDevice, @g_aVertDecl);
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// reset, which will happen after a lost device scenario. This is the best location to
// create D3DPOOL_DEFAULT resources since these resources need to be reloaded whenever
// the device is lost. Resources created here should be released in the OnLostDevice
// callback.
//--------------------------------------------------------------------------------------
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
fAspectRatio: Single;
pControl: CDXUTControl;
iY: Integer;
i: Integer;
d3dSettings: TDXUTDeviceSettings;
begin
Result:= g_DialogResourceManager.OnResetDevice;
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnResetDevice;
if V_Failed(Result) then Exit;
if Assigned(g_pFont) then
begin
Result:= g_pFont.OnResetDevice;
if V_Failed(Result) then Exit;
end;
if Assigned(g_pEffect) then
begin
Result:= g_pEffect.OnResetDevice;
if V_Failed(Result) then Exit;
end;
// Create a sprite to help batch calls when drawing many lines of text
Result:= D3DXCreateSprite(pd3dDevice, g_pTextSprite);
if V_Failed(Result) then Exit;
// Setup the camera's projection parameters
fAspectRatio := pBackBufferSurfaceDesc.Width / pBackBufferSurfaceDesc.Height;
g_Camera.SetProjParams(D3DX_PI/4, fAspectRatio, 0.1, 1000.0);
g_Camera.SetWindow(pBackBufferSurfaceDesc.Width, pBackBufferSurfaceDesc.Height);
g_HUD.SetLocation(pBackBufferSurfaceDesc.Width-170, 0);
g_HUD.SetSize(170, 170);
iY := pBackBufferSurfaceDesc.Height - 170;
pControl := g_HUD.GetControl(IDC_CHECKHDR);
if Assigned(pControl) then pControl.SetLocation(35, iY);
pControl := g_HUD.GetControl(IDC_CHANGEMESH); Inc(iY, 24);
if Assigned(pControl) then pControl.SetLocation(35, iY);
pControl := g_HUD.GetControl(IDC_RESETPARAM); Inc(iY, 24);
if Assigned(pControl) then pControl.SetLocation(35, iY);
pControl := g_HUD.GetControl(IDC_SLIDERLIGHTTEXT); Inc(iY, 35);
if Assigned(pControl) then pControl.SetLocation(35, iY);
pControl := g_HUD.GetControl(IDC_SLIDERLIGHT); Inc(iY, 17);
if Assigned(pControl) then pControl.SetLocation(35, iY);
pControl := g_HUD.GetControl(IDC_SLIDERREFLECTTEXT); Inc(iY, 24);
if Assigned(pControl) then pControl.SetLocation(35, iY);
pControl := g_HUD.GetControl(IDC_SLIDERREFLECT); Inc(iY, 17);
if Assigned(pControl) then pControl.SetLocation(35, iY);
// Restore meshes
for i := 0 to NUM_MESHES - 1 do
g_EnvMesh[i].m_Mesh.RestoreDeviceObjects(pd3dDevice);
g_Room.RestoreDeviceObjects(pd3dDevice);
g_LightMesh.RestoreDeviceObjects(pd3dDevice);
for i := 0 to High(g_Orbiter) do
g_Orbiter[i].m_Mesh.RestoreDeviceObjects(pd3dDevice);
// Create the cube textures
ZeroMemory(@g_apCubeMapFp, SizeOf(g_apCubeMapFp));
Result := pd3dDevice.CreateCubeTexture(ENVMAPSIZE,
1,
D3DUSAGE_RENDERTARGET,
D3DFMT_A16B16G16R16F,
D3DPOOL_DEFAULT,
g_apCubeMapFp[0],
nil);
if FAILED(Result) then
begin
// Create 2 G16R16 textures as fallback
Result := pd3dDevice.CreateCubeTexture(ENVMAPSIZE,
1,
D3DUSAGE_RENDERTARGET,
D3DFMT_G16R16F,
D3DPOOL_DEFAULT,
g_apCubeMapFp[0],
nil);
if V_Failed(Result) then Exit;
Result := pd3dDevice.CreateCubeTexture(ENVMAPSIZE,
1,
D3DUSAGE_RENDERTARGET,
D3DFMT_G16R16F,
D3DPOOL_DEFAULT,
g_apCubeMapFp[1],
nil);
if V_Failed(Result) then Exit;
end;
Result := pd3dDevice.CreateCubeTexture(ENVMAPSIZE,
1,
D3DUSAGE_RENDERTARGET,
D3DFMT_A8R8G8B8,
D3DPOOL_DEFAULT,
g_pCubeMap32,
nil);
if V_Failed(Result) then Exit;
// Create the stencil buffer to be used with the cube textures
// Create the depth-stencil buffer to be used with the shadow map
// We do this to ensure that the depth-stencil buffer is large
// enough and has correct multisample type/quality when rendering
// the shadow map. The default depth-stencil buffer created during
// device creation will not be large enough if the user resizes the
// window to a very small size. Furthermore, if the device is created
// with multisampling, the default depth-stencil buffer will not
// work with the shadow map texture because texture render targets
// do not support multisample.
d3dSettings := DXUTGetDeviceSettings;
Result := pd3dDevice.CreateDepthStencilSurface(ENVMAPSIZE,
ENVMAPSIZE,
d3dSettings.pp.AutoDepthStencilFormat,
D3DMULTISAMPLE_NONE,
0,
True,
g_pDepthCube,
nil);
if V_Failed(Result) then Exit;
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called once at the beginning of every frame. This is the
// best location for your application to handle updates to the scene, but is not
// intended to contain actual rendering calls, which should instead be placed in the
// OnFrameRender callback.
//--------------------------------------------------------------------------------------
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
var
i: Integer;
begin
// Update the camera's position based on user input
g_Camera.FrameMove(fElapsedTime);
for i := 0 to High(g_Orbiter) do g_Orbiter[i].Orbit(fElapsedTime);
end;
//--------------------------------------------------------------------------------------
// This callback function will be called at the end of every frame to perform all the
// rendering calls for the scene, and it will also be called if the window needs to be
// repainted. After this function has returned, the sample framework will call
// IDirect3DDevice9::Present to display the contents of the next buffer in the swap chain
//--------------------------------------------------------------------------------------
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
begin
// If the settings dialog is being shown, then
// render it instead of rendering the app's scene
if g_SettingsDlg.Active then
begin
g_SettingsDlg.OnRender(fElapsedTime);
Exit;
end;
RenderSceneIntoCubeMap(pd3dDevice, fTime);
// Clear the render buffers
V(pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER, $000000ff, 1.0, 0));
// Begin the scene
if SUCCEEDED(pd3dDevice.BeginScene) then
begin
RenderScene(pd3dDevice, g_Camera.GetViewMatrix^, g_Camera.GetProjMatrix^, g_pTech[0], True, fTime);
// Render stats and help text
RenderText;
g_HUD.OnRender(fElapsedTime);
pd3dDevice.EndScene;
end;
end;
//--------------------------------------------------------------------------------------
// Set up the cube map by rendering the scene into it.
//--------------------------------------------------------------------------------------
procedure RenderSceneIntoCubeMap(const pd3dDevice: IDirect3DDevice9; fTime: Double);
var
mProj: TD3DXMatrixA16;
mViewDir: TD3DXMatrixA16;
pRTOld: IDirect3DSurface9;
pDSOld: IDirect3DSurface9;
nCube: Integer;
nFace: TD3DCubemapFaces;
pSurf: IDirect3DSurface9;
mView: TD3DXMatrixA16;
begin
// The projection matrix has a FOV of 90 degrees and asp ratio of 1
D3DXMatrixPerspectiveFovLH(mProj, D3DX_PI * 0.5, 1.0, 0.01, 100.0);
mViewDir := g_Camera.GetViewMatrix^;
mViewDir._41 := 0.0; mViewDir._42 := 0.0; mViewDir._43 := 0.0;
V(pd3dDevice.GetRenderTarget(0, pRTOld));
if SUCCEEDED(pd3dDevice.GetDepthStencilSurface(pDSOld)) then
begin
// If the device has a depth-stencil buffer, use
// the depth stencil buffer created for the cube textures.
V(pd3dDevice.SetDepthStencilSurface(g_pDepthCube));
end;
for nCube := 0 to g_nNumCubes - 1 do
for nFace := Low(TD3DCubemapFaces) to High(TD3DCubemapFaces) do
begin
V(g_apCubeMap[nCube].GetCubeMapSurface(nFace, 0, pSurf));
V(pd3dDevice.SetRenderTarget(0, pSurf));
SAFE_RELEASE(pSurf);
mView := DXUTGetCubeMapViewMatrix(nFace);
D3DXMatrixMultiply(mView, mViewDir, mView);
V(pd3dDevice.Clear(0, nil, D3DCLEAR_ZBUFFER, $000000ff, 1.0, 0));
// Begin the scene
if SUCCEEDED(pd3dDevice.BeginScene) then
begin
RenderScene(pd3dDevice, mView, mProj, g_pTech[nCube], False, fTime);
// End the scene.
pd3dDevice.EndScene;
end;
end;
// Restore depth-stencil buffer and render target
if (pDSOld <> nil) then
begin
V(pd3dDevice.SetDepthStencilSurface(pDSOld));
SAFE_RELEASE(pDSOld);
end;
V(pd3dDevice.SetRenderTarget(0, pRTOld));
SAFE_RELEASE(pRTOld);
end;
//--------------------------------------------------------------------------------------
// Renders the scene with a specific view and projection matrix.
//--------------------------------------------------------------------------------------
procedure RenderScene(const pd3dDevice: IDirect3DDevice9; const pmView, pmProj: TD3DXMatrix;
const pTechGroup: TTechniqueGroup; bRenderEnvMappedMesh: Boolean; fTime: Double);
function fmod(x, y: Single): Single;
begin
//;Description fmod calculates x - (y * chop (x / y));
Result:= x - (y*Trunc(x/y));
end;
var
p, cPass: LongWord;
mWorldView: TD3DXMatrixA16;
avLightPosView: array [0..NUM_LIGHTS-1] of TD3DXVector4;
i: Integer;
fDisp: Single; // Distance to move
vMove: TD3DXVector4; // In vector form
pMesh: ID3DXMesh;
pMeshObj: ID3DXMesh;
m: Integer;
begin
V(g_pEffect.SetMatrix(g_hProj, pmProj));
// Write camera-space light positions to effect
for i := 0 to NUM_LIGHTS - 1 do
begin
// Animate the lights
fDisp := (1.0 + cos(fmod(fTime, D3DX_PI))) * 0.5 * g_aLights[i].fMoveDist; // Distance to move
// vMove := g_aLights[i].vMoveDir * fDisp; // In vector form
D3DXVec4Scale(vMove, g_aLights[i].vMoveDir, fDisp);
D3DXMatrixTranslation(g_aLights[i].mWorking, vMove.x, vMove.y, vMove.z); // Matrix form
D3DXMatrixMultiply(g_aLights[i].mWorking, g_aLights[i].mWorld, g_aLights[i].mWorking);
// vMove += g_aLights[i].vPos; // Animated world coordinates
D3DXVec4Add(vMove, vMove, g_aLights[i].vPos); // Animated world coordinates
D3DXVec4Transform(avLightPosView[i], vMove, pmView);
end;
V(g_pEffect.SetVectorArray(g_hLightPosView, @avLightPosView, NUM_LIGHTS));
//
// Render the environment-mapped mesh if specified
//
if bRenderEnvMappedMesh then
begin
V(g_pEffect.SetTechnique(pTechGroup.hRenderEnvMap));
// Combine the offset and scaling transformation with
// rotation from the camera to form the final
// world transformation matrix.
D3DXMatrixMultiply(mWorldView, g_EnvMesh[g_nCurrMesh].m_mWorld, g_Camera.GetWorldMatrix^);
D3DXMatrixMultiply(mWorldView, mWorldView, pmView);
V(g_pEffect.SetMatrix(g_hWorldView, mWorldView ));
V(g_pEffect._Begin(@cPass, 0));
for i := 0 to g_nNumCubes - 1 do
V(g_pEffect.SetTexture(g_ahtxCubeMap[i], g_apCubeMap[i]));
for p := 0 to cPass - 1 do
begin
V(g_pEffect.BeginPass(p));
pMesh := g_EnvMesh[g_nCurrMesh].m_Mesh.Mesh;
for i := 0 to g_EnvMesh[g_nCurrMesh].m_Mesh.m_dwNumMaterials - 1 do
V(pMesh.DrawSubset(i));
V(g_pEffect.EndPass);
end;
V(g_pEffect._End);
end;
//
// Render light spheres
//
V(g_pEffect.SetTechnique(pTechGroup.hRenderLight));
V(g_pEffect._Begin(@cPass, 0));
for p := 0 to cPass - 1 do
begin
V(g_pEffect.BeginPass(p));
for i := 0 to NUM_LIGHTS - 1 do
begin
D3DXMatrixMultiply(mWorldView, g_aLights[i].mWorking, pmView);
V(g_pEffect.SetMatrix(g_hWorldView, mWorldView));
V(g_pEffect.CommitChanges);
V(g_LightMesh.Render(pd3dDevice));
end;
V(g_pEffect.EndPass);
end;
V(g_pEffect._End);
//
// Render the rest of the scene
//
V(g_pEffect.SetTechnique(pTechGroup.hRenderScene));
V(g_pEffect._Begin(@cPass, 0));
for p := 0 to cPass - 1 do
begin
V(g_pEffect.BeginPass(p));
//
// Orbiters
//
for i := 0 to High(g_Orbiter) do
begin
D3DXMatrixMultiply(mWorldView, g_Orbiter[i].m_mWorld, pmView);
V(g_pEffect.SetMatrix(g_hWorldView, mWorldView));
// Obtain the D3DX mesh object
pMeshObj := g_Orbiter[i].m_Mesh.Mesh;
// Iterate through each subset and render with its texture
for m := 0 to g_Orbiter[i].m_Mesh.m_dwNumMaterials - 1 do
begin
V(g_pEffect.SetTexture(g_htxScene, g_Orbiter[i].m_Mesh.m_pTextures[m]));
V(g_pEffect.CommitChanges);
V(pMeshObj.DrawSubset(m));
end;
end;
//
// The room object (walls, floor, ceiling)
//
V(g_pEffect.SetMatrix(g_hWorldView, pmView));
pMeshObj := g_Room.Mesh;
// Iterate through each subset and render with its texture
for m := 0 to g_Room.m_dwNumMaterials - 1 do
begin
V(g_pEffect.SetTexture(g_htxScene, g_Room.m_pTextures[m]));
V(g_pEffect.CommitChanges);
V(pMeshObj.DrawSubset(m));
end;
V(g_pEffect.EndPass);
end;
V(g_pEffect._End);
end;
//--------------------------------------------------------------------------------------
// Render the help and statistics text. This function uses the ID3DXFont interface for
// efficient text rendering.
//--------------------------------------------------------------------------------------
procedure RenderText;
var
txtHelper: CDXUTTextHelper;
pd3dsdBackBuffer: PD3DSurfaceDesc;
begin
// The helper object simply helps keep track of text position, and color
// and then it calls pFont->DrawText( m_pSprite, strMsg, -1, &rc, DT_NOCLIP, m_clr );
// If NULL is passed in as the sprite object, then it will work however the
// pFont->DrawText() will not be batched together. Batching calls will improves performance.
txtHelper := CDXUTTextHelper.Create(g_pFont, g_pTextSprite, 15);
// Output statistics
txtHelper._Begin;
txtHelper.SetInsertionPos(5, 5);
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 0.0, 1.0));
txtHelper.DrawTextLine(DXUTGetFrameStats);
txtHelper.DrawTextLine(DXUTGetDeviceStats);
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0));
// Draw help
pd3dsdBackBuffer := DXUTGetBackBufferSurfaceDesc;
if g_bShowHelp then
begin
txtHelper.SetInsertionPos(10, pd3dsdBackBuffer.Height-15*12);
txtHelper.SetForegroundColor(D3DXColor(1.0, 0.75, 0.0, 1.0));
txtHelper.DrawTextLine('Controls:');
txtHelper.SetInsertionPos(40, pd3dsdBackBuffer.Height-15*11);
txtHelper.DrawTextLine('Rotate object: Left drag mouse'#10 +
'Adjust camera: Right drag mouse'#10'Zoom In/Out: Mouse wheel'#10 +
'Adjust reflectivity: E,D'#10'Adjust light intensity: W,S'#10 +
'Hide help: F1'#10 +
'Quit: ESC');
end else
begin
txtHelper.SetForegroundColor(D3DXColor(1.0, 0.75, 0.0, 1.0));
txtHelper.DrawTextLine('Press F1 for help');
end;
txtHelper.SetForegroundColor(D3DXColor(0.0, 1.0, 0.0, 1.0));
txtHelper.SetInsertionPos(10, pd3dsdBackBuffer.Height - 48);
txtHelper.DrawTextLine('Cube map format'#10 +
'Material reflectivity ( e/E, d/D )'#10 +
'Light intensity ( w/W, s/S )'#10);
txtHelper.SetInsertionPos(190, pd3dsdBackBuffer.Height - 48);
txtHelper.DrawFormattedTextLine('%s'#10'%.2f'#10'%.1f',
[IfThen(g_bUseFloatCubeMap, 'Floating-point ( D3D9 / HDR )', 'Integer ( D3D8 )'),
g_fReflectivity, g_vLightIntensity.x]);
txtHelper._End;
txtHelper.Free;
end;
//--------------------------------------------------------------------------------------
// Before handling window messages, DXUT passes incoming windows
// messages to the application through this callback function. If the application sets
// *pbNoFurtherProcessing to TRUE, then DXUT will not process this message.
//--------------------------------------------------------------------------------------
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
begin
Result:= 0;
// Always allow dialog resource manager calls to handle global messages
// so GUI state is updated correctly
pbNoFurtherProcessing := g_DialogResourceManager.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
if g_SettingsDlg.IsActive then
begin
g_SettingsDlg.MsgProc(hWnd, uMsg, wParam, lParam);
Exit;
end;
// Give the dialogs a chance to handle the message first
pbNoFurtherProcessing := g_HUD.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
// Pass all remaining windows messages to camera so it can respond to user input
g_Camera.HandleMessages(hWnd, uMsg, wParam, lParam);
case uMsg of
//
// Use WM_CHAR to handle parameter adjustment so
// that we can control the granularity based on
// the letter cases.
WM_CHAR:
begin
case Char(wParam) of
'W', 'w':
begin
if (Ord('w') = wParam)
then D3DXVec4Add(g_vLightIntensity, g_vLightIntensity, D3DXVector4(0.1, 0.1, 0.1, 0.0))
else D3DXVec4Add(g_vLightIntensity, g_vLightIntensity, D3DXVector4(10.0, 10.0, 10.0, 0.0));
if (g_vLightIntensity.x > 150.0) then
begin
g_vLightIntensity.x := 150.0;
g_vLightIntensity.y := 150.0;
g_vLightIntensity.z := 150.0;
end;
V(g_pEffect.SetVector(g_hLightIntensity, g_vLightIntensity));
UpdateUiWithChanges;
end;
'S', 's':
begin
if (Ord('s') = wParam)
then D3DXVec4Subtract(g_vLightIntensity, g_vLightIntensity, D3DXVector4(0.1, 0.1, 0.1, 0.0))
else D3DXVec4Subtract(g_vLightIntensity, g_vLightIntensity, D3DXVector4(10.0, 10.0, 10.0, 0.0));
if (g_vLightIntensity.x < 0.0) then
begin
g_vLightIntensity.x := 0.0;
g_vLightIntensity.y := 0.0;
g_vLightIntensity.z := 0.0;
end;
V(g_pEffect.SetVector(g_hLightIntensity, g_vLightIntensity));
UpdateUiWithChanges;
end;
'D', 'd':
begin
if (Ord('d') = wParam)
then g_fReflectivity := g_fReflectivity - 0.01
else g_fReflectivity := g_fReflectivity - 0.1;
if (g_fReflectivity < 0) then g_fReflectivity := 0;
V(g_pEffect.SetFloat(g_hReflectivity, g_fReflectivity));
UpdateUiWithChanges;
end;
'E', 'e':
begin
if (Ord('e') = wParam) then g_fReflectivity := g_fReflectivity + 0.01
else g_fReflectivity := g_fReflectivity + 0.1;
if (g_fReflectivity > 1.0) then g_fReflectivity := 1.0;
V(g_pEffect.SetFloat(g_hReflectivity, g_fReflectivity));
UpdateUiWithChanges;
end;
end;
end;
end;
end;
//--------------------------------------------------------------------------------------
// As a convenience, DXUT inspects the incoming windows messages for
// keystroke messages and decodes the message parameters to pass relevant keyboard
// messages to the application. The framework does not remove the underlying keystroke
// messages, which are still passed to the application's MsgProc callback.
//--------------------------------------------------------------------------------------
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
begin
if bKeyDown then
begin
case nChar of
VK_F1: g_bShowHelp := not g_bShowHelp;
end;
end;
end;
//--------------------------------------------------------------------------------------
// Handles the GUI events
//--------------------------------------------------------------------------------------
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
var
pSlider: CDXUTSlider;
pStatic: CDXUTStatic;
begin
case nControlID of
IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen;
IDC_TOGGLEREF: DXUTToggleREF;
IDC_CHANGEDEVICE: with g_SettingsDlg do Active := not Active;
IDC_CHECKHDR:
begin
g_bUseFloatCubeMap := (pControl as CDXUTCheckBox).Checked;
if g_bUseFloatCubeMap then
begin
g_nNumCubes := g_nNumFpCubeMap;
g_apCubeMap := @g_apCubeMapFp;
g_pTech := @g_aTechGroupFp;
end else
begin
g_nNumCubes := 1;
g_apCubeMap := @g_pCubeMap32;
g_pTech := @g_TechGroup32;
end;
end;
IDC_CHANGEMESH:
begin
Inc(g_nCurrMesh);
if (g_nCurrMesh = NUM_MESHES) then g_nCurrMesh := 0;
end;
IDC_RESETPARAM: ResetParameters;
IDC_SLIDERLIGHT:
begin
if (nEvent = EVENT_SLIDER_VALUE_CHANGED) then
begin
pSlider := (pControl as CDXUTSlider);
g_vLightIntensity.x := pSlider.Value * 0.1;
g_vLightIntensity.y := pSlider.Value * 0.1;
g_vLightIntensity.z := pSlider.Value * 0.1;
if (g_pEffect <> nil) then g_pEffect.SetVector(g_hLightIntensity, g_vLightIntensity);
pStatic := g_HUD.GetStatic(IDC_SLIDERLIGHTTEXT);
if (pStatic <> nil) then
pStatic.Text := PWideChar(WideFormat('Light intensity: %0.2f', [g_vLightIntensity.x]));
end;
end;
IDC_SLIDERREFLECT:
begin
if (nEvent = EVENT_SLIDER_VALUE_CHANGED) then
begin
pSlider := (pControl as CDXUTSlider);
g_fReflectivity := pSlider.Value * 0.01;
if (g_pEffect <> nil) then g_pEffect.SetFloat(g_hReflectivity, g_fReflectivity);
UpdateUiWithChanges;
pStatic := g_HUD.GetStatic(IDC_SLIDERREFLECTTEXT);
if (pStatic <> nil) then
pStatic.Text := PWideChar(WideFormat('Reflectivity: %0.2f', [g_fReflectivity]));
end;
end;
end;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// entered a lost state and before IDirect3DDevice9::Reset is called. Resources created
// in the OnResetDevice callback should be released here, which generally includes all
// D3DPOOL_DEFAULT resources. See the "Lost Devices" section of the documentation for
// information about lost devices.
//--------------------------------------------------------------------------------------
procedure OnLostDevice;
var
i: Integer;
begin
g_DialogResourceManager.OnLostDevice;
g_SettingsDlg.OnLostDevice;
if Assigned(g_pFont) then g_pFont.OnLostDevice;
if Assigned(g_pEffect) then g_pEffect.OnLostDevice;
SAFE_RELEASE(g_pTextSprite);
for i := 0 to NUM_MESHES - 1 do g_EnvMesh[i].m_Mesh.InvalidateDeviceObjects;
g_Room.InvalidateDeviceObjects;
g_LightMesh.InvalidateDeviceObjects;
for i := 0 to High(g_Orbiter) do g_Orbiter[i].m_Mesh.InvalidateDeviceObjects;
SAFE_RELEASE(g_apCubeMapFp[0]);
SAFE_RELEASE(g_apCubeMapFp[1]);
SAFE_RELEASE(g_pCubeMap32);
SAFE_RELEASE(g_pDepthCube);
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// been destroyed, which generally happens as a result of application termination or
// windowed/full screen toggles. Resources created in the OnCreateDevice callback
// should be released here, which generally includes all D3DPOOL_MANAGED resources.
//--------------------------------------------------------------------------------------
procedure OnDestroyDevice;
var
i: Integer;
begin
g_DialogResourceManager.OnDestroyDevice;
g_SettingsDlg.OnDestroyDevice;
SAFE_RELEASE(g_pEffect);
SAFE_RELEASE(g_pFont);
SAFE_RELEASE(g_pVertDecl);
g_Room.DestroyMesh;
g_LightMesh.DestroyMesh;
for i := 0 to High(g_Orbiter) do g_Orbiter[i].m_Mesh.DestroyMesh;
for i := 0 to NUM_MESHES - 1 do g_EnvMesh[i].m_Mesh.DestroyMesh;
end;
{ CObj }
constructor CObj.Create;
begin
D3DXMatrixIdentity(m_mWorld);
m_Mesh := CDXUTMesh.Create;
end;
//
// Compute the world transformation matrix
// to center the mesh at origin in world space
// and scale its size to the specified radius.
//
function CObj.WorldCenterAndScaleToRadius(fRadius: Single): HRESULT;
var
fRadiusBound: Single;
vCtr: TD3DXVector3;
mScale: TD3DXMatrixA16;
begin
Result := ComputeBoundingSphere(m_Mesh, vCtr, fRadiusBound);
if FAILED(Result) then Exit;
D3DXMatrixTranslation(m_mWorld, -vCtr.x, -vCtr.y, -vCtr.z);
D3DXMatrixScaling(mScale, fRadius / fRadiusBound,
fRadius / fRadiusBound,
fRadius / fRadiusBound);
D3DXMatrixMultiply(m_mWorld, m_mWorld, mScale);
end;
{ COrbiter }
constructor COrbiter.Create;
begin
inherited;
m_vAxis := D3DXVector3(0.0, 1.0, 0.0);
m_fRadius := 1.0;
m_fSpeed := D3DX_PI;
end;
// Compute the orbit transformation and apply to m_mWorld
procedure COrbiter.Orbit(fElapsedTime: Single);
var
m: TD3DXMatrixA16;
begin
D3DXMatrixRotationAxis(m, m_vAxis, m_fSpeed * fElapsedTime);
D3DXMatrixMultiply(m_mWorld, m_mWorld, m);
end;
// Call this after m_mWorld is initialized
procedure COrbiter.SetOrbit(const vAxis: TD3DXVector3; fRadius, fSpeed: Single);
var
m: TD3DXMatrixA16;
vX: TD3DXVector3;
vRot: TD3DXVector3;
fAng: Single; // Angle to rotate
vXxRot: TD3DXVector3; // X cross vRot
begin
m_vAxis := vAxis; m_fRadius := fRadius; m_fSpeed := fSpeed;
D3DXVec3Normalize(m_vAxis, m_vAxis);
// Translate by m_fRadius in -Y direction
D3DXMatrixTranslation(m, 0.0, -m_fRadius, 0.0);
D3DXMatrixMultiply(m_mWorld, m_mWorld, m);
// Apply rotation from X axis to the orbit axis
vX := D3DXVector3(1.0, 0.0, 0.0);
D3DXVec3Cross(vRot, m_vAxis, vX); // Axis of rotation
// If the cross product is 0, m_vAxis is on the X axis
// So we either rotate 0 or PI.
if D3DXVec3LengthSq(vRot) = 0 then
begin
if (m_vAxis.x < 0.0) then D3DXMatrixRotationY(m, D3DX_PI) // PI
else D3DXMatrixIdentity(m); // 0
end else
begin
fAng := ArcCos(D3DXVec3Dot(m_vAxis, vX)); // Angle to rotate
// Find out direction to rotate
D3DXVec3Cross(vXxRot, vX, vRot);
if (D3DXVec3Dot(vXxRot, m_vAxis) >= 0) then fAng := -fAng;
D3DXMatrixRotationAxis(m, vRot, fAng);
end;
D3DXMatrixMultiply(m_mWorld, m_mWorld, m);
end;
procedure CreateCustomDXUTobjects;
var
i: Integer;
begin
g_DialogResourceManager:= CDXUTDialogResourceManager.Create; // manager for shared resources of dialogs
g_SettingsDlg:= CD3DSettingsDlg.Create; // Device settings dialog
g_Camera:= CModelViewerCamera.Create; // A model viewing camera
g_HUD:= CDXUTDialog.Create; // dialog for standard controls
g_Room:= CDXUTMesh.Create; // Mesh representing room (wall, floor, ceiling)
g_LightMesh:= CDXUTMesh.Create; // Mesh for the light object
for i:= 0 to NUM_MESHES-1 do g_EnvMesh[i]:= CObj.Create; // Mesh to receive environment mapping
for i:= 0 to High(g_Orbiter) do g_Orbiter[i]:= COrbiter.Create; // Orbiter meshes
end;
procedure DestroyCustomDXUTobjects;
var
i: Integer;
begin
FreeAndNil(g_DialogResourceManager);
FreeAndNil(g_SettingsDlg);
g_Camera.Free;
g_HUD.Free;
g_Room.Free;
g_LightMesh.Free;
for i:= 0 to NUM_MESHES-1 do g_EnvMesh[i].Free; // Mesh to receive environment mapping
for i:= 0 to High(g_Orbiter) do g_Orbiter[i].Free; // Orbiter meshes
end;
end.
|
{La oficina meteorológica calcula la sensación térmica de acuerdo a la temperatura, humedad,
dirección (N, S, E, O) y velocidad del viento.
Si la velocidad del viento es menor 10 km/h, la sensación coincide con la temperatura
Si es mayor o igual a 10 km/h y la dirección es S ó O la sensación es 3 grados menos que
la temperatura, en cambio si la dirección es N ó E es 1 grado menos.
Cuando el viento incide en el calculo, si la humedad es mayor al 50% la sensación
disminuye en un grado mas.
Determine los datos que se requieren para calcular la sensación térmica}
Program TP1eje12;
Var
temperatura,humedad,velocidad:byte;
direccion:char;
Begin
write('Cual es la velocidad del viento en km/h : ');readln(velocidad);
write('Cual es la direccion del viento? N / S / E / O : ');readln(direccion);
write('Ingrese la temperatura: ');readln(temperatura);
write('Ingrese el % de la humedad: ');readln(humedad);
If (velocidad < 10) then
write('La sensacion termica es: ',temperatura,'º C')
Else
if (velocidad >= 10) and (humedad <= 50) and (direccion = 'S') or (direccion = 'O') then
write('La sensacion termica es: ',temperatura - 3,'º C')
Else
if (velocidad >= 10) and (humedad > 50) and (direccion = 'S') or (direccion = 'O') then
write('La sensacion termica es: ',temperatura - 4,'º C')
Else
if (velocidad >= 10) and (humedad <= 50) and (direccion = 'N') or (direccion = 'E') then
write('La sensacion termica es: ',temperatura - 1,'º C')
Else
write('La sensacion termica es: ',temperatura - 2,'º C');
end.
|
{
@abstract Implements @link(TNtVirtualTreeViewTranslator) extension class that translates columns of TVirtualTreeView.
TVirtualTreeView is an old control that was designed before Delphi properly supported Unicode.
This is why the makers of TVirtualTreeView decided to stored Text and Hint properties
of the column item in a defined custom property. @link(TNtTranslator) can not
automatically translate defined properties because there is no direct mapping
between form properties and runtime properties. This extension enables
runtime language switch for columns of TVirtualTreeView.
To enable runtime language switch of TVirtualTreeView just add this unit into
your project or add unit into any uses block.
@longCode(#
implementation
uses
NtVirtualTreeTranslator;
#)
See @italic(Samples\Delphi\VCL\VirtualTree) sample to see how to use the unit.
}
unit NtVirtualTreeTranslator;
interface
uses
Classes, NtBaseTranslator;
type
{ @abstract Translator extension class that translates TVirtualTreeView component. }
TNtVirtualTreeViewTranslator = class(TNtTranslatorExtension)
public
{ @seealso(TNtTranslatorExtension.CanTranslate) }
function CanTranslate(obj: TObject): Boolean; override;
{ @seealso(TNtTranslatorExtension.Translate) }
procedure Translate(
component: TComponent;
obj: TObject;
const name: String;
value: Variant;
index: Integer); override;
{ @seealso(TNtTranslatorExtension.GetActualObject) }
function GetActualObject(obj: TObject; const propName: String): TObject; override;
{ @seealso(TNtTranslatorExtension.GetActualName) }
function GetActualName(obj: TObject; const propName: String): String; override;
end;
implementation
uses
VirtualTrees;
function TNtVirtualTreeViewTranslator.CanTranslate(obj: TObject): Boolean;
begin
Result := obj is TVirtualTreeColumn;
end;
procedure TNtVirtualTreeViewTranslator.Translate(
component: TComponent;
obj: TObject;
const name: String;
value: Variant;
index: Integer);
var
item: TVirtualTreeColumn;
begin
if obj is TVirtualTreeColumn then
begin
item := TVirtualTreeColumn(obj);
if name = 'WideText' then
item.Text := value
else if name = 'WideHint' then
item.Hint := value
end
end;
function TNtVirtualTreeViewTranslator.GetActualObject(
obj: TObject;
const propName: String): TObject;
begin
if (obj is TVirtualStringTree) and (propName = 'Columns') then
Result := TVirtualStringTree(obj).Header
else
Result := nil;
end;
function TNtVirtualTreeViewTranslator.GetActualName(
obj: TObject;
const propName: String): String;
begin
if (obj is TVirtualTreeColumn) and (propName = 'WideText') then
Result := 'Text'
else if (obj is TVirtualTreeColumn) and (propName = 'WideHint') then
Result := 'Hint'
else
Result := '';
end;
initialization
NtTranslatorExtensions.Register(TNtVirtualTreeViewTranslator);
end.
|
unit UDMCadContato;
interface
uses
System.SysUtils, System.Classes, UDMPai, Data.DB, Datasnap.DBClient,
Datasnap.DSConnect, UDMConexao, Data.DBXDataSnap, Data.DBXCommon,
IPPeerClient, Data.SqlExpr, ClassContato;
type
TDMCadContato = class(TDMPai)
CDS_CadastroCODIGO_CONTATO: TIntegerField;
CDS_CadastroNOME_CONTATO: TStringField;
CDS_CadastroDTNASCIMENTO_CONTATO: TDateField;
CDS_CadastroSQL_Telefone: TDataSetField;
CDS_CadastroSQL_Endereco: TDataSetField;
CDS_Endereco: TClientDataSet;
CDS_Telefone: TClientDataSet;
CDS_EnderecoCODIGO_ENDERECO: TIntegerField;
CDS_EnderecoRUA_ENDERECO: TStringField;
CDS_EnderecoNUMERO_ENDERECO: TStringField;
CDS_TelefoneCODIGO_TELEFONE: TIntegerField;
CDS_TelefoneNUMERO_TELEFONE: TStringField;
CDS_EnderecoCONTATO_CODCONTATO: TIntegerField;
CDS_TelefoneCONTATO_CODCONTATO: TIntegerField;
procedure CDS_EnderecoBeforeDelete(DataSet: TDataSet);
procedure CDS_TelefoneBeforeDelete(DataSet: TDataSet);
procedure CDS_EnderecoNewRecord(DataSet: TDataSet);
procedure CDS_TelefoneNewRecord(DataSet: TDataSet);
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
procedure CDS_EnderecoBeforePost(DataSet: TDataSet);
procedure CDS_TelefoneBeforePost(DataSet: TDataSet);
private
{ Private declarations }
public
{ Public declarations }
end;
var
DMCadContato: TDMCadContato;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
procedure TDMCadContato.CDS_EnderecoBeforeDelete(DataSet: TDataSet);
begin
inherited;
//if not (CDS_Cadastro.State in [dsEdit, dsInsert]) then
CDS_Cadastro.Edit;
end;
procedure TDMCadContato.CDS_EnderecoBeforePost(DataSet: TDataSet);
begin
inherited;
if CDS_Endereco.State = dsInsert then
CDS_Endereco.FieldByName('CODIGO_ENDERECO').AsInteger := DMConexao.ProximoCodigo('CONTATO_ENDERECO');
end;
procedure TDMCadContato.CDS_EnderecoNewRecord(DataSet: TDataSet);
begin
inherited;
CDS_Endereco.FieldByName('CONTATO_CODCONTATO').AsInteger := CDS_Cadastro.FieldByName('CODIGO_CONTATO').AsInteger;
end;
procedure TDMCadContato.CDS_TelefoneBeforeDelete(DataSet: TDataSet);
begin
inherited;
//if not (CDS_Cadastro.State in [dsEdit, dsInsert]) then
CDS_Cadastro.Edit;
end;
procedure TDMCadContato.CDS_TelefoneBeforePost(DataSet: TDataSet);
begin
inherited;
if CDS_Telefone.State = dsInsert then
CDS_Telefone.FieldByName('CODIGO_TELEFONE').AsInteger := DMConexao.ProximoCodigo('CONTATO_TELEFONE');
end;
procedure TDMCadContato.CDS_TelefoneNewRecord(DataSet: TDataSet);
begin
inherited;
CDS_Telefone.FieldByName('CONTATO_CODCONTATO').AsInteger := CDS_Cadastro.FieldByName('CODIGO_CONTATO').AsInteger;
end;
procedure TDMCadContato.DataModuleCreate(Sender: TObject);
begin
ClasseFilha := TClassContato;
inherited;
end;
procedure TDMCadContato.DataModuleDestroy(Sender: TObject);
begin
inherited;
CDS_Endereco.Close;
CDS_Telefone.Close;
end;
end.
|
unit Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, XDebugFile, XDebugItem, ActnList, ComCtrls, VirtualTrees, Menus;
type
TNodeData = record
Data: PXItem;
end;
PNodeData = ^TNodeData;
TForm1 = class(TForm)
OpenDialog: TOpenDialog;
ActionList1: TActionList;
OpenFileAction: TAction;
StatusBar: TStatusBar;
ProgressBar: TProgressBar;
TreeView: TVirtualStringTree;
PopupMenu1: TPopupMenu;
Openfile1: TMenuItem;
Closefile1: TMenuItem;
CloseFileAction: TAction;
N1: TMenuItem;
MemoryAnalysis1: TMenuItem;
procedure OpenFileActionExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure StatusBarDrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel;
const Rect: TRect);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure TreeViewInitNode(Sender: TBaseVirtualTree; ParentNode,
Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
procedure TreeViewGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString);
procedure TreeViewPaintText(Sender: TBaseVirtualTree;
const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex;
TextType: TVSTTextType);
procedure TreeViewExpanded(Sender: TBaseVirtualTree; Node: PVirtualNode);
procedure TreeViewGetNodeDataSize(Sender: TBaseVirtualTree;
var NodeDataSize: Integer);
procedure CloseFileActionExecute(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure PopupMenu1Popup(Sender: TObject);
procedure TreeViewInitChildren(Sender: TBaseVirtualTree; Node: PVirtualNode;
var ChildCount: Cardinal);
procedure MemoryAnalysis1Click(Sender: TObject);
private
XDebugFile: XFile;
Processing: boolean;
procedure UpdateProgress(Sender: TObject; const Position: Cardinal; const Total: Cardinal);
procedure UpdateStatus(Status: string);
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses Math, Memory;
{$R *.dfm}
function FormatFloat(const X: Extended; const D: Byte = 2): String;
begin
Result := Format('%.*f', [D, X]);
end;
function FormatDecimal(D: Cardinal): String;
begin
Result := Format('%.0n', [D * 1.0]);
end;
function FormatSign(X: Integer): Char;
begin
case Sign(X) of
1: Result := '+';
-1: Result := '-';
else
Result := ' ';
end;
end;
procedure TForm1.CloseFileActionExecute(Sender: TObject);
begin
if Assigned(XDebugFile) then begin
TreeView.Clear;
XDebugFile.Free;
XDebugFile := nil;
end;
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if Assigned(XDebugFile) then
XDebugFile.Free;
end;
procedure TForm1.FormCreate(Sender: TObject);
var ProgressBarStyle: integer;
begin
ProgressBar.Parent := StatusBar;
ProgressBarStyle := GetWindowLong(ProgressBar.Handle, GWL_EXSTYLE);
ProgressBarStyle := ProgressBarStyle - WS_EX_STATICEDGE;
SetWindowLong(ProgressBar.Handle, GWL_EXSTYLE, ProgressBarStyle);
Processing := false;
end;
procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_ESCAPE then begin
if Assigned(XDebugFile) then begin
XDebugFile.Terminate;
end;
end;
end;
procedure TForm1.MemoryAnalysis1Click(Sender: TObject);
begin
MemoryForm := TMemoryForm.Create(self, XDebugFile);
MemoryForm.Show;
{
try
MemoryForm.ShowModal;
finally
MemoryForm.Free;
end;
}
end;
procedure TForm1.OpenFileActionExecute(Sender: TObject);
begin
if OpenDialog.Execute then begin
if Assigned(XDebugFile) then begin
TreeView.Clear;
XDebugFile.Free;
end;
Processing := true;
try
UpdateStatus('Opening file');
XDebugFile := Xfile.Create(OpenDialog.FileName);
XDebugFile.OnProgress := self.UpdateProgress;
UpdateStatus('Processing file');
XDebugFile.Parse;
if XDebugFile.Terminated then begin
CloseFileAction.Execute;
UpdateStatus('Processing terminated');
end else begin
UpdateStatus('Drawing tree');
TreeView.RootNodeCount := XDebugFile.Root^.ChildCount;
UpdateStatus('Ready');
end;
finally
ProgressBar.Position := 0;
Processing := false;
end;
end;
end;
procedure TForm1.PopupMenu1Popup(Sender: TObject);
begin
CloseFile1.Enabled := Assigned(XDebugFile) and not Processing;
OpenFile1.Enabled := not Processing;
end;
procedure TForm1.StatusBarDrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel;
const Rect: TRect);
begin
if Panel = StatusBar.Panels[1] then
with ProgressBar do begin
Top := Rect.Top;
Left := Rect.Left;
Width := Rect.Right - Rect.Left;
Height := Rect.Bottom - Rect.Top;
end;
end;
procedure TForm1.TreeViewExpanded(Sender: TBaseVirtualTree; Node: PVirtualNode);
begin
with (Sender as TVirtualStringTree).Header do begin
AutoFitColumns(true, smaUseColumnOption, MainColumn, MainColumn);
end;
end;
procedure TForm1.TreeViewGetNodeDataSize(Sender: TBaseVirtualTree;
var NodeDataSize: Integer);
begin
NodeDataSize := SizeOf(TNodeData);
end;
procedure TForm1.TreeViewGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString);
var NodeData: PNodeData;
Delta: cardinal;
begin
NodeData := Sender.GetNodeData(Node);
with NodeData.Data^ do
case Column of
-1, 6:
CellText := FunctionName+' ('+IntToStr(FunctionNo)+')';
0:
CellText := FormatFloat(TimeStart, 6);
1:
CellText := FormatFloat(TimeEnd, 6);
2:
CellText := FormatFloat(TimeEnd - TimeStart, 6);
3:
CellText := FormatDecimal(MemoryStart);
4:
CellText := FormatDecimal(MemoryEnd);
5: begin
if MemoryEnd = 0 then
CellText := 'FINISH'
else begin
Delta := MemoryEnd - MemoryStart;
CellText := Format('%s%.0n (%.0n) (%.0n)', [FormatSign(Delta), Abs(Delta) * 1.0, OwnMemory * 1.0, DebugMemoryUsage * 1.0]);
end;
end;
7: begin
CellText := Format('%s (%d)', [FileName, FileLine]);
if IncludeFile<>'' then
CellText := CellText + ' - ' +IncludeFile;
end;
end;
end;
procedure TForm1.TreeViewInitChildren(Sender: TBaseVirtualTree;
Node: PVirtualNode; var ChildCount: Cardinal);
var NodeData: PNodeData;
begin
NodeData := Sender.GetNodeData(Node);
ChildCount := NodeData.Data^.ChildCount;
end;
procedure TForm1.TreeViewInitNode(Sender: TBaseVirtualTree; ParentNode,
Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
var PItem: PXItem;
NodeData, ParentNodeData: PNodeData;
begin
with Sender do begin
NodeData := GetNodeData(Node);
ParentNodeData := GetNodeData(ParentNode);
end;
if Assigned(ParentNodeData) then begin
if ParentNodeData.Data^.ChildCount > Node.Index then
PItem := ParentNodeData.Data^.Children[Node.Index];
end else begin
if XDebugFile.Root^.ChildCount > Node.Index then
PItem := XDebugFile.Root^.Children[Node.Index];
InitialStates := InitialStates + [ivsExpanded];
end;
if not Assigned(PItem) then
raise Exception.Create('Could not locate node');
NodeData.Data := PItem;
if (NodeData.Data^.ChildCount > 0) then
InitialStates := InitialStates + [ivsHasChildren];
end;
procedure TForm1.TreeViewPaintText(Sender: TBaseVirtualTree;
const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex;
TextType: TVSTTextType);
var NodeData: PNodeData;
begin
NodeData := Sender.GetNodeData(Node);
if vsSelected in Node.States then
TargetCanvas.Font.Color := clHighLightText
else if NodeData.Data.FunctionType = XFT_INTERNAL then
TargetCanvas.Font.Color := clHighLight
else
TargetCanvas.Font.Color := clWindowText;
end;
procedure TForm1.UpdateProgress(Sender: TObject; const Position: Cardinal; const Total: Cardinal);
begin
ProgressBar.Max := 100;
ProgressBar.Position := Trunc(Position*100/Total);
application.ProcessMessages;
end;
procedure TForm1.UpdateStatus(Status: string);
begin
StatusBar.Panels[0].Text := Status;
end;
end.
|
unit UController;
interface
uses
Classes, SysUtils, Forms, Windows, DB, DBClient, DBXJSON, IWSystem,
Rtti, Atributos, StrUtils, TypInfo, Generics.Collections, Biblioteca,
Vcl.Dialogs, UGenericVO, UDAO;
type
TController<T: TGenericVO> = class
private
public
function Inserir(Objeto: T): integer;
function Consultar(condicao: String): TObjectList<T>;overload;
function Consultar(condicao: String; orderby:String): TObjectList<T>;overload;
function ConsultarPorId(id: integer): T;
function Alterar(Objeto: T): boolean;
function Excluir(Objeto: T): boolean;
procedure ValidarDados(Objeto:T);virtual;abstract;
end;
implementation
function TController<T>.Inserir(Objeto: T): integer;
begin
validarDados(Objeto);
Result := TDAO.Inserir(Objeto);
end;
function TController<T>.Alterar(Objeto: T): boolean;
begin
validarDados(Objeto);
Result := TDAO.Alterar(Objeto);
end;
function TController<T>.Consultar(condicao: String): TObjectList<T>;
begin
Result := TDAO.Consultar<T>(condicao,'', 0, true);
end;
function TController<T>.Consultar(condicao: String; orderby:String): TObjectList<T>;
begin
Result := TDAO.Consultar<T>(condicao,orderby, 0, true);
end;
function TController<T>.ConsultarPorId(id: integer): T;
begin
Result := TDAO.ConsultarPorId<T>(id);
end;
function TController<T>.Excluir(Objeto: T): boolean;
begin
Result := TDAO.Excluir(Objeto);
end;
end.
|
unit rtti_broker_iBroker;
interface
uses
TypInfo, Classes;
const
crbNone = 0;
crbList = 1;
crbListCounter = 2;
crbObject = 4;
crbRef = 8;
crbNotStored = 16;
crbMemo = 32;
crbBlob = 64;
type
{.$interfaces corba}
TRBDataType = (rbdtString, rbdtInteger, rbdtClass, rbdtEnumeration);
{ IRBDataItem }
IRBDataItem = interface
['{30206B79-2DC2-4A3C-AD96-70B9617EDD69}']
function GetName: string;
function GetClassName: string;
function GetIsObject: Boolean;
function GetIsList: Boolean;
function GetIsListCounter: Boolean;
function GetIsReference: Boolean;
function GetIsNotStored: Boolean;
function GetIsMemo: Boolean;
function GetDataKind: integer;
function GetTypeKind: TTypeKind;
function GetListCount: integer;
procedure SetListCount(ACount: integer);
function GetAsPersist: string;
function GetAsPersistList(AIndex: integer): string;
procedure SetAsPersist(AValue: string);
procedure SetAsPersistList(AIndex: integer; AValue: string);
function GetAsInteger: integer;
function GetAsIntegerList(AIndex: integer): integer;
function GetAsString: string;
function GetAsStringList(AIndex: integer): string;
function GetAsBoolean: Boolean;
function GetAsBooleanList(AIndex: integer): Boolean;
procedure SetAsInteger(AValue: integer);
procedure SetAsIntegerList(AIndex: integer; AValue: integer);
procedure SetAsString(AValue: string);
procedure SetAsStringList(AIndex: integer; AValue: string);
procedure SetAsBoolean(AValue: Boolean);
procedure SetAsBooleanList(AIndex: integer; AValue: Boolean);
function GetAsObject: TObject;
function GetAsObjectList(AIndex: integer): TObject;
procedure SetAsObject(AValue: TObject);
procedure SetAsObjectList(AIndex: integer; AValue: TObject);
function GetAsVariant: Variant;
function GetAsVariantList(AIndex: integer): Variant;
procedure SetAsVariant(AValue: Variant);
procedure SetAsVariantList(AIndex: integer; AValue: Variant);
function GetAsClass: TClass;
function GetEnumName(AValue: integer): string;
function GetEnumNameCount: integer;
function GetAsPtrInt: PtrInt;
procedure SetAsPtrInt(AValue: PtrInt);
function GetAsInterface: IUnknown;
procedure SetAsInterface(AValue: IUnknown);
property Name: string read GetName;
property ClassName: string read GetClassName;
property IsObject: Boolean read GetIsObject;
property IsList: Boolean read GetIsList;
property IsListCounter: Boolean read GetIsListCounter;
property IsReference: Boolean read GetIsReference;
property IsNotStored: Boolean read GetIsNotStored;
property IsMemo: Boolean read GetIsMemo;
property DataKind: integer read GetDataKind;
property TypeKind: TTypeKind read GetTypeKind;
property ListCount: Integer read GetListCount write SetListCount;
property AsPersist: string read GetAsPersist write SetAsPersist;
property AsPersistList[AIndex: integer]: string read GetAsPersistList write SetAsPersistList;
property AsString: string read GetAsString write SetAsString;
property AsStringList[AIndex: integer]: string read GetAsStringList write SetAsStringList;
property AsInteger: integer read GetAsInteger write SetAsInteger;
property AsIntegerList[AIndex: integer]: integer read GetAsIntegerList write SetAsIntegerList;
property AsBoolean: Boolean read GetAsBoolean write SetAsBoolean;
property AsBooleanList[AIndex: integer]: Boolean read GetAsBooleanList write SetAsBooleanList;
property AsObject: TObject read GetAsObject write SetAsObject;
property AsObjectList[AIndex: integer]: TObject read GetAsObjectList write SetAsObjectList;
property AsVariant: variant read GetAsVariant write SetAsVariant;
property AsVariantList[AIndex: integer]: variant read GetAsVariantList write SetAsVariantList;
property AsClass: TClass read GetAsClass;
property EnumNameCount: integer read GetEnumNameCount;
property EnumName[AValue: integer]: string read GetEnumName;
property AsPtrInt: PtrInt read GetAsPtrInt write SetAsPtrInt;
property AsInterface: IUnknown read GetAsInterface write SetAsInterface;
end;
{ IRBData }
IRBData = interface
['{2B5DE8F9-F2FA-4E5A-A0F4-15C87BFB0551}']
function GetClassName: string;
function GetClassType: TClass;
function GetCount: integer;
function GetItemByName(const AName: string): IRBDataItem;
function GetItemIndex(const AName: string): integer;
function GetItems(AIndex: integer): IRBDataItem;
function FindItem(const AName: string): IRBDataItem;
function GetUnderObject: TObject;
procedure Assign(const AData: IRBData);
property Count: integer read GetCount;
property ClassName: string read GetClassName;
property ClassType: TClass read GetClassType;
property Items[AIndex: integer]: IRBDataItem read GetItems; default;
property ItemByName[const AName: string]: IRBDataItem read GetItemByName;
property ItemIndex[const AName: string]: integer read GetItemIndex;
property UnderObject: TObject read GetUnderObject;
end;
{ IRBDataText }
IRBDataText = interface
['{1D0EDB6E-3CA5-47DA-952A-A6106F9B8604}']
end;
{ IRBDataNumber }
IRBDataNumber = interface
['{5B9B3622-D44D-4692-B19D-8553B19AAE97}']
end;
{ IRBDataOffer }
IRBDataOffer = interface
['{2BF8E862-02A9-4351-BE26-97A119E0EE74}']
function GetCount: integer;
function GetName: string;
property Count: integer read GetCount;
property Name: string read GetName;
end;
{ IRBDataList }
IRBDataList = interface
['{CD6765BF-F11E-4FFE-938F-A3D41DFC5307}']
function GetCount: integer;
function GetItems(AIndex: integer): TObject;
function GetAsData(AIndex: integer): IRBData;
procedure Add(AObject: TObject);
procedure Insert(ARow: integer; AObject: TObject);
procedure AddData(AData: IRBData);
procedure InsertData(ARow: integer; AData: IRBData);
procedure Delete(AIndex: integer);
property Items[AIndex: integer]: TObject read GetItems; default;
property Count: integer read GetCount;
property AsData[AIndex: integer]: IRBData read GetAsData;
end;
IRBDataQuery = interface
['{1C4AF71B-C3FB-11E3-B4AE-08002721C44F}']
function Retrive(const AClass: string): IRBDataList;
end;
{ IRBFactory }
IRBFactory = interface
['{231BD5BD-DB2B-49DD-9A19-BB9788475F37}']
procedure RegisterClass(const AClass: TClass);
function CreateObject(const AClass: string): TObject;
function FindClass(const AClass: String): TClass;
end;
{ IRBStore }
IRBStore = interface
['{90F80CF8-362E-479E-A22D-8D7586E5E66C}']
procedure Save(AData: TObject);
procedure Save(AData: IRBData);
function Load(const AClass: string; const AProperty, AValue: string): TObject;
function LoadList(const AClass: string): IRBDataList;
procedure Flush;
procedure Delete(AData: TObject);
procedure Delete(AData: IRBData);
end;
{ IRBPersistClassRegister }
IRBPersistClassRegister = interface
['{DBF4A7EB-50EC-4328-B248-5BF998BFADD5}']
procedure Add(const AClass: TPersistentClass);
function GetCount: integer;
function GetItem(AIndex: integer): TPersistentClass;
property Item[AIndex: integer]: TPersistentClass read GetItem; default;
property Count: integer read GetCount;
end;
implementation
end.
|
unit LrColor;
interface
uses
SysUtils, Graphics;
type
TRgb24 = Record
b, g, r: Byte;
end;
//
TRgb32 = Record
case Integer of
0: (r, g, b, a: Byte);
1: (c: TColor);
end;
//
TRgbf = Record
r, g, b: Single;
end;
//
EColorError = CLASS(Exception);
function MixColors(const inColor0, inColor1: TColor; inMix: Single): TColor;
function MultColors(const inColor0, inColor1: TColor): TColor;
function ColorSetHue(const inColor: TColor; inHue: Word): TColor;
function ColorSetLum(const inColor: TColor; inLum: Word): TColor;
function Colorize(const inSource, inColor: TColor): TColor;
implementation
uses
Math, GraphUtil;
{$R-}
function ColorToRgb24(const inColor: TColor;
inScalar1024: Integer = 0): TRgb24;
begin
with TRgb24(Pointer(@inColor)^) do
begin
Result.r := b;
Result.g := g;
Result.b := r;
end;
end;
function Clamp(inByte: Integer): Byte;
begin
if (inByte < 0) then
Result := 0
else if (inByte > 255) then
Result := 255
else
Result := inByte;
end;
function ScaledColorToRgb24(const inColor: TColor;
inScalar1024: Integer = 0): TRgb24;
begin
with TRgb24(Pointer(@inColor)^) do
begin
Result.r := Clamp((b * inScalar1024) shr 10);
Result.g := Clamp((g * inScalar1024) shr 10);
Result.b := Clamp((r * inScalar1024) shr 10);
end;
end;
function MixColors(const inColor0, inColor1: TColor; inMix: Single): TColor;
var
omm: Single;
c0, c1: TRgb32;
begin
omm := 1 - inMix;
c0.c := inColor0;
c1.c := inColor1;
with c0 do
begin
r := Round(c1.r * inMix + r * omm);
g := Round(c1.g * inMix + g * omm);
b := Round(c1.b * inMix + b * omm);
end;
Result := c0.c;
//Result := clYellow;
end;
function MultColors(const inColor0, inColor1: TColor): TColor;
var
c0, c1: TRgb32;
begin
c0.c := inColor0;
c1.c := inColor1;
with c0 do
begin
r := Clamp(r * c1.r{ div 255});
g := Clamp(g * c1.g{ div 255});
b := Clamp(b * c1.b{ div 255});
end;
Result := c0.c;
end;
function ColorToRgbf(const inColor: TColor): TRgbf;
begin
with TRgb32(Pointer(@inColor)^) do
begin
Result.r := r / 255;
Result.g := g / 255;
Result.b := b / 255;
end;
end;
function RgbfToColor(const inRgbf: TRgbf): TColor;
var
r32: TRgb32;
begin
with r32 do
begin
r := Round(inRgbf.r * 255);
g := Round(inRgbf.g * 255);
b := Round(inRgbf.b * 255);
end;
Result := r32.c;
end;
function Colorize(const inSource, inColor: TColor): TColor;
var
sh, sl, ss, ch, cl, cs: Word;
begin
ColorRGBToHLS(inSource, sh, sl, ss);
ColorRGBToHLS(inColor, ch, cl, cs);
if (cs = 0) then
ss := cs;
Result := ColorHLSToRGB(ch, sl, ss);
end;
function ColorSetHue(const inColor: TColor; inHue: Word): TColor;
var
h, l, s: Word;
begin
ColorRGBToHLS(inColor, h, l, s);
Result := ColorHLSToRGB(inHue, l, s);
end;
function ColorSetLum(const inColor: TColor; inLum: Word): TColor;
var
h, l, s: Word;
begin
ColorRGBToHLS(inColor, h, l, s);
Result := ColorHLSToRGB(h, inLum, s);
end;
end.
|
unit DataModuleBanco;
interface
uses
System.SysUtils, System.Classes, Data.DBXMySQL, ZAbstractConnection,Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
ZConnection, Data.DB, Data.SqlExpr, ZAbstractRODataset, ZAbstractDataset,
ZDataset, uParamsConexao;
type
TBanco = class(TDataModule)
SQLConnection1: TSQLConnection;
zConnectionMySql: TZConnection;
ZQryTables: TZQuery;
ZQryTablesTABLE_NAME: TWideStringField;
ZQryPesquisa: TZQuery;
ZQryTablesCOLUMN_NAME: TWideStringField;
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Class Function GetInstanse : TBanco;
end;
var
Banco: TBanco;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TBanco }
procedure TBanco.DataModuleCreate(Sender: TObject);
var
CaminhoDLL : String;
begin
CaminhoDLL := extractfilepath(Application.ExeName)+'libmysql.dll';
if FileExists(CaminhoDLL) then
begin
zConnectionMySql.LibraryLocation := CaminhoDLL;
end;
end;
class function TBanco.GetInstanse: TBanco;
begin
if Banco = nil then
begin
Banco := TBanco.Create(nil);
end;
Result := Banco;
end;
end.
|
unit uSetPrtJrnlParams;
{*******************************************************************************
* *
* Название модуля : *
* *
* uSetPrtJrnlParams *
* *
* Назначение модуля : *
* *
* Диалог выбора параметров печати журнала. *
* *
* Copyright © Год 2006, Автор: Найдёнов Е.А *
* *
*******************************************************************************}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, FIBQuery, pFIBQuery,
pFIBStoredProc, DB, FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase,
cxControls, cxContainer, cxEdit, cxCheckBox, cxTextEdit, cxMaskEdit,
cxDropDownEdit, cxMRUEdit, frxClass, frxDBSet, uneTypes, cxSpinEdit,
frxExportPDF, frxExportImage, frxExportRTF, frxExportXML, frxExportXLS,
frxExportHTML, frxExportTXT;
type
//Перечисляемый тип для определения типа преобразований
TEnm_TypeCoversion = ( ctIntToSet, ctSetToInt );
TfmSetPrtJrnlParams = class(TForm)
dbWork : TpFIBDatabase;
trRead : TpFIBTransaction;
trWrite : TpFIBTransaction;
dstWork : TpFIBDataSet;
spcWork : TpFIBStoredProc;
btnOK : TcxButton;
btnCancel : TcxButton;
gbxPeriod : TGroupBox;
gbxParamsPrtJrnl : TGroupBox;
cbxSCH : TcxCheckBox;
cbxSmet : TcxCheckBox;
cbxRazd : TcxCheckBox;
cbxStat : TcxCheckBox;
cbxKekv : TcxCheckBox;
cbxGrSmet : TcxCheckBox;
cbxSubSCH : TcxCheckBox;
lblYear : TLabel;
lblMonth : TLabel;
edtYear : TcxSpinEdit;
edtMonth : TcxMRUEdit;
frdsWork : TfrxDBDataset;
frrWork: TfrxReport;
frxTXTExport1: TfrxTXTExport;
frxHTMLExport1: TfrxHTMLExport;
frxXLSExport1: TfrxXLSExport;
frxXMLExport1: TfrxXMLExport;
frxRTFExport1: TfrxRTFExport;
frxBMPExport1: TfrxBMPExport;
frxJPEGExport1: TfrxJPEGExport;
frxTIFFExport1: TfrxTIFFExport;
frxPDFExport1: TfrxPDFExport;
procedure FormShortCut (var Msg: TWMKey; var Handled: Boolean);
procedure cbxSCHClick (Sender: TObject);
procedure frrWorkGetValue (const VarName: String; var Value: Variant);
procedure edtYearPropertiesChange (Sender: TObject);
procedure edtYearPropertiesValidate (Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean);
private
FDateBeg : TDateTime;
FDateEnd : TDateTime;
FParamCount : Integer;
FCurrPeriod : TDateTime;
FSysOptions : TRec_SysOptions;
FPrtJrnlParams : TSet_PrtJrnlParams;
function GetDateBeg : TDateTime;
function GetDateEnd : TDateTime;
function GetParamCount : Integer;
function GetCurrPeriod : TDateTime;
function GetSysOptions : TRec_SysOptions;
function GetPrtJrnlParams : TSet_PrtJrnlParams;
procedure SetDateBeg ( aValue: TDateTime );
procedure SetDateEnd ( aValue: TDateTime );
procedure SetParamCount ( aValue: Integer );
procedure SetCurrPeriod ( aValue: TDateTime );
procedure SetPrtJrnlParams ( aValue: TSet_PrtJrnlParams );
public
constructor Create( const aDBFMParams: TRec_DBFMParams; const aSysOptions: TRec_SysOptions ); reintroduce;
procedure SetYears;
procedure FillMonthList( var aMonthList: TStringList; const aFillMode: TFillMode );
property pDateBeg : TDateTime read GetDateBeg write SetDateBeg;
property pDateEnd : TDateTime read GetDateEnd write SetDateEnd;
property pParamCount : Integer read GetParamCount write SetParamCount;
property pCurrPeriod : TDateTime read GetCurrPeriod write SetCurrPeriod;
Property pSysOptions : TRec_SysOptions read GetSysOptions;
Property pPrtJrnlParams : TSet_PrtJrnlParams read GetPrtJrnlParams write SetPrtJrnlParams;
end;
procedure PrintJournal ( const aDBFMParams: TRec_DBFMParams; const aSysOptions: TRec_SysOptions ); stdcall;
procedure ConvertPrtJrnlParams ( var aParamValue: Integer; var aParamSet: TSet_PrtJrnlParams; const aTypeCoversion: TEnm_TypeCoversion );
exports
PrintJournal;
implementation
uses DateUtils, uneUtils;
resourcestring
//Названия локальных переменных отчета
sFRN_Year = 'Year';
sFRN_Month = 'Month';
sFRN_Period = 'Period';
const
cMaxParamCount = 2;
{$R *.dfm}
procedure ConvertPrtJrnlParams( var aParamValue: Integer; var aParamSet: TSet_PrtJrnlParams; const aTypeCoversion: TEnm_TypeCoversion );
{*******************************************************************************
* *
* Название процедуры : *
* *
* ConvertPrtJrnlParams *
* *
* Назначение процедуры : *
* *
* Преобразование числового значения параметра печати журнала в соответствующее*
* значение перечислимого типа. Для коректной работы процедуры критично: *
* значения свойств Tag компонентов TcxCheckBox; последовательность эл-ов *
* перечислимого типа. *
* *
* IN: *
* *
* aParamSet - значение перечислимого типа параметра печати. *
* aParamValue - числовое значение параметра печати. *
* aTypeCoversion - тип преобразований вышеописанных значений. *
* *
* OUT: *
* *
* aParamSet - значение перечислимого типа параметра печати. *
* aParamValue - числовое значение параметра печати. *
* *
*******************************************************************************}
var
i, vCount : Integer;
vParamValueStr : String;
begin
try
case aTypeCoversion of
ctIntToSet : begin
vParamValueStr := IntToStr( aParamValue );
case Length( vParamValueStr ) of
1 : begin
aParamSet := [ TEnm_PrtJrnlParams(0), TEnm_PrtJrnlParams( StrToInt( vParamValueStr[1] ) ) ];
end;
cMaxParamCount : begin
aParamSet := [ TEnm_PrtJrnlParams( StrToInt( vParamValueStr[1] ) ), TEnm_PrtJrnlParams( StrToInt( vParamValueStr[2] ) ) ];
end;
end;
end;
ctSetToInt : begin
vParamValueStr := '';
vCount := Ord( High( TEnm_PrtJrnlParams ) );
for i := 0 to vCount
do begin
if TEnm_PrtJrnlParams(i) in aParamSet
then begin
vParamValueStr := vParamValueStr + IntToStr(i);
end;
end;
aParamValue := StrToInt( vParamValueStr );
end;
end;
except
on E: Exception
do begin
case aTypeCoversion of
ctIntToSet : begin
aParamSet := [];
end;
ctSetToInt : begin
aParamValue := -1;
end;
end;
MessageBox( 0, PChar( sErrorTextExtUA + E.Message ), PChar( sMsgCaptionErrUA ), MB_OK or MB_ICONERROR );
end;
end;
end; //End of procedure ConvertPrtJrnlParams
function TfmSetPrtJrnlParams.GetDateBeg: TDateTime;
begin
Result := FDateBeg;
end;
function TfmSetPrtJrnlParams.GetDateEnd: TDateTime;
begin
Result := FDateEnd;
end;
function TfmSetPrtJrnlParams.GetParamCount: Integer;
begin
Result := FParamCount;
end;
function TfmSetPrtJrnlParams.GetCurrPeriod: TDateTime;
begin
Result := FCurrPeriod;
end;
function TfmSetPrtJrnlParams.GetSysOptions: TRec_SysOptions;
begin
Result := FSysOptions;
end;
function TfmSetPrtJrnlParams.GetPrtJrnlParams: TSet_PrtJrnlParams;
begin
Result := FPrtJrnlParams;
end;
procedure TfmSetPrtJrnlParams.SetDateBeg(aValue: TDateTime);
begin
FDateBeg := aValue;
end;
procedure TfmSetPrtJrnlParams.SetDateEnd(aValue: TDateTime);
begin
FDateEnd := aValue;
end;
procedure TfmSetPrtJrnlParams.SetParamCount(aValue: Integer);
begin
FParamCount := aValue;
end;
procedure TfmSetPrtJrnlParams.SetCurrPeriod(aValue: TDateTime);
begin
FCurrPeriod := aValue;
end;
procedure TfmSetPrtJrnlParams.SetPrtJrnlParams(aValue: TSet_PrtJrnlParams);
begin
FPrtJrnlParams := aValue;
end;
//Печатаем журнал
procedure PrintJournal( const aDBFMParams: TRec_DBFMParams; const aSysOptions: TRec_SysOptions );
var
i, n : Integer;
ModRes : Integer;
CaseKey : Integer;
fmParams : TfmSetPrtJrnlParams;
AppHandle : THandle;
LogFileName : String;
KS_SaldoOborot : Int64;
KS_Korrespondent : Int64;
begin
try
try
try
fmParams := TfmSetPrtJrnlParams.Create( aDBFMParams, aSysOptions );
AppHandle := fmParams.pSysOptions.AppHandle;
LogFileName := fmParams.pSysOptions.LogFileName;
ModRes := fmParams.ShowModal;
if ModRes = mrOK
then begin
//Оператор не явл. лишним, поскольку в теле экпортируемой ф-ции не видны составляющие класса
with fmParams
do begin
Hide;
//Получаем дату, соответствующую выбранному пользователем периоду
n := High( cMonthUA );
for i := Low( cMonthUA ) to n
do begin
if edtMonth.Text = cMonthUA[i] then Break;
end;
pCurrPeriod := EncodeDate( StrToInt( edtYear.Text ), i + 1, cFIRST_DAY_OF_MONTH );
//Заполняем буфер данными для расчета сальдо и оборотов
spcWork.StoredProcName := 'JO5_PREPARE_BUFFER_SALDO_OBOROT';
spcWork.ParamByName('IN_CURR_PERIOD').AsDate := pCurrPeriod;
try
trWrite.StartTransaction;
spcWork.Prepare;
spcWork.ExecProc;
KS_SaldoOborot := spcWork.FN('OUT_KEY_SESSION').AsInt64;
//Заполняем буфер данными для расшифровки корреспонденции
spcWork.StoredProcName := 'JO5_PREPARE_BUFFER_KOR_PRT_JNRL';
spcWork.ParamByName('IN_CURR_PERIOD').AsDate := pCurrPeriod;
spcWork.Prepare;
spcWork.ExecProc;
KS_Korrespondent := spcWork.FN('OUT_KEY_SESSION').AsInt64;
finally
trWrite.Commit;
spcWork.Close;
end;
//Получаем текущее значение ключа выбора для данного контрагента
ConvertPrtJrnlParams( CaseKey, FPrtJrnlParams, ctSetToInt );
//Получаем информацию для печати
if dstWork.Active then dstWork.Close;
dstWork.SQLs.SelectSQL.Text := 'SELECT* FROM JO5_GET_DATA_FOR_PRT_JOURNAL(' + cTICK + DateToStr( pCurrPeriod ) + cTICK + cSEMICOLON + IntToStr( CaseKey ) + cSEMICOLON + IntToStr( KS_SaldoOborot ) + cSEMICOLON + IntToStr( KS_Korrespondent ) + cBRAKET_CL + ' ORDER BY OUT_LVL_0_NUMBER, OUT_LVL_1_NUMBER, OUT_KOR_SCH_NUMBER';
dstWork.Open;
//Загружаем шаблон файла отчёта
if frrWork.LoadFromFile('Reports\JO5\JO5_PRT_JOURNAL.fr3')
then begin
//Показываем шаблон файла отчёта
frrWork.PrepareReport;
frrWork.ShowPreparedReport;
end
else begin
MessageBox( Handle, PChar( 'Файл отчета ' + 'Reports\JO5\JO5_PRT_JOURNAL.fr3' + ' не найден!' ), PChar( sMsgCaptionWrnUA ), MB_OK or MB_ICONWARNING );
end;
//Очищаем буфер
spcWork.StoredProcName := 'JO5_BUFFER_DEL';
spcWork.ParamByName('IN_KEY_SESSION').AsInt64 := KS_SaldoOborot;
try
trWrite.StartTransaction;
spcWork.Prepare;
spcWork.ExecProc;
spcWork.ParamByName('IN_KEY_SESSION').AsInt64 := KS_Korrespondent;
spcWork.ExecProc;
finally
trWrite.Commit;
spcWork.Close;
end;
end;
end;
finally
if fmParams <> nil then FreeAndNil( fmParams );
end;
except
//Протоколируем ИС
LogException( LogFileName );
Raise;
end;
except
on E: Exception
do begin
MessageBox( AppHandle, PChar( sErrorTextExtUA + E.Message ), PChar( sMsgCaptionErrUA ), MB_OK or MB_ICONERROR );
end;
end;
end;
constructor TfmSetPrtJrnlParams.Create(const aDBFMParams: TRec_DBFMParams;
const aSysOptions: TRec_SysOptions);
var
i, j, n, k : Integer;
begin
try
try
inherited Create( aDBFMParams.Owner );
FSysOptions := aSysOptions;
ConvertPrtJrnlParams( FSysOptions.DefCaseKey, FPrtJrnlParams, ctIntToSet );
//Выставляем умалчиваемые значения переключателей
n := Ord( High( TEnm_PrtJrnlParams ) );
k := gbxParamsPrtJrnl.ControlCount - 1;
for i := 0 to n
do begin
if TEnm_PrtJrnlParams(i) in pPrtJrnlParams
then begin
for j := 0 to k
do begin
if ( gbxParamsPrtJrnl.Controls[j] is TcxCheckBox )
AND ( gbxParamsPrtJrnl.Controls[j].Tag = i )
then begin
TcxCheckBox( gbxParamsPrtJrnl.Controls[j] ).Checked := True;
Break;
end;
end; //End of Loop for controls
end;
end; //End of Loop for Enumerated elements
//Выставляем значения свойств
with aSysOptions
do begin
SetDateBeg( DateFirstImport );
SetDateEnd( DateCurrPeriod );
SetCurrPeriod( DateCurrPeriod );
end;
dbWork.Handle := aDBFMParams.DBHandle;
trRead.StartTransaction;
SetYears;
except
//Протоколируем ИС
LogException( pSysOptions.LogFileName );
Raise;
end;
except
on E: Exception
do begin
MessageBox( Handle, PChar( sErrorTextExtUA + E.Message ), PChar( sMsgCaptionErrUA ), MB_OK or MB_ICONERROR );
end;
end;
end;
//Получаем допустимый набор лет
procedure TfmSetPrtJrnlParams.SetYears;
begin
try
try
if pDateBeg <= pDateEnd
then begin
//Формируем допустимый диапазон для интервала лет
edtYear.Properties.MinValue := YearOf ( pDateBeg );
edtYear.Properties.MaxValue := YearOf ( pDateEnd );
edtYear.Text := IntToStr( YearOf( pCurrPeriod ) );
end;
except
//Протоколируем ИС
LogException( pSysOptions.LogFileName );
Raise;
end;
except
on E: Exception
do begin
MessageBox( Handle, PChar( sErrorTextExtUA + E.Message ), PChar( sMsgCaptionErrUA ), MB_OK or MB_ICONERROR );
end;
end;
end;
//Получаем допустимый набор месяцев
procedure TfmSetPrtJrnlParams.FillMonthList(var aMonthList: TStringList; const aFillMode: TFillMode );
var
i, n : Integer;
begin
try
try
case aFillMode of
fmInc : begin
n := High( cMonthUA );
for i := ( MonthOf(pDateBeg) - 1 ) to n
do begin
aMonthList.Add( cMonthUA[i] )
end;
end;
fmDec : begin
n := ( MonthOf(pDateEnd) - 1 );
for i := Low( cMonthUA ) to n
do begin
aMonthList.Add( cMonthUA[i] )
end;
end;
fmFull : begin
n := High( cMonthUA );
for i := Low( cMonthUA ) to n
do begin
aMonthList.Add( cMonthUA[i] )
end;
end;
end;
except
//Протоколируем ИС
LogException( pSysOptions.LogFileName );
Raise;
end;
except
on E: Exception
do begin
MessageBox( Handle, PChar( sErrorTextExtUA + E.Message ), PChar( sMsgCaptionErrUA ), MB_OK or MB_ICONERROR );
end;
end;
end;
//Обрабатываем горячие клавиши
procedure TfmSetPrtJrnlParams.FormShortCut(var Msg: TWMKey;
var Handled: Boolean);
begin
case Msg.CharCode of
VK_F10 : begin
ModalResult := mrOk;
Handled := True;
end;
VK_ESCAPE : begin
ModalResult := mrCancel;
Handled := True;
end;
end;
end;
//Получаем допустимый набор периодов печати журнала
procedure TfmSetPrtJrnlParams.edtYearPropertiesChange(Sender: TObject);
var
FillMode : TFillMode;
YearBeg : Word;
YearEnd : Word;
CurrYear : Word;
MonthList : TStringList;
IndexSearch : Integer;
begin
try
try
YearBeg := YearOf ( pDateBeg );
YearEnd := YearOf ( pDateEnd );
CurrYear := StrToInt( edtYear.Text );
edtMonth.Properties.LookupItems.Clear;
try
MonthList := TStringList.Create;
if ( YearBeg < CurrYear ) AND ( CurrYear < YearEnd )
then begin
FillMode := fmFull;
FillMonthList( MonthList, FillMode );
edtMonth.Properties.LookupItems.AddStrings( MonthList );
IndexSearch := edtMonth.Properties.LookupItems.IndexOf( cMonthUA[MonthOf( pCurrPeriod ) - 1] );
if IndexSearch = -1
then begin
edtMonth.Text := edtMonth.Properties.LookupItems.Strings[0];
end
else begin
edtMonth.Text := cMonthUA[MonthOf( pCurrPeriod ) - 1]
end;
end
else begin
if YearBeg = CurrYear
then begin
FillMode := fmInc;
FillMonthList( MonthList, FillMode );
edtMonth.Properties.LookupItems.AddStrings( MonthList );
IndexSearch := edtMonth.Properties.LookupItems.IndexOf( cMonthUA[MonthOf( pCurrPeriod ) - 1] );
if IndexSearch = -1
then begin
edtMonth.Text := edtMonth.Properties.LookupItems.Strings[0];
end
else begin
edtMonth.Text := cMonthUA[MonthOf( pCurrPeriod ) - 1]
end;
end
else
if CurrYear = YearEnd
then begin
FillMode := fmDec;
FillMonthList( MonthList, FillMode );
edtMonth.Properties.LookupItems.AddStrings( MonthList );
IndexSearch := edtMonth.Properties.LookupItems.IndexOf( cMonthUA[MonthOf( pCurrPeriod ) - 1] );
if IndexSearch = -1
then begin
edtMonth.Text := edtMonth.Properties.LookupItems.Strings[edtMonth.Properties.LookupItems.Count - 1];
end
else begin
edtMonth.Text := cMonthUA[MonthOf( pCurrPeriod ) - 1]
end;
end
end;
finally
if MonthList <> nil then FreeAndNil( MonthList );
end;
except
//Протоколируем ИС
LogException( pSysOptions.LogFileName );
Raise;
end;
except
on E: Exception
do begin
MessageBox( Handle, PChar( sErrorTextExtUA + E.Message ), PChar( sMsgCaptionErrUA ), MB_OK or MB_ICONERROR );
end;
end;
end;
//Активируем(деактивируем) элементы выбора параметров печатной формы
procedure TfmSetPrtJrnlParams.cbxSCHClick(Sender: TObject);
var
i, vCount : Integer;
begin
//Изменяем значение счетчика выбранных параметров
if ( Sender is TcxCheckBox )
then begin
if TcxCheckBox( Sender ).Checked
then begin
Inc( FParamCount );
if not( TEnm_PrtJrnlParams( TcxCheckBox( Sender ).Tag ) in pPrtJrnlParams )
then begin
Include( FPrtJrnlParams, TEnm_PrtJrnlParams( TcxCheckBox( Sender ).Tag ) );
end;
end
else begin
Dec( FParamCount );
if TEnm_PrtJrnlParams( TcxCheckBox( Sender ).Tag ) in pPrtJrnlParams
then begin
Exclude( FPrtJrnlParams, TEnm_PrtJrnlParams( TcxCheckBox( Sender ).Tag ) );
end;
end;
//Активируем(деактивируем) элементы выбора
vCount := gbxParamsPrtJrnl.ControlCount - 1 ;
if pParamCount >= cMaxParamCount
then begin
//Деактивируем элементы выбора
for i := 0 to vCount
do begin
if ( gbxParamsPrtJrnl.Controls[i] is TcxCheckBox )
then
if not TcxCheckBox( gbxParamsPrtJrnl.Controls[i] ).Checked
AND TcxCheckBox( gbxParamsPrtJrnl.Controls[i] ).Enabled
then begin
TcxCheckBox( gbxParamsPrtJrnl.Controls[i] ).Enabled := False;
end;
end;
end
else begin
//Активируем элементы выбора
for i := 0 to vCount
do begin
if ( gbxParamsPrtJrnl.Controls[i] is TcxCheckBox )
then
if not TcxCheckBox( gbxParamsPrtJrnl.Controls[i] ).Checked
AND not TcxCheckBox( gbxParamsPrtJrnl.Controls[i] ).Enabled
then begin
TcxCheckBox( gbxParamsPrtJrnl.Controls[i] ).Enabled := True;
end;
end;
end;
end;
end;
//Обрабатываем ввод недопустимого значения года
procedure TfmSetPrtJrnlParams.edtYearPropertiesValidate(Sender: TObject;
var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean);
begin
if TcxSpinEdit( Sender ).Properties.MinValue > DisplayValue
then begin
DisplayValue := TcxSpinEdit( Sender ).Properties.MinValue;
Error := False;
end;
if TcxSpinEdit( Sender ).Properties.MaxValue < DisplayValue
then begin
DisplayValue := TcxSpinEdit( Sender ).Properties.MaxValue;
Error := False;
end;
end;
//Получаем значения для динамических переменных отчета
procedure TfmSetPrtJrnlParams.frrWorkGetValue(const VarName: String;
var Value: Variant);
var
CurrMonth : String;
begin
//Получаем название месяца для заголовка отчет
if CompareText( VarName, sFRN_Period ) = 0
then begin
CurrMonth := cMonthUA[ MonthOf( pCurrPeriod ) - 1 ];
Value := CurrMonth + ' ' + IntToStr( YearOf( pCurrPeriod ) ) + ' ' + 'г.'
end;
//Получаем название месяца для заголовка страницы отчет
if CompareText( VarName, sFRN_Month ) = 0
then begin
CurrMonth := cMonthUA[ MonthOf( pCurrPeriod ) - 1 ];
Value := CurrMonth;
end;
//Получаем год для заголовка страницы отчет
if CompareText( VarName, sFRN_Year ) = 0
then begin
Value := YearOf( pCurrPeriod );
end;
end;
end.
|
(*
Category: SWAG Title: MATH ROUTINES
Original name: 0044.PAS
Description: PATTERNS
Author: WILLIAM SCHROEDER
Date: 11-02-93 10:30
*)
{
WILLIAM SCHROEDER
I'd like to extend thanks to everyone For helping me set up a PATTERN Program.
Yes, I have done it! Unfortunatley, this Program doesn't have all possible
pattern searches, but I figured out an algorithm For increasing size geometric
patterns such as 2 4 7 11. The formula produced is as follows: N = the Nth
term. So whatever the formula, if you want to find an Nth term, get out some
paper and replace N! :) Well, here's the Program, folks. I hope somebody can
make some improvements on it...
}
Program PatternFinder;
Uses
Crt;
Var
ans : Char;
PatType : Byte;
n1, n2,
n3, n4 : Integer;
Procedure GetInput;
begin
ClrScr;
TextColor(lightcyan);
Writeln('This Program finds patterns For numbers in increasing size.');
Write('Enter the first four terms in order: ');
TextColor(yellow);
readln(n1, n2, n3, n4);
end;
Procedure TestRelations;
begin
PatType := 0;
{ 1 3 5 }
if (n3 - n2 = n2 - n1) and ((n4 - n3) = n2 - n1) then
PatType := 1
else
{ 1 3 9 }
if (n3 / n2) = (n4 / n3) then
PatType := 2
else
{ 1 1 2 }
if (n3 = n2 + n1) and (n4 = (n3 + n2)) then
PatType := 3
else
{ 1 2 4 7 11 }
if ((n4 - n3) - (n3 - n2)) = ((n3 - n2) - (n2 - n1)) then
PatType := 4;
end;
Procedure FindFormula;
Procedure DoGeoCalc;
Var
Factor : Real;
Dif,
Shift,
tempn,
nx, ny : Integer;
begin
Dif := (n3 - n2) - (n2 - n1);
Factor := Dif * 0.5;
Shift := 0;
ny := n2;
nx := n1;
if ny > nx then
While (ny-nx) <> dif do
begin
Inc(Shift);
tempn := nx;
nx := nx - ((ny - nx) - dif);
ny := tempn;
end;
if Factor <> 1 then
Write('(', Factor : 0 : 1, ')');
if Shift = 0 then
Write('(N + 0)(N - 1)')
else
begin
if Shift > 0 then
begin
Write('(N + ', shift, ')(N');
if Shift = 1 then
Write(')')
else
Write(' + ', shift - 1, ')');
end;
end;
if nx <> 0 then
Writeln(' + ', nx)
else
Writeln;
end;
begin
TextColor(LightGreen);
Writeln('Formula =');
TextColor(white);
Case PatType of
1 :
begin
{ Nth term = first term + difference * (N - 1) }
if n2 - n1 = 0 then
Writeln(n1)
else
if (n2 - n1 = 1) and (n1 - 1 = 0) then
Writeln('N')
else
if n2 - n1 = 1 then
Writeln('N + ', n1 - 1)
else
if (n2 - n1) = n1 then
Writeln(n1, 'N')
else
Writeln(n2 - n1, '(N - 1) + ', n1);
end;
2 :
begin
{ Nth term = first term * ratio^(N - 1) }
if n1 = 1 then
Writeln(n2 / n1 : 0 : 0, '^(N - 1)')
else
Writeln(n1, ' x ', n2 / n1 : 0 : 0, '^(N - 1)');
end;
3 :
begin
{ Fibonacci Sequence }
Writeln('No formula: Fibonacci Sequence (Term1 + Term2 = Term3)');
Writeln(' ',
n1 : 5, ' + ', n2 : 5, ' = ', (n1 + n2) : 5);
end;
4 :
begin
{ Geometric Patterns }
DoGeoCalc;
end;
end;
end;
begin
GetInput;
TestRelations;
TextColor(LightRed);
Writeln;
if PatType <> 0 then
FindFormula
else
Writeln('No pattern found: This Program may not know how to look '+
'for that pattern.');
TextColor(lightred);
Writeln;
Write('Press any key...');
ans := ReadKey;
ClrScr;
end.
{
That's all folks! if you can find and fix any bugs For me, please send me that
section of the code so I can change it. if anybody cares to ADD to the pattern
check, be my guest! This Program can be altered and used by ANYBODY. I'd just
like to expand it a bit. Have fun!
}
|
unit Logger;
interface
uses
LoggerDep;
type
ILogger = interface(IInterface)
['{04E3D497-0CA3-429B-8723-95AA1DA2DFC2}']
procedure LogIt;
end;
TLogger = class(TInterfacedObject, ILogger)
private
fLoggerGui: ILoggerGui;
public
constructor Create(ALoggerGui: ILoggerGui);
destructor Destroy; override;
procedure LogIt;
end;
implementation
uses
Dialogs;
constructor TLogger.Create(ALoggerGui: ILoggerGui);
begin
inherited Create;
fLoggerGui := ALoggerGui;
end;
destructor TLogger.Destroy;
begin
inherited Destroy;
end;
procedure TLogger.LogIt;
begin
fLoggerGui.Show('A Logger Message');
end;
end.
|
unit o_CopyFile;
interface
uses
System.Classes, System.SysUtils, Winapi.Windows, Winapi.Messages;
type
TCopyCallBack = function( TotalFileSize, TotalBytesTransferred, StreamSize, StreamBytesTransferred: int64;
StreamNumber, CallbackReason: Dword;
SourceFile, DestinationFile: THandle; Data: Pointer): DWord;
type
TCopyFile = class
private
public
fCallBack: TCopyCallBack;
procedure CopyFile(aSource, aDest: TStrings);
property CallBack: TCopyCallBack read fCallBack write fCallBack;
end;
implementation
{ Tfrm_CopyFile }
procedure TCopyFile.CopyFile(aSource, aDest: TStrings);
var
Cancelled: Boolean;
begin
Cancelled := false;
CopyFileEx(PWideChar(aSource), PWideChar(aSource), @fCallBack, nil, @Cancelled, COPY_FILE_FAIL_IF_EXISTS);
end;
end.
|
{==============================================================================|
| Project : Ararat Synapse | 004.015.007 |
|==============================================================================|
| Content: support procedures and functions |
|==============================================================================|
| Copyright (c)1999-2017, Lukas Gebauer |
| All rights reserved. |
| |
| Redistribution and use in source and binary forms, with or without |
| modification, are permitted provided that the following conditions are met: |
| |
| Redistributions of source code must retain the above copyright notice, this |
| list of conditions and the following disclaimer. |
| |
| Redistributions in binary form must reproduce the above copyright notice, |
| this list of conditions and the following disclaimer in the documentation |
| and/or other materials provided with the distribution. |
| |
| Neither the name of Lukas Gebauer nor the names of its contributors may |
| be used to endorse or promote products derived from this software without |
| specific prior written permission. |
| |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR |
| ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
| DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR |
| SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
| CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
| LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY |
| OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH |
| DAMAGE. |
|==============================================================================|
| The Initial Developer of the Original Code is Lukas Gebauer (Czech Republic).|
| Portions created by Lukas Gebauer are Copyright (c) 1999-2017. |
| Portions created by Hernan Sanchez are Copyright (c) 2000. |
| Portions created by Petr Fejfar are Copyright (c)2011-2012. |
| All Rights Reserved. |
|==============================================================================|
| Contributor(s): |
| Hernan Sanchez (hernan.sanchez@iname.com) |
| Tomas Hajny (OS2 support) |
| Radek Cervinka (POSIX support) |
|==============================================================================|
| History: see HISTORY.HTM from distribution package |
| (Found at URL: http://www.ararat.cz/synapse/) |
|==============================================================================}
{:@abstract(Support procedures and functions)}
{$I jedi.inc} // load common compiler defines
{$Q-}
{$R-}
{$H+}
{$IFDEF UNICODE}
{$WARN IMPLICIT_STRING_CAST OFF}
{$WARN IMPLICIT_STRING_CAST_LOSS OFF}
{$WARN SUSPICIOUS_TYPECAST OFF}
{$ENDIF}
unit synautil;
interface
uses
{$IFDEF MSWINDOWS}
Windows,
{$ELSE MSWINDOWS}
{$IFDEF FPC}
{$IFDEF OS2}
Dos, TZUtil,
{$ELSE OS2}
UnixUtil, Unix, BaseUnix,
{$ENDIF OS2}
{$ELSE FPC}
{$IFDEF POSIX}
Posix.Base, Posix.Time, Posix.SysTypes, Posix.SysTime, Posix.Stdio,
{$ELSE}
Libc,
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$IFDEF CIL}
System.IO,
{$ENDIF}
SysUtils, Classes, SynaFpc;
{$IFDEF VER100}
type
int64 = integer;
{$ENDIF}
{$IFDEF POSIX}
type
TTimeVal = Posix.SysTime.timeval;
Ttimezone = record
tz_minuteswest: Integer ; // minutes west of Greenwich
tz_dsttime: integer ; // type of DST correction
end;
PTimeZone = ^Ttimezone;
{$ENDIF}
{:Return your timezone bias from UTC time in minutes.}
function TimeZoneBias: integer;
{:Return your timezone bias from UTC time in string representation like "+0200".}
function TimeZone: string;
{:Returns current time in format defined in RFC-822. Useful for SMTP messages,
but other protocols use this time format as well. Results contains the timezone
specification. Four digit year is used to break any Y2K concerns. (Example
'Fri, 15 Oct 1999 21:14:56 +0200')}
function Rfc822DateTime(t: TDateTime): string;
{:Returns date and time in format defined in C compilers in format "mmm dd hh:nn:ss"}
function CDateTime(t: TDateTime): string;
{:Returns date and time in format defined in format 'yymmdd hhnnss'}
function SimpleDateTime(t: TDateTime): string;
{:Returns date and time in format defined in ANSI C compilers in format
"ddd mmm d hh:nn:ss yyyy" }
function AnsiCDateTime(t: TDateTime): string;
{:Decode three-letter string with name of month to their month number. If string
not match any month name, then is returned 0. For parsing are used predefined
names for English, French and German and names from system locale too.}
function GetMonthNumber(Value: String): integer;
{:Return decoded time from given string. Time must be witch separator ':'. You
can use "hh:mm" or "hh:mm:ss".}
function GetTimeFromStr(Value: string): TDateTime;
{:Decode string representation of TimeZone (CEST, GMT, +0200, -0800, etc.)
to timezone offset.}
function DecodeTimeZone(Value: string; var Zone: integer): Boolean;
{:Decode string in format "m-d-y" to TDateTime type.}
function GetDateMDYFromStr(Value: string): TDateTime;
{:Decode various string representations of date and time to Tdatetime type.
This function do all timezone corrections too! This function can decode lot of
formats like:
@longcode(#
ddd, d mmm yyyy hh:mm:ss
ddd, d mmm yy hh:mm:ss
ddd, mmm d yyyy hh:mm:ss
ddd mmm dd hh:mm:ss yyyy #)
and more with lot of modifications, include:
@longcode(#
Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() Format
#)
Timezone corrections known lot of symbolic timezone names (like CEST, EDT, etc.)
or numeric representation (like +0200). By convention defined in RFC timezone
+0000 is GMT and -0000 is current your system timezone.}
function DecodeRfcDateTime(Value: string): TDateTime;
{:Return current system date and time in UTC timezone.}
function GetUTTime: TDateTime;
{:Set Newdt as current system date and time in UTC timezone. This function work
only if you have administrator rights!}
function SetUTTime(Newdt: TDateTime): Boolean;
{:Return current value of system timer with precizion 1 millisecond. Good for
measure time difference.}
function GetTick: LongWord;
{:Return difference between two timestamps. It working fine only for differences
smaller then maxint. (difference must be smaller then 24 days.)}
function TickDelta(TickOld, TickNew: LongWord): LongWord;
{:Return two characters, which ordinal values represents the value in byte
format. (High-endian)}
function CodeInt(Value: Word): Ansistring;
{:Decodes two characters located at "Index" offset position of the "Value"
string to Word values.}
function DecodeInt(const Value: Ansistring; Index: Integer): Word;
{:Return four characters, which ordinal values represents the value in byte
format. (High-endian)}
function CodeLongInt(Value: LongInt): Ansistring;
{:Decodes four characters located at "Index" offset position of the "Value"
string to LongInt values.}
function DecodeLongInt(const Value: Ansistring; Index: Integer): LongInt;
{:Dump binary buffer stored in a string to a result string.}
function DumpStr(const Buffer: Ansistring): string;
{:Dump binary buffer stored in a string to a result string. All bytes with code
of character is written as character, not as hexadecimal value.}
function DumpExStr(const Buffer: Ansistring): string;
{:Dump binary buffer stored in a string to a file with DumpFile filename.}
procedure Dump(const Buffer: AnsiString; DumpFile: string);
{:Dump binary buffer stored in a string to a file with DumpFile filename. All
bytes with code of character is written as character, not as hexadecimal value.}
procedure DumpEx(const Buffer: AnsiString; DumpFile: string);
{:Like TrimLeft, but remove only spaces, not control characters!}
function TrimSPLeft(const S: string): string;
{:Like TrimRight, but remove only spaces, not control characters!}
function TrimSPRight(const S: string): string;
{:Like Trim, but remove only spaces, not control characters!}
function TrimSP(const S: string): string;
{:Returns a portion of the "Value" string located to the left of the "Delimiter"
string. If a delimiter is not found, results is original string.}
function SeparateLeft(const Value, Delimiter: string): string;
{:Returns the portion of the "Value" string located to the right of the
"Delimiter" string. If a delimiter is not found, results is original string.}
function SeparateRight(const Value, Delimiter: string): string;
{:Returns parameter value from string in format:
parameter1="value1"; parameter2=value2}
function GetParameter(const Value, Parameter: string): string;
{:parse value string with elements differed by Delimiter into stringlist.}
procedure ParseParametersEx(Value, Delimiter: string; const Parameters: TStrings);
{:parse value string with elements differed by ';' into stringlist.}
procedure ParseParameters(Value: string; const Parameters: TStrings);
{:Index of string in stringlist with same beginning as Value is returned.}
function IndexByBegin(Value: string; const List: TStrings): integer;
{:Returns only the e-mail portion of an address from the full address format.
i.e. returns 'nobody@@somewhere.com' from '"someone" <nobody@@somewhere.com>'}
function GetEmailAddr(const Value: string): string;
{:Returns only the description part from a full address format. i.e. returns
'someone' from '"someone" <nobody@@somewhere.com>'}
function GetEmailDesc(Value: string): string;
{:Returns a string with hexadecimal digits representing the corresponding values
of the bytes found in "Value" string.}
function StrToHex(const Value: Ansistring): string;
{:Returns a string of binary "Digits" representing "Value".}
function IntToBin(Value: Integer; Digits: Byte): string;
{:Returns an integer equivalent of the binary string in "Value".
(i.e. ('10001010') returns 138)}
function BinToInt(const Value: string): Integer;
{:Parses a URL to its various components.}
function ParseURL(URL: string; var Prot, User, Pass, Host, Port, Path,
Para: string): string;
{:Replaces all "Search" string values found within "Value" string, with the
"Replace" string value.}
function ReplaceString(Value, Search, Replace: AnsiString): AnsiString;
{:It is like RPos, but search is from specified possition.}
function RPosEx(const Sub, Value: string; From: integer): Integer;
{:It is like POS function, but from right side of Value string.}
function RPos(const Sub, Value: String): Integer;
{:Like @link(fetch), but working with binary strings, not with text.}
function FetchBin(var Value: string; const Delimiter: string): string;
{:Fetch string from left of Value string.}
function Fetch(var Value: string; const Delimiter: string): string;
{:Fetch string from left of Value string. This function ignore delimitesr inside
quotations.}
function FetchEx(var Value: string; const Delimiter, Quotation: string): string;
{:If string is binary string (contains non-printable characters), then is
returned true.}
function IsBinaryString(const Value: AnsiString): Boolean;
{:return position of string terminator in string. If terminator found, then is
returned in terminator parameter.
Possible line terminators are: CRLF, LFCR, CR, LF}
function PosCRLF(const Value: AnsiString; var Terminator: AnsiString): integer;
{:Delete empty strings from end of stringlist.}
Procedure StringsTrim(const value: TStrings);
{:Like Pos function, buf from given string possition.}
function PosFrom(const SubStr, Value: String; From: integer): integer;
{$IFNDEF CIL}
{:Increase pointer by value.}
function IncPoint(const p: pointer; Value: integer): pointer;
{$ENDIF}
{:Get string between PairBegin and PairEnd. This function respect nesting.
For example:
@longcode(#
Value is: 'Hi! (hello(yes!))'
pairbegin is: '('
pairend is: ')'
In this case result is: 'hello(yes!)'#)}
function GetBetween(const PairBegin, PairEnd, Value: string): string;
{:Return count of Chr in Value string.}
function CountOfChar(const Value: string; Chr: char): integer;
{:Remove quotation from Value string. If Value is not quoted, then return same
string without any modification. }
function UnquoteStr(const Value: string; Quote: Char): string;
{:Quote Value string. If Value contains some Quote chars, then it is doubled.}
function QuoteStr(const Value: string; Quote: Char): string;
{:Convert lines in stringlist from 'name: value' form to 'name=value' form.}
procedure HeadersToList(const Value: TStrings);
{:Convert lines in stringlist from 'name=value' form to 'name: value' form.}
procedure ListToHeaders(const Value: TStrings);
{:swap bytes in integer.}
function SwapBytes(Value: integer): integer;
{:read string with requested length form stream.}
function ReadStrFromStream(const Stream: TStream; len: integer): AnsiString;
{:write string to stream.}
procedure WriteStrToStream(const Stream: TStream; Value: AnsiString);
{:Return filename of new temporary file in Dir (if empty, then default temporary
directory is used) and with optional filename prefix.}
function GetTempFile(const Dir, prefix: String): String;
{:Return padded string. If length is greater, string is truncated. If length is
smaller, string is padded by Pad character.}
function PadString(const Value: AnsiString; len: integer; Pad: AnsiChar): AnsiString;
{:XOR each byte in the strings}
function XorString(Indata1, Indata2: AnsiString): AnsiString;
{:Read header from "Value" stringlist beginning at "Index" position. If header
is Splitted into multiple lines, then this procedure de-split it into one line.}
function NormalizeHeader(Value: TStrings; var Index: Integer): string;
{pf}
{:Search for one of line terminators CR, LF or NUL. Return position of the
line beginning and length of text.}
procedure SearchForLineBreak(var APtr:PANSIChar; AEtx:PANSIChar; out ABol:PANSIChar; out ALength:integer);
{:Skip both line terminators CR LF (if any). Move APtr position forward.}
procedure SkipLineBreak(var APtr:PANSIChar; AEtx:PANSIChar);
{:Skip all blank lines in a buffer starting at APtr and move APtr position forward.}
procedure SkipNullLines (var APtr:PANSIChar; AEtx:PANSIChar);
{:Copy all lines from a buffer starting at APtr to ALines until empty line
or end of the buffer is reached. Move APtr position forward).}
procedure CopyLinesFromStreamUntilNullLine(var APtr:PANSIChar; AEtx:PANSIChar; ALines:TStrings);
{:Copy all lines from a buffer starting at APtr to ALines until ABoundary
or end of the buffer is reached. Move APtr position forward).}
procedure CopyLinesFromStreamUntilBoundary(var APtr:PANSIChar; AEtx:PANSIChar; ALines:TStrings; const ABoundary:ANSIString);
{:Search ABoundary in a buffer starting at APtr.
Return beginning of the ABoundary. Move APtr forward behind a trailing CRLF if any).}
function SearchForBoundary (var APtr:PANSIChar; AEtx:PANSIChar; const ABoundary:ANSIString): PANSIChar;
{:Compare a text at position ABOL with ABoundary and return position behind the
match (including a trailing CRLF if any).}
function MatchBoundary (ABOL,AETX:PANSIChar; const ABoundary:ANSIString): PANSIChar;
{:Compare a text at position ABOL with ABoundary + the last boundary suffix
and return position behind the match (including a trailing CRLF if any).}
function MatchLastBoundary (ABOL,AETX:PANSIChar; const ABoundary:ANSIString): PANSIChar;
{:Copy data from a buffer starting at position APtr and delimited by AEtx
position into ANSIString.}
function BuildStringFromBuffer (AStx,AEtx:PANSIChar): ANSIString;
{/pf}
var
{:can be used for your own months strings for @link(getmonthnumber)}
CustomMonthNames: array[1..12] of string;
implementation
{==============================================================================}
const
MyDayNames: array[1..7] of AnsiString =
('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
var
MyMonthNames: array[0..6, 1..12] of String =
(
('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', //rewrited by system locales
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'),
('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', //English
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'),
('jan', 'fév', 'mar', 'avr', 'mai', 'jun', //French
'jul', 'aoû', 'sep', 'oct', 'nov', 'déc'),
('jan', 'fev', 'mar', 'avr', 'mai', 'jun', //French#2
'jul', 'aou', 'sep', 'oct', 'nov', 'dec'),
('Jan', 'Feb', 'Mar', 'Apr', 'Mai', 'Jun', //German
'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'),
('Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', //German#2
'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'),
('Led', 'Úno', 'Bøe', 'Dub', 'Kvì', 'Èen', //Czech
'Èec', 'Srp', 'Záø', 'Øíj', 'Lis', 'Pro')
);
{==============================================================================}
function TimeZoneBias: integer;
{$IFNDEF MSWINDOWS}
{$IFNDEF FPC}
var
{$IFDEF POSIX}
t: Posix.SysTypes.time_t;
UT: Posix.time.tm;
{$ELSE}
t: TTime_T;
UT: TUnixTime;
{$ENDIF}
begin
{$IFDEF POSIX}
__time(T);
localtime_r(T, UT);
Result := UT.tm_gmtoff div 60;
{$ELSE}
__time(@T);
localtime_r(@T, UT);
Result := ut.__tm_gmtoff div 60;
{$ENDIF}
{$ELSE}
begin
Result := TZSeconds div 60;
{$ENDIF}
{$ELSE}
var
zoneinfo: TTimeZoneInformation;
bias: Integer;
begin
case GetTimeZoneInformation(Zoneinfo) of
2:
bias := zoneinfo.Bias + zoneinfo.DaylightBias;
1:
bias := zoneinfo.Bias + zoneinfo.StandardBias;
else
bias := zoneinfo.Bias;
end;
Result := bias * (-1);
{$ENDIF}
end;
{==============================================================================}
function TimeZone: string;
var
bias: Integer;
h, m: Integer;
begin
bias := TimeZoneBias;
if bias >= 0 then
Result := '+'
else
Result := '-';
bias := Abs(bias);
h := bias div 60;
m := bias mod 60;
Result := Result + Format('%.2d%.2d', [h, m]);
end;
{==============================================================================}
function Rfc822DateTime(t: TDateTime): string;
var
wYear, wMonth, wDay: word;
begin
DecodeDate(t, wYear, wMonth, wDay);
Result := Format('%s, %d %s %s %s', [MyDayNames[DayOfWeek(t)], wDay,
MyMonthNames[1, wMonth], FormatDateTime('yyyy hh":"nn":"ss', t), TimeZone]);
end;
{==============================================================================}
function CDateTime(t: TDateTime): string;
var
wYear, wMonth, wDay: word;
begin
DecodeDate(t, wYear, wMonth, wDay);
Result:= Format('%s %2d %s', [MyMonthNames[1, wMonth], wDay,
FormatDateTime('hh":"nn":"ss', t)]);
end;
{==============================================================================}
function SimpleDateTime(t: TDateTime): string;
begin
Result := FormatDateTime('yymmdd hhnnss', t);
end;
{==============================================================================}
function AnsiCDateTime(t: TDateTime): string;
var
wYear, wMonth, wDay: word;
begin
DecodeDate(t, wYear, wMonth, wDay);
Result := Format('%s %s %d %s', [MyDayNames[DayOfWeek(t)], MyMonthNames[1, wMonth],
wDay, FormatDateTime('hh":"nn":"ss yyyy ', t)]);
end;
{==============================================================================}
function DecodeTimeZone(Value: string; var Zone: integer): Boolean;
var
x: integer;
zh, zm: integer;
s: string;
begin
Result := false;
s := Value;
if (Pos('+', s) = 1) or (Pos('-',s) = 1) then
begin
if s = '-0000' then
Zone := TimeZoneBias
else
if Length(s) > 4 then
begin
zh := StrToIntdef(s[2] + s[3], 0);
zm := StrToIntdef(s[4] + s[5], 0);
zone := zh * 60 + zm;
if s[1] = '-' then
zone := zone * (-1);
end;
Result := True;
end
else
begin
x := 32767;
if s = 'NZDT' then x := 13;
if s = 'IDLE' then x := 12;
if s = 'NZST' then x := 12;
if s = 'NZT' then x := 12;
if s = 'EADT' then x := 11;
if s = 'GST' then x := 10;
if s = 'JST' then x := 9;
if s = 'CCT' then x := 8;
if s = 'WADT' then x := 8;
if s = 'WAST' then x := 7;
if s = 'ZP6' then x := 6;
if s = 'ZP5' then x := 5;
if s = 'ZP4' then x := 4;
if s = 'BT' then x := 3;
if s = 'EET' then x := 2;
if s = 'MEST' then x := 2;
if s = 'MESZ' then x := 2;
if s = 'SST' then x := 2;
if s = 'FST' then x := 2;
if s = 'CEST' then x := 2;
if s = 'CET' then x := 1;
if s = 'FWT' then x := 1;
if s = 'MET' then x := 1;
if s = 'MEWT' then x := 1;
if s = 'SWT' then x := 1;
if s = 'UT' then x := 0;
if s = 'UTC' then x := 0;
if s = 'GMT' then x := 0;
if s = 'WET' then x := 0;
if s = 'WAT' then x := -1;
if s = 'BST' then x := -1;
if s = 'AT' then x := -2;
if s = 'ADT' then x := -3;
if s = 'AST' then x := -4;
if s = 'EDT' then x := -4;
if s = 'EST' then x := -5;
if s = 'CDT' then x := -5;
if s = 'CST' then x := -6;
if s = 'MDT' then x := -6;
if s = 'MST' then x := -7;
if s = 'PDT' then x := -7;
if s = 'PST' then x := -8;
if s = 'YDT' then x := -8;
if s = 'YST' then x := -9;
if s = 'HDT' then x := -9;
if s = 'AHST' then x := -10;
if s = 'CAT' then x := -10;
if s = 'HST' then x := -10;
if s = 'EAST' then x := -10;
if s = 'NT' then x := -11;
if s = 'IDLW' then x := -12;
if x <> 32767 then
begin
zone := x * 60;
Result := True;
end;
end;
end;
{==============================================================================}
function GetMonthNumber(Value: String): integer;
var
n: integer;
function TestMonth(Value: String; Index: Integer): Boolean;
var
n: integer;
begin
Result := False;
for n := 0 to 6 do
if Value = AnsiUppercase(MyMonthNames[n, Index]) then
begin
Result := True;
Break;
end;
end;
begin
Result := 0;
Value := AnsiUppercase(Value);
for n := 1 to 12 do
if TestMonth(Value, n) or (Value = AnsiUppercase(CustomMonthNames[n])) then
begin
Result := n;
Break;
end;
end;
{==============================================================================}
function GetTimeFromStr(Value: string): TDateTime;
var
x: integer;
begin
x := rpos(':', Value);
if (x > 0) and ((Length(Value) - x) > 2) then
Value := Copy(Value, 1, x + 2);
Value := ReplaceString(Value, ':', {$IFDEF COMPILER15_UP}FormatSettings.{$ENDIF}TimeSeparator);
Result := -1;
try
Result := StrToTime(Value);
except
on Exception do ;
end;
end;
{==============================================================================}
function GetDateMDYFromStr(Value: string): TDateTime;
var
wYear, wMonth, wDay: word;
s: string;
begin
Result := 0;
s := Fetch(Value, '-');
wMonth := StrToIntDef(s, 12);
s := Fetch(Value, '-');
wDay := StrToIntDef(s, 30);
wYear := StrToIntDef(Value, 1899);
if wYear < 1000 then
if (wYear > 99) then
wYear := wYear + 1900
else
if wYear > 50 then
wYear := wYear + 1900
else
wYear := wYear + 2000;
try
Result := EncodeDate(wYear, wMonth, wDay);
except
on Exception do ;
end;
end;
{==============================================================================}
function DecodeRfcDateTime(Value: string): TDateTime;
var
day, month, year: Word;
zone: integer;
x, y: integer;
s: string;
t: TDateTime;
begin
// ddd, d mmm yyyy hh:mm:ss
// ddd, d mmm yy hh:mm:ss
// ddd, mmm d yyyy hh:mm:ss
// ddd mmm dd hh:mm:ss yyyy
// Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
// Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
// Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() Format
Result := 0;
if Value = '' then
Exit;
day := 0;
month := 0;
year := 0;
zone := 0;
Value := ReplaceString(Value, ' -', ' #');
Value := ReplaceString(Value, '-', ' ');
Value := ReplaceString(Value, ' #', ' -');
while Value <> '' do
begin
s := Fetch(Value, ' ');
s := uppercase(s);
// timezone
if DecodetimeZone(s, x) then
begin
zone := x;
continue;
end;
x := StrToIntDef(s, 0);
// day or year
if x > 0 then
if (x < 32) and (day = 0) then
begin
day := x;
continue;
end
else
begin
if (year = 0) and ((month > 0) or (x > 12)) then
begin
year := x;
if year < 32 then
year := year + 2000;
if year < 1000 then
year := year + 1900;
continue;
end;
end;
// time
if rpos(':', s) > Pos(':', s) then
begin
t := GetTimeFromStr(s);
if t <> -1 then
Result := t;
continue;
end;
//timezone daylight saving time
if s = 'DST' then
begin
zone := zone + 60;
continue;
end;
// month
y := GetMonthNumber(s);
if (y > 0) and (month = 0) then
month := y;
end;
if year = 0 then
year := 1980;
if month < 1 then
month := 1;
if month > 12 then
month := 12;
if day < 1 then
day := 1;
x := MonthDays[IsLeapYear(year), month];
if day > x then
day := x;
Result := Result + Encodedate(year, month, day);
zone := zone - TimeZoneBias;
x := zone div 1440;
Result := Result - x;
zone := zone mod 1440;
t := EncodeTime(Abs(zone) div 60, Abs(zone) mod 60, 0, 0);
if zone < 0 then
t := 0 - t;
Result := Result - t;
end;
{==============================================================================}
function GetUTTime: TDateTime;
{$IFDEF MSWINDOWS}
{$IFNDEF FPC}
var
st: TSystemTime;
begin
GetSystemTime(st);
result := SystemTimeToDateTime(st);
{$ELSE}
var
st: SysUtils.TSystemTime;
stw: Windows.TSystemTime;
begin
GetSystemTime(stw);
st.Year := stw.wYear;
st.Month := stw.wMonth;
st.Day := stw.wDay;
st.Hour := stw.wHour;
st.Minute := stw.wMinute;
st.Second := stw.wSecond;
st.Millisecond := stw.wMilliseconds;
result := SystemTimeToDateTime(st);
{$ENDIF}
{$ELSE MSWINDOWS}
{$IFNDEF FPC}
var
TV: TTimeVal;
begin
gettimeofday(TV, nil);
Result := UnixDateDelta + (TV.tv_sec + TV.tv_usec / 1000000) / 86400;
{$ELSE FPC}
{$IFDEF UNIX}
var
TV: TimeVal;
begin
fpgettimeofday(@TV, nil);
Result := UnixDateDelta + (TV.tv_sec + TV.tv_usec / 1000000) / 86400;
{$ELSE UNIX}
{$IFDEF OS2}
var
ST: TSystemTime;
begin
GetLocalTime (ST);
Result := SystemTimeToDateTime (ST);
{$ENDIF OS2}
{$ENDIF UNIX}
{$ENDIF FPC}
{$ENDIF MSWINDOWS}
end;
{==============================================================================}
function SetUTTime(Newdt: TDateTime): Boolean;
{$IFDEF MSWINDOWS}
{$IFNDEF FPC}
var
st: TSystemTime;
begin
DateTimeToSystemTime(newdt,st);
Result := SetSystemTime(st);
{$ELSE}
var
st: SysUtils.TSystemTime;
stw: Windows.TSystemTime;
begin
DateTimeToSystemTime(newdt,st);
stw.wYear := st.Year;
stw.wMonth := st.Month;
stw.wDay := st.Day;
stw.wHour := st.Hour;
stw.wMinute := st.Minute;
stw.wSecond := st.Second;
stw.wMilliseconds := st.Millisecond;
Result := SetSystemTime(stw);
{$ENDIF}
{$ELSE MSWINDOWS}
{$IFNDEF FPC}
var
TV: TTimeVal;
d: double;
TZ: Ttimezone;
PZ: PTimeZone;
begin
TZ.tz_minuteswest := 0;
TZ.tz_dsttime := 0;
PZ := @TZ;
gettimeofday(TV, PZ);
d := (newdt - UnixDateDelta) * 86400;
TV.tv_sec := trunc(d);
TV.tv_usec := trunc(frac(d) * 1000000);
{$IFNDEF POSIX}
Result := settimeofday(TV, TZ) <> -1;
{$ELSE}
Result := False; // in POSIX settimeofday is not defined? http://www.kernel.org/doc/man-pages/online/pages/man2/gettimeofday.2.html
{$ENDIF}
{$ELSE FPC}
{$IFDEF UNIX}
var
TV: TimeVal;
d: double;
begin
d := (newdt - UnixDateDelta) * 86400;
TV.tv_sec := trunc(d);
TV.tv_usec := trunc(frac(d) * 1000000);
Result := fpsettimeofday(@TV, nil) <> -1;
{$ELSE UNIX}
{$IFDEF OS2}
var
ST: TSystemTime;
begin
DateTimeToSystemTime (NewDT, ST);
SetTime (ST.Hour, ST.Minute, ST.Second, ST.Millisecond div 10);
Result := true;
{$ENDIF OS2}
{$ENDIF UNIX}
{$ENDIF FPC}
{$ENDIF MSWINDOWS}
end;
{==============================================================================}
{$IFNDEF MSWINDOWS}
function GetTick: LongWord;
var
Stamp: TTimeStamp;
begin
Stamp := DateTimeToTimeStamp(Now);
Result := Stamp.Time;
end;
{$ELSE}
function GetTick: LongWord;
var
tick, freq: TLargeInteger;
{$IFDEF VER100}
x: TLargeInteger;
{$ENDIF}
begin
if Windows.QueryPerformanceFrequency(freq) then
begin
Windows.QueryPerformanceCounter(tick);
{$IFDEF VER100}
x.QuadPart := (tick.QuadPart / freq.QuadPart) * 1000;
Result := x.LowPart;
{$ELSE}
Result := Trunc((tick / freq) * 1000) and High(LongWord)
{$ENDIF}
end
else
Result := Windows.GetTickCount;
end;
{$ENDIF}
{==============================================================================}
function TickDelta(TickOld, TickNew: LongWord): LongWord;
begin
//if DWord is signed type (older Deplhi),
// then it not work properly on differencies larger then maxint!
Result := 0;
if TickOld <> TickNew then
begin
if TickNew < TickOld then
begin
TickNew := TickNew + LongWord(MaxInt) + 1;
TickOld := TickOld + LongWord(MaxInt) + 1;
end;
Result := TickNew - TickOld;
if TickNew < TickOld then
if Result > 0 then
Result := 0 - Result;
end;
end;
{==============================================================================}
function CodeInt(Value: Word): Ansistring;
begin
setlength(result, 2);
result[1] := AnsiChar(Value div 256);
result[2] := AnsiChar(Value mod 256);
// Result := AnsiChar(Value div 256) + AnsiChar(Value mod 256)
end;
{==============================================================================}
function DecodeInt(const Value: Ansistring; Index: Integer): Word;
var
x, y: Byte;
begin
if Length(Value) > Index then
x := Ord(Value[Index])
else
x := 0;
if Length(Value) >= (Index + 1) then
y := Ord(Value[Index + 1])
else
y := 0;
Result := x * 256 + y;
end;
{==============================================================================}
function CodeLongInt(Value: Longint): Ansistring;
var
x, y: word;
begin
// this is fix for negative numbers on systems where longint = integer
x := (Value shr 16) and integer($ffff);
y := Value and integer($ffff);
setlength(result, 4);
result[1] := AnsiChar(x div 256);
result[2] := AnsiChar(x mod 256);
result[3] := AnsiChar(y div 256);
result[4] := AnsiChar(y mod 256);
end;
{==============================================================================}
function DecodeLongInt(const Value: Ansistring; Index: Integer): LongInt;
var
x, y: Byte;
xl, yl: Byte;
begin
if Length(Value) > Index then
x := Ord(Value[Index])
else
x := 0;
if Length(Value) >= (Index + 1) then
y := Ord(Value[Index + 1])
else
y := 0;
if Length(Value) >= (Index + 2) then
xl := Ord(Value[Index + 2])
else
xl := 0;
if Length(Value) >= (Index + 3) then
yl := Ord(Value[Index + 3])
else
yl := 0;
Result := ((x * 256 + y) * 65536) + (xl * 256 + yl);
end;
{==============================================================================}
function DumpStr(const Buffer: Ansistring): string;
var
n: Integer;
begin
Result := '';
for n := 1 to Length(Buffer) do
Result := Result + ' +#$' + IntToHex(Ord(Buffer[n]), 2);
end;
{==============================================================================}
function DumpExStr(const Buffer: Ansistring): string;
var
n: Integer;
x: Byte;
begin
Result := '';
for n := 1 to Length(Buffer) do
begin
x := Ord(Buffer[n]);
if x in [65..90, 97..122] then
Result := Result + ' +''' + char(x) + ''''
else
Result := Result + ' +#$' + IntToHex(Ord(Buffer[n]), 2);
end;
end;
{==============================================================================}
procedure Dump(const Buffer: AnsiString; DumpFile: string);
var
f: Text;
begin
AssignFile(f, DumpFile);
if FileExists(DumpFile) then
DeleteFile(DumpFile);
Rewrite(f);
try
Writeln(f, DumpStr(Buffer));
finally
CloseFile(f);
end;
end;
{==============================================================================}
procedure DumpEx(const Buffer: AnsiString; DumpFile: string);
var
f: Text;
begin
AssignFile(f, DumpFile);
if FileExists(DumpFile) then
DeleteFile(DumpFile);
Rewrite(f);
try
Writeln(f, DumpExStr(Buffer));
finally
CloseFile(f);
end;
end;
{==============================================================================}
function TrimSPLeft(const S: string): string;
var
I, L: Integer;
begin
Result := '';
if S = '' then
Exit;
L := Length(S);
I := 1;
while (I <= L) and (S[I] = ' ') do
Inc(I);
Result := Copy(S, I, Maxint);
end;
{==============================================================================}
function TrimSPRight(const S: string): string;
var
I: Integer;
begin
Result := '';
if S = '' then
Exit;
I := Length(S);
while (I > 0) and (S[I] = ' ') do
Dec(I);
Result := Copy(S, 1, I);
end;
{==============================================================================}
function TrimSP(const S: string): string;
begin
Result := TrimSPLeft(s);
Result := TrimSPRight(Result);
end;
{==============================================================================}
function SeparateLeft(const Value, Delimiter: string): string;
var
x: Integer;
begin
x := Pos(Delimiter, Value);
if x < 1 then
Result := Value
else
Result := Copy(Value, 1, x - 1);
end;
{==============================================================================}
function SeparateRight(const Value, Delimiter: string): string;
var
x: Integer;
begin
x := Pos(Delimiter, Value);
if x > 0 then
x := x + Length(Delimiter) - 1;
Result := Copy(Value, x + 1, Length(Value) - x);
end;
{==============================================================================}
function GetParameter(const Value, Parameter: string): string;
var
s: string;
v: string;
begin
Result := '';
v := Value;
while v <> '' do
begin
s := Trim(FetchEx(v, ';', '"'));
if Pos(Uppercase(parameter), Uppercase(s)) = 1 then
begin
Delete(s, 1, Length(Parameter));
s := Trim(s);
if s = '' then
Break;
if s[1] = '=' then
begin
Result := Trim(SeparateRight(s, '='));
Result := UnquoteStr(Result, '"');
break;
end;
end;
end;
end;
{==============================================================================}
procedure ParseParametersEx(Value, Delimiter: string; const Parameters: TStrings);
var
s: string;
begin
Parameters.Clear;
while Value <> '' do
begin
s := Trim(FetchEx(Value, Delimiter, '"'));
Parameters.Add(s);
end;
end;
{==============================================================================}
procedure ParseParameters(Value: string; const Parameters: TStrings);
begin
ParseParametersEx(Value, ';', Parameters);
end;
{==============================================================================}
function IndexByBegin(Value: string; const List: TStrings): integer;
var
n: integer;
s: string;
begin
Result := -1;
Value := uppercase(Value);
for n := 0 to List.Count -1 do
begin
s := UpperCase(List[n]);
if Pos(Value, s) = 1 then
begin
Result := n;
Break;
end;
end;
end;
{==============================================================================}
function GetEmailAddr(const Value: string): string;
var
s: string;
begin
s := SeparateRight(Value, '<');
s := SeparateLeft(s, '>');
Result := Trim(s);
end;
{==============================================================================}
function GetEmailDesc(Value: string): string;
var
s: string;
begin
Value := Trim(Value);
s := SeparateRight(Value, '"');
if s <> Value then
s := SeparateLeft(s, '"')
else
begin
s := SeparateLeft(Value, '<');
if s = Value then
begin
s := SeparateRight(Value, '(');
if s <> Value then
s := SeparateLeft(s, ')')
else
s := '';
end;
end;
Result := Trim(s);
end;
{==============================================================================}
function StrToHex(const Value: Ansistring): string;
var
n: Integer;
begin
Result := '';
for n := 1 to Length(Value) do
Result := Result + IntToHex(Byte(Value[n]), 2);
Result := LowerCase(Result);
end;
{==============================================================================}
function IntToBin(Value: Integer; Digits: Byte): string;
var
x, y, n: Integer;
begin
Result := '';
x := Value;
repeat
y := x mod 2;
x := x div 2;
if y > 0 then
Result := '1' + Result
else
Result := '0' + Result;
until x = 0;
x := Length(Result);
for n := x to Digits - 1 do
Result := '0' + Result;
end;
{==============================================================================}
function BinToInt(const Value: string): Integer;
var
n: Integer;
begin
Result := 0;
for n := 1 to Length(Value) do
begin
if Value[n] = '0' then
Result := Result * 2
else
if Value[n] = '1' then
Result := Result * 2 + 1
else
Break;
end;
end;
{==============================================================================}
function ParseURL(URL: string; var Prot, User, Pass, Host, Port, Path,
Para: string): string;
var
x, y: Integer;
sURL: string;
s: string;
s1, s2: string;
begin
Prot := 'http';
User := '';
Pass := '';
Port := '80';
Para := '';
x := Pos('://', URL);
if x > 0 then
begin
Prot := SeparateLeft(URL, '://');
sURL := SeparateRight(URL, '://');
end
else
sURL := URL;
if UpperCase(Prot) = 'HTTPS' then
Port := '443';
if UpperCase(Prot) = 'FTP' then
Port := '21';
x := Pos('@', sURL);
y := Pos('/', sURL);
if (x > 0) and ((x < y) or (y < 1))then
begin
s := SeparateLeft(sURL, '@');
sURL := SeparateRight(sURL, '@');
x := Pos(':', s);
if x > 0 then
begin
User := SeparateLeft(s, ':');
Pass := SeparateRight(s, ':');
end
else
User := s;
end;
x := Pos('/', sURL);
if x > 0 then
begin
s1 := SeparateLeft(sURL, '/');
s2 := SeparateRight(sURL, '/');
end
else
begin
s1 := sURL;
s2 := '';
end;
if Pos('[', s1) = 1 then
begin
Host := Separateleft(s1, ']');
Delete(Host, 1, 1);
s1 := SeparateRight(s1, ']');
if Pos(':', s1) = 1 then
Port := SeparateRight(s1, ':');
end
else
begin
x := Pos(':', s1);
if x > 0 then
begin
Host := SeparateLeft(s1, ':');
Port := SeparateRight(s1, ':');
end
else
Host := s1;
end;
Result := '/' + s2;
x := Pos('?', s2);
if x > 0 then
begin
Path := '/' + SeparateLeft(s2, '?');
Para := SeparateRight(s2, '?');
end
else
Path := '/' + s2;
if Host = '' then
Host := 'localhost';
end;
{==============================================================================}
function ReplaceString(Value, Search, Replace: AnsiString): AnsiString;
var
x, l, ls, lr: Integer;
begin
if (Value = '') or (Search = '') then
begin
Result := Value;
Exit;
end;
ls := Length(Search);
lr := Length(Replace);
Result := '';
x := Pos(Search, Value);
while x > 0 do
begin
{$IFNDEF CIL}
l := Length(Result);
SetLength(Result, l + x - 1);
Move(Pointer(Value)^, Pointer(@Result[l + 1])^, x - 1);
{$ELSE}
Result:=Result+Copy(Value,1,x-1);
{$ENDIF}
{$IFNDEF CIL}
l := Length(Result);
SetLength(Result, l + lr);
Move(Pointer(Replace)^, Pointer(@Result[l + 1])^, lr);
{$ELSE}
Result:=Result+Replace;
{$ENDIF}
Delete(Value, 1, x - 1 + ls);
x := Pos(Search, Value);
end;
Result := Result + Value;
end;
{==============================================================================}
function RPosEx(const Sub, Value: string; From: integer): Integer;
var
n: Integer;
l: Integer;
begin
result := 0;
l := Length(Sub);
for n := From - l + 1 downto 1 do
begin
if Copy(Value, n, l) = Sub then
begin
result := n;
break;
end;
end;
end;
{==============================================================================}
function RPos(const Sub, Value: String): Integer;
begin
Result := RPosEx(Sub, Value, Length(Value));
end;
{==============================================================================}
function FetchBin(var Value: string; const Delimiter: string): string;
var
s: string;
begin
Result := SeparateLeft(Value, Delimiter);
s := SeparateRight(Value, Delimiter);
if s = Value then
Value := ''
else
Value := s;
end;
{==============================================================================}
function Fetch(var Value: string; const Delimiter: string): string;
begin
Result := FetchBin(Value, Delimiter);
Result := TrimSP(Result);
Value := TrimSP(Value);
end;
{==============================================================================}
function FetchEx(var Value: string; const Delimiter, Quotation: string): string;
var
b: Boolean;
begin
Result := '';
b := False;
while Length(Value) > 0 do
begin
if b then
begin
if Pos(Quotation, Value) = 1 then
b := False;
Result := Result + Value[1];
Delete(Value, 1, 1);
end
else
begin
if Pos(Delimiter, Value) = 1 then
begin
Delete(Value, 1, Length(delimiter));
break;
end;
b := Pos(Quotation, Value) = 1;
Result := Result + Value[1];
Delete(Value, 1, 1);
end;
end;
end;
{==============================================================================}
function IsBinaryString(const Value: AnsiString): Boolean;
var
n: integer;
begin
Result := False;
for n := 1 to Length(Value) do
if Value[n] in [#0..#8, #10..#31] then
//ignore null-terminated strings
if not ((n = Length(value)) and (Value[n] = AnsiChar(#0))) then
begin
Result := True;
Break;
end;
end;
{==============================================================================}
function PosCRLF(const Value: AnsiString; var Terminator: AnsiString): integer;
var
n, l: integer;
begin
Result := -1;
Terminator := '';
l := length(value);
for n := 1 to l do
if value[n] in [#$0d, #$0a] then
begin
Result := n;
Terminator := Value[n];
if n <> l then
case value[n] of
#$0d:
if value[n + 1] = #$0a then
Terminator := #$0d + #$0a;
#$0a:
if value[n + 1] = #$0d then
Terminator := #$0a + #$0d;
end;
Break;
end;
end;
{==============================================================================}
Procedure StringsTrim(const Value: TStrings);
var
n: integer;
begin
for n := Value.Count - 1 downto 0 do
if Value[n] = '' then
Value.Delete(n)
else
Break;
end;
{==============================================================================}
function PosFrom(const SubStr, Value: String; From: integer): integer;
var
ls,lv: integer;
begin
Result := 0;
ls := Length(SubStr);
lv := Length(Value);
if (ls = 0) or (lv = 0) then
Exit;
if From < 1 then
From := 1;
while (ls + from - 1) <= (lv) do
begin
{$IFNDEF CIL}
if CompareMem(@SubStr[1],@Value[from],ls) then
{$ELSE}
if SubStr = copy(Value, from, ls) then
{$ENDIF}
begin
result := from;
break;
end
else
inc(from);
end;
end;
{==============================================================================}
{$IFNDEF CIL}
function IncPoint(const p: pointer; Value: integer): pointer;
begin
Result := PAnsiChar(p) + Value;
end;
{$ENDIF}
{==============================================================================}
//improved by 'DoggyDawg'
function GetBetween(const PairBegin, PairEnd, Value: string): string;
var
n: integer;
x: integer;
s: string;
lenBegin: integer;
lenEnd: integer;
str: string;
max: integer;
begin
lenBegin := Length(PairBegin);
lenEnd := Length(PairEnd);
n := Length(Value);
if (Value = PairBegin + PairEnd) then
begin
Result := '';//nothing between
exit;
end;
if (n < lenBegin + lenEnd) then
begin
Result := Value;
exit;
end;
s := SeparateRight(Value, PairBegin);
if (s = Value) then
begin
Result := Value;
exit;
end;
n := Pos(PairEnd, s);
if (n = 0) then
begin
Result := Value;
exit;
end;
Result := '';
x := 1;
max := Length(s) - lenEnd + 1;
for n := 1 to max do
begin
str := copy(s, n, lenEnd);
if (str = PairEnd) then
begin
Dec(x);
if (x <= 0) then
Break;
end;
str := copy(s, n, lenBegin);
if (str = PairBegin) then
Inc(x);
Result := Result + s[n];
end;
end;
{==============================================================================}
function CountOfChar(const Value: string; Chr: char): integer;
var
n: integer;
begin
Result := 0;
for n := 1 to Length(Value) do
if Value[n] = chr then
Inc(Result);
end;
{==============================================================================}
// ! do not use AnsiExtractQuotedStr, it's very buggy and can crash application!
function UnquoteStr(const Value: string; Quote: Char): string;
var
n: integer;
inq, dq: Boolean;
c, cn: char;
begin
Result := '';
if Value = '' then
Exit;
if Value = Quote + Quote then
Exit;
inq := False;
dq := False;
for n := 1 to Length(Value) do
begin
c := Value[n];
if n <> Length(Value) then
cn := Value[n + 1]
else
cn := #0;
if c = quote then
if dq then
dq := False
else
if not inq then
inq := True
else
if cn = quote then
begin
Result := Result + Quote;
dq := True;
end
else
inq := False
else
Result := Result + c;
end;
end;
{==============================================================================}
function QuoteStr(const Value: string; Quote: Char): string;
var
n: integer;
begin
Result := '';
for n := 1 to length(value) do
begin
Result := result + Value[n];
if value[n] = Quote then
Result := Result + Quote;
end;
Result := Quote + Result + Quote;
end;
{==============================================================================}
procedure HeadersToList(const Value: TStrings);
var
n, x, y: integer;
s: string;
begin
for n := 0 to Value.Count -1 do
begin
s := Value[n];
x := Pos(':', s);
if x > 0 then
begin
y:= Pos('=',s);
if not ((y > 0) and (y < x)) then
begin
s[x] := '=';
Value[n] := s;
end;
end;
end;
end;
{==============================================================================}
procedure ListToHeaders(const Value: TStrings);
var
n, x: integer;
s: string;
begin
for n := 0 to Value.Count -1 do
begin
s := Value[n];
x := Pos('=', s);
if x > 0 then
begin
s[x] := ':';
Value[n] := s;
end;
end;
end;
{==============================================================================}
function SwapBytes(Value: integer): integer;
var
s: AnsiString;
x, y, xl, yl: Byte;
begin
s := CodeLongInt(Value);
x := Ord(s[4]);
y := Ord(s[3]);
xl := Ord(s[2]);
yl := Ord(s[1]);
Result := ((x * 256 + y) * 65536) + (xl * 256 + yl);
end;
{==============================================================================}
function ReadStrFromStream(const Stream: TStream; len: integer): AnsiString;
var
x: integer;
{$IFDEF CIL}
buf: Array of Byte;
{$ENDIF}
begin
{$IFDEF CIL}
Setlength(buf, Len);
x := Stream.read(buf, Len);
SetLength(buf, x);
Result := StringOf(Buf);
{$ELSE}
Setlength(Result, Len);
x := Stream.read(PAnsiChar(Result)^, Len);
SetLength(Result, x);
{$ENDIF}
end;
{==============================================================================}
procedure WriteStrToStream(const Stream: TStream; Value: AnsiString);
{$IFDEF CIL}
var
buf: Array of Byte;
{$ENDIF}
begin
{$IFDEF CIL}
buf := BytesOf(Value);
Stream.Write(buf,length(Value));
{$ELSE}
Stream.Write(PAnsiChar(Value)^, Length(Value));
{$ENDIF}
end;
{==============================================================================}
{$IFDEF POSIX}
function tempnam(const Path: PAnsiChar; const Prefix: PAnsiChar): PAnsiChar; cdecl;
external libc name _PU + 'tempnam';
{$ENDIF}
function GetTempFile(const Dir, prefix: String): String;
{$IFNDEF FPC}
{$IFDEF MSWINDOWS}
var
Path: String;
x: integer;
{$ENDIF}
{$ENDIF}
begin
{$IFDEF FPC}
Result := GetTempFileName(Dir, Prefix);
{$ELSE}
{$IFNDEF MSWINDOWS}
Result := tempnam(Pointer(Dir), Pointer(prefix));
{$ELSE}
{$IFDEF CIL}
Result := System.IO.Path.GetTempFileName;
{$ELSE}
if Dir = '' then
begin
Path := StringOfChar(#0, MAX_PATH);
x := GetTempPath(Length(Path), PChar(Path));
Path := PChar(Path);
end
else
Path := Dir;
x := Length(Path);
if Path[x] <> '\' then
Path := Path + '\';
Result := StringOfChar(#0, MAX_PATH);
GetTempFileName(PChar(Path), PChar(Prefix), 0, PChar(Result));
Result := PChar(Result);
SetFileattributes(PChar(Result), GetFileAttributes(PChar(Result)) or FILE_ATTRIBUTE_TEMPORARY);
{$ENDIF}
{$ENDIF}
{$ENDIF}
end;
{==============================================================================}
function PadString(const Value: AnsiString; len: integer; Pad: AnsiChar): AnsiString;
begin
if length(value) >= len then
Result := Copy(value, 1, len)
else
Result := Value + StringOfChar(Pad, len - length(value));
end;
{==============================================================================}
function XorString(Indata1, Indata2: AnsiString): AnsiString;
var
i: integer;
begin
Indata2 := PadString(Indata2, length(Indata1), #0);
Result := '';
for i := 1 to length(Indata1) do
Result := Result + AnsiChar(ord(Indata1[i]) xor ord(Indata2[i]));
end;
{==============================================================================}
function NormalizeHeader(Value: TStrings; var Index: Integer): string;
var
s, t: string;
n: Integer;
begin
s := Value[Index];
Inc(Index);
if s <> '' then
while (Value.Count - 1) > Index do
begin
t := Value[Index];
if t = '' then
Break;
for n := 1 to Length(t) do
if t[n] = #9 then
t[n] := ' ';
if not(AnsiChar(t[1]) in [' ', '"', ':', '=']) then
Break
else
begin
s := s + ' ' + Trim(t);
Inc(Index);
end;
end;
Result := TrimRight(s);
end;
{==============================================================================}
{pf}
procedure SearchForLineBreak(var APtr:PANSIChar; AEtx:PANSIChar; out ABol:PANSIChar; out ALength:integer);
begin
ABol := APtr;
while (APtr<AEtx) and not (APtr^ in [#0,#10,#13]) do
inc(APtr);
ALength := APtr-ABol;
end;
{/pf}
{pf}
procedure SkipLineBreak(var APtr:PANSIChar; AEtx:PANSIChar);
begin
if (APtr<AEtx) and (APtr^=#13) then
inc(APtr);
if (APtr<AEtx) and (APtr^=#10) then
inc(APtr);
end;
{/pf}
{pf}
procedure SkipNullLines(var APtr:PANSIChar; AEtx:PANSIChar);
var
bol: PANSIChar;
lng: integer;
begin
while (APtr<AEtx) do
begin
SearchForLineBreak(APtr,AEtx,bol,lng);
SkipLineBreak(APtr,AEtx);
if lng>0 then
begin
APtr := bol;
Break;
end;
end;
end;
{/pf}
{pf}
procedure CopyLinesFromStreamUntilNullLine(var APtr:PANSIChar; AEtx:PANSIChar; ALines:TStrings);
var
bol: PANSIChar;
lng: integer;
s: ANSIString;
begin
// Copying until body separator will be reached
while (APtr<AEtx) and (APtr^<>#0) do
begin
SearchForLineBreak(APtr,AEtx,bol,lng);
SkipLineBreak(APtr,AEtx);
if lng=0 then
Break;
SetString(s,bol,lng);
ALines.Add(s);
end;
end;
{/pf}
{pf}
procedure CopyLinesFromStreamUntilBoundary(var APtr:PANSIChar; AEtx:PANSIChar; ALines:TStrings; const ABoundary:ANSIString);
var
bol: PANSIChar;
lng: integer;
s: ANSIString;
BackStop: ANSIString;
eob1: PANSIChar;
eob2: PANSIChar;
begin
BackStop := '--'+ABoundary;
eob2 := nil;
// Copying until Boundary will be reached
while (APtr<AEtx) do
begin
SearchForLineBreak(APtr,AEtx,bol,lng);
SkipLineBreak(APtr,AEtx);
eob1 := MatchBoundary(bol,APtr,ABoundary);
if Assigned(eob1) then
eob2 := MatchLastBoundary(bol,AEtx,ABoundary);
if Assigned(eob2) then
begin
APtr := eob2;
Break;
end
else if Assigned(eob1) then
begin
APtr := eob1;
Break;
end
else
begin
SetString(s,bol,lng);
ALines.Add(s);
end;
end;
end;
{/pf}
{pf}
function SearchForBoundary(var APtr:PANSIChar; AEtx:PANSIChar; const ABoundary:ANSIString): PANSIChar;
var
eob: PANSIChar;
Step: integer;
begin
Result := nil;
// Moving Aptr position forward until boundary will be reached
while (APtr<AEtx) do
begin
if strlcomp(APtr,#13#10'--',4)=0 then
begin
eob := MatchBoundary(APtr,AEtx,ABoundary);
Step := 4;
end
else if strlcomp(APtr,'--',2)=0 then
begin
eob := MatchBoundary(APtr,AEtx,ABoundary);
Step := 2;
end
else
begin
eob := nil;
Step := 1;
end;
if Assigned(eob) then
begin
Result := APtr; // boundary beginning
APtr := eob; // boundary end
exit;
end
else
inc(APtr,Step);
end;
end;
{/pf}
{pf}
function MatchBoundary(ABol,AEtx:PANSIChar; const ABoundary:ANSIString): PANSIChar;
var
MatchPos: PANSIChar;
Lng: integer;
begin
Result := nil;
MatchPos := ABol;
Lng := length(ABoundary);
if (MatchPos+2+Lng)>AETX then
exit;
if strlcomp(MatchPos,#13#10,2)=0 then
inc(MatchPos,2);
if (MatchPos+2+Lng)>AETX then
exit;
if strlcomp(MatchPos,'--',2)<>0 then
exit;
inc(MatchPos,2);
if strlcomp(MatchPos,PANSIChar(ABoundary),Lng)<>0 then
exit;
inc(MatchPos,Lng);
if ((MatchPos+2)<=AEtx) and (strlcomp(MatchPos,#13#10,2)=0) then
inc(MatchPos,2);
Result := MatchPos;
end;
{/pf}
{pf}
function MatchLastBoundary(ABOL,AETX:PANSIChar; const ABoundary:ANSIString): PANSIChar;
var
MatchPos: PANSIChar;
begin
Result := nil;
MatchPos := MatchBoundary(ABOL,AETX,ABoundary);
if not Assigned(MatchPos) then
exit;
if strlcomp(MatchPos,'--',2)<>0 then
exit;
inc(MatchPos,2);
if (MatchPos+2<=AEtx) and (strlcomp(MatchPos,#13#10,2)=0) then
inc(MatchPos,2);
Result := MatchPos;
end;
{/pf}
{pf}
function BuildStringFromBuffer(AStx,AEtx:PANSIChar): ANSIString;
var
lng: integer;
begin
Lng := 0;
if Assigned(AStx) and Assigned(AEtx) then
begin
Lng := AEtx-AStx;
if Lng<0 then
Lng := 0;
end;
SetString(Result,AStx,lng);
end;
{/pf}
{==============================================================================}
var
n: integer;
begin
for n := 1 to 12 do
begin
CustomMonthNames[n] := {$IFDEF COMPILER15_UP}FormatSettings.{$ENDIF}ShortMonthNames[n];
MyMonthNames[0, n] := {$IFDEF COMPILER15_UP}FormatSettings.{$ENDIF}ShortMonthNames[n];
end;
end.
|
unit PedidosProdutos;
interface
uses
Windows, SysUtils, Classes, Controls, Forms, ComCtrls, DB, SqlExpr, DBClient,
StrUtils, Math, Controle, Produtos;
type
TPedidosProdutos = class
private
iAutoIncremento: integer;
iNumeroPedido: integer;
iProduto: integer;
sDescricao: string;
iQuantidade: integer;
nVlrUnitario: double;
nVlrTotal: double;
iOldProduto: integer;
iOldQuantidade: Integer;
nOldVlrUnitario: double;
nOldVlrTotal: double;
oProdutos: TProdutos;
function getDescricao: string;
function getCdsPedidosProdutos: TClientDataSet;
function getCdsListaPedidosProdutos: TClientDataSet;
protected
oControle: TControle;
procedure OnAfterInsert(DataSet: TDataSet);
procedure OnAfterEdit(DataSet: TDataSet);
procedure OnAfterOpen(DataSet: TDataSet);
procedure PreencherPropriedade;
procedure PreencherPropriedadeOLD;
procedure LimparPropriedade;
procedure LimparPropriedadeOLD;
property OldProduto: Integer read iOldProduto write iOldProduto;
property OldQuantidade: Integer read iOldQuantidade write iOldQuantidade;
property OldVlrUnitario: Double read nOldVlrUnitario write nOldVlrUnitario;
property OldVlrTotal: Double read nOldVlrTotal write nOldVlrTotal;
public
constructor Create(pConexaoControle: TControle);
destructor Destroy; override;
procedure Carregar_PedidoProdutos(pNumeroPedido: Integer);
function CalcularTotal_PedidoProdutos: Currency;
function SalvarItem_PedidoProdutos: Boolean;
procedure ExcluirItem_PedidoProdutos(pAutoIncremento: Integer);
property AutoIncremento: Integer read iAutoIncremento;
property NumeroPedido: integer read iNumeroPedido write iNumeroPedido;
property Produto: Integer read iProduto write iProduto;
property Descricao: string read getDescricao;
property Quantidade: integer read iQuantidade write iQuantidade;
property VlrUnitario: Double read nVlrUnitario write nVlrUnitario;
property VlrTotal: Double read nVlrTotal write nVlrTotal;
property Produtos: TProdutos read oProdutos;
property CdsPedidosProdutos: TClientDataSet read getCdsPedidosProdutos;
property CdsListaPedidosProdutos: TClientDataSet read getCdsListaPedidosProdutos;
end;
implementation
{ TPedidosProdutos }
function TPedidosProdutos.CalcularTotal_PedidoProdutos: Currency;
var
nTotal: Currency;
begin
if oControle.CdsLista.State in [dsInsert, dsEdit] then
Result := oControle.CdsLista.FieldByName('VLR_TOTAL').AsCurrency
else
begin
try
oControle.CdsLista.DisableControls;
nTotal := 0;
Result := 0;
oControle.CdsLista.First;
while not oControle.CdsLista.Eof do
begin
nTotal := nTotal + oControle.CdsLista.FieldByName('VLR_TOTAL').AsCurrency;
oControle.CdsLista.Next;
end;
finally
Result := nTotal;
oControle.CdsLista.EnableControls;
end;
end;
end;
procedure TPedidosProdutos.Carregar_PedidoProdutos(pNumeroPedido: Integer);
begin
oControle.CdsLista.Close;
oControle.CdsLista.Params.ParamByName('pNumeroPedido').AsInteger := pNumeroPedido;
oControle.CdsLista.Open;
end;
constructor TPedidosProdutos.Create(pConexaoControle: TControle);
begin
if not Assigned(pConexaoControle) then
oControle := TControle.Create
else
oControle := pConexaoControle;
if not Assigned(oProdutos) then
oProdutos := TProdutos.Create(pConexaoControle);
oControle.CdsLista.AfterInsert := Self.OnAfterInsert;
oControle.CdsLista.AfterEdit := Self.OnAfterEdit;
oControle.CdsLista.AfterOpen := Self.OnAfterOpen;
oControle.CdsLista.Close;
oControle.CdsLista.CommandText := 'SELECT '+
' PEDIDOSPRODUTOS.AUTOINCREMENTO, '+
' PEDIDOSPRODUTOS.NUMEROPEDIDO, '+
' PEDIDOSPRODUTOS.PRODUTO, '+
' PRODUTOS.DESCRICAO, '+
' PEDIDOSPRODUTOS.QUANTIDADE, '+
' PEDIDOSPRODUTOS.VLR_UNITARIO, '+
' PEDIDOSPRODUTOS.VLR_TOTAL '+
'FROM '+
' PEDIDOSPRODUTOS '+
' INNER JOIN PRODUTOS ON '+
' PRODUTOS.CODIGO = PEDIDOSPRODUTOS.PRODUTO '+
'WHERE '+
' PEDIDOSPRODUTOS.NUMEROPEDIDO = :pNumeroPedido ';
oControle.CdsLista.Params.Clear;
oControle.CdsLista.Params.CreateParam(ftInteger, 'pNumeroPedido', ptInput);
end;
destructor TPedidosProdutos.Destroy;
begin
inherited;
end;
procedure TPedidosProdutos.ExcluirItem_PedidoProdutos(pAutoIncremento: Integer);
begin
if pAutoIncremento > 0 then
begin
oControle.SqlQuery.Close;
oControle.SqlQuery.SQL.Clear;
oControle.SqlQuery.SQL.Add('DELETE FROM PEDIDOSPRODUTOS WHERE AUTOINCREMENTO = :pAutoIncremento ');
oControle.SqlQuery.Params.Clear;
oControle.SqlQuery.Params.CreateParam(ftInteger, 'pAutoIncremento', ptInput);
oControle.SqlQuery.ParamByName('pAutoIncremento').AsInteger := pAutoIncremento;
try
oControle.SqlQuery.ExecSQL;
Self.Carregar_PedidoProdutos(Self.NumeroPedido);
except
on e: Exception do
begin
Application.MessageBox(PWideChar('Ocorreu um erro ao tentar excluir o item do pedido "'+IntToStr(Self.NumeroPedido)+'".'+#13+#10+'Erro: "'+e.Message+'"'), 'Erro na exclusão do registro', MB_ICONERROR + MB_OK);
end;
end;
end;
end;
function TPedidosProdutos.getCdsListaPedidosProdutos: TClientDataSet;
begin
Result := oControle.CdsLista;
end;
function TPedidosProdutos.getCdsPedidosProdutos: TClientDataSet;
begin
Result := oControle.CdsResult;
end;
function TPedidosProdutos.getDescricao: string;
begin
if oProdutos.PesquisarProduto(Self.Produto) then
sDescricao := oProdutos.Descricao
else
sDescricao := '';
Result := sDescricao;
end;
procedure TPedidosProdutos.LimparPropriedade;
begin
Self.iAutoIncremento := 0;
Self.NumeroPedido := 0;
Self.Produto := 0;
Self.Quantidade := 0;
Self.VlrUnitario := 0;
Self.VlrTotal := 0;
end;
procedure TPedidosProdutos.LimparPropriedadeOLD;
begin
Self.OldProduto := 0;
Self.OldQuantidade := 0;
Self.OldVlrUnitario := 0;
Self.OldVlrTotal := 0;
end;
procedure TPedidosProdutos.OnAfterEdit(DataSet: TDataSet);
begin
Self.LimparPropriedade;
Self.PreencherPropriedadeOLD;
end;
procedure TPedidosProdutos.OnAfterInsert(DataSet: TDataSet);
begin
Self.LimparPropriedade;
Self.LimparPropriedadeOLD;
end;
procedure TPedidosProdutos.OnAfterOpen(DataSet: TDataSet);
begin
TCurrencyField(DataSet.FindField('VLR_UNITARIO')).DisplayFormat := '#,###,###,##0.00';
TCurrencyField(DataSet.FindField('VLR_TOTAL')).DisplayFormat := '#,###,###,##0.00';
PreencherPropriedade;
PreencherPropriedadeOLD;
end;
procedure TPedidosProdutos.PreencherPropriedade;
begin
if oControle.CdsLista.FieldByName('AUTOINCREMENTO').AsInteger > 0 then
Self.iAutoIncremento := oControle.CdsLista.FieldByName('AUTOINCREMENTO').AsInteger
else
Self.iAutoIncremento := 0;
Self.NumeroPedido := oControle.CdsLista.FieldByName('NUMEROPEDIDO').AsInteger;
Self.Produto := oControle.CdsLista.FieldByName('PRODUTO').AsInteger;
Self.Quantidade := oControle.CdsLista.FieldByName('QUANTIDADE').AsInteger;
Self.VlrUnitario := oControle.CdsLista.FieldByName('VLR_UNITARIO').AsCurrency;
Self.VlrTotal := oControle.CdsLista.FieldByName('VLR_TOTAL').AsCurrency;
end;
procedure TPedidosProdutos.PreencherPropriedadeOLD;
begin
Self.OldProduto := oControle.CdsLista.FieldByName('PRODUTO').AsInteger;
Self.OldQuantidade := oControle.CdsLista.FieldByName('QUANTIDADE').AsInteger;
Self.OldVlrUnitario := oControle.CdsLista.FieldByName('VLR_UNITARIO').AsCurrency;
Self.OldVlrTotal := oControle.CdsLista.FieldByName('VLR_TOTAL').AsCurrency;
end;
function TPedidosProdutos.SalvarItem_PedidoProdutos: Boolean;
begin
if oControle.CdsLista.State = dsInsert then
begin
Result := True;
LimparPropriedadeOLD;
LimparPropriedade;
PreencherPropriedade;
oControle.SqlQuery.Close;
oControle.SqlQuery.SQL.Clear;
oControle.SqlQuery.SQL.Add('INSERT INTO PEDIDOSPRODUTOS ');
oControle.SqlQuery.SQL.Add(' (NUMEROPEDIDO ');
oControle.SqlQuery.SQL.Add(' ,PRODUTO ');
oControle.SqlQuery.SQL.Add(' ,QUANTIDADE ');
oControle.SqlQuery.SQL.Add(' ,VLR_UNITARIO ');
oControle.SqlQuery.SQL.Add(' ,VLR_TOTAL) ');
oControle.SqlQuery.SQL.Add('VALUES ');
oControle.SqlQuery.SQL.Add(' (:pNumeroPedido ');
oControle.SqlQuery.SQL.Add(' ,:pProduto ');
oControle.SqlQuery.SQL.Add(' ,:pQuantidade ');
oControle.SqlQuery.SQL.Add(' ,:pVlrUnitario ');
oControle.SqlQuery.SQL.Add(' ,:pVlrTotal)');
oControle.SqlQuery.Params.Clear;
oControle.SqlQuery.Params.CreateParam(ftInteger, 'pNumeroPedido', ptInput);
oControle.SqlQuery.Params.CreateParam(ftInteger, 'pProduto', ptInput);
oControle.SqlQuery.Params.CreateParam(ftInteger, 'pQuantidade', ptInput);
oControle.SqlQuery.Params.CreateParam(ftFloat, 'pVlrUnitario', ptInput);
oControle.SqlQuery.Params.CreateParam(ftFloat, 'pVlrTotal', ptInput);
oControle.SqlQuery.ParamByName('pNumeroPedido').AsInteger := Self.NumeroPedido;
oControle.SqlQuery.ParamByName('pProduto').AsInteger := Self.Produto;
oControle.SqlQuery.ParamByName('pQuantidade').AsInteger := Self.Quantidade;
oControle.SqlQuery.ParamByName('pVlrUnitario').AsFloat := Self.VlrUnitario;
oControle.SqlQuery.ParamByName('pVlrTotal').AsFloat := Self.VlrTotal;
try
try
oControle.SqlQuery.ExecSQL;
oControle.CdsLista.Cancel;
oControle.CdsLista.Refresh;
oControle.CdsLista.Last;
except
on e: Exception do
begin
Result := False;
Application.MessageBox(PWideChar('Ocorreu o seguinte erro ao inserir um produto no pedido.'+#13+#10+' "'+e.Message+'".'), 'Erro de inclusão', MB_ICONERROR + MB_OK);
end;
end;
finally
oControle.SqlQuery.Close;
end;
end
else if oControle.CdsLista.State = dsEdit then
begin
PreencherPropriedade;
Result := (SameValue(Self.Quantidade, Self.OldQuantidade)) or
(SameValue(Self.VlrUnitario, Self.OldVlrUnitario)) or
(SameValue(Self.VlrTotal, Self.OldVlrTotal));
if Result then
begin
oControle.SqlQuery.Close;
oControle.SqlQuery.SQL.Clear;
oControle.SqlQuery.SQL.Add('UPDATE ');
oControle.SqlQuery.SQL.Add(' PEDIDOSPRODUTOS ');
oControle.SqlQuery.SQL.Add('SET ');
if (not SameValue(Self.Quantidade, Self.OldQuantidade)) then
oControle.SqlQuery.SQL.Add(' QUANTIDADE = :pQuantidade, ');
if (not SameValue(Self.VlrUnitario, Self.OldVlrUnitario)) then
oControle.SqlQuery.SQL.Add(' VLR_UNITARIO = :pVlrUnitario, ');
if (not SameValue(Self.VlrTotal, Self.OldVlrTotal)) then
oControle.SqlQuery.SQL.Add(' VLR_TOTAL = :pVlrTotal ');
oControle.SqlQuery.SQL.Add('WHERE ');
oControle.SqlQuery.SQL.Add(' AUTOINCREMENTO = :pAutoIncremento');
oControle.SqlQuery.Params.Clear;
if (not SameValue(Self.Quantidade, Self.OldQuantidade)) then
oControle.SqlQuery.Params.CreateParam(ftInteger, 'pQuantidade', ptInput);
if (not SameValue(Self.VlrUnitario, Self.OldVlrUnitario)) then
oControle.SqlQuery.Params.CreateParam(ftInteger, 'pVlrUnitario', ptInput);
if (not SameValue(Self.VlrTotal, Self.OldVlrTotal)) then
oControle.SqlQuery.Params.CreateParam(ftInteger, 'pVlrTotal', ptInput);
oControle.SqlQuery.Params.CreateParam(ftInteger, 'pAutoIncremento', ptInput);
if (not SameValue(Self.Quantidade, Self.OldQuantidade)) then
oControle.SqlQuery.ParamByName('pQuantidade').AsInteger := Self.Quantidade;
if (not SameValue(Self.VlrUnitario, Self.OldVlrUnitario)) then
oControle.SqlQuery.ParamByName('pVlrUnitario').AsFloat := Self.VlrUnitario;
if (not SameValue(Self.VlrTotal, Self.OldVlrTotal)) then
oControle.SqlQuery.ParamByName('pVlrTotal').AsFloat := Self.VlrTotal;
oControle.SqlQuery.ParamByName('pAutoIncremento').AsInteger := Self.AutoIncremento;
try
try
oControle.SqlQuery.ExecSQL;
oControle.CdsLista.Cancel;
oControle.CdsLista.Refresh;
oControle.CdsLista.Locate('AUTOINCREMENTO', Self.AutoIncremento, [loCaseInsensitive, loPartialKey]);
except
on e: Exception do
begin
Result := False;
Application.MessageBox(PWideChar('Ocorreu o seguinte erro ao alterar o produto no pedido.'+#13+#10+' "'+e.Message+'".'), 'Erro na alteração', MB_ICONERROR + MB_OK);
end;
end;
finally
oControle.SqlQuery.Close;
end;
end;
end;
end;
end.
|
unit DPM.IDE.Options;
interface
uses
JsonDataObjects,
DPM.Core.Types;
type
IDPMIDEOptions = interface
['{7DC7324F-781C-4400-AFB7-E68FB9066494}']
function LoadFromFile(const fileName : string = '') : boolean;
function SaveToFile(const fileName : string = '') : boolean;
function GetOptionsFileName : string;
function GetLogVerbosity : TVerbosity;
procedure SetLogVebosity(const value : TVerbosity);
function GetShowLogForRestore : boolean;
procedure SetShowLogForRestore(const value : boolean);
function GetShowLogForInstall : boolean;
procedure SetShowLogForInstall(const value : boolean);
function GetShowLogForUnInstall : boolean;
procedure SetShowLogForUnInstall(const value : boolean);
function GetAutoCloseLogOnSuccess : boolean;
procedure SetAutoCloseLogOnSuccess(const value : boolean);
function GetAutoCloseLogDelaySeconds : integer;
procedure SetAutoCloseLogDelaySelcond(const value : integer);
function GetAddDPMToProjectTree : boolean;
procedure SetAddDPMToProjectTree(const value : boolean);
function GetLogWindowWidth : integer;
procedure SetLogWindowWidth(const value : integer);
function GetLogWindowHeight : integer;
procedure SetLogWindowHeight(const value : integer);
property LogVerbosity : TVerbosity read GetLogVerbosity write SetLogVebosity;
property LogWindowWidth : integer read GetLogWindowWidth write SetLogWindowWidth;
property LogWindowHeight : integer read GetLogWindowHeight write SetLogWindowHeight;
property ShowLogForRestore : boolean read GetShowLogForRestore write SetShowLogForRestore;
property ShowLogForInstall : boolean read GetShowLogForInstall write SetShowLogForInstall;
property ShowLogForUninstall : boolean read GetShowLogForUninstall write SetShowLogForUninstall;
property AutoCloseLogOnSuccess : boolean read GetAutoCloseLogOnSuccess write SetAutoCloseLogOnSuccess;
property AutoCloseLogDelaySeconds : integer read GetAutoCloseLogDelaySeconds write SetAutoCloseLogDelaySelcond;
property AddDPMToProjectTree : boolean read GetAddDPMToProjectTree write SetAddDPMToProjectTree;
property FileName : string read GetOptionsFileName;
end;
TDPMIDEOptions = class(TInterfacedObject, IDPMIDEOptions)
private
FFileName : string;
FVerbosity : TVerbosity;
FShowLogForRestore : boolean;
FSHowLogForInstall : boolean;
FShowLogForUninstall : boolean;
FAutoCloseOnSuccess : boolean;
FAutoCloseLogDelaySeconds : integer;
FAddDPMToProjectTree : boolean;
FLogWindowWidth : integer;
FLogWindowHeight : integer;
protected
function LoadFromJson(const jsonObj : TJsonObject) : boolean;
function SaveToJson(const parentObj : TJsonObject) : boolean;
function LoadFromFile(const fileName: string = ''): Boolean;
function SaveToFile(const fileName: string = ''): Boolean;
function GetOptionsFileName : string;
function GetLogVerbosity : TVerbosity;
procedure SetLogVebosity(const value : TVerbosity);
function GetShowLogForRestore : boolean;
procedure SetShowLogForRestore(const value : boolean);
function GetShowLogForInstall : boolean;
procedure SetShowLogForInstall(const value : boolean);
function GetShowLogForUnInstall : boolean;
procedure SetShowLogForUnInstall(const value : boolean);
function GetAutoCloseLogOnSuccess : boolean;
procedure SetAutoCloseLogOnSuccess(const value : boolean);
function GetAutoCloseLogDelaySeconds : integer;
procedure SetAutoCloseLogDelaySelcond(const value : integer);
function GetAddDPMToProjectTree : boolean;
procedure SetAddDPMToProjectTree(const value : boolean);
function GetLogWindowWidth : integer;
procedure SetLogWindowWidth(const value : integer);
function GetLogWindowHeight : integer;
procedure SetLogWindowHeight(const value : integer);
public
constructor Create;
end;
implementation
uses
System.SysUtils,
System.TypInfo,
DPM.IDE.Types,
DPM.Core.Utils.System;
{ TDPMIDEOptions }
constructor TDPMIDEOptions.Create;
begin
FFileName := TSystemUtils.ExpandEnvironmentStrings(cDPMIDEDefaultOptionsFile);
{$IFDEF DEBUG}
FVerbosity := TVerbosity.Debug;
{$ELSE}
FVerbosity := TVerbosity.Normal;
{$ENDIF}
FShowLogForRestore := true;
FShowLogForRestore := true;
FShowLogForUninstall := true;
FAutoCloseOnSuccess := true;
FAutoCloseLogDelaySeconds := 3;
FAddDPMToProjectTree := true;
FLogWindowWidth := 800;
FLogWindowHeight := 500;
end;
function TDPMIDEOptions.GetAddDPMToProjectTree: boolean;
begin
result := FAddDPMToProjectTree;
end;
function TDPMIDEOptions.GetAutoCloseLogDelaySeconds: integer;
begin
result := FAutoCloseLogDelaySeconds;
end;
function TDPMIDEOptions.GetAutoCloseLogOnSuccess: boolean;
begin
result := FAutoCloseOnSuccess;
end;
function TDPMIDEOptions.GetLogVerbosity: TVerbosity;
begin
result := FVerbosity;
end;
function TDPMIDEOptions.GetLogWindowHeight: integer;
begin
result := FLogWindowHeight;
end;
function TDPMIDEOptions.GetLogWindowWidth: integer;
begin
result := FLogWindowWidth
end;
function TDPMIDEOptions.GetOptionsFileName: string;
begin
result := FFileName;
end;
function TDPMIDEOptions.GetShowLogForInstall: boolean;
begin
result := FSHowLogForInstall;
end;
function TDPMIDEOptions.GetShowLogForRestore: boolean;
begin
result := FShowLogForRestore;
end;
function TDPMIDEOptions.GetShowLogForUnInstall: boolean;
begin
result := FShowLogForUninstall;
end;
function TDPMIDEOptions.LoadFromFile(const fileName: string): Boolean;
var
jsonObj : TJsonObject;
sFileName : string;
begin
if fileName <> '' then
sFileName := fileName
else
sFileName := FFileName;
if sFileName = '' then
raise Exception.Create('No filename set for config file, unable to load');
try
jsonObj := TJsonObject.ParseFromFile(sFileName) as TJsonObject;
try
Result := LoadFromJson(jsonObj);
FFileName := sFileName;
finally
jsonObj.Free;
end;
except
on e : Exception do
raise Exception.Create('Exception while loading config file [' + fileName + ']' + #13#10 + e.Message);
end;
end;
function TDPMIDEOptions.LoadFromJson(const jsonObj: TJsonObject): boolean;
var
sVerbosity : string;
iValue : integer;
begin
result := false;
sVerbosity := jsonObj.s['logverbosity'];
if sVerbosity <> '' then
begin
iValue := GetEnumValue(TypeInfo(TVerbosity),sVerbosity);
if iValue <> -1 then
FVerbosity := TVerbosity(iValue);
end;
if jsonObj.Contains('showlogforrestore') then
FShowLogForRestore := jsonObj.B['showlogforrestore'];
if jsonObj.Contains('showlogforinstall') then
FShowLogForInstall := jsonObj.B['showlogforinstall'];
if jsonObj.Contains('showlogforuninstall') then
FShowLogForInstall := jsonObj.B['showlogforuninstall'];
if jsonObj.Contains('autocloselogonsuccess') then
FAutoCloseOnSuccess := jsonObj.B['autocloselogonsuccess'];
if jsonObj.Contains('autocloselogdelayseconds') then
FAutoCloseLogDelaySeconds := jsonObj.I['autocloselogdelayseconds'];
if jsonObj.Contains('addtoprojecttree') then
FAddDPMToProjectTree := jsonObj.B['addtoprojecttree'];
if jsonObj.Contains('logwindowwidth') then
FLogWindowWidth := jsonObj.I['logwindowwidth'];
if jsonObj.Contains('logwindowheight') then
FLogWindowHeight := jsonObj.I['logwindowheight'];
end;
function TDPMIDEOptions.SaveToFile(const fileName: string): Boolean;
var
sFileName : string;
jsonObj : TJsonObject;
begin
if fileName <> '' then
sFileName := fileName
else
sFileName := FFileName;
if sFileName = '' then
raise Exception.Create('No filename set for config file, unable to save');
jsonObj := TJsonObject.Create;
try
try
result := SaveToJson(jsonObj);
if result then
jsonObj.SaveToFile(sFileName, false);
FFileName := sFileName;
except
on e : Exception do
raise Exception.Create('Exception while saving config to file [' + sFileName + ']' + #13#10 + e.Message);
end;
finally
jsonObj.Free;
end;
end;
function TDPMIDEOptions.SaveToJson(const parentObj: TJsonObject): boolean;
begin
parentObj.S['logverbosity'] := GetEnumName(TypeInfo(TVerbosity), Ord(FVerbosity));
parentObj.B['showlogforrestore'] := FShowLogForRestore;
parentObj.B['showlogforinstall'] := FShowLogForInstall;
parentObj.B['showlogforuninstall'] := FShowLogForUninstall;
parentObj.B['autocloselogonsuccess'] := FAutoCloseOnSuccess;
parentObj.I['autocloselogdelayseconds'] := FAutoCloseLogDelaySeconds;
parentObj.B['addtoprojecttree'] := FAddDPMToProjectTree;
parentObj.I['logwindowwidth'] := FLogWindowWidth;
parentObj.I['logwindowheight'] := FLogWindowHeight;
result := true;
end;
procedure TDPMIDEOptions.SetAddDPMToProjectTree(const value: boolean);
begin
FAddDPMToProjectTree := value;
end;
procedure TDPMIDEOptions.SetAutoCloseLogDelaySelcond(const value: integer);
begin
FAutoCloseLogDelaySeconds := value;
if FAutoCloseLogDelaySeconds < 0 then
FAutoCloseLogDelaySeconds := 0;
end;
procedure TDPMIDEOptions.SetAutoCloseLogOnSuccess(const value: boolean);
begin
FAutoCloseOnSuccess := value;
end;
procedure TDPMIDEOptions.SetLogVebosity(const value: TVerbosity);
begin
FVerbosity := value;
end;
procedure TDPMIDEOptions.SetLogWindowHeight(const value: integer);
begin
FLogWindowHeight := value;
end;
procedure TDPMIDEOptions.SetLogWindowWidth(const value: integer);
begin
FLogWindowWidth := value;
end;
procedure TDPMIDEOptions.SetShowLogForInstall(const value: boolean);
begin
FSHowLogForInstall := value;
end;
procedure TDPMIDEOptions.SetShowLogForRestore(const value: boolean);
begin
FShowLogForRestore := value;
end;
procedure TDPMIDEOptions.SetShowLogForUnInstall(const value: boolean);
begin
FShowLogForUninstall := value;
end;
end.
|
unit SuraWin;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
QuranStruct, ComCtrls, ExtCtrls, DFSSplitter, StdCtrls, AmlView, ImgList,
TeeProcs, TeEngine, Chart, Series;
type
TSuraSelectEvent = procedure(const ASura : PSuraInfoRec) of object;
TSuraListSort = (slsNum, slsName, slsAyahCount, slsRevealed, slsCity);
TSuraListForm = class(TForm)
ImageList: TImageList;
PageControl: TPageControl;
SurasSheet: TTabSheet;
RukuSplitter: TDFSSplitter;
SuraList: TListView;
RukuPanel: TPanel;
RukuListLabel: TLabel;
RukuList: TListView;
AjzaSheet: TTabSheet;
AjzaList: TListView;
SajdasSheet: TTabSheet;
SajdaList: TListView;
OptionsPanel: TPanel;
StayOnTopCheckbox: TCheckBox;
AutoHideCheckbox: TCheckBox;
TabSheet1: TTabSheet;
AyahChart: TChart;
Series1: TBarSeries;
procedure SuraListCompare(Sender: TObject; Item1, Item2: TListItem;
Data: Integer; var Compare: Integer);
procedure SuraListColumnClick(Sender: TObject; Column: TListColumn);
procedure SuraListDblClick(Sender: TObject);
procedure SuraListClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure RukuListDblClick(Sender: TObject);
procedure AjzaListDblClick(Sender: TObject);
procedure SajdaListDblClick(Sender: TObject);
procedure StayOnTopCheckboxClick(Sender: TObject);
procedure ListBoxKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
protected
FAddrMgr : IAddressManager;
FDataMgr : TDataManager;
FSort : TSuraListSort;
FSortDescend : Boolean;
FStruct : TQuranStructure;
FActiveSura : PSuraInfoRec;
procedure Populate(const ASura : TSuraNum); overload;
public
procedure Populate(const AStruct : TQuranStructure); overload;
property AddressMgr : IAddressManager read FAddrMgr write FAddrMgr;
property DataMgr : TDataManager read FDataMgr write FDataMgr;
end;
var
SuraListForm: TSuraListForm;
implementation
{$R *.DFM}
procedure TSuraListForm.Populate(const AStruct : TQuranStructure);
var
S : TSuraNum;
Item : TListItem;
ThisLoc, NextLoc : TSuraAyah;
Range, R : Cardinal;
AyahCountSeries : TBarSeries;
begin
if FStruct = AStruct then
Exit;
FStruct := AStruct;
SuraList.Items.Clear;
AjzaList.Items.Clear;
if AStruct = Nil then
Exit;
AyahCountSeries := AyahChart[0] as TBarSeries;
SuraList.Items.BeginUpdate;
for S := Low(TSuraNum) to High(TSuraNum) do begin
Item := SuraList.Items.Add;
Item.Caption := IntToStr(S);
Item.ImageIndex := 0;
Item.StateIndex := 0;
Item.Data := AStruct.SuraData[S];
with AStruct.Sura[S] do begin
Item.Subitems.Add(suraName);
Item.Subitems.Add(IntToStr(ayahCount));
Item.Subitems.Add(IntToStr(revealedNum));
Item.Subitems.Add(revealedInCityName);
AyahCountSeries.Add(ayahCount, IntToStr(S), clInfoBk);
end;
end;
SuraList.Items.EndUpdate;
AjzaList.Items.BeginUpdate;
for S := Low(TJuzNum) to High(TJuzNum) do begin
Item := AjzaList.Items.Add;
Item.Caption := IntToStr(S);
Item.ImageIndex := 0;
Item.StateIndex := 0;
if S < High(TJuzNum) then
NextLoc := AStruct.Ajza[S+1]
else begin
NextLoc.suraNum := High(TSuraNum);
NextLoc.ayahNum := AStruct.Sura[NextLoc.suraNum].ayahCount;
end;
ThisLoc := AStruct.Ajza[S];
if ThisLoc.suraNum = NextLoc.suraNum then
Range := NextLoc.ayahNum - ThisLoc.ayahNum + 1
else begin
Range := AStruct.Sura[ThisLoc.suraNum].ayahCount - ThisLoc.ayahNum + 1;
for R := Succ(ThisLoc.suraNum) to Pred(NextLoc.suraNum) do begin
Inc(Range, AStruct.Sura[R].ayahCount);
end;
Inc(Range, NextLoc.ayahNum);
end;
with AStruct.Ajza[S] do begin
Item.Subitems.Add(IntToStr(suraNum));
Item.Subitems.Add(AStruct.SuraName[suraNum]);
Item.Subitems.Add(IntToStr(ayahNum));
Item.Subitems.Add(IntToStr(Range));
end;
end;
AjzaList.Items.EndUpdate;
SajdaList.Items.BeginUpdate;
for S := Low(TSajdaNum) to High(TSajdaNum) do begin
Item := SajdaList.Items.Add;
Item.Caption := IntToStr(S);
Item.ImageIndex := 0;
Item.StateIndex := 0;
with AStruct.Sajda[S] do begin
Item.Subitems.Add(IntToStr(suraNum));
Item.Subitems.Add(AStruct.SuraName[suraNum]);
Item.Subitems.Add(IntToStr(ayahNum));
end;
end;
SajdaList.Items.EndUpdate;
end;
procedure TSuraListForm.Populate(const ASura : TSuraNum);
var
I : Integer;
begin
Assert(FStruct <> Nil);
RukuList.Items.BeginUpdate;
RukuList.Items.Clear;
FActiveSura := FStruct.SuraData[ASura];
RukuListLabel.Caption := Format('Sura %d%sSections (%d) ', [FActiveSura.suraNum, #13#10, FActiveSura.rukuCount]);
if FActiveSura.rukuCount > 1 then begin
for I := 1 to FActiveSura.rukuCount do begin
with FActiveSura.rukus[I], RukuList.Items.Add do begin
ImageIndex := 1;
StateIndex := 1;
Caption := IntToStr(I);
Subitems.Add(IntToStr(startAyah));
Subitems.Add(IntToStr(endAyah));
Subitems.Add(IntToStr(endAyah-startAyah+1));
end;
end;
end else begin
with FActiveSura^, RukuList.Items.Add do begin
ImageIndex := 1;
StateIndex := 1;
Caption := '1';
Subitems.Add('1');
Subitems.Add(IntToStr(ayahCount));
Subitems.Add(IntToStr(ayahCount));
end;
end;
RukuList.Items.EndUpdate;
end;
procedure TSuraListForm.SuraListCompare(Sender: TObject; Item1,
Item2: TListItem; Data: Integer; var Compare: Integer);
procedure CompareNum(Num1, Num2 : LongInt);
begin
if Num1 < Num2 then
Compare := -1
else if Num1 > Num2 then
Compare := 1
else
Compare := 0;
end;
begin
FSort := TSuraListSort(Data);
case FSort of
slsNum : CompareNum(PSuraInfoRec(Item1.Data)^.suraNum, PSuraInfoRec(Item2.Data)^.suraNum);
slsName : Compare := CompareText(PSuraInfoRec(Item1.Data)^.suraName, PSuraInfoRec(Item2.Data)^.suraName);
slsAyahCount : CompareNum(PSuraInfoRec(Item1.Data)^.ayahCount, PSuraInfoRec(Item2.Data)^.ayahCount);
slsRevealed : CompareNum(PSuraInfoRec(Item1.Data)^.revealedNum, PSuraInfoRec(Item2.Data)^.revealedNum);
slsCity :
begin
Compare := CompareText(PSuraInfoRec(Item1.Data)^.revealedInCityName, PSuraInfoRec(Item2.Data)^.revealedInCityName);
if Compare = 0 then
CompareNum(PSuraInfoRec(Item1.Data)^.revealedNum, PSuraInfoRec(Item2.Data)^.revealedNum);
end;
end;
if FSortDescend then begin
if Compare < 0 then
Compare := 1
else if Compare > 0 then
Compare := -1;
end;
end;
procedure TSuraListForm.SuraListColumnClick(Sender: TObject;
Column: TListColumn);
begin
if FSort = TSuraListSort(Column.Id) then
FSortDescend := not FSortDescend;
SuraList.CustomSort(Nil, Column.Id);
end;
procedure TSuraListForm.SuraListDblClick(Sender: TObject);
begin
if Assigned(FAddrMgr) then begin
if AutoHideCheckbox.Checked then begin
Hide;
Application.ProcessMessages;
end;
FAddrMgr.SetAddress(Format('qs:%d', [PSuraInfoRec(SuraList.Selected.Data).SuraNum]));
end;
end;
procedure TSuraListForm.SuraListClick(Sender: TObject);
begin
Populate(PSuraInfoRec(SuraList.Selected.Data).suraNum);
end;
procedure TSuraListForm.FormCreate(Sender: TObject);
begin
// the design-time width is assumed to be exact width of SuraList width
Width := GetSystemMetrics(SM_CXVSCROLL) + (PageControl.ClientWidth-SuraList.Width) +
SuraList.Width + (SuraList.Columns.Count * 2);
end;
procedure TSuraListForm.RukuListDblClick(Sender: TObject);
begin
if Assigned(FAddrMgr) and Assigned(FActiveSura) then begin
if AutoHideCheckbox.Checked then begin
Hide;
Application.ProcessMessages;
end;
if FActiveSura.rukuCount > 1 then
FAddrMgr.SetAddress(CreateQuranAddress(qatGeneric, FActiveSura.SuraNum, FActiveSura.rukus[RukuList.Selected.Index+1].startAyah))
else
FAddrMgr.SetAddress(CreateQuranAddress(qatGeneric, FActiveSura.SuraNum));
end;
end;
procedure TSuraListForm.AjzaListDblClick(Sender: TObject);
var
Loc : TSuraAyah;
begin
if Assigned(FAddrMgr) then begin
if AutoHideCheckbox.Checked then begin
Hide;
Application.ProcessMessages;
end;
Loc := FStruct.Ajza[AjzaList.Selected.Index+1];
FAddrMgr.SetAddress(CreateQuranAddress(qatGeneric, Loc.suraNum, Loc.ayahNum));
end;
end;
procedure TSuraListForm.SajdaListDblClick(Sender: TObject);
var
Loc : TSuraAyah;
begin
if Assigned(FAddrMgr) then begin
if AutoHideCheckbox.Checked then begin
Hide;
Application.ProcessMessages;
end;
Loc := FStruct.Sajda[SajdaList.Selected.Index+1];
FAddrMgr.SetAddress(CreateQuranAddress(qatGeneric, Loc.suraNum, Loc.ayahNum));
end;
end;
procedure TSuraListForm.StayOnTopCheckboxClick(Sender: TObject);
begin
if StayOnTopCheckbox.Checked then
FormStyle := fsStayOnTop
else
FormStyle := fsNormal;
end;
procedure TSuraListForm.ListBoxKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Key = VK_RETURN) and (Sender is TListView) and (Assigned((Sender as TListView).OnDblClick)) then
(Sender as TListView).OnDblClick(Sender);
end;
end.
|
unit AcqInterfaces;
interface
{$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF}
uses classes,
stmdef ;
type
TAcqInterFaces=class
drivers:TstringList;
currentDriver1,currentDriver2:AnsiString;
constructor create;
destructor destroy;override;
function choose(var st1:DriverString):boolean;
function install(st1:driverstring):boolean;
function exist:boolean;
end;
var
boards:TacqInterfaces;
procedure RegisterBoard(BrdName:AnsiString;brdType:pointer);
implementation
uses ParSystem, AcqBrd1 ;
{******************** Méthodes de TacqInterfaces *****************************}
constructor TacqInterfaces.create;
begin
drivers:=TstringList.create;
end;
destructor TacqInterfaces.destroy;
begin
drivers.free;
end;
function TacqInterfaces.choose(var st1:Driverstring):boolean;
begin
if paramSystem.execution(st1,drivers)then install(st1);
end;
function TacqInterfaces.install(st1:driverstring):boolean;
var
index:integer;
begin
result:=(st1=currentDriver1);
if result then exit;
board.free;
board:=nil;
index:=drivers.indexof(st1);
if index<0 then st1:='';
currentDriver1:=st1;
if st1='' then
begin
result:=false;
exit;
end;
board:=TinterfaceClass(drivers.objects[index]).create(st1);
if assigned(board) then board.loadOptions;
result:=true;
end;
function TacqInterfaces.exist:boolean;
begin
result:=drivers.count>0;
end;
procedure RegisterBoard(BrdName:AnsiString;brdType:pointer);
begin
if not assigned(boards) then boards:=TacqInterfaces.create;
boards.drivers.AddObject(BrdName,brdType) ;
end;
end.
|
program inifile;
{$mode objfpc}{$H+}
uses
classes, sysutils, IniFiles;
const
INI_Section = 'DB INFO';
var
INI_fn, INI_Key: string;
INI_obj: TINIFile;
Author, Pass, DBFile: String; MaxAttempts: integer;
begin
INI_fn := 'subdir' + DirectorySeparator + 'main.ini';
if not FileExists(INI_fn) then begin writeln('no file');exit;end;
{Create the object, specifying the the INI_obj file that contains
the settings}
INI_obj := TINIFile.Create(INI_fn);
{Put reading the INI_obj file inside a try/finally block
to prevent memory leaks}
try
if not INI_obj.SectionExists(INI_Section) then
begin writeln('no section');exit;end;
// Demonstrates reading values from the INI_obj file.
// ValueExists actually check if Key exists
INI_Key := 'Author';
if not INI_obj.ValueExists(INI_Section, INI_Key) then begin
writeln(INI_Key, ' not exist.');exit; end;
Author := INI_obj.ReadString(INI_Section,INI_Key,'');
INI_Key := 'Pass';
if not INI_obj.ValueExists(INI_Section, INI_Key) then begin
writeln(INI_Key, ' not exist.');exit; end;
Pass := INI_obj.ReadString(INI_Section,INI_Key,'');
INI_Key := 'DBFile';
if not INI_obj.ValueExists(INI_Section, 'DBFile') then begin
writeln(INI_Key, ' not exist.');exit; end;
DBFile := INI_obj.ReadString(INI_Section,INI_Key,'');
INI_Key := 'MaxAttempts';
if not INI_obj.ValueExists(INI_Section, INI_Key) then begin
writeln(INI_Key, ' not exist.');exit; end;
MaxAttempts := INI_obj.ReadInteger(INI_Section,INI_Key,-1);
writeln('Author : ', Author);
writeln('File : ', DBFile);
writeln('Password : ', Pass);
writeln('Max password attempts: ', MaxAttempts);
finally
{After the INI_obj file was used it must be freed
to prevent memory leaks.}
INI_obj.Free;
end;
//write section-key-value(string) to ini file
INI_obj := TINIFile.Create(INI_fn);
try
INI_obj.WriteString(INI_Section,'DBFile','D:\DATA\base.fdb');
finally
INI_obj.Free;
end;
end.
|
{
New script template, only shows processed records
Assigning any nonzero value to Result will terminate script
}
unit userscript;
uses mteFunctions;
uses userUtilities;
const
target_filename = 'Angry Wenches.esp';
num_entries_in_lvln = 1;
no_faction_limit = False;
var
target_file : IInterface;
slMasters, slRaces, slFactions, slVampireKeywords, exemplarToFakerKey, slFactionsNoRestrictions, slTargetFactions : TStringList;
lvlList, exemplarToFakerValue, lvlListNoFactions : TList;
faceNPCs : TList;
//---------------------------------------------------------------------------------------
// File IO
//---------------------------------------------------------------------------------------
procedure getUserFile;
begin
target_file := getOrCreateFile(target_filename);
if not Assigned(target_file) then begin
AddMessage('File not created or retrieved!');
Exit;
end;
AddMastersToFile(target_file, slMasters, True);
//AddMastersMine(target_file, slMasters);
end;
//---------------------------------------------------------------------------------------
// Tes5Edit Manipulation
//---------------------------------------------------------------------------------------
function getTargetFaction(npc : IInterface) : IInterface;
var
i, j : integer;
factions, faction : IInterface;
begin
factions := ElementByName(npc, 'Factions');
for i:= 0 to Pred(ElementCount(factions)) do begin
faction := ElementByIndex(factions, i);
faction := LinksTo(ElementByPath(faction, 'Faction'));
for j := 0 to slFactions.Count-1 do begin
if EditorID(faction) = slFactions[j] then
Result := slFactions[j];
end;
end;
end;
function getBaseRaceFromVampire(src: IInterface) : IInterface;
var
race_rec, race_rec2 : IInterface;
race, race2 : integer;
begin
// Sets npc's race to non-vampire race. Using keywords instead like Alva's record
race_rec: = LinksTo(ElementBySignature(src, 'RNAM'));
race := slRaces.IndexOf(EditorID(race_rec));
if race <> -1 then begin
AddMessage('Standard race: ' + EditorID(race_rec));
Exit;
end;
// Get non-vampire race record from morph race attribute
race_rec2 := LinksTo(ElementBySignature(race_rec, 'NAM8'));
race2 := slRaces.IndexOf(EditorID(race_rec2));
if race2 = -1 then begin
AddMessage('Not a vampire: '+ EditorID(race_rec) + ' : ' + EditorID(race_rec2));
Exit;
end;
Result := race_rec2;
end;
// Checks DW's leveled list overrides and returns the winning override before DW
// i.e. skyim | dragonborn | Deadly wenches
// returns ^
function getTargetLeveledListOverride(elem : IInterface): IInterface;
var
i : integer;
cur_ovr, next_ovr, m : IInterface;
s : string;
begin
if not Assigned(elem) then begin
AddMessage('getTargetLeveledListOverride: input "elem" not assigned.');
Exit;
end;
m := MasterOrSelf(elem);
cur_ovr := m;
//AddMessage(EditorID(elem));
for i := 0 to Pred(OverrideCount(m)) do begin
next_ovr := OverrideByIndex(m, i);
s := Name(GetFile(next_ovr));
if SameText(GetFileName(GetFile(next_ovr)), 'deadly wenches.esp') then
Break;
cur_ovr := next_ovr;
end;
Result := cur_ovr;
end;
//---------------------------------------------------------------------------------------
// Step 1. Get a list of faces "templates" to use by iterating through Deadly Wenches
// npc records and recording their respectiver templates from IW
//---------------------------------------------------------------------------------------
// Check if valid template (NPC must have all facegen entries to be a template)
function isValidFaceTemplate(npc : IInterface): boolean;
var
temp : boolean;
begin
temp := ElementExists(npc, 'Head Parts');
temp := ElementExists(npc, 'QNAM - Texture lighting') and temp;
temp := ElementExists(npc, 'NAM9 - Face morph') and temp;
temp := ElementExists(npc, 'NAMA - Face parts') and temp;
temp := ElementExists(npc, 'Tint Layers') and temp;
Result := temp;
end;
procedure printTest;
var
i, j, k : integer;
race, faction : integer;
race_list, faction_list : TList;
rec : IInterface;
begin
for i := 0 to slRaces.Count-1 do begin
AddMessage('Race: ' + slRaces[i]);
race_list := TList(faceNPCs[i]);
for j := 0 to slTargetFactions.Count-1 do begin
AddMessage(' Faction: ' + slTargetFactions[j]);
faction_list := TList(race_list[j]);
for k := 0 to faction_list.Count-1 do begin
rec := ObjectToElement(faction_list[k]);
AddMessage('>>>>' + EditorID(rec));
end;
end;
end;
end;
procedure addDeadlyWenchesTemplatesToFaceNPCs;
var
i, race, faction, vampire : integer;
npcs, npc, template_npc : IInterface;
template_file : IInterface;
race_list, faction_list : TList;
begin
template_file := getOrCreateFile('Deadly Wenches.esp');
npcs := GroupBySignature(template_file, 'NPC_');
for i := 0 to Pred(ElementCount(npcs)) do begin
npc := ElementByIndex(npcs, i);
template_npc := LinksTo(ElementByPath(npc, 'TPLT'));
if not Assigned(template_npc) then Continue;
// skips records not from IW
if not SameText(Lowercase(GetFileName(GetFile(template_npc))), 'immersive wenches.esp') then
Continue;
// skip records without valid face templates
if not isValidFaceTemplate(template_npc) then Continue;
// Ignore non-target races and factions
faction := slFactions.IndexOf(getTargetFaction(npc));
if faction = -1 then Continue;
race := slRaces.IndexOf(EditorID(LinksTo(ElementBySignature(npc, 'RNAM'))));
if race = -1 then Continue;
// Get corresponding race list from faceNPCs
race_list := TList(faceNPCs[race]);
if not no_faction_limit then begin
faction_list := TList(race_list[faction]);
end else begin
if SameText(GetTargetFaction(npc), 'VampireFaction') then vampire := 1 else vampire := 0;
faction_list := TList(race_list[vampire])
end;
faction_list.Add(template_npc);
end;
end;
//---------------------------------------------------------------------------------------
// Exemplar Logic
//---------------------------------------------------------------------------------------
procedure getLevedListStats(lvln : IInterface);
var
llct : IInterface;
begin
llct := GetElementNativeValues(lvln, 'LLCT');
if llct = 0 then AddMessage('LVLN: ' + EditorID(lvln) + ' has 0 LLCT');
end;
function getLevedListForFaker(faker : IInterface) : IInterface;
var
faction, race, vampire : integer;
tar_lvln : IInterface;
race_lvlList : TList;
begin
if not Assigned(faker) then begin
AddMessage('Warning! Faker is unassigned.');
Exit;
end;
// Ignore non-target factions
faction := slFactions.IndexOf(getTargetFaction(faker));
if faction = -1 then Exit;
// Ignore non-target races
if SameText(getTargetFaction(faker), 'VampireFaction') then begin
race := slRaces.IndexOf(EditorID(getBaseRaceFromVampire(faker)));
end else begin
race := slRaces.IndexOf(EditorID(LinksTo(ElementBySignature(faker, 'RNAM'))));
end;
if race = -1 then Exit;
//getFakerStats(faker);
// Get leveled list
race_lvlList := TList(lvlList[race]);
//tar_lvln := ObjectToElement(race_lvlList[faction]);
if not no_faction_limit then begin
tar_lvln := ObjectToElement(race_lvlList[faction]);
end else begin
if SameText(GetTargetFaction(faker), 'VampireFaction') then vampire := 1 else vampire := 0;
tar_lvln := ObjectToElement(race_lvlList[vampire])
end;
if not Assigned(tar_lvln) then begin
AddMessage('tar_lvln is not assigned.');
Exit;
end;
getLevedListStats(tar_lvln);
Result := tar_lvln;
end;
procedure getFakerStats(faker : IInterface);
begin
AddMessage(EditorID(faker));
AddMessage('>>Faction: ' + getTargetFaction(faker));
AddMessage('>>RaceB: ' + EditorID(LinksTo(ElementBySignature(faker, 'RNAM'))));
AddMessage('>>RaceV: ' + EditorID(getBaseRaceFromVampire(faker)));
end;
procedure handleVampireFakers(faker : IInterface);
var
race_rec : IInterface;
s : string;
begin
if not Assigned(faker) then begin
AddMessage('Warning! Faker is unassigned.');
Exit;
end;
if not SameText(getTargetFaction(faker), 'VampireFaction') then Exit;
// Set race to non-vampire race
s := 'RNAM';
race_rec := getBaseRaceFromVampire(faker);
SetEditValue(ElementByPath(faker, s), Name(race_rec));
// Assign keywords to handle not being a "vampire" race
addKeyword(faker, slVampireKeywords);
end;
function getNameFromExemplarTemplate(exemplar : IInterface) : string;
var
cur_rec : IInterface;
hasParent : boolean;
begin
cur_rec := exemplar;
hasParent := false;
repeat
if Assigned(ElementBySignature(cur_rec, 'FULL')) then
Break;
hasParent := Assigned(ElementBySignature(cur_rec, 'TPLT'));
cur_rec := LinksTo(ElementBySignature(cur_rec, 'TPLT'));
until not hasParent;
if Assigned(ElementBySignature(cur_rec, 'FULL')) then
Result := GetElementEditValues(cur_rec, 'FULL');
end;
function createFakerFromExemplarWithFace(exemplar, face_npc : IInterface; variation : integer) : IInterface;
var
faker, lvln : IInterface;
s : string;
begin
if not Assigned(exemplar) then begin
AddMessage('Warning! Exemplar is unassigned.');
Exit;
end;
if not Assigned(face_npc) then begin
AddMessage('Warning! Face NPC is unassigned.');
Exit;
end;
faker := wbCopyElementToFile(exemplar, target_file, true, true);
if not Assigned(faker) then begin
AddMessage('Warning! Faker not copied from exemplar');
end;
s := 'EDID';
SetElementEditValues(faker, 'EDID', 'AW_' + GetElementEditValues(exemplar, 'EDID') + '_' + IntToStr(variation));
s := 'FULL';
SetElementEditValues(faker, 'FULL', getNameFromExemplarTemplate(exemplar));
// Use only the traits (i.e. appearance) from the template
s := 'ACBS\Template Flags';
SetElementNativeValues(faker, s, $0001); // Only use leveled lists traits
// Set template to the face_npc for "template" appearances
s := 'TPLT';
SetEditValue(ElementByPath(faker, s), Name(face_npc));
// Handle Faction-related issues
handleVampireFakers(faker);
// Add faker to exemplarToFaker map
Result := faker;
end;
function getRaceFactionList(npc : IInterface) : TList;
var
faction, race, vampire : integer;
race_list, faction_list : TList;
begin
// Ignore non-target races and factions
faction := slFactions.IndexOf(getTargetFaction(npc));
if faction = -1 then Exit;
if SameText(getTargetFaction(npc), 'VampireFaction') then begin
race := slRaces.IndexOf(EditorID(getBaseRaceFromVampire(npc)));
end else begin
race := slRaces.IndexOf(EditorID(LinksTo(ElementBySignature(npc, 'RNAM'))));
end;
if race = -1 then Exit;
// Get corresponding race faction list
race_list := TList(faceNPCs[race]);
if not no_faction_limit then begin
faction_list := TList(race_list[faction]);
end else begin
if SameText(GetTargetFaction(npc), 'VampireFaction') then vampire := 1 else vampire := 0;
faction_list := TList(race_list[vampire])
end;
Result := faction_list;
end;
function createFakerLevelListFromExemplar(exemplar : IInterface) : IInterface;
var
i : integer;
lvln_rec, face_npc, faker_npc : IInterface;
s : string;
face_list : TList;
begin
if not Assigned(exemplar) then begin
AddMessage('Warning! Exemplar is unassigned.');
Exit;
end;
s := 'AW_L' + EditorID(exemplar);
lvln_rec := createLeveledList(target_file, s);
face_list := getRaceFactionList(exemplar);
// For each face npc, create a variation and add to leveled list
for i := 0 to face_list.Count-1 do begin
face_npc := ObjectToElement(face_list[i]);
faker_npc := createFakerFromExemplarWithFace(exemplar, face_npc, i);
AddLeveledListEntry(lvln_rec, 1, faker_npc, 1);
end;
exemplarToFakerKey.Add(EditorID(exemplar));
exemplarToFakerValue.Add(lvln_rec);
Result := lvln_rec;
end;
// Get or create a faker leveled list from the exemplar record
function getFakerLevelListFromExemplar(exemplar : IInterface) : IInterface;
var
tar_index : integer;
faker_lvln : IInterface;
begin
if not Assigned(exemplar) then begin
AddMessage('Warning! Exemplar is unassigned.');
Exit;
end;
// Retrieve existing faker or create a new one if no fakers
tar_index := exemplarToFakerKey.IndexOf(EditorID(exemplar));
if tar_index=-1 then begin
faker_lvln := createFakerLevelListFromExemplar(exemplar);
end else begin
faker_lvln := ObjectToElement(exemplarToFakerValue[tar_index]);
end;
Result := faker_lvln;
end;
procedure createExemplarsFromLeveledList(m : IInterface);
var
i, j : integer;
lvln_ents, lvln_ent, exemplar : IInterface;
new_override, faker : IInterface;
isEdited : boolean;
begin
// Iterate through all leveled list entries
isEdited := false;
lvln_ents := ElementByName(m, 'Leveled List Entries');
for i := 0 to Pred(ElementCount(lvln_ents)) do begin
lvln_ent := ElementByIndex(lvln_ents, i);
exemplar := LinksTo(ElementByPath(lvln_ent, 'LVLO\Reference'));
// Only make exemplar from female NPCs
if Signature(exemplar) <> 'NPC_' then Continue;
if GetElementNativeValues(exemplar, 'ACBS\Flags') and 1 <> 1 then Continue;
// Create lvln override for new plugin
if not isEdited then begin
new_override := wbCopyElementToFile(m, target_file, False, True);
isEdited := true;
end;
// Get Faker
faker := getFakerLevelListFromExemplar(exemplar);
if not Assigned(faker) then begin
AddMessage('Faker not retrieved');
AddMessage('>> Exemplar: ' + EditorID(exemplar));
Exit;
end;
// For up to global constant, add a lvln entry to the lvln with the same fields as the exemplar
for j := 1 to num_entries_in_lvln do begin
AddLeveledListEntry(new_override, GetElementNativeValues(lvln_ent, 'LVLO\Level'), faker, GetElementNativeValues(lvln_ent, 'LVLO\Count'));
end;
end;
end;
procedure addFakers;
var
i : integer;
m_lvln, lvln, lvlns : IInterface;
begin
// Iterate through modified leveled lists from DW
lvlns := getFileElements('deadly wenches.esp', 'LVLN');
for i := 0 to Pred(ElementCount(lvlns)) do begin
lvln := ElementByIndex(lvlns, i);
// Only deal with LVLN that were modified
if IsMaster(lvln) then begin
//AddMessage('Skipped: ' + EditorID(lvln));
Continue;
end;
//AddMessage('Getting override');
m_lvln := getTargetLeveledListOverride(lvln);
//AddMessage('Creating exemplars');
createExemplarsFromLeveledList(m_lvln);
end;
end;
//---------------------------------------------------------------------------------------
// Setup
//---------------------------------------------------------------------------------------
procedure setupGlobalVariables;
var
i, j : integer;
begin
slMasters := TStringList.Create;
slMasters.Add('Skyrim.esm');
slMasters.Add('Update.esm');
slMasters.Add('Dawnguard.esm');
slMasters.Add('Dragonborn.esm');
slMasters.Add('Unofficial Skyrim Legendary Edition Patch.esp');
slMasters.Add('Immersive Wenches.esp');
slRaces := TStringList.Create;
slRaces.Add('DarkElfRace');
//slRaces.Add('ArgonianRace');
slRaces.Add('BretonRace');
slRaces.Add('HighElfRace');
slRaces.Add('ImperialRace');
//slRaces.Add('KhajiitRace');
slRaces.Add('NordRace');
//slRaces.Add('OrcRace');
slRaces.Add('RedguardRace');
slRaces.Add('WoodElfRace');
//slRaces.Add('NordRaceVampire');
slFactions := TStringList.Create;
slFactions.Add('VampireFaction');
slFactions.Add('BanditFaction');
slFactions.Add('ForswornFaction');
slFactions.Add('VigilantOfStendarrFaction');
slFactions.Add('CWImperialFaction');
slFactions.Add('CWSonsFaction');
// Dawnguard
//
//slFactions.Add('');
slVampireKeywords := TStringList.Create;
slVampireKeywords.Add('00013796'); //ActorTypeUndead
slVampireKeywords.Add('000A82BB'); //Vampire
slFactionsNoRestrictions := TStringList.Create;
slFactionsNoRestrictions.Add('NonVampire');
slFactionsNoRestrictions.Add('Vampire');
lvlList := TList.Create;
for i := 0 to slRaces.Count-1 do begin
lvlList.Add(TList.Create);
end;
lvlListNoFactions := TList.Create;
for i := 0 to slRaces.Count-1 do begin
lvlListNoFactions.Add(TList.Create);
end;
if no_faction_limit then
slTargetFactions := slFactionsNoRestrictions
else
slTargetFactions := slFactions;
faceNPCs := TList.Create;
for i := 0 to slRaces.Count-1 do begin
faceNPCs.Add(TList.Create);
for j := 0 to slTargetFactions.Count-1 do begin
TList(faceNPCs[i]).Add(TList.Create);
end;
end;
exemplarToFakerKey := TStringList.Create;
exemplarToFakerValue := TList.Create;
end;
procedure freeGlobalVariables;
var
i, j : integer;
lst : TList;
begin
//printStringList(exemplarToFakerKey, 'exemplarToFakerKey');
// arrays first
for i := 0 to slRaces.Count-1 do begin
TList(lvlList[i]).Free;
end;
lvlList.Free;
for i := 0 to slRaces.Count-1 do begin
TList(lvlListNoFactions[i]).Free;
end;
lvlListNoFactions.Free;
for i := 0 to slRaces.Count-1 do begin
lst := TList(faceNPCs[i]);
for j := 0 to slTargetFactions.Count-1 do begin
TList(lst[j]).Free;
end;
lst.Free;
end;
faceNPCs.Free;
// single variables last
slMasters.Free;
slRaces.Free;
slFactions.Free;
slVampireKeywords.Free;
slFactionsNoRestrictions.Free;
exemplarToFakerKey.Free;
exemplarToFakerValue.Free;
end;
//---------------------------------------------------------------------------------------
// Required Tes5Edit Script Functions
//---------------------------------------------------------------------------------------
// Called before processing
// You can remove it if script doesn't require initialization code
function Initialize: integer;
begin
setupGlobalVariables;
getUserFile;
addDeadlyWenchesTemplatesToFaceNPCs;
//printTest;
//createRaceFactionLists;
//addTemplatesToRaceFactionLists;
addFakers;
Result := 0;
end;
// called for every record selected in xEdit
function Process(e: IInterface): integer;
begin
Result := 0;
// comment this out if you don't want those messages
//AddMessage('Processing: ' + FullPath(e));
// processing code goes here
end;
// Called after processing
// You can remove it if script doesn't require finalization code
function Finalize: integer;
begin
freeGlobalVariables;
Result := 0;
end;
end.
|
unit Matriz;
interface
uses Windows, Classes, SysUtils;
type
pVetor = ^tVetor;
tVetor = array[0..0] of Extended;
TMatriz= class
private
Tamanho: LongInt;
Matriz : pVetor;
public
Status : Boolean;
Altura : LongInt;
Largura: LongInt;
constructor Create (_Largura, _Altura: LongInt);
destructor Destroy; override;
function Retornar (X, Y: LongInt): Extended;
procedure Armazenar (X, Y: LongInt; Valor: Extended);
end;
var
eMatriz: TMatriz;
procedure MultiplicarPorEscalar (Escalar: Extended);
procedure Triangular (var Sinal: SmallInt);
function CalcularDeterminanteTriangulacao: Extended;
function CalcularInversa: Boolean;
implementation
uses Principal;
// Classe: TMatriz
constructor TMatriz.Create (_Largura, _Altura: LongInt);
begin
inherited Create;
Largura:= _Largura;
Altura := _Altura;
Tamanho:= Largura*Altura*SizeOf (Extended);
try
GetMem (Matriz, Tamanho);
Status:= True;
except
Status:= False;
end;
end; // Create ()
destructor TMatriz.Destroy;
begin
FreeMem (Matriz, Tamanho);
inherited Destroy;
end; // Destroy ()
// Retorna o índice da matriz relativa ao par (X, Y)
function TMatriz.Retornar (X, Y: LongInt): Extended;
begin
Result:= Matriz^[X + Y*Largura];
end; // Retornar ()
// Armazenar um elemento na matriz
procedure TMatriz.Armazenar (X, Y: LongInt; Valor: Extended);
begin
Matriz^[X + Y*Largura]:= Valor;
end; // Armazenar ()
// Classe: TMatriz
procedure MultiplicarPorEscalar (Escalar: Extended);
var
X, Y: Integer;
begin
for Y:= 0 to eMatriz.Largura-1 do
for X:= 0 to eMatriz.Altura-1 do
eMatriz.Armazenar (X, Y, eMatriz.Retornar (X, Y)*Escalar);
end; // MultiplicarPorEscalar ()
procedure PermutarLinhas (A, B: LongInt);
var
X : LongInt;
Temp: Extended;
begin
for X:= 0 to eMatriz.Largura-1 do begin
Temp:= eMatriz.Retornar (X, B);
eMatriz.Armazenar (X, B, eMatriz.Retornar (X, A));
eMatriz.Armazenar (X, A, Temp);
end;
end; // PermutarLinhas ()
function ProcurarNaoZero (X, Y: LongInt): LongInt;
var
P: LongInt;
begin
Result:= -1;
for P:= Y to eMatriz.Altura-1 do
if eMatriz.Retornar (X, P) <> 0 then begin
Result:= P;
Exit;
end;
end; // ProcurarNaoZero ()
procedure TriangularLinhas (PosicaoPivo: LongInt; SerParaBaixo: Boolean);
var
X, Y : LongInt;
Escalar: Extended;
begin
if SerParaBaixo then
for Y:= PosicaoPivo+1 to eMatriz.Altura-1 do begin
Escalar:= eMatriz.Retornar (PosicaoPivo, Y)/eMatriz.Retornar (PosicaoPivo, PosicaoPivo);
eMatriz.Armazenar (PosicaoPivo, Y, 0.0);
for X:= PosicaoPivo+1 to eMatriz.Largura-1 do
eMatriz.Armazenar (X, Y, eMatriz.Retornar (X, Y) - eMatriz.Retornar (X, PosicaoPivo)*Escalar);
end
else
for Y:= PosicaoPivo-1 downto 0 do begin
Escalar:= eMatriz.Retornar (PosicaoPivo, Y)/eMatriz.Retornar (PosicaoPivo, PosicaoPivo);
for X:= eMatriz.Largura-1 downto 0 do
eMatriz.Armazenar (X, Y, eMatriz.Retornar (X, Y) - eMatriz.Retornar (X, PosicaoPivo)*Escalar);
eMatriz.Armazenar (PosicaoPivo, Y, 0.0);
end;
end; // TriangularLinhas ()
// O sinal do DETERMINANTE muda quando se permuta 2 linhas
procedure Triangular (var Sinal: SmallInt);
var
P, PosicaoPivo: LongInt;
begin
Sinal:= 1;
for P:= 0 to eMatriz.Altura-1 do
if eMatriz.Retornar (P, P) <> 0 then
TriangularLinhas (P, True)
else if P < eMatriz.Altura then begin // Para evitar de permutar a última linha
PosicaoPivo:= ProcurarNaoZero (P, P);
if PosicaoPivo > 0 then begin
Sinal:= -Sinal;
PermutarLinhas (P, PosicaoPivo);
TriangularLinhas (P, True);
end;
end;
end; // Triangular ()
function CalcularInversa: Boolean;
var
P, PosicaoPivo: LongInt;
Escalar : Extended;
procedure FazerPivoUm;
var
X : LongInt;
Valor: Extended;
begin
for X:= 0 to eMatriz.Largura-1 do begin
Valor:= eMatriz.Retornar (X, P);
if Valor <> 0 then
eMatriz.Armazenar (X, P, Valor*Escalar);
end;
end; // FazerPivoUm ()
procedure AnexarIdentidade;
var
I, X, Y: LongInt;
begin
I:= eMatriz.Largura div 2;
for Y:= 0 to eMatriz.Altura-1 do
for X:= I to eMatriz.Largura-1 do
if X = Y+I then
eMatriz.Armazenar (X, Y, 1.0)
else
eMatriz.Armazenar (X, Y, 0.0);
end; // AnexarIdentidade ()
begin
Result:= True;
AnexarIdentidade;
for P:= 0 to eMatriz.Altura-1 do
if eMatriz.Retornar (P, P) <> 0 then begin
TriangularLinhas (P, True);
TriangularLinhas (P, False);
Escalar:= 1/eMatriz.Retornar (P, P);
FazerPivoUm;
end
else if P < eMatriz.Altura then begin // Para evitar de permutar a última linha
PosicaoPivo:= ProcurarNaoZero (P, P);
if PosicaoPivo > 0 then begin
PermutarLinhas (P, PosicaoPivo);
TriangularLinhas (P, True);
TriangularLinhas (P, False);
Escalar:= 1/eMatriz.Retornar (P, P);
FazerPivoUm;
end
else begin
Result:= False; // Determinante = 0
Exit;
end;
end
else begin
Result:= False; // Determinante = 0
Exit;
end;
end; // CalcularInversa ()
function CalcularDeterminanteTriangulacao: Extended;
var
Sinal: SmallInt;
P : LongInt;
begin
Result:= 1.0;
Triangular (Sinal);
for P:= 0 to eMatriz.Altura-1 do
Result:= Result*eMatriz.Retornar (P, P); // Multiplicar os elementos da Diagonal Principal
Result:= Result*Sinal;
end; // CalcularDeterminanteTriangulacao ()
end.
// Final do Arquivo
|
unit fPointInMesh;
interface
uses
Winapi.Windows,
Winapi.Messages,
Winapi.mmsystem,
System.SysUtils,
System.Variants,
System.Classes,
System.Math,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Vcl.ComCtrls,
Vcl.ExtCtrls,
GLScene,
GLVectorGeometry,
GLVectorFileObjects,
GLCadencer,
GLWin32Viewer,
GLObjects,
GLCoordinates,
GLCrossPlatform,
GLBaseClasses,
GLFile3DS, GLGeomObjects;
type
TfrmCellsInMesh = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
GLCadencer1: TGLCadencer;
GLCamera1: TGLCamera;
GLFreeForm1: TGLFreeForm;
GLLightSource1: TGLLightSource;
GLLines1: TGLLines;
ProgressBar1: TProgressBar;
GLDummyCube1: TGLDummyCube;
PanelTop: TPanel;
cbShowHull: TCheckBox;
StatusBar1: TStatusBar;
rgHull: TRadioGroup;
rgCells: TRadioGroup;
GLCone1: TGLCone;
procedure FormCreate(Sender: TObject);
procedure FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure cbShowHullClick(Sender: TObject);
procedure rgHullClick(Sender: TObject);
procedure rgCellsClick(Sender: TObject);
private
MousePoint: TPoint;
procedure ShowCameraLocation;
public
procedure BuildGrid(Sender : TObject);
end;
var
frmCellsInMesh: TfrmCellsInMesh;
implementation
{$R *.dfm}
var
mx, my : integer;
procedure TfrmCellsInMesh.FormCreate(Sender: TObject);
begin
randomize;
GLFreeForm1.LoadFromFile('bunny.glsm');
GLFreeForm1.BuildOctree;
GLFreeForm1.Visible := cbShowHull.Checked;
Show;
BuildGrid(nil);
end;
procedure TfrmCellsInMesh.FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
begin
GLCamera1.AdjustDistanceToTarget(Power(1.1, WheelDelta/120));
end;
procedure TfrmCellsInMesh.GLSceneViewer1MouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
if ssLeft in Shift then
GLCamera1.MoveAroundTarget(my-y, mx-x)
else if shift = [ssRight] then
GLCamera1.AdjustDistanceToTarget(1.0 + (y - my) / 100);
mx := x;
my := y;
end;
procedure TfrmCellsInMesh.rgCellsClick(Sender: TObject);
begin
BuildGrid(Sender);
end;
procedure TfrmCellsInMesh.rgHullClick(Sender: TObject);
begin
case rgHull.ItemIndex of
0: GLFreeForm1.LoadFromFile('bunny.glsm');
1: GLFreeForm1.LoadFromFile('cube.3ds');
2: GLFreeForm1.LoadFromFile('sphere.3ds');
3: // Convert GLCone1 -> GLFreeForm1;
end;
GLFreeForm1.BuildOctree;
Show;
BuildGrid(nil);
end;
procedure TfrmCellsInMesh.ShowCameraLocation;
begin
with GLCamera1.Position do
StatusBar1.Panels[0].Text := 'Camera: '+FloatToStrF(X, ffNumber, 5, 2)+', '+
FloatToStrF(Y, ffNumber, 5, 2)+', '+FloatToStrF(Z, ffNumber, 5, 2);
end;
procedure TfrmCellsInMesh.cbShowHullClick(Sender: TObject);
begin
GLFreeForm1.Visible := cbShowHull.Checked;
end;
procedure TfrmCellsInMesh.BuildGrid(Sender : TObject);
const
cResolution = 32;
var
x, y, z, Hits, Tests : integer;
step : single;
Point : TVector;
brad : single;
StartTime : cardinal;
begin
// Note - this could be speeded up enourmously by using a proprietary method
// instead of OctreePointInMesh - which is recalculated for each node where
// it could be calculated once per column (cutting down run time by aprox.
// 1/cResolution).
// Increasing the bounding sphere radius to generate a box that's guaranteed
// to encompas the entire freeform
brad := GLFreeForm1.BoundingSphereRadius*1.42;
step := brad/(cResolution+1);
Hits := 0; Tests := 0;
ProgressBar1.Max := cResolution-1;
while GLDummyCube1.Count>0 do
GLDummyCube1.Children[GLDummyCube1.Count-1].Free;
StartTime := timeGetTime;
if (rgCells.ItemIndex <> 3) then
for x := 0 to cResolution-1 do
begin
ProgressBar1.Position := x;
for y := 0 to cResolution-1 do
for z := 0 to cResolution-1 do
begin
Point := VectorAdd(GLFreeForm1.Position.AsVector,
VectorMake(x*step-brad/2, y*step-brad/2, z*step-brad/2));
Inc(Tests);
if GLFreeForm1.OctreePointInMesh(Point) then
begin
inc(Hits);
if (rgCells.ItemIndex = 0) then // Cube cells
with TGLCube(GLDummyCube1.AddNewChild(TGLCube)) do
begin
Position.AsVector := Point;
Material.FrontProperties.Emission.RandomColor;
CubeDepth := step;
CubeWidth := step;
CubeHeight := step;
end
else
if (rgCells.ItemIndex = 1) then // Sphere cells
with TGLSphere(GLDummyCube1.AddNewChild(TGLSphere)) do
begin
Position.AsVector := Point;
Material.FrontProperties.Ambient.AsWinColor := clBlue;
Slices := 5;
Stacks := 5;
Radius := step / 2 * 1.42;
end
else
if (rgCells.ItemIndex = 2) then // Sprite cells
with TGLSprite(GLDummyCube1.AddNewChild(TGLSprite)) do
begin
Position.AsVector := Point;
Material.FrontProperties.Ambient.AsWinColor := clGreen;
Height := step / 2 * 1.42;
Width := step / 2 * 1.42;
end//}
end;
end;
end;
ProgressBar1.Position := 0;
Caption := Format('Cells %d ms, %d hits, %d tests',[(timeGetTime-StartTime),Hits, Tests]);
end;
end.
|
unit crandom;
(*
Random number unit for encryption using multiple sources of randomness from Windows and Intel (if available)
by Alexander Morris, 2015-08-05
Delphi's Random() function isn't enough because every CSPRNG should satisfy the next-bit test.
That is, given the first k bits of a random sequence, there is no polynomial-time algorithm that
can predict the (k+1)th bit with probability of success better than 50%. This is not the case of
Delphi's Random(). CryptGenRandom() and RdRand() are considered to satisfy the CSPRNG test.
CryptGenRandomBytes() function will randomly choose between CryptGenRandom(), RdRand(), and fall
back to Random() as a last resort.
usage:
var buf: array[0..7] of byte;
CryptGenRandomBytes(@buf,8);
References:
http://stackoverflow.com/questions/3946869/how-reliable-is-the-random-function-in-delphi
http://www.merlyn.demon.co.uk/pas-rand.htm#Rand
http://stackoverflow.com/questions/28538370/using-intels-rdrand-opcode-in-delphi-6-7
http://stackoverflow.com/questions/2621897/are-there-any-cryptographically-secure-prng-libraries-for-delphi
*)
interface
uses WinTypes;
//forceMode=-1 (default) to randomly select between Windows and Intel
//forceMode=0 forces CryptGenRandom() if avail, forceMode=1 forces RdRand() if avail, forceMode=2 forces Random()
procedure CryptGenRandomBytes(const pbBuffer: PAnsiChar; const dwLength: DWORD; const forceMode: ShortInt = -1);
implementation
uses Classes;
type fWCCryptAcquireContextA = Function (phProv: Pointer; pszContainer: LPCSTR; pszProvider: LPCSTR; dwProvType: DWORD; dwFlags: DWORD): BOOL; stdcall;
fWCCryptReleaseContext = Function (hProv: Pointer; dwFlags: DWORD): BOOL; stdcall;
fWCCryptGenRandom = Function (hProv: ULONG; dwLen: DWORD; pbBuffer: PBYTE): BOOL; stdcall;
var winCryptOk: integer = 0; //Windows Random function available
intCryptOk: integer = 0; //Intel Random RdRand function available
hProvider: ULONG = 0; //Windows HCryptProvider Handle
WinCryptHndl: THandle = 0;
WCCryptAcquireContextA: fWCCryptAcquireContextA;
WCCryptReleaseContext: fWCCryptReleaseContext;
WCCryptGenRandom: fWCCryptGenRandom;
//http://stackoverflow.com/questions/28538370/using-intels-rdrand-opcode-in-delphi-6-7
function TryRdRand(out Value: Cardinal): Boolean;
asm
db $0f
db $c7
db $f1
jc @success
xor eax,eax
ret
@success:
mov [eax],ecx
mov eax,1
end;
procedure InitWinCrypto;
var rnd: cardinal;
begin
intCryptOk := 1;
try TryRdRand(rnd); except intCryptOk := -1; end;
WinCryptHndl := LoadLibrary(PChar('advapi32.dll'));
if (WinCryptHndl < 32) then begin
winCryptOk := -1;
exit;
end;
@WCCryptAcquireContextA := GetProcAddress(WinCryptHndl,'CryptAcquireContextA');
@WCCryptReleaseContext := GetProcAddress(WinCryptHndl,'CryptReleaseContext');
@WCCryptGenRandom := GetProcAddress(WinCryptHndl,'CryptGenRandom');
if WCCryptAcquireContextA(@hProvider, Nil, Nil, 1{PROV_RSA_FULL}, $F0000000{CRYPT_VERIFYCONTEXT}) then
winCryptOk := 1;
end;
//forceMode=-1 (default) to randomly select between Windows and Intel
//forceMode=0 forces Windows CryptGenRandom() if avail
//forceMode=1 forces Intel RdRand() if avail
//forceMode=2 forces Delphi Random()
procedure CryptGenRandomBytes(const pbBuffer: PAnsiChar; const dwLength: DWORD; const forceMode: ShortInt = -1);
var i,mode,byteCount,fails: integer;
rnd: cardinal;
rndBufArr: array [0..3] of Byte absolute rnd;
begin
byteCount := 0;
if (forceMode >= 0) and (forceMode <= 2) then mode := forceMode else //force mode of operation
mode := Random(2); //randomize entropy source functions
repeat
if (mode = 0) and (winCryptOk <> 1) then mode := 1;
if (mode = 1) and (intCryptOk <> 1) then mode := 2;
if (mode=2) then begin
for i := 0 to dwLength-1 do pbBuffer[i] := AnsiChar(random(256));
exit;
end else
if (mode=1) then begin
try
repeat
if TryRdRand(rnd) then begin
fails := 0;
for i := 0 to 3 do begin
if (byteCount < dwLength-1) then begin
if (rndBufArr[i] <> 0) then begin
pbBuffer[byteCount] := AnsiChar(rndBufArr[i]);
byteCount := byteCount + 1;
end;
end else exit;
end;
end else fails := fails + 1;
if (fails >= 10) then mode := 2;
until (byteCount >= dwLength-1) or (mode=2);
except mode := 2; end;
if (mode=2) then intCryptOk := -1;
end else begin
if WCCryptGenRandom(hProvider, dwLength, @pbBuffer[0]) then exit;
mode := 1;
winCryptOk := -1;
end;
until false;
end;
initialization
begin
Randomize;
InitWinCrypto;
end;
finalization
begin
if (hProvider > 0) then WCCryptReleaseContext(@hProvider, 0);
end;
end.
|
unit UStr;
interface
function space ( n:integer):string ;
function replicate(ch:char; n:integer):string ;
function trim (str:string;c:boolean=false):string ;
function alike (a,b:string;var d, p: integer): boolean;
function center (str:string;n:integer):string ;
function UpSt ( s:string ):string;
function LoSt ( s:string ):string;
function lpad ( s:string;n:integer;c:char):string;
function rpad ( s:string;n:integer;c:char):string;
function addbackslash(p : string) : string;
function match (sm : string; var st: string) : boolean;
function lines (p, l, s : longint) : string;
function LoCase (c : char) : char;
function JustPathName(PathName : string) : string;
function JustFileName(PathName : string) : string;
function JustName (PathName : string) : string;
function CRC16 (s : string) : system.word;
implementation
function space;
var i : integer;
tempstr : string;
begin
tempstr:='';
for i:=1 to n do tempstr:=tempstr+' ';
space:=tempstr;
end;
function replicate;
var i : integer;
tempstr : string;
begin
tempstr:='';
for i:=1 to n do tempstr:=tempstr+ch;
replicate:=tempstr;
end;
function trim;
var i,j : integer;
s : string;
begin
trim := '';
s := str;
if length(str) > 1 then begin
i := length(str);
j := 1;
while (j <= i) and (str[j] = ' ') do inc(j);
if j > i then begin
result := '';
exit;
end;
while (str[i] = ' ') do dec(i);
s := copy(str, j, i - j + 1);
end;
if c and (length(s) > 3) then begin
repeat
i := pos(' ', s);
if i > 0 then begin
s := copy(s, 1, i - 1) + copy(s, i + 1, length(s) - i);
end;
until i = 0;
end;
if c then result := LoSt(s)
else result := s;
end;
function alike;
var e, f: integer;
begin
result := false;
p := 0;
e := length(a);
f := length(b);
if e + f = 0 then begin
result := true;
d := 100;
exit;
end;
if (e = 0) or (f = 0) then begin
d := 0;
exit;
end;
while (p < e) and (p < f) do begin
inc(p);
if a[p] <> b[p] then begin
dec(p);
break;
end;
end;
d := 200 * p div (e + f);
if p * 2 > (e + f) div 2 then begin
result := true;
end;
end;
function center;
var tempstr : string;
j : integer;
begin
j := n - length(trim(str));
if j > 0 then tempstr := space(j - j div 2) + trim(str) + space(j div 2)
else tempstr := trim(str);
center := tempstr;
end;
function UpSt;
var t : string;
i : integer;
begin
t := s;
for i := 1 to length(s) do t[i] := UpCase(s[i]);
UpSt := t;
end;
function LoSt;
var t : string;
i : integer;
begin
t := s;
for i := 1 to length(s) do t[i] := LoCase(s[i]);
LoSt := t;
end;
function lpad;
begin
lpad := replicate(c, n - length(s)) + s;
end;
function rpad;
begin
rpad := s + replicate(c, n - length(s));
end;
function addbackslash;
begin
if length(p) > 0 then
if p[length(p)] = '\' then addbackslash := p
else addbackslash := p + '\'
else addbackslash := p;
end;
function match(sm : string; var st: string) : boolean;
var p : integer;
_sm,
_st : string;
begin
match := false;
if (length(sm) > 0) and (length(st) > 0) then begin
_sm := UpSt(sm);
_st := UpSt(st);
while pos(_sm, _st) > 0 do begin
match := true;
p := pos(_sm, _st);
_st := copy(_st, 1, p - 1) + copy(_st, p + length(_sm), 250);
st := copy( st, 1, p - 1) + copy( st, p + length( sm), 250);
end;
end;
end;
function lines;
var o : string;
i : longint;
n : longint;
begin
if l > 0 then begin
i := p * s div l;
n := p * s * 2 div l;
o := replicate('Û', i);
if n > i * 2 then o := o + 'Ý';
lines := o + space(s - length(o));
end else lines := '';
end;
function LoCase;
var t : char;
begin
if (c >= 'A') and (c <= 'Z') then t := chr(ord(c) + 32)
else t := c;
LoCase := t;
end;
function JustPathname(PathName : string) : string;
{-Return just the drive:directory portion of a pathname}
var
I : Word;
begin
I := Succ(Word(Length(PathName)));
repeat
Dec(I);
until (PathName[I] in ['\',':',#0]) or (I = 1);
if I = 1 then
{Had no drive or directory name}
JustPathname := ''
else if I = 1 then
{Either the root directory of default drive or invalid pathname}
JustPathname := PathName[1]
else if (PathName[I] = '\') then begin
if PathName[Pred(I)] = ':' then
{Root directory of a drive, leave trailing backslash}
JustPathname := Copy(PathName, 1, I)
else
{Subdirectory, remove the trailing backslash}
JustPathname := Copy(PathName, 1, Pred(I));
end else
{Either the default directory of a drive or invalid pathname}
JustPathname := Copy(PathName, 1, I);
end;
function JustFilename(PathName : string) : string;
{-Return just the filename of a pathname}
var
I : Word;
begin
I := Succ(Word(Length(PathName)));
repeat
Dec(I);
until (I = 0) or (PathName[I] in ['\', ':', #0]);
JustFilename := Copy(PathName, Succ(I), 64);
end;
function JustName(PathName : string) : string;
{-Return just the name (no extension, no path) of a pathname}
var
DotPos : Byte;
begin
PathName := JustFileName(PathName);
DotPos := Pos('.', PathName);
if DotPos > 0 then
PathName := Copy(PathName, 1, DotPos-1);
JustName := PathName;
end;
function CRC16(s : string) : system.word; { By Kevin Cooney }
var
crc : longint;
t,r : byte;
begin
crc := 0;
for t := 1 to length(s) do
begin
crc := (crc xor (ord(s[t]) shl 8));
for r := 1 to 8 do
if (crc and $8000)>0 then
crc := ((crc shl 1) xor $1021)
else
crc := (crc shl 1);
end;
CRC16 := (crc and $FFFF);
end;
end.
|
//------------------------------------------------------------------------------
//The contents of this file are subject to the Mozilla Public License
//Version 1.1 (the "License"); you may not use this file except in compliance
//with the License. You may obtain a copy of the License at
//http://www.mozilla.org/MPL/ Software distributed under the License is
//distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
//or implied. See the License for the specific language governing rights and
//limitations under the License.
//
//The Original Code is UsbDev.pas.
//
//The Initial Developer of the Original Code is Alex Shovkoplyas, VE3NEA.
//Portions created by Alex Shovkoplyas are
//Copyright (C) 2008 Alex Shovkoplyas. All Rights Reserved.
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// TUsbDevice: low level USB device functions
//------------------------------------------------------------------------------
// requires LibUsb.pas
//------------------------------------------------------------------------------
unit UsbDev;
interface
uses
Windows, SysUtils, Classes, Forms, SndTypes, LibUsb;
type
TUsbDevice = class;
TReadThread = class(TTHread)
protected
Papa: TUsbDevice;
Buf: TByteArray;
ControlPoint: integer;
procedure Execute; override;
end;
TUsbDevice = class
protected
FInitialized: boolean;
FStatusText: string;
FLib: THandle;
Thr: TReadThread;
FProductId: integer;
FVendorId: integer;
FHandle: pusb_dev_handle;
FunUsbInit: function: integer; cdecl;
FunUsbFindBuses: function: integer; cdecl;
FunUsbFindDefices: function: integer; cdecl;
FunUsbGetBuses: function: pusb_bus; cdecl;
FunUsbOpen: function(dev: pusb_device): pusb_dev_handle; cdecl;
FunUsbSetConfiguration: function (dev: pusb_dev_handle;configuration: longword): integer; cdecl;
FunUsbClaimInterface: function (dev: pusb_dev_handle;iinterface: longword): integer; cdecl;
FunUsbReleaseInterface: function (dev: pusb_dev_handle;iinterface: longword): integer; cdecl;
FunUsbSetAltInterface: function (dev: pusb_dev_handle;alternate: longword): integer; cdecl;
FunUsbClearHalt: function (dev: pusb_dev_handle;ep: longword): integer; cdecl;
FunUsbClose: function (dev: pusb_dev_handle): longword; cdecl;
FunUsbControlMsg: function (dev: pusb_dev_handle;requesttype, request, value, index: longword;var bytes;size, timeout: longword): integer; cdecl;
FunUsbBulkRead: function (dev: pusb_dev_handle;ep: longword; var bytes; size,timeout:longword): integer; cdecl;
FunUsbBulkWrite: function (dev: pusb_dev_handle;ep : longword; var bytes;size,timeout:longword): longword; cdecl;
FunUsbStrError: function : pchar; cdecl;
procedure Err(Msg: string);
procedure Initialize;
procedure LoadDll;
procedure OpenDevice;
procedure CloseDevice; virtual;
procedure ReadDataInternal(AControlPoint: integer; var ABuf: TByteArray);
procedure ReadData(AControlPoint: integer; var ABuf: TByteArray);
procedure ReadDataAsync(AControlPoint, ACount: integer);
procedure WriteData(AControlPoint: integer; var ABuf: TByteArray);
procedure DataArrived;
procedure DoData(AData: TByteArray; var ADone: boolean); virtual; abstract;
public
constructor Create;
destructor Destroy; override;
function IsRunning: boolean;
property VendorId: integer read FVendorId write FVendorId;
property ProductId: integer read FProductId write FProductId;
property Initialized: boolean read FInitialized;
property StatusText: string read FStatusText;
end;
implementation
{ TReadThread }
procedure TReadThread.Execute;
begin
repeat
if Terminated then Exit;
try
Papa.ReadDataInternal(ControlPoint, Buf);
except on E: Exception do
begin
Papa.FStatusText := E.Message;
Papa.Thr := nil;
Terminate;
end;
end;
if Terminated then Exit;
Synchronize(Papa.DataArrived);
until false;
end;
{ TUsbDevice }
constructor TUsbDevice.Create;
begin
Initialize;
end;
destructor TUsbDevice.Destroy;
begin
CloseDevice;
if FLib <> 0 then FreeLibrary(FLib);
inherited;
end;
procedure TUsbDevice.Err(Msg: string);
begin
CloseDevice;
FStatusText := Msg;
raise Exception.Create(Msg);
end;
procedure TUsbDevice.Initialize;
begin
try
LoadDll;
FInitialized := true;
FStatusText := 'OK';
except
FStatusText := 'Unable to load ' + LIBUSB_DLL_NAME;
end;
end;
procedure TUsbDevice.LoadDll;
begin
FLib := LoadLibrary(LIBUSB_DLL_NAME);
if FLib = 0 then Abort;
try
@FunUsbInit := GetProcAddress(FLib, 'usb_init');
if not Assigned(FunUsbInit) then Abort;
@FunUsbFindBuses := GetProcAddress(FLib, 'usb_find_busses');
if not Assigned(FunUsbFindBuses) then Abort;
@FunUsbFindDefices := GetProcAddress(FLib, 'usb_find_devices');
if not Assigned(FunUsbFindDefices) then Abort;
@FunUsbGetBuses := GetProcAddress(FLib, 'usb_get_busses');
if not Assigned(FunUsbGetBuses) then Abort;
@FunUsbOpen := GetProcAddress(FLib, 'usb_open');
if not Assigned(FunUsbOpen) then Abort;
@FunUsbSetConfiguration := GetProcAddress(FLib, 'usb_set_configuration');
if not Assigned(FunUsbSetConfiguration) then Abort;
@FunUsbClaimInterface := GetProcAddress(FLib, 'usb_claim_interface');
if not Assigned(FunUsbClaimInterface) then Abort;
@FunUsbReleaseInterface := GetProcAddress(FLib, 'usb_release_interface');
if not Assigned(FunUsbReleaseInterface) then Abort;
@FunUsbSetAltInterface := GetProcAddress(FLib, 'usb_set_altinterface');
if not Assigned(FunUsbSetAltInterface) then Abort;
@FunUsbClearHalt := GetProcAddress(FLib, 'usb_clear_halt');
if not Assigned(FunUsbClearHalt) then Abort;
@FunUsbClose := GetProcAddress(FLib, 'usb_close');
if not Assigned(FunUsbClose) then Abort;
@FunUsbControlMsg := GetProcAddress(FLib, 'usb_control_msg');
if not Assigned(FunUsbControlMsg) then Abort;
@FunUsbBulkRead := GetProcAddress(FLib, 'usb_bulk_read');
if not Assigned(FunUsbBulkRead) then Abort;
@FunUsbBulkWrite := GetProcAddress(FLib, 'usb_bulk_write');
if not Assigned(FunUsbBulkWrite) then Abort;
@FunUsbStrError := GetProcAddress(FLib, 'usb_strerror');
if not Assigned(FunUsbStrError) then Abort;
except
FreeLibrary(FLib);
FLib := 0;
Abort;
end;
end;
procedure TUsbDevice.OpenDevice;
var
Bus: pusb_bus;
Dev: pusb_device;
begin
if not FInitialized then Err(FStatusText);
FStatusText := 'OK';
FunUsbInit;
FunUsbFindBuses;
FunUsbFindDefices;
Bus := FunUsbGetBuses;
while Bus <> nil do
begin
Dev := Bus.devices;
while Dev <> nil do
with Dev.descriptor do
if (idVendor = FVendorId) and (idProduct = FProductId)
then
begin
FHandle := FunUsbOpen(Dev);
if FHandle <> nil then Exit else Err('usb_open failed');
end
else
Dev := Dev.next;
Bus := Bus.next;
end;
Err('USB device not found');
end;
procedure TUsbDevice.CloseDevice;
begin
if FHandle = nil then Exit;
if Thr <> nil then
if Thr.Suspended
then
FreeAndNil(Thr)
else
begin
Thr.Terminate;
Thr := nil;
end;
FunUsbClose(FHandle);
FHandle := nil;
end;
//calls Err() if an error occurs
procedure TUsbDevice.ReadData(AControlPoint: integer; var ABuf: TByteArray);
begin
if FHandle = nil then Err('ReadData failed: device not open');
try
ReadDataInternal(AControlPoint, ABuf);
except on E: Exception do
Err(E.Message);
end;
end;
//raises an exception if an error occurs
procedure TUsbDevice.ReadDataInternal(AControlPoint: integer; var ABuf: TByteArray);
var
Cnt: integer;
begin
Cnt := FunUsbBulkRead(FHandle, AControlPoint, ABuf[0], Length(ABuf), 5000);
if Cnt <> Length(ABuf)
then raise Exception.Create('usb_bulk_read failed');
end;
procedure TUsbDevice.WriteData(AControlPoint: integer; var ABuf: TByteArray);
var
Cnt: integer;
begin
Cnt := FunUsbBulkWrite(FHandle, AControlPoint, ABuf[0], Length(ABuf), 5000);
if Cnt <> Length(ABuf)
then raise Exception.Create('usb_bulk_write failed');
end;
procedure TUsbDevice.ReadDataAsync(AControlPoint, ACount: integer);
begin
if FHandle = nil then Err('ReadDataAsync failed: device not open');
Thr := TReadThread.Create(true);
Thr.FreeOnTerminate := true;
Thr.Papa := Self;
Thr.ControlPoint := AControlPoint;
SetLength(Thr.Buf, ACount);
Thr.Resume;
end;
procedure TUsbDevice.DataArrived;
var
Done: boolean;
begin
if Thr = nil then Exit;
Done := false;
try
DoData(Thr.Buf, Done);
except
//Application.HandleException(Self);
end;
if Done then begin Thr.Terminate; Thr := nil; end;
end;
function TUsbDevice.IsRunning: boolean;
begin
Result := (FHandle <> nil);
end;
end.
|
//
// Generated by JavaToPas v1.5 20171018 - 170907
////////////////////////////////////////////////////////////////////////////////
unit java.util.OptionalLong;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
java.util.function.LongConsumer,
java.util.function.LongSupplier,
java.util.function.Supplier;
type
JOptionalLong = interface;
JOptionalLongClass = interface(JObjectClass)
['{0E28DD2A-8CEA-428A-AC78-37962087C9D8}']
function &of(value : Int64) : JOptionalLong; cdecl; // (J)Ljava/util/OptionalLong; A: $9
function empty : JOptionalLong; cdecl; // ()Ljava/util/OptionalLong; A: $9
function equals(obj : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1
function getAsLong : Int64; cdecl; // ()J A: $1
function hashCode : Integer; cdecl; // ()I A: $1
function isPresent : boolean; cdecl; // ()Z A: $1
function orElse(other : Int64) : Int64; cdecl; // (J)J A: $1
function orElseGet(other : JLongSupplier) : Int64; cdecl; // (Ljava/util/function/LongSupplier;)J A: $1
function orElseThrow(exceptionSupplier : JSupplier) : Int64; cdecl; // (Ljava/util/function/Supplier;)J A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
procedure ifPresent(consumer : JLongConsumer) ; cdecl; // (Ljava/util/function/LongConsumer;)V A: $1
end;
[JavaSignature('java/util/OptionalLong')]
JOptionalLong = interface(JObject)
['{87DF52AC-CC18-4180-9754-039D2A7995D7}']
function equals(obj : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1
function getAsLong : Int64; cdecl; // ()J A: $1
function hashCode : Integer; cdecl; // ()I A: $1
function isPresent : boolean; cdecl; // ()Z A: $1
function orElse(other : Int64) : Int64; cdecl; // (J)J A: $1
function orElseGet(other : JLongSupplier) : Int64; cdecl; // (Ljava/util/function/LongSupplier;)J A: $1
function orElseThrow(exceptionSupplier : JSupplier) : Int64; cdecl; // (Ljava/util/function/Supplier;)J A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
procedure ifPresent(consumer : JLongConsumer) ; cdecl; // (Ljava/util/function/LongConsumer;)V A: $1
end;
TJOptionalLong = class(TJavaGenericImport<JOptionalLongClass, JOptionalLong>)
end;
implementation
end.
|
unit XED.ExtensionEnum;
{$Z4}
interface
type
TXED_Extension_Enum = (
XED_EXTENSION_INVALID,
XED_EXTENSION_3DNOW,
XED_EXTENSION_3DNOW_PREFETCH,
XED_EXTENSION_ADOX_ADCX,
XED_EXTENSION_AES,
XED_EXTENSION_AMD_INVLPGB,
XED_EXTENSION_AMX_BF16,
XED_EXTENSION_AMX_INT8,
XED_EXTENSION_AMX_TILE,
XED_EXTENSION_AVX,
XED_EXTENSION_AVX2,
XED_EXTENSION_AVX2GATHER,
XED_EXTENSION_AVX512EVEX,
XED_EXTENSION_AVX512VEX,
XED_EXTENSION_AVXAES,
XED_EXTENSION_AVX_VNNI,
XED_EXTENSION_BASE,
XED_EXTENSION_BMI1,
XED_EXTENSION_BMI2,
XED_EXTENSION_CET,
XED_EXTENSION_CLDEMOTE,
XED_EXTENSION_CLFLUSHOPT,
XED_EXTENSION_CLFSH,
XED_EXTENSION_CLWB,
XED_EXTENSION_CLZERO,
XED_EXTENSION_ENQCMD,
XED_EXTENSION_F16C,
XED_EXTENSION_FMA,
XED_EXTENSION_FMA4,
XED_EXTENSION_GFNI,
XED_EXTENSION_HRESET,
XED_EXTENSION_INVPCID,
XED_EXTENSION_KEYLOCKER,
XED_EXTENSION_KEYLOCKER_WIDE,
XED_EXTENSION_LONGMODE,
XED_EXTENSION_LZCNT,
XED_EXTENSION_MCOMMIT,
XED_EXTENSION_MMX,
XED_EXTENSION_MONITOR,
XED_EXTENSION_MONITORX,
XED_EXTENSION_MOVBE,
XED_EXTENSION_MOVDIR,
XED_EXTENSION_MPX,
XED_EXTENSION_PAUSE,
XED_EXTENSION_PCLMULQDQ,
XED_EXTENSION_PCONFIG,
XED_EXTENSION_PKU,
XED_EXTENSION_PREFETCHWT1,
XED_EXTENSION_PTWRITE,
XED_EXTENSION_RDPID,
XED_EXTENSION_RDPRU,
XED_EXTENSION_RDRAND,
XED_EXTENSION_RDSEED,
XED_EXTENSION_RDTSCP,
XED_EXTENSION_RDWRFSGS,
XED_EXTENSION_RTM,
XED_EXTENSION_SERIALIZE,
XED_EXTENSION_SGX,
XED_EXTENSION_SGX_ENCLV,
XED_EXTENSION_SHA,
XED_EXTENSION_SMAP,
XED_EXTENSION_SMX,
XED_EXTENSION_SNP,
XED_EXTENSION_SSE,
XED_EXTENSION_SSE2,
XED_EXTENSION_SSE3,
XED_EXTENSION_SSE4,
XED_EXTENSION_SSE4A,
XED_EXTENSION_SSSE3,
XED_EXTENSION_SVM,
XED_EXTENSION_TBM,
XED_EXTENSION_TDX,
XED_EXTENSION_TSX_LDTRK,
XED_EXTENSION_UINTR,
XED_EXTENSION_VAES,
XED_EXTENSION_VIA_PADLOCK_AES,
XED_EXTENSION_VIA_PADLOCK_MONTMUL,
XED_EXTENSION_VIA_PADLOCK_RNG,
XED_EXTENSION_VIA_PADLOCK_SHA,
XED_EXTENSION_VMFUNC,
XED_EXTENSION_VPCLMULQDQ,
XED_EXTENSION_VTX,
XED_EXTENSION_WAITPKG,
XED_EXTENSION_WBNOINVD,
XED_EXTENSION_X87,
XED_EXTENSION_XOP,
XED_EXTENSION_XSAVE,
XED_EXTENSION_XSAVEC,
XED_EXTENSION_XSAVEOPT,
XED_EXTENSION_XSAVES,
XED_EXTENSION_LAST);
/// This converts strings to #xed_extension_enum_t types.
/// @param s A C-string.
/// @return #xed_extension_enum_t
/// @ingroup ENUM
function str2xed_extension_enum_t(s: PAnsiChar): TXED_Extension_Enum; cdecl; external 'xed.dll';
/// This converts strings to #xed_extension_enum_t types.
/// @param p An enumeration element of type xed_extension_enum_t.
/// @return string
/// @ingroup ENUM
function xed_extension_enum_t2str(const p: TXED_Extension_Enum): PAnsiChar; cdecl; external 'xed.dll';
/// Returns the last element of the enumeration
/// @return xed_extension_enum_t The last element of the enumeration.
/// @ingroup ENUM
function xed_extension_enum_t_last:TXED_Extension_Enum;cdecl; external 'xed.dll';
implementation
end.
|
unit uECFFch;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, ExtCtrls, cxDBEdit,
cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit,
cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, DB, DBClient;
type
TECFFch = class(TForm)
pnlBottom: TPanel;
btCancel: TcxButton;
btOk: TcxButton;
luStore: TcxDBLookupComboBox;
luCashRegister: TcxDBLookupComboBox;
edECFNumber: TcxDBTextEdit;
edSerialNumber: TcxDBTextEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
dsFch: TDataSource;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btOkClick(Sender: TObject);
procedure btCancelClick(Sender: TObject);
private
FDataSet: TClientDataSet;
function ValidateECF: Boolean;
function ValidateRequiredFields: Boolean;
public
procedure Start(ADataSet: TClientDataSet);
procedure NewRecord;
procedure EditRecord;
end;
implementation
uses uDMSintegra, ADODB;
{$R *.dfm}
procedure TECFFch.FormCreate(Sender: TObject);
begin
with DMSintegra do
begin
if quStore.Active then
quStore.Close;
quStore.Open;
if quCashRegister.Active then
quCashRegister.Close;
quCashRegister.Open;
end;
end;
procedure TECFFch.NewRecord;
begin
FDataSet.Append;
with DMSintegra.spGetNextCode do
begin
Parameters.ParamByName('@Tabela').Value := 'Sal_ECF.IDECF';
ExecProc;
FDataSet.FieldByName('IDECF').AsInteger := Parameters.ParamByName('@NovoCodigo').Value;
end;
ShowModal;
end;
procedure TECFFch.btOkClick(Sender: TObject);
begin
if ValidateRequiredFields then
if ValidateECF then
begin
if FDataSet.State in dsEditModes then
FDataSet.Post;
FDataSet.ApplyUpdates(-1);
Close;
end;
end;
procedure TECFFch.EditRecord;
begin
FDataSet.Edit;
ShowModal;
end;
procedure TECFFch.btCancelClick(Sender: TObject);
begin
FDataSet.Cancel;
Close;
end;
procedure TECFFch.Start(ADataSet: TClientDataSet);
begin
FDataSet := ADataSet;
dsFch.DataSet := FDataSet;
end;
function TECFFch.ValidateECF: Boolean;
begin
with DMSintegra.quFreeSQL do
begin
SQL.Text := 'SELECT * FROM Sal_ECF WHERE IDStore = :IDStore AND NumeroECF = :NumeroECF AND IDECF <> :IDECF';
Parameters.ParamByName('IDECF').Value := FDataSet.FieldByName('IDECF').Value;
Parameters.ParamByName('IDStore').Value := luStore.EditValue;
Parameters.ParamByName('NumeroECF').Value := edECFNumber.Text;
Open;
Result := IsEmpty;
Close;
if Result then
begin
SQL.Text := 'SELECT * FROM Sal_ECF WHERE NumeroSerie = :NumeroSerie AND IDECF <> :IDECF';
Parameters.ParamByName('IDECF').Value := FDataSet.FieldByName('IDECF').Value;
Parameters.ParamByName('NumeroSerie').Value := edSerialNumber.Text;
Open;
Result := IsEmpty;
if not Result then
ShowMessage('Número de série já cadastrado.');
end
else
ShowMessage('ECF já cadastrado para esta loja.');
end;
end;
procedure TECFFch.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if FDataSet.State in dsEditModes then
FDataSet.Cancel;
end;
function TECFFch.ValidateRequiredFields: Boolean;
begin
Result := False;
if luStore.EditValue = null then
begin
ShowMessage('Loja não preenchida.');
Exit;
end;
if luCashRegister.EditValue = null then
begin
ShowMessage('Caixa não preenchida.');
Exit;
end;
if edECFNumber.Text = '' then
begin
ShowMessage('ECF não preenchido.');
Exit;
end;
if edSerialNumber.Text = '' then
begin
ShowMessage('Número de série não preenchido.');
Exit;
end;
Result := True;
end;
end.
|
procedure CaptureDesktop(aBitmap:TBitMap);
//
// Captura o Desktop corrente
//
var
Canvas : TCanvas;
begin
Canvas:=Tcanvas.Create;
try
Canvas.Handle:=GetDc(0);
aBitMap.Canvas.CopyRect(Canvas.ClipRect,Canvas,Canvas.ClipRect);
finally
ReleaseDc(0,Canvas.Handle);
Canvas.Free;
end;
end;
|
unit ConfiguracoesExportar.Model;
interface
uses ConfiguracoesExportar.Model.interf, Inifiles, System.SysUtils;
type
TConfiguracoesExportarModel = class(TInterfacedObject,
IConfiguracoesExportarModel)
private
FFileName: string;
FFileIni: TIniFile;
procedure verificarParametrosDeExportacao;
procedure gravarParametrosPadraoDeExportacao;
public
constructor Create;
destructor Destroy; override;
class function New: IConfiguracoesExportarModel;
function diretorioExportarOrcamentoCsv: string;
end;
implementation
{ TConfiguracoesExportarModel }
constructor TConfiguracoesExportarModel.Create;
begin
FFileName := ChangeFileExt(ParamStr(0), '.ini');
FFileIni := TIniFile.Create(FFileName);
verificarParametrosDeExportacao;
end;
destructor TConfiguracoesExportarModel.Destroy;
begin
inherited;
end;
function TConfiguracoesExportarModel.diretorioExportarOrcamentoCsv: string;
begin
Result := FFileIni.ReadString('Exportar', 'DiretorioOrcamento', 'c:\tcc\exportar');
end;
procedure TConfiguracoesExportarModel.gravarParametrosPadraoDeExportacao;
begin
FFileIni.WriteString('Exportar', 'DiretorioOrcamento', 'c:\tcc\exportar');
end;
class function TConfiguracoesExportarModel.New: IConfiguracoesExportarModel;
begin
Result := Self.Create;
end;
procedure TConfiguracoesExportarModel.verificarParametrosDeExportacao;
begin
if not(FileExists(FFileName)) then
gravarParametrosPadraoDeExportacao;
if FileExists(FFileName) then
if (FFileIni.ReadString('Exportar', 'DiretorioOrcamento', '') = EmptyStr) then
gravarParametrosPadraoDeExportacao;
end;
end.
|
unit BaseTestRest;
interface
uses RestClient, TestFramework;
type
TBaseTestRest = class(TTestCase)
private
FRestClient: TRestClient;
protected
procedure SetUp; override;
procedure TearDown; override;
public
property RestClient: TRestClient read FRestClient;
class procedure RegisterTest;
end;
const
CONTEXT_PATH = 'http://localhost:8080/java-rest-server/rest/';
implementation
{ TBaseTestRest }
class procedure TBaseTestRest.RegisterTest;
begin
TestFramework.RegisterTest(Self.Suite);
end;
procedure TBaseTestRest.SetUp;
begin
inherited;
FRestClient := TRestClient.Create;
end;
procedure TBaseTestRest.TearDown;
begin
FRestClient.Free;
inherited;
end;
end.
|
unit Log4DDemo1;
{
Demonstrate the Log4D package.
Written by Keith Wood (kbwood@iprimus.com.au)
}
interface
{$I Defines.inc}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, Log4D, Log4DXML;
type
{ A custom appender to write to a named memo component. }
TMemoAppender = class(TLogCustomAppender)
private
FMemo: TMemo;
protected
procedure DoAppend(const Message: string); override;
procedure SetOption(const Name, Value: string); override;
public
constructor Create(const Name: string; const Memo: TMemo); reintroduce;
end;
{ A custom renderer for components. }
TComponentRenderer = class(TLogCustomRenderer)
public
function Render(const Message: TObject): string; override;
end;
{ The demonstration form.
Allows you to set logging levels, filter value, NDC, and threshold,
then generate logging events at will. }
TfrmLog4DDemo = class(TForm)
pnlControls: TPanel;
Label1: TLabel;
cmbLevel: TComboBox;
Label2: TLabel;
cmbLogger: TComboBox;
Label3: TLabel;
edtMessage: TEdit;
btnLog: TButton;
btnLoop: TButton;
grpFilter: TGroupBox;
edtFilter: TEdit;
grpNDC: TGroupBox;
edtNDC: TEdit;
btnPush: TButton;
lblNDC: TLabel;
btnPop: TButton;
grpThreshold: TGroupBox;
cmbThreshold: TComboBox;
pnlLeft: TPanel;
pnlMyapp: TPanel;
chkMyappAdditive: TCheckBox;
cmbMyappLevel: TComboBox;
memMyApp: TMemo;
splLeft: TSplitter;
pnlMyappMore: TPanel;
chkMyappMoreAdditive: TCheckBox;
cmbMyappMoreLevel: TComboBox;
memMyAppMore: TMemo;
splVert: TSplitter;
pnlRight: TPanel;
pnlMyappOther: TPanel;
chkMyappOtherAdditive: TCheckBox;
cmbMyappOtherLevel: TComboBox;
memMyAppOther: TMemo;
splRight: TSplitter;
pnlAlt: TPanel;
chkAltAdditive: TCheckBox;
cmbAltLevel: TComboBox;
memAlt: TMemo;
procedure FormCreate(Sender: TObject);
procedure btnLogClick(Sender: TObject);
procedure btnPushClick(Sender: TObject);
procedure btnPopClick(Sender: TObject);
procedure btnLoopClick(Sender: TObject);
procedure cmbLoggerLevelChange(Sender: TObject);
procedure cmbThresholdChange(Sender: TObject);
procedure chkAdditiveChange(Sender: TObject);
procedure edtFilterChange(Sender: TObject);
procedure splLeftMoved(Sender: TObject);
procedure splRightMoved(Sender: TObject);
private
FFilter: ILogFilter;
FLogs: array [0..3] of TLogLogger;
public
end;
var
frmLog4DDemo: TfrmLog4DDemo;
implementation
{$R *.DFM}
{ TMemoAppender ---------------------------------------------------------------}
{ Initialisation - attach to memo. }
constructor TMemoAppender.Create(const Name: string; const Memo: TMemo);
begin
inherited Create(Name);
FMemo := Memo;
end;
{ Add the message to the memo. }
procedure TMemoAppender.DoAppend(const Message: string);
var
Msg: string;
begin
if Assigned(FMemo) and Assigned(FMemo.Parent) then
begin
if Copy(Message, Length(Message) - 1, 2) = #13#10 then
Msg := Copy(Message, 1, Length(Message) - 2)
else
Msg := Message;
FMemo.Lines.Add(Msg);
end;
end;
{ Find the named memo and attach to it (if the param is 'memo'). }
procedure TMemoAppender.SetOption(const Name, Value: string);
begin
inherited SetOption(Name, Value);
if (Name = 'memo') and (Value <> '') then
begin
FMemo := frmLog4DDemo.FindComponent(Value) as TMemo;
WriteHeader;
end;
end;
{ TComponentRenderer ----------------------------------------------------------}
{ Display a component as its name and type. }
function TComponentRenderer.Render(const Message: TObject): string;
var
Comp: TComponent;
begin
if not (Message is TComponent) then
Result := 'Object must be a TComponent'
else
begin
Comp := Message as TComponent;
if Comp is TControl then
// Add position and size info
with TControl(Comp) do
Result := Format('%s: %s [%d x %d at %d, %d]',
[Name, ClassName, Width, Height, Left, Top])
else
Result := Format('%s: %s', [Comp.Name, Comp.ClassName]);
end;
end;
{ TfrmLog4DDemo ---------------------------------------------------------------}
{ Initialisation. }
procedure TfrmLog4DDemo.FormCreate(Sender: TObject);
const
IsAdditive: array [Boolean] of string = ('not ', '');
Header = ' %s (%sadditive) - %s';
begin
// Initialise from stored configuration - select between INI style file
// or XML document by uncommenting one of the following two lines
TLogPropertyConfigurator.Configure('log4d.props');
// TLogXMLConfigurator.Configure('log4d.xml');
// Create loggers for logging - both forms are equivalent
FLogs[0] := DefaultHierarchy.GetLogger('myapp');
FLogs[1] := TLogLogger.GetLogger('myapp.more');
FLogs[2] := DefaultHierarchy.GetLogger('myapp.other');
FLogs[3] := TLogLogger.GetLogger('alt');
// Show their state on the form
pnlMyApp.Caption := ' ' + FLogs[0].Name;
pnlMyAppMore.Caption := ' ' + FLogs[1].Name;
pnlMyAppOther.Caption := ' ' + FLogs[2].Name;
pnlAlt.Caption := ' ' + FLogs[3].Name;
// Attach to the filter on the first logger
FFilter := ILogFilter(ILogAppender(FLogs[0].Appenders[0]).Filters[0]);
edtFilter.Text := FFilter.Options['match'];
// Load levels into a combobox
cmbLevel.Items.AddObject(Fatal.Name, Fatal);
cmbLevel.Items.AddObject(Error.Name, Error);
cmbLevel.Items.AddObject(Warn.Name, Warn);
cmbLevel.Items.AddObject(Info.Name, Info);
cmbLevel.Items.AddObject(Debug.Name, Debug);
cmbLevel.ItemIndex := 0;
// Set threshold level
cmbThreshold.Items.Assign(cmbLevel.Items);
cmbThreshold.Items.InsertObject(0, Off.Name, Off);
cmbThreshold.Items.AddObject(All.Name, All);
cmbThreshold.ItemIndex :=
cmbThreshold.Items.IndexOfObject(FLogs[0].Hierarchy.Threshold);
// Set levels and additivity per logger
cmbMyappLevel.Items.Assign(cmbThreshold.Items);
cmbMyappLevel.ItemIndex := cmbMyAppLevel.Items.IndexOf(FLogs[0].Level.Name);
chkMyappAdditive.Checked := Flogs[0].Additive;
cmbMyappMoreLevel.Items.Assign(cmbThreshold.Items);
cmbMyappMoreLevel.ItemIndex :=
cmbMyAppMoreLevel.Items.IndexOf(FLogs[1].Level.Name);
chkMyappMoreAdditive.Checked := Flogs[1].Additive;
cmbMyappOtherLevel.Items.Assign(cmbThreshold.Items);
cmbMyappOtherLevel.ItemIndex :=
cmbMyAppOtherLevel.Items.IndexOf(FLogs[2].Level.Name);
chkMyappOtherAdditive.Checked := Flogs[2].Additive;
cmbAltLevel.Items.Assign(cmbThreshold.Items);
cmbAltLevel.ItemIndex :=
cmbAltLevel.Items.IndexOf(FLogs[3].Level.Name);
chkAltAdditive.Checked := Flogs[3].Additive;
end;
{ Log an event based on user selections. }
procedure TfrmLog4DDemo.btnLogClick(Sender: TObject);
var
Level: TLogLevel;
begin
Level := TLogLevel(cmbLevel.Items.Objects[cmbLevel.ItemIndex]);
// Log message as given
FLogs[cmbLogger.ItemIndex].Log(Level, edtMessage.Text);
// Log the edit control as an object as well
FLogs[cmbLogger.ItemIndex].Log(Level, edtMessage);
end;
{ Add a context entry. }
procedure TfrmLog4DDemo.btnPushClick(Sender: TObject);
begin
if edtNDC.Text <> '' then
begin
TLogNDC.Push(edtNDC.Text);
edtNDC.Text := '';
edtNDC.SetFocus;
lblNDC.Caption := TLogNDC.Peek;
end;
end;
{ Remove a context entry. }
procedure TfrmLog4DDemo.btnPopClick(Sender: TObject);
begin
TLogNDC.Pop;
lblNDC.Caption := TLogNDC.Peek;
end;
{ Sample logging from loop, including error. }
procedure TfrmLog4DDemo.btnLoopClick(Sender: TObject);
var
Index: Integer;
begin
try
for Index := 5 downto 0 do
FLogs[cmbLogger.ItemIndex].Info(
Format('%d divided by %d is %g', [3, Index, 3 / Index]));
except on ex: Exception do
FLogs[cmbLogger.ItemIndex].Fatal('Error in calculation', ex);
end;
end;
{ Change logging level for a log. }
procedure TfrmLog4DDemo.cmbLoggerLevelChange(Sender: TObject);
begin
with TComboBox(Sender) do
FLogs[Tag].Level := TLogLevel(Items.Objects[ItemIndex]);
end;
{ Set the overall logging level threshold. }
procedure TfrmLog4DDemo.cmbThresholdChange(Sender: TObject);
begin
FLogs[0].Hierarchy.Threshold :=
TLogLevel(cmbThreshold.Items.Objects[cmbThreshold.ItemIndex]);
end;
{ Change additivity for a log. }
procedure TfrmLog4DDemo.chkAdditiveChange(Sender: TObject);
begin
with TCheckBox(Sender) do
FLogs[Tag].Additive := Checked;
end;
{ Apply a new filter value. }
procedure TfrmLog4DDemo.edtFilterChange(Sender: TObject);
begin
FFilter.Options[MatchOpt] := edtFilter.Text;
end;
{ Keep splitters aligned. }
procedure TfrmLog4DDemo.splLeftMoved(Sender: TObject);
begin
memMyAppOther.Height := memMyApp.Height;
end;
{ Keep splitters aligned. }
procedure TfrmLog4DDemo.splRightMoved(Sender: TObject);
begin
memMyApp.Height := memMyAppOther.Height;
end;
initialization
{ Register new logging classes. }
RegisterAppender(TMemoAppender);
RegisterRendered(TComponent);
RegisterRenderer(TComponentRenderer);
end.
|
unit ufrmInputRekening;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufrmMaster, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Vcl.Menus,
Vcl.StdCtrls, cxButtons, cxMaskEdit, cxSpinEdit, cxTextEdit, cxStyles,
cxClasses, Vcl.ExtCtrls, uModRekening, uDmClient, UClientClasses, UAppUtils, uDxutils,
cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, Data.DB, cxDBData,
cxGridLevel, cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, uDbUtils, DbClient, cxDropDownEdit, cxLookupEdit,
cxDBLookupEdit, cxDBExtLookupComboBox;
type
TfrmInputRekening = class(TfrmMaster)
Label2: TLabel;
edDesciption: TcxTextEdit;
Label3: TLabel;
Label4: TLabel;
edName: TcxTextEdit;
edLevel: TcxSpinEdit;
Label5: TLabel;
edRekCode: TcxTextEdit;
Label6: TLabel;
pnlFooter: TPanel;
btnSave: TcxButton;
btnClose: TcxButton;
cxButton1: TcxButton;
cxLookupRekening: TcxExtLookupComboBox;
procedure FormCreate(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
private
FCDSRekening: tclientDataset;
FCrud: TCrudClient;
FDsProvider: TDSProviderClient;
FModRekening: TModRekening;
function GetCDSRekening: tclientDataset;
function GetCrud: TCrudClient;
function GetDsProvider: TDSProviderClient;
function GetModRekening: TModRekening;
procedure SimpanData;
property CDSRekening: tclientDataset read GetCDSRekening write FCDSRekening;
property Crud: TCrudClient read GetCrud write FCrud;
property DsProvider: TDSProviderClient read GetDsProvider write FDsProvider;
{ Private declarations }
public
{ Public declarations }
published
property ModRekening: TModRekening read GetModRekening write FModRekening;
end;
var
frmInputRekening: TfrmInputRekening;
implementation
{$R *.dfm}
procedure TfrmInputRekening.FormCreate(Sender: TObject);
begin
inherited;
cxLookupRekening.Properties.LoadFromCDS(cdsrekening,'REK_CODE', 'REK_NAME', ['ID'] , self);
cxLookupRekening.Properties.SetMultiPurposeLookup;
end;
procedure TfrmInputRekening.btnSaveClick(Sender: TObject);
begin
inherited;
SimpanData;
end;
function TfrmInputRekening.GetCDSRekening: tclientDataset;
begin
if not assigned(FCDSRekening) then
fCDSRekening := Tdbutils.DSToCDS(DsProvider.Rekening_GetDSOverview(), self);
Result := FCDSRekening;
end;
function TfrmInputRekening.GetCrud: TCrudClient;
begin
if not assigned(fCrud) then
fCrud := TCrudClient.Create(DmClient.RestConn,False);
Result := FCrud;
end;
function TfrmInputRekening.GetDsProvider: TDSProviderClient;
begin
if not assigned(FDsProvider) then
FDsProvider := TDSProviderClient.Create(DmClient.RestConn,False);
Result := FDsProvider;
end;
function TfrmInputRekening.GetModRekening: TModRekening;
begin
if not assigned(fModRekening) then
FModRekening := TModRekening.Create;
Result := FModRekening;
end;
procedure TfrmInputRekening.SimpanData;
begin
ModRekening.REK_CODE := edRekCode.Text;
ModRekening.REK_DESCRIPTION := edDesciption.Text;
ModRekening.REK_PARENT_CODE := cxLookupRekening.EditValue;
ModRekening.REK_NAME := edName.Text;
ModRekening.REK_LEVEL := edLevel.Value;
try
Crud.SaveToDB(ModRekening);
TAppUtils.Information('Berhasil bro');
except
TAppUtils.Error('gagal');
raise
end;
end;
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2015 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of an Embarcadero developer tools product.
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
unit AddPair;
interface
uses
Test;
type
TAddPair = class(TTest)
public
constructor Create;
class function CreateTest: TTest; static;
end;
implementation
uses
Box2D.Common, Box2D.Collision, Box2D.Dynamics, DebugDraw;
{ TAddPair }
constructor TAddPair.Create;
const
minX = -6.0;
maxX = 0.0;
minY = 4.0;
maxY = 6.0;
var
I: Integer;
shape: b2CircleShapeWrapper;
shape2: b2PolygonShapeWrapper;
bd: b2BodyDef;
body: b2BodyWrapper;
begin
inherited;
m_world.SetGravity(b2Vec2.Create(0.0, 0.0));
shape := b2CircleShapeWrapper.Create;
shape.Get_m_p.SetZero;
shape.Set_m_radius(0.1);
for I := 0 to 400 - 1 do
begin
bd := b2BodyDef.Create;
bd.&type := b2_dynamicBody;
bd.position := b2Vec2.Create(RandomFloat(minX,maxX),RandomFloat(minY,maxY));
body := m_world.CreateBody(@bd);
body.CreateFixture(shape, 0.01);
end;
shape2 := b2PolygonShapeWrapper.Create;
shape2.SetAsBox(1.5, 1.5);
bd := b2BodyDef.Create;
bd.&type := b2_dynamicBody;
bd.position.&Set(-40.0, 5.0);
bd.bullet := true;
body := m_world.CreateBody(@bd);
body.CreateFixture(shape2, 1.0);
body.SetLinearVelocity(b2Vec2.Create(150.0, 0.0));
shape.Destroy;
shape2.Destroy;
end;
class function TAddPair.CreateTest: TTest;
begin
Result := TAddPair.Create;
end;
initialization
RegisterTest(TestEntry.Create('AddPair', @TAddPair.CreateTest));
end.
|
unit TPAGFORNECEDOR.Entidade.Model;
interface
uses
DB,
Classes,
SysUtils,
Generics.Collections,
/// orm
ormbr.types.blob,
ormbr.types.lazy,
ormbr.types.mapping,
ormbr.types.nullable,
ormbr.mapping.Classes,
ormbr.mapping.register,
ormbr.mapping.attributes;
type
[Entity]
[Table('TPAGFORNECEDOR', '')]
[PrimaryKey('CODIGO', NotInc, NoSort, False, 'Chave primária')]
TTPAGFORNECEDOR = class
private
{ Private declarations }
FCODIGO: String;
FIDFORNECEDOR: Integer;
FNOMEFANTASIA: nullable<String>;
FCNPJ: nullable<String>;
FIE: nullable<String>;
FTELEFONE: nullable<String>;
FEMAIL: nullable<String>;
FDATA_CADASTRO: TDateTime;
FULTIMA_ATUALIZACAO: TDateTime;
function getCODIGO: String;
function getDATA_CADASTRO: TDateTime;
function getULTIMA_ATUALIZACAO: TDateTime;
public
{ Public declarations }
[Restrictions([NotNull])]
[Column('CODIGO', ftString, 64)]
[Dictionary('CODIGO', 'Mensagem de validação', '', '', '', taLeftJustify)]
property CODIGO: String read getCODIGO write FCODIGO;
[Restrictions([NotNull])]
[Column('IDFORNECEDOR', ftInteger)]
[Dictionary('IDFORNECEDOR', 'Mensagem de validação', '', '', '', taCenter)]
property IDFORNECEDOR: Integer read FIDFORNECEDOR write FIDFORNECEDOR;
[Column('NOMEFANTASIA', ftString, 100)]
[Dictionary('NOMEFANTASIA', 'Mensagem de validação', '', '', '',
taLeftJustify)]
property NOMEFANTASIA: nullable<String> read FNOMEFANTASIA
write FNOMEFANTASIA;
[Column('CNPJ', ftString, 14)]
[Dictionary('CNPJ', 'Mensagem de validação', '', '', '', taLeftJustify)]
property CNPJ: nullable<String> read FCNPJ write FCNPJ;
[Column('IE', ftString, 22)]
[Dictionary('IE', 'Mensagem de validação', '', '', '', taLeftJustify)]
property IE: nullable<String> read FIE write FIE;
[Column('TELEFONE', ftString, 15)]
[Dictionary('TELEFONE', 'Mensagem de validação', '', '', '', taLeftJustify)]
property TELEFONE: nullable<String> read FTELEFONE write FTELEFONE;
[Column('EMAIL', ftString, 100)]
[Dictionary('EMAIL', 'Mensagem de validação', '', '', '', taLeftJustify)]
property EMAIL: nullable<String> read FEMAIL write FEMAIL;
[Restrictions([NotNull])]
[Column('DATA_CADASTRO', ftDateTime)]
[Dictionary('DATA_CADASTRO', 'Mensagem de validação', 'Now', '',
'!##/##/####;1;_', taCenter)]
property DATA_CADASTRO: TDateTime read getDATA_CADASTRO
write FDATA_CADASTRO;
[Restrictions([NotNull])]
[Column('ULTIMA_ATUALIZACAO', ftDateTime)]
[Dictionary('ULTIMA_ATUALIZACAO', 'Mensagem de validação', 'Now', '',
'!##/##/####;1;_', taCenter)]
property ULTIMA_ATUALIZACAO: TDateTime read getULTIMA_ATUALIZACAO
write FULTIMA_ATUALIZACAO;
end;
implementation
{ TTPAGFORNECEDOR }
function TTPAGFORNECEDOR.getCODIGO: String;
begin
if FCODIGO.IsEmpty then
FCODIGO := TGUID.NewGuid.ToString;
Result := FCODIGO;
end;
function TTPAGFORNECEDOR.getDATA_CADASTRO: TDateTime;
begin
if FDATA_CADASTRO = StrToDateTime('30/12/1899 00:00') then
FDATA_CADASTRO := Now;
Result := FDATA_CADASTRO;
end;
function TTPAGFORNECEDOR.getULTIMA_ATUALIZACAO: TDateTime;
begin
FULTIMA_ATUALIZACAO := Now;
Result := FULTIMA_ATUALIZACAO;
end;
initialization
TRegisterClass.RegisterEntity(TTPAGFORNECEDOR)
end.
|
unit uMundo;
interface
uses
System.Generics.Collections, uContinente, System.Classes, System.SysUtils;
type
TMundo = class
private
FoListaDeContinentes : TList<TContinente>;
function GetContinentes: TList<TContinente>;
procedure SetContinentes(const Value: TList<TContinente>);
public
property Continentes : TList<TContinente> read GetContinentes write SetContinentes;
procedure AdicionarContinente(AoContinente : TContinente);
constructor Create;
destructor Destroy; override;
function ToString : String; override;
end;
implementation
{ TListaDeContinentes }
procedure TMundo.AdicionarContinente(AoContinente: TContinente);
begin
FoListaDeContinentes.Add(AoContinente);
end;
constructor TMundo.Create;
begin
FoListaDeContinentes := TList<TContinente>.Create;
end;
function TMundo.GetContinentes: TList<TContinente>;
begin
Result := FoListaDeContinentes;
end;
procedure TMundo.SetContinentes(const Value: TList<TContinente>);
begin
FoListaDeContinentes := Value;
end;
function TMundo.ToString: String;
var
oContinente : TContinente;
begin
for oContinente in FoListaDeContinentes do
Result := oContinente.ToString + sLineBreak;
Result := Result + 'Dimensão total: ' + oContinente.AreaTotal.ToString + sLineBreak
+ 'População total: ' + oContinente.PopulacaoTotal.ToString + sLineBreak
+ 'Densidade: ' + oContinente.Densidade.ToString + sLineBreak
+ 'Maior População: ' + oContinente.MaiorPopulacao.ToString + sLineBreak
+ 'Menor População: ' + oContinente.MenorPopulacao.ToString + sLineBreak
+ 'Maior Área: ' + oContinente.MaiorArea.ToString + sLineBreak
+ 'Menor Área: ' + oContinente.MenorArea.ToString + sLineBreak
+ 'Diferença entre áreas: ' + oContinente.MaiorMenor.ToString + sLineBreak
+ ' ' + sLineBreak;
end;
destructor TMundo.Destroy;
begin
FoListaDeContinentes.Free;
end;
end.
|
unit ufrmSearchRekening;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufraFooterDialog2Button, ExtCtrls, DB,
StdCtrls, uConn, ufrmMasterDialog,
cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus,
cxButtons, cxControls, cxStyles, cxCustomData, cxFilter, cxData,
cxDataStorage, cxEdit, cxNavigator, cxDBData, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxGridLevel, cxClasses, cxGridCustomView,
cxGrid, System.Actions, Vcl.ActnList, ufraFooterDialog3Button;
type
TsearchRekMode = (mDebet,mCredit,mDisburstment,mReceipt,mJournalEntry,
mDailyBalance,mARPayments,mAPPayment);
TfrmDialogSearchRekening = class(TfrmMasterDialog)
pnl1: TPanel;
lbl1: TLabel;
lbl2: TLabel;
edtRekeningCode: TEdit;
edtRekeningName: TEdit;
pnl2: TPanel;
btnSearch: TcxButton;
cxGridViewSearchRekening: TcxGridDBTableView;
cxGridLevel1: TcxGridLevel;
cxGrid: TcxGrid;
cxColRekeningCode: TcxGridDBColumn;
cxColRekeningName: TcxGridDBColumn;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure edtRekeningCodeChange(Sender: TObject);
procedure footerDialogMasterbtnSaveClick(Sender: TObject);
procedure edtRekeningNameChange(Sender: TObject);
procedure edtRekeningCodeKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure edtRekeningCodeKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure strgGridKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure edtRekeningNameKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure strgGridKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure strgGridDblClick(Sender: TObject);
private
FIsProcessSuccessfull: boolean;
FCol: Integer;
FRow: Integer;
FKodeJurnalId: string;
procedure SetIsProcessSuccessfull(const Value: boolean);
procedure FindDataOnGrid(AText: String);
function GetDataRekeningByCompanyID(aCompanyID: Integer; aRekType: Smallint): TDataSet;
function GetDataAllRekeningByKdJurId: TDataSet;
function GetDataRekeningKasDanBank(ACode: string): TDataSet;
function LoadData(): TDataSet;
procedure SetCol(const Value: Integer);
procedure SetRow(const Value: Integer);
procedure SetKodeJurnalId(const Value: string);
public
{ Public declarations }
RekeningCode: string;
RekeningName: string;
searcMode: TsearchRekMode;
published
property IsProcessSuccessfull: boolean read FIsProcessSuccessfull write SetIsProcessSuccessfull;
property Col: Integer read FCol write SetCol;
property Row: Integer read FRow write SetRow;
property KodeJurnalId: string read FKodeJurnalId write SetKodeJurnalId;
end;
var
frmDialogSearchRekening: TfrmDialogSearchRekening;
implementation
{$R *.dfm}
procedure TfrmDialogSearchRekening.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
procedure TfrmDialogSearchRekening.FormDestroy(Sender: TObject);
begin
inherited;
frmDialogSearchRekening := nil;
end;
procedure TfrmDialogSearchRekening.FormShow(Sender: TObject);
var data : TDataSet;
i, countData : integer;
isDebet: SmallInt;
begin
// what kind of rek will be shown and from what company code?
if searcMode = mDebet then isDebet := 1
else isDebet := 0;
if searcMode in [mDebet,mCredit] then
data := GetDataRekeningByCompanyID(DialogCompany, isDebet)
else if searcMode in [mJournalEntry] then
data := GetDataAllRekeningByKdJurId
else if searcMode in [mDailyBalance] then
data := GetDataRekeningKasDanBank('1110')
else
data := LoadData;
countData := data.RecordCount;
{
with strgGrid do
begin
Clear;
RowCount := countData + 1;
ColCount := 2;
Cells[0,0] := 'REKENING CODE';
Cells[1,0] := 'REKENING NAME';
if RowCount > 1 then
begin
i := 1;
while not data.Eof do
begin
Cells[0, i] := data.FieldByName('REK_CODE').AsString;
Cells[1, i] := data.FieldByName('REK_NAME').AsString;
Inc(i);
data.Next;
end;
end
else
begin
RowCount := 2;
Cells[0, 1] := ' ';
Cells[1, 1] := ' ';
end;
AutoSize := true;
FixedRows := 1;
end;
}
edtRekeningCode.SetFocus;
end;
procedure TfrmDialogSearchRekening.edtRekeningCodeChange(Sender: TObject);
begin
FindDataOnGrid(edtRekeningCode.Text);
end;
procedure TfrmDialogSearchRekening.SetIsProcessSuccessfull(
const Value: boolean);
begin
FIsProcessSuccessfull := Value;
end;
procedure TfrmDialogSearchRekening.footerDialogMasterbtnSaveClick(
Sender: TObject);
begin
//initiate
RekeningCode := '';
RekeningName := '';
IsProcessSuccessfull := False;
{
if(strgGrid.Cells[0,strgGrid.Row])='' then Exit
else
begin
RekeningCode := strgGrid.Cells[0,strgGrid.Row];
RekeningName := strgGrid.Cells[1,strgGrid.Row];
IsProcessSuccessfull := True;
end;
}
Close;
end;
procedure TfrmDialogSearchRekening.FindDataOnGrid(AText: String);
var
resPoint: TPoint;
begin
if (AText <> '') then
begin
{
resPoint := strgGrid.Find(Point(0,0),AText,[fnIncludeFixed]);
if (resPoint.Y <> -1) then
begin
strgGrid.ScrollInView(resPoint.X, resPoint.Y);
strgGrid.SelectRows(resPoint.Y, 1);
end;
}
end;
end;
procedure TfrmDialogSearchRekening.edtRekeningNameChange(Sender: TObject);
begin
FindDataOnGrid(edtRekeningName.Text);
end;
function TfrmDialogSearchRekening.GetDataRekeningByCompanyID(aCompanyID: Integer; aRekType: SmallInt): TDataSet;
var arrParam : TArr;
begin
// if not Assigned(SearchRekening) then
// SearchRekening := TSearchRekening.Create;
SetLength(arrParam,2);
arrParam[0].tipe := ptInteger;
arrParam[0].data := aRekType;
arrParam[1].tipe := ptInteger;
arrParam[1].data := aCompanyID;
// Result := SearchRekening.GetListRekening(arrParam);
end;
procedure TfrmDialogSearchRekening.SetCol(const Value: Integer);
begin
FCol := Value;
end;
procedure TfrmDialogSearchRekening.SetRow(const Value: Integer);
begin
FRow := Value;
end;
procedure TfrmDialogSearchRekening.edtRekeningCodeKeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
if Key=VK_RETURN then footerDialogMasterbtnSaveClick(Self);
end;
procedure TfrmDialogSearchRekening.edtRekeningCodeKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
{add by didit: 19112007}
if (Key = VK_DOWN) then
cxGrid.SetFocus;
end;
procedure TfrmDialogSearchRekening.strgGridKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
{add by didit: 19112007}
if (Key = VK_UP) then
if (cxGridViewSearchRekening.DataController.RecNo = 1) then
begin
edtRekeningCode.SetFocus;
edtRekeningCode.SelectAll;
end;
end;
procedure TfrmDialogSearchRekening.edtRekeningNameKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
{add by didit: 19112007}
if (Key = VK_DOWN) then
cxGrid.SetFocus;
end;
procedure TfrmDialogSearchRekening.SetKodeJurnalId(const Value: string);
begin
FKodeJurnalId := Value;
end;
function TfrmDialogSearchRekening.LoadData: TDataSet;
var arrParam: TArr;
begin
Result := TDataSet.Create(Self);
if searcMode in [mDisburstment, mReceipt, mJournalEntry, mARPayments, mAPPayment] then
begin
SetLength(arrParam, 2);
arrParam[0].tipe := ptString;
arrParam[0].data := KodeJurnalId;
arrParam[1].tipe := ptInteger;
arrParam[1].data := DialogCompany;
// Result := SearchRekening.GetListRekeningByKodeJurnalId(arrParam);
end;
end;
function TfrmDialogSearchRekening.GetDataAllRekeningByKdJurId: TDataSet;
var arrParam: TArr;
begin
SetLength(arrParam, 2);
arrParam[0].tipe := ptString;
arrParam[0].data := KodeJurnalId;
arrParam[1].tipe := ptInteger;
arrParam[1].data := DialogCompany;
// if not Assigned(SearchRekening) then
// SearchRekening := TSearchRekening.Create;
//
// Result := SearchRekening.GetListAllRekeningByKodeJurnalId(arrParam);
end;
procedure TfrmDialogSearchRekening.strgGridKeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
if Key = VK_RETURN then
footerDialogMaster.btnSave.Click;
end;
procedure TfrmDialogSearchRekening.strgGridDblClick(Sender: TObject);
begin
inherited;
footerDialogMaster.btnSave.Click;
end;
function TfrmDialogSearchRekening.GetDataRekeningKasDanBank(
ACode: string): TDataSet;
var arrParam: TArr;
begin
SetLength(arrParam, 2);
arrParam[0].tipe := ptString;
arrParam[0].data := ACode + '%';
arrParam[1].tipe := ptInteger;
arrParam[1].data := DialogCompany;
// Result := SearchRekening.GetListRekeningKasDanBank(arrParam);
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Core.Compiler.MSBuild;
interface
uses
System.Classes,
Spring.Collections,
VSoft.CancellationToken,
DPM.Core.Types,
DPM.Core.Logging,
DPM.Core.Compiler.Interfaces;
type
//Do not create directly, inject a compilerfactory.
TMSBuildCompiler = class(TInterfacedObject, ICompiler)
private
FLogger : ILogger;
FEnv : ICompilerEnvironmentProvider;
FCompilerLogFile : string;
FBPLOutput : string;
FLibOutput : string;
FCompilerVersion : TCompilerVersion;
FConfiguration : string;
FProjectFile : string;
FPlatform : TDPMPlatform;
FSearchPaths : IList<string>;
FVerbosity : TCompilerVerbosity;
FCompilerOutput : TStringList;
FBuildForDesign : boolean;
protected
function GetBPLOutput : string;
function GetCompilerVersion : TCompilerVersion;
function GetConfiguration : string;
function GetLibOutput : string;
function GetPlatform : TDPMPlatform;
function GetSearchPaths : IList<string>;
procedure SetConfiguration(const value : string);
procedure SetLibOutput(const value : string);
procedure SetBPLOutput(const value : string);
procedure SetSearchPaths(const value : IList<string>);
function GetVerbosity : TCompilerVerbosity;
procedure SetVerbosity(const value : TCompilerVerbosity);
function GetPlatformName : string;
function GetProjectSearchPath(const configName : string) : string;
function GetCompilerOutput : TStrings;
function GetMSBuildParameters(const configName : string; const packageVersion : TPackageVersion) : string;
function GetCommandLine(const projectFile : string; const configName : string; const packageVersion : TPackageVersion) : string;
function BuildProject(const cancellationToken : ICancellationToken; const projectFile : string; const configName : string; const packageVersion : TPackageVersion; const forDesign : boolean) : Boolean;
public
constructor Create(const logger : ILogger; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const env : ICompilerEnvironmentProvider);
destructor Destroy; override;
end;
implementation
uses
System.SysUtils,
System.IOUtils,
DPM.Core.Utils.Path,
DPM.Core.Utils.Process,
DPM.Core.Compiler.ProjectSettings;
{ TMSBuildCompiler }
function TMSBuildCompiler.BuildProject(const cancellationToken : ICancellationToken; const projectFile : string; const configName : string; const packageVersion : TPackageVersion; const forDesign : boolean) : Boolean;
var
commandLine : string;
env : IEnvironmentBlock;
begin
result := false;
FBuildForDesign := forDesign;
FCompilerOutput.Clear;
FCompilerLogFile := TPath.GetTempFileName;
FProjectFile := projectFile;
try
commandLine := GetCommandLine(projectFile, configName, packageVersion);
except
on e : Exception do
begin
FLogger.Error('Error generating command line : ' + e.Message);
exit;
end;
end;
env := TEnvironmentBlockFactory.Create(nil, true);
{$IFDEF DEBUG}
//THE IDE set these, which makes it difficult to debug the command line version.
env.RemoveVariable('BDS');
env.RemoveVariable('BDSLIB');
env.RemoveVariable('BDSINCLUDE');
env.RemoveVariable('BDSCOMMONDIR');
{$ENDIF}
env.RemoveVariable('PLATFORM');
//envoptions causes problems on our build machines, haven't figured out why yet.
env.AddOrSet('ImportEnvOptions','false');
FLogger.Debug('Compler - cmdline : ' + commandLine);
try
result := TProcess.Execute2(cancellationToken, 'cmd.exe', commandLine,'',env) = 0;
except
on e : Exception do
begin
FLogger.Error('Error executing compiler : ' + e.Message);
exit;
end;
end;
//TODO : Doesn't give realtime feedback, remove when we have a CreateProcess version of TProcess.
if TFile.Exists(FCompilerLogFile) then
begin
if not result then
begin
FLogger.Error('Package compilation failed.');
FCompilerOutput.LoadFromFile(FCompilerLogFile);
//TODO : This should be logged as an error, but then you would get a wall of red text which is hard to read.
FLogger.Information(FCompilerOutput.Text);
FCompilerOutput.Clear;
end;
TFile.Delete(FCompilerLogFile);
end;
end;
constructor TMSBuildCompiler.Create(const logger : ILogger; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const env : ICompilerEnvironmentProvider);
begin
FLogger := logger;
FCompilerVersion := compilerVersion;
FPlatform := platform;
FEnv := env;
FSearchPaths := TCollections.CreateList<string>;
FCompilerOutput := TStringList.Create;
end;
destructor TMSBuildCompiler.Destroy;
begin
FCompilerOutput.Free;
inherited;
end;
function TMSBuildCompiler.GetLibOutput: string;
begin
result := FLibOutput;
end;
function TMSBuildCompiler.GetBPLOutput : string;
begin
result := FBPLOutput;
end;
function TMSBuildCompiler.GetCommandLine(const projectFile, configName : string; const packageVersion : TPackageVersion) : string;
begin
//I don't like this... but it will do for a start.
result := 'call "' + FEnv.GetRsVarsFilePath(FCompilerVersion) + '"';
result := result + ' & msbuild "' + projectfile + '" ' + GetMSBuildParameters(configName, packageVersion);
result := ' cmd /c ' + result + ' > ' + FCompilerLogFile;
end;
function TMSBuildCompiler.GetCompilerOutput : TStrings;
begin
result := FCompilerOutput;
end;
function TMSBuildCompiler.GetCompilerVersion : TCompilerVersion;
begin
result := FCompilerVersion;
end;
function TMSBuildCompiler.GetConfiguration : string;
begin
result := FConfiguration;
end;
function TMSBuildCompiler.GetMSBuildParameters(const configName : string; const packageVersion : TPackageVersion) : string;
var
libPath : string;
bplPath : string;
begin
//build version info resource first, then bpl.
//this assumes the dproj has the correct version info.
//We should investigate updating the dproj.
result := '/target:BuildVersionResource;Build';
result := result + ' /p:Config=' + configName;
if FBuildForDesign then
result := result + ' /p:Platform=' + DPMPlatformToBDString(TDPMPlatform.Win32)
else
result := result + ' /p:Platform=' + DPMPlatformToBDString(FPlatform);
//THIS DOES NOT WORK!!!
//attempting to update version info
// result := result + ' /p:VerInfo_IncludeVerInfo=true';
// result := result + ' /p:VerInfo_MajorVer=' + IntToStr(packageVersion.Major);
// result := result + ' /p:VerInfo_MinorVer=' + IntToStr(packageVersion.Minor);
// result := result + ' /p:VerInfo_Release=' + IntToStr(packageVersion.Patch);
//
// if packageVersion.IsStable then
// result := result + ' /p:VerInfo_Build=1'
// else
// result := result + ' /p:VerInfo_Build=0';
//TODO : Check that these props are correctly named for all supported compiler versions.
if FLibOutput <> '' then
begin
libPath := TPathUtils.QuotePath(ExcludeTrailingPathDelimiter(FLibOutput)); //msbuild is fussy about trailing path delimeters!
result := result + ' /p:DCC_DcpOutput=' + libPath;
result := result + ' /p:DCC_DcuOutput=' + libPath;
result := result + ' /p:DCC_ObjOutput=' + libPath;
result := result + ' /p:DCC_HppOutput=' + libPath;
result := result + ' /p:DCC_BpiOutput=' + libPath;
end;
if FBPLOutput <> '' then
begin
bplPath := TPathUtils.QuotePath(ExcludeTrailingPathDelimiter(FBPLOutput));
result := result + ' /p:DCC_BplOutput=' + bplPath;
end;
//implict rebuild off - stops the E2466 Never-build package 'X' requires always-build package 'Y'
//Note that some third party libs like omnithreadlibrary have always-build/implicitbuild on
result := result + ' /p:DCC_OutputNeverBuildDcps=true';
result := result + ' /p:DCC_UnitSearchPath=' + GetProjectSearchPath(configName);
//result := result + ' /v:diag';
end;
function TMSBuildCompiler.GetPlatform : TDPMPlatform;
begin
result := FPlatform;
end;
function TMSBuildCompiler.GetPlatformName: string;
begin
if FBuildForDesign then
result := DPMPlatformToBDString(TDPMPlatform.Win32)
else
result := DPMPlatformToBDString(FPlatform);
end;
function TMSBuildCompiler.GetProjectSearchPath(const configName: string): string;
var
s : string;
settingsLoader : IProjectSettingsLoader;
platform : TDPMPlatform;
begin
result := '';// '$(BDSLIB)\$(PLATFORM)\release;$(BDS)\include';
if FSearchPaths.Any then
begin
for s in FSearchPaths do
begin
if result <> '' then
result := result + ';';
result := result + ExcludeTrailingPathDelimiter(s);
end;
end;
if FBuildForDesign then
platform := TDPMPlatform.Win32
else
platform := FPlatform;
settingsLoader := TDPMProjectSettingsLoader.Create(FProjectFile, configName, platform);
s := settingsLoader.GetSearchPath;
if s <> '' then
result := s + ';' + result;
FLogger.Debug('SearchPath : ' + result);
result := TPathUtils.QuotePath(result, true);
end;
function TMSBuildCompiler.GetSearchPaths : IList<string>;
begin
result := FSearchPaths;
end;
function TMSBuildCompiler.GetVerbosity : TCompilerVerbosity;
begin
result := FVerbosity;
end;
procedure TMSBuildCompiler.SetLibOutput(const value: string);
begin
FLibOutput := value;
end;
procedure TMSBuildCompiler.SetBPLOutput(const value : string);
begin
FBPLOutput := value;
end;
procedure TMSBuildCompiler.SetConfiguration(const value : string);
begin
FConfiguration := value;
end;
procedure TMSBuildCompiler.SetSearchPaths(const value : IList<string> );
begin
FSearchPaths.Clear;
if value <> nil then
FSearchPaths.AddRange(value);
end;
procedure TMSBuildCompiler.SetVerbosity(const value : TCompilerVerbosity);
begin
FVerbosity := value;
end;
end.
|
unit FSearch;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Grids, ExtCtrls, StdCtrls;
type
TfrmSearch = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
Panel3: TPanel;
CBCore: TCheckBox;
CBShort: TCheckBox;
CBHeading: TCheckBox;
CBScale: TCheckBox;
CBLong: TCheckBox;
rgAndOr: TRadioGroup;
Bevel1: TBevel;
SearchFor: TStringGrid;
FirstBtn: TButton;
NextBtn: TButton;
Cancel: TButton;
ClearBtn: TButton;
Label1: TLabel;
procedure CancelClick(Sender: TObject);
procedure NextBtnClick(Sender: TObject);
procedure FirstBtnClick(Sender: TObject);
procedure ClearBtnClick(Sender: TObject);
procedure SearchForKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmSearch: TfrmSearch;
FromTheTop : boolean;
implementation
{$R *.DFM}
procedure TfrmSearch.CancelClick(Sender: TObject);
begin
ClearBtnClick(sender);
close;
end;
procedure TfrmSearch.NextBtnClick(Sender: TObject);
begin
FromTheTop := false;
close;
end;
procedure TfrmSearch.FirstBtnClick(Sender: TObject);
begin
FromTheTop := true;
close;
end;
procedure TfrmSearch.ClearBtnClick(Sender: TObject);
var i : integer;
begin
CBCore.checked := false;
CBHeading.checked := false;
CBLong.checked := false;
CBScale.checked := false;
CBShort.checked := false;
for i := 0 to SearchFor.RowCount-1 do searchfor.cells[0,i] := '';
end;
procedure TfrmSearch.SearchForKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key=vk_return then FirstBtnClick(Sender);
end;
end.
|
unit nsSecSettingsFrm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, nsGlobals, nsTypes;
type
TfrmSecSettings = class(TForm)
btnOK: TButton;
btnCancel: TButton;
btnHelp: TButton;
chkStorePwd: TCheckBox;
Bevel2: TBevel;
Panel9: TPanel;
Image3: TImage;
lblTitle: TLabel;
Label1: TLabel;
Label2: TLabel;
edtOldPwd: TEdit;
Label4: TLabel;
cbEncryption: TComboBox;
Label3: TLabel;
edtNewPwd: TEdit;
Label5: TLabel;
edtVerifyPwd: TEdit;
Bevel1: TBevel;
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure btnHelpClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
FProject: TNSProject;
procedure GetSettings(AProject: TNSProject);
procedure SetSettings(AProject: TNSProject);
protected
procedure UpdateActions; override;
public
{ Public declarations }
end;
function DisplaySecSettingsDialog(AOwner: TForm; AProject: TNSProject): Boolean;
implementation
uses
nsUtils;
{$R *.dfm}
function DisplaySecSettingsDialog(AOwner: TForm; AProject: TNSProject): Boolean;
begin
with TfrmSecSettings.Create(AOwner) do
try
GetSettings(AProject);
if ShowModal = mrOk then
begin
SetSettings(AProject);
Result := True;
end
else
Result := False;
finally
Free;
end;
end;
{ TSecSettingsForm }
procedure TfrmSecSettings.GetSettings(AProject: TNSProject);
var
Method: TEncryptionMethod;
begin
FProject := AProject;
for Method := Low(TEncryptionMethod) to High(TEncryptionMethod) do
cbEncryption.Items.Add(Encryptions[Method]^);
cbEncryption.ItemIndex := Ord(AProject.EncryptionMethod);
chkStorePwd.Checked := AProject.StoreArchivePwd;
end;
procedure TfrmSecSettings.SetSettings(AProject: TNSProject);
begin
AProject.EncryptionMethod := TEncryptionMethod(cbEncryption.ItemIndex);
AProject.ProjPwd := edtNewPwd.Text;
AProject.StoreArchivePwd := chkStorePwd.Checked;
end;
procedure TfrmSecSettings.UpdateActions;
begin
btnOK.Enabled := AnsiSameStr(edtOldPwd.Text, FProject.ProjPwd);
end;
procedure TfrmSecSettings.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
if ModalResult <> mrOk then
CanClose := True
else
begin
if cbEncryption.ItemIndex <> 0 then
begin
if (edtNewPwd.Text = EmptyStr) or (edtVerifyPwd.Text = EmptyStr) then
begin
MessageBox(
Handle,
PChar(sEmptyPassword),
PChar(sChangePassword),
$00000030);
CanClose := False;
end
else if not AnsiSameStr(edtNewPwd.Text, edtVerifyPwd.Text) then
begin
MessageBox(
Handle,
PChar(sPasswordsMismatch),
PChar(sChangePassword),
$00000030);
edtNewPwd.Text := EmptyStr;
;
edtVerifyPwd.Text := EmptyStr;
;
CanClose := False;
end;
end;
end;
end;
procedure TfrmSecSettings.FormShow(Sender: TObject);
begin
UpdateVistaFonts(Self);
end;
procedure TfrmSecSettings.btnHelpClick(Sender: TObject);
begin
Application.HelpSystem.ShowContextHelp(HelpContext, Application.HelpFile);
end;
end.
|
unit ImageGreyLongData;
interface
uses Windows, Graphics, Abstract2DImageData, LongDataSet, dglOpenGL;
type
T2DImageGreyLongData = class (TAbstract2DImageData)
private
// Gets
function GetData(_x, _y: integer):longword;
// Sets
procedure SetData(_x, _y: integer; _value: longword);
protected
// Constructors and Destructors
procedure Initialize; override;
// Gets
function GetBitmapPixelColor(_Position: longword):longword; override;
function GetRPixelColor(_Position: longword):byte; override;
function GetGPixelColor(_Position: longword):byte; override;
function GetBPixelColor(_Position: longword):byte; override;
function GetAPixelColor(_Position: longword):byte; override;
function GetRedPixelColor(_x,_y: integer):single; override;
function GetGreenPixelColor(_x,_y: integer):single; override;
function GetBluePixelColor(_x,_y: integer):single; override;
function GetAlphaPixelColor(_x,_y: integer):single; override;
// Sets
procedure SetBitmapPixelColor(_Position, _Color: longword); override;
procedure SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte); override;
procedure SetRedPixelColor(_x,_y: integer; _value:single); override;
procedure SetGreenPixelColor(_x,_y: integer; _value:single); override;
procedure SetBluePixelColor(_x,_y: integer; _value:single); override;
procedure SetAlphaPixelColor(_x,_y: integer; _value:single); override;
public
// Gets
function GetOpenGLFormat:TGLInt; override;
// Misc
procedure ScaleBy(_Value: single); override;
procedure Invert; override;
// properties
property Data[_x,_y:integer]:longword read GetData write SetData; default;
end;
implementation
// Constructors and Destructors
procedure T2DImageGreyLongData.Initialize;
begin
FData := TLongDataSet.Create;
end;
// Gets
function T2DImageGreyLongData.GetData(_x, _y: integer):longword;
begin
if (_x >= 0) and (_x < FXSize) and (_y >= 0) and (_y < FYSize) then
begin
Result := (FData as TLongDataSet).Data[(_y * FXSize) + _x];
end
else
begin
Result := 0;
end;
end;
function T2DImageGreyLongData.GetBitmapPixelColor(_Position: longword):longword;
begin
Result := RGB((FData as TLongDataSet).Data[_Position],(FData as TLongDataSet).Data[_Position],(FData as TLongDataSet).Data[_Position]);
end;
function T2DImageGreyLongData.GetRPixelColor(_Position: longword):byte;
begin
Result := (FData as TLongDataSet).Data[_Position] and $FF;
end;
function T2DImageGreyLongData.GetGPixelColor(_Position: longword):byte;
begin
Result := (FData as TLongDataSet).Data[_Position] and $FF;
end;
function T2DImageGreyLongData.GetBPixelColor(_Position: longword):byte;
begin
Result := (FData as TLongDataSet).Data[_Position] and $FF;
end;
function T2DImageGreyLongData.GetAPixelColor(_Position: longword):byte;
begin
Result := 0;
end;
function T2DImageGreyLongData.GetRedPixelColor(_x,_y: integer):single;
begin
Result := (FData as TLongDataSet).Data[(_y * FXSize) + _x];
end;
function T2DImageGreyLongData.GetGreenPixelColor(_x,_y: integer):single;
begin
Result := 0;
end;
function T2DImageGreyLongData.GetBluePixelColor(_x,_y: integer):single;
begin
Result := 0;
end;
function T2DImageGreyLongData.GetAlphaPixelColor(_x,_y: integer):single;
begin
Result := 0;
end;
function T2DImageGreyLongData.GetOpenGLFormat:TGLInt;
begin
Result := GL_RGB;
end;
// Sets
procedure T2DImageGreyLongData.SetBitmapPixelColor(_Position, _Color: longword);
begin
(FData as TLongDataSet).Data[_Position] := Round(((0.299 * GetRValue(_Color)) + (0.587 * GetGValue(_Color)) + (0.114 * GetBValue(_Color))) * 255);
end;
procedure T2DImageGreyLongData.SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte);
begin
(FData as TLongDataSet).Data[_Position] := Round(((0.299 * _r) + (0.587 * _g) + (0.114 * _b)) * 255);
end;
procedure T2DImageGreyLongData.SetRedPixelColor(_x,_y: integer; _value:single);
begin
(FData as TLongDataSet).Data[(_y * FXSize) + _x] := Round(_value);
end;
procedure T2DImageGreyLongData.SetGreenPixelColor(_x,_y: integer; _value:single);
begin
// Do nothing
end;
procedure T2DImageGreyLongData.SetBluePixelColor(_x,_y: integer; _value:single);
begin
// Do nothing
end;
procedure T2DImageGreyLongData.SetAlphaPixelColor(_x,_y: integer; _value:single);
begin
// Do nothing
end;
procedure T2DImageGreyLongData.SetData(_x, _y: integer; _value: longword);
begin
if (_x >= 0) and (_x < FXSize) and (_y >= 0) and (_y < FYSize) then
begin
(FData as TLongDataSet).Data[(_y * FXSize) + _x] := _value;
end;
end;
// Misc
procedure T2DImageGreyLongData.ScaleBy(_Value: single);
var
x,maxx: integer;
begin
maxx := (FXSize * FYSize) - 1;
for x := 0 to maxx do
begin
(FData as TLongDataSet).Data[x] := Round((FData as TLongDataSet).Data[x] * _Value);
end;
end;
procedure T2DImageGreyLongData.Invert;
var
x,maxx: integer;
begin
maxx := (FXSize * FYSize) - 1;
for x := 0 to maxx do
begin
(FData as TLongDataSet).Data[x] := 255 - (FData as TLongDataSet).Data[x];
end;
end;
end.
|
unit uDadosGlobal;
interface
uses
System.SysUtils, System.Classes, Data.DB, Datasnap.DBClient,
Vcl.Dialogs, Data.FMTBcd, Data.SqlExpr, Vcl.Controls,
Winapi.Windows, Vcl.Forms, Datasnap.Provider, System.UITypes;
type
TdmDadosGlobal = class(TDataModule)
cdsUf: TClientDataSet;
cdsUfufdescr: TStringField;
cdsUfuf: TStringField;
dsUf: TDataSource;
cdsStatusAssinante: TClientDataSet;
cdsStatusAssinanteCodigo: TIntegerField;
cdsStatusAssinanteDescr: TStringField;
sqlTblsen: TSQLDataSet;
sqlTblsensensenha: TStringField;
cdsLookupSimNao: TClientDataSet;
cdsLookupSimNaoCodigo: TStringField;
cdsLookupSimNaoDescr: TStringField;
cdsStatusAssinante2: TClientDataSet;
cdsStatusAssinante2Codigo: TIntegerField;
cdsStatusAssinante2Descr: TStringField;
sqlDataHoraBanco: TSQLDataSet;
sqlDataHoraBancodatahora: TSQLTimeStampField;
cdsLookupSimNao2: TClientDataSet;
cdsLookupSimNao2Descr: TStringField;
cdsLookupSimNao2Codigo: TStringField;
procedure DataModuleCreate(Sender: TObject);
procedure dspLookupZonasUpdateError(Sender: TObject;
DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind;
var Response: TResolverResponse);
private
{ Private declarations }
public
{ Public declarations }
function ValidarEmail(AEmail: string): Boolean;
function ValidarCNPJ(ACNPJ: String): Boolean;
function ValidarCPF(ACPF: String): Boolean;
function ValidarCEP(ACEP: String): Boolean;
function GetDataHoraBanco: TDateTime;
function GetMesPorExtenso(AMes: Integer): String;
function ConvertePrimeiraLetraMaiuscula(AStr: String): String;
function FormataEndereco(AEndereco: String = ''; ANro: String = ''; AComplemento: String = ''): String;
function ValorPorExtenso(AValor: Double): String;
function PadL(const S: string; const ComprimentoFinal: integer; const Complemento: string): string;
function PadR(const S: string; const ComprimentoFinal: integer; const Complemento: string = ' '): string;
function GetSoNumeros(const Str: String; const ReturnIfNull: String = ''): String;
function GetSoLetras(const Str: String; const ReturnIfNull: String = ''): String;
function GetPrimeirosNumeroComplementoEndereco(const Str: String; const ReturnIfNull: String = ''): String;
function FormatDateTimeToString(const Format: string; DateTime: TDateTime): String;
function GetDescricaoSimNao(Aindicador: String): String;
end;
var
dmDadosGlobal: TdmDadosGlobal;
implementation
{%CLASSGROUP 'System.Classes.TPersistent'}
uses uConexao;
{$R *.dfm}
function TdmDadosGlobal.PadL(const S: string; const ComprimentoFinal: integer;
const Complemento: string): string;
var
Texto: string;
begin
Texto := S;
while Length(Texto) < ComprimentoFinal do
Texto := Texto + Complemento;
Result := Copy(Texto, 1, ComprimentoFinal);
end;
function TdmDadosGlobal.PadR(const S: string; const ComprimentoFinal: integer;
const Complemento: string = ' '): string;
var
Texto: string;
begin
Texto := S;
while Length(Texto) < ComprimentoFinal do
Texto := Complemento + Texto;
Result := Copy(Texto, 1, ComprimentoFinal);
end;
function TdmDadosGlobal.ConvertePrimeiraLetraMaiuscula(AStr: String): String;
var
i: integer;
esp: boolean;
begin
AStr := LowerCase(Trim(AStr));
for i := 1 to Length(AStr) do
begin
if i = 1 then
AStr[i] := UpCase(AStr[i])
else
begin
if i <> Length(AStr) then
begin
esp := (AStr[i] = ' ');
if esp then
AStr[i+1] := UpCase(AStr[i+1]);
end;
end;
end;
Result := AStr;
end;
procedure TdmDadosGlobal.DataModuleCreate(Sender: TObject);
begin
cdsUf.Close;
cdsUf.CreateDataSet;
cdsUf.Open;
cdsUf.AppendRecord(['AC', 'Acre']);
cdsUf.AppendRecord(['AL', 'Alagoas']);
cdsUf.AppendRecord(['AP', 'Amapá']);
cdsUf.AppendRecord(['AM', 'Amazonas']);
cdsUf.AppendRecord(['BA', 'Bahia']);
cdsUf.AppendRecord(['CE', 'Ceará']);
cdsUf.AppendRecord(['DF', 'Distrito Federal']);
cdsUf.AppendRecord(['ES', 'Espírito Santo']);
cdsUf.AppendRecord(['GO', 'Goiás']);
cdsUf.AppendRecord(['MA', 'Maranhão']);
cdsUf.AppendRecord(['MT', 'Mato Grosso']);
cdsUf.AppendRecord(['MS', 'Mato Grosso do Sul']);
cdsUf.AppendRecord(['MG', 'Minas Gerais']);
cdsUf.AppendRecord(['PA', 'Pará']);
cdsUf.AppendRecord(['PB', 'Paraíba']);
cdsUf.AppendRecord(['PR', 'Paraná']);
cdsUf.AppendRecord(['PE', 'Pernambuco']);
cdsUf.AppendRecord(['PI', 'Piauí']);
cdsUf.AppendRecord(['RJ', 'Rio de Janeiro']);
cdsUf.AppendRecord(['RN', 'Rio Grande do Norte']);
cdsUf.AppendRecord(['RS', 'Rio Grande do Sul']);
cdsUf.AppendRecord(['RO', 'Rondônia']);
cdsUf.AppendRecord(['RR', 'Roraima']);
cdsUf.AppendRecord(['SC', 'Santa Catarina']);
cdsUf.AppendRecord(['SP', 'São Paulo']);
cdsUf.AppendRecord(['SE', 'Sergipe']);
cdsUf.AppendRecord(['TO', 'Tocantins']);
cdsUf.First;
// ---------------------------------------------------------------------------
cdsStatusAssinante.Close;
cdsStatusAssinante.CreateDataSet;
cdsStatusAssinante.Open;
cdsStatusAssinante.AppendRecord([-1, '']);
cdsStatusAssinante.AppendRecord([0, 'Ativo']);
cdsStatusAssinante.AppendRecord([1, 'Inativo']);
cdsStatusAssinante.First;
// ---------------------------------------------------------------------------
cdsStatusAssinante2.Close;
cdsStatusAssinante2.CreateDataSet;
cdsStatusAssinante2.Open;
cdsStatusAssinante2.AppendRecord([0, 'Ativo']);
cdsStatusAssinante2.AppendRecord([1, 'Inativo']);
cdsStatusAssinante2.First;
// ---------------------------------------------------------------------------
cdsLookupSimNao.Close;
cdsLookupSimNao.CreateDataSet;
cdsLookupSimNao.Open;
cdsLookupSimNao.AppendRecord(['S', 'Sim']);
cdsLookupSimNao.AppendRecord(['N', 'Não']);
cdsLookupSimNao.First;
// ---------------------------------------------------------------------------
cdsLookupSimNao2.Close;
cdsLookupSimNao2.CreateDataSet;
cdsLookupSimNao2.Open;
cdsLookupSimNao2.AppendRecord(['S', 'Sim']);
cdsLookupSimNao2.AppendRecord(['N', 'Não']);
cdsLookupSimNao2.First;
end;
procedure TdmDadosGlobal.dspLookupZonasUpdateError(Sender: TObject;
DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind;
var Response: TResolverResponse);
begin
raise Exception.Create(e.Message);
end;
function TdmDadosGlobal.FormataEndereco(AEndereco, ANro,
AComplemento: String): String;
begin
Result := '';
AEndereco := trim(AEndereco);
ANro := trim(ANro);
AComplemento := trim(AComplemento);
// Faz a montagem do endereço completo do assinante
Result := AEndereco;
if ANro <> EmptyStr then
Result := Result + ', ' + ANro;
if AComplemento <> EmptyStr then
Result := Result + ' - ' + AComplemento;
end;
function TdmDadosGlobal.FormatDateTimeToString(const Format: string;
DateTime: TDateTime): String;
begin
if DateTime = 0 then
Result := ''
else
Result := FormatDateTime(Format, DateTime);
end;
function TdmDadosGlobal.GetDataHoraBanco: TDateTime;
begin
try
sqlDataHoraBanco.Close;
sqlDataHoraBanco.Open;
Result := sqlDataHoraBancodatahora.AsDateTime;
finally
sqlDataHoraBanco.Close;
end;
end;
function TdmDadosGlobal.GetDescricaoSimNao(Aindicador: String): String;
begin
if UpperCase(Aindicador) = 'S' then
Result := 'Sim'
else if UpperCase(Aindicador) = 'N' then
Result := 'Não'
else
Result := '';
end;
function TdmDadosGlobal.GetMesPorExtenso(AMes: Integer): String;
begin
case AMes of
01: Result := 'Janeiro';
02: Result := 'Fevereiro';
03: Result := 'Março';
04: Result := 'Abril';
05: Result := 'Maio';
06: Result := 'Junho';
07: Result := 'Julho';
08: Result := 'Agosto';
09: Result := 'Setembro';
10: Result := 'Outubro';
11: Result := 'Novembro';
12: Result := 'Dezembro';
end;
end;
function TdmDadosGlobal.GetPrimeirosNumeroComplementoEndereco(const Str,
ReturnIfNull: String): String;
var
I: integer;
S: string;
Flag: Boolean;
begin
S := '';
Flag := false;
for I := 1 To Length(Str) Do
begin
if CharInSet(Str[I], ['0'..'9']) then
begin
S := S + Copy(Str, I, 1);
Flag := true;
end
else
begin
if Flag then
Break;
end;
end;
if S = '' then
Result := ReturnIfNull
else
result := S;
end;
function TdmDadosGlobal.GetSoLetras(const Str, ReturnIfNull: String): String;
var
I: integer;
S: string;
begin
S := '';
for I := 1 To Length(Str) Do
if not (CharInSet(Str[I], ['0'..'9'])) then
S := S + Copy(Str, I, 1);
if S = '' then
Result := ReturnIfNull
else
result := S;
end;
function TdmDadosGlobal.GetSoNumeros(const Str: String;
const ReturnIfNull: String = ''): String;
var
I: integer;
S: string;
begin
S := '';
for I := 1 To Length(Str) Do
if CharInSet(Str[I], ['0'..'9']) then
S := S + Copy(Str, I, 1);
if S = '' then
Result := ReturnIfNull
else
result := S;
end;
function TdmDadosGlobal.ValidarCEP(ACEP: String): Boolean;
begin
Result := true;
end;
function TdmDadosGlobal.ValidarCNPJ(ACNPJ: String): Boolean;
var
n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12: Integer;
d1, d2: Integer;
digitado, calculado: string;
begin
ACNPJ := GetSoNumeros(ACNPJ);
if Length(ACNPJ) <> 14 then
begin
ValidarCNPJ := false;
exit;
end;
n1 := StrToInt(ACNPJ[1]);
n2 := StrToInt(ACNPJ[2]);
n3 := StrToInt(ACNPJ[3]);
n4 := StrToInt(ACNPJ[4]);
n5 := StrToInt(ACNPJ[5]);
n6 := StrToInt(ACNPJ[6]);
n7 := StrToInt(ACNPJ[7]);
n8 := StrToInt(ACNPJ[8]);
n9 := StrToInt(ACNPJ[9]);
n10 := StrToInt(ACNPJ[10]);
n11 := StrToInt(ACNPJ[11]);
n12 := StrToInt(ACNPJ[12]);
d1 := n12 * 2 + n11 * 3 + n10 * 4 + n9 * 5 + n8 * 6 + n7 * 7 + n6 * 8 + n5 * 9 + n4 * 2 + n3 * 3 + n2 * 4 + n1 * 5;
d1 := 11 - (d1 mod 11);
if d1 >= 10 then
d1 := 0;
d2 := d1 * 2 + n12 * 3 + n11 * 4 + n10 * 5 + n9 * 6 + n8 * 7 + n7 * 8 + n6 * 9 + n5 * 2 + n4 * 3 + n3 * 4 + n2 * 5 + n1 * 6;
d2 := 11 - (d2 mod 11);
if d2 >= 10 then
d2 := 0;
calculado := inttostr(d1) + inttostr(d2);
digitado := ACNPJ[13] + ACNPJ[14];
if calculado = digitado then
ValidarCNPJ := true
else
ValidarCNPJ := false;
end;
function TdmDadosGlobal.ValidarCPF(ACPF: String): Boolean;
var
n1, n2, n3, n4, n5, n6, n7, n8, n9: Integer;
d1, d2: Integer;
digitado, calculado: string;
begin
ACPF := GetSoNumeros(ACPF);
if Length(ACPF) <> 11 then
begin
ValidarCPF := false;
exit;
end;
// Pega os 9 primeiros números
n1 := StrToInt(ACPF[1]);
n2 := StrToInt(ACPF[2]);
n3 := StrToInt(ACPF[3]);
n4 := StrToInt(ACPF[4]);
n5 := StrToInt(ACPF[5]);
n6 := StrToInt(ACPF[6]);
n7 := StrToInt(ACPF[7]);
n8 := StrToInt(ACPF[8]);
n9 := StrToInt(ACPF[9]);
// Faz o cálculo do primeiro dígito
d1 := n9 * 2 + n8 * 3 + n7 * 4 + n6 * 5 + n5 * 6 + n4 * 7 + n3 * 8 + n2 * 9
+ n1 * 10;
d1 := 11 - (d1 mod 11);
if d1 >= 10 then
d1 := 0; // Se o cálculo for igual a 10 então ele é zero
// Faz o calculo do segundo digito
d2 := d1 * 2 + n9 * 3 + n8 * 4 + n7 * 5 + n6 * 6 + n5 * 7 + n4 * 8 + n3 * 9 +
n2 * 10 + n1 * 11;
d2 := 11 - (d2 mod 11);
if d2 >= 10 then
d2 := 0; // se o cálculo for igual a 10 então ele é zero
calculado := inttostr(d1) + inttostr(d2); // Define o que foi calculado
digitado := ACPF[10] + ACPF[11]; // Define o que foi digitado
// Se o número que foi calculado for igual ao que foi digitado
// a função retorna verdadeiro, senão retorna falso
Result := (calculado = digitado);
end;
function TdmDadosGlobal.ValidarEmail(AEmail: string): Boolean;
const
l_Maiuscula = ['A'..'Z'];
l_Letras_validas = ['0'..'9', 'a'..'z', '_', '-', '.'];
var
l_Qtd_Arroba, l_Qtd_Espacos : smallint;
l_i : smallint;
l_Usuario, l_Dominio : string;
l_char : Char;
l_Carac_Ant : String;
begin
l_Qtd_Arroba := 0;
l_Qtd_Espacos := 0;
l_Carac_Ant := '';
result := false;
// Verifica se existe algum coisa no parametro.
if AEmail = '' then
begin
MessageDlg('E-mail nao foi informado.', mtWarning, [mbok], 0);
exit;
end;
for l_i := 1 to length(AEmail) do
begin
if (copy(AEmail, l_i, 1) = '.') and (l_Carac_Ant = '.') then
begin
MessageDlg('Existem dois ou mais pontos juntos, verifique.', mtWarning, [mbok], 0);
exit;
end;
if ((copy(AEmail, l_i, 1) = '.') and (l_Carac_Ant = '@')) or ((copy(AEmail, l_i, 1) = '@') and (l_Carac_Ant = '.')) then
begin
MessageDlg('Nao pode haver uma arroba e um ponto juntos, verifique.', mtWarning, [mbok], 0);
exit;
end;
if copy(AEmail, l_i, 1) = ' ' then
l_Qtd_Espacos := l_Qtd_Espacos + 1;
if l_Qtd_Espacos <> 0 then
begin
MessageDlg('Existem espacos em branco, verifique.', mtWarning, [mbok], 0);
exit;
end;
if copy(AEmail, l_i, 1) = '@' then
l_Qtd_Arroba := l_Qtd_Arroba + 1;
l_Carac_Ant := copy(AEmail, l_i, 1);
end;
if l_Qtd_Arroba = 0 then
begin
MessageDlg('Deve existir uma @ (arroba) para o e-mail ser válido.', mtWarning, [mbok], 0);
exit;
end
else if l_Qtd_Arroba > 1 then
begin
MessageDlg('Existem mais de 1 @ (arroba), verifique.', mtWarning, [mbok], 0);
exit;
end;
// ---------------------------------------------------------------------------
// Separar o usuário do dominio.
// ---------------------------------------------------------------------------
l_i := pos('@', AEmail);
l_Usuario := copy(AEmail, 1, (l_i - 1));
l_Dominio := copy(AEmail, (l_i + 1), length(AEmail));
if l_Usuario = '' then
begin
MessageDlg('Nao foi informado a parte antes da @ (arroba), verifique.', mtWarning, [mbok], 0);
exit;
end;
if l_Dominio = '' then
begin
MessageDlg('Nao foi informado a parte depois da @ (arroba), verifique.', mtWarning, [mbok], 0);
exit;
end;
// ---------------------------------------------------------------------------
// Validando a parte do usuário
// ---------------------------------------------------------------------------
for l_i := 1 to length(l_Usuario) do
begin
l_char := l_Usuario[l_i];
if (CharInSet(l_char, l_Maiuscula)) then
//if l_char in l_Maiuscula then
begin
MessageDlg('Existem letras maiúsculas antes da @ (arroba), verifique.', mtWarning, [mbok], 0);
exit;
end;
if not (CharInSet(l_char, l_Letras_validas)) then
//if not (l_char in l_Letras_validas) then
begin
MessageDlg('Existem caracteres invalidos antes da @ (arroba), verifique.', mtWarning, [mbok], 0);
exit;
end;
end;
//----------------------------------------------------------------------------
// Validando a parte do domino
//----------------------------------------------------------------------------
for l_i := 1 to length(l_Dominio) do
begin
l_char := l_Dominio[l_i];
if (CharInSet(l_char, l_Maiuscula)) then
//if l_char in l_Maiuscula then
begin
MessageDlg('Existem letras maiúsculas depois da @ (arroba), verifique.', mtWarning, [mbok], 0);
exit;
end;
if not (CharInSet(l_char, l_Letras_validas)) then
//if not (l_char in l_Letras_validas) then
begin
MessageDlg('Existem caracteres invalidos depois da @ (arroba), verifique.', mtWarning, [mbok], 0);
exit;
end;
end;
if copy(l_Dominio, length(l_Dominio), 1) = '.' then
begin
MessageDlg('O último caracter do e-mail não pode ser um ponto, verifique.', mtWarning, [mbok], 0);
exit;
end;
result := true;
end;
function TdmDadosGlobal.ValorPorExtenso(AValor: Double): String;
const
unidade: array [1 .. 19] of string = ('Um', 'Dois', 'Três', 'Quatro', 'Cinco',
'Seis', 'Sete', 'Oito', 'Nove', 'Dez', 'Onze', 'Doze', 'Treze', 'Quatorze',
'Quinze', 'Dezesseis', 'Dezessete', 'Dezoito', 'Dezenove');
dezena: array [2 .. 9] of string = ('Vinte', 'Trinta', 'Quarenta',
'Cinquenta', 'Sessenta', 'Setenta', 'Oitenta', 'Noventa');
centena: array [1 .. 9] of string = ('Cento', 'Duzentos', 'Trezentos',
'Quatrocentos', 'Quinhentos', 'Seiscentos', 'Setecentos', 'Oitocentos',
'Novecentos');
qualificaS: array [0 .. 4] of string = ('', 'Mil', 'Milhão', 'Bilhão',
'Trilhão');
qualificaP: array [0 .. 4] of string = ('', 'Mil', 'Milhões', 'Bilhões',
'Trilhões');
var
inteiro: Int64;
resto: real;
vlrS, s, saux, vlrP, centavos: string;
n, unid, dez, cent, tam, I: Integer;
umReal, tem: Boolean;
begin
if AValor = 0 then
begin
valorPorExtenso := 'Zero';
exit;
end;
inteiro := trunc(AValor); // parte inteira do valor
resto := AValor - inteiro; // parte fracionária do valor
vlrS := inttostr(inteiro);
if (length(vlrS) > 15) then
begin
valorPorExtenso := 'Erro: valor superior a 999 trilhões.';
exit;
end;
s := '';
centavos := inttostr(round(resto * 100));
// definindo o extenso da parte inteira do valor
i := 0;
umReal := false; tem := false;
while (vlrS <> '0') do
begin
tam := length(vlrS);
// retira do valor a 1a. parte, 2a. parte, por exemplo, para 123456789:
// 1a. parte = 789 (centena)
// 2a. parte = 456 (mil)
// 3a. parte = 123 (milhões)
if (tam > 3) then
begin
vlrP := copy(vlrS, tam-2, tam);
vlrS := copy(vlrS, 1, tam-3);
end
else
begin // última parte do valor
vlrP := vlrS;
vlrS := '0';
end;
if (vlrP <> '000') then
begin
saux := '';
if (vlrP = '100') then
saux := 'cem'
else
begin
n := strtoint(vlrP); // para n = 371, tem-se:
cent := n div 100; // cent = 3 (centena trezentos)
dez := (n mod 100) div 10; // dez = 7 (dezena setenta)
unid := (n mod 100) mod 10; // unid = 1 (unidade um)
if (cent <> 0) then
saux := centena[cent];
if ((dez <> 0) or (unid <> 0)) then
begin
if ((n mod 100) <= 19) then
begin
if (length(saux) <> 0) then
saux := saux + ' e ' + unidade[n mod 100]
else
saux := unidade[n mod 100];
end
else
begin
if (length(saux) <> 0) then
saux := saux + ' e ' + dezena[dez]
else
saux := dezena[dez];
if (unid <> 0) then
if (length(saux) <> 0) then
saux := saux + ' e ' + unidade[unid]
else
saux := unidade[unid];
end;
end;
end;
if ((vlrP = '1') or (vlrP = '001')) then
begin
if (i = 0) then // 1a. parte do valor (um real)
umReal := true
else
saux := saux + ' ' + qualificaS[i];
end
else if (i <> 0) then
saux := saux + ' ' + qualificaP[i];
if (length(s) <> 0) then
s := saux + ', ' + s
else
s := saux;
end;
if (((i = 0) or (i = 1)) and (length(s) <> 0)) then
tem := true; // tem centena ou mil no valor
i := i + 1; // próximo qualificador: 1- mil, 2- milhão, 3- bilhão, ...
end;
if (length(s) <> 0) then
begin
if (umReal) then
s := s + ' Real'
else if (tem) then
s := s + ' Reais'
else
s := s + ' de Reais';
end;
// definindo o extenso dos centavos do valor
if (centavos <> '0') then // valor com centavos
begin
if (length(s) <> 0) then // se não é valor somente com centavos
s := s + ' e ';
if (centavos = '1') then
s := s + 'Um Centavo'
else
begin
n := strtoint(centavos);
if (n <= 19) then
s := s + unidade[n]
else
begin // para n = 37, tem-se:
unid := n mod 10; // unid = 37 % 10 = 7 (unidade sete)
dez := n div 10; // dez = 37 / 10 = 3 (dezena trinta)
s := s + dezena[dez];
if (unid <> 0) then
s := s + ' e ' + unidade[unid];
end;
s := s + ' Centavos';
end;
end;
valorPorExtenso := s;
end;
end.
|
unit ibSHSimpleFieldListRetriever;
interface
uses Classes, SysUtils,
SHDesignIntf, ibSHDesignIntf, ibSHValues, ibSHSQLs,
pSHIntf;
type
TibBTSimpleFieldListRetriever = class(TComponent, IpSHFieldListRetriever)
private
FDatabase: IibSHDatabase;
function GetDatabase: IInterface;
procedure SetDatabase(const Value: IInterface);
protected
public
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
function GetFieldList(const AObjectName: string; AList: TStrings): Boolean;
property Database: IInterface read GetDatabase write SetDatabase;
end;
implementation
{ TibBTSimpleFieldListRetriever }
function TibBTSimpleFieldListRetriever.GetDatabase: IInterface;
begin
Result := FDatabase;
end;
procedure TibBTSimpleFieldListRetriever.SetDatabase(
const Value: IInterface);
begin
if Supports(Value, IibSHDatabase, FDatabase) then
ReferenceInterface(FDatabase, opInsert);
end;
function TibBTSimpleFieldListRetriever.GetFieldList(
const AObjectName: string; AList: TStrings): Boolean;
var
vClassIIDList: TStrings;
vDesigner: ISHDesigner;
vObjectName: string;
vCodeNormalizer: IibSHCodeNormalizer;
vObjectIID: TGUID;
vSQL_TEXT: string;
function NormalizeName(AName: string): string;
begin
if Assigned(vCodeNormalizer) then
Result := vCodeNormalizer.MetadataNameToSourceDDLCase(FDatabase, AName)
else
Result := AName;
end;
begin
Result := False;
if Assigned(FDatabase) then
begin
if SHSupports(ISHDesigner, vDesigner) and
Supports(vDesigner.GetDemon(IibSHCodeNormalizer), IibSHCodeNormalizer, vCodeNormalizer) then
vObjectName := vCodeNormalizer.SourceDDLToMetadataName(AObjectName)
else
vObjectName := AObjectName;
vClassIIDList := FDatabase.GetSchemeClassIIDList(vObjectName);
if vClassIIDList.Count > 0 then
begin
vObjectIID := StringToGUID(vClassIIDList[0]);
if IsEqualGUID(vObjectIID, IibSHTable) or
IsEqualGUID(vObjectIID, IibSHSystemTable) then vSQL_TEXT := FormatSQL(SQL_GET_TABLE_FIELDS) else
if IsEqualGUID(vObjectIID, IibSHView) then vSQL_TEXT := FormatSQL(SQL_GET_VIEW_FIELDS) else
if IsEqualGUID(vObjectIID, IibSHProcedure) then vSQL_TEXT := FormatSQL(SQL_GET_PROCEDURE_PARAMS) else Exit;
if FDatabase.DRVQuery.ExecSQL(vSQL_TEXT, [vObjectName], False) then
begin
AList.Clear;
while not FDatabase.DRVQuery.Eof do
begin
AList.Add(NormalizeName(FDatabase.DRVQuery.GetFieldStrValue(0)));
FDatabase.DRVQuery.Next;
end;
FDatabase.DRVQuery.Transaction.Commit;
end;
end;
end;
end;
procedure TibBTSimpleFieldListRetriever.Notification(
AComponent: TComponent; Operation: TOperation);
begin
if (Operation = opRemove) then
begin
if AComponent.IsImplementorOf(FDatabase) then
FDatabase := nil;
end;
inherited Notification(AComponent, Operation);
end;
end.
|
(*
Category: SWAG Title: STREAM HANDLING ROUTINES
Original name: 0006.PAS
Description: Simple STREAM Example
Author: SWAG SUPPORT TEAM
Date: 02-28-95 10:09
*)
{
This program example will demonstrate how to save your
desktop using a stream. It will give you the ability
to insert windows on the destop and save the state in a
.DSK file and load them from the file to restore its'
state. Streams REQURE registration of decendant object
types. Many fall folly to using objects in a stream
that have not been registered.
}
Program Simple_Stream;
Uses Objects, Drivers, Views, Menus, App;
Type
PMyApp = ^MyApp;
MyApp = Object(TApplication)
Constructor Init;
Procedure InitStatusLine; Virtual;
Procedure InitMenuBar; Virtual;
Procedure HandleEvent(var Event: TEvent); Virtual;
Procedure NewWindow;
Destructor Done; Virtual;
End;
PMyWindow = ^TMyWindow;
TMyWindow = Object(TWindow)
Constructor Init(Bounds: TRect; WinTitle: String; WindowNo: Word);
End;
PMyDeskTop = ^TMyDeskTop;
TMyDeskTop = object(TDeskTop)
Windw: PMyWindow;
Constructor Load(var S:TBufStream);
Procedure Store(var S: TBufStream); Virtual;
End;
Const
cmNewWin = 101;
cmSaveDesk = 102;
cmLoadDesk = 103;
RMyDeskTop: TstreamRec = (
ObjType : 1001;
VmtLink : Ofs(TypeOf(TMyDeskTop)^);
Load : @TMyDeskTop.Load;
Store : @TMyDeskTop.Store
);
RMyWindow: TstreamRec = (
ObjType : 1002;
VmtLink : Ofs(TypeOf(TMyWindow)^);
Load : @TMyWindow.Load;
Store : @TMyWindow.Store
);
Procedure SaveDeskStream;
Var
SaveFile:TBufStream;
Begin
SaveFile.Init('Rdesk.dsk',stCreate,1024);
SaveFile.Put(DeskTop);
If Savefile.Status <>0 then
write('Bad Save',Savefile.Status);
SaveFile.Done;
End;
Procedure LoadDeskStream;
Var
SaveFile:TBufStream;
Begin
SaveFile.Init('Rdesk.dsk',stOpen,1024);
DeskTop^.insert(PMyDeskTop(SaveFile.Get));
If Savefile.Status <>0 then
write('Bad Load',Savefile.Status)
else
DeskTop^.ReDraw;
SaveFile.Done;
End;
{ ** MyApp **}
Constructor MyApp.Init;
Begin
TApplication.Init;
RegisterType(RMyDesktop);
RegisterType(RDesktop);
RegisterType(Rwindow);
RegisterType(RMywindow);
RegisterType(RFrame);
RegisterType(RMenuBar);
RegisterType(RStatusLine);
RegisterType(RBackground);
End;
Destructor MyApp.Done;
Begin
TApplication.Done;
End;
Procedure MyApp.InitMenuBar;
Var
R: TRect;
Begin
GetExtent(R);
R.B.Y := R.A.Y + 1;
MenuBar := New(PMenuBar, Init(R, NewMenu(
NewSubMenu('~F~ile', hcNoContext, NewMenu(
NewItem('~N~ew', 'F4', kbF4, cmNewWin, hcNoContext,
NewLine(
NewItem('E~x~it', 'Alt-X', kbAltX, cmQuit, hcNoContext,
Nil)))),
NewSubMenu('~D~eskTop', hcNoContext, NewMenu(
NewItem('~S~ave Desktop','',kbF2,cmSaveDesk,hcNoContext,
NewItem('~L~oad Desktop','',kbF3,cmLoadDesk,hcNoContext,
nil))),nil)))));
End;
Procedure MyApp.InitStatusLine;
Var
R: TRect;
Begin
GetExtent(R);
R.A.Y := R.B.Y - 1;
StatusLine := New(PStatusLine, Init(R,
NewStatusDef(0, $FFFF,
NewStatusKey('', kbF10, cmMenu,
NewStatusKey('~Alt-X~ Exit', kbAltX, cmQuit,
NewStatusKey('~F4~ New', kbF4, cmNewWin,
NewStatusKey('~Alt-F3~ Close', kbAltF3, cmClose,
nil)))),
nil)));
End;
Procedure MyApp.HandleEvent(var Event: TEvent);
Begin
TApplication.HandleEvent(Event);
if Event.What = evCommand then
Begin
Case Event.Command of
cmNewWin: NewWindow;
cmSaveDesk:SaveDeskStream;
cmLoadDesk:LoadDeskStream;
else
Exit;
End;
ClearEvent(Event);
End;
End;
Procedure MyApp.NewWindow;
Var
Window:PMyWindow;
R: TRect;
Begin
R.Assign(0, 0, 24, 7);
R.Move(Random(55), Random(16));
Window := New(PMyWindow, Init(R, 'Demo Window', 1));
DeskTop^.Insert(Window);
End;
{ ** MyDeskTop **}
Constructor TMyDeskTop.Load(Var S: TBufStream);
Begin
TDeskTop.Load(S);
GetSubViewPtr(S,Windw);
End;
Procedure TMyDeskTop.Store(Var S: TBufStream);
Begin
TDeskTop.Store(S);
PutSubViewPtr(S,Windw);
End;
{ ** MyWindow **}
Constructor TMyWindow.Init(Bounds: TRect; WinTitle: String; WindowNo: Word);
Begin
TWindow.init(Bounds,WinTitle,WindowNo);
End;
{ Main Program }
Var
MyTApp:MyApp;
Begin
MyTApp.Init;
MyTApp.Run;
MyTApp.Done;
End.
|
unit Light;
interface
uses Vcl.Graphics, System.Math.Vectors;
type
TLight = class
pos, lum: TVector;
pow: Integer;
constructor Create(pos, lum: TVector; pow: Integer);
end;
implementation
{ TLight }
constructor TLight.Create(pos, lum: TVector; pow: Integer);
begin
Self.pos := pos;
Self.lum := lum;
Self.pow := pow;
end;
end.
|
unit Ils.Kafka.Offset;
interface
uses
StrUtils, DateUtils, IniFiles, SysUtils, ULibKafka, Ils.Logger;
type
TKafkaOffset = class
private
FFileName: string;
FOffset: Int64;
FWriteOffsetPeriod: Integer;
FWriteOffsetDTPrev: TDateTime;
FWriteOffsetDT: TDateTime;
FLastOffsetCounted: Int64;
FLastOffsetDT: TDateTime;
FPrev10KOffset: Int64;
FPrev10KDT : TDateTime;
FOffsetIniFile: TIniFile;
procedure SaveOffset(const ANewOffset: Int64; const AStoreValue: Boolean; const ADT: TDateTime = 0);
procedure StoreOffset;
function GetValue: Int64;
procedure SetValue(const Value: Int64);
public
function Save(AOffset: Int64): Int64;
property Value: Int64 read GetValue write SetValue;
constructor Create(const AFileName: string = ''; const AWriteOffsetPeriod: Integer = 1000);
destructor Destroy; override;
end;
const
CKafkaOffsetExt: string = '.kafka.offset';
implementation
{ TOffset }
constructor TKafkaOffset.Create(const AFileName: string;
const AWriteOffsetPeriod: Integer);
begin
FFileName := AFileName;
FWriteOffsetPeriod := AWriteOffsetPeriod;
if FFileName = '' then
FFileName := ChangeFileExt(GetModuleName(0), CKafkaOffsetExt);
FOffsetIniFile := TIniFile.Create(FFileName);
FOffset := StrToInt64Def(FOffsetIniFile.ReadString('kafka', 'offset', ''), RD_KAFKA_OFFSET_BEGINNING);
end;
destructor TKafkaOffset.Destroy;
begin
StoreOffset;
FOffsetIniFile.Free;
inherited;
end;
function TKafkaOffset.GetValue: Int64;
begin
Result := FOffset;
end;
procedure TKafkaOffset.SetValue(const Value: Int64);
begin
if FOffset = Value then
Exit;
SaveOffset(Value, True, 0);
end;
procedure TKafkaOffset.StoreOffset;
begin
FOffsetIniFile.WriteString('kafka', 'offset', IntToStr(FOffset));
end;
function TKafkaOffset.Save(AOffset: Int64): Int64;
begin
Value := AOffset;
Result := Value;
end;
procedure TKafkaOffset.SaveOffset(const ANewOffset: Int64; const AStoreValue: Boolean; const ADT: TDateTime = 0);
begin
FOffset := ANewOffset;
if AStoreValue then
if (FLastOffsetDT + FWriteOffsetPeriod * OneSecond) < Now then
begin
StoreOffset;
FWriteOffsetDTPrev := FWriteOffsetDT;
FWriteOffsetDT := Now();
if (FWriteOffsetDTPrev > 0) and (FWriteOffsetDTPrev <> FWriteOffsetDT) then
begin
FOffsetIniFile.WriteInteger('stat', 'PointPerSec', Round((ANewOffset - FLastOffsetCounted) / (FWriteOffsetDT - FWriteOffsetDTPrev) / SecsPerDay));
FLastOffsetCounted := ANewOffset;
end;
FLastOffsetDT := Now;
end;
if (Trunc(ANewOffset/10000)*10000 = ANewOffset) and (FPrev10KOffset < ANewOffset) then
begin
ToLog('Offset = ' + IntToStr(ANewOffset) + IfThen(ADT = 0, '', ', ' + FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', ADT)) + ', ' + IntToStr( Round((ANewOffset - FPrev10KOffset)/(Now - FPrev10KDT)/SecsPerDay)) + 'pps');
FPrev10KDT := Now;
FPrev10KOffset := ANewOffset;
end;
end;
end.
|
unit frmSmallLearningGroup;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, dbfunc, uKernel;
type
TfSmallLearningGroup = class(TForm)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
lvSmallLearningGroup: TListView;
GroupBox1: TGroupBox;
GroupBox2: TGroupBox;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
Label13: TLabel;
Label14: TLabel;
bClose: TButton;
bSave: TButton;
bNewRecord: TButton;
bGroupMembers: TButton;
bDeleteGroup: TButton;
cmbChooseAcademicYear: TComboBox;
cmbChooseEducationProgram: TComboBox;
cmbChoosePedagogue: TComboBox;
cmbChooseStatus: TComboBox;
cmbAcademicYear: TComboBox;
cmbEducationProgram: TComboBox;
cmbHoursAmount: TComboBox;
cmbLearningForm: TComboBox;
cmbLearningLevel: TComboBox;
cmbPedagogue: TComboBox;
cmbStatus: TComboBox;
eGroupName: TEdit;
Label10: TLabel;
procedure bDeleteGroupeClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure lvSmallLearningGroupSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
procedure bNewRecordClick(Sender: TObject);
procedure lvSmallLearningGroupCustomDrawItem(Sender: TCustomListView;
Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean);
procedure cmbChooseEducationProgramChange(Sender: TObject);
procedure cmbChoosePedagogueChange(Sender: TObject);
procedure cmbChooseAcademicYearChange(Sender: TObject);
procedure cmbChooseLearningFormChange(Sender: TObject);
procedure cmbChooseStatusChange(Sender: TObject);
procedure bGroupMembersClick(Sender: TObject);
procedure bCloseClick(Sender: TObject);
procedure bSaveClick(Sender: TObject);
private
AcademicYear: TResultTable;
EducationProgram: TResultTable;
PedagogueSurnameNP: TResultTable;
StatusLearningGroup: TResultTable;
SmallLearnGroupList: TResultTable;
LearningLevel: TResultTable;
AmountHours: TResultTable;
GroupeName: TResultTable;
LearningForm: TResultTable;
NewIDSmallLG: TResultTable;
FIDPedagogue: integer;
FIDCurAcademicYear: integer;
IDLearningGroup: integer;
procedure ShowSmallLearnGrList;
procedure OnChangeCMBsSetProperties;
/// //////////////function ChangeCMBsSetProperties: Array of integer; ??????
procedure SetIDPedagogue(const Value: integer);
procedure SetIDCurAcademicYear(const Value: integer);
procedure DoClearSmallLearnGroup;
public
// IDLearningGroup: integer;
property IDPedagogue: integer read FIDPedagogue write SetIDPedagogue;
property IDCurAcademicYear: integer read FIDCurAcademicYear
write SetIDCurAcademicYear;
end;
var
fSmallLearningGroup: TfSmallLearningGroup;
implementation
{$R *.dfm}
uses frmSmallLearnGrMembers;
procedure TfSmallLearningGroup.bGroupMembersClick(Sender: TObject);
begin
if (not Assigned(fSmallLearnGrMembers)) then
fSmallLearnGrMembers := TfSmallLearnGrMembers.Create(Self);
fSmallLearnGrMembers.ShowModal;
if fSmallLearnGrMembers.ModalResult = mrOk then
ShowSmallLearnGrList;
end;
procedure TfSmallLearningGroup.bNewRecordClick(Sender: TObject);
begin
IDLearningGroup := -1;
DoClearSmallLearnGroup;
end;
procedure TfSmallLearningGroup.bSaveClick(Sender: TObject);
var
idLearningForm, idEducationProgram, id_Pedagogue, idLearningLevel,
idAcademicYear, idStatusLearningGroup, Amount_Hours: integer;
GName: string;
begin
// при сохранении изменений создается новая группа, а не вносятся изменения
idLearningForm := LearningForm[cmbLearningForm.ItemIndex].ValueByName('ID');
idEducationProgram := EducationProgram[cmbEducationProgram.ItemIndex]
.ValueByName('ID');
id_Pedagogue := PedagogueSurnameNP[cmbPedagogue.ItemIndex].ValueByName
('ID_OUT');
idLearningLevel := LearningLevel[cmbLearningLevel.ItemIndex]
.ValueByName('ID');
idAcademicYear := AcademicYear[cmbAcademicYear.ItemIndex].ValueByName('ID');
idStatusLearningGroup := StatusLearningGroup[cmbStatus.ItemIndex]
.ValueByName('CODE');
Amount_Hours := AmountHours[cmbHoursAmount.ItemIndex].ValueByName
('WEEK_AMOUNT');
GName := 'Временное название.';
if (cmbEducationProgram.ItemIndex = -1) or (cmbPedagogue.ItemIndex = -1) or
(cmbAcademicYear.ItemIndex = -1) or (cmbLearningForm.ItemIndex = -1) or
(cmbStatus.ItemIndex = -1) or (cmbLearningLevel.ItemIndex = -1) or
(cmbHoursAmount.ItemIndex = -1) then
begin
ShowMessage('Не все поля заполнены!');
Exit;
end;
// if Kernel.SaveLearningGroup([IDLearningGroup, idLearningForm,
// idEducationProgram, id_Pedagogue, idLearningLevel, idAcademicYear,
// idStatusLearningGroup, Amount_Hours, GName]) then
// begin
// ShowMessage('Сохранение выполнено!');
if Assigned(NewIDSmallLG) then
FreeAndNil(NewIDSmallLG);
NewIDSmallLG := Kernel.GetIDSmallLearnGroup(IDLearningGroup,
idLearningForm, idEducationProgram, id_Pedagogue, idLearningLevel,
idAcademicYear, idStatusLearningGroup, Amount_Hours, GName);
if (not Assigned(fSmallLearnGrMembers)) then // стр 110 тоже создание формы
fSmallLearnGrMembers := TfSmallLearnGrMembers.Create(Self);
if NewIDSmallLG.Count > 0 then
fSmallLearnGrMembers.IDLearningGroup := NewIDSmallLG[0]
.ValueByName('ID_OUT');
fSmallLearnGrMembers.GName := GName;
fSmallLearnGrMembers.ShowModal;
if fSmallLearnGrMembers.ModalResult = mrOk then
ShowSmallLearnGrList;
// end
// else
// ShowMessage('Ошибка при сохранении!');
end;
procedure TfSmallLearningGroup.bCloseClick(Sender: TObject);
begin
Close;
end;
procedure TfSmallLearningGroup.bDeleteGroupeClick(Sender: TObject);
begin
//TODO: продумать удаление группы, ведь в нее могут быть зачислены дети и привязано расписание
if Kernel.DeleteGroup([fSmallLearnGrMembers.IDLearningGroup]) then
begin
ShowMessage('Группа удалена!'); // МОЖЕТ НЕ СТОИТ ВЫВОДИТЬ ЭТО СООБЩЕНИЕ!!???
ShowSmallLearnGrList; // для обновления осн.сведений
end
else
ShowMessage('Ошибка при удалении группы!');
end;
procedure TfSmallLearningGroup.cmbChooseAcademicYearChange(Sender: TObject);
begin
ShowSmallLearnGrList;
end;
procedure TfSmallLearningGroup.cmbChooseEducationProgramChange(Sender: TObject);
begin
ShowSmallLearnGrList;
end;
procedure TfSmallLearningGroup.cmbChooseLearningFormChange(Sender: TObject);
begin
ShowSmallLearnGrList;
end;
procedure TfSmallLearningGroup.cmbChoosePedagogueChange(Sender: TObject);
begin
ShowSmallLearnGrList;
end;
procedure TfSmallLearningGroup.cmbChooseStatusChange(Sender: TObject);
begin
ShowSmallLearnGrList;
end;
procedure TfSmallLearningGroup.DoClearSmallLearnGroup;
var
i: integer;
begin
cmbHoursAmount.ItemIndex := 0; // мелкогрупповые обычно по часу
cmbLearningLevel.ItemIndex := -1;
cmbStatus.ItemIndex := 2; // статус "группы" при очистке всегда предварительная/о - еще подумать..
cmbLearningForm.ItemIndex := 1; // форма обучения всегда мелкогрупповая
cmbLearningForm.Enabled := false;
// комбик с учебным годом после очистки должен содержать текущий учебный год
Kernel.ChooseComboBoxItemIndex(cmbAcademicYear, AcademicYear, true, 'ID',
IDCurAcademicYear);
// комбик с педагогом должен содержать педагога из cmbChoosePedagogue, а если там 'Все'
// то по выбираю по IDPedagogue
if cmbChoosePedagogue.ItemIndex = 0 then
Kernel.ChooseComboBoxItemIndex(cmbPedagogue, PedagogueSurnameNP, true,
'ID_OUT', IDPedagogue) else
cmbPedagogue.ItemIndex := cmbChoosePedagogue.ItemIndex - 1;
cmbEducationProgram.ItemIndex := -1;
eGroupName.Clear;
end;
procedure TfSmallLearningGroup.FormCreate(Sender: TObject);
begin
AcademicYear := nil;
EducationProgram := nil;
PedagogueSurnameNP := nil;
StatusLearningGroup := nil;
SmallLearnGroupList := nil;
LearningLevel := nil;
AmountHours := nil;
GroupeName := nil; // ?????
LearningForm := nil;
NewIDSmallLG := nil;
end;
procedure TfSmallLearningGroup.FormDestroy(Sender: TObject);
begin
if Assigned(AcademicYear) then
FreeAndNil(AcademicYear);
if Assigned(EducationProgram) then
FreeAndNil(EducationProgram);
if Assigned(PedagogueSurnameNP) then
FreeAndNil(PedagogueSurnameNP);
if Assigned(StatusLearningGroup) then
FreeAndNil(StatusLearningGroup);
if Assigned(SmallLearnGroupList) then
FreeAndNil(SmallLearnGroupList);
if Assigned(LearningLevel) then
FreeAndNil(LearningLevel);
if Assigned(AmountHours) then
FreeAndNil(AmountHours);
if Assigned(GroupeName) then // ???
FreeAndNil(GroupeName);
if Assigned(LearningForm) then
FreeAndNil(LearningForm);
if Assigned(NewIDSmallLG) then
FreeAndNil(NewIDSmallLG);
end;
procedure TfSmallLearningGroup.FormShow(Sender: TObject);
var
i: integer;
begin
if not Assigned(AcademicYear) then
AcademicYear := Kernel.GetAcademicYear;
Kernel.FillingComboBox(cmbChooseAcademicYear, AcademicYear, 'NAME', true);
Kernel.ChooseComboBoxItemIndex(cmbChooseAcademicYear, AcademicYear, true,
'ID', IDCurAcademicYear);
Kernel.FillingComboBox(cmbAcademicYear, AcademicYear, 'NAME', false);
// Kernel.ChooseComboBoxItemIndex(cmbAcademicYear, AcademicYear, true, 'ID',
// IDCurAcademicYear);
if not Assigned(EducationProgram) then
EducationProgram := Kernel.GetEducationProgram;
Kernel.FillingComboBox(cmbChooseEducationProgram, EducationProgram,
'NAME', true);
cmbChooseEducationProgram.ItemIndex := 0;
Kernel.FillingComboBox(cmbEducationProgram, EducationProgram, 'NAME', false);
// Kernel.ChooseComboBoxItemIndex(cmbEducationProgram, EducationProgram, true,
// 'ID', IDCurAcademicYear);
if not Assigned(PedagogueSurnameNP) then
PedagogueSurnameNP := Kernel.GetPedagogueSurnameNP;
Kernel.FillingComboBox(cmbChoosePedagogue, PedagogueSurnameNP,
'SurnameNP', true);
Kernel.ChooseComboBoxItemIndex(cmbChoosePedagogue, PedagogueSurnameNP, true,
'ID_OUT', IDPedagogue);
Kernel.FillingComboBox(cmbPedagogue, PedagogueSurnameNP, 'SurnameNP', false);
// Kernel.ChooseComboBoxItemIndex(cmbPedagogue, PedagogueSurnameNP, true,
// 'ID_OUT', IDPedagogue);
if not Assigned(LearningLevel) then
LearningLevel := Kernel.GetLearningLevel;
Kernel.FillingComboBox(cmbLearningLevel, LearningLevel, 'NAME', false);
// Kernel.ChooseComboBoxItemIndex(cmbLearningLevel, LearningLevel, true, 'ID',
// IDCurAcademicYear);
if not Assigned(AmountHours) then
AmountHours := Kernel.GetAmountHours;
Kernel.FillingComboBox(cmbHoursAmount, AmountHours, 'WEEK_AMOUNT', false);
cmbHoursAmount.ItemIndex := 0;
if not Assigned(LearningForm) then
LearningForm := Kernel.GetLearningForm;
Kernel.FillingComboBox(cmbLearningForm, LearningForm, 'NAME', false);
cmbLearningForm.ItemIndex := 1; // всегда мелкогрупповая
cmbLearningForm.Enabled := false;
if not Assigned(StatusLearningGroup) then
StatusLearningGroup := Kernel.GetStatusLearningGroup(3);
Kernel.FillingComboBox(cmbChooseStatus, StatusLearningGroup, 'NOTE', true);
cmbChooseStatus.ItemIndex := 0;
Kernel.FillingComboBox(cmbStatus, StatusLearningGroup, 'NOTE', false);
// cmbStatus.ItemIndex := 0;
eGroupName.Enabled := false;
ShowSmallLearnGrList;
end;
procedure TfSmallLearningGroup.lvSmallLearningGroupCustomDrawItem
(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState;
var DefaultDraw: Boolean);
begin
if Item.SubItems.Strings[5] = 'Расформированная' then
Sender.Canvas.Brush.Color := 6521080; {
Sender.Canvas.Brush.Color := $00FF0000;
else
Sender.Canvas.Brush.Color := clWindow; }
// if Item.Selected { in State } then
// Sender.Canvas.Brush.Color := 6521080 // ан не работает...
end;
procedure TfSmallLearningGroup.lvSmallLearningGroupSelectItem(Sender: TObject;
Item: TListItem; Selected: Boolean);
var
i, education_program, pedagogue, academic_year, learning_group_type,
status: integer;
begin
if (not Assigned(fSmallLearnGrMembers)) then
fSmallLearnGrMembers := TfSmallLearnGrMembers.Create(Self);
with SmallLearnGroupList[Item.Index] do
begin
fSmallLearnGrMembers.IDLearningGroup := ValueByName('ID_OUT');
fSmallLearnGrMembers.idAcademicYear := ValueByName('ID_ACADEMIC_YEAR');
fSmallLearnGrMembers.idEducationProgram :=
ValueByName('ID_EDUCATION_PROGRAM'); // ???
fSmallLearnGrMembers.IDPedagogue := ValueByName('ID_PEDAGOGUE'); // ???
fSmallLearnGrMembers.StrEducationProgram :=
ValueStrByName('EDUCATION_PROGRAM');
fSmallLearnGrMembers.StrPedagogue := ValueStrByName('SURNAMENP');
fSmallLearnGrMembers.StrAcademicYear := ValueStrByName('ACADEMIC_YEAR');
fSmallLearnGrMembers.StrLearningLevel := ValueStrByName('LEARNING_LEVEL');
fSmallLearnGrMembers.GName := ValueStrByName('NAME');
end;
eGroupName.Text := SmallLearnGroupList[Item.Index].ValueByName('NAME');
// здесь меняю индексы у "нижних" комбиков - перенести в процедуры cmbChoose...Change
for i := 0 to StatusLearningGroup.Count - 1 do
if StatusLearningGroup[i].ValueByName('CODE') = SmallLearnGroupList
[Item.Index].ValueByName('ID_STATUS') then
cmbStatus.ItemIndex := i;
for i := 0 to LearningLevel.Count - 1 do
if LearningLevel[i].ValueByName('ID') = SmallLearnGroupList[Item.Index]
.ValueByName('ID_LEARNING_LEVEL') then
cmbLearningLevel.ItemIndex := i;
for i := 0 to AmountHours.Count - 1 do
if AmountHours[i].ValueByName('WEEK_AMOUNT') = SmallLearnGroupList
[Item.Index].ValueByName('ID_WEEK_AMOUNT') then
cmbHoursAmount.ItemIndex := i;
for i := 0 to EducationProgram.Count - 1 do
if EducationProgram[i].ValueByName('ID') = fSmallLearnGrMembers.idEducationProgram
then
cmbEducationProgram.ItemIndex := i;
for i := 0 to PedagogueSurnameNP.Count - 1 do
if PedagogueSurnameNP[i].ValueByName('ID_OUT') = fSmallLearnGrMembers.IDPedagogue
then
cmbPedagogue.ItemIndex := i;
for i := 0 to AcademicYear.Count - 1 do
if AcademicYear[i].ValueByName('ID') = fSmallLearnGrMembers.idAcademicYear
then
cmbAcademicYear.ItemIndex := i;
end;
// TODO: ВМЕСТО ПРОЦЕДУРЫ ЗАМУТИТЬ ФУНКЦИЮ, возвращающую целочисленный массив?????????
procedure TfSmallLearningGroup.OnChangeCMBsSetProperties;
var
education_program, pedagogue, academic_year, learning_group_type,
status: integer;
begin
// if cmbChooseEducationProgram.ItemIndex = 0 then
// education_program := 0
// else
// education_program := EducationProgram[cmbChooseEducationProgram.ItemIndex -
// 1].ValueByName('ID');
//
// if cmbChoosePedagogue.ItemIndex = 0 then
// pedagogue := 0
// else
// pedagogue := PedagogueSurnameNP[cmbChoosePedagogue.ItemIndex - 1]
// .ValueByName('ID_OUT');
// if cmbChooseAcademicYear.ItemIndex = 0 then
// academic_year := 0
// else
// academic_year := AcademicYear[cmbChooseAcademicYear.ItemIndex - 1]
// .ValueByName('ID');
// if cmbChooseStatus.ItemIndex = 0 then
// status := 0
// else
// status := StatusLearningGroup[cmbChooseStatus.ItemIndex - 1]
// .ValueByName('CODE');
// if (not Assigned(fSmallLearnGrMembers)) then
// fSmallLearnGrMembers := TfSmallLearnGrMembers.Create(Self);
// fSmallLearnGrMembers.idEducationProgram := education_program;
// fSmallLearnGrMembers.IDPedagogue := pedagogue;
end;
procedure TfSmallLearningGroup.SetIDCurAcademicYear(const Value: integer);
begin
if FIDCurAcademicYear <> Value then
FIDCurAcademicYear := Value;
end;
procedure TfSmallLearningGroup.SetIDPedagogue(const Value: integer);
begin
if FIDPedagogue <> Value then
FIDPedagogue := Value;
end;
procedure TfSmallLearningGroup.ShowSmallLearnGrList;
var
i, education_program, pedagogue, academic_year, learning_group_type,
status: integer;
begin
if cmbChooseEducationProgram.ItemIndex = 0 then
education_program := 0
else
begin
education_program := EducationProgram[cmbChooseEducationProgram.ItemIndex -
1].ValueByName('ID');
//
// for i := 0 to EducationProgram.Count - 1 do
// if EducationProgram[i].ValueByName('ID') = education_program then
// cmbEducationProgram.ItemIndex := i;
//
end;
if cmbChoosePedagogue.ItemIndex = 0 then
pedagogue := 0
else
begin
pedagogue := PedagogueSurnameNP[cmbChoosePedagogue.ItemIndex - 1]
.ValueByName('ID_OUT');
//
// for i := 0 to PedagogueSurnameNP.Count - 1 do
// if PedagogueSurnameNP[i].ValueByName('ID_OUT') = pedagogue then
// cmbPedagogue.ItemIndex := i;
//
end;
if cmbChooseAcademicYear.ItemIndex = 0 then
academic_year := 0
else
begin
academic_year := AcademicYear[cmbChooseAcademicYear.ItemIndex - 1]
.ValueByName('ID');
//
// for i := 0 to AcademicYear.Count - 1 do
// if AcademicYear[i].ValueByName('ID') = academic_year then
// cmbAcademicYear.ItemIndex := i;
//
end;
if cmbChooseStatus.ItemIndex = 0 then
status := 0
else
status := StatusLearningGroup[cmbChooseStatus.ItemIndex - 1]
.ValueByName('CODE');
learning_group_type := 2; // я не получаю программно этот тип, а закладываю
// вручную - несовершенство, с которым нужно смириться? как изменить не знаю пока
OnChangeCMBsSetProperties;
if Assigned(SmallLearnGroupList) then
FreeAndNil(SmallLearnGroupList);
SmallLearnGroupList := Kernel.GetLearningGroupList(education_program,
pedagogue, academic_year, learning_group_type, status);
Kernel.GetLVSmallLearningGroup(lvSmallLearningGroup, SmallLearnGroupList);
if lvSmallLearningGroup.Items.Count > 0 then
begin
lvSmallLearningGroup.ItemIndex := 0;
bGroupMembers.Enabled := true;
bDeleteGroup.Enabled := true;
end
else
begin
IDLearningGroup := -1;
DoClearSmallLearnGroup;
bGroupMembers.Enabled := false;
bDeleteGroup.Enabled := false;
end;
end;
end.
|
{-----------------------------------------------------------------------------
Least-Resistance Designer Library
The Initial Developer of the Original Code is Scott J. Miles
<sjmiles (at) turbophp (dot) com>.
Portions created by Scott J. Miles are
Copyright (C) 2005 Least-Resistance Software.
All Rights Reserved.
-------------------------------------------------------------------------------}
unit DesignMouse;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, Graphics, Forms, ExtCtrls,
Contnrs,
DesignHandles, DesignController;
type
TDesignCustomMouseTool = class(TDesignMouseTool)
private
FController: TDesignController;
FMouseLast: TPoint;
FMouseStart: TPoint;
protected
function GetMouseDelta: TPoint; virtual;
public
constructor Create(AOwner: TDesignController); virtual;
property Controller: TDesignController read FController write FController;
end;
//
TDesignMover = class(TDesignCustomMouseTool)
private
FDragRects: array of TRect;
protected
procedure ApplyDragRects;
procedure CalcDragRects;
procedure CalcPaintRects;
procedure PaintDragRects;
public
constructor Create(AOwner: TDesignController); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
end;
//
TDesignBander = class(TDesignCustomMouseTool)
protected
function GetClient: TControl; virtual;
function GetPaintRect: TRect;
procedure CalcDragRect; virtual;
procedure PaintDragRect; virtual;
public
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
end;
//
TDesignSizer = class(TDesignBander)
private
FHandleId: TDesignHandleId;
protected
function GetClient: TControl; override;
procedure ApplyDragRect;
procedure ApplyMouseDelta(X, Y: Integer);
procedure CalcDragRect; override;
public
constructor CreateSizer(AOwner: TDesignController;
inHandle: TDesignHandleId);
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
end;
implementation
procedure LrPaintRubberbandRect(const inRect: TRect; inPenStyle: TPenStyle);
var
desktopWindow: HWND;
dc: HDC;
c: TCanvas;
begin
desktopWindow := GetDesktopWindow;
dc := GetDCEx(desktopWindow, 0, DCX_CACHE or DCX_LOCKWINDOWUPDATE);
try
c := TCanvas.Create;
with c do
try
Handle := dc;
Pen.Style := inPenStyle;
Pen.Color := clWhite;
Pen.Mode := pmXor;
Brush.Style := bsClear;
Rectangle(inRect);
finally
c.Free;
end;
finally
ReleaseDC(desktopWindow, dc);
end;
end;
{ TDesignCustomMouseTool }
constructor TDesignCustomMouseTool.Create(AOwner: TDesignController);
begin
Controller := AOwner;
end;
function TDesignCustomMouseTool.GetMouseDelta: TPoint;
const
GridX = 4;
GridY = 4;
begin
with Result do
begin
X := FMouseLast.X - FMouseStart.X;
Dec(X, X mod GridX);
Y := FMouseLast.Y - FMouseStart.Y;
Dec(Y, Y mod GridY);
end;
end;
{ TDesignMover }
constructor TDesignMover.Create(AOwner: TDesignController);
begin
inherited;
SetLength(FDragRects, Controller.Count);
end;
procedure TDesignMover.CalcDragRects;
var
delta: TPoint;
i: Integer;
begin
delta := GetMouseDelta;
for i := 0 to Pred(Controller.Count) do
with Controller.Selection[i] do
begin
FDragRects[i] := BoundsRect;
OffsetRect(FDragRects[i], delta.X, delta.Y);
end;
end;
procedure TDesignMover.CalcPaintRects;
var
i: Integer;
begin
CalcDragRects;
for i := 0 to Pred(Controller.Count) do
with Controller.Selection[i] do
with Parent.ClientToScreen(Point(0, 0)) do
OffsetRect(FDragRects[i], X, Y);
end;
procedure TDesignMover.PaintDragRects;
var
i: Integer;
begin
for i := 0 to Pred(Controller.Count) do
LrPaintRubberbandRect(FDragRects[i], psDot);
end;
procedure TDesignMover.ApplyDragRects;
var
i: Integer;
begin
if (GetMouseDelta.X <> 0) or (GetMouseDelta.Y <> 0) then
begin
CalcDragRects;
for i := 0 to Pred(Controller.Count) do
Controller.Selection[i].BoundsRect := FDragRects[i];
Controller.UpdateDesigner;
Controller.Change;
end;
end;
procedure TDesignMover.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
FMouseStart := Point(X, Y);
FMouseLast := FMouseStart;
CalcPaintRects;
PaintDragRects;
end;
procedure TDesignMover.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
PaintDragRects;
FMouseLast := Point(X, Y);
CalcPaintRects;
PaintDragRects;
end;
procedure TDesignMover.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
PaintDragRects;
FMouseLast := Point(X, Y);
ApplyDragRects;
end;
{ TDesignBander }
procedure TDesignBander.CalcDragRect;
begin
with GetMouseDelta do
begin
DragRect := Rect(0, 0, X, Y);
OffsetRect(FDragRect, FMouseStart.X, FMouseStart.Y);
end;
end;
function TDesignBander.GetClient: TControl;
begin
Result := Controller.Container;
end;
function TDesignBander.GetPaintRect: TRect;
begin
Result := FDragRect;
with GetClient.ClientToScreen(Point(0, 0)) do
OffsetRect(Result, X, Y);
end;
procedure TDesignBander.PaintDragRect;
begin
LrPaintRubberbandRect(GetPaintRect, psDot);
end;
procedure TDesignBander.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
FMouseStart := Point(X, Y);
FMouseLast := FMouseStart;
CalcDragRect;
PaintDragRect;
end;
procedure TDesignBander.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
PaintDragRect;
FMouseLast := Point(X, Y);
CalcDragRect;
PaintDragRect;
end;
procedure TDesignBander.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
PaintDragRect;
CalcDragRect;
end;
{ TDesignSizer }
constructor TDesignSizer.CreateSizer(AOwner: TDesignController;
inHandle: TDesignHandleId);
begin
inherited Create(AOwner);
FHandleId := inHandle;
end;
procedure TDesignSizer.ApplyMouseDelta(X, Y: Integer);
begin
case FHandleId of
dhLeftTop, dhMiddleTop, dhRightTop: Inc(FDragRect.Top, Y);
dhLeftBottom, dhMiddleBottom, dhRightBottom: Inc(FDragRect.Bottom, Y);
end;
case FHandleId of
dhLeftTop, dhLeftMiddle, dhLeftBottom: Inc(FDragRect.Left, X);
dhRightTop, dhRightMiddle, dhRightBottom: Inc(FDragRect.Right, X);
end;
end;
procedure TDesignSizer.CalcDragRect;
begin
FDragRect := Controller.Selected.BoundsRect;
with GetMouseDelta do
ApplyMouseDelta(X, Y);
end;
function TDesignSizer.GetClient: TControl;
begin
Result := Controller.Selected.Parent;
end;
procedure TDesignSizer.ApplyDragRect;
begin
Controller.Selected.BoundsRect := FDragRect;
Controller.UpdateDesigner;
Controller.Change;
end;
procedure TDesignSizer.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
inherited;
ApplyDragRect;
end;
end.
|
unit o_lpBaseList;
interface
uses
SysUtils, Classes, Contnrs;
type
Tlp_BaseList = class
private
function GetCount: Integer;
protected
fList: TObjectList;
public
constructor Create; virtual;
destructor Destroy; override;
property Count: Integer read GetCount;
procedure Clear;
end;
implementation
{ Tci_BaseList }
constructor Tlp_BaseList.Create;
begin
fList := TObjectList.Create;
end;
destructor Tlp_BaseList.Destroy;
begin
FreeAndNil(fList);
inherited;
end;
procedure Tlp_BaseList.Clear;
begin
fList.Clear;
end;
function Tlp_BaseList.GetCount: Integer;
begin
Result := fList.Count;
end;
end.
|
unit svm_exceptions;
//{$define WindowsSEH}
{$mode objfpc}
{$H+}
interface
uses
Classes,
SysUtils,
svm_common
{$IfDef WindowsSEH},
Windows,
JwaWinBase,
JwaWinNT
{$endif};
type
TTRBlock = record
CatchPoint, EndPoint: TInstructionPointer;
end;
EUnhandledException = class(Exception);
EUnhandledVirtualRaisedException = class(EUnhandledException);
TTRBlocks = object
public
trblocks: array of TTRBlock;
procedure add(CP, EP: TInstructionPointer);
function TR_Catch(E: Exception): TInstructionPointer;
function TR_Finally: TInstructionPointer;
end;
type
EUnknownException = class(Exception);
{***** Windows VEH ************************************************************}
{$IfDef WindowsSEH}
var
VEHExceptions: TThreadList;
VEHExceptions_Count: word = 0;
SEH_Handler: Pointer;
function WinSVMVectoredHandler(ExceptionInfo: PExceptionPointers): longint; stdcall;
procedure SVM_InitVEH;
procedure SVM_FreeVEH;
{$EndIf}
procedure RaiseSafeException;
implementation
procedure TTRBlocks.add(CP, EP: TInstructionPointer); inline;
begin
SetLength(self.trblocks, length(self.trblocks) + 1);
with self.trblocks[length(self.trblocks) - 1] do
begin
CatchPoint := CP;
EndPoint := EP;
end;
end;
function TTRBlocks.TR_Catch(E: Exception): TInstructionPointer; inline;
begin
if Length(self.trblocks) > 0 then
begin
Result := self.trblocks[length(self.trblocks) - 1].CatchPoint;
SetLength(self.trblocks, length(self.trblocks) - 1);
end
else
begin
{$IfDef WindowsSEH}
writeln('Unhandled exception <', E.ClassName, '>', sLineBreak,
'- Message: "', E.Message, '"', sLineBreak,
'- ThreadID: ', GetCurrentThreadId);
ExitThread(1);
{$Else}
raise E;
{$EndIf}
end;
end;
function TTRBlocks.TR_Finally: TInstructionPointer; inline;
begin
Result := self.trblocks[length(self.trblocks) - 1].EndPoint;
setlength(self.trblocks, length(self.trblocks) - 1);
end;
{$IfDef WindowsSEH}
// For Win 32/64 VEH exceptions.
{function GetRegistrationHead: PExceptionRegistrationRecord;
external 'kernel32.dll' name 'GetRegistrationHead';
procedure RtlRaiseException(ExceptionRecord: PExceptionRecord);
external 'kernel32.dll' name 'RtlRaiseException';
function NtContinue(ThreadContext:PContext; RaiseAlert: boolean): THandle;
external 'ntdll.dll' name 'NtContinue';
function NtRaiseException(ExceptionRecord: PExceptionRecord; ThreadContext:
PContext; HandleException: boolean): THandle;
external 'ntdll.dll' name 'NtRaiseException';}
function WinSVMVectoredHandler(ExceptionInfo: PExceptionPointers): longint; stdcall;
var
pExceptReg: PExceptionRegistrationRecord;
begin
if byte(ExceptionInfo^.ExceptionRecord^.ExceptionCode) in
[byte(Windows.EXCEPTION_FLT_DIVIDE_BY_ZERO),
byte(Windows.EXCEPTION_ACCESS_VIOLATION),
byte(Windows.EXCEPTION_ARRAY_BOUNDS_EXCEEDED),
byte(Windows.EXCEPTION_FLT_INVALID_OPERATION),
byte(Windows.EXCEPTION_FLT_OVERFLOW), byte(Windows.EXCEPTION_FLT_UNDERFLOW),
byte(Windows.EXCEPTION_NONCONTINUABLE_EXCEPTION)] then
Result := EXCEPTION_EXECUTE_HANDLER
else
begin
try
Exception(ExceptionInfo^.ExceptionRecord^.ExceptionInformation[1]).Free;
//ExceptionInfo^.ExceptionRecord^.ExceptionCode := 0;
finally
Result := EXCEPTION_CONTINUE_EXECUTION;
end;
VEHExceptions.Add(Pointer(GetCurrentThreadId));
Inc(VEHExceptions_Count);
end;
end;
procedure SVM_InitVEH;
begin
VEHExceptions := TThreadList.Create;
SEH_Handler := nil;
SEH_Handler := AddVectoredExceptionHandler(0, @WinSVMVectoredHandler);
end;
procedure SVM_FreeVEH;
begin
if SEH_Handler <> nil then
RemoveVectoredExceptionHandler(SEH_Handler);
FreeAndNil(VEHExceptions);
end;
{$EndIf}
procedure RaiseSafeException;
begin
{$IfDef WindowsSEH}
VEHExceptions.Add(Pointer(GetCurrentThreadId));
Inc(VEHExceptions_Count);
{$Else}
raise EUnhandledVirtualRaisedException.Create('Unhandled virtual raised exception');
{$EndIf}
end;
end.
|
namespace TabBar;
interface
uses
UIKit;
type
[IBObject]
RootViewController = public class(UIViewController, IUITabBarDelegate)
private
fSelectedTab: weak UITabBarItem;
public
method init: id; override;
method viewDidLoad; override;
method didReceiveMemoryWarning; override;
{$REGION IUITabBarDelegate}
method tabBar(aTabBar: UITabBar) didSelectItem(aItem: UITabBarItem);
//method tabBar(aTabBar: UITabBar) willBeginCustomizingItems(aItem: NSArray);
//method tabBar(aTabBar: UITabBar) willEndCustomizingItems(aItem: NSArray) changed(aChanged: Boolean);
{$ENDREGION}
[IBOutlet] property label: weak UILabel;
[IBOutlet] property button: weak UIButton;
[IBOutlet] property tabBar: weak UITabBar;
[IBAction] method buttonClick(aSender: id);
end;
implementation
method RootViewController.init: id;
begin
self := inherited initWithNibName('RootViewController') bundle(nil);
if assigned(self) then begin
title := 'TabBar';
// Custom initialization
end;
result := self;
end;
method RootViewController.viewDidLoad;
begin
inherited viewDidLoad;
label.text := 'Select a Tab';
button.hidden := true;
// Do any additional setup after loading the view.
end;
method RootViewController.didReceiveMemoryWarning;
begin
inherited didReceiveMemoryWarning;
// Dispose of any resources that can be recreated.
end;
method RootViewController.tabBar(aTabBar: UITabBar) didSelectItem(aItem: UITabBarItem);
begin
NSLog('tabbar:%@ didSelectItem:%@', aTabBar, aItem);
fSelectedTab := aItem;
label.text := 'Selected tab '+tabBar.items.indexOfObject(aItem);
button.hidden := false;
end;
method RootViewController.buttonClick(aSender: id);
begin
if assigned(fSelectedTab) then
fSelectedTab.badgeValue := coalesce((fSelectedTab.badgeValue:integerValue+1):stringValue, "1");
end;
end.
|
unit Cn_uReportsConst;
interface
{Message}
const Studcity_MESSAGE_NO_CHOOSE_SUMMA :array[1..2] of String=('Не вибран тип заборгованості','Не выбран тип зодолженности');
const Studcity_MESSAGE_WARNING_CONST :array[1..2] of String=('Увага','Внимание');
const Studcity_MESSAGE_WAIT_CONST :array[1..2] of String=('Чекайте! Йде обробка данних!','Ждите! Идет обработка данных!');
const Studcity_MESSAGE_SCH_DB :array[1..2] of String=('Не вибран дебетовий рахунок','Не выбран дебетовый счет');
const Studcity_MESSAGE_SCH_KD :array[1..2] of String=('Не вибран кредитовий рахунок','Не выбран кредитовый счет');
const Studcity_MESSAGE_SMETA :array[1..2] of String=('Не вибрана бюджет','Не выбрана смета');
{Button}
const cn_ButtonView :array[1..2] of String=('Перегляд(F12)','Просмотр(F12)');
const cn_ButtonCancel :array[1..2] of String=('Відмінити','Отменить');
const cn_RepFIO :array[1..2] of String=('П.І.Б.','Ф.И.О.');
const cn_RepDog :array[1..2] of String=('Договір №','Договор №');
const cn_RepDateDog :array[1..2] of String=('Дата заключення','Дата заключения');
const cn_RepDogperiod :array[1..2] of String=('Період дії договору','Период действия договора');
const cn_RepDogPay :array[1..2] of String=('Платник по договору','Плательщик по договору');
const cn_RepDogSumEnd :array[1..2] of String=('Сума договору, грн','Сумма договора, грн');
const cn_RepDogSumNeed :array[1..2] of String=('Спл. на дату разрахунку, грн','Опл. на дату расчета, грн');
const cn_RepDogSumPay :array[1..2] of String=('Сплачено, грн','Оплачено, грн');
const cn_RepDogSumOverPay :array[1..2] of String=('Переплата, грн','Переплата, грн');
const cn_RepDogSumNeedPay :array[1..2] of String=('Заборгованність, грн','Задолженность, грн');
const cn_RepDogSumDate :array[1..2] of String=('Сплачено по','Оплачено по');
const cn_RepDogSumTextOver :array[1..2] of String=('Сума переплати','Сумма переплаты');
const cn_RepDogSumText :array[1..2] of String=('Точна сплата','Точная оплата');
const cn_RepDogSumTextNEED :array[1..2] of String=('Сума заборгованності','Сумма задолженности');
const cn_RepDatePayNeed :array[1..2] of String=('Заборгованність на','Задолженность на');
const cn_RepSumAll :array[1..2] of String=('Усього:','Итого:');
{Отчет}
const cn_RepStudFT :array[1..2] of String=('Реєстр/Зведена відомость осіб, що навчаються','Реестр/сводная обучаемых');
const cn_RepStudPayFT :array[1..2] of String=('Реєстр/Зведена відомость боржників за навчання','Реестр/сводная должников за обучение');
const cn_RepStudSVFT :array[1..2] of String=('Зведена відомость осіб, що навчаються','Сводная форма колическва обучаемых');
const cn_RepStudPeriod :array[1..2] of String=('Період навчання','Период обучения');
const cn_RepStudPeriodBeg :array[1..2] of String=('з','с');
const cn_RepStudPeriodEnd :array[1..2] of String=('по','по');
const cn_RepStudFilter :array[1..2] of String=('Відбір параметрів навчання(F7)','Установка параметров обучения(F7)');
const cn_RepStudRun :array[1..2] of String=('Формувати(F10)','Формировать(F10)');
const cn_RepStudCancel :array[1..2] of String=('Відміна','Отмена');
const cn_RepStudQuit :array[1..2] of String=('Вихід','Выход');
const cn_RepStudMainDog :array[1..2] of String=('Основні договора','Основные договора');
const cn_RepStudDopDog :array[1..2] of String=('Додаткові договора','Дополнительные договора');
const cn_RepStudView :array[1..2] of String=('Перегляд(F12)','Просмотр(F12)');
const cn_RepStudDOC :array[1..2] of String=('Провести документ переплати','Провести документ переплаты');
const cn_RepStudDOC_Message :array[1..2] of String=('Документ переплати проведен успiшно','Документ переплаты проведен успешно');
const cn_RepStudDOC_Message_Err_del :array[1..2] of String=('Помилка при редагуваннi документа','Ошибка при редавктировании документа');
const cn_RepStudSelFiled :array[1..2] of String=('Групувати по','Группировать по');
const cn_RepRestr :array[1..2] of String=('Реєстр','Реестр');
const cn_RepRestr_ex :array[1..2] of String=('Реєстр(розгорнутий)','Реестр(развернутый)');
const cn_RepSV :array[1..2] of String=('Зведена','Сводная');
const cn_RepSVPAY :array[1..2] of String=('Зведена форма заборгованності','Сводная форма о задолженности');
const cn_RepSVPAYPERE :array[1..2] of String=('Зведена форма переплати','Сводная форма о переплаты');
const cn_RepSVPAY1 :array[1..2] of String=('за сплату договорів за навчання на','по оплате договоров за обучение на');
const cn_RepALL :array[1..2] of String=('Загальна кількість договірників:','Общее количество договорников:');
const cn_RepSVALL :array[1..2] of String=('Усього','Всего');
const cn_RepMainDog :array[1..2] of String=('студентів, що навчаються за основними договорами','обучаемых по основным договорам');
const cn_RepDopDog :array[1..2] of String=('студентів, що навчаються за додатковими договорами','обучаемых по дополнительным договорам');
const cn_RepPeiodDog :array[1..2] of String=('за період','в период');
const cn_RepPere :array[1..2] of String=('студентів, що переплатили за навчання','переплативших за обучения');
const cn_RepNeed :array[1..2] of String=('студентів, що заборгували за навчання','должников за обучение');
const cn_RepToch :array[1..2] of String=('студентів, що повністю сплатили за навчання','полностью оплативших');
const cn_RepOpldate :array[1..2] of String=('розрахунок суми до сплати на','расчет суммы к оплате на');
const cn_RepMainDogEX :array[1..2] of String=('за основними договорами','по основным договорам');
const cn_RepDopDogEX :array[1..2] of String=('за додатковими договорами','по дополнительным договорам');
const cn_RepFormZad :array[1..2] of String=('Заборгованність','Задолженность');
const cn_RepFormToch :array[1..2] of String=('Точна сплата','Точная оплата');
const cn_RepFormPere :array[1..2] of String=('Переплата','Переплата');
const cn_RepDogNotArhiv :array[1..2] of String=('Діючі договора','Действующие договора');
const cn_RepDogArhiv :array[1..2] of String=('Не діючі договора','Не действующие договора');
{Фильтр}
const cn_RepFilterFT :array[1..2] of String=('Параметри навчання','Параметры обучения');
const cn_RepFacult :array[1..2] of String=('Факультет','Факультет');
const cn_RepSpec :array[1..2] of String=('Спеціальність','Специальность');
const cn_RepNational :array[1..2] of String=('Громадянство','Гражданство');
const cn_RepFormStud :array[1..2] of String=('Форма навчання','Форма обучения');
const cn_RepKatStud :array[1..2] of String=('Категорія навчання','Категория обучения');
const cn_RepKurs :array[1..2] of String=('Курс','Курс');
const cn_RepGroup :array[1..2] of String=('Група','Группа');
const cn_Zamov :array[1..2] of String=('Споживча спилка', 'Потребительский союз');
const cn_Type_Stage : array[1..2] of string = ('Періодичність оплати','Периодичность оплаты');
const cn_RepFilterFac :array[1..2] of String=('Вибір факультетів','Выбор факультетов');
const cn_RepFilterSpec :array[1..2] of String=('Вибір спеціальностей','Выбор специальностей');
const cn_RepFilterNational :array[1..2] of String=('Вибір національностей','Выбор национальностей');
const cn_RepFilterFormStud :array[1..2] of String=('Вибір форм навчання','Выбор форм обучения');
const cn_RepFilterKatStud :array[1..2] of String=('Вибір категорій навчання','Выбор категорий обучения');
const cn_RepFilterCurs :array[1..2] of String=('Вибір курсів','Выбор курсов');
const cn_RepFilterGroup :array[1..2] of String=('Вибір груп','Выбор групп');
const cn_RepFilterFacL :array[1..2] of String=('Вибрано факультетів:','Выбрано факультетов:');
const cn_RepFilterSpecL :array[1..2] of String=('Вибрано спеціальностей:','Выбрано специальностей:');
const cn_RepFilterNationalL :array[1..2] of String=('Вибрано національностей:','Выбрано национальностей:');
const cn_RepFilterFormStudL :array[1..2] of String=('Вибрано форм навчання:','Выбрано форм обучения:');
const cn_RepFilterKatStudL :array[1..2] of String=('Вибрано категорій навчання:','Выбрано категорий обучения:');
const cn_RepFilterCursL :array[1..2] of String=('Вибрано курсів:','Выбрано курсов:');
const cn_RepFilterGroupL :array[1..2] of String=('Вибрано груп:','Выбрано групп:');
{Поступления}
const cn_RepFormFilter :array[1..2] of String=('Джерела фінансування','Источники финансирования');
const cn_RepFormFilterSmNotProv :array[1..2] of String=('Неприв'''+''''+'язані документи оплати','Непривязанные документы оплаты');
const cn_RepFormFilterSmNotProvGet :array[1..2] of String=('Відібрати неприв'''+''''+'язані документи оплати','Отобрать непривязанные документы оплаты');
const cn_RepDocProv :array[1..2] of String=('Реєстр/Зведена відомость надходжень за навчання','Реестр/сводная поступлений за обучение');
const cn_RepDocProvROS :array[1..2] of String=('Реєстр надходжень за навчання за основними договорами','Реестр поступлений за обучение по основным договорам');
const cn_RepDocProvRDop :array[1..2] of String=('Реєстр надходжень за навчання за додатковими договорами','Реестр поступлений за обучение по дополнительным договорам');
const cn_RepDocProvR :array[1..2] of String=('Зведена відомость надходжень за навчання','Сводная поступлений за обучение');
const cn_RepDocProvR1 :array[1..2] of String=('в розрізі джерел фінансування','в разрезе источников финансирования');
const cn_RepDocProvR2 :array[1..2] of String=('за період з','за период с');
const cn_RepDocProvR3 :array[1..2] of String=('до','по');
const cn_RepDocProvRT1 :array[1..2] of String=('Найменування бюджету','Наименование сметы');
const cn_RepDocProvRT2 :array[1..2] of String=('Розділ Стаття КЕКВ','Раздел Статья КЕКВ');
const cn_RepDocProvRT3 :array[1..2] of String=('Дебет','Дебет');
const cn_RepDocProvRT4 :array[1..2] of String=('Кредіт','Кредит');
const cn_RepDocProvRT5 :array[1..2] of String=('Усьго по бюджету','Всего по смете');
const cn_RepDocProvRT6 :array[1..2] of String=('Сума, грн','Сумма, грн');
const cn_RepDocProvSch :array[1..2] of String=('З разбивкою по рахунках','С разбивкой по счетам');
const cn_RepDocProvSm :array[1..2] of String=('З разбивкою по бюджетам','С разбивкой по сметам');
const cn_RepDocPrintProvSm :array[1..2] of String=('Зведена по іст. фін. ','Сводная по ист. фин.');
const cn_RepDocProvRT7 :array[1..2] of String=('Документ №','Документ №');
const cn_RepDocProvRT8 :array[1..2] of String=('Дата документу','Дата документа');
const cn_RepDocProvRT9 :array[1..2] of String=('Платник/ Отримувач','Плательщик/ Получатель');
const cn_RepDocProvRT10 :array[1..2] of String=('Призначення платежу','Назначение платежа');
const cn_RepDocProvRT11 :array[1..2] of String=('Сума надходжень','сумма поступлений');
const cn_RepDocProvRT12 :array[1..2] of String=('від','от');
const cn_RepDocProvRT13 :array[1..2] of String=('Іст. фін.','Ист. фин.');
const cn_RepSchDB :array[1..2] of String=('Дебетові рахунки','Дебетовые счета');
const cn_RepSchKD :array[1..2] of String=('Кредитові рахунки','Кредитовые счета');
const cn_RepSmeta :array[1..2] of String=('См\Розд\Ст\КЕКВ','См\Разд\Ст\КЕКВ');
const cn_RepSmetaName :array[1..2] of String=('Назва бюджету','Название сметы');
const cn_RepDocAllSum :array[1..2] of String=('Надрукована сума надходжень','Распечатанная сумма поступлений');
const cn_RepDocAllDoc :array[1..2] of String=('Загальна кількість надходжень','Общее число поступлений');
{Количество для ДонГУЭТ}
const cn_RepDONGUETOtdel :array[1..2] of String=('Відділення','Отделение');
const cn_RepDONGUETCNT :array[1..2] of String=('Кіл-сть','Кол-во');
const cn_RepDONGUETCNTOtdel :array[1..2] of String=('Усього по відділу','Итого по отделению');
const cn_RepDONGUETAll :array[1..2] of String=('Усього по звіту','Итого по списку');
{Аналитеческие формы}
const cn_RepRAnalyz :array[1..2] of String=('Аналітичний реєстр сплати за навчання','Аналитический реестр по оплате за обучение');
const cn_RepSVAnalyz :array[1..2] of String=('Аналітичий звіт сплати за навчання','Аналитическая сводная по оплате за обучение');
const cn_RepRAnalyzIN :array[1..2] of String=('Вхідне сальдо, грн','Входящее сальдо, грн');
const cn_RepRAnalyzNEED :array[1..2] of String=('Планова сума, грн.','Планируемая сумма, грн');
const cn_RepRAnalyzPAY :array[1..2] of String=('Сплачено, грн','Поступившая сумма, грн');
const cn_RepRAnalyzOUT :array[1..2] of String=('Вихідне сальдо, грн','Исходящее сальдо, грн');
const cn_RepRAnalyzAllSaldo :array[1..2] of String=('Усього вихідне сальдо','Всего исходящее сальдо, грн');
const cn_RepRAnalyzCNT :array[1..2] of String=('Загальна кількість','Общее число обучаемых');
const cn_RepRAnalyzSUMPrint :array[1..2] of String=('Надрукована сума','Распечатанная сумма');
const cn_RepRAnalyzAll :array[1..2] of String=('Загальний список','Общий список');
{анализ в разрезе источников финансирования}
const cn_RepRAnalyzSmetaSV :array[1..2] of String=('Аналіз сплати за навчання за джерелами фінансування','Анализ оплаты обучения в разрезе источников финансирования');
const cn_RepSVAnalyzSmName :array[1..2] of String=('Джерела фінансування','Источник финансирования');
const cn_RepSVAnalyzSmOstNach :array[1..2] of String=('Залишок на початок періода','Остаток на начало периода');
const cn_RepSVAnalyzSmOstNow :array[1..2] of String=('Поточний період','Текущий период');
const cn_RepSVAnalyzSmOstBeg :array[1..2] of String=('Залишок на кінец періода','Остаток на конец пеиода');
const cn_RepSVAnalyzSmDolg :array[1..2] of String=('Борг','Долг');
const cn_RepSVAnalyzSmPere :array[1..2] of String=('Переплата','Переплата');
const cn_RepSVAnalyzSmIn :array[1..2] of String=('Вхідне сальдо','Входящее сальдо');
const cn_RepSVAnalyzSmOut :array[1..2] of String=('Віхідне сальдо','Исходящее сальдо');
const cn_RepSVAnalyzSmNach :array[1..2] of String=('Нараховано','Начислено');
const cn_RepSVAnalyzSmOpl :array[1..2] of String=('Сплачено','Оплачено');
const cn_RepSVAnalyzSmZad :array[1..2] of String=('Заборгованність','Задолженность');
{Накопительная ведоомсть}
const cn_RepSVDPDocShort :array[1..2] of String=('Накопичувальна відомість','Накопительная ведомость');
const cn_RepSVDPDoc :array[1..2] of String=('Накопичувальна відомість сплати за навчання','Накопительная ведомость оплаты за обучение');
const cn_RepSVDPDocNumber :array[1..2] of String=('№№','№№');
const cn_RepSVDPDocDate :array[1..2] of String=('Дата','Дата');
const cn_RepSVDPDocCNT :array[1..2] of String=('Кіл-сть','Кол-во');
const cn_RepSVDPDocSumma :array[1..2] of String=('Сума, грн','Сумма, грн');
const cn_RepSVDPDocAll :array[1..2] of String=('Усьго','Итого');
{Форма процентного выполнения договоров}
const cn_RepSVPercent :array[1..2] of String=('Форма відсоткового виконання договорів за навчання','Форма процентного выполнения договоров');
const cn_RepSVPercentPay :array[1..2] of String=('Сплата навчання','Оплата обучения');
const cn_RepSVPercentCNT :array[1..2] of String=('Загальна кіл-сть договорів','Общее кол-во договоров');
const cn_RepSVPercentCNTShort :array[1..2] of String=('Кіл-сть','Кол-во');
const cn_RepSVPercentPeriod :array[1..2] of String=('Період','Период');
{недопоступившие суммы}
const cn_RepUnSumName :array[1..2] of String=('Реєстр/Зведена відомость сумм, що не надійшли','Реестр/Сводная недопоступившых сумм');
const cn_RepUnSumSV :array[1..2] of String=('Зведена форма сум, що не надійшли за навчання','Сводная форма недопоступивших сумм за обучение');
const cn_RepUnSumR :array[1..2] of String=('Реєстр сум, що не надійшли за навчання','Реестр недопоступивших сумм за обучение');
const cn_RepUnSumNew :array[1..2] of String=('Тільки зараховані','Вновь поступившые');
const cn_RepUnSumCNT :array[1..2] of String=('Кіл-сть','Кол-во');
const cn_RepUnSumSum :array[1..2] of String=('Сума, грн','Сумма, грн');
const cn_RepUnSumSumALL :array[1..2] of String=('Загальна сума','Общая сумма');
const cn_RepUnRSumCNT :array[1..2] of String=('Загальна кількість, що навчається','Общее число обучаемых');
const cn_RepUnRSumSum :array[1..2] of String=('Сума, що не надійшла, грн','Недопоступившая сумма, грн');
const cn_RepUnRSumSumALL :array[1..2] of String=('Надрукована сума','Распечатанная сумма');
const cn_RepUnRSumALL :array[1..2] of String=('Усього не надійшло','Всего недополучено');
const cn_RepSVPeriod :array[1..2] of String=('Період','Период');
{Сводная отчисленных}
const cn_RepSVDiss :array[1..2] of String=('Зведена відсоткового відношення відрахованих','Сводная процентного отношения отчисленных');
const cn_RepSVDISSDISS :array[1..2] of String=('Відрах.','Отчисл.');
const cn_RepSVDISSUNDISS :array[1..2] of String=('Навч.','Обуч.');
const cn_RepSVDISSPERSENT :array[1..2] of String=('Від., %','Отн., %');
const cn_RepSVDissChPersent :array[1..2] of String=('Відсоткова Зведена','Процентная сводная');
const cn_RepSVDissChCNT :array[1..2] of String=('Перенесені, до недіючих','Перенесенные в недействующие');
const cn_RepSVDissType :array[1..2] of String=('Найменування підстави переносу до архіву','Наименование причины переноса в архив');
const cn_RepSVDissArchName :array[1..2] of String=('Кількість перенесених до архіву','Количество перенесенных в архив');
implementation
end.
|
{-------------------------------------------------------------------------------
Copyright 2012 Ethea S.r.l.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-------------------------------------------------------------------------------}
unit Kitto.Ext.AccordionPanel;
{$I Kitto.Defines.inc}
interface
uses
Ext,
Kitto.Ext.Base, Kitto.Metadata.Views;
type
/// <summary>Displays subviews/controllers in an accordion.</summary>
/// <remarks>All contained views and controllers must have
/// ShowHeader=True.</remarks>
TKExtAccordionPanelController = class(TKExtPanelControllerBase)
private
procedure DisplaySubViewsAndControllers;
protected
procedure DoDisplay; override;
end;
implementation
uses
SysUtils,
ExtPascal, ExtLayout,
EF.Tree, EF.Localization,
Kitto.Types, Kitto.AccessControl, Kitto.Ext.Controller, Kitto.Ext.Session;
{ TKExtAccordionPanelController }
procedure TKExtAccordionPanelController.DoDisplay;
begin
inherited;
Layout := lyAccordion;
{ TODO : make these customizable }
MinSize := 20;
MaxSize := 400;
LayoutConfig := JSObject('animate:true');
DisplaySubViewsAndControllers;
end;
procedure TKExtAccordionPanelController.DisplaySubViewsAndControllers;
var
LController: IKExtController;
LViews: TEFNode;
I: Integer;
LView: TKView;
begin
LViews := Config.FindNode('SubViews');
if Assigned(LViews) then
begin
for I := 0 to LViews.ChildCount - 1 do
begin
if SameText(LViews.Children[I].Name, 'View') then
begin
LView := Session.Config.Views.ViewByNode(LViews.Children[I]);
if LView.IsAccessGranted(ACM_VIEW) then
begin
LController := TKExtControllerFactory.Instance.CreateController(Self, LView, Self);
LController.Display;
end;
end
else if SameText(LViews.Children[I].Name, 'Controller') then
begin
LController := TKExtControllerFactory.Instance.CreateController(
Self, View, Self, LViews.Children[I]);
InitSubController(LController);
LController.Display;
end
else
raise EKError.Create(_('AccordionPanel''s SubViews node may only contain View or Controller subnodes.'));
end;
if Items.Count > 0 then
On('afterrender', JSFunction(JSName + '.getLayout().setActiveItem(0);'));
end;
end;
initialization
TKExtControllerRegistry.Instance.RegisterClass('AccordionPanel', TKExtAccordionPanelController);
finalization
TKExtControllerRegistry.Instance.UnregisterClass('AccordionPanel');
end.
|
unit TestForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IdServerIOHandler, IdSSL, IdSSLOpenSSL,
IdBaseComponent, IdComponent, IdCustomTCPServer, IdTCPServer, IdContext, Vcl.StdCtrls,
IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdTCPConnection, IdTCPClient,
IdAntiFreezeBase, Vcl.IdAntiFreeze;
type
TForm2 = class(TForm)
Button1: TButton;
IdTCPServer1: TIdTCPServer;
IdServerIOHandlerSSLOpenSSL1: TIdServerIOHandlerSSLOpenSSL;
memResults: TMemo;
Button2: TButton;
IdTCPClient1: TIdTCPClient;
IdSSLIOHandlerSocketOpenSSL1: TIdSSLIOHandlerSocketOpenSSL;
Button3: TButton;
edtEcho: TEdit;
Button4: TButton;
Button5: TButton;
Label1: TLabel;
IdAntiFreeze1: TIdAntiFreeze;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure IdSSLIOHandlerSocketOpenSSL1Status(ASender: TObject;
const AStatus: TIdStatus; const AStatusText: string);
private
{ Private declarations }
procedure ServerExecute(AContext: TIdContext);
procedure GetPassword(var Password: string);
procedure ServerConnect(AContext: TIdContext);
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
const
SERVER_PORT = 6050;
{$R *.dfm}
procedure TForm2.Button1Click(Sender: TObject);
begin
//In the real world:
// FileNames should not be hardcoded, let the be configured external.
// Certs expire and change be prepared to handle it.
IdServerIOHandlerSSLOpenSSL1.SSLOptions.CertFile := 'c:\dev\keys\localhost.cert.pem';
IdServerIOHandlerSSLOpenSSL1.SSLOptions.KeyFile := 'c:\dev\keys\localhost.key.pem';
IdServerIOHandlerSSLOpenSSL1.SSLOptions.RootCertFile := 'C:\dev\keys\ca.cert.pem';
IdServerIOHandlerSSLOpenSSL1.SSLOptions.Mode := sslmServer;
IdServerIOHandlerSSLOpenSSL1.SSLOptions.VerifyMode := [];
IdServerIOHandlerSSLOpenSSL1.SSLOptions.VerifyDepth := 0;
IdServerIOHandlerSSLOpenSSL1.SSLOptions.SSLVersions := [sslvTLSv1_2]; // Avoid using SSL
IdServerIOHandlerSSLOpenSSL1.OnGetPassword := GetPassword;
IdTCPServer1.DefaultPort := SERVER_PORT;
IdTCPServer1.IOHandler := IdServerIOHandlerSSLOpenSSL1;
IdTCPServer1.OnConnect := ServerConnect;
IdTCPServer1.OnExecute := ServerExecute;
IdTCPServer1.Active := True;
end;
procedure TForm2.Button2Click(Sender: TObject);
begin
IdTCPClient1.IOHandler.WriteLn(edtEcho.text);
memResults.Lines.add(IdTCPClient1.IOHandler.Readln());
end;
procedure TForm2.Button3Click(Sender: TObject);
begin
// Ok for self singned but you will want to verify if you are using signed certs
IdSSLIOHandlerSocketOpenSSL1.sslOptions.VerifyMode := [];
IdSSLIOHandlerSocketOpenSSL1.sslOptions.VerifyDepth := 0;
IdSSLIOHandlerSocketOpenSSL1.sslOptions.SSLVersions := [sslvTLSv1_2];
IdSSLIOHandlerSocketOpenSSL1.sslOptions.Mode := sslmUnassigned;
IdTCPClient1.Host := '127.0.0.1';
IdTCPClient1.Port := SERVER_PORT;
IdTCPClient1.ReadTimeout := 50;
IdTCPClient1.IOHandler := IdSSLIOHandlerSocketOpenSSL1;
IdTCPClient1.Connect;
memResults.Lines.add(IdTCPClient1.IOHandler.ReadLn);
end;
procedure TForm2.Button4Click(Sender: TObject);
begin
IdTCPServer1.Active := false;
end;
procedure TForm2.Button5Click(Sender: TObject);
begin
IdTCPClient1.SendCmd('QUIT');
IdTCPClient1.Disconnect;
end;
procedure TForm2.GetPassword(var Password: string);
begin
//In the real world:
// This should never be hardcoded as it could change when the cert changes.
// Don't use Dictonary Words or your key can be brute force attacked.
Password := 'test';
end;
procedure TForm2.IdSSLIOHandlerSocketOpenSSL1Status(ASender: TObject;
const AStatus: TIdStatus; const AStatusText: string);
begin
memResults.Lines.Add(AStatusText);
end;
procedure TForm2.ServerConnect(AContext: TIdContext);
begin
//These two lines are required to get SSL to work.
if (AContext.Connection.IOHandler is TIdSSLIOHandlerSocketBase) then
TIdSSLIOHandlerSocketBase(AContext.Connection.IOHandler).PassThrough := false;
end;
procedure TForm2.ServerExecute(AContext: TIdContext);
var
lCmdLine: string;
connected : Boolean;
begin
AContext.Connection.IOHandler.WriteLn('Welcome to the Echo Server');
Connected := true;
while Connected do
begin
lCmdLine := AContext.Connection.IOHandler.ReadLn;
AContext.Connection.IOHandler.Writeln('>' + lCmdLine);
if SameText(lCmdLine, 'QUIT') then
begin
AContext.Connection.IOHandler.Writeln('Disconnecting');
AContext.Connection.Disconnect;
Connected := false;
end;
end;
end;
end.
|
unit Geo.Pos;
interface
uses
SysUtils, Math;
const
CEvDegLengthKm = 111.225; //! среднее значение длины градуса ((меридиан + экватор) / 2), км
CEvDegLength = 111225.; //! среднее значение длины градуса ((меридиан + экватор) / 2), м
CEvEarthRadiusKm = 6371.; //! средний радиус Земли, км
CEvEarthRadius = 6371000.; //! средний радиус Земли, м
CTolerance = 1E-5; //! максимально допустимая относительная погрешность при сравнении
CMpsToKmh = 3.6;
CKmhToMps = 1 / CMpsToKmh;
type
TCartesianPos = packed record
X, Y: Double;
constructor Create(const AX, AY: Double);
end;
PGeoPos = ^TGeoPos;
TGeoPos = packed record
Latitude: Double;
Longitude: Double;
class operator Equal(a, b: TGeoPos) : Boolean;
function IsValid: Boolean;
function IsSame(ALatitude: Double; ALongitude: Double): Boolean;
function ToCartesianPos(XOffset: Double): TCartesianPos;
function ToGeoHash(aPrec: Integer = 12): string;
function ToHash: Int64;
function ToString: string;
constructor Create(
const ALatitude: Double;
const ALongitude: Double
); overload;
constructor Create(
const ACartesianPos: TCartesianPos;
const ALongitudeOffset: Double = 0); overload;
end;
TGeoPosArray = TArray<TGeoPos>;
PGeoPosFull = ^TGeoPosFull;
TGeoPosFull = packed record
Pos: TGeoPos;
Altitude: Double;
function IsValid: Boolean;
constructor Create(
ALatitude: Double;
ALongitude: Double;
AAltitude: Double = 0
);
end;
TGeoPosFullArray = TArray<TGeoPosFull>;
TGeoTrackPoint = packed record
Pos: TGeoPosFull;
DateTime: TDateTime;
SatellitesCount: Integer;
ProviderID: Smallint;
class operator Equal(a, b: TGeoTrackPoint): Boolean;
constructor Create(
const ALatitude: Double;
const ALongitude: Double;
const ADateTime: TDateTime;
const ASatCount: Integer;
const AAltitude: Double = 0
);
end;
PGeoSquare = ^TGeoSquare;
TGeoSquare = record
NorthWest: TGeoPos;
SouthEast: TGeoPos;
end;
TGeoSquareArray = TArray<TGeoSquare>;
TGeoCircle = record
Pos: TGeoPos;
Radius: Double;
// Возвращает точку окружности в данном направлении от центра
function CirclePoint(const ADirection: Double): TGeoPos;
end;
implementation
uses
Geo.Hash;
{ TCartesianPos }
constructor TCartesianPos.Create(const AX, AY: Double);
begin
X := AX;
Y := AY;
end;
{ TGeoPos }
constructor TGeoPos.Create(const ALatitude, ALongitude: Double);
begin
Latitude := ALatitude;
Longitude := ALongitude;
end;
constructor TGeoPos.Create(const ACartesianPos: TCartesianPos; const ALongitudeOffset: Double);
begin
Latitude := ACartesianPos.Y / CEvDegLength;
if Abs(Latitude) = 90 then
Longitude := 0
else if Abs(Latitude) < 90 then
begin
Longitude := ALongitudeOffset + ACartesianPos.X / CEvDegLength / Cos(DegToRad(Latitude));
if Abs(Longitude) > 180 then
Longitude := Longitude - 360 * (Round(Longitude + Sign(Longitude) * 180) div 360);
end
else
begin
Latitude := 0;
Longitude := 0;
end;
end;
function TGeoPos.IsValid: Boolean;
begin
Result := not ((Latitude < -90) or (Latitude > 90) or (Longitude < -180) or (Longitude > 180));
end;
class operator TGeoPos.Equal(a, b: TGeoPos) : Boolean;
begin
Result :=
SameValue(a.Latitude, b.Latitude, CTolerance) and
SameValue(a.Longitude, b.Longitude, CTolerance);
end;
function TGeoPos.IsSame(ALatitude: Double; ALongitude: Double): Boolean;
begin
Result := (ALatitude = Latitude) and (ALongitude = Longitude);
end;
function TGeoPos.ToCartesianPos(XOffset: Double): TCartesianPos;
begin
Result.X := (Longitude - XOffset) * cEvDegLength * Cos(DegToRad(Latitude));
Result.Y := Latitude * cEvDegLength;
end;
function TGeoPos.ToGeoHash(aPrec: Integer = 12): string;
begin
Result := TGeoHash.EncodePointString(Latitude, Longitude, aPrec);
end;
function TGeoPos.ToHash: Int64;
begin
Result := TGeoHash.EncodePointBin(Latitude, Longitude);
end;
function TGeoPos.ToString: string;
var
fs: TFormatSettings;
begin
fs := TFormatSettings.Create;
fs.DecimalSeparator := '.';
Result := FloatToStr(Latitude, fs) + ' ' + FloatToStr(Longitude, fs);
end;
{ TGeoPosFull }
constructor TGeoPosFull.Create(ALatitude, ALongitude: Double; AAltitude: Double = 0);
begin
Pos.Latitude := ALatitude;
Pos.Longitude := ALongitude;
Altitude := AAltitude;
end;
function TGeoPosFull.IsValid: Boolean;
begin
Result := Pos.IsValid;
end;
{ TGeoTrackPoint }
constructor TGeoTrackPoint.Create(
const ALatitude: Double;
const ALongitude: Double;
const ADateTime: TDateTime;
const ASatCount: Integer;
const AAltitude: Double = 0
);
begin
Pos.Create(ALatitude, ALongitude, AAltitude);
DateTime := ADateTime;
SatellitesCount := ASatCount;
end;
class operator TGeoTrackPoint.Equal(a, b: TGeoTrackPoint): Boolean;
begin
Result := (a.DateTime = b.DateTime) and (a.SatellitesCount = b.SatellitesCount) and (a.ProviderID = b.ProviderID) and (a.Pos.Pos = b.Pos.Pos);
end;
{ TGeoCircle }
function TGeoCircle.CirclePoint(const ADirection: Double): TGeoPos;
begin
if (Pos.Latitude + Radius / CEvDegLength >= 90)
or (Pos.Latitude - Radius / CEvDegLength <= -90) then
Exit(Pos);
Result.Latitude := Pos.Latitude + Radius / CEvDegLength + Cos(DegToRad(ADirection));
Result.Longitude := Pos.Longitude + Radius / CEvDegLength + Sin(DegToRad(ADirection));
end;
end.
|
{ *********************************************************************** }
{ }
{ Author: Yanniel Alvarez Alfonso }
{ Description: Synchronization Classes }
{ Copyright (c) ????-2012 Pinogy Corporation }
{ }
{ *********************************************************************** }
unit uSynchronizationClasses;
interface
uses
ADODB, IniFiles, DBUtils;
type
TSynchronizationINIParams = class
private
FSynchronizationINIFile: TIniFile;
FExportPath,
FConnectionStr: string; //ConnectionString,
//RsyncParams //TODO
public
constructor Create(aFileName: string);
destructor Destroy; override;
property ExportPath: string read FExportPath write FExportPath;
property ConnectionStr: string read FConnectionStr write FConnectionStr;
end;
//Serializes a table or view, in general a DataSet
TDataSetSerializer = class
private
FConnection: TADOConnection;
public
constructor Create(aConnection: TADOConnection); //Inject the connection
function SaveAsXML(aExportPath, aTable: string): Boolean;
function SaveAsTSV(aExportPath, aTable: string): Boolean;
property Connection: TADOConnection read FConnection
write FConnection;
end;
implementation
uses
uEncryptFunctions, uReplicationClasses,
DB;
{ TDataSetSerializer }
//Inject the connection
constructor TDataSetSerializer.Create(aConnection: TADOConnection);
begin
inherited Create;
FConnection:= aConnection;
end;
function TDataSetSerializer.SaveAsXML(aExportPath,
aTable: string): Boolean;
var
TableToXML: TTableToXML;
begin
Result := True;
if (aTable = '') then Exit;
TableToXML:= TTableToXML.Create(nil);
try
try
TableToXML.Connection:= FConnection;
TableToXML.ReplicateSince := -1;
TableToXML.SelectWhereClause := '';
TableToXML.TableName := aTable;
except
Result:= False;
end;
Result := TableToXML.SaveToXML(aExportPath + aTable) = '';
finally
TableToXML.UnloadData;
TableToXML.Free;
end;
end;
function TDataSetSerializer.SaveAsTSV(aExportPath,
aTable: string): Boolean;
var
ADOQuery: TADOQuery;
begin
ADOQuery:= TADOQuery.Create(nil);
ADOQuery.CommandTimeout:= 30;
try
ADOQuery.Connection:= FConnection;
SelectSQL(ADOQuery, 'select * from ' + aTable + ';');
Result:= DataSet2TSV(ADOQuery, aExportPath + aTable + '.tsv');
finally
ADOQuery.Free;
end;
end;
{ TSynchronizationINIParams }
constructor TSynchronizationINIParams.Create(aFileName: string);
begin
inherited Create;
FSynchronizationINIFile:= TIniFile.Create(aFileName);
with FSynchronizationINIFile do
begin
FExportPath := FSynchronizationINIFile.ReadString('TablesToXML', 'ExportPath', '');
FConnectionStr := FSynchronizationINIFile.ReadString('DBConnection', 'ConnectionString', '');
//Decoding the ConnectionString
FConnectionStr:= DecodeServerInfo(FConnectionStr, 'Server', CIPHER_TEXT_STEALING, FMT_UU);
end;
end;
destructor TSynchronizationINIParams.Destroy;
begin
with FSynchronizationINIFile do
begin
FSynchronizationINIFile.WriteString('TablesToXML', 'ExportPath', FExportPath);
//Encoding the ConnectionString
FConnectionStr:= EncodeServerInfo(FConnectionStr, 'Server', CIPHER_TEXT_STEALING, FMT_UU);
FSynchronizationINIFile.WriteString('DBConnection', 'ConnectionString', FConnectionStr);
Free;
end;
inherited;
end;
end.
|
{
----------------------------------------------------------------
File - USB_DIAG_LIB.PAS
Utility functions for printing device information,
detecting USB devices
Copyright (c) 2003 Jungo Ltd. http://www.jungo.com
----------------------------------------------------------------
}
unit USB_diag_lib;
interface
uses
Windows,
SysUtils,
WinDrvr,
print_struct,
status_strings;
type READ_PIPE_FUNC = function(hDevice : HANDLE; pBuffer : POINTER; dwSize : DWORD) : DWORD; stdcall;
type PROCESS_DATA_FUNC = procedure(pBuffer : POINTER; dwSize : DWORD; pContext : POINTER) stdcall;
type STOP_PIPE_FUNC = procedure(hDevice : HANDLE) stdcall;
const
MAX_BUFFER_SIZE = 4096;
BYTES_IN_LINE = 16;
HEX_CHARS_PER_BYTE = 3; {2 digits and one space}
HEX_STOP_POS = BYTES_IN_LINE*HEX_CHARS_PER_BYTE;
type
USB_LISTEN_PIPE = record
read_pipe_func : READ_PIPE_FUNC;
stop_pipe_func : STOP_PIPE_FUNC;
hDevice : HANDLE;
dwPacketSize : DWORD;
process_data_func : PROCESS_DATA_FUNC; { if NULL call PrintHexBuffer }
pContext : PVOID;
fStopped : BOOLEAN;
hThread : HANDLE;
end;
PUSB_LISTEN_PIPE = ^USB_LISTEN_PIPE;
function USB_Get_WD_handle(phWD : PHANDLE) : BOOLEAN;
procedure USB_Print_device_info(dwVendorId : DWORD; dwProductId : DWORD);
procedure USB_Print_all_devices_info;
procedure USB_Print_device_Configurations(uniqueId : DWORD; configIndex : DWORD);
procedure PrintHexBuffer(pBuffer : POINTER; dwBytes : DWORD);
function GetHexBuffer(pBuffer : POINTER; dwBytes : DWORD) : DWORD;
function GetHexChar (line : string) : INTEGER;
procedure CloseListening(pListenPipe : PUSB_LISTEN_PIPE);
procedure ListenToPipe(pListenPipe : PUSB_LISTEN_PIPE);
function PipeListenHandler(pParam : POINTER) : DWORD stdcall;
function IsHexDigit(c : string) : BOOLEAN;
implementation
function pipeType2Str(pipeType : DWORD) : STRING;
begin
case pipeType of
UsbdPipeTypeControl:
pipeType2Str := 'Control';
UsbdPipeTypeIsochronous:
pipeType2Str := 'Isochronous';
UsbdPipeTypeBulk:
pipeType2Str := 'Bulk';
UsbdPipeTypeInterrupt:
pipeType2Str := 'Interrupt';
else
pipeType2Str := 'Unknown';
end;
end;
function USB_Get_WD_handle(phWD : PHANDLE) : BOOLEAN;
var
ver : SWD_VERSION;
begin
phWD^ := INVALID_HANDLE_VALUE;
phWD^ := WD_Open();
{ Check whether handle is valid and version OK }
if phWD^ = INVALID_HANDLE_VALUE
then
begin
Writeln('Cannot open WinDriver device');
USB_Get_WD_handle := False;
Exit;
end;
FillChar(ver, SizeOf(ver), 0);
WD_Version(phWD^,ver);
if ver.dwVer<WD_VER
then
begin
Writeln('Error - incorrect WinDriver version');
WD_Close (phWD^);
phWD^ := INVALID_HANDLE_VALUE;
USB_Get_WD_handle := False;
end
else
USB_Get_WD_handle := True;
end;
procedure USB_Print_device_info(dwVendorId : DWORD; dwProductId : DWORD);
var
i : DWORD;
{strTransType, strStatus : STRING;}
hWD : HANDLE;
usbScan : WD_USB_SCAN_DEVICES;
{openCloseInfo : WD_USB_OPEN_CLOSE;}
genInfo : PWD_USB_DEVICE_GENERAL_INFO;
tmp : string;
dwStatus : DWORD;
begin
if not USB_Get_WD_handle (@hWD)
then
Exit;
FillChar(usbScan, SizeOf(usbScan), 0);
usbScan.searchId.dwVendorId := dwVendorId;
usbScan.searchId.dwProductId := dwProductId;
dwStatus := WD_UsbScanDevice(hWD,@usbScan);
if dwStatus>0
then
begin
Writeln('WD_UsbScanDevice failed with status $', IntToHex(dwStatus, 8), Stat2Str(dwStatus));
WD_Close(hWD);
Exit;
end;
for i:=1 to usbScan.dwDevices do
begin
genInfo := @usbScan.deviceGeneralInfo[i];
Writeln('USB device - Vendor ID: ', IntToHex(usbScan.deviceGeneralInfo[i-1].deviceId.dwVendorId, 4),
', Product ID: ', IntToHex(usbScan.deviceGeneralInfo[i-1].deviceId.dwProductId, 4),
', unique ID: ', usbScan.uniqueId[i-1]);
Writeln(' phisical address: 0x', IntToHex(usbScan.deviceGeneralInfo[i-1].deviceAddress, 4),
' Hub No. ',usbScan.deviceGeneralInfo[i-1].dwHubNum,
' Port No.',usbScan.deviceGeneralInfo[i-1].dwPortNum);
if usbScan.deviceGeneralInfo[i-1].fFullSpeed <> 0 then
Writeln(' Full speed, device has ',usbScan.deviceGeneralInfo[i-1].dwConfigurationsNum,
'configuration(s)')
else
Writeln(' Low speed, device has ',usbScan.deviceGeneralInfo[i-1].dwConfigurationsNum,
' configuration(s)');
if genInfo^.fHub <> 0 then
if genInfo^.hubInfo.fBusPowered = 1 then
Writeln(' Device is Hub, Hub has ', genInfo^.hubInfo.dwPorts,
' ports, Bus powered, ',genInfo^.hubInfo.dwHubControlCurrent,
' mA')
else
Writeln(' Device is Hub, Hub has ', genInfo^.hubInfo.dwPorts,
' ports, Self powered, ',genInfo^.hubInfo.dwHubControlCurrent,
' mA');
Writeln('');
if i < usbScan.dwDevices then
begin
Writeln('Press Enter to continue to the next device');
Readln(tmp);
end;
end;
WD_Close (hWD);
end;
procedure USB_Print_all_devices_info;
begin
USB_Print_device_info(0, 0);
end;
procedure USB_Print_device_Configurations(uniqueId : DWORD; configIndex : DWORD);
var
config : WD_USB_CONFIGURATION;
i, j : INTEGER;
hWD : HANDLE;
pInterface : PWD_USB_INTERFACE_DESC;
pEndPoint : PWD_USB_ENDPOINT_DESC;
tmp : string;
dwStatus : DWORD;
begin
if not USB_Get_WD_handle (@hWD)
then
Exit;
FillChar(config, SizeOf(config), 0);
config.uniqueId := uniqueId;
config.dwConfigurationIndex := configIndex;
dwStatus := WD_UsbGetConfiguration(hWD, @config);
if dwStatus>0
then
begin
Writeln('WD_UsbGetConfiguration failed with status $', IntToHex(dwStatus, 8), Stat2Str(dwStatus));
WD_Close(hWD);
Exit;
end;
Writeln('Configuration No. ', config.configuration.dwValue,
' has ', config.configuration.dwNumInterfaces,
' interface(s)');
Writeln('configuration attributes: 0x', IntToHex(config.configuration.dwAttributes, 2),
' max power: ', config.configuration.MaxPower*2, 'mA');
Writeln('');
for i:=0 to config.dwInterfaceAlternatives-1 do
begin
pInterface := @config.UsbInterface[i].InterfaceDesc;
Writeln('interface No. ', pInterface^.dwNumber,
', alternate setting: ', pInterface^.dwAlternateSetting,
', index: ', pInterface^.dwIndex);
Writeln('end-points: ', pInterface^.dwNumEndpoints,
', class: 0x', IntToHex(pInterface^.dwClass, 2),
', sub-class: 0x', IntToHex(pInterface^.dwSubClass, 2),
', protocol: 0x', IntToHex(pInterface^.dwProtocol, 2));
for j:=0 to pInterface^.dwNumEndpoints-1 do
begin
pEndPoint := @config.UsbInterface[i].Endpoints[j];
Writeln(' end-point address: 0x',IntToHex(pEndPoint^.dwEndpointAddress, 2),
', attributes: 0x', IntToHex(pEndPoint^.dwAttributes, 2),
', max packet size: ', pEndPoint^.dwMaxPacketSize,
', Interval: ',pEndPoint^.dwInterval);
end;
Writeln('');
if i < config.dwInterfaceAlternatives-1 then
begin
Writeln('Press Enter to continue to the next configuration');
Readln(tmp);
end;
end;
WD_Close (hWD);
end;
procedure PrintHexBuffer(pBuffer : POINTER; dwBytes : DWORD);
var
pData : PBYTE;
pHex : array [0..HEX_STOP_POS-1] of CHAR; {48}
pAscii : array [0..BYTES_IN_LINE-1] of CHAR; {16}
offset, line_offset, i : DWORD;
intVal : INTEGER;
byteVal : BYTE;
hexStr : string;
begin
if dwBytes = 0 then
Exit;
pData := pBuffer;
for offset:=0 to dwBytes-1 do
begin
line_offset := offset mod BYTES_IN_LINE;
if (offset <> 0) and (line_offset = 0) then
begin
Write(pHex, '| ', pAscii);
Writeln(' ');
end;
byteVal := PBYTE(DWORD(pData) + offset)^;
hexStr := IntToHex(byteVal, 2);
pHex[line_offset*HEX_CHARS_PER_BYTE] := hexStr[1];
pHex[line_offset*HEX_CHARS_PER_BYTE+1] := hexStr[2];
pHex[line_offset*HEX_CHARS_PER_BYTE+2] := ' ';
if byteVal >= $20 then
pAscii[line_offset] := CHAR(byteVal)
else
pAscii[line_offset] := '.';
end;
{ print the last line. fill with blanks if needed }
if (offset mod BYTES_IN_LINE) <> 0 then
begin
for i:=(offset mod BYTES_IN_LINE)*HEX_CHARS_PER_BYTE to BYTES_IN_LINE*HEX_CHARS_PER_BYTE-1 do
pHex[i] := ' ';
for i:=(offset mod BYTES_IN_LINE) to BYTES_IN_LINE-1 do
pAscii[i] := ' ';
end;
Write(pHex, '| ', pAscii);
Writeln(' ');
end;
procedure CloseListening(pListenPipe : PUSB_LISTEN_PIPE);
var
transfer : WD_USB_TRANSFER;
begin
FillChar(transfer, SizeOf(transfer), 0);
if pListenPipe^.hThread = 0 then
Exit;
Writeln('Stop listening to pipe');
pListenPipe^.fStopped := True;
pListenPipe^.stop_pipe_func(pListenPipe^.hDevice);
WaitForSingleObject(pListenPipe^.hThread, INFINITE);
CloseHandle(pListenPipe^.hThread);
pListenPipe^.hThread := 0;
end;
procedure ListenToPipe(pListenPipe : PUSB_LISTEN_PIPE);
var
threadId : DWORD;
begin
{ start the running thread }
Writeln('Start listening to pipe');
pListenPipe^.hThread := CreateThread (nil, $1000, @PipeListenHandler, POINTER(pListenPipe), 0, threadId);
end;
function PipeListenHandler(pParam : POINTER) : DWORD; stdcall;
var
pListenPipe : PUSB_LISTEN_PIPE;
pbuf : POINTER;
dwBytesTransfered : DWORD;
begin
pListenPipe := PUSB_LISTEN_PIPE(pParam);
GetMem(POINTER(pbuf), pListenPipe^.dwPacketSize);
while True do
begin
dwBytesTransfered := pListenPipe^.read_pipe_func(pListenPipe^.hDevice, pbuf, pListenPipe^.dwPacketSize);
if pListenPipe^.fStopped then
BREAK;
if dwBytesTransfered = $ffffffff then
begin
writeln('Transfer failed');
BREAK;
end;
if @pListenPipe^.process_data_func <> POINTER(0) then
pListenPipe^.process_data_func(pbuf, dwBytesTransfered, pListenPipe^.pContext)
else
PrintHexBuffer(pbuf, dwBytesTransfered);
end;
FreeMem(pbuf);
PipeListenHandler := 0;
end;
function GetHexChar (line : string) : INTEGER;
var
ch : INTEGER;
tmpStr : string;
begin
ch := Ord(line[1]);
if (not IsHexDigit(line[1])) then
begin
GetHexChar := -1;
Exit;
end;
if ((ch >= Ord('0')) and (ch <= Ord('9'))) then
GetHexChar := StrToInt(line[1])
else
begin
tmpStr := UpperCase(line[1]);
GetHexChar := BYTE(tmpStr[1]) - BYTE('A') + 10;
end;
end;
function GetHexBuffer(pBuffer : POINTER; dwBytes : DWORD) : DWORD;
var
i , pos: DWORD;
pData : PBYTE;
res : BYTE;
ch : INTEGER;
line : string;
strLength : INTEGER;
begin
pData := pBuffer;
i := 1;
pos := 0;
Readln(line);
strLength := Length(line);
while pos < dwBytes do
begin
if i > strLength then
begin
Readln(line);
strLength := Length(line);
i := 1;
end;
ch := GetHexChar(line[i]);
if ch<0 then
begin
i := i+1;
continue;
end;
res := ch * 16;
i := i+1;
if i > strLength then
begin
Readln(line);
strLength := Length(line);
i := 1;
end;
ch := GetHexChar(line[i]);
if ch<0 then
begin
i := i+1;
continue;
end;
res := res + ch;
PBYTE(DWORD(pData) +pos)^ := res;
i := i+1;
pos := pos+1;
end;
// return the number of bytes that was read
GetHexBuffer := pos;
end;
function IsHexDigit(c : string) : BOOLEAN;
var
cOrd : Longint;
begin
cOrd := Ord(c[1]);
IsHexDigit := ((cOrd >= Ord('0')) and (cOrd <= Ord('9')))
or ((cOrd >= Ord('A')) and (cOrd <= Ord('F')))
or ((cOrd >= Ord('a')) and (cOrd <= Ord('f')));
end;
end.
|
unit htFlowPanel;
interface
uses
Windows, SysUtils, Types, Classes, Controls, Graphics,
htInterfaces, htMarkup, htControls;
type
ThtCustomFlowPanel = class(ThtCustomControl)
private
protected
procedure AlignControls(AControl: TControl; var Rect: TRect); override;
procedure GenerateCtrls(inMarkup: ThtMarkup);
procedure GenerateCtrl(inMarkup: ThtMarkup; const inContainer: string;
inCtrl: TControl);
public
constructor Create(inOwner: TComponent); override;
destructor Destroy; override;
procedure Generate(const inContainer: string;
inMarkup: ThtMarkup); override;
end;
//
ThtFlowPanel = class(ThtCustomFlowPanel)
published
property Align;
property Outline;
property Style;
property Transparent;
property Visible;
end;
implementation
uses
LrVclUtils, LrControlIterator;
{ ThtCustomFlowPanel }
constructor ThtCustomFlowPanel.Create(inOwner: TComponent);
begin
inherited;
ControlStyle := ControlStyle + [ csAcceptsControls ];
end;
destructor ThtCustomFlowPanel.Destroy;
begin
inherited;
end;
procedure ThtCustomFlowPanel.AlignControls(AControl: TControl;
var Rect: TRect);
var
lineHeight, x, y: Integer;
begin
inherited;
lineHeight := 0;
x := 0;
y := 0;
with TLrCtrlIterator.Create(Self) do
try
while Next do
begin
lineHeight := LrMax(Ctrl.Height, lineHeight);
if (x > 0) and (Ctrl.Width + x > ClientWidth) then
begin
Inc(y, lineHeight);
lineHeight := 0;
x := 0;
end;
Ctrl.Left := x;
Ctrl.Top := y;
Inc(x, Ctrl.Width);
end;
finally
Free;
end;
end;
procedure ThtCustomFlowPanel.GenerateCtrl(inMarkup: ThtMarkup;
const inContainer: string; inCtrl: TControl);
var
c: IhtControl;
begin
if LrIsAs(inCtrl, IhtControl, c) then
c.Generate(inContainer, inMarkup)
else
inMarkup.Add(inCtrl.Name);
end;
procedure ThtCustomFlowPanel.GenerateCtrls(inMarkup: ThtMarkup);
begin
with TLrCtrlIterator.Create(Self) do
try
while Next do
GenerateCtrl(inMarkup, Ctrl.Name, Ctrl);
finally
Free;
end;
end;
procedure ThtCustomFlowPanel.Generate(const inContainer: string;
inMarkup: ThtMarkup);
begin
GenerateStyle('#' + Name, inMarkup);
inMarkup.Styles.Add(
Format('#%s { position: relative; margin-right: 0; height: %dpx; }',
[ Name, Height ]));
inMarkup.Add(Format('<div id="%s">', [ Name ]));
GenerateCtrls(inMarkup);
inMarkup.Add('</div>');
end;
end.
|
unit uOther;
interface
uses SysUtils, Dialogs, Controls, Forms, uSvcInfoIntf, uDefCom, uOtherIntf;
const
LogDir = 'Log';//保存日志的目录
type
TExManagement = class(TInterfacedObject, ISvcInfo, IExManagement)
private
protected
{ISvcInfo}
function GetModuleName: string;
function GetTitle: string;
function GetVersion: string;
function GetComments: string;
{IExManagement}
function CreateSysEx(const AShowMsg: string; const AWriteMsg: string = ''): Exception; //创建系统级异常
function CreateFunEx(const AShowMsg: string; const AWriteMsg: string = ''): Exception; //创建函数级异常
public
end;
TMsgBox = class(TInterfacedObject, ISvcInfo, IMsgBox)
private
protected
{ISvcInfo}
function GetModuleName: string;
function GetTitle: string;
function GetVersion: string;
function GetComments: string;
{IMsgBox}
function MsgBox(AMsg: string; ACaption: string = ''; AMsgType: TMessageBoxType = mbtInformation;
AButtons: TMessageBoxButtons = [mbbOk]): Integer;
function InputBox(const ACaption, APrompt: string; var ADefautValue: string; AMaxLen:
Integer = 0; ADataType: TColField = cfString): Integer;
public
end;
type
TLogObj = class(TInterfacedObject, ISvcInfo, ILog)
private
protected
{ILog}
procedure WriteLogDB(ALogType: TLogType; const AStr: string);
procedure WriteLogTxt(ALogType: TLogType; const AErr: string);
{ISvcInfo}
function GetModuleName: string;
function GetTitle: string;
function GetVersion: string;
function GetComments: string;
public
constructor Create;
end;
implementation
uses uSysSvc, uSysFactory, uExDef, uPubFun, uFrmMsgBox, uFrmInputBox;
{ TExManagement }
function TExManagement.CreateFunEx(const AShowMsg: string; const AWriteMsg: string = ''): Exception;
begin
if not StringEmpty(AWriteMsg) then
begin
(SysService as ILog).WriteLogTxt(ltErrFun, AWriteMsg);
end;
Result := EFunException.Create(AShowMsg);
end;
function TExManagement.CreateSysEx(const AShowMsg: string; const AWriteMsg: string = ''): Exception;
begin
if not StringEmpty(AWriteMsg) then
begin
(SysService as ILog).WriteLogTxt(ltErrSys, AWriteMsg);
end;
Result := ESysException.Create(AShowMsg);
end;
function TExManagement.GetComments: string;
begin
Result := '用于异常操作';
end;
function TExManagement.GetModuleName: string;
begin
Result := '异常操作接口(IExManagement)';
end;
function TExManagement.GetTitle: string;
begin
Result := '用于异常操作';
end;
function TExManagement.GetVersion: string;
begin
Result := '20141203.001';
end;
{ TMsgBox }
function TMsgBox.GetComments: string;
begin
Result := '用于对话框操作';
end;
function TMsgBox.GetModuleName: string;
begin
Result := ExtractFileName(SysUtils.GetModuleName(HInstance));
end;
function TMsgBox.GetTitle: string;
begin
Result := '用于对话框操作';
end;
function TMsgBox.GetVersion: string;
begin
Result := '20150829';
end;
function TMsgBox.InputBox(const ACaption, APrompt: string;
var ADefautValue: string; AMaxLen: Integer;
ADataType: TColField): Integer;
begin
with TfrmInputBox.Create(nil) do
try
Captions := ACaption;
Prompt := APrompt;
InputValue := ADefautValue;
MaxLen := AMaxLen;
DataType := ADataType;
Result := ShowModal;
if Result = mrok then
begin
ADefautValue := Trim(edtInput.Text);
end;
finally
Free
end;
end;
function TMsgBox.MsgBox(AMsg, ACaption: string; AMsgType: TMessageBoxType;
AButtons: TMessageBoxButtons): Integer;
var
aFrm: TfrmMsgBox;
begin
aFrm := TfrmMsgBox.Create(Application); //要用Application不然可能出错
try
aFrm.Captions := ACaption;
aFrm.Messages := AMsg;
aFrm.MsgType := AMsgType;
aFrm.Buttons := AButtons;
Result := aFrm.ShowModal;
finally
aFrm.Free
end;
end;
{ TLogObj }
constructor TLogObj.Create;
var
aLogDir: string;
begin
inherited;
aLogDir := ExtractFilePath(Paramstr(0)) + LogDir;
if not DirectoryExists(aLogDir) then
begin
ForceDirectories(aLogDir);
end;
end;
function TLogObj.GetComments: string;
begin
Result := '封装日志相关操作';
end;
function TLogObj.GetModuleName: string;
begin
Result := ExtractFileName(SysUtils.GetModuleName(HInstance));
end;
function TLogObj.GetTitle: string;
begin
Result := '封装日志相关操作';
end;
function TLogObj.GetVersion: string;
begin
Result := '20150829';
end;
procedure TLogObj.WriteLogTxt(ALogType: TLogType; const AErr: string);
var
aFileName, aErrMsg: string;
aFileHandle: TextFile;
begin
aFileName := ExtractFilePath(Paramstr(0)) + LogDir + '\' + FormatDateTime('YYYY-MM-DD', Now) + '.txt'; ;
assignfile(aFileHandle, aFileName);
try
if FileExists(aFileName) then
append(aFileHandle) //Reset(FileHandle)
else ReWrite(aFileHandle);
case ALogType of
ltErrSys: aErrMsg := '系统错误';
ltErrFun: aErrMsg := '函数错误';
else
aErrMsg := '未知错误类型'
end;
aErrMsg := FormatDateTime('[HH:MM:SS]', now) + ' ' + aErrMsg + ':' + AErr;
WriteLn(aFileHandle, aErrMsg);
finally
CloseFile(aFileHandle);
end;
end;
procedure TLogObj.WriteLogDB(ALogType: TLogType; const AStr: string);
begin
//这个可能要写入数据表。。。
raise Exception.Create('未实现。。。');
end;
procedure CreateExManagement(out anInstance: IInterface);
begin
anInstance := TExManagement.Create;
end;
procedure CreateMsgBox(out anInstance: IInterface);
begin
anInstance := TMsgBox.Create;
end;
procedure CreateLogObj(out anInstance: IInterface);
begin
anInstance := TLogObj.Create;
end;
initialization
TSingletonFactory.Create(IExManagement, @CreateExManagement);
TIntfFactory.Create(IMsgBox, @CreateMsgBox);
TSingletonFactory.Create(ILog, @CreateLogObj);
finalization
end.
|
unit Addlow;
interface
uses WinTypes, WinProcs, Classes, Graphics, Forms, Controls, Buttons,
StdCtrls, ExtCtrls, SysUtils ;
const
Units = 'ug/kg' ;
type
TAddDoseLow = class(TForm)
bOK: TBitBtn;
CancelBtn: TBitBtn;
Bevel1: TBevel;
cbDose: TComboBox;
lbDrugName: TLabel;
rgInjectionSite: TRadioGroup;
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
AddDoseLow: TAddDoseLow;
implementation
{$R *.DFM}
procedure TAddDoseLow.FormShow(Sender: TObject);
// ------------------------------------------
// Initialise controls when form is displayed
// ------------------------------------------
begin
cbDose.Clear ;
cbDose.Items.Add( format( ' %.3g %s', [0.1,Units] )) ;
cbDose.Items.Add( format( ' %.3g %s', [0.2,Units] )) ;
cbDose.Items.Add( format( ' %.3g %s', [0.5,Units] )) ;
cbDose.Items.Add( format( ' %.3g %s', [1.0,Units] )) ;
cbDose.Items.Add( format( ' %.3g %s', [2.0,Units] )) ;
cbDose.Items.Add( format( ' %.3g %s', [5.0,Units] )) ;
cbDose.Items.Add( format( ' %.3g %s', [10.0,Units] )) ;
cbDose.Items.Add( format( ' %.3g %s', [20.0,Units] )) ;
cbDose.Items.Add( format( ' %.3g %s', [50.0,Units] )) ;
cbDose.Items.Add( format( ' %.3g %s', [100.0,Units] )) ;
cbDose.ItemIndex := 0 ;
end;
end.
|
{******************************************************************************}
{ }
{ Delphi PnHttpSysServer }
{ }
{ Copyright (c) 2018 pony,นโร๗(7180001@qq.com) }
{ }
{ Homepage: https://github.com/pony5551/PnHttpSysServer }
{ }
{******************************************************************************}
unit uPNSysThreadPool;
interface
{$I PnDefs.inc}
// if needed, we should later make this cross-platform. Currently it's not needed
// since it's only being used by the server (which is windows-only)
{$IFDEF MSWINDOWS}
uses
Classes, SyncObjs, SysUtils;
type
TSysThreadPool = class
private
const DefaultStopTimeout = 20000;
private
FStopTimeout: integer;
FStarted: boolean;
protected
function WaitWorkItems(const Timeout: Cardinal): boolean; virtual; abstract;
procedure DoStart; virtual;
procedure DoStop; virtual;
public
constructor Create; virtual;
destructor Destroy; override;
procedure Start;
function QueueUserWorkItem(Proc: TNotifyEvent; Context: TObject): boolean; virtual; abstract;
function Stop: boolean;
property StopTimeout: integer read FStopTimeout write FStopTimeout;
property Started: boolean read FStarted;
end;
TWinThreadPool = class(TSysThreadPool)
private
FWorkCount: integer;
FEvent: TEvent;
protected
function WaitWorkItems(const Timeout: Cardinal): boolean; override;
public
constructor Create; override;
destructor Destroy; override;
function QueueUserWorkItem(Proc: TNotifyEvent; Context: TObject): boolean; override;
property WorkCount: Integer read FWorkCount write FWorkCount;
end;
{$ENDIF}
implementation
{$IFDEF MSWINDOWS}
uses
Winapi.Windows;
type
PWinWorkItem = ^TWinWorkItem;
TWinWorkItem = record
private
FPool: TWinThreadPool;
FContext: TObject;
FProc: TNotifyEvent;
public
procedure Create(AProc: TNotifyEvent; AContext: TObject; APool: TWinThreadPool);
property Context: TObject read FContext;
property Pool: TWinThreadPool read FPool;
property Proc: TNotifyEvent read FProc;
end;
function WorkItemFunction(lpThreadParameter: Pointer): Integer; stdcall;
var
W: PWinWorkItem;
Pool: TWinThreadPool;
begin
Result := 0;
W := PWinWorkItem(lpThreadParameter);
try
W.Proc(W.Context);
finally
Pool := W.Pool;
Dispose(W);
if InterlockedDecrement(Pool.FWorkCount) = 0 then
Pool.FEvent.SetEvent;
end;
end;
{ TWinThreadPool }
constructor TWinThreadPool.Create;
begin
inherited;
FEvent := TEvent.Create;
FEvent.SetEvent;
end;
destructor TWinThreadPool.Destroy;
begin
FEvent.Free;
inherited;
end;
function TWinThreadPool.QueueUserWorkItem(Proc: TNotifyEvent; Context: TObject): boolean;
var
WorkItem: PWinWorkItem;
begin
New(WorkItem);
try
WorkItem.Create(Proc, Context, Self);
InterlockedIncrement(FWorkCount);
FEvent.ResetEvent;
Result := Winapi.Windows.QueueUserWorkItem(WorkItemFunction, WorkItem, 0);
if not Result then
Dispose(WorkItem);
except
Dispose(WorkItem);
raise;
end;
end;
function TWinThreadPool.WaitWorkItems(const Timeout: Cardinal): boolean;
begin
Result := WaitForSingleObject(FEvent.Handle, Timeout) = WAIT_OBJECT_0;
end;
{ TWinWorkItem }
procedure TWinWorkItem.Create(AProc: TNotifyEvent; AContext: TObject; APool: TWinThreadPool);
begin
FContext := AContext;
FPool := APool;
FProc := AProc;
end;
{ TSysThreadPool }
constructor TSysThreadPool.Create;
begin
FStopTimeout := DefaultStopTimeout;
FStarted := false;
end;
destructor TSysThreadPool.Destroy;
begin
Stop;
inherited;
end;
procedure TSysThreadPool.DoStart;
begin
end;
procedure TSysThreadPool.DoStop;
begin
end;
procedure TSysThreadPool.Start;
begin
if Started then Exit;
DoStart;
FStarted := true;
end;
function TSysThreadPool.Stop: boolean;
begin
if not Started then Exit(true);
FStarted := false;
Result := WaitWorkItems(StopTimeout);
DoStop;
end;
{$ENDIF}
end.
|
unit FMaskSelect;
(*====================================================================
Dialog box for selecting set of disks/files by a mask
======================================================================*)
interface
uses
SysUtils,
{$ifdef mswindows}
WinTypes,WinProcs,
{$ELSE}
LCLIntf, LCLType, LMessages,
{$ENDIF}
Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls,
UTypes;
type
TFormMaskSelect = class(TForm)
ButtonOK: TButton;
ButtonCancel: TButton;
LabelMask: TLabel;
ButtonHelp: TButton;
ComboBoxMaskDisks: TComboBox;
ComboBoxMaskFiles: TComboBox;
procedure ButtonOKClick(Sender: TObject);
procedure ButtonCancelClick(Sender: TObject);
procedure ButtonHelpClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FormMaskSelect: TFormMaskSelect;
implementation
{$R *.dfm}
//-----------------------------------------------------------------------------
// Add masks to history lists
procedure TFormMaskSelect.ButtonOKClick(Sender: TObject);
var
Found : boolean;
i : Integer;
begin
with ComboboxMaskDisks do
if Visible and (Text <> '') then
begin
Found := false;
for i := 0 to pred(Items.Count) do
if Items.Strings[i] = Text then
Found := true;
if not Found then Items.Add(Text);
end;
with ComboboxMaskFiles do
if Visible and (Text <> '') then
begin
Found := false;
for i := 0 to pred(Items.Count) do
if Items.Strings[i] = Text then
Found := true;
if not Found then Items.Add(Text);
end;
ModalResult := mrOK;
end;
//-----------------------------------------------------------------------------
procedure TFormMaskSelect.ButtonCancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
//-----------------------------------------------------------------------------
procedure TFormMaskSelect.ButtonHelpClick(Sender: TObject);
begin
Application.HelpContext(140);
end;
//-----------------------------------------------------------------------------
procedure TFormMaskSelect.FormShow(Sender: TObject);
begin
if ComboBoxMaskFiles.Visible then
ActiveControl := ComboBoxMaskFiles;
if ComboBoxMaskDisks.Visible then
ActiveControl := ComboBoxMaskDisks;
end;
//-----------------------------------------------------------------------------
end.
|
unit ideSHSystemOptions;
interface
uses
SysUtils, Classes, Dialogs, Graphics, DesignIntf, VirtualTrees,
SHDesignIntf, SHOptionsIntf;
type
TideSHSystemOptions = class(TSHComponentOptions, ISHSystemOptions)
private
FStartBranch: Integer;
FUseWorkspaces: Boolean;
FExternalDiffPath: string;
FExternalDiffParams: string;
FShowSplashWindow: Boolean;
FWarningOnExit: Boolean;
FLeftWidth: Integer;
FRightWidth: Integer;
FIDE1Height: Integer;
FIDE2Height: Integer;
FIDE3Height: Integer;
FNavigatorLeft: Boolean;
FToolboxTop: Boolean;
FStartPage: Integer;
FMultilineMode: Boolean;
FFilterMode: Boolean;
function GetStartBranch: Integer;
procedure SetStartBranch(Value: Integer);
function GetShowSplashWindow: Boolean;
procedure SetShowSplashWindow(Value: Boolean);
function GetUseWorkspaces: Boolean;
procedure SetUseWorkspaces(Value: Boolean);
function GetExternalDiffPath: string;
procedure SetExternalDiffPath(Value: string);
function GetExternalDiffParams: string;
procedure SetExternalDiffParams(Value: string);
function GetWarningOnExit: Boolean;
procedure SetWarningOnExit(Value: Boolean);
function GetLeftWidth: Integer;
procedure SetLeftWidth(Value: Integer);
function GetRightWidth: Integer;
procedure SetRightWidth(Value: Integer);
function GetIDE1Height: Integer;
procedure SetIDE1Height(Value: Integer);
function GetIDE2Height: Integer;
procedure SetIDE2Height(Value: Integer);
function GetIDE3Height: Integer;
procedure SetIDE3Height(Value: Integer);
function GetNavigatorLeft: Boolean;
procedure SetNavigatorLeft(Value: Boolean);
function GetToolboxTop: Boolean;
procedure SetToolboxTop(Value: Boolean);
function GetStartPage: Integer;
procedure SetStartPage(Value: Integer);
function GetMultilineMode: Boolean;
procedure SetMultilineMode(Value: Boolean);
function GetFilterMode: Boolean;
procedure SetFilterMode(Value: Boolean);
protected
function GetCategory: string; override;
procedure RestoreDefaults; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property ExternalDiffPath: string read GetExternalDiffPath write SetExternalDiffPath;
property ExternalDiffParams: string read GetExternalDiffParams write SetExternalDiffParams;
published
property ShowSplashWindow: Boolean read GetShowSplashWindow write SetShowSplashWindow;
property UseWorkspaces: Boolean read GetUseWorkspaces write SetUseWorkspaces;
property WarningOnExit: Boolean read GetWarningOnExit write SetWarningOnExit;
{Invisible}
property StartBranch: Integer read GetStartBranch write SetStartBranch;
property LeftWidth: Integer read GetLeftWidth write SetLeftWidth;
property RightWidth: Integer read GetRightWidth write SetRightWidth;
property IDE1Height: Integer read GetIDE1Height write SetIDE1Height;
property IDE2Height: Integer read GetIDE2Height write SetIDE2Height;
property IDE3Height: Integer read GetIDE3Height write SetIDE3Height;
property NavigatorLeft: Boolean read GetNavigatorLeft write SetNavigatorLeft;
property ToolboxTop: Boolean read GetToolboxTop write SetToolboxTop;
property StartPage: Integer read GetStartPage write SetStartPage;
property MultilineMode: Boolean read GetMultilineMode write SetMultilineMode;
property FilterMode: Boolean read GetFilterMode write SetFilterMode;
end;
TideSHExternalDiffPathPropEditor = class(TSHPropertyEditor)
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
implementation
uses
ideSHConsts, ideSHSystem, ideSHMainFrm;
{ TideSHSystemOptions }
constructor TideSHSystemOptions.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
MakePropertyInvisible('StartBranch');
MakePropertyInvisible('LeftWidth');
MakePropertyInvisible('RightWidth');
MakePropertyInvisible('IDE1Height');
MakePropertyInvisible('IDE2Height');
MakePropertyInvisible('IDE3Height');
MakePropertyInvisible('NavigatorLeft');
MakePropertyInvisible('ToolboxTop');
MakePropertyInvisible('StartPage');
MakePropertyInvisible('MultilineMode');
MakePropertyInvisible('FilterMode');
FLeftWidth := 165;
FRightWidth := 145;
FIDE1Height := 160;
FIDE2Height := 400;
FIDE3Height := 200;
FNavigatorLeft := True;
FToolboxTop := True;
FMultilineMode := False;
FFilterMode := False;
end;
destructor TideSHSystemOptions.Destroy;
begin
inherited Destroy;
end;
function TideSHSystemOptions.GetCategory: string;
begin
Result := Format('%s', [SSystem]);
end;
procedure TideSHSystemOptions.RestoreDefaults;
begin
FShowSplashWindow := True;
FUseWorkspaces := True;
FExternalDiffPath := EmptyStr;
FExternalDiffParams := '%File1% %File2%';
FWarningOnExit := True;
end;
function TideSHSystemOptions.GetStartBranch: Integer;
begin
Result := FStartBranch;
end;
procedure TideSHSystemOptions.SetStartBranch(Value: Integer);
begin
FStartBranch := Value;
end;
function TideSHSystemOptions.GetShowSplashWindow: Boolean;
begin
Result := FShowSplashWindow;
end;
procedure TideSHSystemOptions.SetShowSplashWindow(Value: Boolean);
begin
FShowSplashWindow := Value;
end;
function TideSHSystemOptions.GetUseWorkspaces: Boolean;
begin
Result := FUseWorkspaces;
end;
procedure TideSHSystemOptions.SetUseWorkspaces(Value: Boolean);
begin
if FUseWorkspaces <> Value then
begin
if not Assigned(Designer.CurrentComponent) then
FUseWorkspaces := Value
else
Designer.ShowMsg(Format('%s', ['Object Editor must be empty']), mtInformation);
end;
end;
function TideSHSystemOptions.GetExternalDiffPath: string;
begin
Result := FExternalDiffPath;
end;
procedure TideSHSystemOptions.SetExternalDiffPath(Value: string);
begin
FExternalDiffPath := Value;
end;
function TideSHSystemOptions.GetExternalDiffParams: string;
begin
Result := FExternalDiffParams;
end;
procedure TideSHSystemOptions.SetExternalDiffParams(Value: string);
begin
FExternalDiffParams := Value;
end;
function TideSHSystemOptions.GetWarningOnExit: Boolean;
begin
Result := FWarningOnExit;
end;
procedure TideSHSystemOptions.SetWarningOnExit(Value: Boolean);
begin
FWarningOnExit := Value;
end;
function TideSHSystemOptions.GetLeftWidth: Integer;
begin
Result := FLeftWidth;
end;
procedure TideSHSystemOptions.SetLeftWidth(Value: Integer);
begin
FLeftWidth := Value;
end;
function TideSHSystemOptions.GetRightWidth: Integer;
begin
Result := FRightWidth;
end;
procedure TideSHSystemOptions.SetRightWidth(Value: Integer);
begin
FRightWidth := Value;
end;
function TideSHSystemOptions.GetIDE1Height: Integer;
begin
Result := FIDE1Height;
end;
procedure TideSHSystemOptions.SetIDE1Height(Value: Integer);
begin
FIDE1Height := Value;
end;
function TideSHSystemOptions.GetIDE2Height: Integer;
begin
Result := FIDE2Height;
end;
procedure TideSHSystemOptions.SetIDE2Height(Value: Integer);
begin
FIDE2Height := Value;
end;
function TideSHSystemOptions.GetIDE3Height: Integer;
begin
Result := FIDE3Height;
end;
procedure TideSHSystemOptions.SetIDE3Height(Value: Integer);
begin
FIDE3Height := Value;
end;
function TideSHSystemOptions.GetNavigatorLeft: Boolean;
begin
Result := FNavigatorLeft;
end;
procedure TideSHSystemOptions.SetNavigatorLeft(Value: Boolean);
begin
FNavigatorLeft := Value;
end;
function TideSHSystemOptions.GetToolboxTop: Boolean;
begin
Result := FToolboxTop;
end;
procedure TideSHSystemOptions.SetToolboxTop(Value: Boolean);
begin
FToolboxTop := Value;
end;
function TideSHSystemOptions.GetStartPage: Integer;
begin
Result := FStartPage;
end;
procedure TideSHSystemOptions.SetStartPage(Value: Integer);
begin
FStartPage := Value;
end;
function TideSHSystemOptions.GetMultilineMode: Boolean;
begin
Result := FMultilineMode;
end;
procedure TideSHSystemOptions.SetMultilineMode(Value: Boolean);
begin
FMultilineMode := Value;
end;
function TideSHSystemOptions.GetFilterMode: Boolean;
begin
Result := FFilterMode;
end;
procedure TideSHSystemOptions.SetFilterMode(Value: Boolean);
begin
FFilterMode := Value;
end;
{ TideSHExternalDiffPathPropEditor }
function TideSHExternalDiffPathPropEditor.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog];
end;
procedure TideSHExternalDiffPathPropEditor.Edit;
var
OpenDialog: TOpenDialog;
begin
OpenDialog := TOpenDialog.Create(nil);
try
OpenDialog.Filter := 'Executables (*.exe; *.bat; *.cmd)|*.exe; *.bat; *.cmd|All Files (*.*)|*.*';
if OpenDialog.Execute then SetStrValue(OpenDialog.FileName);
finally
FreeAndNil(OpenDialog);
end;
end;
end.
|
unit USplitter;
interface
uses UFlow, URegularFunctions;
type
Splitter = class
ratio: array of real;
constructor(ratio: array of real);
function calculate(flow_: Flow): array of Flow;
end;
implementation
constructor Splitter.Create(ratio: array of real);
begin
self.ratio := normalize(ratio)
end;
function Splitter.calculate(flow_: Flow): array of Flow;
begin
var mass_flows := ArrFill(self.ratio.Length, 0.0);
foreach var i in mass_flows.Indices do
mass_flows[i] := flow_.mass_flow_rate * self.ratio[i];
SetLength(result, self.ratio.Length);
foreach var i in result.Indices do
result[i] := new Flow(mass_flows[i], flow_.mass_fractions,
flow_.temperature)
end;
end. |
unit ScrnCap;
//Download by http://www.codefans.net
interface
uses Dialogs, Messages, WinTypes, WinProcs, Forms, Controls, Classes, Graphics, Math, SysUtils;
type
TFColor = record
b, g, r: Byte;
end;
PFColor = ^TFColor;
TLine = array[0..0] of TFColor;
PLine = ^TLine;
function CaptureScreenRect(ARect: TRect): TBitmap;
function CaptureScreen: TBitmap;
function CaptureClientImage(Control: TControl): TBitmap;
function CaptureControlImage(Control: TControl): TBitmap;
function CaptureWindowImage(Wnd: HWND): TBitmap;
function CaptureActiveWindow: TBitmap;
function CaptureScrollImage(Wnd: HWND): TBitmap;
implementation
//抓取屏幕上的一个矩形区域
function CaptureScreenRect(ARect: TRect): TBitmap;
var
ScreenDC: HDC;
begin
Result := TBitmap.Create;
with Result, ARect do
begin
Width := Right - Left;
Height := Bottom - Top;
ScreenDC := GetDC(0);
try
BitBlt(Canvas.Handle, 0, 0, Width, Height, ScreenDC,
Left, Top, SRCCOPY);
finally
ReleaseDC(0, ScreenDC);
end;
end;
end;
function CaptureScreen: TBitmap;
begin
with Screen do
Result := CaptureScreenRect(Rect(0, 0, Width, Height));
end;
function CaptureActiveWindow: TBitmap;
var
Re: TRect;
AWnd: HWND;
begin
AWnd := GetForeGroundWindow;
GetWindowRect(AWnd, Re);
Result := CaptureScreenRect(Re);
end;
function CaptureClientImage(Control: TControl): TBitmap;
begin
with Control, Control.ClientOrigin do
Result := CaptureScreenRect(Bounds(X, Y, ClientWidth,
ClientHeight));
end;
function CaptureControlImage(Control: TControl): TBitmap;
begin
with Control do
if Parent = nil then
Result := CaptureScreenRect(Bounds(Left, Top, Width,
Height))
else
with Parent.ClientToScreen(Point(Left, Top)) do
Result := CaptureScreenRect(Bounds(X, Y, Width,
Height));
end;
function CaptureWindowImage(Wnd: HWND): TBitmap;
var
R: TRect;
begin
GetWindowRect(Wnd, R);
Result := CaptureScreenRect(R);
end;
function CaptureScrollImage(Wnd: HWND): TBitmap;
var
ClientR: TRect;
Flag, NotFound: Boolean;
ScrollBmp: TBitmap;
ScrImgHeight: integer;
Width, Height: integer;
TmpHND: HWND;
ScrollPos: Integer;
ScrollInfo: TScrollInfo;
PresentPos: Integer;
IncreaseM, DrawPos, HalfHeight, HalfWidth, RemainHeight: integer;
x, y: integer;
WinHDC: HDC;
PointColor: ColorREF;
ScrollExist: Boolean;
begin
SetForeGroundWindow(Wnd);
Sleep(5);
WinHDC := GetDC(Wnd);
GetClientRect(Wnd, ClientR);
Width := ClientR.Right - ClientR.Left;
HalfWidth := Width div 2;
Height := ClientR.Bottom - ClientR.Top;
HalfHeight := Height div 2;
ScrollBmp := TBitmap.Create;
ScrollBmp.Height := HalfHeight + 1;
ScrollBmp.Width := Width;
Flag := true;
BitBlt(ScrollBmp.Canvas.Handle, 0, 0, Width, HalfHeight + 1, WinHDC,
ClientR.Left, ClientR.Top, SRCCOPY);
SetRop2(WinHDC, R2_BLACK);
MoveToEx(WinHDC, 20, HalfHeight, nil);
LineTo(WinHDC, Width, HalfHeight);
SendMessage(Wnd, WM_VSCROLL, SB_LINEDOWN, 0);
y := HalfHeight;
x := 20;
PointColor := GetPixel(WinHDC, x, y);
while (PointColor = 0) and (x < Width - 1) do
begin
x := x + 1;
PointColor := GetPixel(WinHDC, x, y);
end;
if x = Width - 1 then
begin
ScrollBmp.Height := Height;
ScrollBmp.Width := Width;
BitBlt(ScrollBmp.Canvas.Handle, 0, HalfHeight + 1, Width, Height - HalfHeight, WinHDC,
ClientR.Left, ClientR.Top + HalfHeight + 1, SRCCOPY);
SendMessage(Wnd, WM_Paint, WinHDC, 0);
Result := ScrollBmp;
Exit;
end;
NotFound := True;
while NotFound and (y > 0) do
begin
y := y - 1;
x := 20;
PointColor := GetPixel(WinHDC, x, y);
while (PointColor = 0) and (x < Width - 1) do
begin
x := x + 1;
PointColor := GetPixel(WinHDC, x, y);
end;
if x = Width - 1 then
begin
NotFound := False;
IncreaseM := HalfHeight - y;
end
else
NotFound := True;
end;
ScrImgHeight := HalfHeight + 1;
while Flag do
begin
ScrImgHeight := ScrImgHeight + IncreaseM;
ScrollBmp.Height := ScrImgHeight;
DrawPos := ScrImgHeight - IncreaseM;
BitBlt(ScrollBmp.Canvas.Handle, 0, DrawPos, Width, IncreaseM, WinHDC,
ClientR.Left, ClientR.Top + HalfHeight - IncreaseM + 1, SRCCOPY);
MoveToEx(WinHDC, 20, HalfHeight, nil);
LineTo(WinHDC, Width, HalfHeight);
ScrollPos := GetScrollPos(Wnd, SB_VERT);
SendMessage(Wnd, WM_VSCROLL, SB_LINEDOWN, 0);
PresentPos := GetScrollPos(Wnd, SB_VERT);
if PresentPos = ScrollPos then
begin
flag := false;
RemainHeight := Height - HalfHeight;
ScrollBmp.Height := ScrollBmp.Height + RemainHeight;
BitBlt(ScrollBmp.Canvas.Handle, 0, ScrImgHeight, Width, RemainHeight,
WinHDC, ClientR.Left, ClientR.Top + HalfHeight + 1, SRCCOPY);
end
else
begin
flag := true;
y := HalfHeight;
NotFound := True;
while NotFound and (y > 0) do
begin
y := y - 1;
x := 20;
PointColor := GetPixel(WinHDC, x, y);
while (PointColor = 0) and (x <= Width) do
begin
x := x + 1;
PointColor := GetPixel(WinHDC, x, y);
end;
if x = Width then
begin
NotFound := False;
IncreaseM := HalfHeight - y;
end
else
NotFound := True;
end;
end;
end;
result := ScrollBmp;
SendMessage(Wnd, WM_Paint, WinHDC, 0);
ReleaseDC(Wnd, WinHDC);
end;
end.
|
unit UDSectionFont;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Buttons, UCrpe32;
type
TCrpeSectionFontDlg = class(TForm)
pnlSectionFont: TPanel;
lblName: TLabel;
lblSize: TLabel;
lblCharSet: TLabel;
lblFamily: TLabel;
lblWeight: TLabel;
lblSection: TLabel;
editName: TEdit;
pnlSample: TPanel;
lblSample: TLabel;
editSize: TEdit;
btnSelectFont: TBitBtn;
cbCharSet: TComboBox;
cbItalic: TCheckBox;
cbUnderlined: TCheckBox;
cbStrikeThrough: TCheckBox;
cbFamily: TComboBox;
rgScope: TRadioGroup;
rgPitch: TRadioGroup;
cbWeight: TComboBox;
lbSections: TListBox;
btnOk: TButton;
btnClear: TButton;
FontDialog1: TFontDialog;
lblCount: TLabel;
editCount: TEdit;
procedure btnSelectFontClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure lbSectionsClick(Sender: TObject);
procedure editNameChange(Sender: TObject);
procedure cbItalicClick(Sender: TObject);
procedure cbUnderlinedClick(Sender: TObject);
procedure cbStrikeThroughClick(Sender: TObject);
procedure editSizeKeyPress(Sender: TObject; var Key: Char);
procedure editSizeExit(Sender: TObject);
procedure cbWeightChange(Sender: TObject);
procedure rgScopeClick(Sender: TObject);
procedure rgPitchClick(Sender: TObject);
procedure cbCharSetChange(Sender: TObject);
procedure cbFamilyChange(Sender: TObject);
procedure btnClearClick(Sender: TObject);
procedure UpdateSectionFont;
procedure btnOkClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure InitializeControls(OnOff: boolean);
private
{ Private declarations }
public
{ Public declarations }
Cr : TCrpe;
SFIndex : smallint;
end;
var
CrpeSectionFontDlg: TCrpeSectionFontDlg;
bSectionFont : boolean;
implementation
{$R *.DFM}
uses UCrpeUtl;
{------------------------------------------------------------------------------}
{ FormCreate procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFontDlg.FormCreate(Sender: TObject);
begin
bSectionFont := True;
LoadFormPos(Self);
btnOk.Tag := 1;
end;
{------------------------------------------------------------------------------}
{ FormShow procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFontDlg.FormShow(Sender: TObject);
begin
{Fill in the Combo Boxes}
{FontWeight}
cbWeight.Clear;
cbWeight.Items.Add('fwDefault');
cbWeight.Items.Add('fwThin');
cbWeight.Items.Add('fwExtraLight');
cbWeight.Items.Add('fwLight');
cbWeight.Items.Add('fwNormal');
cbWeight.Items.Add('fwMedium');
cbWeight.Items.Add('fwSemiBold');
cbWeight.Items.Add('fwBold');
cbWeight.Items.Add('fwExtraBold');
cbWeight.Items.Add('fwHeavy');
{FontCharSet}
cbCharSet.Clear;
cbCharSet.Items.Add('fcAnsi');
cbCharSet.Items.Add('fcDefault');
cbCharSet.Items.Add('fcSymbol');
cbCharSet.Items.Add('fcShiftJis');
cbCharSet.Items.Add('fcHangeul');
cbCharSet.Items.Add('fcChineseBig5');
cbCharSet.Items.Add('fcOEM');
{FontFamily}
cbFamily.Clear;
cbFamily.Items.Add('ffDefault');
cbFamily.Items.Add('ffRoman');
cbFamily.Items.Add('ffSwiss');
cbFamily.Items.Add('ffModern');
cbFamily.Items.Add('ffScript');
cbFamily.Items.Add('ffDecorative');
UpdateSectionFont;
end;
{------------------------------------------------------------------------------}
{ UpdateSectionFont procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFontDlg.UpdateSectionFont;
var
OnOff : boolean;
begin
{Enable/Disable controls}
if IsStrEmpty(Cr.ReportName) then
begin
OnOff := False;
SFIndex := -1;
end
else
begin
OnOff := (Cr.SectionFont.Count > 0);
{Get SectionFont Index}
if OnOff then
begin
if Cr.SectionFont.ItemIndex > -1 then
SFIndex := Cr.SectionFont.ItemIndex
else
SFIndex := 0;
end;
end;
InitializeControls(OnOff);
{Update list box}
if OnOff = True then
begin
lbSections.Items.AddStrings(Cr.SectionFormat.Names);
editCount.Text := IntToStr(Cr.SectionFont.Count);
lbSections.ItemIndex := SFIndex;
lbSectionsClick(self);
end;
end;
{------------------------------------------------------------------------------}
{ InitializeControls }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFontDlg.InitializeControls(OnOff: boolean);
var
i : integer;
begin
{Enable/Disable the Form Controls}
for i := 0 to ComponentCount - 1 do
begin
if TComponent(Components[i]).Tag = 0 then
begin
if Components[i] is TButton then
TButton(Components[i]).Enabled := OnOff;
if Components[i] is TCheckBox then
TCheckBox(Components[i]).Enabled := OnOff;
if Components[i] is TRadioGroup then
TRadioGroup(Components[i]).Enabled := OnOff;
if Components[i] is TBitBtn then
TBitBtn(Components[i]).Enabled := OnOff;
if Components[i] is TComboBox then
begin
TComboBox(Components[i]).Color := ColorState(OnOff);
TComboBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TListBox then
begin
TListBox(Components[i]).Clear;
TListBox(Components[i]).Color := ColorState(OnOff);
TListBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TEdit then
begin
TEdit(Components[i]).Text := '';
if TEdit(Components[i]).ReadOnly = False then
TEdit(Components[i]).Color := ColorState(OnOff);
TEdit(Components[i]).Enabled := OnOff;
end;
end;
end;
end;
{------------------------------------------------------------------------------}
{ lbSectionsClick }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFontDlg.lbSectionsClick(Sender: TObject);
begin
SFIndex := lbSections.ItemIndex;
{Disable events}
editSize.OnExit := nil;
{Update form}
editName.Text := Cr.SectionFont[SFIndex].Name;
editSize.Text := IntToStr(Cr.SectionFont.Item.Size);
cbWeight.ItemIndex := Ord(Cr.SectionFont.Item.Weight);
cbCharSet.ItemIndex := Ord(Cr.SectionFont.Item.CharSet);
cbFamily.ItemIndex := Ord(Cr.SectionFont.Item.Family);
case Ord(Cr.SectionFont.Item.Italic) of
0: cbItalic.State := cbUnchecked;
1: cbItalic.State := cbChecked;
2: cbItalic.State := cbGrayed;
end;
case Ord(Cr.SectionFont.Item.Underlined) of
0: cbUnderlined.State := cbUnchecked;
1: cbUnderlined.State := cbChecked;
2: cbUnderlined.State := cbGrayed;
end;
case Ord(Cr.SectionFont.Item.StrikeThrough) of
0: cbStrikeThrough.State := cbUnchecked;
1: cbStrikeThrough.State := cbChecked;
2: cbStrikeThrough.State := cbGrayed;
end;
rgScope.ItemIndex := Ord(Cr.SectionFont.Item.Scope);
rgPitch.ItemIndex := Ord(Cr.SectionFont.Item.Pitch);
{Enable events}
editSize.OnExit := editSizeExit;
end;
{------------------------------------------------------------------------------}
{ btnSelectFontClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFontDlg.btnSelectFontClick(Sender: TObject);
var
nIndex : integer;
i : integer;
begin
if Cr.SectionFont.Item.Name = '' then
begin
{Update Font Dialog font}
FontDialog1.Font.Name := 'System';
FontDialog1.Font.Size := 10;
FontDialog1.Font.Style := [];
end
else
begin
{Update Font Dialog defaults}
FontDialog1.Font.Name := Cr.SectionFont.Item.Name;
FontDialog1.Font.Size := Cr.SectionFont.Item.Size;
if (Cr.SectionFont.Item.Italic = cTrue) then
FontDialog1.Font.Style := FontDialog1.Font.Style + [fsItalic]
else
FontDialog1.Font.Style := FontDialog1.Font.Style - [fsItalic];
if (Cr.SectionFont.Item.Underlined = cTrue) then
FontDialog1.Font.Style := FontDialog1.Font.Style + [fsUnderline]
else
FontDialog1.Font.Style := FontDialog1.Font.Style - [fsUnderline];
if (Cr.SectionFont.Item.StrikeThrough = cTrue) then
FontDialog1.Font.Style := FontDialog1.Font.Style + [fsStrikeOut]
else
FontDialog1.Font.Style := FontDialog1.Font.Style - [fsStrikeOut];
if (Cr.SectionFont.Item.Weight <> fwDefault) then
FontDialog1.Font.Style := FontDialog1.Font.Style + [fsBold]
else
FontDialog1.Font.Style := FontDialog1.Font.Style - [fsBold];
end;
if FontDialog1.Execute then
begin
Refresh;
nIndex := lbSections.ItemIndex;
{Update Form}
editName.Text := FontDialog1.Font.Name;
editSize.Text := IntToStr(FontDialog1.Font.Size);
cbItalic.Checked := (fsItalic in FontDialog1.Font.Style);
cbUnderlined.Checked := (fsUnderline in FontDialog1.Font.Style);
cbStrikeThrough.Checked := (fsStrikeOut in FontDialog1.Font.Style);
if fsBold in FontDialog1.Font.Style then
cbWeight.ItemIndex := 7 {fwBold}
else
cbWeight.ItemIndex := 0; {fwDefault}
{Update Font sample text}
lblSample.Font.Name := FontDialog1.Font.Name;
lblSample.Font.Size := FontDialog1.Font.Size;
lblSample.Font.Style := FontDialog1.Font.Style;
lblSample.Caption := FontDialog1.Font.Name;
if lblSample.Font.Size > 0 then
lblSample.Caption := lblSample.Caption + ' ' +
editSize.Text + ' point';
{Update the VCL}
for i := 0 to (lbSections.Items.Count - 1) do
begin
if lbSections.Selected[i] then
begin
Cr.SectionFont[i];
Cr.SectionFont.Item.Name := FontDialog1.Font.Name;
Cr.SectionFont.Item.Size := FontDialog1.Font.Size;
if cbItalic.Checked then
Cr.SectionFont.Item.Italic := cTrue;
if cbUnderlined.Checked then
Cr.SectionFont.Item.Underlined := cTrue;
if cbStrikeThrough.Checked then
Cr.SectionFont.Item.StrikeThrough := cTrue;
if cbWeight.ItemIndex = 7 then
Cr.SectionFont.Item.Weight := fwBold;
end;
end;
lbSections.ItemIndex := nIndex;
Cr.SectionFont[nIndex];
end;
end;
{------------------------------------------------------------------------------}
{ editNameChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFontDlg.editNameChange(Sender: TObject);
begin
Cr.SectionFont.Item.Name := editName.Text;
lblSample.Font.Name := editName.Text;
lblSample.Caption := editName.Text;
if lblSample.Font.Size > 0 then
lblSample.Caption := lblSample.Caption + ' ' +
editSize.Text + ' point';
end;
{------------------------------------------------------------------------------}
{ cbItalicClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFontDlg.cbItalicClick(Sender: TObject);
begin
case cbItalic.State of
cbUnchecked : Cr.SectionFont.Item.Italic := cFalse;
cbChecked : Cr.SectionFont.Item.Italic := cTrue;
cbGrayed : Cr.SectionFont.Item.Italic := cDefault;
end;
if cbItalic.State = cbUnchecked then
lblSample.Font.Style := lblSample.Font.Style - [fsItalic];
if cbItalic.State = cbChecked then
lblSample.Font.Style := lblSample.Font.Style + [fsItalic];
end;
{------------------------------------------------------------------------------}
{ cbUnderlinedClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFontDlg.cbUnderlinedClick(Sender: TObject);
begin
case cbUnderlined.State of
cbUnchecked : Cr.SectionFont.Item.Underlined := cFalse;
cbChecked : Cr.SectionFont.Item.Underlined := cTrue;
cbGrayed : Cr.SectionFont.Item.Underlined := cDefault;
end;
if cbUnderlined.State = cbUnchecked then
lblSample.Font.Style := lblSample.Font.Style - [fsUnderline];
if cbUnderlined.State = cbChecked then
lblSample.Font.Style := lblSample.Font.Style + [fsUnderline];
end;
{------------------------------------------------------------------------------}
{ cbStrikeThroughClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFontDlg.cbStrikeThroughClick(Sender: TObject);
begin
case cbStrikeThrough.State of
cbUnchecked : Cr.SectionFont.Item.StrikeThrough := cFalse;
cbChecked : Cr.SectionFont.Item.StrikeThrough := cTrue;
cbGrayed : Cr.SectionFont.Item.StrikeThrough := cDefault;
end;
if cbStrikeThrough.State = cbUnchecked then
lblSample.Font.Style := lblSample.Font.Style - [fsStrikeOut];
if cbStrikeThrough.State = cbChecked then
lblSample.Font.Style := lblSample.Font.Style + [fsStrikeOut];
end;
{------------------------------------------------------------------------------}
{ cbWeightChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFontDlg.cbWeightChange(Sender: TObject);
begin
Cr.SectionFont.Item.Weight := TCrFontWeight(cbWeight.ItemIndex);
if Cr.SectionFont.Item.Weight = fwBold then
lblSample.Font.Style := lblSample.Font.Style + [fsBold];
if Cr.SectionFont.Item.Weight = fwDefault then
lblSample.Font.Style := lblSample.Font.Style - [fsBold];
end;
{------------------------------------------------------------------------------}
{ cbCharSetChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFontDlg.cbCharSetChange(Sender: TObject);
begin
Cr.SectionFont.Item.CharSet := TCrFontCharSet(cbCharSet.ItemIndex);
end;
{------------------------------------------------------------------------------}
{ cbFamilyChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFontDlg.cbFamilyChange(Sender: TObject);
begin
Cr.SectionFont.Item.Family := TCrFontFamily(cbFamily.ItemIndex);
end;
{------------------------------------------------------------------------------}
{ rgScopeClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFontDlg.rgScopeClick(Sender: TObject);
begin
Cr.SectionFont.Item.Scope := TCrFontScope(rgScope.ItemIndex);
end;
{------------------------------------------------------------------------------}
{ rgPitchClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFontDlg.rgPitchClick(Sender: TObject);
begin
Cr.SectionFont.Item.Pitch := TFontPitch(rgPitch.ItemIndex);
lblSample.Font.Pitch := Cr.SectionFont.Item.Pitch;
end;
{------------------------------------------------------------------------------}
{ editSizeKeyPress procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFontDlg.editSizeKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then
begin
Key := #0;
Perform(wm_NextDlgCtl,0,0);
end;
end;
{------------------------------------------------------------------------------}
{ editSizeExit procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFontDlg.editSizeExit(Sender: TObject);
var
i : integer;
begin
try
i := StrToInt(editSize.Text);
Cr.SectionFont.Item.Size := i;
lblSample.Font.Size := i;
lblSample.Caption := editName.Text;
if lblSample.Font.Size > 0 then
lblSample.Caption := lblSample.Caption + ' ' +
editSize.Text + ' point';
except
MessageDlg('Size value must be numeric!', mtWarning, [mbOk], 0);
editSize.SetFocus;
editSize.SelLength := Length(editSize.Text);
end;
end;
{------------------------------------------------------------------------------}
{ btnClearClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFontDlg.btnClearClick(Sender: TObject);
begin
Cr.SectionFont.Clear;
UpdateSectionFont;
end;
{------------------------------------------------------------------------------}
{ btnOkClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFontDlg.btnOkClick(Sender: TObject);
begin
SaveFormPos(Self);
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFontDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
bSectionFont := False;
Release;
end;
end.
|
unit UMensagens;
interface
resourcestring
//Geral
STR_ATENCAO = 'Atenção';
STR_CAPTION_ABA_CONSULTAS = '%d - %s...';
STR_TODOS = 'Todos';
STR_ATUALIZADO = 'atualizado(a)';
STR_GRAVADO = 'gravado(a)';
STR_EXCLUIDO = 'excluido(a)';
STR_OPERACAO_COM_SUCESSO = '%s com código %d %s com sucesso.';
STR_ENTIDADE_NAO_ENCONTRADA = '%s com código %d não foi encontrado(a)';
//Entidade
STR_ENTIDADE_GRAVADA_COM_SUCESSO = '%s gravado(a) com sucesso! Código gerado: %d.';
STR_ENTIDADE_ATUALIZADO_COM_SUCESSO = '%s atualizado(a) com sucesso!';
STR_ENTIDADE_DESEJA_EXCLUIR = 'Deseja realmente excluir este(a) %s?';
//CRUD
STR_CRUD_CABECALHO = 'Cadastro de %s';
//Transação
STR_JA_EXISTE_TRANSACAO_ATIVA = 'Não foi possivel abrir uma nova transação! Motivo: Já existe uma transação ativa.';
STR_NAO_EXISTE_TRANSACAO_ATIVA = 'Não foi possivel %s a transação! Motivo: Não existe uma transação ativa.';
STR_VALIDA_TRANSACAO_ATIVA = 'Operação abortada! Motivo: Para realizar esta operação é necessário ter uma transação ativa.';
STR_ABORTAR = 'abortar';
STR_FINALIZAR = 'finalizar';
//Pais
STR_PAIS_NOME_NAO_INFORMADO = 'Nome do País é obrigatório';
//Estado
STR_ESTADO_NOME_NAO_INFORMADO = 'Nome do Estado é obrigatório';
STR_ESTADO_PAIS_NAO_INFORMADO = 'O País é obrigatório';
//Cidade
STR_CIDADE_NOME_NAO_INFORMADO = 'O Nome da Cidade é obrigatório';
STR_CIDADE_ESTADO_NAO_INFORMADO = 'O Estado é obrigatório';
//Marca
STR_MARCA_NOME_NAO_INFORMADA = 'O Nome é obrigatório.';
//Deposito
STR_DEPOSITO_DESCRICAO_NAO_INFORMADO = 'Descrição do depósito é obrigatório.';
STR_DEPOSITO_EMPRESA_NAO_INFORMADA = 'Empresa do depósito é obrigatório.';
//Usuario
STR_SENHA_NAO_SEGURA = 'Senha digitada não é segura, senha deve ter no mínimo %d caracteres';
STR_SENHAS_NAO_CONFEREM = 'Senhas não conferem.';
STR_USUARIO_NOME_NAO_INFORMADO = 'Nome do usuário não foi informado.';
STR_SENHA_ATUAL_NAO_CONFERE = 'Senha atual não confere.';
//Login
STR_USUARIO_OU_SENHA_SAO_INVALIDOS = 'Usuário ou senha são inválidos.';
//Empresa
STR_EMPRESA_NOME_NAO_INFORMADO = 'O Nome da empresa é obrigatório.';
STR_EMPRESA_IE_INVÁLIDO_NULO = 'Inscrição estadual nula ou inválida.';
STR_EMPRESA_LOGRADOURO_NAO_INFORMADO = 'O Logradouro é obrigatório.';
STR_EMPRESA_NUMERO_NAO_INFORMADO = 'O Número é obrigatório';
STR_EMPRESA_BAIRRO_NAO_INFORMADO = 'O Bairro é obrigatório';
STR_EMPRESA_CIDADE_NAO_INFORMADO = 'A Cidade é obrigatória.';
STR_EMPRESA_CNPJ_NAO_INFORMMADO = 'Informe um CNPJ válido.';
STR_EMPRESA_TELEFONE_NAO_INFORMADO = 'O telefone é obrigatório.';
//Status
STR_STATUS_NOME_NAO_INFORMADO = 'Informe o nome do Status';
//Tipo Movimentacao
STR_TIPO_MOVIMENTACAO_NAO_INFORMADO = 'Informe o tipo de Movimentação';
implementation
end.
|
unit MyDBGrid;
(*************************************************************************
----------------------------------------------------
Autor.: Eduardo Silva dos Santos -- DRD SISTEMAS
Data..: 10.04.2007
e-mail: eduardo.drd@gmail.com
----------------------------------------------------
Versão 1.02 14.08.2007
- Adicionada a function GetClientRect: TRect; override; para redimensionar o desenho do rodapé.
Versão 1.01 25.05.2007
- Agora o TMyBDGrid descende do TCRDBGrid da CoreLab
- Adicionada a propriedade AutoFormatFloatFields, para formatar automaticamento campos float.
- Adicionada a propriedade ColorOfSortedColumn, para definir a cor da coluna selecionada para ordenar os registros
Versão 1.00 10.04.2007
- Criado o TMyDBGrid descendente do TDBGrid.
****************************************************************************)
interface
uses
Windows, Messages, Classes, Controls, Forms, Graphics, StdCtrls, SysUtils, Grids, DBGrids, ExtCtrls, FlatSB,
CommCtrl,CRGrid, DB;
type
TMyDBGrid = class(TCRDBGrid)
private
{ Private declarations }
FBorderColor: TColor;
FFormatFloatFields: boolean;
FFormatOfFloatFields: string;
FColorOfSortedColumn:TColor;
procedure WMNCPaint (var Message: TMessage); message WM_NCPAINT;
procedure CMSysColorChange (var Message: TMessage);
procedure CMParentColorChanged (var Message: TWMNoParams);
procedure RedrawBorder (const Clip: HRGN);
procedure KeyDown(var Key: Word;Shift: TShiftState); override;
procedure TitleClick(Column: TColumn); override;
procedure DrawColumnCell(const Rect: TRect; DataCol: integer;Column: TColumn; State: TGridDrawState); override;
protected
{ Protected declarations }
function GetClientRect: TRect; override;
public
{ Public declarations }
constructor Create (AOwner: TComponent); override;
procedure Focar;
published
{ Published declarations }
Property BorderColor:TColor read FBorderColor write FBorderColor Default $008396A0;
Property ColorOfSortedColumn:TColor read FColorOfSortedColumn write FColorOfSortedColumn Default $00CEFFFF;
property FormatFloatFields: boolean read FFormatFloatFields write FFormatFloatFields default True;
property FormatOfFloatFields: string read FFormatOfFloatFields write FFormatOfFloatFields;
property OnKeyDown;
property OnTitleClick;
end;
procedure Register;
implementation
constructor TMyDBGrid.Create (AOwner: TComponent);
begin
inherited Create(AOwner);
Ctl3D := False;
ParentCtl3D := False;
FixedColor := $00C5D6D9;
FBorderColor := $008396A0;
AutoSize := False;
ShowHint := True;
Options := [dgTitles,dgColLines,dgTabs,dgRowSelect,dgAlwaysShowSelection,dgCancelOnExit];
// OptionsEx := OptionsEx + [dgeEnableSort,dgeLocalFilter,dgeLocalSorting];
ReadOnly := True;
FFormatFloatFields := True;
FColorOfSortedColumn := $00CEFFFF;
FFormatOfFloatFields := '#,#0.00';
end;
procedure TMyDBGrid.WMNCPaint (var Message: TMessage);
begin
inherited;
RedrawBorder(HRGN(Message.WParam));
end;
function TMyDBGrid.GetClientRect: TRect;
begin
Result := inherited GetClientRect;
if dgRowLines in options then
Inc(Result.Bottom);
if [dgeSummary,dgeRecordCount] * OptionsEx <> [] then begin
Result.Bottom := Result.Bottom + 18; //para suprimir a barra do rodapé desenhada no CRGRID.PAS
Dec( Result.Bottom ,DefaultRowHeight );
end;
end;
procedure TMyDBGrid.CMSysColorChange (var Message: TMessage);
begin
RedrawBorder(0);
end;
procedure TMyDBGrid.KeyDown(var Key: Word;Shift: TShiftState);
begin
if (Shift = [ssCtrl]) and (Key = 46) then //Desativar o Ctrl + Delete
Key := 0;
inherited KeyDown(Key,Shift);
end;
procedure TMyDBGrid.CMParentColorChanged (var Message: TWMNoParams);
begin
RedrawBorder(0);
end;
procedure TMyDBGrid.TitleClick(Column: TColumn);
var
str : String;
nCount : Integer;
begin
try
for nCount := 0 to Columns.Count - 1 do
if Columns[ nCount ].FieldName <> Column.FieldName then
if (Columns[ nCount ].Font.Color <> clRed) then begin
Columns[ nCount ].Font.Color := clBlack;
Columns[ nCount ].Color := clWhite;
end;
if Column.Font.Color <> clRed then begin
Column.Font.Color := clBlue;
Column.Color := FColorOfSortedColumn;
end;
except
Columns[ 0 ].Font.Color := clBlue;
if Column.Font.Color <> clRed then begin
Column.Font.Color := clBlack;
Column.Color := clWhite;
end;
end;
inherited TitleClick(Column);
end;
procedure TMyDBGrid.RedrawBorder (const Clip: HRGN);
var
DC: HDC;
R: TRect;
BtnFaceBrush, WindowBrush, FocusBrush: HBRUSH;
begin
DC := GetWindowDC(Handle);
try
GetWindowRect(Handle, R);
OffsetRect( R, -R.Left, -R.Top);
BtnFaceBrush := CreateSolidBrush(ColorToRGB(FBorderColor));
WindowBrush := CreateSolidBrush(ColorToRGB( Color ));
FocusBrush := CreateSolidBrush(ColorToRGB( Color ));
if (not(csDesigning in ComponentState) and (Focused or (not(Screen.ActiveControl is TMyDBGRID)))) then begin { Focus }
FrameRect(DC, R, BtnFaceBrush);
InflateRect(R, -1, -1);
FrameRect(DC, R, FocusBrush);
InflateRect(R, 0, 0);
FrameRect(DC, R, FocusBrush);
if ScrollBars = ssBoth then
FillRect(DC, Rect(R.Right - 17, R.Bottom - 17, R.Right - 1, R.Bottom - 1), FocusBrush);
end else begin { non Focus }
FrameRect(DC, R, BtnFaceBrush);
InflateRect(R, -1, -1);
FrameRect(DC, R, WindowBrush);
InflateRect( R, 0, 0);
FrameRect(DC, R, WindowBrush);
if ScrollBars = ssBoth then
FillRect(DC, Rect(R.Right - 17, R.Bottom - 17, R.Right - 1, R.Bottom - 1), WindowBrush);
end;
finally
ReleaseDC(Handle, DC);
end;
DeleteObject(WindowBrush);
DeleteObject(BtnFaceBrush);
DeleteObject(FocusBrush);
end;
procedure TMyDBGrid.DrawColumnCell(const Rect: TRect; DataCol: integer;Column: TColumn; State: TGridDrawState);
begin
if Assigned( Column.Field ) then
if (Column.Field.DataType in [ftFloat]) and FFormatFloatFields then
TFloatField( Column.Field ).DisplayFormat := FFormatOfFloatFields;
inherited;
end;
procedure TMyDBGrid.Focar;
begin
if CanFocus then
SetFocus;
end;
procedure Register;
begin
RegisterComponents('ARTHUS', [TMyDBGrid]);
end;
end.
|
unit FastBMP;
interface // TFastBMP v1.5
// Gordon Alex Cowie <gfody@jps.net>
uses Windows, // www.jps.net/gfody
FastRGB; //
// This unit is Freeware. Comments, Ideas,
const // Optimizations, Corrections, and Effects
{$IFDEF VER90} // are welcome. See FastLIB.hlp for a brief
hSection=nil; // documentation. (4/14/99)
{$ELSE}
hSection=0;
{$ENDIF}
type
TFastBMP=class(TFastRGB)
hDC,
Handle: Integer;
bmInfo: TBitmapInfo;
constructor Create;
destructor Destroy; override;
// initializers
procedure SetSize(fWidth,fHeight:Integer); override;
procedure LoadFromFile(FileName:string);
procedure SaveToFile(FileName:string);
procedure LoadFromhBmp(hBmp:Integer);
procedure LoadFromRes(hInst:Integer;sName:string);
procedure SetInterface(fWidth,fHeight:Integer;pBits:Pointer);
procedure Copy(FB:TFastBMP);
// GDI drawing methods
procedure Draw(fdc,x,y:Integer); override;
procedure Stretch(fdc,x,y,w,h:Integer); override;
procedure DrawRect(fdc,x,y,w,h,sx,sy:Integer); override;
procedure StretchRect(fdc,x,y,w,h,sx,sy,sw,sh:Integer); override;
procedure TileDraw(fdc,x,y,w,h:Integer); override;
// native conversions
procedure Resize(Dst:TFastRGB); override;
procedure SmoothResize(Dst:TFastRGB); override;
procedure CopyRect(Dst:TFastRGB;x,y,w,h,sx,sy:Integer); override;
procedure Tile(Dst:TFastRGB); override;
function CountColors:Longint;
end;
implementation
constructor TFastBMP.Create;
begin
hDC:=CreateCompatibleDC(0);
Width:=0; Height:=0; Bits:=nil; Pixels:=nil;
bmInfo.bmiHeader.biSize:=SizeOf(TBitmapInfoHeader);
bmInfo.bmiHeader.biPlanes:=1;
bmInfo.bmiHeader.biBitCount:=24;
bmInfo.bmiHeader.biCompression:=BI_RGB;
end;
destructor TFastBMP.Destroy;
begin
DeleteDC(hDC);
DeleteObject(Handle);
FreeMem(Pixels);
inherited Destroy;
end;
procedure TFastBMP.SetSize(fWidth,fHeight:Integer);
var
x: Longint;
i: Integer;
begin
if(fWidth=Width)and(fHeight=Height)then Exit;
Width:=fWidth; Height:=fHeight;
bmInfo.bmiHeader.biWidth:=Width;
bmInfo.bmiHeader.biHeight:=Height;
Handle:=CreateDIBSection(0,bmInfo,DIB_RGB_COLORS,Bits,hSection,0);
DeleteObject(SelectObject(hDC,Handle));
RowInc:=((Width*24+31)shr 5)shl 2;
Gap:=Width mod 4;
Size:=RowInc*Height;
GetMem(Pixels,Height*4);
x:=Longint(Bits);
for i:=0 to Height-1 do
begin
Pixels[i]:=Pointer(x);
Inc(x,RowInc);
end;
end;
procedure TFastBMP.LoadFromFile(FileName:string);
type
TByteArray = array[0..0]of Byte;
PByteArray =^TByteArray;
TBMInfo256 = record
bmiHeader: TBitmapInfoHeader;
bmiColors: array[0..255]of TRGBQuad;
end;
var
hFile,
bSize: Integer;
iRead: Cardinal;
fData: TofStruct;
fHead: TBitmapFileHeader;
fInfo: TBMInfo256;
fBits: PByteArray;
begin
hFile:=OpenFile(PChar(FileName),fData,OF_READ);
ReadFile(hFile,fHead,SizeOf(fHead),iRead,nil);
ReadFile(hFile,fInfo,SizeOf(fInfo),iRead,nil);
SetFilePointer(hFile,fHead.bfOffBits,nil,FILE_BEGIN);
SetSize(fInfo.bmiHeader.biWidth,Abs(fInfo.bmiHeader.biHeight));
bSize:=(((fInfo.bmiHeader.biWidth*fInfo.bmiHeader.biBitCount+31)shr 5)shl 2)*fInfo.bmiHeader.biHeight;
GetMem(fBits,bSize);
ReadFile(hFile,fBits^,bSize,iRead,nil);
StretchDIBits(hDC,0,0,Width,Height,0,0,Width,Height,fBits,PBitmapInfo(@fInfo)^,DIB_RGB_COLORS,SRCCOPY);
FreeMem(fBits);
CloseHandle(hFile);
end;
procedure TFastBMP.SaveToFile(FileName:string);
type
TByteArray = array[0..0]of Byte;
PByteArray =^TByteArray;
var
hFile: Integer;
iWrote: Cardinal;
fData: TofStruct;
fHead: TBitmapFileHeader;
begin
// saves upside down.. just Flop from FastFX if you want
hFile:=OpenFile(PChar(FileName),fData,OF_CREATE or OF_WRITE);
fHead.bfType:=19778; // "BM"
fHead.bfSize:=SizeOf(fHead)+SizeOf(bmInfo)+Size;
fHead.bfOffBits:=SizeOf(fHead)+SizeOf(bmInfo);
WriteFile(hFile,fHead,SizeOf(fHead),iWrote,nil);
bmInfo.bmiHeader.biHeight:=Abs(bmInfo.bmiHeader.biHeight);
WriteFile(hFile,bmInfo,SizeOf(bmInfo),iWrote,nil);
bmInfo.bmiHeader.biHeight:=-bmInfo.bmiHeader.biHeight;
WriteFile(hFile,PByteArray(Bits)^,Size,iWrote,nil);
CloseHandle(hFile);
end;
procedure TFastBMP.LoadFromhBmp(hBmp:Integer);
var
Bmp: TBitmap;
memDC: Integer;
begin
GetObject(hBmp,SizeOf(Bmp),@Bmp);
SetSize(Bmp.bmWidth,Bmp.bmHeight);
memDC:=CreateCompatibleDC(0);
SelectObject(memDC,hBmp);
GetDIBits(memDC,hBmp,0,Height,Bits,bmInfo,DIB_RGB_COLORS);
DeleteDC(memDC);
end;
procedure TFastBMP.LoadFromRes(hInst:Integer;sName:string);
var
hBmp: Integer;
begin
hBmp:=LoadImage(hInst,PChar(sName),IMAGE_BITMAP,0,0,0);
LoadFromhBmp(hBmp);
DeleteObject(hBmp);
end;
procedure TFastBMP.SetInterface(fWidth,fHeight:Integer;pBits:Pointer);
var
x: Longint;
i: Integer;
begin
Width:=fWidth;
Height:=Abs(fHeight);
bmInfo.bmiHeader.biWidth:=fWidth;
bmInfo.bmiHeader.biHeight:=fHeight;
RowInc:=((Width*24+31)shr 5)shl 2;
Gap:=Width mod 4;
Size:=RowInc*Height;
ReallocMem(Pixels,Height*4);
Bits:=pBits;
x:=Longint(Bits);
for i:=0 to fHeight-1 do
begin
Pixels[i]:=Pointer(x);
Inc(x,RowInc);
end;
end;
procedure TFastBMP.Copy(FB:TFastBMP);
begin
SetSize(FB.Width,FB.Height);
CopyMemory(Bits,FB.Bits,Size);
end;
procedure TFastBMP.Draw(fdc,x,y:Integer);
begin
StretchDIBits(fdc,x,y,Width,Height,0,0,Width,
Height,Bits,bmInfo,DIB_RGB_COLORS,SRCCOPY);
end;
procedure TFastBMP.Stretch(fdc,x,y,w,h:Integer);
begin
SetStretchBltMode(fdc,STRETCH_DELETESCANS);
StretchDIBits(fdc,x,y,w,h,0,0,Width,Height,
Bits,bmInfo,DIB_RGB_COLORS,SRCCOPY);
end;
procedure TFastBMP.DrawRect(fdc,x,y,w,h,sx,sy:Integer);
begin
StretchDIBits(fdc,x,y,w,h,sx,sy,w,h,
Bits,bmInfo,DIB_RGB_COLORS,SRCCOPY);
end;
procedure TFastBMP.StretchRect(fdc,x,y,w,h,sx,sy,sw,sh:Integer);
begin
SetStretchBltMode(fdc,STRETCH_DELETESCANS);
StretchDIBits(fdc,x,y,w,h,sx,sy,sw,sh,
Bits,bmInfo,DIB_RGB_COLORS,SRCCOPY);
end;
procedure TFastBMP.TileDraw(fdc,x,y,w,h:Integer);
var
wd,hd,
hBmp,
memDC: Integer;
begin
if(Width=0)or(Height=0)then Exit;
memDC:=CreateCompatibleDC(fdc);
hBmp:=CreateCompatibleBitmap(fdc,w,h);
SelectObject(memDC,hBmp);
Draw(memDC,0,0);
wd:=Width;
hd:=Height;
while wd<w do
begin
BitBlt(memDC,wd,0,wd*2,h,memDC,0,0,SRCCOPY);
Inc(wd,wd);
end;
while hd<h do
begin
BitBlt(memDC,0,hd,w,hd*2,memDC,0,0,SRCCOPY);
Inc(hd,hd);
end;
BitBlt(fdc,x,y,w,h,memDC,0,0,SRCCOPY);
DeleteDC(memDC);
DeleteObject(hBmp);
end;
procedure TFastBMP.Resize(Dst:TFastRGB);
var
xCount,
yCount,
x,y,xP,yP,
xD,yD,
yiScale,
xiScale: Integer;
xScale,
yScale: Single;
Read,
Line: PLine;
Tmp: TFColor;
pc: PFColor;
begin
if(Dst.Width=0)or(Dst.Height=0)then Exit;
if(Dst.Width=Width)and(Dst.Height=Height)then
begin
CopyMemory(Dst.Bits,Bits,Size);
Exit;
end;
xScale:=Dst.Width/Width;
yScale:=Dst.Height/Height;
if(xScale<1)or(yScale<1)then
begin // shrinking
xiScale:=(Width shl 16) div Dst.Width;
yiScale:=(Height shl 16) div Dst.Height;
yP:=0;
for y:=0 to Dst.Height-1 do
begin
xP:=0;
read:=Pixels[yP shr 16];
pc:=@Dst.Pixels[y,0];
for x:=0 to Dst.Width-1 do
begin
pc^:=Read[xP shr 16];
Inc(pc);
Inc(xP,xiScale);
end;
Inc(yP,yiScale);
end;
end
else // zooming
begin
yiScale:=Round(yScale+0.5);
xiScale:=Round(xScale+0.5);
GetMem(Line,Dst.Width*3);
for y:=0 to Height-1 do
begin
yP:=Trunc(yScale*y);
Read:=Pixels[y];
for x:=0 to Width-1 do
begin
xP:=Trunc(xScale*x);
Tmp:=Read[x];
for xCount:=0 to xiScale-1 do
begin
xD:=xCount+xP;
if xD>=Dst.Width then Break;
Line[xD]:=Tmp;
end;
end;
for yCount:=0 to yiScale-1 do
begin
yD:=yCount+yP;
if yD>=Dst.Height then Break;
CopyMemory(Dst.Pixels[yD],Line,Dst.Width*3);
end;
end;
FreeMem(Line);
end;
end;
// huge thanks to Vit Kovalcik for this awesome function!
// performs a fast bilinear interpolation <vkovalcik@iname.com>
procedure TFastBMP.SmoothResize(Dst:TFastRGB);
var
x,y,xP,yP,
yP2,xP2: Integer;
Read,Read2: PLine;
t,z,z2,iz2: Integer;
pc:PFColor;
w1,w2,w3,w4: Integer;
Col1,Col2: PFColor;
begin
if(Dst.Width<1)or(Dst.Height<1)then Exit;
if Width=1 then
begin
Resize(Dst);
Exit;
end;
if(Dst.Width=Width)and(Dst.Height=Height)then
begin
CopyMemory(Dst.Bits,Bits,Size);
Exit;
end;
xP2:=((Width-1)shl 15)div Dst.Width;
yP2:=((Height-1)shl 15)div Dst.Height;
yP:=0;
for y:=0 to Dst.Height-1 do
begin
xP:=0;
Read:=Pixels[yP shr 15];
if yP shr 16<Height-1 then
Read2:=Pixels[yP shr 15+1]
else
Read2:=Pixels[yP shr 15];
pc:=@Dst.Pixels[y,0];
z2:=yP and $7FFF;
iz2:=$8000-z2;
for x:=0 to Dst.Width-1 do
begin
t:=xP shr 15;
Col1:=@Read[t];
Col2:=@Read2[t];
z:=xP and $7FFF;
w2:=(z*iz2)shr 15;
w1:=iz2-w2;
w4:=(z*z2)shr 15;
w3:=z2-w4;
pc.b:=
(Col1.b*w1+PFColor(Integer(Col1)+3).b*w2+
Col2.b*w3+PFColor(Integer(Col2)+3).b*w4)shr 15;
pc.g:=
(Col1.g*w1+PFColor(Integer(Col1)+3).g*w2+
Col2.g*w3+PFColor(Integer(Col2)+3).g*w4)shr 15;
pc.r:=
(Col1.r*w1+PFColor(Integer(Col1)+3).r*w2+
Col2.r*w3+PFColor(Integer(Col2)+3).r*w4)shr 15;
Inc(pc);
Inc(xP,xP2);
end;
Inc(yP,yP2);
end;
end;
procedure TFastBMP.CopyRect(Dst:TFastRGB;x,y,w,h,sx,sy:Integer);
var
n1,n2: Pointer;
i: Integer;
begin
if x<0 then
begin
Dec(sx,x);
Inc(w,x);
x:=0;
end;
if y<0 then
begin
Dec(sy,y);
Inc(h,y);
y:=0;
end;
if sx<0 then
begin
Dec(x,sx);
Inc(w,sx);
sx:=0;
end;
if sy<0 then
begin
Dec(y,sy);
Inc(h,sy);
sy:=0;
end;
if(sx>Width-1)or(sy>Height-1)then Exit;
if sx+w>Width then Dec(w,(sx+w)-(Width));
if sy+h>Height then Dec(h,(sy+h)-(Height));
if x+w>Dst.Width then Dec(w,(x+w)-(Dst.Width));
if y+h>Dst.Height then Dec(h,(y+h)-(Dst.Height));
n1:=@Dst.Pixels[y,x];
n2:=@Pixels[sy,sx];
for i:=0 to h-1 do
begin
CopyMemory(n1,n2,w*3);
n1:=Ptr(Integer(n1)+Dst.RowInc);
n2:=Ptr(Integer(n2)+RowInc);
end;
end;
procedure TFastBMP.Tile(Dst:TFastRGB);
var
w,h,cy,cx: Integer;
begin
if(Dst.Width=0)or(Dst.Height=0)or
(Width=0)or(Height=0)then Exit;
CopyRect(Dst,0,0,Width,Height,0,0);
w:=Width;
h:=Height;
cx:=Dst.Width;
cy:=Dst.Height;
while w<cx do
begin
Dst.CopyRect(Dst,w,0,w*2,h,0,0);
Inc(w,w);
end;
while h<cy do
begin
Dst.CopyRect(Dst,0,h,w,h*2,0,0);
Inc(h,h);
end;
end;
// Vit's function, accurate to 256^3!
function TFastBMP.CountColors:Longint;
type
TSpace = array[0..255,0..255,0..31]of Byte;
PSpace =^TSpace;
var
x,y: Integer;
Tmp: PFColor;
Count: Longint;
Buff: PByte;
Test: Byte;
Space: PSpace;
begin
New(Space);
FillChar(Space^,SizeOf(TSpace),0);
Tmp:=Bits;
Count:=0;
for y:=0 to Height-1 do
begin
for x:=0 to Width-1 do
begin
Buff:=@Space^[Tmp.r,Tmp.g,Tmp.b shr 3];
Test:=(1 shl(Tmp.b and 7));
if(Buff^ and Test)=0 then
begin
Inc(Count);
Buff^:=Buff^ or Test;
end;
Inc(Tmp);
end;
Tmp:=Ptr(Integer(Tmp)+Gap);
end;
Result:=Count;
Dispose(Space);
end;
end.
|
unit Render;
interface
uses
Types, Classes, Graphics, Style;
type
TNode = class;
TNodeList = class;
TBox = class;
TBoxList = class;
TContext = class;
TRenderer = class;
//
TBox = class
Left: Integer;
Top: Integer;
Width: Integer;
Height: Integer;
Name: string;
Node: TNode;
Text: string;
Boxes: TBoxList;
Context: TDisplay;
constructor Create;
destructor Destroy; override;
end;
//
TBoxList = class(TList)
private
function GetBox(inIndex: Integer): TBox;
procedure SetBox(inIndex: Integer; const Value: TBox);
function GetMax: Integer;
public
property Box[inIndex: Integer]: TBox read GetBox write SetBox; default;
property Max: Integer read GetMax;
end;
//
TNode = class
public
Element: string;
Nodes: TNodeList;
Text: string;
// attributes
// styles
Style: TStyle;
constructor Create; virtual;
destructor Destroy; override;
function NextBox(inContext: TContext;
var inBox: TBox): Boolean; virtual; abstract;
procedure InitBoxes; virtual; abstract;
procedure Render(inRenderer: TRenderer;
const inBox: TBox); virtual; abstract;
end;
//
TNodeList = class(TList)
private
function GetNode(inIndex: Integer): TNode;
procedure SetNode(inIndex: Integer; const Value: TNode);
public
property Node[inIndex: Integer]: TNode read GetNode write SetNode; default;
end;
//
TContext = class
protected
Boxes: TBoxList;
Context: TDisplay;
Pen: TPoint;
Renderer: TRenderer;
Width: Integer;
function BuildBoxes(inNodes: TNodeList;
inIndex: Integer): Integer; virtual;
procedure SetContext; virtual; abstract;
public
constructor Create(inRenderer: TRenderer; inBoxes: TBoxList);
procedure BuildBox(inNode: TNode); virtual; abstract;
end;
//
TContextClass = class of TContext;
//
TBlockContext = class(TContext)
protected
procedure SetContext; override;
public
procedure BuildBox(inNode: TNode); override;
end;
//
TInlineContext = class(TContext)
protected
Line: TBox;
procedure SetContext; override;
function BuildBoxes(inNodes: TNodeList;
inIndex: Integer): Integer; override;
procedure BuildLineBox;
procedure BuildNodeBoxes(inNode: TNode);
function FitNodeText(const inText: string): Integer;
public
procedure BuildBox(inNode: TNode); override;
end;
//
TRenderer = class
private
function BuildContext(inContextClass: TContextClass; inBoxes: TBoxList;
inNodes: TNodeList; inIndex: Integer): Integer;
procedure DoRenderBoxes(inBoxes: TBoxList);
procedure MeasureBox(inBox: TBox);
procedure MeasureBoxes(inBoxes: TBoxList);
procedure RenderBox(inBox: TBox);
procedure RenderNode(inNode: TNode);
procedure RenderNodes(inNodes: TNodeList);
public
Canvas: TCanvas;
Pen: TPoint;
Width, Height: Integer;
function BuildBoxes(inNodes: TNodeList): TBoxList;
procedure Render(inNodes: TNodeList; inCanvas: TCanvas; inRect: TRect);
procedure RenderBoxes(inBoxes: TBoxList);
end;
//
TDivNode = class(TNode)
public
constructor Create; override;
function NextBox(inContext: TContext; var inBox: TBox): Boolean; override;
procedure InitBoxes; override;
procedure Render(inRenderer: TRenderer; const inBox: TBox); override;
end;
//
TTextNode = class(TNode)
private
Cursor: Integer;
TextLength: Integer;
public
constructor Create; override;
function NextBox(inContext: TContext; var inBox: TBox): Boolean; override;
procedure InitBoxes; override;
procedure Render(inRenderer: TRenderer; const inBox: TBox); override;
end;
//
TImageNode = class(TNode)
protected
function ImgHeight: Integer;
function ImgWidth: Integer;
public
Picture: TPicture;
Width, Height: Integer;
constructor Create; override;
function NextBox(inContext: TContext; var inBox: TBox): Boolean; override;
procedure InitBoxes; override;
procedure Render(inRenderer: TRenderer; const inBox: TBox); override;
end;
implementation
uses
Math;
function FitText(inCanvas: TCanvas; inWidth: Integer;
const inText: string): Integer;
var
w, i: Integer;
s: string;
begin
s := inText;
w := inCanvas.TextWidth(s);
if (w <= inWidth) then
Result := -1
else begin
i := 0;
while (w > inWidth) do
begin
i := Length(s);
while (i > 0) and (s[i] <> ' ') do //(Pos(s[i], '- ') < 0) do
Dec(i);
if (i = 0) then
break
else begin
s := Copy(s, 1, i - 1);
w := inCanvas.TextWidth(s);
end;
end;
Result := i;
end;
end;
{ TBox }
constructor TBox.Create;
begin
Boxes := TBoxList.Create;
end;
destructor TBox.Destroy;
begin
Boxes.Free;
inherited;
end;
{ TBoxList }
function TBoxList.GetBox(inIndex: Integer): TBox;
begin
Result := TBox(Items[inIndex]);
end;
function TBoxList.GetMax: Integer;
begin
Result := Pred(Count);
end;
procedure TBoxList.SetBox(inIndex: Integer; const Value: TBox);
begin
Items[inIndex] := Value;
end;
{ TNode }
constructor TNode.Create;
begin
Nodes := TNodeList.Create;
Style := TStyle.Create;
end;
destructor TNode.Destroy;
begin
Nodes.Free;
inherited;
end;
{ TNodeList }
function TNodeList.GetNode(inIndex: Integer): TNode;
begin
Result := TNode(Items[inIndex]);
end;
procedure TNodeList.SetNode(inIndex: Integer; const Value: TNode);
begin
Items[inIndex] := Value;
end;
{ TRenderer }
procedure TRenderer.Render(inNodes: TNodeList; inCanvas: TCanvas;
inRect: TRect);
begin
Canvas := inCanvas;
Width := inRect.Right - inRect.Left;
RenderNodes(inNodes);
//RenderBoxes(inNodes);
end;
procedure TRenderer.RenderNode(inNode: TNode);
{
var
box: TBox;
break: Boolean;
}
begin
{
box := TBox.Create;
try
inNode.InitBoxes;
repeat
box.Left := Pen.X;
box.Top := Pen.Y;
break := inNode.NextBox(Self, box);
if (break) then
begin
Pen.Y := Pen.Y + box.Height;
Pen.X := 0;
end else
Pen.X := Pen.X + box.Width;
//
Canvas.Brush.Color := clBtnFace;
Canvas.Font.Color := clBlack;
inNode.RenderBox(Canvas, box);
until not break;
finally
box.Free;
end;
}
end;
procedure TRenderer.RenderNodes(inNodes: TNodeList);
var
i: Integer;
begin
Pen := Point(0, 0);
for i := 0 to Pred(inNodes.Count) do
RenderNode(inNodes[i]);
end;
function TRenderer.BuildContext(inContextClass: TContextClass;
inBoxes: TBoxList; inNodes: TNodeList; inIndex: Integer): Integer;
var
context: TContext;
begin
context := inContextClass.Create(Self, inBoxes);
try
Result := context.BuildBoxes(inNodes, inIndex);
finally
context.Free;
end;
end;
function TRenderer.BuildBoxes(inNodes: TNodeList): TBoxList;
var
i: Integer;
begin
Result := TBoxList.Create;
i := 0;
while (i < inNodes.Count) do
case inNodes[i].Style.Display of
diBlock: i := BuildContext(TBlockContext, Result, inNodes, i);
diInline: i := BuildContext(TInlineContext, Result, inNodes, i);
else exit;
end;
end;
procedure TRenderer.MeasureBox(inBox: TBox);
function MaxHeight(inBoxes: TBoxList): Integer;
var
i: Integer;
begin
Result := 0;
for i := 0 to Pred(inBoxes.Count) do
Result := Max(inBoxes[i].Height, Result);
end;
function SumHeight(inBoxes: TBoxList): Integer;
var
i: Integer;
begin
Result := 0;
for i := 0 to Pred(inBoxes.Count) do
Result := Result + inBoxes[i].Height;
end;
begin
if (inBox.Height <= 0) and (inBox.Boxes.Count > 0)then
begin
MeasureBoxes(inBox.Boxes);
if (inBox.Boxes[0].Context = diInline) then
inBox.Height := MaxHeight(inBox.Boxes)
else
inBox.Height := SumHeight(inBox.Boxes);
end;
end;
procedure TRenderer.MeasureBoxes(inBoxes: TBoxList);
var
i: Integer;
begin
for i := 0 to Pred(inBoxes.Count) do
MeasureBox(inBoxes[i]);
end;
procedure TRenderer.RenderBox(inBox: TBox);
var
y: Integer;
begin
y := 0;
if inBox.Node <> nil then
inBox.Node.Render(Self, inBox);
if (inBox.Node <> nil) and (inBox.Context = diBlock) then
y := Pen.Y;
DoRenderBoxes(inBox.Boxes);
if (inBox.Node <> nil) and (inBox.Context = diBlock) then
Pen.Y := y;
if ((inBox.Node <> nil) or (inBox.Name='LINE')) and (inBox.Context = diBlock) then
Inc(Pen.Y, inBox.Height);
end;
procedure TRenderer.DoRenderBoxes(inBoxes: TBoxList);
var
i: Integer;
begin
for i := 0 to Pred(inBoxes.Count) do
RenderBox(inBoxes[i]);
end;
procedure TRenderer.RenderBoxes(inBoxes: TBoxList);
begin
Pen.X := 0;
Pen.Y := 0;
MeasureBoxes(inBoxes);
DoRenderBoxes(inBoxes);
end;
{ TContext }
constructor TContext.Create(inRenderer: TRenderer; inBoxes: TBoxList);
begin
Renderer := inRenderer;
Boxes := inBoxes;
Width := Renderer.Width;
SetContext;
end;
function TContext.BuildBoxes(inNodes: TNodeList; inIndex: Integer): Integer;
begin
while (inIndex < inNodes.Count) and
(inNodes[inIndex].Style.Display = Context) do
begin
BuildBox(inNodes[inIndex]);
Inc(inIndex);
end;
Result := inIndex;
end;
{ TBlockContext }
procedure TBlockContext.SetContext;
begin
Context := diBlock;
end;
procedure TBlockContext.BuildBox(inNode: TNode);
var
box: TBox;
begin
box := TBox.Create;
box.Node := inNode;
box.Name := 'BLOCK';
box.Context := diBlock;
box.Boxes.Free;
box.Boxes := Renderer.BuildBoxes(inNode.Nodes);
Boxes.Add(box);
end;
{ TInlineContext }
procedure TInlineContext.SetContext;
begin
Context := diInline;
end;
function TInlineContext.FitNodeText(const inText: string): Integer;
begin
Result := FitText(Renderer.Canvas, Width - Pen.X, inText);
if (Result = 0) and (Pen.X = 0) then
Result := Length(inText);
end;
procedure TInlineContext.BuildLineBox;
begin
Line := TBox.Create;
Line.Width := Renderer.Width;
Line.Name := 'LINE';
Line.Context := diBlock;
Boxes.Add(Line);
end;
procedure TInlineContext.BuildNodeBoxes(inNode: TNode);
var
box: TBox;
wrap: Boolean;
begin
inNode.InitBoxes;
repeat
box := TBox.Create;
box.Left := Pen.X;
box.Top := Pen.Y;
box.Name := 'INLINE';
box.Context := diInline;
box.Node := inNode;
wrap := inNode.NextBox(Self, box);
Line.Boxes.Add(box);
if wrap then
begin
BuildLineBox;
Pen.X := 0;
end else
Pen.X := Pen.X + box.Width;
until not wrap;
end;
procedure TInlineContext.BuildBox(inNode: TNode);
begin
BuildNodeBoxes(inNode);
end;
function TInlineContext.BuildBoxes(inNodes: TNodeList;
inIndex: Integer): Integer;
var
box: TBox;
begin
box := TBox.Create;
box.Name := 'INLINE CONTAINER';
box.Context := diBlock;
Boxes.Add(box);
Boxes := box.Boxes;
BuildLineBox;
Pen.Y := 0;
Result := inherited BuildBoxes(inNodes, inIndex);
end;
{ TTextNode }
constructor TTextNode.Create;
begin
inherited;
end;
procedure TTextNode.InitBoxes;
begin
Cursor := 1;
TextLength := Length(Text);
end;
{
function TTextNode.NextBox(inRenderer: TRenderer;
var inBox: TBox): Boolean;
var
e: Integer;
t: string;
begin
t := Copy(Text, Cursor, MAXINT);
e := inRenderer.FitNodeText(t);
if (e > -1) then
t := Copy(t, 1, e);
//
inBox.Width := inRenderer.Canvas.TextWidth(t);
inBox.Height := inRenderer.Canvas.TextHeight(t);
inBox.Text := t;
//
if (e = -1) then
Cursor := TextLength
else
Inc(Cursor, e);
Result := (Cursor < TextLength);
end;
}
function TTextNode.NextBox(inContext: TContext;
var inBox: TBox): Boolean;
var
e: Integer;
t: string;
begin
t := Copy(Text, Cursor, MAXINT);
e := TInlineContext(inContext).FitNodeText(t);
if (e > -1) then
t := Copy(t, 1, e);
//
inBox.Width := inContext.Renderer.Canvas.TextWidth(t);
inBox.Height := inContext.Renderer.Canvas.TextHeight(t);
inBox.Text := t;
inBox.Name := 'TEXT';
//
if (e = -1) then
Cursor := TextLength
else
Inc(Cursor, e);
Result := (Cursor < TextLength);
end;
{
procedure TTextNode.RenderBox(inCanvas: TCanvas;
const inBox: TBox);
begin
with inBox, inCanvas do
begin
if (Style.BackgroundColor <> clDefault) then
begin
Brush.Style := bsSolid;
Brush.Color := Style.BackgroundColor;
FillRect(Rect(Left, Top, Left + Width, Top + Height));
end;
if (Style.Color <> clDefault) then
Font.Color := Style.Color;
TextOut(Left, Top, Text);
Brush.Style := bsClear;
Rectangle(Left, Top, Left + Width, Top + Height);
end;
end;
}
procedure TTextNode.Render(inRenderer: TRenderer; const inBox: TBox);
var
r: TRect;
begin
with inBox, inRenderer, inRenderer.Canvas do
begin
r := Rect(Left, Top + inRenderer.Pen.Y,
Left + Width, Top + inRenderer.Pen.Y + Height);
if (Style.BackgroundColor <> clDefault) then
begin
Brush.Style := bsSolid;
Brush.Color := Style.BackgroundColor;
FillRect(r);
end;
if (Style.Color <> clDefault) then
Font.Color := Style.Color;
TextOut(r.Left, r.Top, Text);
Brush.Style := bsClear;
Rectangle(r);
end;
end;
{ TDivNode }
constructor TDivNode.Create;
begin
inherited;
Style.Display := diBlock;
Element := 'DIV';
end;
procedure TDivNode.InitBoxes;
begin
//
end;
function TDivNode.NextBox(inContext: TContext; var inBox: TBox): Boolean;
begin
inBox.Width := inContext.Width;
inBox.Height := -1;
inBox.Name := 'DIV';
Result := false;
end;
procedure TDivNode.Render(inRenderer: TRenderer; const inBox: TBox);
begin
end;
{ TImageNode }
constructor TImageNode.Create;
begin
inherited;
Style.Display := diInline;
Element := 'IMG';
Width := -1;
Height := -1;
end;
procedure TImageNode.InitBoxes;
begin
inherited;
end;
function TImageNode.ImgWidth: Integer;
begin
if (Width < 0) then
begin
if (Height >= 0) and (Picture.Height > 0) then
Result := Picture.Width * Height div Picture.Height
else
Result := Picture.Width
end else
Result := Width;
end;
function TImageNode.ImgHeight: Integer;
begin
if (Height < 0) then
begin
if (Width >= 0) and (Picture.Width > 0) then
Result := Picture.Height * Width div Picture.Width
else
Result := Picture.Height
end else
Result := Height;
end;
function TImageNode.NextBox(inContext: TContext; var inBox: TBox): Boolean;
begin
if (Picture <> nil) then
begin
inBox.Width := ImgWidth;
inBox.Height := ImgHeight;
inBox.Name := 'IMG';
end;
Result := false;
end;
procedure TImageNode.Render(inRenderer: TRenderer; const inBox: TBox);
var
r: TRect;
begin
with inBox, inRenderer, inRenderer.Canvas do
begin
r := Rect(Left, Top + inRenderer.Pen.Y,
Left + Width, Top + inRenderer.Pen.Y + Height);
if (Picture <> nil) then
StretchDraw(r, Picture.Graphic);
end;
end;
end.
|
Program SDA3_v17;
const
n = 10;
var
a, b, r: real;
i, p: integer;
y, z: array[1..n] of real;
procedure massivY;
begin
randomize;
readln(a, b);
write('Y: ');
for i:=1 to n do
begin
y[i]:=random * 100 - 50;
write(y[i]:3:0, ' ');
end;
writeln;
end;
procedure massivZ;
begin
write('Z: ');
for i:=1 to n do
begin
if (-15 <= y[i]) and (25 >= y[i]) then
z[i]:=y[i] + a * b
else
z[i]:=2 * a + 3 * b;
write(z[i]:3:0, ' ');
end;
writeln;
end;
procedure resultR;
begin
p:=1;
r:=1;
for i:=1 to n do
begin
R:=r * p * (6 * b * z[i] - sqr(i) * a);
p:=-p;
end;
writeln('R=', r:1:3);
end;
begin
writeln('a,b');
massivY;
massivZ;
resultR;
readln;
end. |
unit MeshConvertQuadsTo48TrisCommand;
interface
uses ControllerDataTypes, ActorActionCommandBase, Actor;
{$INCLUDE source/Global_Conditionals.inc}
type
TMeshConvertQuadsTo48TrisCommand = class (TActorActionCommandBase)
public
constructor Create(var _Actor: TActor; var _Params: TCommandParams); override;
procedure Execute; override;
end;
implementation
uses StopWatch, MeshConvertQuadsTo48Tris, GlobalVars, SysUtils;
constructor TMeshConvertQuadsTo48TrisCommand.Create(var _Actor: TActor; var _Params: TCommandParams);
begin
FCommandName := 'Convert Quads to Triangles';
inherited Create(_Actor,_Params);
end;
procedure TMeshConvertQuadsTo48TrisCommand.Execute;
var
Operation : TMeshConvertQuadsTo48Tris;
{$ifdef SPEED_TEST}
StopWatch : TStopWatch;
{$endif}
begin
{$ifdef SPEED_TEST}
StopWatch := TStopWatch.Create(true);
{$endif}
Operation := TMeshConvertQuadsTo48Tris.Create(FActor.Models[0]^.LOD[FActor.Models[0]^.CurrentLOD]);
Operation.Execute;
Operation.Free;
{$ifdef SPEED_TEST}
StopWatch.Stop;
GlobalVars.SpeedFile.Add('Conversion of quads to triangles (4-8 style) in the LOD takes: ' + FloatToStr(StopWatch.ElapsedNanoseconds) + ' nanoseconds.');
StopWatch.Free;
{$endif}
end;
end.
|
{ Copyright (c) 1985, 87 by Borland International, Inc. }
unit MCLIB;
interface
uses Crt, Dos, MCVars, MCUtil, MCDisply, MCParser;
procedure DisplayCell(Col, Row : Word; Highlighting, Updating : Boolean);
{ Displays the contents of a cell }
function SetOFlags(Col, Row : Word; Display : Boolean) : Word;
{ Sets the overwrite flag on cells starting at (col + 1, row) - returns
the number of the column after the last column set.
}
procedure ClearOFlags(Col, Row : Word; Display : Boolean);
{ Clears the overwrite flag on cells starting at (col, row) }
procedure UpdateOFlags(Col, Row : Word; Display : Boolean);
{ Starting in col, moves back to the last TEXT cell and updates all flags }
procedure DeleteCell(Col, Row : Word; Display : Boolean);
{ Deletes a cell }
procedure SetLeftCol;
{ Sets the value of LeftCol based on the value of RightCol }
procedure SetRightCol;
{ Sets the value of rightcol based on the value of leftcol }
procedure SetTopRow;
{ Figures out the value of toprow based on the value of bottomrow }
procedure SetBottomRow;
{ Figures out the value of bottomrow based on the value of toprow }
procedure SetLastCol;
{ Sets the value of lastcol based on the current value }
procedure SetLastRow;
{ Sets the value of lastrow based on the current value }
procedure ClearLastCol;
{ Clears any data left in the last column }
procedure DisplayCol(Col : Word; Updating : Boolean);
{ Displays a column on the screen }
procedure DisplayRow(Row : Word; Updating : Boolean);
{ Displays a row on the screen }
procedure DisplayScreen(Updating : Boolean);
{ Displays the current screen of the spreadsheet }
procedure RedrawScreen;
{ Displays the entire screen }
procedure FixFormula(Col, Row, Action, Place : Word);
{ Modifies a formula when its column or row designations need to change }
procedure ChangeAutoCalc(NewMode : Boolean);
{ Changes and prints the current AutoCalc value on the screen }
procedure ChangeFormDisplay(NewMode : Boolean);
{ Changes and prints the current formula display value on the screen }
procedure Recalc;
{ Recalculates all of the numbers in the speadsheet }
procedure Act(S : String);
{ Acts on a particular input }
implementation
procedure DisplayCell;
var
Color : Word;
S : IString;
begin
if Updating and
((Cell[Col, Row] = Nil) or (Cell[Col, Row]^.Attrib <> FORMULA)) then
Exit;
S := CellString(Col, Row, Color, DOFORMAT);
if Highlighting then
begin
if Color = ERRORCOLOR then
Color := HIGHLIGHTERRORCOLOR
else
Color := HIGHLIGHTCOLOR;
end;
SetColor(Color);
WriteXY(S, ColStart[Succ(Col - LeftCol)], Row - TopRow + 3);
end; { DisplayCell }
function SetOFlags;
var
Len : Integer;
begin
Len := Length(Cell[Col, Row]^.T) - ColWidth[Col];
Inc(Col);
while (Col <= MAXCOLS) and (Len > 0) and (Cell[Col, Row] = nil) do
begin
Format[Col, Row] := Format[Col, Row] or OVERWRITE;
Dec(Len, ColWidth[Col]);
if Display and (Col >= LeftCol) and (Col <= RightCol) then
DisplayCell(Col, Row, NOHIGHLIGHT, NOUPDATE);
Inc(Col);
end;
SetOFlags := Col;
end; { SetOFlags }
procedure ClearOFlags;
begin
while (Col <= MAXCOLS) and (Format[Col, Row] >= OVERWRITE) and
(Cell[Col, Row] = nil) do
begin
Format[Col, Row] := Format[Col, Row] and (not OVERWRITE);
if Display and (Col >= LeftCol) and (Col <= RightCol) then
DisplayCell(Col, Row, NOHIGHLIGHT, NOUPDATE);
Inc(Col);
end;
end; { ClearOFlags }
procedure UpdateOFlags;
var
Dummy : Word;
begin
while (Cell[Col, Row] = nil) and (Col > 1) do
Dec(Col);
if (Cell[Col, Row]^.Attrib = TXT) and (Col >= 1) then
Dummy := SetOFlags(Col, Row, Display);
end; { UpdateOFlags }
procedure DeleteCell;
var
CPtr : CellPtr;
Size : Word;
begin
CPtr := Cell[Col, Row];
if CPtr = nil then
Exit;
case CPtr^.Attrib of
TXT : begin
Size := Length(CPtr^.T) + 3;
ClearOFlags(Succ(Col), Row, Display);
end;
VALUE : Size := SizeOf(Real) + 2;
FORMULA : Size := SizeOf(Real) + Length(CPtr^.Formula) + 3;
end; { case }
Format[Col, Row] := Format[Col, Row] and (not OVERWRITE);
FreeMem(CPtr, Size);
Cell[Col, Row] := nil;
if Col = LastCol then
SetLastCol;
if Row = LastRow then
SetLastRow;
UpdateOFlags(Col, Row, Display);
Changed := True;
end; { DeleteCell }
procedure SetLeftCol;
var
Col : Word;
Total : Integer;
begin
Total := 81;
Col := 0;
while (Total > LEFTMARGIN) and (RightCol - Col > 0) do
begin
Dec(Total, ColWidth[RightCol - Col]);
if Total > LEFTMARGIN then
ColStart[SCREENCOLS - Col] := Total;
Inc(Col);
end;
if Total > LEFTMARGIN then
Inc(Col);
Move(ColStart[SCREENCOLS - Col + 2], ColStart, Pred(Col));
LeftCol := RightCol - Col + 2;
Total := Pred(ColStart[1] - LEFTMARGIN);
if Total <> 0 then
begin
for Col := LeftCol to RightCol do
Dec(ColStart[Succ(Col - LeftCol)], Total);
end;
PrintCol;
end; { SetLeftCol }
procedure SetRightCol;
var
Total, Col : Word;
begin
Total := Succ(LEFTMARGIN);
Col := 1;
repeat
begin
ColStart[Col] := Total;
Inc(Total, ColWidth[Pred(LeftCol + Col)]);
Inc(Col);
end;
until (Total > 81) or (Pred(LeftCol + Col) > MAXCOLS);
if Total > 81 then
Dec(Col);
RightCol := LeftCol + Col - 2;
PrintCol;
end; { SetRightCol }
procedure SetTopRow;
begin
if BottomRow < ScreenRows then
BottomRow := ScreenRows;
TopRow := Succ(BottomRow - ScreenRows);
PrintRow;
end; { SetTopRow }
procedure SetBottomRow;
begin
if TopRow + ScreenRows > Succ(MAXROWS) then
TopRow := Succ(MAXROWS - ScreenRows);
BottomRow := Pred(TopRow + ScreenRows);
PrintRow;
end; { SetBottomRow }
procedure SetLastCol;
var
Row, Col : Word;
begin
for Col := LastCol downto 1 do
begin
for Row := 1 to LastRow do
begin
if Cell[Col, Row] <> nil then
begin
LastCol := Col;
Exit;
end;
end;
end;
LastCol := 1;
end; { SetLastCol }
procedure SetLastRow;
var
Row, Col : Word;
begin
for Row := LastRow downto 1 do
begin
for Col := 1 to LastCol do
begin
if Cell[Col, Row] <> nil then
begin
LastRow := Row;
Exit;
end;
end;
end;
LastRow := 1;
end; { SetLastRow }
procedure ClearLastCol;
var
Col : Word;
begin
Col := ColStart[Succ(RightCol - LeftCol)] + ColWidth[RightCol];
if (Col < 80) then
Scroll(UP, 0, Col, 3, 80, ScreenRows + 2, White);
end; { ClearLastCol }
procedure DisplayCol;
var
Row : Word;
begin
for Row := TopRow to BottomRow do
DisplayCell(Col, Row, NOHIGHLIGHT, Updating);
end; { DisplayCol }
procedure DisplayRow;
var
Col : Word;
begin
for Col := LeftCol to RightCol do
DisplayCell(Col, Row, NOHIGHLIGHT, Updating);
end; { DisplayRow }
procedure DisplayScreen;
var
Row : Word;
begin
for Row := TopRow to BottomRow do
DisplayRow(Row, Updating);
ClearLastCol;
end; { DisplayScreen }
procedure RedrawScreen;
begin
CurRow := 1;
CurCol := 1;
LeftCol := 1;
TopRow := 1;
SetRightCol;
SetBottomRow;
GotoXY(1, 1);
SetColor(MSGMEMORYCOLOR);
Write(MSGMEMORY);
GotoXY(29, 1);
SetColor(PROMPTCOLOR);
Write(MSGCOMMAND);
ChangeAutocalc(Autocalc);
ChangeFormDisplay(FormDisplay);
PrintFreeMem;
DisplayScreen(NOUPDATE);
end; { RedrawScreen }
procedure FixFormula;
var
FormLen, ColStart, RowStart, CurPos, FCol, FRow : Word;
CPtr : CellPtr;
Value : Real;
S : String[5];
NewFormula : IString;
Good : Boolean;
begin
CPtr := Cell[Col, Row];
CurPos := 1;
NewFormula := CPtr^.Formula;
while CurPos < Length(NewFormula) do
begin
if FormulaStart(NewFormula, CurPos, FCol, FRow, FormLen) then
begin
if FCol > 26 then
begin
RowStart := CurPos + 2;
ColStart := RowStart - 2;
end
else begin
RowStart := Succ(CurPos);
ColStart := Pred(RowStart);
end;
case Action of
COLADD : begin
if FCol >= Place then
begin
if FCol = 26 then
begin
if Length(NewFormula) = MAXINPUT then
begin
DeleteCell(Col, Row, NOUPDATE);
Good := AllocText(Col, Row, NewFormula);
Exit;
end;
end;
S := ColString(FCol);
Delete(NewFormula, ColStart, Length(S));
S := ColString(Succ(FCol));
Insert(S, NewFormula, ColStart);
end;
end;
ROWADD : begin
if FRow >= Place then
begin
if RowWidth(Succ(FRow)) <> RowWidth(FRow) then
begin
if Length(NewFormula) = MAXINPUT then
begin
DeleteCell(Col, Row, NOUPDATE);
Good := AllocText(Col, Row, NewFormula);
Exit;
end;
end;
S := WordToString(FRow, 1);
Delete(NewFormula, RowStart, Length(S));
S := WordToString(Succ(FRow), 1);
Insert(S, NewFormula, RowStart);
end;
end;
COLDEL : begin
if FCol > Place then
begin
S := ColString(FCol);
Delete(NewFormula, ColStart, Length(S));
S := ColString(Pred(FCol));
Insert(S, NewFormula, ColStart);
end;
end;
ROWDEL : begin
if FRow > Place then
begin
S := WordToString(FRow, 1);
Delete(NewFormula, RowStart, Length(S));
S := WordToString(Pred(FRow), 1);
Insert(S, NewFormula, RowStart);
end;
end;
end; { case }
Inc(CurPos, FormLen);
end
else
Inc(CurPos);
end;
if Length(NewFormula) <> Length(CPtr^.Formula) then
begin
Value := CPtr^.FValue;
DeleteCell(Col, Row, NOUPDATE);
Good := AllocFormula(Col, Row, NewFormula, Value);
end
else
CPtr^.Formula := NewFormula;
end; { FixFormula }
procedure ChangeAutoCalc;
var
S : String[15];
begin
if (not AutoCalc) and NewMode then
Recalc;
AutoCalc := NewMode;
if AutoCalc then
S := MSGAUTOCALC
else
S := '';
SetColor(MSGAUTOCALCCOLOR);
GotoXY(73, 1);
Write(S:Length(MSGAUTOCALC));
end; { ChangeAutoCalc }
procedure ChangeFormDisplay;
var
S : String[15];
begin
FormDisplay := NewMode;
if FormDisplay then
S := MSGFORMDISPLAY
else
S := '';
SetColor(MSGFORMDISPLAYCOLOR);
GotoXY(65, 1);
Write(S:Length(MSGFORMDISPLAY));
end; { ChangeFormDisplay }
procedure Recalc;
var
Col, Row, Attrib : Word;
begin
for Col := 1 to LastCol do
begin
for Row := 1 to LastRow do
begin
if ((Cell[Col, Row] <> nil) and (Cell[Col, Row]^.Attrib = FORMULA)) then
begin
Cell[Col, Row]^.FValue := Parse(Cell[Col, Row]^.Formula, Attrib);
Cell[Col, Row]^.Error := Attrib >= 4;
end;
end;
end;
DisplayScreen(UPDATE);
end; { Recalc }
procedure Act;
var
Attrib, Dummy : Word;
Allocated : Boolean;
V : Real;
begin
DeleteCell(CurCol, CurRow, UPDATE);
V := Parse(S, Attrib);
case (Attrib and 3) of
TXT : begin
Allocated := AllocText(CurCol, CurRow, S);
if Allocated then
DisplayCell(CurCol, CurRow, NOHIGHLIGHT, NOUPDATE);
end;
VALUE : Allocated := AllocValue(CurCol, CurRow, V);
FORMULA : Allocated := AllocFormula(CurCol, CurRow, UpperCase(S), V);
end; { case }
if Allocated then
begin
if Attrib >= 4 then
begin
Cell[CurCol, CurRow]^.Error := True;
Dec(Attrib, 4);
end
else
Cell[CurCol, CurRow]^.Error := False;
Format[CurCol, CurRow] := Format[CurCol, CurRow] and (not OVERWRITE);
ClearOFlags(Succ(CurCol), CurRow, UPDATE);
if Attrib = TXT then
Dummy := SetOFlags(CurCol, CurRow, UPDATE);
if CurCol > LastCol then
LastCol := CurCol;
if CurRow > LastRow then
LastRow := CurRow;
if AutoCalc then
Recalc;
end
else
ErrorMsg(MSGLOMEM);
PrintFreeMem;
end; { Act }
begin
end.
|
unit ImportarProduto.Controller.interf;
interface
uses Produto.Model.interf, TESTPRODUTO.Entidade.Model;
type
IImportarProdutoOperacaoController = interface;
IImportarProdutoController = interface
['{75337188-7273-4D5E-85E6-4EBF9BBD15B8}']
function localizar(AValue: Integer): IImportarProdutoController;
function produtoSelecionado: TTESTPRODUTO;
function Importar: IImportarProdutoOperacaoController;
end;
IImportarProdutoOperacaoController = interface
['{8676EBB1-7498-49EB-B1E9-7473B51AB780}']
function importarProdutoController(AValue: IImportarProdutoController)
: IImportarProdutoOperacaoController;
function produtoModel(AValue: IProdutoModel)
: IImportarProdutoOperacaoController;
function produtoSelecionado(AValue: TTESTPRODUTO)
: IImportarProdutoOperacaoController;
function codigoSinapi(AValue: string)
: IImportarProdutoOperacaoController;
function descricao(AValue: string)
: IImportarProdutoOperacaoController;
function unidMedida(AValue: string)
: IImportarProdutoOperacaoController;
function origemPreco(AValue: string)
: IImportarProdutoOperacaoController;
function prMedioSinapi(AValue: Currency)
: IImportarProdutoOperacaoController; overload;
function prMedioSinapi(AValue: string)
: IImportarProdutoOperacaoController; overload;
procedure atualizarDadosDoProduto;
procedure salvarDadosNovoProduto;
function &executar: IImportarProdutoController;
end;
implementation
end.
|
unit IteratorTestApp_U;
// Description:
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls,
SDUFileIterator_U, SDUDirIterator_U, ComCtrls;
type
TIteratorTestApp_F = class(TForm)
edStartDir: TEdit;
Label1: TLabel;
GroupBox1: TGroupBox;
GroupBox2: TGroupBox;
pbCreateDirIterator: TButton;
pbDirIterator: TButton;
pbFileIterator: TButton;
pbCreateFileIterator: TButton;
ckReverseFormat: TCheckBox;
cbRecurseSubDirs: TCheckBox;
pbClear: TButton;
pbExit: TButton;
pbBrowse: TButton;
pbCount: TButton;
SDUDirIterator1: TSDUDirIterator;
RichEdit1: TRichEdit;
ckIncludeDirNames: TCheckBox;
ckOmitStartDirPrefix: TCheckBox;
SDUFileIterator1: TSDUFileIterator;
procedure pbCreateDirIteratorClick(Sender: TObject);
procedure pbDirIteratorClick(Sender: TObject);
procedure pbCreateFileIteratorClick(Sender: TObject);
procedure pbFileIteratorClick(Sender: TObject);
procedure pbExitClick(Sender: TObject);
procedure pbBrowseClick(Sender: TObject);
procedure pbClearClick(Sender: TObject);
procedure pbCountClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
IteratorTestApp_F: TIteratorTestApp_F;
implementation
{$R *.DFM}
{$IFDEF LINUX}
This software is only intended for use under MS Windows
{$ENDIF}
{$WARN UNIT_PLATFORM OFF} // Useless warning about platform - we're already
// protecting against that!
uses FileCtrl;
procedure TIteratorTestApp_F.pbCreateDirIteratorClick(Sender: TObject);
begin
SDUdiriterator1.Directory := edStartDir.text;
SDUdiriterator1.ReverseFormat := ckReverseFormat.checked;
SDUdiriterator1.Reset();
end;
procedure TIteratorTestApp_F.pbDirIteratorClick(Sender: TObject);
var
dirname: string;
begin
dirname := SDUdiriterator1.next();
RichEdit1.lines.add(dirname);
if (dirname = '') then
begin
showmessage('Finished.');
end;
end;
procedure TIteratorTestApp_F.pbCreateFileIteratorClick(Sender: TObject);
begin
SDUfileiterator1.Directory := edStartDir.text;
SDUfileiterator1.RecurseSubDirs := cbRecurseSubDirs.checked;
SDUfileiterator1.IncludeDirNames := ckIncludeDirNames.checked;
SDUfileiterator1.OmitStartDirPrefix := ckOmitStartDirPrefix.checked;
SDUfileiterator1.Reset();
end;
procedure TIteratorTestApp_F.pbFileIteratorClick(Sender: TObject);
var
filename: string;
begin
filename := SDUfileiterator1.next();
RichEdit1.lines.add(filename);
if (filename = '') then
begin
showmessage('Finished.');
end;
end;
procedure TIteratorTestApp_F.pbExitClick(Sender: TObject);
begin
Close();
end;
procedure TIteratorTestApp_F.pbBrowseClick(Sender: TObject);
var
dir: string;
begin
if SelectDirectory('Select starting directory', '', dir) then
begin
edStartDir.text := dir;
end;
end;
procedure TIteratorTestApp_F.pbClearClick(Sender: TObject);
begin
RichEdit1.lines.clear();
end;
procedure TIteratorTestApp_F.pbCountClick(Sender: TObject);
begin
RichEdit1.lines.add(inttostr(SDUfileiterator1.Count()));
end;
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
{$WARN UNIT_PLATFORM ON}
// -----------------------------------------------------------------------------
END.
|
unit ControleDeProgramas.View.Principal;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.ExtCtrls,
Vcl.Buttons,
Router4D.Interfaces,
Router4D;
type
TFormPrincipal = class(TForm, iRouter4DComponent)
pnlMain: TPanel;
pnlMenu: TPanel;
pnlTopo: TPanel;
pnlDocker: TPanel;
pnlPrincipal: TPanel;
SpeedButton1: TSpeedButton;
SpeedButton2: TSpeedButton;
procedure FormCreate(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
private
{ Private declarations }
public
function Render: TForm;
procedure UnRender;
end;
var
FormPrincipal: TFormPrincipal;
implementation
uses
ControleDeProgramas.View.Styles.Colors,
ControleDeProgramas.View.Pages.Principal,
ControleDeProgramas.View.Pages.Filmes;
{$R *.dfm}
procedure TFormPrincipal.FormCreate(Sender: TObject);
begin
pnlPrincipal.Color := Color_BackGround;
TRouter4D.Render<TPagePrincipal>.SetElement(pnlPrincipal,pnlMain );
end;
function TFormPrincipal.Render: TForm;
begin
Result := Self;
end;
procedure TFormPrincipal.SpeedButton1Click(Sender: TObject);
begin
TRouter4D.Render<TPageFilmes>.SetElement(pnlPrincipal,pnlMain );
end;
procedure TFormPrincipal.UnRender;
begin
end;
end.
|
{-------------------------------------------------------------------------------
Copyright 2012 Ethea S.r.l.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-------------------------------------------------------------------------------}
/// <summary>
/// Variant-related utility routines.
/// </summary>
unit EF.VariantUtils;
interface
/// <summary>
/// Converts AVariant to a string, returning '' for null/empty variants.
/// </summary>
function EFVarToStr(const AVariant: Variant): string;
/// <summary>
/// Converts AVariant to a TDateTime, returning 0 for null/empty variants.
/// </summary>
function EFVarToDateTime(const AVariant: Variant): TDateTime;
/// <summary>
/// Converts AVariant to an Integer, returning 0 for null/empty variants.
/// </summary>
function EFVarToInt(const AVariant: Variant): Integer;
/// <summary>
/// Converts AVariant to a Boolean, returning False for null/empty variants.
/// </summary>
function EFVarToBoolean(const AVariant: Variant): Boolean;
/// <summary>
/// Converts AVariant to a Double, returning 0 for null/empty variants.
/// </summary>
function EFVarToFloat(const AVariant: Variant): Double;
/// <summary>
/// Converts AVariant to a Currency, returning 0 for null/empty variants.
/// </summary>
function EFVarToCurrency(const AVariant: Variant): Currency;
/// <summary>Returns True if ATo is greater than or equal to AFrom, and False
/// otherwise.</summary>
/// <remarks>If one or both values are not Null, the function returns
/// True.</remarks>
function IsRange(const AFrom, ATo: Variant): Boolean;
implementation
uses
Variants;
function EFVarToStr(const AVariant: Variant): string;
begin
if VarIsNull(AVariant) or VarIsEmpty(AVariant) then
Result := ''
else
Result := AVariant;
end;
function EFVarToDateTime(const AVariant: Variant): TDateTime;
begin
if VarIsNull(AVariant) or VarIsEmpty(AVariant) then
Result := 0
else
Result := VarToDateTime(AVariant);
end;
function EFVarToInt(const AVariant: Variant): Integer;
begin
if VarIsNull(AVariant) or VarIsEmpty(AVariant) then
Result := 0
else
Result := AVariant;
end;
function EFVarToBoolean(const AVariant: Variant): Boolean;
begin
if VarIsNull(AVariant) or VarIsEmpty(AVariant) then
Result := False
else
Result := AVariant;
end;
function EFVarToFloat(const AVariant: Variant): Double;
begin
if VarIsNull(AVariant) or VarIsEmpty(AVariant) then
Result := 0
else
Result := AVariant;
end;
function EFVarToCurrency(const AVariant: Variant): Currency;
begin
if VarIsNull(AVariant) or VarIsEmpty(AVariant) then
Result := 0
else
Result := AVariant;
end;
function IsRange(const AFrom, ATo: Variant): Boolean;
begin
if VarIsNull(AFrom) or VarIsNull(ATo) then
Result := True
else
Result := AFrom <= ATo;
end;
end.
|
unit uMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls;
type
TMain = class(TForm)
ParseBtn: TButton;
DocLabel: TLabel;
ExpressionEdit: TLabeledEdit;
procedure ParseBtnClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Main: TMain;
implementation
{$R *.dfm}
uses
CalcLexer,
CalcParser;
procedure TMain.ParseBtnClick(Sender: TObject);
var
StringStream: TStringStream;
Lexer: TCalcLexer;
Parser: TCalcParser;
begin
StringStream := TStringStream.Create(ExpressionEdit.Text, TEncoding.UTF8);
try
Lexer := TCalcLexer.Create(StringStream);
try
Parser := TCalcParser.Create(Lexer);
try
Parser.Parse();
finally
Parser.Free();
end;
finally
Lexer.Free();
end;
finally
StringStream.Free();
end;
end;
end.
|
{******************************************************************}
{ SVG style class }
{ }
{ home page : http://www.mwcs.de }
{ email : martin.walter@mwcs.de }
{ }
{ date : 26-04-2005 }
{ }
{ Use of this file is permitted for commercial and non-commercial }
{ use, as long as the author is credited. }
{ This file (c) 2005 Martin Walter }
{ }
{ Thanks to: }
{ Kiriakos Vlahos (Process Stylesheet) }
{ }
{ This Software is distributed on an "AS IS" basis, WITHOUT }
{ WARRANTY OF ANY KIND, either express or implied. }
{ }
{ *****************************************************************}
unit SVGStyle;
interface
uses
System.Classes, System.Contnrs;
type
TStyle = class(TObject)
strict private
FValues: TStrings;
function GetCount: Integer;
procedure PutValues(const Key: string; const Value: string);
function GetValues(const Key: string): string;
procedure PutValuesByNum(const Index: Integer; const Value: string);
function GetValuesByNum(const Index: Integer): string;
procedure PutKey(const Index: Integer; const Key: string);
function GetKey(const Index: Integer): string;
function Dequote(const Value: string): string;
private
FName: string;
strict private
FOnChange: TNotifyEvent;
procedure DoOnChange;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
function Clone: TStyle;
procedure SetValues(const Values: string);
function AddStyle(const Key, Value: string): Integer;
function IndexOf(const Key: string): Integer;
procedure Delete(Index: Integer);
function Remove(const Key: string): Integer;
property Count: Integer read GetCount;
property Values[const Key: string]: string read GetValues write PutValues; default;
property ValuesByNum[const Index: Integer]: string read GetValuesByNum write PutValuesByNum;
property Keys[const Index: Integer]: string read GetKey write PutKey;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
end;
TStyleList = class(TObject)
strict private
FList: TObjectList;
function GetCount: Integer;
function GetStyle(const Index: Integer): TStyle;
procedure PutStyle(const Index: Integer; Style: TStyle);
public
constructor Create;
destructor Destroy; override;
procedure Clear;
function Clone: TStyleList;
procedure Delete(Index: Integer);
function Remove(const Style: TStyle): Integer;
function Add(const AStyle: TStyle): Integer; overload;
function Add(const Name, Values: string): Integer; overload;
function Add(const AStyle: string): Integer; overload;
procedure Insert(Index: Integer; Style: TStyle); overload;
procedure Insert(Index: Integer; const Name, Values: string); overload;
procedure Exchange(Index1, Index2: Integer);
procedure Move(CurIndex, NewIndex: Integer);
function IndexOf(Style: TStyle): Integer;
function GetStyleByName(const Name: string): TStyle;
property Style[const Index: Integer]: TStyle read GetStyle write PutStyle; default;
property Count: Integer read GetCount;
end;
procedure ProcessStyleSheet(Var S: string);
implementation
uses
System.SysUtils, System.StrUtils, System.Character;
{$REGION 'TStyle'}
constructor TStyle.Create;
begin
inherited;
FValues := TStringList.Create;
FValues.NameValueSeparator := '"';
end;
destructor TStyle.Destroy;
begin
FreeAndNil(FValues);
inherited;
end;
procedure TStyle.Clear;
begin
if FValues <> nil then
begin
FValues.Clear;
end;
end;
function TStyle.Clone: TStyle;
begin
Result := TStyle.Create;
Result.FName := FName;
Result.FValues.Assign(FValues);
end;
function TStyle.GetCount: Integer;
begin
Result := FValues.Count;
end;
procedure TStyle.DoOnChange;
begin
if Assigned(FOnChange) then
begin
FOnChange(Self);
end;
end;
procedure TStyle.PutValues(const Key: string; const Value: string);
var
Index: Integer;
begin
Index := IndexOf(Key);
if Index > 0 then
PutValuesByNum(Index, Value)
else
AddStyle(Key, Value);
end;
function TStyle.GetValues(const Key: string): string;
begin
Result := GetValuesByNum(IndexOf(Key));
end;
procedure TStyle.PutValuesByNum(const Index: Integer; const Value: string);
begin
if (Index >= 0) and (Index < FValues.Count) then
FValues.ValueFromIndex[Index] := DeQuote(Value);
end;
function TStyle.GetValuesByNum(const Index: Integer): string;
begin
if (Index >= 0) and (Index < FValues.Count) then
Result := FValues.ValueFromIndex[Index]
else
Result := '';
end;
procedure TStyle.PutKey(const Index: Integer; const Key: string);
begin
if (Index >= 0) and (Index < FValues.Count) then
FValues[Index] := Key + FValues.NameValueSeparator + FValues.ValueFromIndex[Index];
end;
function TStyle.GetKey(const Index: Integer): string;
begin
if (Index >= 0) and (Index < FValues.Count) then
Result := FValues.Names[Index]
else
Result := '';
end;
function TStyle.Dequote(const Value: string): string;
begin
if Value <> '' then
begin
if (Value[1] = '''') and (Value[Length(Value)] = '''') then
Result := Copy(Value, 2, Length(Value) - 2)
else
if (Value[1] = '"') and (Value[Length(Value)] = '"') then
Result := Copy(Value, 2, Length(Value) - 2)
else
Result := Value;
end else
Result := Value;
end;
procedure TStyle.SetValues(const Values: string);
var
C: Integer;
Key: string;
Value: string;
Help: string;
begin
Help := Trim(Values);
while Help <> '' do
begin
C := Pos(';', Help);
if C = 0 then
C := Length(Help) + 1;
Key := Copy(Help, 1, C - 1);
Help := Trim(Copy(Help, C + 1, MaxInt));
C := Pos(':', Key);
if C <> 0 then
begin
Value := Trim(Copy(Key, C + 1, MaxInt));
Key := Trim(Copy(Key, 1, C - 1));
C := IndexOf(Key);
if C = -1 then
FValues.Add(Key + FValues.NameValueSeparator + DeQuote(Value))
else
PutValuesByNum(C, Value);
end;
end;
end;
function TStyle.AddStyle(const Key, Value: string): Integer;
begin
Result := IndexOf(Key);
if Result = -1 then
Result := FValues.Add(Key + FValues.NameValueSeparator + DeQuote(Value))
else
PutValuesByNum(Result, Value);
DoOnChange;
end;
function TStyle.IndexOf(const Key: string): Integer;
begin
for Result := 0 to FValues.Count - 1 do
begin
if FValues.Names[Result] = Key then
Exit;
end;
Result := -1;
end;
procedure TStyle.Delete(Index: Integer);
begin
if (Index >= 0) and (Index < FValues.Count) then
begin
FValues.Delete(Index);
end;
end;
function TStyle.Remove(const Key: string): Integer;
begin
Result := IndexOf(Key);
Delete(Result);
end;
{$ENDREGION}
{$REGION 'TStyleList'}
constructor TStyleList.Create;
begin
inherited;
FList := TObjectList.Create(False);
end;
destructor TStyleList.Destroy;
begin
Clear;
FList.Free;
inherited;
end;
procedure TStyleList.Clear;
begin
while FList.Count > 0 do
begin
TStyle(FList[0]).Free;
FList.Delete(0);
end;
end;
function TStyleList.Clone: TStyleList;
var
C: Integer;
begin
Result := TStyleList.Create;
for C := 0 to FList.Count - 1 do
Result.Add(GetStyle(C).Clone);
end;
function TStyleList.GetCount: Integer;
begin
Result := FList.Count;
end;
function TStyleList.GetStyle(const Index: Integer): TStyle;
begin
if (Index >= 0) and (Index < FList.Count) then
Result := TStyle(FList[Index])
else
Result := nil;
end;
procedure TStyleList.PutStyle(const Index: Integer; Style: TStyle);
begin
if (Index >= 0) and (Index < FList.Count) then
begin
FList[Index].Free;
FList[Index] := Style;
end;
end;
procedure TStyleList.Delete(Index: Integer);
begin
if (Index >= 0) and (Index < FList.Count) then
begin
FList[Index].Free;
FList.Delete(Index);
end;
end;
function TStyleList.Remove(const Style: TStyle): Integer;
begin
Result := IndexOf(Style);
Delete(Result);
end;
function TStyleList.Add(const AStyle: TStyle): Integer;
begin
Result := FList.Add(AStyle);
end;
function TStyleList.Add(const Name, Values: string): Integer;
var
S: TStyle;
begin
S := TStyle.Create;
S.FName := Name;
S.SetValues(Values);
Result := Add(S);
end;
function TStyleList.Add(const AStyle: string): Integer;
var
Name: string;
StyleStr: string;
Values: string;
C: Integer;
D: Integer;
begin
Result := -1;
StyleStr := Trim(AStyle);
if StyleStr = '' then
exit;
for C := 1 to Length(StyleStr) do
begin
if StyleStr[C] = '{' then
begin
for D := Length(StyleStr) downto C + 1 do
begin
if StyleStr[D] = '}' then
begin
Name := Trim(Copy(StyleStr, 1, C - 1));
Values := Copy(StyleStr, C + 1, D - C - 1);
Result := Add(Name, Values);
end;
end;
end;
end;
end;
procedure TStyleList.Insert(Index: Integer; Style: TStyle);
begin
if (Index >= 0) and (Index < FList.Count) then
FList.Insert(Index, Style);
end;
procedure TStyleList.Insert(Index: Integer; const Name, Values: string);
var
S: TStyle;
begin
if (Index >= 0) and (Index < FList.Count) then
begin
S := TStyle.Create;
S.FName := Name;
S.SetValues(Values);
Insert(Index, S);
end;
end;
procedure TStyleList.Exchange(Index1, Index2: Integer);
begin
if (Index1 >= 0) and (Index1 < FList.Count) and
(Index2 >= 0) and (Index2 < FList.Count) then
FList.Exchange(Index1, Index2);
end;
procedure TStyleList.Move(CurIndex, NewIndex: Integer);
begin
if (CurIndex >= 0) and (CurIndex < FList.Count) and
(NewIndex >= 0) and (NewIndex < FList.Count) then
FList.Move(CurIndex, NewIndex);
end;
function TStyleList.IndexOf(Style: TStyle): Integer;
begin
Result := FList.IndexOf(Style);
end;
function TStyleList.GetStyleByName(const Name: string): TStyle;
var
C: Integer;
begin
for C := 0 to FList.Count - 1 do
begin
Result := TStyle(FList[C]);
if Result.FName = Name then
Exit;
end;
Result := nil;
end;
procedure ProcessStyleSheet(Var S: string);
Var
OutS: string;
C: Char;
begin
OutS := '';
for C in S do
begin
{$IF CompilerVersion >= 25.0 }
{$LEGACYIFEND ON}
if C.IsWhiteSpace then Continue;
{$ELSE}
if IsWhiteSpace(C) then Continue;
{$IFEND}
if C = '}' then
OutS := OutS + C + SLineBreak
else
OutS := OutS + C;
end;
S := OutS;
end;
{$ENDREGION}
end.
|
// Copyright (c) 2009, ConTEXT Project Ltd
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// Neither the name of ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
unit fExport;
interface
{$I ConTEXT.inc}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, ColorPicker, ComCtrls, HexEdits,
uCommon, uMultiLanguage, fEditor, SynExportRTF,
SynEditExport, SynExportHTML;
type
TExportFormat = (efNone, efRTF, efHTML);
TfmExport = class(TForm)
btnExport: TButton;
btnCancel: TButton;
labTitle: TLabel;
eTitle: TEdit;
dlgSave: TSaveDialog;
expHTML: TSynExporterHTML;
expRTF: TSynExporterRTF;
dlgFont: TFontDialog;
gbOptions: TGroupBox;
cbSelectedOnly: TCheckBox;
cbCreateFragment: TCheckBox;
cbExportToClipboard: TCheckBox;
gbTextSettings: TGroupBox;
labBackground: TLabel;
labFont: TLabel;
cbBgColor: TColorBtn;
btnSetFont: TButton;
labFontName: TLabel;
procedure FormCreate(Sender: TObject);
procedure btnExportClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btnSetFontClick(Sender: TObject);
private
procedure RefreshFontLabel;
public
ExportFormat :TExportFormat;
Editor :TfmEditor;
end;
implementation
{$R *.DFM}
////////////////////////////////////////////////////////////////////////////////////////////
// Functions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmExport.RefreshFontLabel;
begin
labFontName.Caption:=Format('%s, %dpt',[dlgFont.Font.Name, dlgFont.Font.Size]);
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Buttons
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmExport.btnSetFontClick(Sender: TObject);
begin
if dlgFont.Execute then begin
RefreshFontLabel;
end;
end;
//------------------------------------------------------------------------------------------
procedure TfmExport.btnExportClick(Sender: TObject);
var
Exporter :TSynCustomExporter;
SelectedOnly :boolean;
ok :boolean;
label
EXECUTE_DIALOG;
begin
Exporter:=nil;
case ExportFormat of
efRTF:
begin
dlgSave.DefaultExt:='rtf';
Exporter:=expRTF;
end;
efHTML:
begin
with expHTML do begin
CreateHTMLFragment:=cbCreateFragment.Checked;
end;
dlgSave.DefaultExt:='htm';
Exporter:=expHTML;
end;
end;
SelectedOnly:=cbSelectedOnly.Enabled and cbSelectedOnly.Checked;
ok:=TRUE;
if Assigned(Exporter) then begin
with Exporter do begin
Font.Assign(dlgFont.Font);
Color:=cbBgColor.TargetColor;
dlgSave.Filter:=DefaultFilter;
Title:=eTitle.Text;
ExportAsText:=TRUE;
Highlighter:=Editor.memo.Highlighter;
end;
if SelectedOnly then
Exporter.ExportRange(Editor.memo.Lines, Editor.memo.BlockBegin, Editor.memo.BlockEnd)
else
Exporter.ExportAll(Editor.memo.Lines);
if (cbExportToClipboard.Checked) then begin
Exporter.CopyToClipboard;
end else begin
EXECUTE_DIALOG:
if dlgSave.Execute then begin
if DlgReplaceFile(dlgSave.FileName) then begin
try
Exporter.SaveToFile(dlgSave.FileName);
except
ok:=FALSE;
DlgErrorSaveFile(dlgSave.FileName);
end;
end else
goto EXECUTE_DIALOG;
end;
end;
end;
if ok then Close;
end;
//------------------------------------------------------------------------------------------
procedure TfmExport.btnCancelClick(Sender: TObject);
begin
Close;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Form events
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmExport.FormCreate(Sender: TObject);
begin
mlApplyLanguageToForm(SELF, Name);
ExportFormat:=efNone;
cbBgColor.OtherBtnCaption:=mlStr(ML_OPT_FGBG_CAPT1,'&Custom color');
cbBgColor.AutoBtnCaption:=mlStr(ML_OPT_FGBG_CAPT2,'&Default color');
end;
//------------------------------------------------------------------------------------------
procedure TfmExport.FormShow(Sender: TObject);
begin
cbSelectedOnly.Enabled:=Editor.memo.SelAvail;
cbCreateFragment.Visible:=ExportFormat=efHTML;
cbBgColor.ActiveColor:=Editor.memo.Highlighter.WhitespaceAttribute.Background;
cbBgColor.TargetColor:=cbBgColor.ActiveColor;
// iskopiraj postavke fonta u dlgFont
dlgFont.Font.Assign(Editor.memo.Font);
RefreshFontLabel;
end;
//------------------------------------------------------------------------------------------
end.
|
unit UnitSQLOptimizing;
interface
uses
CmpUnit,
UnitLinksSupport,
uDBEntities,
uDBBaseTypes;
type
TOneSQL = record
Value: string;
IDs: TArInteger;
Tag: Integer;
end;
TSQLList = array of TOneSQL;
const
VALUE_TYPE_ERROR = 0;
VALUE_TYPE_KEYWORDS = 1;
VALUE_TYPE_GROUPS = 2;
VALUE_TYPE_LINKS = 3;
procedure FreeSQLList(var SQLList: TSQLList);
procedure AddQuery(var SQLList: TSQLList; Value: string; ID: Integer);
procedure PackSQLList(var SQLList: TSQLList; ValueType: Integer);
implementation
procedure FreeSQLList(var SQLList: TSQLList);
begin
SetLength(SQLList, 0);
end;
procedure AddQuery(var SQLList: TSQLList; Value: string; ID: Integer);
var
L: Integer;
begin
L := Length(SQLList);
SetLength(SQLList, L + 1);
SQLList[L].Value := Value;
SetLength(SQLList[L].IDs, 1);
SQLList[L].IDs[0] := ID;
end;
procedure PackSQLList(var SQLList: TSQLList; ValueType: Integer);
var
I, J, N, L: Integer;
const
limit = 50;
function Compare(Value1, Value2: string): Boolean;
begin
Result := False;
case ValueType of
VALUE_TYPE_KEYWORDS:
begin
Result := not VariousKeyWords(Value1, Value2);
end;
VALUE_TYPE_GROUPS:
begin
Result := TGroups.CompareGroups(Value1, Value2);
end;
VALUE_TYPE_LINKS:
begin
Result := CompareLinks(Value1, Value2);
end;
end;
end;
procedure Merge(var D: TOneSQL; S: TOneSQL);
var
I: Integer;
begin
for I := 0 to Length(S.IDs) - 1 do
begin
SetLength(D.IDs, Length(D.IDs) + 1);
D.IDs[Length(D.IDs) - 1] := S.IDs[I];
end;
end;
begin
// set tag
for I := Length(SQLList) - 1 downto 0 do
SQLList[I].Tag := 0;
// merge queries
for I := Length(SQLList) - 1 downto 0 do
begin
for J := I - 1 downto 0 do
begin
if (SQLList[I].Tag = 0) and (SQLList[J].Tag = 0) then
if Compare(SQLList[I].Value, SQLList[J].Value) then
begin
Merge(SQLList[J], SQLList[I]);
SQLList[I].Tag := 1;
Break;
end;
end;
end;
// cleaning
for I := Length(SQLList) - 1 downto 0 do
if (SQLList[I].Tag = 1) then
begin
for J := I to Length(SQLList) - 2 do
SQLList[J] := SQLList[J + 1];
SetLength(SQLList, Length(SQLList) - 1);
end;
// alloc to LIMIT (limit = 16)
L := Length(SQLList);
for I := 0 to L - 1 do
begin
while Length(SQLList[I].IDs) > Limit do
begin
N := Length(SQLList);
SetLength(SQLList, N + 1);
SetLength(SQLList[N].IDs, 0);
SQLList[N].Value := SQLList[I].Value;
for J := 1 to 16 do
begin
SetLength(SQLList[N].IDs, Length(SQLList[N].IDs) + 1);
SQLList[N].IDs[Length(SQLList[N].IDs) - 1] := SQLList[I].IDs[Length(SQLList[I].IDs) - J];
end;
SetLength(SQLList[I].IDs, Length(SQLList[I].IDs) - 16);
end;
end;
end;
end.
|
unit U_Principal;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TF_Principal = class(TForm)
Label1: TLabel;
edtNumero: TEdit;
btnCalcular: TButton;
Label2: TLabel;
memoTextoLivre: TMemo;
procedure btnCalcularClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
F_Principal: TF_Principal;
implementation
{$R *.dfm}
uses U_CalculoPrimosThread;
procedure TF_Principal.btnCalcularClick(Sender: TObject);
var
vNovaThread: CalculoPrimosThread;
begin
vNovaThread := CalculoPrimosThread.Create(True);
vNovaThread.FreeOnTerminate := True;
try
vNovaThread.Numero := StrToInt(edtNumero.Text);
vNovaThread.Resume;
except on EConvertError do
begin
vNovaThread.Free;
ShowMessage('Não é um número válido!');
end;
end;
end;
end.
|
unit uBonusEdit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, uFControl, uLabeledFControl, uCharControl,
uFloatControl, uDateControl, uSpravControl, uBoolControl, uFormControl,
uInvisControl, IBase, Up_DMAcception, ActnList, uIntControl, DB,
FIBDataSet, pFIBDataSet, BaseTypes, cxLabel, cxControls, cxContainer,
cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar;
const
WarningCaption='Увага!';
type
TfmBonusEdit = class(TForm)
OkButton: TBitBtn;
CancelButton: TBitBtn;
Percent: TqFFloatControl;
IdRaise: TqFSpravControl;
All_Periods: TqFBoolControl;
Smeta: TqFSpravControl;
Kod_Sm_Pps: TqFSpravControl;
Summa: TqFFloatControl;
Label1: TLabel;
ActionList1: TActionList;
AcceptAction: TAction;
CancelAction: TAction;
NumBonus: TqFIntControl;
PubSprR: TpFIBDataSet;
DateBeg: TcxDateEdit;
DateEnd: TcxDateEdit;
lblDateBeg: TcxLabel;
lblDateEnd: TcxLabel;
procedure IdRaiseOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: string);
procedure SmetaOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: string);
procedure SummaChange(Sender: TObject);
procedure PercentChange(Sender: TObject);
procedure IdRaiseChange(Sender: TObject);
procedure All_PeriodsChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure AcceptActionExecute(Sender: TObject);
procedure CancelActionExecute(Sender: TObject);
procedure FormControlModifyRecordAfterPrepare(Sender: TObject);
procedure NumBonusChange(Sender: TObject);
private
{ Private declarations }
ActDate:TDate;
KeySession:Int64;
EditMode:Boolean;
Id_Calc_Type: Integer;
function CheckData:Boolean;
public
DM: TUPAcceptDM;
constructor Create(AOwner:TComponent; DateFilter:TDate; SessionKey:Int64; IdRaiseIn:Variant; isEdit:boolean;
Dmod:TUPAcceptDM);reintroduce;
end;
var
fmBonusEdit: TfmBonusEdit;
implementation
{$R *.dfm}
uses uCommonSp, GlobalSPR, qfTools;
constructor TfmBonusEdit.Create(Aowner:TComponent; DateFilter:TDate; SessionKey:Int64; IdRaiseIn:Variant; isEdit:Boolean; Dmod:TUPAcceptDM);
begin
inherited Create(AOwner);
ActDate:=DateFilter;
KeySession:=SessionKey;
EditMode:=isEdit;
if EditMode then
begin
if PubSprR.Active then PubSprR.Close;
PubSprR.SQLs.SelectSQL.Text:='SELECT * FROM UP_ACCEPT_BONUS_INFO(:KEY_SESSION, :IN_ID_RAISE, :IN_DATE_BEG)';
PubSprR.ParamByName('KEY_SESSION').AsInt64:=SessionKey;
PubSprR.ParamByName('IN_ID_RAISE').AsInteger:=IdRaiseIn;
PubSprR.ParamByName('IN_DATE_BEG').AsDate:=DateFilter;
PubSprR.Open;
IdRaise.Value:=IdRaiseIn;
IdRaise.DisplayText:=PubSprR['RAISE_NAME'];
if not VarIsNull(PubSprR['PERCENT']) then Percent.Value:=PubSprR['PERCENT']
else Summa.Value:=PubSprR['SUMMA'];
Smeta.Value:=PubSprR['ID_SMET'];
Smeta.DisplayText:=PubSprR['SMETA_TITLE'];
if not VarIsNull(PubSprR['ID_SMET_PPS']) then
begin
Kod_Sm_Pps.Value:=PubSprR['ID_SMET_PPS'];
Kod_Sm_Pps.DisplayText:=PubSprR['SMETA_PPS_TITLE'];
end;
if PubSprR['IS_ALL_PERIODS']=0 then
begin
All_Periods.Value:=False;
All_PeriodsChange(Self);
end;
DateBeg.Date:=PubSprR['DATE_BEG'];
DateEnd.Date:=PubSprR['DATE_END'];
end;
DM:=Dmod;
end;
function TfmBonusEdit.CheckData:Boolean;
var d:TDate;
begin
Result:=True;
if VarIsNull(IdRaise.Value) then
begin
IdRaise.Highlight(True);
IdRaise.SetFocus;
agMessageDlg(WarningCaption, 'Ви не обрали надбавку!', mtInformation, [mbOK]);
Result:=False;
end;
if ((VarIsNull(Percent.Value)) and VarIsNull(Summa.Value)) then
begin
Percent.Highlight(True);
Summa.Highlight(True);
agMessageDlg(WarningCaption, 'Ви не обрали процент або суму!', mtInformation, [mbOK]);
Result:=False;
end;
if (Id_Calc_Type = 2) then
begin
if (VarIsNull(DM.Smets['Smeta_Name'])) then
begin
Smeta.Highlight(True);
agMessageDlg(WarningCaption, 'Ви не обрали джерело фінансування!', mtInformation, [mbOK]);
Result:=False;
end;
end
else if VarIsNull(Smeta.Value) then
begin
Smeta.Highlight(True);
agMessageDlg(WarningCaption, 'Ви не обрали джерело фінансування!', mtInformation, [mbOK]);
Result:=False;
end;
if (All_Periods.Value=False) then
begin
if (DateToStr(DateBeg.Date)='') then
begin
DateBeg.Style.Color:=clRed;
DateBeg.SetFocus;
agMessageDlg(WarningCaption, 'Ви не обрали дату початку!', mtInformation, [mbOK]);
Result:=False;
end
else
begin
try
d:=DateBeg.Date;
except
agMessageDlg(WarningCaption, 'Не вірний формат дати!', mtInformation, [mbOK]);
Result:=False;
end;
end;
if (DateToStr(DateEnd.Date)='') then
begin
DateEnd.Style.Color:=clRed;
DateEnd.SetFocus;
agMessageDlg(WarningCaption, 'Ви не обрали дату кінця!', mtInformation, [mbOK]);
Result:=False;
end
else
begin
try
d:=DateEnd.Date;
except
agMessageDlg(WarningCaption, 'Не вірний формат дати!', mtInformation, [mbOK]);
Result:=False;
end;
end;
end;
end;
procedure TfmBonusEdit.IdRaiseOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: string);
var
sp: TSprav;
begin
// создать справочник
sp := GetSprav('ASUP\SpRaise');
if sp <> nil then
begin
// заполнить входные параметры
with sp.Input do
begin
Append;
FieldValues['DBHandle'] := Integer(DM.DB.Handle);
// модальный показ
FieldValues['ShowStyle'] := 0;
// единичная выборка
FieldValues['Select'] := 1;
FieldValues['Raise_Select_Kind'] := 1;
FieldValues['Actual_Date'] := Date;
Post;
end;
sp.Show;
if (sp.Output <> nil) and not sp.Output.IsEmpty then
begin
Value := sp.Output['Id_Raise'];
DisplayText := sp.Output['Name'];
end;
sp.Free;
end;
end;
procedure TfmBonusEdit.SmetaOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: string);
var
id: variant;
begin
id := GlobalSPR.GetSmets(Owner, TISC_DB_Handle(DM.DB.Handle), Date, psmSmet);
if (VarArrayDimCount(id) > 0) and (id[0] <> Null) then
begin
Value := id[0];
DisplayText := IntToStr(id[3]) + '. ' + id[2];
end;
end;
procedure TfmBonusEdit.SummaChange(Sender: TObject);
begin
if not VarIsNull(Summa.Value) and (Summa.Value > 0) then
begin
Percent.Required := False;
Percent.Clear;
end
else
Percent.Required := True;
end;
procedure TfmBonusEdit.PercentChange(Sender: TObject);
begin
if not VarIsNull(Percent.Value) and (Percent.Value > 0) then
begin
Summa.Required := False;
Summa.Clear;
end
else
Summa.Required := True;
end;
procedure TfmBonusEdit.IdRaiseChange(Sender: TObject);
var
// id_Calc_Type: Integer;
OklSmeta, OklSmetaPps: string;
begin
try
if not VarIsNull(IdRaise.Value) then
begin
DM.RaiseDefaults.Close;
DM.RaiseDefaults.ParamByName('Key_Session').AsInteger := KeySession;
DM.RaiseDefaults.ParamByName('Id_Raise').AsInteger := IdRaise.Value;
DM.RaiseDefaults.Open;
if DM.RaiseDefaults.IsEmpty then Id_Calc_Type := 2
else
begin
//если Id_Calc_Type = 1 или 3, значит гибкая привязка к окладам
if ((DM.RaiseDefaults['Id_Calc_Type'] = 1) or
(DM.RaiseDefaults['Id_Calc_Type'] = 3) or
(DM.RaiseDefaults['Id_Calc_Type'] = 6))
then Id_Calc_Type := DM.RaiseDefaults['Id_Calc_Type'].AsInteger
else Id_Calc_Type := 2;
end;
// заполнить процент по умолчанию для случая добавления
//if not EditMode then
begin
if (not DM.RaiseDefaults.IsEmpty) and (not VarISNUll(DM.RaiseDefaults['Percent']))
then Percent.Value := DM.RaiseDefaults['Percent'];
end;
if (Id_Calc_Type = 2) then // жесткая надбавка - согласно сметам оклада
begin
// сами сметы нам здесь не нужны
Smeta.Value := Null;
Kod_Sm_Pps.Value := Null;
// не требовать их
Smeta.Required := False;
Kod_Sm_Pps.Required := False;
// блокировать ввод
Smeta.Blocked := True;
Kod_Sm_Pps.Blocked := True;
// получить список смет оклада
OklSmeta := '';
OklSmetaPps := '';
DM.Smets.First;
while not DM.Smets.Eof do
begin
if not VarIsNull(DM.Smets['Smeta_Name']) then
if Pos(DM.Smets['Smeta_Name'], OklSmeta) = 0 then
OklSmeta := OklSmeta + DM.Smets['Smeta_Name'] + ', ';
if not VarIsNull(DM.Smets['Smeta_Pps_Name']) then
if Pos(DM.Smets['Smeta_Pps_Name'], OklSmetaPps) = 0 then
OklSmetaPps := OklSmetaPps + DM.Smets['Smeta_Pps_Name'] + ', ';
DM.Smets.Next;
end;
Smeta.DisplayText := 'Згідно фінансування окладу: ' + OklSmeta;
Kod_Sm_Pps.DisplayText := 'Згідно фінансування окладу: ' + OklSmetaPps;
end
else
begin // гибкая надбавка - сметы вводятся
// разблокировать сметы
Smeta.Blocked := False;
Kod_Sm_Pps.Blocked := False;
// требовать ввод основной сметы
Smeta.Required := True;
Smeta.DisplayText := '';
Kod_Sm_Pps.DisplayText := '';
// загрузить из реестра - только для случая добавления записи
if not EditMode then
begin
IdRaise.AutoSaveToRegistry := False;
qFAutoLoadFromRegistry(Self);
IdRaise.AutoSaveToRegistry := True;
end;
end
end;
except
end;
end;
procedure TfmBonusEdit.All_PeriodsChange(Sender: TObject);
begin
if All_Periods.Value then
begin
DateBeg.Visible := False;
DateEnd.Visible := False;
lblDateBeg.Visible:=False;
lblDateEnd.Visible:=False;
end
else
begin
DateBeg.Visible := True;
DateEnd.Visible := True;
lblDateBeg.Visible:=True;
lblDateEnd.Visible:=True;
end;
end;
procedure TfmBonusEdit.FormCreate(Sender: TObject);
begin
{DateBeg.Visible := False;
DateEnd.Visible := False; }
end;
procedure TfmBonusEdit.AcceptActionExecute(Sender: TObject);
begin
if CheckData then
begin
ModalResult:=mrOk;
end;
end;
procedure TfmBonusEdit.CancelActionExecute(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TfmBonusEdit.FormControlModifyRecordAfterPrepare(
Sender: TObject);
begin
IdRaise.Value := IdRaise.Value;
end;
procedure TfmBonusEdit.NumBonusChange(Sender: TObject);
var CalcTypeBon: TpFibDataSet;
begin
if VarIsNull(NumBonus.Value)
then exit;
try
PubSprR.Close;
PubSprR.SQLs.SelectSQL.Text:='select * from sp_raise where Current_Date Between Use_Date_Beg And Use_Date_End and display_order=:display_order';
//PubSprR.Database := dm.DB;
//PubSprR.Transaction := dm.ReadTransaction;
PubSprR.ParamByName('display_order').AsInteger := StrToInt(NumBonus.Value);
PubSprR.Open;
PubSprR.FetchAll;
if PubSprR.RecordCount = 1 then
begin
IdRaise.Value := PubSprR['ID_RAISE'];
IdRaise.DisplayText := PubSprR['FULL_NAME'];
PubSprR.Close;
end
else
begin
IdRaise.Value := Null;
IdRaise.DisplayText := 'надбавку не знайдено!';
end;
except on e: Exception do
ShowMessage(e.Message);
end;
end;
initialization
RegisterClass(TfmBonusEdit);
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.