text stringlengths 14 6.51M |
|---|
(*
* Met … jours une cellule qui est vivante au tours courant. Selon le nombre de cellules adjacentes vivantes
* insŠre 1 ou 0 dans le tableau du prochain tours.
*)
Procedure updateLiving(var tab2 : arr; y, x, nbChild : Integer);
Begin
if(nbChild = 2) OR (nbChild = 3) Then
Begin
tab2[y, x] := 1;
end
Else
Begin
tab2[y, x] := 0;
end;
End;
(*
* Met … jours une cellule qui est morte au tours courant. Selon le nombre de cellules adjacentes vivantes
* insŠre 1 ou 0 dans le tableau du prochain tours.
*)
Procedure updateDead(var tab2 : arr; y, x, nbChild : Integer);
Begin
if(nbChild = 3) Then
Begin
tab2[y, x] := 1;
end
Else
Begin
tab2[y, x] := 0;
end;
End;
(*
* Imprime le tableau du tours courant … l'‚cran.
* Pour des raisons d'optimisations, le tableau est imprim‚ ligne par ligne. Chaque index du tableau est concat‚n‚
* dans une chaine caractŠre qui est ensuite imprim‚ … l'ecran.
*)
Procedure printGrid(tab1 : arr);
var
x, y: Integer;
line : String;
Begin
for y := 0 to height -1 do
begin
line := '';
for x := 0 to width -1 do
begin
if(tab1[y, x] = 1) Then
Begin
line += 'X';
End
Else
Begin
line += ' ';
end;
End;
gotoxy(2, y + 2);
write(line);
end;
end;
(*
* Imprime le contours de l'‚cran.
*)
Procedure printBorder;
var
x, y : Integer;
Begin
for x := 1 to width do
begin
gotoxy(x, 1);
write('*');
gotoxy(x, height + 2);
write('*');
end;
for x := 1 to height + 2 do
begin
gotoxy(1, x);
write('*');
gotoxy(width + 2, x);
write('*');
end;
end;
(*
* Passe le jeu en mode circulaire. Ecris … l'ecran que le mode courant est "circulaire".
*)
Procedure switchToCircularMode(var circu : Boolean);
begin
circu := TRUE;
gotoxy(40, 19);
write('Mode : circulaire ');
end;
(*
* Passe le jeu en mode normal. Ecris … l'ecran que le mode courant est "normal".
*)
Procedure switchToNormalMode(var circu : Boolean);
begin
circu := FALSE;
gotoxy(40, 19);
write('Mode : normal ');
end;
(*
* Imprime les options utilisablent par l'utilisateur sur l'ecran.
*)
Procedure printOptions();
Begin
gotoxy(10, 18);
write('Options : ');
gotoxy(10, 19);
write('1 - Continuer (100 tours)');
gotoxy(10, 20);
write('2 - charger');
gotoxy(10, 21);
write('3 - sauvegarder');
gotoxy(10, 22);
write('4 - mode circulaire');
gotoxy(10, 23);
write('5 - mode normal');
gotoxy(10, 24);
write('6 - Generer grille');
gotoxy(10, 25);
write('7 - Gosper Glider Gun');
gotoxy(10, 26);
write('8 - Placer planeur');
gotoxy(10, 27);
write('9 - Quitter');
gotoxy(40, 18);
write('Saisissez l option :');
end;
(*
* Sauvegarde le tableau du tour courant dans le fichier texte de sauvegarde
* Renvoie faux si une erreur intervient durant la sauvegarde du fichier.
*)
Function save(var tab : arr; path : string) : boolean;
var
s : String;
y, x : Integer;
success : Boolean;
begin
AssignFile(MyFile, path);
success := TRUE;
try
ReWrite(MyFile);
append(MyFile);
for y := 0 to height -1 do
Begin
s := '';
For x := 0 to width -1 do
begin
s += intToStr(tab[y, x]);
End;
WriteLn(MyFile, s);
End;
CloseFile(MyFile);
except
success := FALSE;
end;
save := success;
end;
(*
* Charge une sauvegarde dans le tableau du tours courant.
* Renvoie faux si une erreur intervient du chargement du fichier.
*)
function load(var tab : arr; path : string) : Boolean;
var
s : String;
y, x : Integer;
success : Boolean;
begin
success := TRUE;
try
AssignFile(MyFile, path);
reset(MyFile);
for y := 0 to height -1 do
Begin
readln(MyFile, s);
for x := 1 to width do
Begin
tab[y , x - 1] := strToInt(s[x]);
end;
End;
CloseFile(MyFile);
except
success := FALSE;
end;
load := success;
end;
(*
* Demande un entier … l'utilisateur.
*)
Function askOption: Integer;
var
c : Integer;
Begin
gotoxy(60, 18);
write(' ');
gotoxy(60, 18);
read(c);
askOption := c;
end;
(*
* Charge la grille de sauvegarde dans le tableau du tours courant et l'imprime … l'ecran si le chargement
* s'est effectuer correctement.
*)
Procedure loadGrid(var tab : arr; path : string);
begin
gotoxy(40, 20);
if(NOT load(tab, path)) then
begin
WriteLn('Le chargement du fichier a echouee.. .');
End
else
begin
WriteLn('Fichier charge avec succes ');
printGrid(tab);
end;
end;
(*
* Charge la grille contenant le canon, change le mode … normal
*)
Procedure loadGun(var currTurn : arr; path : string; var circu : boolean);
begin
gotoxy(50, 28);
switchToNormalMode(circu);
loadGrid(currTurn, path);
end;
(*
* Appel la fonction permettant de persister le tableau dans un fichier texte.
* Notifie l'utisateur du succŠs de l'op‚rationoun un echec.
*)
Procedure saveGrid(var tab : arr; path : string);
begin
gotoxy(40, 20);
if(save(tab, path)) then write('Sauvegarde reussie! ') Else write('La sauvegarde a ‚chouee! ');
end;
(*
* GŠnere un tableau de 0 et de 1 compos‚ de valeurs al‚atoires. Imprime le tableau … l'‚cran … la fin du processus.
*)
Procedure generateRandomGrid(var tab : arr);
var
y, x, value : Integer;
Begin
randomize();
for y := 0 to height -1 do
Begin
For x := 0 to width -1 do
begin
value := random(10);
if(value > 1) then
begin
tab[y, x ] := 0;
End
else
begin
tab[y, x ] := 1;
end;
End;
End;
printGrid(tab);
end;
(*
* Demande 2 entiers … l'utilisateurs qui peuvent ˆtre ensuite utilis‚s comme des coordonn‚es x et y.
*)
Procedure askCoord(var x, y : Integer);
Begin
gotoxy(40, 20);
write('Choissiez l absisse : ');
read(x);
gotoxy(40, 21);
write('Choissiez l ordonee : ');
read(y);
gotoxy(40, 20);
write(' ');
gotoxy(40, 21);
write(' ');
end;
(*
* InsŠre un planeur dans le tableau aux coordonn‚es sp‚cifi‚s par l'utilisateur.
*)
Procedure createPlanar(var tab : arr; y, x : Integer);
Begin
tab[y, x + 1] := 1;
tab[y + 1, x + 2] := 1;
tab[y + 2, x] := 1;
tab[y + 2, x + 1] := 1;
tab[y + 2, x + 2] := 1;
gotoxy(40, 20);
write('Planeur cree!');
end;
(*
* Appel les fonctions n‚c‚ss‚ssaires … la cr‚ation d'un planeur. Imprime le tableau en fin de processus.
*)
Procedure placePlanar(var tab : arr);
var
posX, posY : Integer;
begin
askCoord(posX, posY);
if(posX < 0) OR (posX > width - 4) OR (posY < 0) OR (posY > height - 4) Then
Begin
gotoxy(40, 20);
write('Coordonees invalides');
end
else
Begin
createPlanar(tab, posY, posX);
end;
printGrid(tab);
end;
(*
* Renvoie une chaŒne de caractŠre qui contient le chemin jusqu'au dossier o— se trouve l'application (.exe).
*)
Function getPath() : string;
var
i : Integer;
s : string;
begin
s := ParamStr(0);
i := length(s);
while(s[i] <> '\') do
i -= 1;
getPath := copy(s, 1, i);
end; |
unit Core.Ball;
interface
uses
System.SysUtils
, System.Classes
, System.Rtti
{Spring}
, Spring
, Spring.Collections
{BowlingGame}
, Core.Interfaces
;
type
TBallFactory = Class(TInterfacedObject, IBallFactory)
public
function CreateBall(const AFrame: IScoreFrame): IBall;
end;
TBall = Class(TInterfacedObject, IBall)
strict private
FFrame: IScoreFrame;
public
Constructor Create( const AFrame: IScoreFrame );
Destructor Destroy; override;
procedure Roll(const ARollInfo: TRollInfo);
end;
implementation
{ TBall }
constructor TBall.Create( const AFrame: IScoreFrame);
begin
inherited Create;
FFrame := AFrame;
end;
destructor TBall.Destroy;
begin
inherited;
end;
procedure TBall.Roll(const ARollInfo: TRollInfo);
begin
if Assigned( FFrame ) then
FFrame.AddRollInfo( ARollInfo );
end;
{ TBallFactory }
function TBallFactory.CreateBall(const AFrame: IScoreFrame): IBall;
begin
Result := TBall.Create( AFrame );
end;
end.
|
Unit StrUtil;
INTERFACE
Function CopyFromTo(source:string; _From,_To: byte):string;
Procedure TruncStr (var TS:string; From: byte);
Function LastPos (c: char; Str: string): byte;
Function Capitalize(S:String):String; {Capitalize The First Letter Of Each Word}
Function Center (S: String; Len: Byte): String;
Function DelBeg (s: String):string; { delete all spaces from beginning }
Function DelEnd (s: String):string; { delete all spaces from end }
{****************************************************************************}
IMPLEMENTATION
Function JustifyR (S: String; Len: Byte): String;
Begin
JustifyR := S;
if Length(S) < Len then
JustifyR := FillStr(' ',(Len - Length(S))) + S;
End;
{---------------}
Function JustifyL (S: String; Len: Byte): String;
Begin
JustifyL := S;
if Length(S) < Len then
JustifyL := S + FillStr(' ',(Len - Length(S)));
End;
{---------------}
Function BreakSum (R: String; Symb: Char): String;
Var
i, j: Byte;
P, K: String;
Function DelTrash(S: String): String;
var P: string;
i:byte;
Begin
P := '';
For i := 1 to Length(S) do
if (S[i]='.') or IsDigit(S[i]) then
P := P + S[i];
DelTrash := P
End;
Function Reverse(S: String): String;
var P: string;
i:byte;
Begin
P := '';
For i := Length(S) downto 1 do
P := P + S[i];
End;
Begin
P:=Reverse(DelTrash(R));
K:=LeftEnd(P,'.');
j := 0;
For i:=1 to Length(P) do
Begin
if j = 3 then
Begin
K := K + Symb;
j := 0;
End;
K := K + P[i];
Inc(j);
End;
P:=Reverse(K);
if CPos('.', P) = 0 then
P := P + '.00';
BreakSum := P;
End;
{---------------}
Function DelBeg(s: String):string;
var Len: Byte absolute s;
begin
While ((s[1]=' ')or(s[len]=#9))and(Len>0) do Delete(s, 1, 1);
DelBeg:=s;
end;
{---------------}
Function DelEnd(s: String):string;
var Len: Byte absolute s;
begin
While ((s[len]=' ')or(s[len]=#9)) and (Len>0) do Dec(Len);
DelEnd:=s;
end;
{---------------}
Function Center (S: String; Len: Integer): String;
Begin
if Len < Length(S) then
Center:= S
else
Center:= FillStr(' ',(Len - Length(S)) shr 1) + S;
End;
{---------------}
Function Capitalize(S:String):String;
var I:byte;
begin
LoStr(S);
S[1]:=UpCase(S[1]);
For I:=1 to Length(S)-1 do
If (S[I]=' ') or (S[I]='.') then
S[i+1]:=UpCase(S[i+1]);
Capitalize:=S;
end;
END. |
unit CatRegex;
{
Catarinka - Regular Expression and some other useful matching functions
Copyright (c) 2003-2017 Felipe Daragon
License: 3-clause BSD
See https://github.com/felipedaragon/catarinka/ for details
Uses the RegExpr library by Andrey V. Sorokin.
}
interface
{$I Catarinka.inc}
uses
{$IFDEF DXE2_OR_UP}
System.Classes, System.SysUtils;
{$ELSE}
Classes, SysUtils;
{$ENDIF}
function RegExpFind(const s, re: string): string;
function RegExpReplace(const s, re, sreplacement: string): string;
function CatMatch(const substr, s: string): boolean;
function IsValidEmail(email: string): boolean;
implementation
uses CatStrings, RegExpr;
function RegExpReplace(const s, re, sreplacement: string): string;
var
r: TRegExpr;
begin
r := TRegExpr.Create;
try
r.Expression := re;
result := r.Replace(s, sreplacement, true);
finally
r.Free;
end;
end;
function RegExpFind(const s, re: string): string;
var
r: TRegExpr;
begin
result := emptystr;
r := TRegExpr.Create;
try
r.Expression := re;
if r.Exec(s) then
repeat
result := result + r.Match[0] + ', ';
until not r.ExecNext;
finally
r.Free;
end;
end;
function CatMatch(const substr, s: string): boolean;
const
cReEx = 'regexp:';
var
tmpsub: string;
begin
result := false;
tmpsub := substr;
if (pos(cReEx, tmpsub) <> 0) then
begin
tmpsub := after(tmpsub, cReEx);
if (RegExpFind(s, tmpsub) <> emptystr) then
result := true;
end
else
begin
if (pos(tmpsub, s) <> 0) then
result := true;
end;
end;
// Thanks ffert2907
function IsValidEmail(email: string): boolean;
const
charslist = ['_', '-', '.', '0'..'9', 'A'..'Z', 'a'..'z'];
var
Arobasc, lastpoint : boolean;
i, n : integer;
c : char;
begin
n := Length(email);
i := 1;
Arobasc := false;
lastpoint := false;
result := true;
while (i <= n) do begin
c := email[i];
if c = '@' then
begin
if Arobasc then // Only 1 Arobasc
begin
result := false;
exit;
end;
Arobasc := true;
end
else if (c = '.') and Arobasc then // at least 1 . after arobasc
begin
lastpoint := true;
end
else if not(c in charslist) then // valid chars
begin
result := false;
exit;
end;
inc(i);
end;
if not(lastpoint) or (email[n] = '.')then // not finish by . and have a . after arobasc
result := false;
end;
// ------------------------------------------------------------------------//
end.
|
unit UModulo;
interface
uses
SysUtils;
Type
TModulo = class
private
FNombreModulo : string;
FVersion : string; {VERSION DEL MODULO}
FIpFtpDescarga : string; {DIRECCION FTP DESCARGA DEL MODULO}
FPuertoFtpDescarga : word; {PUERTO DEL FTP}
FUsuarioFtpDescarga : string; {USUARIO DEL FTP}
FPasswordFtpDescarga : string; {PASSWORD DEL USUARIO FTP}
FRutaFtpDescarga : string; {RUTA CARPETA DESCARGA DEL MODULO}
FRutaDestino : string; {RUTA LOCAL DONDE SE DESCARGA EL MODULO}
FArchivoEjecutable : string; {NOMBRE DEL ARCHIVO EJECUTABLE}
public
{CONSTRUCTORES}
constructor Create;
destructor Destroy;
{PROPIEDADES}
property NombreModulo : string read FNombreModulo write FNombreModulo;
property Version : string read FVersion write FVersion;
property IpFtpDescarga : string read FIpFtpDescarga write FIpFtpDescarga;
property PuertoFtpDescarga : Word read FPuertoFtpDescarga write FPuertoFtpDescarga;
property UsuarioFtpDescarga : string read FUsuarioFtpDescarga write FUsuarioFtpDescarga;
property PasswordFtpDescarga : string read FPasswordFtpDescarga write FPasswordFtpDescarga;
property RutaFtpDescarga : string read FRutaFtpDescarga write FRutaFtpDescarga;
property RutaDestino : string read FRutaDestino write FRutaDestino;
property ArchivoEjecutable : string read FArchivoEjecutable write FArchivoEjecutable;
end;
implementation
{$REGION 'CONSTRUTOR AND DESTRUCTOR'}
constructor TModulo.Create;
begin
inherited;
end;
destructor TModulo.Destroy;
begin
inherited;
end;
{$ENDREGION}
{$REGION 'GETTERS AND SETTERS'}
{$ENDREGION}
end.
|
unit UMsgFunctions;
interface
uses Windows, Classes;
type
TMsgFunctions = class
private
class procedure MessageButtonClick(Sender: TObject);
published
class procedure Atention(const Message: String);
class procedure AtentionFmt(const Message: string; const Args: array of const);
class procedure Error(const Message: String);
class procedure ErrorFmt(const Message: string; const Args: array of const);
class function MessageButton(const Message: String; Botoes: array of string;
TamanhoBotao : Integer = 105; const ShowMessageInTitle: boolean = True) : Integer;
class function Question(const Message: String; Flags: integer = MB_ICONQUESTION + MB_DEFBUTTON2): boolean;
class function ListChoice(const Items: TStringList; const FormCaption, RdgCaption: string; const DefaultIndex: integer = 0): integer;
end;
implementation
uses Forms, SysUtils, StrUtils, StdCtrls, Controls, ExtCtrls, Math, Graphics,
cxRadioGroup;
{ TMsgFunctions }
class procedure TMsgFunctions.Atention(const Message: String);
begin
Application.MessageBox(PChar(Message), PChar(Format('%s - Atenção', [Application.Title])), MB_ICONWARNING + MB_OK);
end;
class procedure TMsgFunctions.AtentionFmt(const Message: string;
const Args: array of const);
begin
Self.Atention(Format(Message, Args));
end;
class procedure TMsgFunctions.Error(const Message: String);
begin
Application.MessageBox(PChar(Message), PChar(Format('%s - Erro', [Application.Title])), MB_ICONERROR + MB_OK);
end;
class procedure TMsgFunctions.ErrorFmt(const Message: string;
const Args: array of const);
begin
Self.Error(Format(Message, Args));
end;
class function TMsgFunctions.MessageButton(const Message: String;
Botoes: array of string; TamanhoBotao: Integer; const ShowMessageInTitle: boolean): Integer;
var
objForm : TForm;
objBotao : TButton;
objLbl : TLabel;
iPosBot, iTopBot, iQteBot, i : integer;
objBevel : TBevel;
begin
iQteBot := Length(Botoes);
objForm := TForm.Create(nil);
try
objForm.BorderIcons := [biSystemMenu];
objForm.BorderStyle := bsDialog;
objForm.Font.Name := 'Arial';
objForm.Icon := Application.Icon;
objForm.KeyPreview := True;
objForm.Position := poScreenCenter;
objForm.Tag := -1;
objForm.Width := (iQteBot * (TamanhoBotao + 12)) + 10;
iPosBot := 10;
objBevel := TBevel.Create(objForm);
objBevel.Align := alClient;
objBevel.Parent := objForm;
objForm.Caption := IfThen(ShowMessageInTitle, Message, Application.Title);
if ShowMessageInTitle then
begin
objForm.Height := 80;
iTopBot := 16;
end
else
begin
objLbl := TLabel.Create(objForm);
objLbl.Parent := objForm;
objLbl.ParentFont := True;
objLbl.WordWrap := True;
objLbl.SetBounds(10, 4, objForm.Width - 20, 16);
objLbl.Height := objLbl.Canvas.TextHeight(Message);
objLbl.Caption := Message;
objForm.Height := objLbl.Height + 90;
iTopBot := objForm.Height - 65;
end;
for i := 0 to iQteBot - 1 do
begin
objBotao := TButton.Create(objForm);
objBotao.Parent := objForm;
objBotao.Tag := i;
objBotao.Caption := Botoes[i];
objBotao.OnClick := MessageButtonClick;
objBotao.SetBounds(iPosBot, iTopBot, TamanhoBotao, 25);
iPosBot := iPosBot + objBotao.Width + 10;
end;
Result := IfThen(objForm.ShowModal = mrOK, objForm.Tag, -1);
finally
objForm.Free;
end;
end;
class procedure TMsgFunctions.MessageButtonClick(Sender: TObject);
var
objButton: TButton;
begin
if Sender is TButton then
begin
objButton := TButton(Sender);
objButton.Owner.Tag := objButton.Tag;
(objButton.Owner as TForm).ModalResult := mrOK;
end;
end;
class function TMsgFunctions.Question(const Message: String;
Flags: integer): boolean;
begin
Result := Application.MessageBox(PChar(Message), PChar(Format('%s - Pergunta', [Application.Title])), MB_YESNO + Flags) = ID_YES;
end;
{ Mostra janela com Items de RadioButton, e retorna o índice selecionado }
class function TMsgFunctions.ListChoice(const Items: TStringList; const FormCaption, RdgCaption: string; const DefaultIndex: integer = 0): integer;
var
Lista: TStringList;
AForm: TForm;
rdg: TcxRadioGroup;
btnOK, btnCancelar: TButton;
Qt, i: integer;
begin
Lista := Items;
Qt := Lista.Count;
AForm := TForm.Create(Application);
with AForm do
begin
BorderIcons := [biSystemMenu];
BorderStyle := bsSingle;
Font.Name := 'Arial';
Position := poScreenCenter;
Height := IfThen(Lista.Count > 1, (Qt * IfThen(Lista.Count >= 5, 25, 40)) + 48, 100);
Width := 250;
Icon := Application.Icon;
KeyPreview := true;
Caption := IfThen(FormCaption <> '', FormCaption, 'Seleção de Itens');
end;
rdg := TcxRadioGroup.Create(Application);
with rdg do
begin
Parent := AForm;
SetBounds(4, 2, AForm.Width - 14, AForm.Height - 68);
for i := 0 to Lista.Count - 1 do
Properties.Items.Add.Caption := Lista[i];
ItemIndex := DefaultIndex;
Caption := ' ' + RdgCaption + ' ';
end;
btnOK := TButton.Create(AForm);
with btnOK do
begin
Parent := AForm;
Default := true;
Caption := 'O&K';
SetBounds(87, rdg.Height + 5, 75, 25);
ModalResult := mrOK;
end;
btnCancelar := TButton.Create(AForm);
with btnCancelar do
begin
Parent := AForm;
Cancel := true;
Caption := '&Cancelar';
SetBounds(165, rdg.Height + 5, 75, 25);
ModalResult := mrCancel;
end;
Result := -1;
if AForm.ShowModal = mrOK then
Result := rdg.ItemIndex;
btnOK.Free;
AForm.Free;
end;
end.
|
{----------------------------------------------------------------------
DEVIUM Content Management System
Copyright (C) 2004 by DEIV Development Team.
http://www.deiv.com/
$Header: /devium/Devium\040CMS\0402/Source/Products/prodUnitsListForm.pas,v 1.2 2004/04/20 05:13:23 paladin Exp $
------------------------------------------------------------------------}
unit prodUnitsListForm;
interface
uses
Forms, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, DB,
cxDBData, cxGridCustomTableView, cxGridTableView, cxGridDBTableView,
TB2Dock, TB2Toolbar, cxGridLevel, cxClasses, cxControls,
cxGridCustomView, Classes, Controls, cxGrid;
type
TUnitsListForm = class(TForm)
cxGrid1DBTableView1: TcxGridDBTableView;
cxGrid1Level1: TcxGridLevel;
cxGrid1: TcxGrid;
TBDock1: TTBDock;
TBToolbar1: TTBToolbar;
unit_name_id: TcxGridDBColumn;
multiplier: TcxGridDBColumn;
weight: TcxGridDBColumn;
private
{ Private declarations }
public
{ Public declarations }
end;
function GetUnitsListForm: Integer;
implementation
uses progDataModule;
{$R *.dfm}
function GetUnitsListForm: Integer;
var
Form: TUnitsListForm;
begin
Form := TUnitsListForm.Create(Application);
try
Result := Form.ShowModal;
finally
Form.Free;
end;
end;
end.
|
unit CkByteData;
interface
type
HCkByteData = Pointer;
HCkString = Pointer;
function CkByteData_Create: HCkByteData; stdcall;
procedure CkByteData_Dispose(handle: HCkByteData); stdcall;
function CkByteData_getSecureClear(objHandle: HCkByteData): wordbool; stdcall;
procedure CkByteData_putSecureClear(objHandle: HCkByteData; newPropVal: wordbool); stdcall;
procedure CkByteData_append(objHandle: HCkByteData; db: HCkByteData); stdcall;
procedure CkByteData_append2(objHandle: HCkByteData; pByteData: pbyte; szByteData: LongWord); stdcall;
procedure CkByteData_appendChar(objHandle: HCkByteData; ch: Char); stdcall;
procedure CkByteData_appendCharN(objHandle: HCkByteData; ch: Char; numTimes: Integer); stdcall;
procedure CkByteData_appendEncoded(objHandle: HCkByteData; str: pbyte; encoding: pbyte); stdcall;
procedure CkByteData_appendEncodedW(objHandle: HCkByteData; str: PWideChar; encoding: PWideChar); stdcall;
function CkByteData_appendFile(objHandle: HCkByteData; path: pbyte): wordbool; stdcall;
function CkByteData_appendFileW(objHandle: HCkByteData; path: PWideChar): wordbool; stdcall;
procedure CkByteData_appendInt(objHandle: HCkByteData; intValue: Integer; littleEndian: wordbool); stdcall;
procedure CkByteData_appendRandom(objHandle: HCkByteData; numBytes: Integer); stdcall;
procedure CkByteData_appendRange(objHandle: HCkByteData; byteData: HCkByteData; index: LongWord; numBytes: LongWord); stdcall;
procedure CkByteData_appendShort(objHandle: HCkByteData; shortValue: SmallInt; littleEndian: wordbool); stdcall;
procedure CkByteData_appendStr(objHandle: HCkByteData; str: pbyte); stdcall;
procedure CkByteData_appendStrW(objHandle: HCkByteData; str: PWideChar; charset: PWideChar); stdcall;
function CkByteData_beginsWith(objHandle: HCkByteData; byteDataObj: HCkByteData): wordbool; stdcall;
function CkByteData_beginsWith2(objHandle: HCkByteData; pByteData: pbyte; szByteData: LongWord): wordbool; stdcall;
procedure CkByteData_borrowData(objHandle: HCkByteData; pByteData: pbyte; szByteData: LongWord); stdcall;
procedure CkByteData_byteSwap4321(objHandle: HCkByteData); stdcall;
procedure CkByteData_clear(objHandle: HCkByteData); stdcall;
procedure CkByteData_encode(objHandle: HCkByteData; encoding: pbyte; str: HCkString); stdcall;
procedure CkByteData_encodeW(objHandle: HCkByteData; encoding: PWideChar; str: HCkString); stdcall;
function CkByteData_ensureBuffer(objHandle: HCkByteData; expectedNumBytes: LongWord): wordbool; stdcall;
function CkByteData_equals(objHandle: HCkByteData; compareBytes: HCkByteData): wordbool; stdcall;
function CkByteData_equals2(objHandle: HCkByteData; pCompareBytes: pbyte; numBytes: LongWord): wordbool; stdcall;
function CkByteData_findBytes(objHandle: HCkByteData; byteDataObj: HCkByteData): Integer; stdcall;
function CkByteData_findBytes2(objHandle: HCkByteData; findBytes: pbyte; findBytesLen: LongWord): Integer; stdcall;
function CkByteData_getByte(objHandle: HCkByteData; byteIndex: LongWord): Byte; stdcall;
function CkByteData_getBytes(objHandle: HCkByteData): pbyte; stdcall;
function CkByteData_getChar(objHandle: HCkByteData; byteIndex: LongWord): Char; stdcall;
function CkByteData_getData(objHandle: HCkByteData): pbyte; stdcall;
function CkByteData_getDataAt(objHandle: HCkByteData; byteIndex: LongWord): pbyte; stdcall;
function CkByteData_getEncodedW(objHandle: HCkByteData; encoding: PWideChar): PWideChar; stdcall;
function CkByteData_getInt(objHandle: HCkByteData; byteIndex: LongWord): Integer; stdcall;
function CkByteData_getRange(objHandle: HCkByteData; byteIndex: LongWord; numBytes: LongWord): pbyte; stdcall;
function CkByteData_getShort(objHandle: HCkByteData; byteIndex: LongWord): SmallInt; stdcall;
function CkByteData_getSize(objHandle: HCkByteData): LongWord; stdcall;
function CkByteData_getUInt(objHandle: HCkByteData; byteIndex: LongWord): LongWord; stdcall;
function CkByteData_getUShort(objHandle: HCkByteData; byteIndex: LongWord): Word; stdcall;
function CkByteData_is7bit(objHandle: HCkByteData): wordbool; stdcall;
function CkByteData_loadFile(objHandle: HCkByteData; path: pbyte): wordbool; stdcall;
function CkByteData_loadFileW(objHandle: HCkByteData; path: PWideChar): wordbool; stdcall;
procedure CkByteData_pad(objHandle: HCkByteData; blockSize: Integer; paddingScheme: Integer); stdcall;
function CkByteData_preAllocate(objHandle: HCkByteData; expectedNumBytes: LongWord): wordbool; stdcall;
procedure CkByteData_removeChunk(objHandle: HCkByteData; startIndex: LongWord; numBytes: LongWord); stdcall;
function CkByteData_removeData(objHandle: HCkByteData): pbyte; stdcall;
procedure CkByteData_replaceChar(objHandle: HCkByteData; existingByteValue: Byte; replacementByteValue: Byte); stdcall;
function CkByteData_saveFile(objHandle: HCkByteData; path: pbyte): wordbool; stdcall;
function CkByteData_saveFileW(objHandle: HCkByteData; path: PWideChar): wordbool; stdcall;
procedure CkByteData_shorten(objHandle: HCkByteData; numBytes: LongWord); stdcall;
function CkByteData_to_ws(objHandle: HCkByteData; charset: pbyte): PWideChar; stdcall;
procedure CkByteData_unpad(objHandle: HCkByteData; blockSize: Integer; paddingScheme: Integer); stdcall;
implementation
{$Include chilkatDllPath.inc}
function CkByteData_Create; external DLLName;
procedure CkByteData_Dispose; external DLLName;
function CkByteData_getSecureClear; external DLLName;
procedure CkByteData_putSecureClear; external DLLName;
procedure CkByteData_append; external DLLName;
procedure CkByteData_append2; external DLLName;
procedure CkByteData_appendChar; external DLLName;
procedure CkByteData_appendCharN; external DLLName;
procedure CkByteData_appendEncoded; external DLLName;
procedure CkByteData_appendEncodedW; external DLLName;
function CkByteData_appendFile; external DLLName;
function CkByteData_appendFileW; external DLLName;
procedure CkByteData_appendInt; external DLLName;
procedure CkByteData_appendRandom; external DLLName;
procedure CkByteData_appendRange; external DLLName;
procedure CkByteData_appendShort; external DLLName;
procedure CkByteData_appendStr; external DLLName;
procedure CkByteData_appendStrW; external DLLName;
function CkByteData_beginsWith; external DLLName;
function CkByteData_beginsWith2; external DLLName;
procedure CkByteData_borrowData; external DLLName;
procedure CkByteData_byteSwap4321; external DLLName;
procedure CkByteData_clear; external DLLName;
procedure CkByteData_encode; external DLLName;
procedure CkByteData_encodeW; external DLLName;
function CkByteData_ensureBuffer; external DLLName;
function CkByteData_equals; external DLLName;
function CkByteData_equals2; external DLLName;
function CkByteData_findBytes; external DLLName;
function CkByteData_findBytes2; external DLLName;
function CkByteData_getByte; external DLLName;
function CkByteData_getBytes; external DLLName;
function CkByteData_getChar; external DLLName;
function CkByteData_getData; external DLLName;
function CkByteData_getDataAt; external DLLName;
function CkByteData_getEncodedW; external DLLName;
function CkByteData_getInt; external DLLName;
function CkByteData_getRange; external DLLName;
function CkByteData_getShort; external DLLName;
function CkByteData_getSize; external DLLName;
function CkByteData_getUInt; external DLLName;
function CkByteData_getUShort; external DLLName;
function CkByteData_is7bit; external DLLName;
function CkByteData_loadFile; external DLLName;
function CkByteData_loadFileW; external DLLName;
procedure CkByteData_pad; external DLLName;
function CkByteData_preAllocate; external DLLName;
procedure CkByteData_removeChunk; external DLLName;
function CkByteData_removeData; external DLLName;
procedure CkByteData_replaceChar; external DLLName;
function CkByteData_saveFile; external DLLName;
function CkByteData_saveFileW; external DLLName;
procedure CkByteData_shorten; external DLLName;
function CkByteData_to_ws; external DLLName;
procedure CkByteData_unpad; external DLLName;
end.
|
//Copyright 2009-2011 by Victor Derevyanko, dvpublic0@gmail.com
//http://code.google.com/p/dvsrc/
//http://derevyanko.blogspot.com/2011/03/kill-word.html
//{$Id: WordThread.pas 34 2011-03-10 04:48:59Z dvpublic0@gmail.com $}
unit WordThread;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, SvcMgr, Dialogs, ExtCtrls, ActiveX;
type
TWordThread = class (TThread)
public
constructor Create(const srcFileName: String);
destructor Destroy; override;
procedure Execute; override;
function GetResultErrorCode: Integer;
private
m_SrcFileName: String;
m_ResultErrorCode: Integer;
end;
implementation
uses WordUtils;
{ TThreadConverter }
constructor TWordThread.Create(const srcFileName: String);
begin
inherited Create(true);
m_SrcFileName := srcFileName;
m_ResultErrorCode := 0;
end;
destructor TWordThread.Destroy;
begin
inherited;
end;
procedure TWordThread.Execute;
begin
inherited;
try
CoInitialize(nil);
try
WordUtils.OpenWord(m_SrcFileName);
finally
CoUninitialize();
end;
except on ex: Exception do begin
m_ResultErrorCode := -1;
end;
end;
end;
function TWordThread.GetResultErrorCode: Integer;
begin
Result := m_ResultErrorCode;
end;
end.
|
unit UProdutos;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.StdCtrls, Vcl.Buttons,
Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.DBCtrls;
type
TFProdutos = class(TForm)
LblLocalizarUsuarios: TLabel;
EdtLocalizarProdutos: TEdit;
G1Grid: TDBGrid;
PainelUsuarios1: TPanel;
PainelUsuarios2: TPanel;
BtnIncluir: TBitBtn;
BtnAlterar: TBitBtn;
BtnExcluir: TBitBtn;
BtnSair: TButton;
lkCbxFornecedor: TDBLookupComboBox;
lblFornecedor: TLabel;
btnAdicionar: TBitBtn;
cbxCompravenda: TComboBox;
SpeedButton1: TSpeedButton;
procedure BtnSairClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure BtnIncluirClick(Sender: TObject);
procedure EdtLocalizarProdutosChange(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure BtnAlterarClick(Sender: TObject);
procedure BtnExcluirClick(Sender: TObject);
procedure G1GridDblClick(Sender: TObject);
procedure lkCbxFornecedorClick(Sender: TObject);
procedure EdtLocalizarProdutosKeyPress(Sender: TObject; var Key: Char);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnAdicionarClick(Sender: TObject);
procedure lkCbxTipoProdutoClick(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
idprod : Integer;
end;
var
FProdutos: TFProdutos;
implementation
{$R *.dfm}
uses UDM, UCadProduto, UCadItens;{units que podem ser acessadas e utilizadas}
procedure TFProdutos.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Close;
end;
procedure TFProdutos.FormCreate(Sender: TObject);
begin
{dm.cdsProdutos.Close;
dm.cdsProdutos.Open; }
dm.sql_produto.Close;
DM.sql_produto.IsEmpty;
dm.sql_produto.Open;
dm.sql_pessoa2.Close;
DM.sql_pessoa2.IsEmpty;
dm.sql_pessoa2.Open;
end;
procedure TFProdutos.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key=VK_ESCAPE then //se a tecla ESC for pressionada então
Close;
end;
procedure TFProdutos.G1GridDblClick(Sender: TObject);
begin
BtnAlterar.Click;
end;
procedure TFProdutos.lkCbxFornecedorClick(Sender: TObject);
begin
begin
DM.sql_produto.Close;
DM.sql_produto.SQL.Clear;
DM.sql_produto.SQL.Add ('select * from produtos');
DM.sql_produto.SQL.Add('where id_pessoa_prod = :idpessoaprod ');
DM.sql_produto.ParamByName('idpessoaprod').AsInteger := DM.sql_pessoa2ID_PESSOA.AsInteger;
DM.sql_produto.Open;
end;
end;
procedure TFProdutos.lkCbxTipoProdutoClick(Sender: TObject);
begin
begin
DM.sql_produto.Close;
DM.sql_produto.SQL.Clear;
DM.sql_produto.SQL.Add ('select * from produtos');
DM.sql_produto.SQL.Add('where tipo_produto = :tipoproduto ');
DM.sql_produto.ParamByName('tipoproduto').AsString := cbxCompravenda.Text;
DM.sql_produto.Open;
end;
end;
procedure TFProdutos.SpeedButton1Click(Sender: TObject);
begin
if (lkCbxFornecedor.Text <> '') and (cbxCompravenda.Text = '') then
begin
begin
DM.sql_produto.Close;
DM.sql_produto.SQL.Clear;
DM.sql_produto.SQL.Add ('select * from produtos');
DM.sql_produto.SQL.Add('where id_pessoa_prod = :idpessoaprod ');
DM.sql_produto.ParamByName('idpessoaprod').AsInteger := DM.sql_pessoa2ID_PESSOA.AsInteger;
DM.sql_produto.Open;
end;
end;
if (lkCbxFornecedor.Text <> '') and (cbxCompravenda.Text = 'Nenhum') then
begin
begin
DM.sql_produto.Close;
DM.sql_produto.SQL.Clear;
DM.sql_produto.SQL.Add ('select * from produtos');
DM.sql_produto.SQL.Add('where id_pessoa_prod = :idpessoaprod ');
DM.sql_produto.ParamByName('idpessoaprod').AsInteger := DM.sql_pessoa2ID_PESSOA.AsInteger;
DM.sql_produto.Open;
end;
end;
if (lkCbxFornecedor.Text = '') and (cbxCompravenda.Text = 'Compra') or (cbxCompravenda.Text = 'Venda') then
begin
DM.sql_produto.Close;
DM.sql_produto.SQL.Clear;
DM.sql_produto.SQL.Add ('select * from produtos');
DM.sql_produto.SQL.Add('where tipo_produto = :tipoproduto ');
DM.sql_produto.ParamByName('tipoproduto').AsString := cbxCompravenda.Text;
DM.sql_produto.Open;
end;
if (lkCbxFornecedor.Text <> '') and (cbxCompravenda.Text <> '') and (cbxCompravenda.Text <> 'Nenhum') then
begin
DM.sql_produto.Close;
DM.sql_produto.SQL.Clear;
DM.sql_produto.SQL.Add ('select * from produtos');
DM.sql_produto.SQL.Add('where id_pessoa_prod = :idpessoaprod and tipo_produto = :tipoproduto ');
DM.sql_produto.ParamByName('idpessoaprod').AsInteger := DM.sql_pessoa2ID_PESSOA.AsInteger;
DM.sql_produto.ParamByName('tipoproduto').AsString := cbxCompravenda.Text;
DM.sql_produto.Open;
if DM.sql_produto.RecordCount = 0 then
begin
ShowMessage('Nehum Produto foi localizado!');
{DM.sql_produto.Close;
DM.sql_produto.SQL.Clear;
DM.sql_produto.SQL.Add ('select * from produtos');
DM.sql_produto.SQL.Add('where tipo_produto = :tipoproduto ');
DM.sql_produto.ParamByName('tipoproduto').AsString := cbxCompravenda.Text;
DM.sql_produto.Open;
lkCbxFornecedor.ListField.IsEmpty;}
end
else
begin
DM.sql_produto.Open;
end;
end;
end;
procedure TFProdutos.btnAdicionarClick(Sender: TObject);
begin
idprod := DM.sql_produtoID_PRODUTO.AsInteger;
Close;
btnAdicionar.ModalResult:= mrOk;
end;
procedure TFProdutos.BtnAlterarClick(Sender: TObject);
begin
{if not dm.cdsProdutos.IsEmpty then //se não estiver vazio então
begin //inicie
Self.Visible:=False; //esconde formulario UUsuario
dm.cdsProdutos.Edit;
dm.CriarFormulario(TFCadProduto,FCadProduto); //criar form
Self.Visible:=True; //mostrar formulario UUsuario
end; }
if not DM.sql_produto.IsEmpty then
begin
Self.Visible :=False;
DM.sql_produto.Edit;
dm.CriarFormulario(TFCadProduto,FCadProduto);
Self.Visible:=True;
end;
end;
procedure TFProdutos.BtnExcluirClick(Sender: TObject);
begin
{if not dm.cdsProdutos.IsEmpty then //se não estiver vazio então
begin //inicie
if MessageDlg('Confirmar a Exclusão',mtInformation,[mbYes,mbNo],0)=mrYes then
//se ao informar a mensagem 'Confirmar a Exclusão' for igual a Yes então
begin //inicie
dm.cdsProdutos.Delete; //delete o registro na tabela usuario
dm.cdsProdutos.ApplyUpdates(0); //aplicar modificações na tabela
ShowMessage('Informações Excluídas com Sucesso!'); //exibir mensagem
end; //fimse
end; }
if not dm.sql_produto.IsEmpty then
begin
if dm.MessageDlgDefault('Confirmar a Exclusão',mtInformation,[mbYes,mbNo],0)=mrYes then
//se ao informar a mensagem 'Confirmar a Exclusão' for igual a Yes então
begin
dm.sql_produto.Delete;
ShowMessage('Informações Excluídas com Sucesso!');
end;
end;
end;
procedure TFProdutos.BtnIncluirClick(Sender: TObject);//incluir produto
begin //inicie
{Self.Visible :=False; //esconde formulario UProduto
dm.cdsProdutos.Append; //acrescentar em uma nova linha
dm.cdsProdutosQUANTIDADE.AsFloat:=0; //campo QUANTIDADE iniciar com 0
dm.cdsProdutosVALOR.AsFloat:=0; //campo VALOR iniciar com 0
dm.cdsProdutosTIPO.AsString:='T'; //campo TIPO iniciar com T
dm.CriarFormulario(TFCadProduto,FCadProduto); //chamar procedimento para criar/abrir formulario UCadUProduto
Self.Visible:=True; } //mostrar formulario UProduto
//Firebird
Self.Visible :=False;
DM.sql_produto.Active := True;
DM.sql_produto.Insert;
dm.CriarFormulario(TFCadProduto,FCadProduto);
Self.Visible:=True;
end;
procedure TFProdutos.BtnSairClick(Sender: TObject);//clique botão sair
begin
Close;
end; //fim
procedure TFProdutos.EdtLocalizarProdutosChange(Sender: TObject);//pesquisa de produtos
begin //inicie
//if EdtLocalizarProdutos.Text<> '' then //se a busca no Localizar for diferente de vazio então
//acesse a tabela, localize o campo NOME no BD,e procure pelo texto que esta escrito no edtlocalizar,
//[loPartialkey= localiza pela primeira letra ] [loCaseInsensitive=case sensitive]
{dm.cdsProdutos.Locate('NOME',EdtLocalizarProdutos.Text,[loPartialKey,loCaseInsensitive]); }
//Firebird
if EdtLocalizarProdutos.Text<> '' then
begin
DM.sql_produto.Close;
DM.sql_produto.Open;
dm.sql_produto.Locate('NOME_PRODUTO',EdtLocalizarProdutos.Text,[loPartialKey,loCaseInsensitive]);
end;
if EdtLocalizarProdutos.Text= '%%' then
begin
DM.sql_produto.Close;
DM.sql_produto.SQL.Clear;
DM.sql_produto.SQL.Add ('select * from produtos');
DM.sql_produto.Open;
end;
end;
procedure TFProdutos.EdtLocalizarProdutosKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then
begin
if EdtLocalizarProdutos.Text<> '' then
begin
dm.sql_produto.Locate('NOME_PRODUTO',EdtLocalizarProdutos.Text,[loPartialKey,loCaseInsensitive]);
end;
if EdtLocalizarProdutos.Text= '%%' then
begin
DM.sql_produto.Close;
DM.sql_produto.SQL.Clear;
DM.sql_produto.SQL.Add ('select * from produtos');
DM.sql_produto.Open;
end;
end;
end;
end.
|
unit VectorOperatorsOnSelfTimingTest;
{$mode objfpc}{$H+}
{$CODEALIGN LOCALMIN=16}
interface
uses
Classes, SysUtils, fpcunit, testregistry, BaseTimingTest, BaseTestCase,
native, GLZVectorMath, GLZProfiler;
type
{ TVectorOperatorsOnSelfTimingTest }
TVectorOperatorsOnSelfTimingTest = class(TVectorBaseTimingTest)
protected
procedure Setup; override;
published
procedure TimepAdd;
procedure TimepSub;
procedure TimepMul;
procedure TimepDiv;
procedure TimepAddSingle;
procedure TimepSubSingle;
procedure TimepMulSingle;
procedure TimepDivSingle;
procedure TimepInvert;
procedure TimepNegate;
procedure TimepAbs;
procedure TimepNormalize;
procedure TimepDivideBy2;
procedure TimepCrossProduct;
procedure TimepMinVector;
procedure TimepMinSingle;
procedure TimepMaxVector;
procedure TimepMaxSingle;
procedure TimepClampVector;
procedure TimepClampSingle;
end;
implementation
{%region%====[ TVectorOperatorsOnSelfTimingTest ]==============================}
procedure TVectorOperatorsOnSelfTimingTest.Setup;
begin
inherited Setup;
Group := rgVector4f;
end;
procedure TVectorOperatorsOnSelfTimingTest.TimepAdd;
begin
TestDispName := 'Self Add with Vector';
GlobalProfiler[0].Clear;
GlobalProfiler[0].Start;
for cnt := 1 to Iterations do begin nt1.pAdd(nt2); end;
GlobalProfiler[0].Stop;
GlobalProfiler[1].Clear;
GlobalProfiler[1].Start;
For cnt:= 1 to Iterations do begin vt1.padd(vt2); end;
GlobalProfiler[1].Stop;
end;
procedure TVectorOperatorsOnSelfTimingTest.TimepSub;
begin
TestDispName := 'Self Sub with Vector';
GlobalProfiler[0].Clear;
GlobalProfiler[0].Start;
for cnt := 1 to Iterations do begin nt1.pSub(nt2); end;
GlobalProfiler[0].Stop;
GlobalProfiler[1].Clear;
GlobalProfiler[1].Start;
For cnt:= 1 to Iterations do begin vt1.pSub(vt2); end;
GlobalProfiler[1].Stop;
end;
procedure TVectorOperatorsOnSelfTimingTest.TimepMul;
begin
TestDispName := 'Self Multiply by Vector';
GlobalProfiler[0].Clear;
GlobalProfiler[0].Start;
for cnt := 1 to Iterations do begin nt1.pMul(natUnitVector); end;
GlobalProfiler[0].Stop;
GlobalProfiler[1].Clear;
GlobalProfiler[1].Start;
For cnt:= 1 to Iterations do begin vt1.pMul(asmUnitVector); end;
GlobalProfiler[1].Stop;
end;
procedure TVectorOperatorsOnSelfTimingTest.TimepDiv;
begin
TestDispName := 'Self Divide by Vector';
GlobalProfiler[0].Clear;
GlobalProfiler[0].Start;
for cnt := 1 to Iterations do begin nt1.pDiv(natUnitVector); end;
GlobalProfiler[0].Stop;
GlobalProfiler[1].Clear;
GlobalProfiler[1].Start;
For cnt:= 1 to Iterations do begin vt1.pDiv(asmUnitVector); end;
GlobalProfiler[1].Stop;
end;
procedure TVectorOperatorsOnSelfTimingTest.TimepAddSingle;
begin
TestDispName := 'Self Add with Single';
GlobalProfiler[0].Clear;
GlobalProfiler[0].Start;
for cnt := 1 to Iterations do begin nt1.pAdd(0.0001); end;
GlobalProfiler[0].Stop;
GlobalProfiler[1].Clear;
GlobalProfiler[1].Start;
For cnt:= 1 to Iterations do begin vt1.padd(0.0001); end;
GlobalProfiler[1].Stop;
end;
procedure TVectorOperatorsOnSelfTimingTest.TimepSubSingle;
begin
TestDispName := 'Self Sub with Single';
GlobalProfiler[0].Clear;
GlobalProfiler[0].Start;
for cnt := 1 to Iterations do begin nt1.pSub(0.0001); end;
GlobalProfiler[0].Stop;
GlobalProfiler[1].Clear;
GlobalProfiler[1].Start;
For cnt:= 1 to Iterations do begin vt1.pSub(0.0001); end;
GlobalProfiler[1].Stop;
end;
procedure TVectorOperatorsOnSelfTimingTest.TimepMulSingle;
begin
TestDispName := 'Self Multiply by single';
GlobalProfiler[0].Clear;
GlobalProfiler[0].Start;
for cnt := 1 to Iterations do begin nt1.pMul(1.0); end;
GlobalProfiler[0].Stop;
GlobalProfiler[1].Clear;
GlobalProfiler[1].Start;
For cnt:= 1 to Iterations do begin vt1.pMul(1.0); end;
GlobalProfiler[1].Stop;
end;
// note in operations on self use 1 to avoid overflow etc
procedure TVectorOperatorsOnSelfTimingTest.TimepDivSingle;
begin
TestDispName := 'Self Divide by single';
GlobalProfiler[0].Clear;
GlobalProfiler[0].Start;
for cnt := 1 to Iterations do begin nt1.pDiv(1.0); end;
GlobalProfiler[0].Stop;
GlobalProfiler[1].Clear;
GlobalProfiler[1].Start;
For cnt:= 1 to Iterations do begin vt1.pDiv(1.0); end;
GlobalProfiler[1].Stop;
end;
procedure TVectorOperatorsOnSelfTimingTest.TimepInvert;
begin
TestDispName := 'Self Invert';
GlobalProfiler[0].Clear;
GlobalProfiler[0].Start;
for cnt := 1 to Iterations do begin nt1.pInvert; end;
GlobalProfiler[0].Stop;
GlobalProfiler[1].Clear;
GlobalProfiler[1].Start;
For cnt:= 1 to Iterations do begin vt1.pInvert; end;
GlobalProfiler[1].Stop;
end;
procedure TVectorOperatorsOnSelfTimingTest.TimepNegate;
begin
TestDispName := 'Self Negate';
GlobalProfiler[0].Clear;
GlobalProfiler[0].Start;
for cnt := 1 to Iterations do begin nt1.pNegate; end;
GlobalProfiler[0].Stop;
GlobalProfiler[1].Clear;
GlobalProfiler[1].Start;
For cnt:= 1 to Iterations do begin vt1.pNegate; end;
GlobalProfiler[1].Stop;
end;
procedure TVectorOperatorsOnSelfTimingTest.TimepAbs;
begin
TestDispName := 'Self Abs';
GlobalProfiler[0].Clear;
GlobalProfiler[0].Start;
for cnt := 1 to Iterations do begin nt1.pAbs; end;
GlobalProfiler[0].Stop;
GlobalProfiler[1].Clear;
GlobalProfiler[1].Start;
For cnt:= 1 to Iterations do begin vt1.pAbs; end;
GlobalProfiler[1].Stop;
end;
procedure TVectorOperatorsOnSelfTimingTest.TimepNormalize;
begin
TestDispName := 'Self Normalize';
GlobalProfiler[0].Clear;
GlobalProfiler[0].Start;
for cnt := 1 to Iterations do begin nt1.pNormalize; end;
GlobalProfiler[0].Stop;
GlobalProfiler[1].Clear;
GlobalProfiler[1].Start;
For cnt:= 1 to Iterations do begin vt1.pNormalize; end;
GlobalProfiler[1].Stop;
end;
//have to a bit more to stop overflows/underflows
procedure TVectorOperatorsOnSelfTimingTest.TimepDivideBy2;
begin
TestDispName := 'Self Divideby2';
GlobalProfiler[0].Clear;
GlobalProfiler[0].Start;
for cnt := 1 to Iterations do begin nt1.pAdd(1); nt1.DivideBy2; end;
GlobalProfiler[0].Stop;
GlobalProfiler[1].Clear;
GlobalProfiler[1].Start;
For cnt:= 1 to Iterations do begin vt1.pAdd(1); vt1.DivideBy2; end;
GlobalProfiler[1].Stop;
end;
procedure TVectorOperatorsOnSelfTimingTest.TimepCrossProduct;
begin
TestDispName := 'Self CrossProduct Vector';
GlobalProfiler[0].Clear;
GlobalProfiler[0].Start;
for cnt := 1 to Iterations do begin nt1.pCrossProduct(nt2); end;
GlobalProfiler[0].Stop;
GlobalProfiler[1].Clear;
GlobalProfiler[1].Start;
For cnt:= 1 to Iterations do begin vt1.pCrossProduct(vt2); end;
GlobalProfiler[1].Stop;
end;
procedure TVectorOperatorsOnSelfTimingTest.TimepMinVector;
begin
TestDispName := 'Self Min Vector';
GlobalProfiler[0].Clear;
GlobalProfiler[0].Start;
for cnt := 1 to Iterations do begin nt1.pMin(nt2); end;
GlobalProfiler[0].Stop;
GlobalProfiler[1].Clear;
GlobalProfiler[1].Start;
For cnt:= 1 to Iterations do begin vt1.pMin(vt2); end;
GlobalProfiler[1].Stop;
end;
procedure TVectorOperatorsOnSelfTimingTest.TimepMinSingle;
begin
TestDispName := 'Self Min Single';
GlobalProfiler[0].Clear;
GlobalProfiler[0].Start;
for cnt := 1 to Iterations do begin nt1.pMin(r1); end;
GlobalProfiler[0].Stop;
GlobalProfiler[1].Clear;
GlobalProfiler[1].Start;
For cnt:= 1 to Iterations do begin vt1.pMin(r1); end;
GlobalProfiler[1].Stop;
end;
procedure TVectorOperatorsOnSelfTimingTest.TimepMaxVector;
begin
TestDispName := 'Self Max Vector';
GlobalProfiler[0].Clear;
GlobalProfiler[0].Start;
for cnt := 1 to Iterations do begin nt1.pMax(nt2); end;
GlobalProfiler[0].Stop;
GlobalProfiler[1].Clear;
GlobalProfiler[1].Start;
For cnt:= 1 to Iterations do begin vt1.pMax(vt2); end;
GlobalProfiler[1].Stop;
end;
procedure TVectorOperatorsOnSelfTimingTest.TimepMaxSingle;
begin
TestDispName := 'Self Max Single';
GlobalProfiler[0].Clear;
GlobalProfiler[0].Start;
for cnt := 1 to Iterations do begin nt1.pMax(r1); end;
GlobalProfiler[0].Stop;
GlobalProfiler[1].Clear;
GlobalProfiler[1].Start;
For cnt:= 1 to Iterations do begin vt1.pMax(r1); end;
GlobalProfiler[1].Stop;
end;
procedure TVectorOperatorsOnSelfTimingTest.TimepClampVector;
begin
TestDispName := 'Self Clamp Vector';
GlobalProfiler[0].Clear;
GlobalProfiler[0].Start;
for cnt := 1 to Iterations do begin nt1.pClamp(nt2,nt1); end;
GlobalProfiler[0].Stop;
GlobalProfiler[1].Clear;
GlobalProfiler[1].Start;
For cnt:= 1 to Iterations do begin vt1.pClamp(vt2,vt1); end;
GlobalProfiler[1].Stop;
end;
procedure TVectorOperatorsOnSelfTimingTest.TimepClampSingle;
begin
TestDispName := 'Self Clamp Single';
GlobalProfiler[0].Clear;
GlobalProfiler[0].Start;
for cnt := 1 to Iterations do begin nt1.pClamp(fs2,fs1); end;
GlobalProfiler[0].Stop;
GlobalProfiler[1].Clear;
GlobalProfiler[1].Start;
For cnt:= 1 to Iterations do begin vt1.pClamp(fs2,fs1); end;
GlobalProfiler[1].Stop;
end;
{%endregion}
initialization
RegisterTest(REPORT_GROUP_VECTOR4F, TVectorOperatorsOnSelfTimingTest);
end.
|
unit TextEditor.KeyboardHandler;
interface
uses
System.Classes, System.SysUtils, Vcl.Controls, Vcl.Forms, Vcl.Graphics, TextEditor.Types;
type
TTextEditorMethodList = class
strict private
FData: TList;
function GetCount: Integer;
function GetItem(const AIndex: Integer): TMethod;
public
constructor Create;
destructor Destroy; override;
procedure Add(const AHandler: TMethod);
procedure Remove(const AHandler: TMethod);
property Count: Integer read GetCount;
property Items[const Aindex: Integer]: TMethod read GetItem; default;
end;
TTextEditorKeyboardHandler = class(TObject)
strict private
FInKeyDown: Boolean;
FInKeyPress: Boolean;
FInKeyUp: Boolean;
FInMouseCursor: Boolean;
FInMouseDown: Boolean;
FInMouseUp: Boolean;
FKeyDownChain: TTextEditorMethodList;
FKeyPressChain: TTextEditorMethodList;
FKeyUpChain: TTextEditorMethodList;
FMouseCursorChain: TTextEditorMethodList;
FMouseDownChain: TTextEditorMethodList;
FMouseUpChain: TTextEditorMethodList;
public
constructor Create;
destructor Destroy; override;
procedure AddKeyDownHandler(const AHandler: TKeyEvent);
procedure AddKeyPressHandler(const AHandler: TTextEditorKeyPressWEvent);
procedure AddKeyUpHandler(const AHandler: TKeyEvent);
procedure AddMouseCursorHandler(const AHandler: TTextEditorMouseCursorEvent);
procedure AddMouseDownHandler(const AHandler: TMouseEvent);
procedure AddMouseUpHandler(const AHandler: TMouseEvent);
procedure ExecuteKeyDown(ASender: TObject; var Key: Word; Shift: TShiftState);
procedure ExecuteKeyPress(ASender: TObject; var Key: Char);
procedure ExecuteKeyUp(ASender: TObject; var Key: Word; Shift: TShiftState);
procedure ExecuteMouseCursor(ASender: TObject; const ALineCharPos: TTextEditorTextPosition; var ACursor: TCursor);
procedure ExecuteMouseDown(ASender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure ExecuteMouseUp(ASender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure RemoveKeyDownHandler(const AHandler: TKeyEvent);
procedure RemoveKeyPressHandler(const AHandler: TTextEditorKeyPressWEvent);
procedure RemoveKeyUpHandler(const AHandler: TKeyEvent);
procedure RemoveMouseCursorHandler(const AHandler: TTextEditorMouseCursorEvent);
procedure RemoveMouseDownHandler(const AHandler: TMouseEvent);
procedure RemoveMouseUpHandler(const AHandler: TMouseEvent);
end;
implementation
uses
TextEditor.Consts;
{ TTextEditorMethodList }
constructor TTextEditorMethodList.Create;
begin
inherited;
FData := TList.Create;
end;
destructor TTextEditorMethodList.Destroy;
begin
FData.Free;
inherited;
end;
function TTextEditorMethodList.GetCount: Integer;
begin
Result := FData.Count div 2;
end;
function TTextEditorMethodList.GetItem(const AIndex: Integer): TMethod;
var
LIndex: Integer;
begin
LIndex := AIndex * 2;
Result.Data := FData[LIndex];
Result.Code := FData[LIndex + 1];
end;
procedure TTextEditorMethodList.Add(const AHandler: TMethod);
begin
FData.Add(AHandler.Data);
FData.Add(AHandler.Code);
end;
procedure TTextEditorMethodList.Remove(const AHandler: TMethod);
var
LIndex: Integer;
begin
if Assigned(FData) then
begin
LIndex := FData.Count - 2;
while LIndex >= 0 do
begin
if (FData.List[LIndex] = AHandler.Data) and (FData.List[LIndex + 1] = AHandler.Code) then
begin
FData.Delete(LIndex);
FData.Delete(LIndex);
Exit;
end;
Dec(LIndex, 2);
end;
end;
end;
{ TTextEditorKeyboardHandler }
constructor TTextEditorKeyboardHandler.Create;
begin
inherited;
FKeyDownChain := TTextEditorMethodList.Create;
FKeyUpChain := TTextEditorMethodList.Create;
FKeyPressChain := TTextEditorMethodList.Create;
FMouseDownChain := TTextEditorMethodList.Create;
FMouseUpChain := TTextEditorMethodList.Create;
FMouseCursorChain := TTextEditorMethodList.Create;
end;
destructor TTextEditorKeyboardHandler.Destroy;
begin
FKeyPressChain.Free;
FKeyDownChain.Free;
FKeyUpChain.Free;
FMouseDownChain.Free;
FMouseUpChain.Free;
FMouseCursorChain.Free;
inherited Destroy;
end;
procedure TTextEditorKeyboardHandler.AddKeyDownHandler(const AHandler: TKeyEvent);
begin
FKeyDownChain.Add(TMethod(AHandler));
end;
procedure TTextEditorKeyboardHandler.AddKeyUpHandler(const AHandler: TKeyEvent);
begin
FKeyUpChain.Add(TMethod(AHandler));
end;
procedure TTextEditorKeyboardHandler.AddKeyPressHandler(const AHandler: TTextEditorKeyPressWEvent);
begin
FKeyPressChain.Add(TMethod(AHandler));
end;
procedure TTextEditorKeyboardHandler.AddMouseDownHandler(const AHandler: TMouseEvent);
begin
FMouseDownChain.Add(TMethod(AHandler));
end;
procedure TTextEditorKeyboardHandler.AddMouseUpHandler(const AHandler: TMouseEvent);
begin
FMouseUpChain.Add(TMethod(AHandler));
end;
procedure TTextEditorKeyboardHandler.AddMouseCursorHandler(const AHandler: TTextEditorMouseCursorEvent);
begin
FMouseCursorChain.Add(TMethod(AHandler));
end;
procedure TTextEditorKeyboardHandler.ExecuteKeyDown(ASender: TObject; var Key: Word; Shift: TShiftState);
var
LIndex: Integer;
begin
if FInKeyDown then
Exit;
FInKeyDown := True;
try
with FKeyDownChain do
for LIndex := Count - 1 downto 0 do
begin
TKeyEvent(Items[LIndex])(ASender, Key, Shift);
if Key = 0 then
begin
FInKeyDown := False;
Exit;
end;
end;
finally
FInKeyDown := False;
end;
end;
procedure TTextEditorKeyboardHandler.ExecuteKeyUp(ASender: TObject; var Key: Word; Shift: TShiftState);
var
LIndex: Integer;
begin
if FInKeyUp then
Exit;
FInKeyUp := True;
try
with FKeyUpChain do
for LIndex := Count - 1 downto 0 do
begin
TKeyEvent(Items[LIndex])(ASender, Key, Shift);
if Key = 0 then
begin
FInKeyUp := False;
Exit;
end;
end;
finally
FInKeyUp := False;
end;
end;
procedure TTextEditorKeyboardHandler.ExecuteKeyPress(ASender: TObject; var Key: Char);
var
LIndex: Integer;
begin
if FInKeyPress then
Exit;
FInKeyPress := True;
try
with FKeyPressChain do
for LIndex := Count - 1 downto 0 do
begin
TTextEditorKeyPressWEvent(Items[LIndex])(ASender, Key);
if Key = TEXT_EDITOR_NONE_CHAR then
begin
FInKeyPress := False;
Exit;
end;
end;
finally
FInKeyPress := False;
end;
end;
procedure TTextEditorKeyboardHandler.ExecuteMouseDown(ASender: TObject; Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
var
LIndex: Integer;
begin
if FInMouseDown then
Exit;
FInMouseDown := True;
try
for LIndex := FMouseDownChain.Count - 1 downto 0 do
TMouseEvent(FMouseDownChain[LIndex])(ASender, Button, Shift, X, Y);
finally
FInMouseDown := False;
end;
end;
procedure TTextEditorKeyboardHandler.ExecuteMouseUp(ASender: TObject; Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
var
LIndex: Integer;
begin
if FInMouseUp then
Exit;
FInMouseUp := True;
try
for LIndex := FMouseUpChain.Count - 1 downto 0 do
TMouseEvent(FMouseUpChain[LIndex])(ASender, Button, Shift, X, Y);
finally
FInMouseUp := False;
end;
end;
procedure TTextEditorKeyboardHandler.ExecuteMouseCursor(ASender: TObject; const ALineCharPos: TTextEditorTextPosition;
var ACursor: TCursor);
var
LIndex: Integer;
begin
if FInMouseCursor then
Exit;
FInMouseCursor := True;
try
for LIndex := FMouseCursorChain.Count - 1 downto 0 do
TTextEditorMouseCursorEvent(FMouseCursorChain[LIndex])(ASender, ALineCharPos, ACursor);
finally
FInMouseCursor := False;
end;
end;
procedure TTextEditorKeyboardHandler.RemoveKeyDownHandler(const AHandler: TKeyEvent);
begin
FKeyDownChain.Remove(TMethod(AHandler));
end;
procedure TTextEditorKeyboardHandler.RemoveKeyUpHandler(const AHandler: TKeyEvent);
begin
FKeyUpChain.Remove(TMethod(AHandler));
end;
procedure TTextEditorKeyboardHandler.RemoveKeyPressHandler(const AHandler: TTextEditorKeyPressWEvent);
begin
FKeyPressChain.Remove(TMethod(AHandler));
end;
procedure TTextEditorKeyboardHandler.RemoveMouseDownHandler(const AHandler: TMouseEvent);
begin
FMouseDownChain.Remove(TMethod(AHandler));
end;
procedure TTextEditorKeyboardHandler.RemoveMouseUpHandler(const AHandler: TMouseEvent);
begin
FMouseUpChain.Remove(TMethod(AHandler));
end;
procedure TTextEditorKeyboardHandler.RemoveMouseCursorHandler(const AHandler: TTextEditorMouseCursorEvent);
begin
FMouseCursorChain.Remove(TMethod(AHandler));
end;
end.
|
{------------------------------------
功能说明:实现IDataRecord接口
创建日期:2010/05/17
作者:wzw
版权:wzw
-------------------------------------}
unit DataRecord;
interface
uses sysUtils, Classes, Variants, SysFactory, DBIntf, SvcInfoIntf, DB;
type
TDataItem = class(TObject)
public
Modified: Variant;
Data: Variant;
end;
TDataRecord = class(TInterfacedObject, IDataRecord, ISvcInfo)
private
FList: TStrings;
procedure ClearList;
function FindFieldData(const FieldName: String): TDataItem;
function GetFieldData(const FieldName: String): TDataItem;
protected
{ISvcInfo}
function GetModuleName: String;
function GetTitle: String;
function GetVersion: String;
function GetComments: String;
{IDataRecord}
procedure LoadFromDataSet(DataSet: TDataSet);
procedure SaveToDataSet(const KeyFields: String; DataSet: TDataSet; FieldsMapping: string = '');
procedure CloneFrom(DataRecord: IDataRecord);
function GetFieldValue(const FieldName: String): Variant;
procedure SetFieldValue(const FieldName: String; Value: Variant);
property FieldValues[const FieldName: string]: Variant read GetFieldValue write SetFieldValue;
function FieldValueAsString(const FieldName: String): String;
function FieldValueAsBoolean(const FieldName: String): Boolean;
function FieldValueAsCurrency(const FieldName: String): Currency;
function FieldValueAsDateTime(const FieldName: String): TDateTime;
function FieldValueAsFloat(const FieldName: String): Double;
function FieldValueAsInteger(const FieldName: String): Integer;
function GetFieldCount: Integer;
function GetFieldName(const Index: Integer): String;
public
constructor Create;
destructor Destroy; override;
end;
implementation
function Create_DataRecord(param: Integer): TObject;
begin
Result := TDataRecord.Create;
end;
{ TDataRecord }
function TDataRecord.GetModuleName: String;
begin
Result := ExtractFileName(SysUtils.GetModuleName(HInstance));
end;
function TDataRecord.GetVersion: String;
begin
Result := '20100517.001';
end;
function TDataRecord.GetComments: String;
begin
Result := '可以把数据集当做一个记录的集合,可以用本接口读出一条记录,并可以写回数据集。';
end;
function TDataRecord.GetTitle: String;
begin
Result := '数据记录接口(IDataRecord)';
end;
procedure TDataRecord.ClearList;
var i: Integer;
begin
for i := 0 to FList.Count - 1 do
FList.Objects[i].Free;
FList.Clear;
end;
constructor TDataRecord.Create;
begin
FList := TStringList.Create;
end;
destructor TDataRecord.Destroy;
begin
ClearList;
FList.Free;
inherited;
end;
function TDataRecord.FieldValueAsBoolean(const FieldName: String): Boolean;
var tmpValue: Variant;
begin
tmpValue := self.GetFieldValue(FieldName);
if VarIsNull(tmpValue) then
Result := False
else Result := tmpValue;
end;
function TDataRecord.FieldValueAsCurrency(
const FieldName: String): Currency;
var tmpValue: Variant;
begin
tmpValue := self.GetFieldValue(FieldName);
if VarIsNull(tmpValue) then
Result := 0
else Result := tmpValue;
end;
function TDataRecord.FieldValueAsDateTime(
const FieldName: String): TDateTime;
var tmpValue: Variant;
begin
tmpValue := self.GetFieldValue(FieldName);
if VarIsNull(tmpValue) then
Result := 0
else Result := tmpValue;
end;
function TDataRecord.FieldValueAsFloat(const FieldName: String): Double;
var tmpValue: Variant;
begin
tmpValue := self.GetFieldValue(FieldName);
if VarIsNull(tmpValue) then
Result := 0.0
else Result := tmpValue;
end;
function TDataRecord.FieldValueAsInteger(const FieldName: String): Integer;
var tmpValue: Variant;
begin
tmpValue := self.GetFieldValue(FieldName);
if VarIsNull(tmpValue) then
Result := 0
else Result := tmpValue;
end;
function TDataRecord.FieldValueAsString(const FieldName: String): String;
begin
Result := VarToStr(GetFieldValue(FieldName));
end;
function TDataRecord.GetFieldCount: Integer;
begin
Result := FList.Count;
end;
function TDataRecord.GetFieldName(const Index: Integer): String;
begin
Result := FList[Index];
end;
function TDataRecord.GetFieldValue(const FieldName: String): Variant;
var DataItem: TDataItem;
begin
DataItem := self.GetFieldData(FieldName);
Result := DataItem.Data;
end;
procedure TDataRecord.LoadFromDataSet(DataSet: TDataSet);
var DataItem: TDataItem;
i: Integer;
begin
self.ClearList;
if DataSet = nil then
exit;
for i := 0 to DataSet.FieldCount - 1 do
begin
DataItem := TDataItem.Create;
DataItem.Modified := False;
DataItem.Data := DataSet.Fields[i].Value;
FList.AddObject(DataSet.Fields[i].FieldName, DataItem);
end;
end;
procedure TDataRecord.SaveToDataSet(const KeyFields: String; DataSet: TDataSet; FieldsMapping: string);
var i, idx: Integer;
DataItem: TDataItem;
FieldValues: Variant;
FieldList, FieldMappingList: TStrings;
s: string;
begin
FieldList := TStringList.Create;
FieldMappingList := TStringList.Create;
try
FieldList.Delimiter := ';';
FieldList.DelimitedText := KeyFields;
FieldMappingList.Delimiter := ';';
FieldMappingList.DelimitedText := FieldsMapping;
FieldValues := VarArrayCreate([0, FieldList.Count - 1], varVariant);
for i := 0 to FieldList.Count - 1 do
begin
s := FieldMappingList.Values[FieldList[i]];
if s = '' then
s := FieldList[i];
idx := FList.IndexOf(s);
if idx <> -1 then
begin
DataItem := TDataItem(FList.Objects[idx]);
FieldValues[i] := DataItem.Data;
end
else FieldValues[i] := NULL;
end;
if DataSet.Locate(KeyFields, FieldValues, []) then
DataSet.Edit
else DataSet.Append;
for i := 0 to DataSet.FieldCount - 1 do
begin
s := FieldMappingList.Values[DataSet.Fields[i].FieldName];
if s = '' then
s := DataSet.Fields[i].FieldName;
idx := FList.IndexOf(s);
if idx <> -1 then
begin
DataItem := TDataItem(FList.Objects[idx]);
if DataItem.Modified then
DataSet.Fields[i].Value := DataItem.Data;
end;
end;
DataSet.Post;
finally
FieldList.Free;
FieldMappingList.Free;
end;
end;
procedure TDataRecord.SetFieldValue(const FieldName: String;
Value: Variant);
var DataItem: TDataItem;
begin
DataItem := self.FindFieldData(FieldName);
if DataItem <> nil then
begin
DataItem.Modified := True;
DataItem.Data := Value;
end
else
begin
DataItem := TDataItem.Create;
DataItem.Modified := True;
DataItem.Data := Value;
FList.AddObject(FieldName, DataItem);
end;
end;
function TDataRecord.GetFieldData(const FieldName: String): TDataItem;
begin
Result := FindFieldData(FieldName);
if Result = nil then
raise Exception.CreateFmt('字段[%s]不存在!', [FieldName]);
end;
function TDataRecord.FindFieldData(const FieldName: String): TDataItem;
var idx: Integer;
begin
Result := nil;
idx := FList.IndexOf(FieldName);
if Idx <> -1 then
Result := TDataItem(FList.Objects[idx]);
end;
procedure TDataRecord.CloneFrom(DataRecord: IDataRecord);
var i: Integer;
FieldName: string;
begin
if DataRecord = nil then
exit;
self.ClearList;
for i := 0 to DataRecord.GetFieldCount - 1 do
begin
FieldName := DataRecord.GetFieldName(i);
self.FieldValues[FieldName] := DataRecord.FieldValues[FieldName];
end;
end;
initialization
TIntfFactory.Create(IDataRecord, @Create_DataRecord);
finalization
end. |
unit uUtils;
{$mode objfpc}{$H+}
{$ModeSwitch advancedrecords}
{$ModeSwitch nestedprocvars}
interface
uses
Classes, SysUtils, Forms, fgl;
type
PThread = ^TThread;
procedure WaitForMultipleThreads(a: PThread; NThreads: Integer; CB: TProcedureOfObject; cancelflag: PBoolean = nil);
type
generic TListTool<T> = record
type
TAList = specialize TFPGList<T>;
TACompareFunc = TAList.TCompareFunc;
TACompareNest = function(const Item1, Item2: T): Integer is nested;
class function FindSmallestValue(AList: TAList; ACompare: TACompareFunc; out Value: T): integer; static; overload;
class function FindSmallestValue(AList: TAList; ACompare: TACompareNest; out Value: T): integer; static; overload;
end;
function GetFileInfos(AFileName: string; out AInfos: TSearchRec): boolean;
function SendFilesToTrash(AFileNames: TStringArray): boolean;
implementation
uses
ShellApi;
procedure WaitForMultipleThreads(a: PThread; NThreads: Integer; CB: TProcedureOfObject; cancelflag: PBoolean = nil);
var
i: Integer;
begin
for i:= 0 to NThreads-1 do begin
repeat
if Assigned(cancelflag) and cancelflag^ then
a[i].Terminate;
if Assigned(CB) then
CB();
Sleep(1);
until a[i].Finished;
end;
end;
{ TListTool }
class function TListTool.FindSmallestValue(AList: TAList; ACompare: TACompareFunc; out Value: T): integer;
function Comp(const Item1, Item2: T): Integer;
begin
Result:= ACompare(Item1, Item2);
end;
begin
Result:= FindSmallestValue(AList, @Comp, Value);
end;
class function TListTool.FindSmallestValue(AList: TAList; ACompare: TACompareNest; out Value: T): integer;
var
i: integer;
begin
if AList.Count = 0 then
Exit(-1);
Value:= AList[0];
Result:= 0;
for i:= 1 to AList.Count - 1 do begin
if ACompare(AList[i], Value) < 0 then begin
Result:= i;
Value:= AList[i];
end;
end;
end;
function GetFileInfos(AFileName: string; out AInfos: TSearchRec): boolean;
begin
Result:= FindFirst(AFileName, faAnyFile, AInfos) = 0;
if Result then
FindClose(AInfos);
end;
function SendFilesToTrash(AFileNames: TStringArray): boolean;
var
fop: TSHFILEOPSTRUCTW;
ws: WideString;
begin
fop.wnd:= 0;
fop.wFunc:= FO_DELETE;
fop.fFlags:= FOF_NOCONFIRMATION or FOF_ALLOWUNDO;
ws:= WideString(AnsiString.Join(#0, AFileNames) + #0);
fop.pFrom:= PWideChar(ws);
Result:= 0 = SHFileOperationW(@fop);
end;
end.
|
(*
@created(2019-12-27)
@author(J.Delauney (BeanzMaster))
Historique : @br
@unorderedList(
@item(27/12/2019 : Creation )
)
--------------------------------------------------------------------------------@br
------------------------------------------------------------------------------
Description : Simulation d'un shader GLSL
------------------------------------------------------------------------------
@bold(Notes :)
Quelques liens :
@unorderedList(
@item(http://www.shadertoy.com)
@item(http://glslsandbox.com)
)
------------------------------------------------------------------------------@br
@bold(Credits :)
@unorderedList(
@item(J.Delauney (BeanzMaster))
@item(http://glslsandbox.com/e#63123.1 )
)
------------------------------------------------------------------------------@br
LICENCE : GPL/MPL
@br
------------------------------------------------------------------------------
*==============================================================================*)
unit BZSoftwareShader_NovaMarble;
//==============================================================================
{$mode objfpc}{$H+}
{$i ..\..\..\bzscene_options.inc}
//------------------------
{$ALIGN 16}
{$CODEALIGN CONSTMIN=16}
{$CODEALIGN LOCALMIN=16}
{$CODEALIGN VARMIN=16}
//------------------------
//==============================================================================
interface
uses
Classes, SysUtils, Math,
BZClasses, BZMath, BZVectorMath, BZRayMarchMath,
BZColors, BZGraphic, BZBitmap,
BZCadencer, BZCustomShader;
Type
{ TBZSoftShader_GroundAndDistortPhongSphere }
TBZSoftShader_NovaMarble = Class(TBZCustomSoftwareShader)
protected
public
Constructor Create; override;
Destructor Destroy; override;
function Clone : TBZCustomSoftwareShader; override;
function ShadePixelFloat:TBZColorVector; override;
end;
implementation
uses BZLogger;
{ TBZSoftShader_GroundAndDistortPhongSphere }
Constructor TBZSoftShader_NovaMarble.Create;
begin
inherited Create;
end;
Destructor TBZSoftShader_NovaMarble.Destroy;
begin
inherited Destroy;
end;
function TBZSoftShader_NovaMarble.Clone : TBZCustomSoftwareShader;
begin
Result := TBZSoftShader_NovaMarble.Create;
Result.Assign(Self);
end;
function TBZSoftShader_NovaMarble.ShadePixelFloat : TBZColorVector;
var
tTime : single;
function RotY(p : TBZVector4f; a : Single) : TBZVector4f;
Var
mat3 : TBZMatrix;
begin
mat3.CreateRotationMatrixY(a);
Result := p * mat3;
end;
function map(p : TBZVector4f) : Single;
var
res, f : Single;
i : Integer;
{$CODEALIGN VARMIN=16}
c, p2 : TBZVector4f;
p1 : TBZVector2f;
{$CODEALIGN VARMIN=4}
begin
res := 0;
c := p;
for i := 0 to 9 do
begin
p := ((p.Abs * 0.9) / p.DotProduct(p)) - 0.7;
p1.Create(p.y * p.y - p.z * p.z, 2.0 * p.y * p.z);
p.Y := p1.X;
p.X := p1.Y;
f := abs(p.DotProduct(c));
res := res + System.exp(-30.0 * f);
end;
result := res * 0.5;
end;
function RayMarch(ro, rd : TBZVector4f) : TBZVector4f;
var
i : Integer;
t, c, cv : Single;
{$CODEALIGN VARMIN=16}
p, col: TBZVector4f;
{$CODEALIGN VARMIN=4}
begin
t := 1.0;
Col.Create(0,0,0,0);
for i :=0 to 9 do
begin
t := t + (0.02 * System.exp(-2.0*c));
c := map(ro + (rd * t));
p.Create(c * 0.5, c*c, c);
p := p * 0.10; // /10
col := col + p;
end;
Result := Col;
end;
function ComputePixel(Coord:TBZVector2f; aTime:Single) : TBZColorVector;
var
{$CODEALIGN VARMIN=16}
uv :TBZVector2f;
ro, rd, uu, vv, c, pt : TBZVector4f;
{$CODEALIGN VARMIN=4}
ScreenZ, Depth, d, vc : Single;
i : Integer;
begin
Result.Create(0.0, 1.0, 1.0, 1.0);
tTime := aTime;
uv :=(Coord * FInvResolution) * 2.0 - 1.0;
uv.x := uv.x * 1.33333; // (resolution.x / resolution.y);
uv := uv * 18.0;
pt.Create(3.0,3.0,3.0,1.0);
ro := RotY(pt, tTime * 0.1);
pt.Create(1.0,0.0,0.0,1.0);
uu := ro.CrossProduct(pt).Normalize;
vv := uu.CrossProduct(ro).Normalize;
pt := (uu * uv.X) ;
pt := pt + (vv * uv.Y) ;
pt := pt - (ro * 0.3);
rd := pt.Normalize;
c := RayMarch(ro, rd);
c := c + RayMarch(ro, (rd * 0.1));
c := c + RayMarch(ro, (rd * 0.2));
Result.Create(c);
Result.Alpha := 1.0;
end;
begin
//ttime := max(0.0,iTime-2.0);
Result := ComputePixel(FragCoords, iTime);
end;
end.
|
unit frmeditarmarcado;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, DividerBevel, DBDateTimePicker, Forms, Controls,
Graphics, Dialogs, ExtCtrls, StdCtrls, DbCtrls, Buttons, frmzedicionbase,
datGeneral, ZDataset, SQLQueryGroup, zcontroladoredicion, zdatasetgroup,
DtDBTimeEdit, dtdbcoordedit, db;
type
{ TfmEditarMarcado }
TfmEditarMarcado = class(TZEdicionBase)
BytesField1: TBytesField;
BytesField2: TBytesField;
dbcbProcesado: TDBCheckBox;
dbcbVivo: TDBCheckBox;
dbcbRemarcado: TDBCheckBox;
dbcbLiberado: TDBCheckBox;
dbdtFecha: TDBDateTimePicker;
dbedCodMarca: TDBEdit;
dbedCodMarcaOrig: TDBEdit;
dbedHora: TDtDBTimeEdit;
dbedLargoCap: TDBEdit;
dbedLatitud: TDtDBCoordEdit;
dbedLongitud: TDtDBCoordEdit;
dbedPeso: TDBEdit;
dbedPorcentHuevos: TDBEdit;
dbedProfundidad: TDBEdit;
dbedSexo: TDBEdit;
dblkEspecieVulgar: TDBLookupComboBox;
dblkEspecieCientifico: TDBLookupComboBox;
dblkEstadoCap: TDBLookupComboBox;
dblkEvento: TDBLookupComboBox;
dblkHuevos: TDBLookupComboBox;
DBMemo1: TDBMemo;
dbEjemplar: TGroupBox;
Label1: TLabel;
Label10: TLabel;
Label11: TLabel;
Label12: TLabel;
Label13: TLabel;
Label16: TLabel;
Label17: TLabel;
Label2: TLabel;
Label25: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
paFechaHora: TPanel;
rgOrden: TRadioGroup;
zqPrincipales_recaptura: TSmallintField;
zqPrincipales_marcado: TSmallintField;
zqPrincipalevento: TStringField;
StringField2: TStringField;
StringField3: TStringField;
zqCodigosCaparazon: TZQuery;
zqEventos: TZQuery;
zqCodigosCaparazoncodigo: TLongintField;
zqCodigosCaparazoncod_desc: TBytesField;
zqCodigosCaparazondescripcion: TStringField;
zqCodigosCaparazonidcodigo_caparazon: TLongintField;
zqCodigosHuevos: TZQuery;
zqCodigosHuevoscodigo: TLongintField;
zqCodigosHuevoscod_desc: TBytesField;
zqCodigosHuevosdescripcion: TStringField;
zqCodigosHuevosidcodigo_huevos: TLongintField;
zqEspeciesCient: TZQuery;
zqEspeciesVulg: TZQuery;
zqEspeciesVulgcomercial: TSmallintField;
zqEspeciesVulgfrecuente: TLongintField;
zqEspeciesCientcodigo_inidep: TStringField;
zqEspeciescodigo_inidep1: TStringField;
zqEspeciesCientcodigo_rapido: TStringField;
zqEspeciescodigo_rapido1: TStringField;
zqEspeciesCientcomercial: TSmallintField;
zqEspeciesCientfrecuente: TLongintField;
zqEspeciesCientidespecie: TLongintField;
zqEspeciesidespecie1: TLongintField;
zqEspeciesCientnombre_cientifico: TStringField;
zqEspeciesnombre_cientifico1: TStringField;
zqEspeciesCientnombre_vulgar: TStringField;
zqEspeciesnombre_vulgar1: TStringField;
zqEventoses_marcado: TSmallintField;
zqEventoses_recaptura: TSmallintField;
zqEventosidevento_marca: TLongintField;
zqEventosnombre: TStringField;
zqPrincipalcod_marca: TStringField;
zqPrincipalcod_marca_original: TStringField;
zqPrincipalcomentarios: TStringField;
zqPrincipalEncabezado: TStringField;
zqPrincipalfecha: TDateField;
zqPrincipalhora: TTimeField;
zqPrincipalidcodigo_caparazon: TLongintField;
zqPrincipalidcodigo_huevos: TLongintField;
zqPrincipalidespecie: TLongintField;
zqPrincipalidevento_marca: TLongintField;
zqPrincipalidmarca: TLongintField;
zqPrincipalidmarea: TLongintField;
zqPrincipallargo: TLongintField;
zqPrincipallatitud: TFloatField;
zqPrincipalliberado: TSmallintField;
zqPrincipallongitud: TFloatField;
zqPrincipalpeso: TFloatField;
zqPrincipalporcentaje_huevos: TFloatField;
zqPrincipalprocesado: TSmallintField;
zqPrincipalprofundidad: TLongintField;
zqPrincipalremarcado: TSmallintField;
zqPrincipalsexo: TLongintField;
zqPrincipalvivo: TSmallintField;
procedure dbdtFechaEnter(Sender: TObject);
procedure dbedSexoChange(Sender: TObject);
procedure dblkEventoChange(Sender: TObject);
procedure dblkEventoExit(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure rgOrdenClick(Sender: TObject);
procedure zqPrincipalCalcFields(DataSet: TDataSet);
procedure zqPrincipalidevento_marcaChange(Sender: TField);
procedure zqPrincipalNewRecord(DataSet: TDataSet);
private
{ private declarations }
procedure HabilitarCampos;
public
{ public declarations }
end;
var
fmEditarMarcado: TfmEditarMarcado;
implementation
{$R *.lfm}
{ TfmEditarMarcado }
procedure TfmEditarMarcado.dbdtFechaEnter(Sender: TObject);
begin
//Hago esto para que se seleccione el día. Si no, el cursor queda
// en la última posición
(Sender as TDBDateTimePicker).SelectTime;
(Sender as TDBDateTimePicker).SelectDate;
end;
procedure TfmEditarMarcado.dbedSexoChange(Sender: TObject);
begin
HabilitarCampos;
end;
procedure TfmEditarMarcado.dblkEventoChange(Sender: TObject);
begin
HabilitarCampos;
end;
procedure TfmEditarMarcado.dblkEventoExit(Sender: TObject);
begin
HabilitarCampos;
end;
procedure TfmEditarMarcado.FormShow(Sender: TObject);
begin
dblkEspecieVulgar.Visible:=(rgOrden.ItemIndex=0);
dblkEspecieCientifico.Visible:=(rgOrden.ItemIndex=1);
HabilitarCampos;
end;
procedure TfmEditarMarcado.rgOrdenClick(Sender: TObject);
begin
dblkEspecieVulgar.Visible:=(rgOrden.ItemIndex=0);
dblkEspecieCientifico.Visible:=(rgOrden.ItemIndex=1);
end;
procedure TfmEditarMarcado.zqPrincipalCalcFields(DataSet: TDataSet);
begin
zqPrincipalEncabezado.Value:=zqPrincipalevento.AsString+' '+zqPrincipalcod_marca.AsString;
zqPrincipal.DisableControls;
zqPrincipal.EnableControls;
end;
procedure TfmEditarMarcado.zqPrincipalidevento_marcaChange(Sender: TField);
begin
HabilitarCampos;
end;
procedure TfmEditarMarcado.zqPrincipalNewRecord(DataSet: TDataSet);
begin
zqPrincipalidmarca.Value:=zcePrincipal.NuevoID('marcas');
zqPrincipalidmarea.Value:=dmGeneral.IdMareaActiva;
zqPrincipalfecha.Value:=Date;
zqPrincipalremarcado.Value:=0;
zqPrincipalvivo.Value:=1;
zqPrincipalliberado.Value:=1;
zqPrincipalprocesado.Value:=0;
end;
procedure TfmEditarMarcado.HabilitarCampos;
begin
dbedCodMarcaOrig.Enabled:=(zqPrincipales_marcado.AsBoolean);
dbcbRemarcado.Enabled:=(zqPrincipales_recaptura.AsBoolean);
dblkHuevos.Enabled:=dbedSexo.Text='2';
dbedPorcentHuevos.Enabled:=dbedSexo.Text='2';
if (dbedSexo.Text<>'2')
and (not zqPrincipalidcodigo_huevos.IsNull)
and (zqPrincipal.State in [dsInsert, dsEdit]) then
begin
zqPrincipalidcodigo_huevos.AsVariant:=Null;
end;
if (dbedSexo.Text<>'2')
and (not zqPrincipalporcentaje_huevos.IsNull)
and (zqPrincipal.State in [dsInsert, dsEdit]) then
begin
zqPrincipalporcentaje_huevos.AsVariant:=Null;
end;
end;
end.
|
unit uReserveServiceListener;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, synsock, uLog, uNetwork, blcksock, uReserveServiceConnection;
type
TReserveServiceListener = class(TThread)
private
{ Private declarations }
trLocalIp:string;
trPort:integer;
trLogMsg:string;
S:TTCPBlockSocket;
procedure ReadParams;
//procedure toLog;
procedure trWriteLog(msg_str:string);
//procedure UpdateCurrSocketID;
protected
{ Protected declarations }
procedure Execute; override;
public
constructor Create(local_ip: string);
end;
implementation
uses uMain;
constructor TReserveServiceListener.Create(local_ip: string);
begin
inherited create(false);
FreeOnTerminate := true;
trLocalIp := local_ip;
end;
procedure TReserveServiceListener.Execute;
var
S_res:TSocketResult;
ss:tSocket;
le:integer;
begin
FreeOnTerminate:=true;
//Synchronize(@ReadParams);
ReadParams;
S_res:=PrepereSocketToListen(trLocalIp,trPort);
While S_res.res<>1 do
begin
if Terminated then
begin
exit;
end;
trWriteLog('Error: cannot bind socket to local ip '+trLocalIp+' port '+inttostr(trPort)+'; err '+inttostr(-1*S_res.res));
trWriteLog('Waiting 5 seconds and try again..');
Sleep(5000);
S_res:=PrepereSocketToListen(trLocalIp,trPort);
end;
S:=S_res.S;
while not Terminated do
begin
if s.CanRead(500) then
begin
S.ResetLastError;
ss:=S.Accept;
le:=s.LastError;
if le<>0 Then
begin
trWriteLog('Error while accepting connection. Err '+inttostr(-1*le));
Continue;
end;
// start new thread to proceed connection
uReserveServiceConnection.TThreadReserveServiceConnection.Create(ss);
end;
end;
s.CloseSocket;
end;
procedure TReserveServiceListener.ReadParams;
begin
cs1.Enter;
trPort:=uMain.sReservServiceListeningPort;
cs1.Leave;
end;
//procedure TReserveServiceListener.toLog;
//begin
// uLog.WriteLogMsg(trLogMsg);
//end;
procedure TReserveServiceListener.trWriteLog(msg_str:string);
begin
//trLogMsg:=msg_str;
//Synchronize(@toLog);
uLog.WriteLogMsg(msg_str);
end;
end.
|
unit acDBGrid;
{$I sDefs.inc}
{.$DEFINE LOGGED}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Grids, DBGrids, DB, acsbUtils,
sConst, sDefaults, sCommonData, sMessages, sScrollBar {$IFDEF LOGGED}, sDebugMsgs{$ENDIF};
type
TsDBGrid = class;
TColumnSortOrder = (csoNone, csoAsc, csoDesc);
{ TacColumnTitle }
TacColumnTitle = class(TColumnTitle)
private
function GetCaption: string;
function IsCaptionStored: boolean;
protected
procedure SetCaption(const Value: string);
published
property Caption: string read GetCaption write SetCaption stored IsCaptionStored;
end;
{ TacDBColumn }
TacDBColumn = class (TColumn)
private
FMinWidth: integer;
FTableSpacePercent: double;
FSortOrder: TColumnSortOrder;
function GetSortOrder: TColumnSortOrder;
procedure SetSortOrder(Value: TColumnSortOrder);
procedure SetWidth(const Value: integer);
function GetWidth: integer;
procedure SetVisible(Value: Boolean);
function GetVisible: Boolean;
function CanBeSorted: boolean;
protected
function CreateTitle: TColumnTitle; override;
procedure ChangedTitle(DoRebuild: boolean);
public
constructor Create(Collection: TCollection); override;
procedure Assign(Source: TPersistent); override;
published
property Width: integer read GetWidth write SetWidth;
property Visible: Boolean read GetVisible write SetVisible;
property MinWidth: integer read FMinWidth write FMinWidth default 0;
property SortOrder: TColumnSortOrder read GetSortOrder write SetSortOrder default csoNone;
end;
{ TacDBGridColumns }
TacDBGridColumns = class(TDBGridColumns)
private
function GetColumn(Index: Integer): TacDBColumn;
procedure SetColumn(Index: Integer; Value: TacDBColumn);
procedure ColumnAdded;
public
property Items[Index: Integer]: TacDBColumn read GetColumn write SetColumn; default;
end;
TGridDrawStateEx = set of (geHighlight, geActiveRow, geMultiSelected);
TGetCellParamsEvent = procedure (Sender: TObject; Field: TField;
AFont: TFont; var Background: TColor; State: TGridDrawState; StateEx: TGridDrawStateEx) of object;
TsDBGrid = class(TDBGrid)
private
FDefaultDrawing: boolean;
FOnGetCellParams: TGetCellParamsEvent;
FExecSorting: boolean;
FExecColAjust: boolean;
FActiveRowSelected: boolean;
FTitleButtonDown: integer;
FTitleBarUp: boolean;
FOldTitleButtonDown: integer;
FCellButtonDown: integer;
FCellButtonRow: integer;
FCellButtonCol: integer;
FCellButtonPressed: boolean;
FCellButtonRect: TRect;
FCellButtonBRect: TRect;
FLevelDelimiterChar: char;
FColumnStretch : boolean;
FColumnSort : boolean;
FCommonData: TsCommonData;
procedure UpdateHeaderHeight;
procedure DrawButton(X, Y: integer; State: boolean);
function IsOnButton(X, Y: integer): boolean;
function GetButtonRect(Cell: TGridCoord): TRect;
procedure SetLevelDelimiterChar(const Value: char);
function CalcFilterBar(Column: TColumn): TRect;
function MouseInLowerstLevel(X, Y: integer; Column: TColumn = nil): boolean;
procedure CalcTableSpacePercent;
function GetColumns: TacDBGridColumns;
procedure SetColumns(const Value: TacDBGridColumns);
protected
FHeaderHeight: integer;
FExecSizing: boolean;
ListSW : TacScrollWnd;
function CreateEditor: TInplaceEdit; override;
procedure PaintWindow(DC: HDC); override;
function GetClientRect: TRect; override;
procedure Loaded; override;
function CreateColumns: TDBGridColumns; override;
procedure ColWidthsChanged; override;
procedure Resize; override;
procedure ResizeColumns(ResizedColumn: integer = -1);
procedure DrawColumnCell(const Rect: TRect; DataCol: integer; Column: TColumn; State: TGridDrawState); override;
procedure GetCellProps(Field: TField; AFont: TFont; var Background: TColor; State: TGridDrawState; StateEx:TGridDrawStateEx); dynamic;
procedure DrawCell(ACol, ARow: Longint; ARect: TRect; AState: TGridDrawState); 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;
function CanEditShow: boolean; override;
procedure TopLeftChanged; override;
procedure WMMouseWheel(var Message: TWMMouseWheel); message WM_MOUSEWHEEL;
procedure TitleClick(Column: TColumn); override;
procedure LayoutChanged; override;
property DefaultRowHeight;
property DataLink;
procedure WndProc (var Message: TMessage); override;
public
procedure AfterConstruction; override;
function GetGridSize: integer;
constructor Create(Owner: TComponent); override;
destructor Destroy; override;
property SelectedRows;
procedure CalcTitleLevel(Level: integer; var aRect: TRect);
function GetTitleLevel(Level: integer): TRect;
procedure AdjustColumns;
published
property SkinData : TsCommonData read FCommonData write FCommonData;
property DefaultDrawing: boolean read FDefaultDrawing write FDefaultDrawing default True;
property LevelDelimiterChar: char read FLevelDelimiterchar write SetLevelDelimiterchar default '|';
property OnGetCellParams: TGetCellParamsEvent read FOnGetCellParams write FOnGetCellParams;
property Columns: TacDBGridColumns read GetColumns write SetColumns stored False;
end;
implementation
uses
Math, sStyleSimply, acntUtils, sVclUtils, sMaskData, sGraphUtils, sSkinProps,
sAlphaGraph, sSkinManager{$IFNDEF DELPHI5}, types{$ENDIF};
var
DrawBitmap: TBitmap;
UserCount: integer;
type
_TCustomControl = class(TWinControl)
private
FCanvas: TCanvas;
end;
TInthernalEdit = class(TEdit)
end;
{$IFNDEF CLR}
_TCustomGrid = class(TCustomGrid)
end;
{$ENDIF}
procedure RefreshGridScrolls(SkinData : TsCommonData; var ListSW : TacScrollWnd);
begin
if SkinData.Skinned then begin
if (ListSW <> nil) and ListSW.Destroyed then FreeAndNil(ListSW);
if ListSW = nil then ListSW := TacEditWnd.Create(TWinControl(SkinData.FOwnerControl).Handle, SkinData, SkinData.SkinManager, SkinData.SkinSection);
end
else begin
if ListSW <> nil then FreeAndNil(ListSW);
end;
end;
procedure UsesBitmap;
begin
if UserCount = 0 then DrawBitmap := TBitmap.Create;
Inc(UserCount);
end;
procedure ReleaseBitmap;
begin
Dec(UserCount);
if UserCount = 0 then DrawBitmap.Free;
end;
function GetCaptionDepth(const Str: string; Delim: char): integer;
var
i: integer;
St: string;
begin
Result := 0;
if Str = '' then Exit;
Result := 1;
i := Pos(Delim, Str);
St := Str;
while i > 0 do begin
Inc(Result);
St[i] := #255;
i := Pos(Delim, St);
end;
end;
function GetCaptionLevel(const Str: string; Level: integer; Delim: char): string;
var
i,j: integer;
St: string;
begin
j := 0;
Result := '';
if Str = '' then
Exit;
i := Pos(Delim, Str);
St := Str;
while (Level > 0) and (I > 0) do begin
Dec(Level);
St[i] := #255;
if Level <= -2 then begin
Result := Copy(St, j + 1, i - 1);
exit;
end;
j := i;
i := Pos(Delim, St);
end;
if Level <= 0 then begin
if i = 0 then i := Length(St) + j else Dec(i);
Result := Copy(Str, j + 1, i - j);
exit;
end;
end;
{ TacColumnTitle }
function TacColumnTitle.GetCaption: string;
begin
Result := inherited Caption;
end;
function TacColumnTitle.IsCaptionStored: boolean;
begin
Result := (cvTitleCaption in Column.AssignedValues) and (Caption <> DefaultCaption);
end;
procedure TacColumnTitle.SetCaption(const Value: string);
begin
if Value <> inherited Caption then begin
inherited Caption := Value;
TacDBColumn(Column).ChangedTitle(True);
end;
end;
{ TacDBColumn }
function TacDBColumn.GetSortOrder: TColumnSortOrder;
begin
Result := FSortOrder;
end;
procedure TacDBColumn.SetSortOrder(Value: TColumnSortOrder);
begin
if not CanBeSorted then Exit;
FSortOrder := Value;
end;
procedure TacDBColumn.Assign(Source: TPersistent);
begin
if Source is TacDBColumn then begin
if Assigned(Collection) then Collection.BeginUpdate;
inherited Assign(Source);
try
FMinWidth := TacDBColumn(Source).FMinWidth;
finally
if Assigned(Collection) then Collection.EndUpdate;
end;
end
else inherited Assign(Source);
end;
function TacDBColumn.CanBeSorted: boolean;
begin
if Assigned(Field) then Result := (Field.FieldKind = fkData) and not (Field.DataType in [ftFmtMemo, ftMemo{$IFNDEF VER4}, ftOraClob {$ENDIF}]) else Result := False;
end;
procedure TacDBColumn.ChangedTitle(DoRebuild: boolean);
begin
if DoRebuild then if Assigned(Grid) then TsDBGrid(Grid).LayoutChanged;
end;
function TacDBColumn.CreateTitle: TColumnTitle;
begin
Result := TacColumnTitle.Create(Self);
end;
constructor TacDBColumn.Create(Collection: TCollection);
begin
inherited;
FMinWidth := 0;
TacDBGridColumns(Collection).ColumnAdded;
end;
procedure TacDBColumn.SetWidth(const Value: integer);
begin
if Value > FMinWidth then inherited Width := Value else inherited Width := FMinWidth
end;
function TacDBColumn.GetWidth: integer;
begin
Result := inherited Width;
end;
procedure TacDBColumn.SetVisible(Value: Boolean);
var
OldVisible: boolean;
begin
OldVisible := inherited Visible;
inherited Visible := Value;
if (OldVisible <> Value) and Assigned(Grid) and TsDBGrid(Grid).FColumnStretch and (not TsDBGrid(Grid).FExecSizing) then begin
TsDBGrid(Grid).FExecSizing := True;
TsDBGrid(Grid).ResizeColumns;
TsDBGrid(Grid).FExecSizing := False;
end;
end;
function TacDBColumn.GetVisible: Boolean;
begin
Result := inherited Visible;
end;
{ TacDBGridColumns }
function TacDBGridColumns.GetColumn(Index: Integer): TacDBColumn;
begin
Result := TacDBColumn(inherited Items[Index]);
end;
procedure TacDBGridColumns.SetColumn(Index: Integer; Value: TacDBColumn);
begin
inherited Items[Index] := Value;
end;
procedure TacDBGridColumns.ColumnAdded;
begin
TsDBGrid(Grid).CalcTableSpacePercent;
end;
{ TsDBGrid }
constructor TsDBGrid.Create(Owner: TComponent);
begin
inherited Create(Owner);
Columns.State := csDefault;
UsesBitmap;
FLevelDelimiterChar := '|';
inherited DefaultDrawing := False;
FDefaultDrawing := True;
FColumnStretch := false;
FColumnSort := false;
FExecSizing := False;
FTitleButtonDown := -1;
FOldTitleButtonDown := -1;
FCellButtonDown := -1;
FCommonData := TsCommonData.Create(Self, True);
FCommonData.COC := COC_TsDBGrid;
end;
destructor TsDBGrid.Destroy;
begin
if ListSW <> nil then FreeAndNil(ListSW);
if Assigned(FCommonData) then FreeAndNil(FCommonData);
ReleaseBitmap;
inherited;
end;
procedure TsDBGrid.Loaded;
var
Stretched: Boolean;
begin
Stretched := FColumnStretch;
FColumnStretch := false;
inherited Loaded;
try
FCommonData.Loaded;
except
Application.HandleException(Self);
end;
FColumnStretch := Stretched;
CalcTableSpacePercent;
end;
procedure TsDBGrid.AfterConstruction;
begin
inherited AfterConstruction;
try
FCommonData.Loaded;
except
Application.HandleException(Self);
end;
end;
function TsDBGrid.CreateColumns: TDBGridColumns;
begin
Result := TacDBGridColumns.Create(Self, TacDBColumn);
end;
procedure TsDBGrid.Resize;
begin
inherited;
if FColumnStretch and not (csLoading in ComponentState) and (not FExecSizing) then begin
FExecSizing := True;
try
ResizeColumns;
finally
FExecSizing := False;
end;
end;
end;
procedure TsDBGrid.ColWidthsChanged;
var
i: integer;
ResizedColumn: integer;
begin
if FColumnStretch and not (csLoading in ComponentState) and (not FExecSizing) then begin
FExecSizing := True;
ResizedColumn := -1;
for i := 0 to Columns.Count - 1 do if ColWidths[i + IndicatorOffset] <> Columns[i].Width then begin
ResizedColumn := i;
break;
end;
if ResizedColumn <> -1 then begin
if ColWidths[ResizedColumn + IndicatorOffset] <= TacDBColumn(Columns[ResizedColumn]).MinWidth then ColWidths[ResizedColumn + IndicatorOffset] := TacDBColumn(Columns[ResizedColumn]).MinWidth;
ResizeColumns(ResizedColumn);
end;
FExecSizing := False;
end
else if not (csLoading in ComponentState) and (not FExecSizing) then CalcTableSpacePercent;
inherited;
end;
function TsDBGrid.GetGridSize: integer;
begin
Result := ClientWidth - 1;
if dgIndicator in Options then Dec(Result, IndicatorWidth);
if dgColLines in Options then Dec(Result, Columns.Count * GridLineWidth);
end;
procedure TsDBGrid.ResizeColumns(ResizedColumn: integer);
const
MinWidth = 10;
var
i: integer;
GridSize, ColumnsSize:integer;
UnresizedSize: integer;
K: double;
Curr,Prev: double;
Width: integer;
MinimizeRest: boolean;
VisiblePercent: double;
begin
if Columns.Count = 0 then Exit;
GridSize := ClientWidth - 1;
if dgIndicator in Options then Dec(GridSize, IndicatorWidth);
if dgColLines in Options then for i := 0 to Columns.Count - 1 do if TacDBColumn(Columns[i]).Visible then Dec(GridSize, GridLineWidth);
if ResizedColumn > -1 then begin
ColumnsSize := 0;
UnresizedSize := 0;
MinimizeRest := False;
for i := 0 to Columns.Count - 1 do begin
if i <= ResizedColumn then begin
Inc(UnresizedSize, ColWidths[i + IndicatorOffset]);
if i = ResizedColumn then
if ColumnsSize + ColWidths[i + IndicatorOffset] + (Columns.Count - i) * MinWidth > GridSize then begin
ColWidths[i + IndicatorOffset] := GridSize - ColumnsSize - (Columns.Count - i - 1) * MinWidth;
MinimizeRest := True;
end
else if i = Columns.Count - 1 then ColWidths[i + IndicatorOffset] := GridSize - ColumnsSize;
end
else if MinimizeRest then ColWidths[i + IndicatorOffset] := MinWidth;
Inc(ColumnsSize, ColWidths[i + IndicatorOffset]);
end;
if ColumnsSize = UnresizedSize then Exit;
K := (GridSize - UnresizedSize) / (ColumnsSize - UnresizedSize);
ColumnsSize := 0;
Prev := 0;
for i := 0 to Columns.Count - 1 do begin
if i <= ResizedColumn then Curr := Prev + ColWidths[i + IndicatorOffset] else begin
Curr := Prev + ColWidths[i + IndicatorOffset]*K;
if i < Columns.Count - 1 then Width := Round(Curr - Prev) else Width := GridSize - ColumnsSize;
if Width < TacDBColumn(Columns[i]).MinWidth then Width := TacDBColumn(Columns[i]).MinWidth;
ColWidths[i + IndicatorOffset] := Width;
end;
Inc(ColumnsSize, ColWidths[i + IndicatorOffset]);
Prev := Curr;
end;
CalcTableSpacePercent;
end
else begin // for a full resize
Inc(GridSize, 2);
if FColumnStretch then begin
VisiblePercent := 0;
for i := 0 to Columns.Count - 1 do
if TacDBColumn(Columns[i]).Visible then VisiblePercent := VisiblePercent + TacDBColumn(Columns[i]).FTableSpacePercent;
if VisiblePercent < 0.0001 then VisiblePercent := 1;
end
else VisiblePercent := 1;
for i := 0 to Columns.Count - 1 do ColWidths[i + IndicatorOffset] := Trunc(TacDBColumn(Columns[i]).FTableSpacePercent * GridSize / VisiblePercent);
end;
end;
{ Grid drawing }
procedure TsDBGrid.GetCellProps(Field: TField; AFont: TFont; var Background: TColor; State: TGridDrawState; StateEx: TGridDrawStateEx);
begin
if Assigned(FOnGetCellParams) then FOnGetCellParams(Self, Field, AFont, Background, State, StateEx);
end;
procedure WriteText(ACanvas: TCanvas; ARect: TRect; DX, DY: integer; const Text: string; Alignment: TAlignment; ARightToLeft: boolean);
const
AlignFlags : array [TAlignment] of integer = (DT_LEFT or DT_WORDBREAK or DT_EXPANDTABS or DT_NOPREFIX,
DT_RIGHT or DT_WORDBREAK or DT_EXPANDTABS or DT_NOPREFIX,
DT_CENTER or DT_WORDBREAK or DT_EXPANDTABS or DT_NOPREFIX);
RTL: array [boolean] of integer = (0, DT_RTLREADING);
var
B, R: TRect;
Hold, Left: integer;
I: TColorRef;
begin
I := ColorToRGB(ACanvas.Brush.Color);
if GetNearestColor(ACanvas.Handle, I) = I then begin
if Text <> '' then begin
if (ACanvas.CanvasOrientation = coRightToLeft) and (not ARightToLeft) then ChangeBiDiModeAlignment(Alignment);
case Alignment of
taLeftJustify: Left := ARect.Left + DX;
taRightJustify: Left := ARect.Right - ACanvas.TextWidth(Text) - 3;
else Left := ARect.Left + (ARect.Right - ARect.Left) shr 1 - (ACanvas.TextWidth(Text) shr 1);
end;
if ARightToLeft then ACanvas.TextFlags := ACanvas.TextFlags or ETO_RTLREADING;
acTextRect(ACanvas, ARect, Left, ARect.Top + DY, Text);
end
else ACanvas.FillRect(ARect);
end
else begin { Use FillRect and Drawtext for different colors }
if ACanvas.Brush.Style <> bsClear then begin
DrawBitmap.Canvas.Lock;
try
with DrawBitmap, ARect do begin { Use offscreen bitmap to eliminate flicker and brush origin tics in painting / scrolling. }
Width := Max(Width, Right - Left);
Height := Max(Height, Bottom - Top);
R := Rect(DX, DY, Right - Left - 1, Bottom - Top - 1);
B := Rect(0, 0, Right - Left, Bottom - Top);
end;
with DrawBitmap.Canvas do begin
Font := ACanvas.Font;
Font.Color := ACanvas.Font.Color;
Brush := ACanvas.Brush;
Brush.Style := bsSolid;
FillRect(B);
SetBkMode(Handle, TRANSPARENT);
if (ACanvas.CanvasOrientation = coRightToLeft) then ChangeBiDiModeAlignment(Alignment);
acDrawText(Handle, PacChar(Text), R, AlignFlags[Alignment] or RTL[ARightToLeft]);
end;
if (ACanvas.CanvasOrientation = coRightToLeft) then begin
Hold := ARect.Left;
ARect.Left := ARect.Right;
ARect.Right := Hold;
end;
ACanvas.CopyRect(ARect, DrawBitmap.Canvas, B);
finally
DrawBitmap.Canvas.Unlock;
end;
end
else begin
end;
end;
end;
function TsDBGrid.GetButtonRect(Cell: TGridCoord): TRect;
var
aCellRect: TRect;
begin
aCellRect := CellRect(Cell.X, Cell.Y);
if (aCellRect.Right - aCellRect.Left < aCellRect.Bottom - aCellRect.Top + 5) then begin
Result := Rect(0, 0, 0, 0);
exit;
end;
Result.Left := aCellRect.Right - (aCellRect.Bottom - aCellRect.Top)+1;
Result.Right := aCellRect.Right-1;
Result.Top := aCellRect.Top+1;
Result.Bottom := aCellRect.Bottom-1;
end;
function TsDBGrid.IsOnButton(X, Y: integer): boolean;
var
Cell: TGridCoord;
Column: TColumn;
aCellRect: TRect;
ButtonRect: TRect;
begin
Cell := MouseCoord(X,Y);
Column := Columns[RawToDataColumn(Cell.X)];
// detecting - is there a button on cell?
if Assigned(Column.Field) then Result := Column.Field.DataType in [ftMemo,ftFmtMemo {$IFNDEF VER4}, ftOraClob {$ENDIF}] else Result := False;
aCellRect := CellRect(Cell.X, Cell.Y);
if Result and (aCellRect.Right - aCellRect.Left < aCellRect.Bottom - aCellRect.Top + 5) then Result := False;
if Result then begin // button present
ButtonRect := GetButtonRect(Cell);
Result := PtInRect(ButtonRect,Point(X,Y))
end
else { there is no button on cell } Result := False;
end;
procedure TsDBGrid.DrawButton(X, Y: integer; State: boolean);
var
ButtonRect: TRect;
Cell: TGridCoord;
Hi, i, Diam: integer;
Flag: integer;
begin
Cell.X := X; Cell.Y := Y;
ButtonRect := GetButtonRect(Cell);
Canvas.Brush.Style := bsSolid;
Canvas.Brush.Color := clBtnFace;
Canvas.FillRect(ButtonRect);
Canvas.Pen.Color := clBlack;
Canvas.Pen.Style := psSolid;
Canvas.Brush.Color := clBlack;
if State then Flag := BDR_SUNKENINNER else Flag := BDR_RAISEDINNER;
DrawEdge(Canvas.Handle, ButtonRect, Flag, BF_TOPLEFT );
InflateRect(ButtonRect, -1, -1);
DrawEdge(Canvas.Handle, ButtonRect, Flag, BF_BOTTOMRIGHT);
InflateRect(ButtonRect, 1, 1);
Canvas.MoveTo(ButtonRect.Left, ButtonRect.Bottom - 1);
Canvas.LineTo(ButtonRect.Right - 1, ButtonRect.Bottom - 1);
Canvas.LineTo(ButtonRect.Right - 1, ButtonRect.Top - 1);
Diam := (ButtonRect.Bottom - ButtonRect.Top) div 7;
Hi := (ButtonRect.Bottom - ButtonRect.Top - Diam) div 2;
inc(ButtonRect.Left,Diam * 2 - 1);
if State then begin
inc(ButtonRect.Left);
inc(ButtonRect.Top);
end;
for i := 0 to 2 do Canvas.Ellipse(ButtonRect.Left + i * Diam * 2 ,ButtonRect.Top + Hi, ButtonRect.Left + i * Diam * 2 + Diam, ButtonRect.Top + Hi + Diam);
end;
procedure TsDBGrid.DrawColumnCell(const Rect: TRect; DataCol: integer; Column: TColumn; State: TGridDrawState);
const
ThreeDot = '...';
var
NewBackgrnd: TColor;
Field: TField;
Value: string;
TextWidth: integer;
ThreeDotWidth: integer;
Alignment: TAlignment;
ColWidth, SelNdx: integer;
StateEx: TGridDrawStateEx;
TextMargin: integer;
i: integer;
isDrawButton: boolean;
OldCanvasFont : TFont;
CI : TCacheInfo;
begin
inherited DrawColumnCell(Rect, DataCol, Column, State);
Field := Column.Field;
if Assigned(Column.Field) then begin
Value := Column.Field.DisplayText;
isDrawButton := Column.Field.DataType in [ftMemo, ftFmtMemo {$IFNDEF VER4}, ftOraClob {$ENDIF}];
end
else begin
Value := '';
isDrawButton := False;
end;
isDrawButton := isDrawButton and (gdSelected in State) and not (dgRowSelect in Options);
if isDrawButton and (Rect.Right - Rect.Left < Rect.Bottom - Rect.Top + 5) then isDrawButton := False;
// if Column.Alignment = taLeftJustify then Alignment := Column.Title.Alignment else
Alignment := Column.Alignment;
if Alignment = taRightJustify then TextMargin:= 4 else TextMargin := 2;
ThreeDotWidth := Canvas.TextWidth(ThreeDot);
TextWidth := Canvas.TextWidth(Value) + TextMargin;
OldCanvasFont := TFont.Create;
OldCanvasFont.Assign(Canvas.Font);
try
ColWidth := Column.Width; // changes font and brush
Canvas.Font.Assign(OldCanvasFont);
finally
OldCanvasFont.Free;
end;
if isDrawButton then ColWidth := ColWidth - (Rect.Bottom - Rect.Top);
if TextWidth > ColWidth then begin
if Field is TNumericField then begin
for i := 1 to Length(Value) do if (Value[i] >= '0') and (Value[i] <= '9') then Value[i] := '#';
end
else begin
while (TextWidth > ColWidth) and (Length(Value) > 1) do begin
SetLength(Value, Length(Value) - 1);
TextWidth := Canvas.TextWidth(Value) + TextMargin + ThreeDotWidth;
end;
Value := Value + ThreeDot;
end;
Alignment := taLeftJustify;
end;
if HighlightCell(Col, Row, Value, State) then begin
Include(StateEx, geHighlight);
if not FActiveRowSelected then Include(StateEx, geMultiSelected);
end;
if FActiveRowSelected then Include(StateEx, geActiveRow);
if HighlightCell(Col, Row, Value, State) then begin
Canvas.Brush.Color := clHighlight;
Canvas.Font.Color := clHighlightText;
end;
if Enabled then begin
NewBackgrnd := Canvas.Brush.Color;
GetCellProps(Field, Canvas.Font, NewBackgrnd, State, StateEx);
Canvas.Brush.Color := NewBackgrnd;
end
else Canvas.Font.Color := clGrayText;
if FDefaultDrawing then begin
if (gdSelected in State) and Focused then begin
if SkinData.Skinned then begin
SelNdx := SkinData.SkinManager.GetSkinIndex(s_Selection);
CI.FillColor := Color;
CI.Ready := False;
PaintItem(SelNdx, s_Selection, CI, True, 1, Rect, Point(0, 0), Canvas.Handle, SkinData.SkinManager);
Canvas.Brush.Style := bsClear;
Canvas.Font.Color := SkinData.SkinManager.GetHighLightFontColor;
end
// else Canvas.FillRect(Rect);
end;
WriteText(Canvas, Rect, 2, 2, Value, Alignment, UseRightToLeftAlignmentForField(Column.Field, Alignment));
if (gdSelected in State) and ((dgAlwaysShowSelection in Options) or Focused) and not (csDesigning in ComponentState)
and not (dgRowSelect in Options) and (UpdateLock = 0) and (ValidParentForm(Self).ActiveControl = Self) then Windows.DrawFocusRect(Canvas.Handle, Rect);
end;
inherited DrawColumnCell(Rect, DataCol, Column, State);
if isDrawButton then begin
if FCellButtonDown > -1 then DrawButton(Col, Row, FCellButtonPressed) else DrawButton(COl, Row, False);
end;
end;
function TsDBGrid.GetTitleLevel(Level: integer): TRect;
begin
if Columns.Count = 0 then begin
Result := Rect(0, 0, 0, 0);
Exit;
end;
Result.Top := Level*(DefaultRowHeight + 1);
Result.Bottom := Result.Top + (DefaultRowHeight + 1);
Result.Left := 0;
Result.Right := 0;
if dgRowLines in Options then dec(Result.Bottom);
end;
procedure TsDBGrid.CalcTitleLevel(Level: integer; var aRect: TRect);
var
X: TRect;
begin
if Columns.Count = 0 then begin
aRect.Top := 0;
aRect.Bottom:= 0;
Exit;
end;
X := GetTitleLevel(Level);
aRect.Top := X.Top;
aRect.Bottom := X.Bottom;
end;
procedure TsDBGrid.DrawCell(ACol,ARow: longint; ARect: TRect; AState: TGridDrawState);
var
FrameOffs: Byte;
// Std mode
procedure DrawTitleCell(ACol, ARow: integer; Column: TColumn; var AState: TGridDrawState);
const
ScrollArrows: array [boolean, boolean] of integer = ((DFCS_SCROLLRIGHT, DFCS_SCROLLLEFT), (DFCS_SCROLLLEFT, DFCS_SCROLLRIGHT));
var
MasterCol: TColumn;
CellRect: TRect;
TitleRect, TextRect: TRect;
Caption: string;
CaptionWidth: integer;
CurLevel: integer;
CurCaption: string;
lvCheckLeft, lvCheckRight, lvShowCaption, lvUpBorder, lvDownBorder, lvLeftBorder, lvRightBorder, lvCheckTextWidth : boolean;
TmpCaption: string;
lvTmpCol: TColumn;
lvTmpColIndex: integer;
lvCaptionXOffset: integer;
lvCaptionAligment : TAlignment;
CellFlag: cardinal;
CaptionDepth: integer;
PressOffset: integer;
begin
CellRect := CalcTitleRect(Column, ARow, MasterCol);
TitleRect := CellRect;
if MasterCol = nil then begin
Canvas.FillRect(ARect);
Exit;
end;
Canvas.Font := MasterCol.Title.Font;
Canvas.Brush.Color := MasterCol.Title.Color;
Canvas.FillRect(ARect);
TextRect := TitleRect;
Caption := MasterCol.Title.Caption;
lvCheckLeft := True;
lvCheckRight := True;
lvShowCaption:= True;
lvLeftBorder := True;
lvRightBorder:= True;
if TacColumnTitle(MasterCol.Title).IsCaptionStored
then CaptionDepth := GetCaptionDepth(Caption,FLevelDelimiterChar)
else CaptionDepth := 1;
FrameOffs := 1;
if (Column.Index = FTitleButtonDown) and (dgRowLines in Options) then PressOffset := 1 else PressOffset := 0;
for CurLevel := 0 to FHeaderHeight - 1 do begin
// Check dependencies
if TacColumnTitle(MasterCol.Title).IsCaptionStored then
CurCaption := GetCaptionLevel(Caption,CurLevel,FLevelDelimiterChar)
else
if CurLevel = 0 then CurCaption := Caption else CurCaption := '';
lvDownBorder := (FHeaderHeight - 1 = CurLevel) or (GetCaptionLevel(Caption,CurLevel+1,FLevelDelimiterChar)<>'');
lvUpBorder := (CurCaption <> '');
lvCaptionXOffset := 0;
if CurCaption <> '' then begin
if lvCheckLeft then begin
lvLeftBorder := True;
lvShowCaption:= True;
if (Column.Index = 0) or (CurLevel = (CaptionDepth-1)) then lvCheckLeft := False else begin
lvTmpColIndex := Column.Index-1;
while lvTmpColIndex >= 0 do begin
lvTmpCol := TColumn(MasterCol.Collection.Items[lvTmpColIndex]);
tmpCaption := GetCaptionLevel(lvTmpCol.Title.Caption,CurLevel,FLevelDelimiterChar);
if UpperCase(tmpCaption) <> UpperCase(CurCaption) then begin
if lvTmpColIndex = Column.Index - 1 then lvCheckLeft := False;
break;
end
else begin
lvShowCaption := False;
lvLeftBorder := False;
inc(lvCaptionXOffset, lvTmpCol.Width);
if dgColLines in Options then
inc(lvCaptionXOffset);
dec(lvTmpColIndex)
end;
end;
end;
end;
if lvCheckRight then begin
lvRightBorder := True;
if (Column.Index = MasterCol.Collection.Count - 1) or (CurLevel = (CaptionDepth-1)) then
lvCheckRight := False
else begin
lvTmpColIndex := Column.Index+1;
lvTmpCol := TColumn(MasterCol.Collection.Items[lvTmpColIndex]);
tmpCaption := GetCaptionLevel(lvTmpCol.Title.Caption,CurLevel,FLevelDelimiterChar);
if UpperCase(tmpCaption) <> UpperCase(CurCaption) then lvCheckRight := False else lvRightBorder := False;
end;
end;
end;
//Check if we need to control caption width
if Column.Index = MasterCol.Collection.Count - 1 then lvCheckTextWidth := True else begin
lvTmpColIndex := Column.Index+1;
lvTmpCol := TColumn(MasterCol.Collection.Items[lvTmpColIndex]);
tmpCaption := GetCaptionLevel(lvTmpCol.Title.Caption,CurLevel,FLevelDelimiterChar);
if UpperCase(tmpCaption) <> UpperCase(CurCaption) then lvCheckTextWidth := True else lvCheckTextWidth := False;
end;
// draw text for level
TitleRect := CellRect;
CalcTitleLevel(CurLevel,TitleRect);
TextRect := TitleRect;
InflateRect(TextRect,-1,-1);
if not lvRightBorder then begin
inc(TextRect.Right);
if (dgColLines in Options) then inc(TextRect.Right);
end;
if CurLevel <> (CaptionDepth-1) then begin
Canvas.Font := Self.TitleFont;
Canvas.Brush.Color := Self.FixedColor;
lvCaptionAligment := taLeftJustify;
end
else begin
Canvas.Font := MasterCol.Title.Font;
Canvas.Brush.Color := MasterCol.Title.Color;
lvCaptionAligment := MasterCol.Title.Alignment;
end;
Canvas.FillRect(TextRect);
if lvShowCaption then begin
CaptionWidth := Canvas.TextWidth(CurCaption);
if lvCheckTextWidth and (CaptionWidth > TextRect.Right - TextRect.Left) then begin
while (CaptionWidth > TextRect.Right - TextRect.Left) and (Length(CurCaption) > 1) do begin
SetLength(CurCaption, Length(CurCaption) - 1);
CaptionWidth := Canvas.TextWidth(CurCaption) + Canvas.TextWidth('...');
end;
CurCaption := CurCaption + '...';
end;
WriteText(Canvas, TextRect, FrameOffs + PressOffset, FrameOffs + PressOffset, CurCaption, lvCaptionAligment, IsRightToLeft);
end
else
if CurCaption = '' then
WriteText(Canvas, TextRect, FrameOffs, FrameOffs, '', lvCaptionAligment, IsRightToLeft)
else begin // mean there is coninue of previous column
if dgColLines in Options then begin
dec(TextRect.Left,1);
dec(lvCaptionXOffset,1);
end;
CaptionWidth := Canvas.TextWidth(CurCaption) - lvCaptionXOffset;
if lvCheckTextWidth and (CaptionWidth > TextRect.Right - TextRect.Left) then begin
while (CaptionWidth > TextRect.Right - TextRect.Left) and (Length(CurCaption) > 1) do begin
SetLength(CurCaption, Length(CurCaption) - 1);
CaptionWidth := Canvas.TextWidth(CurCaption) + Canvas.TextWidth('...') - lvCaptionXOffset;
end;
CurCaption := CurCaption + '...';
end;
WriteText(Canvas, TextRect, FrameOffs - lvCaptionXOffset, FrameOffs, CurCaption, lvCaptionAligment, IsRightToLeft);
end;
// draw borders for level
CellFlag := BDR_RAISEDINNER;
if (FTitleButtonDown = Column.Index)and(CurLevel >= CaptionDepth-1) then
CellFlag := BDR_SUNKENINNER;
if not lvDownBorder then begin
Inc(TitleRect.Bottom,1);
Canvas.Pen.Color := clBtnFace;
Canvas.MoveTo(TitleRect.Left,TitleRect.Bottom - 2);
Canvas.LineTo(TitleRect.Right + 1, TitleRect.Bottom - 2);
if dgRowLines in Options then begin
Canvas.MoveTo(TitleRect.Left, TitleRect.Bottom - 1);
Canvas.LineTo(TitleRect.Right + 1, TitleRect.Bottom - 1);
end;
end;
if not lvUpBorder then begin
Canvas.Pen.Color := clBtnFace;
Canvas.MoveTo(TitleRect.Left, TitleRect.Top);
Canvas.LineTo(TitleRect.Right + 1, TitleRect.Top);
end;
if lvRightBorder then begin
if (dgRowLines in Options) and (dgColLines in Options) then DrawEdge(Canvas.Handle, TitleRect, CellFlag, BF_RIGHT);
end
else Inc(TitleRect.Right,1);
if dgColLines in Options then begin
Canvas.Pen.Color := clBlack;
Canvas.MoveTo(TitleRect.Right, TitleRect.Top);
Canvas.LineTo(TitleRect.Right, TitleRect.Bottom + 1);
end;
if lvDownBorder and ((dgRowLines in Options) and (dgColLines in Options)) then DrawEdge(Canvas.Handle, TitleRect, CellFlag, BF_BOTTOM);
if dgRowLines in Options then begin
Canvas.Pen.Color := clBlack;
Canvas.MoveTo(TitleRect.Left,TitleRect.Bottom);
Canvas.LineTo(TitleRect.Right + 1,TitleRect.Bottom);
end;
if lvUpBorder and ((dgRowLines in Options) and (dgColLines in Options)) then DrawEdge(Canvas.Handle, TitleRect, CellFlag, BF_TOP);
if lvLeftBorder and ((dgRowLines in Options) and (dgColLines in Options)) then DrawEdge(Canvas.Handle, TitleRect, CellFlag, BF_LEFT);
end;
AState := AState - [gdFixed]; // prevent box drawing later
end;
procedure ColumnSkinPaint(ControlRect : TRect; cIndex : Integer);
var
CI : TCacheInfo;
R, TextRC : TRect;
TempBmp : Graphics.TBitmap;
State, si : integer;
R1 : TRect;
Mode : integer;
c : TsColor;
Size : TSize;
BtnIndex : integer;
Alignment: TAlignment;
begin
try
TempBmp := CreateBmp32(WidthOf(ControlRect), HeightOf(ControlRect));
CI := MakeCacheInfo(FCommonData.FCacheBmp, ControlRect.Left, ControlRect.Top);
R := Rect(0, 0, TempBmp.Width, TempBmp.Height);
State := 0;
if FTitleButtonDown > -1 then if cIndex = FTitleButtonDown then State := 2;
si := FCommonData.SkinManager.GetSkinIndex(s_ColHeader);
if FCommonData.SkinManager.IsValidSkinIndex(si) then begin
PaintItem(si, s_ColHeader, Ci, True, State, r, Point(0, 0), TempBmp)
end
else begin
si := FCommonData.SkinManager.GetSkinIndex(s_Button);
PaintItem(si, s_Button, Ci, True, State, r, Point(0, 0), TempBmp)
end;
TempBmp.Canvas.Font.Assign(Font);
TextRC := R;
InflateRect(TextRC, -1, -1);
TextRc.Left := TextRc.Left + 4 + integer(State = 2);
TextRc.Right := TextRc.Right - TextRc.Left - 4 + integer(State = 2);
TextRc.Top := TextRc.Top + integer(State = 2);
TextRc.Bottom := TextRc.Bottom + integer(State = 2);
TempBmp.Canvas.Brush.Style := bsClear;
if cIndex >= 0 then begin
if (Columns[cIndex].Field = nil) or (Columns[cIndex].Alignment = Columns[cIndex].Field.Alignment) then Alignment := Columns[cIndex].Title.Alignment else Alignment := Columns[cIndex].Alignment;
if IsRightToLeft then begin
BitBlt(Canvas.Handle, ControlRect.Left, ControlRect.Top, R.Right, R.Bottom, TempBmp.Canvas.Handle, 0, 0, SRCCOPY);
R := TextRc;
ChangeI(R.Left, R.Right);
OffsetRect(R, ControlRect.Left + Canvas.TextWidth(Columns[cIndex].Title.Caption) + 15 - TempBmp.Width, ControlRect.Top);
WriteTextEx(Canvas, PChar(Columns[cIndex].Title.Caption), True, R,
DT_RTLREADING or DrawTextBiDiModeFlags(DT_EXPANDTABS or DT_WORDBREAK or GetStringFlags(Self, Alignment)),
si, (State <> 0), SkinData.SkinManager)
end
else begin
WriteTextEx(TempBmp.Canvas, PChar(Columns[cIndex].Title.Caption), True, TextRc,
DrawTextBiDiModeFlags(DT_EXPANDTABS or DT_WORDBREAK or GetStringFlags(Self, Alignment)),
si, (State <> 0), SkinData.SkinManager);
BitBlt(Canvas.Handle, ControlRect.Left, ControlRect.Top, R.Right, R.Bottom, TempBmp.Canvas.Handle, 0, 0, SRCCOPY);
end;
end
else begin
if FActiveRowSelected then begin // Indicator
if (DataLink <> nil) and DataLink.Active and DataLink.Editing then begin
TempBmp.Canvas.Font.Assign(Font);
TempBmp.Canvas.Font.Color := FCommonData.SkinManager.gd[si].Props[0].FontColor.Color;
TempBmp.Canvas.Font.Name := 'Courier';
Size := acTextExtent(TempBmp.Canvas, 'I');
TempBmp.Canvas.TextOut(R.Left + (WidthOf(R) - Size.cx) div 2 - 1, R.Top + (HeightOf(R) - Size.cy) div 2, 'I');
end
else begin
BtnIndex := FCommonData.SkinManager.GetMaskIndex(FCommonData.SkinIndex, s_ScrollBtnRight, s_ItemGlyph);
if FCommonData.SkinManager.IsValidImgIndex(BtnIndex) then begin
if ControlIsActive(FCommonData) then c.C := FCommonData.SkinManager.gd[FCommonData.SkinIndex].HotColor else c.C := FCommonData.SkinManager.gd[FCommonData.SkinIndex].Color;
R1 := R;
R1.Top := R1.Top + 4;
if ControlIsActive(FCommonData) then Mode := 1 else Mode := 0;
DrawSkinGlyph(TempBmp, Point(R1.Left + (WidthOf(R1) - WidthOfImage(FCommonData.SkinManager.ma[BtnIndex])) div 2, R1.Top), Mode, 1, FCommonData.SkinManager.ma[BtnIndex], MakeCacheInfo(TempBmp));
end;
end;
end;
BitBlt(Canvas.Handle, ControlRect.Left, ControlRect.Top, R.Right, R.Bottom, TempBmp.Canvas.Handle, 0, 0, SRCCOPY);
end;
TempBmp.Free
except
Application.HandleException(Self);
end;
end;
var
DrawColumn: TColumn;
begin
if FCommonData.Skinned then begin
if (ARow = 0) and (dgTitles in Options) then begin
FActiveRowSelected := false;
ARect.Right := ARect.Right + 1;
ARect.Bottom := ARect.Bottom + 1;
ColumnSkinPaint(ARect, ACol - IndicatorOffset);
end
else begin
if DataLink.Active then
if dgTitles in Options then
FActiveRowSelected := ARow - 1 = DataLink.ActiveRecord
else
FActiveRowSelected := ARow = DataLink.ActiveRecord
else
FActiveRowSelected := False;
if (ACol - IndicatorOffset) < 0 then begin
ARect.Right := ARect.Right + 1;
ARect.Bottom := ARect.Bottom + 1;
ColumnSkinPaint(ARect, ACol - IndicatorOffset);
end
else inherited DrawCell(ACol, ARow, ARect, AState);
end;
end
else begin
if (ARow = 0) and (dgTitles in Options) then begin
if ACol >= IndicatorOffset then begin
DrawColumn := Columns[ACol - IndicatorOffset];
DrawTitleCell(ACol - IndicatorOffset, ARow, DrawColumn, AState);
end
else begin
inherited DrawCell(ACol, ARow, ARect, AState);
end
end
else begin
if DataLink.Active then
if dgTitles in Options then FActiveRowSelected := ARow - 1 = DataLink.ActiveRecord else FActiveRowSelected := ARow = DataLink.ActiveRecord
else FActiveRowSelected := False;
inherited DrawCell(ACol, ARow, ARect, AState);
if gdFixed in AState then begin
if dgColLines in Options then begin
Canvas.Pen.color := clBlack;
Canvas.Pen.style := psSolid;
Canvas.MoveTo(aRect.Right, aRect.Top);
Canvas.LineTo(aRect.Right, aRect.Bottom + 1);
end;
if dgRowLines in Options then begin
Canvas.Pen.color := clBlack;
Canvas.Pen.style := psSolid;
Canvas.MoveTo(aRect.Left, aRect.Bottom);
Canvas.LineTo(aRect.Right, aRect.Bottom);
end;
end;
end;
end;
end;
procedure TsDBGrid.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: integer);
var
State: TGridState;
DrawInfo: TGridDrawInfo;
Index: longint;
Pos, Ofs: integer;
OldActive: integer;
Cell: TGridCoord;
i: integer;
Column: TColumn;
Value: string;
ColWidth, ValueWidth: integer;
begin
FExecColAjust := False;
if FGridState = gsNormal then begin
CalcDrawInfo(DrawInfo);
CalcSizingState(X, Y, State, Index, Pos, Ofs, DrawInfo);
end
else State := FGridState;
if not (State in [gsColSizing]) and DataLink.Active then begin
if (Button = mbLeft) and (dgTitles in Options) then begin
Cell := MouseCoord(X,Y);
if Cell.X >= IndicatorOffset then begin
if not (dgRowSelect in Options) and (Cell.Y >= FixedRows) and (TopRow + Cell.Y - FixedRows = Row) and IsOnButton(X,Y) then begin
FCellButtonDown := RawToDataColumn(Cell.X);
FCellButtonRow := Cell.Y;
FCellButtonCol := Cell.X;
FCellButtonBRect := GetButtonRect(Cell);
FCellButtonRect := CellRect(Cell.X,Cell.Y);
HideEditor;
DrawButton(Cell.X,Cell.Y,PtInRect(FCellButtonBRect,Point(x,y)));
FCellButtonPressed := True;
Exit;
end;
if DataLink.Active and (Cell.Y < FixedRows) and FColumnSort and MouseInLowerstLevel(X, Y, nil) then begin
i := FTitleButtonDown;
FTitleButtonDown := RawToDataColumn(Cell.X);
FOldTitleButtonDown := FTitleButtonDown;
if i > -1 then InvalidateCol(i+1);
invalidatecol(FTitleButtonDown+1);
end;
end;
end;
end;
if (mbLeft = Button) and (State = gsColSizing) and DataLink.Active then begin
if ssDouble in Shift then begin
Index := Min(RawToDataColumn(MouseCoord(X, Y).X), RawToDataColumn(MouseCoord(X - 7, Y).X));
if Index < 0 then Index := Columns.Count - 1;
Column := Columns[Index];
ColWidth := 0;
OldActive := DataLink.ActiveRecord;
try
for i := TopRow - 1 to VisibleRowCount - 1 do begin
Datalink.ActiveRecord := i;
if Assigned(Column.Field) then Value := Column.Field.DisplayText else Value := '';
ValueWidth := Canvas.TextWidth(Value);
if ValueWidth > ColWidth then ColWidth := ValueWidth;
end;
finally
DataLink.ActiveRecord := OldActive;
end;
ColWidths[Index + IndicatorOffset] := ColWidth + 4;
FExecColAjust := True;
end;
end;
inherited;
end;
procedure TsDBGrid.MouseMove(Shift: TShiftState; X, Y: integer);
var
State: TGridState;
DrawInfo: TGridDrawInfo;
Index: Longint;
Pos, Ofs: integer;
Rect: TRect;
Col: TColumn;
begin
inherited;
if FGridState = gsNormal then begin
CalcDrawInfo(DrawInfo);
CalcSizingState(X, Y, State, Index, Pos, Ofs, DrawInfo);
end
else State := FGridState;
if FCellButtonDown > -1 then begin
FCellButtonPressed := PtInRect(FCellButtonBRect,Point(x,y));
DrawButton(FCellButtonCol,FCellButtonRow,FCellButtonPressed);
end;
if (ssLeft in Shift) and (FOldTitleButtonDown > -1) then begin
Rect := CalcTitleRect(Columns[FOldTitleButtonDown], 0, Col);
if (FTitleButtonDown = -1) and PtInRect(Rect,Point(X,Y)) then begin
FTitleButtonDown := FOldTitleButtonDown;
InvalidateCol(FTitleButtonDown + 1);
end
else if (FTitleButtonDown > -1) and ((Y < Rect.Top) or (Y > Rect.Bottom) or ((X < Self.Left) and
(Columns[FTitleButtonDown].Index = 0)) or ((X > Self.Left + Self.Width) and (Columns[FTitleButtonDown].Index = Columns.Count - 1))) then begin
Index := FTitleButtonDown + 1;
FTitleButtonDown := -1;
InvalidateCol(Index)
end;
end;
end;
procedure TsDBGrid.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: integer);
var
State: TGridState;
DrawInfo: TGridDrawInfo;
Index, i: Longint;
Pos, Ofs: integer;
Column: TColumn;
Cell: TGridCoord;
LastBtn: integer;
Widths: array of integer;
begin
if FGridState = gsNormal then begin
CalcDrawInfo(DrawInfo);
CalcSizingState(X, Y, State, Index, Pos, Ofs, DrawInfo);
end
else State := FGridState;
FTitleBarUp := False;
if not (State in [gsColSizing]) and DataLink.Active and not FExecColAjust then begin
Cell := MouseCoord(X,Y);
if not (dgRowSelect in Options) then if FCellButtonDown > -1 then begin
DrawButton(Cell.X,Cell.Y,False);
if FCellButtonDown = RawToDataColumn(Cell.X) then if FCellButtonPressed then begin
FCellButtonDown := -1;
FCellButtonRow := -1;
FCellButtonCol := -1;
invalidate;
end;
end;
FCellButtonDown := -1;
FCellButtonRow := -1;
FCellButtonCol := -1;
LastBtn := FTitleButtonDown;
FOldTitleButtonDown := -1;
if FTitleButtonDown > -1 then begin
invalidatecol(FTitleButtonDown + 1);
FTitleButtonDown := - 1;
end;
if (Button = mbLeft) and (Cell.Y = 0) and (dgTitles in Options) then begin
if Cell.X >= IndicatorOffset then begin
Column := Columns[RawToDataColumn(Cell.X)];
FTitleBarUp := True;
if TacDBColumn(Column).CanBeSorted and FColumnSort and MouseInLowerstLevel(X,Y,Column) and (LastBtn = Column.Index) then begin
FExecSorting := True;
BeginLayout;
try
SetLength(Widths, Columns.Count);
for i := 0 to Columns.Count - 1 do Widths[i] := Columns[i].Width;
finally
EndLayout;
for i := 0 to Columns.Count - 1 do Columns[i].Width := Widths[i];
FExecSorting := False;
end;
end;
end
end;
end;
inherited;
FTitleBarUp := False;
end;
procedure TsDBGrid.UpdateHeaderHeight;
var
Cur, i: integer;
aHeight: integer;
begin
if not (dgTitles in Options) then begin
RowHeights[0]:= DefaultRowHeight;
Exit;
end;
FHeaderHeight := 1;
for i := 0 to Columns.Count - 1 do begin
if TacColumnTitle(Columns[i].Title).IsCaptionStored then Cur := GetCaptionDepth(Columns[i].Title.Caption,FLevelDelimiterChar) else Cur := 1;
if Cur > FHeaderHeight then FHeaderHeight := Cur;
end;
aHeight := (DefaultRowHeight + 1) * FHeaderHeight;
RowHeights[0]:= aHeight - 1;
end;
function TsDBGrid.GetClientRect: TRect;
begin
Result := inherited GetClientRect;
if dgRowLines in options then Inc(Result.Bottom);
end;
procedure TsDBGrid.LayoutChanged;
begin
inherited;
UpdateHeaderHeight;
end;
procedure TsDBGrid.SetLevelDelimiterChar(const Value: char);
begin
FLevelDelimiterChar := Value;
end;
function TsDBGrid.CalcFilterBar(Column: TColumn): TRect;
var
Rect: TRect;
MasterCol: TColumn;
aRow: integer;
begin
aRow := 0;
Rect := CalcTitleRect(Column, aRow, MasterCol);
Rect.Top := Rect.Bottom - (DefaultRowHeight + 9);
Result := Rect;
end;
function TsDBGrid.MouseInLowerstLevel(X, Y: integer; Column: TColumn = nil): boolean;
var
Index: integer;
Rect: TRect;
MasterCol: TColumn;
begin
Result := False;
if Column = nil then begin
Index := RawToDataColumn(MouseCoord(X, Y).X);
if Index < 0 then exit;
Column := Columns[Index];
end;
Index := 0;
Rect := CalcTitleRect(Column, Index, MasterCol);
Index := GetCaptionDepth(Column.Title.Caption, FLevelDelimiterChar);
if Index > 0 then begin
Index := (Index-1) * (DefaultRowHeight + 1);
Rect.Top := Index;
Rect.Bottom := CalcFilterBar(Column).top;
Result := PtInRect(Rect, Point(X, Y));
end
else Result := True;
end;
procedure TsDBGrid.CalcTableSpacePercent;
var
ColumnsSize, i: integer;
begin
ColumnsSize := 0;
for i := 0 to Columns.count - 1 do
if ColWidths[i + IndicatorOffset] > 0 then ColumnsSize := ColumnsSize + ColWidths[i + IndicatorOffset];
for i := 0 to Columns.Count - 1 do
if ColumnsSize > 0 then TacDBColumn(Columns[i]).FTableSpacePercent := ColWidths[i + IndicatorOffset] / ColumnsSize;
end;
function TsDBGrid.CanEditShow: boolean;
begin
if (Columns.Count > 0) and Assigned(SelectedField) and (SelectedField is TMemoField) then Result := False else Result := inherited CanEditShow;
end;
procedure TsDBGrid.TopLeftChanged;
{$IFDEF VER4}
var
R: TRect;
DrawInfo: TGridDrawInfo;
{$ENDIF}
begin
inherited;
{$IFDEF VER4}
if HandleAllocated and (dgTitles in Options) then begin
CalcFixedInfo(DrawInfo);
R := Rect(0, 0, Width, DrawInfo.Vert.FixedBoundary);
InvalidateRect(Handle, {$IFNDEF CLR}@{$ENDIF}R, False);
end;
{$ENDIF}
end;
procedure TsDBGrid.AdjustColumns;
var
Width: array of integer;
i, j, OldActive: integer;
CurWidth: Integer;
begin
if not DataLink.Active then Exit;
SetLength(Width, Columns.Count);
OldActive := DataLink.ActiveRecord;
try
for i := TopRow - 1 to VisibleRowCount - 1 do begin
Datalink.ActiveRecord := i;
for j := 0 to Columns.Count - 1 do begin
if Assigned(Columns[j].Field) then CurWidth := Canvas.TextWidth(Columns[j].Field.DisplayText) else CurWidth := 0;
if CurWidth > Width[j] then Width[j] := CurWidth;
end;
end;
finally
DataLink.ActiveRecord := OldActive;
end;
for i := 0 to Columns.Count - 1 do begin
CurWidth := Canvas.TextWidth(Columns[i].Title.Caption);
if CurWidth > Width[i] then ColWidths[i + IndicatorOffset] := CurWidth + 4 else ColWidths[i + IndicatorOffset] := Width[i] + 4;
end;
end;
function TsDBGrid.GetColumns: TacDBGridColumns;
begin
Result := TacDBGridColumns(inherited Columns);
end;
procedure TsDBGrid.SetColumns(const Value: TacDBGridColumns);
begin
inherited Columns.Assign(Value);
end;
procedure TsDBGrid.WMMouseWheel(var Message: TWMMouseWheel);
begin
if Message.WheelDelta > 0 then SendMessage(Handle, WM_KEYDOWN, VK_UP, 0) else SendMessage(Handle, WM_KEYDOWN, VK_DOWN, 0); // ?
end;
procedure TsDBGrid.TitleClick(Column: TColumn);
begin
if FTitleBarUp then inherited TitleClick(Column);
end;
procedure TsDBGrid.WndProc(var Message: TMessage);
var
SavedDC{, DC} : hdc;
begin
if Message.Msg = SM_ALPHACMD then case Message.WParamHi of
AC_CTRLHANDLED : begin Message.Result := 1; Exit end;
AC_SETNEWSKIN : if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin
CommonWndProc(Message, FCommonData);
exit
end;
AC_REFRESH : if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin
CommonWndProc(Message, FCommonData);
if FCommonData.Skinned and not (csLoading in ComponentState) then begin
RefreshGridScrolls(SkinData, ListSW);
RedrawWindow(Handle, nil, 0, RDW_FRAME or RDW_INVALIDATE or RDW_UPDATENOW);
end;
Exit;
end;
AC_REMOVESKIN : if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) and (SkinData.FOwnerControl <> nil) and (SkinData.FOwnerControl is TCustomGrid) then begin
Color := clWindow;
SkinData.SkinIndex := -1;
RedrawWindow(Handle, nil, 0, RDW_FRAME or RDW_INVALIDATE or RDW_UPDATENOW);
SetWindowPos(Handle, 0, 0, 0, 0, 0, SWP_NOSIZE or SWP_NOMOVE or SWP_NOZORDER or SWP_NOCOPYBITS or SWP_NOSENDCHANGING or SWP_NOREPOSITION or SWP_FRAMECHANGED);
end;
end;
case Message.Msg of
WM_ERASEBKGND : if SkinData.Skinned then begin
SkinData.FUpdating := SkinData.Updating;
Message.Result := 1;
Exit;
end;
WM_PRINT : if SkinData.Skinned then begin
SkinData.CtrlSkinState := SkinData.CtrlSkinState or ACS_PRINTING;
if ListSW = nil then RefreshGridScrolls(SkinData, ListSW);
InitCtrlData(Handle, ListSW.ParentWnd, ListSW.WndRect, ListSW.ParentRect, ListSW.WndSize, ListSW.WndPos, ListSW.Caption);
SkinData.Updating := False;
SkinData.BGChanged := True;
if not ListSW.ParamsChanged then ListSW.SetSkinParams;
PrepareCache(SkinData, Handle, False);
SavedDC := SaveDC(TWMPaint(Message).DC);
try
SendMessage(Handle, WM_PRINTCLIENT, longint(TWMPaint(Message).DC), PRF_CLIENT or PRF_OWNED);
Message.Result := Ac_NCPaint(ListSW, Handle, Message.wParam, Message.lParam, -1, TWMPaint(Message).DC);
finally
RestoreDC(TWMPaint(Message).DC, SavedDC);
end;
BitBltBorder(TWMPaint(Message).DC, 0, 0, SkinData.FCacheBmp.Width, SkinData.FCacheBmp.Height, SkinData.FCacheBmp.Canvas.Handle, 0, 0, ListSW.cxLeftEdge);
SkinData.CtrlSkinState := SkinData.CtrlSkinState and not ACS_PRINTING;
Message.Result := 2;
Exit;
end;
end;
CommonWndProc(Message, FCommonData);
inherited;
if ControlIsReady(Self) and FCommonData.Skinned then begin
case Message.Msg of
CM_SHOWINGCHANGED : RefreshGridScrolls(SkinData, ListSW);
end;
end;
end;
procedure TsDBGrid.PaintWindow(DC: HDC);
var
SavedCanvas : TCanvas;
bWidth : integer;
Bmp : TBitmap;
R : TRect;
begin
if FCommonData.Skinned then begin
if not (csDestroying in ComponentState) then begin
SavedCanvas := _TCustomControl(Self).FCanvas;
Bmp := CreateBmp32(Width, Height);
_TCustomControl(Self).FCanvas := Bmp.Canvas;
try
GetClipBox(DC, R);
Paint;
if (SkinData.CtrlSkinState and ACS_PRINTING = ACS_PRINTING) then bWidth := 2 else bWidth := 0;
BitBlt(DC, bWidth, bWidth, Width, Height, Bmp.Canvas.Handle, 0, 0, SRCCOPY);
finally
_TCustomControl(Self).FCanvas := SavedCanvas;
Bmp.Free;
end;
end
end
else inherited;
end;
function TsDBGrid.CreateEditor: TInplaceEdit;
begin
Result := inherited CreateEditor;
Repaint;
end;
end.
|
unit explorersprocessortestcase;
{$ifdef fpc}{$mode delphi}{$endif}{$H+}
interface
uses
Classes, SysUtils, fpcunit, testregistry,
explorersprocessor;
type
TExplorersProcessorTestCase = class(TTestCase)
published
procedure TestGetExplorersTwoItems;
procedure TestGetExplorersEmpty;
procedure TestGetExplorersUnknownExplorerInStorage;
procedure TestGetExplorersRemovesUnknown;
procedure TestGetExplorersSorts;
procedure TestSetExplorersSecondItem;
procedure TestSetExplorersIgnoresCase;
procedure TestSetExplorersIgnoresSpaces;
procedure TestSetExplorersClears;
end;
TExplorerStorageMock = class(TInterfacedObject, IExplorerStorage)
private
FDummyExplorerNames: TStrings;
public
constructor Create(DummyExplorerNames: TStrings);
destructor Destroy; override;
procedure ReadConfig(ExplorerNames: TStrings);
procedure SaveConfig(ExplorerNames: TStrings);
procedure ClearConfig;
end;
implementation
constructor TExplorerStorageMock.Create(DummyExplorerNames: TStrings);
begin
FDummyExplorerNames := TStringList.Create;
if Assigned(DummyExplorerNames) then
begin
FDummyExplorerNames.AddStrings(DummyExplorerNames);
end;
end;
destructor TExplorerStorageMock.Destroy;
begin
FreeAndNil(FDummyExplorerNames);
inherited Destroy;
end;
procedure TExplorerStorageMock.ReadConfig(ExplorerNames: TStrings);
begin
if FDummyExplorerNames.Count > 0 then
begin
ExplorerNames.Clear;
ExplorerNames.AddStrings(FDummyExplorerNames);
end;
end;
procedure TExplorerStorageMock.SaveConfig(ExplorerNames: TStrings);
begin
FDummyExplorerNames.DelimitedText := ExplorerNames.DelimitedText;
end;
procedure TExplorerStorageMock.ClearConfig;
begin
FDummyExplorerNames.Clear;
end;
procedure TExplorersProcessorTestCase.TestGetExplorersTwoItems;
var
ExplorersProcessor: TExplorersProcessor;
TestArray: TStringArray;
TestStrings: TStrings;
ExplorerStorage: IExplorerStorage;
begin
TestArray := TStringArray.Create;
SetLength(TestArray, 2);
TestArray[0] := 'First';
TestArray[1] := 'Second';
TestStrings := TStringList.Create;
TestStrings.AddStrings(TestArray);
ExplorerStorage := TExplorerStorageMock.Create(TestStrings);
ExplorersProcessor := TExplorersProcessor.Create(TestArray, ExplorerStorage);
try
ExplorersProcessor.GetExplorers;
AssertTrue(ExplorersProcessor.ListOfAllExplorers.Count = 2);
AssertTrue(ExplorersProcessor.ListOfKnownExplorers.Count = 2);
AssertTrue(ExplorersProcessor.ListOfUnknownExplorers.Count = 0);
AssertEquals(TestArray[0], ExplorersProcessor.ListOfKnownExplorers[0]);
AssertEquals(TestArray[1], ExplorersProcessor.ListOfKnownExplorers[1]);
finally
FreeAndNil(ExplorersProcessor);
FreeAndNil(TestStrings);
end;
end;
procedure TExplorersProcessorTestCase.TestGetExplorersEmpty;
var
ExplorersProcessor: TExplorersProcessor;
TestArray: TStringArray;
TestStrings: TStrings;
ExplorerStorage: IExplorerStorage;
begin
TestArray := TStringArray.Create;
TestStrings := TStringList.Create;
ExplorerStorage := TExplorerStorageMock.Create(TestStrings);
ExplorersProcessor := TExplorersProcessor.Create(TestArray, ExplorerStorage);
try
ExplorersProcessor.GetExplorers;
AssertTrue(ExplorersProcessor.ListOfAllExplorers.Count = 0);
AssertTrue(ExplorersProcessor.ListOfKnownExplorers.Count = 0);
AssertTrue(ExplorersProcessor.ListOfUnknownExplorers.Count = 0);
finally
FreeAndNil(ExplorersProcessor);
FreeAndNil(TestStrings);
end;
end;
procedure TExplorersProcessorTestCase.TestGetExplorersUnknownExplorerInStorage;
var
ExplorersProcessor: TExplorersProcessor;
TestArray: TStringArray;
TestStrings: TStrings;
ExplorerStorage: IExplorerStorage;
begin
TestArray := TStringArray.Create;
SetLength(TestArray, 2);
TestArray[0] := 'First';
TestArray[1] := 'Second';
TestStrings := TStringList.Create;
TestStrings.AddStrings(TestArray);
TestStrings.Add('Unknown');
ExplorerStorage := TExplorerStorageMock.Create(TestStrings);
ExplorersProcessor := TExplorersProcessor.Create(TestArray, ExplorerStorage);
try
ExplorersProcessor.GetExplorers;
AssertTrue(ExplorersProcessor.ListOfAllExplorers.Count = 2);
AssertTrue(ExplorersProcessor.ListOfUnknownExplorers.Count = 1);
AssertEquals(TestStrings[2], ExplorersProcessor.ListOfUnknownExplorers[0]);
finally
FreeAndNil(ExplorersProcessor);
FreeAndNil(TestStrings);
end;
end;
procedure TExplorersProcessorTestCase.TestGetExplorersRemovesUnknown;
var
ExplorersProcessor: TExplorersProcessor;
TestArray: TStringArray;
TestStrings: TStrings;
ExplorerStorage: IExplorerStorage;
begin
TestArray := TStringArray.Create;
SetLength(TestArray, 2);
TestArray[0] := 'First';
TestArray[1] := 'Second';
TestStrings := TStringList.Create;
TestStrings.AddStrings(TestArray);
TestStrings.Add('Unknown');
ExplorerStorage := TExplorerStorageMock.Create(TestStrings);
ExplorersProcessor := TExplorersProcessor.Create(TestArray, ExplorerStorage);
try
ExplorersProcessor.GetExplorers;
AssertTrue(ExplorersProcessor.ListOfAllExplorers.Count = 2);
AssertTrue(ExplorersProcessor.ListOfKnownExplorers.Count = 2);
AssertTrue(ExplorersProcessor.ListOfUnknownExplorers.Count = 1);
AssertEquals(TestStrings[2], ExplorersProcessor.ListOfUnknownExplorers[0]);
ExplorersProcessor.GetExplorers;
AssertTrue(ExplorersProcessor.ListOfAllExplorers.Count = 2);
AssertTrue(ExplorersProcessor.ListOfKnownExplorers.Count = 2);
AssertTrue(ExplorersProcessor.ListOfUnknownExplorers.Count = 0);
finally
FreeAndNil(ExplorersProcessor);
FreeAndNil(TestStrings);
end;
end;
procedure TExplorersProcessorTestCase.TestGetExplorersSorts;
var
ExplorersProcessor: TExplorersProcessor;
TestArray: TStringArray;
TestStrings: TStrings;
ExplorerStorage: IExplorerStorage;
begin
TestArray := TStringArray.Create;
SetLength(TestArray, 2);
TestArray[0] := 'Second';
TestArray[1] := 'First';
TestStrings := TStringList.Create;
TestStrings.AddStrings(TestArray);
ExplorerStorage := TExplorerStorageMock.Create(TestStrings);
ExplorersProcessor := TExplorersProcessor.Create(TestArray, ExplorerStorage);
try
ExplorersProcessor.GetExplorers;
AssertTrue(ExplorersProcessor.ListOfKnownExplorers.Count = 2);
AssertEquals(TestArray[1], ExplorersProcessor.ListOfKnownExplorers[0]);
AssertEquals(TestArray[0], ExplorersProcessor.ListOfKnownExplorers[1]);
finally
FreeAndNil(ExplorersProcessor);
FreeAndNil(TestStrings);
end;
end;
procedure TExplorersProcessorTestCase.TestSetExplorersSecondItem;
var
ExplorersProcessor: TExplorersProcessor;
TestArray: TStringArray;
TestStrings: TStrings;
ExplorerStorage: IExplorerStorage;
InputExplorers: TStrings;
begin
TestArray := TStringArray.Create;
SetLength(TestArray, 2);
TestArray[0] := 'First';
TestArray[1] := 'Second';
TestStrings := TStringList.Create;
TestStrings.AddStrings(TestArray);
ExplorerStorage := TExplorerStorageMock.Create(TestStrings);
ExplorersProcessor := TExplorersProcessor.Create(TestArray, ExplorerStorage);
try
InputExplorers := TStringList.Create;
InputExplorers.Add('Second');
ExplorersProcessor.SetExplorers(InputExplorers.CommaText);
AssertTrue(ExplorersProcessor.ListOfAllExplorers.Count = 2);
AssertTrue(ExplorersProcessor.ListOfKnownExplorers.Count = 1);
AssertTrue(ExplorersProcessor.ListOfUnknownExplorers.Count = 0);
AssertEquals(TestArray[1], ExplorersProcessor.ListOfKnownExplorers[0]);
ExplorersProcessor.GetExplorers;
AssertTrue(ExplorersProcessor.ListOfAllExplorers.Count = 2);
AssertTrue(ExplorersProcessor.ListOfKnownExplorers.Count = 1);
AssertTrue(ExplorersProcessor.ListOfUnknownExplorers.Count = 0);
AssertEquals(TestArray[1], ExplorersProcessor.ListOfKnownExplorers[0]);
finally
FreeAndNil(InputExplorers);
FreeAndNil(ExplorersProcessor);
FreeAndNil(TestStrings);
end;
end;
procedure TExplorersProcessorTestCase.TestSetExplorersIgnoresCase;
var
ExplorersProcessor: TExplorersProcessor;
TestArray: TStringArray;
TestStrings: TStrings;
ExplorerStorage: IExplorerStorage;
InputExplorers: TStrings;
begin
TestArray := TStringArray.Create;
SetLength(TestArray, 2);
TestArray[0] := 'First';
TestArray[1] := 'Second';
TestStrings := TStringList.Create;
TestStrings.AddStrings(TestArray);
ExplorerStorage := TExplorerStorageMock.Create(TestStrings);
ExplorersProcessor := TExplorersProcessor.Create(TestArray, ExplorerStorage);
try
InputExplorers := TStringList.Create;
InputExplorers.Add('SECOND');
ExplorersProcessor.SetExplorers(InputExplorers.CommaText);
AssertTrue(ExplorersProcessor.ListOfAllExplorers.Count = 2);
AssertTrue(ExplorersProcessor.ListOfKnownExplorers.Count = 1);
AssertTrue(ExplorersProcessor.ListOfUnknownExplorers.Count = 0);
AssertEquals(TestArray[1], ExplorersProcessor.ListOfKnownExplorers[0]);
finally
FreeAndNil(InputExplorers);
FreeAndNil(ExplorersProcessor);
FreeAndNil(TestStrings);
end;
end;
procedure TExplorersProcessorTestCase.TestSetExplorersIgnoresSpaces;
var
ExplorersProcessor: TExplorersProcessor;
TestArray: TStringArray;
TestStrings: TStrings;
ExplorerStorage: IExplorerStorage;
begin
TestArray := TStringArray.Create;
SetLength(TestArray, 2);
TestArray[0] := 'First';
TestArray[1] := 'Second';
TestStrings := TStringList.Create;
TestStrings.AddStrings(TestArray);
ExplorerStorage := TExplorerStorageMock.Create(TestStrings);
ExplorersProcessor := TExplorersProcessor.Create(TestArray, ExplorerStorage);
try
ExplorersProcessor.SetExplorers('SECOND, First');
AssertTrue(ExplorersProcessor.ListOfAllExplorers.Count = 2);
AssertTrue(ExplorersProcessor.ListOfKnownExplorers.Count = 2);
AssertTrue(ExplorersProcessor.ListOfUnknownExplorers.Count = 0);
AssertEquals(TestArray[0], ExplorersProcessor.ListOfKnownExplorers[0]);
AssertEquals(TestArray[1], ExplorersProcessor.ListOfKnownExplorers[1]);
ExplorersProcessor.SetExplorers('SECOND ,First');
AssertTrue(ExplorersProcessor.ListOfAllExplorers.Count = 2);
AssertTrue(ExplorersProcessor.ListOfKnownExplorers.Count = 2);
AssertTrue(ExplorersProcessor.ListOfUnknownExplorers.Count = 0);
AssertEquals(TestArray[0], ExplorersProcessor.ListOfKnownExplorers[0]);
AssertEquals(TestArray[1], ExplorersProcessor.ListOfKnownExplorers[1]);
finally
FreeAndNil(ExplorersProcessor);
FreeAndNil(TestStrings);
end;
end;
procedure TExplorersProcessorTestCase.TestSetExplorersClears;
var
ExplorersProcessor: TExplorersProcessor;
TestArray: TStringArray;
TestStrings: TStrings;
ExplorerStorage: IExplorerStorage;
begin
TestArray := TStringArray.Create;
SetLength(TestArray, 2);
TestArray[0] := 'First';
TestArray[1] := 'Second';
TestStrings := TStringList.Create;
TestStrings.AddStrings(TestArray);
ExplorerStorage := TExplorerStorageMock.Create(TestStrings);
ExplorersProcessor := TExplorersProcessor.Create(TestArray, ExplorerStorage);
try
ExplorersProcessor.SetExplorers('');
AssertTrue(ExplorersProcessor.ListOfAllExplorers.Count = 2);
AssertTrue(ExplorersProcessor.ListOfKnownExplorers.Count = 0);
AssertTrue(ExplorersProcessor.ListOfUnknownExplorers.Count = 0);
ExplorersProcessor.GetExplorers;
AssertTrue(ExplorersProcessor.ListOfAllExplorers.Count = 2);
AssertTrue(ExplorersProcessor.ListOfKnownExplorers.Count = 0);
AssertTrue(ExplorersProcessor.ListOfUnknownExplorers.Count = 0);
finally
FreeAndNil(ExplorersProcessor);
FreeAndNil(TestStrings);
end;
end;
initialization
RegisterTest(TExplorersProcessorTestCase);
end.
|
(******************************************************************************
* PasVulkan *
******************************************************************************
* Version see PasVulkan.Framework.pas *
******************************************************************************
* zlib license *
*============================================================================*
* *
* Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) *
* *
* This software is provided 'as-is', without any express or implied *
* warranty. In no event will the authors be held liable for any damages *
* arising from the use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not *
* claim that you wrote the original software. If you use this software *
* in a product, an acknowledgement in the product documentation would be *
* appreciated but is not required. *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* 3. This notice may not be removed or altered from any source distribution. *
* *
******************************************************************************
* General guidelines for code contributors *
*============================================================================*
* *
* 1. Make sure you are legally allowed to make a contribution under the zlib *
* license. *
* 2. The zlib license header goes at the top of each source file, with *
* appropriate copyright notice. *
* 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan *
* Pascal header. *
* 4. After a pull request, check the status of your pull request on *
http://github.com/BeRo1985/pasvulkan *
* 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= *
* 3.1.1 *
* 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, *
* but if needed, make it out-ifdef-able. *
* 7. No use of third-party libraries/units as possible, but if needed, make *
* it out-ifdef-able. *
* 8. Try to use const when possible. *
* 9. Make sure to comment out writeln, used while debugging. *
* 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, *
* x86-64, ARM, ARM64, etc.). *
* 11. Make sure the code runs on all platforms with Vulkan support *
* *
******************************************************************************)
unit PasVulkan.Scene3D.Renderer.Globals;
{$i PasVulkan.inc}
{$ifndef fpc}
{$ifdef conditionalexpressions}
{$if CompilerVersion>=24.0}
{$legacyifend on}
{$ifend}
{$endif}
{$endif}
{$m+}
interface
uses SysUtils,
Classes,
Math,
Vulkan,
PasVulkan.Types,
PasVulkan.Math,
PasVulkan.Framework,
PasVulkan.Application,
PasVulkan.VirtualReality,
PasVulkan.VirtualFileSystem;
type TpvScene3DRendererAntialiasingMode=
(
Auto=0,
None,
DSAA,
FXAA,
SMAA,
MSAA,
TAA
);
PpvScene3DRendererAntialiasingMode=^TpvScene3DRendererAntialiasingMode;
TpvScene3DRendererShadowMode=
(
Auto=0,
None=1,
PCF=2,
DPCF=3,
PCSS=4,
MSM=5
);
PpvScene3DRendererShadowMode=^TpvScene3DRendererShadowMode;
TpvScene3DRendererTransparencyMode=
(
Auto=0,
Direct,
SPINLOCKOIT,
INTERLOCKOIT,
LOOPOIT,
WBOIT,
MBOIT,
SPINLOCKDFAOIT,
INTERLOCKDFAOIT
);
PpvScene3DRendererTransparencyMode=^TpvScene3DRendererTransparencyMode;
TpvScene3DRendererDepthOfFieldMode=
(
Auto=0,
None,
HalfResSeparateNearFar,
HalfResBruteforce,
FullResHexagon,
FullResBruteforce
);
PpvScene3DRendererDepthOfFieldMode=^TpvScene3DRendererDepthOfFieldMode;
TpvScene3DRendererLensMode=
(
Auto=0,
None,
DownUpsample
);
PpvScene3DRendererLensMode=^TpvScene3DRendererLensMode;
TpvScene3DRendererGlobalIlluminatonMode=
(
Auto=0,
// No global illumination. Here in this case, it is just StaticEnvironmentMap but with a empty black environment map, for to minimize the count
// of the shader variants, and a cubemap lookup costs almost nothing these days.
//None,
// The simplest and fastest way to add global illumination to a scene is to use a static IBL environment map, for example from the sky.
StaticEnvironmentMap,
// A camera reflection probe is a cubemap that is updated every frame to reflect the scene around it. Nintendo seems to use this technique in some
// of their Nintendo Switch games. It may seem like the wrong approach at first glance, but apparently it still seems to work well, at least when
// used well in a targeted way.
CameraReflectionProbe{,
// Possible further options on my todo list for the future:
// At Voxel cone tracing, the scene is voxelized and then cone traced in an approximated way with help of mipmaps of the 3D voxel texture. This is
// a rather good technique, but it has some drawbacks, for example light leaking artifacts at thin walls. And with cascaded voxel cone tracing, the
// scene is split into multiple cascades, where each cascade has its own voxel grid map. This technique is very similar to cascaded shadow maps (CSMs),
// only that it is used for global illumination instead of shadows.
CascadedVoxelConeTracing,
// The idea of "Radiance hints" is based on reflective shadow maps (RSMs), where but instead of depth, the albedo color is stored in the RSMs. And
// with cascaded radiance hints, the scene is split into multiple cascades, where each cascade has its own voxel-grid-like state. This technique is
// very similar to cascaded shadow maps (CSMs), only that it is used for global illumination instead of shadows.
CascadedRadianceHints,
// And finally, the most accurate and most expensive way to add global illumination to a scene is to use hardware ray tracing for 1SPP path tracing
// together with temporal denoising. This technique is extremely accurate, but also extremely expensive. But it is also the only way to get the most
// accurate global illumination. But sadly it needs hardware support for ray tracing, and this is currently only available on Nvidia RTX graphics cards,
// newer AMD GPUs and Intel graphics cards. But maybe in the future, ray tracing will be more common and available on all graphics cards, and then it
// will be the best way to add global illumination to a scene. But until then, it is only a nice to have feature for the future.
PathTracingWithTemporalDenoising
// I'll avoid Light Propagation Volumes (LPVs) because I do think that it is no more worth to implement it, because it is no real alternative to
// radiance hints in my own opinion, when radiance hints is really good implemented once. And I'll also avoid Screen Space Global Illumination
// (SSGI) because it misses out-of-screen information.
}
);
PpvScene3DRendererGlobalIlluminatonMode=^TpvScene3DRendererGlobalIlluminatonMode;
var pvScene3DShaderVirtualFileSystem:TpvVirtualFileSystem=nil;
implementation
uses PasVulkan.Scene3D.Assets;
initialization
pvScene3DShaderVirtualFileSystem:=TpvVirtualFileSystem.Create(@PasVulkan.Scene3D.Assets.Scene3DSPIRVShadersData[0],PasVulkan.Scene3D.Assets.Scene3DSPIRVShadersDataSize,{$ifdef Windows}'d:\GitHub\pasvulkan\src\assets\shaders\scene3d\scene3dshaders.zip'{$else}'/home/bero/Projects/GitHub/pasvulkan/src/assets/shaders/scene3d/scene3dshaders.zip'{$endif});
finalization
FreeAndNil(pvScene3DShaderVirtualFileSystem);
end.
|
{*******************************************************************************
作者: dmzn@163.com 2011-4-29
描述: 多道计数器
*******************************************************************************}
unit UFormJS_M;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UFormBase, UMultiJS, UMultiJSCtrl, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, dxStatusBar;
type
TfFormJS_M = class(TBaseForm)
dxStatusBar1: TdxStatusBar;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure WorkPanelResize(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormPaint(Sender: TObject);
private
{ Private declarations }
FBGImage: TBitmap;
//背景图
FPerWeight: Double;
//袋重
FLoadPanels: Boolean;
//载入标记
FJSer: TMultiJSManager;
//计数器
FTunnels: array of TMultiJSPanelTunnel;
//装车道
procedure LoadTunnelList;
//载入车道
procedure OnData(nPort: string; nData: TMultiJSTunnel);
//计数数据
procedure DoOnLoad(Sender: TObject; var nDone: Boolean);
procedure DoOnStart(Sender: TObject; var nDone: Boolean);
procedure DoOnStop(Sender: TObject; var nDone: Boolean);
procedure DoOnDone(Sender: TObject; var nDone: Boolean);
//面板按钮
protected
procedure EnableChanged(var Msg: TMessage); message WM_ENABLE;
procedure CreateParams(var Params : TCreateParams); override;
//任务栏
public
{ Public declarations }
class function CreateForm(const nPopedom: string = '';
const nParam: Pointer = nil): TWinControl; override;
class function FormID: integer; override;
end;
implementation
{$R *.dfm}
uses
IniFiles, ULibFun, UMgrControl, UDataModule, USysConst, UFormWait,
UFormZTParam_M, UFormJSTruck_M, USysDB, USysGrid, ZnMD5;
var
gForm: TfFormJS_M;
//全局使用
class function TfFormJS_M.CreateForm(const nPopedom: string;
const nParam: Pointer): TWinControl;
begin
Result := nil;
if not Assigned(gForm) then
begin
gForm := TfFormJS_M.Create(Application);
with gForm do
begin
Caption := '计数控制台';
//FormStyle := fsStayOnTop;
Position := poDesigned;
end;
end;
with gForm do
begin
if not Showing then Show;
WindowState := wsNormal;
end;
end;
class function TfFormJS_M.FormID: integer;
begin
Result := cFI_FormJSForm;
end;
procedure TfFormJS_M.FormCreate(Sender: TObject);
var nStr: string;
nIni: TIniFile;
begin
DoubleBuffered := True;
FLoadPanels := False;
FBGImage := nil;
FJSer := TMultiJSManager.Create;
FJSer.OnData := OnData;
nIni := TIniFile.Create(gPath + sFormConfig);
try
LoadFormConfig(Self, nIni);
nStr := nIni.ReadString(Name, 'BGImage', '');
nStr := MacroValue(nStr, [MI('$Path/', gPath)]);
if FileExists(nStr) then
begin
FBGImage := TBitmap.Create;
FBGImage.LoadFromFile(nStr);
end;
finally
nIni.Free;
end;
end;
procedure TfFormJS_M.FormClose(Sender: TObject; var Action: TCloseAction);
var nIdx: Integer;
begin
for nIdx:=ControlCount - 1 downto 0 do
if Controls[nIdx] is TMultiJSPanel then
if (Controls[nIdx] as TMultiJSPanel).Tunnel.FStatus = sStatus_Busy then
begin
Action := caMinimize; Exit;
end;
SaveFormConfig(Self);
FBGImage.Free;
FJSer.Free;
Action := caFree;
gForm := nil;
end;
//Desc: 任务栏图标
procedure TfFormJS_M.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
Params.WndParent := GetDesktopWindow;
//Params.ExStyle := Params.ExStyle or WS_EX_TOOLWINDOW;
end;
procedure TfFormJS_M.EnableChanged(var Msg: TMessage);
begin
inherited;
if not Active then
EnableWindow(Handle, True);
//has mouse focus
end;
//------------------------------------------------------------------------------
//Desc: 获取有效的栈道数
function GetTunnelCount: Integer;
var nInt: Integer;
nStr,nKey: string;
begin
Result := 1;
nStr := 'Select D_Value From %s Where D_Name=''%s'' And D_Memo=''%s''';;
nStr := Format(nStr, [sTable_SysDict, sFlag_SysParam, sFlag_KeyName]);
with FDM.QueryTemp(nStr) do
if RecordCount > 0 then
begin
nKey := Fields[0].AsString;
if Pos(nKey, gSysParam.FHintText) < 1 then Exit; //公司名称
end else Exit;
nStr := 'Select D_Value,D_ParamB From %s Where D_Name=''%s'' And D_Memo=''%s''';;
nStr := Format(nStr, [sTable_SysDict, sFlag_SysParam, sFlag_ValidDate]);
with FDM.QueryTemp(nStr) do
if RecordCount > 0 then
begin
nStr := Format('dmzn_js_%s_%s', [nKey, Date2Str(Fields[0].AsDateTime)]);
nStr := MD5Print(MD5String(nStr));
if nStr <> Fields[1].AsString then Exit; //系统有效期
nInt := Trunc(Fields[0].AsDateTime - Date());
if nInt < 1 then
begin
Result := 0;
ShowDlg('系统已过期,请联系管理员!', sHint); Exit;
end;
if nInt < 7 then
begin
nStr := Format('系统还有 %d 天到期', [nInt]);
ShowMsg(nStr, sHint);
end;
end else Exit;
nStr := 'Select D_Value,D_ParamB From %s Where D_Name=''%s'' And D_Memo=''%s''';;
nStr := Format(nStr, [sTable_SysDict, sFlag_SysParam, sFlag_Tunnel]);
with FDM.QueryTemp(nStr) do
if RecordCount > 0 then
begin
nStr := Format('dmzn_js_%s_%s', [nKey, Fields[0].AsString]);
nStr := MD5Print(MD5String(nStr));
if nStr = Fields[1].AsString then Result := Fields[0].AsInteger; //装车道数
end;
end;
//Desc: 载入车道列表
procedure TfFormJS_M.LoadTunnelList;
var nList,nTmp: TStrings;
i,nCount,nIdx: Integer;
begin
nList := TStringList.Create;
nTmp := TStringList.Create;
try
SetLength(FTunnels, 0);
if not LoadZTList(nList) then Exit;
nCount := nList.Count - 1;
for i:=0 to nCount do
if SplitStr(nList[i], nTmp, 4, ';') then
begin
nIdx := Length(FTunnels);
SetLength(FTunnels, nIdx + 1);
FillChar(FTunnels[nIdx], SizeOf(TMultiJSPanelTunnel), #0);
with FTunnels[nIdx] do
begin
FPanelName := nTmp[0];
FComm := nTmp[1];
FTunnel := StrToInt(nTmp[2]);
FDelay := StrToInt(nTmp[3]);
end;
end;
i := Length(FTunnels);
nCount := GetTunnelCount;
if i < nCount then
nCount := i;
SetLength(FTunnels, nCount);
nCount := High(FTunnels);
if nCount < 0 then Exit;
nList.Clear;
for i:=Low(FTunnels) to nCount do
begin
if nList.IndexOf(FTunnels[i].FComm) < 0 then
nList.Add(FTunnels[i].FComm);
//port list
with TMultiJSPanel.Create(Self) do
begin
Parent := Self;
OnLoad := DoOnLoad;
OnStart := DoOnStart;
OnStop := DoOnStop;
OnDone := DoOndone;
PerWeight := FPerWeight;
AdjustPostion;
SetTunnel(FTunnels[i]);
end;
end;
for i:=nList.Count - 1 downto 0 do
begin
nCount := 0;
for nIdx:=Low(FTunnels) to High(FTunnels) do
if CompareText(FTunnels[nIdx].FComm, nList[i]) = 0 then Inc(nCount);
FJSer.AddPort(nList[i], 9600, nCount);
end;
finally
nList.Free;
nTmp.Free;
end;
end;
//Desc: 重新调整个组件位置
procedure TfFormJS_M.WorkPanelResize(Sender: TObject);
var i,nCount,nL,nT: Integer;
nInt,nIdx,nNum,nFixL: Integer;
begin
if not FLoadPanels then Exit;
//没创建完毕
if Length(FTunnels) < 1 then Exit;
//没有组件
with TMultiJSPanel.PanelRect do
begin
HorzScrollBar.Position := 0;
VertScrollBar.Position := 0;
nInt := Right + cSpace_H_Edge;
nNum := Trunc((ClientWidth - cSpace_H_Edge) / nInt);
nIdx := Length(FTunnels);
if nNum > nIdx then nNum := nIdx;
if nNum < 1 then nNum := 1;
//每行面板数
nInt := nInt * nNum;
if (ClientWidth - cSpace_H_Edge) <= nInt then
begin
nFixL := cSpace_H_Edge;
end else //fill form
begin
nInt := (ClientWidth + cSpace_H_Edge) - nInt;
nFixL := Trunc(nInt / 2) ;
end; //center form
nCount := Length(FTunnels);
i := Trunc(nCount / nNum);
if nCount mod nNum <> 0 then Inc(i);
//面板行数
nInt := (Bottom + cSpace_H_Edge) * i;
if (ClientHeight - cSpace_H_Edge) <= nInt then
begin
nT := cSpace_H_Edge;
end else //fill form
begin
nInt := ClientHeight - nInt;
nT := Trunc(nInt / 2);
end; //center form
end;
nIdx := 0;
nL := nFixL;
nCount := ControlCount - 1;
for i:=0 to nCount do
begin
if not (Controls[i] is TMultiJSPanel) then Continue;
//only jspanel
Controls[i].Left := nL;
Controls[i].Top := nT;
nL := nL + TMultiJSPanel.PanelRect.Right + cSpace_H_Edge;
Inc(nIdx);
if nIdx = nNum then
begin
nIdx := 0;
nL := nFixL;
nT := nT + TMultiJSPanel.PanelRect.Bottom + cSpace_H_Edge;
end;
end;
end;
//Desc: 载入面板
procedure TfFormJS_M.FormShow(Sender: TObject);
begin
if not FLoadPanels then
try
ShowWaitForm(Application.MainForm, '初始化装车线');
FPerWeight := GetWeightPerPackage;
LoadTunnelList;
FLoadPanels := True;
finally
CloseWaitForm;
end;
end;
//Desc: 绘制背景
procedure TfFormJS_M.FormPaint(Sender: TObject);
var nX,nY: integer;
begin
if Assigned(FBGImage) and (FBGImage.Width > 0) then
begin
nX := -Random(FBGImage.Width);
while nX < Width do
begin
nY := -Random(FBGImage.Height);
while nY < Height do
begin
Canvas.Draw(nX, nY, FBGImage);
Inc(nY, FBGImage.Height);
end;
Inc(nX, FBGImage.Width);
end;
end;
end;
//------------------------------------------------------------------------------
//Desc: 收到数据
procedure TfFormJS_M.OnData(nPort: string; nData: TMultiJSTunnel);
var nIdx: Integer;
begin
for nIdx:=ControlCount - 1 downto 0 do
if Controls[nIdx] is TMultiJSPanel then
with (Controls[nIdx] as TMultiJSPanel) do
begin
if CompareStr(Tunnel.FComm, nPort) <> 0 then Continue;
if Tunnel.FTunnel = nData.FTunnel then JSProgress(nData.FHasDone);
end;
end;
//Desc: 载入计数
procedure TfFormJS_M.DoOnLoad(Sender: TObject; var nDone: Boolean);
var nStr: string;
nIdx: Integer;
nData: TMultiJSPanelData;
begin
nDone := ShowZTTruckForm(nData, Self);
if nDone then
begin
for nIdx:=ControlCount - 1 downto 0 do
if Controls[nIdx] is TMultiJSPanel then
with Controls[nIdx] as TMultiJSPanel do
if nData.FRecordID = UIData.FRecordID then
begin
if Self.Controls[nIdx] = Sender then Exit;
//self is ignor
nStr := '车辆[ %s ]已在[ %s ],要继续吗?';
nStr := Format(nStr, [UIData.FTruckNo, Tunnel.FPanelName]);
if not QueryDlg(nStr, sAsk, Handle) then
begin
nDone := (Sender as TMultiJSPanel).UIData.FRecordID <> '';
Exit;
end;
end;
//forbid multi load
(Sender as TMultiJSPanel).SetData(nData);
end;
end;
//Desc: 开始计数
procedure TfFormJS_M.DoOnStart(Sender: TObject; var nDone: Boolean);
var nStr: string;
begin
with Sender as TMultiJSPanel do
begin
nDone := FJSer.SetTunnelData(Tunnel.FComm, Tunnel.FTunnel, Tunnel.FDelay,
UIData.FTruckNo, UIData.FHaveDai, nStr);
if nStr <> '' then ShowMsg(nStr, sHint);
end;
end;
//Desc: 停止计数
procedure TfFormJS_M.DoOnStop(Sender: TObject; var nDone: Boolean);
var nStr: string;
begin
with Sender as TMultiJSPanel do
begin
nDone := FJSer.StopTunnel(Tunnel.FComm, Tunnel.FTunnel, nStr);
if nStr <> '' then ShowMsg(nStr, sHint);
end;
end;
//Desc: 装车完毕
procedure TfFormJS_M.DoOnDone(Sender: TObject; var nDone: Boolean);
var nStr: string;
begin
with Sender as TMultiJSPanel do
try
nStr := 'Update $TB Set L_DaiShu=$DS,L_BC=$BC,L_ZTLine=''$ZT'',' +
'L_HasDone=''$Yes'',L_OKTime=''$Now'' Where L_ID=$ID';
nStr := MacroValue(nStr, [MI('$TB', sTable_JSLog), MI('$Yes', sFlag_Yes),
MI('$ZT', Tunnel.FPanelName), MI('$DS', IntToStr(UIData.FTotalDS)),
MI('$BC', IntToStr(UIData.FTotalBC)), MI('$ID', UIData.FRecordID),
MI('$Now', DateTime2Str(Now))]);
FDM.ExecuteSQL(nStr);
except
//ignor any error
end;
end;
initialization
gControlManager.RegCtrl(TfFormJS_M, TfFormJS_M.FormID);
end.
|
unit Splash;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, jpeg, MMSystem, Registry;
type
TFormSplash = class(TForm)
TimerClose: TTimer;
BG: TImage;
LabelCalculusEx: TLabel;
LabelLoading: TLabel;
procedure TimerCloseTimer(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure FormCreate(Sender: TObject);
private
public
end;
var
FormSplash: TFormSplash;
CFG_SOUND: Integer;
implementation
{$R *.dfm}
{$R resources.RES}
{$SetPEFlags IMAGE_FILE_RELOCS_STRIPPED}
{$SetPEFlags IMAGE_FILE_LINE_NUMS_STRIPPED}
{$SetPEFlags IMAGE_FILE_LOCAL_SYMS_STRIPPED}
{$SetPEFlags IMAGE_FILE_DEBUG_STRIPPED}
{$SetPEFlags IMAGE_FILE_EXECUTABLE_IMAGE}
uses Main;
procedure TFormSplash.FormCreate(Sender: TObject);
var
PCReg: TRegistry;
begin
PCReg:=TRegistry.Create;
try
PCReg.RootKey:=HKEY_LOCAL_MACHINE;
PCReg.OpenKey('SOFTWARE\NeoVisio\CalculusEx', False);
CFG_SOUND:=PCReg.ReadInteger('Sound');
PCReg.CloseKey;
finally
PCReg.Free;
end;
end;
procedure TFormSplash.FormKeyPress(Sender: TObject; var Key: Char);
begin
If (Key=#27) Then Application.MainForm.Close;
end;
procedure TFormSplash.FormShow(Sender: TObject);
var
Ellipse: HRGN;
begin
Ellipse:=CreateRoundRectRgn(0, 0, ClientWidth,ClientHeight, 20, 20);
SetWindowRgn(Handle, Ellipse, True);
If (CFG_SOUND=1) Then
sndPlaySound('audio', SND_ASYNC Or SND_RESOURCE);
Left:=(Screen.WorkAreaWidth-Width) Div 2;
Top:=(Screen.WorkAreaHeight-Height) Div 2;
AnimateWindow(FormSplash.Handle, 500, AW_BLEND);
If (Length(ParamStr(1))>1) And (FileExists(ParamStr(1))) Then
Main.FormMain.OpenExFile(ParamStr(1));
end;
procedure TFormSplash.TimerCloseTimer(Sender: TObject);
begin
TimerClose.Enabled:=False;
Main.FormMain.Show;
Close;
end;
end.
|
unit ADO_QExportDialog;
interface
uses
Forms, StdCtrls, ExtCtrls, ComCtrls, Controls, Classes, Db, QExport,
Dialogs, Buttons, {$IFDEF VCL4}ImgList,{$ENDIF} Grids, Windows, Graphics,
QExportRTF, QExportHTML, ExtDlgs, QExportXLS, QExportXML, QExportASCII,
QExportClipboard, QExportSQL, QExportLaTeX, QExportDBF, DbGrids,
QExportCommon, QExportDialogProgress, ToolWin, ADO_QExportDatabase,
ADO_QExportAccess, QExportPDF, Menus, QExportOptions, ImgList;
type
TAllowedExport = (aeXLS, aeAccess, aeWord, aeRTF, aeHTML, aeXML, aeDBF, aePDF,
aeTXT, aeCSV, aeDIFF, aeSylk, aeLaTeX, aeSQL, aeClipboard);
TAllowedExports = set of TAllowedExport;
TCommonOption = (coFields, coFormats, coColons, coCaptions, coOptions);
TCommonOptions = set of TCommonOption;
TADO_QExportDialog = class;
TADO_QExportDialogF = class(TForm)
paFileName: TPanel;
laFileName: TLabel;
edFileName: TEdit;
bBrowse: TButton;
chShowFile: TCheckBox;
paButtons: TPanel;
bStart: TButton;
bCancel: TButton;
Pages: TPageControl;
tshExportType: TTabSheet;
tshFields: TTabSheet;
sdExportFile: TSaveDialog;
laAvailableFields: TLabel;
laExportedFields: TLabel;
lstAvailableFields: TListView;
lstExportedFields: TListView;
bAddOneExportedField: TSpeedButton;
bAddAllExportedField: TSpeedButton;
bDelOneExportedField: TSpeedButton;
bDelAllExportedField: TSpeedButton;
imgFields: TImageList;
tshFormats: TTabSheet;
gbStandardFormats: TGroupBox;
laIntegerFormat: TLabel;
laDateFormat: TLabel;
laDateTimeFormat: TLabel;
laFloatFormat: TLabel;
laTimeFormat: TLabel;
laCurrencyFormat: TLabel;
edIntegerFormat: TEdit;
edDateFormat: TEdit;
edDateTimeFormat: TEdit;
edFloatFormat: TEdit;
edTimeFormat: TEdit;
edCurrencyFormat: TEdit;
gbUserFormat: TGroupBox;
cbxFormatFields: TComboBox;
cbxUserFormats: TComboBox;
laEqual_01: TLabel;
lstUserFormats: TListView;
bAddUserFormat: TSpeedButton;
bEditUserFormat: TSpeedButton;
bDeleteUserFormat: TSpeedButton;
bClearUserFormats: TSpeedButton;
tshHeaderFooter: TTabSheet;
laHeader: TLabel;
laFooter: TLabel;
memHeader: TMemo;
memFooter: TMemo;
tshCaptions: TTabSheet;
sgrCaptions: TStringGrid;
tshRTF: TTabSheet;
laRTFDefaultFont: TLabel;
laRTFHeaderFont: TLabel;
pbRTFDefaultFont: TPaintBox;
pbRTFHeaderFont: TPaintBox;
bRTFDefaultFont: TSpeedButton;
bRTFHeaderFont: TSpeedButton;
FontDialog: TFontDialog;
RTFExp: TQExportRTF;
tshXML: TTabSheet;
chXMLStandalone: TCheckBox;
laXMLEncoding: TLabel;
edXMLEncoding: TEdit;
tshSQL: TTabSheet;
gbSQLCommit: TGroupBox;
edSQLCommitRecCount: TEdit;
laSQLUseCommit_02: TLabel;
chSQLCommitAfterScript: TCheckBox;
laSQLCommitStatement: TLabel;
edSQLCommitStatement: TEdit;
gbSQLMisc: TGroupBox;
laSQLNullString: TLabel;
edSQLNullString: TEdit;
laSQLStatementTerm: TLabel;
edSQLStatementTerm: TEdit;
tshHTML: TTabSheet;
pcHTML: TPageControl;
tshHTMLPreview: TTabSheet;
tshHTMLBasic: TTabSheet;
tshHTMLAdvanced: TTabSheet;
paHTMLPreview: TPanel;
paHTMLBackground: TPanel;
laHTMLFont: TLabel;
paHTMLColumnHead_1: TPanel;
paHTMLColumnHead_2: TPanel;
paHTMLColumnHead_3: TPanel;
paHTMLOddRowCol_1: TPanel;
paHTMLOddRowCol_2: TPanel;
paHTMLOddRowCol_3: TPanel;
paHTMLEvenRowCol_1: TPanel;
paHTMLEvenRowCol_2: TPanel;
paHTMLEvenRowCol_3: TPanel;
paHTMLOddRowCol_4: TPanel;
paHTMLOddRowCol_5: TPanel;
paHTMLOddRowCol_6: TPanel;
paHTMLEvenRowCol_4: TPanel;
paHTMLEvenRowCol_5: TPanel;
paHTMLEvenRowCol_6: TPanel;
ColorDialog: TColorDialog;
HTMLExp: TQExportHTML;
laHTMLHead_1: TLabel;
laHTMLHead_2: TLabel;
laHTMLHead_3: TLabel;
laHTMLData_1: TLabel;
laHTMLData_2: TLabel;
laHTMLData_3: TLabel;
laHTMLData_4: TLabel;
laHTMLData_5: TLabel;
laHTMLData_6: TLabel;
laHTMLData_7: TLabel;
laHTMLData_8: TLabel;
laHTMLData_9: TLabel;
laHTMLData_10: TLabel;
laHTMLData_11: TLabel;
laHTMLData_12: TLabel;
laHTMLLink: TLabel;
laHTMLVLink: TLabel;
laHTMLALink: TLabel;
laHTMLTemplate: TLabel;
cbxHTMLTemplate: TComboBox;
bHTMLSaveTemplate: TSpeedButton;
bHTMLLoadTemplate: TSpeedButton;
sdHTMLTemplate: TSaveDialog;
odHTMLTemplate: TOpenDialog;
odHTMLCSS: TOpenDialog;
gbHTMLBodyOptions: TGroupBox;
laHTMLBodyFontName: TLabel;
laHTMLBackground: TLabel;
laHTMLBodyAdvanced: TLabel;
cbxHTMLFontName: TComboBox;
edHTMLBackground: TEdit;
btnHTMLBackground: TSpeedButton;
edHTMLBodyAdvanced: TEdit;
Bevel2: TBevel;
opdHTMLBackground: TOpenPictureDialog;
tshXLS: TTabSheet;
XLSExp: TQExportXLS;
sdOptions: TSaveDialog;
odOptions: TOpenDialog;
XMLExp: TQExportXML;
DBFExp: TQExportDBF;
LaTeXExp: TQExportLaTeX;
SQLExp: TQExportSQL;
ClipExp: TQExportClipboard;
chPrintFile: TCheckBox;
pcXLS: TPageControl;
tshXLSAdvanced: TTabSheet;
tshXLSDataFormat: TTabSheet;
btnXLSResetItem: TSpeedButton;
btnXLSResetAll: TSpeedButton;
laXLSPageHeader: TLabel;
edXLSPageHeader: TEdit;
laXLSPageFooter: TLabel;
edXLSPageFooter: TEdit;
pcXLSDataFormat: TPageControl;
tshXLSFont: TTabSheet;
tshXLSBorders: TTabSheet;
laXLSFont: TLabel;
cbxXLSFont: TComboBox;
laXLSFontSize: TLabel;
cbxXLSFontSize: TComboBox;
Bevel4: TBevel;
btnFontColor: TSpeedButton;
Bevel5: TBevel;
btnFontBold: TSpeedButton;
btnFontItalic: TSpeedButton;
btnFontStrikeOut: TSpeedButton;
Bevel6: TBevel;
btnUnderlineSingle: TSpeedButton;
btnUnderlineSingleAccounting: TSpeedButton;
btnUnderlineDouble: TSpeedButton;
btnUnderlineDoubleAccounting: TSpeedButton;
Bevel3: TBevel;
btnHorizontalLeft: TSpeedButton;
btnHorizontalCenter: TSpeedButton;
btnHorizontalRight: TSpeedButton;
btnHorizontalFill: TSpeedButton;
Bevel8: TBevel;
btnVerticalTop: TSpeedButton;
btnVerticalCenter: TSpeedButton;
btnVerticalBottom: TSpeedButton;
pbFontColor: TPaintBox;
Bevel11: TBevel;
Bevel9: TBevel;
btnBorderTop: TSpeedButton;
btnBorderBottom: TSpeedButton;
btnBorderLeft: TSpeedButton;
btnBorderRight: TSpeedButton;
btnBorderTopColor: TSpeedButton;
Bevel10: TBevel;
pbBorderTop: TPaintBox;
btnBorderBottomColor: TSpeedButton;
pbBorderBottom: TPaintBox;
btnBorderLeftColor: TSpeedButton;
pbBorderLeft: TPaintBox;
btnBorderRightColor: TSpeedButton;
pbBorderRight: TPaintBox;
cmbBorderTop: TComboBox;
cmbBorderBottom: TComboBox;
cmbBorderLeft: TComboBox;
cmbBorderRight: TComboBox;
Bevel7: TBevel;
tshXLSFill: TTabSheet;
tshXLSAggregate: TTabSheet;
pbXLSCell: TPaintBox;
Bevel13: TBevel;
laXLSSampleCell: TLabel;
laSQLUseCommit_01: TLabel;
gbSQLTableOptions: TGroupBox;
chSQLCreateTable: TCheckBox;
laSQLTableName: TLabel;
edSQLTableName: TEdit;
laBooleanTrue: TLabel;
laBooleanFalse: TLabel;
edBooleanTrue: TEdit;
edBooleanFalse: TEdit;
chAllowCaptions: TCheckBox;
cbxColumnAlign: TComboBox;
edColumnWidth: TEdit;
udColumnWidth: TUpDown;
laXLSSheetTitle: TLabel;
edXLSSheetTitle: TEdit;
laNullString: TLabel;
edNullString: TEdit;
pcExportType: TPageControl;
tshExportFormats: TTabSheet;
tshExportOptions: TTabSheet;
rgExportType: TRadioGroup;
gbExportConstraints: TGroupBox;
laSkipRecCount_01: TLabel;
laSkipRecCount_02: TLabel;
edSkipRecCount: TEdit;
chGoToFirstRecord: TCheckBox;
rbExportAllRecords: TRadioButton;
rbExportOnly: TRadioButton;
edExportRecCount: TEdit;
laExportRecCount_02: TLabel;
Bevel12: TBevel;
tshASCII: TTabSheet;
gbTXTOptions: TGroupBox;
chTXTAutoCalcColWidth: TCheckBox;
edTXTSpacing: TEdit;
laTXTSpacing: TLabel;
gbCSVOptions: TGroupBox;
chCSVQuoteStrings: TCheckBox;
laCSVComma: TLabel;
edCSVComma: TEdit;
rgRTFPageOrientation: TRadioGroup;
pcXLSFormats: TPageControl;
tshXLSFields: TTabSheet;
tshXLSOptions: TTabSheet;
lstXLSFields: TListView;
lstXLSOptions: TListView;
tshXLSStyles: TTabSheet;
lstXLSStyles: TListView;
rgXLSStripType: TRadioGroup;
tbrXLSStyles: TToolBar;
tbtAddXLSStyle: TToolButton;
tbtDelXLSStyle: TToolButton;
tbtUpXLSStyle: TToolButton;
tbtDownXLSStyle: TToolButton;
ilXLSStyles: TImageList;
ToolButton1: TToolButton;
tbtLoadXLSStyle: TToolButton;
tbtSaveXLSStyle: TToolButton;
odXLSStyle: TOpenDialog;
sdXLSStyle: TSaveDialog;
chCurrentRecordOnly: TCheckBox;
ASCIIExp: TQExportASCII;
Bevel1: TBevel;
btnFillBackground: TSpeedButton;
pbFillBackground: TPaintBox;
cmbPattern: TComboBox;
btnFillForeground: TSpeedButton;
pbFillForeground: TPaintBox;
Bevel14: TBevel;
rgXLSFunction: TRadioGroup;
edCSVQuote: TEdit;
laCSVQuote: TLabel;
chExportEmpty: TCheckBox;
tshAccess: TTabSheet;
gbAccessTableOptions: TGroupBox;
laAccessTableName: TLabel;
edAccessTableName: TEdit;
chAccessCreateTable: TCheckBox;
laCaptionRow: TLabel;
edCaptionRow: TEdit;
tshHTMLMultifile: TTabSheet;
laHTMLTitle: TLabel;
edHTMLTitle: TEdit;
gbHTMLUsingCSS: TGroupBox;
laHTMLCSSFileName: TLabel;
bvHTMLCSSFileName: TBevel;
btnHTMLCSSFileName: TSpeedButton;
rbInternal: TRadioButton;
rbExternal: TRadioButton;
edHTMLCSSFileName: TEdit;
gbHTMLMultifileOptions: TGroupBox;
laHTMLFileRecCount_01: TLabel;
laHTMLFileRecCount_02: TLabel;
laHTMLIndexLinkTemplate: TLabel;
edHTMLFileRecCount: TEdit;
chHTMLGenerateIndex: TCheckBox;
chHTMLUseMultiFileExport: TCheckBox;
gbHTMLNavigation: TGroupBox;
laHTMLIndexLinkTitle: TLabel;
laHTMLFirstLinkTitle: TLabel;
laHTMLPriorLinkTitle: TLabel;
laHTMLNextLinkTitle: TLabel;
laHTMLLastLinkTitle: TLabel;
chHTMLNavigationOnTop: TCheckBox;
chHTMLNavigationOnBottom: TCheckBox;
edHTMLIndexLinkTitle: TEdit;
edHTMLFirstLinkTitle: TEdit;
edHTMLPriorLinkTitle: TEdit;
edHTMLNextLinkTitle: TEdit;
edHTMLLastLinkTitle: TEdit;
edHTMLIndexLinkTemplate: TEdit;
gbHTMLTableOptions: TGroupBox;
Bevel15: TBevel;
laHTMLCellPadding: TLabel;
laHTMLCellSpacing: TLabel;
laHTMLBorderWidth: TLabel;
laHTMLTableAdvanced: TLabel;
laHTMLTableBackground: TLabel;
btnHTMLTableBackground: TSpeedButton;
edHTMLCellPadding: TEdit;
edHTMLCellSpacing: TEdit;
edHTMLBorderWidth: TEdit;
edHTMLTableAdvanced: TEdit;
edHTMLTableBackground: TEdit;
PDFExp: TQExportPDF;
tshPDF: TTabSheet;
lvPDFFonts: TListView;
Bevel16: TBevel;
paPDFSample: TPanel;
sbPDFFontColor: TSpeedButton;
edPDFFontSize: TEdit;
laPDFFontSize: TLabel;
laPDFFontEncoding: TLabel;
cbPDFFontEncoding: TComboBox;
laPDFFontName: TLabel;
cbPDFFontName: TComboBox;
pmTools: TPopupMenu;
miLoadOptions: TMenuItem;
miSaveOptions: TMenuItem;
bTools: TButton;
chXLSAutoCalcColWidth: TCheckBox;
chHTMLOverwriteCSSFile: TCheckBox;
pcPDFOptions: TPageControl;
tshPDFGridOptions: TTabSheet;
bvPDFGridOptions: TBevel;
laPDFColSpacing: TLabel;
laPDFRowSpacing: TLabel;
laPDFGridLineWidth: TLabel;
edPDFColSpacing: TEdit;
edPDFRowSpacing: TEdit;
edPDFGridLineWidth: TEdit;
tshPDFPageOptions: TTabSheet;
bvPDFPageOptions: TBevel;
laPDFPageFormat: TLabel;
laPDFPageWidth: TLabel;
laPDFPageHeight: TLabel;
laPDFPageUnits: TLabel;
laPDFPageOrientation: TLabel;
cbPDFPageFormat: TComboBox;
edPDFPageWidth: TEdit;
edPDFPageHeight: TEdit;
cbPDFPageUnits: TComboBox;
cbPDFPageOrientation: TComboBox;
gbPDFMargins: TGroupBox;
laPDFPageMarginLeft: TLabel;
laPDFPageMarginRight: TLabel;
laPDFPageMarginTop: TLabel;
laPDFPageMarginBottom: TLabel;
edPDFPageMarginLeft: TEdit;
edPDFPageMarginRight: TEdit;
edPDFPageMarginTop: TEdit;
edPDFPageMarginBottom: TEdit;
procedure edFileNameChange(Sender: TObject);
procedure bBrowseClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure rgExportTypeClick(Sender: TObject);
procedure chShowFileClick(Sender: TObject);
procedure bAddOneExportedFieldClick(Sender: TObject);
procedure bAddAllExportedFieldClick(Sender: TObject);
procedure bDelOneExportedFieldClick(Sender: TObject);
procedure bDelAllExportedFieldClick(Sender: TObject);
procedure cbxFormatFieldsChange(Sender: TObject);
procedure bAddUserFormatClick(Sender: TObject);
procedure PagesChange(Sender: TObject);
procedure bEditUserFormatClick(Sender: TObject);
procedure bDeleteUserFormatClick(Sender: TObject);
procedure bClearUserFormatsClick(Sender: TObject);
procedure sgrCaptionsDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
procedure pbRTFDefaultFontPaint(Sender: TObject);
procedure bRTFDefaultFontClick(Sender: TObject);
procedure pbRTFHeaderFontPaint(Sender: TObject);
procedure bRTFHeaderFontClick(Sender: TObject);
procedure paHTMLColumnHead_1Click(Sender: TObject);
procedure paHTMLOddRowCol_1Click(Sender: TObject);
procedure paHTMLEvenRowCol_1Click(Sender: TObject);
procedure laHTMLData_1Click(Sender: TObject);
procedure bHTMLSaveTemplateClick(Sender: TObject);
procedure bHTMLLoadTemplateClick(Sender: TObject);
procedure cbxHTMLTemplateChange(Sender: TObject);
procedure paHTMLBackgroundClick(Sender: TObject);
procedure cbxXLSFontChange(Sender: TObject);
procedure cbxXLSFontSizeChange(Sender: TObject);
procedure pbFontColorPaint(Sender: TObject);
procedure pbBorderTopPaint(Sender: TObject);
procedure pbBorderBottomPaint(Sender: TObject);
procedure pbBorderLeftPaint(Sender: TObject);
procedure pbBorderRightPaint(Sender: TObject);
procedure pbFillBackgroundPaint(Sender: TObject);
procedure pbFillForegroundPaint(Sender: TObject);
procedure btnFontColorClick(Sender: TObject);
procedure btnBorderTopColorClick(Sender: TObject);
procedure btnBorderBottomColorClick(Sender: TObject);
procedure btnBorderLeftColorClick(Sender: TObject);
procedure btnBorderRightColorClick(Sender: TObject);
procedure btnFillBackgroundClick(Sender: TObject);
procedure btnFillForegroundClick(Sender: TObject);
procedure btnFontBoldClick(Sender: TObject);
procedure btnFontItalicClick(Sender: TObject);
procedure btnFontStrikeOutClick(Sender: TObject);
procedure btnUnderlineSingleClick(Sender: TObject);
procedure btnUnderlineSingleAccountingClick(Sender: TObject);
procedure btnUnderlineDoubleClick(Sender: TObject);
procedure btnUnderlineDoubleAccountingClick(Sender: TObject);
procedure btnHorizontalLeftClick(Sender: TObject);
procedure btnHorizontalCenterClick(Sender: TObject);
procedure btnHorizontalRightClick(Sender: TObject);
procedure btnHorizontalFillClick(Sender: TObject);
procedure btnVerticalTopClick(Sender: TObject);
procedure btnVerticalCenterClick(Sender: TObject);
procedure btnVerticalBottomClick(Sender: TObject);
procedure btnBorderTopClick(Sender: TObject);
procedure btnBorderBottomClick(Sender: TObject);
procedure btnBorderLeftClick(Sender: TObject);
procedure btnBorderRightClick(Sender: TObject);
procedure cmbBorderTopChange(Sender: TObject);
procedure cmbBorderBottomChange(Sender: TObject);
procedure cmbBorderLeftChange(Sender: TObject);
procedure cmbBorderRightChange(Sender: TObject);
procedure cmbBorderTopDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
procedure cmbBorderBottomDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
procedure cmbBorderLeftDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
procedure cmbBorderRightDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
procedure cmbPatternDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
procedure cmbPatternChange(Sender: TObject);
procedure bStartClick(Sender: TObject);
procedure OnBeginExport(Sender: TObject);
procedure OnEndExport(Sender: TObject);
procedure OnBeforeExportRow(Sender: TObject; Row: TQExportRow;
var Accept: Boolean);
procedure OnExportedRecord(Sender: TObject; RecNo: Integer);
procedure chPrintFileClick(Sender: TObject);
procedure FieldsListDragOver(Sender, Source: TObject; X,
Y: Integer; State: TDragState; var Accept: Boolean);
procedure rgXLSFunctionClick(Sender: TObject);
procedure btnXLSResetItemClick(Sender: TObject);
procedure btnXLSResetAllClick(Sender: TObject);
procedure btnFontColorMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure btnFontColorMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure btnBorderTopColorMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure btnBorderTopColorMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure btnBorderBottomColorMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure btnBorderBottomColorMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure btnBorderLeftColorMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure btnBorderLeftColorMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure btnBorderRightColorMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure btnBorderRightColorMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure btnFillBackgroundMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure btnFillBackgroundMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure btnFillForegroundMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure btnFillForegroundMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure pbXLSCellPaint(Sender: TObject);
procedure lstAvailableFieldsDragDrop(Sender, Source: TObject; X,
Y: Integer);
procedure lstExportedFieldsDragDrop(Sender, Source: TObject; X,
Y: Integer);
procedure laHTMLHead_1Click(Sender: TObject);
procedure edIntegerFormatChange(Sender: TObject);
procedure edFloatFormatChange(Sender: TObject);
procedure edDateFormatChange(Sender: TObject);
procedure edTimeFormatChange(Sender: TObject);
procedure edDateTimeFormatChange(Sender: TObject);
procedure edCurrencyFormatChange(Sender: TObject);
procedure edXLSPageHeaderChange(Sender: TObject);
procedure edXLSPageFooterChange(Sender: TObject);
procedure chXLSAutoCalcColWidthClick(Sender: TObject);
procedure edHTMLTitleChange(Sender: TObject);
procedure edHTMLCSSFileNameChange(Sender: TObject);
procedure btnHTMLCSSFileNameClick(Sender: TObject);
procedure chHTMLOverwriteCSSFileClick(Sender: TObject);
procedure edHTMLFileRecCountChange(Sender: TObject);
procedure chHTMLGenerateIndexClick(Sender: TObject);
procedure cbxHTMLFontNameChange(Sender: TObject);
procedure edHTMLBackgroundChange(Sender: TObject);
procedure btnHTMLBackgroundClick(Sender: TObject);
procedure edHTMLBodyAdvancedChange(Sender: TObject);
procedure edHTMLCellPaddingChange(Sender: TObject);
procedure edHTMLCellSpacingChange(Sender: TObject);
procedure edHTMLBorderWidthChange(Sender: TObject);
procedure edHTMLTableBackgroundChange(Sender: TObject);
procedure btnHTMLTableBackgroundClick(Sender: TObject);
procedure edHTMLTableAdvancedChange(Sender: TObject);
procedure laHTMLFontClick(Sender: TObject);
procedure laHTMLLinkClick(Sender: TObject);
procedure laHTMLVLinkClick(Sender: TObject);
procedure laHTMLALinkClick(Sender: TObject);
procedure chXMLStandaloneClick(Sender: TObject);
procedure edXMLEncodingChange(Sender: TObject);
procedure edSQLTableNameChange(Sender: TObject);
procedure chSQLCreateTableClick(Sender: TObject);
procedure edSQLCommitRecCountChange(Sender: TObject);
procedure chSQLCommitAfterScriptClick(Sender: TObject);
procedure edSQLCommitStatementChange(Sender: TObject);
procedure edSQLNullStringChange(Sender: TObject);
procedure edSQLStatementTermChange(Sender: TObject);
procedure edBooleanTrueChange(Sender: TObject);
procedure edBooleanFalseChange(Sender: TObject);
procedure OnStopExport(Sender: TObject; var CanContinue: Boolean);
procedure OnFetchedRecord(Sender: TObject; RecNo: Integer);
procedure chGoToFirstRecordClick(Sender: TObject);
procedure edExportRecCountChange(Sender: TObject);
procedure edSkipRecCountChange(Sender: TObject);
procedure chAllowCaptionsClick(Sender: TObject);
procedure OnSkippedRecord(Sender: TObject; RecNo: Integer);
procedure OnGetExportText(Sender: TObject; ColNo: Integer;
var Text: String);
procedure sgrCaptionsGetEditText(Sender: TObject; ACol, ARow: Integer;
var Value: String);
procedure cbxColumnAlignExit(Sender: TObject);
procedure edColumnWidthExit(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure edXLSSheetTitleChange(Sender: TObject);
procedure edNullStringChange(Sender: TObject);
procedure rbInternalClick(Sender: TObject);
procedure rbExternalClick(Sender: TObject);
procedure rbExportOnlyClick(Sender: TObject);
procedure rbExportAllRecordsClick(Sender: TObject);
procedure chTXTAutoCalcColWidthClick(Sender: TObject);
procedure edTXTSpacingChange(Sender: TObject);
procedure NumberKeyPress(Sender: TObject; var Key: Char);
procedure chCSVQuoteStringsClick(Sender: TObject);
procedure edCSVCommaExit(Sender: TObject);
procedure rgRTFPageOrientationClick(Sender: TObject);
procedure lstXLSFieldsDeletion(Sender: TObject; Item: TListItem);
procedure lstXLSFieldsChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
procedure pcXLSFormatsChange(Sender: TObject);
procedure tbtAddXLSStyleClick(Sender: TObject);
procedure tbtDelXLSStyleClick(Sender: TObject);
procedure tbtUpXLSStyleClick(Sender: TObject);
procedure tbtDownXLSStyleClick(Sender: TObject);
procedure rgXLSStripTypeClick(Sender: TObject);
procedure tbtSaveXLSStyleClick(Sender: TObject);
procedure tbtLoadXLSStyleClick(Sender: TObject);
procedure chCurrentRecordOnlyClick(Sender: TObject);
procedure XLSExpBeforeExportRow(Sender: TObject; Sheet: Integer;
Row: TQExportRow; var Accept: Boolean);
procedure XLSExpExportedRecord(Sender: TObject; Sheet, RecNo: Integer);
procedure XLSExpAdvancedGetExportText(Sender: TObject; Sheet,
ColNo: Integer; var Text: String);
procedure edCSVQuoteExit(Sender: TObject);
procedure chExportEmptyClick(Sender: TObject);
procedure edAccessTableNameChange(Sender: TObject);
procedure chAccessCreateTableClick(Sender: TObject);
procedure edCaptionRowExit(Sender: TObject);
procedure edCaptionRowKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure edHTMLIndexLinkTemplateChange(Sender: TObject);
procedure chHTMLNavigationOnTopClick(Sender: TObject);
procedure chHTMLNavigationOnBottomClick(Sender: TObject);
procedure edHTMLIndexLinkTitleChange(Sender: TObject);
procedure edHTMLFirstLinkTitleChange(Sender: TObject);
procedure edHTMLPriorLinkTitleChange(Sender: TObject);
procedure edHTMLNextLinkTitleChange(Sender: TObject);
procedure edHTMLLastLinkTitleChange(Sender: TObject);
procedure chHTMLUseMultiFileExportClick(Sender: TObject);
procedure edPDFColSpacingChange(Sender: TObject);
procedure edPDFRowSpacingChange(Sender: TObject);
procedure edPDFGridLineWidthChange(Sender: TObject);
procedure lvPDFFontsChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
procedure cbPDFFontNameChange(Sender: TObject);
procedure cbPDFFontEncodingChange(Sender: TObject);
procedure edPDFFontSizeChange(Sender: TObject);
procedure sbPDFFontColorClick(Sender: TObject);
procedure bToolsClick(Sender: TObject);
procedure miSaveOptionsClick(Sender: TObject);
procedure miLoadOptionsClick(Sender: TObject);
procedure cbPDFPageFormatChange(Sender: TObject);
procedure edPDFPageWidthExit(Sender: TObject);
procedure edPDFPageHeightExit(Sender: TObject);
procedure cbPDFPageUnitsChange(Sender: TObject);
procedure cbPDFPageOrientationChange(Sender: TObject);
procedure edPDFPageMarginLeftExit(Sender: TObject);
procedure edPDFPageMarginRightExit(Sender: TObject);
procedure edPDFPageMarginTopExit(Sender: TObject);
procedure edPDFPageMarginBottomExit(Sender: TObject);
private
FQuickExport: TQExport;
FProgress: TQExportDialogProgressF;
FFileName: string;
FShowFile: boolean;
FPrintFile: boolean;
FOptionsFileName: string;
FGoToFirstRecord: boolean;
FCurrentRecordOnly: boolean;
FExportEmpty: boolean;
FExportRecCount: integer;
FSkipRecCount: integer;
FAllowCaptions: boolean;
FCaptionRow: integer;
FIntegerFmt: string;
FFloatFmt: string;
FDateFmt: string;
FTimeFmt: string;
FDateTimeFmt: string;
FCurrencyFmt: string;
FBooleanTrue: string;
FBooleanFalse: string;
FNullString: string;
FRTFPageOrientation: TQExportPageOrientation;
FXLSPageHeader: string;
FXLSPageFooter: string;
FXLSSheetTitle: string;
FXLSStripType: TxlsStripType;
FXLSAutoCalcColWidth: boolean;
FHTMLTitle: string;
FHTMLUsingCSS: TUsingCSS;
FHTMLCSSFileName: string;
FHTMLOverwriteCSSFile: boolean;
FHTMLUseMultiFileExport: boolean;
FHTMLFileRecCount: integer;
FHTMLGenerateIndex: boolean;
FHTMLIndexLinkTemplate: string;
FHTMLNavigationOnTop: boolean;
FHTMLNavigationOnBottom: boolean;
FHTMLIndexLinkTitle: string;
FHTMLFirstLinkTitle: string;
FHTMLPriorLinkTitle: string;
FHTMLNextLinkTitle: string;
FHTMLLastLinkTitle: string;
FHTMLFontName: string;
FHTMLBackground: string;
FHTMLBodyAdvanced: string;
FHTMLCellPadding: integer;
FHTMLCellSpacing: integer;
FHTMLBorderWidth: integer;
FHTMLTableBackground: string;
FHTMLTableAdvanced: string;
FHTMLBackgroundColor: TColor;
FHTMLFontColor: TColor;
FHTMLHeadBackgroundColor: TColor;
FHTMLHeadFontColor: TColor;
FHTMLOddRowBackgroundColor: TColor;
FHTMLEvenRowBackgroundColor: TColor;
FHTMLDataFontColor: TColor;
FHTMLLinkColor: TColor;
FHTMLVLinkColor: TColor;
FHTMLALinkColor: TColor;
FXMLStandalone: boolean;
FXMLEncoding: string;
FSQLTableName: string;
FSQLCreateTable: boolean;
FSQLCommitRecCount: integer;
FSQLCommitAfterScript: boolean;
FSQLCommitStatement: string;
FSQLStatementTerm: string;
FTXTAutoCalcColWidth: boolean;
FTXTSpacing: integer;
FCSVQuoteStrings: boolean;
FCSVComma: char;
FCSVQuote: char;
FAccessTableName: string;
FAccessCreateTable: boolean;
FPDFColSpacing: double;
FPDFRowSpacing: double;
FPDFGridLineWidth: integer;
FPDFPageFormat: TQExportPageFormat;
FPDFPageWidth: integer;
FPDFPageHeight: integer;
FPDFPageUnits: TQExportUnits;
FPDFPageOrientation: TQExportPageOrientation;
FPDFPageMarginLeft: integer;
FPDFPageMarginRight: integer;
FPDFPageMarginTop: integer;
FPDFPageMarginBottom: integer;
FXLSListItem: TListItem;
FPDFFontItem: TListItem;
function GetDialog: TADO_QExportDialog;
function GetDataSet: TDataSet;
function GetListView: TListView;
function GetDBGrid: TDBGrid;
function GetStringGrid: TStringGrid;
function GetAutoChangeFileExt: boolean;
function GetSaveLoadButtons: boolean;
function GetCommonOptions: TCommonOptions;
function GetConfirmAbort: boolean;
function GetAutoSaveOptions: boolean;
function GetAutoLoadOptions: boolean;
function GetExportSource: TQExportSource;
procedure SetFileName(const Value: string);
procedure SetShowFile(const Value: boolean);
procedure SetPrintFile(const Value: boolean);
function GetExportType: TAllowedExport;
procedure SetExportType(const Value: TAllowedExport);
procedure SetOptionsFileName(const Value: string);
procedure SetGoToFirstRecord(const Value: boolean);
procedure SetCurrentRecordOnly(const Value: boolean);
procedure SetExportEmpty(const Value: boolean);
procedure SetExportRecCount(const Value: integer);
procedure SetSkipRecCount(const Value: integer);
procedure SetAllowCaptions(const Value: boolean);
procedure SetCaptionRow(const Value: integer);
procedure SetIntegerFmt(const Value: string);
procedure SetFloatFmt(const Value: string);
procedure SetDateFmt(const Value: string);
procedure SetTimeFmt(const Value: string);
procedure SetDateTimeFmt(const Value: string);
procedure SetCurrencyFmt(const Value: string);
procedure SetBooleanTrue(const Value: string);
procedure SetBooleanFalse(const Value: string);
procedure SetNullString(const Value: string);
procedure SetRTFPageOrientation(const Value: TQExportPageOrientation);
procedure SetXLSPageHeader(const Value: string);
procedure SetXLSPageFooter(const Value: string);
procedure SetXLSSheetTitle(const Value: string);
procedure SetXLSStripType(const Value: TxlsStripType);
procedure SetXLSAutoCalcColWidth(const Value: boolean);
procedure SetHTMLTitle(const Value: string);
procedure SetHTMLUsingCSS(const Value: TUsingCSS);
procedure SetHTMLCSSFileName(const Value: string);
procedure SetHTMLOverwriteCSSFile(const Value: boolean);
procedure SetHTMLUseMultiFileExport(const Value: boolean);
procedure SetHTMLFileRecCount(const Value: integer);
procedure SetHTMLGenerateIndex(const Value: boolean);
procedure SetHTMLIndexLinkTemplate(const Value: string);
procedure SetHTMLNavigationOnTop(const Value: boolean);
procedure SetHTMLNavigationOnBottom(const Value: boolean);
procedure SetHTMLIndexLinkTitle(const Value: string);
procedure SetHTMLFirstLinkTitle(const Value: string);
procedure SetHTMLPriorLinkTitle(const Value: string);
procedure SetHTMLNextLinkTitle(const Value: string);
procedure SetHTMLLastLinkTitle(const Value: string);
procedure SetHTMLFontName(const Value: string);
procedure SetHTMLBackground(const Value: string);
procedure SetHTMLBodyAdvanced(const Value: string);
procedure SetHTMLCellPadding(const Value: integer);
procedure SetHTMLCellSpacing(const Value: integer);
procedure SetHTMLBorderWidth(const Value: integer);
procedure SetHTMLTableBackground(const Value: string);
procedure SetHTMLTableAdvanced(const Value: string);
procedure SetHTMLBackgroundColor(const Value: TColor);
procedure SetHTMLFontColor(const Value: TColor);
procedure SetHTMLHeadBackgroundColor(const Value: TColor);
procedure SetHTMLHeadFontColor(const Value: TColor);
procedure SetHTMLOddRowBackgroundColor(const Value: TColor);
procedure SetHTMLEvenRowBackgroundColor(const Value: TColor);
procedure SetHTMLDataFontColor(const Value: TColor);
procedure SetHTMLLinkColor(const Value: TColor);
procedure SetHTMLVLinkColor(const Value: TColor);
procedure SetHTMLALinkColor(const Value: TColor);
procedure SetXMLEncoding(const Value: string);
procedure SetXMLStandalone(const Value: boolean);
procedure SetSQLTableName(const Value: string);
procedure SetSQLCreateTable(const Value: boolean);
procedure SetSQLCommitRecCount(const Value: integer);
procedure SetSQLCommitAfterScript(const Value: boolean);
procedure SetSQLCommitStatement(const Value: string);
procedure SetSQLStatementTerm(const Value: string);
procedure SetTXTAutoCalcColWidth(const Value: boolean);
procedure SetTXTSpacing(const Value: integer);
procedure SetCSVQuoteStrings(const Value: boolean);
procedure SetCSVComma(const Value: char);
procedure SetCSVQuote(const Value: char);
procedure SetAccessTableName(const Value: string);
procedure SetAccessCreateTable(const Value: boolean);
procedure SetPDFColSpacing(const Value: double);
procedure SetPDFRowSpacing(const Value: double);
procedure SetPDFGridLineWidth(const Value: integer);
function GetPDFPageSizeFormat: string;
procedure SetPDFPageFormat(const Value: TQExportPageFormat);
function GetPDFPageWidth: double;
procedure SetPDFPageWidth(const Value: double);
function GetPDFPageHeight: double;
procedure SetPDFPageHeight(const Value: double);
procedure SetPDFPageUnits(const Value: TQExportUnits);
procedure SetPDFPageOrientation(const Value: TQExportPageOrientation);
function GetPDFPageMarginLeft: double;
procedure SetPDFPageMarginLeft(const Value: double);
function GetPDFPageMarginRight: double;
procedure SetPDFPageMarginRight(const Value: double);
function GetPDFPageMarginTop: double;
procedure SetPDFPageMarginTop(const Value: double);
function GetPDFPageMarginBottom: double;
procedure SetPDFPageMarginBottom(const Value: double);
procedure InitializeDialog;
procedure ShowTitle;
procedure SaveExportOptions(const FileName: string);
procedure LoadExportOptions(const FileName: string);
procedure ChangeFileExtension;
procedure FillAllowedExports;
procedure ResetStandardFormats;
procedure FillFields;
procedure ShowButtons;
procedure MakeStringGrid;
function IsCompatiblePage: boolean;
procedure LoadStringGridCaption;
procedure HTMLFillColors;
procedure HTMLUpdateMultifileControls;
procedure ShowFormatButtons;
function GetIndexOfNewAvailableFields(Item: TListItem): integer;
procedure SetCustomTemplate;
procedure SetCaptions;
function CurrXLSListView: TListView;
procedure CorrectXLSFieldsList;
procedure ShowXLSListItem(Item: TListItem);
procedure ShowXLSListItemM;
procedure XLSUpdateItemFont(Item: TListItem);
procedure XLSUpdateItemFontSize(Item: TListItem);
procedure XLSUpdateItemFontColor(Item: TListItem);
procedure XLSUpdateItemFontBold(Item: TListItem);
procedure XLSUpdateItemFontItalic(Item: TListItem);
procedure XLSUpdateItemFontStrikeOut(Item: TListItem);
procedure XLSUpdateItemFontUnderline(Item: TListItem);
procedure XLSUpdateItemHorAlignment(Item: TListItem);
procedure XLSUpdateItemVertAlignment(Item: TListItem);
procedure XLSUpdateItemBorderTop(Item: TListItem);
procedure XLSUpdateItemBorderTopColor(Item: TListItem);
procedure XLSUpdateItemBorderBottom(Item: TListItem);
procedure XLSUpdateItemBorderBottomColor(Item: TListItem);
procedure XLSUpdateItemBorderLeft(Item: TListItem);
procedure XLSUpdateItemBorderLeftColor(Item: TListItem);
procedure XLSUpdateItemBorderRight(Item: TListItem);
procedure XLSUpdateItemBorderRightColor(Item: TListItem);
procedure XLSUpdateItemFillPattern(Item: TListItem);
procedure XLSUpdateItemFillBackground(Item: TListItem);
procedure XLSUpdateItemFillForeground(Item: TListItem);
procedure XLSUpdateItemAggregate(Item: TListItem);
procedure XLSUpdateItemSetDefault(Item: TListItem);
procedure XLSResetAllItems;
procedure XLSResetAllItems_A;
procedure XLSShowStyleButtons;
procedure XLSRenumStyles;
procedure XLSSaveStyle(const FileName: string);
procedure XLSLoadStyle(const FileName: string);
procedure PDFFillFontList;
procedure PDFShowFontInfo;
procedure PDFShowExample;
public
property Dialog: TADO_QExportDialog read GetDialog;
property DataSet: TDataSet read GetDataSet;
property ListView: TListView read GetListView;
property DBGrid: TDBGrid read GetDBGrid;
property StringGrid: TStringGrid read GetStringGrid;
property AutoChangeFileExt: boolean read GetAutoChangeFileExt;
property SaveLoadButtons: boolean read GetSaveLoadButtons;
property CommonOptions: TCommonOptions read GetCommonOptions;
property ConfirmAbort: boolean read GetConfirmAbort;
property AutoSaveOptions: boolean read GetAutoSaveOptions;
property AutoLoadOptions: boolean read GetAutoLoadOptions;
property ExportSource: TQExportSource read GetExportSource;
property QuickExport: TQExport read FQuickExport write FQuickExport;
property FileName: string read FFileName write SetFileName;
property ShowFile: boolean read FShowFile write SetShowFile;
property PrintFile: boolean read FPrintFile write SetPrintFile;
property ExportType: TAllowedExport read GetExportType write SetExportType;
property OptionsFileName: string read FOptionsFileName
write SetOptionsFileName;
property GoToFirstRecord: boolean read FGoToFirstRecord
write SetGoToFirstRecord;
property CurrentRecordOnly: boolean read FCurrentRecordOnly
write SetCurrentRecordOnly;
property ExportEmpty: boolean read FExportEmpty write SetExportEmpty;
property ExportRecCount: integer read FExportRecCount
write SetExportRecCount;
property SkipRecCount: integer read FSkipRecCount
write SetSkipRecCount;
property AllowCaptions: boolean read FAllowCaptions write SetAllowCaptions;
property CaptionRow: integer read FCaptionRow write SetCaptionRow;
property IntegerFmt: string read FIntegerFmt write SetIntegerFmt;
property FloatFmt: string read FFloatFmt write SetFloatFmt;
property DateFmt: string read FDateFmt write SetDateFmt;
property TimeFmt: string read FTimeFmt write SetTimeFmt;
property DateTimeFmt: string read FDateTimeFmt write SetDateTimeFmt;
property CurrencyFmt: string read FCurrencyFmt write SetCurrencyFmt;
property BooleanTrue: string read FBooleanTrue write SetBooleanTrue;
property BooleanFalse: string read FBooleanFalse write SetBooleanFalse;
property NullString: string read FNullString write SetNullString;
property RTFPageOrientation: TQExportPageOrientation read FRTFPageOrientation
write SetRTFPageOrientation;
property XLSPageHeader: string read FXLSPageHeader write SetXLSPageHeader;
property XLSPageFooter: string read FXLSPageFooter write SetXLSPageFooter;
property XLSSheetTitle: string read FXLSSheetTitle write SetXLSSheetTitle;
property XLSStripType: TxlsStripType read FXLSStripType
write SetXLSStripType;
property XLSAutoCalcColWidth: boolean read FXLSAutoCalcColWidth
write SetXLSAutoCalcColWidth;
property HTMLTitle: string read FHTMLTitle write SetHTMLTitle;
property HTMLUsingCSS: TUsingCSS read FHTMLUsingCSS write SetHTMLUsingCSS;
property HTMLCSSFileName: string read FHTMLCSSFileName
write SetHTMLCSSFileName;
property HTMLOverwriteCSSFile: boolean read FHTMLOverwriteCSSFile
write SetHTMLOverwriteCSSFile;
property HTMLUseMultiFileExport: boolean read FHTMLUseMultiFileExport
write SetHTMLUseMultiFileExport;
property HTMLFileRecCount: integer read FHTMLFileRecCount
write SetHTMLFileRecCount;
property HTMLGenerateIndex: boolean read FHTMLGenerateIndex
write SetHTMLGenerateIndex;
property HTMLIndexLinkTemplate: string read FHTMLIndexLinkTemplate
write SetHTMLIndexLinkTemplate;
property HTMLNavigationOnTop: boolean read FHTMLNavigationOnTop
write SetHTMLNavigationOnTop;
property HTMLNavigationOnBottom: boolean read FHTMLNavigationOnBottom
write SetHTMLNavigationOnBottom;
property HTMLIndexLinkTitle: string read FHTMLIndexLinkTitle
write SetHTMLIndexLinkTitle;
property HTMLFirstLinkTitle: string read FHTMLFirstLinkTitle
write SetHTMLFirstLinkTitle;
property HTMLPriorLinkTitle: string read FHTMLPriorLinkTitle
write SetHTMLPriorLinkTitle;
property HTMLNextLinkTitle: string read FHTMLNextLinkTitle
write SetHTMLNextLinkTitle;
property HTMLLastLinkTitle: string read FHTMLLastLinkTitle
write SetHTMLLastLinkTitle;
property HTMLFontName: string read FHTMLFontName write SetHTMLFontName;
property HTMLBackground: string read FHTMLBackground
write SetHTMLBackground;
property HTMLBodyAdvanced: string read FHTMLBodyAdvanced
write SetHTMLBodyAdvanced;
property HTMLCellPadding: integer read FHTMLCellPadding
write SetHTMLCellPadding;
property HTMLCellSpacing: integer read FHTMLCellSpacing
write SetHTMLCellSpacing;
property HTMLBorderWidth: integer read FHTMLBorderWidth
write SetHTMLBorderWidth;
property HTMLTableBackground: string read FHTMLTableBackground
write SetHTMLTableBackground;
property HTMLTableAdvanced: string read FHTMLTableAdvanced
write SetHTMLTableAdvanced;
property HTMLBackgroundColor: TColor read FHTMLBackgroundColor
write SetHTMLBackgroundColor;
property HTMLFontColor: TColor read FHTMLFontColor write SetHTMLFontColor;
property HTMLHeadBackgroundColor: TColor read FHTMLHeadBackgroundColor
write SetHTMLHeadBackgroundColor;
property HTMLHeadFontColor: TColor read FHTMLHeadFontColor
write SetHTMLHeadFontColor;
property HTMLOddRowBackgroundColor: TColor read FHTMLOddRowBackgroundColor
write SetHTMLOddRowBackgroundColor;
property HTMLEvenRowBackgroundColor: TColor read FHTMLEvenRowBackgroundColor
write SetHTMLEvenRowBackgroundColor;
property HTMLDataFontColor: TColor read FHTMLDataFontColor
write SetHTMLDataFontColor;
property HTMLLinkColor: TColor read FHTMLLinkColor write SetHTMLLinkColor;
property HTMLVLinkColor: TColor read FHTMLVLinkColor
write SetHTMLVLinkColor;
property HTMLALinkColor: TColor read FHTMLALinkColor
write SetHTMLALinkColor;
property XMLStandalone: boolean read FXMLStandalone write SetXMLStandalone;
property XMLEncoding: string read FXMLEncoding write SetXMLEncoding;
property SQLTableName: string read FSQLTableName write SetSQLTableName;
property SQLCreateTable: boolean read FSQLCreateTable
write SetSQLCreateTable;
property SQLCommitRecCount: integer read FSQLCommitRecCount
write SetSQLCommitRecCount;
property SQLCommitAfterScript: boolean read FSQLCommitAfterScript
write SetSQLCommitAfterScript;
property SQLCommitStatement: string read FSQLCommitStatement
write SetSQLCommitStatement;
property SQLStatementTerm: string read FSQLStatementTerm
write SetSQLStatementTerm;
property TXTAutoCalcColWidth: boolean read FTXTAutoCalcColWidth
write SetTXTAutoCalcColWidth;
property TXTSpacing: integer read FTXTSpacing write SetTXTSpacing;
property CSVQuoteStrings: boolean read FCSVQuoteStrings
write SetCSVQuoteStrings;
property CSVComma: char read FCSVComma write SetCSVComma;
property CSVQuote: char read FCSVQuote write SetCSVQuote;
property AccessTableName: string read FAccessTableName
write SetAccessTableName;
property AccessCreateTable: boolean read FAccessCreateTable
write SetAccessCreateTable;
property PDFColSpacing: double read FPDFColSpacing write SetPDFColSpacing;
property PDFRowSpacing: double read FPDFRowSpacing write SetPDFRowSpacing;
property PDFGridLineWidth: integer read FPDFGridLineWidth
write SetPDFGridLineWidth;
property PDFPageFormat: TQExportPageFormat read FPDFPageFormat
write SetPDFPageFormat;
property PDFPageWidth: double read GetPDFPageWidth
write SetPDFPageWidth;
property PDFPageHeight: double read GetPDFPageHeight
write SetPDFPageHeight;
property PDFPageUnits: TQExportUnits read FPDFPageUnits
write SetPDFPageUnits;
property PDFPageOrientation: TQExportPageOrientation
read FPDFPageOrientation write SetPDFPageOrientation;
property PDFPageMarginLeft: double read GetPDFPageMarginLeft
write SetPDFPageMarginLeft;
property PDFPageMarginRight: double read GetPDFPageMarginRight
write SetPDFPageMarginRight;
property PDFPageMarginTop: double read GetPDFPageMarginTop
write SetPDFPageMarginTop;
property PDFPageMarginBottom: double read GetPDFPageMarginBottom
write SetPDFPageMarginBottom;
end;
TQExportEvent = procedure(Sender: TQExport) of object;
TQExportGetColonEvent = procedure(Sender: TObject; Colon: TStrings) of object;
TQRecordExportedEvent = procedure(Sender: TQExport; RecNo: integer) of object;
TQRecordExportedXLSEvent = procedure(Sender: TQExportXLS; Sheet, RecNo: integer) of object;
TQGetExportTextEvent = procedure(Sender: TQExport; ColNo: integer;
var Text: string) of object;
TQGetExportXLSTextEvent = procedure(Sender: TQExportXLS; Sheet, ColNo: Integer;
var Text: String) of object;
TQBeforeExportRowEvent = procedure(Sender: TQExport; Row: TQExportRow;
var Accept: boolean) of object;
TQBeforeExportXLSRowEvent = procedure(Sender: TQExportXLS; Sheet: integer;
Row: TQExportRow; var Accept: boolean) of object;
TADO_QExportDialog = class(TComponent)
private
FColumns: TQExportColumns;
FExportSource: TQExportSource;
FDataSet: TDataSet;
FDBGrid: TDBGrid;
FListView: TListView;
FStringGrid: TStringGrid;
FAllowedExports: TAllowedExports;
FCommonOptions: TCommonOptions;
FAutoChangeFileExt: boolean;
FConfirmAbort: boolean;
FOnlyVisibleFields: boolean;
FAutoCalcStrType: boolean;
FOptionsFileName: string;
FAutoSaveOptions: boolean;
FAutoLoadOptions: boolean;
FSaveLoadButtons: boolean;
FAbout: string;
F_Version: string;
FFileName: string;
FShowFile: boolean;
FPrintFile: boolean;
FExportedFields: TStrings;
FHeader: TStrings;
FAllowCaptions: boolean;
FCaptionRow: integer;
FCaptions: TStrings;
FFooter: TStrings;
FFormats: TQExportFormats;
FUserFormats: TStrings;
FColumnsWidth: TStrings;
FColumnsAlign: TStrings;
FCurrentRecordOnly: boolean;
FExportEmpty: boolean;
FGoToFirstRecord: boolean;
FExportRecCount: integer;
FSkipRecCount: integer;
FRTFOptions: TQExportRTFOptions;
FXMLOptions: TQExportXMLOptions;
FSQLOptions: TQExportSQLOptions;
FHTMLPageOptions: TQExportHTMLPageOptions;
FHTMLTableOptions: TQExportHTMLTableOptions;
FHTMLMultiFileOptions: TQExportHTMLMultiFileOptions;
FTXTOptions: TQExportTXTOptions;
FCSVOptions: TQExportCSVOptions;
FPDFOptions: TQExportPDFOptions;
FAccessOptions: TQExportAccessOptions;
FXLSOptions: TQExportXLSOptions;
FOnGetHeader: TQExportGetColonEvent;
FOnGetFooter: TQExportGetColonEvent;
FOnBeginExport: TQExportEvent;
FOnEndExport: TQExportEvent;
FOnFetchedRecord: TQRecordExportedEvent;
FOnSkippedRecord: TQRecordExportedEvent;
FOnBeforeExportRow: TQBeforeExportRowEvent;
FOnBeforeExportXLSRow: TQBeforeExportXLSRowEvent;
FOnExportedRecord: TQRecordExportedEvent;
FOnExportedRecordXLS: TQRecordExportedXLSEvent;
FOnStopExport: TQExportStopEvent;
FOnGetExportText: TQGetExportTextEvent;
FOnGetExportXLSText: TQGetExportXLSTextEvent;
procedure SetExportedFields(const Value: TStrings);
procedure SetHeader(const Value: TStrings);
procedure SetCaptions(const Value: TStrings);
procedure SetFooter(const Value: TStrings);
procedure SetFormats(const Value: TQExportFormats);
procedure SetUserFormats(const Value: TStrings);
procedure SetColumnsWidth(const Value: TStrings);
procedure SetColumnsAlign(const Value: TStrings);
procedure SetRTFOptions(const Value: TQExportRTFOptions);
procedure SetXMLOptions(const Value: TQExportXMLOptions);
procedure SetSQLOptions(const Value: TQExportSQLOptions);
procedure SetHTMLPageOptions(const Value: TQExportHTMLPageOptions);
procedure SetHTMLTableOptions(const Value: TQExportHTMLTableOptions);
procedure SetHTMLMultiFileOptions(const Value: TQExportHTMLMultiFileOptions);
procedure SetTXTOptions(const Value: TQExportTXTOptions);
procedure SetCSVOptions(const Value: TQExportCSVOptions);
procedure SetPDFOptions(const Value: TQExportPDFOptions);
procedure SetAccessOptions(const Value: TQExportAccessOptions);
procedure SetXLSOptions(const Value: TQExportXLSOptions);
protected
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
property Columns: TQExportColumns read FColumns;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Execute;
published
property ExportSource: TQExportSource read FExportSource
write FExportSource default esDataSet;
property DataSet: TDataSet read FDataSet write FDataSet;
property ListView: TListView read FListView write FListView;
property DBGrid: TDBGrid read FDBGrid write FDBGrid;
property StringGrid: TStringGrid read FStringGrid write FStringGrid;
property AllowedExports: TAllowedExports read FAllowedExports
write FAllowedExports default [Low(TAllowedExport)..High(TAllowedExport)];
property CommonOptions: TCommonOptions read FCommonOptions
write FCommonOptions default [Low(TCommonOption)..High(TCommonOption)];
property AutoChangeFileExt: boolean read FAutoChangeFileExt
write FAutoChangeFileExt default true;
property ConfirmAbort: boolean read FConfirmAbort
write FConfirmAbort default true;
property OnlyVisibleFields: boolean read FOnlyVisibleFields
write FOnlyVisibleFields default false;
property AutoCalcStrType: boolean read FAutoCalcStrType
write FAutoCalcStrType default false;
property OptionsFileName: string read FOptionsFileName
write FOptionsFileName;
property AutoSaveOptions: boolean read FAutoSaveOptions
write FAutoSaveOptions default false;
property AutoLoadOptions: boolean read FAutoLoadOptions
write FAutoLoadOptions default false;
property SaveLoadButtons: boolean read FSaveLoadButtons
write FsaveLoadButtons default false;
property About: string read FAbout write FAbout;
property _Version: string read F_Version write F_Version;
property FileName: string read FFileName write FFileName;
property ShowFile: boolean read FShowFile write FShowFile default true;
property PrintFile: boolean read FPrintFile write FPrintFile default false;
property ExportedFields: TStrings read FExportedFields
write SetExportedFields;
property Header: TStrings read FHeader write SetHeader;
property AllowCaptions: boolean read FAllowCaptions
write FAllowCaptions default true;
property CaptionRow: integer read FCaptionRow write FCaptionRow default -1;
property Captions: TStrings read FCaptions write SetCaptions;
property Footer: TStrings read FFooter write SetFooter;
property Formats: TQExportFormats read FFormats write SetFormats;
property UserFormats: TStrings read FUserFormats write SetUserFormats;
property ColumnsWidth: TStrings read FColumnsWidth write SetColumnsWidth;
property ColumnsAlign: TStrings read FColumnsAlign write SetColumnsAlign;
property CurrentRecordOnly: boolean read FCurrentRecordOnly
write FCurrentRecordOnly default false;
property ExportEmpty: boolean read FExportEmpty
write FExportEmpty default true;
property GoToFirstRecord: boolean read FGoToFirstRecord
write FGoToFirstRecord default true;
property ExportRecCount: integer read FExportRecCount
write FExportRecCount default 0;
property SkipRecCount: integer read FSkipRecCount
write FSkipRecCount default 0;
property RTFOptions: TQExportRTFOptions read FRTFOptions
write SetRTFOptions;
property XMLOptions: TQExportXMLOptions read FXMLOptions
write SetXMLOptions;
property SQLOptions: TQExportSQLOptions read FSQLOptions
write SetSQLOptions;
property HTMLPageOptions: TQExportHTMLPageOptions read FHTMLPageOptions
write SetHTMLPageOptions;
property HTMLTableOptions: TQExportHTMLTableOptions read FHTMLTableOptions
write SetHTMLTableOptions;
property HTMLMultiFileOptions: TQExportHTMLMultiFileOptions
read FHTMLMultiFileOptions write SetHTMLMultiFileOptions;
property TXTOptions: TQExportTXTOptions read FTXTOptions
write SetTXTOptions;
property CSVOptions: TQExportCSVOptions read FCSVOptions
write SetCSVOptions;
property PDFOptions: TQExportPDFOptions read FPDFOptions
write SetPDFOptions;
property AccessOptions: TQExportAccessOptions read FAccessOptions
write SetAccessOptions;
property XLSOptions: TQExportXLSOptions read FXLSOptions
write SetXLSOptions;
property OnGetHeader: TQExportGetColonEvent read FOnGetHeader
write FOnGetHeader;
property OnGetFooter: TQExportGetColonEvent read FOnGetFooter
write FOnGetFooter;
property OnBeginExport: TQExportEvent read FOnBeginExport
write FOnBeginExport;
property OnEndExport: TQExportEvent read FOnEndExport write FOnEndExport;
property OnFetchedRecord: TQRecordExportedEvent read FOnFetchedRecord
write FOnFetchedRecord;
property OnSkippedRecord: TQRecordExportedEvent read FOnSkippedRecord
write FOnSkippedRecord;
property OnBeforeExportRow: TQBeforeExportRowEvent read FOnBeforeExportRow
write FOnBeforeExportRow;
property OnBeforeExportXLSRow: TQBeforeExportXLSRowEvent
read FOnBeforeExportXLSRow write FOnBeforeExportXLSRow;
property OnExportedRecord: TQRecordExportedEvent read FOnExportedRecord
write FOnExportedRecord;
property OnExportedRecordXLS: TQRecordExportedXLSEvent
read FOnExportedRecordXLS write FOnExportedRecordXLS;
property OnStopExport: TQExportStopEvent read FOnStopExport
write FOnStopExport;
property OnGetExportText: TQGetExportTextEvent read FOnGetExportText
write FOnGetExportText;
property OnGetExportXLSText: TQGetExportXLSTextEvent
read FOnGetExportXLSText write FOnGetExportXLSText;
end;
implementation
uses QExportConsts, SysUtils, QExportBIFF, QExportXLSColorEditor,
IniFiles;
const
ExportTypeString: array[0..14] of string =
(QED_ExportType_XLS, QED_ExportType_Access, QED_ExportType_DOC,
QED_ExportType_RTF, QED_ExportType_HTML, QED_ExportType_XML,
QED_ExportType_DBF, QED_ExportType_PDF, QED_ExportType_TXT,
QED_ExportType_CSV, QED_ExportType_DIFF, QED_ExportType_SYLK,
QED_ExportType_LaTeX, QED_ExportType_SQL, QED_ExportType_Clipboard);
ExportTypeExtension: array[0..14] of string =
('xls', 'mdb', 'doc', 'rtf', 'html', 'xml', 'dbf', 'pdf', 'txt', 'csv',
'dif', 'slk', 'tex', 'sql', '');
ExportTypeFilter: array[0..14] of string =
(SMSExcelFilter, SMSAccessFilter, SMSWordFilter, SRTFFilter, SHTMLFilter,
SXMLFilter, SDBFFilter, SPDFFilter, STextFilter, SCSVFilter, SDIFFFilter,
SSYLKFilter, SLaTeXFilter, SSQLFilter, '');
{$R *.DFM}
{ TADO_QExportDialog }
constructor TADO_QExportDialog.Create(AOwner: TComponent);
begin
inherited;
FColumns := TQExportColumns.Create(Self, nil);
FExportSource := esDataSet;
FAllowedExports := [Low(TAllowedExport)..High(TAllowedExport)];
FCommonOptions := [Low(TCommonOption)..High(TCommonOption)];
FAutoChangeFileExt := true;
FConfirmAbort := true;
FOnlyVisibleFields := false;
FAutoCalcStrType := false;
FAutoSaveOptions := false;
FAutoLoadOptions := false;
FSaveLoadButtons := false;
FShowFile := true;
FPrintFile := false;
FExportedFields := TStringList.Create;
FHeader := TStringList.Create;
FAllowCaptions := true;
FCaptionRow := -1;
FCaptions := TStringList.Create;
FFooter := TStringList.Create;
FFormats := TQExportFormats.Create;
FUserFormats := TStringList.Create;
FColumnsWidth := TStringList.Create;
FColumnsAlign := TStringList.Create;
FCurrentRecordOnly := false;
FExportEmpty := true;
FGoToFirstRecord := true;
FExportRecCount := 0;
FSkipRecCount := 0;
FRTFOptions := TQExportRTFOptions.Create(Self);
FXMLOptions := TQExportXMLOptions.Create(Self);
FSQLOptions := TQExportSQLOptions.Create(Self);
FHTMLPageOptions := TQExportHTMLPageOptions.Create(Self);
FHTMLTableOptions := TQExportHTMLTableOptions.Create(Self);
FHTMLMultiFileOptions := TQExportHTMLMultiFileOptions.Create(Self);
FTXTOptions := TQExportTXTOptions.Create(Self);
FCSVOptions := TQExportCSVOptions.Create(Self);
FPDFOptions := TQExportPDFOptions.Create(Self);
FAccessOptions := TQExportAccessOptions.Create(Self);
FXLSOptions := TQExportXLSOptions.Create(Self);
end;
destructor TADO_QExportDialog.Destroy;
begin
FRTFOptions.Free;
FXMLOptions.Free;
FSQLOptions.Free;
FHTMLPageOptions.Free;
FHTMLTableOptions.Free;
FHTMLMultiFileOptions.Free;
FTXTOptions.Free;
FCSVOptions.Free;
FPDFOptions.Free;
FAccessOptions.Free;
FXLSOptions.Free;
FColumns.Free;
FExportedFields.Free;
FHeader.Free;
FCaptions.Free;
FFooter.Free;
FFormats.Free;
FUserFormats.Free;
FColumnsWidth.Free;
FColumnsAlign.Free;
inherited;
end;
procedure TADO_QExportDialog.Execute;
var
F: TADO_QExportDialogF;
begin
if ((ExportSource = esDataSet) and not Assigned(DataSet)) or
((ExportSource = esDBGrid) and not Assigned(DBGrid)) or
((ExportSource = esListView) and not Assigned(ListView)) or
((ExportSource = esStringGrid) and not Assigned(StringGrid))
then raise Exception.CreateFmt(QEM_ExportSourceNotAssigned,
[QExportSourceAsString(ExportSource)]);
if AllowedExports = [] then
raise Exception.Create(QEM_AllowedExportsEmpty);
FColumns.Clear;
FColumns.Fill(true);
F := TADO_QExportDialogF.Create(Self);
try
F.ShowModal;
finally
F.Free;
end;
end;
procedure TADO_QExportDialog.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (Operation = opRemove) then begin
if AComponent = FDataSet then FDataSet := nil;
if AComponent = FListView then FListView := nil;
if AComponent = FDBGrid then FDBGrid := nil;
if AComponent = FStringGrid then FStringGrid := nil;
end;
end;
procedure TADO_QExportDialog.SetExportedFields(const Value: TStrings);
begin
FExportedFields.Assign(Value);
end;
procedure TADO_QExportDialog.SetHeader(const Value: TStrings);
begin
FHeader.Assign(Value);
end;
procedure TADO_QExportDialog.SetCaptions(const Value: TStrings);
begin
FCaptions.Assign(Value);
end;
procedure TADO_QExportDialog.SetFooter(const Value: TStrings);
begin
FFooter.Assign(Value);
end;
procedure TADO_QExportDialog.SetFormats(const Value: TQExportFormats);
begin
FFormats.Assign(Value);
end;
procedure TADO_QExportDialog.SetUserFormats(const Value: TStrings);
begin
FUserFormats.Assign(Value);
end;
procedure TADO_QExportDialog.SetColumnsWidth(const Value: TStrings);
begin
FColumnsWidth.Assign(Value);
end;
procedure TADO_QExportDialog.SetColumnsAlign(const Value: TStrings);
begin
FColumnsAlign.Assign(Value);
end;
procedure TADO_QExportDialog.SetRTFOptions(const Value: TQExportRTFOptions);
begin
FRTFOptions.Assign(Value);
end;
procedure TADO_QExportDialog.SetXMLOptions(const Value: TQExportXMLOptions);
begin
FXMLOptions.Assign(Value);
end;
procedure TADO_QExportDialog.SetSQLOptions(const Value: TQExportSQLOptions);
begin
FSQLOptions.Assign(Value);
end;
procedure TADO_QExportDialog.SetHTMLPageOptions(
const Value: TQExportHTMLPageOptions);
begin
FHTMLPageOptions.Assign(Value);
end;
procedure TADO_QExportDialog.SetHTMLTableOptions(
const Value: TQExportHTMLTableOptions);
begin
FHTMLTableOptions.Assign(Value);
end;
procedure TADO_QExportDialog.SetHTMLMultiFileOptions(
const Value: TQExportHTMLMultiFileOptions);
begin
FHTMLMultiFileOptions.Assign(Value);
end;
procedure TADO_QExportDialog.SetTXTOptions(const Value: TQExportTXTOptions);
begin
FTXTOptions.Assign(Value);
end;
procedure TADO_QExportDialog.SetCSVOptions(const Value: TQExportCSVOptions);
begin
FCSVOptions.Assign(Value);
end;
procedure TADO_QExportDialog.SetPDFOptions(const Value: TQExportPDFOptions);
begin
FPDFOptions.Assign(Value);
end;
procedure TADO_QExportDialog.SetAccessOptions(const Value: TQExportAccessOptions);
begin
FAccessOptions.Assign(Value);
end;
procedure TADO_QExportDialog.SetXLSOptions(const Value: TQExportXLSOptions);
begin
FXLSOptions.Assign(Value);
end;
{ TQExportDialogF }
function TADO_QExportDialogF.GetDialog: TADO_QExportDialog;
begin
Result := Owner as TADO_QExportDialog;
end;
function TADO_QExportDialogF.GetDataSet: TDataSet;
begin
Result := Dialog.DataSet;
end;
function TADO_QExportDialogF.GetListView: TListView;
begin
Result := Dialog.ListView;
end;
function TADO_QExportDialogF.GetDBGrid: TDBGrid;
begin
Result := Dialog.DBGrid;
end;
function TADO_QExportDialogF.GetStringGrid: TStringGrid;
begin
Result := Dialog.StringGrid;
end;
function TADO_QExportDialogF.GetAutoChangeFileExt: boolean;
begin
Result := Dialog.AutoChangeFileExt;
end;
function TADO_QExportDialogF.GetSaveLoadButtons: boolean;
begin
Result := Dialog.SaveLoadButtons;
end;
function TADO_QExportDialogF.GetCommonOptions: TCommonOptions;
begin
Result := Dialog.CommonOptions;
end;
function TADO_QExportDialogF.GetConfirmAbort: boolean;
begin
Result := Dialog.ConfirmAbort;
end;
function TADO_QExportDialogF.GetAutoSaveOptions: boolean;
begin
Result := Dialog.AutoSaveOptions;
end;
function TADO_QExportDialogF.GetAutoLoadOptions: boolean;
begin
Result := Dialog.AutoLoadOptions;
end;
function TADO_QExportDialogF.GetExportSource: TQExportSource;
begin
Result := Dialog.ExportSource;
end;
procedure TADO_QExportDialogF.SetFileName(const Value: string);
begin
if FFileName <> Value then begin
FFileName := Value;
edFileName.Text := FFileName;
ShowTitle;
end;
end;
procedure TADO_QExportDialogF.SetShowFile(const Value: boolean);
begin
if FShowFile <> Value then begin
FShowFile := Value;
chShowFile.Checked := FShowFile;
end;
end;
procedure TADO_QExportDialogF.SetPrintFile(const Value: boolean);
begin
if FPrintFile <> Value then begin
FPrintFile := Value;
chPrintFile.Checked := FPrintFile;
end;
end;
function TADO_QExportDialogF.GetExportType: TAllowedExport;
begin
Result :=
TAllowedExport(Integer(rgExportType.Items.Objects[rgExportType.ItemIndex]));
end;
procedure TADO_QExportDialogF.SetExportType(const Value: TAllowedExport);
var
i: integer;
begin
for i := 0 to rgExportType.Items.Count - 1 do
if Integer(rgExportType.Items.Objects[i]) = Integer(Value) then begin
rgExportType.ItemIndex := i;
Break;
end;
end;
procedure TADO_QExportDialogF.SetOptionsFileName(const Value: string);
begin
if AnsiCompareText(FOptionsFileName, Value) <> 0 then begin
FOptionsFileName := Value;
odOptions.FileName := FOptionsFileName;
sdOptions.FileName := FOptionsFileName;
end;
end;
procedure TADO_QExportDialogF.SetGoToFirstRecord(const Value: boolean);
begin
if FGoToFirstRecord <> Value then begin
FGoToFirstRecord := Value;
chGoToFirstRecord.Checked := FGoToFirstRecord;
end;
end;
procedure TADO_QExportDialogF.SetCurrentRecordOnly(const Value: boolean);
begin
if FCurrentRecordOnly <> Value then begin
FCurrentRecordOnly := Value;
chCurrentRecordOnly.Checked := FCurrentRecordOnly;
end;
end;
procedure TADO_QExportDialogF.SetExportEmpty(const Value: boolean);
begin
if FExportEmpty <> Value then begin
FExportEmpty := Value;
chExportEmpty.Checked := FExportEmpty;
end;
end;
procedure TADO_QExportDialogF.SetExportRecCount(const Value: integer);
begin
if FExportRecCount <> Value then begin
FExportRecCount := Value;
edExportRecCount.Text := IntToStr(FExportRecCount);
if FExportRecCount > 0 then rbExportOnly.Checked := true;
end;
end;
procedure TADO_QExportDialogF.SetSkipRecCount(const Value: integer);
begin
if FSkipRecCount <> Value then begin
FSkipRecCount := Value;
edSkipRecCount.Text := IntToStr(FSkipRecCount);
end;
end;
procedure TADO_QExportDialogF.SetAllowCaptions(const Value: boolean);
begin
if FAllowCaptions <> Value then begin
FAllowCaptions := Value;
chAllowCaptions.Checked := FAllowCaptions;
end;
end;
procedure TADO_QExportDialogF.SetCaptionRow(const Value: integer);
begin
if FCaptionRow <> Value then begin
FCaptionRow := Value;
edCaptionRow.Text := IntToStr(FCaptionRow);
end;
end;
procedure TADO_QExportDialogF.SetIntegerFmt(const Value: string);
begin
if FIntegerFmt <> Value then begin
FIntegerFmt := Value;
edIntegerFormat.Text := FIntegerFmt;
end;
end;
procedure TADO_QExportDialogF.SetFloatFmt(const Value: string);
begin
if FFloatFmt <> Value then begin
FFloatFmt := Value;
edFloatFormat.Text := FFloatFmt;
end;
end;
procedure TADO_QExportDialogF.SetDateFmt(const Value: string);
begin
if FDateFmt <> Value then begin
FDateFmt := Value;
edDateFormat.Text := FDateFmt;
end;
end;
procedure TADO_QExportDialogF.SetTimeFmt(const Value: string);
begin
if FTimeFmt <> Value then begin
FTimeFmt := Value;
edTimeFormat.Text := FTimeFmt;
end;
end;
procedure TADO_QExportDialogF.SetDateTimeFmt(const Value: string);
begin
if FDateTimeFmt <> Value then begin
FDateTimeFmt := Value;
edDateTimeFormat.Text := FDateTimeFmt;
end;
end;
procedure TADO_QExportDialogF.SetCurrencyFmt(const Value: string);
begin
if FCurrencyFmt <> Value then begin
FCurrencyFmt := Value;
edCurrencyFormat.Text := FCurrencyFmt;
end;
end;
procedure TADO_QExportDialogF.SetBooleanTrue(const Value: string);
begin
if FBooleanTrue <> Value then begin
FBooleanTrue := Value;
edBooleanTrue.Text := FBooleanTrue;
end;
end;
procedure TADO_QExportDialogF.SetBooleanFalse(const Value: string);
begin
if FBooleanFalse <> Value then begin
FBooleanFalse := Value;
edBooleanFalse.Text := FBooleanFalse;
end;
end;
procedure TADO_QExportDialogF.SetNullString(const Value: string);
begin
if FNullString <> Value then begin
FNullString := Value;
edNullString.Text := FNullString;
edSQLNullString.Text := FNullString;
end;
end;
procedure TADO_QExportDialogF.SetRTFPageOrientation(
const Value: TQExportPageOrientation);
begin
if FRTFPageOrientation <> Value then begin
FRTFPageOrientation := Value;
rgRTFPageOrientation.ItemIndex := Integer(FRTFPageOrientation);
end;
end;
procedure TADO_QExportDialogF.SetXLSPageHeader(const Value: string);
begin
if FXLSPageHeader <> Value then begin
FXLSPageHeader := Value;
edXLSPageHeader.Text := FXLSPageHeader;
end;
end;
procedure TADO_QExportDialogF.SetXLSPageFooter(const Value: string);
begin
if FXLSPageFooter <> Value then begin
FXLSPageFooter := Value;
edXLSPageFooter.Text := FXLSPageFooter;
end;
end;
procedure TADO_QExportDialogF.SetXLSSheetTitle(const Value: string);
begin
if FXLSSheetTitle <> Value then begin
FXLSSheetTitle := Value;
edXLSSheetTitle.Text := FXLSSheetTitle;
end;
end;
procedure TADO_QExportDialogF.SetXLSStripType(const Value: TxlsStripType);
begin
if FXLSStripType <> Value then begin
FXLSStripType := Value;
rgXLSStripType.ItemIndex := Integer(FXLSStripType);
end;
end;
procedure TADO_QExportDialogF.SetXLSAutoCalcColWidth(const Value: boolean);
begin
if FXLSAutoCalcColWidth <> Value then begin
FXLSAutoCalcColWidth := Value;
chXLSAutoCalcColWidth.Checked := FXLSAutoCalcColWidth;
end;
end;
procedure TADO_QExportDialogF.SetHTMLTitle(const Value: string);
begin
if FHTMLTitle <> Value then begin
FHTMLTitle := Value;
edHTMLTitle.Text := FHTMLTitle;
end;
end;
procedure TADO_QExportDialogF.SetHTMLUsingCSS(const Value: TUsingCSS);
begin
if FHTMLUsingCSS <> Value then begin
FHTMLUsingCSS := Value;
case FHTMLUsingCSS of
usInternal: rbInternal.Checked := true;
usExternal: rbExternal.Checked := true;
end;
edHTMLCSSFileName.Enabled := FHTMLUsingCSS = usExternal;
laHTMLCSSFileName.Enabled := FHTMLUsingCSS = usExternal;
btnHTMLCSSFileName.Enabled := FHTMLUsingCSS = usExternal;
end;
end;
procedure TADO_QExportDialogF.SetHTMLCSSFileName(const Value: string);
begin
if FHTMLCSSFileName <> Value then begin
FHTMLCSSFileName := Value;
edHTMLCSSFileName.Text := FHTMLCSSFileName;
end;
end;
procedure TADO_QExportDialogF.SetHTMLOverwriteCSSFile(const Value: boolean);
begin
if FHTMLOverwriteCSSFile <> Value then begin
FHTMLOverwriteCSSFile := Value;
chHTMLOverwriteCSSFile.Checked := FHTMLOverwriteCSSFile;
end;
end;
procedure TADO_QExportDialogF.SetHTMLUseMultiFileExport(const Value: boolean);
begin
if FHTMLUseMultiFileExport <> Value then begin
FHTMLUseMultiFileExport := Value;
chHTMLUseMultiFileExport.Checked := FHTMLUseMultiFileExport;
end;
end;
procedure TADO_QExportDialogF.SetHTMLFileRecCount(const Value: integer);
begin
if FHTMLFileRecCount <> Value then begin
FHTMLFileRecCount := Value;
edHTMLFileRecCount.Text := IntToStr(FHTMLFileRecCount);
end;
end;
procedure TADO_QExportDialogF.SetHTMLGenerateIndex(const Value: boolean);
begin
if FHTMLGenerateIndex <> Value then begin
FHTMLGenerateIndex := Value;
chHTMLGenerateIndex.Checked := FHTMLGenerateIndex;
end;
end;
procedure TADO_QExportDialogF.SetHTMLIndexLinkTemplate(const Value: string);
begin
if FHTMLIndexLinkTemplate <> Value then begin
FHTMLIndexLinkTemplate := Value;
edHTMLIndexLinkTemplate.Text := Value;
end;
end;
procedure TADO_QExportDialogF.SetHTMLNavigationOnTop(const Value: boolean);
begin
if FHTMLNavigationOnTop <> Value then begin
FHTMLNavigationOnTop := Value;
chHTMLNavigationOnTop.Checked := Value;
end;
end;
procedure TADO_QExportDialogF.SetHTMLNavigationOnBottom(const Value: boolean);
begin
if FHTMLNavigationOnBottom <> Value then begin
FHTMLNavigationOnBottom := Value;
chHTMLNavigationOnBottom.Checked := Value;
end;
end;
procedure TADO_QExportDialogF.SetHTMLIndexLinkTitle(const Value: string);
begin
if FHTMLIndexLinkTitle <> Value then begin
FHTMLIndexLinkTitle := Value;
edHTMLIndexLinkTitle.Text := FHTMLIndexLinkTitle;
end;
end;
procedure TADO_QExportDialogF.SetHTMLFirstLinkTitle(const Value: string);
begin
if FHTMLFirstLinkTitle <> Value then begin
FHTMLFirstLinkTitle := Value;
edHTMLFirstLinkTitle.Text := FHTMLFirstLinkTitle;
end;
end;
procedure TADO_QExportDialogF.SetHTMLPriorLinkTitle(const Value: string);
begin
if FHTMLPriorLinkTitle <> Value then begin
FHTMLPriorLinkTitle := Value;
edHTMLPriorLinkTitle.Text := FHTMLPriorLinkTitle;
end;
end;
procedure TADO_QExportDialogF.SetHTMLNextLinkTitle(const Value: string);
begin
if FHTMLNextLinkTitle <> Value then begin
FHTMLNextLinkTitle := Value;
edHTMLNextLinkTitle.Text := FHTMLNextLinkTitle;
end;
end;
procedure TADO_QExportDialogF.SetHTMLLastLinkTitle(const Value: string);
begin
if FHTMLLastLinkTitle <> Value then begin
FHTMLLastLinkTitle := Value;
edHTMLLastLinkTitle.Text := FHTMLLastLinkTitle;
end;
end;
procedure TADO_QExportDialogF.SetHTMLFontName(const Value: string);
begin
if FHTMLFontName <> Value then begin
FHTMLFontName := Value;
cbxHTMLFontName.Text := FHTMLFontName;
end;
end;
procedure TADO_QExportDialogF.SetHTMLBackground(const Value: string);
begin
if FHTMLBackground <> Value then begin
FHTMLBackground := Value;
edHTMLBackground.Text := FHTMLBackground;
end;
end;
procedure TADO_QExportDialogF.SetHTMLBodyAdvanced(const Value: string);
begin
if FHTMLBodyAdvanced <> Value then begin
FHTMLBodyAdvanced := Value;
edHTMLBodyAdvanced.Text := FHTMLBodyAdvanced;
end;
end;
procedure TADO_QExportDialogF.SetHTMLCellPadding(const Value: integer);
begin
if FHTMLCellPadding <> Value then begin
FHTMLCellPadding := Value;
edHTMLCellPadding.Text := IntToStr(FHTMLCellPadding);
end;
end;
procedure TADO_QExportDialogF.SetHTMLCellSpacing(const Value: integer);
begin
if FHTMLCellSpacing <> Value then begin
FHTMLCellSpacing := Value;
edHTMLCellSpacing.Text := IntToStr(FHTMLCellSpacing);
end;
end;
procedure TADO_QExportDialogF.SetHTMLBorderWidth(const Value: integer);
begin
if FHTMLBorderWidth <> Value then begin
FHTMLBorderWidth := Value;
edHTMLBorderWidth.Text := IntToStr(FHTMLBorderWidth);
end;
end;
procedure TADO_QExportDialogF.SetHTMLTableBackground(const Value: string);
begin
if FHTMLTableBackground <> Value then begin
FHTMLTableBackground := Value;
edHTMLTableBackground.Text := FHTMLTableBackground;
end;
end;
procedure TADO_QExportDialogF.SetHTMLTableAdvanced(const Value: string);
begin
if FHTMLTableAdvanced <> Value then begin
FHTMLTableAdvanced := Value;
edHTMLTableAdvanced.Text := FHTMLTableAdvanced;
end;
end;
procedure TADO_QExportDialogF.SetHTMLBackgroundColor(const Value: TColor);
begin
if FHTMLBackgroundColor <> Value then begin
FHTMLBackgroundColor := Value;
paHTMLBackground.Color := FHTMLBackgroundColor;
end;
end;
procedure TADO_QExportDialogF.SetHTMLFontColor(const Value: TColor);
begin
if FHTMLFontColor <> Value then begin
FHTMLFontColor := Value;
laHTMLFont.Font.Color := FHTMLFontColor;
end;
end;
procedure TADO_QExportDialogF.SetHTMLHeadBackgroundColor(const Value: TColor);
var
i: integer;
begin
if FHTMLHeadBackgroundColor <> Value then begin
FHTMLHeadBackgroundColor := Value;
for i := 1 to 3 do
(FindComponent('paHTMLColumnHead_' + IntToStr(i)) as TPanel).Color :=
FHTMLHeadBackgroundColor;
end;
end;
procedure TADO_QExportDialogF.SetHTMLHeadFontColor(const Value: TColor);
var
i: integer;
begin
if FHTMLHeadFontColor <> Value then begin
FHTMLHeadFontColor := Value;
for i := 1 to 3 do
(FindComponent('laHTMLHead_' + IntToStr(i)) as TLabel).Font.Color :=
FHTMLHeadFontColor;
end;
end;
procedure TADO_QExportDialogF.SetHTMLOddRowBackgroundColor(
const Value: TColor);
var
i: integer;
begin
if FHTMLOddRowBackgroundColor <> Value then begin
FHTMLOddRowBackgroundColor := Value;
for i := 1 to 6 do
(FindComponent('paHTMLOddRowCol_' + IntToStr(i)) as TPanel).Color :=
FHTMLOddRowBackgroundColor;
end;
end;
procedure TADO_QExportDialogF.SetHTMLEvenRowBackgroundColor(
const Value: TColor);
var
i: integer;
begin
if FHTMLEvenRowBackgroundColor <> Value then begin
FHTMLEvenRowBackgroundColor := Value;
for i := 1 to 6 do
(FindComponent('paHTMLEvenRowCol_' + IntToStr(i)) as TPanel).Color :=
FHTMLEvenRowBackgroundColor;
end;
end;
procedure TADO_QExportDialogF.SetHTMLDataFontColor(const Value: TColor);
var
i: integer;
begin
if FHTMLDataFontColor <> Value then begin
FHTMLDataFontColor := Value;
for i := 1 to 12 do
(FindComponent(Format('laHTMLData_%d',[i])) as TLabel).Font.Color :=
FHTMLDataFontColor;
end;
end;
procedure TADO_QExportDialogF.SetHTMLLinkColor(const Value: TColor);
begin
if FHTMLLinkColor <> Value then begin
FHTMLLinkColor := Value;
laHTMLLink.Font.Color := FHTMLLinkColor;
end;
end;
procedure TADO_QExportDialogF.SetHTMLVLinkColor(const Value: TColor);
begin
if FHTMLVLinkColor <> Value then begin
FHTMLVLinkColor := Value;
laHTMLVLink.Font.Color := FHTMLVLinkColor;
end;
end;
procedure TADO_QExportDialogF.SetHTMLALinkColor(const Value: TColor);
begin
if FHTMLALinkColor <> Value then begin
FHTMLALinkColor := Value;
laHTMLALink.Font.Color := FHTMLALinkColor;
end;
end;
procedure TADO_QExportDialogF.SetXMLStandalone(const Value: boolean);
begin
if FXMLStandalone <> Value then begin
FXMLStandalone := Value;
chXMLStandalone.Checked := FXMLStandalone;
end;
end;
procedure TADO_QExportDialogF.SetXMLEncoding(const Value: string);
begin
if AnsiCompareText(FXMLEncoding, Value) <> 0 then begin
FXMLEncoding := Value;
edXMLEncoding.Text := FXMLEncoding;
end;
end;
procedure TADO_QExportDialogF.SetSQLTableName(const Value: string);
begin
if FSQLTableName <> Value then begin
FSQLTableName := Value;
edSQLTableName.Text := FSQLTableName;
end;
end;
procedure TADO_QExportDialogF.SetSQLCreateTable(const Value: boolean);
begin
if FSQLCreateTable <> Value then begin
FSQLCreateTable := Value;
chSQLCreateTable.Checked := FSQLCreateTable;
end;
end;
procedure TADO_QExportDialogF.SetSQLCommitRecCount(const Value: integer);
begin
if FSQLCommitRecCount <> Value then begin
FSQLCommitRecCount := Value;
edSQLCommitRecCount.Text := IntToStr(FSQLCommitRecCount);
end;
end;
procedure TADO_QExportDialogF.SetSQLCommitAfterScript(const Value: boolean);
begin
if FSQLCommitAfterScript <> Value then begin
FSQLCommitAfterScript := Value;
chSQLCommitAfterScript.Checked := FSQLCommitAfterScript;
end;
end;
procedure TADO_QExportDialogF.SetSQLCommitStatement(const Value: string);
begin
if AnsiCompareStr(FSQLCommitStatement, Value) <> 0 then begin
FSQLCommitStatement := Value;
edSQLCommitStatement.Text := FSQLCommitStatement;
end;
end;
procedure TADO_QExportDialogF.SetSQLStatementTerm(const Value: string);
begin
if AnsiCompareStr(FSQLStatementTerm, Value) <> 0 then begin
FSQLStatementTerm := Value;
edSQLStatementTerm.Text := FSQLStatementTerm;
end;
end;
procedure TADO_QExportDialogF.SetTXTAutoCalcColWidth(const Value: boolean);
begin
if FTXTAutoCalcColWidth <> Value then begin
FTXTAutoCalcColWidth := Value;
chTXTAutoCalcColWidth.Checked := FTXTAutoCalcColWidth;
end;
end;
procedure TADO_QExportDialogF.SetTXTSpacing(const Value: integer);
begin
if FTXTSpacing <> Value then begin
FTXTSpacing := Value;
edTXTSpacing.Text := IntToStr(FTXTSpacing);
end;
end;
procedure TADO_QExportDialogF.SetCSVQuoteStrings(const Value: boolean);
begin
if FCSVQuoteStrings <> Value then begin
FCSVQuoteStrings := Value;
chCSVQuoteStrings.Checked := FCSVQuoteStrings;
end;
end;
procedure TADO_QExportDialogF.SetCSVComma(const Value: char);
begin
if FCSVComma <> Value then begin
FCSVComma := Value;
edCSVComma.Text := Char2Str(FCSVComma);
end;
end;
procedure TADO_QExportDialogF.SetCSVQuote(const Value: char);
begin
if FCSVQuote <> Value then begin
FCSVQuote := Value;
edCSVQuote.Text := Char2Str(FCSVQuote);
end;
end;
procedure TADO_QExportDialogF.SetAccessTableName(const Value: string);
begin
if FAccessTableName <> Value then begin
FAccessTableName := Value;
edAccessTableName.Text := FAccessTableName;
end;
end;
procedure TADO_QExportDialogF.SetAccessCreateTable(const Value: boolean);
begin
if FAccessCreateTable <> Value then begin
FAccessCreateTable := Value;
chAccessCreateTable.Checked := FAccessCreateTable;
end;
end;
procedure TADO_QExportDialogF.InitializeDialog;
begin
Pages.ActivePage := tshExportType;
pcExportType.ActivePage := tshExportFormats;
ActiveControl := edFileName;
tshExportOptions.TabVisible := coOptions in CommonOptions;
FillFields;
ResetStandardFormats;
memHeader.Lines.Assign(Dialog.Header);
if Assigned(Dialog.OnGetHeader) then Dialog.OnGetHeader(Self, memHeader.Lines);
memFooter.Lines.Assign(Dialog.Footer);
if Assigned(Dialog.OnGetFooter) then Dialog.OnGetFooter(Self, memFooter.Lines);
SetCaptions;
FileName := Dialog.FileName;
ShowFile := Dialog.ShowFile;
PrintFile := Dialog.PrintFile;
OptionsFileName := Dialog.OptionsFileName;
GoToFirstRecord := Dialog.GoToFirstRecord;
CurrentRecordOnly := Dialog.CurrentRecordOnly;
ExportEmpty := Dialog.ExportEmpty;
ExportRecCount := Dialog.ExportRecCount;
SkipRecCount := Dialog.SkipRecCount;
FillAllowedExports;
rgExportType.OnClick(nil);
rbExportOnly.Checked := Dialog.ExportRecCount > 0;
miSaveOptions.Enabled := SaveLoadButtons;
miSaveOptions.Visible := SaveLoadButtons;
miLoadOptions.Enabled := SaveLoadButtons;
miLoadOptions.Visible := SaveLoadButtons;
bTools.Enabled := (miSaveOptions.Enabled or miLoadOptions.Enabled);
bTools.Visible := (miSaveOptions.Visible or miLoadOptions.Visible);
cbxFormatFields.OnChange(nil);
// Captions
AllowCaptions := Dialog.AllowCaptions;
FCaptionRow := -1;
CaptionRow := Dialog.CaptionRow;
laCaptionRow.Visible := Assigned(Dialog.StringGrid) and
(Dialog.ExportSource = esStringGrid);
edCaptionRow.Visible := laCaptionRow.Visible;
if laCaptionRow.Visible and (CaptionRow > -1) then LoadStringGridCaption;
// RTF
RTFPageOrientation := Dialog.RTFOptions.PageOrientation; //RTFExp.Options.PageOrientation;
RTFExp.Options.DefaultFont.Assign(Dialog.RTFOptions.DefaultFont);
RTFExp.Options.HeaderFont.Assign(Dialog.RTFOptions.HeaderFont);
rgRTFPageOrientation.ItemIndex := Integer(RTFPageOrientation);
// XLS
pcXLS.ActivePage := tshXLSDataFormat;
pcXLSDataFormat.ActivePage := tshXLSFont;
cbxXLSFont.Items.Assign(Screen.Fonts);
XLSPageHeader := Dialog.XLSOptions.PageHeader; //XLSExp.Options.PageHeader;
XLSPageFooter := Dialog.XLSOptions.PageFooter; //XLSExp.Options.PageFooter;
XLSSheetTitle := Dialog.XLSOptions.SheetTitle; //XLSExp.Options.SheetTitle;
XLSStripType := Dialog.XLSOptions.StripType; //XLSExp.StripType;
XLSAutoCalcColWidth := Dialog.XLSOptions.AutoCalcColWidth; //XLSExp.AutoCalcColWidth;
pcXLSFormats.ActivePage := tshXLSFields;
XLSShowStyleButtons;
// HTML
pcHTML.ActivePage := tshHTMLPreview;
cbxHTMLFontName.Items.Assign(Screen.Fonts);
HTMLTitle := Dialog.HTMLPageOptions.Title; //HTMLExp.Title;
HTMLBackgroundColor := Dialog.HTMLPageOptions.BackgroundColor;
HTMLFontName := Dialog.HTMLPageOptions.TextFont.Name; //HTMLExp.HTMLOptions.TextFont.Name;
HTMLLinkColor := Dialog.HTMLPageOptions.LinkColor;
HTMLVLinkColor := Dialog.HTMLPageOptions.VLinkColor;
HTMLALinkColor := Dialog.HTMLPageOptions.ALinkColor;
HTMLBackground := Dialog.HTMLPageOptions.BackgroundFileName; //HTMLExp.HTMLOptions.BackgroundFileName;
HTMLBodyAdvanced := Dialog.HTMLPageOptions.AdvancedAttributes.Text; //HTMLExp.HTMLOptions.AdvancedAttributes.Text;
HTMLUsingCSS := Dialog.HTMLPageOptions.UsingCSS; //HTMLExp.UsingCSS;
HTMLCSSFileName := Dialog.HTMLPageOptions.CSSFileName; //HTMLExp.CSSFileName;
HTMLOverwriteCSSFile := Dialog.HTMLPageOptions.OverwriteCSSFile;
HTMLUseMultiFileExport := Dialog.HTMLMultiFileOptions.FileRecCount > 0; //HTMLExp.MaxRecords > 0;
HTMLFileRecCount := Dialog.HTMLMultiFileOptions.FileRecCount; //HTMLExp.MaxRecords;
HTMLGenerateIndex := Dialog.HTMLMultiFileOptions.GenerateIndex; //HTMLExp.GenerateIndex;
HTMLIndexLinkTemplate := Dialog.HTMLMultiFileOptions.IndexLinkTemplate; //HTMLExp.Navigation.IndexLinkTemplate;
HTMLNavigationOnTop := Dialog.HTMLMultiFileOptions.NavigationOnTop; //HTMLExp.Navigation.OnTop;
HTMLNavigationOnBottom := Dialog.HTMLMultiFileOptions.NavigationOnBottom; //HTMLExp.Navigation.OnBottom;
HTMLIndexLinkTitle := Dialog.HTMLMultiFileOptions.IndexLinkTitle; //HTMLExp.Navigation.IndexLinkTitle;
HTMLFirstLinkTitle := Dialog.HTMLMultiFileOptions.FirstLinkTitle; //HTMLExp.Navigation.FirstLinkTitle;
HTMLPriorLinkTitle := Dialog.HTMLMultiFileOptions.PriorLinkTitle; //HTMLExp.Navigation.PriorLinkTitle;
HTMLNextLinkTitle := Dialog.HTMLMultiFileOptions.NextLinkTitle; //HTMLExp.Navigation.NextLinkTitle;
HTMLLastLinkTitle := Dialog.HTMLMultiFileOptions.LastLinkTitle; //HTMLExp.Navigation.LastLinkTitle;
HTMLUpdateMultifileControls;
HTMLBorderWidth := Dialog.HTMLTableOptions.BorderWidth; //HTMLExp.TableOptions.Border;
HTMLCellPadding := Dialog.HTMLTableOptions.CellPadding; //HTMLExp.TableOptions.CellPadding;
HTMLCellSpacing := Dialog.HTMLTableOptions.CellSpacing; //HTMLExp.TableOptions.CellSpacing;
HTMLTableAdvanced := Dialog.HTMLTableOptions.AdvancedAttributes.Text; //HTMLExp.TableOptions.AdvancedAttributes.Text;
HTMLHeadBackgroundColor := Dialog.HTMLTableOptions.HeadersRowBgColor;
HTMLHeadFontColor := Dialog.HTMLTableOptions.HeadersRowFontColor;
HTMLEvenRowBackgroundColor := Dialog.HTMLTableOptions.TableBgColor;
HTMLDataFontColor := Dialog.HTMLTableOptions.TableFontColor;
HTMLOddRowBackgroundColor := Dialog.HTMLTableOptions.OddRowBgColor;
HTMLTableBackground := Dialog.HTMLTableOptions.BackgroundFileName;
HTMLFillColors;
cbxHTMLTemplate.ItemIndex := Integer(HTMLExp.HTMLTemplate);
cbxHTMLTemplate.OnChange(nil);
// XML
XMLStandAlone := Dialog.XMLOptions.Standalone; //XMLExp.Options.StandAlone;
XMLEncoding := Dialog.XMLOptions.Encoding; //XMLExp.Options.Encoding;
// SQL
SQLTableName := Dialog.SQLOptions.TableName; //SQLExp.TableName;
SQLCreateTable := Dialog.SQLOptions.CreateTable; //SQLExp.CreateTable;
SQLCommitRecCount := Dialog.SQLOptions.CommitRecCount; //SQLExp.CommitRecCount;
SQLCommitAfterScript := Dialog.SQLOptions.CommitAfterScript; //SQLExp.CommitAfterScript;
SQLCommitStatement := Dialog.SQLOptions.CommitStatement; //SQLExp.CommitStatement;
SQLStatementTerm := Dialog.SQLOptions.StatementTerm; //SQLExp.StatementTerm;
// ASCII
TXTAutoCalcColWidth := Dialog.TXTOptions.AutoCalcColWidth; //ASCIIExp.AutoCalcColWidth;
TXTSpacing := Dialog.TXTOptions.ColSpacing; //ASCIIExp.TXTSpacing;
CSVQuoteStrings := Dialog.CSVOptions.QuoteStrings; //ASCIIExp.CSVQuoteStrings;
CSVComma := Dialog.CSVOptions.Comma; //ASCIIExp.CSVComma;
CSVQuote := Dialog.CSVOptions.Quote; //ASCIIExp.CSVQuote;
// Access
AccessTableName := Dialog.AccessOptions.TableName; //AccessExp.TableName;
AccessCreateTable := Dialog.AccessOptions.CreateTable; //AccessExp.AutoCreateTable;
// PDF
PDFColSpacing := Dialog.PDFOptions.ColSpacing;
PDFRowSpacing := Dialog.PDFOptions.RowSpacing;
PDFGridLineWidth := Dialog.PDFOptions.GridLineWidth;
PDFPageFormat := Dialog.PDFOptions.PageOptions.Format;
PDFPageUnits := Dialog.PDFOptions.PageOptions.Units;
PDFPageOrientation := Dialog.PDFOptions.PageOptions.Orientation;
if PDFPageFormat = pfUser then begin
FPDFPageWidth := Units2Dot(Dialog.PDFOptions.PageOptions.Units,
Dialog.PDFOptions.PageOptions.Width);
FPDFPageHeight := Units2Dot(Dialog.PDFOptions.PageOptions.Units,
Dialog.PDFOptions.PageOptions.Height);
end;
FPDFPageMarginLeft := Units2Dot(Dialog.PDFOptions.PageOptions.Units,
Dialog.PDFOptions.PageOptions.MarginLeft);
FPDFPageMarginRight := Units2Dot(Dialog.PDFOptions.PageOptions.Units,
Dialog.PDFOptions.PageOptions.MarginRight);
FPDFPageMarginTop := Units2Dot(Dialog.PDFOptions.PageOptions.Units,
Dialog.PDFOptions.PageOptions.MarginTop);
FPDFPageMarginBottom := Units2Dot(Dialog.PDFOptions.PageOptions.Units,
Dialog.PDFOptions.PageOptions.MarginBottom);
edPDFPageWidth.Text := FormatFloat(GetPDFPageSizeFormat, PDFPageWidth);
edPDFPageHeight.Text := FormatFloat(GetPDFPageSizeFormat, PDFPageHeight);
edPDFPageMarginLeft.Text := FormatFloat(GetPDFPageSizeFormat, PDFPageMarginLeft);
edPDFPageMarginRight.Text := FormatFloat(GetPDFPageSizeFormat, PDFPageMarginRight);
edPDFPageMarginTop.Text := FormatFloat(GetPDFPageSizeFormat, PDFPageMarginTop);
edPDFPageMarginBottom.Text := FormatFloat(GetPDFPageSizeFormat, PDFPageMarginBottom);
FPDFFontItem := nil;
PDFExp.Options.HeaderFont.Assign(Dialog.PDFOptions.HeaderFont);
PDFExp.Options.CaptionFont.Assign(Dialog.PDFOptions.CaptionFont);
PDFExp.Options.DataFont.Assign(Dialog.PDFOptions.DataFont);
PDFExp.Options.FooterFont.Assign(Dialog.PDFOptions.FooterFont);
PDFFillFontList;
if AutoLoadOptions and (OptionsFileName <> EmptyStr)
then LoadExportOptions(OptionsFileName);
end;
procedure TADO_QExportDialogF.ShowTitle;
begin
Caption := QED_Title;
if FileName <> EmptyStr
then Caption := Format(QED_AdvancedTitle, [ExtractFileName(FileName)]);
end;
procedure TADO_QExportDialogF.ChangeFileExtension;
begin
if not AutoChangeFileExt then Exit;
if ExportType = aeClipboard then Exit;
if FileName <> EmptyStr then
FileName := ChangeFileExt(FileName, '.' +
ExportTypeExtension[Integer(ExportType)]);
end;
procedure TADO_QExportDialogF.FillAllowedExports;
var
i: integer;
begin
rgExportType.Items.BeginUpdate;
try
rgExportType.Items.Clear;
for i := Integer(Low(TAllowedExport)) to Integer(High(TAllowedExport)) do
if TAllowedExport(i) in Dialog.AllowedExports then
rgExportType.Items.AddObject(ExportTypeString[i], TObject(i));
rgExportType.ItemIndex := 0;
finally
rgExportType.Items.EndUpdate;
end;
end;
procedure TADO_QExportDialogF.ResetStandardFormats;
begin
IntegerFmt := Dialog.Formats.IntegerFormat;
FloatFmt := Dialog.Formats.FloatFormat;
DateFmt := Dialog.Formats.DateFormat;
TimeFmt := Dialog.Formats.TimeFormat;
DateTimeFmt := Dialog.Formats.DateTimeFormat;
CurrencyFmt := Dialog.Formats.CurrencyFormat;
BooleanTrue := Dialog.Formats.BooleanTrue;
BooleanFalse := Dialog.Formats.BooleanFalse;
NullString := Dialog.Formats.NullString;
end;
procedure TADO_QExportDialogF.FillFields;
var
i, j: Integer;
begin
lstAvailableFields.Items.BeginUpdate;
lstXLSFields.Items.BeginUpdate;
lstXLSOptions.Items.BeginUpdate;
try
lstAvailableFields.Items.Clear;
lstXLSFields.Items.Clear;
for i := 0 to 3 do
with lstXLSOptions.Items.Add do begin
Data := TxlsFieldFormat.Create(nil);
case i of
0: begin
Caption := QED_XLS_HEADER;
TxlsFormat(Data).Assign(Dialog.XLSOptions.HeaderFormat);
end;
1: begin
Caption := QED_XLS_CAPTION;
TxlsFormat(Data).Assign(Dialog.XLSOptions.CaptionFormat);
end;
2: begin
Caption := QED_XLS_AGGREGATE;
TxlsFormat(Data).Assign(Dialog.XLSOptions.AggregateFormat);
end;
3: begin
Caption := QED_XLS_FOOTER;
TxlsFormat(Data).Assign(Dialog.XLSOptions.FooterFormat);
end;
end;
ImageIndex := 3;
end;
for i := 0 to Dialog.Columns.Count - 1 do begin
with lstAvailableFields.Items.Add do begin
Caption := Dialog.Columns[i].Name;
Data := Pointer(i);
ImageIndex := 0;
end;
with lstXLSFields.Items.Add do begin
Caption := Dialog.Columns[i].Name;
Data := TxlsFieldFormat.Create(nil);
TxlsFieldFormat(Data).FieldName := Dialog.Columns[i].Name;
j := Dialog.XLSOptions.FieldFormats.IndexByName(Dialog.Columns[i].Name);
if j > -1
then TxlsFieldFormat(Data).Assign(Dialog.XLSOptions.FieldFormats[j])
else TxlsFieldFormat(Data).Assign(Dialog.XLSOptions.DataFormat);
//!!!
if not Dialog.Columns[i].IsBlob
then ImageIndex := 1
else ImageIndex := 0;
end;
if Dialog.Columns[i].ColType in [ectInteger, ectBigint, ectFloat, ectCurrency,
ectDate, ectTime, ectDateTime]
then cbxFormatFields.Items.AddObject(Dialog.Columns[i].Name,
Pointer(Integer(Dialog.Columns[i].ColType)));
if Dialog.Columns[i].AllowFormat and
not Dialog.Columns[i].IsDefaultFormat then
with lstUserFormats.Items.Add do begin
Caption := Dialog.Columns[i].Name;
SubItems.Add('=');
SubItems.Add(Dialog.Columns[i].Format);
ImageIndex := 2;
end;
sgrCaptions.Cells[0, i + 1] := Dialog.Columns[i].Name;
sgrCaptions.Cells[1, i + 1] := Dialog.Columns[i].Caption;
sgrCaptions.RowCount := sgrCaptions.RowCount + 1;
end;
for i := 0 to Dialog.XLSOptions.StripStyles.Count - 1 do
with lstXLSStyles.Items.Add do begin
Caption := QED_XLS_StyleItem + IntToStr(lstXLSStyles.Items.Count);
Data := TxlsFormat.Create(nil);
TxlsFormat(Data).Assign(Dialog.XLSOptions.StripStyles[i]);
ImageIndex := 2;
end;
if sgrCaptions.RowCount > 1 then
sgrCaptions.RowCount := sgrCaptions.RowCount - 1;
if lstAvailableFields.Items.Count > 0 then
lstAvailableFields.Items[0].Selected := true;
if lstXLSFields.Items.Count > 0 then begin
lstXLSFields.Items[0].Focused := true;
lstXLSFields.Items[0].Selected := true;
end;
if lstXLSOptions.Items.Count > 0 then begin
lstXLSOptions.Items[0].Focused := true;
lstXLSOptions.Items[0].Selected := true;
end;
finally
lstXLSOptions.Items.EndUpdate;
lstXLSFields.Items.EndUpdate;
lstAvailableFields.Items.EndUpdate;
end;
end;
procedure TADO_QExportDialogF.edFileNameChange(Sender: TObject);
begin
FileName := edFileName.Text;
ShowButtons;
end;
procedure TADO_QExportDialogF.bBrowseClick(Sender: TObject);
begin
sdExportFile.FileName := FileName;
if sdExportFile.Execute then FileName := sdExportFile.FileName;
end;
procedure TADO_QExportDialogF.FormCreate(Sender: TObject);
begin
InitializeDialog;
end;
procedure TADO_QExportDialogF.FormShow(Sender: TObject);
begin
ShowTitle;
end;
procedure TADO_QExportDialogF.rgExportTypeClick(Sender: TObject);
begin
if ExportType <> aeClipboard then begin
sdExportFile.Filter := ExportTypeFilter[Integer(ExportType)];
sdExportFile.DefaultExt := ExportTypeExtension[Integer(ExportType)];
end;
ChangeFileExtension;
if not IsCompatiblePage then Pages.ActivePage := tshExportType;
bBrowse.Enabled := ExportType <> aeClipboard;
laFileName.Enabled := ExportType <> aeClipboard;
edFileName.Enabled := ExportType <> aeClipboard;
chShowFile.Enabled := ExportType <> aeClipboard;
tshHTML.TabVisible := ExportType = aeHTML;
tshXLS.TabVisible := ExportType = aeXLS;
tshSQL.TabVisible := ExportType = aeSQL;
tshRTF.TabVisible := ExportType in [aeWord, aeRTF];
tshXML.TabVisible := ExportType = aeXML;
tshASCII.TabVisible := ExportType in [aeTXT, aeCSV];
tshAccess.TabVisible := ExportType = aeAccess;
tshPDF.TabVisible := ExportType = aePDF;
tshFormats.TabVisible := (not (ExportType in [aeDBF, aeSQL, aeAccess])) and
(coFormats in CommonOptions);
tshFields.TabVisible := (coFields in CommonOptions);
tshCaptions.TabVisible := (not (ExportType in [aeXML, aeDBF, aeSQL])) and
(coCaptions in CommonOptions);
tshHeaderFooter.TabVisible := (not (ExportType in [aeXML, aeDBF, aeAccess])) and
(coColons in CommonOptions);
ShowButtons;
MakeStringGrid;
end;
procedure TADO_QExportDialogF.chShowFileClick(Sender: TObject);
begin
ShowFile := chShowFile.Checked;
end;
procedure TADO_QExportDialogF.chPrintFileClick(Sender: TObject);
begin
PrintFile := chPrintFile.Checked;
end;
procedure TADO_QExportDialogF.chGoToFirstRecordClick(Sender: TObject);
begin
GoToFirstRecord := chGoToFirstRecord.Checked;
end;
procedure TADO_QExportDialogF.chCurrentRecordOnlyClick(Sender: TObject);
begin
CurrentRecordOnly := chCurrentRecordOnly.Checked;
end;
procedure TADO_QExportDialogF.chExportEmptyClick(Sender: TObject);
begin
ExportEmpty := chExportEmpty.Checked;
end;
procedure TADO_QExportDialogF.edExportRecCountChange(Sender: TObject);
begin
try ExportRecCount := StrToInt(edExportRecCount.Text) except end;
end;
procedure TADO_QExportDialogF.edSkipRecCountChange(Sender: TObject);
begin
try SkipRecCount := StrToInt(edSkipRecCount.Text) except end;
end;
procedure TADO_QExportDialogF.ShowButtons;
begin
bStart.Enabled := (FileName <> EmptyStr) or (ExportType = aeClipboard);
end;
procedure TADO_QExportDialogF.MakeStringGrid;
var
i, j: integer;
begin
case ExportType of
aeTXT, aeRTF, aeWord, aePDF: begin
sgrCaptions.ColCount := 4;
sgrCaptions.ColWidths[0] := 150;
sgrCaptions.ColWidths[1] := 150;
sgrCaptions.ColWidths[2] := 78;
sgrCaptions.ColWidths[3] := 60;
tshCaptions.Caption := QED_Captions_Caption + ' && ' + QED_Captions_Width +
' && ' + QED_Captions_Align;
end;
aeHTML, aeXLS: begin
sgrCaptions.ColCount := 3;
sgrCaptions.ColWidths[0] := 181;
sgrCaptions.ColWidths[1] := 181;
sgrCaptions.ColWidths[2] := 78;
if ExportType = aeHTML
then tshCaptions.Caption := QED_Captions_Caption + ' && ' + QED_Captions_Align
else tshCaptions.Caption := QED_Captions_Caption + ' && ' + QED_Captions_Width;
end;
else begin
sgrCaptions.ColCount := 2;
sgrCaptions.ColWidths[0] := 220;
sgrCaptions.ColWidths[1] := 220;
tshCaptions.Caption := QED_Captions_Caption;
end;
end;
for i := 0 to Dialog.Columns.Count - 1 do
for j := 1 to sgrCaptions.RowCount - 1 do
if AnsiCompareText(Dialog.Columns[i].Name, sgrCaptions.Cells[0, j]) = 0 then begin
if ExportType in [aeTXT, aeRTF, aeWord, aeHTML, aePDF] then
case Dialog.Columns[i].ColAlign of
ecaLeft: sgrCaptions.Cells[2, j] := QED_Align_Left;
ecaCenter: sgrCaptions.Cells[2, j] := QED_Align_Center;
ecaRight: sgrCaptions.Cells[2, j] := QED_Align_Right;
end;
if ExportType in [aeTXT, aeRTF, aeWord, aeXLS, aePDF] then
sgrCaptions.Cells[2 + Integer(ExportType <> aeXLS), j] :=
IntToStr(Dialog.Columns[i].Width);
end;
end;
procedure TADO_QExportDialogF.LoadStringGridCaption;
var
i, N: integer;
begin
if not Assigned(Dialog.StringGrid) then Exit;
if CaptionRow > Dialog.StringGrid.RowCount then Exit;
for i := 0 to sgrCaptions.RowCount - 1 do begin
N := StrToIntDef(sgrCaptions.Cells[0, i], -1);
if N > -1 then
sgrCaptions.Cells[1, i] := Dialog.StringGrid.Cells[N, CaptionRow];
end;
end;
procedure TADO_QExportDialogF.bAddOneExportedFieldClick(Sender: TObject);
begin
if not Assigned(lstAvailableFields.Selected) then Exit;
with MoveListItem(lstAvailableFields.Selected, lstExportedFields, true, -1) do
ImageIndex := 1;
CorrectXLSFieldsList;
end;
procedure TADO_QExportDialogF.bAddAllExportedFieldClick(Sender: TObject);
var
i: integer;
begin
for i := lstAvailableFields.Items.Count - 1 downto 0 do
with MoveListItem(lstAvailableFields.Items[i], lstExportedFields, true, 0) do
ImageIndex := 1;
CorrectXLSFieldsList;
end;
procedure TADO_QExportDialogF.bDelOneExportedFieldClick(Sender: TObject);
begin
if not Assigned(lstExportedFields.Selected) then Exit;
with MoveListItem(lstExportedFields.Selected, lstAvailableFields, true,
GetIndexOfNewAvailableFields(lstExportedFields.Selected)) do
ImageIndex := 0;
CorrectXLSFieldsList;
end;
procedure TADO_QExportDialogF.bDelAllExportedFieldClick(Sender: TObject);
var
i: integer;
begin
for i := lstExportedFields.Items.Count - 1 downto 0 do
with MoveListItem(lstExportedFields.Items[i], lstAvailableFields, true,
GetIndexOfNewAvailableFields(lstExportedFields.Items[i])) do
ImageIndex := 0;
CorrectXLSFieldsList;
end;
procedure TADO_QExportDialogF.cbxFormatFieldsChange(Sender: TObject);
var
str: string;
begin
cbxUserFormats.Items.BeginUpdate;
try
cbxUserFormats.Clear;
if cbxFormatFields.ItemIndex <> -1 then begin
case TQExportColType(Integer(cbxFormatFields.Items.Objects[cbxFormatFields.ItemIndex])) of
ectDateTime: begin
cbxUserFormats.Items.Add(ShortDateFormat);
cbxUserFormats.Items.Add(LongDateFormat);
cbxUserFormats.Items.Add(ShortDateFormat + ' ' + ShortTimeFormat);
cbxUserFormats.Items.Add(ShortDateFormat + ' ' + LongTimeFormat);
cbxUserFormats.Items.Add(LongDateFormat + ' ' + ShortTimeFormat);
cbxUserFormats.Items.Add(LongDateFormat + ' ' + LongTimeFormat);
cbxUserFormats.Items.Add(ShortTimeFormat);
cbxUserFormats.Items.Add(LongTimeFormat);
end;
ectDate: begin
cbxUserFormats.Items.Add(ShortDateFormat);
cbxUserFormats.Items.Add(LongDateFormat);
end;
ectTime: begin
cbxUserFormats.Items.Add(ShortTimeFormat);
cbxUserFormats.Items.Add(LongTimeFormat);
end;
ectInteger,
ectBigint: begin
cbxUserFormats.Items.Add('#,###,##0');
cbxUserFormats.Items.Add('0');
end;
ectFloat: begin
cbxUserFormats.Items.Add('#,###,##0.00');
cbxUserFormats.Items.Add('#,###,##0.000');
cbxUserFormats.Items.Add('#,###,##0.0000');
cbxUserFormats.Items.Add('0.00');
end;
ectCurrency: begin
str := '00.00';
case SysUtils.CurrencyFormat of
0: str := SysUtils.CurrencyString + str;
1: str := str + SysUtils.CurrencyString;
2: str := SysUtils.CurrencyString + ' ' + str;
3: str := str + ' ' + SysUtils.CurrencyString;
end;
cbxUserFormats.Items.Add(str);
end;
end;
end;
cbxUserFormats.ItemIndex := 0;
finally
cbxUserFormats.Items.EndUpdate();
end;
end;
procedure TADO_QExportDialogF.bAddUserFormatClick(Sender: TObject);
var
i: integer;
begin
if cbxUserFormats.Text = EmptyStr then Exit;
for i := lstUserFormats.Items.Count - 1 downto 0 do
if CompareText(cbxFormatFields.Text, lstUserFormats.Items[i].Caption) = 0 then
lstUserFormats.Items.Delete(i);
with lstUserFormats.Items.Add do begin
Caption := cbxFormatFields.Text;
SubItems.Add('=');
SubItems.Add(cbxUserFormats.Text);
Selected := true;
ImageIndex := 2;
end;
ShowFormatButtons;
end;
procedure TADO_QExportDialogF.ShowFormatButtons;
begin
bEditUserFormat.Enabled := lstUserFormats.Items.Count > 0;
bDeleteUserFormat.Enabled := lstUserFormats.Items.Count > 0;
bClearUserFormats.Enabled := lstUserFormats.Items.Count > 0;
end;
procedure TADO_QExportDialogF.PagesChange(Sender: TObject);
var
LI: TListItem;
begin
if Pages.ActivePage = tshFormats then ShowFormatButtons;
if (Pages.ActivePage = tshXLS) and
(CurrXLSListView.Items.Count > 0) then begin
if not Assigned(CurrXLSListView.Selected)
then LI := CurrXLSListView.Items[0]
else LI := CurrXLSListView.Selected;
if CurrXLSListView.CanFocus then
CurrXLSListView.SetFocus;
LI.Focused := true;
LI.Selected := true;
CurrXLSListView.OnChange(CurrXLSListView, LI, ctState);
end;
end;
procedure TADO_QExportDialogF.bEditUserFormatClick(Sender: TObject);
var
OldFormat, NewFormat: string;
begin
if not Assigned(lstUserFormats.Selected) then Exit;
OldFormat := lstUserFormats.Selected.SubItems[1];
NewFormat := InputBox(QEM_NewFormatValue, QEM_EnterValue, OldFormat);
if NewFormat <> OldFormat
then lstUserFormats.Selected.SubItems[1] := NewFormat;
end;
procedure TADO_QExportDialogF.bDeleteUserFormatClick(Sender: TObject);
begin
if not Assigned(lstUserFormats.Selected) then Exit;
lstUserFormats.Selected.Delete;
if lstUserFormats.Items.Count > 0 then
lstUserFormats.Items[0].Selected := true;
ShowFormatButtons;
end;
procedure TADO_QExportDialogF.bClearUserFormatsClick(Sender: TObject);
begin
while Assigned(lstUserFormats.Selected) do
bDeleteUserFormat.Click;
ShowFormatButtons;
end;
procedure TADO_QExportDialogF.HTMLFillColors;
begin
HTMLBackgroundColor := HTMLExp.HTMLOptions.BackgroundColor;
HTMLFontColor := HTMLExp.HTMLOptions.TextFont.Color;
HTMLHeadBackgroundColor := HTMLExp.TableOptions.HeadersRowBgColor;
HTMLHeadFontColor := HTMLExp.TableOptions.HeadersRowFontColor;
HTMLOddRowBackgroundColor := HTMLExp.TableOptions.OddRowBgColor;
HTMLEvenRowBackgroundColor := HTMLExp.TableOptions.TableBgColor;
HTMLDataFontColor := HTMLExp.TableOptions.TableFontColor;
HTMLLinkColor := HTMLExp.HTMLOptions.LinkColor;
HTMLVLinkColor := HTMLExp.HTMLOptions.VLinkColor;
HTMLALinkColor := HTMLExp.HTMLOptions.ALinkColor;
end;
procedure TADO_QExportDialogF.HTMLUpdateMultifileControls;
begin
laHTMLFileRecCount_01.Enabled := HTMLUseMultiFileExport;
edHTMLFileRecCount.Enabled := HTMLUseMultiFileExport;
laHTMLFileRecCount_02.Enabled := HTMLUseMultiFileExport;
chHTMLGenerateIndex.Enabled := HTMLUseMultiFileExport;
laHTMLIndexLinkTemplate.Enabled := HTMLUseMultiFileExport and
HTMLGenerateIndex;
edHTMLIndexLinkTemplate.Enabled := HTMLUseMultiFileExport and
HTMLGenerateIndex;
chHTMLNavigationOnTop.Enabled := HTMLUseMultiFileExport;
chHTMLNavigationOnBottom.Enabled := HTMLUseMultiFileExport;
laHTMLIndexLinkTitle.Enabled := HTMLUseMultiFileExport and
(HTMLNavigationOnTop or HTMLNavigationOnBottom) and
HTMLGenerateIndex;
edHTMLIndexLinkTitle.Enabled := HTMLUseMultiFileExport and
(HTMLNavigationOnTop or HTMLNavigationOnBottom) and
HTMLGenerateIndex;
laHTMLFirstLinkTitle.Enabled := HTMLUseMultiFileExport and
(HTMLNavigationOnTop or HTMLNavigationOnBottom);
edHTMLFirstLinkTitle.Enabled := HTMLUseMultiFileExport and
(HTMLNavigationOnTop or HTMLNavigationOnBottom);
laHTMLPriorLinkTitle.Enabled := HTMLUseMultiFileExport and
(HTMLNavigationOnTop or HTMLNavigationOnBottom);
edHTMLPriorLinkTitle.Enabled := HTMLUseMultiFileExport and
(HTMLNavigationOnTop or HTMLNavigationOnBottom);
laHTMLNextLinkTitle.Enabled := HTMLUseMultiFileExport and
(HTMLNavigationOnTop or HTMLNavigationOnBottom);
edHTMLNextLinkTitle.Enabled := HTMLUseMultiFileExport and
(HTMLNavigationOnTop or HTMLNavigationOnBottom);
laHTMLLastLinkTitle.Enabled := HTMLUseMultiFileExport and
(HTMLNavigationOnTop or HTMLNavigationOnBottom);
edHTMLLastLinkTitle.Enabled := HTMLUseMultiFileExport and
(HTMLNavigationOnTop or HTMLNavigationOnBottom);
end;
procedure TADO_QExportDialogF.chAllowCaptionsClick(Sender: TObject);
begin
AllowCaptions := chAllowCaptions.Checked;
sgrCaptions.Enabled := AllowCaptions;
end;
procedure TADO_QExportDialogF.edCaptionRowExit(Sender: TObject);
begin
CaptionRow := StrToIntDef(edCaptionRow.Text, CaptionRow);
LoadStringGridCaption;
end;
procedure TADO_QExportDialogF.edCaptionRowKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if Key = VK_RETURN then begin
CaptionRow := StrToIntDef(edCaptionRow.Text, CaptionRow);
LoadStringGridCaption;
end;
end;
procedure TADO_QExportDialogF.sgrCaptionsDrawCell(Sender: TObject; ACol,
ARow: Integer; Rect: TRect; State: TGridDrawState);
var
w, h, x, y: integer;
s: string;
begin
if ARow = 0 then
with sgrCaptions.Canvas do begin
Font.Style := Font.Style + [fsBold];
case ACol of
0: s := QED_Captions_FeldName;
1: s := QED_Captions_Caption;
2: if ExportType = aeXLS
then s := QED_Captions_Width
else s := QED_Captions_Align;
3: s := QED_Captions_Width;
end;
w := TextWidth(s);
h := TextHeight(s);
x := Rect.Left + (Rect.Right - Rect.Left - w) div 2;
y := Rect.Top + (Rect.Bottom - Rect.Top - h) div 2;
TextOut(x, y, s);
end;
end;
procedure TADO_QExportDialogF.pbRTFDefaultFontPaint(Sender: TObject);
begin
PaintSampleFont(RTFExp.Options.DefaultFont, pbRTFDefaultFont, false);
end;
procedure TADO_QExportDialogF.bRTFDefaultFontClick(Sender: TObject);
begin
SelectFontForPaintBox(FontDialog, RTFExp.Options.DefaultFont,
pbRTFDefaultFont);
end;
procedure TADO_QExportDialogF.pbRTFHeaderFontPaint(Sender: TObject);
begin
PaintSampleFont(RTFExp.Options.HeaderFont, pbRTFHeaderFont, false);
end;
procedure TADO_QExportDialogF.bRTFHeaderFontClick(Sender: TObject);
begin
SelectFontForPaintBox(FontDialog, RTFExp.Options.HeaderFont, pbRTFHeaderFont);
end;
procedure TADO_QExportDialogF.SetCustomTemplate;
begin
cbxHTMLTemplate.ItemIndex := 0;
end;
procedure TADO_QExportDialogF.bHTMLSaveTemplateClick(Sender: TObject);
begin
if sdHTMLTemplate.Execute then
HTMLExp.SaveTemplateToFile(sdHTMLTemplate.FileName);
end;
procedure TADO_QExportDialogF.bHTMLLoadTemplateClick(Sender: TObject);
begin
if odHTMLTemplate.Execute then begin
HTMLExp.LoadTemplateFromFile(odHTMLTemplate.FileName);
HTMLFillColors;
SetCustomTemplate;
end;
end;
procedure TADO_QExportDialogF.cbxHTMLTemplateChange(Sender: TObject);
begin
case cbxHTMLTemplate.ItemIndex of
0: HTMLExp.HTMLTemplate := htCustom;
else begin
HTMLExp.HTMLTemplate := THTMLTemplate(cbxHTMLTemplate.ItemIndex);
HTMLFillColors;
end;
end;
end;
procedure TADO_QExportDialogF.cbxXLSFontChange(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
TxlsFormat(FXLSListItem.Data).Font.Name := cbxXLSFont.Text;
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemFont, false);
pbXLSCell.Repaint;
end;
procedure TADO_QExportDialogF.cbxXLSFontSizeChange(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
TxlsFormat(FXLSListItem.Data).Font.Size := StrToIntDef(cbxXLSFontSize.Text, 10);
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemFontSize, false);
pbXLSCell.Repaint;
end;
procedure TADO_QExportDialogF.pbFontColorPaint(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
if CurrXLSListView.SelCount = 1
then PaintXLSColors(pbFontColor, TxlsFormat(CurrXLSListView.Selected.Data).Font.Color)
else PaintXLSColors(pbFontColor, TxlsFormat(FXLSListItem.Data).Font.Color);
end;
procedure TADO_QExportDialogF.pbBorderTopPaint(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
if CurrXLSListView.SelCount = 1
then PaintXLSColors(pbBorderTop,
TxlsFormat(CurrXLSListView.Selected.Data).Borders.Top.Color)
else PaintXLSColors(pbBorderTop,
TxlsFormat(FXLSListItem.Data).Borders.Top.Color);
end;
procedure TADO_QExportDialogF.pbBorderBottomPaint(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
if CurrXLSListView.SelCount = 1
then PaintXLSColors(pbBorderBottom,
TxlsFormat(CurrXLSListView.Selected.Data).Borders.Bottom.Color)
else PaintXLSColors(pbBorderBottom,
TxlsFormat(FXLSListItem.Data).Borders.Bottom.Color);
end;
procedure TADO_QExportDialogF.pbBorderLeftPaint(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
if CurrXLSListView.SelCount = 1
then PaintXLSColors(pbBorderLeft,
TxlsFormat(CurrXLSListView.Selected.Data).Borders.Left.Color)
else PaintXLSColors(pbBorderLeft,
TxlsFormat(FXLSListItem.Data).Borders.Left.Color);
end;
procedure TADO_QExportDialogF.pbBorderRightPaint(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
if CurrXLSListView.SelCount = 1
then PaintXLSColors(pbBorderRight,
TxlsFormat(CurrXLSListView.Selected.Data).Borders.Right.Color)
else PaintXLSColors(pbBorderRight,
TxlsFormat(FXLSListItem.Data).Borders.Right.Color);
end;
procedure TADO_QExportDialogF.pbFillBackgroundPaint(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
if CurrXLSListView.SelCount = 1
then PaintXLSColors(pbFillBackground,
TxlsFormat(CurrXLSListView.Selected.Data).Fill.Background)
else PaintXLSColors(pbFillBackground,
TxlsFormat(FXLSListItem.Data).Fill.Background);
end;
procedure TADO_QExportDialogF.pbFillForegroundPaint(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
if CurrXLSListView.SelCount = 1
then PaintXLSColors(pbFillForeground,
TxlsFormat(CurrXLSListView.Selected.Data).Fill.Foreground)
else PaintXLSColors(pbFillForeground,
TxlsFormat(FXLSListItem.Data).Fill.Foreground);
end;
procedure TADO_QExportDialogF.btnFontColorClick(Sender: TObject);
var
OClr, NClr: TxlsColor;
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
OClr := TxlsFormat(FXLSListItem.Data).Font.Color;
NClr := RunXLSColorEditor(OClr);
if NClr <> OClr then begin
TxlsFormat(FXLSListItem.Data).Font.Color := NClr;
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemFontColor, false);
pbXLSCell.Repaint;
end;
end;
procedure TADO_QExportDialogF.btnFontBoldClick(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
XLSItemEditFontStyle(FXLSListItem, xfsBold, btnFontBold.Down);
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemFontBold, false);
pbXLSCell.Repaint;
end;
procedure TADO_QExportDialogF.btnFontItalicClick(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
XLSItemEditFontStyle(FXLSListItem, xfsItalic, btnFontItalic.Down);
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemFontItalic, false);
pbXLSCell.Repaint;
end;
procedure TADO_QExportDialogF.btnFontStrikeOutClick(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
XLSItemEditFontStyle(FXLSListItem, xfsStrikeOut, btnFontStrikeOut.Down);
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemFontStrikeOut, false);
pbXLSCell.Repaint;
end;
procedure TADO_QExportDialogF.btnUnderlineSingleClick(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
if btnUnderlineSingle.Down
then XLSItemSetUnderline(FXLSListItem, fulSingle)
else XLSItemSetUnderline(FXLSListItem, fulNone);
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemFontUnderline, false);
pbXLSCell.Repaint;
end;
procedure TADO_QExportDialogF.btnUnderlineSingleAccountingClick(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
if btnUnderlineSingleAccounting.Down
then XLSItemSetUnderline(FXLSListItem, fulSingleAccounting)
else XLSItemSetUnderline(FXLSListItem, fulNone);
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemFontUnderline, false);
pbXLSCell.Repaint;
end;
procedure TADO_QExportDialogF.btnUnderlineDoubleClick(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
if btnUnderlineDouble.Down
then XLSItemSetUnderline(FXLSListItem, fulDouble)
else XLSItemSetUnderline(FXLSListItem, fulNone);
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemFontUnderline, false);
pbXLSCell.Repaint;
end;
procedure TADO_QExportDialogF.btnUnderlineDoubleAccountingClick(
Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
if btnUnderlineDoubleAccounting.Down
then XLSItemSetUnderline(FXLSListItem, fulDoubleAccounting)
else XLSItemSetUnderline(FXLSListItem, fulNone);
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemFontUnderline, false);
pbXLSCell.Repaint;
end;
procedure TADO_QExportDialogF.btnHorizontalLeftClick(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
if btnHorizontalLeft.Down
then XLSItemSetHorAlignment(FXLSListItem, halLeft)
else XLSItemSetHorAlignment(FXLSListItem, halGeneral);
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemHorAlignment, false);
pbXLSCell.Repaint;
end;
procedure TADO_QExportDialogF.btnHorizontalCenterClick(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
if btnHorizontalCenter.Down
then XLSItemSetHorAlignment(FXLSListItem, halCenter)
else XLSItemSetHorAlignment(FXLSListItem, halGeneral);
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemHorAlignment, false);
pbXLSCell.Repaint;
end;
procedure TADO_QExportDialogF.btnHorizontalRightClick(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
if btnHorizontalRight.Down
then XLSItemSetHorAlignment(FXLSListItem, halRight)
else XLSItemSetHorAlignment(FXLSListItem, halGeneral);
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemHorAlignment, false);
pbXLSCell.Repaint;
end;
procedure TADO_QExportDialogF.btnHorizontalFillClick(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
if btnHorizontalFill.Down
then XLSItemSetHorAlignment(FXLSListItem, halFill)
else XLSItemSetHorAlignment(FXLSListItem, halGeneral);
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemHorAlignment, false);
pbXLSCell.Repaint;
end;
procedure TADO_QExportDialogF.btnVerticalTopClick(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
if btnVerticalTop.Down then XLSItemSetVertAlignment(FXLSListItem, valTop);
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemVertAlignment, false);
pbXLSCell.Repaint;
end;
procedure TADO_QExportDialogF.btnVerticalCenterClick(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
if btnVerticalCenter.Down then XLSItemSetVertAlignment(FXLSListItem, valCenter);
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemVertAlignment, false);
pbXLSCell.Repaint;
end;
procedure TADO_QExportDialogF.btnVerticalBottomClick(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
if btnVerticalBottom.Down then XLSItemSetVertAlignment(FXLSListItem, valBottom);
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemVertAlignment, false);
pbXLSCell.Repaint;
end;
procedure TADO_QExportDialogF.btnBorderTopColorClick(Sender: TObject);
var
OClr, NClr: TxlsColor;
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
OClr := TxlsFormat(FXLSListItem.Data).Borders.Top.Color;
NClr := RunXLSColorEditor(OClr);
TxlsFormat(FXLSListItem.Data).Borders.Top.Color := NClr;
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemBorderTopColor, false);
pbXLSCell.Repaint;
cmbBorderTop.Repaint;
end;
procedure TADO_QExportDialogF.btnBorderBottomColorClick(Sender: TObject);
var
OClr, NClr: TxlsColor;
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
OClr := TxlsFormat(FXLSListItem.Data).Borders.Bottom.Color;
NClr := RunXLSColorEditor(OClr);
TxlsFormat(FXLSListItem.Data).Borders.Bottom.Color := NClr;
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemBorderBottomColor, false);
pbXLSCell.Repaint;
cmbBorderBottom.Repaint;
end;
procedure TADO_QExportDialogF.btnBorderLeftColorClick(Sender: TObject);
var
OClr, NClr: TxlsColor;
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
OClr := TxlsFormat(FXLSListItem.Data).Borders.Left.Color;
NClr := RunXLSColorEditor(OClr);
TxlsFormat(FXLSListItem.Data).Borders.Left.Color := NClr;
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemBorderLeftColor, false);
pbXLSCell.Repaint;
cmbBorderLeft.Repaint;
end;
procedure TADO_QExportDialogF.btnBorderRightColorClick(Sender: TObject);
var
OClr, NClr: TxlsColor;
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
OClr := TxlsFormat(FXLSListItem.Data).Borders.Right.Color;
NClr := RunXLSColorEditor(OClr);
TxlsFormat(FXLSListItem.Data).Borders.Right.Color := NClr;
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemBorderRightColor, false);
pbXLSCell.Repaint;
cmbBorderRight.Repaint;
end;
procedure TADO_QExportDialogF.btnFillBackgroundClick(Sender: TObject);
var
OClr, NClr: TxlsColor;
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
OClr := TxlsFormat(FXLSListItem.Data).Fill.Background;
NClr := RunXLSColorEditor(OClr);
TxlsFormat(FXLSListItem.Data).Fill.Background := NClr;
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemFillBackground, false);
pbXLSCell.Repaint;
cmbPattern.Repaint;
with TxlsFormat(FXLSListItem.Data) do
if (Fill.Background <> clrWhite) and (Fill.Pattern = ptNone) then begin
Fill.Pattern := ptSolid;
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemFillPattern, false);
CurrXLSListView.OnChange(CurrXLSListView, CurrXLSListView.Selected, ctState);
end
end;
procedure TADO_QExportDialogF.btnFillForegroundClick(Sender: TObject);
var
OClr, NClr: TxlsColor;
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
OClr := TxlsFormat(FXLSListItem.Data).Fill.Foreground;
NClr := RunXLSColorEditor(OClr);
TxlsFormat(FXLSListItem.Data).Fill.Foreground := NClr;
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemFillForeground, false);
pbXLSCell.Repaint;
cmbPattern.Repaint;
end;
procedure TADO_QExportDialogF.btnBorderTopClick(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
if btnBorderTop.Down and (cmbBorderTop.ItemIndex = 0)
then cmbBorderTop.ItemIndex := 1
else cmbBorderTop.ItemIndex := 0;
cmbBorderTop.OnChange(nil);
pbXLSCell.Repaint;
end;
procedure TADO_QExportDialogF.btnBorderBottomClick(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
if btnBorderBottom.Down and (cmbBorderBottom.ItemIndex = 0)
then cmbBorderBottom.ItemIndex := 1
else cmbBorderBottom.ItemIndex := 0;
cmbBorderBottom.OnChange(nil);
pbXLSCell.Repaint;
end;
procedure TADO_QExportDialogF.btnBorderLeftClick(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
if btnBorderLeft.Down and (cmbBorderLeft.ItemIndex = 0)
then cmbBorderLeft.ItemIndex := 1
else cmbBorderLeft.ItemIndex := 0;
cmbBorderLeft.OnChange(nil);
pbXLSCell.Repaint;
end;
procedure TADO_QExportDialogF.btnBorderRightClick(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
if btnBorderRight.Down and (cmbBorderRight.ItemIndex = 0)
then cmbBorderRight.ItemIndex := 1
else cmbBorderRight.ItemIndex := 0;
cmbBorderRight.OnChange(nil);
pbXLSCell.Repaint;
end;
procedure TADO_QExportDialogF.cmbBorderTopChange(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
btnBorderTop.Down := cmbBorderTop.ItemIndex > 0;
if cmbBorderTop.ItemIndex >= 0 then
TxlsFormat(FXLSListItem.Data).Borders.Top.Style :=
TxlsBorderStyle(cmbBorderTop.ItemIndex);
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemBorderTop, false);
pbXLSCell.Repaint;
end;
procedure TADO_QExportDialogF.cmbBorderBottomChange(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
btnBorderBottom.Down := cmbBorderBottom.ItemIndex > 0;
if cmbBorderBottom.ItemIndex >= 0 then
TxlsFormat(FXLSListItem.Data).Borders.Bottom.Style :=
TxlsBorderStyle(cmbBorderBottom.ItemIndex);
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemBorderBottom, false);
pbXLSCell.Repaint;
end;
procedure TADO_QExportDialogF.cmbBorderLeftChange(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
btnBorderLeft.Down := cmbBorderLeft.ItemIndex > 0;
if cmbBorderLeft.ItemIndex >= 0 then
TxlsFormat(FXLSListItem.Data).Borders.Left.Style :=
TxlsBorderStyle(cmbBorderLeft.ItemIndex);
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemBorderLeft, false);
pbXLSCell.Repaint;
end;
procedure TADO_QExportDialogF.cmbBorderRightChange(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
btnBorderRight.Down := cmbBorderRight.ItemIndex > 0;
if cmbBorderRight.ItemIndex >= 0 then
TxlsFormat(FXLSListItem.Data).Borders.Right.Style :=
TxlsBorderStyle(cmbBorderRight.ItemIndex);
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemBorderRight, false);
pbXLSCell.Repaint;
end;
procedure TADO_QExportDialogF.cmbBorderTopDrawItem(Control: TWinControl;
Index: Integer; Rect: TRect; State: TOwnerDrawState);
var
Invert: boolean;
begin
if CurrXLSListView = nil then Exit;
if not Assigned(CurrXLSListView.Selected) then Exit;
Invert := (odSelected in State) or (odFocused in State);
with (Control as TComboBox).Canvas do begin
FillRect(Rect);
if Invert then Pen.Color := clWhite
else Pen.Color := XLS_STANDART_PALETTE[Integer(TxlsFormat(
CurrXLSListView.Selected.Data).Borders.Top.Color)];
end;
DrawBorderStyle(TxlsBorderStyle(Index), (Control as TComboBox).Canvas, Rect);
end;
procedure TADO_QExportDialogF.cmbBorderBottomDrawItem(Control: TWinControl;
Index: Integer; Rect: TRect; State: TOwnerDrawState);
var
Invert: boolean;
begin
if CurrXLSListView = nil then Exit;
if not Assigned(CurrXLSListView.Selected) then Exit;
Invert := (odSelected in State) or (odFocused in State);
with (Control as TComboBox).Canvas do begin
FillRect(Rect);
if Invert then Pen.Color := clWhite
else Pen.Color := XLS_STANDART_PALETTE[Integer(TxlsFormat(
CurrXLSListView.Selected.Data).Borders.Bottom.Color)];
end;
DrawBorderStyle(TxlsBorderStyle(Index), (Control as TComboBox).Canvas, Rect);
end;
procedure TADO_QExportDialogF.cmbBorderLeftDrawItem(Control: TWinControl;
Index: Integer; Rect: TRect; State: TOwnerDrawState);
var
Invert: boolean;
begin
if CurrXLSListView = nil then Exit;
if not Assigned(CurrXLSListView.Selected) then Exit;
Invert := (odSelected in State) or (odFocused in State);
with (Control as TComboBox).Canvas do begin
FillRect(Rect);
if Invert then Pen.Color := clWhite
else Pen.Color := XLS_STANDART_PALETTE[Integer(TxlsFormat(
CurrXLSListView.Selected.Data).Borders.Left.Color)];
end;
DrawBorderStyle(TxlsBorderStyle(Index), (Control as TComboBox).Canvas, Rect);
end;
procedure TADO_QExportDialogF.cmbBorderRightDrawItem(Control: TWinControl;
Index: Integer; Rect: TRect; State: TOwnerDrawState);
var
Invert: boolean;
begin
if CurrXLSListView = nil then Exit;
if not Assigned(CurrXLSListView.Selected) then Exit;
Invert := (odSelected in State) or (odFocused in State);
with (Control as TComboBox).Canvas do begin
FillRect(Rect);
if Invert then Pen.Color := clWhite
else Pen.Color := XLS_STANDART_PALETTE[Integer(TxlsFormat(
CurrXLSListView.Selected.Data).Borders.Right.Color)];
end;
DrawBorderStyle(TxlsBorderStyle(Index), (Control as TComboBox).Canvas, Rect);
end;
procedure TADO_QExportDialogF.cmbPatternDrawItem(Control: TWinControl;
Index: Integer; Rect: TRect; State: TOwnerDrawState);
var
// Invert: boolean;
x, y: integer;
begin
if CurrXLSListView = nil then Exit;
if not Assigned(CurrXLSListView.Selected) then Exit;
// Invert := (odSelected in State) or (odFocused in State);
with (Control as TComboBox).Canvas do begin
{ if Invert then begin
Brush.Color := XLS_STANDART_PALETTE[39 - Integer(TxlsFormat(CurrXLSListView.Selected.Data).Fill.Background)];
Pen.Color := XLS_STANDART_PALETTE[39 - Integer(TxlsFormat(CurrXLSListView.Selected.Data).Fill.Foreground)];
end
else begin}
Brush.Color := XLS_STANDART_PALETTE[Integer(TxlsFormat(CurrXLSListView.Selected.Data).Fill.Background)];
Pen.Color := XLS_STANDART_PALETTE[Integer(TxlsFormat(CurrXLSListView.Selected.Data).Fill.Foreground)];
{end;}
if Index > 0 then
FillRect(Rect);
if Index = 0 then begin
Brush.Color := clWhite;
FillRect(Rect);
Font.Color := clBlack ;
TextOut((Rect.Right + Rect.Left - TextWidth(QED_XLS_Fill_Pattern_None)) div 2,
(Rect.Bottom + Rect.Top - TextHeight(QED_XLS_Fill_Pattern_None)) div 2,
QED_XLS_Fill_Pattern_None);
end
else begin
x := Rect.Left;
y := Rect.Top;
while y <= Rect.Bottom - 4 do begin
while x <= Rect.Right do begin
DrawPattern((Control as TComboBox).Canvas, Index, x, y);
Inc(x, 4);
end;
Inc(y, 4);
x := Rect.Left;
end
end;
end;
end;
procedure TADO_QExportDialogF.cmbPatternChange(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
if cmbPattern.ItemIndex >= 0 then begin
TxlsFormat(FXLSListItem.Data).Fill.Pattern :=
TxlsPattern(cmbPattern.ItemIndex);
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemFillPattern, false);
if (cmbPattern.ItemIndex = 0) and
(TxlsFormat(FXLSListItem.Data).Fill.Background <> clrWhite) then begin
TxlsFormat(FXLSListItem.Data).Fill.Background := clrWhite;
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemFillBackground, false);
CurrXLSListView.OnChange(CurrXLSListView, CurrXLSListView.Selected, ctState);
end;
end;
pbXLSCell.Repaint;
end;
procedure TADO_QExportDialogF.LoadExportOptions(const FileName: string);
var
i, j: integer;
FIniFile: TIniFile;
AStrings: TStrings;
AComponent: TComponent;
prefix, str: string;
LV: TListView;
xlsFormat: TxlsFieldFormat;
PDFFont: TPDFFont;
begin
FIniFile := TIniFile.Create(FileName);
AStrings := TStringList.Create;
try
with FIniFile do begin
// [GENERAL]
Self.FileName := ReadString(S_GENERAL, S_FileName, Dialog.FileName);
ExportType := TAllowedExport(ReadInteger(S_GENERAL, S_ExportType, 0));
ShowFile := ReadBool(S_GENERAL, S_ShowFile, Dialog.ShowFile);
PrintFile := ReadBool(S_GENERAL, S_PrintFile, Dialog.PrintFile);
GoToFirstRecord := ReadBool(S_GENERAL, S_GoToFirstRecord,
Dialog.GoToFirstRecord);
ExportEmpty := ReadBool(S_GENERAL, S_ExportEmpty,
Dialog.ExportEmpty);
CurrentRecordOnly := ReadBool(S_GENERAL, S_CurrentRecordOnly,
Dialog.CurrentRecordOnly);
ExportEmpty := ReadBool(S_GENERAL, S_ExportEmpty, Dialog.ExportEmpty);
ExportRecCount := ReadInteger(S_GENERAL, S_ExportRecCount,
Dialog.ExportRecCount);
SkipRecCount := ReadInteger(S_GENERAL, S_SkipRecCount,
Dialog.SkipRecCount);
AllowCaptions := ReadBool(S_GENERAL, S_AllowCaptions,
Dialog.AllowCaptions);
CaptionRow := ReadInteger(S_GENERAL, S_CaptionRow, Dialog.CaptionRow);
// [FORMATS]
ResetStandardFormats;
IntegerFmt := ReadString(S_FORMATS, S_Integer, IntegerFmt);
FloatFmt := ReadString(S_FORMATS, S_Float, FloatFmt);
DateFmt := ReadString(S_FORMATS, S_Date, DateFmt);
TimeFmt := ReadString(S_FORMATS, S_Time, TimeFmt);
DateTimeFmt := ReadString(S_FORMATS, S_DateTime, DateTimeFmt);
CurrencyFmt := ReadString(S_FORMATS, S_Currency, CurrencyFmt);
BooleanTrue := ReadString(S_FORMATS, S_BooleanTrue, BooleanTrue);
BooleanFalse := ReadString(S_FORMATS, S_BooleanFalse, BooleanFalse);
NullString := ReadString(S_FORMATS, S_NullString, NullString);
// [USER_FORMATS]
lstUserFormats.Items.Clear;
AStrings.Clear;
ReadSection(S_USER_FORMATS, AStrings);
for i := 0 to AStrings.Count - 1 do
for j := 0 to Dialog.Columns.Count - 1 do
if AnsiCompareText(AStrings[i], Dialog.Columns[j].Name) = 0 then
with lstUserFormats.Items.Add do begin
Caption := AStrings[i];
SubItems.Add('=');
SubItems.Add(ReadString(S_USER_FORMATS, AStrings[i], EmptyStr));
ImageIndex := 2;
end;
// [FIELDS]
bDelAllExportedField.Click;
AStrings.Clear;
ReadSection(S_FIELDS, AStrings);
for i := 0 to AStrings.Count - 1 do
for j := 0 to lstAvailableFields.Items.Count - 1 do
if AnsiCompareText(ReadString(S_FIELDS, AStrings[i], EmptyStr),
lstAvailableFields.Items[j].Caption) = 0 then begin
with MoveListItem(lstAvailableFields.Items[j],
lstExportedFields, true, -1) do
ImageIndex := 1;
CorrectXLSFieldsList;
Break;
end;
// [HEADER]
AStrings.Clear;
ReadSection(S_HEADER, AStrings);
memHeader.Lines.Clear;
for i := 0 to AStrings.Count - 1 do
memHeader.Lines.Add(ReadString(S_HEADER, AStrings[i], EmptyStr));
// [FOOTER]
AStrings.Clear;
ReadSection(S_FOOTER, AStrings);
memFooter.Lines.Clear;
for i := 0 to AStrings.Count - 1 do
memFooter.Lines.Add(ReadString(S_FOOTER, AStrings[i], EmptyStr));
// [CAPTIONS]
AStrings.Clear;
for j := 1 to sgrCaptions.RowCount - 1 do
sgrCaptions.Cells[1, j] := EmptyStr;
ReadSection(S_CAPTIONS, AStrings);
for i := 0 to AStrings.Count - 1 do
for j := 1 to sgrCaptions.RowCount - 1 do
if AnsiCompareText(AStrings[i], sgrCaptions.Cells[0, j]) = 0 then begin
sgrCaptions.Cells[1, j] := ReadString(S_CAPTIONS, AStrings[i],
EmptyStr);
Break;
end;
// [WIDTH]
if ExportType in [aeTXT, aeRTF, aeWord, aeXLS] then begin
AStrings.Clear;
for j := 1 to sgrCaptions.RowCount - 1 do
sgrCaptions.Cells[2 + Integer(ExportType <> aeXLS), j] := '0';
ReadSection(S_WIDTH, AStrings);
for i := 0 to AStrings.Count - 1 do
for j := 1 to sgrCaptions.RowCount - 1 do
if AnsiCompareText(AStrings[i], sgrCaptions.Cells[0, j]) = 0 then begin
sgrCaptions.Cells[2 + Integer(ExportType <> aeXLS), j] :=
ReadString(S_WIDTH, AStrings[i], '0');
Break;
end;
end;
// [ALIGN]
if ExportType in [aeTXT, aeRTF, aeWord, aeHTML] then begin
AStrings.Clear;
for j := 1 to sgrCaptions.RowCount - 1 do
sgrCaptions.Cells[2, j] := 'Left';
ReadSection(S_ALIGN, AStrings);
for i := 0 to AStrings.Count - 1 do
for j := 1 to sgrCaptions.RowCount - 1 do
if AnsiCompareText(AStrings[i], sgrCaptions.Cells[0, j]) = 0 then begin
sgrCaptions.Cells[2, j] := ReadString(S_ALIGN, AStrings[i], 'Left');
Break;
end;
end;
case ExportType of
// [XLS]
aeXLS: begin
XLSPageHeader := ReadString(S_XLS, S_PageHeader,
Dialog.XLSOptions.PageHeader);
XLSPageFooter := ReadString(S_XLS, S_PageFooter,
Dialog.XLSOptions.PageFooter);
XLSSheetTitle := ReadString(S_XLS, S_SheetTitle,
Dialog.XLSOptions.SheetTitle);
XLSStripType := TxlsStripStyle(ReadInteger(S_XLS, S_StripType,
Integer(Dialog.XLSOptions.StripType)));
XLSAutoCalcColWidth := ReadBool(S_XLS, S_AutoCalcColWidth,
Dialog.XLSOptions.AutoCalcColWidth);
XLSResetAllItems_A;
AStrings.Clear;
ReadSections(AStrings);
for i := 0 to AStrings.Count - 1 do begin
if AnsiCompareText(S_XLS_FIELD, Copy(AStrings[i], 1,
Length(S_XLS_FIELD))) = 0 then begin
LV := lstXLSFields;
prefix := S_XLS_FIELD;
end
else if AnsiCompareText(S_XLS_OPTION, Copy(AStrings[i], 1,
Length(S_XLS_OPTION))) = 0 then begin
LV := lstXLSOptions;
prefix := S_XLS_OPTION;
end
else if AnsiCompareText(S_XLS_STYLE, Copy(AStrings[i], 1,
Length(S_XLS_STYLE))) = 0 then begin
LV := lstXLSStyles;
prefix := S_XLS_STYLE;
end
else LV := nil;
if Assigned(LV) then begin
xlsFormat := nil;
if (AnsiCompareText(prefix, S_XLS_FIELD) = 0) or
(AnsiCompareText(prefix, S_XLS_OPTION) = 0) then begin
for j := 0 to LV.Items.Count - 1 do
if AnsiCompareText(LV.Items[j].Caption, Copy(AStrings[i],
Length(prefix) + 1, Length(AStrings[i]))) = 0 then begin
xlsFormat := TxlsFieldFormat(LV.Items[j].Data);
Break;
end;
end
else begin
with LV.Items.Add do begin
Caption := Copy(AStrings[i], Length(prefix) + 1, Length(AStrings[i]));
xlsFormat := TxlsFieldFormat.Create(nil);
Data := xlsFormat;
ImageIndex := 2;
end;
end;
if Assigned(xlsFormat)
then xlsFormat.LoadFromIniFile(FIniFile, AStrings[i]);
end;
end;
if lstXLSStyles.Items.Count > 0 then begin
lstXLSStyles.Items[0].Focused := true;
lstXLSStyles.Items[0].Selected := true;
end;
end;
// [RTF]
aeRTF, aeWord: begin
LoadFontFromIniFile(RTFExp.Options.DefaultFont,
Dialog.RTFOptions.DefaultFont, FIniFile, S_RTF_Default_Font);
LoadFontFromIniFile(RTFExp.Options.HeaderFont,
Dialog.RTFOptions.HeaderFont, FIniFile, S_RTF_Header_Font);
PaintSampleFont(RTFExp.Options.DefaultFont, pbRTFDefaultFont, false);
PaintSampleFont(RTFExp.Options.HeaderFont, pbRTFHeaderFont, false);
RTFPageOrientation := TQExportPageOrientation(ReadInteger(S_RTF,
S_RTF_PageOrientation, Integer(Dialog.RTFOptions.PageOrientation)));
end;
// [HTML]
aeHTML: begin
SetCustomTemplate;
HTMLTitle := ReadString(S_HTML, S_HTML_Title,
Dialog.HTMLPageOptions.Title);
HTMLUsingCSS := TUsingCSS(ReadInteger(S_HTML, S_HTML_CSS,
Integer(Dialog.HTMLPageOptions.UsingCSS)));
HTMLCSSFileName := ReadString(S_HTML, S_HTML_CSSFile,
Dialog.HTMLPageOptions.CSSFileName);
HTMLOverwriteCSSFile := ReadBool(S_HTML, S_HTML_OverwriteCSSFile,
Dialog.HTMLPageOptions.OverwriteCSSFile);
HTMLUseMultiFileExport := ReadInteger(S_HTML,
S_HTML_FileRecCount, Dialog.HTMLMultiFileOptions.FileRecCount) > 0;
HTMLFileRecCount := ReadInteger(S_HTML,
S_HTML_FileRecCount, Dialog.HTMLMultiFileOptions.FileRecCount);
HTMLGenerateIndex := ReadBool(S_HTML, S_HTML_GenerateIndex,
Dialog.HTMLMultiFileOptions.GenerateIndex);
HTMLIndexLinkTemplate := ReadString(S_HTML, S_HTML_IndexLinkTemplate,
Dialog.HTMLMultiFileOptions.IndexLinkTemplate);
HTMLNavigationOnTop := ReadBool(S_HTML, S_HTML_NavigationOnTop,
Dialog.HTMLMultiFileOptions.NavigationOnTop);
HTMLNavigationOnBottom := ReadBool(S_HTML, S_HTML_NavigationOnBottom,
Dialog.HTMLMultiFileOptions.NavigationOnBottom);
HTMLIndexLinkTitle := ReadString(S_HTML, S_HTML_IndexLinkTitle,
Dialog.HTMLMultiFileOptions.IndexLinkTitle);
HTMLFirstLinkTitle := ReadString(S_HTML, S_HTML_FirstLinkTitle,
Dialog.HTMLMultiFileOptions.FirstLinkTitle);
HTMLPriorLinkTitle := ReadString(S_HTML, S_HTML_PriorLinkTitle,
Dialog.HTMLMultiFileOptions.PriorLinkTitle);
HTMLNextLinkTitle := ReadString(S_HTML, S_HTML_NextLinkTitle,
Dialog.HTMLMultiFileOptions.NextLinkTitle);
HTMLLastLinkTitle := ReadString(S_HTML, S_HTML_LastLinkTitle,
Dialog.HTMLMultiFileOptions.LastLinkTitle);
HTMLFontName := ReadString(S_HTML, S_HTML_FontName,
Dialog.HTMLPageOptions.TextFont.Name);
HTMLBackground := ReadString(S_HTML, S_HTML_BackgroundFile,
Dialog.HTMLPageOptions.BackgroundFileName);
HTMLBodyAdvanced := ReadString(S_HTML, S_HTML_BodyAdvanced,
Dialog.HTMLPageOptions.AdvancedAttributes.Text);
HTMLCellPadding := ReadInteger(S_HTML, S_HTML_CellPadding,
Dialog.HTMLTableOptions.CellPadding);
HTMLCellSpacing := ReadInteger(S_HTML, S_HTML_CellSpacing,
Dialog.HTMLTableOptions.CellSpacing);
HTMLBorderWidth := ReadInteger(S_HTML, S_HTML_BorderWidth,
Dialog.HTMLTableOptions.BorderWidth);
HTMLTableBackground := ReadString(S_HTML, S_HTML_TableBackground,
Dialog.HTMLTableOptions.BackgroundFileName);
HTMLTableAdvanced := ReadString(S_HTML, S_HTML_TableAdvanced,
Dialog.HTMLTableOptions.AdvancedAttributes.Text);
HTMLBackgroundColor := StringToColor(ReadString(S_HTML,
S_HTML_BackgroundColor,
ColorToString(Dialog.HTMLPageOptions.BackgroundColor)));
HTMLFontColor := StringToColor(ReadString(S_HTML, S_HTML_FontColor,
ColorToString(Dialog.HTMLPageOptions.TextFont.Color)));
str := ReadString(S_HTML, S_HTML_HeadBackgroundColor,
ColorToString(Dialog.HTMLTableOptions.HeadersRowBgColor));
HTMLHeadBackgroundColor := StringToColor(str);
for i := 1 to 3 do begin
AComponent := FindComponent('paHTMLColumnHead_' + IntToStr(i));
if Assigned(AComponent) and (AComponent is TPanel) then
(AComponent as TPanel).Color := StringToColor(str);
end;
str := ReadString(S_HTML, S_HTML_HeadFontColor,
ColorToString(Dialog.HTMLTableOptions.HeadersRowFontColor));
HTMLHeadFontColor := StringToColor(str);
for i := 1 to 3 do begin
AComponent := FindComponent('laHTMLHead_' + IntToStr(i));
if Assigned(AComponent) and (AComponent is TLabel) then
(AComponent as TLabel).Font.Color := StringToColor(str);
end;
str := ReadString(S_HTML, S_HTML_OddRowBackgroundColor,
ColorToString(Dialog.HTMLTableOptions.OddRowBgColor));
HTMLOddRowBackgroundColor := StringToColor(str);
for i := 1 to 6 do begin
AComponent := FindComponent('paHTMLOddRowCol_' + IntToStr(i));
if Assigned(AComponent) and (AComponent is TPanel) then
(AComponent as TPanel).Color := StringToColor(str);
end;
str := ReadString(S_HTML, S_HTML_EvenRowBackgroundColor,
ColorToString(Dialog.HTMLTableOptions.TableBgColor));
HTMLEvenRowBackgroundColor := StringToColor(str);
for i := 1 to 6 do begin
AComponent := FindComponent('paHTMLEvenRowCol_' + IntToStr(i));
if Assigned(AComponent) and (AComponent is TPanel) then
(AComponent as TPanel).Color := StringToColor(str);
end;
str := ReadString(S_HTML, S_HTML_DataFontColor,
ColorToString(Dialog.HTMLTableOptions.TableFontColor));
HTMLDataFontColor := StringToColor(str);
for i := 1 to 12 do begin
AComponent := FindComponent('laHTMLData_' + IntToStr(i));
if Assigned(AComponent) and (AComponent is TLabel) then
(AComponent as TLabel).Font.Color := StringToColor(str);
end;
laHTMLLink.Font.Color := StringToColor(ReadString(S_HTML,
S_HTML_LinkColor,
ColorToString(Dialog.HTMLPageOptions.LinkColor)));
HTMLLinkColor := laHTMLLink.Font.Color;
laHTMLVLink.Font.Color := StringToColor(ReadString(S_HTML,
S_HTML_VLinkColor,
ColorToString(Dialog.HTMLPageOptions.VLinkColor)));
HTMLVLinkColor := laHTMLVLink.Font.Color;
laHTMLALink.Font.Color := StringToColor(ReadString(S_HTML,
S_HTML_ALinkColor,
ColorToString(Dialog.HTMLPageOptions.ALinkColor)));
HTMLALinkColor := laHTMLALink.Font.Color;
end;
// [PDF]
aePDF: begin
PDFColSpacing := StrToDblDef(ReadString(S_PDF, S_PDF_ColSpacing,
FormatFloat('0.0', Dialog.PDFOptions.ColSpacing)),
Dialog.PDFOptions.ColSpacing);
PDFRowSpacing := StrToDblDef(ReadString(S_PDF, S_PDF_RowSpacing,
FormatFloat('0.0', Dialog.PDFOptions.RowSpacing)),
Dialog.PDFOptions.RowSpacing);
PDFGridLineWidth := ReadInteger(S_PDF, S_PDF_GridLineWidth,
Dialog.PDFOptions.GridLineWidth);
PDFPageFormat := TQExportPageFormat(ReadInteger(S_PDF,
S_PDF_PageFormat, Integer(Dialog.PDFOptions.PageOptions.Format)));
PDFPageUnits := TQExportUnits(ReadInteger(S_PDF, S_PDF_PageUnits,
Integer(Dialog.PDFOptions.PageOptions.Units)));
PDFPageOrientation := TQExportPageOrientation(ReadInteger(S_PDF,
S_PDF_PageOrientation, Integer(Dialog.PDFOptions.PageOptions.Orientation)));
if PDFPageFormat = pfUser then begin
FPDFPageWidth := ReadInteger(S_PDF, S_PDF_PageWidth,
Units2Dot(Dialog.PDFOptions.PageOptions.Units,
Dialog.PDFOptions.PageOptions.Width));
FPDFPageHeight := ReadInteger(S_PDF, S_PDF_PageHeight,
Units2Dot(Dialog.PDFOptions.PageOptions.Units,
Dialog.PDFOptions.PageOptions.Height));
end;
FPDFPageMarginLeft := ReadInteger(S_PDF, S_PDF_PageMarginLeft,
Units2Dot(Dialog.PDFOptions.PageOptions.Units,
Dialog.PDFOptions.PageOptions.MarginLeft));
FPDFPageMarginRight := ReadInteger(S_PDF, S_PDF_PageMarginRight,
Units2Dot(Dialog.PDFOptions.PageOptions.Units,
Dialog.PDFOptions.PageOptions.MarginRight));
FPDFPageMarginTop := ReadInteger(S_PDF, S_PDF_PageMarginTop,
Units2Dot(Dialog.PDFOptions.PageOptions.Units,
Dialog.PDFOptions.PageOptions.MarginTop));
FPDFPageMarginBottom := ReadInteger(S_PDF, S_PDF_PageMarginBottom,
Units2Dot(Dialog.PDFOptions.PageOptions.Units,
Dialog.PDFOptions.PageOptions.MarginBottom));
edPDFPageWidth.Text := FormatFloat(GetPDFPageSizeFormat,
PDFPageWidth);
edPDFPageHeight.Text := FormatFloat(GetPDFPageSizeFormat,
PDFPageHeight);
edPDFPageMarginLeft.Text := FormatFloat(GetPDFPageSizeFormat,
PDFPageMarginLeft);
edPDFPageMarginRight.Text := FormatFloat(GetPDFPageSizeFormat,
PDFPageMarginRight);
edPDFPageMarginTop.Text := FormatFloat(GetPDFPageSizeFormat,
PDFPageMarginTop);
edPDFPageMarginBottom.Text := FormatFloat(GetPDFPageSizeFormat,
PDFPageMarginBottom);
//--- Header
PDFFont := PDFExp.Options.HeaderFont;
PDFFont.BaseFont := TPDFFontName(ReadInteger(S_PDF_OPTION_HEADER,
S_PDF_FontName, Integer(Dialog.PDFOptions.HeaderFont.BaseFont)));
PDFFont.FontEncoding := TPDFFontEncoding(ReadInteger(S_PDF_OPTION_HEADER,
S_PDF_FontEncoding, Integer(Dialog.PDFOptions.HeaderFont.FontEncoding)));
PDFFont.FontSize := ReadInteger(S_PDF_OPTION_HEADER, S_PDF_FontSize,
Dialog.PDFOptions.HeaderFont.FontSize);
PDFFont.FontColor := StringToColor(ReadString(S_PDF_OPTION_HEADER,
S_PDF_FontColor, ColorToString(Dialog.PDFOptions.HeaderFont.FontColor)));
//--- Caption
PDFFont := PDFExp.Options.CaptionFont;
PDFFont.BaseFont := TPDFFontName(ReadInteger(S_PDF_OPTION_CAPTION,
S_PDF_FontName, Integer(Dialog.PDFOptions.CaptionFont.BaseFont)));
PDFFont.FontEncoding := TPDFFontEncoding(ReadInteger(S_PDF_OPTION_CAPTION,
S_PDF_FontEncoding, Integer(Dialog.PDFOptions.CaptionFont.FontEncoding)));
PDFFont.FontSize := ReadInteger(S_PDF_OPTION_CAPTION, S_PDF_FontSize,
Dialog.PDFOptions.CaptionFont.FontSize);
PDFFont.FontColor := StringToColor(ReadString(S_PDF_OPTION_CAPTION,
S_PDF_FontColor, ColorToString(Dialog.PDFOptions.CaptionFont.FontColor)));
//--- Data
PDFFont := PDFExp.Options.DataFont;
PDFFont.BaseFont := TPDFFontName(ReadInteger(S_PDF_OPTION_DATA,
S_PDF_FontName, Integer(Dialog.PDFOptions.DataFont.BaseFont)));
PDFFont.FontEncoding := TPDFFontEncoding(ReadInteger(S_PDF_OPTION_DATA,
S_PDF_FontEncoding, Integer(Dialog.PDFOptions.DataFont.FontEncoding)));
PDFFont.FontSize := ReadInteger(S_PDF_OPTION_DATA, S_PDF_FontSize,
Dialog.PDFOptions.DataFont.FontSize);
PDFFont.FontColor := StringToColor(ReadString(S_PDF_OPTION_DATA,
S_PDF_FontColor, ColorToString(Dialog.PDFOptions.DataFont.FontColor)));
//--- Footer
PDFFont := PDFExp.Options.FooterFont;
PDFFont.BaseFont := TPDFFontName(ReadInteger(S_PDF_OPTION_FOOTER,
S_PDF_FontName, Integer(Dialog.PDFOptions.FooterFont.BaseFont)));
PDFFont.FontEncoding := TPDFFontEncoding(ReadInteger(S_PDF_OPTION_FOOTER,
S_PDF_FontEncoding, Integer(Dialog.PDFOptions.FooterFont.FontEncoding)));
PDFFont.FontSize := ReadInteger(S_PDF_OPTION_FOOTER, S_PDF_FontSize,
Dialog.PDFOptions.FooterFont.FontSize);
PDFFont.FontColor := StringToColor(ReadString(S_PDF_OPTION_FOOTER,
S_PDF_FontColor, ColorToString(Dialog.PDFOptions.FooterFont.FontColor)));
FPDFFontItem := lvPDFFonts.ItemFocused;
PDFShowFontInfo;
end;
// [XML]
aeXML: begin
XMLStandalone := ReadBool(S_XML, S_XML_Standalone,
Dialog.XMLOptions.Standalone);
XMLEncoding := ReadString(S_XML, S_XML_Encoding,
Dialog.XMLOptions.Encoding);
end;
// [SQL]
aeSQL: begin
SQLTableName := ReadString(S_SQL, S_SQL_TableName,
Dialog.SQLOptions.TableName);
SQLCreateTable := ReadBool(S_SQL, S_SQL_CreateTable,
Dialog.SQLOptions.CreateTable);
SQLCommitRecCount := ReadInteger(S_SQL,
S_SQL_CommitRecCount, Dialog.SQLOptions.CommitRecCount);
SQLCommitAfterScript := ReadBool(S_SQL, S_SQL_CommitAfterScript,
Dialog.SQLOptions.CommitAfterScript);
SQLCommitStatement := ReadString(S_SQL, S_SQL_CommitStatement,
Dialog.SQLOptions.CommitStatement);
SQLStatementTerm := ReadString(S_SQL, S_SQL_StatementTerm,
Dialog.SQLOptions.StatementTerm);
end;
// [TXT]
aeTXT: begin
TXTAutoCalcColWidth := ReadBool(S_TXT, S_TXT_AutoCalcColWidth,
Dialog.TXTOptions.AutoCalcColWidth);
TXTSpacing := ReadInteger(S_TXT, S_TXT_Spacing,
Dialog.TXTOptions.ColSpacing);
end;
// [CSV]
aeCSV: begin
CSVQuoteStrings := ReadBool(S_CSV, S_CSV_QuoteStrings,
Dialog.CSVOptions.QuoteStrings);
CSVComma := Str2Char(ReadString(S_CSV, S_CSV_Comma,
Char2Str(Dialog.CSVOptions.Comma)));
CSVQuote := Str2Char(ReadString(S_CSV, S_CSV_Quote,
Char2Str(Dialog.CSVOptions.Quote)));
end;
// [Access]
aeAccess: begin
AccessTableName := ReadString(S_ACCESS, S_ACCESS_TableName,
Dialog.AccessOptions.TableName);
AccessCreateTable := ReadBool(S_ACCESS, S_ACCESS_CreateTable,
Dialog.AccessOptions.CreateTable);
end;
end;
end;
finally
AStrings.Free;
FIniFile.Free;
end;
end;
procedure TADO_QExportDialogF.SaveExportOptions(const FileName: string);
var
i, j: Integer;
FIniFile: TIniFile;
AStrings: TStrings;
prefix, str: string;
xlsFormat: TxlsFieldFormat;
LV: TListView;
begin
FIniFile := TIniFile.Create(FileName);
try
ClearIniFile(FIniFile);
AStrings := TStringList.Create;
try
with FIniFile do begin
// [GENERAL]
WriteInteger(S_GENERAL, S_ExportType, Integer(ExportType));
WriteString(S_GENERAL, S_FileName, Self.FileName);
WriteBool(S_GENERAL, S_ShowFile, ShowFile);
WriteBool(S_GENERAL, S_PrintFile, PrintFile);
WriteBool(S_GENERAL, S_GoToFirstRecord, GoToFirstRecord);
WriteBool(S_GENERAL, S_ExportEmpty, ExportEmpty);
WriteBool(S_GENERAL, S_CurrentRecordOnly, CurrentRecordOnly);
WriteInteger(S_GENERAL, S_ExportRecCount, ExportRecCount);
WriteInteger(S_GENERAL, S_SkipRecCount, SkipRecCount);
WriteBool(S_GENERAL, S_AllowCaptions, AllowCaptions);
WriteInteger(S_GENERAL, S_CaptionRow, CaptionRow);
EraseSection(S_USER_FORMATS);
if tshFormats.TabVisible then begin
// [FORMATS]
WriteString(S_FORMATS, S_Integer, IntegerFmt);
WriteString(S_FORMATS, S_Float, FloatFmt);
WriteString(S_FORMATS, S_Date, DateFmt);
WriteString(S_FORMATS, S_Time, TimeFmt);
WriteString(S_FORMATS, S_DateTime, DateTimeFmt);
WriteString(S_FORMATS, S_Currency, CurrencyFmt);
WriteString(S_FORMATS, S_BooleanTrue, BooleanTrue);
WriteString(S_FORMATS, S_BooleanFalse, BooleanFalse);
WriteString(S_FORMATS, S_NullString, NullString);
// [USER_FORMATS]
for i := 0 to lstUserFormats.Items.Count - 1 do
WriteString(S_USER_FORMATS, lstUserFormats.Items[i].Caption,
lstUserFormats.Items[i].SubItems[1]);
end;
// [FIELDS]
EraseSection(S_FIELDS);
for i := 0 to lstExportedFields.Items.Count - 1 do
WriteString(S_FIELDS, S_Field + IntToStr(i),
lstExportedFields.Items[i].Caption);
// [HEADER] & [FOOTER]
EraseSection(S_HEADER);
EraseSection(S_FOOTER);
if tshHeaderFooter.TabVisible then begin
for i := 0 to memHeader.Lines.Count - 1 do
WriteString(S_HEADER, S_Line + IntToStr(i), memHeader.Lines[i]);
for i := 0 to memFooter.Lines.Count - 1 do
WriteString(S_FOOTER, S_Line + IntToStr(i), memFooter.Lines[i]);
end;
// [CAPTIONS & WIDTH & ALIGN]
EraseSection(S_CAPTIONS);
EraseSection(S_WIDTH);
EraseSection(S_ALIGN);
if tshCaptions.TabVisible then begin
for i := 1 to sgrCaptions.RowCount - 1 do begin
WriteString(S_CAPTIONS, sgrCaptions.Cells[0, i],
sgrCaptions.Cells[1, i]);
if ExportType in [aeTXT, aeRTF, aeWord, aeHTML]
then WriteString(S_ALIGN, sgrCaptions.Cells[0, i],
sgrCaptions.Cells[2, i]);
if ExportType in [aeTXT, aeRTF, aeWord, aeXLS]
then WriteInteger(S_WIDTH, sgrCaptions.Cells[0, i],
StrToInt(sgrCaptions.Cells[2 + Integer(ExportType <> aeXLS), i]));
end;
end;
EraseSection(S_XLS);
ReadSections(AStrings);
for i := AStrings.Count - 1 downto 0 do
if Pos(S_XLS_FIELD, AnsiUpperCase(AStrings[i])) > 0
then EraseSection(AStrings[i]);
EraseSection(S_RTF);
EraseSection(S_HTML);
EraseSection(S_SQL);
EraseSection(S_XML);
case ExportType of
// [XLS]
aeXLS: begin
WriteString(S_XLS, S_PageHeader, XLSPageHeader);
WriteString(S_XLS, S_PageFooter, XLSPageFooter);
WriteString(S_XLS, S_SheetTitle, XLSSheetTitle);
WriteInteger(S_XLS, S_StripType, Integer(XLSStripType));
WriteBool(S_XLS, S_AutoCalcColWidth, XLSAutoCalcColWidth);
for j := 1 to 3 do begin
case j of
1: begin
LV := lstXLSFields;
prefix := S_XLS_FIELD;
end;
2: begin
LV := lstXLSOptions;
prefix := S_XLS_OPTION;
end;
3: begin
LV := lstXLSStyles;
prefix := S_XLS_STYLE;
end;
else LV := nil
end;
for i := 0 to LV.Items.Count - 1 do begin
str := prefix + AnsiUpperCase(LV.Items[i].Caption);
xlsFormat := TxlsFieldFormat(LV.Items[i].Data);
xlsFormat.SaveToIniFile(FIniFile, str);
end;
end;
end;
// [RTF]
aeRTF, aeWord: begin
SaveFontToIniFile(RTFExp.Options.DefaultFont, FIniFile, S_RTF_Default_Font);
SaveFontToIniFile(RTFExp.Options.HeaderFont, FIniFile, S_RTF_Header_Font);
WriteInteger(S_RTF, S_RTF_PageOrientation, Integer(RTFPageOrientation));
end;
// [HTML]
aeHTML: begin
WriteString(S_HTML, S_HTML_Title, HTMLTitle);
WriteInteger(S_HTML, S_HTML_CSS, Integer(HTMLUsingCSS));
WriteString(S_HTML, S_HTML_CSSFile, HTMLCSSFileName);
WriteBool(S_HTML, S_HTML_OverwriteCSSFile, HTMLOverwriteCSSFile);
WriteInteger(S_HTML, S_HTML_FileRecCount, HTMLFileRecCount);
WriteBool(S_HTML, S_HTML_GenerateIndex, HTMLGenerateIndex);
WriteString(S_HTML, S_HTML_IndexLinkTemplate, HTMLIndexLinkTemplate);
WriteBool(S_HTML, S_HTML_NavigationOnTop, HTMLNavigationOnTop);
WriteBool(S_HTML, S_HTML_NavigationOnBottom, HTMLNavigationOnBottom);
WriteString(S_HTML, S_HTML_IndexLinkTitle, HTMLIndexLinkTitle);
WriteString(S_HTML, S_HTML_FirstLinkTitle, HTMLFirstLinkTitle);
WriteString(S_HTML, S_HTML_PriorLinkTitle, HTMLPriorLinkTitle);
WriteString(S_HTML, S_HTML_NextLinkTitle, HTMLNextLinkTitle);
WriteString(S_HTML, S_HTML_LastLinkTitle, HTMLLastLinkTitle);
WriteString(S_HTML, S_HTML_FontName, HTMLFontName);
WriteString(S_HTML, S_HTML_BackgroundFile, HTMLBackground);
WriteString(S_HTML, S_HTML_BodyAdvanced, HTMLBodyAdvanced);
WriteInteger(S_HTML, S_HTML_CellPadding, HTMLCellPadding);
WriteInteger(S_HTML, S_HTML_CellSpacing, HTMLCellSpacing);
WriteInteger(S_HTML, S_HTML_BorderWidth, HTMLBorderWidth);
WriteString(S_HTML, S_HTML_TableBackground, HTMLTableBackground);
WriteString(S_HTML, S_HTML_TableAdvanced, HTMLTableAdvanced);
WriteString(S_HTML, S_HTML_BackgroundColor,
ColorToString(HTMLBackgroundColor));
WriteString(S_HTML, S_HTML_FontColor,
ColorToString(HTMLFontColor));
WriteString(S_HTML, S_HTML_HeadBackgroundColor,
ColorToString(paHTMLColumnHead_1.Color));
WriteString(S_HTML, S_HTML_HeadFontColor,
ColorToString(laHTMLHead_1.Font.Color));
WriteString(S_HTML, S_HTML_OddRowBackgroundColor,
ColorToString(paHTMLOddRowCol_1.Color));
WriteString(S_HTML, S_HTML_EvenRowBackgroundColor,
ColorToString(paHTMLEvenRowCol_1.Color));
WriteString(S_HTML, S_HTML_DataFontColor,
ColorToString(laHTMLData_1.Font.Color));
WriteString(S_HTML, S_HTML_LinkColor,
ColorToString(laHTMLLink.Font.Color));
WriteString(S_HTML, S_HTML_VLinkColor,
ColorToString(laHTMLVLink.Font.Color));
WriteString(S_HTML, S_HTML_ALinkColor,
ColorToString(laHTMLALink.Font.Color));
end;
// [PDF]
aePDF: begin
WriteFloat(S_PDF, S_PDF_ColSpacing, PDFColSpacing);
WriteFloat(S_PDF, S_PDF_RowSpacing, PDFRowSpacing);
WriteInteger(S_PDF, S_PDF_GridLineWidth, PDFGridLineWidth);
WriteInteger(S_PDF, S_PDF_PageFormat, Integer(PDFPageFormat));
WriteInteger(S_PDF, S_PDF_PageUnits, Integer(PDFPageUnits));
WriteInteger(S_PDF, S_PDF_PageOrientation,
Integer(PDFPageOrientation));
WriteInteger(S_PDF, S_PDF_PageWidth, FPDFPageWidth);
WriteInteger(S_PDF, S_PDF_PageHeight, FPDFPageHeight);
WriteInteger(S_PDF, S_PDF_PageMarginLeft, FPDFPageMarginLeft);
WriteInteger(S_PDF, S_PDF_PageMarginRight, FPDFPageMarginRight);
WriteInteger(S_PDF, S_PDF_PageMarginTop, FPDFPageMarginTop);
WriteInteger(S_PDF, S_PDF_PageMarginBottom, FPDFPageMarginBottom);
//--- Header
WriteInteger(S_PDF_OPTION_HEADER, S_PDF_FontName,
Integer(PDFExp.Options.HeaderFont.BaseFont));
WriteInteger(S_PDF_OPTION_HEADER, S_PDF_FontEncoding,
Integer(PDFExp.Options.HeaderFont.FontEncoding));
WriteInteger(S_PDF_OPTION_HEADER, S_PDF_FontSize,
Integer(PDFExp.Options.HeaderFont.FontSize));
WriteString(S_PDF_OPTION_HEADER, S_PDF_FontColor,
ColorToString(PDFExp.Options.HeaderFont.FontColor));
//--- Caption
WriteInteger(S_PDF_OPTION_CAPTION, S_PDF_FontName,
Integer(PDFExp.Options.CaptionFont.BaseFont));
WriteInteger(S_PDF_OPTION_CAPTION, S_PDF_FontEncoding,
Integer(PDFExp.Options.CaptionFont.FontEncoding));
WriteInteger(S_PDF_OPTION_CAPTION, S_PDF_FontSize,
Integer(PDFExp.Options.CaptionFont.FontSize));
WriteString(S_PDF_OPTION_CAPTION, S_PDF_FontColor,
ColorToString(PDFExp.Options.CaptionFont.FontColor));
//--- Data
WriteInteger(S_PDF_OPTION_DATA, S_PDF_FontName,
Integer(PDFExp.Options.DataFont.BaseFont));
WriteInteger(S_PDF_OPTION_DATA, S_PDF_FontEncoding,
Integer(PDFExp.Options.DataFont.FontEncoding));
WriteInteger(S_PDF_OPTION_DATA, S_PDF_FontSize,
Integer(PDFExp.Options.DataFont.FontSize));
WriteString(S_PDF_OPTION_DATA, S_PDF_FontColor,
ColorToString(PDFExp.Options.DataFont.FontColor));
//--- Footer
WriteInteger(S_PDF_OPTION_FOOTER, S_PDF_FontName,
Integer(PDFExp.Options.FooterFont.BaseFont));
WriteInteger(S_PDF_OPTION_FOOTER, S_PDF_FontEncoding,
Integer(PDFExp.Options.FooterFont.FontEncoding));
WriteInteger(S_PDF_OPTION_FOOTER, S_PDF_FontSize,
Integer(PDFExp.Options.FooterFont.FontSize));
WriteString(S_PDF_OPTION_FOOTER, S_PDF_FontColor,
ColorToString(PDFExp.Options.FooterFont.FontColor));
end;
// [XML]
aeXML: begin
WriteBool(S_XML, S_XML_Standalone, XMLStandAlone);
WriteString(S_XML, S_XML_Encoding, XMLEncoding);
end;
// [SQL]
aeSQL: begin
WriteString(S_SQL, S_SQL_TableName, SQLTableName);
WriteBool(S_SQL, S_SQL_CreateTable, SQLCreateTable);
WriteInteger(S_SQL, S_SQL_CommitRecCount, SQLCommitRecCount);
WriteBool(S_SQL, S_SQL_CommitAfterScript, SQLCommitAfterScript);
WriteString(S_SQL, S_SQL_CommitStatement, SQLCommitStatement);
WriteString(S_SQL, S_SQL_StatementTerm, SQLStatementTerm);
end;
// [TXT]
aeTXT: begin
WriteBool(S_TXT, S_TXT_AutoCalcColWidth, TXTAutoCalcColWidth);
WriteInteger(S_TXT, S_TXT_Spacing, TXTSpacing);
end;
// [CSV]
aeCSV: begin
WriteBool(S_CSV, S_CSV_QuoteStrings, CSVQuoteStrings);
WriteString(S_CSV, S_CSV_Comma, Char2Str(CSVComma));
WriteString(S_CSV, S_CSV_Quote, Char2Str(CSVQuote));
end;
// [Access]
aeAccess: begin
WriteString(S_ACCESS, S_ACCESS_TableName, AccessTableName);
WriteBool(S_ACCESS, S_ACCESS_CreateTable, AccessCreateTable);
end;
end;
end;
finally
AStrings.Free;
end;
finally
FIniFile.Free;
end;
end;
procedure TADO_QExportDialogF.bStartClick(Sender: TObject);
function CalcAlignment(const Value: string): string;
var
Index: integer;
begin
Index := cbxColumnAlign.Items.IndexOf(Value);
Result := 'Left';
case Index of
1: Result := 'Center';
2: Result := 'Right';
end;
end;
var
i, j: integer;
str, ext: string;
begin
if Dialog.AutoChangeFileExt then
ChangeFileExtension;
case ExportType of
aeXLS: begin
QuickExport := XLSExp;
XLSExp.Options.PageHeader := XLSPageHeader;
XLSExp.Options.PageFooter := XLSPageFooter;
XLSExp.Options.SheetTitle := XLSSheetTitle;
XLSExp.StripType := XLSStripType;
XlsExp.AutoCalcColWidth := XLSAutoCalcColWidth;
XLSExp.Options.HeaderFormat.Assign(TxlsFormat(lstXLSOptions.Items[0].Data));
XLSExp.Options.CaptionsFormat.Assign(TxlsFormat(lstXLSOptions.Items[1].Data));
XLSExp.Options.AggregateFormat.Assign(TxlsFormat(lstXLSOptions.Items[2].Data));
XLSExp.Options.FooterFormat.Assign(TxlsFormat(lstXLSOptions.Items[3].Data));
XLSExp.FieldFormats.Clear;
if lstExportedFields.Items.Count > 0 then begin
for i := 0 to lstExportedFields.Items.Count - 1 do
for j := 0 to lstXLSFields.Items.Count - 1 do
if AnsiCompareText(lstExportedFields.Items[i].Caption,
lstXLSFields.Items[j].Caption) = 0 then
with XLSExp.FieldFormats.Add do begin
FieldName := lstXLSFields.Items[j].Caption;
Assign(TxlsFieldFormat(lstXLSFields.Items[j].Data));
end;
end
else begin
for i := 0 to lstAvailableFields.Items.Count - 1 do
for j := 0 to lstXLSFields.Items.Count - 1 do
if AnsiCompareText(lstAvailableFields.Items[i].Caption,
lstXLSFields.Items[j].Caption) = 0 then
with XLSExp.FieldFormats.Add do begin
FieldName := lstXLSFields.Items[j].Caption;
Assign(TxlsFormat(lstXLSFields.Items[j].Data));
end;
end;
XLSExp.StripStyles.Clear;
if lstXLSStyles.Items.Count > 0 then
for i := 0 to lstXLSStyles.Items.Count - 1 do
XLSExp.StripStyles.Add.Assign(TxlsFormat(lstXLSStyles.Items[i].Data));
end;
aeWord,
aeRTF: begin
QuickExport := RTFExp;
RTFExp.Options.PageOrientation := RTFPageOrientation;
end;
aeHTML: begin
QuickExport := HTMLExp;
with HTMLExp do begin
Title := HTMLTitle;
UsingCSS := HTMLUsingCSS;
CSSFileName := HTMLCSSFileName;
OverwriteCSSFile := HTMLOverwriteCSSFile;
MaxRecords := 0;
if HTMLUseMultiFileExport then
MaxRecords := HTMLFileRecCount;
GenerateIndex := HTMLGenerateIndex;
Navigation.IndexLinkTemplate := HTMLIndexLinkTemplate;
Navigation.OnTop := HTMLNavigationOnTop;
Navigation.OnBottom := HTMLNavigationOnBottom;
Navigation.IndexLinkTitle := HTMLIndexLinkTitle;
Navigation.FirstLinkTitle := HTMLFirstLinkTitle;
Navigation.PriorLinkTitle := HTMLPriorLinkTitle;
Navigation.NextLinkTitle := HTMLNextLinkTitle;
Navigation.LastLinkTitle := HTMLLastLinkTitle;
HTMLOptions.TextFont.Name := HTMLFontName;
HTMLOptions.BackgroundFileName := HTMLBackground;
HTMLOptions.AdvancedAttributes.Text := HTMLBodyAdvanced;
TableOptions.CellPadding := HTMLCellPadding;
TableOptions.CellSpacing := HTMLCellSpacing;
TableOptions.Border := HTMLBorderWidth;
TableOptions.BackgroundFileName := HTMLTableBackground;
TableOptions.AdvancedAttributes.Text := HTMLTableAdvanced;
HTMLOptions.BackgroundColor := HTMLBackgroundColor;
HTMLOptions.TextFont.Color := HTMLFontColor;
TableOptions.HeadersRowBgColor := HTMLHeadBackgroundColor;
TableOptions.HeadersRowFontColor := HTMLHeadFontColor;
TableOptions.OddRowBgColor := HTMLOddRowBackgroundColor;
TableOptions.TableBgColor := HTMLEvenRowBackgroundColor;
TableOptions.TableFontColor := HTMLDataFontColor;
HTMLOptions.LinkColor := HTMLLinkColor;
HTMLOptions.VLinkColor := HTMLVLinkColor;
HTMLOptions.ALinkColor := HTMLALinkColor;
end;
end;
aeTXT,
aeCSV,
aeDIFF,
aeSylk: begin
QuickExport := ASCIIExp;
case ExportType of
aeTXT: begin
ASCIIExp.ExportType := etTXT;
ASCIIExp.AutoCalcColWidth := TXTAutoCalcColWidth;
ASCIIExp.TXTSpacing := TXTSpacing;
end;
aeCSV: begin
ASCIIExp.ExportType := etCSV;
ASCIIExp.CSVQuoteStrings := CSVQuoteStrings;
ASCIIExp.CSVComma := CSVComma;
ASCIIExp.CSVQuote := CSVQuote;
end;
aeDIFF: ASCIIExp.ExportType := etDIF;
aeSylk: ASCIIExp.ExportType := etSYLK;
end;
end;
aeXML: begin
QuickExport := XMLExp;
XMLExp.Options.StandAlone := XMLStandAlone;
XMLExp.Options.Encoding := XMLEncoding;
end;
aeDBF: QuickExport := DBFExp;
aeLaTeX: QuickExport := LaTeXExp;
aeSQL: begin
QuickExport := SQLExp;
SQLExp.TableName := SQLTableName;
if SQLExp.TableName = EmptyStr then begin
str := ExtractFileName(FileName);
ext := ExtractFileExt(FileName);
if ext <> EmptyStr then
Delete(str, Length(str) - Length(ext) + 1, Length(ext));
SQLExp.TableName := AnsiUpperCase(str);
end;
SQLExp.CreateTable := SQLCreateTable;
SQLExp.CommitRecCount := SQLCommitRecCount;
SQLExp.CommitAfterScript := SQLCommitAfterScript;
SQLExp.CommitStatement := SQLCommitStatement;
if Length(SQLStatementTerm) > 0 then
SQLExp.StatementTerm := SQLStatementTerm[1];
end;
aeClipboard: QuickExport := ClipExp;
aePDF: begin
QuickExport := PDFExp;
PDFExp.Options.ColSpacing := PDFColSpacing;
PDFExp.Options.RowSpacing := PDFRowSpacing;
PDFExp.Options.GridLineWidth := PDFGridLineWidth;
PDFExp.Options.PageOptions.Format := PDFPageFormat;
if PDFPageFormat = pfUser then begin
PDFExp.Options.PageOptions.Width := FPDFPageWidth;
PDFExp.Options.PageOptions.Height := FPDFPageHeight;
end;
PDFExp.Options.PageOptions.Orientation := PDFPageOrientation;
PDFExp.Options.PageOptions.MarginLeft := FPDFPageMarginLeft;
PDFExp.Options.PageOptions.MarginRight := FPDFPageMarginRight;
PDFExp.Options.PageOptions.MarginTop := FPDFPageMarginTop;
PDFExp.Options.PageOptions.MarginBottom := FPDFPageMarginBottom;
end;
end;
QuickExport.AutoCalcStrType := Dialog.AutoCalcStrType;
QuickExport.GoToFirstRecord := GoToFirstRecord;
QuickExport.CurrentRecordOnly := CurrentRecordOnly;
QuickExport.ExportEmpty := ExportEmpty;
QuickExport.ExportRecCount := ExportRecCount;
QuickExport.SkipRecCount := SkipRecCount;
QuickExport.Header.Assign(memHeader.Lines);
QuickExport.Footer.Assign(memFooter.Lines);
QuickExport.ExportedFields.Clear;
if lstExportedFields.Items.Count > 0 then
for i := 0 to lstExportedFields.Items.Count - 1 do
QuickExport.ExportedFields.Add(lstExportedFields.Items[i].Caption)
else
for i := 0 to lstAvailableFields.Items.Count - 1 do
if not Dialog.Columns[Integer(lstAvailableFields.Items[i].Data)].IsBlob then
QuickExport.ExportedFields.Add(lstAvailableFields.Items[i].Caption);
QuickExport.Formats.IntegerFormat := IntegerFmt;
QuickExport.Formats.FloatFormat := FloatFmt;
QuickExport.Formats.DateFormat := DateFmt;
QuickExport.Formats.TimeFormat := TimeFmt;
QuickExport.Formats.DateTimeFormat := DateTimeFmt;
QuickExport.Formats.CurrencyFormat := CurrencyFmt;
QuickExport.Formats.BooleanTrue := BooleanTrue;
QuickExport.Formats.BooleanFalse := BooleanFalse;
QuickExport.Formats.NullString := NullString;
QuickExport.UserFormats.Clear;
for i := 0 to lstUserFormats.Items.Count - 1 do
QuickExport.UserFormats.Values[lstUserFormats.Items[i].Caption] :=
lstUserFormats.Items[i].SubItems[1];
QuickExport.ExportSource := ExportSource;
QuickExport.DataSet := DataSet;
QuickExport.ListView := ListView;
QuickExport.DBGrid := DBGrid;
QuickExport.StringGrid := StringGrid;
if QuickExport is TQExportText then
with QuickExport as TQExportText do begin
FileName := Self.FileName;
ShowFile := Self.ShowFile;
PrintFile := Self.PrintFile;
end;
if QuickExport is TQExportFormatText then begin
(QuickExport as TQExportFormatText).AllowCaptions := AllowCaptions;
(QuickExport as TQExportFormatText).CaptionRow := CaptionRow;
end;
if QuickExport is TQExportDatabase then
with QuickExport as TQExportDatabase do begin
DatabaseName := Self.FileName;
ShowFile := Self.ShowFile;
PrintFile := Self.PrintFile;
end;
QuickExport.Captions.Clear;
for i := 1 to sgrCaptions.RowCount - 1 do begin
if AnsiCompareStr(sgrCaptions.Cells[0, i], sgrCaptions.Cells[1, i]) <> 0 then
QuickExport.Captions.Values[sgrCaptions.Cells[0, i]] := sgrCaptions.Cells[1, i];
if QuickExport is TQExportASCII then
with QuickExport as TQExportASCII do begin
ColumnsAlign.Values[sgrCaptions.Cells[0, i]] :=
CalcAlignment(sgrCaptions.Cells[2, i]);
ColumnsWidth.Values[sgrCaptions.Cells[0, i]] := sgrCaptions.Cells[3, i];
end;
if QuickExport is TQExportRTF then
with QuickExport as TQExportRTF do begin
ColumnsAlign.Values[sgrCaptions.Cells[0, i]] :=
CalcAlignment(sgrCaptions.Cells[2, i]);
ColumnsWidth.Values[sgrCaptions.Cells[0, i]] := sgrCaptions.Cells[3, i];
end;
if QuickExport is TQExportPDF then
with QuickExport as TQExportPDF do begin
ColumnsAlign.Values[sgrCaptions.Cells[0, i]] :=
CalcAlignment(sgrCaptions.Cells[2, i]);
ColumnsWidth.Values[sgrCaptions.Cells[0, i]] := sgrCaptions.Cells[3, i];
end;
if QuickExport is TQExportHTML then
with QuickExport as TQExportHTML do
ColumnsAlign.Values[sgrCaptions.Cells[0, i]] :=
CalcAlignment(sgrCaptions.Cells[2, i]);
if QuickExport is TQExportXLS then
with QuickExport as TQExportXLS do
ColumnsWidth.Values[sgrCaptions.Cells[0, i]] := sgrCaptions.Cells[2, i];
end;
FProgress := TQExportDialogProgressF.CreateProgress(Self, QuickExport);
try
FProgress.Show;
QuickExport.Execute;
if ShowFile then begin
if not QuickExport.Aborted and Assigned(FProgress) then begin
PostMessage(FProgress.Handle, WM_QEXPORT_PROGRESS, QEP_DONE, 0);
Application.ProcessMessages;
end;
end
else
while FProgress.ModalResult <> mrOk do
Application.ProcessMessages;
finally
FProgress.Free;
end;
end;
procedure TADO_QExportDialogF.OnBeginExport(Sender: TObject);
begin
if Assigned(FProgress) then begin
PostMessage(FProgress.Handle, WM_QEXPORT_PROGRESS, QEP_START, 0);
Application.ProcessMessages;
end;
if Assigned(Dialog.OnBeginExport) then Dialog.OnBeginExport(QuickExport);
end;
procedure TADO_QExportDialogF.OnEndExport(Sender: TObject);
begin
if Assigned(FProgress) then begin
if not QuickExport.Aborted then
PostMessage(FProgress.Handle, WM_QEXPORT_PROGRESS, QEP_FINISH, 0);
Application.ProcessMessages;
end;
if Assigned(Dialog.OnEndExport) then Dialog.OnEndExport(QuickExport);
end;
procedure TADO_QExportDialogF.OnSkippedRecord(Sender: TObject;
RecNo: Integer);
begin
if Assigned(FProgress) then begin
PostMessage(FProgress.Handle, WM_QEXPORT_PROGRESS, QEP_SKIPPED, 0);
Application.ProcessMessages;
end;
if Assigned(Dialog.OnSkippedRecord) then
Dialog.OnSkippedRecord(QuickExport, RecNo);
end;
procedure TADO_QExportDialogF.OnBeforeExportRow(Sender: TObject;
Row: TQExportRow; var Accept: Boolean);
begin
if Assigned(Dialog.OnBeforeExportRow) then
Dialog.OnBeforeExportRow(QuickExport, Row, Accept);
end;
procedure TADO_QExportDialogF.OnExportedRecord(Sender: TObject; RecNo: Integer);
begin
if Assigned(Dialog.OnExportedRecord) then
Dialog.OnExportedRecord(QuickExport, RecNo);
if Assigned(FProgress) then begin
PostMessage(FProgress.Handle, WM_QEXPORT_PROGRESS, QEP_EXPORTED, 0);
Application.ProcessMessages;
end;
end;
procedure TADO_QExportDialogF.OnFetchedRecord(Sender: TObject;
RecNo: Integer);
begin
if Assigned(Dialog.OnFetchedRecord) then
Dialog.OnFetchedRecord(QuickExport, RecNo);
if Assigned(FProgress) then begin
PostMessage(FProgress.Handle, WM_QEXPORT_PROGRESS, QEP_FETCHED, 0);
Application.ProcessMessages;
end;
end;
procedure TADO_QExportDialogF.OnStopExport(Sender: TObject;
var CanContinue: Boolean);
begin
if Assigned(FProgress) then begin
PostMessage(FProgress.Handle, WM_QEXPORT_PROGRESS, QEP_PAUSE, 0);
Application.ProcessMessages;
end;
CanContinue := Application.MessageBox(PChar(QEM_StopExportConfirm),
PChar(QEM_StopExportCaption),
MB_YESNO + MB_ICONQUESTION + MB_DEFBUTTON2) = ID_NO;
if Assigned(Dialog.OnStopExport) then Dialog.OnStopExport(Dialog, CanContinue);
if Assigned(FProgress) then begin
if CanContinue
then PostMessage(FProgress.Handle, WM_QEXPORT_PROGRESS, QEP_CONTINUE, 0)
else PostMessage(FProgress.Handle, WM_QEXPORT_PROGRESS, QEP_ABORT, 0);
Application.ProcessMessages;
end;
end;
procedure TADO_QExportDialogF.OnGetExportText(Sender: TObject;
ColNo: Integer; var Text: String);
begin
if Assigned(Dialog.OnGetExportText) then
Dialog.OnGetExportText(QuickExport, ColNo, Text);
end;
procedure TADO_QExportDialogF.SetCaptions;
var
DC: HDC;
Size: TSize;
begin
laFileName.Caption := QED_FileName;
bBrowse.Caption := QED_SelectFile;
chShowFile.Caption := QED_OpenAfterExport;
chPrintFile.Caption := QED_PrintAfterExport;
// Export Type
tshExportType.Caption := QED_ExportType_Title;
tshExportFormats.Caption := QED_ExportType_Formats;
rgExportType.Caption := QED_ExportType_ExportTo;
bTools.Caption := QED_Tools;
miSaveOptions.Caption := QED_ExportType_Save;
miLoadOptions.Caption := QED_ExportType_Load;
tshExportOptions.Caption := QED_ExportType_Options;
gbExportConstraints.Caption := QED_ExportType_Constraints;
chGoToFirstRecord.Caption := QED_ExportType_Options_GoToFirstRecord;
chCurrentRecordOnly.Caption := QED_ExportType_Options_CurrentRecordOnly;
chExportEmpty.Caption := QED_ExportType_Options_ExportEmpty;
laSkipRecCount_01.Caption := QED_ExportType_Options_SkipRecCount;
edSkipRecCount.Left := laSkipRecCount_01.Left + laSkipRecCount_01.Width + 4;
laSkipRecCount_02.Left := edSkipRecCount.Left + edSkipRecCount.Width + 4;
laSkipRecCount_02.Caption := QED_ExportType_Options_Records;
rbExportAllRecords.Caption := QED_ExportType_ExportAllRecords;
rbExportOnly.Caption := QED_ExportType_Options_ExportRecCount;
DC := GetDC(rbExportOnly.Handle);
try
GetTextExtentPoint32(DC, PChar(rbExportOnly.Caption),
Length(rbExportOnly.Caption), Size);
finally
ReleaseDC(rbExportOnly.Handle, DC);
end;
rbExportOnly.Width := Size.cx;
edExportRecCount.Left := rbExportOnly.Left + rbExportOnly.Width + 4;
laExportRecCount_02.Left := edExportRecCount.Left + edExportRecCount.Width + 4;
laExportRecCount_02.Caption := QED_ExportType_Options_Records;
bStart.Caption := QED_ExportType_Start;
bCancel.Caption := QED_ExportType_Close;
// Fields
tshFields.Caption := QED_Fields_Title;
laAvailableFields.Caption := QED_Fields_Available;
laExportedFields.Caption := QED_Fields_Exported;
bAddOneExportedField.Caption := QED_Fields_Add;
bAddAllExportedField.Caption := QED_Fields_AddAll;
bDelOneExportedField.Caption := QED_Fields_Remove;
bDelAllExportedField.Caption := QED_Fields_RemoveAll;
// Formats
tshFormats.Caption := QED_Formats_Title;
gbStandardFormats.Caption := QED_Formats_Common;
laIntegerFormat.Caption := QED_Formats_Integer;
laFloatFormat.Caption := QED_Formats_Float;
laDateFormat.Caption := QED_Formats_Date;
laTimeFormat.Caption := QED_Formats_Time;
laDateTimeFormat.Caption := QED_Formats_DateTime;
laCurrencyFormat.Caption := QED_Formats_Currency;
laBooleanTrue.Caption := QED_Formats_BooleanTrue;
laBooleanFalse.Caption := QED_Formats_BooleanFalse;
laNullString.Caption := QED_Formats_NullString;
gbUserFormat.Caption := QED_Formats_User;
bAddUserFormat.Caption := QED_Formats_Add;
bEditUserFormat.Caption := QED_Formats_Edit;
bDeleteUserFormat.Caption := QED_Formats_Delete;
bClearUserFormats.Caption := QED_Formats_Clear;
// Header & Footer
tshHeaderFooter.Caption := QED_Header_Footer_Title;
laHeader.Caption := QED_Header_Footer_Header;
laFooter.Caption := QED_Header_Footer_Footer;
// Captions
tshCaptions.Caption := QED_Captions_Title;
chAllowCaptions.Caption := QED_Captions_AllowCaptions;
cbxColumnAlign.Items.Clear;
cbxColumnAlign.Items.Add(QED_Align_Left);
cbxColumnAlign.Items.Add(QED_Align_Center);
cbxColumnAlign.Items.Add(QED_Align_Right);
laCaptionRow.Caption := QED_StringGrid_CaptionRow;
// Word / RTF
tshRTF.Caption := QED_RTF_Title;
laRTFDefaultFont.Caption := QED_RTF_DefaultFont;
laRTFHeaderFont.Caption := QED_RTF_HeaderFont;
bRTFDefaultFont.Caption := QED_SelectFile;
bRTFHeaderFont.Caption := QED_SelectFile;
rgRTFPageOrientation.Caption := QED_RTF_PageOrientation;
rgRTFPageOrientation.Items.Clear;
rgRTFPageOrientation.Items.Add(QEPO_Portrait);
rgRTFPageOrientation.Items.Add(QEPO_Landscape);
// XML
tshXML.Caption := QED_XML_Title;
chXMLStandAlone.Caption := QED_XML_Standalone;
laXMLEncoding.Caption := QED_XML_Encoding;
// SQL
tshSQL.Caption := QED_SQL_Title;
gbSQLTableOptions.Caption := QED_SQL_TableOptions;
chSQLCreateTable.Caption := QED_SQL_AddCreateTable;
laSQLTableName.Caption := QED_SQL_TableName;
gbSQLCommit.Caption := QED_SQL_Commit;
laSQLUseCommit_01.Caption := QED_SQL_CommitAfter_01;
laSQLUseCommit_02.Caption := QED_SQL_CommitAfter_02;
chSQLCommitAfterScript.Caption := QED_SQL_CommitAfterScript;
laSQLCommitStatement.Caption := QED_SQL_CommitStatement;
gbSQLMisc.Caption := QED_SQL_Other;
laSQLNullString.Caption := QED_SQL_NullAs;
//edSQLNullString.Left := laSQLNullString.Left + laSQLNullString.Width + 4;
laSQLStatementTerm.Caption := QED_SQL_StatementTerm;
// HTML
tshHTML.Caption := QED_HTML_Title;
tshHTMLPreview.Caption := QED_HTML_Preview_Title;
laHTMLFont.Caption := QED_HTML_Preview_DefaultText;
laHTMLLink.Caption := QED_HTML_Preview_NonVisitedLink;
laHTMLVLink.Caption := QED_HTML_Preview_VisitedLink;
laHTMLALink.Caption := QED_HTML_Preview_ActiveLink;
laHTMLTemplate.Caption := QED_HTML_Preview_Template;
bHTMLSaveTemplate.Caption := QED_HTML_Preview_SaveTemplate;
bHTMLLoadTemplate.Caption := QED_HTML_Preview_LoadTemplate;
tshHTMLBasic.Caption := QED_HTML_Basic_Title;
laHTMLTitle.Caption := QED_HTML_Basic_PageTitle;
gbHTMLUsingCSS.Caption := QED_HTML_Basic_CSS;
rbInternal.Caption := QED_HTML_Basic_CSSInternal;
rbExternal.Caption := QED_HTML_Basic_CSSExternal;
laHTMLCSSFileName.Caption := QED_HTML_Basic_CSSFileName;
edHTMLCSSFileName.Left := laHTMLCSSFileName.Left + laHTMLCSSFileName.Width + 4;
bvHTMLCSSFileName.Left := edHTMLCSSFileName.Left + edHTMLCSSFileName.Width + 2;
btnHTMLCSSFileName.Left := bvHTMLCSSFileName.Left + 1;
chHTMLOverwriteCSSFile.Caption := QED_HTML_Basic_OverwriteCSSFile;
tshHTMLMultiFile.Caption := QED_HTML_MultiFile_Title;
gbHTMLMultifileOptions.Caption := QED_HTML_Basic_MultiFile_Options;
chHTMLUseMultiFileExport.Caption := QED_HTML_Basic_MultiFile_Use;
laHTMLFileRecCount_01.Caption := QED_HTML_Basic_MultiFile_RecCount_01;
edHTMLFileRecCount.Left := laHTMLFileRecCount_01.Left +
laHTMLFileRecCount_01.Width + 4;
laHTMLFileRecCount_02.Left := edHTMLFileRecCount.Left +
edHTMLFileRecCount.Width + 4;
laHTMLFileRecCount_02.Caption := QED_HTML_Basic_MultiFile_RecCount_02;
chHTMLGenerateIndex.Caption := QED_HTML_Basic_MultiFile_GenerateIndex;
gbHTMLNavigation.Caption := QED_HTML_Basic_MultiFile_Navigation;
laHTMLIndexLinkTemplate.Caption := QED_HTML_MultiFile_IndexLinkTemplate;
chHTMLNavigationOnTop.Caption := QED_HTML_Basic_MultiFile_Navigation_OnTop;
chHTMLNavigationOnBottom.Caption := QED_HTML_Basic_MultiFile_Navigation_OnBottom;
laHTMLIndexLinkTitle.Caption := QED_HTML_Basic_MultiFile_IndexLinkTitle;
laHTMLFirstLinkTitle.Caption := QED_HTML_Basic_MultiFile_FirstLinkTitle;
laHTMLPriorLinkTitle.Caption := QED_HTML_Basic_MultiFile_PriorLinkTitle;
laHTMLNextLinkTitle.Caption := QED_HTML_Basic_MultiFile_NextLinkTitle;
laHTMLLastLinkTitle.Caption := QED_HTML_Basic_MultiFile_LastLinkTitle;
tshHTMLAdvanced.Caption := QED_HTML_Advanced_Title;
gbHTMLBodyOptions.Caption := QED_HTML_Advanced_Body_Options;
laHTMLBodyFontName.Caption := QED_HTML_Advanced_Body_FontName;
laHTMLBackground.Caption := QED_HTML_Advanced_Body_Background;
laHTMLBodyAdvanced.Caption := QED_HTML_Advanced_Body_Attributes;
gbHTMLTableOptions.Caption := QED_HTML_Advanced_Table_Options;
laHTMLCellPadding.Caption := QED_HTML_Advanced_Table_CellPadding;
laHTMLCellSpacing.Caption := QED_HTML_Advanced_Table_CellSpasing;
laHTMLBorderWidth.Caption := QED_HTML_Advanced_Table_Border;
laHTMLTableBackground.Caption := QED_HTML_Advanced_Table_Background;
laHTMLTableAdvanced.Caption := QED_HTML_Advanced_Table_Attributes;
// XLS
tshXLS.Caption := QED_XLS_Title;
tshXLSAdvanced.Caption := QED_XLS_Advanced_Title;
laXLSPageHeader.Caption := QED_XLS_Page_Header;
laXLSPageFooter.Caption := QED_XLS_Page_Footer;
laXLSSheetTitle.Caption := QED_XLS_Sheet_Title;
chXLSAutoCalcColWidth.Caption := QED_XLS_AutoCalcColWidth;
tshXLSDataFormat.Caption := QED_XLS_DataFormat_Title;
tshXLSFields.Caption := QED_XLS_DataFormat_Fields;
tshXLSOptions.Caption := QED_XLS_DataFormat_Options;
tshXLSStyles.Caption := QED_XLS_DataFormat_Styles;
tbtAddXLSStyle.Hint := QED_XLS_DataFormat_Styles_Add;
tbtDelXLSStyle.Hint := QED_XLS_DataFormat_Styles_Del;
tbtUpXLSStyle.Hint := QED_XLS_DataFormat_Styles_Up;
tbtDownXLSStyle.Hint := QED_XLS_DataFormat_Styles_Down;
tbtSaveXLSStyle.Hint := QED_XLS_DataFormat_Styles_Save;
tbtLoadXLSStyle.Hint := QED_XLS_DataFormat_Styles_Load;
rgXLSStripType.Caption := QED_XLS_DataFormat_Styles_StripStyle_Caption;
rgXLSStripType.Items.Clear;
rgXLSStripType.Items.Add(QED_XLS_DataFormat_Styles_StripStyle_None);
rgXLSStripType.Items.Add(QED_XLS_DataFormat_Styles_StripStyle_Col);
rgXLSStripType.Items.Add(QED_XLS_DataFormat_Styles_StripStyle_Row);
rgXLSStripType.ItemIndex := Integer(XLSExp.StripType);
btnXLSResetItem.Caption := QED_XLS_Reset_Item;
btnXLSResetAll.Caption := QED_XLS_Reset_All;
laXLSSampleCell.Caption := QED_XLS_SampleCell;
tshXLSFont.Caption := QED_XLS_Font_Title;
laXLSFont.Caption := QED_XLS_Font;
laXLSFontSize.Caption := QED_XLS_FontSize;
btnFontColor.Hint := QED_XLS_Font_Color;
btnFontBold.Hint := QED_XLS_Font_Bold;
btnFontItalic.Hint := QED_XLS_Font_Italic;
btnFontStrikeOut.Hint := QED_XLS_Font_StrikeOut;
btnUnderlineSingle.Hint := QED_XLS_Underline_Single;
btnUnderlineSingleAccounting.Hint := QED_XLS_Underline_Single_Accounting;
btnUnderlineDouble.Hint := QED_XLS_Underline_Double;
btnUnderlineDoubleAccounting.Hint := QED_XLS_Underline_Double_Accounting;
btnHorizontalLeft.Hint := QED_XLS_Alignment_Horizontal_Left;
btnHorizontalCenter.Hint := QED_XLS_Alignment_Horizontal_Center;
btnHorizontalRight.Hint := QED_XLS_Alignment_Horizontal_Right;
btnHorizontalFill.Hint := QED_XLS_Alignment_Horizontal_Fill;
btnVerticalTop.Hint := QED_XLS_Alignment_Vertical_Top;
btnVerticalCenter.Hint := QED_XLS_Alignment_Vertical_Center;
btnVerticalBottom.Hint := QED_XLS_Alignment_Vertical_Bottom;
tshXLSBorders.Caption := QED_XLS_Borders_Title;
btnBorderTop.Hint := QED_XLS_Border_Top;
btnBorderTopColor.Hint := QED_XLS_Border_Top_Color;
btnBorderBottom.Hint := QED_XLS_Border_Bottom;
btnBorderBottomColor.Hint := QED_XLS_Border_Bottom_Color;
btnBorderLeft.Hint := QED_XLS_Border_Left;
btnBorderLeftColor.Hint := QED_XLS_Border_Left_Color;
btnBorderRight.Hint := QED_XLS_Border_Right;
btnBorderRightColor.Hint := QED_XLS_Border_Right_Color;
tshXLSFill.Caption := QED_XLS_Fill_Title;
btnFillBackground.Hint := QED_XLS_Fill_Background;
btnFillForeground.Hint := QED_XLS_Fill_Foreground;
tshXLSAggregate.Caption := QED_XLS_Aggregate_Title;
rgXLSFunction.Caption := QED_XLS_Function;
rgXLSFunction.Items.Clear;
rgXLSFunction.Items.Add(QED_XLS_Function_None);
rgXLSFunction.Items.Add(QED_XLS_Function_Sum);
rgXLSFunction.Items.Add(QED_XLS_Function_Avg);
rgXLSFunction.Items.Add(QED_XLS_Function_Min);
rgXLSFunction.Items.Add(QED_XLS_Function_Max);
// ASCII
tshASCII.Caption := QED_ASCII_Title;
gbTXTOptions.Caption := QED_TXT_Title;
chTXTAutoCalcColWidth.Caption := QED_TXT_AutoCalcColWidth;
laTXTSpacing.Caption := QED_TXT_Spacing;
gbCSVOptions.Caption := QED_CSV_Title;
chCSVQuoteStrings.Caption := QED_CSV_QuoteStrings;
laCSVComma.Caption := QED_CSV_Comma;
laCSVQuote.Caption := QED_CSV_Quote;
// Access
tshAccess.Caption := QED_Access_Title;
gbAccessTableOptions.Caption := QED_Access_TableOptions;
laAccessTableName.Caption := QED_Access_TableName;
chAccessCreateTable.Caption := QED_Access_CreateTable;
//PDF
tshPDF.Caption := QED_PDF_Title;
laPDFFontName.Caption := QED_PDF_FontName;
laPDFFontEncoding.Caption := QED_PDF_FontEncoding;
laPDFFontSize.Caption := QED_PDF_FontSize;
sbPDFFontColor.Caption := QED_PDF_FontColor;
paPDFSample.Caption := QED_PDF_Sample;
tshPDFGridOptions.Caption := QED_PDF_GridOptions;
laPDFColSpacing.Caption := QED_PDF_ColSpacing;
laPDFRowSpacing.Caption := QED_PDF_RowSpacing;
laPDFGridLineWidth.Caption := QED_PDF_GridLineWidth;
tshPDFPageOptions.Caption := QED_PDF_PageOptions;
laPDFPageFormat.Caption := QED_PDF_PageSize;
cbPDFPageFormat.Items.Clear;
cbPDFPageFormat.Items.Add(QEPF_Letter);
cbPDFPageFormat.Items.Add(QEPF_Legal);
cbPDFPageFormat.Items.Add(QEPF_A3);
cbPDFPageFormat.Items.Add(QEPF_A4);
cbPDFPageFormat.Items.Add(QEPF_A5);
cbPDFPageFormat.Items.Add(QEPF_B5_JIS);
cbPDFPageFormat.Items.Add(QEPF_US_Std_Fanfold);
cbPDFPageFormat.Items.Add(QEPF_Fanfold);
cbPDFPageFormat.Items.Add(QEPF_User);
cbPDFPageFormat.ItemIndex := Integer(Dialog.PDFOptions.PageOptions.Format);
laPDFPageUnits.Caption := QED_PDF_PageUnits;
cbPDFPageUnits.Items.Clear;
cbPDFPageUnits.Items.Add(QEUN_Inch);
cbPDFPageUnits.Items.Add(QEUN_Millimeter);
cbPDFPageUnits.Items.Add(QEUN_Dot);
cbPDFPageUnits.ItemIndex := Integer(Dialog.PDFOptions.PageOptions.Units);
laPDFPageOrientation.Caption := QED_PDF_PageOrientation;
cbPDFPageOrientation.Items.Clear;
cbPDFPageOrientation.Items.Add(QEPO_Portrait);
cbPDFPageOrientation.Items.Add(QEPO_Landscape);
cbPDFPageOrientation.ItemIndex := Integer(Dialog.PDFOptions.PageOptions.Orientation);
gbPDFMargins.Caption := QED_PDF_Margins;
laPDFPageMarginLeft.Caption := QED_PDF_MarginLeft;
laPDFPageMarginRight.Caption := QED_PDF_MarginRight;
laPDFPageMarginTop.Caption := QED_PDF_MarginTop;
laPDFPageMarginBottom.Caption := QED_PDF_MarginBottom;
end;
procedure TADO_QExportDialogF.FieldsListDragOver(Sender,
Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean);
begin
Accept := (Source is TListView);// and (Source <> Sender);
end;
procedure TADO_QExportDialogF.rgXLSFunctionClick(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
TxlsFieldFormat(FXLSListItem.Data).Aggregate :=
TxlsAggregate(rgXLSFunction.ItemIndex);
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemAggregate, false);
end;
procedure TADO_QExportDialogF.btnXLSResetItemClick(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
TxlsFieldFormat(FXLSListItem.Data).SetDefault;
if CurrXLSListView.SelCount > 1 then
ForAllListViewItems(CurrXLSListView, XLSUpdateItemSetDefault, false);
CurrXLSListView.OnChange(CurrXLSListView, CurrXLSListView.Selected, ctState);
end;
procedure TADO_QExportDialogF.btnXLSResetAllClick(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.Items.Count = 0 then Exit;
if Application.MessageBox(PChar(QED_XLS_Reset_All_Question),
PChar(QED_XLS_Reset_All_Question_Caption),
MB_YESNO + MB_ICONWARNING + MB_DEFBUTTON2) = ID_NO
then Exit;
XLSResetAllItems;
end;
procedure TADO_QExportDialogF.btnFontColorMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
IncLeftAndTop(pbFontColor);
end;
procedure TADO_QExportDialogF.btnFontColorMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
DecLeftAndTop(pbFontColor);
end;
procedure TADO_QExportDialogF.btnBorderTopColorMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
IncLeftAndTop(pbBorderTop);
end;
procedure TADO_QExportDialogF.btnBorderTopColorMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
DecLeftAndTop(pbBorderTop);
end;
procedure TADO_QExportDialogF.btnBorderBottomColorMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
IncLeftAndTop(pbBorderBottom);
end;
procedure TADO_QExportDialogF.btnBorderBottomColorMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
DecLeftAndTop(pbBorderBottom);
end;
procedure TADO_QExportDialogF.btnBorderLeftColorMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
IncLeftAndTop(pbBorderLeft);
end;
procedure TADO_QExportDialogF.btnBorderLeftColorMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
DecLeftAndTop(pbBorderLeft);
end;
procedure TADO_QExportDialogF.btnBorderRightColorMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
IncLeftAndTop(pbBorderRight);
end;
procedure TADO_QExportDialogF.btnBorderRightColorMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
DecLeftAndTop(pbBorderRight);
end;
procedure TADO_QExportDialogF.btnFillBackgroundMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
IncLeftAndTop(pbFillBackground);
end;
procedure TADO_QExportDialogF.btnFillBackgroundMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
DecLeftAndTop(pbFillBackground);
end;
procedure TADO_QExportDialogF.btnFillForegroundMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
IncLeftAndTop(pbFillForeground);
end;
procedure TADO_QExportDialogF.btnFillForegroundMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
DecLeftAndTop(pbFillForeground);
end;
procedure TADO_QExportDialogF.pbXLSCellPaint(Sender: TObject);
begin
if CurrXLSListView = nil then Exit;
if CurrXLSListView.SelCount < 1 then Exit;
if CurrXLSListView.SelCount = 1
then DrawXLSCell(pbXLSCell, TxlsFormat(CurrXLSListView.Selected.Data))
else DrawXLSCell(pbXLSCell, TxlsFormat(FXLSListItem.Data))
end;
function TADO_QExportDialogF.CurrXLSListView: TListView;
begin
if pcXLSFormats.ActivePage = tshXLSFields then
Result := lstXLSFields
else if pcXLSFormats.ActivePage = tshXLSOptions then
Result := lstXLSOptions
else if pcXLSFormats.ActivePage = tshXLSStyles then
Result := lstXLSStyles
else Result := nil
end;
procedure TADO_QExportDialogF.CorrectXLSFieldsList;
var
i, j: integer;
flag: boolean;
begin
if lstExportedFields.Items.Count = 0 then begin
for i := 0 to lstXLSFields.Items.Count - 1 do begin
j := Dialog.Columns.IndexOfName(lstXLSFields.Items[i].Caption);
if not Dialog.Columns[j].IsBlob
then lstXLSFields.Items[i].ImageIndex := 1
else lstXLSFields.Items[i].ImageIndex := 0;
end
end
else begin
// Adding columns which not in lstXLSFields
for i := 0 to lstExportedFields.Items.Count - 1 do
for j := 0 to lstXLSFields.Items.Count - 1 do
if AnsiCompareText(lstExportedFields.Items[i].Caption,
lstXLSFields.Items[j].Caption) = 0 then begin
lstXLSFields.Items[j].ImageIndex := 1;
SetListItemIndex(lstXLSFields.Items[j], i);
Break;
end;
// Deleting columns which not in lstExportedFields
for i := lstXLSFields.Items.Count - 1 downto 0 do begin
flag := false;
for j := 0 to lstExportedFields.Items.Count - 1 do begin
flag := flag or
(AnsiCompareText(lstXLSFields.Items[i].Caption,
lstExportedFields.Items[j].Caption) = 0);
if flag then Break;
end;
if not flag then lstXLSFields.Items[i].ImageIndex := 0;
end;
end;
end;
procedure TADO_QExportDialogF.lstAvailableFieldsDragDrop(Sender,
Source: TObject; X, Y: Integer);
var
Item, Item1: TListItem;
n: integer;
begin
if Source <> Sender then begin
with MoveListItem((Source as TListView).Selected, Sender as TListView, true,
GetIndexOfNewAvailableFields((Source as TListView).Selected)) do
ImageIndex := 0;
CorrectXLSFieldsList;
end
else begin
Item := (Source as TListView).GetItemAt(X, Y);
if Assigned(Item) then begin
if Item.Index > (Source as TListView).Selected.Index
then n := 1
else n := 0;
Item1 := (Source as TListView).Items.Insert(Item.Index + n);
with Item1 do Caption := (Source as TListView).Selected.Caption;
(Source as TListView).Selected.Delete;
Item1.Focused := true;
Item1.Selected := true;
end;
end;
end;
procedure TADO_QExportDialogF.lstExportedFieldsDragDrop(Sender,
Source: TObject; X, Y: Integer);
begin
with MoveListItem((Source as TListView).Selected, Sender as TListView, true, -1) do
ImageIndex := 1;
CorrectXLSFieldsList;
end;
procedure TADO_QExportDialogF.ShowXLSListItem(Item: TListItem);
var
Event: TNotifyEvent;
begin
btnXLSResetItem.Caption := QED_XLS_Reset_Item;
cbxXLSFont.ItemIndex :=
cbxXLSFont.Items.IndexOf(TxlsFormat(Item.Data).Font.Name);
cbxXLSFontSize.Text := IntToStr(TxlsFormat(Item.Data).Font.Size);
pbFontColor.Repaint;
btnFontBold.Down := xfsBold in TxlsFormat(Item.Data).Font.Style;
btnFontItalic.Down := xfsItalic in TxlsFormat(Item.Data).Font.Style;
btnFontStrikeOut.Down := xfsStrikeOut in TxlsFormat(Item.Data).Font.Style;
btnUnderlineSingle.Down := TxlsFormat(Item.Data).Font.Underline = fulSingle;
btnUnderlineSingleAccounting.Down :=
TxlsFormat(Item.Data).Font.Underline = fulSingleAccounting;
btnUnderlineDouble.Down := TxlsFormat(Item.Data).Font.Underline = fulDouble;
btnUnderlineDoubleAccounting.Down :=
TxlsFormat(Item.Data).Font.Underline = fulDoubleAccounting;
btnHorizontalLeft.Down :=
TxlsFormat(Item.Data).Alignment.Horizontal = halLeft;
btnHorizontalCenter.Down :=
TxlsFormat(Item.Data).Alignment.Horizontal = halCenter;
btnHorizontalRight.Down :=
TxlsFormat(Item.Data).Alignment.Horizontal = halRight;
btnHorizontalFill.Down :=
TxlsFormat(Item.Data).Alignment.Horizontal = halFill;
btnVerticalTop.Down := TxlsFormat(Item.Data).Alignment.Vertical = valTop;
btnVerticalCenter.Down :=
TxlsFormat(Item.Data).Alignment.Vertical = valCenter;
btnVerticalBottom.Down :=
TxlsFormat(Item.Data).Alignment.Vertical = valBottom;
btnBorderTop.Down := TxlsFormat(Item.Data).Borders.Top.Style <> bstNone;
cmbBorderTop.ItemIndex := Integer(TxlsFormat(Item.Data).Borders.Top.Style);
btnBorderBottom.Down := TxlsFormat(Item.Data).Borders.Bottom.Style <> bstNone;
cmbBorderBottom.ItemIndex :=
Integer(TxlsFormat(Item.Data).Borders.Bottom.Style);
btnBorderLeft.Down := TxlsFormat(Item.Data).Borders.Left.Style <> bstNone;
cmbBorderLeft.ItemIndex := Integer(TxlsFormat(Item.Data).Borders.Left.Style);
btnBorderRight.Down := TxlsFormat(Item.Data).Borders.Right.Style <> bstNone;
cmbBorderRight.ItemIndex :=
Integer(TxlsFormat(Item.Data).Borders.Right.Style);
pbBorderTop.Repaint;
pbBorderBottom.Repaint;
pbBorderLeft.Repaint;
pbBorderRight.Repaint;
cmbPattern.ItemIndex := Integer(TxlsFormat(Item.Data).Fill.Pattern);
pbFillBackground.Repaint;
pbFillForeground.Repaint;
cmbPattern.Repaint;
if rgXLSFunction.Enabled
then begin
Event := rgXLSFunction.OnClick;
rgXLSFunction.OnClick := nil;
rgXLSFunction.ItemIndex := Integer(TxlsFieldFormat(Item.Data).Aggregate);
rgXLSFunction.OnClick := Event;
end
else rgXLSFunction.ItemIndex := -1;
pbXLSCell.Repaint;
end;
procedure TADO_QExportDialogF.ShowXLSListItemM;
var
i: integer;
IsFont, IsFontSize,
IsTop, IsBottom, IsLeft, IsRight,
IsPattern, IsAggregate, IsFunction: boolean;
begin
if CurrXLSListView = nil then Exit;
btnXLSResetItem.Caption := QED_XLS_Reset_SelectedItems;
IsFont := true;
IsFontSize := true;
IsTop := true;
IsBottom := true;
IsLeft := true;
IsRight := true;
IsPattern := true;
IsAggregate := true;
IsFunction := true;
for i := 0 to CurrXLSListView.Items.Count - 1 do
if CurrXLSListView.Items[i].Selected and
(CurrXLSListView.Items[i] <> FXLSListItem) then begin
if IsFont then
IsFont := IsFont and
(AnsiCompareText(TxlsFormat(FXLSListItem.Data).Font.Name,
TxlsFormat(CurrXLSListView.Items[i].Data).Font.Name) = 0);
if IsFontSize then
IsFontSize := IsFontSize and
(TxlsFormat(FXLSListItem.Data).Font.Size =
TxlsFormat(CurrXLSListView.Items[i].Data).Font.Size);
if IsTop then
IsTop := IsTop and
(TxlsFormat(FXLSListItem.Data).Borders.Top.Style =
TxlsFormat(CurrXLSListView.Items[i].Data).Borders.Top.Style);
if IsBottom then
IsBottom := IsBottom and
(TxlsFormat(FXLSListItem.Data).Borders.Bottom.Style =
TxlsFormat(CurrXLSListView.Items[i].Data).Borders.Bottom.Style);
if IsLeft then
IsLeft := IsLeft and
(TxlsFormat(FXLSListItem.Data).Borders.Left.Style =
TxlsFormat(CurrXLSListView.Items[i].Data).Borders.Left.Style);
if IsRight then
IsRight := IsRight and
(TxlsFormat(FXLSListItem.Data).Borders.Right.Style =
TxlsFormat(CurrXLSListView.Items[i].Data).Borders.Right.Style);
if IsPattern then
IsPattern := IsPattern and
(TxlsFormat(FXLSListItem.Data).Fill.Pattern =
TxlsFormat(CurrXLSListView.Items[i].Data).Fill.Pattern);
if IsAggregate then
IsAggregate := IsAggregate and not (i in [0..3]);
IsFunction := IsFunction and IsAggregate;
if IsFunction then
IsFunction := IsFunction and
(TxlsFieldFormat(FXLSListItem.Data).Aggregate =
TxlsFieldFormat(CurrXLSListView.Items[i].Data).Aggregate);
end;
if IsFont
then cbxXLSFont.ItemIndex := cbxXLSFont.Items.IndexOf(TxlsFormat(FXLSListItem.Data).Font.Name)
else cbxXLSFont.ItemIndex := -1;
if IsFontSize
then cbxXLSFontSize.Text := IntToStr(TxlsFormat(FXLSListItem.Data).Font.Size)
else cbxXLSFontSize.Text := EmptyStr;
pbFontColor.Repaint;
btnFontBold.Down := xfsBold in TxlsFormat(FXLSListItem.Data).Font.Style;
btnFontItalic.Down := xfsItalic in TxlsFormat(FXLSListItem.Data).Font.Style;
btnFontStrikeOut.Down := xfsStrikeOut in TxlsFormat(FXLSListItem.Data).Font.Style;
btnUnderlineSingle.Down :=
TxlsFormat(FXLSListItem.Data).Font.Underline = fulSingle;
btnUnderlineSingleAccounting.Down :=
TxlsFormat(FXLSListItem.Data).Font.Underline = fulSingleAccounting;
btnUnderlineDouble.Down :=
TxlsFormat(FXLSListItem.Data).Font.Underline = fulDouble;
btnUnderlineDoubleAccounting.Down :=
TxlsFormat(FXLSListItem.Data).Font.Underline = fulDoubleAccounting;
btnHorizontalLeft.Down :=
TxlsFormat(FXLSListItem.Data).Alignment.Horizontal = halLeft;
btnHorizontalCenter.Down :=
TxlsFormat(FXLSListItem.Data).Alignment.Horizontal = halCenter;
btnHorizontalRight.Down :=
TxlsFormat(FXLSListItem.Data).Alignment.Horizontal = halRight;
btnHorizontalFill.Down :=
TxlsFormat(FXLSListItem.Data).Alignment.Horizontal = halFill;
btnVerticalTop.Down :=
TxlsFormat(FXLSListItem.Data).Alignment.Vertical = valTop;
btnVerticalCenter.Down :=
TxlsFormat(FXLSListItem.Data).Alignment.Vertical = valCenter;
btnVerticalBottom.Down :=
TxlsFormat(FXLSListItem.Data).Alignment.Vertical = valBottom;
if IsTop
then cmbBorderTop.ItemIndex :=
Integer(TxlsFormat(FXLSListItem.Data).Borders.Top.Style)
else cmbBorderTop.ItemIndex := -1;
if IsBottom
then cmbBorderBottom.ItemIndex :=
Integer(TxlsFormat(FXLSListItem.Data).Borders.Bottom.Style)
else cmbBorderBottom.ItemIndex := -1;
if IsLeft
then cmbBorderLeft.ItemIndex :=
Integer(TxlsFormat(FXLSListItem.Data).Borders.Left.Style)
else cmbBorderLeft.ItemIndex := -1;
if IsRight
then cmbBorderRight.ItemIndex :=
Integer(TxlsFormat(FXLSListItem.Data).Borders.Right.Style)
else cmbBorderRight.ItemIndex := -1;
pbBorderTop.Repaint;
pbBorderBottom.Repaint;
pbBorderLeft.Repaint;
pbBorderRight.Repaint;
if IsPattern
then cmbPattern.ItemIndex :=
Integer(TxlsFormat(FXLSListItem.Data).Fill.Pattern)
else cmbPattern.ItemIndex := -1;
pbFillBackground.Repaint;
pbFillForeground.Repaint;
rgXLSFunction.Enabled := IsAggregate;
if IsFunction
then rgXLSFunction.ItemIndex :=
Integer(TxlsFieldFormat(FXLSListItem.Data).Aggregate)
else rgXLSFunction.ItemIndex := -1;
pbXLSCell.Repaint;
end;
procedure TADO_QExportDialogF.XLSUpdateItemFont(Item: TListItem);
begin
if Item <> FXLSListItem
then TxlsFormat(Item.Data).Font.Name :=
TxlsFormat(FXLSListItem.Data).Font.Name;
end;
procedure TADO_QExportDialogF.XLSUpdateItemFontSize(Item: TListItem);
begin
if Item <> FXLSListItem
then TxlsFormat(Item.Data).Font.Size :=
TxlsFormat(FXLSListItem.Data).Font.Size;
end;
procedure TADO_QExportDialogF.XLSUpdateItemFontColor(Item: TListItem);
begin
if Item <> FXLSListItem
then TxlsFormat(Item.Data).Font.Color :=
TxlsFormat(FXLSListItem.Data).Font.Color;
end;
procedure TADO_QExportDialogF.XLSUpdateItemFontBold(Item: TListItem);
begin
if Item <> FXLSListItem then
XLSItemEditFontStyle(Item, xfsBold,
xfsBold in TxlsFormat(FXLSListItem.Data).Font.Style);
end;
procedure TADO_QExportDialogF.XLSUpdateItemFontItalic(Item: TListItem);
begin
if Item <> FXLSListItem then
XLSItemEditFontStyle(Item, xfsItalic,
xfsItalic in TxlsFormat(FXLSListItem.Data).Font.Style);
end;
procedure TADO_QExportDialogF.XLSUpdateItemFontStrikeOut(Item: TListItem);
begin
if Item <> FXLSListItem then
XLSItemEditFontStyle(Item, xfsStrikeOut,
xfsStrikeOut in TxlsFormat(FXLSListItem.Data).Font.Style);
end;
procedure TADO_QExportDialogF.XLSUpdateItemFontUnderline(Item: TListItem);
begin
if Item <> FXLSListItem then
TxlsFormat(Item.Data).Font.Underline :=
TxlsFormat(FXLSListItem.Data).Font.Underline;
end;
procedure TADO_QExportDialogF.XLSUpdateItemHorAlignment(Item: TListItem);
begin
if Item <> FXLSListItem then
TxlsFormat(Item.Data).Alignment.Horizontal :=
TxlsFormat(FXLSListItem.Data).Alignment.Horizontal;
end;
procedure TADO_QExportDialogF.XLSUpdateItemVertAlignment(Item: TListItem);
begin
if Item <> FXLSListItem then
TxlsFormat(Item.Data).Alignment.Vertical :=
TxlsFormat(FXLSListItem.Data).Alignment.Vertical;
end;
procedure TADO_QExportDialogF.XLSUpdateItemBorderTop(Item: TListItem);
begin
if Item <> FXLSListItem then
TxlsFormat(Item.Data).Borders.Top.Style :=
TxlsFormat(FXLSListItem.Data).Borders.Top.Style;
end;
procedure TADO_QExportDialogF.XLSUpdateItemBorderTopColor(Item: TListItem);
begin
if Item <> FXLSListItem then
TxlsFormat(Item.Data).Borders.Top.Color :=
TxlsFormat(FXLSListItem.Data).Borders.Top.Color;
end;
procedure TADO_QExportDialogF.XLSUpdateItemBorderBottom(Item: TListItem);
begin
if Item <> FXLSListItem then
TxlsFormat(Item.Data).Borders.Bottom.Style :=
TxlsFormat(FXLSListItem.Data).Borders.Bottom.Style;
end;
procedure TADO_QExportDialogF.XLSUpdateItemBorderBottomColor(Item: TListItem);
begin
if Item <> FXLSListItem then
TxlsFormat(Item.Data).Borders.Bottom.Color :=
TxlsFormat(FXLSListItem.Data).Borders.Bottom.Color;
end;
procedure TADO_QExportDialogF.XLSUpdateItemBorderLeft(Item: TListItem);
begin
if Item <> FXLSListItem then
TxlsFormat(Item.Data).Borders.Left.Style :=
TxlsFormat(FXLSListItem.Data).Borders.Left.Style;
end;
procedure TADO_QExportDialogF.XLSUpdateItemBorderLeftColor(Item: TListItem);
begin
if Item <> FXLSListItem then
TxlsFormat(Item.Data).Borders.Left.Color :=
TxlsFormat(FXLSListItem.Data).Borders.Left.Color;
end;
procedure TADO_QExportDialogF.XLSUpdateItemBorderRight(Item: TListItem);
begin
if Item <> FXLSListItem then
TxlsFormat(Item.Data).Borders.Right.Style :=
TxlsFormat(FXLSListItem.Data).Borders.Right.Style;
end;
procedure TADO_QExportDialogF.XLSUpdateItemBorderRightColor(Item: TListItem);
begin
if Item <> FXLSListItem then
TxlsFormat(Item.Data).Borders.Right.Color :=
TxlsFormat(FXLSListItem.Data).Borders.Right.Color;
end;
procedure TADO_QExportDialogF.XLSUpdateItemFillPattern(Item: TListItem);
begin
if Item <> FXLSListItem then
TxlsFormat(Item.Data).Fill.Pattern :=
TxlsFormat(FXLSListItem.Data).Fill.Pattern;
end;
procedure TADO_QExportDialogF.XLSUpdateItemFillBackground(Item: TListItem);
begin
if Item <> FXLSListItem then
TxlsFormat(Item.Data).Fill.Background :=
TxlsFormat(FXLSListItem.Data).Fill.Background;
end;
procedure TADO_QExportDialogF.XLSUpdateItemFillForeground(Item: TListItem);
begin
if Item <> FXLSListItem then
TxlsFormat(Item.Data).Fill.Foreground :=
TxlsFormat(FXLSListItem.Data).Fill.Foreground;
end;
procedure TADO_QExportDialogF.XLSUpdateItemAggregate(Item: TListItem);
begin
if Item <> FXLSListItem then
TxlsFieldFormat(Item.Data).Aggregate :=
TxlsFieldFormat(FXLSListItem.Data).Aggregate;
end;
procedure TADO_QExportDialogF.XLSUpdateItemSetDefault(Item: TListItem);
begin
if Item <> FXLSListItem then begin
if AnsiCompareText(Item.Caption, QED_XLS_Caption) = 0
then SetDefaultXLSCaption(TxlsFormat(Item.Data))
else TxlsFieldFormat(Item.Data).SetDefault;
end;
end;
procedure TADO_QExportDialogF.XLSResetAllItems;
var
Index, i: integer;
begin
if Assigned(FXLSListItem)
then Index := FXLSListItem.Index
else Index := 0;
CurrXLSListView.Items.BeginUpdate;
try
if Assigned(FXLSListItem) then begin
TxlsFieldFormat(FXLSListItem.Data).SetDefault;
if AnsiCompareText(TxlsFieldFormat(FXLSListItem.Data).FieldName,
QED_XLS_Caption) = 0 then
EditFontStyleXLS(TxlsFieldFormat(FXLSListItem.Data).Font, xfsBold, true);
end;
for i := 0 to CurrXLSListView.Items.Count - 1 do
XLSUpdateItemSetDefault(CurrXLSListView.Items[i]);
CurrXLSListView.Items[Index].Selected := true;
finally
CurrXLSListView.Items.EndUpdate;
CurrXLSListView.OnChange(CurrXLSListView, FXLSListItem, ctState);
end;
end;
procedure TADO_QExportDialogF.XLSResetAllItems_A;
var
i, j: integer;
LV: TListView;
begin
for i := 1 to 3 do begin
case i of
1: LV := lstXLSFields;
2: LV := lstXLSOptions;
3: LV := lstXLSStyles;
else LV := nil;
end;
if not Assigned(LV) then Exit;
LV.Items.BeginUpdate;
try
for j := 0 to LV.Items.Count - 1 do begin
XLSUpdateItemSetDefault(LV.Items[j]);
if AnsiCompareText(LV.Items[j].Caption, QED_XLS_Caption) = 0 then
EditFontStyleXLS(TxlsFieldFormat(LV.Items[j].Data).Font, xfsBold, true);
if AnsiCompareText(TxlsFieldFormat(FXLSListItem.Data).FieldName,
QED_XLS_Caption) = 0 then
EditFontStyleXLS(TxlsFieldFormat(FXLSListItem.Data).Font, xfsBold, true);
end;
finally
LV.Items.EndUpdate;
end;
end;
if Assigned(FXLSListItem) then TxlsFieldFormat(FXLSListItem.Data).SetDefault;
end;
procedure TADO_QExportDialogF.XLSShowStyleButtons;
begin
tbtDelXLSStyle.Enabled := Assigned(lstXLSStyles.Selected);
tbtUpXLSStyle.Enabled := Assigned(lstXLSStyles.Selected) and
(lstXLSStyles.Items.Count > 1) and
(lstXLSStyles.Selected.Index > 0);
tbtDownXLSStyle.Enabled := Assigned(lstXLSStyles.Selected) and
(lstXLSStyles.Items.Count > 1) and
(lstXLSStyles.Selected.Index <
lstXLSStyles.Items.Count - 1);
tbtSaveXLSStyle.Enabled := lstXLSStyles.Items.Count > 0;
end;
procedure TADO_QExportDialogF.XLSRenumStyles;
var
i: integer;
LI: TListItem;
begin
lstXLSStyles.Items.BeginUpdate;
try
LI := lstXLSStyles.Selected;
for i := 0 to lstXLSStyles.Items.Count - 1 do
lstXLSStyles.Items[i].Caption := QED_XLS_StyleItem + IntToStr(i + 1);
if Assigned(LI) then begin
LI.Focused := true;
LI.Selected := true;
end;
finally
lstXLSStyles.Items.EndUpdate;
end;
end;
procedure TADO_QExportDialogF.XLSSaveStyle(const FileName: string);
var
IniFile: TIniFile;
i: integer;
begin
IniFile := TIniFile.Create(FileName);
try
ClearIniFile(IniFile);
for i := 0 to lstXLSStyles.Items.Count - 1 do
TxlsFormat(lstXLSStyles.Items[i].Data).SaveToIniFile(IniFile,
S_XLS_STYLE + IntToStr(i));
finally
IniFile.Free;
end;
end;
procedure TADO_QExportDialogF.XLSLoadStyle(const FileName: string);
var
IniFile: TIniFile;
AStrings: TStrings;
i: integer;
begin
lstXLSStyles.Items.BeginUpdate;
try
lstXLSStyles.Items.Clear;
IniFile :=TIniFile.Create(FileName);
try
AStrings := TStringList.Create;
try
IniFile.ReadSections(AStrings);
for i := 0 to AStrings.Count - 1 do
if AnsiCompareText(S_XLS_STYLE, Copy(AStrings[i], 1,
Length(S_XLS_STYLE))) = 0 then
with lstXLSStyles.Items.Add do begin
Caption := QED_XLS_StyleItem + Copy(AStrings[i],
Length(S_XLS_STYLE) + 1, Length(AStrings[i]));
Data := TxlsFormat.Create(nil);
TxlsFormat(Data).LoadFromIniFile(IniFile, AStrings[i]);
ImageIndex := 2;
end;
if lstXLSStyles.Items.Count > 0 then begin
ActiveControl := lstXLSStyles;
lstXLSStyles.Items[0].Focused := true;
lstXLSStyles.Items[0].Selected := true;
end;
finally
AStrings.Free;
end;
finally
IniFile.Free;
end;
finally
lstXLSStyles.Items.EndUpdate;
end;
end;
procedure TADO_QExportDialogF.edIntegerFormatChange(Sender: TObject);
begin
IntegerFmt := edIntegerFormat.Text;
end;
procedure TADO_QExportDialogF.edFloatFormatChange(Sender: TObject);
begin
FloatFmt := edFloatFormat.Text;
end;
procedure TADO_QExportDialogF.edDateFormatChange(Sender: TObject);
begin
DateFmt := edDateFormat.Text;
end;
procedure TADO_QExportDialogF.edTimeFormatChange(Sender: TObject);
begin
TimeFmt := edTimeFormat.Text;
end;
procedure TADO_QExportDialogF.edDateTimeFormatChange(Sender: TObject);
begin
DateTimeFmt := edDateTimeFormat.Text;
end;
procedure TADO_QExportDialogF.edCurrencyFormatChange(Sender: TObject);
begin
CurrencyFmt := edCurrencyFormat.Text;
end;
procedure TADO_QExportDialogF.edXLSPageHeaderChange(Sender: TObject);
begin
XLSPageHeader := edXLSPageHeader.Text;
end;
procedure TADO_QExportDialogF.edXLSPageFooterChange(Sender: TObject);
begin
XLSPageFooter := edXLSPageFooter.Text;
end;
procedure TADO_QExportDialogF.edXLSSheetTitleChange(Sender: TObject);
begin
XLSSheetTitle := edXLSSheetTitle.Text;
end;
procedure TADO_QExportDialogF.chXLSAutoCalcColWidthClick(Sender: TObject);
begin
XLSAutoCalcColWidth := chXLSAutoCalcColWidth.Checked;
end;
procedure TADO_QExportDialogF.edHTMLTitleChange(Sender: TObject);
begin
HTMLTitle := edHTMLTitle.Text;
end;
procedure TADO_QExportDialogF.edHTMLCSSFileNameChange(Sender: TObject);
begin
HTMLCSSFileName := edHTMLCSSFileName.Text;
end;
procedure TADO_QExportDialogF.btnHTMLCSSFileNameClick(Sender: TObject);
begin
if odHTMLCSS.Execute then HTMLCSSFileName := odHTMLCSS.FileName;
end;
procedure TADO_QExportDialogF.chHTMLOverwriteCSSFileClick(Sender: TObject);
begin
HTMLOverwriteCSSFile := chHTMLOverwriteCSSFile.Checked;
end;
procedure TADO_QExportDialogF.edHTMLFileRecCountChange(Sender: TObject);
begin
HTMLFileRecCount := StrToIntDef(edHTMLFileRecCount.Text, 0);
end;
procedure TADO_QExportDialogF.chHTMLGenerateIndexClick(Sender: TObject);
begin
HTMLGenerateIndex := chHTMLGenerateIndex.Checked;
HTMLUpdateMultiFileControls;
end;
procedure TADO_QExportDialogF.cbxHTMLFontNameChange(Sender: TObject);
begin
HTMLFontName := cbxHTMLFontName.Text;
end;
procedure TADO_QExportDialogF.edHTMLBackgroundChange(Sender: TObject);
begin
HTMLBackground := edHTMLBackground.Text;
end;
procedure TADO_QExportDialogF.btnHTMLBackgroundClick(Sender: TObject);
begin
if HTMLBackground <> EmptyStr then
opdHTMLBackground.InitialDir := ExtractFileDir(HTMLBackground);
if opdHTMLBackground.Execute then
HTMLBackground := opdHTMLBackground.FileName;
end;
procedure TADO_QExportDialogF.edHTMLBodyAdvancedChange(Sender: TObject);
begin
HTMLBodyAdvanced := edHTMLBodyAdvanced.Text;
end;
procedure TADO_QExportDialogF.edHTMLCellPaddingChange(Sender: TObject);
begin
HTMLCellPadding := StrToIntDef(edHTMLCellPadding.Text, 0);
end;
procedure TADO_QExportDialogF.edHTMLCellSpacingChange(Sender: TObject);
begin
HTMLCellSpacing := StrToIntDef(edHTMLCellSpacing.Text, 0);
end;
procedure TADO_QExportDialogF.edHTMLBorderWidthChange(Sender: TObject);
begin
HTMLBorderWidth := StrToIntDef(edHTMLBorderWidth.Text, 0);
end;
procedure TADO_QExportDialogF.edHTMLTableBackgroundChange(Sender: TObject);
begin
HTMLTableBackground := edHTMLTableBackground.Text;
end;
procedure TADO_QExportDialogF.btnHTMLTableBackgroundClick(Sender: TObject);
begin
if HTMLTableBackground <> EmptyStr then
opdHTMLBackground.InitialDir := ExtractFileDir(HTMLTableBackground);
if opdHTMLBackground.Execute then
HTMLTableBackground := opdHTMLBackground.FileName;
end;
procedure TADO_QExportDialogF.edHTMLTableAdvancedChange(Sender: TObject);
begin
HTMLTableAdvanced := edHTMLTableAdvanced.Text;
end;
procedure TADO_QExportDialogF.paHTMLBackgroundClick(Sender: TObject);
var
FColor:TColor;
begin
ColorDialog.Color := HTMLBackgroundColor;
if ColorDialog.Execute then begin
FColor := ColorDialog.Color;
HTMLBackgroundColor := FColor;
SetCustomTemplate;
end;
end;
procedure TADO_QExportDialogF.laHTMLFontClick(Sender: TObject);
begin
ColorDialog.Color := HTMLFontColor;
if ColorDialog.Execute then begin
HTMLFontColor := ColorDialog.Color;
SetCustomTemplate;
end;
end;
procedure TADO_QExportDialogF.paHTMLColumnHead_1Click(Sender: TObject);
begin
ColorDialog.Color := HTMLHeadBackgroundColor;
if ColorDialog.Execute then begin
HTMLHeadBackgroundColor := ColorDialog.Color;
SetCustomTemplate;
end;
end;
procedure TADO_QExportDialogF.laHTMLHead_1Click(Sender: TObject);
begin
ColorDialog.Color := HTMLHeadFontColor;
if ColorDialog.Execute then begin
HTMLHeadFontColor := ColorDialog.Color;
SetCustomTemplate;
end;
end;
procedure TADO_QExportDialogF.paHTMLOddRowCol_1Click(Sender: TObject);
begin
ColorDialog.Color := HTMLOddRowBackgroundColor;
if ColorDialog.Execute then begin
HTMLOddRowBackgroundColor := ColorDialog.Color;
SetCustomTemplate;
end;
end;
procedure TADO_QExportDialogF.paHTMLEvenRowCol_1Click(Sender: TObject);
begin
ColorDialog.Color := HTMLEvenRowBackgroundColor;
if ColorDialog.Execute then begin
HTMLEvenRowBackgroundColor := ColorDialog.Color;
SetCustomTemplate;
end;
end;
procedure TADO_QExportDialogF.laHTMLData_1Click(Sender: TObject);
begin
ColorDialog.Color := HTMLDataFontColor;
if ColorDialog.Execute then begin
HTMLDataFontColor := ColorDialog.Color;
SetCustomTemplate;
end;
end;
procedure TADO_QExportDialogF.laHTMLLinkClick(Sender: TObject);
begin
ColorDialog.Color := HTMLLinkColor;
if ColorDialog.Execute then begin
HTMLLinkColor := ColorDialog.Color;
SetCustomTemplate;
end;
end;
procedure TADO_QExportDialogF.laHTMLVLinkClick(Sender: TObject);
begin
ColorDialog.Color := HTMLVLinkColor;
if ColorDialog.Execute then begin
HTMLVLinkColor := ColorDialog.Color;
SetCustomTemplate;
end;
end;
procedure TADO_QExportDialogF.laHTMLALinkClick(Sender: TObject);
begin
ColorDialog.Color := HTMLALinkColor;
if ColorDialog.Execute then begin
HTMLALinkColor := ColorDialog.Color;
SetCustomTemplate;
end;
end;
procedure TADO_QExportDialogF.chXMLStandaloneClick(Sender: TObject);
begin
XMLStandalone := chXMLStandalone.Checked;
end;
procedure TADO_QExportDialogF.edXMLEncodingChange(Sender: TObject);
begin
XMLEncoding := edXMLEncoding.Text;
end;
procedure TADO_QExportDialogF.edSQLTableNameChange(Sender: TObject);
begin
SQLTableName := edSQLTableName.Text;
end;
procedure TADO_QExportDialogF.chSQLCreateTableClick(Sender: TObject);
begin
SQLCreateTable := chSQLCreateTable.Checked;
end;
procedure TADO_QExportDialogF.edSQLCommitRecCountChange(Sender: TObject);
begin
try
SQLCommitRecCount := StrToInt(edSQLCommitRecCount.Text);
except end;
end;
procedure TADO_QExportDialogF.chSQLCommitAfterScriptClick(Sender: TObject);
begin
SQLCommitAfterScript := chSQLCommitAfterScript.Checked;
end;
procedure TADO_QExportDialogF.edSQLCommitStatementChange(Sender: TObject);
begin
SQLCommitStatement := edSQLCommitStatement.Text;
end;
procedure TADO_QExportDialogF.edSQLNullStringChange(Sender: TObject);
begin
NullString := edSQLNullString.Text;
end;
procedure TADO_QExportDialogF.edSQLStatementTermChange(Sender: TObject);
begin
SQLStatementTerm := edSQLStatementTerm.Text;
end;
procedure TADO_QExportDialogF.edBooleanTrueChange(Sender: TObject);
begin
BooleanTrue := edBooleanTrue.Text;
end;
procedure TADO_QExportDialogF.edBooleanFalseChange(Sender: TObject);
begin
BooleanFalse := edBooleanFalse.Text;
end;
procedure TADO_QExportDialogF.edNullStringChange(Sender: TObject);
begin
NullString := edNullString.Text;
end;
function TADO_QExportDialogF.GetIndexOfNewAvailableFields(Item: TListItem): integer;
var
i: integer;
begin
Result := 0;
for i := 0 to lstAvailableFields.Items.Count - 1 do begin
if Integer(lstAvailableFields.Items[i].Data) > Integer(Item.Data)
then Exit
else Result := i + 1;
end
end;
procedure TADO_QExportDialogF.sgrCaptionsGetEditText(Sender: TObject; ACol,
ARow: Integer; var Value: String);
var
Rect: TRect;
begin
if (ExportType in [aeTXT, aeRTF, aeWord, aeHTML, aePDF]) and (ACol = 2) then begin
Rect := sgrCaptions.CellRect(ACol, ARow);
cbxColumnAlign.Left:= Rect.Left + 1;
cbxColumnAlign.Top := Rect.Top + 26;
cbxColumnAlign.Width := Rect.Right - Rect.Left + 2;
cbxColumnAlign.ItemIndex := cbxColumnAlign.Items.IndexOf(sgrCaptions.Cells[ACol, ARow]);
cbxColumnAlign.Visible := true;
cbxColumnAlign.SetFocus;
end;
if ((ExportType in [aeTXT, aeRTF, aeWord, aePDF]) and (ACol = 3)) or
((ExportType = aeXLS) and (ACol = 2)) then begin
Rect := sgrCaptions.CellRect(ACol, ARow);
edColumnWidth.Left:= Rect.Left + 1;
edColumnWidth.Top := Rect.Top + 26;
edColumnWidth.Width := Rect.Right - Rect.Left - udColumnWidth.Width + 2;
edColumnWidth.Text := sgrCaptions.Cells[ACol, ARow];
udColumnWidth.Left:= edColumnWidth.Left + edColumnWidth.Width;
udColumnWidth.Top := edColumnWidth.Top;
udColumnWidth.Height := 20;
udColumnWidth.Position := StrToInt(sgrCaptions.Cells[ACol, ARow]);
edColumnWidth.Visible := true;
udColumnWidth.Visible := true;
edColumnWidth.SetFocus;
end;
end;
procedure TADO_QExportDialogF.cbxColumnAlignExit(Sender: TObject);
begin
sgrCaptions.Cells[sgrCaptions.Col, sgrCaptions.Row] := cbxColumnAlign.Text;
cbxColumnAlign.Visible := false;
end;
procedure TADO_QExportDialogF.edColumnWidthExit(Sender: TObject);
begin
sgrCaptions.Cells[sgrCaptions.Col, sgrCaptions.Row] := edColumnWidth.Text;
edColumnWidth.Visible := false;
udColumnWidth.Visible := false;
end;
procedure TADO_QExportDialogF.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if AutoSaveOptions and (OptionsFileName <> EmptyStr)
then SaveExportOptions(OptionsFileName);
end;
procedure TADO_QExportDialogF.rbInternalClick(Sender: TObject);
begin
if rbInternal.Checked
then HTMLUsingCSS := usInternal;
end;
procedure TADO_QExportDialogF.rbExternalClick(Sender: TObject);
begin
if rbExternal.Checked
then HTMLUsingCSS := usExternal;
end;
procedure TADO_QExportDialogF.rbExportOnlyClick(Sender: TObject);
begin
edExportRecCount.Enabled := true;
laExportRecCount_02.Enabled := true;
end;
procedure TADO_QExportDialogF.rbExportAllRecordsClick(Sender: TObject);
begin
edExportRecCount.Enabled := false;
laExportRecCount_02.Enabled := false;
ExportRecCount := 0;
end;
procedure TADO_QExportDialogF.chTXTAutoCalcColWidthClick(Sender: TObject);
begin
TXTAutoCalcColWidth := chTXTAutoCalcColWidth.Checked;
end;
procedure TADO_QExportDialogF.edTXTSpacingChange(Sender: TObject);
begin
try TXTSpacing := StrToInt(edTXTSpacing.Text); except end;
end;
procedure TADO_QExportDialogF.NumberKeyPress(Sender: TObject;
var Key: Char);
begin
if not (Key in ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', #8])
then Key := #0;
end;
procedure TADO_QExportDialogF.chCSVQuoteStringsClick(Sender: TObject);
begin
CSVQuoteStrings := chCSVQuoteStrings.Checked;
end;
procedure TADO_QExportDialogF.edCSVCommaExit(Sender: TObject);
begin
CSVComma := Str2Char(edCSVComma.Text);
end;
procedure TADO_QExportDialogF.edCSVQuoteExit(Sender: TObject);
begin
CSVQuote := Str2Char(edCSVQuote.Text);
end;
procedure TADO_QExportDialogF.rgRTFPageOrientationClick(Sender: TObject);
begin
RTFPageOrientation := TQExportPageOrientation(rgRTFPageOrientation.ItemIndex);
end;
procedure TADO_QExportDialogF.lstXLSFieldsDeletion(Sender: TObject;
Item: TListItem);
begin
TxlsFormat(Item.Data).Free;
Item.Data := nil;
end;
procedure TADO_QExportDialogF.lstXLSFieldsChange(Sender: TObject;
Item: TListItem; Change: TItemChange);
var
i: integer;
LV: TListView;
begin
if (Change <> ctState) then Exit;
if not Assigned(Item.Data) then Exit;
if not (Sender is TListView) then Exit;
LV := Sender as TListView;
case LV.SelCount of
0: FXLSListItem := nil;
1: FXLSListItem := Item;
end;
if not Assigned(FXLSListItem) and
(LV.SelCount > 0) then
for i := 0 to LV.Items.Count - 1 do
if LV.Items[i].Selected then begin
FXLSListItem := LV.Items[i];
Break;
end;
if LV.SelCount = 1
then ShowXLSListItem(Item)
else if LV.SelCount > 1
then ShowXLSListItemM;
XLSShowStyleButtons;
end;
procedure TADO_QExportDialogF.pcXLSFormatsChange(Sender: TObject);
begin
tshXLSAggregate.TabVisible := pcXLSFormats.ActivePage = tshXLSFields;
if CurrXLSListView = nil then Exit;
if Assigned(CurrXLSListView.Selected) then
CurrXLSListView.OnChange(CurrXLSListView, CurrXLSListView.Selected, ctState);
end;
procedure TADO_QExportDialogF.tbtAddXLSStyleClick(Sender: TObject);
begin
with lstXLSStyles.Items.Add do begin
Caption := QED_XLS_StyleItem + IntToStr(lstXLSStyles.Items.Count);
Data := TxlsFieldFormat.Create(nil);
ImageIndex := 2;
Focused := true;
Selected := true;
end;
ActiveControl := lstXLSStyles;
XLSShowStyleButtons;
end;
procedure TADO_QExportDialogF.tbtDelXLSStyleClick(Sender: TObject);
var
Index: integer;
begin
if Assigned(lstXLSStyles.Selected) then begin
Index := lstXLSStyles.Selected.Index;
lstXLSStyles.Selected.Delete;
if lstXLSStyles.Items.Count > 0 then begin
if Index >= lstXLSStyles.Items.Count
then Index := lstXLSStyles.Items.Count - 1;
lstXLSStyles.Items[Index].Focused := true;
lstXLSStyles.Items[Index].Selected := true;
end;
XLSRenumStyles;
ActiveControl := lstXLSStyles;
XLSShowStyleButtons;
end;
end;
procedure TADO_QExportDialogF.tbtUpXLSStyleClick(Sender: TObject);
var
F: TxlsFormat;
Index: integer;
begin
Index := lstXLSStyles.Selected.Index;
F := TxlsFormat(lstXLSStyles.Items[Index - 1].Data);
lstXLSStyles.Items[Index - 1].Data := lstXLSStyles.Items[Index].Data;
lstXLSStyles.Items[Index].Data := F;
lstXLSStyles.Items[Index - 1].Focused := true;
lstXLSStyles.Items[Index - 1].Selected := true;
end;
procedure TADO_QExportDialogF.tbtDownXLSStyleClick(Sender: TObject);
var
F: TxlsFormat;
Index: integer;
begin
Index := lstXLSStyles.Selected.Index;
F := TxlsFormat(lstXLSStyles.Items[Index + 1].Data);
lstXLSStyles.Items[Index + 1].Data := lstXLSStyles.Items[Index].Data;
lstXLSStyles.Items[Index].Data := F;
lstXLSStyles.Items[Index + 1].Focused := true;
lstXLSStyles.Items[Index + 1].Selected := true;
end;
procedure TADO_QExportDialogF.rgXLSStripTypeClick(Sender: TObject);
begin
XLSStripType := TxlsStripStyle(rgXLSStripType.ItemIndex);
end;
procedure TADO_QExportDialogF.tbtSaveXLSStyleClick(Sender: TObject);
begin
if sdXLSStyle.Execute then
XLSSaveStyle(sdXLSStyle.FileName);
end;
procedure TADO_QExportDialogF.tbtLoadXLSStyleClick(Sender: TObject);
begin
if odXLSStyle.Execute then
XLSLoadStyle(odXLSStyle.FileName);
end;
procedure TADO_QExportDialogF.XLSExpBeforeExportRow(Sender: TObject;
Sheet: Integer; Row: TQExportRow; var Accept: Boolean);
begin
if Assigned(Dialog.OnBeforeExportXLSRow) then
Dialog.OnBeforeExportXLSRow(XLSExp, Sheet, Row, Accept);
end;
procedure TADO_QExportDialogF.XLSExpExportedRecord(Sender: TObject; Sheet,
RecNo: Integer);
begin
if Assigned(Dialog.OnExportedRecordXLS) then
Dialog.OnExportedRecordXLS(XLSExp, Sheet, RecNo);
{ if Assigned(FProgress) then begin
PostMessage(FProgress.Handle, WM_QEXPORT_PROGRESS, QEP_EXPORTED, 0);
Application.ProcessMessages;
end;}
end;
procedure TADO_QExportDialogF.XLSExpAdvancedGetExportText(Sender: TObject;
Sheet, ColNo: Integer; var Text: String);
begin
if Assigned(Dialog.OnGetExportXLSText) then
Dialog.OnGetExportXLSText(XLSExp, Sheet, ColNo, Text);
end;
procedure TADO_QExportDialogF.edAccessTableNameChange(Sender: TObject);
begin
AccessTableName := edAccessTableName.Text;
end;
procedure TADO_QExportDialogF.chAccessCreateTableClick(Sender: TObject);
begin
AccessCreateTable := chAccessCreateTable.Checked;
end;
procedure TADO_QExportDialogF.edHTMLIndexLinkTemplateChange(
Sender: TObject);
begin
HTMLIndexLinkTemplate := edHTMLIndexLinkTemplate.Text;
end;
procedure TADO_QExportDialogF.chHTMLNavigationOnTopClick(Sender: TObject);
begin
HTMLNavigationOnTop := chHTMLNavigationOnTop.Checked;
HTMLUpdateMultifileControls;
end;
procedure TADO_QExportDialogF.chHTMLNavigationOnBottomClick(
Sender: TObject);
begin
HTMLNavigationOnBottom := chHTMLNavigationOnBottom.Checked;
HTMLUpdateMultifileControls;
end;
procedure TADO_QExportDialogF.edHTMLIndexLinkTitleChange(Sender: TObject);
begin
HTMLIndexLinkTitle := edHTMLIndexLinkTitle.Text;
end;
procedure TADO_QExportDialogF.edHTMLFirstLinkTitleChange(Sender: TObject);
begin
HTMLFirstLinkTitle := edHTMLFirstLinkTitle.Text;
end;
procedure TADO_QExportDialogF.edHTMLPriorLinkTitleChange(Sender: TObject);
begin
HTMLPriorLinkTitle := edHTMLPriorLinkTitle.Text;
end;
procedure TADO_QExportDialogF.edHTMLNextLinkTitleChange(Sender: TObject);
begin
HTMLNextLinkTitle := edHTMLNextLinkTitle.Text;
end;
procedure TADO_QExportDialogF.edHTMLLastLinkTitleChange(Sender: TObject);
begin
HTMLLastLinkTitle := edHTMLLastLinkTitle.Text;
end;
procedure TADO_QExportDialogF.chHTMLUseMultiFileExportClick(
Sender: TObject);
begin
HTMLUseMultiFileExport := chHTMLUseMultiFileExport.Checked;
HTMLUpdateMultiFileControls;
end;
//--- PDF
procedure TADO_QExportDialogF.SetPDFColSpacing(const Value: double);
begin
if FPDFColSpacing <> Value then begin
FPDFColSpacing := Value;
edPDFColSpacing.Text := FormatFloat('0.0', PDFColSpacing);
end;
end;
procedure TADO_QExportDialogF.edPDFColSpacingChange(Sender: TObject);
begin
PDFColSpacing := StrToDblDef(edPDFColSpacing.Text,
Dialog.PDFOptions.ColSpacing);
end;
procedure TADO_QExportDialogF.SetPDFRowSpacing(const Value: double);
begin
if FPDFRowSpacing <> Value then begin
FPDFRowSpacing := Value;
edPDFRowSpacing.Text := FormatFloat('0.0', PDFRowSpacing);
end;
end;
procedure TADO_QExportDialogF.edPDFRowSpacingChange(Sender: TObject);
begin
PDFRowSpacing := StrToDblDef(edPDFRowSpacing.Text,
Dialog.PDFOptions.RowSpacing);
end;
procedure TADO_QExportDialogF.SetPDFGridLineWidth(const Value: integer);
begin
if FPDFGridLineWidth <> Value then begin
FPDFGridLineWidth := Value;
edPDFGridLineWidth.Text := IntToStr(PDFGridLineWidth);
end;
end;
procedure TADO_QExportDialogF.edPDFGridLineWidthChange(Sender: TObject);
begin
PDFGridLineWidth := StrToIntDef(edPDFGridLineWidth.Text,
Dialog.PDFOptions.GridLineWidth);
end;
function TADO_QExportDialogF.GetPDFPageSizeFormat: string;
begin
if FPDFPageUnits = unInch
then Result := '0.00'
else Result := '0';
end;
procedure TADO_QExportDialogF.SetPDFPageFormat(const Value: TQExportPageFormat);
begin
if FPDFPageFormat <> Value then begin
FPDFPageFormat := Value;
cbPDFPageFormat.ItemIndex := Integer(FPDFPageFormat);
if FPDFPageFormat <> pfUser then begin
FPDFPageWidth := InchToDot(GetPageFormatInchWidth(FPDFPageFormat));
edPDFPageWidth.Text := FormatFloat(GetPDFPageSizeFormat, PDFPageWidth);
FPDFPageHeight := InchToDot(GetPageFormatInchHeight(FPDFPageFormat));
edPDFPageHeight.Text := FormatFloat(GetPDFPageSizeFormat, PDFPageHeight);
end;
end;
end;
procedure TADO_QExportDialogF.cbPDFPageFormatChange(Sender: TObject);
begin
PDFPageFormat := TQExportPageFormat(cbPDFPageFormat.ItemIndex);
end;
function TADO_QExportDialogF.GetPDFPageWidth: double;
begin
Result := Dot2Units(FPDFPageUnits, FPDFPageWidth);
end;
procedure TADO_QExportDialogF.SetPDFPageWidth(const Value: double);
var
Dummy: integer;
begin
Dummy := Units2Dot(FPDFPageUnits, Value);
if FPDFPageWidth <> Dummy then begin
FPDFPageWidth := Dummy;
edPDFPageWidth.Text := FormatFloat(GetPDFPageSizeFormat, PDFPageWidth);
end;
PDFPageFormat := pfUser;
end;
procedure TADO_QExportDialogF.edPDFPageWidthExit(Sender: TObject);
begin
PDFPageWidth := StrToDblDef(edPDFPageWidth.Text, PDFPageWidth);
end;
function TADO_QExportDialogF.GetPDFPageHeight: double;
begin
Result := Dot2Units(FPDFPageUnits, FPDFPageHeight);
end;
procedure TADO_QExportDialogF.SetPDFPageHeight(const Value: double);
var
Dummy: integer;
begin
Dummy := Units2Dot(FPDFPageUnits, Value);
if FPDFPageHeight <> Dummy then begin
FPDFPageheight := Dummy;
edPDFPageHeight.Text := FormatFloat(GetPDFPageSizeFormat, PDFPageHeight);
end;
PDFPageFormat := pfUser;
end;
procedure TADO_QExportDialogF.edPDFPageHeightExit(Sender: TObject);
begin
PDFPageHeight := StrToDblDef(edPDFPageHeight.Text, PDFPageHeight);
end;
procedure TADO_QExportDialogF.SetPDFPageUnits(const Value: TQExportUnits);
begin
if FPDFPageUnits <> Value then begin
FPDFPageUnits := Value;
cbPDFPageUnits.ItemIndex := Integer(FPDFPageUnits);
edPDFPageWidth.Text := FormatFloat(GetPDFPageSizeFormat, PDFPageWidth);
edPDFPageHeight.Text := FormatFloat(GetPDFPageSizeFormat, PDFPageHeight);
edPDFPageMarginLeft.Text := FormatFloat(GetPDFPageSizeFormat,
PDFPageMarginLeft);
edPDFPageMarginRight.Text := FormatFloat(GetPDFPageSizeFormat,
PDFPageMarginRight);
edPDFPageMarginTop.Text := FormatFloat(GetPDFPageSizeFormat,
PDFPageMarginTop);
edPDFPageMarginBottom.Text := FormatFloat(GetPDFPageSizeFormat,
PDFPageMarginBottom);
end;
end;
procedure TADO_QExportDialogF.cbPDFPageUnitsChange(Sender: TObject);
begin
PDFPageUnits := TQExportUnits(cbPDFPageUnits.ItemIndex);
end;
procedure TADO_QExportDialogF.SetPDFPageOrientation(const Value:
TQExportPageOrientation);
var
Sz: TSize;
Rect: TRect;
begin
if FPDFPageOrientation <> Value then begin
FPDFPageOrientation := Value;
cbPDFPageOrientation.ItemIndex := Integer(FPDFPageOrientation);
Sz.cx := FPDFPageWidth;
Sz.cy := FPDFPageHeight;
FPDFPageWidth := Sz.cy;
FPDFPageHeight := Sz.cx;
Rect.Left := FPDFPageMarginLeft;
Rect.Right := FPDFPageMarginRight;
Rect.Top := FPDFPageMarginTop;
Rect.Bottom := FPDFPageMarginBottom;
if FPDFPageOrientation = poLandscape then begin
FPDFPageMarginLeft := Rect.Bottom;
FPDFPageMarginRight := Rect.Top;
FPDFPageMarginTop := Rect.Left;
FPDFPageMarginBottom := Rect.Right;
end
else begin
FPDFPageMarginLeft := Rect.Top;
FPDFPageMarginRight := Rect.Bottom;
FPDFPageMarginTop := Rect.Right;
FPDFPageMarginBottom := Rect.Left;
end;
edPDFPageWidth.Text := FormatFloat(GetPDFPageSizeFormat, PDFPageWidth);
edPDFPageHeight.Text := FormatFloat(GetPDFPageSizeFormat, PDFPageHeight);
edPDFPageMarginLeft.Text := FormatFloat(GetPDFPageSizeFormat,
PDFPageMarginLeft);
edPDFPageMarginRight.Text := FormatFloat(GetPDFPageSizeFormat,
PDFPageMarginRight);
edPDFPageMarginTop.Text := FormatFloat(GetPDFPageSizeFormat,
PDFPageMarginTop);
edPDFPageMarginBottom.Text := FormatFloat(GetPDFPageSizeFormat,
PDFPageMarginBottom);
end;
end;
procedure TADO_QExportDialogF.cbPDFPageOrientationChange(Sender: TObject);
begin
PDFPageOrientation := TQExportPageOrientation(cbPDFPageOrientation.ItemIndex);
end;
function TADO_QExportDialogF.GetPDFPageMarginLeft: double;
begin
Result := Dot2Units(FPDFPageUnits, FPDFPageMarginLeft);
end;
procedure TADO_QExportDialogF.SetPDFPageMarginLeft(const Value: double);
var
Dummy: integer;
begin
Dummy := Units2Dot(FPDFPageUnits, Value);
if FPDFPageMarginLeft <> Dummy then begin
FPDFPageMarginLeft := Dummy;
edPDFPageMarginLeft.Text := FormatFloat(GetPDFPageSizeFormat,
PDFPageMarginLeft);
end;
end;
procedure TADO_QExportDialogF.edPDFPageMarginLeftExit(Sender: TObject);
begin
PDFPageMarginLeft := StrToDblDef(edPDFPageMarginLeft.Text, PDFPageMarginLeft);
end;
function TADO_QExportDialogF.GetPDFPageMarginRight: double;
begin
Result := Dot2Units(FPDFPageUnits, FPDFPageMarginRight);
end;
procedure TADO_QExportDialogF.SetPDFPageMarginRight(const Value: double);
var
Dummy: integer;
begin
Dummy := Units2Dot(FPDFPageUnits, Value);
if FPDFPageMarginRight <> Dummy then begin
FPDFPageMarginRight := Dummy;
edPDFPageMarginRight.Text := FormatFloat(GetPDFPageSizeFormat,
PDFPageMarginRight);
end;
end;
procedure TADO_QExportDialogF.edPDFPageMarginRightExit(Sender: TObject);
begin
PDFPageMarginRight := StrToDblDef(edPDFPageMarginRight.Text,
PDFPageMarginRight);
end;
function TADO_QExportDialogF.GetPDFPageMarginTop: double;
begin
Result := Dot2Units(FPDFPageUnits, FPDFPageMarginTop);
end;
procedure TADO_QExportDialogF.SetPDFPageMarginTop(const Value: double);
var
Dummy: integer;
begin
Dummy := Units2Dot(FPDFPageUnits, Value);
if FPDFPageMarginTop <> Dummy then begin
FPDFPageMarginTop := Dummy;
edPDFPageMarginTop.Text := FormatFloat(GetPDFPageSizeFormat,
PDFPageMarginTop);
end;
end;
procedure TADO_QExportDialogF.edPDFPageMarginTopExit(Sender: TObject);
begin
PDFPageMarginTop := StrToDblDef(edPDFPageMarginTop.Text, PDFPageMarginTop);
end;
function TADO_QExportDialogF.GetPDFPageMarginBottom: double;
begin
Result := Dot2Units(FPDFPageUnits, FPDFPageMarginBottom);
end;
procedure TADO_QExportDialogF.SetPDFPageMarginBottom(const Value: double);
var
Dummy: integer;
begin
Dummy := Units2Dot(FPDFPageUnits, Value);
if FPDFPageMarginBottom <> Dummy then begin
FPDFPageMarginBottom := Dummy;
edPDFPageMarginBottom.Text := FormatFloat(GetPDFPageSizeFormat,
PDFPageMarginBottom);
end;
end;
procedure TADO_QExportDialogF.edPDFPageMarginBottomExit(Sender: TObject);
begin
PDFPageMarginBottom := StrToDblDef(edPDFPageMarginBottom.Text,
PDFPageMarginBottom);
end;
procedure TADO_QExportDialogF.PDFFillFontList;
begin
lvPDFFonts.Items.BeginUpdate;
try
lvPDFFonts.Items.Clear;
with lvPDFFonts.Items.Add do begin
Caption := QED_PDF_HeaderFont;
ImageIndex := 3;
Data := PDFExp.Options.HeaderFont;
end;
with lvPDFFonts.Items.Add do begin
Caption := QED_PDF_CaptionFont;
ImageIndex := 3;
Data := PDFExp.Options.CaptionFont;
end;
with lvPDFFonts.Items.Add do begin
Caption := QED_PDF_DataFont;
ImageIndex := 3;
Data := PDFExp.Options.DataFont;
end;
with lvPDFFonts.Items.Add do begin
Caption := QED_PDF_FooterFont;
ImageIndex := 3;
Data := PDFExp.Options.FooterFont;
end;
lvPDFFonts.Items[0].Focused := true;
lvPDFFonts.Items[0].Selected := true;
FPDFFontItem := lvPDFFonts.Items[0];
PDFShowFontInfo;
finally
lvPDFFonts.Items.EndUpdate;
end;
end;
procedure TADO_QExportDialogF.PDFShowFontInfo;
begin
if Assigned(FPDFFontItem) then begin
with TPDFFont(FPDFFontItem.Data) do begin
cbPDFFontName.ItemIndex := Integer(BaseFont);
paPDFSample.Font.Color := FontColor;
cbPDFFontEncoding.ItemIndex := Integer(FontEncoding);
edPDFFontSize.Text := IntToStr(FontSize);
end;
PDFShowExample;
end;
end;
procedure TADO_QExportDialogF.lvPDFFontsChange(Sender: TObject;
Item: TListItem; Change: TItemChange);
begin
if not ((Change = ctState) and Assigned(Item) and Assigned(Item.Data)) then Exit;
if Item <> FPDFFontItem then begin
FPDFFontItem := Item;
PDFShowFontInfo;
end;
end;
procedure TADO_QExportDialogF.cbPDFFontNameChange(Sender: TObject);
begin
TPDFFont(FPDFFontItem.Data).BaseFont := TPDFFontName(cbPDFFontName.ItemIndex);
PDFShowExample;
end;
procedure TADO_QExportDialogF.cbPDFFontEncodingChange(Sender: TObject);
begin
TPDFFont(FPDFFontItem.Data).FontEncoding :=
TPDFFontEncoding(cbPDFFontEncoding.ItemIndex);
end;
procedure TADO_QExportDialogF.edPDFFontSizeChange(Sender: TObject);
begin
TPDFFont(FPDFFontItem.Data).FontSize := StrToIntDef(edPDFFontSize.Text, 10);
PDFShowExample;
end;
procedure TADO_QExportDialogF.PDFShowExample;
var
FN: string;
begin
with TPDFFont(FPDFFontItem.Data) do begin
FN := AnsiUpperCase(cbPDFFontName.Text);
paPDFSample.Font.Color := FontColor;
paPDFSample.Font.Size := FontSize;
EditFontStyle(paPDFSample.Font, fsBold, Pos('BOLD', FN) > 0);
EditFontStyle(paPDFSample.Font, fsItalic,
(Pos('OBLIQUE', FN) > 0) or (Pos('ITALIC', FN) > 0));
if Pos('COURIER', FN) > 0 then
paPDFSample.Font.Name := 'Courier New'
else if Pos('TIMES', FN) > 0 then
paPDFSample.Font.Name := 'Times New Roman'
else if Pos('SYMBOL', FN) > 0 then
paPDFSample.Font.Name := 'Symbol'
else paPDFSample.Font.Name := 'Arial'
end;
end;
procedure TADO_QExportDialogF.sbPDFFontColorClick(Sender: TObject);
var
OldColor: TColor;
begin
OldColor := TPDFFont(FPDFFontItem.Data).FontColor;
ColorDialog.Color := OldColor;
if ColorDialog.Execute and (OldColor <> ColorDialog.Color) then begin
TPDFFont(FPDFFontItem.Data).FontColor := ColorDialog.Color;
PDFShowExample;
end;
end;
procedure TADO_QExportDialogF.bToolsClick(Sender: TObject);
var
Point: TPoint;
begin
Point.X := 0;
Point.Y := 0;
Point := bTools.ClientToScreen(Point);
pmTools.Popup(Point.X, Point.Y - pmTools.Items.Count * 25);
end;
procedure TADO_QExportDialogF.miSaveOptionsClick(Sender: TObject);
begin
sdOptions.FileName := OptionsFileName;
if sdOptions.Execute then begin
OptionsFileName := sdOptions.FileName;
SaveExportOptions(OptionsFileName);
end;
end;
procedure TADO_QExportDialogF.miLoadOptionsClick(Sender: TObject);
begin
odOptions.FileName := OptionsFileName;
if odOptions.Execute then begin
OptionsFileName := odOptions.FileName;
LoadExportOptions(odOptions.FileName);
end;
end;
function TADO_QExportDialogF.IsCompatiblePage: boolean;
begin
case ExportType of
aeXLS: Result := Pages.ActivePage.PageIndex in [tshExportType.PageIndex,
tshFields.PageIndex,
tshFormats.PageIndex,
tshHeaderFooter.PageIndex,
tshCaptions.PageIndex,
tshXLS.PageIndex];
aeAccess: Result := Pages.ActivePage.PageIndex in [tshExportType.PageIndex,
tshFields.PageIndex,
tshCaptions.PageIndex,
tshAccess.PageIndex];
aeWord,
aeRTF: Result := Pages.ActivePage.PageIndex in [tshExportType.PageIndex,
tshFields.PageIndex,
tshFormats.PageIndex,
tshHeaderFooter.PageIndex,
tshCaptions.PageIndex,
tshRTF.PageIndex];
aeHTML: Result := Pages.ActivePage.PageIndex in [tshExportType.PageIndex,
tshFields.PageIndex,
tshFormats.PageIndex,
tshHeaderFooter.PageIndex,
tshCaptions.PageIndex,
tshHTML.PageIndex];
aeXML: Result := Pages.ActivePage.PageIndex in [tshExportType.PageIndex,
tshFields.PageIndex,
tshFormats.PageIndex,
tshXML.PageIndex];
aeDBF: Result := Pages.ActivePage.PageIndex in [tshExportType.PageIndex,
tshFields.PageIndex];
aePDF: Result := Pages.ActivePage.PageIndex in [tshExportType.PageIndex,
tshFields.PageIndex,
tshFormats.PageIndex,
tshHeaderFooter.PageIndex,
tshCaptions.PageIndex,
tshPDF.PageIndex];
aeTXT,
aeCSV: Result := Pages.ActivePage.PageIndex in [tshExportType.PageIndex,
tshFields.PageIndex,
tshFormats.PageIndex,
tshHeaderFooter.PageIndex,
tshCaptions.PageIndex,
tshASCII.PageIndex];
aeDIFF,
aeSYLK,
aeLaTeX: Result := Pages.ActivePage.PageIndex in [tshExportType.PageIndex,
tshFields.PageIndex,
tshFormats.PageIndex,
tshHeaderFooter.PageIndex,
tshCaptions.PageIndex];
aeSQL: Result := Pages.ActivePage.PageIndex in [tshExportType.PageIndex,
tshFields.PageIndex,
tshHeaderFooter.PageIndex,
tshSQL.PageIndex];
aeClipboard: Result := Pages.ActivePage.PageIndex in [tshExportType.PageIndex,
tshFields.PageIndex,
tshFormats.PageIndex,
tshHeaderFooter.PageIndex,
tshCaptions.PageIndex];
else Result := false;
end;
end;
end.
|
// Copyright 2018 by John Kouraklis and Contributors. All Rights Reserved.
//
// 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 Casbin.Matcher.Types;
interface
uses
Casbin.Core.Base.Types, Casbin.Effect.Types;
type
IMatcher = interface (IBaseInterface)
['{7870739A-B58D-4127-8F29-F04482D5FCF3}']
function evaluateMatcher (const aMatcherString: string): TEffectResult;
procedure clearIdentifiers;
procedure addIdentifier (const aTag: string);
end;
implementation
end.
|
unit NTrView;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Mask,
CommCtrl, Dialogs, StdCtrls, Imglist, Extctrls, ComCtrls, Forms,
ClipBrd, NumTree;
const
NTVHorzSpace = 2;
NTVVertSpace = 1;
CheckBoxWidth = 13;
CheckBoxHeight = 13;
NTVChangeTimer = 111;
NTVSearchTimer = 112;
NTVShowHintTimer = 113;
NTVHideHintTimer = 114;
NTVDragScrollTimer = 115;
NTVDragExpandTimer = 116;
NTVSearchWaitTime = 1000;
NTVShowHintWaitTime = 400;
NTVHideHintWaitTime = 6000;
NTVDragScrollWaitTime = 150;
NTVDragExpandWaitTime = 500;
sCaretReturn = #13#10;
type
TNumTreeView=class;
TNTVEditor = class(TCustomMaskEdit)
private
FClickTime: Integer;
FTreeView:TNumTreeView;
procedure CMShowingChanged(var Message: TMessage); message CM_SHOWINGCHANGED;
protected
procedure CreateParams(var Params: TCreateParams); override;
procedure WndProc(var Message: TMessage); override;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure KeyPress(var Key: Char); override;
public
constructor Create(AOwner: TComponent); override;
procedure BoundsChanged;
procedure Hide;
procedure Invalidate;override;
procedure Show(const BR:TRect);
procedure SetFocus;override;
procedure SelectNone;
//function Visible: Boolean;
published
property AutoSelect;
property AutoSize;
property CharCase;
property EditMask;
property ImeMode;
property ImeName;
property MaxLength;
property ReadOnly;
property Text;
property OnChange;
property OnClick;
property OnDblClick;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
end;
TNumTreeState = (ntsNormal, ntsEditing, ntsNodeDown, ntsNodeDragging);
TNumTreeNodePos = (thpCaption,thpIcon,thpStateImage,thpCheckBox,thpIndent,thpSpace);
TNTVChangingNodeEnvet=procedure (Sender:TObject;ChgGroup:TNumberGroup;ChgIndex:Integer;var AllowChange:Boolean) of object;
TNTVChangeNodeEnvet=procedure (Sender:TObject;ChgGroup:TNumberGroup;ChgIndex:Integer) of object;
TNTVEditingNodeEvent=procedure (Sender:TObject;EditGroup:TNumberGroup;EditIndex:Integer;var AllowEdit:Boolean) of object;
TNTVEditNodeEvent=procedure (Sender:TObject;EditGroup:TNumberGroup;EditIndex:Integer;var EditText:string;var AllowUpdate:Boolean) of object;
TNTVDragNodeEvent=procedure (Sender:TObject;DragGroup:TNumberGroup;DragIndex:Integer;var AllowDrag:Boolean) of object;
TNTVDropOverNodeEvent=procedure (Sender:TObject;DragGroup,DropGroup:TNumberGroup;DragIndex,DropIndex:Integer;var AllowDrop:Boolean) of object;
TNTVDropNodeEvent=procedure (Sender:TObject;DragGroup,DropGroup:TNumberGroup;DragIndex,DropIndex:Integer) of object;
ENumTreeView=class(Exception);
TNumberTreeHacker=class(TNumberTree);
TNumTreeView=class(TCustomControl)
private
FAutoDrag: Boolean;
FAutoExpand: Boolean;
FBorderStyle: TBorderStyle;
FChangeDelay: Integer;
FCheckBoxes: Boolean;
FHotTrack: Boolean;
FImageChangeLink: TChangeLink;
FImages: TCustomImageList;
FStateImages: TCustomImageList;
FIndent: Integer;
FReadOnly: Boolean;
FRowSelect: Boolean;
FScrollBars: TScrollStyle;
FShowButtons: Boolean;
FShowStruct: Boolean;
FShowLines: Boolean;
FShowRoot: Boolean;
FToolTips: Boolean;
FRightClick: Boolean;
procedure SetAutoDrag(Value: Boolean);
procedure SetAutoExpand(Value: Boolean);
procedure SetBorderStyle(Value: TBorderStyle);
procedure SetChangeDelay(Value: Integer);
procedure SetCheckBoxes(Value: Boolean);
procedure SetHotTrack(Value: Boolean);
procedure SetImages(Value: TCustomImageList);
procedure SetStateImages(Value: TCustomImageList);
procedure SetIndent(Value: Integer);
procedure SetReadOnly(Value: Boolean);
procedure SetRightClick(const Value: Boolean);
procedure SetRowSelect(Value: Boolean);
procedure SetScrollBars(Value: TScrollStyle);
procedure SetShowButtons(Value: Boolean);
procedure SetShowLines(Value: Boolean);
procedure SetShowRoot(Value: Boolean);
procedure SetShowStruct(Value: Boolean);
procedure SetToolTips(Value: Boolean);
protected
procedure CreateParams(var Params: TCreateParams);override;
property AutoDrag: Boolean read FAutoDrag write SetAutoDrag default False;
property AutoExpand: Boolean read FAutoExpand write SetAutoExpand default False;
property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle default bsSingle;
property ChangeDelay: Integer read FChangeDelay write SetChangeDelay default 0;
property CheckBoxes: Boolean read FCheckBoxes write SetCheckBoxes default False;
property HotTrack: Boolean read FHotTrack write SetHotTrack default False;
property Images: TCustomImageList read FImages write SetImages;
property StateImages: TCustomImageList read FStateImages write SetStateImages;
property Indent: Integer read FIndent write SetIndent default 19;
property ReadOnly: Boolean read FReadOnly write SetReadOnly default True;
property RightClick: Boolean read FRightClick write SetRightClick default False;
property RowSelect: Boolean read FRowSelect write SetRowSelect default False;
property ScrollBars: TScrollStyle read FScrollBars write SetScrollBars default ssBoth;
property ShowButtons: Boolean read FShowButtons write SetShowButtons default True;
property ShowLines: Boolean read FShowLines write SetShowLines default True;
property ShowRoot: Boolean read FShowRoot write SetShowRoot default True;
property ShowStruct: Boolean read FShowStruct write SetShowStruct default True;
property ToolTips: Boolean read FToolTips write SetToolTips default True;
private
FState:TNumTreeState;
FUpdateCount:Integer;
FFontHeight:Integer;
FLeftOffset,FMaxCaption:Integer;
FRowHeight:Integer;
FViewCount,FShowCount:Integer;
FTopRow:Integer;
FTopIndex:Integer;
FTopGroup:TNumberGroup;
FCurRow:Integer;
FCurIndex:Integer;
FCurGroup:TNumberGroup;
FCurChildren:TNumberGroup;
FSearching:Boolean;
FSearchText:string;
FSaveRow:Integer;
FSaveIndex:Integer;
FSaveGroup:TNumberGroup;
FSaveChildren:TNumberGroup;
FRightClickGroup:TNumberGroup;
FRightClickIndex:Integer;
FChangeTimer:Integer;
FHintWindow: THintWindow;
FShowHintTimer:Integer;
FHideHintTimer:Integer;
FSearchTimer:Integer;
FEditor:TNTVEditor;
FHotGroup:TNumberGroup;
FHotIndex:Integer;
// DragDrop
FDragObject: TDragObject;
FDragImageList: TDragImageList;
FDragGroup: TNumberGroup;
FDragIndex: Integer;
FDragPos: TPoint;
FDragSaveoffset: Integer;
FDragSaveTopRow: Integer;
FDragOverGroup: TNumberGroup;
FDragOverIndex: Integer;
FDragScrollTimer: Integer;
FDragScrollDelta: Integer;
FDragExpandTimer: Integer;
FOnChanging:TNTVChangingNodeEnvet;
FOnChange:TNTVChangeNodeEnvet;
FOnEditingNode:TNTVEditingNodeEvent;
FOnEditNode:TNTVEditNodeEvent;
FOnDragNode:TNTVDragNodeEvent;
FOnDragNodeOver:TNTVDropOverNodeEvent;
FOnDropNode:TNTVDropNodeEvent;
procedure CMCancelMode(var Msg: TMessage); message CM_CANCELMODE;
procedure CMCtl3DChanged(var Message: TMessage); message CM_CTL3DCHANGED;
procedure CMDrag(var Message: TCMDrag); message CM_DRAG;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER;
procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
procedure CMWantSpecialKey(var Msg: TCMWantSpecialKey); message CM_WANTSPECIALKEY;
procedure WMCancelMode(var Msg: TMessage); message WM_CANCELMODE;
procedure WMDestroy(var Msg: TWMDestroy); message WM_DESTROY;
procedure WMGetDlgCode(var Msg: TWMGetDlgCode); message WM_GETDLGCODE;
procedure WMHScroll(var Msg: TWMHScroll); message WM_HSCROLL;
procedure WMIMEStartComp(var Message: TMessage); message WM_IME_STARTCOMPOSITION;
procedure WMKillFocus(var Msg: TWMKillFocus); message WM_KILLFOCUS;
procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN;
procedure WMMouseWheel(var Message: TWMMouseWheel); message WM_MOUSEWHEEL;
procedure WMNCHitTest(var Msg: TWMNCHitTest); message WM_NCHITTEST;
procedure WMSetCursor(var Msg: TWMSetCursor); message WM_SETCURSOR;
procedure WMSetFocus(var Msg: TWMSetFocus); message WM_SETFOCUS;
procedure WMSize(var Msg: TWMSize); message WM_SIZE;
procedure WMTimer(var Msg: TWMTimer); message WM_TIMER;
procedure WMVScroll(var Msg: TWMVScroll); message WM_VSCROLL;
function GetCaptionWidth(const Caption:string):Integer;
procedure SetLeftOffset(const Value:Integer);
procedure SetTopRow(const Value:Integer);
procedure SetCurRow(Value:Integer);
procedure CheckCurrentHidden(CollapseGroup:TNumberGroup);
procedure OnNodeChange(ChgGroup:TNumberGroup;ChgIndex:Integer);
procedure OnNodeInsert(ChgGroup:TNumberGroup;ChgIndex:Integer);
procedure OnNodeDelete(ChgGroup:TNumberGroup;ChgIndex:Integer);
procedure DoTreeShowChange(ChgGroup:TNumberGroup;ChgIndex:Integer);
protected
FHitTest: TPoint;
procedure Paint;override;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure KeyPress(var Key: Char); 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;
procedure ChangeImmediate;
procedure FreeChangeTimer;
procedure ImageListChange(Sender:TObject);
procedure ShowHint(Immediate:Boolean);
procedure CancelHintShow;
procedure ShowEditor;
procedure HideEditor(Update:Boolean);
procedure DoChange;dynamic;
procedure ResetSearchTimer;
procedure StartSearch(ClearSearch:Boolean);
procedure DoSearch(const SearchText:string;UpSearch:Boolean);
procedure EndSearch;
procedure CheckHotTrackPos(const X,Y:Integer);
procedure HideHotTrack();
procedure CancelMode;
// DragDrop Nodes
function IsTopNode(Group:TNumberGroup;Index:Integer): Boolean;
function IsLastNode(Group:TNumberGroup;Index:Integer): Boolean;
procedure SetDragObject(Value: TDragObject);
procedure UpdateDragging;
procedure RestoreDragOverTop;
function DoBeginDragNode(Group:TNumberGroup;Index:Integer):Boolean; virtual;
procedure DoEndDrag(Target: TObject; X, Y: Integer); override;
procedure DoStartDrag(var DragObject: TDragObject); override;
procedure DragOver(Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); override;
procedure CreateDragNodeImage(Group:TNumberGroup;Index:Integer); virtual;
function GetDragImages: TDragImageList; override;
procedure DoCheckNode(NodeGroup:TNumberGroup;NodeIndex:Integer;ShiftDown:Boolean);
procedure UpdateScrollRange;
procedure UpdateHorzScrollRange;
procedure UpdateVertScrollRange;
procedure UpdateHorzScrollPos;
procedure UpdateVertScrollPos;
function DrawRoot():Boolean;
procedure DrawTreeNode(const RowRect:TRect;NodeGroup:TNumberGroup;NodeIndex:Integer);virtual;
property OnChanging:TNTVChangingNodeEnvet read FOnChanging write FOnChanging;
property OnChange:TNTVChangeNodeEnvet read FOnChange write FOnChange;
property OnEditingNode:TNTVEditingNodeEvent read FOnEditingNode write FOnEditingNode;
property OnEditNode:TNTVEditNodeEvent read FOnEditNode write FOnEditNode;
property OnDragNode:TNTVDragNodeEvent read FOnDragNode write FOnDragNode;
property OnDragNodeOver:TNTVDropOverNodeEvent read FOnDragNodeOver write FOnDragNodeOver;
property OnDropNode:TNTVDropNodeEvent read FOnDropNode write FOnDropNode;
//property On:T read F write F;
public
property TopRow:Integer read FTopRow write SetTopRow;
property RowHeight:Integer read FRowHeight;
property ViewCount:Integer read FViewCount;
property ShowCount:Integer read FShowCount;
property LeftOffset:Integer read FLeftOffset write SetLeftOffset;
property CurRow:Integer read FCurRow write SetCurRow;
property CurIndex:Integer read FCurIndex;
property CurGroup:TNumberGroup read FCurGroup;
property CurChildren:TNumberGroup read FCurChildren;
property RightClickGroup:TNumberGroup read FRightClickGroup;
property RightClickIndex:Integer read FRightClickIndex;
private
FNumTree: TNumberTree;
procedure SetNumTree(Value:TNumberTree);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Updating:Boolean;reintroduce;
procedure BeginUpdate;
procedure EndUpdate;
function SetCurrent(NodeGroup:TNumberGroup;NodeIndex:Integer):Boolean;
function SetCurrentNode(NumNode:TNumberNode):Boolean;
function GetTextRect(NodeGroup:TNumberGroup;NodeIndex:Integer):TRect;
function GetNodeRect(NodeGroup:TNumberGroup;NodeIndex:Integer;FullRow:Boolean=False):TRect;
procedure UpdateNode(NodeGroup:TNumberGroup;NodeIndex:Integer;FullRow:Boolean=False);
procedure UpdateCurrent;
procedure ScrollInView(NodeGroup:TNumberGroup;NodeIndex:Integer;ShowIndex:Integer=-1);
procedure ScrollCurChildrenInView;
function GetHitPos(X,Y:Integer;var NodeGroup:TNumberGroup;var NodeIndex:Integer;var HitPos:TNumTreeNodePos):Boolean;
function FindNodeAt(X,Y:Integer;var NodeGroup:TNumberGroup;var NodeIndex:Integer):Boolean;
procedure CollapseBrothers(AGroup:TNumberGroup;AIndex:Integer);
procedure DragDrop(Source: TObject; X, Y: Integer); override;
property Canvas;
property Editor:TNTVEditor read FEditor;
property NumTree:TNumberTree read FNumTree write SetNumTree;
protected
procedure GetNodeString(NodeID:LongInt;NodeGroup,SubNodes:TNumberGroup;Param:Integer);
public
procedure ListTreeStrings(OutStrings:TStrings;ListRoot:TNumberGroup=nil;
RankLmt:Integer=0;Expand:Boolean=True);
end;
TFTreeView=class(TNumTreeView)
published
property Align;
property AutoDrag;
property AutoExpand;
property BorderStyle;
property ChangeDelay;
property CheckBoxes;
property Color;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property Font;
property HotTrack;
property Images;
property Indent;
property ParentBiDiMode;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ReadOnly;
property RightClick;
property RowSelect;
property ScrollBars;
property ShowButtons;
property ShowLines;
property ShowRoot;
property StateImages;
property ToolTips;
property ShowStruct;
property OnChanging;
property OnChange;
property OnEditingNode;
property OnEditNode;
property OnDragNode;
property OnDropNode;
property OnDragNodeOver;
property OnClick;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheelDown;
property OnMouseWheelUp;
property OnStartDock;
property OnStartDrag;
end;
procedure DrawTreeViewLine(DC:HDC;DrawRect:TRect);overload;
procedure DrawTreeViewLine(DC:HDC;DrawRect:TRect;HasButton,IsLast:Boolean);overload;
procedure DrawTreeViewButton(DC:HDC;DrawRect:TRect;Expanded:Boolean);
implementation
procedure DrawTreeViewButton(DC:HDC;DrawRect:TRect;Expanded:Boolean);
var
X,Y,I,M,B:Integer;
begin
X:=(DrawRect.Left+DrawRect.Right+1) div 2;
Y:=(DrawRect.Top+DrawRect.Bottom+1) div 2;
B:=DrawRect.Right-X-1;
I:=DrawRect.Bottom-Y-1;
if(I<B)then B:=I;
B:=B*2 div 3;B:=B and not $1;
for I:=X-B to X+B do
begin
Windows.SetPixel(DC, I, Y-B, clGray);
Windows.SetPixel(DC, I, Y+B, clGray);
end;
for I:=Y-B+1 to Y+B-1 do
begin
Windows.SetPixel(DC, X-B, I, clGray);
Windows.SetPixel(DC, X+B, I, clGray);
end;
if(B<7)then begin
M:=B*2 div 3;
for I:=X-M to X+M do
Windows.SetPixel(DC, I, Y, clBlack);
if(Expanded)then Exit;
for I:=Y-M to Y+M do
Windows.SetPixel(DC, X, I, clBlack);
end else begin
M:=B*2 div 3;
for I:=X-M to X+M do
if(I<>X)then begin
Windows.SetPixel(DC, I, Y-1, clBlack);
Windows.SetPixel(DC, I, Y+1, clBlack);
end;
Windows.SetPixel(DC, X-M, Y, clBlack);
Windows.SetPixel(DC, X+M, Y, clBlack);
if(Expanded)then
begin
Windows.SetPixel(DC, X, Y-1, clBlack);
Windows.SetPixel(DC, X, Y+1, clBlack);
Exit;
end;
for I:=Y-M to Y+M do
if(I<>Y)then begin
Windows.SetPixel(DC, X-1, I, clBlack);
Windows.SetPixel(DC, X+1, I, clBlack);
end;
Windows.SetPixel(DC, X, Y-M, clBlack);
Windows.SetPixel(DC, X, Y+M, clBlack);
end;
end;
procedure DrawTreeViewLine(DC:HDC;DrawRect:TRect);
var
I,X,Y:Integer;
begin
X:=(DrawRect.Left+DrawRect.Right+1) div 2;
Y:=(DrawRect.Top+DrawRect.Bottom+1) div 2;
I:=Y;
while(I>=DrawRect.Top)do
begin
Windows.SetPixel(DC, X, I, clGray);
Dec(I,2);
end;
I:=Y+2;
while(I<DrawRect.Bottom)do
begin
Windows.SetPixel(DC, X, I, clGray);
Inc(I,2);
end;
end;
procedure DrawTreeViewLine(DC:HDC;DrawRect:TRect;HasButton,IsLast:Boolean);
var
X,Y,I,B:Integer;
begin
X:=(DrawRect.Left+DrawRect.Right+1) div 2;
Y:=(DrawRect.Top+DrawRect.Bottom+1) div 2;
B:=DrawRect.Right-X-1;
I:=DrawRect.Bottom-Y-1;
if(I<B)then B:=I;
B:=B*2 div 3;B:=B and not $1;
I:=X;
while(I<DrawRect.Right)do
begin
if(not HasButton)or(I-X>B)then
Windows.SetPixel(DC, I, Y, clGray);
Inc(I,2);
end;
I:=Y-2;
while(I>=DrawRect.Top)do
begin
if(not HasButton)or(Y-I>B)then
Windows.SetPixel(DC, X, I, clGray);
Dec(I,2);
end;
if(IsLast)then Exit;
I:=Y+2;
while(I<DrawRect.Bottom)do
begin
if(not HasButton)or(I-Y>B)then
Windows.SetPixel(DC, X, I, clGray);
Inc(I,2);
end;
end;
type
TWinControlHacker=class(TWinControl);
function IsActiveControl(Ctrl:TWinControl): Boolean;
var
H: Hwnd;
begin
Result := False;
begin
H := GetFocus;
while IsWindow(H) and (Result = False) do
begin
if H = TWinControlHacker(Ctrl).WindowHandle then
Result := True
else
H := GetParent(H);
end;
end;
end;
{ TNTVEditor }
constructor TNTVEditor.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
BorderStyle := bsSingle;
Ctl3D := False;
ControlStyle := ControlStyle+[csNoDesignVisible];
ParentCtl3D := False;
TabStop := False;
Visible := False;
end;
procedure TNTVEditor.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
Params.Style := Params.Style or ES_MULTILINE;
end;
procedure TNTVEditor.CMShowingChanged(var Message: TMessage);
begin
{ Ignore showing using the Visible property }
end;
procedure TNTVEditor.WndProc(var Message: TMessage);
begin
case Message.Msg of
WM_SETFOCUS:
begin
if(GetParentForm(Self)=nil)or(GetParentForm(Self).SetFocusedControl(FTreeView))then Dispatch(Message);
Exit;
end;
WM_LBUTTONDOWN:
begin
if GetMessageTime - FClickTime < Integer(GetDoubleClickTime) then
Message.Msg := WM_LBUTTONDBLCLK;
FClickTime := 0;
end;
end;
inherited WndProc(Message);
end;
procedure TNTVEditor.KeyDown(var Key: Word; Shift: TShiftState);
procedure SendToParent;
begin
FTreeView.KeyDown(Key, Shift);
Key := 0;
end;
procedure ParentEvent;
var
OnKeyDown: TKeyEvent;
begin
OnKeyDown := FTreeView.OnKeyDown;
if Assigned(OnKeyDown) then OnKeyDown(FTreeView, Key, Shift);
end;
begin
case Key of
VK_UP, VK_DOWN, VK_PRIOR, VK_NEXT, VK_ESCAPE, VK_RETURN: SendToParent;
VK_INSERT:
if Shift = [] then SendToParent;
VK_F2:
begin
ParentEvent;
if Key = VK_F2 then
begin
SelectNone;
Exit;
end;
end;
VK_TAB: if not (ssAlt in Shift) then SendToParent;
end;
if Key <> 0 then
begin
ParentEvent;
inherited KeyDown(Key, Shift);
end;
end;
procedure TNTVEditor.KeyPress(var Key: Char);
begin
inherited KeyPress(Key);
{if(Key=#13)then FTreeView.HideEditor(True) else
if(Key=#27)then FTreeView.HideEditor(False);}
end;
procedure TNTVEditor.BoundsChanged;
var
TR: TRect;
begin
TR := Rect(2, 2, Width - 2, Height);
SendMessage(Handle, EM_SETRECTNP, 0, LongInt(@TR));
SendMessage(Handle, EM_SCROLLCARET, 0, 0);
end;
procedure TNTVEditor.Hide;
begin
if HandleAllocated and IsWindowVisible(Handle) then
begin
Invalidate;
SetWindowPos(Handle, 0, 0, 0, 0, 0, SWP_HIDEWINDOW or SWP_NOZORDER or
SWP_NOREDRAW);
if Focused then Windows.SetFocus(FTreeView.Handle);
end;
end;
procedure TNTVEditor.Invalidate;
var
Client: TRect;
begin
ValidateRect(Handle, nil);
InvalidateRect(Handle, nil, True);
Windows.GetClientRect(Handle, Client);
MapWindowPoints(Handle, FTreeView.Handle, Client, 2);
ValidateRect(FTreeView.Handle, @Client);
InvalidateRect(FTreeView.Handle, @Client, False);
end;
procedure TNTVEditor.SelectNone;
begin
SendMessage(Handle, EM_SETSEL, $7FFFFFFF, Longint($FFFFFFFF));
end;
procedure TNTVEditor.SetFocus;
begin
if IsWindowVisible(Handle) then
Windows.SetFocus(Handle);
end;
procedure TNTVEditor.Show(const BR:TRect);
begin
if IsRectEmpty(BR) then Hide
else begin
CreateHandle;
SetWindowPos(Handle,HWND_TOP,
BR.Left,BR.Top,BR.Right-BR.Left,BR.Bottom-BR.Top,
SWP_SHOWWINDOW or SWP_NOREDRAW);
BoundsChanged;
if FTreeView.Focused then
Windows.SetFocus(Handle);
Invalidate;
end;
end;
{ TNumTreeView }
constructor TNumTreeView.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle - [csCaptureMouse] + [csDisplayDragImage];
Width := 121;
Height := 97;
TabStop := True;
ParentColor := False;
FBorderStyle := bsSingle;
FDragSaveTopRow := -1;
FIndent := 19;
FReadOnly := True;
FScrollBars := ssBoth;
FShowButtons := True;
FShowStruct := True;
FShowLines := True;
FShowRoot := True;
FToolTips := True;
FImageChangeLink := TChangeLink.Create;
FImageChangeLink.OnChange := ImageListChange;
end;
destructor TNumTreeView.Destroy;
begin
CancelHintShow;
NumTree:=nil;
FreeAndNil(FHintWindow);
FStateImages:=nil;
FImageChangeLink:=nil;
FImageChangeLink.Free;
inherited Destroy;
end;
procedure TNumTreeView.SetAutoDrag(Value: Boolean);
begin
if FAutoDrag <> Value then
begin
FAutoDrag := Value;
end;
end;
procedure TNumTreeView.SetAutoExpand(Value: Boolean);
begin
if FAutoExpand <> Value then
begin
FAutoExpand := Value;
end;
end;
procedure TNumTreeView.SetBorderStyle(Value: TBorderStyle);
begin
if FBorderStyle <> Value then
begin
FBorderStyle := Value;
RecreateWnd;
end;
end;
procedure TNumTreeView.SetChangeDelay(Value: Integer);
begin
if FChangeDelay <> Value then
begin
FChangeDelay := Value;
end;
end;
procedure TNumTreeView.SetCheckBoxes(Value: Boolean);
begin
if FCheckBoxes <> Value then
begin
FCheckBoxes := Value;
UpdateScrollRange;
end;
end;
procedure TNumTreeView.SetHotTrack(Value: Boolean);
begin
if FHotTrack <> Value then
begin
FHotTrack := Value;
UpdateNode(FHotGroup,FHotIndex);
end;
end;
procedure TNumTreeView.SetImages(Value: TCustomImageList);
begin
if Images <> nil then
Images.UnRegisterChanges(FImageChangeLink);
FImages := Value;
if Images <> nil then
begin
Images.RegisterChanges(FImageChangeLink);
Images.FreeNotification(Self);
end;
UpdateScrollRange;
end;
procedure TNumTreeView.SetStateImages(Value: TCustomImageList);
begin
if StateImages <> nil then
StateImages.UnRegisterChanges(FImageChangeLink);
FStateImages := Value;
if StateImages <> nil then
begin
StateImages.RegisterChanges(FImageChangeLink);
StateImages.FreeNotification(Self);
end;
UpdateScrollRange;
end;
procedure TNumTreeView.SetIndent(Value: Integer);
begin
if(FIndent<>Value)and(Value>0)then
begin
FIndent := Value;
Invalidate;
UpdateScrollRange;
end;
end;
procedure TNumTreeView.SetReadOnly(Value: Boolean);
begin
if FReadOnly <> Value then
begin
FReadOnly := Value;
end;
end;
procedure TNumTreeView.SetRightClick(const Value: Boolean);
begin
if FRightClick <> Value then
begin
FRightClick := Value;
if(FRightClickGroup<>nil)then
begin
UpdateNode(FRightClickGroup,FRightClickIndex);
FRightClickGroup:=nil;
end;
end;
end;
procedure TNumTreeView.SetRowSelect(Value: Boolean);
begin
if FRowSelect <> Value then
begin
if(FRowSelect)then UpdateCurrent;
FRowSelect := Value;
if(FRowSelect)then UpdateCurrent;
end;
end;
procedure TNumTreeView.SetScrollBars(Value: TScrollStyle);
begin
if FScrollBars <> Value then
begin
FScrollBars := Value;
RecreateWnd;
end;
end;
procedure TNumTreeView.SetShowButtons(Value: Boolean);
begin
if FShowButtons <> Value then
begin
FShowButtons := Value;
Invalidate;
UpdateScrollRange;
end;
end;
procedure TNumTreeView.SetShowStruct(Value: Boolean);
begin
if FShowStruct <> Value then
begin
FShowStruct := Value;
end;
end;
procedure TNumTreeView.SetShowLines(Value: Boolean);
begin
if FShowLines <> Value then
begin
FShowLines := Value;
Invalidate;
UpdateScrollRange;
end;
end;
procedure TNumTreeView.SetShowRoot(Value: Boolean);
begin
if FShowRoot <> Value then
begin
FShowRoot := Value;
Invalidate;
UpdateScrollRange;
end;
end;
procedure TNumTreeView.SetToolTips(Value: Boolean);
begin
if FToolTips <> Value then
begin
FToolTips := Value;
end;
end;
procedure TNumTreeView.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
with Params do
begin
WindowClass.style:=CS_DBLCLKS;
if FBorderStyle = bsSingle then
begin
if(NewStyleControls and Ctl3D)then
begin
Style:=Style and not WS_BORDER;
ExStyle:=ExStyle or WS_EX_CLIENTEDGE;
end else
Style:=Style or WS_BORDER;
end;
if FScrollBars in [ssVertical, ssBoth] then Style := Style or WS_VSCROLL;
if FScrollBars in [ssHorizontal, ssBoth] then Style := Style or WS_HSCROLL;
end;
end;
procedure TNumTreeView.ChangeImmediate;
begin
if(FChangeTimer<>0)then
begin
KillTimer(Handle,FChangeTimer);
FChangeTimer:=0;
DoChange;
end;
end;
procedure TNumTreeView.FreeChangeTimer;
begin
if(FChangeTimer<>0)then
begin
KillTimer(Handle,FChangeTimer);
FChangeTimer:=0;
end;
end;
procedure TNumTreeView.ImageListChange(Sender:TObject);
begin
if(HandleAllocated)and((Sender=Images)or(Sender=StateImages))then
UpdateScrollRange();
end;
procedure TNumTreeView.ShowHint(Immediate:Boolean);
var
Pt,cPt:TPoint;
ShowRect:TRect;
NodeHint:string;
Count,Index:Integer;
Children,Group:TNumberGroup;
begin
CancelHintShow;
if(FState=ntsNodeDragging)then Exit;
if(not ToolTips)and(not ShowStruct)then Exit;
if(not Immediate)then
FShowHintTimer:=SetTimer(Handle,NTVShowHintTimer,NTVShowHintWaitTime,nil)
else begin
GetCursorPos(Pt);
cPt:=ScreenToClient(Pt);
if(not FindNodeAt(cPt.X,cPt.Y,Group,Index))then Exit;
if(FHintWindow=nil)then
begin
FHintWindow:=THintWindow.Create(nil);
FHintWindow.Color:=clInfoBk;
end;
if(ToolTips)then
NodeHint:=FNumTree.GetNodeHint(Group.Child[Index])
else NodeHint:='';
if(ShowStruct)then
begin
Children:=Group.GetChildGroup(Index);
if(Children<>nil)then
begin
if(NodeHint<>'')then NodeHint:=NodeHint+sCaretReturn;
Count:=Children.GetFamilyCount();
if(Count=Children.Count)then
NodeHint:=NodeHint+Format('>%d',[Count])
else
NodeHint:=NodeHint+Format('>%d>%d',[Children.Count,Count]);
end;
end;
ShowRect:=FHintWindow.CalcHintRect(Screen.DesktopWidth,NodeHint,nil);
OffsetRect(ShowRect,Pt.X+20,Pt.Y);
FHintWindow.ActivateHint(ShowRect,NodeHint);
FHideHintTimer:=SetTimer(Handle,NTVHideHintTimer,NTVHideHintWaitTime,nil);
end;
end;
procedure TNumTreeView.CancelHintShow;
begin
if(FShowHintTimer<>0)then
begin
KillTimer(Handle,FShowHintTimer);
FShowHintTimer:=0;
end;
if(FHideHintTimer<>0)then
begin
KillTimer(Handle,FHideHintTimer);
FHideHintTimer:=0;
end;
if(FHintWindow<>nil)then
begin
SetWindowPos(FHintWindow.Handle,0,0,0,0,0,
SWP_HIDEWINDOW or SWP_NOACTIVATE or SWP_NOZORDER or SWP_NOSIZE or SWP_NOMOVE);
FHintWindow.Hide;
end;
end;
procedure TNumTreeView.ShowEditor;
var
OX:Integer;
Allow:Boolean;
NodeRect:TRect;
begin
if(FState<>ntsNormal)or(ReadOnly)or(FCurGroup=nil)then Exit;
Allow:=True;
if(Assigned(OnEditingNode))then OnEditingNode(Self,FCurGroup,FCurIndex,Allow);
if(not Allow)then Exit;
ScrollInView(FCurGroup,FCurIndex,FCurRow);
if(FEditor=nil)then
begin
FEditor:=TNTVEditor.Create(Self);
FEditor.FTreeView:=Self;
FEditor.Parent:=Self;
end;
FEditor.Text:=FNumTree.GetNodeCaption(FCurGroup.Child[FCurIndex]);
NodeRect:=GetTextRect(FCurGroup,FCurIndex);
Inc(NodeRect.Right,FFontHeight);
if(NodeRect.Right>ClientWidth)then
begin
OX:=NodeRect.Right-ClientWidth;
if(OX>NodeRect.Left)then OX:=NodeRect.Left;
LeftOffset:=LeftOffset+OX;
Dec(NodeRect.Left,OX);
Dec(NodeRect.Right,OX);
end;
if(NodeRect.Right-NodeRect.Left>ClientWidth)then
NodeRect.Right:=NodeRect.Left+ClientWidth;
FEditor.Show(NodeRect);
FEditor.SelectAll;
FState:=ntsEditing;
end;
procedure TNumTreeView.HideEditor(Update:Boolean);
var
NewCaption:string;
AllowUpdate:Boolean;
begin
if(FEditor=nil)then Exit;
FState:=ntsNormal;
FEditor.Hide;
if(Update)and(FEditor.Modified)and(FCurGroup<>nil)then
begin
NewCaption:=FEditor.Text;
AllowUpdate:=True;
if(Assigned(OnEditNode))then OnEditNode(Self,FCurGroup,FCurIndex,NewCaption,AllowUpdate);
if(AllowUpdate)then
FNumTree.SetNodeCaption(FCurGroup.Child[FCurIndex],NewCaption);
end;
end;
procedure TNumTreeView.CheckHotTrackPos(const X,Y:Integer);
var
Index:Integer;
Group:TNumberGroup;
begin
Group:=nil;
if(not FindNodeAt(X,Y,Group,Index))then Group:=nil;
if(Group<>FHotGroup)or(Index<>FHotIndex)then
begin
if(HotTrack)and(FHotGroup<>nil)then UpdateNode(FHotGroup,FHotIndex);
FHotGroup:=Group;FHotIndex:=Index;
if(HotTrack)and(FHotGroup<>nil)then UpdateNode(FHotGroup,FHotIndex);
end;
end;
procedure TNumTreeView.HideHotTrack();
begin
if(FHotGroup<>nil)then UpdateNode(FHotGroup,FHotIndex);
FHotGroup:=nil;
end;
procedure TNumTreeView.CancelMode;
begin
try
case FState of
ntsEditing:
begin
HideEditor(False);
end;
ntsNodeDown:
begin
end;
ntsNodeDragging:
begin
EndDrag(False);
end;
end;
CancelHintShow;
finally
FState := ntsNormal;
end;
end;
procedure TNumTreeView.CMCancelMode(var Msg: TMessage);
begin
inherited;
if(Msg.LParam<>Integer(Self))and(Msg.LParam<>Integer(FEditor))then
CancelMode;
end;
procedure TNumTreeView.CMCtl3DChanged(var Message: TMessage);
begin
inherited;
RecreateWnd;
end;
procedure TNumTreeView.CMDrag(var Message: TCMDrag);
begin
DragCursor := crDrag;
inherited;
with Message, DragRec^ do
case DragMessage of
dmDragEnter: SetDragObject(TDragObject(Source));
dmDragLeave,
dmDragDrop: SetDragObject(nil);
end;
end;
procedure TNumTreeView.SetDragObject(Value: TDragObject);
var
PrevDragObject: TDragObject;
begin
if FDragObject <> Value then
begin
PrevDragObject := FDragObject;
FDragObject := Value;
if (FDragObject = nil) and (PrevDragObject <> nil) then
PrevDragObject.HideDragImage;
UpdateDragging;
if (FDragObject <> nil) then
FDragObject.ShowDragImage;
end;
if (FDragObject = nil) and (FDragOverGroup <> nil) then
begin
if(FDragOverGroup<>nil)then UpdateNode(FDragOverGroup,FDragOverIndex);
FDragOverGroup := nil;
end;
end;
procedure TNumTreeView.UpdateDragging;
begin
UpdateWindow(Handle);
end;
procedure TNumTreeView.RestoreDragOverTop;
var
SaveTop:Integer;
begin
if(FDragSaveTopRow>=0)then
begin
if (FDragObject <> nil) then FDragObject.HideDragImage;
SaveTop:=FDragSaveTopRow;
FDragSaveTopRow:=-1;
LeftOffset:=FDragSaveoffset;
TopRow:=SaveTop;
end;
end;
function TNumTreeView.DoBeginDragNode(Group:TNumberGroup;Index:Integer):Boolean;
begin
Result:=DragKind=dkDrag;
if(Assigned(OnDragNode))then OnDragNode(Self,Group,Index,Result);
end;
procedure TNumTreeView.DoEndDrag(Target: TObject; X, Y: Integer);
begin
inherited DoEndDrag(Target, X, Y);
FDragGroup:=nil;
SetDragObject(nil); {+++}
FState:=ntsNormal;
FreeAndNil(FDragImageList);
end;
procedure TNumTreeView.DoStartDrag(var DragObject: TDragObject);
var
Pt: TPoint;
begin
ChangeImmediate;
HideHotTrack;
CancelHintShow;
inherited DoStartDrag(DragObject);
if FDragGroup = nil then
begin
GetCursorPos(Pt);
Pt:=ScreenToClient(Pt);
if(not FindNodeAt(Pt.X,Pt.Y,FDragGroup,FDragIndex))then FDragGroup:=nil;
end;
if(FDragGroup=nil)or(not DoBeginDragNode(FDragGroup,FDragIndex))then
begin
CancelDrag;
FDragGroup:=nil;
Exit;
end;
if(FDragGroup<>nil)then
begin
CreateDragNodeImage(FDragGroup,FDragIndex);
FState:=ntsNodeDragging;
end;
end;
procedure TNumTreeView.DragOver(Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean);
var
Index:Integer;
Group:TNumberGroup;
begin
inherited;
if(FDragSaveTopRow<0)then
begin
FDragSaveTopRow:=TopRow;
FDragSaveoffset:=FLeftOffset;
end;
if(not FindNodeAt(X,Y,Group,Index))then
begin
Group:=nil;Index:=-1;
end;
if(Group<>FDragOverGroup)or(Index<>FDragOverIndex)then
begin
if(FDragExpandTimer<>0)then
begin
KillTimer(Handle,FDragExpandTimer);
FDragExpandTimer:=0;
end;
if(Group<>nil)and(Group.GetChildGroup(Index)<>nil)then
FDragExpandTimer:=SetTimer(Handle,NTVDragExpandTimer,NTVDragExpandWaitTime,nil);
if FDragObject <> nil then FDragObject.HideDragImage;
if(FDragOverGroup<>nil)then UpdateNode(FDragOverGroup,FDragOverIndex);
FDragOverGroup:=Group;FDragOverIndex:=Index;
if(FDragOverGroup<>nil)then
begin
ScrollInView(FDragOverGroup,FDragOverIndex);
UpdateNode(FDragOverGroup,FDragOverIndex,True);
end;
UpdateDragging;
if FDragObject <> nil then FDragObject.ShowDragImage;
end;
FDragScrollDelta:=0;
if(Group<>nil)and(IsTopNode(Group,Index))then
FDragScrollDelta:=-1 else
if(Group<>nil)and(IsLastNode(Group,Index))then
FDragScrollDelta:=1 else
if(Y<=1)then
FDragScrollDelta:=-ShowCount div 10 else
if(Y<RowHeight div 2)then
FDragScrollDelta:=-1 else
if(Y>=ClientHeight)then
FDragScrollDelta:=ShowCount div 10 else
if(Y+RowHeight div 2>=ClientHeight)then
FDragScrollDelta:=1;
if(FDragScrollDelta<>0)then
begin
if(FDragScrollTimer=0)then
FDragScrollTimer:=SetTimer(Handle,NTVDragScrollTimer,NTVDragScrollWaitTime,nil);
end else
if(FDragScrollTimer<>0)then
begin
KillTimer(Handle,FDragScrollTimer);
FDragScrollTimer:=0;
end;
if(Dragging)and(FDragGroup<>nil)and(not Assigned(OnDragOver) or Accept)then
begin
Accept:=(FDragOverGroup<>nil)and(FDragGroup<>FDragOverGroup)or(FDragIndex<>FDragOverIndex);
if(Assigned(OnDragNodeOver))then
OnDragNodeOver(Self,FDragGroup,FDragOverGroup,FDragIndex,FDragOverIndex,Accept);
end;
if(State=dsDragLeave)then RestoreDragOverTop();
end;
procedure TNumTreeView.DragDrop(Source: TObject; X, Y: Integer);
var
Index:Integer;
Group:TNumberGroup;
begin
inherited;
//FDragOverGroup 已经清除
if(not FindNodeAt(X,Y,Group,Index))then
begin
Group:=nil;Index:=-1;
end;
if(Source=Self)and(FDragGroup<>nil)and(Assigned(OnDropNode))then
OnDropNode(Self,FDragGroup,Group,FDragIndex,Index);
RestoreDragOverTop();
end;
procedure TNumTreeView.CheckCurrentHidden(CollapseGroup:TNumberGroup);
begin
if(FCurGroup=nil)then Exit;
if(FCurGroup=CollapseGroup)or(FCurGroup.IsDescendantOf(CollapseGroup))then
begin
FCurGroup:=nil;
SetCurrent(CollapseGroup.OwnerGroup,CollapseGroup.OwnerIndex);
end;
end;
procedure TNumTreeView.CollapseBrothers(AGroup:TNumberGroup;AIndex:Integer);
var
Group:TNumberGroup;
begin
if(AGroup=nil)then Exit;
Group:=AGroup.GetNextChildGroup(nil);
while(Group<>nil)do
begin
if(Group.OwnerIndex<>AIndex)then Group.Collapse(0);
Group:=Group.GetNextBrotherGroup();
end;
end;
procedure TNumTreeView.CreateDragNodeImage(Group:TNumberGroup;Index:Integer);
var
Bmp: TBitmap;
ii: Integer;
S: string;
R, R1: TRect;
begin
Bmp := TBitmap.Create;
try
R:=GetNodeRect(Group,Index);
S:=FNumTree.GetNodeCaption(Group.Child[Index]);
ii:=FNumTree.GetNodeImageIndex(Group.Child[Index]);
// draw bitmap
with Bmp, Canvas do
begin
Width := R.Right - R.Left + Indent;
Height := R.Bottom - R.Top;
Font.Assign(Self.Font);
Brush.Color := Self.Color;
R := Rect(0, 0, Bmp.Width, Bmp.Height);
FillRect(R);
R1 := R; Inc(R1.Left, Indent);
if(FImages<>nil)then
begin
R1.Right := R1.Left + FImages.Width;
if(Index>=0)and(Index<FImages.Count)then
FImages.Draw(Canvas,(R1.Left+R1.Right-FImages.Width+1) div 2,
(R1.Top+R1.Bottom-FImages.Height+1) div 2,ii);
R1.Left := R1.Right + NTVHorzSpace;
end;
// Draw text
R1.Right := R.Right;
SetBkMode(Handle, Windows.TRANSPARENT);
DrawText(Handle, PChar(S), Length(S), R1, DT_LEFT or DT_VCENTER
or DT_SINGLELINE or DT_NOPREFIX or DT_END_ELLIPSIS);
end;
// check image list
if FDragImageList = nil then
FDragImageList := TImageList.CreateSize(Bmp.Width, Bmp.Height)
else FDragImageList.Clear;
FDragImageList.AddMasked(Bmp, Self.Color);
finally
Bmp.Free;
end;
end;
function TNumTreeView.GetDragImages: TDragImageList;
begin
Result:=FDragImageList;
end;
procedure TNumTreeView.DoCheckNode(NodeGroup:TNumberGroup;NodeIndex:Integer;ShiftDown:Boolean);
var
AState:TCheckState;
begin
AState:=InvertState(FNumTree.GetNodeState(NodeGroup.Child[NodeIndex]));
FNumTree.ModifyNodeState(NodeGroup,NodeIndex,AState,-Ord(ShiftDown));
end;
function TNumTreeView.IsLastNode(Group:TNumberGroup;Index:Integer) : Boolean;
begin
Result:=Group.GetChildShowIndex(Index)=TopRow+ViewCount-1;
end;
function TNumTreeView.IsTopNode(Group:TNumberGroup;Index:Integer) : Boolean;
begin
Result :=(Group=FTopGroup)and(Index=FTopIndex);
end;
function TNumTreeView.GetCaptionWidth(const Caption:string):Integer;
begin
Result:=(FFontHeight*Length(Caption)+1) div 2+NTVHorzSpace;
end;
procedure TNumTreeView.CMFontChanged(var Message: TMessage);
begin
inherited;
FFontHeight:=Abs(Font.Height);
UpdateScrollRange;
end;
procedure TNumTreeView.CMMouseEnter(var Message: TMessage);
var
Pt: TPoint;
begin
if(HotTrack)then
begin
GetCursorPos(Pt);
Pt:=ScreenToClient(Pt);
CheckHotTrackPos(Pt.X,Pt.Y);
end;
inherited;
end;
procedure TNumTreeView.CMMouseLeave(var Message: TMessage);
begin
if(HotTrack)then HideHotTrack();
CancelHintShow();
inherited;
end;
procedure TNumTreeView.CMWantSpecialKey(var Msg: TCMWantSpecialKey);
begin
inherited;
if(Char(Msg.CharCode)=#13)then Msg.Result:=1;
end;
procedure TNumTreeView.WMCancelMode(var Msg: TMessage);
begin
CancelMode;
if Assigned(FEditor) then FEditor.WndProc(Msg);
inherited;
end;
procedure TNumTreeView.WMDestroy(var Msg: TWMDestroy);
begin
CancelHintShow;
inherited;
end;
procedure TNumTreeView.WMGetDlgCode(var Msg: TWMGetDlgCode);
begin
inherited;
Msg.Result:=Msg.Result or DLGC_WANTARROWS or DLGC_WANTCHARS;;
end;
procedure TNumTreeView.WMSize(var Msg: TWMSize);
begin
inherited;
UpdateScrollRange;
end;
procedure TNumTreeView.WMTimer(var Msg: TWMTimer);
var
Group:TNumberGroup;
begin
if (Msg.TimerId = FChangeTimer) then
begin
FreeChangeTimer;
DoChange;
end else
if (Msg.TimerId = FSearchTimer) then
begin
KillTimer(Handle,FSearchTimer);
FSearchTimer:=0;
EndSearch();
end else
if (Msg.TimerId = FShowHintTimer) then
begin
KillTimer(Handle,FShowHintTimer);
FShowHintTimer:=0;
ShowHint(True);
end else
if (Msg.TimerId = FHideHintTimer) then
begin
KillTimer(Handle,FHideHintTimer);
FHideHintTimer:=0;
if(FHintWindow<>nil)then
FHintWindow.Hide;
end else
if (Msg.TimerId = FDragScrollTimer) then
begin
KillTimer(Handle,FDragScrollTimer);
FDragScrollTimer:=0;
if FDragObject <> nil then FDragObject.HideDragImage;
TopRow:=TopRow+FDragScrollDelta;
UpdateDragging;
if FDragObject <> nil then FDragObject.ShowDragImage;
end else
if (Msg.TimerId = FDragExpandTimer) then
begin
KillTimer(Handle,FDragExpandTimer);
FDragExpandTimer:=0;
if(FDragOverGroup<>nil)then
begin
Group:=FDragOverGroup.GetChildGroup(FDragOverIndex);
if(Group<>nil)then Group.Expanded:=True;
end;
end;
end;
procedure TNumTreeView.WMHScroll(var Msg: TWMHScroll);
var
ScrollInfo:TScrollInfo;
begin
case Msg.ScrollCode of
SB_TOP:
LeftOffset:=0;
SB_BOTTOM:
LeftOffset:=FMaxCaption;
SB_LINEUP:
LeftOffset:=LeftOffset-FFontHeight;
SB_LINEDOWN:
LeftOffset:=LeftOffset+FFontHeight;
SB_PAGEUP:
LeftOffset:=LeftOffset-ClientWidth;
SB_PAGEDOWN:
LeftOffset:=LeftOffset+ClientWidth;
SB_THUMBPOSITION:
LeftOffset:=GetScrollPos(Handle,SB_HORZ);
SB_THUMBTRACK:
begin
ScrollInfo.cbSize:=SizeOf(ScrollInfo);
ScrollInfo.fMask:=SIF_ALL;
GetScrollInfo(Handle,SB_HORZ,ScrollInfo);
LeftOffset:=ScrollInfo.nTrackPos;
end;
end;
end;
procedure TNumTreeView.WMIMEStartComp(var Message: TMessage);
begin
inherited;
ShowEditor;
end;
procedure TNumTreeView.WMKillFocus(var Msg: TWMKillFocus);
begin
inherited;
if(FEditor<>nil)and(Msg.FocusedWnd=FEditor.Handle)
then Exit;
if(FEditor<>nil)and(Msg.FocusedWnd<>FEditor.Handle)
then HideEditor(True);
UpdateCurrent;
end;
procedure TNumTreeView.WMLButtonDown(var Message: TWMLButtonDown);
begin
inherited;
if FEditor<>nil then FEditor.FClickTime:=GetMessageTime;
end;
procedure TNumTreeView.WMMouseWheel(var Message: TWMMouseWheel);
begin
TopRow:=TopRow-Message.WheelDelta div 120;
end;
procedure TNumTreeView.WMNCHitTest(var Msg:TWMNCHitTest);
begin
DefaultHandler(Msg);
FHitTest:=ScreenToClient(SmallPointToPoint(Msg.Pos));
end;
procedure TNumTreeView.WMSetCursor(var Msg: TWMSetCursor);
var
NodeIndex:Integer;
NodeGroup:TNumberGroup;
HitPos:TNumTreeNodePos;
begin
if(HotTrack)and(Msg.HitTest=HTCLIENT)and(FState in [ntsNormal,ntsEditing])
and(GetHitPos(FHitTest.X,FHitTest.Y,NodeGroup,NodeIndex,HitPos))
and((HitPos=thpCaption)or(HitPos=thpIcon))then
begin
SetCursor(Screen.Cursors[crHandPoint]);
Exit;
end;
inherited;
end;
procedure TNumTreeView.WMSetFocus(var Msg: TWMSetFocus);
begin
inherited;
UpdateCurrent;
end;
procedure TNumTreeView.WMVScroll(var Msg: TWMVScroll);
var
ScrollInfo:TScrollInfo;
begin
case Msg.ScrollCode of
SB_TOP:
TopRow:=0;
SB_BOTTOM:
TopRow:=TopRow+ShowCount;
SB_LINEUP:
TopRow:=TopRow-1;
SB_LINEDOWN:
TopRow:=TopRow+1;
SB_PAGEUP:
TopRow:=TopRow-ViewCount;
SB_PAGEDOWN:
TopRow:=TopRow+ViewCount;
SB_THUMBPOSITION:
TopRow:=GetScrollPos(Handle,SB_VERT);
SB_THUMBTRACK:
begin
ScrollInfo.cbSize:=SizeOf(ScrollInfo);
ScrollInfo.fMask:=SIF_ALL;
GetScrollInfo(Handle,SB_VERT,ScrollInfo);
TopRow:=ScrollInfo.nTrackPos;
end;
end;
end;
procedure TNumTreeView.UpdateHorzScrollPos;
begin
if(not HandleAllocated)then Exit;
if(ScrollBars<>ssHorizontal)and(ScrollBars<>ssBoth)then Exit;
if(FState=ntsEditing)then HideEditor(True);
if(GetScrollPos(Handle,SB_HORZ)<>LeftOffset)then
SetScrollPos(Handle,SB_HORZ,LeftOffset,True);
end;
procedure TNumTreeView.UpdateVertScrollPos;
begin
if(not HandleAllocated)then Exit;
if(ScrollBars<>ssVertical)and(ScrollBars<>ssBoth)then Exit;
if(FState=ntsEditing)then HideEditor(True);
if(GetScrollPos(Handle,SB_VERT)<>TopRow)then
SetScrollPos(Handle,SB_VERT,TopRow,True);
end;
procedure TNumTreeView.UpdateScrollRange;
var
SaveWidth:Integer;
SaveScroll:TScrollStyle;
begin
if(ScrollBars=ssNone)or(not HandleAllocated)then Exit;
Inc(FUpdateCount);
try
SaveScroll:=ScrollBars;
try
FScrollBars:=ssNone;
SaveWidth:=ClientWidth;
if(SaveScroll=ssHorizontal)or(SaveScroll=ssBoth)then
UpdateHorzScrollRange;
if(SaveScroll=ssVertical)or(SaveScroll=ssBoth)then
UpdateVertScrollRange;
if((SaveScroll=ssHorizontal)or(SaveScroll=ssBoth))and(SaveWidth<>ClientWidth)then
UpdateHorzScrollRange;
finally
FScrollBars:=SaveScroll;
end;
UpdateHorzScrollPos;
UpdateVertScrollPos;
finally
Dec(FUpdateCount);
end;
if(not Updating)then
begin
ValidateRect(Handle,nil);
InvalidateRect(Handle,nil,True);
end;
end;
procedure TNumTreeView.UpdateHorzScrollRange;
var
Extent:Integer;
begin
if(FNumTree=nil)then
Extent:=0
else begin
Extent:=(FNumTree.Root.GetMaxShowLevel()+Ord(DrawRoot()))*Indent;
if(CheckBoxes)then Inc(Extent,CheckBoxWidth+NTVHorzSpace);
if(FStateImages<>nil)then Inc(Extent,FStateImages.Width+NTVHorzSpace);
if(FImages<>nil)then Inc(Extent,FImages.Width+NTVHorzSpace);
FMaxCaption:=FNumTree.MaxShowCaption;
Inc(Extent,(FFontHeight*FMaxCaption+1) div 2+NTVHorzSpace);
Extent:=FFontHeight*((Extent+FFontHeight-1) div FFontHeight)-ClientWidth;
end;
if(Extent>0)then
SetScrollRange(Handle,SB_HORZ,0,Extent,True)
else
SetScrollRange(Handle,SB_HORZ,0,0,True);
if(Extent<0)then Extent:=0;
if(LeftOffset>Extent)then LeftOffset:=Extent;
end;
procedure TNumTreeView.UpdateVertScrollRange;
begin
FRowHeight:=Abs(Font.Height)+2*NTVVertSpace;
if(CheckBoxes)and(CheckBoxHeight+NTVVertSpace>FRowHeight)then
FRowHeight:=CheckBoxHeight+NTVVertSpace;
if(FStateImages<>nil)and(FStateImages.Height>FRowHeight)then
FRowHeight:=FStateImages.Height;
if(FImages<>nil)and(FImages.Height>FRowHeight)then
FRowHeight:=FImages.Height;
if(FRowHeight mod 2=1)then Inc(FRowHeight);
FViewCount:=ClientHeight div FRowHeight;
if(FViewCount=0)then Inc(FViewCount);
if(FNumTree=nil)then
FShowCount:=0
else
FShowCount:=FNumTree.Root.GetShowFamilyCount();
if(FShowCount>ViewCount)then
SetScrollRange(Handle,SB_VERT,0,FShowCount-ViewCount,True)
else
SetScrollRange(Handle,SB_VERT,0,0,True);
if(TopRow+ViewCount>ShowCount)then
TopRow:=ShowCount-ViewCount+1
else //<节点收缩是需要更新TopGroup>if(FTopGroup=nil)then
TopRow:=TopRow;
end;
procedure TNumTreeView.SetLeftOffset(const Value:Integer);
var
Old,Min,Max:Integer;
begin
GetScrollRange(Handle,SB_HORZ,Min,Max);
Old:=FLeftOffset;
FLeftOffset:=Value;
if(FLeftOffset<Min)then FLeftOffset:=Min;
if(FLeftOffset>Max)then FLeftOffset:=Max;
if(not Updating)and(Old<>LeftOffset)then
begin
ScrollWindow(Handle,Old-LeftOffset,0,nil,nil);
//InvalidateRect(Handle, nil, True);
end;
UpdateHorzScrollPos;
end;
procedure TNumTreeView.SetTopRow(const Value:Integer);
var
Old,Min,Max:Integer;
begin
if(HandleAllocated)then
GetScrollRange(Handle,SB_VERT,Min,Max)
else begin Min:=0;Max:=0;end;
Old:=TopRow;FTopRow:=Value;
if(FTopRow<Min)then FTopRow:=Min;
if(FTopRow>Max)then FTopRow:=Max;
if(FNumTree=nil)or(TopRow>=ShowCount)then
begin
FTopRow:=0;
FTopGroup:=nil;FTopIndex:=-1;
end else begin
if(not FNumTree.Root.FindNodeByShowIndex(TopRow,FTopGroup,FTopIndex))then
begin
Assert(False,'showindex error, cannot find node');
FTopRow:=0;
FTopGroup:=FNumTree.Root;FTopIndex:=0;
end;
TNumberTreeHacker(FNumTree).ScrollNotify(FTopGroup,FTopIndex,ViewCount+1,Max);
if(Max>FMaxCaption)then
UpdateScrollRange;
end;
if(not Updating)and(Old<>TopRow)then
begin
ScrollWindow(Handle,0,(Old-TopRow)*RowHeight,nil,nil);
//InvalidateRect(Handle, nil, True);
end;
UpdateVertScrollPos;
end;
function TNumTreeView.Updating:Boolean;
begin
Result:=(FUpdateCount>0)or(FNumTree<>nil)and(FNumTree.Updating);
end;
procedure TNumTreeView.BeginUpdate;
begin
if(FNumTree=nil)then Exit;
Inc(FUpdateCount);
FNumTree.BeginUpdate;
end;
procedure TNumTreeView.EndUpdate;
begin
Dec(FUpdateCount);
FNumTree.EndUpdate;
end;
procedure TNumTreeView.SetNumTree(Value:TNumberTree);
begin
FLeftOffset:=0;FMaxCaption:=0;
FTopRow:=0;
FTopGroup:=nil;
FTopIndex:=-1;
FCurRow:=-1;
FCurGroup:=nil;
FCurChildren:=nil;
FHotGroup:=nil;
FSaveRow:=-1;
FSaveGroup:=nil;
FSaveChildren:=nil;
FDragGroup:=nil;
FDragOverGroup:=nil;
FRightClickGroup:=nil;
if(FNumTree<>nil)then
begin
FNumTree.OnChange:=nil;
FNumTree.OnInsert:=nil;
FNumTree.OnDelete:=nil;
FNumTree.OnShowChange:=nil;
end;
FNumTree:=Value;
if(FNumTree<>nil)then
begin
{ TODO : 如何实现多视图事件广播 }
FTopGroup:=Value.Root;
FTopIndex:=0;
FNumTree.Root.Expanded:=True;
FNumTree.OnChange:=OnNodeChange;
FNumTree.OnInsert:=OnNodeInsert;
FNumTree.OnDelete:=OnNodeDelete;
FNumTree.OnShowChange:=DoTreeShowChange;
end;
UpdateScrollRange;
end;
procedure TNumTreeView.OnNodeChange(ChgGroup:TNumberGroup;ChgIndex:Integer);
begin
if(FNumTree.MaxShowCaption>FMaxCaption)then
UpdateScrollRange
else if(ChgGroup<>nil)and(ChgIndex>=0)then
UpdateNode(ChgGroup,ChgIndex,True)
else if(HandleAllocated)and(not Updating)then begin
ValidateRect(Handle,nil);
InvalidateRect(Handle,nil,True);
end;
end;
procedure TNumTreeView.OnNodeInsert(ChgGroup:TNumberGroup;ChgIndex:Integer);
begin
if(ChgIndex>=0)then
begin
if(FTopGroup=ChgGroup)and(FTopIndex>=ChgIndex)then Inc(FTopIndex);
if(FCurGroup=ChgGroup)and(FCurIndex>=ChgIndex)then Inc(FCurIndex);
if(FHotGroup=ChgGroup)and(FHotIndex>=ChgIndex)then Inc(FHotIndex);
if(FSaveGroup=ChgGroup)and(FSaveIndex>=ChgIndex)then Inc(FSaveIndex);
if(FDragGroup=ChgGroup)and(FDragIndex>=ChgIndex)then Inc(FDragIndex);
if(FDragOverGroup=ChgGroup)and(FDragOverIndex>=ChgIndex)then Inc(FDragOverIndex);
if(FRightClickGroup=ChgGroup)and(FRightClickIndex>=ChgIndex)then Inc(FRightClickIndex);
end;
DoTreeShowChange(ChgGroup,ChgIndex);
end;
procedure TNumTreeView.OnNodeDelete(ChgGroup:TNumberGroup;ChgIndex:Integer);
begin
if(ChgIndex<0)then
begin
if(FTopGroup<>nil)and((FTopGroup=ChgGroup)or(FTopGroup.IsDescendantOf(ChgGroup)))then
FTopGroup:=nil;
if(FCurGroup<>nil)and((FCurGroup=ChgGroup)or(FCurGroup.IsDescendantOf(ChgGroup)))then
FCurGroup:=nil;
if(FHotGroup<>nil)and((FHotGroup=ChgGroup)or(FHotGroup.IsDescendantOf(ChgGroup)))then
FHotGroup:=nil;
if(FSaveGroup<>nil)and((FSaveGroup=ChgGroup)or(FSaveGroup.IsDescendantOf(ChgGroup)))then
FSaveGroup:=nil;
if(FDragGroup<>nil)and((FDragGroup=ChgGroup)or(FDragGroup.IsDescendantOf(ChgGroup)))then
FDragGroup:=nil;
if(FDragOverGroup<>nil)and((FDragOverGroup=ChgGroup)or(FDragOverGroup.IsDescendantOf(ChgGroup)))then
FDragOverGroup:=nil;
if(FRightClickGroup<>nil)and((FRightClickGroup=ChgGroup)or(FRightClickGroup.IsDescendantOf(ChgGroup)))then
FRightClickGroup:=nil;
end else begin
if(FTopGroup=ChgGroup)and(FTopIndex=ChgIndex)then FTopGroup:=nil;
if(FTopGroup=ChgGroup)and(FTopIndex>ChgIndex)then Dec(FTopIndex);
if(FCurGroup=ChgGroup)and(FCurIndex=ChgIndex)then FCurGroup:=nil;
if(FCurGroup=ChgGroup)and(FCurIndex>ChgIndex)then Dec(FCurIndex);
if(FHotGroup=ChgGroup)and(FHotIndex=ChgIndex)then FHotGroup:=nil;
if(FHotGroup=ChgGroup)and(FHotIndex>ChgIndex)then Dec(FHotIndex);
if(FSaveGroup=ChgGroup)and(FSaveIndex=ChgIndex)then FSaveGroup:=nil;
if(FSaveGroup=ChgGroup)and(FSaveIndex>ChgIndex)then Dec(FSaveIndex);
if(FDragGroup=ChgGroup)and(FDragIndex=ChgIndex)then FDragGroup:=nil;
if(FDragGroup=ChgGroup)and(FDragIndex>ChgIndex)then Dec(FDragIndex);
if(FDragOverGroup=ChgGroup)and(FDragOverIndex=ChgIndex)then FDragOverGroup:=nil;
if(FDragOverGroup=ChgGroup)and(FDragOverIndex>ChgIndex)then Dec(FDragOverIndex);
if(FRightClickGroup=ChgGroup)and(FRightClickIndex=ChgIndex)then FRightClickGroup:=nil;
if(FRightClickGroup=ChgGroup)and(FRightClickIndex>ChgIndex)then Dec(FRightClickIndex);
end;
if(FCurGroup=nil)then FCurChildren:=nil;
DoTreeShowChange(ChgGroup,ChgIndex);
end;
procedure TNumTreeView.DoTreeShowChange(ChgGroup:TNumberGroup;ChgIndex:Integer);
begin
if(not Updating)then UpdateScrollRange;
end;
function TNumTreeView.GetTextRect(NodeGroup:TNumberGroup;NodeIndex:Integer):TRect;
var
ShowIndex:Integer;
begin
if(RowSelect)then
begin
Result.Left:=0;Result.Right:=ClientWidth;
end else begin
Result.Left:=(NodeGroup.OwnerLevel+Ord(DrawRoot()))*Indent;
if(CheckBoxes)then Inc(Result.Left,CheckBoxWidth+NTVHorzSpace);
if(FStateImages<>nil)then Inc(Result.Left,FStateImages.Width+NTVHorzSpace);
if(FImages<>nil)then Inc(Result.Left,FImages.Width+NTVHorzSpace);
Dec(Result.Left,LeftOffset);
Result.Right:=Result.Left+GetCaptionWidth(FNumTree.GetNodeCaption(NodeGroup.Child[NodeIndex]));
end;
ShowIndex:=NodeGroup.GetChildShowIndex(NodeIndex);
if(ShowIndex<TopRow)or(ShowIndex>TopRow+ViewCount)then
begin
Result.Top:=0;Result.Bottom:=0;
end else begin
Result.Top:=RowHeight*(ShowIndex-TopRow);
Result.Bottom:=Result.Top+FRowHeight;//FFontHeight+2*NTVVertSpace;
end;
end;
function TNumTreeView.GetNodeRect(NodeGroup:TNumberGroup;NodeIndex:Integer;FullRow:Boolean):TRect;
var
ShowIndex:Integer;
begin
if(RowSelect)or(FullRow)then
begin
Result.Left:=0;Result.Right:=ClientWidth;
end else begin
Result.Left:=(NodeGroup.OwnerLevel+Ord(DrawRoot()))*Indent;
Dec(Result.Left,LeftOffset);
Result.Right:=Result.Left;
if(CheckBoxes)then Inc(Result.Right,CheckBoxWidth+NTVHorzSpace);
if(FStateImages<>nil)then Inc(Result.Right,FStateImages.Width+NTVHorzSpace);
if(FImages<>nil)then Inc(Result.Right,FImages.Width+NTVHorzSpace);
Inc(Result.Right,GetCaptionWidth(FNumTree.GetNodeCaption(NodeGroup.Child[NodeIndex])));
end;
if(not NumTree.GroupCanShow(NodeGroup))then
ShowIndex:=-1
else
ShowIndex:=NodeGroup.GetChildShowIndex(NodeIndex);
if(ShowIndex<TopRow)or(ShowIndex>TopRow+ViewCount)then
begin
Result.Top:=0;Result.Bottom:=0;
end else begin
Result.Top:=RowHeight*(ShowIndex-TopRow);
Result.Bottom:=Result.Top+FRowHeight;//FFontHeight+2*NTVVertSpace;
end;
end;
procedure TNumTreeView.UpdateNode(NodeGroup:TNumberGroup;NodeIndex:Integer;FullRow:Boolean);
var
NRc:TRect;
begin
if(HandleAllocated)and(NodeGroup<>nil)and(not Updating)
and(NumTree.GroupCanShow(NodeGroup))then
begin
NRc:=GetNodeRect(NodeGroup,NodeIndex,FullRow);
InvalidateRect(Handle,@NRc,True);
end;
end;
procedure TNumTreeView.UpdateCurrent;
begin
if(FCurGroup<>nil)then
UpdateNode(FCurGroup,FCurIndex);
end;
procedure TNumTreeView.ScrollInView(NodeGroup:TNumberGroup;NodeIndex:Integer;ShowIndex:Integer);
var
LX,NW:Integer;
begin
if(ShowIndex<0)then ShowIndex:=NodeGroup.GetChildShowIndex(NodeIndex);
if(ShowIndex>=0)and(ShowIndex<TopRow)then TopRow:=ShowIndex
else if(ViewCount>0)and(ShowIndex>=TopRow+ViewCount)then
TopRow:=ShowIndex-ViewCount+1;
if(NodeGroup<>nil)then
begin
LX:=(NodeGroup.OwnerLevel+Ord(DrawRoot()))*Indent;
NW:=GetCaptionWidth(FNumTree.GetNodeCaption(NodeGroup.Child[NodeIndex]));
if(CheckBoxes)then Inc(NW,CheckBoxWidth+NTVHorzSpace);
if(FStateImages<>nil)then Inc(NW,FStateImages.Width+NTVHorzSpace);
if(FImages<>nil)then Inc(NW,FImages.Width+NTVHorzSpace);
if(LeftOffset>LX)then
LeftOffset:=LX
else
if(LX+NW-LeftOffset>ClientWidth)then begin
NW:=LX+NW-ClientWidth;
if(NW<LX)then LeftOffset:=NW
else LeftOffset:=LX;
end;
end;
end;
procedure TNumTreeView.ScrollCurChildrenInView;
var
NewTop,Count:Integer;
begin
if(FCurChildren=nil)then Exit;
Count:=FCurChildren.GetShowFamilyCount();
if(CurRow+Count>=TopRow+ViewCount)then
begin
NewTop:=CurRow+Count+1-ViewCount;
if(NewTop>CurRow)then NewTop:=CurRow;
if(NewTop<>TopRow)then TopRow:=NewTop;
end;
end;
function TNumTreeView.GetHitPos(X,Y:Integer;var NodeGroup:TNumberGroup;
var NodeIndex:Integer;var HitPos:TNumTreeNodePos):Boolean;
var
L,R,Index:Integer;
begin
if(FNumTree=nil)then
begin
Result:=False;
Exit;
end;
Index:=TopRow+Y div RowHeight;
Result:=FNumTree.Root.FindNodeByShowIndex(Index,NodeGroup,NodeIndex);
if(Result)then
begin
R:=(NodeGroup.OwnerLevel+Ord(DrawRoot()))*Indent-LeftOffset;
L:=R-Indent;
if(X>L)and(X<R)then
begin
HitPos:=thpIndent;
Exit;
end;
L:=R;
if(CheckBoxes)then
R:=L+CheckBoxWidth+NTVHorzSpace;
if(X>L)and(X<R)then
begin
HitPos:=thpCheckBox;
Exit;
end;
L:=R;
if(FStateImages<>nil)then
R:=L+FStateImages.Width+NTVHorzSpace;
if(X>L)and(X<R)then
begin
HitPos:=thpStateImage;
Exit;
end;
L:=R;
if(FImages<>nil)then
R:=L+FImages.Width+NTVHorzSpace;
if(X>L)and(X<R)then
begin
HitPos:=thpIcon;
Exit;
end;
L:=R;
R:=L+GetCaptionWidth(FNumTree.GetNodeCaption(NodeGroup.Child[NodeIndex]));
if(X>L)and(X<R)then
begin
HitPos:=thpCaption;
Exit;
end;
HitPos:=thpSpace;
end;
end;
function TNumTreeView.FindNodeAt(X,Y:Integer;var NodeGroup:TNumberGroup;var NodeIndex:Integer):Boolean;
var
HitPos:TNumTreeNodePos;
begin
Result:=GetHitPos(X,Y,NodeGroup,NodeIndex,HitPos);
Result:=Result and (RowSelect or (HitPos in [thpCaption,thpIcon]));
end;
procedure TNumTreeView.Paint;
var
ARow:Integer;
RowRect:TRect;
Index:Integer;
SubGroup,Group:TNumberGroup;
begin
if(FNumTree=nil)then
begin
inherited;
Exit;
end;
RowRect.Left:=0;RowRect.Right:=ClientWidth;
RowRect.Bottom:=0;
ARow:=TopRow;
Index:=FTopIndex;Group:=FTopGroup;
while(Group<>nil)and(Index<Group.Count)and(ARow<=TopRow+ViewCount)do
begin
RowRect.Top:=RowRect.Bottom;
RowRect.Bottom:=RowRect.Top+RowHeight;
if(RectVisible(Canvas.Handle,RowRect))then
DrawTreeNode(RowRect,Group,Index);
SubGroup:=Group.GetChildGroup(Index);
if(SubGroup<>nil)and(SubGroup.Expanded)and(SubGroup.Count>0)then
begin
Group:=SubGroup;Index:=0;
end else begin
while(Group<>nil)and(Index=Group.Count-1)do
begin
Index:=Group.OwnerIndex;
Group:=Group.OwnerGroup;
end;
Inc(Index);
end;
Inc(ARow);
end;
end;
function TNumTreeView.DrawRoot():Boolean;
begin
Result:=ShowRoot and (ShowLines or ShowButtons);
end;
procedure TNumTreeView.DrawTreeNode(const RowRect:TRect;NodeGroup:TNumberGroup;NodeIndex:Integer);
const
CheckStates:array[TCheckState] of Integer=
(0,DFCS_CHECKED,DFCS_CHECKED or DFCS_INACTIVE);
var
DR:TRect;
ANode:TNumberNode;
Group:TNumberGroup;
NodeCaption:string;
LX,CX,SX,IX,TX,TW:Integer;
StateIndex,ImageIndex:Integer;
begin
ANode:=NodeGroup.Child[NodeIndex];
NodeCaption:=FNumTree.GetNodeCaption(ANode);
StateIndex:=FNumTree.GetNodeStateIndex(ANode);
ImageIndex:=FNumTree.GetNodeImageIndex(ANode);
DR.Top:=RowRect.Top;DR.Bottom:=RowRect.Bottom;
CX{Line}:=(NodeGroup.OwnerLevel+Ord(DrawRoot()))*Indent-LeftOffset;
LX:=CX-Indent;
if(not CheckBoxes)then SX:=CX
else SX:=CX+CheckBoxWidth+NTVHorzSpace;
if(FStateImages=nil)then IX:=SX
else IX:=SX+FStateImages.Width+NTVHorzSpace;
if(FImages=nil)then TX:=IX
else TX:=IX+FImages.Width+NTVHorzSpace;
TW:=GetCaptionWidth(NodeCaption);
Canvas.Font.Assign(Font);
if(NodeGroup=FCurGroup)and(NodeIndex=FCurIndex)then
begin
if(RowSelect)then
begin
DR.Left:=RowRect.Left;DR.Right:=RowRect.Right;
end else begin
DR.Left:=TX;DR.Right:=DR.Left+TW;
end;
if(Focused)then
begin
Canvas.Brush.Color:=clHighlight;
Canvas.Font.Color:=clHighlightText;
end else begin
Canvas.Brush.Color:=clBtnFace;
Canvas.Font.Color:=clBtnText;
end;
Canvas.Brush.Style:=bsSolid;
Canvas.FillRect(DR);
if(Focused)and(not RowSelect)then
begin
Canvas.Brush.Color:=clBtnShadow;
Canvas.FrameRect(DR);
end;
end else
if(HotTrack)and(NodeGroup=FHotGroup)and(NodeIndex=FHotIndex)then
begin
Canvas.Font.Color:=clBlue;
Canvas.Font.Style:=Canvas.Font.Style+[fsUnderline];
end else
if(NodeGroup=FRightClickGroup)and(NodeIndex=FRightClickIndex)
or(NodeGroup=FDragOverGroup)and(NodeIndex=FDragOverIndex)then
begin
if(RowSelect)then
begin
DR.Left:=RowRect.Left;DR.Right:=RowRect.Right;
end else begin
DR.Left:=TX;DR.Right:=DR.Left+TW;
end;
Canvas.Font.Color:=clBlue;
Canvas.Brush.Color:=clPurple;
Canvas.FrameRect(DR);
end;
DR.Left:=LX;
if(ShowLines)then
begin
Group:=NodeGroup;
while(DR.Left>0)and(Group<>nil)do
begin
DR.Right:=DR.Left;DR.Left:=DR.Right-Indent;
if(Group.OwnerGroup<>nil)and(Group.OwnerIndex<Group.OwnerGroup.Count-1)then
DrawTreeViewLine(Canvas.Handle,DR);
Group:=Group.OwnerGroup;
end;
end;
Group:=NodeGroup.GetChildGroup(NodeIndex);
if(Group<>nil)and(Group.Count=0)then Group:=nil;
DR.Left:=LX;DR.Right:=DR.Left+Indent;
if(DR.Right>0)and(ShowLines)then
DrawTreeViewLine(Canvas.Handle,DR,(ShowButtons)and(Group<>nil),NodeIndex=NodeGroup.Count-1);
if(DR.Right>0)and(ShowButtons)and(Group<>nil)then
DrawTreeViewButton(Canvas.Handle,DR,Group.Expanded);
if(CheckBoxes)then
begin
DR.Left:=CX;DR.Right:=DR.Left+CheckBoxWidth;
DR.Top:=(RowRect.Bottom+RowRect.Top-CheckBoxHeight) div 2;
DR.Bottom:=DR.Top+CheckBoxHeight;
DrawFrameControl(Canvas.Handle,DR,DFC_BUTTON,
DFCS_FLAT or DFCS_BUTTONCHECK
or CheckStates[FNumTree.GetNodeState(ANode)]);
DR.Top:=RowRect.Top;DR.Bottom:=RowRect.Bottom;
end;
if(FStateImages<>nil)and(StateIndex>=0)and(StateIndex<FStateImages.Count)then
begin
ImageList_DrawEx(FStateImages.Handle,StateIndex,Canvas.Handle,
SX,(RowRect.Bottom+RowRect.Top-FStateImages.Height) div 2,0,0,
clNone,clNone,ILD_Transparent);
end;
if(FImages<>nil)and(ImageIndex>=0)and(ImageIndex<FImages.Count)then
begin
ImageList_DrawEx(FImages.Handle,ImageIndex,Canvas.Handle,
IX,(RowRect.Bottom+RowRect.Top-FImages.Height) div 2,0,0,
clNone,clNone,ILD_Transparent);
end;
Canvas.Brush.Style:=bsClear;
Canvas.TextOut(TX+NTVHorzSpace div 2,
(RowRect.Bottom+RowRect.Top-FFontHeight+1) div 2,NodeCaption);
end;
procedure TNumTreeView.KeyDown(var Key: Word; Shift: TShiftState);
var
SL:Integer;
begin
inherited KeyDown(Key, Shift);
if(FNumTree=nil)then Exit;
if Key = VK_ESCAPE then
begin
CancelMode;
if(FSearching)then EndSearch;
Exit;
end;
if (FState = ntsEditing) and (Key in
[VK_UP, VK_DOWN, VK_PRIOR, VK_NEXT, VK_TAB, VK_RETURN]) then
begin
HideEditor(True);
if(Key=VK_RETURN)then Key := 0;
end;
if (Key = VK_F3) and (FSearchText <> '')then
StartSearch(False);
if FSearching and (Key in [VK_F3, VK_DELETE, VK_BACK]) then
begin
case Key of
VK_F3: DoSearch(FSearchText, ssShift in Shift);
VK_DELETE: FSearchText := '';
VK_BACK:
begin
SL:=Length(FSearchText);
if(ByteType(FSearchText,SL)=mbTrailByte)then
Delete(FSearchText, SL-1, 2)
else Delete(FSearchText, SL, 1);
end;
end;
Key:=0;
end;
case Key of
VK_F2:
if(Shift=[])then
begin
ShowEditor();
Key:=0;
end;
VK_SPACE:
if([ssAlt,ssCtrl]*Shift=[])then begin
if(FChangeTimer<>0)then
begin
FreeChangeTimer;
DoChange;
end;
if(CheckBoxes)and(FCurGroup<>nil)then
DoCheckNode(FCurGroup,FCurIndex,[ssShift,ssCtrl]*Shift<>[]);
Key:=0;
end;
VK_RETURN:
if([ssAlt,ssCtrl]*Shift=[])then begin
if(FChangeTimer<>0)then
begin
FreeChangeTimer;
DoChange;
end;
if(not ReadOnly)then ShowEditor else
if(CheckBoxes)and(FCurGroup<>nil)then
DoCheckNode(FCurGroup,FCurIndex,[ssShift,ssCtrl]*Shift<>[]);
end;
VK_HOME:
begin
if(Shift=[ssCtrl])then
begin
TopRow:=0;
Key:=0;
end else
if(Shift=[])then
begin
CurRow:=0;
Key:=0;
end;
end;
VK_END:
begin
if(Shift=[ssCtrl])then
begin
TopRow:=ShowCount-ViewCount;
Key:=0;
end else
if(Shift=[])then
begin
CurRow:=ShowCount-1;
Key:=0;
end;
end;
VK_PRIOR:
begin
if(Shift=[ssCtrl])then
begin
TopRow:=TopRow-ViewCount;
Key:=0;
end else
if(Shift=[])then
begin
CurRow:=CurRow-ViewCount;
Key:=0;
end;
end;
VK_NEXT:
begin
if(Shift=[ssCtrl])then
begin
TopRow:=TopRow+ViewCount;
Key:=0;
end else
if(Shift=[])then
begin
CurRow:=CurRow+ViewCount;
Key:=0;
end;
end;
VK_UP:
begin
if(Shift=[ssCtrl])then
begin
TopRow:=TopRow-1;
Key:=0;
end else
if(Shift=[])then
begin
CurRow:=CurRow-1;
Key:=0;
end;
end;
VK_DOWN:
begin
if(Shift=[ssCtrl])then
begin
TopRow:=TopRow+1;
Key:=0;
end else
if(Shift=[])then
begin
CurRow:=CurRow+1;
Key:=0;
end;
end;
VK_LEFT:
begin
if(FCurGroup<>nil)and((Shift=[])or(Shift=[ssShift]))then begin
if(FCurChildren<>nil)and(FCurChildren.Expanded)then
begin
FCurChildren.Collapse(1-Ord(ssShift in Shift));
//CheckCurrentHidden(FCurChildren);
end else if(FCurGroup<>nil)and(FCurGroup<>NumTree.Root)then
SetCurrent(FCurGroup.OwnerGroup,FCurGroup.OwnerIndex);
Key:=0;
end else
if(Shift=[ssCtrl])then begin
LeftOffset:=LeftOffset-FFontHeight;
Key:=0;
end;
end;
VK_RIGHT:
begin
if(FCurChildren<>nil)and((Shift=[])or(Shift=[ssShift]))then begin
if(not FCurChildren.Expanded)then
begin
FCurChildren.Expand(1-Ord(ssShift in Shift));
ScrollCurChildrenInView;
end else
SetCurrent(FCurChildren,0);
Key:=0;
end else
if(Shift=[ssCtrl])then begin
LeftOffset:=LeftOffset+FFontHeight;
Key:=0;
end;
end;
end;
end;
procedure TNumTreeView.KeyPress(var Key: Char);
function ShiftDown():Boolean;
begin
Result:=GetKeyState(VK_Shift) and $80000000<>0;
end;
function ControlorAltDown: Boolean;
begin
Result := (GetKeyState(VK_CONTROL) <> 0) and
(GetKeyState(VK_MENU) <> 0);
end;
begin
{if(FState=ntsEditing)then
begin
if(Key=#13)then HideEditor(True) else
if(Key=#27)then HideEditor(False);
Exit;
end;}
inherited KeyPress(Key);
if(FNumTree=nil)then Exit;
if(not FSearching)then
case Key of
^X:;{ TODO : Do Cut }
^C:if(ReadOnly)and(FCurGroup<>nil)then
begin
if(ShiftDown)then
Clipboard.SetTextBuf(PChar(FNumTree.GetNodeHint(FCurGroup.Child[FCurIndex])))
else
Clipboard.SetTextBuf(PChar(FNumTree.GetNodeCaption(FCurGroup.Child[FCurIndex])))
end else
;{ TODO : Do Copy }
^V:begin
{ TODO : Do Paste }
Key:=#0;
end;
^F:StartSearch(True);
'+':
begin
if(FCurChildren<>nil)then begin
ScrollInView(FCurGroup,FCurIndex,FCurRow);
FCurChildren.Expand(1-Ord(ShiftDown));
ScrollCurChildrenInView;
end;
Key:=#0;
end;
'-':
begin
if(FCurChildren<>nil)then begin
ScrollInView(FCurGroup,FCurIndex,FCurRow);
FCurChildren.Collapse(1-Ord(ShiftDown));
//CheckCurrentHidden(FCurChildren);
end;
Key:=#0;
end;
'*':
begin
if(FCurChildren<>nil)then begin
ScrollInView(FCurGroup,FCurIndex,FCurRow);
if(FCurChildren.Expanded)then
begin
FCurChildren.Collapse(0);
//CheckCurrentHidden(FCurChildren);
end else begin
FCurChildren.Expand(0);
ScrollCurChildrenInView;
end;
end;
Key:=#0;
end;
end;
if(FSearching)and(Key=^V)then
begin
FSearchText:=FSearchText+ClipBoard.AsText;
DoSearch(FSearchText, False);
end;
if (Key in [#32..#255]) and not ControlorAltDown then
begin
if(not FSearching)then StartSearch(True);
FSearchText := FSearchText + Key;
DoSearch(FSearchText, False);
end;
end;
procedure TNumTreeView.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
var
Index:Integer;
Group,Children:TNumberGroup;
HitPos:TNumTreeNodePos;
AlreadyFocused:Boolean;
begin
if(FNumTree=nil)then
begin
inherited MouseDown(Button, Shift, X, Y);
Exit;
end;
if(FState=ntsEditing)then HideEditor(True);
FState:=ntsNormal;
AlreadyFocused:=Focused;
if CanFocus and not (csDesigning in ComponentState) then
begin
SetFocus;
if not IsActiveControl(Self) then
begin
MouseCapture := False;
Exit;
end;
end;
if(Button=mbRight)then
begin
if(RightClick)and(GetHitPos(X,Y,Group,Index,HitPos))then
begin
FRightClickGroup:=Group;
FRightClickIndex:=Index;
UpdateNode(FRightClickGroup,FRightClickIndex);
end;
end else
if(Button=mbLeft)then
begin
if(GetHitPos(X,Y,Group,Index,HitPos))then
begin
if(RowSelect)and(HitPos=thpSpace)then HitPos:=thpCaption;
Children:=Group.GetChildGroup(Index);
case HitPos of
thpIndent:
begin
if(Children<>nil)then begin
if(Children.Expanded)then
Children.Collapse(1-Ord(ssShift in Shift))
else begin
Children.Expand(1-Ord(ssShift in Shift));
ScrollInView(Children,Children.Count-1);
ScrollInView(Group,Index);
end;
CheckCurrentHidden(Children);
end;
end;
thpCheckBox:
DoCheckNode(Group,Index,[ssShift,ssCtrl]*Shift<>[]);
thpIcon,thpCaption:
begin
if(FCurGroup=Group)and(FCurIndex=Index)then
begin
if(ssDouble in Shift)and(Children<>nil)then
begin
if(Children.Expanded)then
Children.Collapse(1-Ord(ssShift in Shift))
else Children.Expand(1-Ord(ssShift in Shift));
CheckCurrentHidden(Children);
end else begin
if(AlreadyFocused)then ShowEditor();
end;
end else
SetCurrent(Group,Index);
if(AutoExpand)then
begin
if(Children<>nil)then
begin
Children.Expanded:=not Children.Expanded;
if(Children.Expanded)then
ScrollCurChildrenInView;
end;
CollapseBrothers(FCurGroup,FCurIndex);
end;
if(not(ssDouble in Shift))then
begin
FState:=ntsNodeDown;
FDragPos.X:=X;FDragPos.Y:=Y;
end;
end;
end;
end;
end;
try
inherited MouseDown(Button, Shift, X, Y);
except
CancelMode;
raise
end;
end;
procedure TNumTreeView.MouseMove(Shift:TShiftState;X,Y:Integer);
var
Index:Integer;
Group:TNumberGroup;
begin
if(FNumTree=nil)then
begin
inherited MouseMove(Shift, X, Y);
Exit;
end;
if(ssLeft in Shift)and(AutoDrag)and(FState=ntsNodeDown)then
begin
if(FindNodeAt(X,Y,Group,Index))and((Abs(FDragPos.X-X)>3)or(Abs(FDragPos.Y-Y)>3))then
begin
if(Group=FCurGroup)and(Index=FCurIndex)then
begin
BeginDrag(True);
end;
end;
end;
Index:=FHotIndex;
Group:=FHotGroup;
CheckHotTrackPos(X, Y);
if(Group<>FHotGroup)or(Index<>FHotIndex)then
ShowHint(False);
try
inherited MouseMove(Shift, X, Y);
except
CancelMode;
raise
end;
end;
procedure TNumTreeView.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
if(FNumTree=nil)then
begin
inherited MouseUp(Button, Shift, X, Y);
Exit;
end;
UpdateNode(FRightClickGroup,FRightClickIndex);
FRightClickGroup:=nil;
FRightClickIndex:=0;
try
inherited MouseUp(Button, Shift, X, Y);
except
CancelMode;
raise
end;
end;
procedure TNumTreeView.SetCurRow(Value:Integer);
var
Index:Integer;
T,Group:TNumberGroup;
begin
if(Value<0)then Value:=0;
if(Value>=ShowCount)then Value:=ShowCount-1;
Group:=nil;
if(Value=FCurRow)then
begin
Group:=FCurGroup;
Index:=FCurIndex;
end else
if(Value=FCurRow+1)then
begin
if(FCurChildren<>nil)and(FCurChildren.Expanded)then
begin
Group:=FCurChildren;
Index:=0;
end else
if(FCurGroup<>nil)and(FCurIndex<FCurGroup.Count-1)then begin
Group:=FCurGroup;
Index:=FCurIndex+1;
end;
end else
if(Value=FCurRow-1)then
begin
if(FCurGroup<>nil)and(FCurIndex>0)then begin
Group:=FCurGroup;
Index:=FCurIndex-1;
T:=Group.GetChildGroup(Index);
while(T<>nil)and(T.Expanded)do
begin
Group:=T;
Index:=Group.Count-1;
T:=Group.GetChildGroup(Index);
end;
end;
end;
if(Group=nil)then
FNumTree.Root.FindNodeByShowIndex(Value,Group,Index);
if(Group<>nil)then SetCurrent(Group,Index);
end;
function TNumTreeView.SetCurrent(NodeGroup:TNumberGroup;NodeIndex:Integer):Boolean;
begin
Result:=True;
if(Assigned(OnChanging))then OnChanging(Self,NodeGroup,NodeIndex,Result);
if(Result)then
begin
FreeChangeTimer;
UpdateCurrent;
if(NodeGroup<>nil)then
begin
NumTree.ExpandGroup(NodeGroup);
FCurGroup:=NodeGroup;
FCurIndex:=NodeIndex;
FCurChildren:=FCurGroup.GetChildGroup(NodeIndex);
FCurRow:=FCurGroup.GetChildShowIndex(NodeIndex);
ScrollInView(FCurGroup,FCurIndex,FCurRow);
UpdateCurrent;
end else begin
FCurGroup:=nil;
FCurIndex:=-1;
FCurChildren:=nil;
FCurRow:=-1;
UpdateCurrent;
end;
if(ChangeDelay=0)then DoChange
else FChangeTimer:=SetTimer(Handle,NTVChangeTimer,ChangeDelay,nil);
end;
end;
function TNumTreeView.SetCurrentNode(NumNode:TNumberNode):Boolean;
var
Index:Integer;
Group:TNumberGroup;
begin
if(NumTree.Root.FindNode(NumNode,Group,Index))then
Result:=SetCurrent(Group,Index)
else Result:=False;
end;
procedure TNumTreeView.DoChange;
begin
if(Assigned(OnChange))then OnChange(Self,FCurGroup,FCurIndex);
end;
procedure TNumTreeView.ResetSearchTimer;
begin
if FSearchTimer <> 0 then
begin
KillTimer(Handle,FSearchTimer);
FSearchTimer:=0;
end;
FSearchTimer:=SetTimer(Handle,NTVSearchTimer,NTVSearchWaitTime,nil);
end;
procedure TNumTreeView.StartSearch(ClearSearch:Boolean);
begin
FSearching:=True;
if(ClearSearch)then FSearchText:='';
ResetSearchTimer;
end;
procedure TNumTreeView.DoSearch(const SearchText:string;UpSearch:Boolean);
begin
{ TODO : Do Text search ??? }
//OnSearchText:=FNumTree.DoSearchText;
//if(Assigned(OnSearchText))then OnSearchText(Self,CurGroup,CurIndex,SearchText,UpSearch);
ResetSearchTimer;
end;
procedure TNumTreeView.EndSearch;
begin
FSearching:=False;
end;
type
PListStringRec=^TListStringRec;
TListStringRec=record
//TmpZdm :PChar;
Expand :Boolean;
MaxRank :Integer;
DotRank :Integer;
OutStrings:TStrings;
end;
procedure TNumTreeView.ListTreeStrings(OutStrings:TStrings;ListRoot:TNumberGroup;
RankLmt:Integer;Expand:Boolean);
var
ListRec:TListStringRec;
begin
OutStrings.BeginUpdate;
try
OutStrings.Clear;
//ListRec.TmpZdm:=StrAlloc(TQYTree(NumTree).DataEnv.ZDMLength+1);
try
ListRec.Expand:=Expand;
ListRec.OutStrings:=OutStrings;
if(ListRoot=nil)or(ListRoot.OwnerGroup=nil)then begin
ListRoot:=NumTree.Root;
ListRec.DotRank:=1;
if(RankLmt>0)then Inc(RankLmt);
end else begin
ListRec.DotRank:=ListRoot.OwnerLevel;
GetNodeString(ListRoot.OwnerNode,ListRoot.OwnerGroup,ListRoot,Integer(@ListRec));
end;
if(RankLmt=0)then ListRec.MaxRank:=0
else ListRec.MaxRank:=ListRoot.OwnerLevel+RankLmt;
if(RankLmt>0)then
ListRoot.ForSubLevelChild(GetNodeString,RankLmt,Integer(@ListRec))
else if(Expand)then
ListRoot.ForAll(GetNodeString,True,Integer(@ListRec))
else
ListRoot.ForAllExpanded(GetNodeString,Integer(@ListRec));
finally
//StrDispose(ListRec.TmpZdm);
end;
finally
OutStrings.EndUpdate;
end;
end;
procedure TNumTreeView.GetNodeString(NodeID:LongInt;NodeGroup,SubNodes:TNumberGroup;Param:Integer);
var
I:Integer;
sHead:string;
ListRec:PListStringRec;
begin
ListRec:=Pointer(Param);
sHead:='';
for I:=ListRec.DotRank to NodeGroup.OwnerLevel do
sHead:=sHead+'·';//' ';
if(SubNodes=nil)then sHead:=sHead+'o'
else if((ListRec.Expand)or(SubNodes.Expanded))
and((ListRec.MaxRank=0)or(SubNodes.OwnerLevel<ListRec.MaxRank))then
sHead:=sHead+'◇'
else sHead:=sHead+'⊙';
ListRec.OutStrings.Add(sHead+NumTree.GetNodeCaption(NodeID));
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: Unit de Sessão do Usuário - Servidor.
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit SessaoUsuario;
interface
uses Generics.Collections, UsuarioVO, SysUtils;
type
TSessaoUsuario = class
private
FIdSessao: string;
FUsuario: TUsuarioVO;
FUltimaAtividade: TDateTime;
FIdEmpresa: Integer;
public
destructor Destroy; override;
property IdSessao: string read FIdSessao write FIdSessao;
property Usuario: TUsuarioVO read FUsuario write FUsuario;
property UltimaAtividade: TDateTime read FUltimaAtividade write FUltimaAtividade;
property IdEmpresa: Integer read FIdEmpresa write FIdEmpresa;
end;
TListaSessaoUsuario = class
private
FSessoes: TObjectList<TSessaoUsuario>;
class var FInstance: TListaSessaoUsuario;
function GetItem(Index: Integer): TSessaoUsuario;
function GetSessoes: Integer;
public
constructor Create;
destructor Destroy; override;
class function Instance: TListaSessaoUsuario;
function AdicionaSessao(pIdSessao: string; pUsuario: TUsuarioVO): Integer;
procedure RemoveSessao(pIdSessao: string); overload;
procedure RemoveSessao(pSessaoUsuario: TSessaoUsuario); overload;
function GetSessao(pIdSessao: string): TSessaoUsuario;
function GetUltimaAtividade(pIdSessao: string): TDateTime;
procedure SetUltimaAtividade(pIdSessao: string);
property Sessoes: Integer read GetSessoes;
property Items[Index: Integer]: TSessaoUsuario read GetItem;
end;
implementation
{ TListaSessaoUsuario }
function TListaSessaoUsuario.AdicionaSessao(pIdSessao: string; pUsuario: TUsuarioVO): Integer;
var
SessaoUsuario: TSessaoUsuario;
begin
SessaoUsuario := TSessaoUsuario.Create;
SessaoUsuario.IdSessao := pIdSessao;
SessaoUsuario.Usuario := pUsuario;
SessaoUsuario.UltimaAtividade := Now;
Result := FSessoes.Add(SessaoUsuario);
end;
constructor TListaSessaoUsuario.Create;
begin
inherited Create;
FSessoes := TObjectList<TSessaoUsuario>.Create;
end;
destructor TListaSessaoUsuario.Destroy;
begin
FSessoes.Free;
inherited;
end;
function TListaSessaoUsuario.GetItem(Index: Integer): TSessaoUsuario;
begin
if (Index < 0) or (Index >= Sessoes) then
begin
Result := nil;
end
else
begin
Result := FSessoes.Items[Index];
end;
end;
function TListaSessaoUsuario.GetSessao(pIdSessao: string): TSessaoUsuario;
var
Enumerator: TEnumerator<TSessaoUsuario>;
begin
Result := nil;
Enumerator := FSessoes.GetEnumerator;
try
with Enumerator do
begin
while MoveNext do
begin
if Current.IdSessao = pIdSessao then
begin
Result := Current;
Break;
end;
end;
end;
finally
Enumerator.Free;
end;
end;
function TListaSessaoUsuario.GetSessoes: Integer;
begin
Result := FSessoes.Count;
end;
function TListaSessaoUsuario.GetUltimaAtividade(pIdSessao: string): TDateTime;
var
SessaoUsuario: TSessaoUsuario;
begin
SessaoUsuario := GetSessao(pIdSessao);
if Assigned(SessaoUsuario) then
Result := SessaoUsuario.UltimaAtividade
else
Result := 0;
end;
class function TListaSessaoUsuario.Instance: TListaSessaoUsuario;
begin
if not Assigned(FInstance) then
FInstance := TListaSessaoUsuario.Create;
Result := FInstance;
end;
procedure TListaSessaoUsuario.RemoveSessao(pSessaoUsuario: TSessaoUsuario);
begin
if Assigned(pSessaoUsuario) then
FSessoes.Remove(pSessaoUsuario);
end;
procedure TListaSessaoUsuario.RemoveSessao(pIdSessao: string);
var
SessaoUsuario: TSessaoUsuario;
begin
SessaoUsuario := GetSessao(pIdSessao);
RemoveSessao(SessaoUsuario);
end;
procedure TListaSessaoUsuario.SetUltimaAtividade(pIdSessao: string);
var
SessaoUsuario: TSessaoUsuario;
begin
SessaoUsuario := GetSessao(pIdSessao);
if Assigned(SessaoUsuario) then
SessaoUsuario.UltimaAtividade := Now;
end;
{ TSessaoUsuario }
destructor TSessaoUsuario.Destroy;
begin
if Assigned(FUsuario) then
FUsuario.Free;
inherited;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls;
type
TForm1 = class(TForm)
DataInicio: TDateTimePicker;
Button1: TButton;
ProgressBar1: TProgressBar;
EditNumeroArquivos: TEdit;
Label1: TLabel;
Label2: TLabel;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
Arquivo: TextFile;
NomeArquivo, DiretorioArquivos: String;
DataArquivo, fHoraEvento: TDateTime;
I, QuantidadeARquivos: Integer;
begin
TButton(Sender).Enabled := false;
try
DiretorioArquivos := ExcludeTrailingBackslash(ExtractFilePath(ParamStr(0))) + '\Logs\';
if not(DirectoryExists(DiretorioArquivos)) then
ForceDirectories(DiretorioArquivos);
QuantidadeARquivos := StrToInt(EditNumeroArquivos.Text);
DataArquivo := DataInicio.DateTime;
ProgressBar1.Position := 0;
ProgressBar1.Max := QuantidadeARquivos;
for I := 0 to QuantidadeARquivos - 1 do
begin
fHoraEvento := Now;
NomeArquivo := 'Log_' + FormatDateTime('yyyy-mm-dd', DataArquivo + I) + '.log';
try
AssignFile(Arquivo, DiretorioArquivos + NomeArquivo);
Rewrite(Arquivo);
WriteLn(Arquivo, FormatDateTime('tt', fHoraEvento) + ' -> ');
finally
CloseFile(Arquivo);
end;
ProgressBar1.Position := I;
end;
finally
TButton(Sender).Enabled := true;
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
DataInicio.DateTime := Now - (StrToInt(EditNumeroArquivos.Text) - 1); { para gerar arquivos até a data presente }
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
DataInicio.DateTime := Now;
EditNumeroArquivos.Text := '10000';
end;
end.
|
unit PageSpeed;
//TODO: Customization (GridQuant, Colors, etc)
//TODO: Dynamic GridQuant (1/2..10/20..128/256..512, k-M-G)
//TODO: Filter speed spikes
interface
uses
Windows, Messages, AvL, avlUtils, avlEventBus, avlSettings, Aria2,
UpdateThread, MainForm, InfoPane;
const
MaxGraphs = 8;
type
TGraphPoint = record
Time: Cardinal;
Values: array[0 .. MaxGraphs - 1] of Integer;
end;
TGraphPoints = array of TGraphPoint;
TGraphParam = record
Name: string;
Color: TColor;
Style: TPenStyle;
end;
TGraphParams = array[0 .. MaxGraphs - 1] of TGraphParam;
TOnGridLabel = function(Sender: TObject; Value: Integer): string of object;
TGraph = class(TGraphicControl)
private
FBitmap: TBitmap;
FCount: Integer;
FPoints: TGraphPoints;
FGridSpan, FTimeSpan: Cardinal;
FGridQuant: Integer;
FOnGridLabel: TOnGridLabel;
procedure CopyPoints(const Src: TGraphPoints; var Dst: TGraphPoints);
function PurgeOldPoints: Cardinal;
procedure Resize(Sender: TObject);
procedure SetTimeSpan(const Value: Cardinal);
function GetBackup: TGraphPoints;
procedure Restore(Backup: TGraphPoints);
protected
procedure Paint; override;
public
Params: TGraphParams;
constructor Create(AOwner: TWinControl);
destructor Destroy; override;
procedure AddPoint(const Vals: array of Integer);
procedure Clear;
procedure Update;
property Backup: TGraphPoints read GetBackup write Restore;
property Count: Integer read FCount write FCount;
property TimeSpan: Cardinal read FTimeSpan write SetTimeSpan;
property GridSpan: Cardinal read FGridSpan write FGridSpan;
property GridQuant: Integer read FGridQuant write FGridQuant;
property OnGridLabel: TOnGridLabel read FOnGridLabel write FOnGridLabel;
end;
TPageSpeed = class(TInfoPage)
private
Graph: TGraph;
FTimer: TTimer;
procedure ServerChanged(Sender: TObject; const Args: array of const);
procedure UpdateGraph(Sender: TObject; const Args: array of const);
function GridLabel(Sender: TObject; Value: Integer): string;
procedure Resize(Sender: TObject);
procedure TimerTick(Sender: TObject);
protected
function GetName: string; override;
public
constructor Create(Parent: TInfoPane); override;
destructor Destroy; override;
procedure Update(UpdateThread: TUpdateThread); override;
end;
implementation
uses
Utils;
const
SGraphData = 'Speed.GraphData';
type
TGraphData = class
public
Backup: TGraphPoints;
constructor Create(Data: TGraphPoints);
destructor Destroy; override;
end;
{ TGraph }
constructor TGraph.Create(AOwner: TWinControl);
begin
inherited;
ExStyle := ExStyle or WS_EX_STATICEDGE;
CanvasInit;
FBitmap := TBitmap.CreateNew(1, 1);
FBitmap.Canvas.Font := TFont.Create(FBitmap.Canvas);
OnResize := Resize;
end;
destructor TGraph.Destroy;
begin
Finalize(FPoints);
FBitmap.Canvas.Font.Free;
FreeAndNil(FBitmap);
inherited;
end;
procedure TGraph.AddPoint(const Vals: array of Integer);
var
i: Integer;
begin
SetLength(FPoints, Length(FPoints) + 1);
with FPoints[High(FPoints)] do
begin
Time := GetTickCount;
for i := 0 to Min(Length(Vals), MaxGraphs) - 1 do
Values[i] := Vals[i];
end;
Update;
end;
procedure TGraph.Clear;
begin
SetLength(FPoints, 0);
Update;
end;
procedure TGraph.CopyPoints(const Src: TGraphPoints; var Dst: TGraphPoints);
var
i: Integer;
begin
SetLength(Dst, Length(Src) + 1);
for i := 0 to High(Src) do
Dst[i] := Src[i];
with Dst[High(Dst)] do
begin
Time := GetTickCount;
for i := 0 to MaxGraphs - 1 do
Values[i] := -1;
end;
end;
procedure TGraph.Paint;
var
CurTime, GridPos: Cardinal;
i, j, MaxVal, GridLines, MaxWidth, X, Y: Integer;
function GetX(Time: Cardinal): Integer;
begin
Result := Round((1 - (CurTime - Time) / FTimeSpan) * (FBitmap.Width - 1));
end;
function GetY(Value: Integer): Integer;
begin
Result := Round((1 - Value / MaxVal) * (FBitmap.Height - 1));
end;
function GetLabel(Value: Integer): string;
begin
if Assigned(FOnGridLabel) then
Result := FOnGridLabel(Self, Value)
else
Result := IntToStr(Value);
end;
begin
FBitmap.Canvas.Brush.Color := clWhite;
FBitmap.Canvas.FillRect(Rect(0, 0, FBitmap.Width, FBitmap.Height));
SetBkMode(FBitmap.Canvas.Handle, TRANSPARENT);
try
CurTime := PurgeOldPoints;
FBitmap.Canvas.Pen.Color := clSilver;
FBitmap.Canvas.Pen.Style := psDash;
GridPos := 0;
while GridPos < FTimeSpan do
begin
FBitmap.Canvas.MoveTo(GetX(CurTime - GridPos), 0);
FBitmap.Canvas.LineTo(GetX(CurTime - GridPos), FBitmap.Height);
Inc(GridPos, FGridSpan);
end;
if Length(FPoints) = 0 then Exit;
MaxVal := 1;
for i := 0 to High(FPoints) do
for j := 0 to FCount - 1 do
MaxVal := Max(MaxVal, FPoints[i].Values[j]);
MaxVal := ((MaxVal + FGridQuant - 1) div FGridQuant) * FGridQuant;
GridLines := FBitmap.Height div 50;
for i := 0 to GridLines do
begin
Y := FBitmap.Height - Round((i / GridLines) * (FBitmap.Height - 1));
FBitmap.Canvas.MoveTo(0, Y);
FBitmap.Canvas.LineTo(FBitmap.Width, Y);
if i > 0 then
FBitmap.Canvas.TextOut(5, Y + 2, GetLabel(Round((i / GridLines) * MaxVal)));
end;
FBitmap.Canvas.Pen.Color := clBlack;
FBitmap.Canvas.Pen.Style := psSolid;
FBitmap.Canvas.MoveTo(0, FBitmap.Height - 1);
FBitmap.Canvas.LineTo(FBitmap.Width, FBitmap.Height - 1);
MaxWidth := 0;
for i := 0 to FCount - 1 do
MaxWidth := Max(MaxWidth, FBitmap.Canvas.TextWidth(Params[i].Name));
X := FBitmap.Width - MaxWidth - 5;
for i := 0 to FCount - 1 do
begin
Y := FBitmap.Height - 20 * FCount + 20 * i - 5;
FBitmap.Canvas.Pen.Color := Params[i].Color;
FBitmap.Canvas.Pen.Style := Params[i].Style;
FBitmap.Canvas.MoveTo(X - 25, Y + 6);
FBitmap.Canvas.LineTo(X - 5, Y + 6);
FBitmap.Canvas.TextOut(X, Y, Params[i].Name);
end;
for i := 0 to FCount - 1 do
begin
FBitmap.Canvas.Pen.Color := Params[i].Color;
FBitmap.Canvas.Pen.Style := Params[i].Style;
FBitmap.Canvas.MoveTo(GetX(FPoints[0].Time), GetY(FPoints[0].Values[i]));
for j := 1 to High(FPoints) do
if (FPoints[j].Values[i] = -1) or ((j > 0) and (FPoints[j - 1].Values[i] = -1)) then
FBitmap.Canvas.MoveTo(GetX(FPoints[j].Time), GetY(FPoints[j].Values[i]))
else
FBitmap.Canvas.LineTo(GetX(FPoints[j].Time), GetY(FPoints[j].Values[i]));
FBitmap.Canvas.Pen.Color := clGray;
FBitmap.Canvas.LineTo(GetX(CurTime), GetY(FPoints[High(FPoints)].Values[i]));
end;
finally
FBitmap.Draw(Canvas.Handle, 0, 0);
end;
end;
function TGraph.PurgeOldPoints: Cardinal;
var
i, Purge: Integer;
T: Single;
begin
Purge := 0;
Result := GetTickCount;
while Purge < Length(FPoints) do
if Result - FPoints[Purge].Time < FTimeSpan then
Break
else
Inc(Purge);
if Purge = 0 then
Exit
else if Purge = Length(FPoints) then
Finalize(FPoints)
else begin
Dec(Purge);
for i := 0 to High(FPoints) - Purge do
FPoints[i] := FPoints[i + Purge];
T := (Result - FTimeSpan - FPoints[0].Time) / (FPoints[1].Time - FPoints[0].Time);
FPoints[0].Time := Result - FTimeSpan;
for i := 0 to FCount - 1 do
FPoints[0].Values[i] := Round((FPoints[1].Values[i] - FPoints[0].Values[i]) * T) + FPoints[0].Values[i];
end;
SetLength(FPoints, Length(FPoints) - Purge);
end;
procedure TGraph.Resize(Sender: TObject);
begin
FBitmap.Width := ClientWidth;
FBitmap.Height := ClientHeight;
end;
procedure TGraph.SetTimeSpan(const Value: Cardinal);
begin
FTimeSpan := Value;
PurgeOldPoints;
end;
procedure TGraph.Update;
begin
Invalidate;
UpdateWindow(Handle);
end;
function TGraph.GetBackup: TGraphPoints;
begin
CopyPoints(FPoints, Result);
end;
procedure TGraph.Restore(Backup: TGraphPoints);
begin
CopyPoints(Backup, FPoints);
Update;
end;
{ TPageSpeed }
constructor TPageSpeed.Create(Parent: TInfoPane);
begin
inherited;
SetArray(FUpdateKeys, [sfGID]);
Graph := TGraph.Create(Self);
Graph.Count := 2;
Graph.TimeSpan := 10 * 60 * 1000;
Graph.GridSpan := 60 * 1000;
Graph.GridQuant := 1048576;
Graph.OnGridLabel := GridLabel;
Graph.Params[0].Name := 'DL Speed';
Graph.Params[0].Color := clBlue;
Graph.Params[0].Style := psSolid;
Graph.Params[1].Name := 'UL Speed';
Graph.Params[1].Color := clGreen;
Graph.Params[1].Style := psSolid;
FTimer := TTimer.CreateEx(1000, true);
FTimer.OnTimer := TimerTick;
OnResize := Resize;
EventBus.AddListener(EvServerChanged, ServerChanged);
EventBus.AddListener(EvUpdate, UpdateGraph);
end;
destructor TPageSpeed.Destroy;
begin
FreeAndNil(FTimer);
EventBus.RemoveListeners([UpdateGraph, ServerChanged]);
inherited;
end;
function TPageSpeed.GetName: string;
begin
Result := 'Speed';
end;
procedure TPageSpeed.Resize(Sender: TObject);
begin
Graph.SetBounds(0, 0, ClientWidth, ClientHeight);
end;
procedure TPageSpeed.ServerChanged(Sender: TObject; const Args: array of const);
var
Data: TGraphData;
begin
(Args[0].VObject as TServerInfo)[SGraphData] := TGraphData.Create(Graph.Backup);
Data := (Args[1].VObject as TServerInfo)[SGraphData] as TGraphData;
if Assigned(Data) then
Graph.Backup := Data.Backup
else
Graph.Clear;
(Args[1].VObject as TServerInfo)[SGraphData] := nil;
end;
procedure TPageSpeed.UpdateGraph(Sender: TObject; const Args: array of const);
begin
with Args[0].VObject as TUpdateThread do
if Assigned(Stats) then
Graph.AddPoint([Stats.Int[sfDownloadSpeed], Stats.Int[sfUploadSpeed]])
else
Graph.AddPoint([-1, -1]);
end;
procedure TPageSpeed.Update(UpdateThread: TUpdateThread);
begin
end;
function TPageSpeed.GridLabel(Sender: TObject; Value: Integer): string;
begin
Result := SizeToStr(Value) + '/s';
end;
procedure TPageSpeed.TimerTick(Sender: TObject);
begin
if Visible then
Graph.Update;
end;
{ TGraphData }
constructor TGraphData.Create(Data: TGraphPoints);
begin
inherited Create;
Backup := Data;
end;
destructor TGraphData.Destroy;
begin
Finalize(Backup);
inherited;
end;
end.
|
unit UProperty;
interface
uses
System.Classes,URawdataDataType;
type
TDMSropertys = class
private
name :AnsiString;
dataType:RawdataDataType;
value :AnsiString;
public
constructor Create();
destructor Destroy; override;
function getName:string;
function getDatatype:RawdataDataType;
function getvalue:string;
procedure read(buffer:TFileStream);
end;
implementation
{ TDMSropertys }
constructor TDMSropertys.Create();
begin
inherited Create();
end;
destructor TDMSropertys.Destroy;
begin
dataType.Free;
end;
function TDMSropertys.getDatatype: RawdataDataType;
begin
result:= Self.dataType;
end;
function TDMSropertys.getName: string;
begin
result:= self.name;
end;
function TDMSropertys.getvalue: string;
begin
Result:= self.value;
end;
procedure TDMSropertys.read(buffer: TFileStream);
var
num,dataTypelength,typelen:Integer;
bytes:array[0..4] of Byte;
byteArray:array of Byte;
poin:PChar;
Chars,Chars1,Chars2:array of AnsiChar;
begin
buffer.Read(bytes,4);
num := Pinteger(@bytes)^;
SetLength(Chars,num);
buffer.Read(Chars[0],num);
setlength(name,num);
Move(Chars[0], name[1], num);
dataType:=RawdataDataType.Create;
buffer.Read(bytes,4);
typelen := Pinteger(@bytes)^;
dataType.get(typelen);
if dataType.type_name = tdsTypeString then
begin
buffer.Read(bytes,4);
num := Pinteger(@bytes)^;
Setlength(value,num);
SetLength(Chars1,num);
buffer.Read(Chars1[0],num);
Move(Chars1[0], value[1], num);
end
else
begin
dataTypelength := dataType.typeLength;
SetLength(Chars2,dataTypelength);
buffer.Read(Chars2[0],dataTypelength);
Setlength(value,dataTypelength);
Move(Chars2[0], value[1], dataTypelength);
end;
end;
end.
|
unit ModelIntf;
interface
uses
InfraValueTypeIntf;
type
IUser = interface(IInfraObject)
['{541D07F9-B7EA-4E9C-9241-AED9C0F97639}']
function GetLogin: IInfraString;
function GetPassword: IInfraString;
procedure SetLogin(const Value: IInfraString);
procedure SetPassword(const Value: IInfraString);
property Login: IInfraString read GetLogin write SetLogin;
property Password: IInfraString read GetPassword write SetPassword;
end;
ICity = interface(IInfraObject)
['{AAF2F0C1-034F-4A86-827C-6284A82860F4}']
function GetName: IInfraString;
function GetPopulation: IInfraInteger;
procedure SetName(const Value: IInfraString);
procedure SetPopulation(const Value: IInfraInteger);
procedure LoadSampleData;
property Name: IInfraString read GetName write SetName;
property Population: IInfraInteger read GetPopulation write SetPopulation;
end;
IPerson = interface(IInfraObject)
['{9281A67B-128F-4AC3-9B95-A2C5F61D47BD}']
function GetActive: IInfraBoolean;
function GetAddress: IInfraString;
function GetAmount: IInfraDouble;
function GetBirthday: IInfraDateTime;
function GetCountry: IInfraString;
function GetEmail: IInfraString;
function GetID: IInfraInteger;
function GetName: IInfraString;
function GetState: IInfraString;
function GetDetails: IInfraString;
function GetCity: ICity;
procedure SetActive(const Value: IInfraBoolean);
procedure SetAddress(const Value: IInfraString);
procedure SetAmount(const Value: IInfraDouble);
procedure SetBirthday(const Value: IInfraDateTime);
procedure SetCountry(const Value: IInfraString);
procedure SetEmail(const Value: IInfraString);
procedure SetID(const Value: IInfraInteger);
procedure SetName(const Value: IInfraString);
procedure SetState(const Value: IInfraString);
procedure SetDetails(const Value: IInfraString);
procedure SetCity(const Value: ICity);
procedure LoadSampleData;
property ID: IInfraInteger read GetID write SetID;
property Name: IInfraString read GetName write SetName;
property Email: IInfraString read GetEmail write SetEmail;
property Address: IInfraString read GetAddress write SetAddress;
property State: IInfraString read GetState write SetState;
property Country: IInfraString read GetCountry write SetCountry;
property Birthday: IInfraDateTime read GetBirthday write SetBirthday;
property Active: IInfraBoolean read GetActive write SetActive;
property Amount: IInfraDouble read GetAmount write SetAmount;
property Details: IInfraString read GetDetails write SetDetails;
property City: ICity read GetCity write SetCity;
end;
implementation
end.
|
unit Module;
interface
uses Graph, Crt;
type
Location = object
X, Y : integer;
procedure Init(InitX, InitY : integer);
function GetX : integer;
function GetY : integer;
end;
PointPtr = ^Point;
Point = object(Location)
Color : Word;
Visible : boolean;
constructor Init(InitX, InitY : integer; InitColor : Word);
destructor Done; virtual;
procedure Show; virtual;
procedure Hide; virtual;
function IsVisible : boolean;
procedure MoveTo(NewX, NewY : integer);
procedure Drag(DragBy : integer); virtual;
end;
TrianglePtr = ^Triangle;
Triangle = object(Point)
side : integer;
up : boolean;
constructor Init(InitX, InitY, InitSide : integer; InitUp : boolean; InitColor : word);
procedure Show; virtual;
end;
CirclePtr = ^Circle;
Circle = object (Point)
Radius : integer;
constructor Init(InitX, InitY : integer; InitRadius : integer; InitColor : Word);
procedure Show; virtual;
end;
RectanglePtr = ^Rectangle;
Rectangle = object(Point)
width, height: integer;
constructor Init(InitX, InitY, InitX1, InitY1:integer; InitColor: word);
procedure Show; virtual;
procedure Hide; virtual;
end;
function GetDelta(var DeltaX : integer; var DeltaY : integer) : boolean;
implementation
procedure Location.Init(InitX, InitY : integer);
begin
X := InitX;
Y := InitY;
end;
function Location.GetX : integer;
begin
GetX := X;
end;
function Location.GetY :integer;
begin
GetY := Y;
end;
constructor Point.Init(InitX, InitY : integer; InitColor : Word);
begin
Location.Init(InitX, InitY);
Color := InitColor;
Visible := False;
end;
destructor Point.Done;
begin
Hide;
end;
procedure Point.Show;
begin
Graph.SetColor(Color);
Visible := True;
PutPixel(X, Y, GetColor);
end;
procedure Point.Hide;
begin
Visible := False;
end;
function Point.IsVisible : boolean;
begin
IsVisible := Visible;
end;
procedure Point.MoveTo(NewX, NewY : integer);
begin
X := NewX;
Y := NewY;
Show;
end;
function GetDelta(var DeltaX : integer; var DeltaY : integer) : boolean;
var
KeyChar : char;
Quit : Boolean;
begin
DeltaX := 0; DeltaY := 0;
GetDelta := True;
repeat
KeyChar := ReadKey;
Quit := True;
case Ord(KeyChar) of
0: begin
KeyChar := ReadKey;
case Ord(KeyChar) of
72: DeltaY := -1;
80: DeltaY := 1;
75: DeltaX := -1;
77: DeltaX := 1;
else Quit := False;
end;
end;
13: GetDelta := False;
else Quit := False;
end;
until Quit;
end;
procedure Point.Drag(DragBy : integer);
var
DeltaX, DeltaY : integer;
FigureX, FigureY : integer;
begin
Show;
FigureX := GetX;
FigureY := GetY;
while GetDelta(DeltaX, DeltaY) do
begin
FigureX := FigureX + (DeltaX * DragBy);
FigureY := FigureY + (DEltaY * DragBy);
MoveTo(FigureX, FigureY);
end;
end;
constructor Rectangle.Init(InitX, InitY, InitX1, InitY1: integer; InitColor: word);
begin
width:= InitX1-InitX;
height:=InitY1-InitY;
Point.Init(InitX, InitY, InitColor);
end;
procedure Rectangle.Show;
begin
Graph.SetColor(Color);
Visible:=True;
Graph.Rectangle(X,Y,X+width, Y+height);
SetFillStyle(SolidFill, Color);
Bar(X,Y,X+width, Y+height);
end;
procedure Rectangle.Hide;
begin
Graph.SetColor(Color);
SetFillStyle(SolidFill,Color);
Bar(X,Y,X+width,Y+height);
Visible:=False;
end;
constructor Triangle.Init(InitX, InitY, InitSide : integer; InitUp : boolean; InitColor : word);
begin
side := InitSide;
up := InitUp;
Point.Init(InitX, InitY, InitColor);
end;
procedure Triangle.Show;
var Points : array[1..4] of PointType;
begin
Points[1].x := X;
Points[1].y := Y;
Points[2].x := Round(X + side/2);
if up then
Points[2].y := Round(Y - side * sqrt(3) / 2)
else
Points[2].y := Round(Y + side * sqrt(3) / 2);
Points[3].x := X + side;
Points[3].y := Y;
Points[4].x := X;
Points[4].y := Y;
Graph.SetColor(Color);
Visible := True;
SetFillStyle(SolidFill, Color);
Graph.FillPoly(4, Points);
end;
constructor Circle.Init(InitX, InitY : integer; InitRadius : integer; InitColor : Word);
begin
Point.Init(InitX, InitY, InitColor);
Radius := InitRadius;
end;
procedure Circle.Show;
begin
Graph.SetColor(Color);
Visible := True;
SetFillStyle(SolidFill, Color);
FillEllipse(X, Y, Radius, Radius);
Graph.SetColor(0);
end;
end.
|
unit Prng;
interface
type
HCkBinData = Pointer;
HCkPrng = Pointer;
HCkByteData = Pointer;
HCkString = Pointer;
function CkPrng_Create: HCkPrng; stdcall;
procedure CkPrng_Dispose(handle: HCkPrng); stdcall;
procedure CkPrng_getDebugLogFilePath(objHandle: HCkPrng; outPropVal: HCkString); stdcall;
procedure CkPrng_putDebugLogFilePath(objHandle: HCkPrng; newPropVal: PWideChar); stdcall;
function CkPrng__debugLogFilePath(objHandle: HCkPrng): PWideChar; stdcall;
procedure CkPrng_getLastErrorHtml(objHandle: HCkPrng; outPropVal: HCkString); stdcall;
function CkPrng__lastErrorHtml(objHandle: HCkPrng): PWideChar; stdcall;
procedure CkPrng_getLastErrorText(objHandle: HCkPrng; outPropVal: HCkString); stdcall;
function CkPrng__lastErrorText(objHandle: HCkPrng): PWideChar; stdcall;
procedure CkPrng_getLastErrorXml(objHandle: HCkPrng; outPropVal: HCkString); stdcall;
function CkPrng__lastErrorXml(objHandle: HCkPrng): PWideChar; stdcall;
function CkPrng_getLastMethodSuccess(objHandle: HCkPrng): wordbool; stdcall;
procedure CkPrng_putLastMethodSuccess(objHandle: HCkPrng; newPropVal: wordbool); stdcall;
procedure CkPrng_getPrngName(objHandle: HCkPrng; outPropVal: HCkString); stdcall;
procedure CkPrng_putPrngName(objHandle: HCkPrng; newPropVal: PWideChar); stdcall;
function CkPrng__prngName(objHandle: HCkPrng): PWideChar; stdcall;
function CkPrng_getVerboseLogging(objHandle: HCkPrng): wordbool; stdcall;
procedure CkPrng_putVerboseLogging(objHandle: HCkPrng; newPropVal: wordbool); stdcall;
procedure CkPrng_getVersion(objHandle: HCkPrng; outPropVal: HCkString); stdcall;
function CkPrng__version(objHandle: HCkPrng): PWideChar; stdcall;
function CkPrng_AddEntropy(objHandle: HCkPrng; entropy: PWideChar; encoding: PWideChar): wordbool; stdcall;
function CkPrng_AddEntropyBytes(objHandle: HCkPrng; entropy: HCkByteData): wordbool; stdcall;
function CkPrng_ExportEntropy(objHandle: HCkPrng; outStr: HCkString): wordbool; stdcall;
function CkPrng__exportEntropy(objHandle: HCkPrng): PWideChar; stdcall;
function CkPrng_FirebasePushId(objHandle: HCkPrng; outStr: HCkString): wordbool; stdcall;
function CkPrng__firebasePushId(objHandle: HCkPrng): PWideChar; stdcall;
function CkPrng_GenRandom(objHandle: HCkPrng; numBytes: Integer; encoding: PWideChar; outStr: HCkString): wordbool; stdcall;
function CkPrng__genRandom(objHandle: HCkPrng; numBytes: Integer; encoding: PWideChar): PWideChar; stdcall;
function CkPrng_GenRandomBd(objHandle: HCkPrng; numBytes: Integer; bd: HCkBinData): wordbool; stdcall;
function CkPrng_GenRandomBytes(objHandle: HCkPrng; numBytes: Integer; outData: HCkByteData): wordbool; stdcall;
function CkPrng_GetEntropy(objHandle: HCkPrng; numBytes: Integer; encoding: PWideChar; outStr: HCkString): wordbool; stdcall;
function CkPrng__getEntropy(objHandle: HCkPrng; numBytes: Integer; encoding: PWideChar): PWideChar; stdcall;
function CkPrng_GetEntropyBytes(objHandle: HCkPrng; numBytes: Integer; outData: HCkByteData): wordbool; stdcall;
function CkPrng_ImportEntropy(objHandle: HCkPrng; entropy: PWideChar): wordbool; stdcall;
function CkPrng_RandomInt(objHandle: HCkPrng; low: Integer; high: Integer): Integer; stdcall;
function CkPrng_RandomPassword(objHandle: HCkPrng; length: Integer; mustIncludeDigit: wordbool; upperAndLowercase: wordbool; mustHaveOneOf: PWideChar; excludeChars: PWideChar; outStr: HCkString): wordbool; stdcall;
function CkPrng__randomPassword(objHandle: HCkPrng; length: Integer; mustIncludeDigit: wordbool; upperAndLowercase: wordbool; mustHaveOneOf: PWideChar; excludeChars: PWideChar): PWideChar; stdcall;
function CkPrng_RandomString(objHandle: HCkPrng; length: Integer; bDigits: wordbool; bLower: wordbool; bUpper: wordbool; outStr: HCkString): wordbool; stdcall;
function CkPrng__randomString(objHandle: HCkPrng; length: Integer; bDigits: wordbool; bLower: wordbool; bUpper: wordbool): PWideChar; stdcall;
function CkPrng_SaveLastError(objHandle: HCkPrng; path: PWideChar): wordbool; stdcall;
implementation
{$Include chilkatDllPath.inc}
function CkPrng_Create; external DLLName;
procedure CkPrng_Dispose; external DLLName;
procedure CkPrng_getDebugLogFilePath; external DLLName;
procedure CkPrng_putDebugLogFilePath; external DLLName;
function CkPrng__debugLogFilePath; external DLLName;
procedure CkPrng_getLastErrorHtml; external DLLName;
function CkPrng__lastErrorHtml; external DLLName;
procedure CkPrng_getLastErrorText; external DLLName;
function CkPrng__lastErrorText; external DLLName;
procedure CkPrng_getLastErrorXml; external DLLName;
function CkPrng__lastErrorXml; external DLLName;
function CkPrng_getLastMethodSuccess; external DLLName;
procedure CkPrng_putLastMethodSuccess; external DLLName;
procedure CkPrng_getPrngName; external DLLName;
procedure CkPrng_putPrngName; external DLLName;
function CkPrng__prngName; external DLLName;
function CkPrng_getVerboseLogging; external DLLName;
procedure CkPrng_putVerboseLogging; external DLLName;
procedure CkPrng_getVersion; external DLLName;
function CkPrng__version; external DLLName;
function CkPrng_AddEntropy; external DLLName;
function CkPrng_AddEntropyBytes; external DLLName;
function CkPrng_ExportEntropy; external DLLName;
function CkPrng__exportEntropy; external DLLName;
function CkPrng_FirebasePushId; external DLLName;
function CkPrng__firebasePushId; external DLLName;
function CkPrng_GenRandom; external DLLName;
function CkPrng__genRandom; external DLLName;
function CkPrng_GenRandomBd; external DLLName;
function CkPrng_GenRandomBytes; external DLLName;
function CkPrng_GetEntropy; external DLLName;
function CkPrng__getEntropy; external DLLName;
function CkPrng_GetEntropyBytes; external DLLName;
function CkPrng_ImportEntropy; external DLLName;
function CkPrng_RandomInt; external DLLName;
function CkPrng_RandomPassword; external DLLName;
function CkPrng__randomPassword; external DLLName;
function CkPrng_RandomString; external DLLName;
function CkPrng__randomString; external DLLName;
function CkPrng_SaveLastError; external DLLName;
end.
|
Procedure ShowAMessage;
Var
DefaultMessage;
Begin
DefaultMessage := 'Welcome to Altium Designer scripting system';
ShowMessage(DefaultMessage);
End;
|
unit PubSub;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, System.Messaging;
type
//聊天记录的消息结构体
TChatMessageData = packed record
dwtype: DWORD; //消息类型
sztype, //消息类型
source, //消息来源
wxid, //微信ID/群ID
wxname, //微信名称/群名称
sender, //消息发送者
sendername, //消息发送者昵称
content: string; //消息内容
end;
// 好友列表
TFriendList = packed record
wxid: string;
nickname: string;
Remark:string;
wxNumber:string;//微信号
end;
TDefineNotify = record
TxtData: string;
MsgStruct: TChatMessageData;
FriendStruct:TFriendList;
protocol: Integer; //90 文本好友列表 91 结构体 接收消息
end;
var
DefineNotify: TDefineNotify;
var
message_bus: TMessageManager;
var
SubscriptionId: Integer;
var
MsgListener: TMessageListener;
implementation
initialization
message_bus := TMessageManager.DefaultManager;
end.
|
{**********************************************************
* Copyright (c) Zeljko Cvijanovic Teslic RS/BiH
* www.zeljus.com
* Created by: 30-8-15 19:28:32
***********************************************************}
unit ADBDataBase;
{$mode objfpc}{$H+}
{$modeswitch unicodestrings}
{$namespace zeljus.com.units}
interface
uses
androidr15, dataset;
type
{ ASQLDatabase }
ASQLDatabase = class(ADSSQLiteOpenHelper)
private
fContext: ACContext;
fSQL: JUList;
public
procedure onCreate(aDatabase: ADSSQLiteDatabase); override;
procedure onUpgrade(aDatabase: ADSSQLiteDatabase; oldVersion: integer; newVersion: integer); override;
procedure onOpen(aDatabase: ADSSqliteDatabase); override;
public
constructor Create(context: ACContext; DatabaseName: String;
factory: ADSSQLiteDatabase.InnerCursorFactory; version: integer);
function isopen: jboolean;
procedure beginTransaction;
procedure setTransactionSuccessful;
procedure endTransaction;
procedure beginTransactionNonExclusive;
function insert(aTableName: JLString; para2: JLString; aValues: ACContentValues): jlong;
function update(aTableName: JLString; aValues: ACContentValues; aWhere: JLString; para4: Arr1JLString): jint;
function delete(aTableName: JLString; aWhere: JLString; para3: Arr1JLString): jint;
function rawQuery(aSQL: JLString; para2: Arr1JLString): ADCursor;
function query(para1: jboolean; para2: JLString; para3: Arr1JLString; para4: JLString; para5: Arr1JLString; para6: JLString; para7: JLString; para8: JLString; para9: JLString): ADCursor;
procedure execSQL(aSQL: JLString);
property SQL: JUList read FSQL write FSQL;
end;
function checkExistsFile(aDataBase: JLString): boolean;
function CreateFields(aContext: ACContext; aDataBase: ASQLDatabase; aSQL: JLString): JUArrayList;
function CursorToFields(aCurosr: ADCursor): JUArrayList;
function InsertFields(aContext: ACContext; aDataBase: ASQLDatabase; aTable: JLString; aFields: JUList): boolean;
function DBEditFields(aContext: ACContext; aDataBase: ASQLDatabase; aTable: JLString; aFields: JUList): boolean;
function DBInsertFields(aContext: ACContext; aDataBase: ASQLDatabase; aTable: JLString; aFields: JUList): boolean;
implementation
uses AZCDialogs;
function checkExistsFile(aDataBase: JLString): boolean;
var
aFile: JIFile;
begin
aFile:= JIFile.Create(aDataBase);
result := aFile.exists;
end;
function CreateFields(aContext: ACContext; aDataBase: ASQLDatabase; aSQL: JLString): JUArrayList;
var
cur: ADCursor;
tField: ZCField;
i: Integer;
begin
cur := aDataBase.rawQuery(aSQL.toString, nil);
cur.moveToFirst;
Result := JUArrayList.create;
for i:=0 to Cur.getColumnCount - 1 do begin
tField := ZCField.create;
if Cur.getType(i) = 1 then tField.fDataType := ZCField.InnerFDataType.ftIinteger
else if Cur.getType(i) = 2 then tField.fDataType := ZCField.InnerFDataType.ftFloat
else tField.fDataType := ZCField.InnerFDataType.ftString;
tField.fName := cur.getColumnName(i).toString;
tField.fOldValue := Cur.getString(i).toString.trim;
tField.fValue := Cur.getString(i).toString.trim;
Result.add(JLObject(tField));
end;
end;
function CursorToFields(aCurosr: ADCursor): JUArrayList;
var
tField: ZCField;
i: Integer;
begin
Result := JUArrayList.create;
for i:=0 to aCurosr.getColumnCount - 1 do begin
tField := ZCField.create;
tField.fDataType := ZCField.InnerFDataType.ftString; // za prazno kursor nemoze odrediti tip
tField.fName := aCurosr.getColumnName(i).toString;
tField.fCharCase := ZCField.InnerEditCharCase.fNormal;
Result.add(JLObject(tField));
end;
end;
function InsertFields(aContext: ACContext; aDataBase: ASQLDatabase; aTable: JLString; aFields: JUList): boolean;
var
values: ACContentValues;
i: integer;
begin
Result := True;
values := ACContentValues.Create(1);
for i:=0 to aFields.size - 1 do begin
values.put(ZCField(aFields.get(i)).fName, ZCField(aFields.get(i)).fValue);
end;
aDataBase.beginTransactionNonExclusive;
try
try
aDataBase.insert(aTable, Nil, values);
aDataBase.setTransactionSuccessful;
finally
aDataBase.endTransaction;
end;
except
Result := False;
end;
end;
function DBEditFields(aContext: ACContext; aDataBase: ASQLDatabase; aTable: JLString; aFields: JUList): boolean;
var
values: ACContentValues;
i: integer;
key: JLString;
begin
Result := True;
key := JLString(ZCField(aFields.get(0)).fName).concat(' = ').concat(ZCField(aFields.get(0)).fValue);
values := ACContentValues.Create(1);
for i:=1 to aFields.size - 1 do begin
if (ZCField(aFields.get(i)).fChange) then begin
values.put(ZCField(aFields.get(i)).fName, ZCField(aFields.get(i)).fValue);
end;
end;
aDataBase.beginTransactionNonExclusive;
try
try
aDataBase.update (aTable, values, key, nil);
aDataBase.setTransactionSuccessful;
finally
aDataBase.endTransaction;
end;
except
Result := False;
end;
end;
function DBInsertFields(aContext: ACContext; aDataBase: ASQLDatabase; aTable: JLString; aFields: JUList): boolean;
var
values: ACContentValues;
i: integer;
begin
Result := True;
values := ACContentValues.Create(1);
for i:=1 to aFields.size - 1 do begin
if (ZCField(aFields.get(i)).fChange) then begin
values.put(ZCField(aFields.get(i)).fName, ZCField(aFields.get(i)).fValue);
end;
end;
aDataBase.beginTransactionNonExclusive;
try
try
aDataBase.insert(aTable, nil, values);
aDataBase.setTransactionSuccessful;
finally
aDataBase.endTransaction;
end;
except
Result := False;
end;
end;
{ ASQLDatabase }
constructor ASQLDatabase.Create(context: ACContext; DatabaseName: String;
factory: ADSSQLiteDatabase.InnerCursorFactory; version: integer);
begin
inherited Create(context, DatabaseName, factory, version);
FContext := context;
FSQL:= JUArrayList.Create;
end;
function ASQLDatabase.isopen: jboolean;
begin
Result := getWritableDatabase.isopen;
end;
procedure ASQLDatabase.beginTransaction;
begin
getWritableDatabase.beginTransaction;
end;
procedure ASQLDatabase.setTransactionSuccessful;
begin
getWritableDatabase.setTransactionSuccessful;
end;
procedure ASQLDatabase.endTransaction;
begin
getWritableDatabase.endTransaction;
end;
procedure ASQLDatabase.beginTransactionNonExclusive;
begin
getWritableDatabase.beginTransactionNonExclusive;
end;
function ASQLDatabase.insert(aTableName: JLString; para2: JLString;
aValues: ACContentValues): jlong;
begin
getWritableDatabase.insert(aTableName, para2, aValues);
end;
function ASQLDatabase.update(aTableName: JLString; aValues: ACContentValues;
aWhere: JLString; para4: Arr1JLString): jint;
begin
getWritableDatabase.update(aTableName, aValues, aWhere, para4);
end;
function ASQLDatabase.delete(aTableName: JLString; aWhere: JLString; para3: Arr1JLString): jint;
begin
Result := getWritableDatabase.delete(aTableName, aWhere, para3);
end;
function ASQLDatabase.rawQuery(aSQL: JLString; para2: Arr1JLString): ADCursor;
begin
Result := getReadableDatabase.rawQuery(aSQL , para2);
end;
function ASQLDatabase.query(para1: jboolean; para2: JLString;
para3: Arr1JLString; para4: JLString; para5: Arr1JLString; para6: JLString;
para7: JLString; para8: JLString; para9: JLString): ADCursor;
begin
Result := getReadableDatabase.query(para1, para2, para3, para4, para5, para6, para7, para8, para9);
end;
procedure ASQLDatabase.execSQL(aSQL: JLString);
begin
execSQL(aSQL);
end;
procedure ASQLDatabase.onCreate(aDatabase: ADSSQLiteDatabase);
var
i: integer;
begin
try
if aDatabase.isOpen then begin
for i:=0 to FSQL.size - 1 do
aDatabase.execSQL(FSQL.get(i).toString);
end;
except
on e: ADSQLException do
AULog.d('onCreateDB', e.getMessage);
end;
end;
procedure ASQLDatabase.onUpgrade(aDatabase: ADSSQLiteDatabase;
oldVersion: integer; newVersion: integer);
begin
// aDatabase.execSQL('DROP TABLE IF EXISTS scan_result');
// onCreate(aDatabase);
end;
procedure ASQLDatabase.onOpen(aDatabase: ADSSqliteDatabase);
begin
inherited onOpen(aDatabase);
if not aDatabase.isReadOnly then
aDatabase.ExecSQL('pragma foreign_keys=on;');
end;
end.
|
unit sCurrEdit;
{$I sDefs.inc}
interface
uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Menus, Forms,
StdCtrls, Mask, Buttons, sCustomComboEdit, acntUtils,
{$IFNDEF ALITE}
sCalcUnit,
{$ENDIF}
sConst;
type
{ TsCustomNumEdit }
{$IFNDEF NOTFORHELP}
TsCustomNumEdit = class(TsCustomComboEdit)
private
FCanvas: TControlCanvas;
FAlignment: TAlignment;
FFocused: Boolean;
FValue: Extended;
FMinValue, FMaxValue: Extended;
FDecimalPlaces: Cardinal;
FBeepOnError: Boolean;
FCheckOnExit: Boolean;
FFormatOnEditing: Boolean;
FFormatting: Boolean;
FDisplayFormat: POldString;
procedure SetFocused(Value: Boolean);
procedure SetAlignment(Value: TAlignment);
procedure SetBeepOnError(Value: Boolean);
procedure SetDisplayFormat(const Value: string);
function GetDisplayFormat: string;
procedure SetDecimalPlaces(Value: Cardinal);
function GetValue: Extended;
procedure SetValue(AValue: Extended);
function GetAsInteger: Longint;
procedure SetMaxValue(AValue: Extended);
procedure SetMinValue(AValue: Extended);
function GetText: string;
procedure SetText(const AValue: string);
function TextToValText(const AValue: string): string;
function CheckValue(NewValue: Extended; RaiseOnError: Boolean): Extended;
function IsFormatStored: Boolean;
procedure CMEnter(var Message: TCMEnter); message CM_ENTER;
procedure CMExit(var Message: TCMExit); message CM_EXIT;
procedure WMPaste(var Message: TMessage); message WM_PASTE;
procedure CalcWindowClose(Sender: TObject; var Action: TCloseAction); //KJS
protected
procedure Change; override;
procedure ReformatEditText; dynamic;
procedure DataChanged; virtual;
function DefFormat: string; virtual;
procedure KeyPress(var Key: Char); override;
function IsValidChar(Key: Char): Boolean; virtual;
function FormatDisplayText(Value: Extended): string;
function GetDisplayText: string; virtual;
procedure Reset; override;
procedure CheckRange;
procedure UpdateData;
property Formatting: Boolean read FFormatting;
property Alignment: TAlignment read FAlignment write SetAlignment default taRightJustify;
property BeepOnError: Boolean read FBeepOnError write SetBeepOnError default True;
property CheckOnExit: Boolean read FCheckOnExit write FCheckOnExit default False;
property DecimalPlaces: Cardinal read FDecimalPlaces write SetDecimalPlaces default 2;
property DisplayFormat: string read GetDisplayFormat write SetDisplayFormat stored IsFormatStored;
property MaxValue: Extended read FMaxValue write SetMaxValue;
property MinValue: Extended read FMinValue write SetMinValue;
property Text: string read GetText write SetText stored False;
property MaxLength default 0;
procedure PopupWindowShow; override;
property ClickKey;
procedure PaintText; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Clear; override;
procedure WndProc (var Message: TMessage); override;
property AsInteger: Longint read GetAsInteger;
property DisplayText: string read GetDisplayText;
property DroppedDown;
property Value: Extended read GetValue write SetValue;
end;
{$ENDIF} // NOTFORHELP
{ TsCalcEdit }
TsCalcEdit = class(TsCustomNumEdit)
public
property AsInteger;
{$IFNDEF NOTFORHELP}
constructor Create(AOwner: TComponent); override;
published
property ClickKey;
property AutoSelect;
property BeepOnError;
property DirectInput;
property DragCursor;
property Enabled;
property Font;
property HideSelection;
property ImeMode;
property ImeName;
property MaxLength;
property ParentFont;
property ParentShowHint;
property PopupAlign;
property PopupMenu;
property ReadOnly;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnButtonClick;
property OnChange;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDrag;
{$ENDIF} // NOTFORHELP
property Alignment;
property CheckOnExit;
property DecimalPlaces;
property DisplayFormat;
property MaxValue;
property MinValue;
property Text;
property Value;
end;
implementation
uses Consts, sVclUtils, sStyleSimply, sMessages, sMaskData, sGraphUtils, sCommonData, sGlyphUtils, sSKinManager;
{ TsCustomNumEdit }
constructor TsCustomNumEdit.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FAlignment := taRightJustify;
FDisplayFormat := NewStr(DefFormat);
MaxLength := 0;
FDecimalPlaces := 2;
FBeepOnError := True;
inherited Text := '';
inherited Alignment := taLeftJustify;
DataChanged;
PopupWidth := 213;
PopupHeight := 149;
end;
destructor TsCustomNumEdit.Destroy;
begin
if FPopupWindow <> nil then FreeAndNil(FPopupWindow);
if Assigned(FCanvas) then FreeAndNil(FCanvas);
DisposeStr(FDisplayFormat);
inherited Destroy;
end;
function TsCustomNumEdit.DefFormat: string;
begin
Result := '### ### ##0.00;-### ### ##0.00;0';
end;
function TsCustomNumEdit.IsFormatStored: Boolean;
begin
Result := (DisplayFormat <> DefFormat);
end;
function TsCustomNumEdit.IsValidChar(Key: Char): Boolean;
var
S: string;
SelStart, SelStop, DecPos: Integer;
RetValue: Extended;
begin
Result := False;
if (Key = '-') and ((MinValue >= 0) and (MaxValue <> MinValue)) then Exit;
S := EditText;
GetSel(SelStart, SelStop);
System.Delete(S, SelStart + 1, SelStop - SelStart);
System.Insert(Key, S, SelStart + 1);
S := TextToValText(S);
DecPos := Pos(DecimalSeparator, S);
if (DecPos > 0) then begin
SelStart := Pos('E', UpperCase(S));
if (SelStart > DecPos) then DecPos := SelStart - DecPos else DecPos := Length(S) - DecPos;
if DecPos > Integer(FDecimalPlaces) then Exit;
end;
Result := IsValidFloat(S, RetValue);
if Result and (FMinValue >= 0) and (FMaxValue > 0) and (RetValue < 0) then Result := False;
end;
procedure TsCustomNumEdit.KeyPress(var Key: Char);
begin
if CharInSet(AnsiChar(Key), ['.', ','] - [ThousandSeparator]) then Key := DecimalSeparator;
inherited KeyPress(Key);
if not CharInSet(Key, [#8]) and not IsValidChar(Key) then begin
if BeepOnError then MessageBeep(0);
Key := #0;
end
else if Key = #27 then begin
Reset;
Key := #0;
end;
end;
procedure TsCustomNumEdit.Reset;
begin
DataChanged;
SelectAll;
end;
procedure TsCustomNumEdit.SetBeepOnError(Value: Boolean);
begin
if FBeepOnError <> Value then begin
FBeepOnError := Value;
end;
end;
procedure TsCustomNumEdit.SetAlignment(Value: TAlignment);
begin
if FAlignment <> Value then begin
FAlignment := Value;
SkinData.Invalidate;
end;
end;
procedure TsCustomNumEdit.SetDisplayFormat(const Value: string);
begin
if DisplayFormat <> Value then begin
AssignStr(FDisplayFormat, Value);
SkinData.Invalidate;
DataChanged;
end;
end;
function TsCustomNumEdit.GetDisplayFormat: string;
begin
Result := FDisplayFormat^;
end;
procedure TsCustomNumEdit.SetFocused(Value: Boolean);
begin
if FFocused <> Value then begin
FFocused := Value;
if not Focused or not AutoSelect then SkinData.Invalidate;
FFormatting := True;
try
DataChanged;
finally
FFormatting := False;
end;
end;
end;
procedure TsCustomNumEdit.SetDecimalPlaces(Value: Cardinal);
begin
if FDecimalPlaces <> Value then begin
FDecimalPlaces := Value;
DataChanged;
SkinData.Invalidate;
end;
end;
function TsCustomNumEdit.FormatDisplayText(Value: Extended): string;
begin
if DisplayFormat <> '' then begin
Result := FormatFloat(DisplayFormat, Value)
end
else begin
Result := FloatToStr(Value);
end;
end;
function TsCustomNumEdit.GetDisplayText: string;
begin
if not Focused then Result := FormatDisplayText(StrToFloat(TextToValText(Text))) else Result := EditText;
end;
procedure TsCustomNumEdit.Clear;
begin
Text := '';
end;
procedure TsCustomNumEdit.DataChanged;
var
EditFormat : string;
begin
if EditMask = '' then begin
EditFormat := '0';
if FDecimalPlaces > 0 then EditFormat := EditFormat + '.' + MakeStr('#', FDecimalPlaces);
EditText := FormatFloat(EditFormat, FValue);
end;
end;
function TsCustomNumEdit.CheckValue(NewValue: Extended; RaiseOnError: Boolean): Extended;
begin
Result := NewValue;
if (FMaxValue <> FMinValue) then begin
if (FMaxValue > FMinValue) then begin
if NewValue < FMinValue
then Result := FMinValue
else if NewValue > FMaxValue then Result := FMaxValue;
end
else begin
if FMaxValue = 0 then begin
if NewValue < FMinValue then Result := FMinValue;
end
else if FMinValue = 0 then begin
if NewValue > FMaxValue then Result := FMaxValue;
end;
end;
end;
end;
procedure TsCustomNumEdit.CheckRange;
begin
if not (csDesigning in ComponentState) and CheckOnExit then CheckValue(StrToFloat(TextToValText(EditText)), True);
end;
procedure TsCustomNumEdit.UpdateData;
var
s : string;
Minus : integer;
begin
s := Text;
if pos('-', s) = 1 then begin
Delete(s, 1, 1);
Minus := -1
end
else Minus := 1;
FValue := CheckValue(StrToFloat(TextToValText('0' + s)), False) * Minus;
Exit;
Text := DelChars(Text, '?');
Text := DelChars(Text, #13);
Text := DelChars(Text, #10);
FValue := CheckValue(StrToFloat(TextToValText('0' + Text)), False);
end;
function TsCustomNumEdit.GetValue: Extended;
begin
if not (csDesigning in ComponentState) then
try
UpdateData;
except
FValue := FMinValue;
end;
Result := FValue;
end;
procedure TsCustomNumEdit.SetValue(AValue: Extended);
begin
FValue := CheckValue(AValue, False);
DataChanged;
SkinData.Invalidate;
end;
function TsCustomNumEdit.GetAsInteger: Longint;
begin
Result := Trunc(Value);
end;
procedure TsCustomNumEdit.SetMinValue(AValue: Extended);
begin
if FMinValue <> AValue then begin
FMinValue := AValue;
Value := FValue;
end;
end;
procedure TsCustomNumEdit.SetMaxValue(AValue: Extended);
begin
if FMaxValue <> AValue then begin
FMaxValue := AValue;
Value := FValue;
end;
end;
function TsCustomNumEdit.GetText: string;
begin
Result := inherited Text;
Result := DelChars(Result, '?');
Result := DelChars(Result, #13);
Result := DelChars(Result, #10);
end;
function TsCustomNumEdit.TextToValText(const AValue: string): string;
begin
Result := DelRSpace(AValue);
if DecimalSeparator <> ThousandSeparator then Result := DelChars(Result, ThousandSeparator);
if (DecimalSeparator <> '.') and (ThousandSeparator <> '.') then Result := ReplaceStr(Result, '.', DecimalSeparator);
if (DecimalSeparator <> ',') and (ThousandSeparator <> ',') then Result := ReplaceStr(Result, ',', DecimalSeparator);
if Result = '' then Result := '0' else if Result = '-' then Result := '-0';
end;
procedure TsCustomNumEdit.SetText(const AValue: string);
begin
if not (csReading in ComponentState) then begin
FValue := CheckValue(StrToFloat(TextToValText(AValue)), False);
DataChanged;
SkinData.Invalidate;
end;
end;
procedure TsCustomNumEdit.ReformatEditText;
var
S: string;
IsEmpty: Boolean;
OldLen, SelStart, SelStop: Integer;
begin
FFormatting := True;
try
S := inherited Text;
OldLen := Length(S);
IsEmpty := (OldLen = 0) or (S = '-');
if HandleAllocated then GetSel(SelStart, SelStop);
if not IsEmpty then S := TextToValText(S);
S := FormatFloatStr(S, Pos(',', DisplayFormat) > 0);
inherited Text := S;
if HandleAllocated and (GetFocus = Handle) and not (csDesigning in ComponentState) then begin
Inc(SelStart, Length(S) - OldLen);
SetCursor(SelStart);
end;
finally
FFormatting := False;
end;
end;
procedure TsCustomNumEdit.Change;
begin
if not FFormatting then begin
if FFormatOnEditing and FFocused then ReformatEditText;
inherited Change;
end;
end;
procedure TsCustomNumEdit.WMPaste(var Message: TMessage);
var
S: string;
begin
S := EditText;
try
inherited;
UpdateData;
except
EditText := S;
SelectAll;
if CanFocus then SetFocus;
if BeepOnError then MessageBeep(0);
end;
end;
procedure TsCustomNumEdit.CMEnter(var Message: TCMEnter);
begin
SetFocused(True);
if FFormatOnEditing then ReformatEditText;
inherited;
end;
procedure TsCustomNumEdit.CMExit(var Message: TCMExit);
begin
try
CheckRange;
UpdateData;
except
SelectAll;
if CanFocus then SetFocus;
raise;
end;
SetFocused(False);
SetCursor(0);
DoExit;
end;
procedure TsCustomNumEdit.PopupWindowShow;
begin
FadingForbidden := True;
if not Assigned(FPopupWindow) then begin
FPopupWindow := TsCalcForm.Create(Self);
TsCalcForm(FPopupWindow).Height := TsCalcForm(FPopupWindow).Height - 24;
end;
TsCalcForm(FPopupWindow).Position := poDefault;
if TsCalcForm(FPopupWindow).sDragBar1 <> nil then TsCalcForm(FPopupWindow).sDragBar1.Visible := False;
TsCalcForm(FPopupWindow).FPrecision := 16;
TsCalcForm(FPopupWindow).FEditor := Self;
TsCalcForm(FPopupWindow).SetText(Text);
TsCalcForm(FPopupWindow).OnClose := CalcWindowClose;
inherited;
FadingForbidden := False;
end;
procedure TsCustomNumEdit.CalcWindowClose(Sender: TObject; var Action: TCloseAction);
begin
Inherited;
end;
procedure TsCustomNumEdit.PaintText;
var
R : TRect;
s : string;
bw : integer;
al : TAlignment;
begin
SkinData.FCacheBMP.Canvas.Font.Assign(Font);
bw := BorderWidth;
R := Rect(bw, bw, Width - bw - integer(ShowButton) * Button.Width, Height - bw);
if IsActive then al := taLeftJustify else al := Alignment;
if PasswordChar = #0 then
WriteTextEx(SkinData.FCacheBMP.Canvas, PChar(DisplayText), True, R, DT_TOP or GetStringFlags(Self, al) or DT_NOPREFIX,
SkinData, ControlIsActive(SkinData))
else begin
SetLength(s, Length(EditText));
FillChar(s[1], Length(s), PasswordChar);
WriteTextEx(SkinData.FCacheBMP.Canvas, PChar(s), True, R, DT_TOP or DT_SINGLELINE or DT_WORDBREAK or GetStringFlags(Self, al) or DT_NOPREFIX,
SkinData, ControlIsActive(SkinData));
end;
end;
procedure TsCustomNumEdit.WndProc(var Message: TMessage);
begin
case Message.Msg of
CM_MOUSEENTER : if not (csDesigning in ComponentState) and SkinData.Skinned then begin // Preventing of client area repainting
SkinData.FMouseAbove := True;
DefaultManager.ActiveControl := Handle;
ShowGlowingIfNeeded(SkinData);
SkinData.BGChanged := True;
SendMessage(Handle, WM_NCPAINT, 0, 0);
Exit
end;
end;
inherited;
end;
{ TsCalcEdit }
constructor TsCalcEdit.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDefBmpID := iBTN_CALC;
end;
end.
|
unit UXmlUtil;
interface
uses xmldom, XMLIntf, msxmldom, XMLDoc, ActiveX, SysUtils, Forms, Classes, SyncObjs,
DateUtils, UMyUtil, UChangeInfo, IniFiles;
type
// xml 信息 辅助类
MyXmlUtil = class
public
class function getXmlPath : string;
class function getXmlPathTest : string;
class procedure IniXml;
public // 修改
class function AddChild( Parent : IXMLNode; ChildName : string ):IXMLNode;overload;
class function AddChild( Parent : IXMLNode; ChildName, Value : string ):IXMLNode;overload;
class function AddChild( Parent : IXMLNode; ChildName : string; Value : Integer ):IXMLNode;overload;
class function AddChild( Parent : IXMLNode; ChildName : string; Value : Int64 ):IXMLNode;overload;
class function AddChild( Parent : IXMLNode; ChildName : string; Value : Double ):IXMLNode;overload;
class function AddChild( Parent : IXMLNode; ChildName : string; Value : Boolean ):IXMLNode;overload;
class procedure DeleteChild( Parent : IXMLNode; ChildName : string );
public // 读取
class function GetChildValue( Parent : IXMLNode; ChildName : string ): string;
class function GetChildIntValue( Parent : IXMLNode; ChildName : string ): Integer;
class function GetChildInt64Value( Parent : IXMLNode; ChildName : string ): Int64;
class function GetChildBoolValue( Parent : IXMLNode; ChildName : string ): Boolean;
class function GetChildFloatValue( Parent : IXMLNode; ChildName : string ): Double;
public // Hash: Key - Value
class function AddListChild( Parent : IXMLNode; Key : string ):IXMLNode;overload;
class procedure DeleteListChild( Parent : IXMLNode; Key : string );overload;
class function FindListChild( Parent : IXMLNode; Key : string ):IXMLNode;overload;
public // List
class function AddListChild( Parent : IXMLNode ):IXMLNode;overload;
class procedure DeleteListChild( Parent : IXMLNode; NodeIndex : Integer );overload;
end;
// 写 Xml 文件 线程
TXmlDocSaveThread = class( TThread )
private
IsSaveNow : Boolean;
public
constructor Create;
procedure SaveXmlNow;
destructor Destroy; override;
protected
procedure Execute; override;
private
procedure SaveXmlFile;
end;
TMyXmlSave = class
private
XmlDocSaveThread : TXmlDocSaveThread;
public
constructor Create;
procedure StartThread;
procedure SaveNow;
destructor Destroy; override;
end;
const
Xml_ChildName : string = 'cn';
Xml_AttrKey : string = 'k';
Xml_ListChild : string = 'lc';
// 根
Xml_BackupCow = 'bc';
// 备份信息
Xml_MyBackupInfo = 'mbi';
Xml_BackupPathHash = 'bph';
// 备份文件 删除信息
Xml_MyBackupRemoveNotifyInfo = 'mbrni';
Xml_RemoveBackupNotifyHash = 'rbnh';
// 云信息
Xml_MyCloudPathInfo = 'mcpi';
Xml_CloudPathHash = 'cph';
// 云文件 删除信息
Xml_MyCloudRemoveNotifyInfo = 'mcrni';
Xml_RemoveCloudNotifyHash = 'rcnh';
// 网络计算机信息
Xml_MyNetPcInfo = 'mnpi';
Xml_NetPcHash = 'nph';
// 批注册信息
Xml_MyBatRegisterInfo = 'mbri';
Xml_PcBatRegisterHash = 'pbrh';
// 搜索下载信息
Xml_MySearchDownInfo = 'msdi';
Xml_SearchDownFileHash = 'sdfh';
// 恢复文件信息
Xml_MyRestoreFileInfo = 'mrfi';
Xml_RestoreItemHash = 'rih';
// 本地备份 源信息
Xml_MyLocalBackupSourceInfo = 'mlbsi';
Xml_LocalBackupSourceList = 'lbsl';
// 本地备份 目标信息
Xml_MyDestinationInfo = 'mdti';
Xml_DestinationList = 'dtl';
// 接收文件信息
Xml_MyFileReceiveInfo = 'mfri';
Xml_FileReceiveList = 'frl';
Xml_FileReceiveCancelList = 'frcl';
// 发送文件信息
Xml_MyFileSendInfo = 'mfsi';
Xml_FileSendList = 'fsl';
Xml_FileSendCancelList = 'fscl';
// 共享文件信息
Xml_MySharePathInfo = 'mspi';
Xml_SharePathList = 'spl';
Xml_ShareDownList = 'sdl';
Xml_ShareHisrotyList = 'shl';
Xml_ShareFavoriteList = 'sfl';
// 读取 Xml信息
XmlReadCount_Sleep = 10;
var
// Xml Doc 根目录
MyXmlDoc : TXMLDocument;
// 备份信息
MyBackupInfoXml : IXMLNode;
BackupPathHashXml : IXMLNode;
// 备份文件 删除信息
MyBackupRemoveNotifyInfoXml : IXMLNode;
RemoveBackupNotifyHashXml : IXMLNode;
// 云信息
MyCloudPathInfoXml : IXMLNode;
CloudPathHashXml : IXMLNode;
// 云文件 删除信息
MyCloudRemoveNotifyInfoXml : IXMLNode;
RemoveCloudNotifyHashXml : IXMLNode;
// 网络计算机信息
MyNetPcInfoXml : IXMLNode;
NetPcHashXml : IXMLNode;
// 批注册信息
MyBatRegisterXml : IXMLNode;
PcBatRegisterHashXml : IXMLNode;
// 搜索下载信息
MySearchDownXml : IXMLNode;
SearchDownFileHashXml : IXMLNode;
// 恢复文件信息
MyRestoreFileXml : IXMLNode;
RestoreItemHashXml : IXMLNode;
// 本地备份 目标信息
MyDestinationXml : IXMLNode;
DestinationListXml : IXMLNode;
// 本地备份 源信息
MyLocalBackupSourceXml : IXMLNode;
LocalBackupSourceListXml : IXMLNode;
// 接收文件信息
MyFileReceiveXml : IXMLNode;
FileReceiveListXml : IXMLNode;
FileReceiveCancelListXml : IXMLNode;
// 发送文件信息
MyFileSendXml : IXMLNode;
FileSendListXml : IXMLNode;
FileSendCancelListXml : IXMLNode;
// 共享文件信息
MySharePathXml : IXMLNode;
SharePathListXml : IXMLNode;
ShareDownListXml : IXMLNode;
ShareHisrotyListXml : IXMLNode;
ShareFavoriteListXml : IXMLNode;
// Xml 定时保存
MyXmlSave : TMyXmlSave;
implementation
{ TMyXmlUtil }
class procedure MyXmlUtil.DeleteChild(Parent: IXMLNode; ChildName: string);
var
i : Integer;
begin
for i := 0 to Parent.ChildNodes.Count - 1 do
if Parent.ChildNodes[i].NodeName = ChildName then
begin
Parent.ChildNodes.Delete(i);
Break;
end;
end;
class procedure MyXmlUtil.DeleteListChild(Parent: IXMLNode; NodeIndex: Integer);
begin
Parent.ChildNodes.Delete( NodeIndex );
end;
class procedure MyXmlUtil.DeleteListChild(Parent: IXMLNode; Key: string);
var
i : Integer;
Child : IXMLNode;
begin
for i := 0 to Parent.ChildNodes.Count - 1 do
begin
Child := Parent.ChildNodes[i];
if Child.Attributes[ Xml_AttrKey ] = Key then
begin
Parent.ChildNodes.Delete( i );
Break;
end;
end;
end;
class function MyXmlUtil.FindListChild(Parent: IXMLNode; Key: string): IXMLNode;
var
i : Integer;
Child : IXMLNode;
begin
Result := nil;
for i := 0 to Parent.ChildNodes.Count - 1 do
begin
Child := Parent.ChildNodes[i];
if Child.Attributes[ Xml_AttrKey ] = Key then
begin
Result := Child;
Break;
end;
end;
end;
class function MyXmlUtil.GetChildBoolValue(Parent: IXMLNode;
ChildName: string): Boolean;
begin
Result := StrToBoolDef( GetChildValue( Parent, ChildName ), False );
end;
class function MyXmlUtil.GetChildFloatValue(Parent: IXMLNode;
ChildName: string): Double;
begin
Result := StrToFloatDef( GetChildValue( Parent, ChildName ), Now );
end;
class function MyXmlUtil.GetChildInt64Value(Parent: IXMLNode;
ChildName: string): Int64;
begin
Result := StrToInt64Def( GetChildValue( Parent, ChildName ), 0 );
end;
class function MyXmlUtil.GetChildIntValue(Parent: IXMLNode;
ChildName: string): Integer;
begin
Result := StrToIntDef( GetChildValue( Parent, ChildName ), 0 );
end;
class function MyXmlUtil.GetChildValue(Parent: IXMLNode;
ChildName: string): string;
var
Child : IXMLNode;
begin
Result := '';
Child := Parent.ChildNodes.FindNode( ChildName );
if Child <> nil then
Result := Child.Text;
end;
class function MyXmlUtil.getXmlPath: string;
begin
Result := MyAppDataPath.get + 'BackupCowInfo.dat';
end;
class function MyXmlUtil.getXmlPathTest: string;
begin
Result := MyAppDataPath.get + 'BackupCowInfo.xml';
end;
class procedure MyXmlUtil.IniXml;
var
XmlPath : string;
RootNode : IXMLNode;
begin
// 创建 根目录
if MyXmlDoc.DocumentElement = nil then
MyXmlDoc.DocumentElement := MyXmlDoc.CreateNode( Xml_BackupCow );
RootNode := MyXmlDoc.DocumentElement;
// 备份信息的 xml 节点
MyBackupInfoXml := MyXmlUtil.AddChild( RootNode, Xml_MyBackupInfo );
BackupPathHashXml := MyXmlUtil.AddChild( MyBackupInfoXml, Xml_BackupPathHash );
// 备份文件 删除信息 xml 节点
MyBackupRemoveNotifyInfoXml := MyXmlUtil.AddChild( RootNode, Xml_MyBackupRemoveNotifyInfo );
RemoveBackupNotifyHashXml := MyXmlUtil.AddChild( MyBackupRemoveNotifyInfoXml, Xml_RemoveBackupNotifyHash );
// 云信息的 xml 节点
MyCloudPathInfoXml := MyXmlUtil.AddChild( RootNode, Xml_MyCloudPathInfo );
CloudPathHashXml := MyXmlUtil.AddChild( MyCloudPathInfoXml, Xml_CloudPathHash );
// 云文件 删除信息 xml 节点
MyCloudRemoveNotifyInfoXml := MyXmlUtil.AddChild( RootNode, Xml_MyCloudRemoveNotifyInfo );
RemoveCloudNotifyHashXml := MyXmlUtil.AddChild( MyCloudRemoveNotifyInfoXml, Xml_RemoveCloudNotifyHash );
// 网络计算机信息的 Xml 节点
MyNetPcInfoXml := MyXmlUtil.AddChild( RootNode, Xml_MyNetPcInfo );
NetPcHashXml := MyXmlUtil.AddChild( MyNetPcInfoXml, Xml_NetPcHash );
// 批注册 Xml 节点
MyBatRegisterXml := MyXmlUtil.AddChild( RootNode, Xml_MyBatRegisterInfo );
PcBatRegisterHashXml := MyXmlUtil.AddChild( MyBatRegisterXml, Xml_PcBatRegisterHash );
// 搜索下载 Xml 节点
MySearchDownXml := MyXmlUtil.AddChild( RootNode, Xml_MySearchDownInfo );
SearchDownFileHashXml := MyXmlUtil.AddChild( MySearchDownXml, Xml_SearchDownFileHash );
// 恢复文件 Xml 节点
MyRestoreFileXml := MyXmlUtil.AddChild( RootNode, Xml_MyRestoreFileInfo );
RestoreItemHashXml := MyXmlUtil.AddChild( MyRestoreFileXml, Xml_RestoreItemHash );
// 本机备份 源信息 Xml 节点
MyLocalBackupSourceXml := MyXmlUtil.AddChild( RootNode, Xml_MyLocalBackupSourceInfo );
LocalBackupSourceListXml := MyXmlUtil.AddChild( MyLocalBackupSourceXml, Xml_LocalBackupSourceList );
// 本机备份 目标信息 Xml 节点
MyDestinationXml := MyXmlUtil.AddChild( RootNode, Xml_MyDestinationInfo );
DestinationListXml := MyXmlUtil.AddChild( MyDestinationXml, Xml_DestinationList );
// 接收文件 Xml 节点
MyFileReceiveXml := MyXmlUtil.AddChild( RootNode, Xml_MyFileReceiveInfo );
FileReceiveListXml := MyXmlUtil.AddChild( MyFileReceiveXml, Xml_FileReceiveList );
FileReceiveCancelListXml := MyXmlUtil.AddChild( MyFileReceiveXml, Xml_FileReceiveCancelList );
// 发送文件 Xml 节点
MyFileSendXml := MyXmlUtil.AddChild( RootNode, Xml_MyFileSendInfo );
FileSendListXml := MyXmlUtil.AddChild( MyFileSendXml, Xml_FileSendList );
FileSendCancelListXml := MyXmlUtil.AddChild( MyFileSendXml, Xml_FileSendCancelList );
// 共享文件 Xml 节点
MySharePathXml := MyXmlUtil.AddChild( RootNode, Xml_MySharePathInfo );
SharePathListXml := MyXmlUtil.AddChild( MySharePathXml, Xml_SharePathList );
ShareDownListXml := MyXmlUtil.AddChild( MySharePathXml, Xml_ShareDownList );
ShareHisrotyListXml := MyXmlUtil.AddChild( MySharePathXml, Xml_ShareHisrotyList );
ShareFavoriteListXml := MyXmlUtil.AddChild( MySharePathXml, Xml_ShareFavoriteList );
end;
class function MyXmlUtil.AddChild(Parent: IXMLNode; ChildName,
Value: string): IXMLNode;
begin
Result := AddChild( Parent, ChildName );
Result.Text := Value;
end;
class function MyXmlUtil.AddChild(Parent: IXMLNode; ChildName : string;
Value: Int64): IXMLNode;
begin
Result := AddChild( Parent, ChildName, IntToStr( Value ) );
end;
class function MyXmlUtil.AddChild(Parent: IXMLNode; ChildName : string;
Value: Integer): IXMLNode;
begin
Result := AddChild( Parent, ChildName, IntToStr( Value ) );
end;
class function MyXmlUtil.AddChild(Parent: IXMLNode; ChildName : string;
Value: Boolean): IXMLNode;
begin
Result := AddChild( Parent, ChildName, BoolToStr( Value ) );
end;
class function MyXmlUtil.AddChild(Parent: IXMLNode; ChildName : string;
Value: Double): IXMLNode;
begin
Result := AddChild( Parent, ChildName, FloatToStr( Value ) );
end;
class function MyXmlUtil.AddListChild(Parent: IXMLNode): IXMLNode;
begin
Result := Parent.AddChild( Xml_ListChild );
end;
class function MyXmlUtil.AddListChild(Parent: IXMLNode; Key: string): IXMLNode;
var
Child : IXMLNode;
begin
// 找不到则创建
Child := FindListChild( Parent, Key );
if Child = nil then
begin
Child := Parent.AddChild( Xml_ChildName );
Child.Attributes[ Xml_AttrKey ] := Key;
end;
Result := Child;
end;
class function MyXmlUtil.AddChild(Parent: IXMLNode;
ChildName: string): IXMLNode;
begin
Result := Parent.ChildNodes.FindNode( ChildName );
if Result = nil then
Result := Parent.AddChild( ChildName );
end;
{ TXmlDocSaveThread }
constructor TXmlDocSaveThread.Create;
begin
inherited Create( True );
IsSaveNow := False;
end;
destructor TXmlDocSaveThread.Destroy;
begin
Terminate;
Resume;
WaitFor;
inherited;
end;
procedure TXmlDocSaveThread.Execute;
var
StartTime : TDateTime;
begin
while not Terminated do
begin
// 10 分钟 保存一次
IsSaveNow := False;
StartTime := Now;
while not Terminated and ( MinutesBetween( Now, StartTime ) < 10 )
and not IsSaveNow
do
Sleep(100);
// 保存 Xml 文件
SaveXmlFile;
end;
inherited;
end;
procedure TXmlDocSaveThread.SaveXmlFile;
begin
MyXmlChange.EnterXml;
MyXmlDoc.SaveToFile( MyXmlUtil.getXmlPath );
MyXmlChange.LeaveXml;
end;
procedure TXmlDocSaveThread.SaveXmlNow;
begin
IsSaveNow := True;
end;
{ TMyXmlSave }
constructor TMyXmlSave.Create;
begin
XmlDocSaveThread := TXmlDocSaveThread.Create;
end;
destructor TMyXmlSave.Destroy;
begin
XmlDocSaveThread.Free;
inherited;
end;
procedure TMyXmlSave.SaveNow;
begin
XmlDocSaveThread.SaveXmlNow;
end;
procedure TMyXmlSave.StartThread;
begin
XmlDocSaveThread.Resume;
end;
end.
|
unit UDevices;
interface
uses
Windows,
Classes,
eiTypes,
eiHelpers,
eiProtocol,
eiConstants,
UServerTypes,
ULogger;
type
TBaseDevice = class(TInterfacedObject)
private
FLogger: ILogger;
public
// function BlockRead(const offset: short; const dataType: DataTypeEnum; const length: byte): DynamicWordArray; virtual; abstract;
// procedure BlockWrite(const offset: short; const value: DynamicWordArray; const dataType: DataTypeEnum); virtual; abstract;
end;
TEasyIpDevice = class(TBaseDevice, IDevice)
private
FFlags: array[0..9999] of short;
FInputs: array[0..255] of short;
FOutputs: array[0..255] of short;
FRegisters: array[0..255] of short;
FTimers: array[0..255] of short;
public
constructor Create(logger: ILogger);
function BlockRead(const offset: short; const dataType: DataTypeEnum; const dataLength: byte): DynamicWordArray;
procedure BlockWrite(const offset: short; const value: DynamicWordArray; const dataType: DataTypeEnum);
function RangeCheck(const offset: short; const dataType: DataTypeEnum; const dataLength: byte): short;
end;
implementation
constructor TEasyIpDevice.Create(logger: ILogger);
begin
inherited Create;
FLogger := logger;
end;
function TEasyIpDevice.BlockRead(const offset: short; const dataType: DataTypeEnum; const dataLength: byte): DynamicWordArray;
var
resultArray: DynamicWordArray;
copyLength: int;
begin
SetLength(resultArray, dataLength);
copyLength := dataLength * SHORT_SIZE;
case dataType of
dtFlag:
CopyMemory(resultArray, @FFlags[offset], copyLength);
dtInput:
CopyMemory(resultArray, @FInputs[offset], copyLength);
dtOutput:
CopyMemory(resultArray, @FOutputs[offset], copyLength);
dtRegister:
CopyMemory(resultArray, @FRegisters[offset], copyLength);
dtTimer:
CopyMemory(resultArray, @FTimers[offset], copyLength);
end;
// FLogger.Log('Read device value: %d', [FFlags[offset]]);
Result := resultArray;
end;
procedure TEasyIpDevice.BlockWrite(const offset: short; const value: DynamicWordArray; const dataType: DataTypeEnum);
var
copyLength: int;
begin
copyLength := Length(value) * 2;
case dataType of
dtFlag:
CopyMemory(@FFlags[offset], value, copyLength);
dtInput:
CopyMemory(@FInputs[offset], value, copyLength);
dtOutput:
CopyMemory(@FOutputs[offset], value, copyLength);
dtRegister:
CopyMemory(@FRegisters[offset], value, copyLength);
dtTimer:
CopyMemory(@FTimers[offset], value, copyLength);
end;
// FLogger.Log('Write device value: %d', [FFlags[offset]]);
end;
function TEasyIpDevice.RangeCheck(const offset: short; const dataType: DataTypeEnum; const dataLength: byte): short;
var
summaryLength: int;
returnFlag: short;
begin
returnFlag := 0;
summaryLength := offset + dataLength;
if dataLength > High(byte) then
returnFlag := returnFlag or EASYIP_ERROR_DATASIZE;
case dataType of
dtFlag:
begin
if Length(FFlags) < summaryLength then
returnFlag := returnFlag or EASYIP_ERROR_OFFSET;
end;
dtInput:
begin
if Length(FInputs) < summaryLength then
returnFlag := returnFlag or EASYIP_ERROR_OFFSET;
end;
dtOutput:
begin
if Length(FOutputs) < summaryLength then
returnFlag := returnFlag or EASYIP_ERROR_OFFSET;
end;
dtRegister:
begin
if Length(FRegisters) < summaryLength then
returnFlag := returnFlag or EASYIP_ERROR_OFFSET;
end;
dtTimer:
begin
if Length(FTimers) < summaryLength then
returnFlag := returnFlag or EASYIP_ERROR_OFFSET;
end;
else
returnFlag := returnFlag or EASYIP_ERROR_NOSUPPORT;
end;
Result := returnFlag;
end;
end.
|
unit TestGnSingleton;
interface
uses
SysUtils, TestFramework, uGnSingleton;
type
Test_GnSingleton = class(TTestCase)
strict private
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure Test_Singlieton;
end;
TMySingleton = class(TGnSingleton)
public
FMyField: string;
end;
implementation
procedure Test_GnSingleton.SetUp;
begin
end;
procedure Test_GnSingleton.TearDown;
begin
end;
procedure Test_GnSingleton.Test_Singlieton;
var
Obj1, Obj2, Obj3: TMySingleton;
begin
Obj1 := TMySingleton.Create;
Obj2 := TMySingleton.Create;
Obj3 := TMySingleton.Create;
CheckSame(Obj1, Obj2);
CheckSame(Obj2, Obj3);
FreeAndNil(Obj3);
Obj1.FMyField := '123';
CheckEquals(Obj2.FMyField, '123');
Obj2.Destroy;
Obj1.FMyField := '666';
FreeAndNil(Obj2);
Obj2 := TMySingleton.Create;
CheckEquals(Obj2.FMyField, '');
FreeAndNil(Obj2);
end;
initialization
RegisterTest(Test_GnSingleton.Suite);
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtDlgs, ExtCtrls;
type
TColorsType = record
R,
G,
B: byte;
end;
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Image1: TImage;
OpenPictureDialog1: TOpenDialog;
SavePictureDialog1: TSaveDialog;
function RGBToColors(RGB: integer): TColorsType;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
sfn,
dfn: string;
implementation
{$R *.DFM}
function TForm1.RGBToColors(RGB: integer): TColorsType;
var temp: integer;
begin
temp := RGB;
Result.B := temp div 65536;
temp := temp - (Result.B*65536);
Result.G := temp div 256;
temp := temp - (Result.G*256);
Result.R := temp;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if not OpenPictureDialog1.Execute then
Abort;
sfn := OpenPictureDialog1.FileName;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
if not SavePictureDialog1.Execute then
Abort;
dfn := SavePictureDialog1.FileName;
end;
procedure TForm1.Button3Click(Sender: TObject);
var i, k: integer;
tmp: TColorsType;
begin
Screen.Cursor := crHourGlass;
Image1.Picture.Bitmap.LoadFromFile(sfn);
// Image1.Picture.Bitmap.LoadFromFile(sfn);
for i := 1 to Image1.Width do
for k := 1 to Image1.Height do
begin
tmp := RGBToColors(Image1.Canvas.Pixels[i,k]);
Image1.Canvas.Pixels[i,k] := RGB(tmp.B,
tmp.G,
tmp.R);
end;
Image1.Picture.Bitmap.SaveToFile(dfn);
Screen.Cursor := crDefault;
Application.MessageBox('Kész','',mb_OK);
end;
end.
|
unit LinkedList;
interface
uses
LinkedListItem, Inf;
type
SortDirection = function (a, b: integer): boolean;
TLinkedList = class
private
_head: TLinkedListItem;
_tail: TLinkedListItem;
public
constructor Create();
destructor Destroy(); override;
public
//методы добавления элементов
procedure AddFirstItem(const _inf: TInf);
procedure AddLastItem(const _inf: TInf);
procedure AddAfterItem(const _inf: TInf; _item: TLinkedListItem);
procedure AddBeforeItem(const _inf: TInf; _item: TLinkedListItem);
//методы удаления элементов
procedure DeleteFirstItem();
procedure DeleteLastItem();
procedure DeleteItem(var _item: TLinkedListItem);
//методы чтения элементов
function ReadFirstItem(): TInf;
function ReadLastItem(): TInf;
function ReadItem(_item: TLinkedListItem): TInf;
//поиск элемента по rowIndex и colIndex
function SearchItem(const _rowIndex, _colIndex: integer): TLinkedListItem;
//сортировка пузырьком
procedure SortBubble(Order: SortDirection);
//распечатать список
function ToString(): string;
public
property Head: TLinkedListItem read _head;
property Tail: TLinkedListItem read _tail;
end;
//сортировка
function SortUp(a, b: integer): boolean;
function SortDown(a, b: integer): boolean;
implementation
function SortUp(a, b: integer): boolean;
begin
Result := (a > b);
end;
function SortDown(a, b: integer): boolean;
begin
Result := (a < b);
end;
constructor TLinkedList.Create();
begin
inherited;
_head := nil;
_tail := nil;
end;
destructor TLinkedList.Destroy();
begin
if (_head <> nil) then
begin
while (_head.Next <> nil) do
begin
_head := _head.Next;
_head.Prev.Free;
end;
_head.Free;
_head := nil;
_tail := nil;
end;
inherited;
end;
procedure TLinkedList.AddFirstItem(const _inf: TInf);
var
item: TLinkedListItem;
begin
if (_head = nil) then
begin
_head := TLinkedListItem.Create(_inf);
_tail := _head;
end
else
begin
item := TLinkedListItem.Create(_inf);
item.Next := _head;
_head.Prev := item;
_head := item;
end;
end;
procedure TLinkedList.AddLastItem(const _inf: TInf);
var
item: TLinkedListItem;
begin
if (_head = nil) then
begin
_head := TLinkedListItem.Create(_inf);
_tail := _head;
end
else
begin
item := TLinkedListItem.Create(_inf);
_tail.Next := item;
_tail := item;
end;
end;
procedure TLinkedList.AddAfterItem(const _inf: TInf; _item: TLinkedListItem);
var
cell: TLinkedListItem;
begin
if (_item <> nil) then
begin
cell := TLinkedListItem.Create(_inf);
cell.Prev := _item;
cell.Next := _item.Next;
_item.Next := cell;
cell.Next.Prev := cell;
end;
end;
procedure TLinkedList.AddBeforeItem(const _inf: TInf; _item: TLinkedListItem);
var
cell: TLinkedListItem;
begin
if (_item <> nil) then
begin
cell := TLinkedListItem.Create(_inf);
cell.Prev := _item.Prev;
cell.Prev.Next := cell;
cell.Next := _item;
_item.Prev := cell;
end;
end;
procedure TLinkedList.DeleteFirstItem();
begin
if (_head <> nil) then
begin
if (_head <> _tail) then
begin
_head := _head.Next;
_head.Prev.Next := nil;
_head.Prev.Free;
_head.Prev := nil;
end
else begin
_head.Free;
_head := nil;
_tail := nil;
end;
end;
end;
procedure TLinkedList.DeleteLastItem();
begin
if (_tail <> nil) then
begin
if (_head <> _tail) then
begin
_tail := _tail.Prev;
_tail.Next.Prev := nil;
_tail.Next.Free;
_tail.Next := nil;
end
else begin
_head.Free;
_head := nil;
_tail := nil;
end;
end;
end;
procedure TLinkedList.DeleteItem(var _item: TLinkedListItem);
begin
if (_item <> nil) then
begin
if (_item <> _head) then
begin
if (_item <> _tail) then
begin
_item.Prev.Next := _item.Next;
_item.Next.Prev := _item.Prev;
_item.Free;
_item := nil;
end
else
DeleteLastItem();
end
else
DeleteFirstItem();
end;
end;
function TLinkedList.ReadFirstItem: TInf;
begin
if (_head <> nil) then
Result := _head.Inf
else
Result := nil;
end;
function TlinkedList.ReadLastItem: TInf;
begin
if (_tail <> nil) then
Result := _tail.Inf
else
Result := nil;
end;
function TLinkedList.ReadItem(_item: TLinkedListItem): TInf;
begin
if (_item <> nil) then
Result := _item.Inf
else
Result := nil;
end;
function TLinkedList.SearchItem(const _rowIndex, _colIndex: integer): TLinkedListItem;
var
item: TLinkedListItem;
begin
item := _head;
while ((item <> nil) and ((_rowIndex <> item.Inf.Row) or (_colIndex <> item.Inf.Col))) do
item := item.Next;
Result := item;
end;
procedure TLinkedList.SortBubble(Order: SortDirection);
var
rab, item: TLinkedListItem;
inf: TInf;
begin
rab := _head;
while (rab <> nil) do
begin
item := rab.Next;
while (item <> nil) do
begin
if Order(item.Inf.Col, rab.Inf.Col) then
begin
inf := item.Inf;
item.Inf := rab.Inf;
rab.Inf := inf;
end;
item := item.Next;
end;
rab := rab.Next;
end;
end;
function TLinkedList.ToString(): string;
var
item: TLinkedListItem;
begin
Result := '';
item := _head;
while (item <> nil) do
begin
Result := Result + item.Inf.ToString();
if (item.Next <> nil) then
begin
Result := Result + ' ';
end;
item := item.Next;
end;
end;
end.
|
unit RegFilesCollection;
interface
uses Windows, SysUtils, Classes, Registry, Dialogs, Psapi, tlhelp32, IniFiles,
Settings;
const
SysHiveList = 'System\CurrentControlSet\Control\hivelist';
function GetFileSize(FileName: string): int64; //64 bit files
function GetHiveList: boolean;
function GetKeyName(KeyHandler: HKEY): string;
procedure CreateWinNTProcessList(List: TstringList);
var
RegKeysNames: TStringList;
RegKeysList: TStringList;
HivePath: TStringList;
AllSize: int64;
NewAllFilesSize: int64;
implementation
var
DiskList: TStringList;
BeehiveCount: integer;
errorBuf: array[0..80] of WideChar;
lastError: DWORD;
function GetFileSize(FileName: string): int64; //64 bit files
var
SearchRec: TSearchRec;
begin
Result := 0;
if FindFirst(ExpandFileName(FileName), faAnyFile, SearchRec) = 0 then
Result := (SearchRec.FindData.nFileSizeHigh shl 32) + SearchRec.FindData.nFileSizeLow;
FindClose(SearchRec);
end;
//http://expert.delphi.int.ru/question/1713/
procedure GetDosDevices;
var
Device: char;
Volume: string;
lpQuery: array[0..MAXCHAR - 1] of char;
FInfo: string;
begin
for Device := 'A' to 'Z' do
if GetDriveType(PAnsiChar(string(Device + ':\'))) = DRIVE_FIXED then
begin
Volume := Device + ':' + #0;
QueryDosDevice(PChar(Volume), @lpQuery[0], MAXCHAR);
Volume[3] := '\';
FInfo := string(lpQuery);
DiskList.Values[FInfo] := Volume;
end;
end;
function GetHiveList: boolean;
var
Registry: TRegistry;
KeyNum: integer;
KeyNameSub, KeyName, KeyValue: string;
FilePath: string;
FileSize: longint;
SaveKey: HKEY;
begin
Result := false;
Registry := TRegistry.Create;
try
GetDosDevices;
Registry.RootKey := HKEY_LOCAL_MACHINE;
Registry.Access := KEY_WOW64_64KEY or KEY_ALL_ACCESS;
if not Registry.OpenKeyReadOnly(SysHiveList) then AddToLog('Can''t access to system registy files list.')
else
begin
Registry.GetValueNames(RegKeysNames);
AllSize := 0;
BeehiveCount := 0;
for KeyNum := 0 to RegKeysNames.Count - 1 do
begin
KeyName := GetWordString(2, RegKeysNames.Strings[KeyNum], ['\']);
KeyNameSub := GetWordString(3, RegKeysNames.Strings[KeyNum], ['\']);
KeyValue := Registry.ReadString(RegKeysNames.Strings[KeyNum]);
if KeyValue <> '' then
begin
FilePath := TrimRight(DiskList.Values[Copy(KeyValue, 0, GetWordStringPos(3, KeyValue, ['\']) - 2)])
+ Copy(KeyValue, GetWordStringPos(3, KeyValue, ['\']), Length(KeyValue));
FileSize := GetFileSize(FilePath);
AllSize := AllSize + FileSize;
Inc(BeehiveCount);
HivePath.AddObject(FilePath, TObject(FileSize));
SaveKey := 0;
if AnsiUpperCase(KeyName) = 'USER' then SaveKey := HKEY_USERS;
if AnsiUpperCase(KeyName) = 'MACHINE' then SaveKey := HKEY_LOCAL_MACHINE;
if SaveKey <> 0 then RegKeysList.AddObject(KeyNameSub, TObject(SaveKey));
end;
end;
result := true;
end;
finally
Registry.Destroy;
end;
end;
function GetKeyName(KeyHandler: HKEY): string;
begin
Result := '';
if KeyHandler = HKEY_CLASSES_ROOT then Result := 'HKEY_CLASSES_ROOT'
else
if KeyHandler = HKEY_CURRENT_USER then Result := 'HKEY_CURRENT_USER'
else
if KeyHandler = HKEY_LOCAL_MACHINE then Result := 'HKEY_LOCAL_MACHINE'
else
if KeyHandler = HKEY_LOCAL_MACHINE then Result := 'HKEY_LOCAL_MACHINE'
else
if KeyHandler = HKEY_USERS then Result := 'HKEY_USERS';
end;
procedure CreateWinNTProcessList(List: TstringList);
var
PIDArray: array[0..1023] of DWORD;
cb: DWORD;
I: Integer;
ProcCount: Integer;
hMod: HMODULE;
hProcess: THandle;
ModuleName: array[0..300] of Char;
begin
if List = nil then Exit;
EnumProcesses(@PIDArray, SizeOf(PIDArray), cb);
ProcCount := cb div SizeOf(DWORD);
for I := 0 to ProcCount - 1 do
begin
hProcess := OpenProcess(PROCESS_QUERY_INFORMATION or
PROCESS_VM_READ,
False,
PIDArray[I]);
if (hProcess <> 0) then
begin
EnumProcessModules(hProcess, @hMod, SizeOf(hMod), cb);
GetModuleFilenameEx(hProcess, hMod, ModuleName, SizeOf(ModuleName));
List.Add(ModuleName);
CloseHandle(hProcess);
end;
end;
end;
initialization
HivePath := TStringList.Create;
DiskList := TStringList.Create;
RegKeysNames := TStringList.Create;
RegKeysList := TStringList.Create;
finalization
HivePath.Destroy;
DiskList.Destroy;
RegKeysNames.Destroy;
RegKeysList.Destroy;
end.
|
unit CreatePlaylistUnit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, System.Generics.Defaults, System.Generics.Collections,
Vcl.Imaging.jpeg, Vcl.ExtCtrls, Vcl.ExtDlgs, Vcl.Menus;
type
TCreatePlaylistForm = class(TForm)
NameLabel: TLabel;
NameEdit: TEdit;
CreateButton: TBitBtn;
CancelButton: TBitBtn;
MusicListBox: TListBox;
TracksLabel: TLabel;
AddMusicButton: TBitBtn;
DeleteButton: TBitBtn;
AddMusicDialog: TOpenDialog;
CoverLabel: TLabel;
PreviewImage: TImage;
LoadButton: TBitBtn;
OpenPictureDialog: TOpenPictureDialog;
PopupMenu1: TPopupMenu;
procedure AddMusicButtonClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure CancelButtonClick(Sender: TObject);
procedure DeleteButtonClick(Sender: TObject);
procedure CreateButtonClick(Sender: TObject);
procedure LoadButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure CreatePlaylist();
private
{ Private declarations }
public
{ Public declarations }
end;
var
CreatePlaylistForm: TCreatePlaylistForm;
implementation
{$R *.dfm}
uses
MainUnit, ToolsUnit, LocalizationUnit;
var
MusicArr: array of string;
Size: Integer;
ImagePath: string;
const
PLAYLISTS_NAME = 'Playlists';
COVER_NAME = '\cover.jpg';
FILTER = 'Музыка| *.mp3;';
procedure TCreatePlaylistForm.AddMusicButtonClick(Sender: TObject);
var
Name: string;
begin
if AddMusicDialog.Execute then
begin
Inc(Size);
SetLength(MusicArr, Size);
MusicArr[High(MusicArr)] := AddMusicDialog.FileName;
Name := Tools.CuteName(AddMusicDialog.FileName);
Delete(Name, Length(Name) - 3, 4);
MusicListBox.Items.Add(Name);
end;
end;
procedure TCreatePlaylistForm.CancelButtonClick(Sender: TObject);
begin
CreatePlaylistForm.Close;
end;
procedure TCreatePlaylistForm.CreateButtonClick(Sender: TObject);
begin
CreatePlaylist;
end;
procedure TCreatePlaylistForm.CreatePlaylist();
var
I: Integer;
NewPlaylistPath, ErrorCap, ErrorMsg: string;
begin
if Length(NameEdit.Text) <> 0 then
begin
if not FileExists(ExeDirectory + PLAYLISTS_NAME) then
CreateDir(ExeDirectory + PLAYLISTS_NAME);
NewPlaylistPath := ExeDirectory + PLAYLISTS_NAME + '\' + NameEdit.Text;
CreateDir(NewPlaylistPath);
if Length(ImagePath) <> 0 then
begin
CopyFile(PChar(ImagePath), PChar(NewPlaylistPath + COVER_NAME), True);
end;
for I := 0 to High(MusicArr) do
CopyFile(PChar(MusicArr[I]), PChar(NewPlaylistPath + '\' + Tools.CuteName(MusicArr[I])), True);
MainForm.UpdatePlaylists;
CreatePlaylistForm.Close;
end
else
begin
Localization.SelectLanguageForMessage
(ErrorCap, ErrorMsg,
ERROR_CAP_RUS, ENT_PLST_NAME_RUS,
ERROR_CAP_ENG, ENT_PLST_NAME_ENG);
MessageBox(Handle, PChar(ErrorMsg), PChar(ErrorCap), MB_OK + MB_ICONERROR);
end;
end;
procedure TCreatePlaylistForm.DeleteButtonClick(Sender: TObject);
var
I: Integer;
ErrorCap, ErrorMsg: string;
begin
if MusicListBox.ItemIndex <> -1 then
begin
for I := MusicListBox.ItemIndex to High(MusicArr) - 1 do
begin
MusicArr[I] := MusicArr[I + 1];
end;
Dec(Size);
SetLength(MusicArr, Size);
MusicListBox.DeleteSelected;
end
else
begin
Localization.SelectLanguageForMessage(
ErrorCap, ErrorMsg,
ERROR_CAP_RUS, SELECT_TRACK_RUS,
ERROR_CAP_ENG, SELECT_TRACK_ENG);
MessageBox(Handle, PChar(ErrorMsg), PChar(ErrorCap), MB_OK + MB_ICONERROR);
end;
end;
procedure TCreatePlaylistForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Size := 0;
SetLength(MusicArr, Size);
NameEdit.Clear;
MusicListBox.Clear;
ImagePath := '';
PreviewImage.Picture := MainForm.DefaultImage.Picture;
end;
procedure TCreatePlaylistForm.FormCreate(Sender: TObject);
begin
AddMusicDialog.Filter := FILTER;
end;
procedure TCreatePlaylistForm.LoadButtonClick(Sender: TObject);
begin
if OpenPictureDialog.Execute then
begin
ImagePath := OpenPictureDialog.FileName;
PreviewImage.Picture.LoadFromFile(OpenPictureDialog.FileName);
end;
end;
end.
|
Unit GUID;
interface
Uses Error;
Type
TCLSID = TGUID;
POleStr = PWideChar;
function CoCreateGuid(out guid: TGUID): HResult; stdcall;
function StringFromCLSID(const clsid: TCLSID; out psz: POleStr): HResult; stdcall;
procedure CoTaskMemFree(pv: Pointer); stdcall;
function CreateGuid: string;
implementation
function CoCreateGuid; external 'ole32.dll' name 'CoCreateGuid';
function StringFromCLSID; external 'ole32.dll' name 'StringFromCLSID';
procedure CoTaskMemFree; external 'ole32.dll' name 'CoTaskMemFree';
{
function Succeeded(Res: HResult): Boolean;
begin
Result := Res and $80000000 = 0;
end;
procedure OleCheck(Result: HResult);
begin
if not Succeeded(Result) then Exit;//OleError(Result);
end;
}
function GUIDToString(const ClassID: TGUID): string;
var
P: PWideChar;
begin
//OleCheck(StringFromCLSID(ClassID, P));
if Not (StringFromCLSID(ClassID, P) and $80000000 = 0) then
begin
SaveErrorMessage('Uses GUID, function CoCreateGuid');
Exit; //OleError(Result);
end;
Result := P;
CoTaskMemFree(P);
end;
function CreateGuid: string;
var
ID: TGUID;
begin
Result := '';
if CoCreateGuid(ID) = S_OK then
Result := GUIDToString(ID);
end;
end. |
// Copyright 2018 by John Kouraklis and Contributors. All Rights Reserved.
//
// 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 Casbin.Core.Logger.Types;
interface
uses
System.Generics.Collections;
type
ILogger = interface
['{A2FB7DFB-BB81-421C-B2DF-5E76AB6FCB4D}']
{$REGION 'Getters/Setters'}
function getEnableConsole: boolean;
function getEnabled: Boolean;
function getLastLoggedMessage: String;
procedure setEnableConsole(const Value: boolean);
procedure setEnabled(const aValue: Boolean);
{$ENDREGION}
{$REGION 'Logs a message'}
/// <summary>
/// Logs a message
/// </summary>
{$ENDREGION}
procedure log(const aMessage: string);
{$REGION 'Enables and Disables the logger'}
/// <summary>
/// Enables and Disables the logger
/// </summary>
{$ENDREGION}
property Enabled: Boolean read getEnabled write setEnabled;
{$REGION 'If enabled it shows the log message in the console'}
/// <summary>
/// If enabled it shows the log message in the console
/// </summary>
{$ENDREGION}
property EnableConsole: boolean read getEnableConsole write setEnableConsole;
{$REGION 'Retrieves the logged message. Used for debugging purposes'}
/// <summary>
/// <para>
/// Retrieves the logged message.
/// </para>
/// <para>
/// Used for debugging purposes
/// </para>
/// </summary>
{$ENDREGION}
property LastLoggedMessage: String read getLastLoggedMessage;
end;
ILoggerPool = interface
['{BBA7D2FA-DA89-4118-923E-2B8BE3E70AF5}']
function GetLoggers: TList<ILogger>;
procedure SetLoggers(const Value: TList<ILogger>);
procedure log(const aMessage: string);
property Loggers: TList<ILogger> read GetLoggers write SetLoggers;
end;
implementation
end.
|
{ Invokable implementation File for TOperacoes which implements IOperacoes }
unit OperacoesImpl;
interface
uses InvokeRegistry, Types, XSBuiltIns, OperacoesIntf;
type
{ TOperacoes }
TOperacoes = class(TInvokableClass, IOperacoes)
public
function echoEnum(const Value: TEnumTest): TEnumTest; stdcall;
function echoDoubleArray(const Value: TDoubleArray): TDoubleArray; stdcall;
function echoMyEmployee(const Value: TMyEmployee): TMyEmployee; stdcall;
function echoDouble(const Value: Double): Double; stdcall;
end;
implementation
function TOperacoes.echoEnum(const Value: TEnumTest): TEnumTest; stdcall;
begin
{ TODO : Implement method echoEnum }
Result := Value;
end;
function TOperacoes.echoDoubleArray(const Value: TDoubleArray): TDoubleArray; stdcall;
begin
{ TODO : Implement method echoDoubleArray }
Result := Value;
end;
function TOperacoes.echoMyEmployee(const Value: TMyEmployee): TMyEmployee; stdcall;
begin
{ TODO : Implement method echoMyEmployee }
Result := TMyEmployee.Create;
end;
function TOperacoes.echoDouble(const Value: Double): Double; stdcall;
begin
{ TODO : Implement method echoDouble }
Result := Value;
end;
initialization
{ Invokable classes must be registered }
InvRegistry.RegisterInvokableClass(TOperacoes);
end.
|
unit VisibleDSA.AlgoVisualizer;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
Graphics,
Forms,
BGRACanvas2D,
VisibleDSA.AlgoVisHelper,
VisibleDSA.HeapSortData;
type
TAlgoVisualizer = class(TObject)
private
_width: integer;
_height: integer;
_data: THeapSortData;
_form: TForm;
procedure __setData(heapIndex: integer);
public
constructor Create(form: TForm; sceneWidth, sceneHeight, n: integer);
destructor Destroy; override;
procedure Paint(canvas: TBGRACanvas2D);
procedure Run;
end;
implementation
uses
VisibleDSA.AlgoForm;
{ TAlgoVisualizer }
constructor TAlgoVisualizer.Create(form: TForm; sceneWidth, sceneHeight, n: integer);
begin
_form := form;
_width := form.ClientWidth;
_height := form.ClientHeight;
_data := THeapSortData.Create(n, _height, ArrType.Default);
_form.Caption := 'Heap Sort Visualization';
end;
destructor TAlgoVisualizer.Destroy;
begin
FreeAndNil(_data);
inherited Destroy;
end;
procedure TAlgoVisualizer.Paint(canvas: TBGRACanvas2D);
var
w: integer;
i: integer;
begin
w := _width div _data.Length;
for i := 0 to _data.Length - 1 do
begin
if i >= _data.HeapIndex then
TAlgoVisHelper.SetFill(CL_RED)
else
TAlgoVisHelper.SetFill(CL_GREY);
TAlgoVisHelper.FillRectangle(canvas, i * w, _height - _data.GetValue(i), w - 1, _data.GetValue(i));
end;
end;
procedure TAlgoVisualizer.Run;
procedure __shiftDown__(n, k: integer);
var
j: integer;
begin
while 2 * k + 1 < n do
begin
j := 2 * k + 1;
if (j + 1 < n) and (_data.GetValue(j + 1) > _data.GetValue(j)) then
j += 1;
if _data.GetValue(k) >= _data.GetValue(j) then
Break;
_data.Swap(k, j);
__setData(_data.HeapIndex);
k := j;
end;
end;
var
i: integer;
begin
__setData(_data.Length);
// 建堆
for i := (_data.Length() - 1 - 1) div 2 downto 0 do
begin
__shiftDown__(_data.Length(), i);
end;
// 堆排序
for i := _data.Length() - 1 downto 1 do
begin
_data.Swap(0, i);
__shiftDown__(i, 0);
__setData(i);
end;
__setData(0);
end;
procedure TAlgoVisualizer.__setData(heapIndex: integer);
begin
_data.HeapIndex := heapIndex;
TAlgoVisHelper.Pause(1);
AlgoForm.BGRAVirtualScreen.DiscardBitmap;
end;
end.
|
{$include kode.inc}
unit syn_thetic_phase;
{
todo:
check wraparound..
}
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
type
Synthetic_Phase = class
private
FPhase : Single;
FPhaseAdd : Single;
FSampleRate : Single;
FInvRate : Single;
FWrapped : Boolean;
public
constructor create;
destructor destroy; override;
procedure setPhase(APhase:Single);
procedure addPhase(AValue:Single);
procedure setPhaseAdd(APhaseAdd:Single);
procedure setHz(AHz:Single);
procedure setSampleRate(ASampleRate:Single);
function getPhase : Single;
function getPhaseAdd : Single;
function getWrapped : Boolean;
function process : Single;
//function processAddMul(AMod:Single=0) : Single;
end;
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
uses
kode_const;
//----------
constructor Synthetic_Phase.create;
begin
inherited;
FPhase := 0;
FPhaseAdd := 0;
FSampleRate := 0;
FInvRate := 0;
FWrapped := False;
end;
//----------
destructor Synthetic_Phase.destroy;
begin
inherited;
end;
//----------------------------------------
procedure Synthetic_Phase.setPhase(APhase:Single);
begin
FPhase := APhase;
end;
//----------
procedure Synthetic_Phase.addPhase(AValue:Single);
begin
FPhase += AValue;
end;
//----------
procedure Synthetic_Phase.setPhaseAdd(APhaseAdd:Single);
begin
FPhaseAdd := APhaseAdd;
end;
//----------
procedure Synthetic_Phase.setHz(AHz:Single);
begin
FPhaseAdd := AHz * FInvRate;
end;
//----------
procedure Synthetic_Phase.setSampleRate(ASampleRate:Single);
begin
FSampleRate := ASampleRate;
if FSampleRate > KODE_TINY then
FInvRate := 1 / FSampleRate
else
FInvRate := 0;
end;
//----------
function Synthetic_Phase.getPhase : Single;
begin
result := FPhase;
end;
//----------
function Synthetic_Phase.getPhaseAdd : Single;
begin
result := FPhaseAdd;
end;
//----------
function Synthetic_Phase.getWrapped : Boolean;
begin
result := FWrapped;
end;
//----------------------------------------
function Synthetic_Phase.process : Single;
begin
result := FPhase;
FPhase += FPhaseAdd;
if (FPhase < 0) or (FPhase >= 1) then FWrapped := True else FWrapped := False;
FPhase -= trunc(FPhase);
//FPhase := frac(FPhase);
end;
//----------
//function Synthetic_Phase.processAddMul(AMod:Single=0) : Single;
//begin
// result := FPhase;// + AMod;
// FPhase += FPhaseAdd;
// FPhase += (FPhaseAdd * AMod);
// if {(FPhase < 0) or} (FPhase >= 1) then FWrapped := True else FWrapped := False;
// FPhase -= trunc(FPhase);
// //FPhase := frac(FPhase);
//end;
//----------------------------------------------------------------------
end.
|
unit GridControl;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Wwdbigrd, Wwdbgrid, DB, Wwdatsrc, Grids, ControlGridDisp;
type
TGridControl = class(TComponent)
private
{ Private declarations }
FColorRow,
FColorGrid,
FColorTitle : TColor;
FLines,
FColums : Boolean;
FCalcCellColors : TCalcCellColorsEvent;
FGrids : TStrings;
FFontGrid : TFont;
FFontTitle : TFont;
FGrid : TwwDBGrid;
FShowRows,
FShowColumns : Boolean;
FHeight, FWidth : Integer;
FControlGridDisp : TControlGridDisp;
FForm : TCustomForm;
procedure ExtractValue;
protected
{ Protected declarations }
procedure SetGrids ( Value : TStrings );
procedure SetForm ( Value : TCustomForm );
procedure CalcCellColors( Sender: TObject; Field: TField;
State: TGridDrawState; Highlight: Boolean;
AFont: TFont; ABrush: TBrush); virtual;
procedure FindGrids;
procedure ClearGrids;
procedure SetColorRow (Value : TColor);
procedure SetColorGrid (Value : TColor);
procedure SetColorTitle (Value : TColor);
procedure SetFontGrid (Value : TFont);
procedure SetFontTitle (Value : TFont);
function GetFontGrid : TFont;
function GetFontTitle : TFont;
procedure SetControlGridDisp(Value :TControlGridDisp);
procedure SetGrid(Value :TwwDBGrid);
procedure SetShowRows( Value: Boolean );
procedure SetShowColumns( Value: Boolean );
procedure SetHeight(Value : Integer);
procedure SetWidth(Value : Integer);
procedure Notification(AComponent : TComponent; Operation : Toperation); override;
procedure Loaded; override;
public
{ Public declarations }
property Form : TCustomForm read FForm ;
constructor Create(AOwner: TComponent); Override;
destructor Destroy; Override;
published
{ Published declarations }
property Grid : TwwDBGrid read FGrid write SetGrid;
property Grids : TStrings read FGrids write SetGrids;
property ShowRows : Boolean read FShowRows write SetShowRows default True;
property ShowColumns: Boolean read FShowColumns write SetShowColumns default True;
property ColorRow : TColor read FColorRow write SetColorRow default clSilver;
property ColorGrid : TColor read FColorGrid write SetColorGrid default clWindow;
property ColorTitle : TColor read FColorTitle write SetColorTitle default clBtnFace;
property FontGrid : TFont read GetFontGrid write SetFontGrid;
property FontTitle : TFont read GetFontTitle write SetFontTitle;
property Height : Integer read FHeight write SetHeight;
property Width : Integer read FWidth write SetWidth;
property ControlGridDisp : TControlGridDisp read FControlGridDisp write SetControlGridDisp;
property OnCalcCellColorsEvent : TCalcCellColorsEvent read FCalcCellColors write FCalcCellColors;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('oaPck', [TGridControl]);
end;
{ TGridControl }
constructor TGridControl.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FFontGrid := TFont.Create;
FFontTitle := TFont.Create;
FFontGrid.Color := clWindowText;
FFontTitle.Color := clWindowText;
FShowRows := True;
ShowColumns := True;
FColorRow := clSilver;
FColorTitle := clBtnFace;
FColorGrid := clWindow;
FGrids := TStringList.Create;
FGrid := nil;
FControlGridDisp := nil;
FCalcCellColors := nil;
FForm := TForm(Owner);
end;
destructor TGridControl.Destroy;
begin
FFontGrid.Free;
FFontTitle.Free;
ClearGrids;
FGrids.Free;
inherited Destroy;
end;
procedure TGridControl.SetGrids(Value: TStrings);
begin
if Value <> Grids then
begin
FGrids.Assign(Value);
FGrid := nil;
FindGrids;
end;
end;
procedure TGridControl.CalcCellColors(Sender: TObject; Field: TField;
State: TGridDrawState; Highlight: Boolean; AFont: TFont;
ABrush: TBrush);
begin
if not(csDesigning in ComponentState) then
begin
if not(gdSelected in State) then
begin
AFont.Color := clWindowText;
if TwwDBGrid(Sender).CalcCellRow mod 2=0 then
ABrush.Color := FColorRow
else
ABrush.Color := FColorGrid;
end else
begin
AFont.Color := clHighlightText;
ABrush.Color := clHighlight;
end;
if (Highlight) then //(gdSelected in State) and
begin
AFont.Color := clHighlightText;
ABrush.Color := clHighlight;
end;
if Assigned(FCalcCellColors) then
FCalcCellColors(Sender, Field, State, Highlight, AFont, ABrush );
end;
end;
procedure TGridControl.FindGrids;
var
mGrid : TComponent;
i : Integer;
begin
if FGrids=nil then Exit;
if FForm=nil then Exit;
for i:=0 to FGrids.Count-1 do
begin
mGrid := TForm(FForm).FindComponent(Grids.Strings[i]);
if mGrid <> nil then
if mGrid is TwwDBGrid then
begin
with TwwDBGrid(mGrid) do
begin
OnCalcCellColors := CalcCellColors;
Color := FColorGrid;
TitleColor := FColorTitle;
Color := FColorGrid;
Font := FFontGrid;
TitleFont := FFontTitle;
if FShowColumns then
Options := Options + [dgColLines]
else
Options := Options - [dgColLines];
if FShowRows then
Options := Options + [dgRowLines]
else
Options := Options - [dgRowLines];
end;
end;
end;
end;
procedure TGridControl.SetColorGrid(Value: TColor);
begin
if Value <> FColorGrid then
begin
if FGrid = nil then exit;
FColorGrid := Value;
FGrid.Color := FColorGrid;
end;
end;
procedure TGridControl.SetColorRow(Value: TColor);
begin
if Value <> FColorRow then
begin
FColorRow := Value;
end;
end;
procedure TGridControl.SetColorTitle(Value: TColor);
begin
if Value <> FColorTitle then
begin
FColorTitle := Value;
if FGrid = nil then exit;
FGrid.TitleColor := FColorTitle;
end;
end;
procedure TGridControl.SetFontGrid(Value: TFont);
begin
if Value <> FFontGrid then
begin
FFontGrid.Assign(Value);
if Assigned(FGrid) then
begin
FGrid.Font.Assign(FFontGrid);
end;
end;
end;
procedure TGridControl.SetFontTitle(Value: TFont);
begin
if Value <> FFontTitle then
begin
FFontTitle.Assign(Value);
if FGrid <> nil then
begin
FGrid.TitleFont.Assign(FFontTitle);
end;
end;
end;
procedure TGridControl.SetGrid(Value: TwwDBGrid);
begin
FGrid := Value;
if FGrid <> nil then
begin
FGrid.FreeNotification(Self);
FGrid.OnCalcCellColors := CalcCellColors;
FFontGrid.Assign(FGrid.Font);
FFontTitle.Assign(FGrid.TitleFont);
FGrid.Font := FFontGrid;
FGrid.TitleFont := FFontTitle;
FGrid.Color := FColorGrid;
FGrid.TitleColor := FColorTitle;
FWidth := FGrid.Width;
FHeight := FGrid.Height;
if FShowColumns then
FGrid.Options := FGrid.Options + [dgColLines]
else FGrid.Options := FGrid.Options - [dgColLines];
if FShowRows then
FGrid.Options := FGrid.Options + [dgRowLines]
else FGrid.Options := FGrid.Options - [dgRowLines];
FGrids.Clear;
end;
end;
procedure TGridControl.Notification(AComponent : TComponent; Operation : Toperation);
begin
inherited Notification(AComponent,Operation);
if (Operation=opRemove) AND (AComponent=FGrid) then
FGrid:=nil;
if (Operation=opRemove) AND (AComponent=FControlGridDisp) then
FControlGridDisp:=nil;
end;
procedure TGridControl.SetShowColumns(Value: Boolean);
begin
if FShowColumns <> Value then
begin
FShowColumns := Value;
if FGrid = nil then exit;
if FShowColumns then
FGrid.Options := FGrid.Options + [dgColLines]
else
FGrid.Options := FGrid.Options - [dgColLines];
end;
end;
procedure TGridControl.SetShowRows(Value: Boolean);
begin
if FShowRows <> Value then
begin
FShowRows := Value;
if FGrid = nil then exit;
if FShowRows then
FGrid.Options := FGrid.Options + [dgRowLines]
else
FGrid.Options := FGrid.Options - [dgRowLines];
end;
end;
procedure TGridControl.SetHeight(Value: Integer);
begin
if FHeight <> Value then
begin
FHeight := Value;
if FGrid = nil then exit;
if FHeight>0 then FGrid.Height := FHeight;
end;
end;
procedure TGridControl.SetWidth(Value: Integer);
begin
if FWidth <> Value then
begin
FWidth := Value;
if FGrid = nil then exit;
if FWidth>0 then FGrid.Width := FWidth;
end;
end;
function TGridControl.GetFontGrid: TFont;
begin
result := FFontGrid;
end;
function TGridControl.GetFontTitle: TFont;
begin
result := FFontTitle;
end;
procedure TGridControl.SetControlGridDisp(Value: TControlGridDisp);
begin
FControlGridDisp := Value;
if FControlGridDisp <> nil then
begin
FControlGridDisp.FreeNotification(Self);
ExtractValue;
if FGrid = nil then exit;
FGrid.Font := FFontGrid;
FGrid.TitleFont := FFontTitle;
FGrid.Color := FColorGrid;
FGrid.TitleColor := FColorTitle;
if FWidth>0 then
FGrid.Width := FWidth
else
FWidth := FGrid.Width;
if FHeight>0 then
FGrid.Height := FHeight
else
FHeight := FGrid.Height;
if FShowRows then
FGrid.Options := FGrid.Options + [dgRowLines]
else
FGrid.Options := FGrid.Options - [dgRowLines];
if FShowColumns then
FGrid.Options := FGrid.Options + [dgColLines]
else
FGrid.Options := FGrid.Options - [dgColLines];
end;
end;
procedure TGridControl.ExtractValue;
begin
if FControlGridDisp = nil then exit;
FFontGrid.Assign(FControlGridDisp.FontGrid);
FFontTitle.Assign(FControlGridDisp.FontTitle);
FColorGrid := FControlGridDisp.ColorGrid;
FColorTitle := FControlGridDisp.ColorTitle;
FColorRow := FControlGridDisp.ColorRow;
FWidth := FControlGridDisp.Width;
FHeight := FControlGridDisp.Height;
FShowRows := FControlGridDisp.ShowRows;
FShowColumns := FControlGridDisp.ShowColumns;
end;
procedure TGridControl.Loaded;
begin
inherited Loaded;
if not(csDesigning in ComponentState) then
begin
ExtractValue;
FindGrids;
end;
end;
procedure TGridControl.ClearGrids;
var
mGrid : TComponent;
i : Integer;
begin
if FGrids = nil then Exit;
if FForm = nil then Exit;
for i:=0 to FGrids.Count-1 do
begin
mGrid := TForm(FForm).FindComponent(Grids.Strings[i]);
if mGrid <> nil then
if mGrid is TwwDBGrid then
begin
TwwDBGrid(mGrid).OnCalcCellColors := nil;
end;
end;
end;
procedure TGridControl.SetForm(Value: TCustomForm);
begin
FForm.Assign(Value);
if Assigned(FForm) then
begin
FForm.FreeNotification(Self);
end;
end;
end.
|
(******************************************************************************
* PasVulkan *
******************************************************************************
* Version see PasVulkan.Framework.pas *
******************************************************************************
* zlib license *
*============================================================================*
* *
* Copyright (C) 2016-2023, Benjamin Rosseaux (benjamin@rosseaux.de) *
* *
* This software is provided 'as-is', without any express or implied *
* warranty. In no event will the authors be held liable for any damages *
* arising from the use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not *
* claim that you wrote the original software. If you use this software *
* in a product, an acknowledgement in the product documentation would be *
* appreciated but is not required. *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* 3. This notice may not be removed or altered from any source distribution. *
* *
******************************************************************************
* General guidelines for code contributors *
*============================================================================*
* *
* 1. Make sure you are legally allowed to make a contribution under the zlib *
* license. *
* 2. The zlib license header goes at the top of each source file, with *
* appropriate copyright notice. *
* 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan *
* Pascal header. *
* 4. After a pull request, check the status of your pull request on *
http://github.com/BeRo1985/pasvulkan *
* 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= *
* 3.1.1 *
* 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, *
* but if needed, make it out-ifdef-able. *
* 7. No use of third-party libraries/units as possible, but if needed, make *
* it out-ifdef-able. *
* 8. Try to use const when possible. *
* 9. Make sure to comment out writeln, used while debugging. *
* 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, *
* x86-64, ARM, ARM64, etc.). *
* 11. Make sure the code runs on all platforms with Vulkan support *
* *
******************************************************************************)
unit PasVulkan.Scene;
{$i PasVulkan.inc}
{$ifndef fpc}
{$ifdef conditionalexpressions}
{$if CompilerVersion>=24.0}
{$legacyifend on}
{$ifend}
{$endif}
{$endif}
interface
uses Classes,
SysUtils,
PasMP,
PasVulkan.Types,
PasVulkan.Math,
PasVulkan.Collections,
PasVulkan.Scene3D;
{
A scene node can be an entity or even a component for an entity node as well, here is no distinction for simplicity, for the contrast to
the entity-component-system pattern, which is also implemented in the PasVulkan framework, see the PasVulkan.EntityComponentSystem.pas unit.
So it's your choice, if you want to use the entity-component-system pattern or the scene graph pattern or both.
The scene graph pattern is a tree structure, where each node can have zero or more child nodes, but only one parent node. The root node
has no parent node. Each node can have zero or more data objects, which can be used for any purpose, even as components for an entity
node. The scene graph pattern is very useful for rendering, physics, audio, AI, etc. and is very flexible and easy to use.
GetNodeListOf returns a list of all child nodes of the specified node class.
GetNodeOf returns the child node of the specified node class at the specified index, which is zero by default, and nil if there is out of bounds.
GetNodeCountOf returns the count of child nodes of the specified node class.
StartLoad, BackgroundLoad and FinishLoad are used for loading of data, which can be done in parallel, like loading of textures, meshes, etc.
Or to be more precise, StartLoad is called before the background loading of the scene graph, BackgroundLoad is called in a background thread
and should be used for loading of data, which can be done in parallel and FinishLoad is called after the background loading of the scene graph.
StartLoad is called before the background loading of the scene graph. It's called in the main thread.
BackgroundLoad is called in a background thread and should be used for loading of data, which can be done in parallel.
FinishLoad is called after the background loading of the scene graph. It's called in the main thread.
WaitForLoaded waits until the scene graph or node is loaded.
IsLoaded returns true, if the scene graph or node is loaded.
These loading functions should be called just once before the beginning of a level or game together with a loading screen, etc. For other
resources, which are loaded during the game, like textures, meshes, etc. should be loaded in an other way, for example, with the
resource manager of the PasVulkan framework, see the PasVulkan.Resources.pas unit. These loading functions here are just for to simplify
the initial loading of a level or game without the actual mess of loading of resources during the game with a resource manager, etc.
Store and Interpolate are used for interpolation of the scene graph for the "Fix your timestep" pattern, which means, that the scene graph
is updated with a fixed timestep, but rendered with a variable timestep, which is interpolated between the last and the current scene graph
state for smooth rendering. Where Store is called for storing the scene graph state, Interpolate is called for interpolating the scene graph
with a fixed timestep with aDeltaTime as parameter, Interpolate is called for interpolating the scene graph with a variable timestep with
aAlpha as parameter. And FrameUpdate is called after Interpolate for updating some stuff just frame-wise, like audio, etc. and is called
in the main thread.
Render is called for rendering the scene graph and can be called in the main "or" in a render thread, depending on the settings of the
PasVulkan main loop, so be careful with thread-safety.
UpdateAudio is called for updating audio and is called in the audio thread, so be careful with thread-safety. So use it in combination with
FrameUpdate, which is called in the main thread, with a thread safe data ring buffer oder queue for audio data, which is filled in FrameUpdate
and read in UpdateAudio. You can use the constructs from PasMP for that, see the PasMP.pas unit.
}
type TpvScene=class;
TpvSceneNode=class;
TpvSceneNodeClass=class of TpvSceneNode;
TpvSceneNodes=TpvObjectGenericList<TpvSceneNode>;
TpvSceneNodeHashMap=TpvHashMap<TpvSceneNodeClass,TpvSceneNodes>;
{ TpvSceneNode }
TpvSceneNode=class
public
private
fScene:TpvScene;
fParent:TpvSceneNode;
fData:TObject;
fChildren:TpvSceneNodes;
fNodeHashMap:TpvSceneNodeHashMap;
fLock:TpvInt32;
fLoadState:TPasMPInt32;
fDestroying:boolean;
public
constructor Create(const aParent:TpvSceneNode;const aData:TObject=nil); reintroduce; virtual;
destructor Destroy; override;
procedure Add(const aNode:TpvSceneNode);
procedure Remove(const aNode:TpvSceneNode);
function GetNodeListOf(const aNodeClass:TpvSceneNodeClass):TpvSceneNodes;
function GetNodeOf(const aNodeClass:TpvSceneNodeClass;const aIndex:TpvSizeInt=0):TpvSceneNode;
function GetNodeCountOf(const aNodeClass:TpvSceneNodeClass):TpvSizeInt;
procedure StartLoad; virtual;
procedure BackgroundLoad; virtual;
procedure FinishLoad; virtual;
procedure WaitForLoaded; virtual;
function IsLoaded:boolean; virtual;
procedure Store; virtual;
procedure Update(const aDeltaTime:TpvDouble); virtual;
procedure Interpolate(const aAlpha:TpvDouble); virtual;
procedure FrameUpdate; virtual;
procedure Render; virtual;
procedure UpdateAudio; virtual;
published
property Scene:TpvScene read fScene;
property Parent:TpvSceneNode read fParent;
property Data:TObject read fData;
property Children:TpvSceneNodes read fChildren;
end;
{ TpvScene }
TpvScene=class
private
fRootNode:TpvSceneNode;
fData:TObject;
public
constructor Create(const aData:TObject=nil); reintroduce; virtual;
destructor Destroy; override;
procedure StartLoad; virtual;
procedure BackgroundLoad; virtual;
procedure FinishLoad; virtual;
procedure WaitForLoaded; virtual;
function IsLoaded:boolean; virtual;
procedure Store; virtual;
procedure Update(const aDeltaTime:TpvDouble); virtual;
procedure Interpolate(const aAlpha:TpvDouble); virtual;
procedure FrameUpdate; virtual;
procedure Render; virtual;
procedure UpdateAudio; virtual;
published
property RootNode:TpvSceneNode read fRootNode;
property Data:TObject read fData;
end;
{ TpvSceneNode3D }
TpvSceneNode3D=class(TpvSceneNode)
private
fLastNode3DParent:TpvSceneNode3D;
fTransform:TpvMatrix4x4;
fCachedWorldTransform:TpvMatrix4x4;
fLastCachedWorldTransform:TpvMatrix4x4;
fInterpolatedCachedWorldTransform:TpvMatrix4x4;
fBounds:TpvAABB;
protected
procedure UpdateCachedWorldTransform; virtual;
function GetWorldTransform:TpvMatrix4x4; virtual;
procedure SetWorldTransform(const aWorldTransform:TpvMatrix4x4); virtual;
procedure UpdateBounds; virtual;
public
constructor Create(const aParent:TpvSceneNode;const aData:TObject=nil); override;
destructor Destroy; override;
procedure Store; override;
procedure Update(const aDeltaTime:TpvDouble); override;
procedure Interpolate(const aAlpha:TpvDouble); override;
public
property Transform:TpvMatrix4x4 read fTransform write fTransform;
property WorldTransform:TpvMatrix4x4 read GetWorldTransform write SetWorldTransform;
property CachedWorldTransform:TpvMatrix4x4 read fCachedWorldTransform;
property LastCachedWorldTransform:TpvMatrix4x4 read fLastCachedWorldTransform;
property InterpolatedCachedWorldTransform:TpvMatrix4x4 read fInterpolatedCachedWorldTransform;
property Bounds:TpvAABB read fBounds write fBounds;
end;
implementation
uses PasVulkan.Application;
{ TpvSceneNode }
constructor TpvSceneNode.Create(const aParent:TpvSceneNode;const aData:TObject);
begin
inherited Create;
fLock:=0;
fParent:=aParent;
if assigned(fScene) then begin
fScene:=fParent.fScene;
end else begin
fScene:=nil;
end;
fData:=aData;
fChildren:=TpvSceneNodes.Create;
fChildren.OwnsObjects:=true;
fDestroying:=false;
TPasMPInterlocked.Write(fLoadState,0);
fNodeHashMap:=TpvSceneNodeHashMap.Create(nil);
if assigned(fParent) then begin
fParent.Add(self);
end;
end;
destructor TpvSceneNode.Destroy;
var ChildNodeIndex:TpvSizeInt;
ChildNode,ParentNode:TpvSceneNode;
NodeClass:TpvSceneNodeClass;
Nodes:TpvSceneNodes;
begin
if assigned(fParent) and not fDestroying then begin
ParentNode:=fParent;
TPasMPMultipleReaderSingleWriterSpinLock.AcquireWrite(ParentNode.fLock);
try
fParent:=nil;
ChildNodeIndex:=ParentNode.fChildren.IndexOf(self);
if ChildNodeIndex>=0 then begin
NodeClass:=TpvSceneNodeClass(ClassType);
Nodes:=ParentNode.fNodeHashMap[NodeClass];
if assigned(Nodes) then begin
Nodes.Remove(self);
end;
ParentNode.fChildren.Extract(ChildNodeIndex);
end;
finally
TPasMPMultipleReaderSingleWriterSpinLock.ReleaseWrite(ParentNode.fLock);
end;
end;
for ChildNodeIndex:=0 to fChildren.Count-1 do begin
ChildNode:=fChildren[ChildNodeIndex];
ChildNode.fDestroying:=true;
end;
FreeAndNil(fChildren);
for Nodes in fNodeHashMap.Values do begin
Nodes.Free;
end;
FreeAndNil(fNodeHashMap);
inherited Destroy;
end;
procedure TpvSceneNode.Add(const aNode:TpvSceneNode);
var NodeClass:TpvSceneNodeClass;
Nodes:TpvSceneNodes;
begin
if assigned(aNode) then begin
TPasMPMultipleReaderSingleWriterSpinLock.AcquireWrite(fLock);
try
NodeClass:=TpvSceneNodeClass(aNode.ClassType);
Nodes:=fNodeHashMap[NodeClass];
if not assigned(Nodes) then begin
Nodes:=TpvSceneNodes.Create;
Nodes.OwnsObjects:=false;
fNodeHashMap[NodeClass]:=Nodes;
end;
Nodes.Add(aNode);
fChildren.Add(aNode);
aNode.fParent:=self;
finally
TPasMPMultipleReaderSingleWriterSpinLock.ReleaseWrite(fLock);
end;
end;
end;
procedure TpvSceneNode.Remove(const aNode:TpvSceneNode);
var Index:TpvSizeInt;
NodeClass:TpvSceneNodeClass;
Nodes:TpvSceneNodes;
begin
if assigned(aNode) and (aNode.fParent=self) and not aNode.fDestroying then begin
TPasMPMultipleReaderSingleWriterSpinLock.AcquireWrite(fLock);
try
Index:=fChildren.IndexOf(aNode);
if Index>=0 then begin
aNode.fDestroying:=true;
NodeClass:=TpvSceneNodeClass(aNode.ClassType);
Nodes:=fNodeHashMap[NodeClass];
if assigned(Nodes) then begin
Nodes.Remove(aNode);
end;
fChildren.Extract(Index);
aNode.Free;
end;
finally
TPasMPMultipleReaderSingleWriterSpinLock.ReleaseWrite(fLock);
end;
end;
end;
function TpvSceneNode.GetNodeListOf(const aNodeClass:TpvSceneNodeClass):TpvSceneNodes;
begin
result:=fNodeHashMap[aNodeClass];
end;
function TpvSceneNode.GetNodeOf(const aNodeClass:TpvSceneNodeClass;const aIndex:TpvSizeInt=0):TpvSceneNode;
var Nodes:TpvSceneNodes;
begin
Nodes:=fNodeHashMap[aNodeClass];
if assigned(Nodes) and (aIndex>=0) and (aIndex<Nodes.Count) then begin
result:=Nodes[aIndex];
end else begin
result:=nil;
end;
end;
function TpvSceneNode.GetNodeCountOf(const aNodeClass:TpvSceneNodeClass):TpvSizeInt;
var Nodes:TpvSceneNodes;
begin
Nodes:=fNodeHashMap[aNodeClass];
if assigned(Nodes) then begin
result:=Nodes.Count;
end else begin
result:=0;
end;
end;
procedure TpvSceneNode.StartLoad;
var ChildNodeIndex:TpvSizeInt;
ChildNode:TpvSceneNode;
begin
for ChildNodeIndex:=0 to fChildren.Count-1 do begin
ChildNode:=fChildren[ChildNodeIndex];
ChildNode.StartLoad;
end;
TPasMPInterlocked.Write(fLoadState,1);
end;
procedure TpvSceneNode.BackgroundLoad;
var ChildNodeIndex:TpvSizeInt;
ChildNode:TpvSceneNode;
begin
for ChildNodeIndex:=0 to fChildren.Count-1 do begin
ChildNode:=fChildren[ChildNodeIndex];
ChildNode.BackgroundLoad;
end;
TPasMPInterlocked.Write(fLoadState,2);
end;
procedure TpvSceneNode.FinishLoad;
var ChildNodeIndex:TpvSizeInt;
ChildNode:TpvSceneNode;
begin
for ChildNodeIndex:=0 to fChildren.Count-1 do begin
ChildNode:=fChildren[ChildNodeIndex];
ChildNode.FinishLoad;
end;
pvApplication.Log(LOG_DEBUG,ClassName+'.FinishLoad.WaitForLoaded','Entering...');
try
while TPasMPInterlocked.Read(fLoadState)<2 do begin
Sleep(1);
end;
TPasMPInterlocked.Write(fLoadState,3);
finally
pvApplication.Log(LOG_DEBUG,ClassName+'.FinishLoad.WaitForLoaded','Leaving...');
end;
end;
procedure TpvSceneNode.WaitForLoaded;
var ChildNodeIndex:TpvSizeInt;
ChildNode:TpvSceneNode;
begin
pvApplication.Log(LOG_DEBUG,ClassName+'.WaitForLoaded','Entering...');
try
for ChildNodeIndex:=0 to fChildren.Count-1 do begin
ChildNode:=fChildren[ChildNodeIndex];
ChildNode.WaitForLoaded;
end;
while TPasMPInterlocked.Read(fLoadState)<3 do begin
Sleep(1);
end;
finally
pvApplication.Log(LOG_DEBUG,ClassName+'.WaitForLoaded','Leaving...');
end;
end;
function TpvSceneNode.IsLoaded:boolean;
var ChildNodeIndex:TpvSizeInt;
ChildNode:TpvSceneNode;
begin
for ChildNodeIndex:=0 to fChildren.Count-1 do begin
ChildNode:=fChildren[ChildNodeIndex];
result:=ChildNode.IsLoaded;
if not result then begin
exit;
end;
end;
result:=TPasMPInterlocked.Read(fLoadState)>=3;
end;
procedure TpvSceneNode.Store;
var ChildNodeIndex:TpvSizeInt;
ChildNode:TpvSceneNode;
begin
for ChildNodeIndex:=0 to fChildren.Count-1 do begin
ChildNode:=fChildren[ChildNodeIndex];
ChildNode.Store;
end;
end;
procedure TpvSceneNode.Update(const aDeltaTime:TpvDouble);
var ChildNodeIndex:TpvSizeInt;
ChildNode:TpvSceneNode;
begin
for ChildNodeIndex:=0 to fChildren.Count-1 do begin
ChildNode:=fChildren[ChildNodeIndex];
ChildNode.Update(aDeltaTime);
end;
end;
procedure TpvSceneNode.Interpolate(const aAlpha:TpvDouble);
var ChildNodeIndex:TpvSizeInt;
ChildNode:TpvSceneNode;
begin
for ChildNodeIndex:=0 to fChildren.Count-1 do begin
ChildNode:=fChildren[ChildNodeIndex];
ChildNode.Interpolate(aAlpha);
end;
end;
procedure TpvSceneNode.FrameUpdate;
var ChildNodeIndex:TpvSizeInt;
ChildNode:TpvSceneNode;
begin
for ChildNodeIndex:=0 to fChildren.Count-1 do begin
ChildNode:=fChildren[ChildNodeIndex];
ChildNode.FrameUpdate;
end;
end;
procedure TpvSceneNode.Render;
var ChildNodeIndex:TpvSizeInt;
ChildNode:TpvSceneNode;
begin
for ChildNodeIndex:=0 to fChildren.Count-1 do begin
ChildNode:=fChildren[ChildNodeIndex];
ChildNode.Render;
end;
end;
procedure TpvSceneNode.UpdateAudio;
var ChildNodeIndex:TpvSizeInt;
ChildNode:TpvSceneNode;
begin
for ChildNodeIndex:=0 to fChildren.Count-1 do begin
ChildNode:=fChildren[ChildNodeIndex];
ChildNode.UpdateAudio;
end;
end;
{ TpvScene }
constructor TpvScene.Create(const aData:TObject=nil);
begin
inherited Create;
fRootNode:=TpvSceneNode.Create(nil);
fRootNode.fScene:=self;
fData:=aData;
end;
destructor TpvScene.Destroy;
begin
FreeAndNil(fRootNode);
inherited Destroy;
end;
procedure TpvScene.StartLoad;
begin
fRootNode.StartLoad;
end;
procedure TpvScene.BackgroundLoad;
begin
fRootNode.BackgroundLoad;
end;
procedure TpvScene.FinishLoad;
begin
fRootNode.FinishLoad;
end;
procedure TpvScene.WaitForLoaded;
begin
fRootNode.WaitForLoaded;
end;
function TpvScene.IsLoaded:boolean;
begin
result:=fRootNode.IsLoaded;
end;
procedure TpvScene.Store;
begin
fRootNode.Store;
end;
procedure TpvScene.Update(const aDeltaTime:TpvDouble);
begin
fRootNode.Update(aDeltaTime);
end;
procedure TpvScene.Interpolate(const aAlpha:TpvDouble);
begin
fRootNode.Interpolate(aAlpha);
end;
procedure TpvScene.FrameUpdate;
begin
fRootNode.FrameUpdate;
end;
procedure TpvScene.Render;
begin
fRootNode.Render;
end;
procedure TpvScene.UpdateAudio;
begin
fRootNode.UpdateAudio;
end;
{ TpvSceneNode3D }
constructor TpvSceneNode3D.Create(const aParent:TpvSceneNode;const aData:TObject=nil);
var LastNode3D:TpvSceneNode;
begin
inherited Create(aParent,aData);
LastNode3D:=fParent;
while assigned(LastNode3D) and not (LastNode3D is TpvSceneNode3D) do begin
LastNode3D:=LastNode3D.fParent;
end;
if not (assigned(LastNode3D) and (LastNode3D is TpvSceneNode3D)) then begin
LastNode3D:=nil; // No parent TpvSceneNode3D found
end;
fLastNode3DParent:=TpvSceneNode3D(LastNode3D);
fTransform:=TpvMatrix4x4.Identity;
fCachedWorldTransform:=TpvMatrix4x4.Identity;
end;
destructor TpvSceneNode3D.Destroy;
begin
inherited Destroy;
end;
procedure TpvSceneNode3D.UpdateCachedWorldTransform;
begin
if assigned(fLastNode3DParent) then begin
fCachedWorldTransform:=fLastNode3DParent.fCachedWorldTransform*fTransform;
end else begin
fCachedWorldTransform:=fTransform;
end;
end;
function TpvSceneNode3D.GetWorldTransform:TpvMatrix4x4;
begin
if assigned(fLastNode3DParent) then begin
result:=fLastNode3DParent.GetWorldTransform*fTransform;
end else begin
result:=fTransform;
end;
end;
procedure TpvSceneNode3D.SetWorldTransform(const aWorldTransform:TpvMatrix4x4);
begin
if assigned(fLastNode3DParent) then begin
fTransform:=fLastNode3DParent.GetWorldTransform.Inverse*aWorldTransform;
end else begin
fTransform:=aWorldTransform;
end;
end;
procedure TpvSceneNode3D.UpdateBounds;
begin
end;
procedure TpvSceneNode3D.Store;
begin
inherited Store;
fLastCachedWorldTransform:=fCachedWorldTransform;
end;
procedure TpvSceneNode3D.Update(const aDeltaTime:TpvDouble); // <- should call UpdateCachedWorldTransform on your own
begin
inherited Update(aDeltaTime);
end;
procedure TpvSceneNode3D.Interpolate(const aAlpha:TpvDouble);
begin
fInterpolatedCachedWorldTransform:=fLastCachedWorldTransform.Slerp(fCachedWorldTransform,aAlpha);
inherited Interpolate(aAlpha);
end;
end.
|
unit uBchEditor;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, Grids, Menus,
StdCtrls, math, uCustomTypes, uEditBatch, uStrUtils;
type
{ TfBchEditor }
TfBchEditor = class(TForm)
bCancel: TButton;
bOK: TButton;
pmiCopyBatch: TMenuItem;
miCopyBatch: TMenuItem;
pmiDelBatch: TMenuItem;
pmiEditBatch: TMenuItem;
pmiAddBatch: TMenuItem;
miDeleteBatch: TMenuItem;
miEditBatch: TMenuItem;
miAddBatch: TMenuItem;
miActions: TMenuItem;
mmBatchEditor: TMainMenu;
pmBatchEditor: TPopupMenu;
sgBch: TStringGrid;
procedure bCancelClick(Sender: TObject);
procedure bOKClick(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure miAddBatchClick(Sender: TObject);
procedure miCopyBatchClick(Sender: TObject);
procedure miDeleteBatchClick(Sender: TObject);
procedure miEditBatchClick(Sender: TObject);
procedure pmiAddBatchClick(Sender: TObject);
procedure pmiCopyBatchClick(Sender: TObject);
procedure pmiDelBatchClick(Sender: TObject);
procedure pmiEditBatchClick(Sender: TObject);
procedure sgBchDblClick(Sender: TObject);
procedure sgBchResize(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
fBchEditor: TfBchEditor;
COPYarrServerBatchList:array of TBatch;
res:string;
isSelectMode:boolean;
procedure StartBchEdit;
function SelectBatch(batch_name:string):string;
procedure RefreshList;
procedure EditB;
procedure CopyB;
procedure AddB;
procedure DelB;
function BatchUsedInEvent(batch:TBatch):boolean;
function BatchNameUsed(batch_name,initial_batch_name:string):boolean;
implementation
uses uMain, uSchEditor;
{$R *.lfm}
{ TfBchEditor }
procedure StartBchEdit;
var
x:integer;
begin
isSelectMode:=false;
Setlength(COPYarrServerBatchList,length(uMain.arrServerBatchList));
for x:=1 to length(uMain.arrServerBatchList) do
begin
COPYarrServerBatchList[x-1]:=uMain.arrServerBatchList[x-1];
end;
Application.CreateForm(TfBchEditor, fBchEditor);
RefreshList;
fBchEditor.ShowModal;
end;
function SelectBatch(batch_name:string):string;
var
x:integer;
begin
isSelectMode:=true;
Setlength(COPYarrServerBatchList,length(uMain.arrServerBatchList));
for x:=1 to length(uMain.arrServerBatchList) do
begin
COPYarrServerBatchList[x-1]:=uMain.arrServerBatchList[x-1];
end;
Application.CreateForm(TfBchEditor, fBchEditor);
RefreshList;
// find batch name
for x:=1 to length(COPYarrServerBatchList) do
begin
if UpperCase(batch_name)=UpperCase(COPYarrServerBatchList[x-1].batch_name) then
begin
fBchEditor.sgBch.Row:=x;
end;
end;
fBchEditor.bOK.Caption:='Select';
fBchEditor.ShowModal;
Result:=res;
end;
function BatchNameUsed(batch_name,initial_batch_name:string):boolean;
var
x:integer;
begin
result:=false;
if UPPERCASE(batch_name)=UPPERCASE(initial_batch_name) then
begin
exit;
end;
for x:=1 to length(COPYarrServerBatchList) do
begin
if UPPERCASE(batch_name)=UPPERCASE(COPYarrServerBatchList[x-1].batch_name) then
begin
result:=true;
exit;
end;
end;
end;
function BatchUsedInEvent(batch:TBatch):boolean;
var
x,l:integer;
tmp_bn:string;
begin
result:=false;
if isSelectMode then
begin
l:=length(uSchEditor.COPYarrServerSch);
for x:=1 to l do
begin
tmp_bn:=uStrUtils.GetFieldFromString(uSchEditor.COPYarrServerSch[x-1].event_execution_str,ParamLimiter,3);
if UpperCase(tmp_bn)=UpperCase(batch.batch_name) then
begin
result:=true;
exit;
end;
end;
end
else
begin
l:=length(arrServerSch);
for x:=1 to l do
begin
tmp_bn:=uStrUtils.GetFieldFromString(arrServerSch[x-1].event_execution_str,ParamLimiter,3);
if UpperCase(tmp_bn)=UpperCase(batch.batch_name) then
begin
result:=true;
exit;
end;
end;
end;
end;
procedure TfBchEditor.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
CloseAction:=caFree;
end;
procedure TfBchEditor.miAddBatchClick(Sender: TObject);
begin
AddB;
end;
procedure TfBchEditor.miCopyBatchClick(Sender: TObject);
begin
CopyB;
end;
procedure TfBchEditor.miDeleteBatchClick(Sender: TObject);
begin
DelB;
end;
procedure TfBchEditor.miEditBatchClick(Sender: TObject);
begin
EditB;
end;
procedure TfBchEditor.pmiAddBatchClick(Sender: TObject);
begin
AddB;
end;
procedure TfBchEditor.pmiCopyBatchClick(Sender: TObject);
begin
CopyB;
end;
procedure TfBchEditor.pmiDelBatchClick(Sender: TObject);
begin
DelB;
end;
procedure TfBchEditor.pmiEditBatchClick(Sender: TObject);
begin
EditB;
end;
procedure TfBchEditor.sgBchDblClick(Sender: TObject);
begin
if isSelectMode then
begin
bOK.Click;
end
else
begin
EditB;
end;
end;
procedure TfBchEditor.sgBchResize(Sender: TObject);
begin
sgBch.Columns.Items[0].Width:=sgBch.Width-(574-540);
end;
procedure TfBchEditor.bCancelClick(Sender: TObject);
begin
Close;
end;
procedure TfBchEditor.bOKClick(Sender: TObject);
var
x,r:integer;
begin
if isSelectMode then
begin
r:=fBchEditor.sgBch.Row;
if r<1 then
begin
ShowMessage('Select batch first!');
exit;
end;
if r>Length(COPYarrServerBatchList) then
begin
ShowMessage('Select batch first!');
exit;
end;
Setlength(uMain.arrServerBatchList,length(COPYarrServerBatchList));
for x:=1 to length(COPYarrServerBatchList) do
begin
uMain.arrServerBatchList[x-1]:=COPYarrServerBatchList[x-1];
end;
res:=COPYarrServerBatchList[r-1].batch_name;
close;
end
else
begin
Setlength(uMain.arrServerBatchList,length(COPYarrServerBatchList));
for x:=1 to length(COPYarrServerBatchList) do
begin
uMain.arrServerBatchList[x-1]:=COPYarrServerBatchList[x-1];
end;
WaitSocketForOp(5); // save batch list to server
close;
end;
end;
procedure RefreshList;
var
x,l,r:integer;
begin
r:=fBchEditor.sgBch.Row;
l:=length(COPYarrServerBatchList);
fBchEditor.sgBch.RowCount:=max(l+1,2);
if l=0 then
begin
fBchEditor.sgBch.Cells[0,1]:='';
end;
for x:=1 to l do
begin
fBchEditor.sgBch.Cells[0,x]:=COPYarrServerBatchList[x-1].batch_name;
end;
fBchEditor.sgBch.Row:=r;
end;
procedure EditB;
var
r:integer;
br:TBatchResult;
begin
r:=fBchEditor.sgBch.Row;
if r<1 then
begin
ShowMessage('Select batch first!');
exit;
end;
if r>Length(COPYarrServerBatchList) then
begin
ShowMessage('Select batch first!');
exit;
end;
br:=uEditBatch.EditBatch(COPYarrServerBatchList[r-1],BatchUsedInEvent(COPYarrServerBatchList[r-1]));
if br.res then
begin
COPYarrServerBatchList[r-1]:=br.br_batch;
RefreshList;
end;
end;
procedure CopyB;
var
r:integer;
br:TBatchResult;
b:TBatch;
begin
r:=fBchEditor.sgBch.Row;
if r<1 then
begin
ShowMessage('Select batch first!');
exit;
end;
if r>Length(COPYarrServerBatchList) then
begin
ShowMessage('Select batch first!');
exit;
end;
b:=COPYarrServerBatchList[r-1];
b.batch_name:='';
br:=uEditBatch.EditBatch(b,false);
if br.res then
begin
SetLength(COPYarrServerBatchList,Length(COPYarrServerBatchList)+1);
COPYarrServerBatchList[Length(COPYarrServerBatchList)-1]:=br.br_batch;
RefreshList;
end;
end;
procedure AddB;
var
tmpBatch:tBatch;
br:TBatchResult;
begin
tmpBatch.batch_name:='';
tmpBatch.batch_str:='0';
tmpBatch.batch_params:='';
br:=uEditBatch.EditBatch(tmpBatch,false);
if br.res then
begin
SetLength(COPYarrServerBatchList,Length(COPYarrServerBatchList)+1);
COPYarrServerBatchList[Length(COPYarrServerBatchList)-1]:=br.br_batch;
RefreshList;
end;
end;
procedure DelB;
var
r:integer;
x:integer;
begin
r:=fBchEditor.sgBch.Row;
if r<1 then
begin
ShowMessage('Select batch first!');
exit;
end;
if r>Length(COPYarrServerBatchList) then
begin
ShowMessage('Select batch first!');
exit;
end;
if BatchUsedInEvent(COPYarrServerBatchList[r-1]) then
begin
ShowMessage('Selected batch used in tasks!');
exit;
end;
if MessageDlg('Are you sure?','Delete batch '+COPYarrServerBatchList[r-1].batch_name+'?',mtConfirmation,[mbYes, mbNo],0)=mrYes then
begin
for x:=r to Length(COPYarrServerBatchList)-1 do
begin
COPYarrServerBatchList[x-1]:=COPYarrServerBatchList[x];
end;
SetLength(COPYarrServerBatchList,Length(COPYarrServerBatchList)-1);
RefreshList;
end;
end;
end.
|
{*****************************************************************}
{ TWEBDATA component }
{ for Delphi 3.0,4.0,5.0,6.0 C++Builder 3,4,5 }
{ version 1.0 - October 2001 }
{ }
{ written by }
{ TMS Software }
{ copyright © 1999 - 2001 }
{ Email: info@tmssoftware.com }
{ Web: http://www.tmssoftware.com }
{*****************************************************************}
unit wdatreg;
interface
uses
WebData, Classes;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('TMS Web',[TWebData]);
end;
end.
|
unit guiobject;
//not part of the game mechanics, but handles click events and wraps basic gui stuff like text
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, controls, renderobject, gamepanel, types;
type
TNotifyEventF=function(sender: TObject): boolean of object;
TGUIObject=class(TRenderObject) //abstract
private
fOwner: TGamePanel;
protected
fOnClick: TNotifyEventF;
function getWidth:single; override;
function getHeight:single; override;
function getTopLeftCorner: tpointf;
function mhandler(sender: TObject; meventtype: integer; Button: TMouseButton; Shift: TShiftState; mX, mY: Integer): boolean; virtual;
public
constructor create(owner: TGamePanel=nil; zpos: integer=-1);
destructor destroy; override;
property OnClick: TNotifyEventF read fOnClick write fOnClick;
end;
implementation
function TGUIObject.getTopLeftCorner: TPointF;
begin
//only functions when no rotation is applied
result.x:=x-(width/2)*(rotationpoint.x+1);
result.y:=y-(height/2)*(rotationpoint.y+1);
end;
function TGUIObject.getWidth:single;
begin
result:=2;
end;
function TGUIObject.getHeight:single;
begin
result:=2;
end;
function TGUIObject.mhandler(sender: TObject; meventtype: integer; Button: TMouseButton; Shift: TShiftState; mX, mY: Integer): boolean;
var gamepos, objectpos: tpointf;
begin
if meventtype=0 then
begin
gamepos:=TGamePanel(sender).PixelPosToGamePos(mx,my);
objectpos:=getTopLeftCorner;
if (gamepos.x>=objectpos.x) and (gamepos.x<objectpos.x+width) and (gamepos.y>=objectpos.y) and (gamepos.y<objectpos.y+height) then
begin
if assigned(fOnClick) then
exit(fOnClick(self));
end;
end;
result:=false;
end;
constructor TGUIObject.create(owner: TGamePanel; zpos: integer);
begin
fowner:=owner;
if owner<>nil then
owner.AddMouseEventHandler(@mhandler, zpos);
inherited create;
end;
destructor TGUIObject.destroy;
begin
if fowner<>nil then
fowner.RemoveMouseEventHandler(@mhandler);
inherited destroy;
end;
end.
|
unit untProgram;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, untLiableSignedEventArgs, untInifilehelper,
untdestaplocaldatabasehelper, untremotedatabasehelper,
untDataStoreArrayList, sqldb, Dialogs, untDataStore, sqlite3conn, DB,
untlocation, untUtils, frmSerialKey, Windows, untAdminTools, untStruct, dateutils,
untWatchDogTimerRefresh;
function AddNewLiable(LiableId: integer): boolean;
function DeleteLiable(LiableId: integer): boolean;
function UpdateLiable(LiableId: integer): boolean;
function Db_Updater(p: Pointer): longint;
function Log_Updater(p: Pointer): longint;
function WacthdogTrace(p: pointer): longint;
function InitializeApplication: boolean;
procedure CloseAll;
function LogWriter(LogRecord: _LOGRECORD): integer;
function SystemLogger(p: Pointer): longint;
function GetLocationName(LocationId:integer):string;
function AutoResetDevice(p:Pointer):longint;
function CheckConnection:boolean;
var
Me: _Lokasyon;
EvtLiableSigned: TLiableSignedEventArgs;
Config: TIniFileHelper;
LocalDatabaseConn: TDestapLocalDatabaseHelper;
RemoteDatabaseConn: RemoteDatabaseHelper;
WatchDogTimerRefresher:TWatchDogTimerRefresh;
bolStopDBUpdater, bolWatchDogManual, bolNoTraceWatchDog: boolean;
bolStopLogUpdater: boolean;
thDbUpdater, thLogUploader, thWatchdogTrace, thSystemLogger, thAutoReset: TThreadID;
hWatchdogFile: HANDLE;
nNoConnectionCounter:integer;
strLocationName:string;
implementation
function AddNewLiable(LiableId: integer): boolean;
var
dstLiables, dstFingers, dstMessage: TDataStoreArrayList;
strCmdLiables, strCmdFingerPrint, strCmdMessage: WideString;
strInsertLiable, strInsertFingerPrints, strInsertMessage: WideString;
strQueryInsertMessage, strQueryInsertFingerPrints: WideString;
i: integer;
qryResult: TSQLQuery;
strFingerData: ansistring;
arbFingerData, arbDummyArray: TemplateByteArray;
stmFingerData: TMemoryStream;
bolExecuteResult:Boolean;
begin
strCmdLiables := Format(
'select KimlikNo, Isim, Soyisim, Degistirildi from YUKUMLULER where YukumluId=%d',
[LiableId]);
strCmdFingerPrint := Format(
'select FingerData, FingerIndex from PARMAKIZI where YukumluId=%d', [LiableId]);
strCmdMessage := Format(
'select MesajId, YukumluId, MesajIndex, Mesaj from YUKUMLUMESAJ where Durum=0 and YukumluId=%d',
[LiableId]);
bolExecuteResult:=true;
dstLiables := TDataStoreArrayList.Create;
bolExecuteResult:=bolExecuteResult and RemoteDatabaseConn.ExecuteMultiRow(strCmdLiables, dstLiables);
dstFingers := TDataStoreArrayList.Create;
bolExecuteResult:=bolExecuteResult and RemoteDatabaseConn.ExecuteMultiRow(strCmdFingerPrint, dstFingers);
dstMessage := TDataStoreArrayList.Create;
bolExecuteResult:=bolExecuteResult and RemoteDatabaseConn.ExecuteMultiRow(strCmdMessage, dstMessage);
if(not bolExecuteResult) then
begin
FreeAndNil(dstFingers);
FreeAndNil(dstLiables);
FreeAndNil(dstMessage);
Result:=false;
exit;
end;
strInsertLiable :=
'Insert into Liables(LiableId, IdentityId, Name, Surname, ModifiedTime) values(:LiableId, :IdentityId, :Name, :Surname, :ModifiedTime)';
qryResult := LocalDatabaseConn.ExecuteQuery(strInsertLiable);
qryResult.Params.ParamByName('LiableId').AsInteger := LiableId;
qryResult.Params.ParamByName('IdentityId').AsString :=
dstLiables.GetItems(0).GetString('KimlikNo');
qryResult.Params.ParamByName('Name').AsString :=
dstLiables.GetItems(0).GetString('Isim');
qryResult.Params.ParamByName('Surname').AsString :=
dstLiables.GetItems(0).GetString('Soyisim');
qryResult.Params.ParamByName('ModifiedTime').AsLargeInt :=
LocalDatabaseConn.DateTimeToComp(dstLiables.GetItems(0).GetDateTime('Degistirildi'));
qryResult.ExecSQL;
TSQLTransaction(qryResult.Transaction).Commit;
LocalDatabaseConn.ReturnDBQuery(qryResult);
for i := 0 to dstFingers.Count - 1 do
begin
strInsertFingerPrints :=
'insert into FingerPrints (LiableId, FingerData,FingerIndex ) values (:YukumluId, :FingerData, :FingerIndex)';
qryResult := LocalDatabaseConn.ExecuteQuery(strInsertFingerPrints);
qryResult.Params.ParamByName('YukumluId').AsInteger := LiableId;
qryResult.Params.ParamByName('FingerIndex').AsInteger :=
dstFingers.GetItems(i).GetInt32('FingerIndex');
arbFingerData := dstFingers.GetItems(i).GetTemplateByteArray('FingerData');
stmFingerData := TMemoryStream.Create;
stmFingerData.Write(arbFingerData, Length(arbFingerData));
stmFingerData.Seek(0, soBeginning);
qryResult.Params.ParamByName('FingerData').LoadFromStream(stmFingerData, ftBlob);
FreeAndNil(stmFingerData);
qryResult.ExecSQL;
TSQLTransaction(qryResult.Transaction).Commit;
LocalDatabaseConn.ReturnDBQuery(qryResult);
end;
for i := 0 to dstMessage.Count - 1 do
begin
strInsertMessage :=
'INSERT INTO Message (LiableId, MessageId, MessageIndex, Message, IsActive)' +
'VALUES (:LiableId, :MessageId, :MessageIndex, :Message, 1)';
qryResult := LocalDatabaseConn.ExecuteQuery(strInsertMessage);
qryResult.Params.ParamByName('LiableId').AsInteger := LiableId;
qryResult.Params.ParamByName('MessageId').AsInteger :=
dstMessage.GetItems(i).GetInt32('MesajId');
qryResult.Params.ParamByName('MessageIndex').AsInteger :=
dstMessage.GetItems(i).GetInt32('MesajIndex');
qryResult.Params.ParamByName('Message').AsString :=
dstMessage.GetItems(i).GetString('Mesaj');
qryResult.ExecSQL;
TSQLTransaction(qryResult.Transaction).Commit;
LocalDatabaseConn.ReturnDBQuery(qryResult);
end;
FreeAndNil(dstFingers);
FreeAndNil(dstLiables);
FreeAndNil(dstMessage);
Result := True;
exit;
end;
function DeleteLiable(LiableId: integer): boolean;
var
strDeleteLiableInfo, strQueryDeleteLiableInfo: WideString;
begin
strDeleteLiableInfo := 'delete from Message where LiableId=%d;';
strQueryDeleteLiableInfo := Format(strDeleteLiableInfo, [LiableId]);
LocalDatabaseConn.ExecuteNonQuery(strQueryDeleteLiableInfo, 'Liables');
strDeleteLiableInfo := 'delete from FingerPrints where LiableId=%d;';
strQueryDeleteLiableInfo := Format(strDeleteLiableInfo, [LiableId]);
LocalDatabaseConn.ExecuteNonQuery(strQueryDeleteLiableInfo, 'Liables');
strDeleteLiableInfo := 'delete from Liables where LiableId=%d';
strQueryDeleteLiableInfo := Format(strDeleteLiableInfo, [LiableId]);
if (LocalDatabaseConn.ExecuteNonQuery(strQueryDeleteLiableInfo, 'Liables') = 0) then
begin
ShowMessage(Format('Yükümlü silme işlemi başarısız: %d', [LiableId]));
Result := False;
exit;
end
else
begin
Result := True;
exit;
end;
end;
function UpdateLiable(LiableId: integer): boolean;
var
strSelectLiables, strSelectFingerPrints, strSelectLiableMessage: WideString;
strQuerySelectLiables, strQuerySelectFingerPrints,
strQuerySelectLiableMessage: WideString;
rowsQerySelectLiables, rowsQuerySelectFingerPrints,
rowsQuerySelectLiableMessage: TDataStoreArrayList;
strDeleteMessage, strDeleteFingerPrints: WideString;
strQueryDeleteMessage, strQueryDeleteFingerPrints: WideString;
strUpdateLocalLiables: WideString;
strQueryUpdateLocalLiables: WideString;
strInsertIntoFingerPrints: WideString;
strQueryInsertIntoFingers: WideString;
rowLiable: TDataStore;
strInsertMesssageToLocalDb, strQueryInsertMessageToLocalDb: WideString;
i: integer;
strFingerData: ansistring;
arbFingerData: TemplateByteArray;
qryResult: TSQLQuery;
stmFingerData: TMemoryStream;
bolExecuteResult:Boolean;
begin
bolExecuteResult:=true;
strSelectLiables :=
'select KimlikNo, Isim, Soyisim, Degistirildi from YUKUMLULER where YukumluId = %d;';
strQuerySelectLiables := Format(strSelectLiables, [LiableId]);
rowsQerySelectLiables := TDataStoreArrayList.Create;
bolExecuteResult:= bolExecuteResult and RemoteDatabaseConn.ExecuteMultiRow(strQuerySelectLiables, rowsQerySelectLiables);
strSelectFingerPrints :=
'select FingerData, FingerIndex from PARMAKIZI where YukumluId = %d';
strQuerySelectFingerPrints := Format(strSelectFingerPrints, [LiableId]);
rowsQuerySelectFingerPrints := TDataStoreArrayList.Create;
bolExecuteResult:= bolExecuteResult and RemoteDatabaseConn.ExecuteMultiRow(strQuerySelectFingerPrints,
rowsQuerySelectFingerPrints);
strSelectLiableMessage :=
'select MesajId, YukumluId, MesajIndex, Mesaj from YUKUMLUMESAJ where YukumluId = %d and Durum = 0';
strQuerySelectLiableMessage := Format(strSelectLiableMessage, [LiableId]);
rowsQuerySelectLiableMessage := TDataStoreArrayList.Create;
bolExecuteResult:= bolExecuteResult and RemoteDatabaseConn.ExecuteMultiRow(strQuerySelectLiableMessage,
rowsQuerySelectLiableMessage);
if((not bolExecuteResult) or (rowsQerySelectLiables.Count = 0) ) then
begin
FreeAndNil(rowsQerySelectLiables);
FreeAndNil(rowsQuerySelectFingerPrints);
FreeAndNil(rowsQuerySelectLiableMessage);
Result:=false;
exit;
end;
rowLiable := rowsQerySelectLiables.GetItems(0);
strDeleteMessage := 'delete from Message where LiableId=%d';
strQueryDeleteMessage := Format(strDeleteMessage, [LiableId]);
LocalDatabaseConn.ExecuteNonQuery(strQueryDeleteMessage);
strDeleteFingerPrints := 'delete from FingerPrints where LiableId=%d';
strQueryDeleteFingerPrints := Format(strDeleteFingerPrints, [LiableId]);
LocalDatabaseConn.ExecuteNonQuery(strQueryDeleteFingerPrints);
strUpdateLocalLiables :=
'UPDATE [Liables] SET IdentityId=:IdentityId, Name=:Name, Surname=:Surname,' +
'ModifiedTime=:ModifiedTime WHERE LiableId=:LiableId';
qryResult := LocalDatabaseConn.ExecuteQuery(strUpdateLocalLiables);
qryResult.Params.ParamByName('IdentityId').AsString := rowLiable.GetString('KimlikNo');
qryREsult.Params.ParamByName('Name').AsString := rowLiable.GetString('Isim');
qryResult.Params.ParamByName('Surname').AsString := rowLiable.GetString('Soyisim');
qryResult.Params.ParamByName('ModifiedTime').AsLargeInt :=
LocalDatabaseConn.DateTimeToComp(rowLiable.GetDateTime('Degistirildi'));
qryResult.ExecSQL;
TSQLTransaction(qryResult.Transaction).Commit;
LocalDatabaseConn.ReturnDBQuery(qryResult);
//LocalDatabaseConn.ExecuteNonQuery(strQueryUpdateLocalLiables);
strInsertIntoFingerPrints :=
'INSERT INTO FingerPrints (LiableId, FingerData, FingerIndex) ' +
'VALUES (:LiableId, :FingerData, :FingerIndex)';
for i := 0 to rowsQuerySelectFingerPrints.Count - 1 do
begin
qryResult := LocalDatabaseConn.ExecuteQuery(strInsertIntoFingerPrints);
qryResult.Params.ParamByName('LiableId').AsInteger := LiableId;
qryResult.Params.ParamByName('FingerIndex').AsInteger :=
rowsQuerySelectFingerPrints.GetItems(i).GetInt32('FingerIndex');
arbFingerData := rowsQuerySelectFingerPrints.GetItems(i).GetTemplateByteArray(
'FingerData');
stmFingerData := TMemoryStream.Create;
stmFingerData.Write(arbFingerData, Length(arbFingerData));
stmFingerData.Seek(0, soBeginning);
qryResult.Params.ParamByName('FingerData').LoadFromStream(stmFingerData, ftBlob);
qryResult.ExecSQL;
TSQLTransaction(qryResult.Transaction).Commit;
LocalDatabaseConn.ReturnDBQuery(qryResult);
end;
strInsertMesssageToLocalDb :=
'INSERT INTO Message (LiableId, MessageId, MessageIndex, Message, IsActive) VALUES (:LiableId, :MessageId, :MessageIndex, :Message, 1)';
for i := 0 to rowsQuerySelectLiableMessage.Count - 1 do
begin
qryResult := LocalDatabaseConn.ExecuteQuery(strInsertMesssageToLocalDb);
qryResult.Params.ParamByName('LiableId').AsInteger := LiableId;
qryResult.Params.ParamByName('MessageId').AsInteger :=
rowsQuerySelectLiableMessage.GetItems(i).GetInt32('MesajId');
qryResult.Params.ParamByName('MessageIndex').AsInteger :=
rowsQuerySelectLiableMessage.GetItems(i).GetInt32('Index');
qryResult.Params.ParamByName('Message').AsString :=
rowsQuerySelectLiableMessage.GetItems(i).GetString('Mesaj');
qryResult.ExecSQL;
TSQLTransaction(qryResult.Transaction).Commit;
LocalDatabaseConn.ReturnDBQuery(qryResult);
end;
FreeAndNil(rowsQerySelectLiables);
FreeAndNil(rowsQuerySelectFingerPrints);
FreeAndNil(rowsQuerySelectLiableMessage);
Result := True;
exit;
end;
function Db_Updater(p: Pointer): longint;
const
nUpdaterInterval: integer = 300000;
nNoConnectionInterval: integer = 5000;
var
strCommandText, strIAmAlive, strGetDate: WideString;
rows: TDataStoreArrayList;
i, nRowCount: integer;
dtTime:TDateTime;
recSYSTEMTIME:_SYSTEMTIME;
wYear, wMonth, wDay, wHour, wMin, wSec, wMSec:WORD;
NewDateTime: TSystemTime;
begin
while (not bolStopDBUpdater) do
begin
while(not CheckConnection) do
begin
Sleep(StrToInt(Config.GetValue('DBUpdaterInterval')));
end;
//Sunucuya ulaşma vakti
strIAmAlive := Format('update Lokasyon set SonErisim=GetDate() where LokasyonId=%d', [Me.LokasyonId]);
RemoteDatabaseConn.ExecuteNonQuery(strIAmAlive);
//sistem saati güncelleniyor
strGetDate:='select GetDate()';
rows := TDataStoreArrayList.Create;
RemoteDatabaseConn.ExecuteMultiRow(strGetDate, rows);
dtTime:=rows.GetItems(0).GetDateTime(0);
{
DecodeDate(dtTime, wYear, wMonth, wDay);
recSYSTEMTIME.wDay:= wDay;
recSYSTEMTIME.wYear:=wYear;
recSYSTEMTIME.wMonth:=wMonth;
recSYSTEMTIME.wDayOfWeek:=DayOfTheWeek(dtTime);
DecodeTime(dtTime, wHour, wMin, wSec, wMSec);
recSYSTEMTIME.wHour:=wHour;
recSYSTEMTIME.wMinute:=wMin;
recSYSTEMTIME.wSecond:=wSec;
recSYSTEMTIME.wMilliseconds:=wMSec;
SetSystemTime(@recSYSTEMTIME);
}
FillChar(NewDateTime, SizeOf(NewDateTime), #0);
DecodeDate(dtTime, wYear, wMonth, wDay);
NewDateTime.wYear:=wYear;
NewDateTime.wMonth:=wMonth;
NewDateTime.wDay:=wDay;
DecodeTime(dtTime, wHour, wMin, wSec, wMSec);
NewDateTime.wHour:=wHour;
NewDateTime.wMinute:=wMin;
NewDateTime.wSecond:=wSec;
NewDateTime.wMilliseconds:=wMSec;
SetLocalTime(NewDateTime);
FreeAndNil(rows);
//Veritabanı güncellemeleleri alınıyor
if (StrToBool(Config.GetValue('SeminarLocation'))) then
begin
strCommandText := 'select Y.YukumluId, Y.Degistirildi, DP.IsActive ' +
'from YUKUMLULER as Y inner join DENETIMPLANLARI as DP ON Y.YukumluId = DP.YukumluId'
+ ' where DP.DenetimId in (select DenetimId from LINK_Lokasyon_DenetimPlani)';
end
else
begin
strCommandText := Format('select Y.YukumluId, Y.Degistirildi, DP.IsActive ' +
'from YUKUMLULER as Y inner join DENETIMPLANLARI as DP ON Y.YukumluId = DP.YukumluId'
+ ' where DP.DenetimId in (select DenetimId from LINK_Lokasyon_DenetimPlani where LokasyonId = %d)', [Me.LokasyonId]);
end;
rows := TDataStoreArrayList.Create;
RemoteDatabaseConn.ExecuteMultiRow(strCommandText, rows);
for i := 0 to rows.Count - 1 do
begin
strCommandText := Format('select count(LiableId) from Liables where LiableId=%d',
[rows.GetItems(i).GetInt32('YukumluId')]);
nRowCount := StrToInt(LocalDatabaseConn.ExecuteScalar(strCommandText));
if (nRowCount = 0) then
begin
try
AddNewLiable(rows.GetItems(i).GetInt32('YukumluId'));
except
on E: Exception do
WriteLog('Db_Updater.Add New Liable:' + E.Message);
end;
end
else
begin
if (not rows.GetItems(i).GetBoolean(2)) then
begin
try
DeleteLiable(rows.GetItems(i).GetInt32(0));
except
on E: Exception do
WriteLog('Db_Updater.DeleteLiable:' + E.Message);
end;
break;
end;
strCommandText :=
Format('select COUNT(*) from Liables ' +
'where LiableId=%d and ModifiedTime<%d',
[rows.GetItems(i).GetInt32(0),
LocalDatabaseConn.DateTimeToComp(rows.GetItems(i).GetDateTime(1))]);
nRowCount := StrToInt(LocalDatabaseConn.ExecuteScalar(strCommandText));
try
if (UpdateLiable(rows.GetItems(i).GetInt32(0))) then
begin
strCommandText :=
Format('update Liables set ModifiedTime=%d where LiableId=%d',
[LocalDatabaseConn.DateTimeToComp(rows.GetItems(i).GetDateTime(1)),
rows.GetItems(i).GetInt32(0)]);
LocalDatabaseConn.ExecuteNonQuery(strCommandText);
end;
except
on E: Exception do
WriteLog('DB_Updater.UpdateLiable' + E.Message);
end;
{
if (nRowCount <> 0) then
begin
try
if (UpdateLiable(rows.GetItems(i).GetInt32(0))) then
begin
strCommandText :=
Format('update Liables set ModifiedTime=%d where LiableId=%d',
[LocalDatabaseConn.DateTimeToComp(rows.GetItems(i).GetDateTime(1)),
rows.GetItems(i).GetInt32(0)]);
LocalDatabaseConn.ExecuteNonQuery(strCommandText);
end;
except
on E: Exception do
WriteLog('DB_Updater.UpdateLiable' + E.Message);
end;
end;
}
end;
end;
FreeAndNil(rows);
Sleep(StrToInt(Config.GetValue('DBUpdaterInterval')));
end;
end;
function Log_Updater(p: Pointer): longint;
const
nLogUpdateInterval: integer = 300000;
var
strInsertLogPanel, strQueryInsertLogPanel: WideString;
strUpdateLog, strQueryUpdateLog: WideString;
qryLogs: TSQLQuery;
strSelectFromLogs: WideString;
i: integer;
aryLogIds: array of integer;
begin
strInsertLogPanel :=
'INSERT INTO [LOG_Panel] (LokasyonId, YukumluId, ImzaZamani, Olusturuldu, MesajId, IsActive) '
+ 'VALUES (%d, %d, ''%s'', CURRENT_TIMESTAMP,%d, 1)';
strUpdateLog := 'UPDATE [LOG] SET IsSend=1 WHERE Id=%d';
while (not bolStopLogUpdater) do
begin
while(not CheckConnection) do
begin
Sleep(StrToInt(Config.GetValue('LogUpdaterInterval')));
end;
SetLength(aryLogIds, 0);
qryLogs := LocalDatabaseConn.ExecuteQuery(
'SELECT Id, LiableId, ProcessTime, MessageId FROM LOG WHERE IsSend=0');
qryLogs.Open;
while not qryLogs.EOF do
begin
strQueryInsertLogPanel :=
Format(strInsertLogPanel, [Me.LokasyonId,
qryLogs.FieldByName('LiableId').AsInteger,
FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz',
LocalDatabaseConn.CompToDateTime(qryLogs.FieldByName('ProcessTime').AsLargeInt)),
qryLogs.FieldByName('MessageId').AsInteger]);
if (RemoteDatabaseConn.ExecuteNonQuery(strQueryInsertLogPanel) = 1) then
begin
SetLength(aryLogIds, Length(aryLogIds) + 1);
aryLogIds[Length(aryLogIds) - 1] := qryLogs.FieldByName('Id').AsInteger;
end;
qryLogs.Next;
end;
qryLogs.Close;
LocalDatabaseConn.ReturnDBQuery(qryLogs);
for i := Low(aryLogIds) to High(aryLogIds) do
begin
strQueryInsertLogPanel := Format(strUpdateLog, [aryLogIds[i]]);
LocalDatabaseConn.ExecuteNonQuery(strQueryInsertLogPanel);
end;
sleep(StrToInt(Config.GetValue('LogUpdaterInterval')));
end;
LocalDatabaseConn.ReturnDBQuery(qryLogs);
end;
function LogWriter(LogRecord: _LOGRECORD): integer;
var
strCmdLogUpdate: string;
qryResult: TSQLQuery;
begin
strCmdLogUpdate := 'INSERT INTO LOG_Sistem (LogTipi, Mesaj, KullaniciId, Olusturuldu, Origin, Kod) '
+ 'VALUES (%d,' + #39 + '%s' + #39 + ', %d,' + #39 + '%s' + #39 + ', %d, %d)';
strCmdLogUpdate := Format(strCmdLogUpdate,
[integer(LogRecord.nLogType),
LogRecord.strMessage, LogRecord.nUserID,
FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', LogRecord.dtCreated),
Me.LokasyonId, 0]);
Result := RemoteDatabaseConn.ExecuteNonQuery(strCmdLogUpdate);
end;
function SystemLogger(p: Pointer): longint;
var
PingResult: RPingResult;
LogRecord: _LOGRECORD;
begin
while True do
begin
PingResult.Error := 0;
PingResult.PacketNumber := 0;
PingResult.RoundTripTime := 0;
PingResult.TTL := 0;
Ping(Config.GetValue('RemoteDatabaseIp'), PingResult);
if (PingResult.RoundTripTime <> 0) then
begin
if (nNoConnectionCounter > 1) then
begin
LogRecord.nLogType := integer(EnumLogType.CHECK_CONNECTION);
LogRecord.nUserID := -1;
LogRecord.dtCreated := Now;
LogRecord.strMessage := Format('%d dakika boyunca süren bağlantı kesintisi',
[(StrToInt(Config.GetValue('LogInterval')) div 60000)*nNoConnectionCounter]);
LogWriter(LogRecord);
nNoConnectionCounter:=0;
end;
LogRecord.nLogType := integer(EnumLogType.CHECK_CONNECTION);
LogRecord.nUserID := -1;
LogRecord.dtCreated := Now;
LogRecord.strMessage :=
Format('Cevap Süresi(ms):%d; TTL:%d; Hata Kodu:%d',
[PingResult.RoundTripTime, PingResult.TTL, PingResult.Error]);
LogWriter(LogRecord);
end
else
begin
inc(nNoConnectionCounter);
end;
Sleep(StrToInt(Config.GetValue('LogInterval')));
end;
end;
function GetLocationName(LocationId: integer): string;
var
strGetLocationName:string;
rows: TDataStoreArrayList;
begin
strGetLocationName:=Format('select LokasyonAdi from LOKASYON where LokasyonId=%d', [LocationId]);
rows := TDataStoreArrayList.Create;
if(RemoteDatabaseConn.ExecuteMultiRow(strGetLocationName, rows)) then
Result:=UTF8Encode(rows.GetItems(0).GetString('LokasyonAdi'))
else
Result:='';
FreeAndNil(rows);
end;
function AutoResetDevice(p: Pointer): longint;
var
stlResetPoints:TStringList;
i:integer;
wHour, wMin, wSec,wMSec:WORD;
dtTime:TDateTime;
begin
while(true) do
begin
stlResetPoints:=TStringList.Create;
stlResetPoints.Delimiter:=',';
stlResetPoints.DelimitedText:=Config.GetValue('ResetTime');
dtTime:=Now;
DecodeTime(dtTime, wHour, wMin, wSec, wMSec);
for i:=0 to stlResetPoints.Count -1 do
begin
if((wHour = StrToInt(stlResetPoints[i])) and (wMin= 0)) then SoftReset;
end;
sleep(30000);
end;
end;
function CheckConnection: boolean;
var
PingResult: RPingResult;
bolResult:Boolean;
begin
PingResult.Error := 0;
PingResult.PacketNumber := 0;
PingResult.RoundTripTime := 0;
PingResult.TTL := 0;
Ping(Config.GetValue('RemoteDatabaseIp'), PingResult);
Result:=(PingResult.RoundTripTime<>0);
end;
procedure CloseAll;
var
LogRecord: _LOGRECORD;
begin
bolStopDBUpdater := True;
bolStopLogUpdater := True;
bolNoTraceWatchDog := True;
LogRecord.dtCreated := Now;
LogRecord.nUserID := -1;
LogRecord.strMessage := 'Program Kapatıldı';
LogRecord.nLogType := integer(EnumLogType.PROGRAM_EXIT);
LogWriter(LogRecord);
WatchDogTimerRefresher.SayBye;
end;
function WacthdogTrace(p: pointer): longint;
begin
hWatchdogFile := WatchDogStart;
while True do
begin
while bolWatchDogManual do
begin
Sleep(10);
end;
WatchDogTouch(hWatchdogFile);
Sleep(10);
if bolNoTraceWatchDog then
begin
WatchDogKick(hWatchdogFile);
WatchDogClose(hWatchdogFile);
break;
end;
end;
end;
function InitializeApplication: boolean;
var
Success: boolean;
strRemoteDatabaseIp: WideString;
wRemoteDatabasePort: word;
strLocalDatabasePath: WideString;
recLogUpdate: _LOGRECORD;
strWatchDogTimerHost:string;
nWatchdogTimerPort:integer;
nWatchDogTimerInterval:integer;
begin
try
Me := _Lokasyon.Create;
Config := TIniFileHelper.IniFileHelper;
strRemoteDatabaseIp := Config.GetValue('RemoteDatabaseIp');
wRemoteDatabasePort := StrToInt(Config.GetValue('RemoteDatabasePort'));
strLocalDatabasePath := Config.GetValue('LocalDatabasePath');
Success := False;
RemoteDatabaseConn := RemoteDatabaseHelper.Create(strRemoteDatabaseIp,
wRemoteDatabasePort, Success);
Me.LokasyonId := StrToInt(Config.GetValue('LocationId'));
strLocationName:=GetLocationName(Me.LokasyonId);
LocalDatabaseConn := TDestapLocalDatabaseHelper.Create(strLocalDatabasePath);
//Threads starting
bolStopDBUpdater := False;
thDbUpdater := BeginThread(@Db_Updater);
bolStopLogUpdater := False;
thLogUploader := BeginThread(@Log_Updater);
thSystemLogger := BeginThread(@SystemLogger);
bolNoTraceWatchDog := False;
bolWatchDogManual := False;
thWatchdogTrace := BeginThread(@WacthdogTrace);
thAutoReset:=BeginThread(@AutoResetDevice);
strWatchDogTimerHost:=Config.GetValue('WatchDogTimerHost');
nWatchdogTimerPort:=StrToInt(Config.GetValue('WatchDogTimerPort'));
nWatchDogTimerInterval:=StrToInt(Config.GetValue('WatchDogTimerInterval'));
WatchDogTimerRefresher:=TWatchDogTimerRefresh.Create(true,strWatchDogTimerHost, nWatchdogTimerPort, nWatchDogTimerInterval);
WatchDogTimerRefresher.Start;
//Log: Program starting
recLogUpdate.nUserID := -1;
recLogUpdate.dtCreated := Now;
recLogUpdate.nLogType := integer(EnumLogType.PROGRAM_START);
recLogUpdate.strMessage := 'Program başlatılıyor';
LogWriter(recLogUpdate);
Result := True;
except
on E: Exception do
begin
ShowMessage(E.Message);
Result := False;
end;
end;
end;
end.
|
unit CreateAccountForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, UserClass;
type
TCreateAccount = class(TForm)
edtUsername: TEdit;
edtPassword: TEdit;
edtRepeatPassword: TEdit;
btnCreateAccount: TButton;
procedure btnCreateAccountClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
CreateAccount: TCreateAccount;
implementation
{$R *.dfm}
procedure TCreateAccount.btnCreateAccountClick(Sender: TObject);
var UserFile : TextFile; NewUser : TUser; UserAlreadyExists : Boolean; ReadInUser : String; UserPassCombo : TStringList;
begin
// New account username and password must be of right length
if (edtPassword.Text = edtRepeatPassword.Text) and (Length(edtUsername.Text) > 5)
and (Length(edtUsername.Text) < 16) and (Length(edtPassword.Text) > 5) and (Length(edtPassword.Text) < 16) then
begin
// User can only be created if does not exist already
UserAlreadyExists := false;
// Check each user in file to make sure not repeating if created
if FileExists('Users.AMF') then
begin
AssignFile(UserFile, 'Users.AMF');
Reset(UserFile);
UserPassCombo := TStringList.Create;
while not EoF(UserFile) do
begin
Readln(UserFile, ReadInUser);
ExtractStrings(['|'], [], PChar(ReadInUser), UserPassCombo);
// Compare new user username to read in username
if (edtUsername.Text = UserPassCombo[0]) then UserAlreadyExists := true;
end;
CloseFile(UserFile);
end;
if UserAlreadyExists then ShowMessage ('User already exists.')
// Create account
else
begin
NewUser := TUser.Create(edtUsername.Text, edtPassword.Text);
AssignFile(UserFile, 'Users.AMF');
if FileExists('Users.AMF') then Append(UserFile)
else Rewrite(UserFile);
Writeln(UserFile, NewUser.Username + '|' + NewUser.Password);
CloseFile(UserFile);
Close;
end;
end
// Cannot create account as passwords dont match
else ShowMessage ('Account not created. Username and password must be between 6-15 characters, and passwords must match.');
end;
// Make sure text boxes are blank when form is shown
procedure TCreateAccount.FormShow(Sender: TObject);
begin
edtUsername.Text := '';
edtPassword.Text := '';
edtRepeatPassword.Text := '';
end;
end.
|
//
// Created by the DataSnap proxy generator.
//
unit ClientFunctions;
interface
uses DBXCommon, DBXJSON, Classes, SysUtils, DB, SqlExpr, DBXDBReaders;
type
TDSServerModuleRFIDPanelClient = class
private
FDBXConnection: TDBXConnection;
FInstanceOwner: Boolean;
FGetJSONFTPConnCommand: TDBXCommand;
FechoCommand: TDBXCommand;
FGetSoldItemsCommand: TDBXCommand;
FGetOrderedItemsCommand: TDBXCommand;
FGetNameCommand: TDBXCommand;
FGetCreditCommand: TDBXCommand;
public
constructor Create(ADBXConnection: TDBXConnection); overload;
constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload;
destructor Destroy; override;
function GetJSONFTPConn: TJSONValue;
function echo(s: string): string;
function GetSoldItems(VIPID: string): string;
function GetOrderedItems(VIPID: string): string;
function GetName(VIPID: string): string;
function GetCredit(VIPID: string): string;
end;
implementation
function TDSServerModuleRFIDPanelClient.GetJSONFTPConn: TJSONValue;
begin
if FGetJSONFTPConnCommand = nil then
begin
FGetJSONFTPConnCommand := FDBXConnection.CreateCommand;
FGetJSONFTPConnCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FGetJSONFTPConnCommand.Text := 'TDSServerModuleRFIDPanel.GetJSONFTPConn';
FGetJSONFTPConnCommand.Prepare;
end;
FGetJSONFTPConnCommand.ExecuteUpdate;
Result := TJSONValue(FGetJSONFTPConnCommand.Parameters[0].Value.GetJSONValue(FInstanceOwner));
end;
function TDSServerModuleRFIDPanelClient.echo(s: string): string;
begin
if FechoCommand = nil then
begin
FechoCommand := FDBXConnection.CreateCommand;
FechoCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FechoCommand.Text := 'TDSServerModuleRFIDPanel.echo';
FechoCommand.Prepare;
end;
FechoCommand.Parameters[0].Value.SetWideString(s);
FechoCommand.ExecuteUpdate;
Result := FechoCommand.Parameters[1].Value.GetWideString;
end;
function TDSServerModuleRFIDPanelClient.GetSoldItems(VIPID: string): string;
begin
if FGetSoldItemsCommand = nil then
begin
FGetSoldItemsCommand := FDBXConnection.CreateCommand;
FGetSoldItemsCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FGetSoldItemsCommand.Text := 'TDSServerModuleRFIDPanel.GetSoldItems';
FGetSoldItemsCommand.Prepare;
end;
FGetSoldItemsCommand.Parameters[0].Value.SetWideString(VIPID);
FGetSoldItemsCommand.ExecuteUpdate;
Result := FGetSoldItemsCommand.Parameters[1].Value.GetWideString;
end;
function TDSServerModuleRFIDPanelClient.GetOrderedItems(VIPID: string): string;
begin
if FGetOrderedItemsCommand = nil then
begin
FGetOrderedItemsCommand := FDBXConnection.CreateCommand;
FGetOrderedItemsCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FGetOrderedItemsCommand.Text := 'TDSServerModuleRFIDPanel.GetOrderedItems';
FGetOrderedItemsCommand.Prepare;
end;
FGetOrderedItemsCommand.Parameters[0].Value.SetWideString(VIPID);
FGetOrderedItemsCommand.ExecuteUpdate;
Result := FGetOrderedItemsCommand.Parameters[1].Value.GetWideString;
end;
function TDSServerModuleRFIDPanelClient.GetName(VIPID: string): string;
begin
if FGetNameCommand = nil then
begin
FGetNameCommand := FDBXConnection.CreateCommand;
FGetNameCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FGetNameCommand.Text := 'TDSServerModuleRFIDPanel.GetName';
FGetNameCommand.Prepare;
end;
FGetNameCommand.Parameters[0].Value.SetWideString(VIPID);
FGetNameCommand.ExecuteUpdate;
Result := FGetNameCommand.Parameters[1].Value.GetWideString;
end;
function TDSServerModuleRFIDPanelClient.GetCredit(VIPID: string): string;
begin
if FGetCreditCommand = nil then
begin
FGetCreditCommand := FDBXConnection.CreateCommand;
FGetCreditCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FGetCreditCommand.Text := 'TDSServerModuleRFIDPanel.GetCredit';
FGetCreditCommand.Prepare;
end;
FGetCreditCommand.Parameters[0].Value.SetWideString(VIPID);
FGetCreditCommand.ExecuteUpdate;
Result := FGetCreditCommand.Parameters[1].Value.GetWideString;
end;
constructor TDSServerModuleRFIDPanelClient.Create(ADBXConnection: TDBXConnection);
begin
inherited Create;
if ADBXConnection = nil then
raise EInvalidOperation.Create('Connection cannot be nil. Make sure the connection has been opened.');
FDBXConnection := ADBXConnection;
FInstanceOwner := True;
end;
constructor TDSServerModuleRFIDPanelClient.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean);
begin
inherited Create;
if ADBXConnection = nil then
raise EInvalidOperation.Create('Connection cannot be nil. Make sure the connection has been opened.');
FDBXConnection := ADBXConnection;
FInstanceOwner := AInstanceOwner;
end;
destructor TDSServerModuleRFIDPanelClient.Destroy;
begin
FreeAndNil(FGetJSONFTPConnCommand);
FreeAndNil(FechoCommand);
FreeAndNil(FGetSoldItemsCommand);
FreeAndNil(FGetOrderedItemsCommand);
FreeAndNil(FGetNameCommand);
FreeAndNil(FGetCreditCommand);
inherited;
end;
end.
|
{ ********************************* }
{ Модуль главного окна программы }
{ Copyright (C) 2019 }
{ Author: Daniyar Khayitov }
{ Date: 23.03.2009 }
{ ********************************* }
unit uAbout;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Imaging.jpeg, Vcl.ExtCtrls,
Vcl.StdCtrls, ShellApi, Vcl.Imaging.pngimage;
type
TFileVersionInfo = record
FileType, CompanyName, FileDescription, FileVersion, InternalName,
LegalCopyRight, LegalTradeMarks, OriginalFileName, ProductName,
ProductVersion, Comments, SpecialBuildStr, PrivateBuildStr,
FileFunction: string;
DebugBuild, PreRelease, SpecialBuild, PrivateBuild, Patched,
InfoInferred: Boolean;
end;
type
TAboutF = class(TForm)
Image1: TImage;
Panel1: TPanel;
ListBox1: TListBox;
btnOK: TButton;
Panel2: TPanel;
Image2: TImage;
procedure btnOkClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
AboutF: TAboutF;
implementation
{$R *.dfm}
procedure TAboutF.btnOkClick(Sender: TObject);
begin
Close;
end;
function FileVersionInfo(const sAppNamePath: TFileName): TFileVersionInfo;
var
rSHFI: TSHFileInfo;
iRet: Integer;
VerSize: Integer;
VerBuf: PChar;
VerBufValue: Pointer;
VerHandle: Cardinal;
VerBufLen: Cardinal;
VerKey: string;
FixedFileInfo: PVSFixedFileInfo;
function GetFileSubType(FixedFileInfo: PVSFixedFileInfo): string;
begin
case FixedFileInfo.dwFileType of
VFT_UNKNOWN:
Result := 'Unknown';
VFT_APP:
Result := 'Application';
VFT_DLL:
Result := 'DLL';
VFT_STATIC_LIB:
Result := 'Static-link Library';
VFT_DRV:
case FixedFileInfo.dwFileSubtype of
VFT2_UNKNOWN:
Result := 'Unknown Driver';
VFT2_DRV_COMM:
Result := 'Communications Driver';
VFT2_DRV_PRINTER:
Result := 'Printer Driver';
VFT2_DRV_KEYBOARD:
Result := 'Keyboard Driver';
VFT2_DRV_LANGUAGE:
Result := 'Language Driver';
VFT2_DRV_DISPLAY:
Result := 'Display Driver';
VFT2_DRV_MOUSE:
Result := 'Mouse Driver';
VFT2_DRV_NETWORK:
Result := 'Network Driver';
VFT2_DRV_SYSTEM:
Result := 'System Driver';
VFT2_DRV_INSTALLABLE:
Result := 'InstallableDriver';
VFT2_DRV_SOUND:
Result := 'Sound Driver';
end;
VFT_FONT:
case FixedFileInfo.dwFileSubtype of
VFT2_UNKNOWN:
Result := 'Unknown Font';
VFT2_FONT_RASTER:
Result := 'Raster Font';
VFT2_FONT_VECTOR:
Result := 'Vector Font';
VFT2_FONT_TRUETYPE:
Result := 'Truetype Font';
else
;
end;
VFT_VXD:
Result := 'Virtual Defice Identifier = ' +
IntToHex(FixedFileInfo.dwFileSubtype, 8);
end;
end;
function HasdwFileFlags(FixedFileInfo: PVSFixedFileInfo; Flag: Word): Boolean;
begin
Result := (FixedFileInfo.dwFileFlagsMask and FixedFileInfo.dwFileFlags and
Flag) = Flag;
end;
function GetFixedFileInfo: PVSFixedFileInfo;
begin
if not VerQueryValue(VerBuf, '', Pointer(Result), VerBufLen) then
Result := nil
end;
function GetInfo(const aKey: string): string;
begin
Result := '';
VerKey := Format('\StringFileInfo\%.4x%.4x\%s',
[LoWord(Integer(VerBufValue^)), HiWord(Integer(VerBufValue^)), aKey]);
if VerQueryValue(VerBuf, PChar(VerKey), VerBufValue, VerBufLen) then
Result := PChar(VerBufValue);
end;
function QueryValue(const aValue: string): string;
begin
Result := '';
// obtain version information about the specified file
if GetFileVersionInfo(PChar(sAppNamePath), VerHandle, VerSize, VerBuf) and
// return selected version information
VerQueryValue(VerBuf, '\VarFileInfo\Translation', VerBufValue, VerBufLen)
then
Result := GetInfo(aValue);
end;
begin
// Initialize the Result
with Result do
begin
FileType := '';
CompanyName := '';
FileDescription := '';
FileVersion := '';
InternalName := '';
LegalCopyRight := '';
LegalTradeMarks := '';
OriginalFileName := '';
ProductName := '';
ProductVersion := '';
Comments := '';
SpecialBuildStr := '';
PrivateBuildStr := '';
FileFunction := '';
DebugBuild := False;
Patched := False;
PreRelease := False;
SpecialBuild := False;
PrivateBuild := False;
InfoInferred := False;
end;
// Get the file type
if SHGetFileInfo(PChar(sAppNamePath), 0, rSHFI, SizeOf(rSHFI),
SHGFI_TYPENAME) <> 0 then
begin
Result.FileType := rSHFI.szTypeName;
end;
iRet := SHGetFileInfo(PChar(sAppNamePath), 0, rSHFI, SizeOf(rSHFI),
SHGFI_EXETYPE);
if iRet <> 0 then
begin
// determine whether the OS can obtain version information
VerSize := GetFileVersionInfoSize(PChar(sAppNamePath), VerHandle);
if VerSize > 0 then
begin
VerBuf := AllocMem(VerSize);
try
with Result do
begin
CompanyName := QueryValue('CompanyName');
FileDescription := QueryValue('FileDescription');
FileVersion := QueryValue('FileVersion');
InternalName := QueryValue('InternalName');
LegalCopyRight := QueryValue('LegalCopyRight');
LegalTradeMarks := QueryValue('LegalTradeMarks');
OriginalFileName := QueryValue('OriginalFileName');
ProductName := QueryValue('ProductName');
ProductVersion := QueryValue('ProductVersion');
Comments := QueryValue('Comments');
SpecialBuildStr := QueryValue('SpecialBuild');
PrivateBuildStr := QueryValue('PrivateBuild');
// Fill the VS_FIXEDFILEINFO structure
FixedFileInfo := GetFixedFileInfo;
DebugBuild := HasdwFileFlags(FixedFileInfo, VS_FF_DEBUG);
PreRelease := HasdwFileFlags(FixedFileInfo, VS_FF_PRERELEASE);
PrivateBuild := HasdwFileFlags(FixedFileInfo, VS_FF_PRIVATEBUILD);
SpecialBuild := HasdwFileFlags(FixedFileInfo, VS_FF_SPECIALBUILD);
Patched := HasdwFileFlags(FixedFileInfo, VS_FF_PATCHED);
InfoInferred := HasdwFileFlags(FixedFileInfo, VS_FF_INFOINFERRED);
FileFunction := GetFileSubType(FixedFileInfo);
end;
finally
FreeMem(VerBuf, VerSize);
end
end;
end
end;
procedure TAboutF.FormCreate(Sender: TObject);
var
FvI: TFileVersionInfo;
begin
FvI := FileVersionInfo(Application.ExeName);
ListBox1.TabWidth := 1;
ListBox1.Items.Add(FvI.ProductName);
ListBox1.Items.Add('Версия ' + FvI.FileVersion);
ListBox1.Items.Add(FvI.Comments);
ListBox1.Items.Add('© 2018 ' + FvI.CompanyName);
ListBox1.Items.Add('Автор: Хайитов Д.Д.');
if FvI.DebugBuild = True then
ListBox1.Items.Add('Отладочная версия: ' + 'Да')
else
ListBox1.Items.Add('Отладочная версия: ' + 'Нет');
end;
end.
|
{$INCLUDE switches}
unit NatStat;
interface
uses
Protocol,ClientTools,Term,ScreenTools,BaseWin,
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
ButtonBase, ButtonB, ButtonC, Menus, EOTButton;
type
PEnemyReport=^TEnemyReport;
TNatStatDlg = class(TBufferedDrawDlg)
ToggleBtn: TButtonB;
CloseBtn: TButtonB;
Popup: TPopupMenu;
ScrollUpBtn: TButtonC;
ScrollDownBtn: TButtonC;
ContactBtn: TEOTButton;
TellAIBtn: TButtonC;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure CloseBtnClick(Sender: TObject);
procedure DialogBtnClick(Sender: TObject);
procedure ToggleBtnClick(Sender: TObject);
procedure PlayerClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: word;
Shift: TShiftState);
procedure FormDestroy(Sender: TObject);
procedure ScrollUpBtnClick(Sender: TObject);
procedure ScrollDownBtnClick(Sender: TObject);
procedure TellAIBtnClick(Sender: TObject);
public
procedure CheckAge;
procedure ShowNewContent(NewMode: integer; p: integer = -1);
procedure EcoChange;
protected
procedure OffscreenPaint; override;
private
pView, AgePrepared, LinesDown: integer;
SelfReport,CurrentReport: PEnemyReport;
ShowContact,ContactEnabled: boolean;
Back, Template: TBitmap;
ReportText: TStringList;
procedure GenerateReportText;
end;
var
NatStatDlg: TNatStatDlg;
implementation
{$R *.DFM}
uses
Diagram,Select,Messg,MessgEx, Help,Tribes,Directories;
const
xIcon=326; yIcon=49;
xAttrib=96; yAttrib=40;
xRelation=16; yRelation=110;
PaperShade=3;
ReportLines=12;
LineSpacing=22;
xReport=24; yReport=165; wReport=352; hReport=ReportLines*LineSpacing;
procedure TNatStatDlg.FormCreate(Sender: TObject);
begin
inherited;
AgePrepared:=-2;
GetMem(SelfReport,SizeOf(TEnemyReport)-2*(INFIN+1));
ReportText:=TStringList.Create;
InitButtons();
ContactBtn.Template:=Templates;
HelpContext:='DIPLOMACY';
ToggleBtn.Hint:=Phrases.Lookup('BTN_SELECT');
ContactBtn.Hint:=Phrases.Lookup('BTN_DIALOG');
Back:=TBitmap.Create;
Back.PixelFormat:=pf24bit;
Back.Width:=ClientWidth; Back.Height:=ClientHeight;
Template:=TBitmap.Create;
LoadGraphicFile(Template, HomeDir+'Graphics\Nation', gfNoGamma);
Template.PixelFormat:=pf8bit;
end;
procedure TNatStatDlg.FormDestroy(Sender: TObject);
begin
ReportText.Free;
FreeMem(SelfReport);
Template.Free;
Back.Free;
end;
procedure TNatStatDlg.CheckAge;
begin
if MainTextureAge<>AgePrepared then
begin
AgePrepared:=MainTextureAge;
bitblt(Back.Canvas.Handle,0,0,ClientWidth,ClientHeight,
MainTexture.Image.Canvas.Handle,(wMainTexture-ClientWidth) div 2,
(hMainTexture-ClientHeight) div 2,SRCCOPY);
ImageOp_B(Back,Template,0,0,0,0,ClientWidth,ClientHeight);
end
end;
procedure TNatStatDlg.FormShow(Sender: TObject);
begin
if pView=me then
begin
SelfReport.TurnOfCivilReport:=MyRO.Turn;
SelfReport.TurnOfMilReport:=MyRO.Turn;
move(MyRO.Treaty, SelfReport.Treaty, sizeof(SelfReport.Treaty));
SelfReport.Government:=MyRO.Government;
SelfReport.Money:=MyRO.Money;
CurrentReport:=pointer(SelfReport);
end
else CurrentReport:=pointer(MyRO.EnemyReport[pView]);
if CurrentReport.TurnOfCivilReport>=0 then
GenerateReportText;
ShowContact:= (pView<>me) and (not supervising or (me<>0));
ContactEnabled:= ShowContact and not supervising
and (1 shl pView and MyRO.Alive<>0);
ContactBtn.Visible:=ContactEnabled and (MyRO.Happened and phGameEnd=0)
and (ClientMode<scContact);
ScrollUpBtn.Visible:=(CurrentReport.TurnOfCivilReport>=0)
and (ReportText.Count>ReportLines);
ScrollDownBtn.Visible:=(CurrentReport.TurnOfCivilReport>=0)
and (ReportText.Count>ReportLines);
if OptionChecked and (1 shl soTellAI)<>0 then
TellAIBtn.ButtonIndex:=3
else TellAIBtn.ButtonIndex:=2;
Caption:=Tribe[pView].TPhrase('TITLE_NATION');
LinesDown:=0;
OffscreenPaint;
end;
procedure TNatStatDlg.ShowNewContent(NewMode,p: integer);
begin
if p<0 then
if ClientMode>=scContact then
pView:=DipMem[me].pContact
else
begin
pView:=0;
while (pView<nPl) and ((MyRO.Treaty[pView]<trNone)
or (1 shl pView and MyRO.Alive=0)) do
inc(pView);
if pView>=nPl then pView:=me;
end
else pView:=p;
inherited ShowNewContent(NewMode);
end;
procedure TNatStatDlg.PlayerClick(Sender: TObject);
begin
ShowNewContent(FWindowMode, TComponent(Sender).Tag);
end;
procedure TNatStatDlg.GenerateReportText;
var
List: ^TChart;
function StatText(no: integer): string;
var
i: integer;
begin
if (CurrentReport.TurnOfCivilReport>=0) and (Server(sGetChart+no shl 4,me,pView,List^)>=rExecuted) then
begin
i:=List[CurrentReport.TurnOfCivilReport];
case no of
stPop: result:=Format(Phrases.Lookup('FRSTATPOP'),[i]);
stTerritory: result:=Format(Phrases.Lookup('FRSTATTER'),[i]);
stScience: result:=Format(Phrases.Lookup('FRSTATTECH'),[i div nAdv]);
stExplore: result:=Format(Phrases.Lookup('FRSTATEXP'),[i*100 div (G.lx*G.ly)]);
end;
end
end;
var
p1,Treaty: integer;
s: string;
HasContact,ExtinctPart: boolean;
begin
GetMem(List,4*(MyRO.Turn+2));
ReportText.Clear;
ReportText.Add('');
if (MyRO.Turn-CurrentReport.TurnOfCivilReport>1)
and (1 shl pView and MyRO.Alive<>0) then
begin
s:=Format(Phrases.Lookup('FROLDCIVILREP'),
[TurnToString(CurrentReport.TurnOfCivilReport)]);
ReportText.Add('C'+s);
ReportText.Add('');
end;
if (1 shl pView and MyRO.Alive<>0) then
begin
ReportText.Add('M'+Format(Phrases.Lookup('FRTREASURY'),[CurrentReport.Money]));
ReportText.Add('P'+StatText(stPop));
ReportText.Add('T'+StatText(stTerritory));
end;
ReportText.Add('S'+StatText(stScience));
ReportText.Add('E'+StatText(stExplore));
HasContact:=false;
for p1:=0 to nPl-1 do
if (p1<>me) and (CurrentReport.Treaty[p1]>trNoContact) then
HasContact:=true;
if HasContact then
begin
ReportText.Add('');
ReportText.Add(' '+Phrases.Lookup('FRRELATIONS'));
for ExtinctPart:=false to true do
for Treaty:=trAlliance downto trNone do
for p1:=0 to nPl-1 do
if (p1<>me) and (CurrentReport.Treaty[p1]=Treaty)
and ((1 shl p1 and MyRO.Alive=0)=ExtinctPart) then
begin
s:=Tribe[p1].TString(Phrases.Lookup('HAVETREATY', Treaty));
if ExtinctPart then s:='('+s+')';
ReportText.Add(char(48+Treaty)+s);
end;
end;
ReportText.Add('');
FreeMem(List);
end;
procedure TNatStatDlg.OffscreenPaint;
var
i, y: integer;
s: string;
ps: pchar;
Extinct: boolean;
begin
inherited;
Extinct:= 1 shl pView and MyRO.Alive=0;
bitblt(offscreen.canvas.handle,0,0,ClientWidth,ClientHeight,Back.Canvas.handle,0,0,SRCCOPY);
offscreen.Canvas.Font.Assign(UniFont[ftCaption]);
RisedTextout(offscreen.Canvas,40{(ClientWidth-BiColorTextWidth(offscreen.canvas,caption)) div 2},7,Caption);
offscreen.Canvas.Font.Assign(UniFont[ftNormal]);
with offscreen do
begin
// show leader picture
Tribe[pView].InitAge(GetAge(pView));
if Tribe[pView].faceHGr>=0 then
begin
Dump(offscreen,Tribe[pView].faceHGr,18,yIcon-4,64,48,
1+Tribe[pView].facepix mod 10 *65,1+Tribe[pView].facepix div 10 *49);
frame(offscreen.Canvas,18-1,yIcon-4-1,18+64,yIcon-4+48,$000000,$000000);
end;
if (pView=me) or not Extinct then
LoweredTextOut(Canvas,-1,MainTexture,xAttrib,yAttrib,
Phrases.Lookup('GOVERNMENT',CurrentReport.Government)+Phrases.Lookup('FRAND'));
if pView=me then
begin
LoweredTextOut(Canvas,-1,MainTexture,xAttrib,yAttrib+19,
Phrases.Lookup('CREDIBILITY',RoughCredibility(MyRO.Credibility)));
LoweredTextOut(Canvas,-1,MainTexture,xAttrib,yAttrib+38,
Format(Phrases.Lookup('FRCREDIBILITY'),[MyRO.Credibility]));
end
else
begin
if Extinct then
begin
LoweredTextOut(Canvas,-1,MainTexture,xAttrib,yAttrib+9,
Phrases.Lookup('FREXTINCT'));
LoweredTextOut(Canvas,-1,MainTexture,xAttrib,yAttrib+28,
TurnToString(CurrentReport.TurnOfCivilReport))
end
else
begin
LoweredTextOut(Canvas,-1,MainTexture,xAttrib,yAttrib+19,
Phrases.Lookup('CREDIBILITY',RoughCredibility(CurrentReport.Credibility)));
LoweredTextOut(Canvas,-1,MainTexture,xAttrib,yAttrib+38,
Format(Phrases.Lookup('FRCREDIBILITY'),[CurrentReport.Credibility]));
end;
if MyRO.Treaty[pView]=trNoContact then
begin
s:=Phrases.Lookup('FRNOCONTACT');
LoweredTextOut(Canvas,-1,MainTexture,
(ClientWidth-BiColorTextWidth(canvas,s)) div 2,yRelation+9,s)
end
else if ShowContact then
begin
LoweredTextOut(Canvas,-1,MainTexture,xRelation,yRelation,
Phrases.Lookup('FRTREATY'));
LoweredTextOut(Canvas,-1,MainTexture,ClientWidth div 2,yRelation,
Phrases.Lookup('TREATY',MyRO.Treaty[pView]));
if CurrentReport.TurnOfContact<0 then
LoweredTextOut(Canvas,-1,MainTexture,ClientWidth div 2,yRelation+19,
Phrases.Lookup('FRNOVISIT'))
else
begin
LoweredTextOut(Canvas,-1,MainTexture,xRelation,yRelation+19,
Phrases.Lookup('FRLASTCONTACT'));
if CurrentReport.TurnOfContact>=0 then
LoweredTextOut(Canvas,-1,MainTexture,ClientWidth div 2,yRelation+19,
TurnToString(CurrentReport.TurnOfContact));
end;
end;
if Extinct then
FrameImage(canvas,BigImp,xIcon,yIcon,xSizeBig,ySizeBig,0,200)
{else if CurrentReport.Government=gAnarchy then
FrameImage(canvas,BigImp,xIcon,yIcon,xSizeBig,ySizeBig,112,400,
ContactEnabled and (MyRO.Happened and phGameEnd=0) and (ClientMode<scContact))
else
FrameImage(canvas,BigImp,xIcon,yIcon,xSizeBig,ySizeBig,
56*(CurrentReport.Government-1),40,
ContactEnabled and (MyRO.Happened and phGameEnd=0) and (ClientMode<scContact))};
end;
if CurrentReport.TurnOfCivilReport>=0 then
begin // print state report
FillSeamless(Canvas, xReport, yReport, wReport, hReport, 0, 0, Paper);
with canvas do
begin
Brush.Color:=MainTexture.clBevelShade;
FillRect(Rect(xReport+wReport, yReport+PaperShade,
xReport+wReport+PaperShade, yReport+hReport+PaperShade));
FillRect(Rect(xReport+PaperShade, yReport+hReport,
xReport+wReport+PaperShade, yReport+hReport+PaperShade));
Brush.Style:=bsClear;
end;
y:=0;
for i:=0 to ReportText.Count-1 do
begin
if (i>=LinesDown) and (i<LinesDown+ReportLines) then
begin
s:=ReportText[i];
if s<>'' then
begin
// LineType:=s[1];
delete(s,1,1);
BiColorTextOut(canvas,Colors.Canvas.Pixels[clkMisc,cliPaperText],
$7F007F,xReport+8,yReport+LineSpacing*y,s);
end;
inc(y);
end
end;
end
else
begin
s:=Phrases.Lookup('FRNOCIVILREP');
RisedTextOut(Canvas,(ClientWidth-BiColorTextWidth(Canvas,s)) div 2,
yReport+hReport div 2-10,s);
end;
if OptionChecked and (1 shl soTellAI)<>0 then
begin
Server(sGetAIInfo,me,pView,ps);
LoweredTextOut(Canvas,-1,MainTexture,42,445,ps);
end
else LoweredTextOut(Canvas,-2,MainTexture,42,445,Phrases2.Lookup('MENU_TELLAI'));
end;
ContactBtn.SetBack(Offscreen.Canvas,ContactBtn.Left,ContactBtn.Top);
MarkUsedOffscreen(ClientWidth,ClientHeight);
end; {OffscreenPaint}
procedure TNatStatDlg.CloseBtnClick(Sender: TObject);
begin
Close
end;
procedure TNatStatDlg.DialogBtnClick(Sender: TObject);
var
ContactResult: integer;
begin
ContactResult:=MainScreen.DipCall(scContact+pView shl 4);
if ContactResult<rExecuted then
begin
if ContactResult=eColdWar then
SoundMessage(Phrases.Lookup('FRCOLDWAR'),'MSG_DEFAULT')
else if MyRO.Government=gAnarchy then
SoundMessage(Tribe[me].TPhrase('FRMYANARCHY'),'MSG_DEFAULT')
else if ContactResult=eAnarchy then
if MyRO.Treaty[pView]>=trPeace then
begin
if MainScreen.ContactRefused(pView, 'FRANARCHY') then
SmartUpdateContent
end
else SoundMessage(Tribe[pView].TPhrase('FRANARCHY'),'MSG_DEFAULT');
end
else Close
end;
procedure TNatStatDlg.ToggleBtnClick(Sender: TObject);
var
p1,StartCount: integer;
m: TMenuItem;
ExtinctPart: boolean;
begin
EmptyMenu(Popup.Items);
// own nation
if G.Difficulty[me]<>0 then
begin
m:=TMenuItem.Create(Popup);
m.RadioItem:=true;
m.Caption:=Tribe[me].TPhrase('TITLE_NATION');
m.Tag:=me;
m.OnClick:=PlayerClick;
if me=pView then m.Checked:=true;
Popup.Items.Add(m);
end;
// foreign nations
for ExtinctPart:=false to true do
begin
StartCount:=Popup.Items.Count;
for p1:=0 to nPl-1 do
if ExtinctPart and (G.Difficulty[p1]>0) and (1 shl p1 and MyRO.Alive=0)
or not ExtinctPart and (1 shl p1 and MyRO.Alive<>0)
and (MyRO.Treaty[p1]>=trNone) then
begin
m:=TMenuItem.Create(Popup);
m.RadioItem:=true;
m.Caption:=Tribe[p1].TPhrase('TITLE_NATION');
if ExtinctPart then
m.Caption:='('+m.Caption+')';
m.Tag:=p1;
m.OnClick:=PlayerClick;
if p1=pView then m.Checked:=true;
Popup.Items.Add(m);
end;
if (StartCount>0) and (Popup.Items.Count>StartCount) then
begin //seperator
m:=TMenuItem.Create(Popup);
m.Caption:='-';
Popup.Items.Insert(StartCount,m);
end;
end;
Popup.Popup(Left+ToggleBtn.Left, Top+ToggleBtn.Top+ToggleBtn.Height);
end;
procedure TNatStatDlg.FormKeyDown(Sender: TObject; var Key: word;
Shift: TShiftState);
var
i: integer;
begin
if Key=VK_F9 then // my key
begin // toggle nation
i:=0;
repeat
pView:=(pView+1) mod nPl;
inc(i);
until (i>=nPl)
or (1 shl pView and MyRO.Alive<>0) and (MyRO.Treaty[pView]>=trNone);
if i>=nPl then pView:=me;
Tag:=pView;
PlayerClick(self); // no, this is not nice
end
else inherited
end;
procedure TNatStatDlg.EcoChange;
begin
if Visible and (pView=me) then
begin
SelfReport.Government:=MyRO.Government;
SelfReport.Money:=MyRO.Money;
SmartUpdateContent
end
end;
procedure TNatStatDlg.ScrollUpBtnClick(Sender: TObject);
begin
if LinesDown>0 then
begin
dec(LinesDown);
SmartUpdateContent;
end
end;
procedure TNatStatDlg.ScrollDownBtnClick(Sender: TObject);
begin
if LinesDown+ReportLines<ReportText.Count then
begin
inc(LinesDown);
SmartUpdateContent;
end
end;
procedure TNatStatDlg.TellAIBtnClick(Sender: TObject);
begin
OptionChecked:=OptionChecked xor (1 shl soTellAI);
if OptionChecked and (1 shl soTellAI)<>0 then
TellAIBtn.ButtonIndex:=3
else TellAIBtn.ButtonIndex:=2;
SmartUpdateContent
end;
end.
|
unit IconPanel;
interface
uses Windows, WNineSlicesPanel, Classes, WFileIcon, WImage, Logger, Contnrs, Controls,
Types, WComponent, ExtCtrls, Forms, SysUtils, Graphics, MathUtils, Imaging,
ShellAPI, WImageButton, Menus, User, StringUtils, EditFolderItemUnit, SystemUtils,
IconToolTipUnit;
type
TComponentDragData = record
Component: TWComponent;
Timer: TTimer;
MouseDownLoc: TPoint;
Started: Boolean;
StartIconLoc: TPoint;
IconForm: TForm;
InsertionCursor: TWImage;
end;
TIconPanel = class(TWNineSlicesPanel)
private
pComponents: TObjectList;
pIconSize: Word;
pIconDragData: TComponentDragData;
pTooltipForm: TIconTooltipForm;
pBrowseButton: TWImageButton;
pLastVisibleIconIndex: Integer;
function FolderItemToComponent(const folderItem:TFolderItem): TWComponent;
function CreateFormPopupMenu():TPopupMenu;
procedure Icon_MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure Icon_MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure IconDragData_timer(Sender: TObject);
procedure IconForm_Paint(Sender: TObject);
procedure MenuItem_Click_NewShortcut(Sender: TObject);
procedure MenuItem_Click_NewSeparator(Sender: TObject);
procedure MenuItem_Click_Delete(Sender: TObject);
procedure MenuItem_Click_Properties(Sender: TObject);
procedure MenuItem_Click_AddItToQuickLaunch(Sender: TObject);
procedure UpdateFolderItemsOrder();
function GetInsertionIndexAtPoint(const aPoint: TPoint): Integer;
procedure Icon_Click(sender: TObject);
procedure Icon_MouseEnter(sender: TObject);
procedure Icon_MouseExit(sender: TObject);
procedure Self_MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
function GetComponentByID(const componentID: Integer): TWComponent;
procedure BrowseButton_Click(Sender: TObject);
procedure BrowseButtonPopupMenu_Click(Sender: TObject);
procedure FitToContent;
public
constructor Create(AOwner: TComponent); override;
procedure LoadFolderItems();
procedure UpdateLayout();
end;
implementation
uses Main;
constructor TIconPanel.Create(AOwner: TComponent);
begin
inherited;
pLastVisibleIconIndex := -1;
pIconSize := 40;
ImagePathPrefix := TMain.Instance.FilePaths.SkinDirectory + '\BarInnerPanel';
pComponents := TObjectList.Create();
pComponents.OwnsObjects := false;
MinWidth := pIconSize + TMain.Instance.Style.barInnerPanel.paddingH;
MinHeight := pIconSize + TMain.Instance.Style.barInnerPanel.paddingV;
self.OnMouseDown := Self_MouseDown;
end;
procedure TIconPanel.BrowseButton_Click(Sender: TObject);
var pPopupMenu: TPopupMenu;
menuItem: TMenuItem;
i: Integer;
folderItem: TFolderItem;
component: TWComponent;
mouse: TMouse;
menuItemBitmap: TBitmap;
begin
pPopupMenu := TPopupMenu.Create(self);
for i := pLastVisibleIconIndex + 1 to pComponents.Count - 1 do begin
if i >= pComponents.Count then break;
component := TWComponent(pComponents[i]);
folderItem := TMain.Instance.User.GetFolderItemByID(component.Tag);
menuItem := TMenuItem.Create(self);
if folderItem.IsSeparator then begin
menuItem.Caption := '-';
menuItem.Enabled := false;
end else begin
menuItem.Caption := folderItem.Name;
menuItem.Tag := folderItem.ID;
if folderItem.SmallIcon <> nil then begin
menuItemBitmap := TBitmap.Create();
menuItemBitmap.Width := 16;
menuItemBitmap.Height := 16;
menuItemBitmap.Canvas.Draw(0, 0, folderItem.SmallIcon);
menuItem.OnClick := BrowseButtonPopupMenu_Click;
menuItem.Bitmap := menuItemBitmap;
end;
end;
pPopupMenu.Items.Add(menuItem);
end;
mouse := TMouse.Create();
pPopupMenu.Popup(mouse.CursorPos.X, mouse.CursorPos.Y);
end;
procedure TIconPanel.BrowseButtonPopupMenu_Click(Sender: TObject);
var folderItem: TFolderItem;
begin
folderItem := TMain.Instance.User.GetFolderItemByID((Sender as TMenuItem).Tag);
folderItem.Launch();
end;
function TIconPanel.GetComponentByID(const componentID: Integer): TWComponent;
var i: Integer;
begin
for i := 0 to pComponents.Count do begin
if TWComponent(pComponents[i]).ID = componentID then begin
result := TWComponent(pComponents[i]);
Exit;
end;
end;
result := nil;
end;
procedure TIconPanel.Self_MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
self.PopupMenu := CreateFormPopupMenu();
end;
function TIconPanel.CreateFormPopupMenu;
var menuItem: TMenuItem;
begin
result := TPopupMenu.Create(self);
menuItem := TMenuItem.Create(result);
menuItem.Caption := TMain.Instance.Loc.GetString('IconPanel.PopupMenu.NewShortcut');
menuItem.OnClick := MenuItem_Click_NewShortcut;
result.Items.Add(menuItem);
// menuItem := TMenuItem.Create(result);
// menuItem.Caption := TMain.Instance.Loc.GetString('IconPanel.PopupMenu.NewSeparator');
// menuItem.OnClick := MenuItem_Click_NewSeparator;
// result.Items.Add(menuItem);
end;
procedure TIconPanel.MenuItem_Click_NewShortcut;
var folderItem: TFolderItem;
component: TWComponent;
filePath: String;
begin
filePath := '';
if OpenSaveFileDialog(Application.Handle, '', TMain.Instance.Loc.GetString('Global.OpenDialog.AllFiles') + '|*.*', '', TMain.Instance.Loc.GetString('IconPanel.NewShorcut.OpenDialog'), filePath, true) then begin
folderItem := TFolderItem.Create();
folderItem.FilePath := TFolderItem.ConvertToRelativePath(filePath);
folderItem.AutoSetName();
TMain.Instance.User.AddFolderItem(folderItem);
component := FolderItemToComponent(folderItem);
AddChild(component);
pComponents.Add(TObject(component));
UpdateLayout();
end;
end;
procedure TIconPanel.MenuItem_Click_NewSeparator;
var folderItem: TFolderItem;
component: TWComponent;
begin
folderItem := TFolderItem.Create();
folderItem.IsSeparator := true;
TMain.Instance.User.AddFolderItem(folderItem);
component := FolderItemToComponent(folderItem);
AddChild(component);
pComponents.Add(TObject(component));
UpdateLayout();
end;
procedure TIconPanel.MenuItem_Click_AddItToQuickLaunch;
var component: TWComponent;
menuItem: TMenuItem;
folderItem: TFolderItem;
begin
menuItem := Sender as TMenuItem;
component := GetComponentByID(menuItem.Tag);
folderItem := TMain.Instance.User.GetFolderItemByID(component.Tag);
folderItem.QuickLaunch := not folderItem.QuickLaunch;
TMain.Instance.User.InvalidateFolderItems();
end;
procedure TIconPanel.MenuItem_Click_Delete(Sender: TObject);
var component: TWComponent;
menuItem: TMenuItem;
answer: Integer;
begin
answer := TMain.Instance.ConfirmationMessage(TMain.Instance.Loc.GetString('IconPanel.DeleteConfirmation'));
if answer <> mrYes then Exit;
menuItem := Sender as TMenuItem;
component := GetComponentByID(menuItem.Tag);
if component = nil then begin
elog('Couldn''t find component with ID: ' + IntToStr(menuItem.Tag));
Exit;
end;
pComponents.Remove(TObject(component));
component.Destroy();
UpdateFolderItemsOrder();
UpdateLayout();
end;
procedure TIconPanel.MenuItem_Click_Properties(Sender: TObject);
var folderItem: TFolderItem;
component: TWComponent;
hasChanged: Boolean;
begin
component := GetComponentByID(TMenuItem(sender).Tag);
folderItem := TMain.Instance.User.GetFolderItemByID(component.Tag);
hasChanged := TMain.Instance.User.EditFolderItem(folderItem);
if hasChanged then begin
if component is TWFileIcon then begin
TWFileIcon(component).FilePath := folderItem.FilePath;
end;
end;
end;
function TIconPanel.FolderItemToComponent;
var icon: TWFileIcon;
separatorImage: TWImage;
begin
if not folderItem.IsSeparator then begin
icon := TWFileIcon.Create(Owner);
icon.Tag := folderItem.ID;
icon.Width := pIconSize;
icon.Height := pIconSize;
icon.Visible := false;
icon.OnMouseDown := icon_mouseDown;
icon.OnMouseUp := icon_mouseUp;
icon.OnClick := Icon_Click;
icon.OnMouseEnter := Icon_MouseEnter;
icon.OnMouseExit := Icon_MouseExit;
result := TWComponent(icon);
end else begin
// separatorImage := TWImage.Create(Owner);
// separatorImage.FilePath := TMain.Instance.FilePaths.SkinDirectory + '\InnerPanelSeparator.png';
// separatorImage.Visible := false;
// separatorImage.Tag := folderItem.ID;
// separatorImage.FitToContent();
// separatorImage.Height := pIconSize;
// separatorImage.StretchToFit := true;
// separatorImage.MaintainAspectRatio := false;
// separatorImage.OnMouseDown := icon_mouseDown;
// separatorImage.OnMouseUp := icon_mouseUp;
// result := TWComponent(separatorImage);
end;
end;
function TIconPanel.GetInsertionIndexAtPoint(const aPoint: TPoint): Integer;
var i:Integer;
component: TWComponent;
point: TPoint;
begin
point.X := aPoint.X;
point.Y := aPoint.Y;
result := -1;
for i := 0 to pComponents.Count - 1 do begin
component := TWComponent(pComponents[i]);
// Early exits
if point.Y < component.ScreenTop then Continue;
if point.Y >= component.ScreenTop + component.Height then Continue;
if point.X < component.ScreenLeft then Continue;
if point.X >= component.ScreenLeft + component.Width then Continue;
if point.X < component.ScreenLeft + Round(component.Width / 2) then begin
result := i;
Exit;
end;
result := i + 1;
Exit;
end;
end;
procedure TIconPanel.IconDragData_timer(Sender: TObject);
var mouse: TMouse;
formMask: Graphics.TBitmap;
rect: TRect;
region: THandle;
mouseOffset: TPoint;
formCenter: Tpoint;
indexUnderCursor: Integer;
currentIndex: Integer;
saveItem: TWComponent;
componentUnderCursor: TWComponent;
begin
mouse := TMouse.Create();
if not pIconDragData.Started then begin
if PointDistance(mouse.CursorPos, pIconDragData.MouseDownLoc) >= 5 then begin
ilog('Starting to drag icon...');
pIconDragData.Started := true;
if pIconDragData.IconForm = nil then begin
pIconDragData.IconForm := TForm.Create(self);
pIconDragData.IconForm.Visible := false;
pIconDragData.IconForm.BorderStyle := bsNone;
pIconDragData.IconForm.OnPaint := iconForm_paint;
SetTransparentForm(pIconDragData.IconForm.Handle, 100);
end;
if pIconDragData.InsertionCursor = nil then begin
pIconDragData.InsertionCursor := TWImage.Create(Owner);
pIconDragData.InsertionCursor.FilePath := TMain.Instance.FilePaths.SkinDirectory + '\InsertionCursor.png';
pIconDragData.InsertionCursor.StretchToFit := true;
pIconDragData.InsertionCursor.MaintainAspectRatio := false;
pIconDragData.InsertionCursor.FitToContent();
pIconDragData.InsertionCursor.Height := pIconSize;
AddChild(pIconDragData.InsertionCursor);
end;
pIconDragData.InsertionCursor.Visible := true;
pIconDragData.Component.Visible := false;
if pIconDragData.Component is TWFileIcon then begin
formMask := Graphics.TBitmap.Create();
try
formMask.Width := pIconDragData.IconForm.Width;
formMask.Height := pIconDragData.IconForm.Height;
rect.Top := 0;
rect.Left := 0;
rect.Bottom := formMask.Height;
rect.Right := formMask.Width;
formMask.LoadFromFile(TMain.Instance.FilePaths.SkinDirectory + '/IconOverlayMask.bmp');
region := CreateRegion(formMask);
SetWindowRGN(pIconDragData.IconForm.Handle, region, True);
finally
formMask.Free();
end;
end;
pIconDragData.IconForm.Width := pIconDragData.Component.Width;
pIconDragData.IconForm.Height := pIconDragData.Component.Height;
end;
end else begin
mouseOffset.X := mouse.CursorPos.X - pIconDragData.MouseDownLoc.X;
mouseOffset.Y := mouse.CursorPos.Y - pIconDragData.MouseDownLoc.Y;
pIconDragData.IconForm.Left := pIconDragData.StartIconLoc.X + mouseOffset.X;
pIconDragData.IconForm.Top := pIconDragData.StartIconLoc.Y + mouseOffset.Y;
formCenter.X := pIconDragData.IconForm.Left + Round(pIconDragData.IconForm.Width / 2);
formCenter.Y := pIconDragData.IconForm.Top + Round(pIconDragData.IconForm.Height / 2);
indexUnderCursor := GetInsertionIndexAtPoint(formCenter);
if indexUnderCursor < 0 then begin
componentUnderCursor := TWComponent(pComponents[0]);
pIconDragData.InsertionCursor.Left := componentUnderCursor.Left;
end else begin
if indexUnderCursor >= pComponents.Count then begin
componentUnderCursor := TWComponent(pComponents[pComponents.Count - 1]);
pIconDragData.InsertionCursor.Left := componentUnderCursor.Left + componentUnderCursor.Width;
end else begin
componentUnderCursor := TWComponent(pComponents[indexUnderCursor]);
pIconDragData.InsertionCursor.Left := componentUnderCursor.Left;
end;
end;
pIconDragData.InsertionCursor.Top := componentUnderCursor.Top;
pIconDragData.IconForm.Visible := true;
end;
end;
procedure TIconPanel.IconForm_Paint(Sender: TObject);
var rect:TRect;
begin
if pIconDragData.IconForm = nil then Exit;
if pIconDragData.Component is TWFileIcon then begin
pIconDragData.IconForm.Canvas.Brush.Style := bsClear;
TWFileIcon(pIconDragData.Component).DrawToCanvas(pIconDragData.IconForm.Canvas, 0, 0);
end else begin
rect.Top := 0;
rect.Left := 0;
rect.Bottom := pIconDragData.IconForm.Height;
rect.Right := pIconDragData.IconForm.Width;
pIconDragData.IconForm.Canvas.StretchDraw(rect, TWImage(pIconDragData.Component).ImageObject);
end;
end;
procedure TIconPanel.Icon_MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var screenMouseLoc: TPoint;
component: TWComponent;
mouse: TMouse;
popupMenu: TPopupMenu;
menuItem: TMenuItem;
folderItem: TFolderItem;
begin
component := Sender as TWComponent;
mouse := TMouse.Create();
screenMouseLoc.X := mouse.CursorPos.X;
screenMouseLoc.Y := mouse.CursorPos.Y;
if Button = mbRight then begin
ilog('Showing icon popup menu...');
popupMenu := CreateFormPopupMenu();
menuItem := TMenuItem.Create(popupMenu);
menuItem.Caption := '-';
menuItem.Enabled := false;
popupMenu.Items.Add(menuItem);
menuItem := TMenuItem.Create(popupMenu);
menuItem.Caption := TMain.Instance.Loc.GetString('IconPanel.PopupMenu.Delete');
menuItem.Tag := component.ID;
menuItem.OnClick := MenuItem_Click_Delete;
popupMenu.Items.Add(menuItem);
if component is TWFileIcon then begin
folderItem := TMain.Instance.User.GetFolderItemByID(component.Tag);
menuItem := TMenuItem.Create(popupMenu);
menuItem.Caption := '-';
menuItem.Enabled := false;
popupMenu.Items.Add(menuItem);
menuItem := TMenuItem.Create(popupMenu);
menuItem.Caption := TMain.Instance.Loc.GetString('IconPanel.PopupMenu.AddToQuickLaunch');
menuItem.Tag := component.ID;
menuItem.Checked := folderItem.QuickLaunch;
menuItem.OnClick := MenuItem_Click_AddItToQuickLaunch;
popupMenu.Items.Add(menuItem);
menuItem := TMenuItem.Create(popupMenu);
menuItem.Caption := TMain.Instance.Loc.GetString('IconPanel.PopupMenu.Properties');
menuItem.Tag := component.ID;
menuItem.OnClick := MenuItem_Click_Properties;
popupMenu.Items.Add(menuItem);
end;
popupMenu.Popup(screenMouseLoc.X, screenMouseLoc.Y);
end else begin
ilog('Initializing drag data...');
if pIconDragData.Timer = nil then begin
pIconDragData.Timer := TTimer.Create(self);
pIconDragData.Timer.Interval := 50;
pIconDragData.Timer.OnTimer := iconDragData_timer;
end;
pIconDragData.MouseDownLoc := screenMouseLoc;
pIconDragData.Component := component as TWComponent;
pIconDragData.Started := false;
pIconDragData.Timer.Enabled := true;
pIconDragData.StartIconLoc := component.ScreenLoc;
end;
end;
procedure TIconPanel.Icon_Click(sender: TObject);
var icon: TWFileIcon;
folderItem: TFolderItem;
begin
if pIconDragData.Started then Exit;
pIconDragData.Timer.Enabled := false;
icon := Sender as TWFileIcon;
folderItem := TMain.Instance.User.GetFolderItemByID(icon.Tag);
if folderItem = nil then begin
elog('No FolderItem with ID: ' + IntToStr(icon.Tag));
Exit;
end;
ilog('Icon click: ' + folderItem.FilePath);
folderItem.Launch();
end;
procedure TIconPanel.Icon_MouseEnter(sender: TObject);
var icon: TWFileIcon;
folderItem: TFolderItem;
begin
icon := TWFileIcon(sender);
folderItem := TMain.Instance.User.GetFolderItemByID(icon.Tag);
if pTooltipForm = nil then begin
pTooltipForm := TIconTooltipForm.Create(Self);
end;
pTooltipForm.ShowAbove(icon, folderItem.Name);
end;
procedure TIconPanel.Icon_MouseExit(sender: TObject);
begin
pTooltipForm.Hide();
end;
procedure TIconPanel.Icon_MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var insertionIndex: Integer;
formCenter: TPoint;
i: Integer;
component: TWComponent;
added: Boolean;
tempList: TObjectList;
begin
if Button <> mbLeft then Exit;
if not pIconDragData.Started then Exit;
formCenter.X := pIconDragData.IconForm.Left + Round(pIconDragData.IconForm.Width / 2);
formCenter.Y := pIconDragData.IconForm.Top + Round(pIconDragData.IconForm.Height / 2);
insertionIndex := GetInsertionIndexAtPoint(formCenter);
if insertionIndex >= 0 then begin
added := false;
tempList := TObjectList.Create(false);
for i := 0 to pComponents.Count - 1 do begin
component := TWComponent(pComponents[i]);
if component.ID = pIconDragData.Component.ID then Continue;
if i = insertionIndex then begin
tempList.Add(TObject(pIconDragData.Component));
added := true;
end;
tempList.Add(pComponents[i]);
end;
if not added then tempList.Add(TObject(pIconDragData.Component));
FreeAndNil(pComponents);
pComponents := tempList;
UpdateFolderItemsOrder();
UpdateLayout();
end;
pIconDragData.Started := false;
if pIconDragData.Timer <> nil then pIconDragData.Timer.Enabled := false;
if pIconDragData.IconForm <> nil then FreeAndNil(pIconDragData.IconForm);
if pIconDragData.Component <> nil then pIconDragData.Component.Visible := true;
if pIconDragData.InsertionCursor <> nil then pIconDragData.InsertionCursor.Visible := false;
end;
procedure TIconPanel.UpdateFolderItemsOrder();
var folderItemIDs: Array of Integer;
i: Integer;
begin
SetLength(folderItemIDs, pComponents.Count);
for i := 0 to pComponents.Count - 1 do begin
folderItemIDs[i] := TWComponent(pComponents[i]).Tag;
end;
TMain.Instance.User.ReorderAndDeleteFolderItems(folderItemIDs);
end;
procedure TIconPanel.LoadFolderItems();
var i: Integer;
folderItem: TFolderItem;
component: TWComponent;
begin
ilog('Creating icons');
for i := 0 to (pComponents.Count - 1) do begin
component := TWComponent(pComponents.Items[i]);
component.Free();
end;
pComponents.Clear();
for i := 0 to TMain.instance.User.FolderItemCount - 1 do begin
folderItem := TMain.instance.User.getFolderItemAt(i);
if folderItem.IsSeparator then Continue;
component := FolderItemToComponent(folderItem);
AddChild(component);
pComponents.Add(TObject(component));
end;
end;
procedure TIconPanel.FitToContent();
begin
UpdateLayout();
end;
procedure TIconPanel.UpdateLayout;
var i: Integer;
componentX, componentY: Integer;
component: TWComponent;
maxRight: Integer;
lastIconBottom: Integer;
lastIconRight: Integer;
isWrapping: Boolean;
folderItem: TFolderItem;
begin
if pBrowseButton = nil then begin
pBrowseButton := TWImageButton.Create(Owner);
pBrowseButton.Visible := true;
pBrowseButton.ImagePathPrefix := TMain.Instance.FilePaths.SkinDirectory + '\BrowseArrowButton';
pBrowseButton.FitToContent();
pBrowseButton.OnClick := BrowseButton_Click;
AddChild(pBrowseButton);
end;
componentX := TMain.Instance.Style.barInnerPanel.paddingLeft;
componentY := TMain.Instance.Style.barInnerPanel.paddingTop;
pLastVisibleIconIndex := -1;
isWrapping := false;
maxRight := Width - TMain.Instance.Style.barInnerPanel.paddingRight;
for i := 0 to pComponents.Count - 1 do begin
component := TWComponent(pComponents[i]);
if component is TWFileIcon then begin
with TWFileIcon(component) do begin
if FilePath = '' then begin
folderItem := TMain.Instance.User.GetFolderItemByID(Tag);
FilePath := folderItem.ResolvedFilePath;
OverlayImageUpPath := TMain.Instance.FilePaths.SkinDirectory + '\IconOverlayUp.png';
OverlayImageDownPath := TMain.Instance.FilePaths.SkinDirectory + '\IconOverlayDown.png';
end;
end;
end;
component.Left := componentX;
component.Top := componentY;
component.Visible := true;
if (componentX + component.Width >= maxRight) and (i <> 0) then begin
componentX := TMain.Instance.Style.barInnerPanel.paddingLeft;
componentY := componentY + component.Height;
component.Left := componentX;
component.Top := componentY;
isWrapping := true;
end;
componentX := component.Left + component.Width;
if component.Top + component.Height > Height then begin
if pLastVisibleIconIndex < 0 then pLastVisibleIconIndex := i - 1;
component.Visible := false;
end;
lastIconBottom := component.Top + component.Height;
lastIconRight := component.Left + component.Width;
end;
if pLastVisibleIconIndex >= 0 then begin
pBrowseButton.Visible := true;
pBrowseButton.Left := Width - pBrowseButton.Width;
pBrowseButton.Top := Height - pBrowseButton.Height;
end else begin
pBrowseButton.Visible := false;
end;
MaxHeight := lastIconBottom + TMain.Instance.Style.barInnerPanel.paddingBottom;
// if isWrapping then begin
// MaxWidth := -1;
// end else begin
// MaxWidth := lastIconRight + TMain.Instance.Style.barInnerPanel.paddingRight;
// end;
end;
end.
|
(******************************************************************************
* PasVulkan *
******************************************************************************
* Version see PasVulkan.Framework.pas *
******************************************************************************
* zlib license *
*============================================================================*
* *
* Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) *
* *
* This software is provided 'as-is', without any express or implied *
* warranty. In no event will the authors be held liable for any damages *
* arising from the use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not *
* claim that you wrote the original software. If you use this software *
* in a product, an acknowledgement in the product documentation would be *
* appreciated but is not required. *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* 3. This notice may not be removed or altered from any source distribution. *
* *
******************************************************************************
* General guidelines for code contributors *
*============================================================================*
* *
* 1. Make sure you are legally allowed to make a contribution under the zlib *
* license. *
* 2. The zlib license header goes at the top of each source file, with *
* appropriate copyright notice. *
* 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan *
* Pascal header. *
* 4. After a pull request, check the status of your pull request on *
http://github.com/BeRo1985/pasvulkan *
* 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= *
* 3.1.1 *
* 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, *
* but if needed, make it out-ifdef-able. *
* 7. No use of third-party libraries/units as possible, but if needed, make *
* it out-ifdef-able. *
* 8. Try to use const when possible. *
* 9. Make sure to comment out writeln, used while debugging. *
* 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, *
* x86-64, ARM, ARM64, etc.). *
* 11. Make sure the code runs on all platforms with Vulkan support *
* *
******************************************************************************)
unit PasVulkan.Compression.Deflate;
{$i PasVulkan.inc}
{$ifndef fpc}
{$ifdef conditionalexpressions}
{$if CompilerVersion>=24.0}
{$legacyifend on}
{$ifend}
{$endif}
{$endif}
{$rangechecks off}
{$overflowchecks off}
interface
uses SysUtils,
Classes,
Math,
{$if not defined(fpc)}
System.ZLIB,
{$ifend}
PasVulkan.Math,
PasVulkan.Types;
type PpvDeflateMode=^TpvDeflateMode;
TpvDeflateMode=
(
None=0,
VeryFast=1,
Faster=2,
Fast=3,
FasterThanMedium=4,
Medium=5,
SlowerThanMedium=6,
MoreSlowerThanMedium=7,
YetMoreSlowerThanMedium=8,
Slow=9
);
function DoDeflate(const aInData:TpvPointer;const aInLen:TpvSizeUInt;var aDestData:TpvPointer;var aDestLen:TpvSizeUInt;const aMode:TpvDeflateMode;const aWithHeader:boolean):boolean;
function DoInflate(const aInData:TpvPointer;aInLen:TpvSizeUInt;var aDestData:TpvPointer;var aDestLen:TpvSizeUInt;const aParseHeader:boolean):boolean;
implementation
{$if defined(fpc) and (defined(Linux) or defined(Android))}
uses zlib;
{$ifend}
{$if not (defined(fpc) and (defined(Linux) or defined(Android)))}
const LengthCodes:array[0..28,0..3] of TpvUInt32=
( // Code, ExtraBits, Min, Max
(257,0,3,3),
(258,0,4,4),
(259,0,5,5),
(260,0,6,6),
(261,0,7,7),
(262,0,8,8),
(263,0,9,9),
(264,0,10,10),
(265,1,11,12),
(266,1,13,14),
(267,1,15,16),
(268,1,17,18),
(269,2,19,22),
(270,2,23,26),
(271,2,27,30),
(272,2,31,34),
(273,3,35,42),
(274,3,43,50),
(275,3,51,58),
(276,3,59,66),
(277,4,67,82),
(278,4,83,98),
(279,4,99,114),
(280,4,115,130),
(281,5,131,162),
(282,5,163,194),
(283,5,195,226),
(284,5,227,257),
(285,0,258,258)
);
DistanceCodes:array[0..29,0..3] of TpvUInt32=
( // Code, ExtraBits, Min, Max
(0,0,1,1),
(1,0,2,2),
(2,0,3,3),
(3,0,4,4),
(4,1,5,6),
(5,1,7,8),
(6,2,9,12),
(7,2,13,16),
(8,3,17,24),
(9,3,25,32),
(10,4,33,48),
(11,4,49,64),
(12,5,65,96),
(13,5,97,128),
(14,6,129,192),
(15,6,193,256),
(16,7,257,384),
(17,7,385,512),
(18,8,513,768),
(19,8,769,1024),
(20,9,1025,1536),
(21,9,1537,2048),
(22,10,2049,3072),
(23,10,3073,4096),
(24,11,4097,6144),
(25,11,6145,8192),
(26,12,8193,12288),
(27,12,12289,16384),
(28,13,16385,24576),
(29,13,24577,32768)
);
var LengthCodesLookUpTable:array[0..258] of TpvInt32;
DistanceCodesLookUpTable:array[0..32768] of TpvInt32;
procedure InitializeLookUpTables;
var Index,ValueIndex:TpvInt32;
begin
for Index:=0 to length(LengthCodes)-1 do begin
for ValueIndex:=IfThen(Index=0,0,LengthCodes[Index,2]) to LengthCodes[Index,3] do begin
LengthCodesLookUpTable[ValueIndex]:=Index;
end;
end;
for Index:=0 to length(DistanceCodes)-1 do begin
for ValueIndex:=IfThen(Index=0,0,DistanceCodes[Index,2]) to DistanceCodes[Index,3] do begin
DistanceCodesLookUpTable[ValueIndex]:=Index;
end;
end;
end;
{$ifend}
function DoDeflate(const aInData:TpvPointer;const aInLen:TpvSizeUInt;var aDestData:TpvPointer;var aDestLen:TpvSizeUInt;const aMode:TpvDeflateMode;const aWithHeader:boolean):boolean;
{$if not defined(fpc)}
const OutChunkSize=65536;
var d_stream:z_stream;
r,Level:TpvInt32;
Allocated,Have:TpvSizeUInt;
begin
result:=false;
aDestLen:=0;
Allocated:=0;
aDestData:=nil;
FillChar(d_stream,SizeOf(z_stream),AnsiChar(#0));
Level:=Min(Max(TpvInt32(aMode),0),9);
if aWithHeader then begin
r:=deflateInit(d_stream,Level);
end else begin
r:=deflateInit2(d_stream,Level,Z_DEFLATED,-15{MAX_WBITS},9{Z_MEM_LEVEL},Z_DEFAULT_STRATEGY);
end;
try
if r=Z_OK then begin
try
d_stream.next_in:=aInData;
d_stream.avail_in:=aInLen;
Allocated:=deflateBound(d_stream,aInLen);
if Allocated<RoundUpToPowerOfTwo(aInLen) then begin
Allocated:=RoundUpToPowerOfTwo(aInLen);
end;
if Allocated<OutChunkSize then begin
Allocated:=OutChunkSize;
end;
GetMem(aDestData,Allocated);
d_stream.next_out:=aDestData;
d_stream.avail_out:=Allocated;
r:=deflate(d_stream,Z_FINISH);
aDestLen:=d_stream.total_out;
finally
if r=Z_STREAM_END then begin
r:=deflateEnd(d_stream);
end else begin
deflateEnd(d_stream);
end;
end;
end;
finally
if (r=Z_OK) or (r=Z_STREAM_END) then begin
if assigned(aDestData) then begin
ReallocMem(aDestData,aDestLen);
end else begin
aDestLen:=0;
end;
result:=true;
end else begin
if assigned(aDestData) then begin
FreeMem(aDestData);
end;
aDestData:=nil;
end;
end;
end;
{$elseif defined(fpc) and (defined(Linux) or defined(Android))}
const OutChunkSize=65536;
var d_stream:z_stream;
r,Level:TpvInt32;
Allocated,Have:TpvSizeUInt;
begin
result:=false;
aDestLen:=0;
Allocated:=0;
aDestData:=nil;
FillChar(d_stream,SizeOf(z_stream),AnsiChar(#0));
Level:=Min(Max(TpvInt32(aMode),0),9);
if aWithHeader then begin
r:=deflateInit(d_stream,Level);
end else begin
r:=deflateInit2(d_stream,Level,Z_DEFLATED,-15{MAX_WBITS},9{Z_MEM_LEVEL},Z_DEFAULT_STRATEGY);
end;
try
if r=Z_OK then begin
try
d_stream.next_in:=aInData;
d_stream.avail_in:=aInLen;
Allocated:=deflateBound(d_stream,aInLen);
if Allocated<RoundUpToPowerOfTwo(aInLen) then begin
Allocated:=RoundUpToPowerOfTwo(aInLen);
end;
if Allocated<OutChunkSize then begin
Allocated:=OutChunkSize;
end;
GetMem(aDestData,Allocated);
d_stream.next_out:=aDestData;
d_stream.avail_out:=Allocated;
r:=deflate(d_stream,Z_FINISH);
aDestLen:=d_stream.total_out;
finally
if r=Z_STREAM_END then begin
r:=deflateEnd(d_stream);
end else begin
deflateEnd(d_stream);
end;
end;
end;
finally
if (r=Z_OK) or (r=Z_STREAM_END) then begin
if assigned(aDestData) then begin
ReallocMem(aDestData,aDestLen);
end else begin
aDestLen:=0;
end;
result:=true;
end else begin
if assigned(aDestData) then begin
FreeMem(aDestData);
end;
aDestData:=nil;
end;
end;
end;
{$else}
const HashBits=16;
HashSize=1 shl HashBits;
HashMask=HashSize-1;
HashShift=32-HashBits;
WindowSize=32768;
WindowMask=WindowSize-1;
MinMatch=3;
MaxMatch=258;
MaxOffset=32768;
MirrorBytes:array[TpvUInt8] of TpvUInt8=
(
$00,$80,$40,$c0,$20,$a0,$60,$e0,
$10,$90,$50,$d0,$30,$b0,$70,$f0,
$08,$88,$48,$c8,$28,$a8,$68,$e8,
$18,$98,$58,$d8,$38,$b8,$78,$f8,
$04,$84,$44,$c4,$24,$a4,$64,$e4,
$14,$94,$54,$d4,$34,$b4,$74,$f4,
$0c,$8c,$4c,$cc,$2c,$ac,$6c,$ec,
$1c,$9c,$5c,$dc,$3c,$bc,$7c,$fc,
$02,$82,$42,$c2,$22,$a2,$62,$e2,
$12,$92,$52,$d2,$32,$b2,$72,$f2,
$0a,$8a,$4a,$ca,$2a,$aa,$6a,$ea,
$1a,$9a,$5a,$da,$3a,$ba,$7a,$fa,
$06,$86,$46,$c6,$26,$a6,$66,$e6,
$16,$96,$56,$d6,$36,$b6,$76,$f6,
$0e,$8e,$4e,$ce,$2e,$ae,$6e,$ee,
$1e,$9e,$5e,$de,$3e,$be,$7e,$fe,
$01,$81,$41,$c1,$21,$a1,$61,$e1,
$11,$91,$51,$d1,$31,$b1,$71,$f1,
$09,$89,$49,$c9,$29,$a9,$69,$e9,
$19,$99,$59,$d9,$39,$b9,$79,$f9,
$05,$85,$45,$c5,$25,$a5,$65,$e5,
$15,$95,$55,$d5,$35,$b5,$75,$f5,
$0d,$8d,$4d,$cd,$2d,$ad,$6d,$ed,
$1d,$9d,$5d,$dd,$3d,$bd,$7d,$fd,
$03,$83,$43,$c3,$23,$a3,$63,$e3,
$13,$93,$53,$d3,$33,$b3,$73,$f3,
$0b,$8b,$4b,$cb,$2b,$ab,$6b,$eb,
$1b,$9b,$5b,$db,$3b,$bb,$7b,$fb,
$07,$87,$47,$c7,$27,$a7,$67,$e7,
$17,$97,$57,$d7,$37,$b7,$77,$f7,
$0f,$8f,$4f,$cf,$2f,$af,$6f,$ef,
$1f,$9f,$5f,$df,$3f,$bf,$7f,$ff
);
MultiplyDeBruijnBytePosition:array[0..31] of byte=(0,0,3,0,3,1,3,0,3,2,2,1,3,2,0,1,3,3,1,2,2,2,2,0,3,1,2,0,1,0,1,1);
type PHashTable=^THashTable;
THashTable=array[0..HashSize-1] of PpvUInt8;
PChainTable=^TChainTable;
TChainTable=array[0..WindowSize-1] of TpvPointer;
PThreeBytes=^TThreeBytes;
TThreeBytes=array[0..2] of TpvUInt8;
PBytes=^TBytes;
TBytes=array[0..$7ffffffe] of TpvUInt8;
var OutputBits,CountOutputBits:TpvUInt32;
AllocatedDestSize:TpvUInt64;
procedure DoOutputBits(const aBits,aCountBits:TpvUInt32);
begin
Assert((CountOutputBits+aCountBits)<=32);
OutputBits:=OutputBits or (aBits shl CountOutputBits);
inc(CountOutputBits,aCountBits);
while CountOutputBits>=8 do begin
if AllocatedDestSize<(aDestLen+1) then begin
AllocatedDestSize:=(aDestLen+1) shl 1;
ReallocMem(aDestData,AllocatedDestSize);
end;
PBytes(aDestData)^[aDestLen]:=OutputBits and $ff;
inc(aDestLen);
OutputBits:=OutputBits shr 8;
dec(CountOutputBits,8);
end;
end;
procedure DoOutputLiteral(const aValue:TpvUInt8);
begin
case aValue of
0..143:begin
DoOutputBits(MirrorBytes[$30+aValue],8);
end;
else begin
DoOutputBits((MirrorBytes[$90+(aValue-144)] shl 1) or 1,9);
end;
end;
end;
procedure DoOutputCopy(const aDistance,aLength:TpvUInt32);
var Remain,ToDo,Index:TpvUInt32;
begin
Remain:=aLength;
while Remain>0 do begin
case Remain of
0..258:begin
ToDo:=Remain;
end;
259..260:begin
ToDo:=Remain-3;
end;
else begin
ToDo:=258;
end;
end;
dec(Remain,ToDo);
Index:=LengthCodesLookUpTable[Min(Max(ToDo,0),258)];
if LengthCodes[Index,0]<=279 then begin
DoOutputBits(MirrorBytes[(LengthCodes[Index,0]-256) shl 1],7);
end else begin
DoOutputBits(MirrorBytes[$c0+(LengthCodes[Index,0]-280)],8);
end;
if LengthCodes[Index,1]<>0 then begin
DoOutputBits(ToDo-LengthCodes[Index,2],LengthCodes[Index,1]);
end;
Index:=DistanceCodesLookUpTable[Min(Max(aDistance,0),32768)];
DoOutputBits(MirrorBytes[DistanceCodes[Index,0] shl 3],5);
if DistanceCodes[Index,1]<>0 then begin
DoOutputBits(aDistance-DistanceCodes[Index,2],DistanceCodes[Index,1]);
end;
end;
end;
procedure OutputStartBlock;
begin
DoOutputBits(1,1); // Final block
DoOutputBits(1,2); // Static huffman block
end;
procedure OutputEndBlock;
begin
DoOutputBits(0,7); // Close block
DoOutputBits(0,7); // Make sure all bits are flushed
end;
function Adler32(const aData:TpvPointer;const aLength:TpvSizeUInt):TpvUInt32;
const Base=65521;
MaximumCountAtOnce=5552;
var Buf:PpvRawByteChar;
Remain,ToDo,Index:TpvSizeUInt;
s1,s2:TpvUInt32;
begin
s1:=1;
s2:=0;
Buf:=aData;
Remain:=aLength;
while Remain>0 do begin
if Remain<MaximumCountAtOnce then begin
ToDo:=Remain;
end else begin
ToDo:=MaximumCountAtOnce;
end;
dec(Remain,ToDo);
for Index:=1 to ToDo do begin
inc(s1,TpvUInt8(Buf^));
inc(s2,s1);
inc(Buf);
end;
s1:=s1 mod Base;
s2:=s2 mod Base;
end;
result:=(s2 shl 16) or s1;
end;
var CurrentPointer,EndPointer,EndSearchPointer,Head,CurrentPossibleMatch:PpvUInt8;
BestMatchDistance,BestMatchLength,MatchLength,MaximumMatchLength,CheckSum,Step,MaxSteps,
Difference,Offset,SkipStrength,UnsuccessfulFindMatchAttempts:TpvUInt32;
HashTable:PHashTable;
ChainTable:PChainTable;
HashTableItem:PPpvUInt8;
DoCompression,Greedy:boolean;
begin
result:=false;
AllocatedDestSize:=SizeOf(TpvUInt32);
GetMem(aDestData,AllocatedDestSize);
aDestLen:=0;
InitializeLookUpTables;
try
DoCompression:=aMode<>TpvDeflateMode.None;
MaxSteps:=1 shl TpvInt32(aMode);
SkipStrength:=(32-9)+TpvInt32(aMode);
Greedy:=TpvInt32(aMode)>=1;
OutputBits:=0;
CountOutputBits:=0;
if DoCompression then begin
if aWithHeader then begin
DoOutputBits($78,8); // CMF
DoOutputBits($9c,8); // FLG Default Compression
end;
OutputStartBlock;
GetMem(HashTable,SizeOf(THashTable));
try
FillChar(HashTable^,SizeOf(THashTable),#0);
GetMem(ChainTable,SizeOf(TChainTable));
try
FillChar(ChainTable^,SizeOf(TChainTable),#0);
CurrentPointer:=aInData;
EndPointer:={%H-}TpvPointer(TpvPtrUInt(TpvPtrUInt(CurrentPointer)+TpvPtrUInt(aInLen)));
EndSearchPointer:={%H-}TpvPointer(TpvPtrUInt((TpvPtrUInt(CurrentPointer)+TpvPtrUInt(aInLen))-TpvPtrUInt(TpvInt64(Max(TpvInt64(MinMatch),TpvInt64(SizeOf(TpvUInt32)))))));
UnsuccessfulFindMatchAttempts:=TpvUInt32(1) shl SkipStrength;
while {%H-}TpvPtrUInt(CurrentPointer)<{%H-}TpvPtrUInt(EndSearchPointer) do begin
HashTableItem:=@HashTable[((((PpvUInt32(TpvPointer(CurrentPointer))^ and TpvUInt32({$if defined(FPC_BIG_ENDIAN)}$ffffff00{$else}$00ffffff{$ifend}){$if defined(FPC_BIG_ENDIAN)}shr 8{$ifend}))*TpvUInt32($1e35a7bd)) shr HashShift) and HashMask];
Head:=HashTableItem^;
CurrentPossibleMatch:=Head;
BestMatchDistance:=0;
BestMatchLength:=1;
Step:=0;
while assigned(CurrentPossibleMatch) and
({%H-}TpvPtrUInt(CurrentPointer)>{%H-}TpvPtrUInt(CurrentPossibleMatch)) and
(TpvPtrInt({%H-}TpvPtrUInt({%H-}TpvPtrUInt(CurrentPointer)-{%H-}TpvPtrUInt(CurrentPossibleMatch)))<TpvPtrInt(MaxOffset)) do begin
Difference:=PpvUInt32(TpvPointer(@PBytes(CurrentPointer)^[0]))^ xor PpvUInt32(TpvPointer(@PBytes(CurrentPossibleMatch)^[0]))^;
if (Difference and TpvUInt32({$if defined(FPC_BIG_ENDIAN)}$ffffff00{$else}$00ffffff{$ifend}))=0 then begin
if (BestMatchLength<=({%H-}TpvPtrUInt(EndPointer)-{%H-}TpvPtrUInt(CurrentPointer))) and
(PBytes(CurrentPointer)^[BestMatchLength-1]=PBytes(CurrentPossibleMatch)^[BestMatchLength-1]) then begin
MatchLength:=MinMatch;
while ({%H-}TpvPtrUInt(@PBytes(CurrentPointer)^[MatchLength+(SizeOf(TpvUInt32)-1)])<{%H-}TpvPtrUInt(EndPointer)) do begin
Difference:=PpvUInt32(TpvPointer(@PBytes(CurrentPointer)^[MatchLength]))^ xor PpvUInt32(TpvPointer(@PBytes(CurrentPossibleMatch)^[MatchLength]))^;
if Difference=0 then begin
inc(MatchLength,SizeOf(TpvUInt32));
end else begin
{$if defined(FPC_BIG_ENDIAN)}
if (Difference shr 16)<>0 then begin
inc(MatchLength,not (Difference shr 24));
end else begin
inc(MatchLength,2+(not (Difference shr 8)));
end;
{$else}
inc(MatchLength,MultiplyDeBruijnBytePosition[TpvUInt32(TpvUInt32(Difference and (-Difference))*TpvUInt32($077cb531)) shr 27]);
{$ifend}
break;
end;
end;
if BestMatchLength<MatchLength then begin
BestMatchDistance:={%H-}TpvPtrUInt({%H-}TpvPtrUInt(CurrentPointer)-{%H-}TpvPtrUInt(CurrentPossibleMatch));
BestMatchLength:=MatchLength;
end;
end;
end;
inc(Step);
if Step<MaxSteps then begin
CurrentPossibleMatch:=ChainTable^[({%H-}TpvPtrUInt(CurrentPossibleMatch)-{%H-}TpvPtrUInt(aInData)) and WindowMask];
end else begin
break;
end;
end;
if (BestMatchDistance>0) and (BestMatchLength>1) then begin
DoOutputCopy(BestMatchDistance,BestMatchLength);
end else begin
if SkipStrength>31 then begin
DoOutputLiteral(CurrentPointer^);
end else begin
Step:=UnsuccessfulFindMatchAttempts shr SkipStrength;
Offset:=0;
while (Offset<Step) and (({%H-}TpvPtrUInt(CurrentPointer)+Offset)<{%H-}TpvPtrUInt(EndSearchPointer)) do begin
DoOutputLiteral(PpvUInt8Array(CurrentPointer)^[Offset]);
inc(Offset);
end;
BestMatchLength:=Offset;
inc(UnsuccessfulFindMatchAttempts,ord(UnsuccessfulFindMatchAttempts<TpvUInt32($ffffffff)) and 1);
end;
end;
HashTableItem^:=CurrentPointer;
ChainTable^[({%H-}TpvPtrUInt(CurrentPointer)-{%H-}TpvPtrUInt(aInData)) and WindowMask]:=Head;
if Greedy then begin
inc(CurrentPointer);
dec(BestMatchLength);
while (BestMatchLength>0) and ({%H-}TpvPtrUInt(CurrentPointer)<{%H-}TpvPtrUInt(EndSearchPointer)) do begin
HashTableItem:=@HashTable[((((PpvUInt32(TpvPointer(CurrentPointer))^ and TpvUInt32({$if defined(FPC_BIG_ENDIAN)}$ffffff00{$else}$00ffffff{$ifend}){$if defined(FPC_BIG_ENDIAN)}shr 8{$ifend}))*TpvUInt32($1e35a7bd)) shr HashShift) and HashMask];
Head:=HashTableItem^;
HashTableItem^:=CurrentPointer;
ChainTable^[({%H-}TpvPtrUInt(CurrentPointer)-{%H-}TpvPtrUInt(aInData)) and WindowMask]:=Head;
inc(CurrentPointer);
dec(BestMatchLength);
end;
end;
inc(CurrentPointer,BestMatchLength);
end;
while {%H-}TpvPtrUInt(CurrentPointer)<{%H-}TpvPtrUInt(EndPointer) do begin
DoOutputLiteral(CurrentPointer^);
inc(CurrentPointer);
end;
finally
FreeMem(ChainTable);
end;
finally
FreeMem(HashTable);
end;
OutputEndBlock;
end else begin
if aWithHeader then begin
if AllocatedDestSize<(aDestLen+2) then begin
AllocatedDestSize:=(aDestLen+2) shl 1;
ReallocMem(aDestData,AllocatedDestSize);
end;
PBytes(aDestData)^[aDestLen+0]:=$78; // CMF
PBytes(aDestData)^[aDestLen+1]:=$01; // FLG No Compression
inc(aDestLen,2);
end;
if aInLen>0 then begin
if AllocatedDestSize<(aDestLen+aInLen) then begin
AllocatedDestSize:=(aDestLen+aInLen) shl 1;
ReallocMem(aDestData,AllocatedDestSize);
end;
Move(aInData^,PBytes(aDestData)^[aDestLen],aInLen);
inc(aDestLen,aInLen);
end;
end;
if aWithHeader then begin
CheckSum:=Adler32(aInData,aInLen);
if AllocatedDestSize<(aDestLen+4) then begin
AllocatedDestSize:=(aDestLen+4) shl 1;
ReallocMem(aDestData,AllocatedDestSize);
end;
PBytes(aDestData)^[aDestLen+0]:=(CheckSum shr 24) and $ff;
PBytes(aDestData)^[aDestLen+1]:=(CheckSum shr 16) and $ff;
PBytes(aDestData)^[aDestLen+2]:=(CheckSum shr 8) and $ff;
PBytes(aDestData)^[aDestLen+3]:=(CheckSum shr 0) and $ff;
inc(aDestLen,4);
end;
finally
if aDestLen>0 then begin
ReallocMem(aDestData,aDestLen);
result:=true;
end else if assigned(aDestData) then begin
FreeMem(aDestData);
aDestData:=nil;
end;
end;
end;
{$ifend}
function DoInflate(const aInData:TpvPointer;aInLen:TpvSizeUInt;var aDestData:TpvPointer;var aDestLen:TpvSizeUInt;const aParseHeader:boolean):boolean;
{$if not defined(fpc)}
const OutChunkSize=65536;
var d_stream:z_stream;
r:TpvInt32;
Allocated,Have:TpvSizeUInt;
begin
result:=false;
aDestLen:=0;
Allocated:=0;
aDestData:=nil;
FillChar(d_stream,SizeOf(z_stream),AnsiChar(#0));
d_stream.next_in:=aInData;
d_stream.avail_in:=aInLen;
if aParseHeader then begin
r:=inflateInit(d_stream);
end else begin
r:=inflateInit2(d_stream,-15{MAX_WBITS});
end;
try
if r=Z_OK then begin
try
Allocated:=RoundUpToPowerOfTwo(aInLen);
if Allocated<OutChunkSize then begin
Allocated:=OutChunkSize;
end;
GetMem(aDestData,Allocated);
repeat
repeat
if Allocated<(aDestLen+OutChunkSize) then begin
Allocated:=RoundUpToPowerOfTwo(aDestLen+OutChunkSize);
if assigned(aDestData) then begin
ReallocMem(aDestData,Allocated);
end else begin
GetMem(aDestData,Allocated);
end;
end;
d_stream.next_out:=@PpvUInt8Array(aDestData)^[aDestLen];
d_stream.avail_out:=OutChunkSize;
r:=Inflate(d_stream,Z_NO_FLUSH);
if r<Z_OK then begin
break;
end;
if d_stream.avail_out<OutChunkSize then begin
inc(aDestLen,OutChunkSize-d_stream.avail_out);
end;
until d_stream.avail_out<>0;
until (r<Z_OK) or (r=Z_STREAM_END);
finally
if r=Z_STREAM_END then begin
r:=InflateEnd(d_stream);
end else begin
InflateEnd(d_stream);
end;
end;
end;
finally
if (r=Z_OK) or (r=Z_STREAM_END) then begin
if assigned(aDestData) then begin
ReallocMem(aDestData,aDestLen);
end else begin
aDestLen:=0;
end;
result:=true;
end else begin
if assigned(aDestData) then begin
FreeMem(aDestData);
end;
aDestData:=nil;
end;
end;
end;
{$elseif defined(fpc) and (defined(Linux) or defined(Android))}
const OutChunkSize=65536;
var d_stream:z_stream;
r:TpvInt32;
Allocated,Have:TpvSizeUInt;
begin
result:=false;
aDestLen:=0;
Allocated:=0;
aDestData:=nil;
FillChar(d_stream,SizeOf(z_stream),AnsiChar(#0));
d_stream.next_in:=aInData;
d_stream.avail_in:=aInLen;
if aParseHeader then begin
r:=inflateInit(d_stream);
end else begin
r:=inflateInit2(d_stream,-15{MAX_WBITS});
end;
try
if r=Z_OK then begin
try
Allocated:=RoundUpToPowerOfTwo(aInLen);
if Allocated<OutChunkSize then begin
Allocated:=OutChunkSize;
end;
GetMem(aDestData,Allocated);
repeat
repeat
if Allocated<(aDestLen+OutChunkSize) then begin
Allocated:=RoundUpToPowerOfTwo(aDestLen+OutChunkSize);
if assigned(aDestData) then begin
ReallocMem(aDestData,Allocated);
end else begin
GetMem(aDestData,Allocated);
end;
end;
d_stream.next_out:=@PpvUInt8Array(aDestData)^[aDestLen];
d_stream.avail_out:=OutChunkSize;
r:=Inflate(d_stream,Z_NO_FLUSH);
if r<Z_OK then begin
break;
end;
if d_stream.avail_out<OutChunkSize then begin
inc(aDestLen,OutChunkSize-d_stream.avail_out);
end;
until d_stream.avail_out<>0;
until (r<Z_OK) or (r=Z_STREAM_END);
finally
if r=Z_STREAM_END then begin
r:=InflateEnd(d_stream);
end else begin
InflateEnd(d_stream);
end;
end;
end;
finally
if (r=Z_OK) or (r=Z_STREAM_END) then begin
if assigned(aDestData) then begin
ReallocMem(aDestData,aDestLen);
end else begin
aDestLen:=0;
end;
result:=true;
end else begin
if assigned(aDestData) then begin
FreeMem(aDestData);
end;
aDestData:=nil;
end;
end;
end;
{$else}
const CLCIndex:array[0..18] of TpvUInt8=(16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15);
type pword=^TpvUInt16;
PTree=^TTree;
TTree=packed record
Table:array[0..15] of TpvUInt16;
Translation:array[0..287] of TpvUInt16;
end;
PBuffer=^TBuffer;
TBuffer=array[0..65535] of TpvUInt8;
PLengths=^TLengths;
TLengths=array[0..288+32-1] of TpvUInt8;
POffsets=^TOffsets;
TOffsets=array[0..15] of TpvUInt16;
PBits=^TBits;
TBits=array[0..29] of TpvUInt8;
PBase=^TBase;
TBase=array[0..29] of TpvUInt16;
var Tag,BitCount,DestSize:TpvUInt32;
SymbolLengthTree,DistanceTree,FixedSymbolLengthTree,FixedDistanceTree:PTree;
LengthBits,DistanceBits:PBits;
LengthBase,DistanceBase:PBase;
Source,SourceEnd:PpvRawByteChar;
Dest:PpvRawByteChar;
procedure IncSize(length:TpvUInt32);
var j:TpvUInt32;
begin
if (aDestLen+length)>=DestSize then begin
if DestSize=0 then begin
DestSize:=1;
end;
while (aDestLen+length)>=DestSize do begin
inc(DestSize,DestSize);
end;
j:=TpvPtrUInt(Dest)-TpvPtrUInt(aDestData);
ReAllocMem(aDestData,DestSize);
TpvPtrUInt(Dest):=TpvPtrUInt(aDestData)+j;
end;
end;
function Adler32(data:TpvPointer;length:TpvSizeUInt):TpvUInt32;
const BASE=65521;
NMAX=5552;
var buf:PpvRawByteChar;
s1,s2:TpvUInt32;
k,i:TpvSizeUInt;
begin
s1:=1;
s2:=0;
buf:=data;
while length>0 do begin
if length<NMAX then begin
k:=length;
end else begin
k:=NMAX;
end;
dec(length,k);
for i:=1 to k do begin
inc(s1,TpvUInt8(buf^));
inc(s2,s1);
inc(buf);
end;
s1:=s1 mod BASE;
s2:=s2 mod BASE;
end;
result:=(s2 shl 16) or s1;
end;
procedure BuildBitsBase(Bits:PpvRawByteChar;Base:pword;Delta,First:TpvInt32);
var i,Sum:TpvInt32;
begin
for i:=0 to Delta-1 do begin
Bits[i]:=TpvRawByteChar(#0);
end;
for i:=0 to (30-Delta)-1 do begin
Bits[i+Delta]:=TpvRawByteChar(TpvUInt8(i div Delta));
end;
Sum:=First;
for i:=0 to 29 do begin
Base^:=Sum;
inc(Base);
inc(Sum,1 shl TpvUInt8(Bits[i]));
end;
end;
procedure BuildFixedTrees(var lt,dt:TTree);
var i:TpvInt32;
begin
for i:=0 to 6 do begin
lt.Table[i]:=0;
end;
lt.Table[7]:=24;
lt.Table[8]:=152;
lt.Table[9]:=112;
for i:=0 to 23 do begin
lt.Translation[i]:=256+i;
end;
for i:=0 to 143 do begin
lt.Translation[24+i]:=i;
end;
for i:=0 to 7 do begin
lt.Translation[168+i]:=280+i;
end;
for i:=0 to 111 do begin
lt.Translation[176+i]:=144+i;
end;
for i:=0 to 4 do begin
dt.Table[i]:=0;
end;
dt.Table[5]:=32;
for i:=0 to 31 do begin
dt.Translation[i]:=i;
end;
end;
procedure BuildTree(var t:TTree;Lengths:PpvRawByteChar;Num:TpvInt32);
var Offsets:POffsets;
i:TpvInt32;
Sum:TpvUInt32;
begin
New(Offsets);
try
for i:=0 to 15 do begin
t.Table[i]:=0;
end;
for i:=0 to Num-1 do begin
inc(t.Table[TpvUInt8(Lengths[i])]);
end;
t.Table[0]:=0;
Sum:=0;
for i:=0 to 15 do begin
Offsets^[i]:=Sum;
inc(Sum,t.Table[i]);
end;
for i:=0 to Num-1 do begin
if lengths[i]<>TpvRawByteChar(#0) then begin
t.Translation[Offsets^[TpvUInt8(lengths[i])]]:=i;
inc(Offsets^[TpvUInt8(lengths[i])]);
end;
end;
finally
Dispose(Offsets);
end;
end;
function GetBit:TpvUInt32;
begin
if BitCount=0 then begin
Tag:=TpvUInt8(Source^);
inc(Source);
BitCount:=7;
end else begin
dec(BitCount);
end;
result:=Tag and 1;
Tag:=Tag shr 1;
end;
function ReadBits(Num,Base:TpvUInt32):TpvUInt32;
var Limit,Mask:TpvUInt32;
begin
result:=0;
if Num<>0 then begin
Limit:=1 shl Num;
Mask:=1;
while Mask<Limit do begin
if GetBit<>0 then begin
inc(result,Mask);
end;
Mask:=Mask shl 1;
end;
end;
inc(result,Base);
end;
function DecodeSymbol(var t:TTree):TpvUInt32;
var Sum,c,l:TpvInt32;
begin
Sum:=0;
c:=0;
l:=0;
repeat
c:=(c*2)+TpvInt32(GetBit);
inc(l);
inc(Sum,t.Table[l]);
dec(c,t.Table[l]);
until not (c>=0);
result:=t.Translation[Sum+c];
end;
procedure DecodeTrees(var lt,dt:TTree);
var CodeTree:PTree;
Lengths:PLengths;
hlit,hdist,hclen,i,num,length,clen,Symbol,Prev:TpvUInt32;
begin
New(CodeTree);
New(Lengths);
try
FillChar(CodeTree^,sizeof(TTree),TpvRawByteChar(#0));
FillChar(Lengths^,sizeof(TLengths),TpvRawByteChar(#0));
hlit:=ReadBits(5,257);
hdist:=ReadBits(5,1);
hclen:=ReadBits(4,4);
for i:=0 to 18 do begin
lengths^[i]:=0;
end;
for i:=1 to hclen do begin
clen:=ReadBits(3,0);
lengths^[CLCIndex[i-1]]:=clen;
end;
BuildTree(CodeTree^,PpvRawByteChar(TpvPointer(@lengths^[0])),19);
num:=0;
while num<(hlit+hdist) do begin
Symbol:=DecodeSymbol(CodeTree^);
case Symbol of
16:begin
prev:=lengths^[num-1];
length:=ReadBits(2,3);
while length>0 do begin
lengths^[num]:=prev;
inc(num);
dec(length);
end;
end;
17:begin
length:=ReadBits(3,3);
while length>0 do begin
lengths^[num]:=0;
inc(num);
dec(length);
end;
end;
18:begin
length:=ReadBits(7,11);
while length>0 do begin
lengths^[num]:=0;
inc(num);
dec(length);
end;
end;
else begin
lengths^[num]:=Symbol;
inc(num);
end;
end;
end;
BuildTree(lt,PpvRawByteChar(TpvPointer(@lengths^[0])),hlit);
BuildTree(dt,PpvRawByteChar(TpvPointer(@lengths^[hlit])),hdist);
finally
Dispose(CodeTree);
Dispose(Lengths);
end;
end;
function InflateBlockData(var lt,dt:TTree):boolean;
var Symbol:TpvUInt32;
Length,Distance,Offset,i:TpvInt32;
begin
result:=false;
while (Source<SourceEnd) or (BitCount>0) do begin
Symbol:=DecodeSymbol(lt);
if Symbol=256 then begin
result:=true;
break;
end;
if Symbol<256 then begin
IncSize(1);
Dest^:=TpvRawByteChar(TpvUInt8(Symbol));
inc(Dest);
inc(aDestLen);
end else begin
dec(Symbol,257);
Length:=ReadBits(LengthBits^[Symbol],LengthBase^[Symbol]);
Distance:=DecodeSymbol(dt);
Offset:=ReadBits(DistanceBits^[Distance],DistanceBase^[Distance]);
IncSize(length);
for i:=0 to length-1 do begin
Dest[i]:=Dest[i-Offset];
end;
inc(Dest,Length);
inc(aDestLen,Length);
end;
end;
end;
function InflateUncompressedBlock:boolean;
var length,invlength:TpvUInt32;
begin
result:=false;
length:=(TpvUInt8(source[1]) shl 8) or TpvUInt8(source[0]);
invlength:=(TpvUInt8(source[3]) shl 8) or TpvUInt8(source[2]);
if length<>((not invlength) and $ffff) then begin
exit;
end;
IncSize(length);
inc(Source,4);
if Length>0 then begin
Move(Source^,Dest^,Length);
inc(Source,Length);
inc(Dest,Length);
end;
BitCount:=0;
inc(aDestLen,Length);
result:=true;
end;
function InflateFixedBlock:boolean;
begin
result:=InflateBlockData(FixedSymbolLengthTree^,FixedDistanceTree^);
end;
function InflateDynamicBlock:boolean;
begin
DecodeTrees(SymbolLengthTree^,DistanceTree^);
result:=InflateBlockData(SymbolLengthTree^,DistanceTree^);
end;
function Uncompress:boolean;
var Final,r:boolean;
BlockType:TpvUInt32;
begin
result:=false;
BitCount:=0;
Final:=false;
while not Final do begin
Final:=GetBit<>0;
BlockType:=ReadBits(2,0);
case BlockType of
0:begin
r:=InflateUncompressedBlock;
end;
1:begin
r:=InflateFixedBlock;
end;
2:begin
r:=InflateDynamicBlock;
end;
else begin
r:=false;
end;
end;
if not r then begin
exit;
end;
end;
result:=true;
end;
function UncompressZLIB:boolean;
var cmf,flg:TpvUInt8;
a32:TpvUInt32;
begin
result:=false;
Source:=aInData;
cmf:=TpvUInt8(Source[0]);
flg:=TpvUInt8(Source[1]);
if ((((cmf shl 8)+flg) mod 31)<>0) or ((cmf and $f)<>8) or ((cmf shr 4)>7) or ((flg and $20)<>0) then begin
exit;
end;
a32:=(TpvUInt8(Source[aInLen-4]) shl 24) or (TpvUInt8(Source[aInLen-3]) shl 16) or (TpvUInt8(Source[aInLen-2]) shl 8) or (TpvUInt8(Source[aInLen-1]) shl 0);
inc(Source,2);
dec(aInLen,6);
SourceEnd:=@Source[aInLen];
result:=Uncompress;
if not result then begin
exit;
end;
result:=Adler32(aDestData,aDestLen)=a32;
end;
function UncompressDirect:boolean;
begin
Source:=aInData;
SourceEnd:=@Source[aInLen];
result:=Uncompress;
end;
begin
aDestData:=nil;
LengthBits:=nil;
DistanceBits:=nil;
LengthBase:=nil;
DistanceBase:=nil;
SymbolLengthTree:=nil;
DistanceTree:=nil;
FixedSymbolLengthTree:=nil;
FixedDistanceTree:=nil;
try
New(LengthBits);
New(DistanceBits);
New(LengthBase);
New(DistanceBase);
New(SymbolLengthTree);
New(DistanceTree);
New(FixedSymbolLengthTree);
New(FixedDistanceTree);
try
begin
FillChar(LengthBits^,sizeof(TBits),TpvRawByteChar(#0));
FillChar(DistanceBits^,sizeof(TBits),TpvRawByteChar(#0));
FillChar(LengthBase^,sizeof(TBase),TpvRawByteChar(#0));
FillChar(DistanceBase^,sizeof(TBase),TpvRawByteChar(#0));
FillChar(SymbolLengthTree^,sizeof(TTree),TpvRawByteChar(#0));
FillChar(DistanceTree^,sizeof(TTree),TpvRawByteChar(#0));
FillChar(FixedSymbolLengthTree^,sizeof(TTree),TpvRawByteChar(#0));
FillChar(FixedDistanceTree^,sizeof(TTree),TpvRawByteChar(#0));
end;
begin
BuildFixedTrees(FixedSymbolLengthTree^,FixedDistanceTree^);
BuildBitsBase(PpvRawByteChar(TpvPointer(@LengthBits^[0])),pword(TpvPointer(@LengthBase^[0])),4,3);
BuildBitsBase(PpvRawByteChar(TpvPointer(@DistanceBits^[0])),pword(TpvPointer(@DistanceBase^[0])),2,1);
LengthBits^[28]:=0;
LengthBase^[28]:=258;
end;
begin
GetMem(aDestData,4096);
DestSize:=4096;
Dest:=aDestData;
aDestLen:=0;
if aParseHeader then begin
result:=UncompressZLIB;
end else begin
result:=UncompressDirect;
end;
if result then begin
ReAllocMem(aDestData,aDestLen);
end else if assigned(aDestData) then begin
FreeMem(aDestData);
aDestData:=nil;
end;
end;
finally
if assigned(LengthBits) then begin
Dispose(LengthBits);
end;
if assigned(DistanceBits) then begin
Dispose(DistanceBits);
end;
if assigned(LengthBase) then begin
Dispose(LengthBase);
end;
if assigned(DistanceBase) then begin
Dispose(DistanceBase);
end;
if assigned(SymbolLengthTree) then begin
Dispose(SymbolLengthTree);
end;
if assigned(DistanceTree) then begin
Dispose(DistanceTree);
end;
if assigned(FixedSymbolLengthTree) then begin
Dispose(FixedSymbolLengthTree);
end;
if assigned(FixedDistanceTree) then begin
Dispose(FixedDistanceTree);
end;
end;
except
result:=false;
end;
end;
{$ifend}
{$if not (defined(fpc) and (defined(Linux) or defined(Android)))}
initialization
InitializeLookUpTables;
{$ifend}
end.
|
program HelloWorld;
uses
App, MsgBox;
var
MyApp: TApplication;
begin
MyApp.Init;
MessageBox('Hello, World!', nil, mfOkButton);
MyApp.Done;
end.
|
unit UMyBackupEventInfo;
interface
uses SysUtils;
type
TBackupCompletedEventParam = record
public
PcID, SourcePath : string;
IsFile : Boolean;
FileCount : Integer;
FileSpce : Int64;
end;
// 网络备份 事件
NetworkBackupEvent = class
public
class procedure BackupCompleted( Params : TBackupCompletedEventParam );
class procedure RemoveBackupItem( PcID, SourcePath : string );
end;
TLocalBackupEventParam = record
public
DesPath, SourcePath : string;
IsFile : Boolean;
FileCount : Integer;
FileSpce : Int64;
end;
// 本地备份 事件
LocalBackupEvent = class
public
class procedure AddDesPath( DesPath : string );
class procedure RemoveDesPath( DesPath : string );
public
class procedure BackupCompleted( Params : TLocalBackupEventParam );
class procedure RemoveBackupItem( DesPath, SourcePath : string );
end;
implementation
uses UMyClient, UMyNetPcInfo, UMyRestoreApiInfo;
{ NetworkBackupMsgEvent }
class procedure NetworkBackupEvent.BackupCompleted(Params : TBackupCompletedEventParam);
var
NetworkBackupAddMsg : TNetworkBackupAddCloudMsg;
begin
NetworkBackupAddMsg := TNetworkBackupAddCloudMsg.Create;
NetworkBackupAddMsg.SetPcID( PcInfo.PcID );
NetworkBackupAddMsg.SetBackupPath( Params.SourcePath );
NetworkBackupAddMsg.SetIsFile( Params.IsFile );
NetworkBackupAddMsg.SetSpaceInfo( Params.FileCount, Params.FileSpce );
NetworkBackupAddMsg.SetLastBackupTime( Now );
MyClient.SendMsgToPc( Params.PcID, NetworkBackupAddMsg );
end;
class procedure NetworkBackupEvent.RemoveBackupItem(PcID,
SourcePath: string);
var
NetworkBackupRemoveMsg : TNetworkBackupRemoveCloudMsg;
begin
NetworkBackupRemoveMsg := TNetworkBackupRemoveCloudMsg.Create;
NetworkBackupRemoveMsg.SetPcID( PcInfo.PcID );
NetworkBackupRemoveMsg.SetBackupPath( SourcePath );
MyClient.SendMsgToPc( PcID, NetworkBackupRemoveMsg );
end;
{ LocalBackupEventInfo }
class procedure LocalBackupEvent.AddDesPath(DesPath: string);
begin
LocalRestoreAppApi.AddRestoreDes( DesPath );
end;
class procedure LocalBackupEvent.BackupCompleted(
Params: TLocalBackupEventParam);
var
RestoreParams : TLocalRestoreAddParams;
begin
RestoreParams.DesPath := Params.DesPath;
RestoreParams.BackupPath := Params.SourcePath;
RestoreParams.IsFile := Params.IsFile;
RestoreParams.FileCount := Params.FileCount;
RestoreParams.ItemSize := Params.FileSpce;
RestoreParams.LastBackupTime := Now;
LocalRestoreAppApi.AddBackupItem( RestoreParams );
end;
class procedure LocalBackupEvent.RemoveBackupItem(DesPath,
SourcePath: string);
begin
LocalRestoreAppApi.RemoveBackupItem( DesPath, SourcePath );
end;
class procedure LocalBackupEvent.RemoveDesPath(DesPath: string);
begin
LocalRestoreAppApi.RemoveRestoreDes( DesPath );
end;
end.
|
unit uOperationsTest;
interface
uses
DUnitX.TestFramework,
uOperations;
type
[TestFixture]
TOperationsTest = class(TObject)
private
FOperations: TOperations;
public
[Setup]
procedure Setup;
[TearDown]
procedure TearDown;
[Test]
[TestCase('SortLetters','woodcutter,cdeoorttuw')]
[TestCase('SortLetters','Nice,ceiN')]
procedure TestSortLetters(Const pWord, pExpected: string);
[Test]
[TestCase('CountOccurrencesOk','Everybody,e,2')]
[TestCase('CountOccurrencesOk2','Everybody,Y,2')]
procedure TestCountOccurrences(Const pWord, pLetter: string; const pExpected: integer);
[Test]
[TestCase('CountOccurrencesWordEmpty',',e')]
procedure TestCountOccurrencesWordEmpty(Const pWord, pLetter: string);
[Test]
[TestCase('CountOccurrencesLetterEmpty','Everybody,')]
procedure TestCountOccurrencesLetterEmpty(Const pWord, pLetter: string);
[Test]
[TestCase('CountOccurrencesLetterEmpty','João,Joao')]
[TestCase('CountOccurrencesLetterEmpty','André,Andre')]
procedure TestRemoveAccents(Const pWord, pExpected: string);
[Test]
[TestCase('CountOccurrencesLetterEmpty','Jo@o')]
procedure TestRemoveAccentsNoAlphaNumeric(Const pWord: string);
end;
implementation
procedure TOperationsTest.Setup;
begin
FOperations := TOperations.Create;
end;
procedure TOperationsTest.TearDown;
begin
FOperations.Free;
end;
procedure TOperationsTest.TestCountOccurrences(const pWord, pLetter: string;
const pExpected: integer);
var
vResult: integer;
begin
vResult := FOperations.CountOccurrences(pWord, pLetter);
Assert.AreEqual(pExpected,vResult);
end;
procedure TOperationsTest.TestCountOccurrencesLetterEmpty(const pWord,
pLetter: string);
begin
Assert.WillRaise(
procedure
begin
FOperations.CountOccurrences(pWord, pLetter);
end,
ELetterIsEmpty
);
end;
procedure TOperationsTest.TestCountOccurrencesWordEmpty(const pWord,
pLetter: string);
begin
Assert.WillRaise(
procedure
begin
FOperations.CountOccurrences(pWord, pLetter);
end,
EWordIsEmpty
);
end;
procedure TOperationsTest.TestRemoveAccents(const pWord, pExpected: string);
var
vResult: string;
begin
vResult := FOperations.RemoveAccents(pWord);
Assert.AreEqual(pExpected,vResult);
end;
procedure TOperationsTest.TestRemoveAccentsNoAlphaNumeric(const pWord: string);
begin
Assert.WillRaise(
procedure
begin
FOperations.RemoveAccents(pWord);
end,
ENoAlphaNumeric
);
end;
procedure TOperationsTest.TestSortLetters(const pWord, pExpected: string);
var
vResult: string;
begin
vResult := FOperations.SortLetters(pWord);
Assert.AreEqual(pExpected,vResult);
end;
initialization
TDUnitX.RegisterTestFixture(TOperationsTest);
end.
|
unit LuaProgressBar;
{$mode delphi}
interface
uses
Classes, SysUtils, lua, lualib, lauxlib, LuaHandler, ceguicomponents,
pluginexports, controls, ComCtrls, betterControls;
procedure initializeLuaProgressBar;
implementation
uses luaclass, LuaWinControl;
function createProgressBar(L: Plua_State): integer; cdecl;
var
ProgressBar: TProgressBar;
parameters: integer;
owner: TWincontrol;
begin
result:=0;
parameters:=lua_gettop(L);
if parameters>=1 then
owner:=lua_toceuserdata(L, -parameters)
else
owner:=nil;
lua_pop(L, lua_gettop(L));
ProgressBar:=TProgressBar.Create(owner);
if owner<>nil then
ProgressBar.Parent:=owner;
luaclass_newClass(L, ProgressBar);
result:=1;
end;
function progressbar_stepIt(L: Plua_State): integer; cdecl;
var progressbar: TCustomProgressBar;
begin
result:=0;
progressbar:=luaclass_getClassObject(L);
progressbar.StepIt;
end;
function progressbar_stepBy(L: Plua_State): integer; cdecl;
var
progressbar: TCustomProgressBar;
begin
result:=0;
progressbar:=luaclass_getClassObject(L);
if lua_gettop(L)>=1 then
progressbar.StepBy(lua_tointeger(L, -1));
end;
function progressbar_getMax(L: PLua_State): integer; cdecl;
var
progressbar: Tcustomprogressbar;
begin
progressbar:=luaclass_getClassObject(L);
lua_pushinteger(L, progressbar.Max);
result:=1;
end;
function progressbar_setMax(L: PLua_State): integer; cdecl;
var
progressbar: Tcustomprogressbar;
begin
result:=0;
progressbar:=luaclass_getClassObject(L);
if lua_gettop(l)>=1 then
progressbar.max:=lua_tointeger(L, -1);
end;
function progressbar_getMin(L: PLua_State): integer; cdecl;
var
progressbar: Tcustomprogressbar;
begin
progressbar:=luaclass_getClassObject(L);
lua_pushinteger(L, progressbar.Min);
result:=1;
end;
function progressbar_setMin(L: PLua_State): integer; cdecl;
var
progressbar: Tcustomprogressbar;
begin
result:=0;
progressbar:=luaclass_getClassObject(L);
if lua_gettop(l)>=1 then
progressbar.Min:=lua_tointeger(L, -1);
end;
function progressbar_getPosition(L: PLua_State): integer; cdecl;
var
progressbar: Tcustomprogressbar;
begin
progressbar:=luaclass_getClassObject(L);
lua_pushinteger(L, progressbar.Position);
result:=1;
end;
function progressbar_setPosition(L: PLua_State): integer; cdecl;
var
progressbar: Tcustomprogressbar;
begin
result:=0;
progressbar:=luaclass_getClassObject(L);
if lua_gettop(l)>=1 then
progressbar.Position:=lua_tointeger(L, -1);
end;
function progressbar_setPosition2(L: PLua_State): integer; cdecl;
var
progressbar: Tcustomprogressbar;
newPos: integer;
begin
result:=0;
progressbar:=luaclass_getClassObject(L);
if lua_gettop(l)>=1 then
begin
newPos:=lua_tointeger(L, -1);
if newPos>progressbar.Position then
begin
if newPos=progressbar.Max then
begin
progressbar.Max:=progressbar.Max+1;
progressbar.Position:=newPos+1;
progressbar.Position:=newPos;
progressbar.Max:=progressbar.Max-1;
end
else
begin
progressbar.Position:=newPos+1;
progressbar.Position:=newPos;
end;
end
else
progressbar.Position:=newPos;
end;
end;
procedure progressbar_addMetaData(L: PLua_state; metatable: integer; userdata: integer );
begin
wincontrol_addMetaData(L, metatable, userdata);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'stepIt', progressbar_stepIt);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'stepBy', progressbar_stepBy);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'getMax', progressbar_getMax);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'setMax', progressbar_setMax);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'getMin', progressbar_getMin);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'setMin', progressbar_setMin);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'getPosition', progressbar_getPosition);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'setPosition', progressbar_setPosition);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'setPosition2', progressbar_setPosition2); // without slow progress animation on win7 and later
luaclass_addPropertyToTable(L, metatable, userdata, 'Min', progressbar_getMin, progressbar_setMin);
luaclass_addPropertyToTable(L, metatable, userdata, 'Max', progressbar_getMax, progressbar_setMax);
luaclass_addPropertyToTable(L, metatable, userdata, 'Position', progressbar_getPosition, progressbar_setPosition);
end;
procedure initializeLuaProgressBar;
begin
lua_register(LuaVM, 'createProgressBar', createProgressBar);
lua_register(LuaVM, 'progressbar_stepIt', progressbar_stepIt);
lua_register(LuaVM, 'progressbar_stepBy', progressbar_stepBy);
lua_register(LuaVM, 'progressbar_getMax', progressbar_getMax);
lua_register(LuaVM, 'progressbar_setMax', progressbar_setMax);
lua_register(LuaVM, 'progressbar_getMin', progressbar_getMin);
lua_register(LuaVM, 'progressbar_setMin', progressbar_setMin);
lua_register(LuaVM, 'progressbar_getPosition', progressbar_getPosition);
lua_register(LuaVM, 'progressbar_setPosition', progressbar_setPosition);
end;
initialization
luaclass_register(TCustomProgressBar, progressbar_addMetaData);
end.
|
unit TimerOne;
{
仿Cena的评测计时、内存检测模块
在Cena的基础上略有修改
Martian 2010年12月4日
}
interface
uses
Windows,PsAPI,SysUtils;
type
TSystem_Performance_Information= packed record
liIdleTime: LARGE_INTEGER;
dwSpare:array[0..75] of DWORD;
end;
ReturnResult=record
Status:Integer;
Time:Double;
Information:Cardinal;
Memory:Integer;
end;
CheckLimitResult=record
Status:Integer;
Time:Double;
Memory:Integer;
end;
const
ST_UNKNOWN = 0 ; // 未知
ST_OK = 1 ; // 正常
ST_CANNOT_EXECUTE = 2 ; // 无法运行
ST_TIME_LIMIT_EXCEEDED = 3 ; // 超时
ST_MEMORY_LIMIT_EXCEEDED = 4 ; // 超内存
ST_RUNTIME_ERROR = 5 ; // 运行时错误
ST_CRASH = 6 ; // 崩溃
//SystemPerformanceInformation = 2;
var
//LastIdleTime:Int64;
ProcessRunning:Boolean;
JudgeFaster:Boolean;
function Exec(Cmd:string;TimeLimit:Cardinal{限制时间 单位毫秒};MemoryLimit:Integer{限制内存 单位kb};JudgeFasterA:Boolean):ReturnResult;
implementation
function NtQuerySystemInformation(infoClass: DWORD; buffer: Pointer;
bufSize: DWORD; returnSize: PDword):DWORD; stdcall external 'ntdll.dll';
function CheckLimits(var pi:PROCESS_INFORMATION;TimeLimit:Cardinal{限制时间 单位毫秒};MemoryLimit:Integer{限制内存 单位kb}):CheckLimitResult;
var
ct,et,kt,ut,ut2:FILETIME;
Time:Double;
TimeLimitMax:Double; //限制时间(s) TimeLimit换算成秒以后*3
pmc:_PROCESS_MEMORY_COUNTERS;
begin
Result.Status:=ST_OK;
Result.Time:=0;
Result.Memory:=0;
GetProcessTimes(pi.hProcess,ct,et,kt,ut); //获取进程的时间 仅需要UserTime 用户时间
ut2:=ut; //因为Int64(ut)会修改指针 所以备份一遍
{
Cena的计时模式的研究:
运行程序过程中,用户时间减去启动进程到进程满载的CPU空闲时间
如果程序执行完毕以后没有超时,则加紧要求,直接使用用户时间
感觉多此一举
所以以下代码仅使用UserTime 暂时不考虑CPU空闲时间
——Martian 2010年12月4日
}
if JudgeFaster then
TimeLimitMax:=TimeLimit/1000 //最长执行时间
else
TimeLimitMax:=(TimeLimit/1000)*2;
if {Final}True then
begin
Time:=trunc((int64(ut))/10000)/1000;
end;{ else
begin
Time:=(int64(ut)+GetIdleTime-LastIdleTime)/10000000;
Form1.lbl2.Caption:=FloatToStr(Time);
end;}
//16bit程序无法获取内存 Cena中进行了判断
//但是现在的新版编译器均不再编译16BIT程序 所以可以直接取内存
try
ZeroMemory(@pmc,sizeof(pmc));
pmc.cb:=sizeof(pmc);
GetProcessMemoryInfo(pi.hProcess,@pmc,sizeof(pmc));
Result.Memory:=pmc.PeakPagefileUsage shr 10;
if Result.Memory>MemoryLimit then begin
{ 超出内存限制 }
Result.Time:=-1;
Result.Status:=ST_MEMORY_LIMIT_EXCEEDED;
TerminateProcess(pi.hProcess,1);
Exit;
end;
except
Result.Memory:=-1;
end;
Result.Time:=Time;
if Time>TimeLimit/1000 then
begin
Result.Status:=ST_TIME_LIMIT_EXCEEDED;
{ 超过时间限制 }
end;
if Time>TimeLimitMax then
begin
Result.Status:=ST_TIME_LIMIT_EXCEEDED;
Result.Time:=-1;
TerminateProcess(pi.hProcess,1);
{ 超过限制时间三倍 返回 同时结束进程 }
end;
end;
function ExtractFilePath(const FileName: string): string;
var
I: Integer;
begin
I := LastDelimiter(PathDelim + DriveDelim, FileName);
Result := Copy(FileName, 1, I);
end;
function Exec(Cmd:AnsiString;TimeLimit:Cardinal{限制时间 单位毫秒};MemoryLimit:Integer{限制内存 单位kb};JudgeFasterA:Boolean{是否启用快速评测}):ReturnResult;
var
si:STARTUPINFO;
pi:PROCESS_INFORMATION;
ok:boolean;
de:_DEBUG_EVENT;
CheckLimitResultA:CheckLimitResult;
ExceptionInfo:String;
WorkPath:string;
begin
FillChar(si,SizeOf(si),0);
ProcessRunning:=False;
Result.Status:=ST_UNKNOWN;
Result.Time:=0;
Result.Information:=0;
JudgeFaster:=JudgeFasterA;
with si do
begin
cb:=sizeof(si);
dwFlags:=STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW;
//dwFlags:=STARTF_USESHOWWINDOW;
wShowWindow:=SW_HIDE;
hStdOutput := 0;
hStdInput := 0;
hStdError := 0;
end;
WorkPath:=ExtractFilePath(Cmd);
//以下代码均修改自Cena源程序
ok:=CreateProcess(nil,PChar(Cmd),nil,nil,True,DEBUG_PROCESS or DEBUG_ONLY_THIS_PROCESS or CREATE_NEW_CONSOLE,nil,PChar(WorkPath),si,pi);
if ok then
begin
ProcessRunning:=True;
{LastIdleTime:=GetIdleTime;}
Repeat
while WaitForDebugEvent(de,1) do
begin
ContinueDebugEvent(de.dwProcessId,de.dwThreadId,DBG_CONTINUE);
case de.dwDebugEventCode of
EXCEPTION_DEBUG_EVENT:
begin
case de.Exception.ExceptionRecord.ExceptionCode of
{STATUS_ACCESS_VIOLATION, STATUS_ILLEGAL_INSTRUCTION, STATUS_NO_MEMORY
STATUS_IN_PAGE_ERROR, STATUS_INVALID_HANDLE, STATUS_PRIVILEGED_INSTRUCTION: // !!! any other possible statuses?
begin
Result.Status:=ST_CRASH_A;
Result.Time:=0;
Result.Information:=de.Exception.ExceptionRecord.ExceptionCode;
TerminateProcess(pi.hProcess,de.Exception.ExceptionRecord.ExceptionCode);
end; }
{STATUS_FLOAT_DIVIDE_BY_ZERO, STATUS_INTEGER_OVERFLOW,
STATUS_FLOAT_OVERFLOW, STATUS_STACK_OVERFLOW, STATUS_INTEGER_DIVIDE_BY_ZERO:
begin
Result.Status:=ST_CRASH_B;
Result.Information:=de.Exception.ExceptionRecord.ExceptionCode;
TerminateProcess(pi.hProcess,de.Exception.ExceptionRecord.ExceptionCode);
end; }
STATUS_BREAKPOINT:; {Every program will have a breakpoint at starting}
STATUS_SEGMENT_NOTIFICATION:; {only 16bit DOS want this}
else begin
Result.Status:=ST_CRASH;
Result.Time:=0;
Result.Information:=de.Exception.ExceptionRecord.ExceptionCode;
//经过测试直接传String无法得到值,只能传Cardinal
TerminateProcess(pi.hProcess,de.Exception.ExceptionRecord.ExceptionCode);
{
删掉原Cena的判崩溃方式
除STATUS_BREAKPOINT与STATUS_SEGMENT_NOTIFICATION均统一响应
}
end;
end;
end;
CREATE_THREAD_DEBUG_EVENT:;
CREATE_PROCESS_DEBUG_EVENT: CloseHandle(de.CreateProcessInfo.hFile);
EXIT_THREAD_DEBUG_EVENT:;
EXIT_PROCESS_DEBUG_EVENT:
begin
if de.dwProcessId=pi.dwProcessId then begin
if Result.Status=ST_UNKNOWN then
Result.Status:=ST_OK;
{
这里有两种情况:
一、正常结束
二、编译器已经处理一些错误,比如数组下溢,以致程序不崩溃,然后结束程序
}
Result.Information:=de.ExitProcess.dwExitCode; //详细说明参见该模块文档的“补充说明”部分
ProcessRunning:=False;
end;
end;
LOAD_DLL_DEBUG_EVENT:CloseHandle(de.LoadDll.hFile);
UNLOAD_DLL_DEBUG_EVENT:;
OUTPUT_DEBUG_STRING_EVENT:;
RIP_EVENT:;
end;
if not ProcessRunning then Break;
end;
if not ProcessRunning then break;
CheckLimitResultA:=CheckLimits(pi,TimeLimit,MemoryLimit);
Result.Status:=CheckLimitResultA.Status;
Result.Time:=CheckLimitResultA.Time;
Result.Memory:=CheckLimitResultA.Memory;
until not ProcessRunning;
end else begin
Result.Status:=ST_CANNOT_EXECUTE;
Result.Time:=0;
Result.Information:=0;
Result.Memory:=0;
end;
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
end;
end.
|
unit FrmDBConfig;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ADODB, FrmQueryDevices;
const
//DataIndex
csIniDBIp = 'DBIp';
csIniDBPort = 'DBPort';
csIniDBName = 'DBName';
csIniDBUsername= 'DBUserName';
csIniDBPassword= 'DBPassword';
CS_EncryptKey = '11E246A';
type
TDBConfigForm = class(TForm)
img1: TImage;
Label21: TLabel;
cbbServerName: TComboBox;
Label23: TLabel;
edtLoginName: TEdit;
Label24: TLabel;
edtPassword: TEdit;
Label22: TLabel;
cbbDBName: TComboBox;
btnTestCon: TButton;
Label1: TLabel;
edtPort: TEdit;
lbl1: TLabel;
btnOk: TButton;
procedure btnTestConClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure cbbDBNameDropDown(Sender: TObject);
procedure cbbServerNameDropDown(Sender: TObject);
procedure btnOkClick(Sender: TObject);
private
{ Private declarations }
FOwner: TQueryDevicesForm;
protected
procedure CreateParams(var Params: TCreateParams); override;
public
{ Public declarations }
MainFrmHandle: Cardinal;
procedure LoadSetting;
procedure SaveSetting;
class function DisplayOutForm(AMainForm: TQueryDevicesForm): Boolean;
constructor Create(AMainForm: TQueryDevicesForm); reintroduce;
end;
procedure ReadDBConfigFromIni;
procedure SaveDBConfigToIni;
implementation
uses
Math, DateUtils, uDBInf, ComObj, IniFiles, uSimpleEncrypt;
{$R *.dfm}
procedure ReadDBConfigFromIni;
var
iniSet: TIniFile;
sFileName, sDBPassword: string;
i:Integer;
begin
sFileName := ExtractFilePath(ParamStr(0)) + 'Option.ini';
iniSet := TIniFile.Create(sFileName);
try
gDBInterface.DBName := iniSet.ReadString('SystemConfig','DatabaseName','');
gDBInterface.DBUserName := iniSet.ReadString('SystemConfig','UserName','');
sDBPassword := iniSet.ReadString('SystemConfig','Password','');
gDBInterface.DBPassword := DecryStrHex(sDBPassword, CS_EncryptKey);
gDBInterface.DBServer := iniSet.ReadString('SystemConfig','Server','');
gDBInterface.DBPort := iniSet.ReadInteger('SystemConfig','Port',1433);
finally
iniSet.Free;
end;
end;
procedure SaveDBConfigToIni;
var
iniSet: TIniFile;
sFileName: string;
begin
sFileName := ExtractFilePath(ParamStr(0)) + 'Option.ini';
iniSet := TIniFile.Create(sFileName);
try
iniSet.WriteString('SystemConfig','DatabaseName',gDBInterface.DBName);
iniSet.WriteString('SystemConfig','UserName',gDBInterface.DBUserName);
iniSet.WriteString('SystemConfig','Password', EncryStrHex(Trim(gDBInterface.DBPassword), CS_EncryptKey));
iniSet.WriteString('SystemConfig','Server',gDBInterface.DBServer);
iniSet.WriteInteger('SystemConfig','Port',gDBInterface.DBPort);
finally
iniSet.Free;
end;
end;
procedure GetServerList(Names: TStrings);
var
SQLServer: Variant;
ServerList: Variant;
i, nServers: integer;
begin
Names.Clear;
SQLServer := CreateOleObject('SQLDMO.Application');
ServerList := SQLServer.ListAvailableSQLServers;
nServers := ServerList.Count;
for i := 1 to nServers do
begin
Names.Add(ServerList.Item(i));
end;
VarClear(SQLServer);
VarClear(serverList);
end;
procedure GetAllDBName(const AConnetStr: string; Names: TStrings);
var
adoCon: TADOConnection;
adoReset: TADODataSet;
begin
adoCon := TADOConnection.Create(nil);
adoReset := TADODataSet.Create(nil);
try
try
adoCon.LoginPrompt := False;
adoCon.ConnectionString := AConnetStr;
adoCon.Connected := True;
adoReset.Connection := adoCon;
adoReset.CommandText := 'use master;Select name From sysdatabases';
adoReset.CommandType := cmdText;
adoReset.Open;
Names.BeginUpdate;
Names.Clear;
while not adoReset.Eof do
begin
Names.Add(adoReset.FieldByName('name').AsString);
adoReset.Next;
end;
Names.EndUpdate;
except
on e:Exception do
begin
{$IFDEF _Log}
WriteLogMsg(ltError,Format('%s,HAPPEN AT GetAllDBName',[e.Message]));
{$ENDIF}
raise;
end;
end;
finally
adoReset.Close;
FreeAndNil(adoReset);
FreeAndNil(adoCon);
end;
end;
procedure TDBConfigForm.LoadSetting();
begin
cbbServerName.Text:= gDBInterface.DBServer;
edtPort.Text := IntToStr(gDBInterface.DBPort);
cbbDBName.Text:= gDBInterface.DBName;
edtLoginName.Text:= gDBInterface.DBUsername;
edtPassword.Text:= gDBInterface.DBPassword;
end;
procedure TDBConfigForm.SaveSetting();
begin
gDBInterface.DBServer:= cbbServerName.Text;
gDBInterface.DBPort:= StrToIntDef(edtPort.Text, 1433);
gDBInterface.DBName:= cbbDBName.Text;
gDBInterface.DBUsername:= edtLoginName.Text;
gDBInterface.DBPassword:= edtPassword.Text;
end;
procedure TDBConfigForm.btnTestConClick(Sender: TObject);
var
AdoCon: TADOConnection;
begin
AdoCon := TADOConnection.Create(nil);
try
try
AdoCon.LoginPrompt := False;
AdoCon.ConnectionString := Format(CSSQLConnectionString, [cbbServerName.Text,
edtPort.Text, cbbDBName.Text, edtLoginName.Text, edtPassword.Text]);
AdoCon.Connected := True;
MessageDlg('Connect to ' + cbbServerName.Text + ' Successfully!', mtInformation,[mbOk], 0);
except
on e:Exception do
MessageDlg('Unable to Connect to server ' + cbbServerName.Text + ':' + cbbDBName.Text + #13#10#13#10
+ e.Message, mtError,[mbOk], 0);
end;
finally
FreeAndNil(AdoCon);
end;
end;
procedure TDBConfigForm.FormCreate(Sender: TObject);
begin
LoadSetting;
end;
procedure TDBConfigForm.cbbDBNameDropDown(Sender: TObject);
var
sConStr: string;
begin
Screen.Cursor:= crHourGlass;
try
try
sConStr := Format(CSSQLConnectionString, [cbbServerName.Text,
edtPort.Text, cbbDBName.Text, edtLoginName.Text, edtPassword.Text]);
GetAllDBName(sConStr, cbbDBName.Items);
except
on e:Exception do
MessageDlg('Unable to Connect to server ' + cbbServerName.Text + #13#10#13#10
+ e.Message, mtError,[mbOk], 0);
end;
finally
Screen.Cursor:= crDefault;
end;
end;
procedure TDBConfigForm.cbbServerNameDropDown(Sender: TObject);
begin
Screen.Cursor:= crHourGlass;
try
try
GetServerList(cbbServerName.Items);
except
;
end;
finally
Screen.Cursor:= crDefault;
end;
end;
procedure TDBConfigForm.btnOkClick(Sender: TObject);
begin
SaveSetting;
ModalResult := mrOk;
end;
class function TDBConfigForm.DisplayOutForm(AMainForm: TQueryDevicesForm): Boolean;
var
DBConfigForm: TDBConfigForm;
begin
DBConfigForm := TDBConfigForm.Create(AMainForm);
try
Result := (DBConfigForm.ShowModal = mrOk);
finally
if Assigned(DBConfigForm) then
FreeAndNil(DBConfigForm);
end;
end;
procedure TDBConfigForm.CreateParams(var Params: TCreateParams);
begin
inherited;
Params.WndParent := FOwner.Handle;
end;
constructor TDBConfigForm.Create(AMainForm: TQueryDevicesForm);
begin
FOwner := AMainForm;
inherited Create(Application);
end;
end.
|
unit SetupSpec;
// ---------------------------------------------
// CHART - Setup dialog box for special channels
// ---------------------------------------------
// 20.5.03
// 21.12.11
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, ValEdit, ValidatedEdit, math ;
type
TSetupSpeFrm = class(TForm)
RMSGroup: TGroupBox;
Label3: TLabel;
Label13: TLabel;
Label14: TLabel;
cbRMSFromChannel: TComboBox;
cbRMSToChannel: TComboBox;
ckRMSInUse: TCheckBox;
edRMSNumPoints: TValidatedEdit;
HeartrateGrp: TGroupBox;
Label15: TLabel;
Label16: TLabel;
Label18: TLabel;
Label17: TLabel;
ckHRinUse: TCheckBox;
cbHRFromChannel: TComboBox;
cbHRToChannel: TComboBox;
RadioGroup1: TRadioGroup;
rbDisplayRR: TRadioButton;
rbDisplayHR: TRadioButton;
edHRMaxScale: TValidatedEdit;
edHRThreshold: TValidatedEdit;
bOK: TButton;
Button1: TButton;
procedure FormShow(Sender: TObject);
procedure bOKClick(Sender: TObject);
procedure rbDisplayHRClick(Sender: TObject);
procedure rbDisplayRRClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
SetupSpeFrm: TSetupSpeFrm;
implementation
uses shared , Main;
{$R *.DFM}
procedure TSetupSpeFrm.FormShow(Sender: TObject);
{ ---------------------------------------------------------------------------
Initialise setup's combo lists and tables with current recording parameters
---------------------------------------------------------------------------}
var
ch : Integer ;
begin
{ RMS processor }
cbRMSFromChannel.clear ;
for ch := 0 to MainFrm.ADCNumChannels-1 do
cbRMSFromChannel.items.add(format('Ch.%d %s',[ch,MainFrm.ADCChannelName[ch]])) ;
cbRMSToChannel.items := cbRMSFromChannel.items ;
cbHRFromChannel.items := cbRMSFromChannel.items ;
cbHRToChannel.items := cbRMSFromChannel.items ;
ckRMSInUse.checked := MainFrm.RMS.InUse ;
cbRMSFromChannel.itemindex := MainFrm.RMS.FromChannel ;
cbRMSToChannel.itemindex := MainFrm.RMS.ToChannel ;
edRMSNumPoints.value := MainFrm.RMS.NumAverage ;
{ Heart rate processor }
ckHRInUse.checked := MainFrm.HR.InUse ;
cbHRFromChannel.itemindex := MainFrm.HR.FromChannel ;
cbHRToChannel.itemindex := MainFrm.HR.ToChannel ;
{ Heartbeat detection threshold }
edHRThreshold.Value := MainFrm.HR.PercentageThreshold ;
{ Set display mode radio buttons and scale maximum}
if MainFrm.HR.DisplayHR then begin
rbDisplayHR.checked := True ;
edHRMaxScale.Units := 'bpm' ;
end
else begin
rbDisplayRR.checked := True ;
edHRMaxScale.Units := 's' ;
end ;
edHRMaxScale.Value := MainFrm.HR.MaxScale ;
end ;
procedure TSetupSpeFrm.bOKClick(Sender: TObject);
var
ch : Integer ;
begin
MainFrm.RMS.FromChannel := cbRMSFromChannel.itemindex ;
MainFrm.RMS.ToChannel := cbRMSToChannel.itemindex ;
MainFrm.RMS.NumAverage := Round(edRMSNumPoints.value) ;
MainFrm.RMS.InUse := ckRMSInUse.checked ;
if MainFrm.ADCNumChannels <= 1 then begin
{ If only one channel disable RMS calculation }
MainFrm.RMS.InUse := False ;
ckRMSInUse.checked := False ;
end ;
if MainFrm.RMS.InUse then begin
//MainFrm.Channel[MainFrm.RMS.ToChannel] := MainFrm.Channel[MainFrm.RMS.FromChannel] ;
MainFrm.ADCChannelName[MainFrm.RMS.ToChannel] := 'RMS' ;
end
else if MainFrm.ADCChannelName[MainFrm.RMS.ToChannel] = 'RMS' then begin
{ If channel has been used for RMS result, remove RMS title }
MainFrm.ADCChannelName[MainFrm.RMS.ToChannel] :=
'Ch.' + IntToStr(MainFrm.RMS.ToChannel) ;
end ;
{ Heart rate processor }
MainFrm.HR.FromChannel := cbHRFromChannel.itemindex ;
MainFrm.HR.ToChannel := cbHRToChannel.itemindex ;
MainFrm.HR.InUse := ckHRInUse.checked ;
if MainFrm.ADCNumChannels <= 1 then begin
{ If only one channel disable RMS calculation }
MainFrm.HR.InUse := False ;
ckHRInUse.checked := False ;
end ;
MainFrm.HR.PercentageThreshold := ExtractFloat(edHRThreshold.text,50.0);
if rbDisplayHR.checked then MainFrm.HR.DisplayHR := True
else MainFrm.HR.DisplayHR := False ;
MainFrm.HR.MaxScale := ExtractFloat( edHRMaxScale.text, MainFrm.HR.MaxScale ) ;
if MainFrm.HR.InUse then begin
if MainFrm.HR.DisplayHR then begin
MainFrm.HR.Scale := (60.*MainFrm.ADCMaxValue) / ( MainFrm.HR.MaxScale * MainFrm.ADCSamplingInterval ) ;
MainFrm.ADCChannelUnits[MainFrm.HR.ToChannel] := 'bpm' ;
MainFrm.ADCChannelName[MainFrm.HR.ToChannel] := 'H.R.' ;
end
else begin
MainFrm.HR.Scale := MainFrm.scDisplay.MaxADCValue*MainFrm.ADCSamplingInterval / MainFrm.HR.MaxScale ;
MainFrm.ADCChannelUnits[MainFrm.HR.ToChannel] := 's' ;
MainFrm.ADCChannelName[MainFrm.HR.ToChannel] := 'R-R' ;
end ;
MainFrm.ADCChannelScale[MainFrm.HR.ToChannel] := MainFrm.HR.MaxScale / Max(MainFrm.ADCMaxValue,1) ;
MainFrm.ADCChannelGain[MainFrm.HR.ToChannel] := 1. ;
MainFrm.ADCChannelVoltsPerUnit[MainFrm.HR.ToChannel] := MainFrm.ADCChannelVoltageRange[MainFrm.HR.ToChannel] /
(MainFrm.ADCChannelScale[MainFrm.HR.ToChannel]*
MainFrm.ADCChannelGain[MainFrm.HR.ToChannel]*
(MainFrm.ADCMaxValue+1)) ;
MainFrm.ADCChannelZero[MainFrm.HR.ToChannel] := 0 ;
end
else if MainFrm.ADCChannelName[MainFrm.HR.ToChannel] = 'H.R.' then
{ If channel has been used for HR result, remove HR title }
MainFrm.ADCChannelName[MainFrm.HR.ToChannel] := format('Ch.%d',[MainFrm.HR.ToChannel]) ;
end;
procedure TSetupSpeFrm.rbDisplayHRClick(Sender: TObject);
// -------------------------------
// Display heart rate as beats/min.
// -------------------------------
begin
edHRMaxScale.Units := 'bpm' ;
end;
procedure TSetupSpeFrm.rbDisplayRRClick(Sender: TObject);
// ----------------------------------
// Display heart rate as R-R interval
// ----------------------------------
begin
edHRMaxScale.Units := 's' ;
end;
end.
|
unit FreeOTFEfmeOptions_General;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Spin64,
FreeOTFESettings, SDUStdCtrls, CommonfmeOptions_Base,
FreeOTFEfmeOptions_Base;
type
TLanguageTranslation = record
Name: string;
Code: string;
Contact: string;
end;
PLanguageTranslation = ^TLanguageTranslation;
TfmeOptions_FreeOTFEGeneral = class(TfmeFreeOTFEOptions_Base)
gbGeneral: TGroupBox;
ckDisplayToolbar: TSDUCheckBox;
ckDisplayStatusbar: TSDUCheckBox;
ckExploreAfterMount: TSDUCheckBox;
pnlVertSplit: TPanel;
cbDrive: TComboBox;
lblDefaultDriveLetter: TLabel;
ckShowPasswords: TSDUCheckBox;
cbLanguage: TComboBox;
lblLanguage: TLabel;
pbLangDetails: TButton;
ckPromptMountSuccessful: TSDUCheckBox;
ckDisplayToolbarLarge: TSDUCheckBox;
ckDisplayToolbarCaptions: TSDUCheckBox;
cbChkUpdatesFreq: TComboBox;
lblChkUpdatesFreq: TLabel;
procedure pbLangDetailsClick(Sender: TObject);
procedure cbLanguageChange(Sender: TObject);
procedure ControlChanged(Sender: TObject);
private
FLanguages: array of TLanguageTranslation;
procedure PopulateLanguages();
procedure SetLanguageSelection(langCode: string);
function SelectedLanguage(): TLanguageTranslation;
function LanguageControlLanguage(idx: integer): TLanguageTranslation;
protected
procedure _ReadSettings(config: TFreeOTFESettings); override;
procedure _WriteSettings(config: TFreeOTFESettings); override;
public
procedure Initialize(); override;
procedure EnableDisableControls(); override;
end;
implementation
{$R *.dfm}
uses
SDUi18n,
SDUGeneral,
SDUDialogs,
CommonConsts,
CommonSettings,
CommonfrmOptions;
{$IFDEF _NEVER_DEFINED}
// This is just a dummy const to fool dxGetText when extracting message
// information
// This const is never used; it's #ifdef'd out - SDUCRLF in the code refers to
// picks up SDUGeneral.SDUCRLF
const
SDUCRLF = ''#13#10;
{$ENDIF}
const
CONTROL_MARGIN_LBL_TO_CONTROL = 5;
procedure TfmeOptions_FreeOTFEGeneral.cbLanguageChange(Sender: TObject);
var
useLang: TLanguageTranslation;
langIdx: integer;
begin
inherited;
// Preserve selected language; the selected language gets change by the
// PopulateLanguages() call
langIdx := cbLanguage.ItemIndex;
useLang:= SelectedLanguage();
TfrmOptions(Owner).ChangeLanguage(useLang.Code);
// Repopulate the languages list; translation would have translated them all
PopulateLanguages();
// Restore selected
cbLanguage.ItemIndex := langIdx;
EnableDisableControls();
end;
procedure TfmeOptions_FreeOTFEGeneral.ControlChanged(Sender: TObject);
begin
inherited;
EnableDisableControls();
end;
procedure TfmeOptions_FreeOTFEGeneral.EnableDisableControls();
begin
inherited;
// Language at index 0 is "(Default)"
SDUEnableControl(pbLangDetails, (cbLanguage.ItemIndex > 0));
SDUEnableControl(ckDisplayToolbarLarge, ckDisplayToolbar.checked);
SDUEnableControl(ckDisplayToolbarCaptions, (
ckDisplayToolbar.checked and
ckDisplayToolbarLarge.checked
));
// Only allow captions if the user has selected large icons
if not(ckDisplayToolbarLarge.checked) then
begin
ckDisplayToolbarCaptions.Checked := FALSE;
end;
end;
procedure TfmeOptions_FreeOTFEGeneral.Initialize();
const
// Vertical spacing between checkboxes, and min horizontal spacing between
// checkbox label and the vertical separator line
// Set to 6 for now as that looks reasonable. 10 is excessive, 5 is a bit
// cramped
CHKBOX_CONTROL_MARGIN = 6;
// This adjusts the width of a checkbox, and resets it caption so it
// autosizes. If it autosizes such that it's too wide, it'll drop the width
// and repeat
procedure NudgeCheckbox(chkBox: TCheckBox);
var
tmpCaption: string;
maxWidth: integer;
useWidth: integer;
lastTriedWidth: integer;
begin
tmpCaption := chkBox.Caption;
maxWidth := (pnlVertSplit.left - CHKBOX_CONTROL_MARGIN) - chkBox.Left;
useWidth := maxWidth;
chkBox.Caption := 'X';
chkBox.Width := useWidth;
lastTriedWidth := useWidth;
chkBox.Caption := tmpCaption;
while (
(chkBox.Width > maxWidth) and
(lastTriedWidth > 0)
) do
begin
// 5 used here; just needs to be something sensible to reduce the
// width by; 1 would do pretty much just as well
useWidth := useWidth - 5;
chkBox.Caption := 'X';
chkBox.Width := useWidth;
lastTriedWidth := useWidth;
chkBox.Caption := tmpCaption;
end;
end;
procedure NudgeFocusControl(lbl: TLabel);
begin
if (lbl.FocusControl <> nil) then
begin
lbl.FocusControl.Top := lbl.Top + lbl.Height + CONTROL_MARGIN_LBL_TO_CONTROL;
end;
end;
var
driveLetter: char;
stlChkBoxOrder: TStringList;
YPos: integer;
i: integer;
currChkBox: TCheckBox;
begin
inherited;
SDUCenterControl(gbGeneral, ccHorizontal);
SDUCenterControl(gbGeneral, ccVertical, 25);
pnlVertSplit.caption := '';
pnlVertSplit.bevelouter := bvLowered;
pnlVertSplit.width := 3;
PopulateLanguages();
cbDrive.Items.clear();
cbDrive.Items.Add(USE_DEFAULT);
// for driveLetter:='C' to 'Z' do
for driveLetter:='A' to 'Z' do
begin
cbDrive.Items.Add(driveLetter+':');
end;
// Here we re-jig the checkboxes so that they are nicely spaced vertically.
// This is needed as some language translation require the checkboxes to have
// more than one line of text
//
// !! IMPORTANT !!
// When adding a checkbox:
// 1) Add it to stlChkBoxOrder below (doesn't matter in which order these
// are added)
// 2) Make sure the checkbox is a TSDUCheckBox, not just a normal Delphi
// TCheckBox
// 3) Make sure it's autosize property is TRUE
//
stlChkBoxOrder:= TStringList.Create();
try
// stlChkBoxOrder is used to order the checkboxes in their vertical order;
// this allows checkboxes to be added into the list below in *any* order,
// and it'll still work
stlChkBoxOrder.Sorted := TRUE;
stlChkBoxOrder.AddObject(Format('%.5d', [ckExploreAfterMount.Top]), ckExploreAfterMount);
stlChkBoxOrder.AddObject(Format('%.5d', [ckDisplayToolbar.Top]), ckDisplayToolbar);
stlChkBoxOrder.AddObject(Format('%.5d', [ckDisplayToolbarLarge.Top]), ckDisplayToolbarLarge);
stlChkBoxOrder.AddObject(Format('%.5d', [ckDisplayToolbarCaptions.Top]), ckDisplayToolbarCaptions);
stlChkBoxOrder.AddObject(Format('%.5d', [ckDisplayStatusbar.Top]), ckDisplayStatusbar);
stlChkBoxOrder.AddObject(Format('%.5d', [ckShowPasswords.Top]), ckShowPasswords);
stlChkBoxOrder.AddObject(Format('%.5d', [ckPromptMountSuccessful.Top]), ckPromptMountSuccessful);
currChkBox := TCheckBox(stlChkBoxOrder.Objects[0]);
YPos := currChkBox.Top;
YPos := YPos + currChkBox.Height;
for i:=1 to (stlChkBoxOrder.count - 1) do
begin
currChkBox := TCheckBox(stlChkBoxOrder.Objects[i]);
if currChkBox.visible then
begin
currChkBox.Top := YPos + CHKBOX_CONTROL_MARGIN;
// Sort out the checkbox's height
NudgeCheckbox(currChkBox);
YPos := currChkBox.Top;
YPos := YPos + currChkBox.Height;
end;
end;
finally
stlChkBoxOrder.Free();
end;
// Here we move controls associated with labels, such that they appear
// underneath the label
// NudgeFocusControl(lblLanguage);
// NudgeFocusControl(lblDefaultDriveLetter);
// NudgeFocusControl(lblMRUMaxItemCount);
end;
procedure TfmeOptions_FreeOTFEGeneral.pbLangDetailsClick(Sender: TObject);
var
rcdLanguage: TLanguageTranslation;
begin
inherited;
rcdLanguage := SelectedLanguage();
SDUMessageDlg(
SDUParamSubstitute(_('Language name: %1'), [rcdLanguage.Name])+SDUCRLF+
SDUParamSubstitute(_('Language code: %1'), [rcdLanguage.Code])+SDUCRLF+
SDUParamSubstitute(_('Translator: %1'), [rcdLanguage.Contact])
);
end;
procedure TfmeOptions_FreeOTFEGeneral._ReadSettings(config: TFreeOTFESettings);
var
uf: TUpdateFrequency;
idx: integer;
useIdx: integer;
begin
// General...
ckExploreAfterMount.checked := config.OptExploreAfterMount;
ckDisplayToolbar.checked := config.OptDisplayToolbar;
ckDisplayToolbarLarge.checked := config.OptDisplayToolbarLarge;
ckDisplayToolbarCaptions.checked := config.OptDisplayToolbarCaptions;
ckDisplayStatusbar.checked := config.OptDisplayStatusbar;
ckShowPasswords.checked := config.OptShowPasswords;
ckPromptMountSuccessful.checked := config.OptPromptMountSuccessful;
// In case language code not found; reset to "(Default)" entry; at index 0
SetLanguageSelection(config.OptLanguageCode);
// Default drive letter
if (config.OptDefaultDriveLetter = #0) then
begin
cbDrive.ItemIndex := 0;
end
else
begin
cbDrive.ItemIndex := cbDrive.Items.IndexOf(config.OptDefaultDriveLetter+':');
end;
// Populate and set update frequency dropdown
cbChkUpdatesFreq.Items.Clear();
idx := -1;
useIdx := -1;
for uf:=low(uf) to high(uf) do
begin
// Daily and weekly disabled for now; not sure what the load on the
// server would be like
if (
(uf = ufDaily) or
(uf = ufWeekly)
) then
begin
continue;
end;
inc(idx);
cbChkUpdatesFreq.Items.Add(UpdateFrequencyTitle(uf));
if (config.OptUpdateChkFrequency = uf) then
begin
useIdx := idx;
end;
end;
cbChkUpdatesFreq.ItemIndex := useIdx;
end;
procedure TfmeOptions_FreeOTFEGeneral._WriteSettings(config: TFreeOTFESettings);
var
uf: TUpdateFrequency;
useLang: TLanguageTranslation;
begin
// General...
config.OptExploreAfterMount := ckExploreAfterMount.checked;
config.OptDisplayToolbar := ckDisplayToolbar.checked;
config.OptDisplayToolbarLarge := ckDisplayToolbarLarge.checked;
config.OptDisplayToolbarCaptions := ckDisplayToolbarCaptions.checked;
config.OptDisplayStatusbar := ckDisplayStatusbar.checked;
config.OptShowPasswords := ckShowPasswords.checked;
config.OptPromptMountSuccessful := ckPromptMountSuccessful.checked;
useLang:= SelectedLanguage();
config.OptLanguageCode := useLang.Code;
// Default drive letter
if (cbDrive.ItemIndex = 0) then
begin
config.OptDefaultDriveLetter := #0;
end
else
begin
config.OptDefaultDriveLetter := cbDrive.Items[cbDrive.ItemIndex][1];
end;
// Decode update frequency
config.OptUpdateChkFrequency := ufNever;
for uf:=low(uf) to high(uf) do
begin
if (UpdateFrequencyTitle(uf) = cbChkUpdatesFreq.Items[cbChkUpdatesFreq.ItemIndex]) then
begin
config.OptUpdateChkFrequency := uf;
break;
end;
end;
end;
procedure TfmeOptions_FreeOTFEGeneral.PopulateLanguages();
var
i: integer;
origLangCode: string;
langCodes: TStringlist;
sortedList: TStringList;
begin
// Store language information for later use...
langCodes:= TStringlist.Create();
try
// Get all language codes...
SDUGetLanguageCodes(langCodes);
// +1 to include "Default"
SetLength(FLanguages, langCodes.count);
// Spin though the languages, getting their corresponding human-readable
// names
origLangCode:= SDUGetCurrentLanguageCode();
try
for i:=0 to (langCodes.count - 1) do
begin
SDUSetLanguage(langCodes[i]);
FLanguages[i].Code := langCodes[i];
FLanguages[i].Name := _(CONST_LANGUAGE_ENGLISH);
FLanguages[i].Contact := SDUGetTranslatorNameAndEmail();
// Force set contact details for English version; the dxgettext software sets
// this to some stupid default
if (langCodes[i] = ISO639_ALPHA2_ENGLISH) then
begin
FLanguages[i].Contact := ENGLISH_TRANSLATION_CONTACT;
end;
end;
finally
// Flip back to original language...
SDUSetLanguage(origLangCode);
end;
finally
langCodes.Free();
end;
// Add "default" into the list
SetLength(FLanguages, (length(FLanguages) + 1));
FLanguages[length(FLanguages)-1].Code := '';
FLanguages[length(FLanguages)-1].Name := _('(Default)');
FLanguages[length(FLanguages)-1].Contact := '';
// Populate list
sortedList:= TStringList.Create();
try
for i:=0 to (length(FLanguages) - 1) do
begin
sortedList.AddObject(FLanguages[i].Name, @(FLanguages[i]));
end;
sortedList.Sorted := TRUE;
sortedList.Sorted := FALSE;
cbLanguage.Items.Assign(sortedList)
finally
sortedList.Free();
end;
end;
procedure TfmeOptions_FreeOTFEGeneral.SetLanguageSelection(langCode: string);
var
useIdx: integer;
currLang: TLanguageTranslation;
i: integer;
begin
useIdx := 0;
for i:=0 to (cbLanguage.items.count - 1) do
begin
currLang := LanguageControlLanguage(i);
if (currLang.Code = langCode) then
begin
useIdx := i;
break
end;
end;
cbLanguage.ItemIndex := useIdx;
end;
function TfmeOptions_FreeOTFEGeneral.SelectedLanguage(): TLanguageTranslation;
var
retval: TLanguageTranslation;
begin
retval := LanguageControlLanguage(cbLanguage.ItemIndex);
Result := retval;
end;
function TfmeOptions_FreeOTFEGeneral.LanguageControlLanguage(idx: integer): TLanguageTranslation;
var
retval: TLanguageTranslation;
begin
retval := (PLanguageTranslation(cbLanguage.Items.Objects[idx]))^;
Result := retval;
end;
END.
|
unit uMainForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, FileCtrl, StdCtrls, ExtCtrls, Menus, ComCtrls,
Grids, AdvObj, BaseGrid, AdvGrid, ShellAPI, TreeList, Buttons,
ActnList, AdvMenus, ToolWin;
type
TMainForm = class(TForm)
OpenDialog: TOpenDialog;
TreeList: TTreeList;
edtFilter: TLabeledEdit;
btnApply: TSpeedButton;
chbAutoApply: TCheckBox;
ActionList: TActionList;
actApplyFilter: TAction;
actExecuteFile: TAction;
actAutoApply: TAction;
MainMenu: TMainMenu;
N1: TMenuItem;
ToolBar: TToolBar;
Open1: TMenuItem;
actOpenProject: TAction;
Settings1: TMenuItem;
StatusBar: TStatusBar;
PopupMenu: TPopupMenu;
Open2: TMenuItem;
View1: TMenuItem;
actShowAbout: TAction;
About1: TMenuItem;
About2: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure actApplyFilterExecute(Sender: TObject);
procedure actExecuteFileExecute(Sender: TObject);
procedure actAutoApplyExecute(Sender: TObject);
procedure edtFilterChange(Sender: TObject);
procedure actOpenProjectExecute(Sender: TObject);
procedure actShowAboutExecute(Sender: TObject);
private
FProjectRootDir: string;
FProjects: TList;
protected
procedure ParseBPGFile(aFileName: string; out aProjectsFiles: TStrings);
procedure ParseProjectFile(aFileName: string; out aFiles: TStrings);
procedure OpenBPG(aFileName: string);
procedure BuildTree();
public
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
uses
IniFiles,
ProjectInfo,
AboutForm;
procedure Split(aStr: string; aDelimiter: Char; out aWords: TStrings);
var
Strings: TStrings;
begin
Strings := TStringList.Create();
try
Strings.Delimiter := aDelimiter;
Strings.DelimitedText := aStr;
aWords.AddStrings(Strings);
finally
Strings.Free();
end;
end;
procedure TMainForm.ParseBPGFile(aFileName: string; out aProjectsFiles: TStrings);
var
i, k: Integer;
Str, Name, Value: string;
Found: Boolean;
FileStrings,
Projects,
ProjectsFiles: TStrings;
begin
FileStrings := TStringList.Create();
Projects := TStringList.Create();
ProjectsFiles := THashedStringList.Create();
try
FileStrings.LoadFromFile(aFileName);
i := 0;
Found := False;
while (not Found) and (i < FileStrings.Count) do
begin
Str := FileStrings.Strings[i];
Found := (Pos('PROJECTS =', Str) > 0);
Inc(i);
end;
if not Found then Exit;
Dec(i);
while (i < FileStrings.Count) do
begin
Str := FileStrings.Strings[i];
if (Str[1] = '#') then
Break;
Split(Str, ' ', Projects);
Inc(i);
end;
k := 0;
while (k < Projects.Count) do
begin
Str := ExtractFileExt(Projects.Strings[k]);
if (Str <> '.bpl') and (Str <> '.ocx') and (Str <> '.exe') and (Str <> '.dll') then
Projects.Delete(k)
else
Inc(k);
end;
ProjectsFiles.NameValueSeparator := ':';
while (i < FileStrings.Count) do
begin
ProjectsFiles.Add(FileStrings.Strings[i]);
Inc(i);
end;
aProjectsFiles.Clear();
aProjectsFiles.NameValueSeparator := ';';
for i := 0 to Projects.Count - 1 do
begin
Name := Projects.Strings[i];
Value := Trim(ProjectsFiles.Values[Name]);
if (Value <> '') then
aProjectsFiles.Add(Name + ';' + Value);
end;
finally
ProjectsFiles.Free();
Projects.Free();
FileStrings.Free();
end;
end;
procedure TMainForm.ParseProjectFile(aFileName: string; out aFiles: TStrings);
var
i, k: Integer;
Str, Ext, Text,
Name, FileName, FormName: string;
Found: Boolean;
FileStrings,
Files,
Words: TStrings;
begin
aFiles.Clear();
aFiles.NameValueSeparator := ';';
Ext := ExtractFileExt(aFileName);
if (Ext = '.dpk') then
Text := 'contains'
else
if (Ext = '.dpr') then
Text := 'uses'
else
Exit;
FileStrings := TStringList.Create();
Files := TStringList.Create();
Words := TStringList.Create();
try
FileStrings.LoadFromFile(aFileName);
i := 0;
Found := False;
while (not Found) and (i < FileStrings.Count) do
begin
Str := FileStrings.Strings[i];
Found := (Pos(Text, Str) > 0);
Inc(i);
end;
if (not Found) then Exit;
while (i < FileStrings.Count) do
begin
Str := Trim(FileStrings.Strings[i]);
Files.StrictDelimiter := True;
Files.CommaText := Str;
for k := 0 to Files.Count - 1 do
begin
Name := '';
FileName := '';
FormName := '';
Words.Clear();
Split(Files.Strings[k], ' ', Words);
if (Words.Count > 0) then
begin
Name := Words.Strings[0];
if (Words.Count > 2) and (Words.Strings[1] = 'in') then
begin
FileName := Words.Strings[2];
FileName := Copy(FileName, 2, Length(FileName) - 2);
end;
if (Words.Count > 3) then
begin
FormName := Words.Strings[3];
if (FormName[1] = '{') then
FormName := Copy(FormName, 2, Length(FormName) - 2)
else
FormName := '';
end;
end;
if (Name <> '') then
aFiles.Add(Name + ';' + FileName + ';' + FormName);
end;
if (Str[Length(Str)] = ';') then
Break;
Inc(i);
end;
finally
Words.Free();
Files.Free();
FileStrings.Free();
end;
end;
procedure TMainForm.OpenBPG(aFileName: string);
var
i: Integer;
Files,
ProjectsFiles: TStrings;
Name, Value: string;
Project: TProjectInfo;
begin
FProjectRootDir := ExtractFilePath(aFileName);
FProjects.Clear();
Files := TStringList.Create();
ProjectsFiles := THashedStringList.Create();
try
ParseBPGFile(aFileName, ProjectsFiles);
for i := 0 to ProjectsFiles.Count - 1 do
begin
Name := ProjectsFiles.Names[i];
Value := ProjectsFiles.Values[Name];
if (Value = '') then
Continue;
if (Value[2] <> ':') then
Value := FProjectRootDir + Value;
Files.Clear();
ParseProjectFile(Value, Files);
Project := TProjectInfo.Create(Name, Value, Files);
FProjects.Add(Project);
end;
finally
ProjectsFiles.Free();
Files.Free();
end;
end;
procedure TMainForm.BuildTree();
procedure AddProjectToTree(aProject: TProjectInfo);
var
i: Integer;
ProjectNode,
FileNode: TTreeNode;
begin
if (aProject.Count = 0) then Exit;
ProjectNode := TreeList.Items.AddChild(nil, aProject.ProjectName);
ProjectNode.Data := aProject;
for i := 0 to aProject.Count - 1 do
begin
FileNode := TreeList.Items.AddChild(ProjectNode, aProject.UnitName[i]);
TreeList.SetNodeColumn(FileNode, 1, aProject.FileName[i]);
TreeList.SetNodeColumn(FileNode, 2, aProject.FormName[i]);
TreeList.SetNodeColumn(FileNode, 3, aProject.FormCaption[i]);
end;
end;
var
i: Integer;
begin
TreeList.Items.Clear();
for i := 0 to FProjects.Count - 1 do
begin
AddProjectToTree(TProjectInfo(FProjects.Items[i]));
end;
end;
procedure TMainForm.edtFilterChange(Sender: TObject);
begin
if chbAutoApply.Checked then
actApplyFilterExecute(Sender);
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
FProjects := TList.Create();
end;
procedure TMainForm.FormDestroy(Sender: TObject);
var
i: Integer;
begin
for i := 0 to FProjects.Count - 1 do
try
TObject(FProjects.Items[i]).Free();
except
end;
FProjects.Free();
end;
procedure TMainForm.actApplyFilterExecute(Sender: TObject);
var
i: Integer;
Filter: string;
begin
Filter := edtFilter.Text;
for i := 0 to FProjects.Count - 1 do
begin
TProjectInfo(FProjects.Items[i]).ApplyFilter(Filter);
end;
BuildTree();
TreeList.FullExpand();
end;
procedure TMainForm.actAutoApplyExecute(Sender: TObject);
begin
if chbAutoApply.Checked then
actApplyFilterExecute(Sender);
end;
procedure TMainForm.actExecuteFileExecute(Sender: TObject);
var
Node: TTreeNode;
Project: TProjectInfo;
Str,
ProjectRootDir: string;
begin
Node := TreeList.Selected;
if not Assigned(Node) then Exit;
if Assigned(Node.Parent) then
Project := TProjectInfo(Node.Parent.Data)
else
Project := TProjectInfo(Node.Data);
if Assigned(Project) then
begin
if not Assigned(Node.Parent) then
begin
Str := Project.ProjectFileName
end
else
begin
ProjectRootDir := ExtractFilePath(Project.ProjectFileName);
Str := ProjectRootDir + TreeList.GetNodeColumn(Node, 1);
end;
ShellExecute(Self.Handle, PChar('open'), PChar(Str), nil, nil, 0);
end;
end;
procedure TMainForm.actOpenProjectExecute(Sender: TObject);
var
i: Integer;
ProjectsFiles: TStrings;
Path,
Name, Value: string;
begin
if not OpenDialog.Execute() then Exit;
OpenBPG(OpenDialog.FileName);
BuildTree();
StatusBar.SimpleText := OpenDialog.FileName;
end;
procedure TMainForm.actShowAboutExecute(Sender: TObject);
begin
AboutFrm.ShowModal();
end;
end.
|
{ *******************************************************************************
Title: T2Ti ERP
Description: Janela Informativos e Guias para a Folha de Pagamento
The MIT License
Copyright: Copyright (C) 2016 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com</p>
@author Albert Eije (alberteije@gmail.com)
@version 2.0
******************************************************************************* }
unit UFolhaInformativosGuias;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, DBClient, Grids, DBGrids, StdCtrls, ExtCtrls,
JvExDBGrids, JvDBGrid, JvDBUltimGrid, ActnList, RibbonSilverStyleActnCtrls,
ActnMan, ToolWin, ActnCtrls, DBXJSON, ACBrPonto_AFD_Class, Mask, JvExMask,
JvToolEdit, LabeledCtrls, ACBrPonto_AFDT_Class, ComCtrls, JvBaseEdits,
{ACBrFolha, }SessaoUsuario, System.Actions, Vcl.Imaging.pngimage, Controller,
Biblioteca, ACBrBancoBrasilFolha;
type
TFFolhaInformativosGuias = class(TForm)
PanelCabecalho: TPanel;
Bevel1: TBevel;
Image1: TImage;
Label2: TLabel;
ActionToolBarPrincipal: TActionToolBar;
ActionManagerLocal: TActionManager;
ActionCancelar: TAction;
ActionGerarSefip: TAction;
ActionGerarCaged: TAction;
ActionGerarFichaFinanceira: TAction;
PageControlItens: TPageControl;
tsInformativosMensais: TTabSheet;
PanelInformativosMensais: TPanel;
ActionSair: TAction;
GroupBox1: TGroupBox;
ComboBoxGfipCodigoRecolhimento: TLabeledComboBox;
EditGfipCompetencia: TLabeledMaskEdit;
GroupBox2: TGroupBox;
ComboBoxCagedAlteracao: TLabeledComboBox;
EditCagedCompetencia: TLabeledMaskEdit;
ActionToolBarInformativosMensais: TActionToolBar;
tsInformativosAnuais: TTabSheet;
PanelInformativosAnuais: TPanel;
GroupBox3: TGroupBox;
ComboBoxFichaFinanceiraOrdem: TLabeledComboBox;
EditFichaFinanceiraAnoBase: TLabeledMaskEdit;
GroupBox4: TGroupBox;
ActionToolBar1: TActionToolBar;
ActionGerarComprovanteRendimentos: TAction;
EditComprovanteRendimentosAnoBase: TLabeledMaskEdit;
ComboBoxComprovanteRendimentosOrdem: TLabeledComboBox;
GroupBox5: TGroupBox;
EditRaisAnoBase: TLabeledMaskEdit;
ComboBoxRaisTipoInformativo: TLabeledComboBox;
ComboBoxRaisOrdem: TLabeledComboBox;
ActionGerarRais: TAction;
GroupBox6: TGroupBox;
EditDirfAnoBase: TLabeledMaskEdit;
ActionGerarDirf: TAction;
tsInformativosEventuais: TTabSheet;
PanelInformativosEventuais: TPanel;
GroupBox7: TGroupBox;
ComboBoxManadCentralizacaoEscrituracao: TLabeledComboBox;
EditManadPeriodoDe: TLabeledMaskEdit;
ActionToolBar2: TActionToolBar;
EditManadPediodoA: TLabeledMaskEdit;
ComboBoxManadFinalidadeArquivo: TLabeledComboBox;
ActionGerarManad: TAction;
tsGuias: TTabSheet;
Panel1: TPanel;
GroupBox8: TGroupBox;
EditGpsCompetencia: TLabeledMaskEdit;
ActionToolBar3: TActionToolBar;
ActionGerarGps: TAction;
ActionGerarIrrf: TAction;
ActionGerarPis: TAction;
GroupBox9: TGroupBox;
EditGrrfPeriodoDe: TLabeledMaskEdit;
EditGrrfPeriodoA: TLabeledMaskEdit;
EditGrrfDataPagamento: TLabeledDateEdit;
ActionGerarGrrf: TAction;
GroupBox13: TGroupBox;
EditGrcsuCompetencia: TLabeledMaskEdit;
EditGrcsuMulta: TLabeledCalcEdit;
EditGrcsuJuros: TLabeledCalcEdit;
ActionGerarGrscu: TAction;
//ACBrFolha: TACBrFolha;
CDSColaborador: TClientDataSet;
GroupBox12: TGroupBox;
EditValorMulta: TLabeledCalcEdit;
EditValorJuros: TLabeledCalcEdit;
EditDataVencimento: TLabeledDateEdit;
EditPeriodoApuracao: TLabeledDateEdit;
EditCodigoReceita: TLabeledMaskEdit;
EditNumeroReferencia: TLabeledMaskEdit;
EditValorPrincipal: TLabeledCalcEdit;
EditValorTotal: TLabeledCalcEdit;
EditGpsCodigoPagamento: TLabeledMaskEdit;
EditGpsIdentificador: TLabeledMaskEdit;
EditGpsValorInss: TLabeledCalcEdit;
EditGpsValorOutrasEntidades: TLabeledCalcEdit;
EditGpsValorJuros: TLabeledCalcEdit;
EditGpsValorTotal: TLabeledCalcEdit;
tsEDI: TTabSheet;
ActionGerarRemessa: TAction;
ActionLerRetorno: TAction;
GroupBox10: TGroupBox;
ActionToolBar4: TActionToolBar;
DSColaborador: TDataSource;
GridColaborador: TJvDBUltimGrid;
procedure ActionCancelarExecute(Sender: TObject);
procedure ActionSairExecute(Sender: TObject);
procedure ActionGerarSefipExecute(Sender: TObject);
procedure ActionGerarCagedExecute(Sender: TObject);
procedure ActionGerarFichaFinanceiraExecute(Sender: TObject);
procedure ActionGerarComprovanteRendimentosExecute(Sender: TObject);
procedure ActionGerarRaisExecute(Sender: TObject);
procedure ActionGerarDirfExecute(Sender: TObject);
procedure ActionGerarManadExecute(Sender: TObject);
procedure ActionGerarGpsExecute(Sender: TObject);
procedure ActionGerarIrrfExecute(Sender: TObject);
procedure ActionGerarPisExecute(Sender: TObject);
procedure ActionGerarGrrfExecute(Sender: TObject);
procedure ActionGerarGrfcExecute(Sender: TObject);
procedure ActionGerarGrscuExecute(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure EmiteDarf;
class function Sessao: TSessaoUsuario;
procedure FormCreate(Sender: TObject);
procedure ActionLerRetornoExecute(Sender: TObject);
procedure ActionGerarRemessaExecute(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FFolhaInformativosGuias: TFFolhaInformativosGuias;
implementation
uses
UDataModule, ViewPessoaColaboradorController, ViewPessoaColaboradorVO,
UPreview;
{$R *.dfm}
class function TFFolhaInformativosGuias.Sessao: TSessaoUsuario;
begin
Result := TSessaoUsuario.Instance;
end;
procedure TFFolhaInformativosGuias.ActionCancelarExecute(Sender: TObject);
begin
Close;
end;
procedure TFFolhaInformativosGuias.ActionSairExecute(Sender: TObject);
begin
Close;
end;
procedure TFFolhaInformativosGuias.FormCreate(Sender: TObject);
begin
// Configura a Grid do Colaborador
ConfiguraCDSFromVO(CDSColaborador, TViewPessoaColaboradorVO);
ConfiguraGridFromVO(GridColaborador, TViewPessoaColaboradorVO);
// Consulta os Colaboradores
TViewPessoaColaboradorController.SetDataSet(CDSColaborador);
TController.ExecutarMetodo('ViewPessoaColaboradorController.TViewPessoaColaboradorController', 'Consulta', ['ID>0', '0', False], 'GET', 'Lista');
end;
procedure TFFolhaInformativosGuias.FormShow(Sender: TObject);
begin
EditGfipCompetencia.Clear;
EditCagedCompetencia.Clear;
EditFichaFinanceiraAnoBase.Clear;
EditComprovanteRendimentosAnoBase.Clear;
EditRaisAnoBase.Clear;
EditDirfAnoBase.Clear;
EditManadPeriodoDe.Clear;
EditManadPediodoA.Clear;
EditGpsCompetencia.Clear;
EditGrrfPeriodoDe.Clear;
EditGrrfPeriodoA.Clear;
EditGrcsuCompetencia.Clear;
end;
procedure TFFolhaInformativosGuias.ActionGerarSefipExecute(Sender: TObject);
begin
(*
ACBrFolha.Path := ExtractFilePath(Application.ExeName);
ACBrFolha.Folha_Sefip.LimpaRegistros;
// REGISTRO TIPO 00 – Informações do Responsável (Header do arquivo)
ACBrFolha.Folha_Sefip.RegistroTipo00.TipoRemessa := '1'; //1=GFIP
ACBrFolha.Folha_Sefip.RegistroTipo00.TipoInscricaoResponsavel := '1'; //1=CNPJ
ACBrFolha.Folha_Sefip.RegistroTipo00.InscricaoResponsavel := Sessao.Empresa.Cnpj;
ACBrFolha.Folha_Sefip.RegistroTipo00.NomeResponsavel := Sessao.Empresa.RazaoSocial;
ACBrFolha.Folha_Sefip.RegistroTipo00.NomePessoaContato := Sessao.Empresa.RazaoSocial;
ACBrFolha.Folha_Sefip.RegistroTipo00.Logradouro := TEnderecoVO(Sessao.Empresa.ListaEnderecoVO[0]).Logradouro;
ACBrFolha.Folha_Sefip.RegistroTipo00.Bairro := TEnderecoVO(Sessao.Empresa.ListaEnderecoVO[0]).Bairro;
ACBrFolha.Folha_Sefip.RegistroTipo00.Cep := TEnderecoVO(Sessao.Empresa.ListaEnderecoVO[0]).Cep;
ACBrFolha.Folha_Sefip.RegistroTipo00.Cidade := TEnderecoVO(Sessao.Empresa.ListaEnderecoVO[0]).Cidade;
ACBrFolha.Folha_Sefip.RegistroTipo00.UnidadeFederacao := TEnderecoVO(Sessao.Empresa.ListaEnderecoVO[0]).Uf;
ACBrFolha.Folha_Sefip.RegistroTipo00.TelefoneContato := TEnderecoVO(Sessao.Empresa.ListaEnderecoVO[0]).Fone;
ACBrFolha.Folha_Sefip.RegistroTipo00.EnderecoInternetContato := Sessao.Empresa.Email;
ACBrFolha.Folha_Sefip.RegistroTipo00.Competencia := Copy(EditGfipCompetencia.Text, 4, 4) + Copy(EditGfipCompetencia.Text, 1, 2);
ACBrFolha.Folha_Sefip.RegistroTipo00.CodigoRecolhimento := Copy(ComboBoxGfipCodigoRecolhimento.Text, 1, 3);
ACBrFolha.Folha_Sefip.RegistroTipo00.IndicadorRecolhimentoFGTS := '1'; //1 (GRF no prazo)
ACBrFolha.Folha_Sefip.RegistroTipo00.ModalidadeArquivo := '1'; //1 - Declaração ao FGTS e à Previdência
ACBrFolha.Folha_Sefip.RegistroTipo00.TipoInscricaoFornecedorFolhaPagamento := '1'; //1=CNPJ
ACBrFolha.Folha_Sefip.RegistroTipo00.DataRecolhimentoFGTS := Now;
ACBrFolha.Folha_Sefip.RegistroTipo00.IndicadorRecolhimentoPrevidenciaSocial := '1'; //1 (no prazo)
ACBrFolha.Folha_Sefip.RegistroTipo00.DataRecolhimentoPrevidenciaSocial := Now;
ACBrFolha.Folha_Sefip.RegistroTipo00.TipoInscricaoFornecedorFolhaPagamento := '1'; //1=CNPJ
ACBrFolha.Folha_Sefip.RegistroTipo00.InscricaoFornecedorFolhaPagamento := Sessao.Empresa.Cnpj;
//REGISTRO TIPO 10 – Informações da Empresa (Header da empresa )
ACBrFolha.Folha_Sefip.RegistroTipo10.TipoInscricaoEmpresa := '1'; //1=CNPJ
ACBrFolha.Folha_Sefip.RegistroTipo10.InscricaoEmpresa := Sessao.Empresa.Cnpj;
ACBrFolha.Folha_Sefip.RegistroTipo10.NomeEmpresaRazaoSocial := Sessao.Empresa.RazaoSocial;
ACBrFolha.Folha_Sefip.RegistroTipo10.Logradouro := TEnderecoVO(Sessao.Empresa.ListaEnderecoVO[0]).Logradouro;
ACBrFolha.Folha_Sefip.RegistroTipo10.Bairro := TEnderecoVO(Sessao.Empresa.ListaEnderecoVO[0]).Bairro;
ACBrFolha.Folha_Sefip.RegistroTipo10.Cep := TEnderecoVO(Sessao.Empresa.ListaEnderecoVO[0]).Cep;
ACBrFolha.Folha_Sefip.RegistroTipo10.Cidade := TEnderecoVO(Sessao.Empresa.ListaEnderecoVO[0]).Cidade;
ACBrFolha.Folha_Sefip.RegistroTipo10.UnidadeFederacao := TEnderecoVO(Sessao.Empresa.ListaEnderecoVO[0]).Uf;
ACBrFolha.Folha_Sefip.RegistroTipo10.TelefoneContato := TEnderecoVO(Sessao.Empresa.ListaEnderecoVO[0]).Fone;
ACBrFolha.Folha_Sefip.RegistroTipo10.IndicadorAlteracaoEndereco := 'N';
ACBrFolha.Folha_Sefip.RegistroTipo10.CNAE:= Sessao.Empresa.CodigoCnaePrincipal;
ACBrFolha.Folha_Sefip.RegistroTipo10.IndicadorAlteracaoCNAE := 'N';
ACBrFolha.Folha_Sefip.RegistroTipo10.AliquotaRAT := '00'; //Será zeros para FPAS 604, 647, 825, 833 e 868 (empregador doméstico) e para a empresa optante pelo SIMPLES.
ACBrFolha.Folha_Sefip.RegistroTipo10.CodigoCentralizacao := '1'; //1 (centralizadora)
ACBrFolha.Folha_Sefip.RegistroTipo10.SIMPLES := '2'; //2 – Optante;
ACBrFolha.Folha_Sefip.RegistroTipo10.FPAS := Sessao.Empresa.DescricaoFpas;
ACBrFolha.Folha_Sefip.RegistroTipo10.CodigoOutrasEntidades := IntToStr(Sessao.Empresa.CodigoTerceiros);
ACBrFolha.Folha_Sefip.RegistroTipo10.CodigoPagamentoGPS := IntToStr(Sessao.Empresa.CodigoGps);
//REGISTRO TIPO 12 – Informações Adicionais do Recolhimento da Empresa (Opcional)
{ Implementado a critério do Participante do T2Ti ERP }
//REGISTRO TIPO 13 – Alteração Cadastral Trabalhador (Opcional)
{ Implementado a critério do Participante do T2Ti ERP }
//REGISTRO TIPO 14 – Inclusão/Alteração Endereço do Trabalhador (Opcional)
{ Implementado a critério do Participante do T2Ti ERP }
//REGISTRO TIPO 20 – Registro do Tomador de Serviço/Obra de Construção Civil (Opcional)
{ Implementado a critério do Participante do T2Ti ERP }
//REGISTRO TIPO 21 - Registro de informações adicionais do Tomador de Serviço/Obra de Const. Civil (Opcional)
{ Implementado a critério do Participante do T2Ti ERP }
//REGISTRO TIPO 30 - Registro do Trabalhador
TViewPessoaColaboradorController.SetDataSet(CDSColaborador);
TViewPessoaColaboradorController.Consulta('ID>0', -1);
CDSColaborador.First;
while not CDSColaborador.Eof do
begin
with ACBrFolha.Folha_Sefip.RegistroTipo30.New do
begin
TipoInscricaoEmpresa := ACBrFolha.Folha_Sefip.RegistroTipo10.TipoInscricaoEmpresa;
InscricaoEmpresa := ACBrFolha.Folha_Sefip.RegistroTipo10.InscricaoEmpresa;
PISPASEPCI := CDSColaboradorPIS_NUMERO.AsString;
DataAdmissao := CDSColaboradorDATA_ADMISSAO.AsDateTime;
CategoriaTrabalhador := CDSColaboradorCATEGORIA_SEFIP.AsString;
NomeTrabalhador := CDSColaboradorNOME.AsString;
MatriculaEmpregado := CDSColaboradorMATRICULA.AsString;
NumeroCTPS := CDSColaboradorCTPS_NUMERO.AsString;
SerieCTPS := CDSColaboradorCTPS_SERIE.AsString;
DataOpcao := CDSColaboradorFGTS_DATA_OPCAO.AsDateTime;
end;
CDSColaborador.Next;
end;
//REGISTRO TIPO 32 – Movimentação do Trabalhador (Opcional)
{ Implementado a critério do Participante do T2Ti ERP }
//REGISTRO TIPO 50– Empresa Com Recolhimento pelos códigos 027, 046, 604 e 736 (Header da empresa ) (PARA IMPLEMENTAÇÃO FUTURA)
{ Implementado a critério do Participante do T2Ti ERP }
//REGISTRO TIPO 51 - Registro de Individualização de valores recolhidos pelos códigos 027, 046, 604 e 736 (PARA IMPLEMENTAÇÃO FUTURA)
{ Implementado a critério do Participante do T2Ti ERP }
//Gera arquivo
ACBrFolha.SaveFileTXT_Sefip('SEFIP.RE');
Application.CreateForm(TFPreview, FPreview);
FPreview.RichEdit.Lines.LoadFromFile(ACBrFolha.Path + 'SEFIP.RE');
FPreview.ShowModal;
*)
end;
procedure TFFolhaInformativosGuias.ActionGerarCagedExecute(Sender: TObject);
begin
(*
ACBrFolha.Path := ExtractFilePath(Application.ExeName);
ACBrFolha.Folha_Caged.LimpaRegistros;
// REGISTRO A (AUTORIZADO)
ACBrFolha.Folha_Caged.RegistroTipoA.Competencia := Copy(EditCagedCompetencia.Text, 1, 2) + Copy(EditCagedCompetencia.Text, 4, 4);
ACBrFolha.Folha_Caged.RegistroTipoA.Alteracao := Copy(ComboBoxCagedAlteracao.Text, 1, 1);
ACBrFolha.Folha_Caged.RegistroTipoA.TipoIdentificador := '1'; //CNPJ
ACBrFolha.Folha_Caged.RegistroTipoA.NumeroIdentificadorDoAutorizado := Sessao.Empresa.Cnpj;
ACBrFolha.Folha_Caged.RegistroTipoA.NomeRazaoSocialDoAutorizado := Sessao.Empresa.RazaoSocial;
ACBrFolha.Folha_Caged.RegistroTipoA.Endereco := TEnderecoVO(Sessao.Empresa.ListaEnderecoVO[0]).Logradouro + ' ' + TEnderecoVO(Sessao.Empresa.ListaEnderecoVO[0]).Numero;
ACBrFolha.Folha_Caged.RegistroTipoA.Cep := TEnderecoVO(Sessao.Empresa.ListaEnderecoVO[0]).Cep;
ACBrFolha.Folha_Caged.RegistroTipoA.UF := TEnderecoVO(Sessao.Empresa.ListaEnderecoVO[0]).Uf;
ACBrFolha.Folha_Caged.RegistroTipoA.Telefone := TEnderecoVO(Sessao.Empresa.ListaEnderecoVO[0]).Fone;
// REGISTRO B (ESTABELECIMENTO)
ACBrFolha.Folha_Caged.RegistroTipoB.TipoIdentificador := '1'; //CNPJ
ACBrFolha.Folha_Caged.RegistroTipoB.NumeroIdentificadorDoEstabelecimento := Sessao.Empresa.Cnpj;
ACBrFolha.Folha_Caged.RegistroTipoB.PrimeiraDeclaracao := '1';
ACBrFolha.Folha_Caged.RegistroTipoB.Alteracao := Copy(ComboBoxCagedAlteracao.Text, 1, 1);
ACBrFolha.Folha_Caged.RegistroTipoB.Cep := TEnderecoVO(Sessao.Empresa.ListaEnderecoVO[0]).Cep;
ACBrFolha.Folha_Caged.RegistroTipoB.NomeRazaoSocialDoEstabelecimento := Sessao.Empresa.RazaoSocial;
ACBrFolha.Folha_Caged.RegistroTipoB.Endereco := TEnderecoVO(Sessao.Empresa.ListaEnderecoVO[0]).Logradouro + ' ' + TEnderecoVO(Sessao.Empresa.ListaEnderecoVO[0]).Numero;
ACBrFolha.Folha_Caged.RegistroTipoB.Bairro := TEnderecoVO(Sessao.Empresa.ListaEnderecoVO[0]).Bairro;
ACBrFolha.Folha_Caged.RegistroTipoB.UF := TEnderecoVO(Sessao.Empresa.ListaEnderecoVO[0]).Uf;
ACBrFolha.Folha_Caged.RegistroTipoB.TotalDeEmpregadosExistentesNoPrimeiroDia := '0';
ACBrFolha.Folha_Caged.RegistroTipoB.PorteDoEstabelecimento := '1';
ACBrFolha.Folha_Caged.RegistroTipoB.Cnae2ComSubClasse := Sessao.Empresa.CodigoCnaePrincipal;
ACBrFolha.Folha_Caged.RegistroTipoB.Telefone := TEnderecoVO(Sessao.Empresa.ListaEnderecoVO[0]).Fone;
ACBrFolha.Folha_Caged.RegistroTipoB.Email := Sessao.Empresa.Email;
//REGISTRO C (MOVIMENTAÇÃO)
TViewPessoaColaboradorController.SetDataSet(CDSColaborador);
TViewPessoaColaboradorController.Consulta('ID>0', -1);
CDSColaborador.First;
while not CDSColaborador.Eof do
begin
with ACBrFolha.Folha_Caged.RegistroTipoC.New do
begin
TipoIdentificador := '1';
NumeroIdentificadorDoEstabelecimento := Sessao.Empresa.Cnpj;
PisPasep := CDSColaboradorPIS_NUMERO.AsString;
Admissao := CDSColaboradorDATA_ADMISSAO.AsDateTime;
Cpf := CDSColaboradorCPF_CNPJ.AsString;
end;
CDSColaborador.Next;
end;
//REGISTRO X (ACERTO)
{ Implementado a critério do Participante do T2Ti ERP }
//Gera arquivo
ACBrFolha.SaveFileTXT_Caged('CAGED.TXT');
Application.CreateForm(TFPreview, FPreview);
FPreview.RichEdit.Lines.LoadFromFile(ACBrFolha.Path + 'CAGED.TXT');
FPreview.ShowModal;
*)
end;
procedure TFFolhaInformativosGuias.ActionGerarFichaFinanceiraExecute(Sender: TObject);
begin
Showmessage('Implementado a critério do Participante do T2Ti ERP');
{ Relatório dos valores calculados para os colaboradores mês a mês dentro de determinado ano. }
{ Implementado a critério do Participante do T2Ti ERP }
end;
procedure TFFolhaInformativosGuias.ActionGerarComprovanteRendimentosExecute(Sender: TObject);
begin
Showmessage('Implementado a critério do Participante do T2Ti ERP');
{ Relatório com todos os rendimentos de um determinado período, por colaborador. }
{ Implementado a critério do Participante do T2Ti ERP }
end;
procedure TFFolhaInformativosGuias.ActionGerarRaisExecute(Sender: TObject);
begin
Showmessage('Aguardar levantamento de requisitos do segundo ciclo por conta do eSocial');
{ Aguardar levantamento de requisitos do segundo ciclo por conta do eSocial }
end;
procedure TFFolhaInformativosGuias.ActionGerarDirfExecute(Sender: TObject);
begin
Showmessage('Aguardar levantamento de requisitos do segundo ciclo por conta do eSocial');
{ Aguardar levantamento de requisitos do segundo ciclo por conta do eSocial }
end;
procedure TFFolhaInformativosGuias.ActionGerarManadExecute(Sender: TObject);
begin
Showmessage('Aguardar levantamento de requisitos do segundo ciclo por conta do eSocial');
{ Aguardar levantamento de requisitos do segundo ciclo por conta do eSocial }
end;
procedure TFFolhaInformativosGuias.ActionGerarGpsExecute(Sender: TObject);
var
RemoteDataInfo: TStringList;
ConsultaSQL, NomeArquivo: String;
i: Integer;
begin
(*
try
try
NomeArquivo := 'GPS.rep';
FDataModule.VCLReport.GetRemoteParams(Sessao.ServidorImpressao.Servidor, Sessao.ServidorImpressao.Porta, Sessao.ServidorImpressao.Usuario, Sessao.ServidorImpressao.Senha, Sessao.ServidorImpressao.Alias, NomeArquivo);
FDataModule.VCLReport.Report.Params.ParamByName('CODIGOPAGAMENTO').Value := EditGpsCodigoPagamento.Text;
FDataModule.VCLReport.Report.Params.ParamByName('COMPETENCIA').Value := EditGpsCompetencia.Text;
FDataModule.VCLReport.Report.Params.ParamByName('IDENTIFICADOR').Value := EditGpsIdentificador.Text;
FDataModule.VCLReport.Report.Params.ParamByName('VALORINSS').Value := EditGpsValorInss.Value;
FDataModule.VCLReport.Report.Params.ParamByName('VALOROUTRASENTIDADES').Value := EditGpsValorOutrasEntidades.Value;
FDataModule.VCLReport.Report.Params.ParamByName('VALORJURO').Value := EditGpsValorJuros.Value;
FDataModule.VCLReport.Report.Params.ParamByName('VALORTOTAL').Value := EditGpsValorTotal.Value;
//
FDataModule.VCLReport.GetRemoteDataInfo(Sessao.ServidorImpressao.Servidor, Sessao.ServidorImpressao.Porta, Sessao.ServidorImpressao.Usuario, Sessao.ServidorImpressao.Senha, Sessao.ServidorImpressao.Alias, NomeArquivo);
RemoteDataInfo := FDataModule.VCLReport.Report.RemoteDataInfo;
//
ConsultaSQL := '';
FDataModule.VCLReport.ExecuteRemote(Sessao.ServidorImpressao.Servidor, Sessao.ServidorImpressao.Porta, Sessao.ServidorImpressao.Usuario, Sessao.ServidorImpressao.Senha, Sessao.ServidorImpressao.Alias, NomeArquivo, ConsultaSQL);
except
on E: Exception do
Application.MessageBox(PChar('Ocorreu um erro na construção do relatório. Informe a mensagem ao Administrador do sistema.' + #13 + #13 + E.Message), 'Erro do sistema', MB_OK + MB_ICONERROR);
end;
finally
end;
*)
end;
procedure TFFolhaInformativosGuias.ActionGerarIrrfExecute(Sender: TObject);
begin
EmiteDarf;
end;
procedure TFFolhaInformativosGuias.ActionGerarPisExecute(Sender: TObject);
begin
EmiteDarf;
end;
procedure TFFolhaInformativosGuias.ActionGerarGrrfExecute(Sender: TObject);
begin
Showmessage('Aguardar levantamento de requisitos do segundo ciclo por conta do eSocial');
{ Aguardar levantamento de requisitos do segundo ciclo por conta do eSocial }
end;
procedure TFFolhaInformativosGuias.ActionGerarGrfcExecute(Sender: TObject);
begin
Showmessage('Aguardar levantamento de requisitos do segundo ciclo por conta do eSocial');
{ Aguardar levantamento de requisitos do segundo ciclo por conta do eSocial }
end;
procedure TFFolhaInformativosGuias.ActionGerarGrscuExecute(Sender: TObject);
begin
Showmessage('Aguardar levantamento de requisitos do segundo ciclo por conta do eSocial');
{ Aguardar levantamento de requisitos do segundo ciclo por conta do eSocial }
end;
procedure TFFolhaInformativosGuias.EmiteDarf;
var
RemoteDataInfo: TStringList;
ConsultaSQL, NomeArquivo: String;
i: Integer;
begin
(*
try
try
NomeArquivo := 'DARF.rep';
FDataModule.VCLReport.GetRemoteParams(Sessao.ServidorImpressao.Servidor, Sessao.ServidorImpressao.Porta, Sessao.ServidorImpressao.Usuario, Sessao.ServidorImpressao.Senha, Sessao.ServidorImpressao.Alias, NomeArquivo);
FDataModule.VCLReport.Report.Params.ParamByName('PERIODOAPURACAO').Value := EditPeriodoApuracao.Text;
FDataModule.VCLReport.Report.Params.ParamByName('DATAVENCIMENTO').Value := EditDataVencimento.Text;
FDataModule.VCLReport.Report.Params.ParamByName('CODIGORECEITA').Value := EditCodigoReceita.Text;
FDataModule.VCLReport.Report.Params.ParamByName('NUMEROREFERENCIA').Value := EditNumeroReferencia.Text;
FDataModule.VCLReport.Report.Params.ParamByName('VALORPRINCIPAL').Value := EditValorPrincipal.Value;
FDataModule.VCLReport.Report.Params.ParamByName('VALORMULTA').Value := EditValorMulta.Value;
FDataModule.VCLReport.Report.Params.ParamByName('VALORJURO').Value := EditValorJuros.Value;
FDataModule.VCLReport.Report.Params.ParamByName('VALORTOTAL').Value := EditValorTotal.Value;
//
FDataModule.VCLReport.GetRemoteDataInfo(Sessao.ServidorImpressao.Servidor, Sessao.ServidorImpressao.Porta, Sessao.ServidorImpressao.Usuario, Sessao.ServidorImpressao.Senha, Sessao.ServidorImpressao.Alias, NomeArquivo);
RemoteDataInfo := FDataModule.VCLReport.Report.RemoteDataInfo;
//
ConsultaSQL := '';
FDataModule.VCLReport.ExecuteRemote(Sessao.ServidorImpressao.Servidor, Sessao.ServidorImpressao.Porta, Sessao.ServidorImpressao.Usuario, Sessao.ServidorImpressao.Senha, Sessao.ServidorImpressao.Alias, NomeArquivo, ConsultaSQL);
except
on E: Exception do
Application.MessageBox(PChar('Ocorreu um erro na construção do relatório. Informe a mensagem ao Administrador do sistema.' + #13 + #13 + E.Message), 'Erro do sistema', MB_OK + MB_ICONERROR);
end;
finally
end;
*)
end;
procedure TFFolhaInformativosGuias.ActionLerRetornoExecute(Sender: TObject);
begin
/// EXERCICIO: Implemente o LerRetorno240
end;
procedure TFFolhaInformativosGuias.ActionGerarRemessaExecute(Sender: TObject);
var
ACBrBancoBrasil: TACBrBancoBrasilFolha;
begin
ACBrBancoBrasil := TACBrBancoBrasilFolha.Create;
ACBrBancoBrasil.SaveFileTXT('c:\t2ti\remessa_folha_bb.txt');
Showmessage('Arquivo Gerado com Sucesso');
end;
end.
|
unit CommonFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, BaseObjects, BaseGUI, ComCtrls, FramesWizard, CoreInterfaces, LoggerImpl;
type
TfrmCommonFrame = class;
TCommonFrameClass = class of TfrmCommonFrame;
TfrmCommonFrame = class(TFrame, ILogger)
StatusBar: TStatusBar;
procedure StatusBarDrawPanel(StatusBar: TStatusBar;
Panel: TStatusPanel; const Rect: TRect);
private
FEditingClass: TIDObjectClass;
FParentClass: TIDObjectClass;
FInspector: THintManager;
FNeedCopyState: boolean;
FShadeEditingObject: TIDObject;
FNeedsShadeEditing: boolean;
FShowStatus: boolean;
FViewOnly: Boolean;
FDataLoaded: boolean;
procedure SetEditingObject(const Value: TIDObject);
function GetShadeEditingObject: TIDObject;
procedure SetShowStatus(const Value: boolean);
function GetLogger: TMemoLogger;
protected
FEditingObject: TIDObject;
FSaved: boolean;
FEdited: boolean;
procedure FillControls(ABaseObject: TIDObject); virtual;
procedure ClearControls; virtual;
procedure FillParentControls; virtual;
procedure RegisterInspector; virtual;
procedure CheckEvent(Sender: TObject);
function InternalCheck: boolean; virtual;
function GetParentCollection: TIDObjects; virtual;
procedure CopyEditingValues(Dest: TIDObject); virtual;
procedure SetViewOnly(const Value: Boolean); virtual;
function GetEditingObject: TIDObject;
public
property DataLoaded: boolean read FDataLoaded write FDataLoaded;
property Logger: TMemoLogger read GetLogger implements ILogger;
property Inspector: THintManager read FInspector write FInspector;
function Check: boolean; virtual;
function UnCheck: boolean;
property EditingClass: TIDObjectClass read FEditingClass write FEditingClass;
property ParentClass: TIDObjectClass read FParentClass write FParentClass;
property EditingObject: TIDObject read GetEditingObject write SetEditingObject;
property ShadeEditingObject: TIDObject read GetShadeEditingObject;
property NeedsShadeEditing: boolean read FNeedsShadeEditing write FNeedsShadeEditing;
property ShowStatus: boolean read FShowStatus write SetShowStatus;
property ParentCollection: TIDObjects read GetParentCollection;
property Edited: boolean read FEdited write FEdited;
property Saved: boolean read FSaved;
property ViewOnly: Boolean read FViewOnly write SetViewOnly;
procedure Clear; virtual;
procedure Save(AObject: TIDObject = nil); virtual;
procedure CancelEdit; virtual;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
implementation
{$R *.dfm}
{ TBaseFrame }
procedure TfrmCommonFrame.CancelEdit;
begin
end;
function TfrmCommonFrame.Check: boolean;
begin
Result := FInspector.Check and InternalCheck;
if Owner is TDialogFrame then
with Owner as TDialogFrame do
begin
btnNext.Enabled := (NextActiveFrameIndex < FrameCount - 1) and Result;
if FinishEnableIndex > -1 then
btnFinish.Enabled := (FrameCount > 0) and (NextActiveFrameIndex >= FinishEnableIndex)
else btnFinish.Enabled := (FrameCount > 0) and not btnNext.Enabled;
btnFinish.Enabled := btnFinish.Enabled and Result;
end;
end;
procedure TfrmCommonFrame.CheckEvent(Sender: TObject);
begin
Check;
end;
procedure TfrmCommonFrame.Clear;
begin
FEditingObject := nil;
FShadeEditingObject := nil;
ClearControls;
end;
procedure TfrmCommonFrame.ClearControls;
begin
FEditingObject := nil;
FShadeEditingObject := nil;
FDataLoaded := false;
end;
procedure TfrmCommonFrame.CopyEditingValues(Dest: TIDObject);
begin
end;
constructor TfrmCommonFrame.Create(AOwner: TComponent);
begin
inherited;
FEdited := false;
FSaved := false;
FNeedCopyState := true;
FEditingClass := TIDObject;
FNeedsShadeEditing := true;
FShowStatus := true;
FInspector := THintManager.Create(StatusBar);
FInspector.CheckEvent := CheckEvent;
end;
destructor TfrmCommonFrame.Destroy;
begin
FInspector.Free;
inherited;
end;
procedure TfrmCommonFrame.FillControls(ABaseObject: TIDObject);
begin
FShadeEditingObject := nil;
DataLoaded := Assigned(EditingObject);
end;
procedure TfrmCommonFrame.FillParentControls;
begin
DataLoaded := Assigned(EditingObject);
end;
function TfrmCommonFrame.GetEditingObject: TIDObject;
begin
Result := FEditingObject;
end;
function TfrmCommonFrame.GetLogger: TMemoLogger;
begin
Result := TMemoLogger.GetInstance;
end;
function TfrmCommonFrame.GetParentCollection: TIDObjects;
begin
Result := nil;
end;
function TfrmCommonFrame.GetShadeEditingObject: TIDObject;
begin
if NeedsShadeEditing then
begin
if not Assigned(FShadeEditingObject) then
begin
if Assigned(EditingObject) and (EditingObject is EditingClass) then
FShadeEditingObject := EditingClass.Create(ParentCollection)
else
if Assigned(EditingObject) and (EditingObject is ParentClass) then
FShadeEditingObject := EditingClass.Create(ParentCollection) as TIDObject
else
FShadeEditingObject := EditingClass.Create(nil) as TIDObject;
end;
Result := FShadeEditingObject;
end
else Result := FEditingObject;
CopyEditingValues(Result);
end;
function TfrmCommonFrame.InternalCheck: boolean;
begin
Result := true;
end;
procedure TfrmCommonFrame.RegisterInspector;
begin
FInspector.Clear;
end;
procedure TfrmCommonFrame.Save(AObject: TIDObject = nil);
begin
FEdited := false;
FSaved := true;
end;
procedure TfrmCommonFrame.SetEditingObject(const Value: TIDObject);
begin
if (Value = nil) and ((not Edited) or Saved) then ClearControls;
RegisterInspector;
if FEditingObject <> Value then
begin
FEditingObject := Value;
if Assigned(FEditingObject) and (FEditingObject.ID > 0) and (FEditingObject is EditingClass) then
FillControls(nil)
else if (Assigned(FEditingObject) and
(FEditingObject.ID <= 0) and (FEditingObject is EditingClass)) then
begin
FillControls(nil);
FillParentControls;
end
else if (Assigned(FEditingObject) and Assigned(ParentClass) and (FEditingObject is ParentClass)) then
FillParentControls
else ClearControls;
if Assigned(FEditingObject) then
begin
StatusBar.Panels[1].Text := FEditingObject.List;//(loBrief, false, true);
StatusBar.Hint := StatusBar.Panels[1].Text;
Caption := StatusBar.Panels[1].Text;
StatusBar.ShowHint := true;
end
end;
FEdited := true;
FSaved := false;
Check;
end;
procedure TfrmCommonFrame.SetShowStatus(const Value: boolean);
begin
FShowStatus := Value;
StatusBar.Visible := FShowStatus;
end;
procedure TfrmCommonFrame.SetViewOnly(const Value: Boolean);
begin
FViewOnly := Value;
end;
function TfrmCommonFrame.UnCheck: boolean;
var i: integer;
begin
Result := true;
if Owner is TDialogFrame then
with Owner as TDialogFrame do
begin
btnNext.Enabled := (ActiveFrameIndex < FrameCount);
if FinishEnableIndex > -1 then
btnFinish.Enabled := (FrameCount > 0) and (ActiveFrameIndex >= FinishEnableIndex)
else btnFinish.Enabled := (FrameCount > 0) and not btnNext.Enabled;
for i := 0 to StatusBar.Panels.Count - 2 do
StatusBar.Panels[i].Text := '';
end;
end;
procedure TfrmCommonFrame.StatusBarDrawPanel(StatusBar: TStatusBar;
Panel: TStatusPanel; const Rect: TRect);
begin
with StatusBar.Canvas do
begin
case Panel.Index of
0: //fist panel
begin
if Panel.Text <> '' then
Brush.Color := clRed
else
Brush.Color := clGreen;
FillRect(Rect) ;
TextRect(Rect, 1 + Rect.Left, 1 + Rect.Top,Panel.Text) ;
end;
end;
end;
end;
end.
|
// Copyright 2018 by John Kouraklis and Contributors. All Rights Reserved.
//
// 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 Casbin.Core.Logger.Base;
interface
uses
Casbin.Core.Base.Types, Casbin.Core.Logger.Types;
{$I ..\Casbin.inc}
type
{$REGION 'This is the base logger class. It does not do anything. You can expand the functionality by subclassing this one'}
/// <summary>
/// <para>
/// This is the base logger class. It does not do anything.
/// </para>
/// <para>
/// You can expand the functionality by subclassing this one
/// </para>
/// </summary>
{$ENDREGION}
TBaseLogger = class (TBaseInterfacedObject, ILogger)
private
{$REGION 'Interface'}
function getEnabled: Boolean;
function getLastLoggedMessage: string;
procedure setEnabled(const aValue: Boolean);
function getEnableConsole: Boolean;
procedure setEnableConsole(const Value: Boolean);
{$ENDREGION}
public
protected
fEnabled: Boolean;
fEnableConsole: boolean;
fLastLoggedMessage: string; //PALOFF
{$REGION 'Interface'}
procedure log(const aMessage: string); virtual;
{$ENDREGION}
public
constructor Create;
end;
implementation
uses
System.SysUtils;
constructor TBaseLogger.Create;
begin
inherited;
fEnabled:=True;
fEnableConsole:={$IFDEF CASBIN_DEBUG}True{$ELSE}False{$ENDIF};
end;
{ TBaseLogger }
function TBaseLogger.getEnableConsole: Boolean;
begin
result:=fEnableConsole;
end;
function TBaseLogger.getEnabled: Boolean;
begin
result:=fEnabled;
end;
function TBaseLogger.getLastLoggedMessage: string;
begin
Result:=fLastLoggedMessage;
end;
procedure TBaseLogger.log(const aMessage: string);
begin
if fEnabled then
fLastLoggedMessage:=trim(aMessage)
else
fLastLoggedMessage:='';
end;
procedure TBaseLogger.setEnableConsole(const Value: Boolean);
begin
fEnableConsole:=Value;
end;
procedure TBaseLogger.setEnabled(const aValue: Boolean);
begin
fEnabled:=aValue;
fLastLoggedMessage:='';
end;
end.
|
unit CommonUnitEng;
interface
uses Controls;
type
TBlock=record
id:integer; {номер по списку}
id_logical:integer; {номер логический}
type_block:string[20];
end;
TAgency=record
Name:string[10];
id:integer;
server:string[20];
isOldFormat:boolean;
Name_ext:string[10];
Dbase:string[20];
end;
TChannel=record
id:integer;
Name:string;
Ext:string;
delta:integer;
end;
TSetter=record
Name:string;
id:integer;
end;
TServer=record
Server,DataBase,BaseName,UserName,Password,FirstChar:String[40];
id_agency:integer;
isOldFormat:boolean;
end;
//Работа с телефонами и другие вспомогательные
function FindPhone(var str:string;var phone:integer):boolean;
function FindPhone2(var strng:string;var phone:Longint):boolean;
function PhoneToPhoneNew(var ANum:int64):boolean;
function PhoneToPhoneOld(var ANum:int64):boolean;{перевод любого телефона в 6-значный, даже если он уже не существует, например 7127244->127244}
function CalcBlock(const auction,forma:integer):integer;
function AuctionFromBlock(const id_block:integer):integer;
function FormaFromBlock(const id_block:integer):integer;
function CalcSignature(const str:string):integer;
function CalcLongSignature(const strng:string):Int64;
//работа с текстовыми строками и датами
function AddSpaces(const Strn:string;len:integer):string;
function AddSpaces2(Strn:string;lenStrn:integer;isLeftAlign:boolean):string;
function isRussianChars(const Strng:string):boolean;
function CheckLength(const Str:string):integer;
procedure DosToWin(var Str:string);
procedure WinToDos(var Str:string);
procedure WinToDosInByte(var chr:byte);
function ConvertDateToFName(const D:TDateTime):string;
function ConvertDateToStr(const D:TDateTime):string;
function DeleteReturns(const A:string):string;
function DeleteFirstSpaces(const A:string):string;
function MondayOfDate(const Day:TDate):TDate;
function DayOfWeekRussian(CurDate:TDateTime):integer;
function DetectDay(CurDate:TDateTime):string;
function Decrypt(const AStrng:string):String;
//Процедуры работы с реестром
function WriteToRegistry(const FVar,FProg,FName:string):boolean;
function ReadFromRegistry(var FVar:string;const FProg,FName:string):boolean;
function NameToDeposit(const FStr:string;const Gazeta:integer):string;
function GetUser(var AUser,APWD,AName:string;var AID:integer):boolean; //Читается из реестра
function SetUser(const AUser,APWD,AName:string;const AID:integer):boolean;//записывается в реестр
function DetectDCOM:boolean;//Определение чтением из реестра
function DetectMDAC:boolean;//Определение чтением из реестра
//Функции работы с именами файлов и путями, определение имени программы
function SaveFileToDir(const Source,Dir:string;const IDRub:integer):boolean;
function MoveFile(const Source,Dest:string):boolean;
function CopyFile(const Source,Dest:string;var MessageStr:string):boolean;
function DeleteFolder(const DirDest:string):boolean;
function GetProgName:string;//Функция определяет имя программы
function GetProgDir:string;//Функция определяет путь запускаемой программы
function GetProgDirWOLetter:string;//Функция определяет путь запускаемой программы без первой буквы (С:)
implementation
uses Registry, Windows,Classes, Sysutils, Dialogs;
function DayOfWeekRussian(CurDate:TDateTime):integer;
begin
Result:=DayOfWeek(CurDate)-1;
if Result=0 then Result:=7;
end;
function DetectDay(CurDate:TDateTime):string;
begin
case DayOfWeek(CurDate) of
1:Result:='Sunday';
2:Result:='Monday';
3:Result:='Tuesday';
4:Result:='Wednesday';
5:Result:='Thursday';
6:Result:='Friday';
7:Result:='Saturday';
end; {case}
end;
function ConvertDateToStr(const D:TDateTime):string;
var Year, Month, Day: Word;Str:String;
begin
DecodeDate(D,Year,Month,Day);
if Day>9 then Str:=IntToStr(Day)
else Str:='0'+IntToStr(Day);
Str:=Str+'.';
if Month>9 then Str:=Str+IntToStr(Month)
else Str:=Str+'0'+IntToStr(Month);
Str:=Str+'.';
Result:=Str+IntToStr(Year);
end;
function ConvertDateToFName(const D:TDateTime):string;
var Year, Month, Day: Word;StrName:string;
begin
DecodeDate(D,Year,Month,Day);
case Month of
1:StrName:='jan';
2:StrName:='feb';
3:StrName:='mar';
4:StrName:='apr';
5:StrName:='may';
6:StrName:='june';
7:StrName:='july';
8:StrName:='aug';
9:StrName:='sept';
10:StrName:='oct';
11:StrName:='nov';
12:StrName:='dec';
else begin MessageDlg('Internal error in program while converting data',mtError,[mbOK],0);Result:='???';end;
end;{case}
if Day>9 then StrName:=IntToStr(Day)+StrName
else StrName:='0'+IntToStr(Day)+StrName;
Result:=StrName;
end;
function CalcBlock(const auction,forma:integer):integer;
begin
{Функция рассчитывает тип id_block из forma auction.
При превышении правил она формирует id_block "по максимуму" для восстановления сбоев с минимальными потерями}
Result:=106;
if (forma=0) and (auction>=3) then Result:=101; {обычн}
if (forma>=1) and(auction>=4) then Result:=103; {выделен}
if (forma>=3)and (auction>=3) then Result:=102; {рамка}
if (forma>=4)and (auction>=6) then Result:=104; {дайджест}
end;
function AuctionFromBlock(const id_block:integer):integer;
{ TODO : Функция вычисляет поле auction для старых баз из id_block.
Правило такое:
для А/ТВК результат всегда 0
Для br (101) результат 0+3, возврат 3
Для ram (102)результат 3+3, возврат 3
Для vd (103) результат 1+4, возврат 4
Для didj (104)результат 4+6, возврат 6
Для code (105)результат 0+3, возврат 3
Для free (106,107) результат 0+0, возврат 0
Это правило может измениться}
begin
case id_block of
101:Result:=3;
102:Result:=3;
103:Result:=4;
104:Result:=6;
105:Result:=3
else Result:=0;
end; {case}
end;
function FormaFromBlock(const id_block:integer):integer;
{ TODO : Функция вычисляет поле forma для старых баз из id_block
Правило такое:
для А/ТВК результат всегда 0
Для br (101) результат 0+3, возврат 0
Для ram (102)результат 3+3, возврат 3
Для vd (103) результат 1+4, возврат 1
Для didj (104)результат 4+6, возврат 4
Для code (105)результат 0+3, возврат 0
Для free (106,107) результат 0+0, возврат 0
Это правило может измениться}
begin
case id_block of
101:Result:=0;
102:Result:=3;
103:Result:=1;
104:Result:=4;
else Result:=0;
end; {case}
end;
function CalcSignature(const str:string):integer;
var i:integer;R:integer;
begin
R:=0;
for i:=1 to length(str) do R:=R+word(str[i]);
result:=R mod 5000;
end;
function CalcLongSignature(const strng:string):Int64;
var i,j, Len:integer;
Step:int64;
R:array of byte;
Res:array[1..8] of byte;
//Расчет фукции хэширования на поразрядном XOR. Размер 8 байт, 64 бит
//Переводим строку 8-битовых char в буфер
begin
try
if length(Strng)=0 then begin result:=0;exit;end;
Len:=1+(length(strng) div 8);
SetLength(R,8+Len*9);
for i:=1 to Len*8 do
begin
if i<=length(strng)
then R[i]:=Byte(Strng[i])
else R[i]:=$A5;
end;
for j:=1 to 8 do Res[j]:=0;
for j:=1 to 8 do
for i:=1 to Len do //проход от второго до последнего столбца
Res[j]:=Res[j] XOR R[i*8+j];
Result:=1;
Step:=1;
for i:=1 to 8 do
begin
Result:=Result+Res[i]*Step;
Step:=Step*256;
end;
{ TODO : Убрать проверку в релизе }
except on E:Exception do
ShowMessage('Exception in CalcLongSignature');
end;
end;
function MondayofDate(const Day:TDate):TDate;
var DWeek:integer;
begin
DWeek:=DayOfWeek(Day);
case Dweek of
1:Result:=Day-6;
2:Result:=Day;
3:Result:=Day-1;
4:Result:=Day-2;
5:Result:=Day-3;
6:Result:=Day-4;
7:Result:=Day-5;
else Result:=0;
end;
end;
function CheckLength(const Str:string):integer;
var i,j,words,max_mas:integer;Mas:array[1..200] of integer;
begin
words:=0;
j:=1;Mas[1]:=1;
for i:=1 to length(str) do
begin
if (str[i] =' ') then begin inc(j);Mas[j]:=i;end;
end;
max_mas:=j;
for j:=1 to max_mas-1 do
if Mas[j+1]-Mas[j]>3 then begin inc(words);end;
Result:=1+words div 20;
end;
procedure WinToDos(var Str:string);
var i:integer;ch:byte;
begin
for i:=1 to Length(Str) do
begin
ch:=byte(str[i]);
if (ch>=192)and(ch<=239) then str[i]:=char(ch-64);
if (ch>=240) then str[i]:=char(ch-16);
if ch=$A8 then str[i]:=char($F0);
if ch=$B8 then str[i]:=char($F1);
if ch=$B9 then str[i]:=char($FC);
end;
end;
procedure WinToDosInByte(var chr:byte);
var ch:byte;
begin
ch:=chr;
if (ch>=192)and(ch<=239) then chr:=ch-64;
if (ch>=240) then chr:=ch-16;
if ch=$A8 then chr:=$F0;
if ch=$B8 then chr:=$F1;
if ch=$B9 then chr:=$FC;
end;
procedure DosToWin(var Str:string);
var i:integer;ch:byte;
begin
for i:=1 to Length(Str) do
begin
ch:=byte(str[i]);
if (ch>=128)and(ch<=175) then str[i]:=char(ch+64);
if (ch>=224)and(ch<=239) then str[i]:=char(ch+16);
if (ch=240) then str[i]:='Ё';
if (ch=241) then str[i]:='ё';
if (ch=242) then str[i]:='Є';
if (ch=243) then str[i]:='є';
if (ch=244) then str[i]:='Ї';
if (ch=245) then str[i]:='ї';
end;
end;
function FindPhone(var str:string;var phone:integer):boolean;
var pstn:integer;strphone:string;phone64:int64;
begin
{При нахождении телефона он удалется из присылаемой строки и заполняется phone
Если телефона нет, то Result:=false
Снаружи должна стоять проверка на Result и на размер возвращаемой строки
Если стока пустая то искать дальше не имеет смысла
Правило телефона следующее:
если это межгород, то телефон начинается с 8 и далее 10 цифр и тире
используются ли скобки? непонятно но неплохо было бы использовать
разделителями в межгороде являются тире и скобки, всего 11 цифр включая ведущую 8
если это город, то в нем 5,6 или 7 цифр и одно-два тире, скобок нет, это требование жесткое
разделителями являются только тире, остальные знаки не входят }
{ TODO : сейчас межгородские телефоны не блокируются, доработать }
{если телефон найден то телефон из строки удаляется и result:=true}
{Алгоритм поиска следующий: удаляем ведущие символы до первой цифры,
затем копируем в новую строку начиная с первой цифры до символа-разделителя
и удалем скопированное в первоначальной строке}
Result:=true;
while (length(str)>4) do
if not (str[1] in ['0'..'9','(']) then delete(str,1,1) else break;
if length(str)<5 then begin Result:=false;str:='';exit;end;
pstn:=1;
repeat
if not(str[pstn] in ['0'..'9','-','(',')']) then break
else inc(pstn);
until pstn>length(str);
dec(pstn);
strphone:=Copy(str,1,pstn);
Str:=Copy(str,pstn+1,length(str)-pstn);
{Теперь крутим strphone как можем на предмет телефонности.
Если strphone не имеет телефона,то запускаем еще раз,выход по первому exit для которого length<5}
if (pos('-',strphone)=0) then begin Result:=false;exit;end;
{Если нет минуса- не телефон}
if (pos('-',strphone)=length(strphone)) then begin Result:=false;exit;end;
{Если минус в конце - не телефон}
while pos('-',strphone)>0 do delete(strphone,pos('-',strphone),1);
while pos('(',strphone)>0 do delete(strphone,pos('(',strphone),1);
while pos(')',strphone)>0 do delete(strphone,pos(')',strphone),1);
if strphone[1]='8' then Delete(strphone,1,1); {храним без ведущей 8, иначе не входит в размер integer}
if not((length(strphone)=6)or(length(strphone)=7)or(length(strphone)=10)) then begin Result:=false;exit;end;
try
phone64:=StrToInt64(strPhone);
except on E:EConvertError do
begin
ShowMessage('Ошибка программы, при конвертировании в телефон');
Result:=false;
phone64:=0;
str:='';
end;
end;
if (phone64<2147483647)and(phone64>99999) then phone:=phone64
else
begin
Result:=false;
phone:=0;
end;
end;
function FindPhone2(var strng:string;var phone:Longint):boolean;
var i,pstn:integer;Strn2, strphone:string;
begin
{Внимание! Строка изменяется при работе,сделать копию если нужно её сохранить в БД
При нахождении телефона он удалется из присылаемой строки и заполняется phone
Если телефона нет, то Result:=false. Снаружи должна стоять проверка на
while FindPhone2() do
Алгоритм поиска следующий:
Удаляем ВСЕ символы оставляем только цифры и разделители.
ВСе разделители переводим в ";" убираем "," и "("
Если в конце не стоит разделитель, добавляем его.
Убираем двойные разделители если они есть.
Затем копируем в новую строку B начиная с первой цифры до разделителя
и удалем скопированное в первоначальной строке.
Из новой строки B формируем телефон
Если цифр в строке B больше не осталось, возвращаем false
Если цифры в строке В не являются телефоном}
if length(Strng)<4 then begin phone:=0; Result:=false;exit;end;
Strn2:='';
while Pos('(044)',Strng)>0 do Delete(Strng,Pos('(044)',Strng),5);
for i:=1 to length(Strng) do
begin
if strng[i] in ['0'..'9',';'] then Strn2:=Strn2+Strng[i];
if (strng[i]='(')or(strng[i]=',') then Strn2:=Strn2+';';
end;
Strn2:=Strn2+';';
while (pos(';;',strn2)>0) do
delete(strn2,pos(';;',strn2),1);
while Pos(';',Strn2)=1 do delete(strn2,1,1);
Pstn:=Pos(';',Strn2);
Strphone:=Copy(Strn2,1,pstn-1);
Strn2:=Copy(strn2,pstn+1,length(strn2)-pstn);
Result:=true;
if (length(Strn2)>7) and (Strn2[1]='8') then Delete(Strn2,1,1);
if length(StrPhone)<7 then
begin
//Почему-то неверно определился телефон, перестраховка
Phone:=0;
Result:=false;
exit;
end;
Strng:=Strn2;
try
phone:=StrToInt64(strPhone);
except on E:EConvertError do
begin
Result:=false;
phone:=0;
end;
end;
end;
function GetProgDir:string;
begin
Result:=ExtractFileDir(Paramstr(0));
end;
function GetProgDirWOLetter:string;
var FStr:string;
begin
FStr:=ExtractFileDir(Paramstr(0));
Result:=Copy(FStr,3,length(FStr)-2);
end;
function GetProgName:string;
begin
Result:=ExtractFileName(Paramstr(0));
end;
function DeleteReturns(const A:string):string;
var i:integer;strng:string;
begin
strng:=A;
for i:=1 to length(strng) do
if strng[i] in [char(13),char(10)] then strng[i]:=' ';
Result:=strng;
end;
function DeleteFirstSpaces(const A:string):string;
var strng:string;
begin
if length(A)<1 then
begin
Result:='';
exit;
end;
strng:=A;
while pos(' ',strng)=1 do Delete(strng,1,1);
Result:=strng;
end;
function PhoneToPhoneNew(var ANum:int64):boolean;
begin
{Процедура переводит телефон Num в новый
Обрабатываются следующие ситуации:
Телефон не 6-значный или неверный 7-значный - возвращаем false, Num не изменился
Телефон старый 6-значный - возврат 7-значного и true
Телефон 6-значный без семерок - возврат true, Num не изменился}
{710,711,712,713,715,770,771,772,773,774,775,776,777,778,779}
if (ANum>80100000000)and(ANum<89999999999) then
begin
ANum:=ANum-80000000000;
Result:=true;
exit;
end;
if (ANum<100000)or(ANum>7999999) then
begin
Result:=false;
exit;{неверный телефон}
end;
if (ANum>=100000)and(ANum<=999999) then
begin
Result:=true;
if (ANum div 10000 in [10,11,12,13,15,70,71,72,73,74,75,76,77,78,79]) then ANum:=ANum+7000000;
end
else
begin
Result:=((ANum-7000000) div 10000 in [10,11,12,13,15,70,71,72,73,74,75,76,77,78,79]);
end;
end;
function PhoneToPhoneOld(var ANum:int64):boolean;
begin
{Процедура переводит телефон Num в шестизначный
Обрабатываются следующие ситуации:
Сотовый телефон - добавляем 80 и возвращаем
Диапазон сотовых телефонов от 80-10 000-00-00 до 80-99 999-99-99
Новый телефон неверный - возвращаем false, Num не изменился
Телефон верный 7-значный - возврат true, тот же телефон без 7 в начале
Телефон любой 6-значный - возврат true, тот же телефон }
{710,711,712,713,715,770,771,772,773,774,775,776,777,778,779}
{Проверка диапазона телефонов}
if (ANum>100000000)and(ANum<999999999) then
begin
ANum:=ANum+80000000000;
Result:=true;
exit;
end;
if (ANum<100000)or(ANum>7999999) then
begin
Result:=false;
exit;{неверный телефон}
end;
{Является ли 7-значным телефон}
if (ANum>=1000000)and(ANum<7999999)
then
begin
Result:=((ANum-7000000) div 10000 in [10,11,12,13,15,70,71,72,73,74,75,76,77,78,79]);
if Result then ANum:=ANum-7000000;
end
{Если телефон 6-значный другая проверка}
else Result:=true;
end;
function GetUser(var AUser,APWD,AName:string;var AID:integer):boolean;
{Процедура читает имя пользователя из реестра. Если имя не указано или нет такого реестра, то выдается false}
var R:TRegistry;
begin
R:=TRegistry.Create;
try
R.Rootkey:=HKEY_LOCAL_MACHINE;
R.OpenKey('SOFTWARE\PterikSoft\TyperADS',False);
AUSER:=R.ReadString('USER');
APWD:=R.ReadString('PWD');
AName:=R.ReadString('Name');
AID:=R.ReadInteger('ID');
R.CloseKey;
except on E:ERegistryException do
begin
Result:=false;
R.Free;
exit;
end;
end;
Result:=true;
if (AUSER='')or(APWD='') then Result:=false;
R.Free;
end;
function SetUser(const AUser,APWD,AName:string;const AID:integer):boolean;
{Процедура устанавливает/изменяет значения имени и пароля в реестре}
var R:TRegistry;
begin
R:=TRegistry.Create;
try
R.Rootkey:=HKEY_LOCAL_MACHINE;
R.OpenKey('SOFTWARE\PterikSoft\TyperADS',true);
R.WriteString('USER',AUser);
R.WriteString('PWD',APWD);
R.WriteString('Name',AName);
R.WriteInteger('ID',AID);
R.CloseKey;
except on E:ERegistryException do
begin
Result:=false;
R.Free;
exit;
end;
end;
Result:=true;
R.Free;
end;
function WriteToRegistry(const FVar,FProg,FName:string):boolean;
var R:TRegistry;
begin
R:=TRegistry.Create;
try
R.Rootkey:=HKEY_LOCAL_MACHINE;
R.OpenKey('SOFTWARE\PterikSoft\'+FProg,True);
R.WriteString(FName,FVar);
R.CloseKey;
except on E:ERegistryException do
begin
MessageDlg('Internal error, program may not write into registry. Please contact to developer.',mtError,[mbOK],0);
R.Free;
Result:=false;
exit;
end;
end;
R.Free;
Result:=true;
end;
function ReadFromRegistry(var FVar:string;const FProg,FName:string):boolean;
var R:TRegistry;
begin
R:=TRegistry.Create;
try
R.Rootkey:=HKEY_LOCAL_MACHINE;
R.OpenKey('SOFTWARE\PterikSoft\'+FProg,False);
FVar:=R.ReadString(FName);
except on E:ERegistryException do
begin
R.Free;
Result:=false;
exit;
end;
end;
if FVar='' then Result:=false else Result:=true;
//Если прочитало пустую строку, то в действительности не прочитало
end;
function DetectDCOM:boolean;
var S:String;R:TRegistry;
begin
Result:=False;
R:=TRegistry.Create;
try
R.Rootkey:=HKEY_LOCAL_MACHINE;
R.OpenKey('SOFTWARE\Microsoft\OLE',False);
S:=UpperCase(R.ReadString('EnableDCOM'));
if S='Y' then Result:=true;
R.CloseKey;
finally R.Free;end;
end;
function DetectMDAC:boolean;
var R:TRegistry;
begin
Result:=False;
R:=TRegistry.Create;
try
R.Rootkey:=HKEY_CLASSES_ROOT;
R.OpenKey('\ADODB.Connection\CurVer',False);
if R.ReadString('')<>'' then Result:=true;
R.CloseKey;
finally R.Free;end;
end;
procedure MakeXOR(var AByte:Char;const BByte:integer);
begin
AByte:=char(integer(AByte) XOR BByte);
end;
function Decrypt(const AStrng:string):String;
var i:integer;Bt:char;Str2:string[100];
begin
Str2:=AStrng;
for i:=1 to length(AStrng) do
begin
Bt:=AStrng[i];
MakeXOR(Bt,$96);
Str2[i]:=Bt;
end;
Result:=Str2;
end;
function NameToDeposit(const FStr:string;const Gazeta:integer):string;
var RPath:string;
begin
if not ReadFromRegistry(Rpath,GetProgName,'Repository') then MessageDlg('Internal error in program. Path to repositary is invalid. Please contact to developer.',mtError,[mbOK],0);
Result:=RPath+'\'+FStr[1];
end;
function SaveFileToDir(const Source,Dir:string;const IDRub:integer):boolean;
{Процедура переписывает файл с именем FName в директорию Dir с именем IDRub+FShortName
Если указать idRub<0 то номер опускается, если указать idRub=0 то номер =000
Если возникает ошибка при записи, возвращается false. Все в порядке - возврат true }
var Dest,MessageStr:string;
begin
Dest:=ExtractFileName(Source);//Вырезаем короткое имя
if IDRUb<0 then Dest:=Dir+'\'+Dest else
if IDRub=0 then Dest:=Dir+'\000_'+Dest
else Dest:=Dir+'\'+Format('%d',[idRub])+'_'+Dest;
if not CopyFile(Source,Dest,MessageStr) then begin MessageDlg(MessageStr,mtError,[mbOK],0);Result:=false;end
else Result:=true;
end;
function MoveFile(const Source,Dest:string):boolean;
var MessageStr:string;
begin
if not CopyFile(Source,Dest,MessageStr) then begin MessageDlg(MessageStr,mtError,[mbOK],0);Result:=false;exit;end;
if not DeleteFile(PChar(Source)) then MessageDlg('Can`t delete file'+Source,mtInformation,[mbOK],0);
Result:=true;
end;
function CopyFile(const Source,Dest:string;var MessageStr:string):boolean;
//Процедура переписывает файл с именем FName в файл Dest
//Если возникает ошибка при записи, возвращается false и MessageStr. Все в порядке - возврат true
var S,D:TFileStream;
FHSource,FHDest:integer;
begin
Result:=true;
try //EOpen error
S:=TFileStream.Create(Source,fmOpenRead);
except on E:EFOpenError do
begin
MessageStr:='Can`t open file '+Source;
Result:=false;
exit;
end;
end;
try //ECreateError
D:=TFileStream.Create(Dest,fmOpenWrite or fmCreate);
except on E:EFCreateError do
begin
MessageStr:='Can`t create file '+Dest+'. Make sure disk drive is valid';
Result:=false;
D.Free;
exit;
end;
end;
try //EWriteError
D.CopyFrom(S,S.Size);
except on E:EWriteError do
begin
MessageStr:='Can`t write file '+Dest+'. Possible, no free disk space.';
Result:=false;
S.Free;
D.Free;
exit;
end;
end;
FreeandNil(D);
FreeAndNil(S);
if Result then
begin
FHSource:=FileOpen(Source,fmOpenRead);
FHDest:=FileOpen(Dest,fmOpenReadWrite);
FileSetDate(FHDest,FileGetDate(FHSource));
FileClose(FHSource);
FileClose(FHDest);
end;
end;
function DeleteFolder(const DirDest:string):boolean;
var DelFile:TSearchRec;
begin
Result:=true;
if FindFirst(DirDest+'\*.*',faAnyFile,DelFile)=0 then
repeat
if (DelFile.Name='.') or (DelFile.Name='..') then continue;
if (DelFile.Attr and faDirectory)=0 then
begin
if not DeleteFile(DirDest+'\'+DelFile.Name) then Result:=false;
end
else
begin
if not DeleteFolder(DirDest+'\'+DelFile.Name) then Result:=false;
end;
until FindNext(DelFile)<>0;
FindClose(DelFile);
if not RemoveDir(DirDest) then Result:=false;
end;
function isRussianChars(const Strng:string):boolean;
//Есть ли русские буквы в передаваемой строке
var i:integer;
begin
Result:=false;
for i:=1 to length(Strng) do
if Strng[i] in [char($80)..char($FF)] then Result:=true;
end;
function AddSpaces(const Strn:string;len:integer):string;
var k:integer;
Str2:string;
begin
Str2:=TrimLeft(Strn);
if length(Str2)>len then result:=Copy(Str2,1,len)
else
begin
Result:=Str2;
SetLength(Result,len);
for k:=length(Str2)+1 to len do Result[k]:=' ';
end;
end;
function AddSpaces2(Strn:string;lenStrn:integer;isLeftAlign:boolean):string;
var k:integer;
Str2:string;
begin
Strn:=trim(strn);
if Length(Strn)>=LenStrn then begin Result:=Strn;exit; end;
Str2:='';
for k:=Length(Strn)+1 to LenStrn do Str2:=' '+Str2;
if isLeftAlign then Result:=strn+Str2 else Result:=Str2+Strn;
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [SINDICATO]
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit SindicatoVO;
interface
uses
VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils;
type
[TEntity]
[TTable('SINDICATO')]
TSindicatoVO = class(TVO)
private
FID: Integer;
FNOME: String;
FCODIGO_BANCO: Integer;
FCODIGO_AGENCIA: Integer;
FCONTA_BANCO: String;
FCODIGO_CEDENTE: String;
FLOGRADOURO: String;
FNUMERO: String;
FBAIRRO: String;
FMUNICIPIO_IBGE: Integer;
FUF: String;
FFONE1: String;
FFONE2: String;
FEMAIL: String;
FTIPO_SINDICATO: String;
FDATA_BASE: TDateTime;
FPISO_SALARIAL: Extended;
FCNPJ: String;
FCLASSIFICACAO_CONTABIL_CONTA: String;
public
[TId('ID', [ldGrid, ldLookup, ldComboBox])]
[TGeneratedValue(sAuto)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property Id: Integer read FID write FID;
[TColumn('NOME', 'Nome', 450, [ldGrid, ldLookup, ldCombobox], False)]
property Nome: String read FNOME write FNOME;
[TColumn('CODIGO_BANCO', 'Codigo Banco', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property CodigoBanco: Integer read FCODIGO_BANCO write FCODIGO_BANCO;
[TColumn('CODIGO_AGENCIA', 'Codigo Agencia', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property CodigoAgencia: Integer read FCODIGO_AGENCIA write FCODIGO_AGENCIA;
[TColumn('CONTA_BANCO', 'Conta Banco', 160, [ldGrid, ldLookup, ldCombobox], False)]
property ContaBanco: String read FCONTA_BANCO write FCONTA_BANCO;
[TColumn('CODIGO_CEDENTE', 'Codigo Cedente', 240, [ldGrid, ldLookup, ldCombobox], False)]
property CodigoCedente: String read FCODIGO_CEDENTE write FCODIGO_CEDENTE;
[TColumn('LOGRADOURO', 'Logradouro', 450, [ldGrid, ldLookup, ldCombobox], False)]
property Logradouro: String read FLOGRADOURO write FLOGRADOURO;
[TColumn('NUMERO', 'Numero', 80, [ldGrid, ldLookup, ldCombobox], False)]
property Numero: String read FNUMERO write FNUMERO;
[TColumn('BAIRRO', 'Bairro', 450, [ldGrid, ldLookup, ldCombobox], False)]
property Bairro: String read FBAIRRO write FBAIRRO;
[TColumn('MUNICIPIO_IBGE', 'Municipio Ibge', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property MunicipioIbge: Integer read FMUNICIPIO_IBGE write FMUNICIPIO_IBGE;
[TColumn('UF', 'Uf', 16, [ldGrid, ldLookup, ldCombobox], False)]
property Uf: String read FUF write FUF;
[TColumn('FONE1', 'Fone1', 112, [ldGrid, ldLookup, ldCombobox], False)]
property Fone1: String read FFONE1 write FFONE1;
[TColumn('FONE2', 'Fone2', 112, [ldGrid, ldLookup, ldCombobox], False)]
property Fone2: String read FFONE2 write FFONE2;
[TColumn('EMAIL', 'Email', 450, [ldGrid, ldLookup, ldCombobox], False)]
property Email: String read FEMAIL write FEMAIL;
[TColumn('TIPO_SINDICATO', 'Tipo Sindicato', 8, [ldGrid, ldLookup, ldCombobox], False)]
property TipoSindicato: String read FTIPO_SINDICATO write FTIPO_SINDICATO;
[TColumn('DATA_BASE', 'Data Base', 80, [ldGrid, ldLookup, ldCombobox], False)]
property DataBase: TDateTime read FDATA_BASE write FDATA_BASE;
[TColumn('PISO_SALARIAL', 'Piso Salarial', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property PisoSalarial: Extended read FPISO_SALARIAL write FPISO_SALARIAL;
[TColumn('CNPJ', 'Cnpj', 112, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftCnpj, taLeftJustify)]
property Cnpj: String read FCNPJ write FCNPJ;
[TColumn('CLASSIFICACAO_CONTABIL_CONTA', 'Classificacao Contabil Conta', 240, [ldGrid, ldLookup, ldCombobox], False)]
property ClassificacaoContabilConta: String read FCLASSIFICACAO_CONTABIL_CONTA write FCLASSIFICACAO_CONTABIL_CONTA;
end;
implementation
initialization
Classes.RegisterClass(TSindicatoVO);
finalization
Classes.UnRegisterClass(TSindicatoVO);
end.
|
unit UnitHardInfo;
interface
uses
Windows, SysUtils,
NB30, WinSock, Registry, DateUtils;
const
ID_BIT = $200000; // EFLAGS ID bit
type
TCPUID = array[1..4] of Longint;
TVendor = array[0..11] of char;
function GetIdeNum: string;
function IsCPUID_Available: Boolean; register; //判断CPU序列号是否可用函数
function GetCPUID: TCPUID; assembler; register; //获取CPU序列号函数
function GetCPUVendor: TVendor; assembler; register; //获取CPU生产厂家函数
function GetCPUInfo: string; //CPU序列号(格式化成字符串)
function GetCPUSpeed: Double; //获取CPU速度函数
function GetDisplayFrequency: Integer; //获取显示器刷新率
function GetMemoryTotalSize: DWORD; //获取内存总量
function Getmac: string;
function GetHostName: string;
function NameToIP(Name: string): string;
function GetDiskSize: string;
function GetCPUName: string;
function GetIdeSerialNumber(): PChar; stdcall;
function spendtime(sj: tdatetime): string;
function GetCPUSN(InfoID: Byte): string;
type
PASTAT = ^TASTAT;
TASTAT = record
adapter: TAdapterStatus;
name_buf: TNameBuffer;
end;
implementation
//-----------------------------------------------------------------------
//获取CPU硬件信息
//-----------------------------------------------------------------------
//参数:
// InfoID:=1 获取CPU序列号
// InfoID:=2 获取CPU 频率
// InfoID:=3 获取CPU厂商
//-----------------------------------------------------------------------
function GetCPUSN(InfoID: Byte): string;
var
_eax, _ebx, _ecx, _edx: Longword;
i: Integer;
b: Byte;
b1: Word;
s, s1, s2, s3, s_all: string;
begin
case InfoID of //获取CPU序列号
1:
begin
asm
mov eax,1
db $0F,$A2
mov _eax,eax
mov _ebx,ebx
mov _ecx,ecx
mov _edx,edx
end;
s := IntToHex(_eax, 8);
s1 := IntToHex(_edx, 8);
s2 := IntToHex(_ecx, 8);
Insert('-', s, 5);
Insert('-', s1, 5);
Insert('-', s2, 5);
result := s + '-' + s1 + '-' + s2;
end;
2: //获取 CPU 频率
begin
asm //execute the extended CPUID inst.
mov eax,$80000000 //sub. func call
db $0F,$A2
mov _eax,eax
end;
if _eax > $80000000 then //any other sub. funct avail. ?
begin
asm //get brand ID
mov eax,$80000002
db $0F
db $A2
mov _eax,eax
mov _ebx,ebx
mov _ecx,ecx
mov _edx,edx
end;
s := '';
s1 := '';
s2 := '';
s3 := '';
for i := 0 to 3 do
begin
b := lo(_eax);
s3 := s3 + chr(b);
b := lo(_ebx);
s := s + chr(b);
b := lo(_ecx);
s1 := s1 + chr(b);
b := lo(_edx);
s2 := s2 + chr(b);
_eax := _eax shr 8;
_ebx := _ebx shr 8;
_ecx := _ecx shr 8;
_edx := _edx shr 8;
end;
s_all := trim(s3 + s + s1 + s2);
asm
mov eax,$80000003
db $0F
db $A2
mov _eax,eax
mov _ebx,ebx
mov _ecx,ecx
mov _edx,edx
end;
s := '';
s1 := '';
s2 := '';
s3 := '';
for i := 0 to 3 do
begin
b := lo(_eax);
s3 := s3 + chr(b);
b := lo(_ebx);
s := s + chr(b);
b := lo(_ecx);
s1 := s1 + chr(b);
b := lo(_edx);
s2 := s2 + chr(b);
_eax := _eax shr 8;
_ebx := _ebx shr 8;
_ecx := _ecx shr 8;
_edx := _edx shr 8;
end;
s_all := s_all + s3 + s + s1 + s2;
asm
mov eax,$80000004
db $0F
db $A2
mov _eax,eax
mov _ebx,ebx
mov _ecx,ecx
mov _edx,edx
end;
s := '';
s1 := '';
s2 := '';
s3 := '';
for i := 0 to 3 do
begin
b := lo(_eax);
s3 := s3 + chr(b);
b := lo(_ebx);
s := s + chr(b);
b := lo(_ecx);
s1 := s1 + chr(b);
b := lo(_edx);
s2 := s2 + chr(b);
_eax := _eax shr 8;
_ebx := _ebx shr 8;
_ecx := _ecx shr 8;
_edx := _edx shr 8;
end;
if s2[Length(s2)] = #0 then
setlength(s2, Length(s2) - 1);
result := s_all + s3 + s + s1 + s2;
end
else
result := '';
end;
3: //获取 CPU厂商
begin
asm //asm call to the CPUID inst.
mov eax,0 //sub. func call
db $0F,$A2 //db $0F,$A2 = CPUID instruction
mov _ebx,ebx
mov _ecx,ecx
mov _edx,edx
end;
for i := 0 to 3 do //extract vendor id
begin
b := lo(_ebx);
s := s + chr(b);
b := lo(_ecx);
s1 := s1 + chr(b);
b := lo(_edx);
s2 := s2 + chr(b);
_ebx := _ebx shr 8;
_ecx := _ecx shr 8;
_edx := _edx shr 8;
end;
result := s + s2 + s1;
end;
else
result := '错误的信息标识!';
end;
end;
function spendtime(sj: tdatetime): string;
var
sj3: tdatetime;
secondcount: integer;
begin
//
result := '';
sj3 := now;
secondcount := SecondsBetween(sj, now);
// lbl6.Caption := '系统生成完毕';
result := inttostr(secondcount div 60) + '分钟' + inttostr(secondcount mod 60) + '秒';
end;
function IsCPUID_Available: Boolean; register;
asm
PUSHFD {direct access to flags no possible, only via stack}
POP EAX {flags to EAX}
MOV EDX,EAX {save current flags}
XOR EAX,ID_BIT {not ID bit}
PUSH EAX {onto stack}
POPFD {from stack to flags, with not ID bit}
PUSHFD {back to stack}
POP EAX {get back to EAX}
XOR EAX,EDX {check if ID bit affected}
JZ @exit {no, CPUID not availavle}
MOV AL,True {Result=True}
@exit:
end;
function GetCPUID: TCPUID; assembler; register;
asm
PUSH EBX {Save affected register}
PUSH EDI
MOV EDI,EAX {@Resukt}
MOV EAX,1
DW $A20F {CPUID Command}
STOSD {CPUID[1]}
MOV EAX,EBX
STOSD {CPUID[2]}
MOV EAX,ECX
STOSD {CPUID[3]}
MOV EAX,EDX
STOSD {CPUID[4]}
POP EDI {Restore registers}
POP EBX
end;
function GetCPUVendor: TVendor; assembler; register;
//获取CPU生产厂家函数
//调用方法:EDIT.TEXT:='Current CPU Vendor:'+GetCPUVendor;
asm
PUSH EBX {Save affected register}
PUSH EDI
MOV EDI,EAX {@Result (TVendor)}
MOV EAX,0
DW $A20F {CPUID Command}
MOV EAX,EBX
XCHG EBX,ECX {save ECX result}
MOV ECX,4
@1:
STOSB
SHR EAX,8
LOOP @1
MOV EAX,EDX
MOV ECX,4
@2:
STOSB
SHR EAX,8
LOOP @2
MOV EAX,EBX
MOV ECX,4
@3:
STOSB
SHR EAX,8
LOOP @3
POP EDI {Restore registers}
POP EBX
end;
function GetCPUInfo: string;
var
CPUID: TCPUID;
I: Integer;
S: TVendor;
begin
for I := Low(CPUID) to High(CPUID) do
CPUID[I] := -1;
if IsCPUID_Available then
begin
CPUID := GetCPUID;
S := GetCPUVendor;
Result := IntToHex(CPUID[1], 8)
+ '-' + IntToHex(CPUID[2], 8)
+ '-' + IntToHex(CPUID[3], 8)
+ '-' + IntToHex(CPUID[4], 8);
end
else
Result := 'CPUID not available';
end;
function GetCPUSpeed: Double;
//获取CPU速率函数
//调用方法:EDIT.TEXT:='Current CPU Speed:'+floattostr(GetCPUSpeed)+'MHz';
const
DelayTime = 500; // 时间单位是毫秒
var
TimerHi, TimerLo: DWORD;
PriorityClass, Priority: Integer;
begin
PriorityClass := GetPriorityClass(GetCurrentProcess);
Priority := GetThreadPriority(GetCurrentThread);
SetPriorityClass(GetCurrentProcess, REALTIME_PRIORITY_CLASS);
SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_TIME_CRITICAL);
Sleep(10);
asm
dw 310Fh // rdtsc
mov TimerLo, eax
mov TimerHi, edx
end;
Sleep(DelayTime);
asm
dw 310Fh // rdtsc
sub eax, TimerLo
sbb edx, TimerHi
mov TimerLo, eax
mov TimerHi, edx
end;
SetThreadPriority(GetCurrentThread, Priority);
SetPriorityClass(GetCurrentProcess, PriorityClass);
Result := TimerLo / (1000.0 * DelayTime);
end;
function GetDisplayFrequency: Integer;
// 这个函数返回的显示刷新率是以Hz为单位的
//调用方法:EDIT.TEXT:='Current DisplayFrequency:'+inttostr(GetDisplayFrequency)+' Hz';
var
DeviceMode: TDeviceMode;
begin
EnumDisplaySettings(nil, Cardinal(-1), DeviceMode);
Result := DeviceMode.dmDisplayFrequency;
end;
function GetMemoryTotalSize: DWORD; //获取内存总量
var
msMemory: TMemoryStatus;
iPhysicsMemoryTotalSize: DWORD;
begin
msMemory.dwLength := SizeOf(msMemory);
GlobalMemoryStatus(msMemory);
iPhysicsMemoryTotalSize := msMemory.dwTotalPhys;
Result := iPhysicsMemoryTotalSize;
end;
//
// type
// PASTAT =^TASTAT;
// TASTAT = record
// adapter:TAdapterStatus;
// name_buf:TNameBuffer;
// end;
function Getmac: string;
var
ncb: TNCB;
s: string;
adapt: TASTAT;
lanaEnum: TLanaEnum;
i, j, m: integer;
strPart, strMac: string;
begin
FillChar(ncb, SizeOf(TNCB), 0);
ncb.ncb_command := Char(NCBEnum);
ncb.ncb_buffer := PChar(@lanaEnum);
ncb.ncb_length := SizeOf(TLanaEnum);
s := Netbios(@ncb);
for i := 0 to integer(lanaEnum.length) - 1 do
begin
FillChar(ncb, SizeOf(TNCB), 0);
ncb.ncb_command := Char(NCBReset);
ncb.ncb_lana_num := lanaEnum.lana[i];
Netbios(@ncb);
Netbios(@ncb);
FillChar(ncb, SizeOf(TNCB), 0);
ncb.ncb_command := Chr(NCBAstat);
ncb.ncb_lana_num := lanaEnum.lana[i];
ncb.ncb_callname := '*';
ncb.ncb_buffer := PChar(@adapt);
ncb.ncb_length := SizeOf(TASTAT);
m := 0;
if (Win32Platform = VER_PLATFORM_WIN32_NT) then
m := 1;
if m = 1 then
begin
if Netbios(@ncb) = Chr(0) then
strMac := '';
for j := 0 to 5 do
begin
strPart := IntToHex(integer(adapt.adapter.adapter_address[j]), 2);
strMac := strMac + strPart + '-';
end;
SetLength(strMac, Length(strMac) - 1);
end;
if m = 0 then
if Netbios(@ncb) <> Chr(0) then
begin
strMac := '';
for j := 0 to 5 do
begin
strPart := IntToHex(integer(adapt.adapter.adapter_address[j]), 2);
strMac := strMac + strPart + '-';
end;
SetLength(strMac, Length(strMac) - 1);
end;
end;
result := strmac;
end;
function GetHostName: string;
var
ComputerName: array[0..MAX_COMPUTERNAME_LENGTH + 1] of char;
Size: Cardinal;
begin
result := '';
Size := MAX_COMPUTERNAME_LENGTH + 1;
GetComputerName(ComputerName, Size);
Result := StrPas(ComputerName);
end;
function NameToIP(Name: string): string;
var
WSAData: TWSAData;
HostEnt: PHostEnt;
begin
result := '';
WSAStartup(2, WSAData);
HostEnt := GetHostByName(PChar(Name));
if HostEnt <> nil then
begin
with HostEnt^ do
result := Format('%d.%d.%d.%d', [Byte(h_addr^[0]), Byte(h_addr^[1]), Byte(h_addr^[2]), Byte(h_addr^[3])]);
end;
WSACleanup;
end;
function GetDiskSize: string;
var
Available, Total, Free: Int64;
AvailableT, TotalT: real;
Drive: Char;
const
GB = 1024 * 1024 * 1024;
begin
AvailableT := 0;
TotalT := 0;
for Drive := 'C' to 'Z' do
if GetDriveType(Pchar(Drive + ':\')) = DRIVE_FIXED then
begin
GetDiskFreeSpaceEx(PChar(Drive + ':\'), Available, Total, @Free);
AvailableT := AvailableT + Available;
TotalT := TotalT + Total;
end;
Result := Format('%.2fGB', [TotalT / GB]);
end;
function GetCPUName: string;
var
myreg: TRegistry;
CPUInfo: string;
begin
myreg := TRegistry.Create;
myreg.RootKey := HKEY_LOCAL_MACHINE;
if myreg.OpenKey('Hardware\Description\System\CentralProcessor\0', true) then
begin
if myreg.ValueExists('ProcessorNameString') then
begin
CPUInfo := myreg.ReadString('ProcessorNameString');
myreg.CloseKey;
end
else
CPUInfo := 'UnKnow';
end;
Result := CPUInfo;
end;
function GetIdeSerialNumber: pchar; //获取硬盘的出厂系列号;
const
IDENTIFY_BUFFER_SIZE = 512;
type
TIDERegs = packed record
bFeaturesReg: BYTE;
bSectorCountReg: BYTE;
bSectorNumberReg: BYTE;
bCylLowReg: BYTE;
bCylHighReg: BYTE;
bDriveHeadReg: BYTE;
bCommandReg: BYTE;
bReserved: BYTE;
end;
TSendCmdInParams = packed record
cBufferSize: DWORD;
irDriveRegs: TIDERegs;
bDriveNumber: BYTE;
bReserved: array[0..2] of Byte;
dwReserved: array[0..3] of DWORD;
bBuffer: array[0..0] of Byte;
end;
TIdSector = packed record
wGenConfig: Word;
wNumCyls: Word;
wReserved: Word;
wNumHeads: Word;
wBytesPerTrack: Word;
wBytesPerSector: Word;
wSectorsPerTrack: Word;
wVendorUnique: array[0..2] of Word;
sSerialNumber: array[0..19] of CHAR;
wBufferType: Word;
wBufferSize: Word;
wECCSize: Word;
sFirmwareRev: array[0..7] of Char;
sModelNumber: array[0..39] of Char;
wMoreVendorUnique: Word;
wDoubleWordIO: Word;
wCapabilities: Word;
wReserved1: Word;
wPIOTiming: Word;
wDMATiming: Word;
wBS: Word;
wNumCurrentCyls: Word;
wNumCurrentHeads: Word;
wNumCurrentSectorsPerTrack: Word;
ulCurrentSectorCapacity: DWORD;
wMultSectorStuff: Word;
ulTotalAddressableSectors: DWORD;
wSingleWordDMA: Word;
wMultiWordDMA: Word;
bReserved: array[0..127] of BYTE;
end;
PIdSector = ^TIdSector;
TDriverStatus = packed record
bDriverError: Byte;
bIDEStatus: Byte;
bReserved: array[0..1] of Byte;
dwReserved: array[0..1] of DWORD;
end;
TSendCmdOutParams = packed record
cBufferSize: DWORD;
DriverStatus: TDriverStatus;
bBuffer: array[0..0] of BYTE;
end;
var
hDevice: Thandle;
cbBytesReturned: DWORD;
SCIP: TSendCmdInParams;
aIdOutCmd: array[0..(SizeOf(TSendCmdOutParams) + IDENTIFY_BUFFER_SIZE - 1) - 1] of Byte;
IdOutCmd: TSendCmdOutParams absolute aIdOutCmd;
procedure ChangeByteOrder(var Data; Size: Integer);
var
ptr: Pchar;
i: Integer;
c: Char;
begin
ptr := @Data;
for I := 0 to (Size shr 1) - 1 do
begin
c := ptr^;
ptr^ := (ptr + 1)^;
(ptr + 1)^ := c;
Inc(ptr, 2);
end;
end;
begin
Result := '';
if SysUtils.Win32Platform = VER_PLATFORM_WIN32_NT then
begin // Windows NT, Windows 2000
hDevice := CreateFile('\\.\PhysicalDrive0', GENERIC_READ or GENERIC_WRITE,
FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, 0, 0);
end
else // Version Windows 95 OSR2, Windows 98
hDevice := CreateFile('\\.\SMARTVSD', 0, 0, nil, CREATE_NEW, 0, 0);
if hDevice = INVALID_HANDLE_VALUE then
Exit;
try
FillChar(SCIP, SizeOf(TSendCmdInParams) - 1, #0);
FillChar(aIdOutCmd, SizeOf(aIdOutCmd), #0);
cbBytesReturned := 0;
with SCIP do
begin
cBufferSize := IDENTIFY_BUFFER_SIZE;
with irDriveRegs do
begin
bSectorCountReg := 1;
bSectorNumberReg := 1;
bDriveHeadReg := $A0;
bCommandReg := $EC;
end;
end;
if not DeviceIoControl(hDevice, $0007C088, @SCIP, SizeOf(TSendCmdInParams) - 1,
@aIdOutCmd, SizeOf(aIdOutCmd), cbBytesReturned, nil) then
Exit;
finally
CloseHandle(hDevice);
end;
with PIdSector(@IdOutCmd.bBuffer)^ do
begin
ChangeByteOrder(sSerialNumber, SizeOf(sSerialNumber));
(Pchar(@sSerialNumber) + SizeOf(sSerialNumber))^ := #0;
Result := Pchar(@sSerialNumber);
end;
end;
function GetIdeNum: string;
type
TSrbIoControl = packed record
HeaderLength: ULONG;
Signature: array[0..7] of Char;
Timeout: ULONG;
ControlCode: ULONG;
ReturnCode: ULONG;
Length: ULONG;
end;
SRB_IO_CONTROL = TSrbIoControl;
PSrbIoControl = ^TSrbIoControl;
TIDERegs = packed record
bFeaturesReg: Byte;
bSectorCountReg: Byte;
bSectorNumberReg: Byte;
bCylLowReg: Byte;
bCylHighReg: Byte;
bDriveHeadReg: Byte;
bCommandReg: Byte;
bReserved: Byte;
end;
IDEREGS = TIDERegs;
PIDERegs = ^TIDERegs;
TSendCmdInParams = packed record
cBufferSize: DWORD;
irDriveRegs: TIDERegs;
bDriveNumber: Byte;
bReserved: array[0..2] of Byte;
dwReserved: array[0..3] of DWORD;
bBuffer: array[0..0] of Byte;
end;
SENDCMDINPARAMS = TSendCmdInParams;
PSendCmdInParams = ^TSendCmdInParams;
TIdSector = packed record
wGenConfig: Word;
wNumCyls: Word;
wReserved: Word;
wNumHeads: Word;
wBytesPerTrack: Word;
wBytesPerSector: Word;
wSectorsPerTrack: Word;
wVendorUnique: array[0..2] of Word;
sSerialNumber: array[0..19] of Char;
wBufferType: Word;
wBufferSize: Word;
wECCSize: Word;
sFirmwareRev: array[0..7] of Char;
sModelNumber: array[0..39] of Char;
wMoreVendorUnique: Word;
wDoubleWordIO: Word;
wCapabilities: Word;
wReserved1: Word;
wPIOTiming: Word;
wDMATiming: Word;
wBS: Word;
wNumCurrentCyls: Word;
wNumCurrentHeads: Word;
wNumCurrentSectorsPerTrack: Word;
ulCurrentSectorCapacity: ULONG;
wMultSectorStuff: Word;
ulTotalAddressableSectors: ULONG;
wSingleWordDMA: Word;
wMultiWordDMA: Word;
bReserved: array[0..127] of Byte;
end;
PIdSector = ^TIdSector;
const
IDE_ID_FUNCTION = $EC;
IDENTIFY_BUFFER_SIZE = 512;
DFP_RECEIVE_DRIVE_DATA = $0007C088;
IOCTL_SCSI_MINIPORT = $0004D008;
IOCTL_SCSI_MINIPORT_IDENTIFY = $001B0501;
DataSize = sizeof(TSendCmdInParams) - 1 + IDENTIFY_BUFFER_SIZE;
BufferSize = SizeOf(SRB_IO_CONTROL) + DataSize;
W9xBufferSize = IDENTIFY_BUFFER_SIZE + 16;
var
hDevice: THandle;
cbBytesReturned: DWORD;
pInData: PSendCmdInParams;
pOutData: Pointer;
Buffer: array[0..BufferSize - 1] of Byte;
srbControl: TSrbIoControl absolute Buffer;
procedure ChangeByteOrder(var Data; Size: Integer);
var
ptr: PChar;
i: Integer;
c: Char;
begin
ptr := @Data;
for i := 0 to (Size shr 1) - 1 do
begin
c := ptr^;
ptr^ := (ptr + 1)^;
(ptr + 1)^ := c;
Inc(ptr, 2);
end;
end;
begin
Result := '';
FillChar(Buffer, BufferSize, #0);
if Win32Platform = VER_PLATFORM_WIN32_NT then
begin
hDevice := CreateFile('.Scsi0', GENERIC_READ or GENERIC_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE, nil,
OPEN_EXISTING, 0, 0);
if hDevice = INVALID_HANDLE_VALUE then
Exit;
try
srbControl.HeaderLength := SizeOf(SRB_IO_CONTROL);
System.Move('SCSIDISK', srbControl.Signature, 8);
srbControl.Timeout := 2;
srbControl.Length := DataSize;
srbControl.ControlCode := IOCTL_SCSI_MINIPORT_IDENTIFY;
pInData := PSendCmdInParams(PChar(@Buffer) + SizeOf(SRB_IO_CONTROL));
pOutData := pInData;
with pInData^ do
begin
cBufferSize := IDENTIFY_BUFFER_SIZE;
bDriveNumber := 0;
with irDriveRegs do
begin
bFeaturesReg := 0;
bSectorCountReg := 1;
bSectorNumberReg := 1;
bCylLowReg := 0;
bCylHighReg := 0;
bDriveHeadReg := $A0;
bCommandReg := IDE_ID_FUNCTION;
end;
end;
if not DeviceIoControl(hDevice, IOCTL_SCSI_MINIPORT, @Buffer, BufferSize, @Buffer, BufferSize, cbBytesReturned,
nil) then
Exit;
finally
CloseHandle(hDevice);
end;
end
else
begin
hDevice := CreateFile('.SMARTVSD', 0, 0, nil, CREATE_NEW, 0, 0);
if hDevice = INVALID_HANDLE_VALUE then
Exit;
try
pInData := PSendCmdInParams(@Buffer);
pOutData := @pInData^.bBuffer;
with pInData^ do
begin
cBufferSize := IDENTIFY_BUFFER_SIZE;
bDriveNumber := 0;
with irDriveRegs do
begin
bFeaturesReg := 0;
bSectorCountReg := 1;
bSectorNumberReg := 1;
bCylLowReg := 0;
bCylHighReg := 0;
bDriveHeadReg := $A0;
bCommandReg := IDE_ID_FUNCTION;
end;
end;
if not DeviceIoControl(hDevice, DFP_RECEIVE_DRIVE_DATA, pInData, SizeOf(TSendCmdInParams) - 1, pOutData,
W9xBufferSize, cbBytesReturned, nil) then
Exit;
finally
CloseHandle(hDevice);
end;
end;
with PIdSector(PChar(pOutData) + 16)^ do
begin
ChangeByteOrder(sSerialNumber, SizeOf(sSerialNumber));
SetString(Result, sSerialNumber, SizeOf(sSerialNumber));
end;
Result := Trim(Result);
end;
end.
|
{ Este exemplo foi baixado no site www.andrecelestino.com
Passe por lá a qualquer momento para conferir os novos artigos! :)
contato@andrecelestino.com }
unit UnitFormulario;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DBXpress, FMTBcd, DB, Provider, DBClient, SqlExpr, Grids,
DBGrids, StdCtrls, Buttons, ExtCtrls;
type
TfrmFormulario = class(TForm)
grdDados: TDBGrid;
SQLConnection: TSQLConnection;
SQLQuery: TSQLQuery;
ClientDataSet: TClientDataSet;
DataSetProvider: TDataSetProvider;
DataSource: TDataSource;
lblTitulo: TLabel;
Panel: TPanel;
lblPesquisa: TLabel;
edtPesquisa: TEdit;
btnPesquisar: TBitBtn;
procedure FormCreate(Sender: TObject);
procedure btnPesquisarClick(Sender: TObject);
procedure edtPesquisaKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmFormulario: TfrmFormulario;
implementation
{$R *.dfm}
procedure TfrmFormulario.FormCreate(Sender: TObject);
var
CaminhoExecutavel: string;
begin
CaminhoExecutavel := ExtractFilePath(Application.ExeName);
SQLCOnnection.Params.Values['Database'] := CaminhoExecutavel + 'Banco.fdb';
try
SQLConnection.Connected := True;
SQLQuery.SQL.Add('Select * from CLIENTES');
SQLQuery.Open;
ClientDataSet.Open;
except
MessageDlg('O banco de dados não está disponível no diretório.', mtWarning, [mbOK], 0);
end;
end;
procedure TfrmFormulario.btnPesquisarClick(Sender: TObject);
begin
// limpa a instrução SQL da Query
SQLQuery.SQL.Clear;
// atribui a instrução SQL, criando um parâmetro
SQLQuery.SQL.Add('Select * from CLIENTES where Nome like :pNome');
// preenche o parâmetro recém-criado na instrução SQL
SQLQuery.ParamByName('pNome').AsString := edtPesquisa.Text + '%';
// abre a Query
SQLQuery.Open;
// atualiza o conjunto de dados
ClientDataSet.Refresh;
end;
procedure TfrmFormulario.edtPesquisaKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then
begin
Key := #0;
btnPesquisar.Click;
end;
end;
end.
|
// Copyright 2018 by John Kouraklis and Contributors. All Rights Reserved.
//
// 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 Casbin.Adapter.Policy.Types;
interface
uses
Casbin.Adapter.Types, Casbin.Core.Base.Types;
type
IPolicyAdapter = interface (IAdapter)
['{56990FAD-9212-4169-8A94-D55039D1F403}']
function getAutoSave: Boolean;
function getCached: boolean;
procedure setAutoSave(const aValue: Boolean);
procedure setCached(const aValue: boolean);
procedure add (const aTag: string);
function getCacheSize: Integer;
{$REGION 'Removes a policy rule from the adapter'}
/// <summary>
/// Removes a policy rule from the adapter
/// </summary>
/// <param name="aPolicyDefinition">
/// The tag of the policy (e.g. p, g, g2)
/// </param>
/// <example>
/// <list type="bullet">
/// <item>
/// <font color="#2A2A2A">remove ('p')</font>
/// </item>
/// </list>
/// </example>
{$ENDREGION}
procedure remove (const aPolicyDefinition: string); overload;
procedure setCacheSize(const aValue: Integer);
property AutoSave: Boolean read getAutoSave write setAutoSave;
property Cached: boolean read getCached write setCached;
property CacheSize: Integer read getCacheSize write setCacheSize;
end;
const
DefaultCacheSize = 15;
implementation
end.
|
unit ListAlbums;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Grids, ExtCtrls, MediaFile, AlbumsController, BaseForm,
Generics.Collections;
type
TfrmListAlbums = class(TBaseForm)
PanelTop: TPanel;
BevelTop: TBevel;
MainPanel: TPanel;
Grid: TStringGrid;
BevelBottom: TBevel;
PanelBottom: TPanel;
btNew: TButton;
btExit: TButton;
btEdit: TButton;
btDelete: TButton;
procedure FormCreate(Sender: TObject);
procedure btNewClick(Sender: TObject);
procedure btDeleteClick(Sender: TObject);
procedure btEditClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure GridDblClick(Sender: TObject);
private
FController: TAlbumsController;
function GetSelectedAlbum: TAlbum;
procedure LoadAlbums;
end;
implementation
uses
EditAlbum;
{$R *.dfm}
procedure TfrmListAlbums.btEditClick(Sender: TObject);
var
Album: TAlbum;
frmEditAlbum: TfrmEditAlbum;
begin
Album := GetSelectedAlbum;
frmEditAlbum := TfrmEditAlbum.Create(Self);
try
frmEditAlbum.SetAlbum(Album.Id);
frmEditAlbum.ShowModal;
if frmEditAlbum.ModalResult = mrOk then
LoadAlbums;
finally
frmEditAlbum.Free;
end;
end;
procedure TfrmListAlbums.btDeleteClick(Sender: TObject);
var
Album: TAlbum;
Msg: string;
begin
Album := GetSelectedAlbum;
Msg := 'Are you sure you want to delete Album "' + Album.AlbumName + '"?';
if MessageDlg(Msg, mtWarning, mbYesNo, 0) = mrYes then
begin
FController.DeleteAlbum(Album);
LoadAlbums;
end;
end;
procedure TfrmListAlbums.btNewClick(Sender: TObject);
var
frmEditAlbum: TfrmEditAlbum;
begin
frmEditAlbum := TfrmEditAlbum.Create(Self);
try
frmEditAlbum.ShowModal;
if frmEditAlbum.ModalResult = mrOk then
LoadAlbums;
finally
frmEditAlbum.Free;
end;
end;
procedure TfrmListAlbums.LoadAlbums;
var
Albums: TList<TAlbum>;
Album: TAlbum;
I, J: Integer;
begin
for I := 0 to Grid.RowCount - 1 do
for J := 0 to Grid.ColCount - 1 do
Grid.Cells[J, I] := '';
Grid.RowCount := 2;
Grid.Cells[0, 0] := 'Name';
Grid.Cells[1, 0] := 'Year';
Grid.Cells[2, 0] := 'Duration';
Grid.Cells[3, 0] := 'Total Files';
Albums := FController.GetAllAlbums;
try
if Albums.Count > 0 then
begin
Grid.RowCount := 1 + Albums.Count;
for I := 0 to Albums.Count - 1 do
begin
Album := Albums[I];
Grid.Cols[0].Objects[I + 1] := Album;
Grid.Cells[0, I + 1] := Album.AlbumName;
if Album.ReleaseYear.HasValue then
Grid.Cells[1, I + 1] := IntToStr(Album.ReleaseYear);
if Album.Duration.HasValue then
Grid.Cells[2, I + 1] := Format(
'%s:%s',
[FormatFloat('#0', Album.Duration.Value div 60),
FormatFloat('00', Album.Duration.Value mod 60)
]);
Grid.Cells[3, I + 1] := IntToStr(Album.MediaFiles.Count);
end;
end;
finally
Albums.Free;
end;
end;
procedure TfrmListAlbums.FormCreate(Sender: TObject);
begin
FController := TAlbumsController.Create;
LoadAlbums;
end;
procedure TfrmListAlbums.FormDestroy(Sender: TObject);
begin
FController.Free;
end;
function TfrmListAlbums.GetSelectedAlbum: TAlbum;
begin
Result := TAlbum(Grid.Cols[0].Objects[Grid.Row]);
end;
procedure TfrmListAlbums.GridDblClick(Sender: TObject);
begin
btEditClick(nil);
end;
end.
|
unit uJxdP2PUserManage;
interface
uses
Windows, SysUtils, Classes, WinSock2, uJxdDataStream,
uJxdUdpBasic, uJxdUdpSynchroClient, uJxdUdpDefine;
type
{客户端节点信息, P2P使用}
TConAddrStyle = (caPublic, caLocal, caBoth);
PClientPeerInfo = ^TClientPeerInfo;
TClientPeerInfo = record
FUserID: Cardinal; //客户端ID
FPublicIP, FLocalIP: Cardinal; //网络地址
FPublicPort, FLocalPort: Word;
FConnectState: TConnectState; //当前连接状态
FConAddrStyle: TConAddrStyle; //指明使用那个地址来通讯, 当 FConnectState = csConnetSuccess 时有效
FClientVersion: Word; //当前使用版本号
FLastSendActiveTime: Cardinal; //最后发送时间
FLastRecvActiveTime: Cardinal; //最后接收时间
FTimeoutCount: Integer; //超时次数
end;
TOnClientPeerInfo = procedure(Ap: PClientPeerInfo) of object;
TOnCheckP2PUser = procedure(const ACurTime: Cardinal; Ap: PClientPeerInfo; var ADel: Boolean) of object;
TDeleteUserReason = (drInvalideID, drSelf, drTimeout, drNotify);
TOnDeleteUser = procedure(Ap: PClientPeerInfo; const AReason: TDeleteUserReason) of object;
TxdP2PUserManage = class
public
constructor Create;
destructor Destroy; override;
procedure LockList; inline;
procedure UnLockList; inline;
function FindUserInfo(const AUserID: Cardinal): PClientPeerInfo; //非锁定状态, 外部手工调用Lock
function AddUserInfo(const ApUser: PUserNetInfo): Boolean; //自动进入锁定状态
function AddConnectingUser(const AIP: Cardinal; const APort: Word; pUser: PUserNetInfo): Boolean; //锁定,判断是否有效,并加入到列表
procedure DeleteUser(const AUserID: Cardinal; const AReason: TDeleteUserReason);
procedure UpdateUserInfo(const ApNet: PUserNetInfo); //在未连接时可进行更新
procedure ActiveUserRecvTime(const AUserID: Cardinal); //只对已连接用户有效
private
FCloseing, FThreadRunning: Boolean;
FCheckEvent: Cardinal;
procedure DoThreadCheck;
procedure DoUpdateUserInfo(ApUser: PClientPeerInfo; ApNet: PUserNetInfo);
private
FUserList: TList;
FLock: TRTLCriticalSection;
FCheckThreadSpaceTime: Cardinal;
FOnAddUser: TOnClientPeerInfo;
FOnDelUser: TOnDeleteUser;
FOnUpdateUserNetInfo: TOnClientPeerInfo;
FOnP2PConnected: TOnClientPeerInfo;
FOnCheckP2PUser: TOnCheckP2PUser;
function GetCount: Integer;
function GetItem(index: Integer): PClientPeerInfo;
procedure SetCheckThreadSpaceTime(const Value: Cardinal);
public
property CheckThreadSpaceTime: Cardinal read FCheckThreadSpaceTime write SetCheckThreadSpaceTime;
property Count: Integer read GetCount;
property Item[index: Integer]: PClientPeerInfo read GetItem;
property OnAddUser: TOnClientPeerInfo read FOnAddUser write FOnAddUser;
property OnDelUser: TOnDeleteUser read FOnDelUser write FOnDelUser;
property OnUpdateUserNetInfo: TOnClientPeerInfo read FOnUpdateUserNetInfo write FOnUpdateUserNetInfo;
property OnP2PConnected: TOnClientPeerInfo read FOnP2PConnected write FOnP2PConnected;
property OnCheckP2PUser: TOnCheckP2PUser read FOnCheckP2PUser write FOnCheckP2PUser;
end;
procedure GetClientIP(const Ap: PClientPeerInfo; var AIP: Cardinal; var APort: Word);
function GetConnectString(AState: TConnectState): string;
implementation
uses
uSysInfo, uSocketSub, uJxdThread;
procedure GetClientIP(const Ap: PClientPeerInfo; var AIP: Cardinal; var APort: Word);
begin
case Ap^.FConAddrStyle of
caPublic:
begin
AIP := Ap^.FPublicIP;
APort := Ap^.FPublicPort;
end
else
begin
AIP := Ap^.FLocalIP;
APort := Ap^.FLocalPort;
end;
end;
end;
function GetConnectString(AState: TConnectState): string;
begin
case AState of
csNULL: Result := '未连接';
csConneting: Result := '正在建立连接';
csConnetFail: Result := '无法建立连接';
csConnetSuccess: Result := '已经成功建立连接';
else
Result := '未知的状态(出错)';
end;
end;
const
CtClientPeerInfoSize = SizeOf(TClientPeerInfo);
{ TxdP2PUserManage }
function TxdP2PUserManage.AddUserInfo(const ApUser: PUserNetInfo): Boolean;
var
i: Integer;
p: PClientPeerInfo;
bAdd: Boolean;
begin
Result := False;
LockList;
try
bAdd := True;
for i := 0 to FUserList.Count - 1 do
begin
p := FUserList[i];
if p^.FUserID = ApUser^.FUserID then
begin
bAdd := False;
//更新状态
DoUpdateUserInfo( p, ApUser );
Break;
end;
end;
if bAdd then
begin
New( p );
p^.FUserID := ApUser^.FUserID;
p^.FPublicIP := ApUser^.FPublicIP;
p^.FLocalIP := ApUser^.FLocalIP;
p^.FPublicPort := ApUser^.FPublicPort;
p^.FLocalPort := ApUser^.FLocalPort;
p^.FConnectState := csNULL;
p^.FClientVersion := 0;
p^.FLastSendActiveTime := 0;
p^.FLastRecvActiveTime := 0;
p^.FTimeoutCount := 0;
if Assigned(OnAddUser) then
OnAddUser( p );
FUserList.Add(p);
Result := True;
end;
finally
UnLockList;
end;
end;
procedure TxdP2PUserManage.ActiveUserRecvTime(const AUserID: Cardinal);
var
p: PClientPeerInfo;
begin
LockList;
try
p := FindUserInfo( AUserID );
if Assigned(p) then
p^.FLastRecvActiveTime := GetTickCount;
finally
UnLockList;
end;
end;
function TxdP2PUserManage.AddConnectingUser(const AIP: Cardinal; const APort: Word; pUser: PUserNetInfo): Boolean;
var
p: PClientPeerInfo;
addrStyle: TConAddrStyle;
begin
if (pUser^.FPublicIP = AIP) and (pUser^.FPublicPort = APort) then
addrStyle := caPublic
else if (pUser^.FLocalIP = AIP) and (pUser^.FLocalPort = APort) then
addrStyle := caLocal
else
begin
//直接当成是public信息处理
addrStyle := caPublic;
pUser^.FPublicIP := AIP;
pUser^.FPublicPort := APort;
end;
LockList;
try
p := FindUserInfo( pUser^.FUserID );
if Assigned(p) then
begin
//已经存在的节点
if p^.FConnectState = csConneting then
begin
p^.FConnectState := csConnetSuccess;
p^.FConAddrStyle := addrStyle;
p^.FTimeoutCount := 0;
end
else if p^.FConnectState = csConnetSuccess then
begin
if p^.FConAddrStyle <> addrStyle then
p^.FConAddrStyle := caBoth;
Result := True;
Exit;
end
else
p^.FConAddrStyle := addrStyle;
end
else
begin
//新增节点
New( p );
p^.FUserID := pUser^.FUserID;
p^.FConnectState := csConnetSuccess;
p^.FConAddrStyle := addrStyle;
p^.FClientVersion := 0;
p^.FLastSendActiveTime := 0;
p^.FTimeoutCount := 0;
FUserList.Add( p );
end;
p^.FPublicIP := pUser^.FPublicIP;
p^.FLocalIP := pUser^.FLocalIP;
p^.FPublicPort := pUser^.FPublicPort;
p^.FLocalPort := pUser^.FLocalPort;
p^.FLastRecvActiveTime := GetTickCount;
Result := True;
if Assigned(OnP2PConnected) then
OnP2PConnected( p );
finally
UnLockList;
end;
end;
constructor TxdP2PUserManage.Create;
begin
FUserList := TList.Create;
InitializeCriticalSection( FLock );
CheckThreadSpaceTime := 10 * 1000;
FCloseing := False;
FCheckEvent := CreateEvent( nil, False, False, nil );
FThreadRunning := False;
RunningByThread( DoThreadCheck );
end;
procedure TxdP2PUserManage.DeleteUser(const AUserID: Cardinal; const AReason: TDeleteUserReason);
var
i: Integer;
p: PClientPeerInfo;
begin
LockList;
try
for i := 0 to FUserList.Count - 1 do
begin
p := FUserList[i];
if p^.FUserID = AUserID then
begin
if (AReason = drInvalideID) and (p^.FConnectState = csConnetSuccess) then Exit;
//释放此用户
FUserList.Delete( i );
if Assigned(OnDelUser) then
OnDelUser( p, AReason );
Dispose( p );
Break;
end;
end;
finally
UnLockList;
end;
end;
destructor TxdP2PUserManage.Destroy;
var
i: Integer;
begin
FCloseing := True;
if FCheckEvent <> 0 then
begin
SetEvent( FCheckEvent );
while FThreadRunning do
begin
Sleep( 10 );
SetEvent( FCheckEvent );
end;
CloseHandle( FCheckEvent );
FCheckEvent := 0;
end;
for i := 0 to FUserList.Count - 1 do
Dispose( FUserList[i] );
FUserList.Free;
DeleteCriticalSection( FLock );
inherited;
end;
procedure TxdP2PUserManage.DoThreadCheck;
var
i: Integer;
p: PClientPeerInfo;
bDel: Boolean;
CurTime: Cardinal;
begin
FThreadRunning := True;
try
while not FCloseing do
begin
WaitForSingleObject( FCheckEvent, CheckThreadSpaceTime );
//开始检查P2P连接
LockList;
try
CurTime := GetTickCount;
for i := FUserList.Count - 1 downto 0 do
begin
p := FUserList[i];
bDel := False;
if Assigned(OnCheckP2PUser) then
OnCheckP2PUser( CurTime, p, bDel );
if bDel then
begin
Dispose( p );
FUserList.Delete( i );
end;
end;
finally
UnLockList;
end;
end;
finally
FThreadRunning := False;
end;
end;
procedure TxdP2PUserManage.DoUpdateUserInfo(ApUser: PClientPeerInfo; ApNet: PUserNetInfo);
var
bChanged: Boolean;
begin
bChanged := False;
if ApUser^.FConnectState <> csConnetSuccess then
begin
//更新公网
if (ApNet^.FPublicIP > 0) and (ApNet^.FPublicPort > 0) and
( (ApUser^.FPublicIP <> ApNet^.FPublicIP) or (ApUser^.FPublicPort <> ApNet^.FPublicPort) ) then
begin
ApUser^.FPublicIP := ApNet^.FPublicIP;
ApUser^.FPublicPort := ApNet^.FPublicPort;
bChanged := True;
end;
//更新本地
if (ApNet^.FLocalIP > 0) and (ApNet^.FLocalPort > 0) and
( (ApUser^.FLocalIP <> ApNet^.FLocalIP) or (ApUser^.FLocalPort <> ApNet^.FLocalPort) ) then
begin
ApUser^.FLocalIP := ApNet^.FLocalIP;
ApUser^.FLocalPort := ApNet^.FLocalPort;
bChanged := True;
end;
end;
if bChanged then
if Assigned(OnUpdateUserNetInfo) then
OnUpdateUserNetInfo( ApUser );
end;
function TxdP2PUserManage.FindUserInfo(const AUserID: Cardinal): PClientPeerInfo;
var
i: Integer;
p: PClientPeerInfo;
begin
Result := nil;
for i := 0 to FUserList.Count - 1 do
begin
p := FUserList[i];
if p^.FUserID = AUserID then
begin
Result := p;
Break;
end;
end;
end;
function TxdP2PUserManage.GetCount: Integer;
begin
Result := FUserList.Count;
end;
function TxdP2PUserManage.GetItem(index: Integer): PClientPeerInfo;
begin
if (index >= 0) and (index < FUserList.Count) then
Result := FUserList[index]
else
Result := nil;
end;
procedure TxdP2PUserManage.LockList;
begin
EnterCriticalSection( FLock );
end;
procedure TxdP2PUserManage.SetCheckThreadSpaceTime(const Value: Cardinal);
begin
FCheckThreadSpaceTime := Value;
end;
procedure TxdP2PUserManage.UnLockList;
begin
LeaveCriticalSection( FLock );
end;
procedure TxdP2PUserManage.UpdateUserInfo(const ApNet: PUserNetInfo);
var
i: Integer;
p: PClientPeerInfo;
begin
LockList;
try
for i := 0 to FUserList.Count - 1 do
begin
p := FUserList[i];
if p^.FUserID = ApNet^.FUserID then
begin
DoUpdateUserInfo( p, ApNet );
Break;
end;
end;
finally
UnLockList;
end;
end;
end.
|
unit WellPassportClientCommon;
interface
uses SysUtils, ClientCommon;
type
TWellRecord = record
iWellUIN,
iAreaID: integer;
iDistrictID,
iPetrolRegionID,
iTectonicStructID,
iTopographicalListId,
iLicenseZoneId: integer;
iSearchingMinistryID,
iSearchingTrustID,
iSearchingExpeditionID,
iExploitingMinistryID,
iExploitingTrustID,
iExploitingExpeditionID: integer;
iCategoryID,
iTargetAgeID,
iTrueAgeID,
iStatusID,
iAbandonReasonID,
iProfileID: integer;
vTargetFluidIDArray,
vTrueFluidIDArray,
vFinanceSourceIDArray: variant;
dtmEnteringDate,
dtmDrillingStart,
dtmDrillingFinish,
dtmSuspendActionDate,
dtmAbandonDate,
dtmConstructionStarted,
dtmConstructionFinished: TDateTime;
fRotorAltitude,
fTargetDepth,
fTrueDepth,
fTargetCost,
fTrueCost: variant;
sWellNum,
sRegNum,
sProductivity,
sSuspendAction,
sCommentText: shortstring;
vDinamicsArray,
vWellOrgStatusArray,
vDocumentsArray: Variant;
{ vCoordTypeArray,
vCoordXArray,
vCoordYArray: Variant;}
end;
function SwapOilGas(Value: variant): variant;
function LoadWell(var wrCurrent: TWellRecord):smallint;
procedure ClearWellRecord();
var wrCurrentWell: TWellRecord;
vAreaDict, vWellCategoryDict, vFinanceSourceDict,
vWellStateDict, vProfileDict, vSynonymDict,
vTopoListDict, vLicenseZoneDict, vTectonicStructDict,
vDistrictDict, vPetrolRegionDict, vTestResultDict,
vFluidTypeDict, vStratigraphyDict, vAbandonReasonDict,
vOrgStatusDict, vOrganizationDict, vDocTypeDict,
vGeolFoundationDict, vTableDict: Variant;
//Âèä ôîðìû äîáàâëåíèÿ ñêâàæèíû
iAddWellFormKind: byte = 0; //0 - êðàòêàÿ (òèïà ÒÁÄ), 1 - íîâàÿ
implementation
function SwapOilGas(Value: variant): variant;
begin
Result:= Value;
if (varType(Value) = varOleStr)
or (varType(Value) = varStrArg) then
if Value = 'ÃÍ' then Result:='ÍÃ'
else if Value = 'ÂÍ' then Result:='ÍÂ'
else if Value = 'ÂÃ' then Result:='ÃÂ'
else if Value = 'ÂÃÊ' then Result:='ÃÊÂ'
else if Value = 'ÂÃÊÍ' then Result:='ÍÃÊÂ'
else if Value = 'ÂÃÍ' then Result:='ÍÃÂ'
else if Value = 'ÃÊÍ' then Result:='ÍÃÊ';
end;
procedure ClearWellRecord();
begin
with wrCurrentWell do
begin
iWellUIN:=0;
iAreaID:=0;
iDistrictID:=0;
iPetrolRegionID:=0;
iTectonicStructID:=0;
iTopographicalListId:=0;
iLicenseZoneId:=0;
iSearchingMinistryID:=0;
iSearchingTrustID:=0;
iSearchingExpeditionID:=0;
iExploitingMinistryID:=0;
iExploitingTrustID:=0;
iExploitingExpeditionID:=0;
iCategoryID:=0;
iTargetAgeID:=0;
iTrueAgeID:=0;
iStatusID:=0;
iAbandonReasonID:=0;
iProfileID:=0;
varClear(vTargetFluidIDArray);
varClear(vTrueFluidIDArray);
varClear(vFinanceSourceIDArray);
dtmEnteringDate:=0;
dtmDrillingStart:=0;
dtmDrillingFinish:=0;
dtmSuspendActionDate:=0;
dtmAbandonDate:=0;
dtmConstructionStarted:=0;
dtmConstructionFinished:=0;
fRotorAltitude:=null;
fTargetDepth:=null;
fTrueDepth:=null;
fTargetCost:=null;
fTrueCost:=null;
sWellNum:='';
sRegNum:='';
sProductivity:='';
sSuspendAction:='';
sCommentText:='';
varClear(vDinamicsArray);
varClear(vWellOrgStatusArray);
varClear(vDocumentsArray);
{ varClear(vCoordTypeArray);
varClear(vCoordXArray);
varClear(vCoordYArray);}
end;
end;
function LoadWell(var wrCurrent: TWellRecord):smallint;
var vQR: variant;
i, iRes: smallint;
begin
Result:=0;
iRes:=IServer.SelectRows(
'spd_Get_Well_Info',
varArrayOf(['Area_Id', 'vch_Well_Num', 'vch_Passport_Num',
'Well_Category_Id', 'Well_State_Id',
'Profile_Id', 'num_Rotor_Altitude',
'num_Target_Depth', 'num_True_Depth',
'Target_Age_Id', 'True_Age_Id',
'dtm_Construction_Started', 'dtm_Construction_Finished',
'dtm_Drilling_Start', 'dtm_Drilling_Finish',
'num_Target_Cost', 'num_True_Cost',
'vch_Well_Productivity', 'Topographical_List_Id',
'License_Zone_Id', 'Struct_Id', 'District_Id',
'Petrol_Region_Id']),
'', wrCurrent.iWellUIN);
if iRes<0 then
begin
Result:=-1;
Exit;
end;
if iRes>0 then
begin
Result:=iRes;
vQR:=IServer.QueryResult;
with wrCurrent do
try
iAreaId:= GetSingleValue(vQR,0);
sWellNum:= GetSingleValue(vQR,1);
sRegNum:= GetSingleValue(vQR,2);
iCategoryID:= GetSingleValue(vQR,3);
iStatusId:= GetSingleValue(vQR,4);
iProfileID:= GetSingleValue(vQR,5);
fRotorAltitude:=GetSingleValue(vQR,6);
fTargetDepth:=GetSingleValue(vQR,7);
fTrueDepth:=GetSingleValue(vQR,8);
iTargetAgeID:=GetSingleValue(vQR,9);
iTrueAgeId:=GetSingleValue(vQR,10);
dtmConstructionStarted:=GetSingleValue(vQR,11);
dtmConstructionFinished:=GetSingleValue(vQR,12);
dtmDrillingStart:=GetSingleValue(vQR,13);
dtmDrillingFinish:=GetSingleValue(vQR,14);
fTargetCost:=GetSingleValue(vQR,15);
fTrueCost:=GetSingleValue(vQR,16);
sProductivity:=GetSingleValue(vQR,17);
iTopographicalListId:=GetSingleValue(vQR,18);
iLicenseZoneId:=GetSingleValue(vQR,19);
iTectonicStructId:=GetSingleValue(vQR,20);
iDistrictId:=GetSingleValue(vQR,21);
iPetrolRegionId:=GetSingleValue(vQR,22);
// IWPServer.GetWellCoords(AWellUIN, vCoordTypeArray, vCoordXArray, vCoordYArray);
IServer.SelectRows('spd_Get_Well_Finance_Source', 'Finance_Source_ID', '', iWellUIN);
vQR:=IServer.QueryResult;
vFinanceSourceIDArray:= ReduceArrayDimCount(vQR);
IServer.SelectRows('spd_Get_Well_Organization',
varArrayOf(['Org_Status_Id', 'Organization_Id']),
'', iWellUIN);
vWellOrgStatusArray:= IServer.QueryResult;
if not varIsEmpty(vWellOrgStatusArray) then
begin
for i:=0 to varArrayHighBound(vWellOrgStatusArray, 2) do
case GetSingleValue(vWellOrgStatusArray, 0, i) of
3: iSearchingMinistryID:= vWellOrgStatusArray[1, i];
4: iExploitingMinistryID:= vWellOrgStatusArray[1, i];
1, 5: iSearchingTrustID:= vWellOrgStatusArray[1, i];
2, 6: iExploitingTrustID:= vWellOrgStatusArray[1, i];
7: iSearchingExpeditionID:= vWellOrgStatusArray[1, i];
8: iExploitingExpeditionID:= vWellOrgStatusArray[1, i];
end;//case
end;
IServer.SelectRows('spd_Get_Well_True_Result', 'Fluid_Type_ID', '', iWellUIN);
vQR:=IServer.QueryResult;
vTrueFluidIdArray:= ReduceArrayDimCount(vQR);
IServer.SelectRows('spd_Get_Well_Target_Result', 'Fluid_Type_ID', '', iWellUIN);
vQR:=IServer.QueryResult;
vTargetFluidIdArray:= ReduceArrayDimCount(vQR);
IServer.SelectRows('spd_Get_Abandoned_Well_Info',
varArrayOf(['Abandon_Reason_ID', 'dtm_Abandon_Date']),
'', iWellUIN);
vQR:=IServer.QueryResult;
iAbandonReasonID:=GetSingleValue(vQR, 0);
dtmAbandonDate:=GetSingleValue(vQR,1);
IServer.SelectRows('spd_Get_Suspended_Well_Info',
varArrayOf(['vch_Action_Type', 'dtm_Action_Date']),
'', iWellUIN);
vQR:=IServer.QueryResult;
sSuspendAction:=GetSingleValue(vQR);
dtmSuspendActionDate:=GetSingleValue(vQR,1);
IServer.SelectRows('spd_Get_Comment',
'vch_Comment_Text', '',
varArrayOf([iWellUIN,1]));
vQR:=IServer.QueryResult;
sCommentText:=GetSingleValue(vQR);
IServer.SelectRows('spd_Get_Well_Dinamics',
varArrayOf(['num_Charges_Def_Year',
'num_Progress_Per_Year',
'num_Annual_Charges']),
'', iWellUIN);
vDinamicsArray:=IServer.QueryResult;
IServer.SelectRows('spd_Get_Info_Sources',
varArrayOf(['Doc_Type_Id','vch_Doc_Num','Foundation_Id']),
'', varArrayOf([iWellUIN, 1]));
vDocumentsArray:=IServer.QueryResult;
except on Exception do Result:=-1;
end; //try..except
end; //if iRes>0
end;
end.
|
Unit AdvCSVFormatters;
{
Copyright (c) 2001-2013, Kestral Computing Pty Ltd (http://www.kestral.com.au)
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 HL7 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 HOLDER 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.
}
Interface
Uses
EncodeSupport,
AdvTextFormatters, AdvStringLists;
Type
TAdvCSVFormatter = Class(TAdvTextFormatter)
Private
FSeparator : Char;
FQuote : Char;
FHasQuote : Boolean;
FEmptyLine : Boolean;
Public
Constructor Create; Override;
Destructor Destroy; Override;
Procedure Clear; Override;
Procedure ProduceEntryStringArray(Const aEntryStringArray : Array Of String);
Procedure ProduceEntryStringList(oEntryStringList : TAdvStringList);
Procedure ProduceEntry(Const sEntry : String);
Procedure ProduceSeparator;
Procedure ProduceNewLine; Override;
Property Separator : Char Read FSeparator Write FSeparator;
Property Quote : Char Read FQuote Write FQuote;
Property HasQuote : Boolean Read FHasQuote Write FHasQuote;
End;
Implementation
Constructor TAdvCSVFormatter.Create;
Begin
Inherited;
FSeparator := ',';
FQuote := '"';
FHasQuote := True;
FEmptyLine := True;
End;
Destructor TAdvCSVFormatter.Destroy;
Begin
Inherited;
End;
Procedure TAdvCSVFormatter.Clear;
Begin
Inherited;
FEmptyLine := True;
End;
Procedure TAdvCSVFormatter.ProduceEntryStringList(oEntryStringList: TAdvStringList);
Var
iEntryIndex : Integer;
Begin
For iEntryIndex := 0 To oEntryStringList.Count - 1 Do
ProduceEntry(oEntryStringList[iEntryIndex]);
End;
Procedure TAdvCSVFormatter.ProduceEntryStringArray(Const aEntryStringArray: Array Of String);
Var
iEntryIndex : Integer;
Begin
For iEntryIndex := Low(aEntryStringArray) To High(aEntryStringArray) Do
ProduceEntry(aEntryStringArray[iEntryIndex]);
End;
Procedure TAdvCSVFormatter.ProduceEntry(Const sEntry : String);
Begin
If FEmptyLine Then
FEmptyLine := False
Else
ProduceSeparator;
if sEntry <> '' then
If FHasQuote Then
Produce(EncodeQuotedString(sEntry, FQuote))
Else
Produce(sEntry)
End;
Procedure TAdvCSVFormatter.ProduceNewLine;
Begin
Inherited;
FEmptyLine := True;
End;
Procedure TAdvCSVFormatter.ProduceSeparator;
Begin
Produce(FSeparator);
End;
End. // AdvCSVFormatters //
|
{$INCLUDE switches}
unit CityProcessing;
interface
uses
Protocol, Database;
// Reporting
procedure GetCityAreaInfo(p,Loc: integer; var CityAreaInfo: TCityAreaInfo);
function CanCityGrow(p,cix: integer): boolean;
function GetCityReport(p,cix: integer; var CityReport: TCityReport): integer;
function GetCityReportNew(p,cix: integer; var CityReportNew: TCityReportNew): integer;
// Internal Tile Picking
function AddBestCityTile(p,cix: integer): boolean;
procedure CityGrowth(p,cix: integer);
procedure CityShrink(p,cix: integer);
procedure Pollute(p,cix: integer);
// Turn Processing
procedure PayCityMaintenance(p,cix: integer);
procedure CollectCityResources(p,cix: integer);
function CityTurn(p,cix: integer): boolean;
// Tile Access
function SetCityTiles(p, cix, NewTiles: integer; TestOnly: boolean = false): integer;
procedure GetCityTileAdvice(p, cix: integer; var Advice: TCityTileAdviceData);
// Start/End Game
procedure InitGame;
procedure ReleaseGame;
implementation
type
TTradeProcessing=record
TaxBonus,LuxBonus,ScienceBonus,FutResBonus,ScienceDoubling,HappyBase: integer;
RelCorr: single;
FlexibleLuxury: boolean;
end;
TProdProcessing=record
ProdBonus,PollBonus,FutProdBonus,PollThreshold: integer;
end;
PCityReportEx=^TCityReportEx;
TCityReportEx=record
BaseHappiness,BaseControl,Material: integer;
ProdProcessing: TProdProcessing;
TradeProcessing: TTradeProcessing;
end;
var
MaxDist: integer;
{
Reporting
____________________________________________________________________
}
procedure GetCityAreaInfo(p,Loc: integer; var CityAreaInfo: TCityAreaInfo);
var
V21, Loc1, p1: integer;
Radius: TVicinity21Loc;
begin
{$IFOPT O-}assert(1 shl p and InvalidTreatyMap=0);{$ENDIF}
with CityAreaInfo do
begin
V21_to_Loc(Loc,Radius);
for V21:=0 to 26 do
begin
Loc1:=Radius[V21];
if (Loc1<0) or (Loc1>=MapSize) then Available[V21]:=faInvalid
else
begin
p1:=RealMap[Loc1] shr 27;
if (p1<nPl) and (p1<>p) and (RW[p].Treaty[p1]>=trPeace) then
Available[V21]:=faTreaty
else if (ZoCMap[Loc1]>0) and (Occupant[Loc1]<>p)
and (RW[p].Treaty[Occupant[Loc1]]<trAlliance) then
Available[V21]:=faSiege
else if (UsedByCity[Loc1]<>-1) and (UsedByCity[Loc1]<>Loc) then
Available[V21]:=faNotAvailable
else Available[V21]:=faAvailable
end
end;
end
end;
function CanCityGrow(p,cix: integer): boolean;
begin
with RW[p].City[cix] do
result:= (Size<MaxCitySize) and ((Size<NeedAqueductSize)
or (Built[imAqueduct]=1) and (Size<NeedSewerSize)
or (Built[imSewer]=1));
end;
procedure DetermineCityProdProcessing(p,cix: integer;
var ProdProcessing: TProdProcessing);
begin
with RW[p].City[cix],ProdProcessing do
begin
ProdBonus:=0;
PollBonus:=0;
if Built[imFactory]=1 then
inc(ProdBonus);
if Built[imMfgPlant]=1 then
inc(ProdBonus);
if (Built[imPower]=1) or (Built[imHydro]=1)
or (Built[imNuclear]=1) or (GWonder[woHoover].EffectiveOwner=p) then
ProdBonus:=ProdBonus*2;
if Built[imFactory]=1 then
inc(PollBonus);
if Built[imMfgPlant]=1 then
inc(PollBonus);
if (Built[imFactory]+Built[imMfgPlant]>0) then
if (Built[imHydro]>0)
or (GWonder[woHoover].EffectiveOwner=p) then
dec(PollBonus)
else if (Built[imNuclear]=0) and (Built[imPower]=1) then
inc(PollBonus);
if (RW[p].Government<=gDespotism) or (Built[imRecycling]=1) then
PollBonus:=-2; // no pollution
PollThreshold:=Size;
FutProdBonus:=0;
if RW[p].Tech[futProductionTechnology]>0 then
begin // future tech benefits
if Built[imFactory]=1 then
inc(FutProdBonus,FactoryFutureBonus*RW[p].Tech[futProductionTechnology]);
if Built[imMfgPlant]=1 then
inc(FutProdBonus,MfgPlantFutureBonus*RW[p].Tech[futProductionTechnology]);
end;
end;
end;
procedure BoostProd(BaseProd: integer; ProdProcessing: TProdProcessing;
var Prod,Poll: integer);
begin
Poll:=BaseProd*(2+ProdProcessing.PollBonus) shr 1;
if Poll<=ProdProcessing.PollThreshold then
Poll:=0
else dec(Poll,ProdProcessing.PollThreshold);
if ProdProcessing.FutProdBonus>0 then
Prod:=BaseProd*(100+ProdProcessing.ProdBonus*50+ProdProcessing.FutProdBonus) div 100
else Prod:=BaseProd*(2+ProdProcessing.ProdBonus) shr 1;
end;
procedure DetermineCityTradeProcessing(p,cix,HappinessBeforeLux: integer;
var TradeProcessing: TTradeProcessing);
var
i,Dist: integer;
begin
with RW[p].City[cix],TradeProcessing do
begin
TaxBonus:=0;
ScienceBonus:=0;
if Built[imMarket]=1 then
inc(TaxBonus,2);
if Built[imBank]=1 then
begin
inc(TaxBonus,3);
if RW[p].NatBuilt[imStockEx]=1 then
inc(TaxBonus,3);
end;
LuxBonus:=TaxBonus;
if Built[imLibrary]=1 then
inc(ScienceBonus,2);
if Built[imUniversity]=1 then
inc(ScienceBonus,3);
if Built[imResLab]=1 then
inc(ScienceBonus,3);
ScienceDoubling:=0;
if Built[imNatObs]>0 then
inc(ScienceDoubling);
if RW[p].Government=gFundamentalism then
dec(ScienceDoubling)
else if (GWonder[woNewton].EffectiveOwner=p) and (RW[p].Government=gMonarchy) then
inc(ScienceDoubling);
FlexibleLuxury:=
((ServerVersion[p]>=$0100F1) and (GWonder[woLiberty].EffectiveOwner=p)
or (ServerVersion[p]<$0100F1) and (GWonder[woMich].EffectiveOwner=p))
and (RW[p].Government<>gAnarchy);
FutResBonus:=0;
if RW[p].Tech[futResearchTechnology]>0 then
begin // future tech benefits
if Built[imUniversity]=1 then
inc(FutResBonus,UniversityFutureBonus*RW[p].Tech[futResearchTechnology]);
if Built[imResLab]=1 then
inc(FutResBonus,ResLabFutureBonus*RW[p].Tech[futResearchTechnology]);
end;
if (RW[p].NatBuilt[imPalace]>0) or (ServerVersion[p]<$010000) then
begin // calculate corruption
Dist:=MaxDist;
for i:=0 to RW[p].nCity-1 do
if (RW[p].City[i].Loc>=0) and (RW[p].City[i].Built[imPalace]=1) then
Dist:=Distance(Loc,RW[p].City[i].Loc);
if (Dist=0) or (CorrLevel[RW[p].Government]=0) then
RelCorr:=0.0
else
begin
RelCorr:=Dist/MaxDist;
if CorrLevel[RW[p].Government]>1 then
RelCorr:=
Exp(ln(RelCorr)/CorrLevel[RW[p].Government]);
if Built[imCourt]=1 then
RelCorr:=RelCorr/2;
// !!! floating point calculation always deterministic???
end
end
else if Built[imCourt]=1 then
RelCorr:=0.5
else RelCorr:=1.0;
HappyBase:=Size+HappinessBeforeLux;
end
end;
procedure SplitTrade(Trade,TaxRate,LuxRate,Working: integer;
TradeProcessing :TTradeProcessing; var Corruption,Tax,Lux,Science: integer);
var
plus: integer;
begin
Corruption:=Trunc(Trade*TradeProcessing.RelCorr);
Tax:=(TaxRate*(Trade-Corruption)+50) div 100;
if TradeProcessing.FlexibleLuxury then
begin
plus:=Working*2-TradeProcessing.HappyBase; // required additional luxury
if plus>0 then
begin
Lux:=(4*plus +3+TradeProcessing.LuxBonus) div (4+TradeProcessing.LuxBonus);
if Lux>Trade-Corruption then Lux:=Trade-Corruption;
if Tax>Trade-Corruption-Lux then Tax:=Trade-Corruption-Lux;
end
else Lux:=0;
end
else if (LuxRate=0) or (TaxRate=100) then Lux:=0
else Lux:=(LuxRate*(Trade-Corruption)+49) div 100;
Science:=Trade-Corruption-Lux-Tax;
Tax:=Tax*(4+TradeProcessing.TaxBonus) shr 2;
Lux:=Lux*(4+TradeProcessing.LuxBonus) shr 2;
if TradeProcessing.FutResBonus>0 then
Science:=Science*(100+TradeProcessing.ScienceBonus*25+TradeProcessing.FutResBonus) div 100
else Science:=Science*(4+TradeProcessing.ScienceBonus) shr 2;
Science:=Science shl 2 shr (2-TradeProcessing.ScienceDoubling);
end;
function GetProjectCost(p,cix: integer): integer;
var
i: integer;
begin
with RW[p].City[cix] do
begin
if Project and cpImp=0 then
begin
result:=RW[p].Model[Project and cpIndex].Cost; {unit project}
if Project and cpConscripts<>0 then
begin
i:=RW[p].Model[Project and cpIndex].MCost;
result:=result-3*i;
if result<=0 then result:=i
end
else if RW[p].Model[Project and cpIndex].Cap[mcLine]>0 then
if Project0 and (not cpAuto or cpRepeat)=Project and not cpAuto or cpRepeat then
result:=result shr 1
else result:=result*2
end
else
begin {improvement project}
result:=Imp[Project and cpIndex].Cost;
if (Project and cpIndex<28) and (GWonder[woColossus].EffectiveOwner=p) then
result:=result*ColossusEffect div 100;
end;
result:=result*BuildCostMod[Difficulty[p]] div 12;
end
end;
function GetSmallCityReport(p,cix: integer; var CityReport: TCityReport;
pCityReportEx: PCityReportEx = nil): integer;
var
i,uix,V21,Loc1,ForcedSupport,BaseHappiness,Control: integer;
ProdProcessing: TProdProcessing;
TradeProcessing: TTradeProcessing;
Radius: TVicinity21Loc;
UnitReport: TUnitReport;
RareOK: array[0..3] of integer;
TileInfo:TTileInfo;
begin
with RW[p].City[cix], CityReport do
begin
if HypoTiles<=0 then HypoTiles:=Tiles;
if HypoTax<0 then HypoTax:=RW[p].TaxRate;
if HypoLux<0 then HypoLux:=RW[p].LuxRate;
if (Flags and chCaptured<>0) or (RW[p].Government=gAnarchy) then
begin
Working:=0;
for V21:=1 to 26 do if HypoTiles and (1 shl V21)<>0 then
inc(Working); // for backward compatibility
if RW[p].Government=gFundamentalism then
begin Happy:=Size; Control:=Size end // !!! old bug, kept for compatibility
else begin Happy:=0; Control:=0 end;
BaseHappiness:=BasicHappy*2;
Support:=0;
Deployed:=0;
Eaten:=Size*2;
FoodRep:=Size*2;
ProdRep:=0;
Trade:=0;
PollRep:=0;
Corruption:=0;
Tax:=0;
Lux:=0;
Science:=0;
if pCityReportEx<>nil then
begin
pCityReportEx.Material:=ProdRep;
pCityReportEx.BaseHappiness:=BaseHappiness;
pCityReportEx.BaseControl:=Control;
end;
end
else // not captured, no anarchy
begin
Control:=0;
BaseHappiness:=BasicHappy*2;
Happy:=BasicHappy;
if (Built[imColosseum]>0) then
begin
if (Happy<(Size+1) shr 1) then
Happy:=(Size+1) shr 1;
if Size>4 then
BaseHappiness:=Size;
end;
for i:=0 to 27 do if Built[i]=1 then
begin inc(Happy); inc(BaseHappiness,2) end;
if Built[imTemple]=1 then
begin inc(Happy); inc(BaseHappiness,2) end;
if Built[imCathedral]=1 then
begin
inc(Happy,2); inc(BaseHappiness,4);
if GWonder[woBach].EffectiveOwner=p then
begin inc(Happy); inc(BaseHappiness,2) end;
end;
if Built[imTheater]>0 then
begin inc(Happy,2); inc(BaseHappiness,4) end;
// calculate unit support
{$IFOPT O-}assert(InvalidTreatyMap=0);{$ENDIF}
Support:=0; ForcedSupport:=0; Eaten:=Size*2; Deployed:=0;
for uix:=0 to RW[p].nUn-1 do with RW[p].Un[uix] do
if (Loc>=0) and (Home=cix) then
begin
GetUnitReport(p,uix,UnitReport);
inc(Eaten,UnitReport.FoodSupport);
if UnitReport.ReportFlags and urfAlwaysSupport<>0 then
inc(ForcedSupport, UnitReport.ProdSupport)
else inc(Support, UnitReport.ProdSupport);
if UnitReport.ReportFlags and urfDeployed<>0 then
inc(Deployed);
end;
if Deployed>=Happy then Happy:=0 else dec(Happy,Deployed);
dec(Support,Size*SupportFree[RW[p].Government] shr 1);
if Support<0 then Support:=0;
inc(Support,ForcedSupport);
{control}
case RW[p].Government of
gDespotism:
for uix:=0 to RW[p].nUn-1 do
if (RW[p].Un[uix].Loc=Loc)
and (RW[p].Model[RW[p].Un[uix].mix].Kind=mkSpecial_TownGuard) then
begin inc(Happy); inc(Control,2) end;
gFundamentalism:
begin
BaseHappiness:=0; // done by control
Happy:=Size;
Control:=Size
end;
end;
// collect processing parameters
DetermineCityProdProcessing(p, cix, ProdProcessing);
DetermineCityTradeProcessing(p, cix, BaseHappiness+Control-2*Deployed, TradeProcessing);
// collect resources
Working:=0;
FoodRep:=0;ProdRep:=0;Trade:=0;
FillChar(RareOK,SizeOf(RareOK),0);
V21_to_Loc(Loc,Radius);
for V21:=1 to 26 do if HypoTiles and (1 shl V21)<>0 then
begin {sum resources of exploited tiles}
Loc1:=Radius[V21];
if (Loc1<0) or (Loc1>=MapSize) then // HypoTiles go beyond map border!
begin result:=eInvalid; exit end;
GetTileInfo(p,cix,Loc1,TileInfo);
inc(FoodRep,TileInfo.Food);
inc(ProdRep,TileInfo.Prod);
inc(Trade,TileInfo.Trade);
if (RealMap[Loc1] and fModern<>0) and (RW[p].Tech[adMassProduction]>=tsApplicable) then
inc(RareOK[RealMap[Loc1] shr 25 and 3]);
inc(Working)
end;
if Built[imAlgae]=1 then
inc(FoodRep,12);
if pCityReportEx<>nil then
begin
pCityReportEx.Material:=ProdRep;
pCityReportEx.BaseHappiness:=BaseHappiness;
pCityReportEx.BaseControl:=Control;
pCityReportEx.ProdProcessing:=ProdProcessing;
pCityReportEx.TradeProcessing:=TradeProcessing;
end;
BoostProd(ProdRep,ProdProcessing,ProdRep,PollRep);
SplitTrade(Trade,HypoTax,HypoLux,Working,TradeProcessing,
Corruption,Tax,Lux,Science);
Happy:=Happy+(Lux+Size and 1) shr 1;
//new style disorder requires 1 lux less for cities with odd size
// check if rare resource available
if (GTestFlags and tfNoRareNeed=0) and (ProdRep>Support)
and (Project and cpImp<>0)
and ((Project and cpIndex=imShipComp) and (RareOK[1]=0)
or (Project and cpIndex=imShipPow) and (RareOK[2]=0)
or (Project and cpIndex=imShipHab) and (RareOK[3]=0)) then
ProdRep:=Support;
end;
end;
result:=eOk;
end; {GetSmallCityReport}
function GetCityReport(p,cix: integer; var CityReport: TCityReport): integer;
begin
result:=GetSmallCityReport(p,cix,CityReport);
CityReport.Storage:=StorageSize[Difficulty[p]];
CityReport.ProdCost:=GetProjectCost(p,cix);
end;
function GetCityReportNew(p,cix: integer; var CityReportNew: TCityReportNew): integer;
var
CityReport: TCityReport;
CityReportEx: TCityReportEx;
begin
with CityReportNew do
begin
CityReport.HypoTiles:=HypoTiles;
CityReport.HypoTax:=HypoTaxRate;
CityReport.HypoLux:=HypoLuxuryRate;
result:=GetSmallCityReport(p,cix,CityReport,@CityReportEx);
FoodSupport:=CityReport.Eaten-2*RW[p].City[cix].Size;
MaterialSupport:=CityReport.Support;
ProjectCost:=GetProjectCost(p,cix);
Storage:=StorageSize[Difficulty[p]];
Deployed:=CityReport.Deployed;
Morale:=CityReportEx.BaseHappiness;
CollectedControl:=CityReportEx.BaseControl+(RW[p].City[cix].Size-CityReport.Working)*2;
CollectedFood:=CityReport.FoodRep;
CollectedMaterial:=CityReportEx.Material;
CollectedTrade:=CityReport.Trade;
Working:=CityReport.Working;
Production:=CityReport.ProdRep-CityReport.Support;
AddPollution:=CityReport.PollRep;
Corruption:=CityReport.Corruption;
Tax:=CityReport.Tax;
Science:=CityReport.Science;
Luxury:=CityReport.Lux;
FoodSurplus:=CityReport.FoodRep-CityReport.Eaten;
HappinessBalance:=Morale+Luxury+CollectedControl
-RW[p].City[cix].Size-2*Deployed;
end;
end;
{
Internal Tile Picking
____________________________________________________________________
}
procedure NextBest(p,cix:integer; var SelectedLoc, SelectedV21: integer);
{best tile unused but available by city cix}
var
Resources,Most,Loc1,p1,V21:integer;
TileInfo:TTileInfo;
Radius: TVicinity21Loc;
begin
{$IFOPT O-}assert(1 shl p and InvalidTreatyMap=0);{$ENDIF}
Most:=0;
SelectedLoc:=-1;
SelectedV21:=-1;
with RW[p].City[cix] do
begin
V21_to_Loc(Loc,Radius);
for V21:=1 to 26 do
begin
Loc1:=Radius[V21];
if (Loc1>=0) and (Loc1<MapSize) and (UsedByCity[Loc1]=-1) then
begin
p1:=RealMap[Loc1] shr 27;
if ((p1=nPl) or (p1=p) or (RW[p].Treaty[p1]<trPeace))
and ((ZoCMap[Loc1]=0) or (Occupant[Loc1]=p)
or (RW[p].Treaty[Occupant[Loc1]]=trAlliance)) then
begin
GetTileInfo(p,cix,Loc1,TileInfo);
Resources:=TileInfo.Food shl 16+TileInfo.Prod shl 8+TileInfo.Trade;
{priority: 1.food - 2.prod - 3.trade}
if Resources>Most then
begin
SelectedLoc:=Loc1;
SelectedV21:=V21;
Most:=Resources
end
end
end
end;
end;
end;
procedure NextWorst(p,cix:integer; var SelectedLoc, SelectedV21: integer);
{worst tile used by city cix}
var
Resources,Least,Loc1,V21:integer;
Radius: TVicinity21Loc;
TileInfo:TTileInfo;
begin
Least:=MaxInt;
SelectedLoc:=-1;
SelectedV21:=-1;
with RW[p].City[cix] do
begin
V21_to_Loc(Loc,Radius);
for V21:=1 to 26 do if V21<>CityOwnTile then
begin
Loc1:=Radius[V21];
if (Loc1>=0) and (Loc1<MapSize) and (1 shl V21 and Tiles<>0) then
begin
GetTileInfo(p,cix,Loc1,TileInfo);
Resources:=TileInfo.Food shl 16+TileInfo.Prod shl 8+TileInfo.Trade;
{priority: 1.food - 2.prod - 3.trade}
if Resources<Least then
begin
SelectedLoc:=Loc1;
SelectedV21:=V21;
Least:=Resources
end
end;
end
end
end;
function NextPoll(p,cix:integer):integer;
var
Resources,Best,dx,dy,Loc1,Dist,BestDist,V21,pTerr:integer;
Radius: TVicinity21Loc;
TileInfo:TTileInfo;
begin
{$IFOPT O-}assert(1 shl p and InvalidTreatyMap=0);{$ENDIF}
Best:=0;
BestDist:=0;
result:=-1;
with RW[p].City[cix] do
begin
V21_to_Loc(Loc,Radius);
for V21:=1 to 26 do if V21<>CityOwnTile then
begin
Loc1:=Radius[V21];
if (Loc1>=0) and (Loc1<MapSize)
and (RealMap[Loc1] and fTerrain>=fGrass)
and (RealMap[Loc1] and (fPoll or fDeadLands or fCity)=0) then
begin
pTerr:=RealMap[Loc1] shr 27;
if (pTerr=nPl) or (pTerr=p) or (RW[p].Treaty[pTerr]<trPeace) then
begin
GetTileInfo(p,cix,Loc1,TileInfo);
Resources:=TileInfo.Prod shl 16+TileInfo.Trade shl 8+TileInfo.Food;
{priority: 1.prod - 2.trade - 3.food}
dy:=V21 shr 2-3;
dx:=V21 and 3 shl 1 -3 + (dy+3) and 1;
Dist:=abs(dx)+abs(dy)+abs(abs(dx)-abs(dy)) shr 1;
if (Resources>Best) or (Resources=Best) and (Dist<BestDist) then
begin
result:=Loc1;
Best:=Resources;
BestDist:=Dist
end
end
end
end;
end
end;
function AddBestCityTile(p,cix: integer): boolean;
var
TileLoc,V21: integer;
begin
NextBest(p,cix,TileLoc,V21);
result:= TileLoc>=0;
if result then with RW[p].City[cix] do
begin
assert(1 shl V21 and Tiles=0);
Tiles:=Tiles or (1 shl V21);
UsedByCity[TileLoc]:=Loc
end
end;
procedure CityGrowth(p,cix: integer);
var
TileLoc,V21: integer;
AltCityReport:TCityReport;
begin
with RW[p].City[cix] do
begin
inc(Size);
NextBest(p,cix,TileLoc,V21);
if TileLoc>=0 then
begin {test whether exploitation of tile would lead to disorder}
AltCityReport.HypoTiles:=Tiles+1 shl V21;
AltCityReport.HypoTax:=-1;
AltCityReport.HypoLux:=-1;
GetSmallCityReport(p,cix,AltCityReport);
if AltCityReport.Working-AltCityReport.Happy<=Size shr 1 then // !!! change to new style disorder
begin {no disorder -- exploit tile}
assert(1 shl V21 and Tiles=0);
Tiles:=Tiles or (1 shl V21);
UsedByCity[TileLoc]:=Loc
end
end;
end
end;
procedure CityShrink(p,cix: integer);
var
TileLoc, V21, Working: integer;
AltCityReport:TCityReport;
begin
with RW[p].City[cix] do
begin
Working:=0;
for V21:=1 to 26 do if Tiles and (1 shl V21)<>0 then inc(Working);
dec(Size);
if Food>StorageSize[Difficulty[p]] then Food:=StorageSize[Difficulty[p]];
NextWorst(p,cix,TileLoc,V21);
if Working>Size then
begin {all citizens were working -- worst tile no longer exploited}
assert(1 shl V21 and Tiles<>0);
Tiles:=Tiles and not (1 shl V21);
UsedByCity[TileLoc]:=-1
end
else {test whether exploitation of tile would lead to disorder}
begin
AltCityReport.HypoTiles:=-1;
AltCityReport.HypoTax:=-1;
AltCityReport.HypoLux:=-1;
GetSmallCityReport(p,cix,AltCityReport);
if AltCityReport.Working-AltCityReport.Happy>Size shr 1 then // !!! change to new style disorder
begin {disorder -- don't exploit tile}
assert(1 shl V21 and Tiles<>0);
Tiles:=Tiles and not (1 shl V21);
UsedByCity[TileLoc]:=-1
end
end;
end
end;
procedure Pollute(p,cix: integer);
var
PollutionLoc: integer;
begin
with RW[p].City[cix] do
begin
Pollution:=Pollution-MaxPollution;
PollutionLoc:=NextPoll(p,cix);
if PollutionLoc>=0 then
begin
inc(Flags,chPollution);
RealMap[PollutionLoc]:=RealMap[PollutionLoc] or fPoll;
end
end;
end;
{
Turn Processing
____________________________________________________________________
}
procedure PayCityMaintenance(p,cix: integer);
var
i: integer;
begin
with RW[p],City[cix] do
for i:=28 to nImp-1 do
if (Built[i]>0)
and (Project0 and (cpImp or cpIndex)<>(cpImp or i)) then // don't pay maintenance when just completed
begin
dec(Money,Imp[i].Maint);
if Money<0 then
begin {out of money - sell improvement}
inc(Money,Imp[i].Cost*BuildCostMod[Difficulty[p]] div 12);
Built[i]:=0;
if Imp[i].Kind<>ikCommon then
begin
assert(i<>imSpacePort); // never sell automatically! (solution: no maintenance)
NatBuilt[i]:=0;
if i=imGrWall then GrWallContinent[p]:=-1;
end;
inc(Flags,chImprovementLost)
end
end;
end;
procedure CollectCityResources(p,cix: integer);
var
CityStorage,CityProjectCost: integer;
CityReport: TCityReportNew;
Disorder: boolean;
begin
with RW[p],City[cix],CityReport do
if Flags and chCaptured<>0 then
begin
Flags:=Flags and not chDisorder;
dec(Flags,$10000);
if Flags and chCaptured=0 then
Flags:=Flags or chAfterCapture;
end
else if Government=gAnarchy then
Flags:=Flags and not chDisorder
else
begin
HypoTiles:=-1;
HypoTaxRate:=-1;
HypoLuxuryRate:=-1;
GetCityReportNew(p,cix,CityReport);
CityStorage:=StorageSize[Difficulty[p]];
CityProjectCost:=GetProjectCost(p,cix);
Disorder:= (HappinessBalance<0);
if Disorder and (Flags and chDisorder<>0) then
CollectedMaterial:=0; // second turn disorder
if Disorder then
Flags:=Flags or chDisorder
else Flags:=Flags and not chDisorder;
if not Disorder
and ((Government=gFuture)
or (Size>=NeedAqueductSize) and (FoodSurplus<2)) and (FoodSurplus>0) then
inc(Money,FoodSurplus)
else if not (Disorder and (FoodSurplus>0)) then
begin {calculate new food storage}
Food:=Food+FoodSurplus;
if ((GTestFlags and tfImmGrow<>0)
or (Food>=CityStorage) and (Food-FoodSurplus<CityStorage)) // only warn once
and (Size<MaxCitySize)
and (Project and (cpImp+cpIndex)<>cpImp+imAqueduct)
and (Project and (cpImp+cpIndex)<>cpImp+imSewer)
and not CanCityGrow(p,cix) then
inc(Flags,chNoGrowthWarning);
end;
if Prod>CityProjectCost then
begin inc(Money,Prod-CityProjectCost); Prod:=CityProjectCost end;
if Production<0 then
Flags:=Flags or chUnitLost
else if not Disorder and (Flags and chProductionSabotaged=0) then
if Project and (cpImp+cpIndex)=cpImp+imTrGoods then
inc(Money,Production)
else inc(Prod,Production);
if not Disorder then
begin
{sum research points and taxes}
inc(Research,Science);
inc(Money,Tax);
Pollution:=Pollution+AddPollution;
end;
end;
end;
function CityTurn(p,cix: integer): boolean;
// return value: whether city keeps existing
var
i,uix,cix2,p1,SizeMod,CityStorage,CityProjectCost,NewImp,Det,TestDet: integer;
LackOfMaterial, CheckGrow, DoProd, IsActive: boolean;
begin
with RW[p],City[cix] do
begin
SizeMod:=0;
CityStorage:=StorageSize[Difficulty[p]];
CityProjectCost:=GetProjectCost(p,cix);
LackOfMaterial:= Flags and chUnitLost<>0;
Flags:=Flags and not chUnitLost;
IsActive:= (Government<>gAnarchy) and (Flags and chCaptured=0);
CheckGrow:=(Flags and chDisorder=0) and IsActive
and (Government<>gFuture);
if CheckGrow and (GTestFlags and tfImmGrow<>0) then {fast growth}
begin
if CanCityGrow(p,cix) then inc(SizeMod)
end
else if CheckGrow and (Food>=CityStorage) then {normal growth}
begin
if CanCityGrow(p,cix) then
begin
if Built[imGranary]=1 then dec(Food,CityStorage shr 1)
else dec(Food,CityStorage);
inc(SizeMod)
end
end
else if Food<0 then {famine}
begin
Food:=0;
// check if settlers or conscripts there to disband
uix:=-1;
for i:=0 to nUn-1 do
if (Un[i].Loc>=0) and (Un[i].Home=cix)
and ((Model[Un[i].mix].Kind=mkSettler)
{and (GWonder[woFreeSettlers].EffectiveOwner<>p)}
or (Un[i].Flags and unConscripts<>0))
and ((uix=-1) or (Model[Un[i].mix].Cost<Model[Un[uix].mix].Cost)
or (Model[Un[i].mix].Cost=Model[Un[uix].mix].Cost)
and (Un[i].Exp<Un[uix].Exp)) then
uix:=i;
if uix>=0 then
begin RemoveUnit_UpdateMap(p,uix); inc(Flags,chUnitLost); end
else begin dec(SizeMod); inc(Flags,chPopDecrease) end
end;
if Food>CityStorage then Food:=CityStorage;
if LackOfMaterial then
begin
if Flags and chUnitLost=0 then
begin {one unit lost}
uix:=-1;
Det:=MaxInt;
for i:=0 to nUn-1 do if (Un[i].Loc>=0) and (Un[i].Home=cix) then
with Model[Un[i].mix] do
begin
if Kind=mkSpecial_TownGuard then
TestDet:=Un[i].Health+Un[i].Exp shl 8 // disband townguards first
else
begin
TestDet:=Un[i].Health+Un[i].Exp shl 8+Cost shl 16; // value of unit
if Flags and mdDoubleSupport<>0 then
TestDet:=TestDet shr 1; // double support, tend to disband first
end;
if TestDet<Det then
begin uix:=i; Det:=TestDet end;
end;
if uix>=0 then
begin
RemoveUnit_UpdateMap(p,uix);
inc(Flags,chUnitLost);
end
end
end;
if GTestFlags and tfImmImprove<>0 then Prod:=CityProjectCost;
DoProd:= (Project and (cpImp+cpIndex)<>cpImp+imTrGoods)
and (Prod>=CityProjectCost);
// check if wonder already built
if (Project and cpImp<>0) and (Project and cpIndex<28)
and (GWonder[Project and cpIndex].CityID<>-1) then
begin inc(Flags,chOldWonder); DoProd:=false; end;
// check if producing settlers would disband city
if DoProd and (Project and (cpImp or cpDisbandCity)=0)
and ((Size+SizeMod-2<2) and (Model[Project and cpIndex].Kind=mkSettler)
or (Size+SizeMod-1<2) and ((Model[Project and cpIndex].Kind=mkSlaves)
or (Project and cpConscripts<>0))) then
begin inc(Flags,chNoSettlerProd); DoProd:=false; end;
if DoProd then
begin {project complete}
dec(Prod,CityProjectCost);
if Project and cpImp=0 then {produce unit}
begin
if nUn<numax then
begin
CreateUnit(p,Project and cpIndex);
Un[nUn-1].Loc:=Loc;
with Un[nUn-1] do
begin
Home:=cix;
if (Model[mix].Domain<dSea) and (Built[imElite]=1) then
Exp:=ExpCost*(nExp-1){elite}
else if (Model[mix].Domain<dSea) and (Built[imBarracks]=1)
or (Model[mix].Domain=dSea) and (Built[imDockyard]=1)
or (Model[mix].Domain=dAir) and (Built[imAirport]=1) then
Exp:=ExpCost*2;{vet}
if Project and cpConscripts<>0 then Flags:=Flags or unConscripts
end;
PlaceUnit(p,nUn-1);
UpdateUnitMap(Loc);
if Model[Project and cpIndex].Kind=mkSettler then
dec(SizeMod,2) {settler produced - city shrink}
else if (Model[Project and cpIndex].Kind=mkSlaves)
or (Project and cpConscripts<>0) then
dec(SizeMod); {slaves/conscripts produced - city shrink}
end;
Project0:=Project or cpRepeat or cpCompleted;
end
else if Imp[Project and cpIndex].Kind=ikShipPart then
begin {produce ship parts}
inc(GShip[p].Parts[Project and cpIndex-imShipComp]);
Project0:=Project or cpCompleted;
end
else {produce improvement}
begin
NewImp:=Project and cpIndex;
inc(Money,Prod);{change rest to money}
Project0:=Project or cpCompleted;
Project:=cpImp+imTrGoods;
Prod:=0;
if Imp[NewImp].Kind in [ikNatLocal,ikNatGlobal] then
begin // nat. project
for i:=0 to nCity-1 do
if (City[i].Loc>=0) and (City[i].Built[NewImp]=1) then
begin {allowed only once}
inc(Money,Imp[NewImp].Cost
*BuildCostMod[Difficulty[p]] div 12);
City[i].Built[NewImp]:=0;
end;
NatBuilt[NewImp]:=1;
// immediate nat. project effects
case NewImp of
imGrWall: GrWallContinent[p]:=Continent[Loc];
end;
end;
if NewImp<28 then
begin // wonder
GWonder[NewImp].CityID:=ID;
GWonder[NewImp].EffectiveOwner:=p;
CheckExpiration(NewImp);
// immediate wonder effects
case NewImp of
woEiffel:
begin // reactivate wonders
for i:=0 to 27 do if Imp[i].Expiration>=0 then
for cix2:=0 to nCity-1 do
if (City[cix2].Loc>=0) and (City[cix2].Built[i]=1) then
GWonder[i].EffectiveOwner:=p
end;
woLighthouse: CheckSpecialModels(p,preLighthouse);
woLeo:
begin
inc(Research,
TechBaseCost(nTech[p],Difficulty[p])
+TechBaseCost(nTech[p]+2,Difficulty[p]));
CheckSpecialModels(p,preLeo);
end;
woPyramids: CheckSpecialModels(p,preBuilder);
woMir:
begin
for p1:=0 to nPl-1 do
if (p1<>p) and (1 shl p1 and GAlive<>0) then
begin
if RW[p].Treaty[p1]=trNoContact then
IntroduceEnemy(p,p1);
GiveCivilReport(p, p1);
GiveMilReport(p, p1)
end;
end
end;
end;
for i:=0 to nImpReplacement-1 do // sell obsolete buildings
if (ImpReplacement[i].NewImp=NewImp)
and (Built[ImpReplacement[i].OldImp]>0) then
begin
inc(RW[p].Money, Imp[ImpReplacement[i].OldImp].Cost
*BuildCostMod[Difficulty[p]] div 12);
Built[ImpReplacement[i].OldImp]:=0;
end;
if NewImp in [imPower,imHydro,imNuclear] then
for i:=0 to nImp-1 do
if (i<>NewImp) and (i in [imPower,imHydro,imNuclear])
and (Built[i]>0) then
begin // sell obsolete power plant
inc(RW[p].Money, Imp[i].Cost*BuildCostMod[Difficulty[p]] div 12);
Built[i]:=0;
end;
Built[NewImp]:=1;
end;
Prod0:=Prod;
inc(Flags,chProduction)
end
else
begin
Project0:=Project0 and not cpCompleted;
if Project0 and not cpAuto<>Project and not cpAuto then
Project0:=Project;
Prod0:=Prod;
end;
if SizeMod>0 then
begin
CityGrowth(p,cix);
inc(Flags,chPopIncrease);
end;
result:= Size+SizeMod>=2;
if result then
while SizeMod<0 do
begin CityShrink(p,cix); inc(SizeMod) end;
end
end; //CityTurn
{
Tile Access
____________________________________________________________________
}
function SetCityTiles(p, cix, NewTiles: integer; TestOnly: boolean = false): integer;
var
V21,Working,ChangeTiles,AddTiles,Loc1: integer;
CityAreaInfo: TCityAreaInfo;
Radius: TVicinity21Loc;
begin
with RW[p].City[cix] do
begin
ChangeTiles:=NewTiles xor integer(Tiles);
AddTiles:=NewTiles and not Tiles;
if Mode=moPlaying then
begin // do all checks
if NewTiles and not $67F7F76<>0 then
begin result:=eInvalid; exit end; // invalid tile index included
if NewTiles and (1 shl 13)=0 then
begin result:=eViolation; exit end; // city tile must be exploited
if ChangeTiles=0 then
begin result:=eNotChanged; exit end;
if AddTiles<>0 then
begin
// check if new tiles possible
GetCityAreaInfo(p, Loc, CityAreaInfo);
for V21:=1 to 26 do if AddTiles and (1 shl V21)<>0 then
if CityAreaInfo.Available[V21]<>faAvailable then
begin result:=eTileNotAvailable; exit end;
// not more tiles than inhabitants
Working:=0;
for V21:=1 to 26 do if NewTiles and (1 shl V21)<>0 then inc(Working);
if Working>Size then
begin result:=eNoWorkerAvailable; exit end;
end;
end;
result:=eOK;
if not TestOnly then
begin
V21_to_Loc(Loc,Radius);
for V21:=1 to 26 do if ChangeTiles and (1 shl V21)<>0 then
begin
Loc1:=Radius[V21];
assert((Loc1>=0) and (Loc1<MapSize));
if NewTiles and (1 shl V21)<>0 then UsedByCity[Loc1]:=Loc // employ tile
else if UsedByCity[Loc1]<>Loc then
assert(Mode<moPlaying)
// should only happen during loading, because of wrong sSetCityTiles command order
else UsedByCity[Loc1]:=-1 // unemploy tile
end;
Tiles:=NewTiles
end
end;
end;
procedure GetCityTileAdvice(p, cix: integer; var Advice: TCityTileAdviceData);
const
oFood=0; oProd=1; oTax=2; oScience=3;
type
TTileData=record
Food,Prod,Trade,SubValue,V21: integer;
end;
var
i,V21,Loc1,nHierarchy,iH,iT,iH_Switch,MinWorking,MaxWorking,
WantedProd,MinFood,MinProd,count,Take,MaxTake,AreaSize,FormulaCode,
NeedRare, RareTiles,cix1,dx,dy,BestTiles,ProdBeforeBoost,TestTiles,
SubPlus,SuperPlus: integer;
SuperValue,BestSuperValue,SubValue,BestSubValue: integer;
Value,BestValue,ValuePlus: extended;
ValueFormula_Weight: array[oFood..oScience] of extended;
ValueFormula_Multiply: array[oFood..oScience] of boolean;
Output: array[oFood..oScience] of integer;
TileInfo, BaseTileInfo: TTileInfo;
Radius, Radius1: TVicinity21Loc;
TestReport: TCityReport;
CityReportEx: TCityReportEx;
CityAreaInfo: TCityAreaInfo;
Hierarchy: array[0..20,0..31] of TTileData;
nTile,nSelection: array[0..20] of integer;
SubCriterion: array[0..27] of integer;
FoodWasted, FoodToTax, ProdToTax, RareOk, NeedStep2, IsBest: boolean;
begin
if (RW[p].Government=gAnarchy) or (RW[p].City[cix].Flags and chCaptured<>0) then
begin
Fillchar(Advice.CityReport, sizeof(Advice.CityReport), 0);
Advice.Tiles:=1 shl CityOwnTile;
Advice.CityReport.HypoTiles:=1 shl CityOwnTile;
exit;
end;
for i:=oFood to oScience do
begin //decode evaluation formula from weights parameter
FormulaCode:=Advice.ResourceWeights shr (24-8*i) and $FF;
ValueFormula_Multiply[i]:= FormulaCode and $80<>0;
if FormulaCode and $40<>0 then
ValueFormula_Weight[i]:=(FormulaCode and $0F)
*(1 shl (FormulaCode and $30 shr 4))/16
else ValueFormula_Weight[i]:=(FormulaCode and $0F)
*(1 shl (FormulaCode and $30 shr 4));
end;
TestReport.HypoTiles:=1 shl CityOwnTile;
TestReport.HypoTax:=-1;
TestReport.HypoLux:=-1;
GetSmallCityReport(p,cix,TestReport,@CityReportEx);
with RW[p].City[cix] do
begin
V21_to_Loc(Loc,Radius);
FoodToTax:= RW[p].Government=gFuture;
ProdToTax:= Project and (cpImp+cpIndex)=cpImp+imTrGoods;
FoodWasted:=not FoodToTax and (Food=StorageSize[Difficulty[p]])
and not CanCityGrow(p,cix);
// sub criteria
for V21:=1 to 26 do
begin
Loc1:=Radius[V21];
if Loc1>=0 then
SubCriterion[V21]:=3360-(Distance(Loc,Loc1)-1)*32-V21 xor $15;
end;
for cix1:=0 to RW[p].nCity-1 do if cix1<>cix then
begin
Loc1:=RW[p].City[cix1].Loc;
if Loc1>=0 then
begin
if Distance(Loc,Loc1)<=10 then
begin // cities overlap -- prefer tiles outside common range
V21_to_Loc(Loc1,Radius1);
for V21:=1 to 26 do
begin
Loc1:=Radius1[V21];
if (Loc1>=0) and (Loc1<MapSize) and (Distance(Loc,Loc1)<=5) then
begin
dxdy(Loc,Loc1,dx,dy);
dec(SubCriterion[(dy+3) shl 2+(dx+3) shr 1],160);
end
end
end
end
end;
GetCityAreaInfo(p,Loc,CityAreaInfo);
AreaSize:=0;
for V21:=1 to 26 do
if CityAreaInfo.Available[V21]=faAvailable then
inc(AreaSize);
if RW[p].Government=gFundamentalism then
begin
MinWorking:=Size;
MaxWorking:=Size;
end
else
begin
MinWorking:=CityReportEx.TradeProcessing.HappyBase shr 1;
if MinWorking>Size then
MinWorking:=Size;
if (RW[p].LuxRate=0)
and not CityReportEx.TradeProcessing.FlexibleLuxury then
MaxWorking:=MinWorking
else MaxWorking:=Size;
end;
if MaxWorking>AreaSize then
begin
MaxWorking:=AreaSize;
if MinWorking>AreaSize then
MinWorking:=AreaSize;
end;
if TestReport.Support=0 then
WantedProd:=0
else WantedProd:=1+(TestReport.Support*100-1)
div (100+CityReportEx.ProdProcessing.ProdBonus*50+CityReportEx.ProdProcessing.FutProdBonus);
// consider resources for ship parts
NeedRare:=0;
if (GTestFlags and tfNoRareNeed=0) and (Project and cpImp<>0) then
case Project and cpIndex of
imShipComp: NeedRare:=fCobalt;
imShipPow: NeedRare:=fUranium;
imShipHab: NeedRare:=fMercury;
end;
if NeedRare>0 then
begin
RareTiles:=0;
for V21:=1 to 26 do
begin
Loc1:=Radius[V21];
if (Loc1>=0) and (Loc1<MapSize) and (RealMap[Loc1] and fModern=cardinal(NeedRare)) then
RareTiles:=RareTiles or (1 shl V21);
end
end;
// step 1: sort tiles to hierarchies
nHierarchy:=0;
for V21:=1 to 26 do // non-rare tiles
if (CityAreaInfo.Available[V21]=faAvailable)
and ((NeedRare=0) or (1 shl V21 and RareTiles=0)) then
begin
Loc1:=Radius[V21];
assert((Loc1>=0) and (Loc1<MapSize));
GetTileInfo(p,cix,Loc1,TileInfo);
if V21=CityOwnTile then
BaseTileInfo:=TileInfo
else
begin
iH:=0;
iT:=0;
while iH<nHierarchy do
begin
iT:=0;
while (iT<nTile[iH])
and (TileInfo.Food<=Hierarchy[iH,iT].Food)
and (TileInfo.Prod<=Hierarchy[iH,iT].Prod)
and (TileInfo.Trade<=Hierarchy[iH,iT].Trade)
and not ((TileInfo.Food=Hierarchy[iH,iT].Food)
and (TileInfo.Prod=Hierarchy[iH,iT].Prod)
and (TileInfo.Trade=Hierarchy[iH,iT].Trade)
and (SubCriterion[V21]>=SubCriterion[Hierarchy[iH,iT].V21])) do
inc(iT);
if (iT=nTile[iH]) // new worst tile in this hierarchy
or ((TileInfo.Food>=Hierarchy[iH,iT].Food) // new middle tile in this hierarchy
and (TileInfo.Prod>=Hierarchy[iH,iT].Prod)
and (TileInfo.Trade>=Hierarchy[iH,iT].Trade)) then
break; // insert position found!
inc(iH);
end;
if iH=nHierarchy then
begin // need to start new hierarchy
nTile[iH]:=0;
inc(nHierarchy);
iT:=0;
end;
move(Hierarchy[iH,iT], Hierarchy[iH,iT+1], (nTile[iH]-iT)*sizeof(TTileData));
inc(nTile[iH]);
Hierarchy[iH,iT].V21:=V21;
Hierarchy[iH,iT].Food:=TileInfo.Food;
Hierarchy[iH,iT].Prod:=TileInfo.Prod;
Hierarchy[iH,iT].Trade:=TileInfo.Trade;
Hierarchy[iH,iT].SubValue:=SubCriterion[V21];
end
end;
if NeedRare<>0 then
begin // rare tiles need own hierarchy
iH:=nHierarchy;
for V21:=1 to 26 do
if (CityAreaInfo.Available[V21]=faAvailable)
and (1 shl V21 and RareTiles<>0) then
begin
Loc1:=Radius[V21];
assert((V21<>CityOwnTile) and (Loc1>=0) and (Loc1<MapSize));
GetTileInfo(p,cix,Loc1,TileInfo);
if iH=nHierarchy then
begin // need to start new hierarchy
nTile[iH]:=0;
inc(nHierarchy);
iT:=0;
end
else iT:=nTile[iH];
inc(nTile[iH]);
Hierarchy[iH,iT].V21:=V21;
Hierarchy[iH,iT].Food:=TileInfo.Food; // = 0
Hierarchy[iH,iT].Prod:=TileInfo.Prod; // = 1
Hierarchy[iH,iT].Trade:=TileInfo.Trade; // = 0
Hierarchy[iH,iT].SubValue:=SubCriterion[V21];
end;
end;
if Built[imAlgae]>0 then
inc(BaseTileInfo.Food,12);
// step 2: summarize resources
for iH:=0 to nHierarchy-1 do
begin
move(Hierarchy[iH,0], Hierarchy[iH,1], nTile[iH]*sizeof(TTileData));
Hierarchy[iH,0].Food:=0;
Hierarchy[iH,0].Prod:=0;
Hierarchy[iH,0].Trade:=0;
Hierarchy[iH,0].SubValue:=0;
Hierarchy[iH,0].V21:=0;
for iT:=1 to nTile[iH] do
begin
inc(Hierarchy[iH,iT].Food, Hierarchy[iH,iT-1].Food);
inc(Hierarchy[iH,iT].Prod, Hierarchy[iH,iT-1].Prod);
inc(Hierarchy[iH,iT].Trade, Hierarchy[iH,iT-1].Trade);
inc(Hierarchy[iH,iT].SubValue, Hierarchy[iH,iT-1].SubValue);
Hierarchy[iH,iT].V21:=1 shl Hierarchy[iH,iT].V21+Hierarchy[iH,iT-1].V21;
end;
end;
// step 3: try all combinations
BestValue:=0.0;
BestSuperValue:=0;
BestSubValue:=0;
BestTiles:=0;
fillchar(nSelection, sizeof(nSelection),0);
TestReport.FoodRep:=BaseTileInfo.Food;
ProdBeforeBoost:=BaseTileInfo.Prod;
TestReport.Trade:=BaseTileInfo.Trade;
TestReport.Working:=1;
MinFood:=0;
MinProd:=0;
iH_Switch:=nHierarchy;
count:=0;
repeat
// ensure minima
iH:=0;
while (TestReport.Working<MaxWorking) and (iH<iH_Switch)
and ((TestReport.Working<MinWorking) or (TestReport.FoodRep<TestReport.Eaten)
or (ProdBeforeBoost<WantedProd)) do
begin
assert(nSelection[iH]=0);
Take:=MinWorking-TestReport.Working;
if Take>nTile[iH] then
Take:=nTile[iH]
else
begin
if Take<0 then
Take:=0;
MaxTake:=nTile[iH];
if TestReport.Working+MaxTake>MaxWorking then
MaxTake:=MaxWorking-TestReport.Working;
while (Take<MaxTake) and (TestReport.FoodRep+Hierarchy[iH,Take].Food<MinFood) do
inc(Take);
while (Take<MaxTake) and (ProdBeforeBoost+Hierarchy[iH,Take].Prod<MinProd) do
inc(Take);
end;
nSelection[iH]:=Take;
inc(TestReport.Working, Take);
with Hierarchy[iH,Take] do
begin
inc(TestReport.FoodRep,Food);
inc(ProdBeforeBoost,Prod);
inc(TestReport.Trade,Trade);
end;
inc(iH);
end;
assert((TestReport.Working>=MinWorking) and (TestReport.Working<=MaxWorking));
if (TestReport.FoodRep>=MinFood) and (ProdBeforeBoost>=MinProd) then
begin
SplitTrade(TestReport.Trade,RW[p].TaxRate,RW[p].LuxRate,TestReport.Working,
CityReportEx.TradeProcessing, TestReport.Corruption, TestReport.Tax,
TestReport.Lux, TestReport.Science);
if CityReportEx.BaseHappiness+CityReportEx.BaseControl+TestReport.Lux
+2*(Size-TestReport.Working)-2*TestReport.Deployed>=Size then
begin // city is not in disorder -- evaluate combination
inc(count);
if (MinProd<WantedProd) and (ProdBeforeBoost>MinProd) then
begin // no combination reached wanted prod yet
MinProd:=ProdBeforeBoost;
if MinProd>WantedProd then
MinProd:=WantedProd
end;
if MinProd=WantedProd then // do not care for food before prod is ensured
if (MinFood<TestReport.Eaten) and (TestReport.FoodRep>MinFood) then
begin // no combination reached wanted food yet
MinFood:=TestReport.FoodRep;
if MinFood>TestReport.Eaten then
MinFood:=TestReport.Eaten
end;
BoostProd(ProdBeforeBoost, CityReportEx.ProdProcessing,
TestReport.ProdRep, TestReport.PollRep);
SuperValue:=0;
// super-criterion A: unit support granted?
if TestReport.ProdRep>=TestReport.Support then
SuperValue:=SuperValue or 1 shl 30;
// super-criterion B: food demand granted?
if TestReport.FoodRep>=TestReport.Eaten then
SuperValue:=SuperValue or 63 shl 24
else if TestReport.FoodRep>TestReport.Eaten-63 then
SuperValue:=SuperValue or (63-(TestReport.Eaten-TestReport.FoodRep)) shl 24;
SuperPlus:=SuperValue-BestSuperValue;
if SuperPlus>=0 then
begin
Output[oTax]:=TestReport.Tax;
Output[oScience]:=TestReport.Science;
if TestReport.FoodRep<TestReport.Eaten then
Output[oFood]:=TestReport.FoodRep
// appreciate what we have, combination will have bad supervalue anyway
else if FoodWasted then
Output[oFood]:=0
else
begin
Output[oFood]:=TestReport.FoodRep-TestReport.Eaten;
if FoodToTax or (Size>=NeedAqueductSize) and (Output[oFood]=1) then
begin
inc(Output[oTax],Output[oFood]);
Output[oFood]:=0;
end;
end;
if TestReport.ProdRep<TestReport.Support then
Output[oProd]:=TestReport.ProdRep
// appreciate what we have, combination will have bad supervalue anyway
else
begin
if NeedRare>0 then
begin
RareOk:=false;
for iH:=0 to nHierarchy-1 do
if Hierarchy[iH,nSelection[iH]].V21 and RareTiles<>0 then
RareOk:=true;
if not RareOk then
TestReport.ProdRep:=TestReport.Support;
end;
Output[oProd]:=TestReport.ProdRep-TestReport.Support;
if ProdToTax then
begin
inc(Output[oTax],Output[oProd]);
Output[oProd]:=0;
end;
end;
NeedStep2:=false;
Value:=0;
for i:=oFood to oScience do
if ValueFormula_Multiply[i] then
NeedStep2:=true
else Value:=Value+ValueFormula_Weight[i]*Output[i];
if NeedStep2 then
begin
if Value>0 then
Value:=ln(Value)+123;
for i:=oFood to oScience do
if ValueFormula_Multiply[i] and (Output[i]>0) then
Value:=Value+ValueFormula_Weight[i]*(ln(Output[i])+123);
end;
ValuePlus:=Value-BestValue;
if (SuperPlus>0) or (ValuePlus>=0.0) then
begin
SubValue:=(TestReport.FoodRep+ProdBeforeBoost+TestReport.Trade) shl 18;
TestTiles:=1 shl CityOwnTile;
for iH:=0 to nHierarchy-1 do
begin
inc(TestTiles, Hierarchy[iH,nSelection[iH]].V21);
inc(SubValue, Hierarchy[iH,nSelection[iH]].SubValue);
end;
IsBest:=true;
if (SuperPlus=0) and (ValuePlus=0.0) then
begin
SubPlus:=SubValue-BestSubValue;
if SubPlus<0 then
IsBest:=false
else if SubPlus=0 then
begin
assert(TestTiles<>BestTiles);
IsBest:= TestTiles>BestTiles
end
end;
if IsBest then
begin
BestSuperValue:=SuperValue;
BestValue:=Value;
BestSubValue:=SubValue;
BestTiles:=TestTiles;
TestReport.Happy:=(CityReportEx.TradeProcessing.HappyBase-Size) div 2
+TestReport.Lux shr 1;
Advice.CityReport:=TestReport;
end
end // if (SuperPlus>0) or (ValuePlus>=0.0)
end // if SuperPlus>=0
end
end;
// calculate next combination
iH_Switch:=0;
repeat
with Hierarchy[iH_Switch,nSelection[iH_Switch]] do
begin
dec(TestReport.FoodRep,Food);
dec(ProdBeforeBoost,Prod);
dec(TestReport.Trade,Trade);
end;
inc(nSelection[iH_Switch]);
inc(TestReport.Working);
if (nSelection[iH_Switch]<=nTile[iH_Switch]) and (TestReport.Working<=MaxWorking) then
begin
with Hierarchy[iH_Switch,nSelection[iH_Switch]] do
begin
inc(TestReport.FoodRep,Food);
inc(ProdBeforeBoost,Prod);
inc(TestReport.Trade,Trade);
end;
break;
end;
dec(TestReport.Working,nSelection[iH_Switch]);
nSelection[iH_Switch]:=0;
inc(iH_Switch);
until iH_Switch=nHierarchy;
until iH_Switch=nHierarchy; // everything tested -- done
end;
assert(BestSuperValue>0); // advice should always be possible
Advice.Tiles:=BestTiles;
Advice.CityReport.HypoTiles:=BestTiles;
end; // GetCityTileAdvice
{
Start/End Game
____________________________________________________________________
}
procedure InitGame;
var
p,i,mixTownGuard: integer;
begin
MaxDist:=Distance(0,MapSize-lx shr 1);
for p:=0 to nPl-1 do if (1 shl p and GAlive<>0) then with RW[p] do
begin // initialize capital
mixTownGuard:=0;
while Model[mixTownGuard].Kind<>mkSpecial_TownGuard do
inc(mixTownGuard);
with City[0] do
begin
Built[imPalace]:=1;
Size:=4;
for i:=2 to Size do
AddBestCityTile(p,0);
Project:=mixTownGuard;
end;
NatBuilt[imPalace]:=1;
end;
end;
procedure ReleaseGame;
begin
end;
end.
|
unit PointerscanConnector;
//thread that will constantly check if it has a connection queue and if so try to connect it and initiate a connection
//it also sets up the basic connection type
{$mode delphi}
interface
uses
Classes, SysUtils, sockets, resolve, syncobjs, math, {$ifdef windows}winsock2,{$endif} CELazySocket,
PointerscanNetworkCommands, NewKernelHandler{$ifdef darwin},macport{$endif};
type
TConnectEntry=record
id: integer;
deleted: boolean; //when set this entry should get deleted
ip: pchar;
port: word;
password: pchar;
becomeparent: boolean;
trusted: boolean;
end;
PConnectentry=^TConnectentry;
TConnectEntryArray=array of TConnectentry;
TPointerscanConnectEvent=procedure(sender: TObject; sockethandle: TSocket; IBecameAParent: boolean; entry: PConnectEntry) of object;
TPointerScanConnectorLogEvent=procedure(sender: TObject; message: string) of object;
TPointerscanConnector=class(TThread)
private
fOnConnected: TPointerscanConnectEvent;
fOnLog: TPointerScanConnectorLogEvent;
nextid: integer; //id to pass on to the next added entry
lastlog: string; //debug only
list: TList;
listcs: TCriticalSection;
hr: THostResolver;
procedure Log(msg: string);
procedure FreeEntry(entry: PConnectEntry);
procedure RemoveDeletedEntries; //only called by the thread.
public
function AddConnection(ip: string; port: word; password: string; becomeparent: boolean; trusted: boolean=false): integer;
procedure MarkEntryForDeletion(id: integer); //marks for deletion
procedure GetList(var l: TConnectEntryArray);
procedure execute; override;
constructor create(onconnect: TPointerscanConnectEvent=nil);
destructor destroy; override;
property OnConnected: TPointerscanConnectEvent read fOnConnected write fOnConnected;
end;
implementation
resourcestring
rsHost = 'host:';
rsCouldNotBeResolved = ' could not be resolved';
rsFailureCreatingSocket = 'Failure creating socket';
rsInvalidResponseFrom = 'invalid response from ';
rsSomeoneForgotToGiveThisConnector = 'Someone forgot to give this connector an OnConnected event...';
rsErrorWhileConnecting = 'Error while connecting: ';
procedure TPointerscanConnector.GetList(var l: TConnectEntryArray);
{
Passes a copy of the list of entries to the caller
}
var i: integer;
begin
listcs.enter;
try
setlength(l, list.count);
for i:=0 to list.count-1 do
l[i]:=PConnectEntry(list[i])^;
finally
listcs.leave;
end;
end;
procedure TPointerscanConnector.FreeEntry(entry: PConnectEntry);
begin
if (entry.ip<>nil) then
StrDispose(entry.ip);
if entry.password<>nil then
StrDispose(entry.password);
Freemem(entry);
end;
procedure TPointerscanConnector.RemoveDeletedEntries;
var
i: integer;
entry: PConnectentry;
begin
listcs.enter;
try
i:=0;
while i<list.count do
begin
entry:=list[i];
if entry.deleted then
begin
freeEntry(entry);
list.Delete(i);
end
else
inc(i);
end;
finally
listcs.leave;
end;
end;
procedure TPointerscanConnector.MarkEntryForDeletion(id: integer);
var i: integer;
begin
listcs.enter;
try
for i:=0 to list.count-1 do
if PConnectentry(list[i]).id=id then
PConnectentry(list[i]).deleted:=true;
finally
listcs.leave;
end;
end;
function TPointerscanConnector.AddConnection(ip: string; port: word; password: string; becomeparent: boolean; trusted: boolean=false): integer;
var
i: integer;
entry: PConnectentry;
begin
if port=0 then exit; //do not allow port 0
getmem(entry, sizeof(TConnectEntry));
entry.ip:=strnew(pchar(ip));
entry.port:=port;
entry.password:=strnew(pchar(password));
entry.becomeparent:=becomeparent;
entry.trusted:=trusted;
entry.deleted:=false;
entry.id:=nextid;
inc(nextid);
listcs.enter;
try
list.Add(entry);
finally
listcs.leave;
end;
result:=entry.id;
end;
procedure TPointerscanConnector.Log(msg: string);
begin
lastlog:=msg;
if assigned(fOnLog) then
fOnLog(self, msg);
end;
procedure TPointerscanConnector.execute;
var
i: integer;
entry: PConnectentry;
sockaddr: TInetSockAddr;
sockethandle: TSocket;
ss: TSocketStream;
result: byte;
wait: boolean;
begin
SetThreadDebugName(handle,'TPointerscanConnector');
i:=0;
while not terminated do
begin
RemoveDeletedEntries;
sockethandle:=INVALID_SOCKET;
entry:=nil;
try
wait:=false;
listcs.enter;
//check the list
try
if i>=list.count then //start from the beginning
begin
wait:=true; //end of the list, wait a bit to prevent hammering
i:=0;
end;
if i<list.count then
entry:=list[i];
finally
listcs.leave;
end;
if wait then sleep(1000);
if terminated then exit;
if entry<>nil then
begin
//connect to this entry
//first resolve the ip
if entry.deleted then
begin
inc(i);
continue;
end;
sockaddr.sin_addr:=StrToNetAddr(entry.ip);
if sockaddr.sin_addr.s_bytes[4]=0 then
begin
if hr.NameLookup(entry.ip) then
sockaddr.sin_addr:=hr.NetHostAddress
else
raise exception.create(rsHost+entry.ip+rsCouldNotBeResolved);
end;
if sockaddr.sin_addr.s_bytes[4]<>0 then
begin
//connect
sockethandle:=fpsocket(AF_INET, SOCK_STREAM, 0);
if sockethandle=INVALID_SOCKET then
raise exception.create(rsFailureCreatingSocket);
sockaddr.sin_family:=AF_INET;
sockaddr.sin_port:=htons(entry.port);
if fpconnect(sockethandle, @SockAddr, sizeof(SockAddr))=0 then
begin
//connected, do the initial handshake
//build the message
ss:=TSocketStream.Create(sockethandle, false); //don't take ownership of this socket
try
ss.WriteByte(PSCONNECT_INIT);
ss.WriteAnsiString8(entry.password);
ss.WriteByte(ifthen(entry.becomeparent, 0, 1));
//send it
ss.flushWrites;
result:=ss.ReadByte;
finally
ss.free;
end;
if result<>0 then
raise exception.create(rsInvalidResponseFrom+entry.ip)
else
begin
if Assigned(fOnConnected) then
begin
fOnConnected(self, sockethandle, entry.becomeparent, entry);
//remove this from the list
MarkEntryForDeletion(entry.id);
continue;
end
else
raise exception.create(rsSomeoneForgotToGiveThisConnector);
end;
end
else
begin
closeSocket(sockethandle);
sockethandle:=INVALID_SOCKET;
end;
end;
end;
except
on e: exception do
begin
if sockethandle<>INVALID_SOCKET then
closesocket(sockethandle);
OutputDebugString(rsErrorWhileConnecting+e.message);
log(e.message);
sleep(1000);
end;
end;
inc(i);
end;
end;
destructor TPointerscanConnector.destroy;
begin
listcs.free;
list.free;
hr.free;
inherited destroy;
end;
constructor TPointerscanConnector.create(onconnect: TPointerscanConnectEvent=nil);
begin
hr:=THostResolver.Create(nil);
list:=tlist.create;
listcs:=tcriticalsection.Create;
fOnConnected:=onconnect;
inherited create(false);
end;
end.
|
unit Services.Hash;
interface
uses
System.SysUtils, System.StrUtils;
type
TServicesHash = class
strict private
class var _instance : TServicesHash;
private
class function StrToMD5(Value : String) : String;
class function StrToEncode(Value : String) : String;
class function StrToDecode(Value : String) : String;
public
class function getInstance() : TServicesHash;
class function StrToHash(Value : String; const Chave : String) : String;
class function StrRenewHash(Base : String; const Chave : String) : String;
class function StrCompareHash(Base, Value : String; const Chave : String) : Boolean;
class function StrIsHash(Value : String) : Boolean;
end;
implementation
uses
System.Classes
, System.Types
, System.DateUtils
, IdCoderMIME
, IdHashMessageDigest;
{ TServicesHash }
class function TServicesHash.getInstance: TServicesHash;
begin
if not Assigned(_instance) then
_instance := TServicesHash.Create;
Result := _instance;
end;
class function TServicesHash.StrToDecode(Value: String): String;
var
aDecode : TIdDecoderMIME;
begin
aDecode := TIdDecoderMIME.Create;
try
Result := aDecode.DecodeString(Value);
finally
aDecode.DisposeOf;
end;
end;
class function TServicesHash.StrToEncode(Value: String): String;
var
aEncode : TIdEncoderMIME;
begin
aEncode := TIdEncoderMIME.Create;
try
Result := aEncode.EncodeString(Value);
finally
aEncode.DisposeOf;
end;
end;
class function TServicesHash.StrToHash(Value: String; const Chave: String): String;
var
aChave ,
aHash ,
aHora ,
aMarcacao,
aRetorno : String;
aTamanho ,
aPosicao : Integer;
begin
try
aHora := TServicesHash.StrToEncode( ReverseString(FormatDateTime('hh:mm:ss', Time)) ).Replace('=', ''); // Tamanho 11
aChave := TServicesHash.StrToEncode( ReverseString(Chave.Trim.ToLower) );
aTamanho := aChave.Length;
aPosicao := -1;
while (aPosicao < 1) do
aPosicao := Random( aTamanho );
aMarcacao := TServicesHash.StrToEncode( FormatFloat('000', aPosicao) ); // Tamanho 4
aHash := Self.StrToMD5( ReverseString(Value + Chave) ).ToLower; // Tamanho 32
if ((aPosicao mod 2) = 0) then
aHash := ReverseString( aHash );
aRetorno := aHora
+ Copy(aChave, 1, aPosicao)
+ aHash
+ Copy(aChave, aPosicao + 1, aTamanho)
+ ReverseString( aMarcacao );
finally
Result := aRetorno;
end;
end;
class function TServicesHash.StrRenewHash(Base: String; const Chave: String): String;
var
aBase ,
aChave ,
aHash ,
aHora ,
aMarcacao,
aRetorno : String;
aTamanho ,
aPosicao : Integer;
begin
try
// Remover hora
aBase := Copy(Base, 12, Base.Length);
// Capiturar posição inicial do hash
aMarcacao := ReverseString( Copy(aBase, aBase.Length - 3, 4) ); // Tamanho 4
aPosicao := TServicesHash.StrToDecode(aMarcacao).ToInteger();
aHash := Copy(aBase, aPosicao + 1, 32); // Tamanho 32
// Remover hash e marcador da posição da base
aBase := aBase.Replace(aHash, EmptyStr);
aBase := Copy(aBase, 1, aBase.Length - 4);
aHora := TServicesHash.StrToEncode( ReverseString(FormatDateTime('hh:mm:ss', Time)) ).Replace('=', ''); // Tamanho 11
aTamanho := aBase.Length;
aPosicao := -1;
while (aPosicao < 1) do
aPosicao := Random( aTamanho );
aMarcacao := TServicesHash.StrToEncode( FormatFloat('000', aPosicao) ); // Tamanho 4
aRetorno := aHora
+ Copy(aBase, 1, aPosicao)
+ ReverseString( aHash )
+ Copy(aBase, aPosicao + 1, aTamanho)
+ ReverseString( aMarcacao );
finally
Result := aRetorno;
end;
end;
class function TServicesHash.StrCompareHash(Base, Value: String; const Chave: String): Boolean;
var
aChave ,
aMarcacao,
aHash0 ,
aHash1 : String;
aRetorno : Boolean;
begin
try
aMarcacao := ReverseString( Copy(Base, Base.Length - 3, 4) ); // Tamanho 4
aHash0 := Self.StrToMD5( ReverseString(Value + Chave) ).ToLower; // Tamanho 32
aHash1 := ReverseString( aHash0 );
aRetorno := (Pos(aHash0, Base) > 0) or (Pos(aHash1, Base) > 0);
finally
Result := aRetorno;
end;
end;
class function TServicesHash.StrIsHash(Value: String): Boolean;
var
aMarcacao : String;
aPosicao : Integer;
begin
try
aMarcacao := ReverseString( Copy(Value, Value.Length - 3, 4) ); // Tamanho 4
Result := TryStrToInt(TServicesHash.StrToDecode(aMarcacao), aPosicao);
except
Result := False;
end;
end;
class function TServicesHash.StrToMD5(Value: String): String;
var
aMD5 : TIdHashMessageDigest5;
begin
aMD5 := TIdHashMessageDigest5.Create;
try
Result := aMD5.HashStringAsHex(Value);
finally
aMD5.DisposeOf;
end;
end;
end.
|
unit Vector3bFunctionalTest;
{$mode objfpc}{$H+}
{$CODEALIGN LOCALMIN=16}
interface
uses
Classes, SysUtils, fpcunit, testregistry, BaseTestCase,
BZVectorMath;
type
{ TVector3bFunctionalTest }
TVector3bFunctionalTest = class(TByteVectorBaseTestCase)
published
procedure TestCreate3Byte;
procedure TestOpAdd;
procedure TestOpAddByte;
procedure TestOpSub;
procedure TestOpSubByte;
procedure TestOpMul;
procedure TestOpMulByte;
procedure TestOpMulSingle;
procedure TestOpDiv;
procedure TestOpDivByte;
procedure TestOpEquality;
procedure TestOpNotEquals;
procedure TestOpAnd;
procedure TestOpAndByte;
procedure TestOpOr;
procedure TestOpOrByte;
procedure TestOpXor;
procedure TestOpXorByte;
procedure TestSwizzle;
end;
implementation
{ TVector3bFunctionalTest }
procedure TVector3bFunctionalTest.TestCreate3Byte;
begin
abt1.Create(1,2,3);
AssertEquals('Create:Sub1 X failed ', 1, abt1.X);
AssertEquals('Create:Sub2 Red failed ', 1, abt1.Red);
AssertEquals('Create:Sub3 Y failed ', 2, abt1.Y);
AssertEquals('Create:Sub4 Green failed ', 2, abt1.Green);
AssertEquals('Create:Sub5 Z failed ', 3, abt1.Z);
AssertEquals('Create:Sub6 Blue failed ', 3, abt1.Blue);
end;
procedure TVector3bFunctionalTest.TestOpAdd;
begin
abt1.Create(1,2,3);
abt2.Create(1,2,3);
abt3 := abt1 + abt2;
AssertEquals('OpAdd:Sub1 X failed ', 2, abt3.X);
AssertEquals('OpAdd:Sub2 Y failed ', 4, abt3.Y);
AssertEquals('OpAdd:Sub3 Z failed ', 6, abt3.Z);
abt3 := abt2 + abt1;
AssertEquals('OpAdd:Sub4 X failed ', 2, abt3.X);
AssertEquals('OpAdd:Sub5 Y failed ', 4, abt3.Y);
AssertEquals('OpAdd:Sub6 Z failed ', 6, abt3.Z);
abt1.Create(200,200,200);
abt2.Create(100,60,80);
abt3 := abt2 + abt1;
AssertEquals('OpAdd:Sub7 X failed ', 255, abt3.X);
AssertEquals('OpAdd:Sub8 Y failed ', 255, abt3.Y);
AssertEquals('OpAdd:Sub9 Z failed ', 255, abt3.Z);
end;
procedure TVector3bFunctionalTest.TestOpAddByte;
begin
abt1.Create(100,60,80);
abt3 := abt1 + 20;
AssertEquals('OpAddByte:Sub1 X failed ', 120, abt3.X);
AssertEquals('OpAddByte:Sub2 Y failed ', 80, abt3.Y);
AssertEquals('OpAddByte:Sub3 Z failed ', 100, abt3.Z);
abt3 := abt1 + 200;
AssertEquals('OpAddByte:Sub4 X failed ', 255, abt3.X);
AssertEquals('OpAddByte:Sub5 Y failed ', 255, abt3.Y);
AssertEquals('OpAddByte:Sub6 Z failed ', 255, abt3.Z);
end;
procedure TVector3bFunctionalTest.TestOpSub;
begin
abt1.Create(1,2,3);
abt2.Create(4,5,6);
abt3 := abt1 - abt2;
AssertEquals('OpSub:Sub1 X failed ', 0, abt3.X);
AssertEquals('OpSub:Sub2 Y failed ', 0, abt3.Y);
AssertEquals('OpSub:Sub3 Z failed ', 0, abt3.Z);
abt3 := abt2 - abt1;
AssertEquals('OpSub:Sub1 X failed ', 3, abt3.X);
AssertEquals('OpSub:Sub2 Y failed ', 3, abt3.Y);
AssertEquals('OpSub:Sub3 Z failed ', 3, abt3.Z);
end;
procedure TVector3bFunctionalTest.TestOpSubByte;
begin
abt1.Create(100,60,80);
abt3 := abt1 - 20;
AssertEquals('OpSubByte:Sub1 X failed ', 80, abt3.X);
AssertEquals('OpSubByte:Sub2 Y failed ', 40, abt3.Y);
AssertEquals('OpSubByte:Sub3 Z failed ', 60, abt3.Z);
abt3 := abt1 - 200;
AssertEquals('OpAddByte:Sub4 X failed ', 0, abt3.X);
AssertEquals('OpAddByte:Sub5 Y failed ', 0, abt3.Y);
AssertEquals('OpAddByte:Sub6 Z failed ', 0, abt3.Z);
end;
procedure TVector3bFunctionalTest.TestOpMul;
begin
abt1.Create(100,60,80);
abt2.Create(1,2,3);
abt3 := abt1 * abt2;
AssertEquals('OpMul:Sub1 X failed ', 100, abt3.X);
AssertEquals('OpMul:Sub2 Y failed ', 120, abt3.Y);
AssertEquals('OpMul:Sub3 Z failed ', 240, abt3.Z);
abt2.Create(3,5,4);
abt3 := abt1 * abt2;
AssertEquals('OpMul:Sub4 X failed ', 255, abt3.X);
AssertEquals('OpMul:Sub5 Y failed ', 255, abt3.Y);
AssertEquals('OpMul:Sub6 Z failed ', 255, abt3.Z);
abt2.Create(3,2,4);
abt3 := abt1 * abt2;
AssertEquals('OpMul:Sub7 X failed ', 255, abt3.X);
AssertEquals('OpMul:Sub8 Y failed ', 120, abt3.Y);
AssertEquals('OpMul:Sub9 Z failed ', 255, abt3.Z);
end;
// with these overloads using a const number makes compiler barf as
// it cannot work out if 2 is Single or byte so we have to use a typed var.
procedure TVector3bFunctionalTest.TestOpMulByte;
var
a: byte;
begin
abt1.Create(100,60,80);
a := 2;
abt3 := abt1 * a;
AssertEquals('OpMulByte:Sub1 X failed ', 200, abt3.X);
AssertEquals('OpMulByte:Sub2 Y failed ', 120, abt3.Y);
AssertEquals('OpMulByte:Sub3 Z failed ', 160, abt3.Z);
a := 3;
abt3 := abt1 * a;
AssertEquals('OpMulByte:Sub3 X failed ', 255, abt3.X);
AssertEquals('OpMulByte:Sub4 Y failed ', 180, abt3.Y);
AssertEquals('OpMulByte:Sub5 Z failed ', 240, abt3.Z);
a := 4;
abt3 := abt1 * a;
AssertEquals('OpMulByte:Sub6 X failed ', 255, abt3.X);
AssertEquals('OpMulByte:Sub7 Y failed ', 240, abt3.Y);
AssertEquals('OpMulByte:Sub8 Z failed ', 255, abt3.Z);
end;
procedure TVector3bFunctionalTest.TestOpMulSingle;
begin
abt1.Create(100,60,80);
abt3 := abt1 * 2.0;
AssertEquals('OpMulSingle:Sub1 X failed ', 200, abt3.X);
AssertEquals('OpMulSingle:Sub2 Y failed ', 120, abt3.Y);
AssertEquals('OpMulSingle:Sub3 Z failed ', 160, abt3.Z);
abt3 := abt1 * 3.0;
AssertEquals('OpMulSingle:Sub3 X failed ', 255, abt3.X);
AssertEquals('OpMulSingle:Sub4 Y failed ', 180, abt3.Y);
AssertEquals('OpMulSingle:Sub5 Z failed ', 240, abt3.Z);
abt3 := abt1 * 4.0;
AssertEquals('OpMulSingle:Sub6 X failed ', 255, abt3.X);
AssertEquals('OpMulSingle:Sub7 Y failed ', 240, abt3.Y);
AssertEquals('OpMulSingle:Sub8 Z failed ', 255, abt3.Z);
end;
// div truncs
procedure TVector3bFunctionalTest.TestOpDiv;
begin
abt1.Create(120,60,180);
abt2.Create(1,2,3);
abt3 := abt1 Div abt2;
AssertEquals('OpDiv:Sub1 X failed ', 120, abt3.X);
AssertEquals('OpDiv:Sub2 Y failed ', 30, abt3.Y);
AssertEquals('OpDiv:Sub3 Z failed ', 60, abt3.Z);
abt2.Create(4,5,6);
abt3 := abt1 Div abt2;
AssertEquals('OpDiv:Sub4 X failed ', 30, abt3.X);
AssertEquals('OpDiv:Sub5 Y failed ', 12, abt3.Y);
AssertEquals('OpDiv:Sub6 Z failed ', 30, abt3.Z);
abt2.Create(11,9,17); // these are all above 0.5
abt3 := abt1 Div abt2; // 10.909, 6.6666., 10.588235
AssertEquals('OpDiv:Sub7 X failed ', 10, abt3.X);
AssertEquals('OpDiv:Sub8 Y failed ', 6, abt3.Y);
AssertEquals('OpDiv:Sub9 Z failed ', 10, abt3.Z);
end;
procedure TVector3bFunctionalTest.TestOpDivByte;
begin
abt1.Create(120,60,180);
abt3 := abt1 Div 4;
AssertEquals('OpDivByte:Sub1 X failed ', 30, abt3.X);
AssertEquals('OpDivByte:Sub2 Y failed ', 15, abt3.Y);
AssertEquals('OpDivByte:Sub3 Z failed ', 45, abt3.Z);
abt3 := abt1 Div 7;
AssertEquals('OpDivByte:Sub4 X failed ', 17, abt3.X);
AssertEquals('OpDivByte:Sub5 Y failed ', 8, abt3.Y);
AssertEquals('OpDivByte:Sub6 Z failed ', 25, abt3.Z);
end;
procedure TVector3bFunctionalTest.TestOpEquality;
begin
abt1.Create(120,60,180);
abt2.Create(120,60,180);
nb := abt1 = abt2;
AssertEquals('OpEquality:Sub1 does not match ', True, nb);
abt2.Create(120,60,181);
nb := abt1 = abt2;
AssertEquals('OpEquality:Sub2 should not match ', False, nb);
abt2.Create(120,61,180);
nb := abt1 = abt2;
AssertEquals('OpEquality:Sub3 should not match ', False, nb);
abt2.Create(119,60,180);
nb := abt1 = abt2;
AssertEquals('OpEquality:Sub4 should not match ', False, nb);
end;
procedure TVector3bFunctionalTest.TestOpNotEquals;
begin
abt1.Create(120,60,180);
abt2.Create(120,60,180);
nb := abt1 <> abt2;
AssertEquals('OpNotEquals:Sub1 should not match ', False, nb);
abt2.Create(120,60,181);
nb := abt1 <> abt2;
AssertEquals('OpNotEquals:Sub2 does not match ', True, nb);
abt2.Create(120,61,180);
nb := abt1 <> abt2;
AssertEquals('OpNotEquals:Sub3 does not match ', True, nb);
abt2.Create(119,60,180);
nb := abt1 <> abt2;
AssertEquals('OpNotEquals:Sub4 does not match ', True, nb);
end;
procedure TVector3bFunctionalTest.TestOpAnd;
begin
b1 := 170; //10101010
b2 := 85; //01010101
b3 := 255; //11111111
b4 := 0; //00000000;
abt1.Create(b1,b2,b3);
abt2.Create(b2,b2,b2);
abt3 := abt1 and abt2;
AssertEquals('OpAnd:Sub1 X failed ', b4, abt3.X);
AssertEquals('OpAnd:Sub2 Y failed ', b2, abt3.Y);
AssertEquals('OpAnd:Sub3 Z failed ', b2, abt3.Z);
abt2.Create(b1,b1,b1);
abt3 := abt1 and abt2;
AssertEquals('OpAnd:Sub4 X failed ', b1, abt3.X);
AssertEquals('OpAnd:Sub5 Y failed ', b4, abt3.Y);
AssertEquals('OpAnd:Sub6 Z failed ', b1, abt3.Z);
abt2.Create(b3,b3,b3);
abt3 := abt1 and abt2;
AssertEquals('OpAnd:Sub7 X failed ', b1, abt3.X);
AssertEquals('OpAnd:Sub8 Y failed ', b2, abt3.Y);
AssertEquals('OpAnd:Sub9 Z failed ', b3, abt3.Z);
end;
procedure TVector3bFunctionalTest.TestOpAndByte;
begin
b1 := 170; //10101010
b2 := 85; //01010101
b3 := 255; //11111111
b4 := 0; //00000000;
abt1.Create(b1,b2,b3);
abt3 := abt1 and b2;
AssertEquals('OpAnd:Sub1 X failed ', b4, abt3.X);
AssertEquals('OpAnd:Sub2 Y failed ', b2, abt3.Y);
AssertEquals('OpAnd:Sub3 Z failed ', b2, abt3.Z);
abt3 := abt1 and b1;
AssertEquals('OpAnd:Sub4 X failed ', b1, abt3.X);
AssertEquals('OpAnd:Sub5 Y failed ', b4, abt3.Y);
AssertEquals('OpAnd:Sub6 Z failed ', b1, abt3.Z);
abt3 := abt1 and b3;
AssertEquals('OpAnd:Sub7 X failed ', b1, abt3.X);
AssertEquals('OpAnd:Sub8 Y failed ', b2, abt3.Y);
AssertEquals('OpAnd:Sub9 Z failed ', b3, abt3.Z);
end;
procedure TVector3bFunctionalTest.TestOpOr;
begin
b1 := 170; //10101010
b2 := 85; //01010101
b3 := 255; //11111111
b4 := 0; //00000000;
abt1.Create(b1,b2,b4);
abt2.Create(b2,b2,b2);
abt3 := abt1 or abt2;
AssertEquals('OpAnd:Sub1 X failed ', b3, abt3.X);
AssertEquals('OpAnd:Sub2 Y failed ', b2, abt3.Y);
AssertEquals('OpAnd:Sub3 Z failed ', b2, abt3.Z);
abt2.Create(b1,b1,b1);
abt3 := abt1 or abt2;
AssertEquals('OpAnd:Sub4 X failed ', b1, abt3.X);
AssertEquals('OpAnd:Sub5 Y failed ', b3, abt3.Y);
AssertEquals('OpAnd:Sub6 Z failed ', b1, abt3.Z);
abt2.Create(b4,b4,b4);
abt3 := abt1 or abt2;
AssertEquals('OpAnd:Sub7 X failed ', b1, abt3.X);
AssertEquals('OpAnd:Sub8 Y failed ', b2, abt3.Y);
AssertEquals('OpAnd:Sub9 Z failed ', b4, abt3.Z);
end;
procedure TVector3bFunctionalTest.TestOpOrByte;
begin
b1 := 170; //10101010
b2 := 85; //01010101
b3 := 255; //11111111
b4 := 0; //00000000;
abt1.Create(b1,b2,b4);
abt3 := abt1 or b2;
AssertEquals('OpAnd:Sub1 X failed ', b3, abt3.X);
AssertEquals('OpAnd:Sub2 Y failed ', b2, abt3.Y);
AssertEquals('OpAnd:Sub3 Z failed ', b2, abt3.Z);
abt3 := abt1 or b1;
AssertEquals('OpAnd:Sub4 X failed ', b1, abt3.X);
AssertEquals('OpAnd:Sub5 Y failed ', b3, abt3.Y);
AssertEquals('OpAnd:Sub6 Z failed ', b1, abt3.Z);
abt3 := abt1 or b4;
AssertEquals('OpAnd:Sub7 X failed ', b1, abt3.X);
AssertEquals('OpAnd:Sub8 Y failed ', b2, abt3.Y);
AssertEquals('OpAnd:Sub9 Z failed ', b4, abt3.Z);
end;
procedure TVector3bFunctionalTest.TestOpXor;
begin
b1 := 170; //10101010
b2 := 85; //01010101
b3 := 255; //11111111
b4 := 0; //00000000;
abt1.Create(b1,b2,b4);
abt2.Create(b2,b2,b2);
abt3 := abt1 xor abt2;
AssertEquals('OpAnd:Sub1 X failed ', b3, abt3.X);
AssertEquals('OpAnd:Sub2 Y failed ', b4, abt3.Y);
AssertEquals('OpAnd:Sub3 Z failed ', b2, abt3.Z);
abt2.Create(b1,b1,b1);
abt3 := abt1 xor abt2;
AssertEquals('OpAnd:Sub4 X failed ', b4, abt3.X);
AssertEquals('OpAnd:Sub5 Y failed ', b3, abt3.Y);
AssertEquals('OpAnd:Sub6 Z failed ', b1, abt3.Z);
abt2.Create(b3,b3,b3);
abt3 := abt1 xor abt2;
AssertEquals('OpAnd:Sub7 X failed ', b2, abt3.X);
AssertEquals('OpAnd:Sub8 Y failed ', b1, abt3.Y);
AssertEquals('OpAnd:Sub9 Z failed ', b3, abt3.Z);
end;
procedure TVector3bFunctionalTest.TestOpXorByte;
begin
b1 := 170; //10101010
b2 := 85; //01010101
b3 := 255; //11111111
b4 := 0; //00000000;
abt1.Create(b1,b2,b4);
abt3 := abt1 xor b2;
AssertEquals('OpAnd:Sub1 X failed ', b3, abt3.X);
AssertEquals('OpAnd:Sub2 Y failed ', b4, abt3.Y);
AssertEquals('OpAnd:Sub3 Z failed ', b2, abt3.Z);
abt3 := abt1 xor b1;
AssertEquals('OpAnd:Sub4 X failed ', b4, abt3.X);
AssertEquals('OpAnd:Sub5 Y failed ', b3, abt3.Y);
AssertEquals('OpAnd:Sub6 Z failed ', b1, abt3.Z);
abt3 := abt1 xor b3;
AssertEquals('OpAnd:Sub7 X failed ', b2, abt3.X);
AssertEquals('OpAnd:Sub8 Y failed ', b1, abt3.Y);
AssertEquals('OpAnd:Sub9 Z failed ', b3, abt3.Z);
end;
//swXXX, swYYY, swZZZ, swXYZ, swXZY, swZYX, swZXY, swYXZ, swYZX,
//swRRR, swGGG, swBBB, swRGB, swRBG, swBGR, swBRG, swGRB, swGBR
procedure TVector3bFunctionalTest.TestSwizzle;
Var R, G, B: byte;
begin
R := 170; //10101010
G := 85; //01010101
B := 255; //11111111
abt1.Create(R,G,B);
abt3 := abt1.Swizzle(swRRR);
AssertEquals('Swizzle:Sub1 X failed ', R, abt3.X);
AssertEquals('Swizzle:Sub2 Y failed ', R, abt3.Y);
AssertEquals('Swizzle:Sub3 Z failed ', R, abt3.Z);
abt1.Create(R,G,B);
abt3 := abt1.Swizzle(swGGG);
AssertEquals('Swizzle:Sub4 X failed ', G, abt3.X);
AssertEquals('Swizzle:Sub5 Y failed ', G, abt3.Y);
AssertEquals('Swizzle:Sub6 Z failed ', G, abt3.Z);
abt1.Create(R,G,B);
abt3 := abt1.Swizzle(swBBB);
AssertEquals('Swizzle:Sub7 X failed ', B, abt3.X);
AssertEquals('Swizzle:Sub8 Y failed ', B, abt3.Y);
AssertEquals('Swizzle:Sub9 Z failed ', B, abt3.Z);
abt1.Create(R,G,B);
abt3 := abt1.Swizzle(swRGB);
AssertEquals('Swizzle:Sub10 X failed ', R, abt3.X);
AssertEquals('Swizzle:Sub11 Y failed ', G, abt3.Y);
AssertEquals('Swizzle:Sub12 Z failed ', B, abt3.Z);
abt1.Create(R,G,B);
abt3 := abt1.Swizzle(swRBG);
AssertEquals('Swizzle:Sub13 X failed ', R, abt3.X);
AssertEquals('Swizzle:Sub14 Y failed ', B, abt3.Y);
AssertEquals('Swizzle:Sub15 Z failed ', G, abt3.Z);
abt1.Create(R,G,B);
abt3 := abt1.Swizzle(swBGR);
AssertEquals('Swizzle:Sub16 X failed ', B, abt3.X);
AssertEquals('Swizzle:Sub17 Y failed ', G, abt3.Y);
AssertEquals('Swizzle:Sub18 Z failed ', R, abt3.Z);
abt1.Create(R,G,B);
abt3 := abt1.Swizzle(swBRG);
AssertEquals('Swizzle:Sub19 X failed ', B, abt3.X);
AssertEquals('Swizzle:Sub20 Y failed ', R, abt3.Y);
AssertEquals('Swizzle:Sub21 Z failed ', G, abt3.Z);
abt1.Create(R,G,B);
abt3 := abt1.Swizzle(swGRB);
AssertEquals('Swizzle:Sub22 X failed ', G, abt3.X);
AssertEquals('Swizzle:Sub23 Y failed ', R, abt3.Y);
AssertEquals('Swizzle:Sub24 Z failed ', B, abt3.Z);
abt1.Create(R,G,B);
abt3 := abt1.Swizzle(swGBR);
AssertEquals('Swizzle:Sub25 X failed ', G, abt3.X);
AssertEquals('Swizzle:Sub26 Y failed ', B, abt3.Y);
AssertEquals('Swizzle:Sub27 Z failed ', R, abt3.Z);
end;
initialization
RegisterTest(REPORT_GROUP_VECTOR3B, TVector3bFunctionalTest);
end.
|
unit AsyncIO.Test.AsyncReadUntil;
interface
procedure RunAsyncReadUntilDelimTest;
implementation
uses
System.SysUtils, System.Classes,
AsyncIO, AsyncIO.ErrorCodes, AsyncIO.Filesystem;
type
FileReader = class
private
FInputStream: AsyncFileStream;
FOutputStream: TStringStream;
FBuffer: StreamBuffer;
procedure HandleRead(const ErrorCode: IOErrorCode; const BytesTransferred: UInt64);
public
constructor Create(const Service: IOService; const Filename: string);
end;
procedure RunAsyncReadUntilDelimTest;
var
inputFilename: string;
ios: IOService;
reader: FileReader;
r: Int64;
begin
ios := nil;
reader := nil;
try
ios := NewIOService();
inputFilename := ParamStr(1);
if (inputFilename = '') then
raise Exception.Create('Missing command line parameter');
reader := FileReader.Create(ios, inputFilename);
r := ios.Run;
WriteLn(Format('%d handlers executed', [r]));
finally
reader.Free;
end;
end;
{ FileReader }
constructor FileReader.Create(const Service: IOService; const Filename: string);
begin
inherited Create;
FInputStream := NewAsyncFileStream(Service, Filename, fcOpenExisting, faRead, fsNone);
FOutputStream := TStringStream.Create('', TEncoding.ASCII, False);
FBuffer := StreamBuffer.Create();
AsyncReadUntil(FInputStream, FBuffer, [13, 10], HandleRead);
end;
procedure FileReader.HandleRead(const ErrorCode: IOErrorCode; const BytesTransferred: UInt64);
begin
// if (ErrorCode) then
// begin
// if (ErrorCode = IOErrorCode.EndOfFile) then
// begin
// WriteLn(Format('Finished reading %d bytes from file', [FBytesRead]));
// exit;
// end;
//
// WriteLn('Error: ' + ErrorCode.Message);
// exit;
// end;
if (ErrorCode <> IOErrorCode.EndOfFile) then
begin
WriteLn('Error: ' + ErrorCode.Message);
FInputStream.Service.Stop;
exit;
end;
WriteLn(Format('Read %d bytes from file', [BytesTransferred]));
FInputStream.Service.Stop;
end;
end.
|
unit uTParovatko;
interface
uses
SysUtils, Variants, Classes, Controls, StrUtils,
Windows, Messages, Dialogs, Forms,
ZAbstractRODataset, ZAbstractDataset, ZDataset, ZAbstractConnection, ZConnection,
uTVypis, uTPlatbaZVypisu, AbraEntities;
type
TPlatbaDokladPar = class
public
Platba : TPlatbaZVypisu;
Doklad : TDoklad;
Doklad_ID : string[10];
CastkaPouzita : currency;
Popis : string;
vazbaNaDoklad : boolean;
pdparTyp : string; // speciální typy - "VoipKredit" nebo "InternetKredit"
end;
TParovatko = class
public
Vypis: TVypis;
qrAbra: TZQuery;
AbraOLE: variant;
listPlatbaDokladPar : TList; // list všech párů platba-doklad (objekty z TPlatbaDokladPar)
constructor create(Vypis: TVypis);
published
procedure sparujPlatbu(Platba : TPlatbaZVypisu);
procedure odparujPlatbu(currPlatba : TPlatbaZVypisu);
procedure vytvorPDPar(Platba : TPlatbaZVypisu; Doklad : TDoklad;
Castka: currency; popis : string; vazbaNaDoklad : boolean; pdparTyp : string = '');
function zapisDoAbry() : string;
function getUzSparovano(Doklad_ID : string) : currency;
function getPDParyAsText() : string;
function getPDParyPlatbyAsText(currPlatba : TPlatbaZVypisu) : string;
function getPDPar(currPlatba : TPlatbaZVypisu; currDoklad_ID: string) : TPlatbaDokladPar;
function getFirmIdKdyzNeniDoklad(currPlatba : TPlatbaZVypisu) : string;
end;
implementation
uses
DesUtils, AArray, Superobject;
constructor TParovatko.create(Vypis: TVypis);
begin
self.Vypis := Vypis;
self.qrAbra := DesU.qrAbra;
self.listPlatbaDokladPar := TList.Create();
end;
procedure TParovatko.sparujPlatbu(Platba : TPlatbaZVypisu);
procedure zpracujPreplatek(Platba : TPlatbaZVypisu; Doklad : TDoklad; Castka: currency);
var
vsPatriKreditniVoipSmlouve, vsPatriKreditniSmlouve : boolean;
begin
vsPatriKreditniVoipSmlouve := false;
vsPatriKreditniSmlouve := false;
Platba.potrebaPotvrzeniUzivatelem := false;
if ((copy(Platba.VS, 5, 1) = '9') AND (copy(Platba.VS, 1, 2) = '20')) OR (Platba.SS = '8888') then
{ kreditní smlouva má na 5. místě číslici 9, tedy VS je 20xx9xxxxx; nebo má SS 8888
pokud je VS ve VoIP formátu nebo je SS 8888 tak se podívám jestli je v dbZakos contract oznacen jako VoipContract
nedívám se tedy pro všechny záznamy kvůli šetření času a možným chybám v dbZakos }
vsPatriKreditniVoipSmlouve := DesU.isVoipKreditContract(Platba.VS);
if not vsPatriKreditniVoipSmlouve then
vsPatriKreditniSmlouve := DesU.isCreditContract(Platba.VS);
if vsPatriKreditniVoipSmlouve OR vsPatriKreditniSmlouve then
Platba.potrebaPotvrzeniUzivatelem := true; // v 8. sloupci StringGridu s platbami se nakonec objeví checkbox
if Platba.potrebaPotvrzeniUzivatelem AND Platba.jePotvrzenoUzivatelem then
begin
if vsPatriKreditniVoipSmlouve then
begin
vytvorPDPar(Platba, nil, Castka, 'kredit VoIP |', false, 'VoipKredit');
Platba.zprava := 'VoIP kredit ' + FloatToStr(Castka) + ' Kč';
Platba.problemLevel := 3;
end
else if vsPatriKreditniSmlouve then
begin
vytvorPDPar(Platba, nil, Castka, 'kredit Internet |' , false, 'InternetKredit');
Platba.zprava := 'Internet kredit ' + FloatToStr(Castka) + ' Kč';
Platba.problemLevel := 3;
end;
end
else
begin
//if Platba.getProcentoPredchozichPlatebZeStejnehoUctu() > 0.5 then begin //změna z nadpoloviční většiny na více jak 3 platby
if Platba.getPocetPredchozichPlatebZeStejnehoUctu() >= 3 then begin
vytvorPDPar(Platba, Doklad, Castka, 'přepl. | ' + Platba.VS + ' |' , false);
Platba.zprava := 'přepl. ' + FloatToStr(Castka) + ' Kč';
Platba.problemLevel := 1;
end else begin
vytvorPDPar(Platba, Doklad, Castka, 'přepl. | ' + Platba.VS + ' |', false);
Platba.zprava := 'neznámý přepl. ' + FloatToStr(Castka) + ' Kč';
Platba.problemLevel := 5;
end;
end;
end;
var
i : integer;
nezaplaceneDoklady : TList;
iDoklad : TDoklad;
zbyvaCastka,
kNaparovani : currency;
begin
iDoklad := nil;
Platba.rozdeleniPlatby := 0;
Platba.castecnaUhrada := 0;
self.odparujPlatbu(Platba); // vždy smažeme všechny položky listPlatbaDokladPar, kde figuruje vstupní Platba (a začneme pak párovat nanovo)
if Platba.DokladyList.Count > 0 then
iDoklad := TDoklad(Platba.DokladyList[0]); //pokud je alespon 1 doklad, priradime si ho pro debety a kredity bez nezaplacenych dokladu
if Platba.debet then
begin //platba je debet (mínusová)
Platba.zprava := 'debet';
Platba.problemLevel := 0;
vytvorPDPar(Platba, iDoklad, Platba.Castka, '', false);
end // end platba je debet
else
begin //platba je kredit (plusová)
// vyrobím si list jen nezaplacených dokladů
nezaplaceneDoklady := TList.Create;
for i := 0 to Platba.DokladyList.Count - 1 do
if TDoklad(Platba.DokladyList[i]).CastkaNezaplaceno <> 0 then
nezaplaceneDoklady.Add(Platba.DokladyList[i]);
// pokud není žádný nezaplacený
if (nezaplaceneDoklady.Count = 0) then
begin
if Platba.znamyPripad then
begin
vytvorPDPar(Platba, iDoklad, Platba.Castka, '', false);
Platba.zprava := 'známý kredit';
Platba.problemLevel := 0;
end else begin
zpracujPreplatek(Platba, iDoklad, Platba.Castka);
end;
Exit;
end;
zbyvaCastka := Platba.Castka;
for i := nezaplaceneDoklady.Count - 1 downto 0 do
// begin existují nezaplacené doklady
begin
iDoklad := TDoklad(nezaplaceneDoklady[i]);
kNaparovani := iDoklad.CastkaNezaplaceno - getUzSparovano(iDoklad.ID); // getUzSparovano se podívá na všechny pdPáry a zjistí, zda už je iDoklad hrazzený a jakou částkou
if (kNaparovani <> 0) then
begin
if (kNaparovani = zbyvaCastka) then
begin
vytvorPDPar(Platba, iDoklad, zbyvaCastka, '', true); //přesně
Platba.zprava := 'přesně';
if Platba.rozdeleniPlatby > 0 then
Platba.problemLevel := 0 //bylo 1
else
Platba.problemLevel := 0;
zbyvaCastka := 0;
Break;
end;
if (kNaparovani > zbyvaCastka) AND not(iDoklad.DocumentType = '10') then //částečná úhrada, doklad nesmí být zálohovým listem
begin
vytvorPDPar(Platba, iDoklad, zbyvaCastka, 'část. ' + floattostr(zbyvaCastka) + ' z ' + floattostr(kNaparovani) + ' Kč |', true);
Platba.zprava := 'částečná úhrada';
Platba.castecnaUhrada := 1;
Platba.problemLevel := 1;
zbyvaCastka := 0;
Break;
end;
if (kNaparovani < zbyvaCastka) then
begin
//vytvorPDPar(Platba, iDoklad, kNaparovani, 'přiřazeno ' + floattostr(kNaparovani), true); // dělení
vytvorPDPar(Platba, iDoklad, kNaparovani, '', true); // dělení
zbyvaCastka := zbyvaCastka - kNaparovani;
Inc(Platba.rozdeleniPlatby);
end;
end;
end;
// end existují nezaplacené doklady
if (zbyvaCastka > 0) then
begin
zpracujPreplatek(Platba, iDoklad, zbyvaCastka);
end;
if (Platba.getPocetPredchozichPlatebZeStejnehoUctu() = 0)
AND (Platba.PredchoziPlatbyVsList.Count > 3) then
begin
Platba.zprava := 'neznámý účet - ' + Platba.zprava;
Platba.problemLevel := 2;
end;
end;
// end platba je kredit
end;
procedure TParovatko.odparujPlatbu(currPlatba : TPlatbaZVypisu);
// smažu všechny položky listPlatbaDokladPar, kde Platba je vtupní currPlatba
var
i : integer;
iPDPar : TPlatbaDokladPar;
begin
for i := listPlatbaDokladPar.Count - 1 downto 0 do
begin
iPDPar := TPlatbaDokladPar(listPlatbaDokladPar[i]);
if iPDPar.Platba = currPlatba then
listPlatbaDokladPar.Delete(i);
end;
end;
procedure TParovatko.vytvorPDPar(Platba : TPlatbaZVypisu; Doklad : TDoklad;
Castka: currency; popis : string; vazbaNaDoklad : boolean; pdparTyp : string = '');
var
iPDPar : TPlatbaDokladPar;
begin
iPDPar := TPlatbaDokladPar.Create();
// správně by bylo vytvořit pořádný konstruktor a nepřiřazovat hodnoty do iPDPar v této proceduře
iPDPar.Platba := Platba;
iPDPar.Doklad := Doklad;
if assigned(iPDPar.Doklad) then
iPDPar.Doklad_ID := iPDPar.Doklad.ID
else
iPDPar.Doklad_ID := '';
iPDPar.CastkaPouzita := Castka;
iPDPar.Popis := Popis;
iPDPar.vazbaNaDoklad := vazbaNaDoklad;
iPDPar.pdparTyp := pdparTyp;
self.listPlatbaDokladPar.Add(iPDPar);
end;
function TParovatko.zapisDoAbry() : string;
var
i, j : integer;
iPDPar : TPlatbaDokladPar;
boAA, boRowAA: TAArray;
newID, faId : string;
begin
if (listPlatbaDokladPar.Count = 0) then Exit;
Result := 'Zápis pomocí AArray metoda ' + DesU.abraDefaultCommMethod + ' výpisu pro účet ' + self.Vypis.abraBankaccount.name + '.';
boAA := TAArray.Create;
boAA['DocQueue_ID'] := self.Vypis.abraBankaccount.bankStatementDocqueueId;
boAA['Period_ID'] := DesU.getAbraPeriodId(self.Vypis.Datum);
boAA['BankAccount_ID'] := self.Vypis.abraBankaccount.id;
boAA['ExternalNumber'] := self.Vypis.PoradoveCislo;
boAA['DocDate$DATE'] := self.Vypis.Datum;
//boAA['CreatedAt$DATE'] := IntToStr(Trunc(Date));
for i := 0 to listPlatbaDokladPar.Count - 1 do
begin
iPDPar := TPlatbaDokladPar(listPlatbaDokladPar[i]);
boRowAA := boAA.addRow();
boRowAA['Amount'] := iPDPar.CastkaPouzita;
//boRowAA['Credit'] := IfThen(iPDPar.Platba.Kredit,'1','0'); //pro WebApi nefungovalo dobře
boRowAA['Credit'] := iPDPar.Platba.Kredit;
boRowAA['BankAccount'] := iPDPar.Platba.cisloUctuSNulami;
boRowAA['Text'] := Trim(iPDPar.popis + ' ' + iPDPar.Platba.nazevProtistrany);
boRowAA['SpecSymbol'] := iPDPar.Platba.SS;
boRowAA['DocDate$DATE'] := iPDPar.Platba.Datum;
boRowAA['AccDate$DATE'] := iPDPar.Platba.Datum;
boRowAA['Division_ID'] := AbraEnt.getDivisionId;
boRowAA['Currency_ID'] := AbraEnt.getCurrencyId;
if Assigned(iPDPar.Doklad) then
if iPDPar.vazbaNaDoklad then //Doklad vyplnime jen pokud chceme vazbu (vazbaNaDoklad je true). Doklad máme načtený i v situaci kdy vazbu nechceme - kvůli Firm_ID
begin
boRowAA['PDocumentType'] := iPDPar.Doklad.DocumentType; // např. 03, 10, 61
boRowAA['PDocument_ID'] := iPDPar.Doklad.ID;
end
else
begin
boRowAA['Firm_ID'] := iPDPar.Doklad.Firm_ID;
end
else //není Assigned(iPDPar.Doklad)
if not(iPDPar.pdparTyp = 'VoipKredit') AND not(iPDPar.pdparTyp = 'InternetKredit') then //tyto podmínky nejsou nutné, Abra by Firm_ID přebila hodnotou z fa, nicméně s VoipKredit a InternetKredit pracujeme v algoritmu níže a párujeme na faktury, tedy Firm_ID nebudeme zasílat
boRowAA['Firm_ID'] := getFirmIdKdyzNeniDoklad(iPDPar.Platba); //když má text platby na začátku Abra kód, najde se firma. Jinak se dá '3Y90000101' (DES), aby tam nebyl default "drobný nákup"
if iPDPar.pdparTyp = 'VoipKredit' then
begin
faId := DesU.vytvorFaZaVoipKredit(iPDPar.Platba.VS, iPDPar.CastkaPouzita, iPDPar.Platba.Datum);
if faId = '' then
//pokud nenajdeme podle VS firmu, zapíšeme VS - nemělo by se stát, ale pro jistotu
boRowAA['VarSymbol'] := iPDPar.Platba.VS
else begin
//byla vytvořena fa a tu teď připojíme. VS pak abra automaticky doplní
boRowAA['PDocumentType'] := '03'; // je to vždy faktura
boRowAA['PDocument_ID'] := faId;
end;
end;
if iPDPar.pdparTyp = 'InternetKredit' then
begin
faId := DesU.vytvorFaZaInternetKredit(iPDPar.Platba.VS, iPDPar.CastkaPouzita, iPDPar.Platba.Datum);
if faId = '' then
//pokud nenajdeme podle VS firmu, zapíšeme VS - nemělo by se stát, ale pro jistotu
boRowAA['VarSymbol'] := iPDPar.Platba.VS
else begin
//byla vytvořena fa a tu teď připojíme. VS pak abra automaticky doplní
boRowAA['PDocumentType'] := '03'; // je to vždy faktura
boRowAA['PDocument_ID'] := faId;
end;
end;
if iPDPar.Platba.Debet then
boRowAA['VarSymbol'] := iPDPar.Platba.VS; //pro debety aby vždy zůstal VS
if (iPDPar.Platba.cisloUctuVlastni = '2389210008000000') AND iPDPar.Platba.kredit then begin //PayU platba, rušíme peníze na cestě
DesU.zrusPenizeNaCeste(iPDPar.Platba.VS);
end;
end;
try begin
newId := DesU.abraBoCreate(boAA, 'bankstatement');
Result := Result + ' Číslo nového výpisu je ' + newID;
// DesU.abraOLELogout; // 29.3. přesunuto do DesU.abraBoCreateOLE
end;
except on E: exception do
begin
Application.MessageBox(PChar('Problem ' + ^M + E.Message), 'Vytváření výpisu');
Result := 'Chyba při vytváření výpisu';
end;
end;
end;
function TParovatko.getUzSparovano(Doklad_ID : string) : currency;
var
i : integer;
iPDPar : TPlatbaDokladPar;
begin
Result := 0;
if listPlatbaDokladPar.Count > 0 then
for i := 0 to listPlatbaDokladPar.Count - 1 do
begin
iPDPar := TPlatbaDokladPar(listPlatbaDokladPar[i]);
if Assigned(iPDPar.Doklad) AND (iPDPar.vazbaNaDoklad) then
if (iPDPar.Doklad.ID = Doklad_ID) then
Result := Result + iPDPar.CastkaPouzita;
end;
end;
function TParovatko.getPDParyAsText() : string;
var
i : integer;
iPDPar : TPlatbaDokladPar;
begin
Result := '';
if listPlatbaDokladPar.Count = 0 then exit;
for i := 0 to listPlatbaDokladPar.Count - 1 do
begin
iPDPar := TPlatbaDokladPar(listPlatbaDokladPar[i]);
Result := Result + 'VS: ' + iPDPar.Platba.VS + ' | ';
if iPDPar.vazbaNaDoklad AND Assigned(iPDPar.Doklad) then
Result := Result + 'Na doklad ' + iPDPar.Doklad.CisloDokladu + ' napárováno ' + FloatToStr(iPDPar.CastkaPouzita) + ' Kč | ';
Result := Result + iPDPar.Popis + sLineBreak;
end;
end;
function TParovatko.getPDParyPlatbyAsText(currPlatba : TPlatbaZVypisu) : string;
var
i : integer;
iPDPar : TPlatbaDokladPar;
begin
Result := '';
if listPlatbaDokladPar.Count = 0 then exit;
for i := 0 to listPlatbaDokladPar.Count - 1 do
begin
iPDPar := TPlatbaDokladPar(listPlatbaDokladPar[i]);
if iPDPar.Platba = currPlatba then begin
Result := Result + 'VS: ' + iPDPar.Platba.VS + ' | ';
if iPDPar.vazbaNaDoklad AND Assigned(iPDPar.Doklad) then
Result := Result + 'Na doklad ' + iPDPar.Doklad.CisloDokladu + ' napárováno ' + FloatToStr(iPDPar.CastkaPouzita) + ' Kč | ';
Result := Result + iPDPar.Popis;
Result := Result.Trim.TrimRight(['|']) + sLineBreak;
end;
end;
end;
function TParovatko.getPDPar(currPlatba : TPlatbaZVypisu; currDoklad_ID: string) : TPlatbaDokladPar;
var
i : integer;
iPDPar : TPlatbaDokladPar;
begin
Result := nil;
if listPlatbaDokladPar.Count = 0 then exit;
for i := 0 to listPlatbaDokladPar.Count - 1 do
begin
iPDPar := TPlatbaDokladPar(listPlatbaDokladPar[i]);
if (iPDPar.Platba = currPlatba) and (iPDPar.Doklad_ID = currDoklad_ID) and
(iPDPar.vazbaNaDoklad) then
Result := iPDPar;
end;
end;
function TParovatko.getFirmIdKdyzNeniDoklad(currPlatba : TPlatbaZVypisu) : string;
var
platbaText, prvni2pismena : string;
begin
platbaText := currPlatba.nazevProtistrany;
prvni2pismena := copy(platbaText, 1, 2);
if (prvni2pismena = 'T0') or (prvni2pismena = 'M0') or (prvni2pismena = 'N0') then
begin
Result := DesU.getFirmIdByCode(Copy(platbaText, 1, Pos(' ', platbaText + ' ') - 1));
end
else
Result := '3Y90000101'; //ať je firma DES;
end;
end.
|
unit Dkim;
interface
type
HCkBinData = Pointer;
HCkPrivateKey = Pointer;
HCkByteData = Pointer;
HCkString = Pointer;
HCkDkim = Pointer;
HCkTask = Pointer;
function CkDkim_Create: HCkDkim; stdcall;
procedure CkDkim_Dispose(handle: HCkDkim); stdcall;
function CkDkim_getAbortCurrent(objHandle: HCkDkim): wordbool; stdcall;
procedure CkDkim_putAbortCurrent(objHandle: HCkDkim; newPropVal: wordbool); stdcall;
procedure CkDkim_getDebugLogFilePath(objHandle: HCkDkim; outPropVal: HCkString); stdcall;
procedure CkDkim_putDebugLogFilePath(objHandle: HCkDkim; newPropVal: PWideChar); stdcall;
function CkDkim__debugLogFilePath(objHandle: HCkDkim): PWideChar; stdcall;
procedure CkDkim_getDkimAlg(objHandle: HCkDkim; outPropVal: HCkString); stdcall;
procedure CkDkim_putDkimAlg(objHandle: HCkDkim; newPropVal: PWideChar); stdcall;
function CkDkim__dkimAlg(objHandle: HCkDkim): PWideChar; stdcall;
function CkDkim_getDkimBodyLengthCount(objHandle: HCkDkim): Integer; stdcall;
procedure CkDkim_putDkimBodyLengthCount(objHandle: HCkDkim; newPropVal: Integer); stdcall;
procedure CkDkim_getDkimCanon(objHandle: HCkDkim; outPropVal: HCkString); stdcall;
procedure CkDkim_putDkimCanon(objHandle: HCkDkim; newPropVal: PWideChar); stdcall;
function CkDkim__dkimCanon(objHandle: HCkDkim): PWideChar; stdcall;
procedure CkDkim_getDkimDomain(objHandle: HCkDkim; outPropVal: HCkString); stdcall;
procedure CkDkim_putDkimDomain(objHandle: HCkDkim; newPropVal: PWideChar); stdcall;
function CkDkim__dkimDomain(objHandle: HCkDkim): PWideChar; stdcall;
procedure CkDkim_getDkimHeaders(objHandle: HCkDkim; outPropVal: HCkString); stdcall;
procedure CkDkim_putDkimHeaders(objHandle: HCkDkim; newPropVal: PWideChar); stdcall;
function CkDkim__dkimHeaders(objHandle: HCkDkim): PWideChar; stdcall;
procedure CkDkim_getDkimSelector(objHandle: HCkDkim; outPropVal: HCkString); stdcall;
procedure CkDkim_putDkimSelector(objHandle: HCkDkim; newPropVal: PWideChar); stdcall;
function CkDkim__dkimSelector(objHandle: HCkDkim): PWideChar; stdcall;
procedure CkDkim_getDomainKeyAlg(objHandle: HCkDkim; outPropVal: HCkString); stdcall;
procedure CkDkim_putDomainKeyAlg(objHandle: HCkDkim; newPropVal: PWideChar); stdcall;
function CkDkim__domainKeyAlg(objHandle: HCkDkim): PWideChar; stdcall;
procedure CkDkim_getDomainKeyCanon(objHandle: HCkDkim; outPropVal: HCkString); stdcall;
procedure CkDkim_putDomainKeyCanon(objHandle: HCkDkim; newPropVal: PWideChar); stdcall;
function CkDkim__domainKeyCanon(objHandle: HCkDkim): PWideChar; stdcall;
procedure CkDkim_getDomainKeyDomain(objHandle: HCkDkim; outPropVal: HCkString); stdcall;
procedure CkDkim_putDomainKeyDomain(objHandle: HCkDkim; newPropVal: PWideChar); stdcall;
function CkDkim__domainKeyDomain(objHandle: HCkDkim): PWideChar; stdcall;
procedure CkDkim_getDomainKeyHeaders(objHandle: HCkDkim; outPropVal: HCkString); stdcall;
procedure CkDkim_putDomainKeyHeaders(objHandle: HCkDkim; newPropVal: PWideChar); stdcall;
function CkDkim__domainKeyHeaders(objHandle: HCkDkim): PWideChar; stdcall;
procedure CkDkim_getDomainKeySelector(objHandle: HCkDkim; outPropVal: HCkString); stdcall;
procedure CkDkim_putDomainKeySelector(objHandle: HCkDkim; newPropVal: PWideChar); stdcall;
function CkDkim__domainKeySelector(objHandle: HCkDkim): PWideChar; stdcall;
function CkDkim_getHeartbeatMs(objHandle: HCkDkim): Integer; stdcall;
procedure CkDkim_putHeartbeatMs(objHandle: HCkDkim; newPropVal: Integer); stdcall;
procedure CkDkim_getLastErrorHtml(objHandle: HCkDkim; outPropVal: HCkString); stdcall;
function CkDkim__lastErrorHtml(objHandle: HCkDkim): PWideChar; stdcall;
procedure CkDkim_getLastErrorText(objHandle: HCkDkim; outPropVal: HCkString); stdcall;
function CkDkim__lastErrorText(objHandle: HCkDkim): PWideChar; stdcall;
procedure CkDkim_getLastErrorXml(objHandle: HCkDkim; outPropVal: HCkString); stdcall;
function CkDkim__lastErrorXml(objHandle: HCkDkim): PWideChar; stdcall;
function CkDkim_getLastMethodSuccess(objHandle: HCkDkim): wordbool; stdcall;
procedure CkDkim_putLastMethodSuccess(objHandle: HCkDkim; newPropVal: wordbool); stdcall;
function CkDkim_getVerboseLogging(objHandle: HCkDkim): wordbool; stdcall;
procedure CkDkim_putVerboseLogging(objHandle: HCkDkim; newPropVal: wordbool); stdcall;
procedure CkDkim_getVerifyInfo(objHandle: HCkDkim; outPropVal: HCkString); stdcall;
function CkDkim__verifyInfo(objHandle: HCkDkim): PWideChar; stdcall;
procedure CkDkim_getVersion(objHandle: HCkDkim; outPropVal: HCkString); stdcall;
function CkDkim__version(objHandle: HCkDkim): PWideChar; stdcall;
function CkDkim_AddDkimSignature(objHandle: HCkDkim; mimeIn: HCkByteData; outData: HCkByteData): wordbool; stdcall;
function CkDkim_AddDomainKeySignature(objHandle: HCkDkim; mimeIn: HCkByteData; outData: HCkByteData): wordbool; stdcall;
function CkDkim_DkimSign(objHandle: HCkDkim; mimeData: HCkBinData): wordbool; stdcall;
function CkDkim_DkimVerify(objHandle: HCkDkim; sigIndex: Integer; mimeData: HCkBinData): wordbool; stdcall;
function CkDkim_DomainKeySign(objHandle: HCkDkim; mimeData: HCkBinData): wordbool; stdcall;
function CkDkim_DomainKeyVerify(objHandle: HCkDkim; sigIndex: Integer; mimeData: HCkBinData): wordbool; stdcall;
function CkDkim_LoadDkimPk(objHandle: HCkDkim; privateKey: PWideChar; optionalPassword: PWideChar): wordbool; stdcall;
function CkDkim_LoadDkimPkBytes(objHandle: HCkDkim; privateKeyDer: HCkByteData; optionalPassword: PWideChar): wordbool; stdcall;
function CkDkim_LoadDkimPkFile(objHandle: HCkDkim; privateKeyFilePath: PWideChar; optionalPassword: PWideChar): wordbool; stdcall;
function CkDkim_LoadDomainKeyPk(objHandle: HCkDkim; privateKey: PWideChar; optionalPassword: PWideChar): wordbool; stdcall;
function CkDkim_LoadDomainKeyPkBytes(objHandle: HCkDkim; privateKeyDer: HCkByteData; optionalPassword: PWideChar): wordbool; stdcall;
function CkDkim_LoadDomainKeyPkFile(objHandle: HCkDkim; privateKeyFilePath: PWideChar; optionalPassword: PWideChar): wordbool; stdcall;
function CkDkim_LoadPublicKey(objHandle: HCkDkim; selector: PWideChar; domain: PWideChar; publicKey: PWideChar): wordbool; stdcall;
function CkDkim_LoadPublicKeyFile(objHandle: HCkDkim; selector: PWideChar; domain: PWideChar; publicKeyFilepath: PWideChar): wordbool; stdcall;
function CkDkim_NumDkimSignatures(objHandle: HCkDkim; mimeData: HCkByteData): Integer; stdcall;
function CkDkim_NumDkimSigs(objHandle: HCkDkim; mimeData: HCkBinData): Integer; stdcall;
function CkDkim_NumDomainKeySignatures(objHandle: HCkDkim; mimeData: HCkByteData): Integer; stdcall;
function CkDkim_NumDomainKeySigs(objHandle: HCkDkim; mimeData: HCkBinData): Integer; stdcall;
function CkDkim_PrefetchPublicKey(objHandle: HCkDkim; selector: PWideChar; domain: PWideChar): wordbool; stdcall;
function CkDkim_PrefetchPublicKeyAsync(objHandle: HCkDkim; selector: PWideChar; domain: PWideChar): HCkTask; stdcall;
function CkDkim_SaveLastError(objHandle: HCkDkim; path: PWideChar): wordbool; stdcall;
function CkDkim_SetDkimPrivateKey(objHandle: HCkDkim; privateKey: HCkPrivateKey): wordbool; stdcall;
function CkDkim_SetDomainKeyPrivateKey(objHandle: HCkDkim; privateKey: HCkPrivateKey): wordbool; stdcall;
function CkDkim_UnlockComponent(objHandle: HCkDkim; unlockCode: PWideChar): wordbool; stdcall;
function CkDkim_VerifyDkimSignature(objHandle: HCkDkim; sigIndex: Integer; mimeData: HCkByteData): wordbool; stdcall;
function CkDkim_VerifyDkimSignatureAsync(objHandle: HCkDkim; sigIndex: Integer; mimeData: HCkByteData): HCkTask; stdcall;
function CkDkim_VerifyDomainKeySignature(objHandle: HCkDkim; sigIndex: Integer; mimeData: HCkByteData): wordbool; stdcall;
function CkDkim_VerifyDomainKeySignatureAsync(objHandle: HCkDkim; sigIndex: Integer; mimeData: HCkByteData): HCkTask; stdcall;
implementation
{$Include chilkatDllPath.inc}
function CkDkim_Create; external DLLName;
procedure CkDkim_Dispose; external DLLName;
function CkDkim_getAbortCurrent; external DLLName;
procedure CkDkim_putAbortCurrent; external DLLName;
procedure CkDkim_getDebugLogFilePath; external DLLName;
procedure CkDkim_putDebugLogFilePath; external DLLName;
function CkDkim__debugLogFilePath; external DLLName;
procedure CkDkim_getDkimAlg; external DLLName;
procedure CkDkim_putDkimAlg; external DLLName;
function CkDkim__dkimAlg; external DLLName;
function CkDkim_getDkimBodyLengthCount; external DLLName;
procedure CkDkim_putDkimBodyLengthCount; external DLLName;
procedure CkDkim_getDkimCanon; external DLLName;
procedure CkDkim_putDkimCanon; external DLLName;
function CkDkim__dkimCanon; external DLLName;
procedure CkDkim_getDkimDomain; external DLLName;
procedure CkDkim_putDkimDomain; external DLLName;
function CkDkim__dkimDomain; external DLLName;
procedure CkDkim_getDkimHeaders; external DLLName;
procedure CkDkim_putDkimHeaders; external DLLName;
function CkDkim__dkimHeaders; external DLLName;
procedure CkDkim_getDkimSelector; external DLLName;
procedure CkDkim_putDkimSelector; external DLLName;
function CkDkim__dkimSelector; external DLLName;
procedure CkDkim_getDomainKeyAlg; external DLLName;
procedure CkDkim_putDomainKeyAlg; external DLLName;
function CkDkim__domainKeyAlg; external DLLName;
procedure CkDkim_getDomainKeyCanon; external DLLName;
procedure CkDkim_putDomainKeyCanon; external DLLName;
function CkDkim__domainKeyCanon; external DLLName;
procedure CkDkim_getDomainKeyDomain; external DLLName;
procedure CkDkim_putDomainKeyDomain; external DLLName;
function CkDkim__domainKeyDomain; external DLLName;
procedure CkDkim_getDomainKeyHeaders; external DLLName;
procedure CkDkim_putDomainKeyHeaders; external DLLName;
function CkDkim__domainKeyHeaders; external DLLName;
procedure CkDkim_getDomainKeySelector; external DLLName;
procedure CkDkim_putDomainKeySelector; external DLLName;
function CkDkim__domainKeySelector; external DLLName;
function CkDkim_getHeartbeatMs; external DLLName;
procedure CkDkim_putHeartbeatMs; external DLLName;
procedure CkDkim_getLastErrorHtml; external DLLName;
function CkDkim__lastErrorHtml; external DLLName;
procedure CkDkim_getLastErrorText; external DLLName;
function CkDkim__lastErrorText; external DLLName;
procedure CkDkim_getLastErrorXml; external DLLName;
function CkDkim__lastErrorXml; external DLLName;
function CkDkim_getLastMethodSuccess; external DLLName;
procedure CkDkim_putLastMethodSuccess; external DLLName;
function CkDkim_getVerboseLogging; external DLLName;
procedure CkDkim_putVerboseLogging; external DLLName;
procedure CkDkim_getVerifyInfo; external DLLName;
function CkDkim__verifyInfo; external DLLName;
procedure CkDkim_getVersion; external DLLName;
function CkDkim__version; external DLLName;
function CkDkim_AddDkimSignature; external DLLName;
function CkDkim_AddDomainKeySignature; external DLLName;
function CkDkim_DkimSign; external DLLName;
function CkDkim_DkimVerify; external DLLName;
function CkDkim_DomainKeySign; external DLLName;
function CkDkim_DomainKeyVerify; external DLLName;
function CkDkim_LoadDkimPk; external DLLName;
function CkDkim_LoadDkimPkBytes; external DLLName;
function CkDkim_LoadDkimPkFile; external DLLName;
function CkDkim_LoadDomainKeyPk; external DLLName;
function CkDkim_LoadDomainKeyPkBytes; external DLLName;
function CkDkim_LoadDomainKeyPkFile; external DLLName;
function CkDkim_LoadPublicKey; external DLLName;
function CkDkim_LoadPublicKeyFile; external DLLName;
function CkDkim_NumDkimSignatures; external DLLName;
function CkDkim_NumDkimSigs; external DLLName;
function CkDkim_NumDomainKeySignatures; external DLLName;
function CkDkim_NumDomainKeySigs; external DLLName;
function CkDkim_PrefetchPublicKey; external DLLName;
function CkDkim_PrefetchPublicKeyAsync; external DLLName;
function CkDkim_SaveLastError; external DLLName;
function CkDkim_SetDkimPrivateKey; external DLLName;
function CkDkim_SetDomainKeyPrivateKey; external DLLName;
function CkDkim_UnlockComponent; external DLLName;
function CkDkim_VerifyDkimSignature; external DLLName;
function CkDkim_VerifyDkimSignatureAsync; external DLLName;
function CkDkim_VerifyDomainKeySignature; external DLLName;
function CkDkim_VerifyDomainKeySignatureAsync; external DLLName;
end.
|
{
PicToMif
Author: Yao Chunhui & Zhou Xintong
IDE: Borland Developer Studio 2006 (Delphi)
Copyright @ 2006 Laputa Develop Group
July 16th, 2006
PicToMif is a freeware, which can be used to convert
bitmap or binary files to QuartusII memory initialization
files. It can be spread freely, as long as not being used
in commerce.
}
unit Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, RzTabs, Lib, ComCtrls, Spin, ExtDlgs, Menus,
About, PreView;
type
TFormMain = class(TForm)
RzPageControl: TRzPageControl;
TabSheetBmp: TRzTabSheet;
OpenDialog: TOpenDialog;
SaveDialog: TSaveDialog;
ScrollBoxPic: TScrollBox;
ImagePic: TImage;
TabSheetBinary: TRzTabSheet;
BtnLoadFile: TButton;
EditFile: TEdit;
GroupBoxBoundary: TGroupBox;
PanelColor: TPanel;
LabelRed: TLabel;
EditRed: TEdit;
EditGreen: TEdit;
LabelGreen: TLabel;
EditBlue: TEdit;
LabelBlue: TLabel;
TrackBarRed: TTrackBar;
TrackBarGreen: TTrackBar;
TrackBarBlue: TTrackBar;
mmoLog: TMemo;
Label1: TLabel;
seLen: TSpinEdit;
Label3: TLabel;
OpenPictureDialog1: TOpenPictureDialog;
Panel1: TPanel;
ButtonMake: TButton;
ButtonLoad: TButton;
LabelSize: TLabel;
GroupBoxType: TGroupBox;
RadioButtonTypeBlack: TRadioButton;
RadioButtonTypeColor: TRadioButton;
GroupBoxColor: TGroupBox;
RadioButtonColorSingle: TRadioButton;
RadioButtonColorMultiple: TRadioButton;
GroupBoxBlack: TGroupBox;
RadioButtonBlack: TRadioButton;
RadioButtonWhite: TRadioButton;
ColorDialog1: TColorDialog;
MainMenu1: TMainMenu;
M1: TMenuItem;
mExit: TMenuItem;
A1: TMenuItem;
N1: TMenuItem;
Button1: TButton;
ButtonPreView: TButton;
ButtonColorReset: TButton;
TabSheet1: TRzTabSheet;
mmoHelp: TMemo;
procedure ButtonColorResetClick(Sender: TObject);
procedure ButtonPreViewClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure A1Click(Sender: TObject);
procedure mExitClick(Sender: TObject);
procedure ScrollBoxPicDblClick(Sender: TObject);
procedure RadioButtonTypeColorClick(Sender: TObject);
procedure RadioButtonTypeBlackClick(Sender: TObject);
procedure TrackBarBlueChange(Sender: TObject);
procedure TrackBarGreenChange(Sender: TObject);
procedure TrackBarRedChange(Sender: TObject);
procedure EditRedGreenBlueChange(Sender: TObject);
procedure btnBinToMifClick(Sender: TObject);
procedure BtnLoadFileClick(Sender: TObject);
procedure ButtonMakeClick(Sender: TObject);
procedure ButtonLoadClick(Sender: TObject);
private
{ Private declarations }
PicFile: string;
public
{ Public declarations }
end;
var
FormMain: TFormMain;
implementation
{$R *.dfm}
procedure TFormMain.Button1Click(Sender: TObject);
var
w, h: Integer;
I, J: Integer;
br, bg, bb: TBitmap;
blue, green, red: Integer;
color: TColor;
begin
w := ImagePic.Picture.Width;
h := ImagePic.Picture.Height;
br := TBitmap.Create;
bg := TBitmap.Create;
bb := TBitmap.Create;
br.SetSize(w, h);
bg.SetSize(w, h);
bb.SetSize(w, h);
for I := 0 to w - 1 do
for J := 0 to h - 1 do
begin
color := ImagePic.Picture.Bitmap.Canvas.Pixels[I, J];
blue := color shr 16;
green := (color and ($0000FF00)) shr 8;
red := color and $000000FF;
if red > TrackBarRed.Position then
br.Canvas.Pixels[I, J] := clRed
else
br.Canvas.Pixels[I, J] := clBlack;
if green > TrackBarGreen.Position then
bg.Canvas.Pixels[I, J] := clGreen
else
bg.Canvas.Pixels[I, J] := clBlack;
if blue > TrackBarBlue.Position then
bb.Canvas.Pixels[I, J] := clBlue
else
bb.Canvas.Pixels[I, J] := clBlack;
end;
br.SaveToFile('red.bmp');
bg.SaveToFile('green.bmp');
bb.SaveToFile('blue.bmp');
br.Free;
bg.Free;
bb.Free;
end;
procedure TFormMain.ButtonColorResetClick(Sender: TObject);
begin
TrackBarRed.Position := 128;
TrackBarGreen.Position := 128;
TrackBarBlue.Position := 128;
end;
procedure TFormMain.ButtonLoadClick(Sender: TObject);
begin
// OpenDialog.Filter := 'Bitmap|*.bmp';
if OpenPictureDialog1.Execute = True then
if FileExists(OpenPictureDialog1.FileName) then
begin
PicFile := OpenPictureDialog1.FileName;
ImagePic.Picture.LoadFromFile(OpenPictureDialog1.FileName);
LabelSize.Caption := Format('Size:%d x %d',
[ImagePic.Picture.Width, ImagePic.Picture.Height]
);
end;
end;
procedure TFormMain.BtnLoadFileClick(Sender: TObject);
begin
OpenDialog.Filter := 'All Files|*.*';
if OpenDialog.Execute = True then
if FileExists(OpenDialog.FileName) then
begin
EditFile.Text := OpenDialog.FileName;
end;
end;
procedure TFormMain.ButtonMakeClick(Sender: TObject);
var
MifFilered: TextFile;
MifFilegreen: TextFile;
MifFileblue: TextFile;
PicSource: TBitmap;
PicCanvas: TCanvas;
FileName: string;
blue, green, red: Integer;
color: TColor;
i: Integer;
j: Integer;
counter: Integer;
content: string;
charwhite: Char;
charblack: Char;
begin
if PicFile = '' then
begin
Application.MessageBox('请先选择图像文件.', 'Pic2Mif');
end else if SaveDialog.Execute = True then
begin
PicSource := TBitmap.Create();
PicSource.LoadFromFile(PicFile);
PicCanvas := PicSource.Canvas;
{$I-}
if RadioButtonTypeBlack.Checked = True then
begin
FileName := SaveDialog.FileName;
AssignFile(MifFilered, FileName);
Rewrite(MifFilered);
Writeln(MifFilered, COPYRIGHT);
Writeln(MifFilered, '');
Writeln(MifFilered, 'WIDTH=' + '1' + ';');
Writeln(MifFilered, 'DEPTH=' + IntToStr(PicSource.Width * PicSource.Height) + ';');
Writeln(MifFilered, '');
Writeln(MifFilered, 'ADDRESS_RADIX=UNS;');
Writeln(MifFilered, 'DATA_RADIX=BIN;');
Writeln(MifFilered, '');
Writeln(MifFilered, 'CONTENT BEGIN');
counter := 0;
if RadioButtonBlack.Checked = True then
begin
charblack := '1';
charwhite := '0';
end else if RadioButtonWhite.Checked = True then
begin
charwhite := '1';
charblack := '0';
end;
for i := 0 to PicSource.Height - 1 do
for j := 0 to PicSource.Width - 1 do
begin
color := PicCanvas.Pixels[j, i];
blue := (color and $00FF0000) shr 16;
green := (color and ($0000FF00)) shr 8;
red := color and $000000FF;
if (blue <= TrackBarBlue.Position) and
(green <= TrackBarGreen.Position) and
(red <= TrackBarRed.Position) then
Writeln(MifFilered, #09 + IntToStr(counter) + ' : ' + charblack + ';')
else
Writeln(MifFilered, #09 + IntToStr(counter) + ' : ' + charwhite + ';');
Inc(counter);
end;
Writeln(MifFilered, 'END;');
CloseFile(MifFilered);
end else if RadioButtonTypeColor.Checked = True then
begin
FileName := SaveDialog.FileName;
if RadioButtonColorSingle.Checked = True then
begin
AssignFile(MifFilered, FileName);
Rewrite(MifFilered);
Writeln(MifFilered, COPYRIGHT);
Writeln(MifFilered, '');
Writeln(MifFilered, 'WIDTH=' + '3' + ';');
Writeln(MifFilered, 'DEPTH=' + IntToStr(PicSource.Width * PicSource.Height) + ';');
Writeln(MifFilered, '');
Writeln(MifFilered, 'ADDRESS_RADIX=UNS;');
Writeln(MifFilered, 'DATA_RADIX=BIN;');
Writeln(MifFilered, '');
Writeln(MifFilered, 'CONTENT BEGIN');
counter := 0;
for i := 0 to PicSource.Height - 1 do
for j := 0 to PicSource.Width - 1 do
begin
color := PicCanvas.Pixels[j, i];
blue := (color and $00FF0000) shr 16;
green := (color and ($0000FF00)) shr 8;
red := color and $000000FF;
if red >= TrackBarRed.Position then
content := '1'
else
content := '0';
if green >= TrackBarGreen.Position then
content := content + '1'
else
content := content + '0';
if blue >= TrackBarBlue.Position then
content := content + '1'
else
content := content + '0';
Writeln(MifFilered, #09 + IntToStr(counter) + ' : ' + content + ';');
Inc(counter);
end;
Writeln(MifFilered, 'END;');
CloseFile(MifFilered);
end else if RadioButtonColorMultiple.Checked = True then
begin
AssignFile(MifFilered, FileName + '.red.mif');
AssignFile(MifFilegreen, FileName + '.green.mif');
AssignFile(MifFileblue, FileName + '.blue.mif');
Rewrite(MifFilered);
Rewrite(MifFilegreen);
Rewrite(MifFileblue);
Writeln(MifFilered, COPYRIGHT);
Writeln(MifFilegreen, COPYRIGHT);
Writeln(MifFileblue, COPYRIGHT);
Writeln(MifFilered, 'WIDTH=' + '1' + ';');
Writeln(MifFilered, 'DEPTH=' + IntToStr(PicSource.Width * PicSource.Height) + ';');
Writeln(MifFilered, '');
Writeln(MifFilegreen, 'WIDTH=' + '1' + ';');
Writeln(MifFilegreen, 'DEPTH=' + IntToStr(PicSource.Width * PicSource.Height) + ';');
Writeln(MifFilegreen, '');
Writeln(MifFileblue, 'WIDTH=' + '1' + ';');
Writeln(MifFileblue, 'DEPTH=' + IntToStr(PicSource.Width * PicSource.Height) + ';');
Writeln(MifFileblue, '');
Writeln(MifFilered, 'ADDRESS_RADIX=UNS;');
Writeln(MifFilered, 'DATA_RADIX=BIN;');
Writeln(MifFilered, '');
Writeln(MifFilegreen, 'ADDRESS_RADIX=UNS;');
Writeln(MifFilegreen, 'DATA_RADIX=BIN;');
Writeln(MifFilegreen, '');
Writeln(MifFileblue, 'ADDRESS_RADIX=UNS;');
Writeln(MifFileblue, 'DATA_RADIX=BIN;');
Writeln(MifFileblue, '');
Writeln(MifFilered, 'CONTENT BEGIN');
Writeln(MifFilegreen, 'CONTENT BEGIN');
Writeln(MifFileblue, 'CONTENT BEGIN');
counter := 0;
for i := 0 to PicSource.Height - 1 do
for j := 0 to PicSource.Width - 1 do
begin
color := PicCanvas.Pixels[j, i];
blue := color shr 16;
green := (color and ($0000FF00)) shr 8;
red := color and $000000FF;
if red >= TrackBarRed.Position then
Writeln(MifFilered, #09 + IntToStr(counter) + ' : ' + '1' + ';')
else
Writeln(MifFilered, #09 + IntToStr(counter) + ' : ' + '0' + ';');
if green >= TrackBarGreen.Position then
Writeln(MifFilegreen, #09 + IntToStr(counter) + ' : ' + '1' + ';')
else
Writeln(MifFilegreen, #09 + IntToStr(counter) + ' : ' + '0' + ';');
if blue >= TrackBarBlue.Position then
Writeln(MifFileblue, #09 + IntToStr(counter) + ' : ' + '1' + ';')
else
Writeln(MifFileblue, #09 + IntToStr(counter) + ' : ' + '0' + ';');
Inc(counter);
end;
Writeln(MifFilered, 'END;');
Writeln(MifFilegreen, 'END;');
Writeln(MifFileblue, 'END;');
CloseFile(MifFilered);
CloseFile(MifFilegreen);
CloseFile(MifFileblue);
end;
{$I+}
if (IOResult <> 0) then
Application.MessageBox('读写文件出错。', 'PicToMif');
end;
PicSource.Free;
end;
end;
procedure TFormMain.ButtonPreViewClick(Sender: TObject);
var
PreViewCanvas: TCanvas;
PicCanvas: TCanvas;
W, H: Integer;
WhiteC, BlackC: TColor;
i, j: Integer;
color: TColor;
blue, green, red: Integer;
begin
if ImagePic.Picture <> nil then
begin
FormPreView.ImagePreView.Picture.Bitmap.SetSize(ImagePic.Picture.Width, ImagePic.Picture.Height);
W := FormPreView.ImagePreView.Width;
H := FormPreView.ImagePreView.Height;
PicCanvas := ImagePic.Picture.Bitmap.Canvas;
PreViewCanvas := FormPreView.ImagePreView.Picture.Bitmap.Canvas;
PreViewCanvas.Brush.Color := clBlack;
PreViewCanvas.FillRect(Rect(0, 0, W, H));
if RadioButtonTypeBlack.Checked = True then
begin
if RadioButtonBlack.Checked = True then
begin
BlackC := clWhite;
WhiteC := clBlack;
end else if RadioButtonWhite.Checked = True then
begin
BlackC := clBlack;
WhiteC := clWhite;
end;
for i := 0 to H - 1 do
for j := 0 to W - 1 do
begin
color := PicCanvas.Pixels[j, i];
blue := (color and $00FF0000) shr 16;
green := (color and ($0000FF00)) shr 8;
red := color and $000000FF;
if (blue <= TrackBarBlue.Position) and
(green <= TrackBarGreen.Position) and
(red <= TrackBarRed.Position) then
PreViewCanvas.Pixels[j, i] := BlackC
else
PreViewCanvas.Pixels[j, i] := WhiteC;
end;
end else if RadioButtonTypeColor.Checked = True then
begin
for i := 0 to H - 1 do
for j := 0 to W - 1 do
begin
color := PicCanvas.Pixels[j, i];
blue := color shr 16;
green := (color and ($0000FF00)) shr 8;
red := color and $000000FF;
color := 0;
if red >= TrackBarRed.Position then
color := color or $000000FF;
if green >= TrackBarGreen.Position then
color := color or $0000FF00;
if blue >= TrackBarBlue.Position then
color := color or $00FF0000;
PreViewCanvas.Pixels[j, i] := color;
end;
end;
end;
FormPreView.Show;
end;
procedure TFormMain.A1Click(Sender: TObject);
begin
AboutBox.ShowModal;
end;
procedure TFormMain.btnBinToMifClick(Sender: TObject);
var
Len: Integer;
begin
mmoLog.Visible := False;
if (not FileExists(EditFile.Text)) then
begin
ShowMessage('请确认源文件存在');
Exit;
end;
Len := seLen.Value;
if (Len <= 0) then
begin
ShowMessage('请输入字长');
Exit;
end;
if (SaveDialog.Execute = True) then
begin
mmoLog.Lines.Clear;
mmoLog.Lines.Add('Source : ' + EditFile.Text);
mmoLog.Lines.Add('Dest : ' + SaveDialog.FileName);
SaveBinaryToMif(EditFile.Text, Len, SaveDialog.FileName, mmoLog.Lines);
if IOResult <> 0 then
begin
ShowMessage('读写文件出错');
end else begin
end;
mmoLog.Visible := True;
end;
end;
procedure TFormMain.EditRedGreenBlueChange(Sender: TObject);
var
blue, green, red: Integer;
begin
blue := StrToInt(EditBlue.Text);
green := StrToInt(EditGreen.Text);
red := StrToInt(EditRed.Text);
PanelColor.Color := (blue shl 16) or (green shl 8) or red;
end;
procedure TFormMain.mExitClick(Sender: TObject);
begin
Close;
end;
procedure TFormMain.RadioButtonTypeBlackClick(Sender: TObject);
begin
if RadioButtonTypeBlack.Checked = True then
begin
GroupBoxBlack.Visible := True;
GroupBoxColor.Visible := False;
end;
end;
procedure TFormMain.RadioButtonTypeColorClick(Sender: TObject);
begin
if RadioButtonTypeColor.Checked = True then
begin
GroupBoxBlack.Visible := False;
GroupBoxColor.Visible := True;
end;
end;
procedure TFormMain.ScrollBoxPicDblClick(Sender: TObject);
begin
if ColorDialog1.Execute then
begin
ScrollBoxPic.Color := ColorDialog1.Color;
end;
end;
procedure TFormMain.TrackBarBlueChange(Sender: TObject);
begin
EditBlue.Text := IntToStr(TrackBarBlue.Position);
end;
procedure TFormMain.TrackBarGreenChange(Sender: TObject);
begin
EditGreen.Text := IntToStr(TrackBarGreen.Position);
end;
procedure TFormMain.TrackBarRedChange(Sender: TObject);
begin
EditRed.Text := IntToStr(TrackBarRed.Position);
end;
end.
|
unit TBCEditorDemo.Forms.Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BCEditor.Editor.Base, BCEditor.Editor, Vcl.ExtCtrls, Vcl.StdCtrls;
type
TMainForm = class(TForm)
Editor: TBCEditor;
ListBoxColors: TListBox;
ListBoxHighlighters: TListBox;
PanelLeft: TPanel;
SplitterVertical: TSplitter;
SplitterHorizontal: TSplitter;
procedure FormCreate(Sender: TObject);
procedure ListBoxHighlightersClick(Sender: TObject);
procedure ListBoxColorsClick(Sender: TObject);
private
{ Private declarations }
procedure SetSelectedColor;
procedure SetSelectedHighlighter;
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
procedure AddFileNamesFromPathIntoListBox(const APath: string; AListBox: TListBox);
var
LSearchRec: TSearchRec;
begin
if FindFirst(APath + '*.json', faNormal, LSearchRec) = 0 then
try
repeat
AListBox.AddItem(LSearchRec.Name, nil);
until FindNext(LSearchRec) <> 0;
finally
FindClose(LSearchRec);
end;
end;
procedure TMainForm.FormCreate(Sender: TObject);
var
LApplicationPath, LHighlighterPath, LColorsPath: string;
begin
LApplicationPath := IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName));
with Editor.Directories do
begin
LHighlighterPath := IncludeTrailingPathDelimiter(LApplicationPath + Highlighters);
LColorsPath := IncludeTrailingPathDelimiter(LApplicationPath + Colors);
end;
AddFileNamesFromPathIntoListBox(LHighlighterPath, ListBoxHighlighters);
AddFileNamesFromPathIntoListBox(LColorsPath, ListBoxColors);
with ListBoxHighlighters do
Selected[Items.IndexOf('Object Pascal.json')] := True;
with ListBoxColors do
Selected[Items.IndexOf('Default.json')] := True;
SetSelectedHighlighter;
SetSelectedColor;
end;
procedure TMainForm.SetSelectedColor;
begin
with ListBoxColors do
Editor.Highlighter.Colors.LoadFromFile(Items[ItemIndex]);
end;
procedure TMainForm.SetSelectedHighlighter;
begin
with ListBoxHighlighters do
Editor.Highlighter.LoadFromFile(Items[ItemIndex]);
Editor.Lines.Text := Editor.Highlighter.Info.General.Sample;
end;
procedure TMainForm.ListBoxColorsClick(Sender: TObject);
begin
SetSelectedColor;
end;
procedure TMainForm.ListBoxHighlightersClick(Sender: TObject);
begin
SetSelectedHighlighter;
end;
end.
|
unit UConsDevolucao;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, RxLookup, StdCtrls, Mask, ToolEdit, Buttons, Grids, DBGrids,
RXDBCtrl, ALed, Db, DBTables;
type
TfConsDevolucao = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
Label1: TLabel;
RxDBLookupCombo1: TRxDBLookupCombo;
Label2: TLabel;
DateEdit1: TDateEdit;
Label3: TLabel;
Edit1: TEdit;
BitBtn1: TBitBtn;
RxDBGrid1: TRxDBGrid;
Label4: TLabel;
ALed1: TALed;
Label5: TLabel;
ALed2: TALed;
qDevolucoes: TQuery;
qDevolucoesNumMov: TIntegerField;
qDevolucoesNome: TStringField;
qDevolucoesDtContato: TDateField;
qDevolucoesQtdPares: TFloatField;
qDevolucoesResolvido: TBooleanField;
qDevolucoesNumNota: TIntegerField;
qsDevolucoes: TDataSource;
qDevolucoesCodCliente: TIntegerField;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure RxDBLookupCombo1Enter(Sender: TObject);
procedure RxDBLookupCombo1Exit(Sender: TObject);
procedure RxDBGrid1GetCellParams(Sender: TObject; Field: TField;
AFont: TFont; var Background: TColor; Highlight: Boolean);
procedure FormCreate(Sender: TObject);
procedure BitBtn1Click(Sender: TObject);
procedure RxDBLookupCombo1CloseUp(Sender: TObject);
procedure DateEdit1Enter(Sender: TObject);
procedure DateEdit1Change(Sender: TObject);
procedure Edit1Enter(Sender: TObject);
procedure Edit1Change(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
end;
var
fConsDevolucao: TfConsDevolucao;
implementation
uses UDM1, UDevolucao, UAgendaTelef;
{$R *.DFM}
procedure TfConsDevolucao.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if not(DM1.tDevolucao.IsEmpty) then
DM1.tDevolucao.FindKey([qDevolucoesNumMov.AsInteger]);
Action := Cafree;
end;
procedure TfConsDevolucao.RxDBLookupCombo1Enter(Sender: TObject);
begin
DateEdit1.Clear;
Edit1.Clear;
DM1.tCliente.IndexFieldNames := 'Nome';
qDevolucoes.Close;
qDevolucoes.SQL.Clear;
qDevolucoes.SQL.Add('SELECT Dbdevolucao.NumMov, Dbcliente.Nome, Dbdevolucao.DtContato, Dbdevolucao.QtdPares, Dbdevolucao.Resolvido, Dbdevolucao.NumNota, Dbdevolucao.CodCliente');
qDevolucoes.SQL.Add('FROM "dbDevolucao.db" Dbdevolucao');
qDevolucoes.SQL.Add(' INNER JOIN "dbCliente.DB" Dbcliente');
qDevolucoes.SQL.Add(' ON (Dbdevolucao.CodCliente = Dbcliente.Codigo)');
qDevolucoes.SQL.Add('ORDER BY Dbcliente.Nome, Dbdevolucao.NumMov');
qDevolucoes.Open;
end;
procedure TfConsDevolucao.RxDBLookupCombo1Exit(Sender: TObject);
begin
DM1.tCliente.IndexFieldNames := 'Codigo';
end;
procedure TfConsDevolucao.RxDBGrid1GetCellParams(Sender: TObject;
Field: TField; AFont: TFont; var Background: TColor; Highlight: Boolean);
begin
if (qDevolucoesResolvido.AsBoolean) then
begin
AFont.Color := clWhite;
Background := clGreen;
end;
end;
procedure TfConsDevolucao.FormCreate(Sender: TObject);
begin
qDevolucoes.Close;
qDevolucoes.Open;
end;
procedure TfConsDevolucao.BitBtn1Click(Sender: TObject);
begin
Close;
end;
procedure TfConsDevolucao.RxDBLookupCombo1CloseUp(Sender: TObject);
begin
if RxDBLookupCombo1.Text <> '' then
qDevolucoes.Locate('CodCliente',RxDBLookupCombo1.KeyValue,[loCaseInsensitive]);
end;
procedure TfConsDevolucao.DateEdit1Enter(Sender: TObject);
begin
RxDBLookupCombo1.ClearValue;
Edit1.Clear;
qDevolucoes.Close;
qDevolucoes.SQL.Clear;
qDevolucoes.SQL.Add('SELECT Dbdevolucao.NumMov, Dbcliente.Nome, Dbdevolucao.DtContato, Dbdevolucao.QtdPares, Dbdevolucao.Resolvido, Dbdevolucao.NumNota, Dbdevolucao.CodCliente');
qDevolucoes.SQL.Add('FROM "dbDevolucao.db" Dbdevolucao');
qDevolucoes.SQL.Add(' INNER JOIN "dbCliente.DB" Dbcliente');
qDevolucoes.SQL.Add(' ON (Dbdevolucao.CodCliente = Dbcliente.Codigo)');
qDevolucoes.SQL.Add('ORDER BY Dbdevolucao.DtContato, Dbdevolucao.NumMov');
qDevolucoes.Open;
end;
procedure TfConsDevolucao.DateEdit1Change(Sender: TObject);
begin
if DateEdit1.Date > 1 then
qDevolucoes.Locate('DtContato',DateEdit1.Date,[loCaseInsensitive]);
end;
procedure TfConsDevolucao.Edit1Enter(Sender: TObject);
begin
RxDBLookupCombo1.ClearValue;
DateEdit1.Clear;
qDevolucoes.Close;
qDevolucoes.SQL.Clear;
qDevolucoes.SQL.Add('SELECT Dbdevolucao.NumMov, Dbcliente.Nome, Dbdevolucao.DtContato, Dbdevolucao.QtdPares, Dbdevolucao.Resolvido, Dbdevolucao.NumNota, Dbdevolucao.CodCliente');
qDevolucoes.SQL.Add('FROM "dbDevolucao.db" Dbdevolucao');
qDevolucoes.SQL.Add(' INNER JOIN "dbCliente.DB" Dbcliente');
qDevolucoes.SQL.Add(' ON (Dbdevolucao.CodCliente = Dbcliente.Codigo)');
qDevolucoes.SQL.Add('ORDER BY Dbdevolucao.NumMov');
qDevolucoes.Open;
end;
procedure TfConsDevolucao.Edit1Change(Sender: TObject);
begin
if Edit1.Text <> '' then
qDevolucoes.Locate('NumMov',Edit1.Text,[loCaseInsensitive]);
end;
procedure TfConsDevolucao.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Shift = ([ssAlt])) and (Key = 101) then
begin
fAgendaTelef := TfAgendaTelef.Create(Self);
fAgendaTelef.ShowModal;
end;
end;
end.
|
unit ExceptionsResStrings;
{$mode objfpc}{$H+}
interface
// при добавлении строк НЕЗАБУДЬ!!! добавить эти строки в *.inc.po.en
resourcestring
errEmptyParam = 'Не задан объект для постановки в очередь.';
{ rsXMLTagDNameHost = 'Хост';
rsXMLTagDNameHostList = 'Список хостов';
rsXMLTagDNameIDCS = 'Подсистема сбора информации';
rsXMLTagDNameProtocolList = 'Список протоколов';
rsXMLTagDNameServerProtocolList = 'Список серверных протоколов';
rsXMLTagDNameRemoutProtocolList = 'Список удаленных протоколов';
rsXMLTagDNameProtocol = 'Протокол';
rsXMLTagDNameServerProtocol = 'Серверный протокол';
rsXMLTagDNameRemoutProtocol = 'Удаленный протокол';
rsXMLTagDNameDeviceList = 'Список устройств';
rsXMLTagDNameServerDeviceList = 'Список серверных устройств';
rsXMLTagDNameRemoutDeviceList = 'Список удаленных устройств';
rsXMLTagDNameDevice = 'Устройство';
rsXMLTagDNameServerDevice = 'Серверное устройство';
rsXMLTagDNameRemoutDevice = 'Удаленное устройство';
rsXMLTagDNameChannelList = 'Список каналов';
rsXMLTagDNameServerChannelList = 'Список серверных каналов';
rsXMLTagDNameRemoutChannelList = 'Список удаленных каналов';
rsXMLTagDNameChannel = 'Канал';
rsXMLTagDNameServerChannel = 'Серверный канал';
rsXMLTagDNameRemoutChannel = 'Удаленный канал';
rsXMLTagDNameModuleList = 'Список модулей';
rsXMLTagDNameModule = 'Модуль';
rsXMLRangeDescrSrvProt = 'ServerProtocolIDRange';
rsXMLRangeDescrRemProt = 'RemoutProtocolIDRange';
rsXMLRangeDescrSrvChanTCP = 'ServerChannelTCPIDRange';
rsXMLRangeDescrRemChanTCP = 'RemoutChannelTCPIDRange';
rsXMLRangeDescrSrvChanRTU = 'ServerChannelRTUIDRange';
rsXMLRangeDescrRemChanRTU = 'RemoutChannelRTUIDRange';
rsXMLRangeDescrSrvDev = 'ServerDeviceIDRange';
rsXMLRangeDescrRemDev = 'RemoutDeviceIDRange';
rsXMLRangeDescrModules = 'ModulesIDRange';
rsXMLRSModbusRTUDescr = 'RSModbusRTU';
rsXMLRangeDescrHost = 'HostIDRange';}
rsNoError = 'Нет ошибки.';
rsErrUnknown = 'Неизвестная ошибка';
rsErrPortCustom = 'Ошибка порта';
rsErrRequestNotAssigned = 'Запрос не определен.';
rsErrPortNotAssigned = 'Интерфейсный порт не определен.';
rsErrPortParNotAssigned = 'Параметры порта не заданы.';
rsErrPortParInvalid = 'Ошибка в параметрах порта.';
rsErrRequestDataNotAssigned = 'Не удалось получить данные из запроса.';
rsErrResiveProcNotAssigned = 'Не установлена процедура возврата данных в интерфейсном порту.';
rsErrItfPortParamType = 'Класс параметров порта не соответствует требуемому';
rsErrItfPortParamNotAssigned = 'Не заданы параметры интерфейсного порта.';
rsErrItfPortParamInvalid = 'Ошибка в параметрах интерфейсного порта.';
rsErrPortNotActive = 'Порт не открыт.';
rsErrChannelParamNotAssiged = 'Параметры канала не заданы.';
rsErrChannelParamInvalid = 'Ошибка в параметрах канала.';
rsErrChannelIsntFound = 'Запрашиваемый канал не найден';
rsErrResiveDataTimeout = 'Таймаут ожидания ответа устройства.';
rsErrResiveDataNull = 'Пришел ответ нулевой длины.';
rsErrPortDataWriteTimeout = 'Не удалось записать данные в порт.';
rsErrPortDataWrite = 'Ошибка записи данных в порт';
rsErrPortDataWait = 'Ошибка ожидания данных';
rsErrPortDataRead = 'Ошибка чтения данных';
rsErrPortParityError = 'Ошибка паритета.';
rsDevErrorCommand = 'Ошибка выполнения команды. %s';
rsDevErrorCommandNotAssigned = 'Команда не задана.';
rsErrDeviceParamInvalid = 'Ошибка в параметрах устройства.';
rsDevLoadParamXMLNotAssign = 'Не задан узел XML для загрузки параметров устройства.';
rsDevSaveParamXMLNotAssign = 'Не задан узел XML для сохранения параметров устройства.';
rsPortOperationAborted = 'Операция ввода/вывода была прервана из-за завершения потока команд или по запросу приложения.';
rsDeviceNotAssigned = 'Не задано устройство для мониторинга.';
rsChannelListNotAssigned = 'Не задан список каналов для осуществления мониторинга.';
rsXMLLoadError = 'Ошибка загрузки устройства';
rsXMLLoadDevTypeError = 'Тип устройства не соответствует типу указанному в параметрах.';
rsXMLLoadDevFuncNotAssign = 'В конфигурации не заданы функции поддерживаемые устройством.';
rsXMLLoadOutOfRangeID = 'Не задан идентификатор диапазона адресов.';
rsXMLLoadOutOfRangeOfAddr = 'Выход за пределы допустимого диапазона адресов.';
rsXMLLoadOutOfRangeOfReg = 'Выход за пределы допустимого диапазона количества регистров.';
rsCommandDevItfNotInit = 'Команда не инициализирована интерфейсом устройства.';
rsCommandSrvProtNotMBProt = 'Установленный протокол не поддерживает серверный Modbus протокол.';
rsCommandMBDevNotSet = 'Не задан объект Modbus устройства.';
rsCommandChannelListNotSet = 'Не задан список каналов до удаленных устройств.';
rsCommandChannelListIsEmpty = 'Список каналов для доступа к удаленному устройству пуст.';
rsModbusError = 'Ошибка Modbus';
rsCommandMBDevNumNotSet = 'Не задан номер устройства для команды.';
rsCommandIsAnotherDevice = 'Команда предназначается другому устройству.';
rsProtLoadParamXMLNotAssign = 'Не задан узел XML для загрузки параметров протокола.';
rsProtDoesNotSupportThisCmd = 'Протокол не поддерживает данный тип команд.';
rsProtIDMissing = 'В параметрах отсутствует идентификатор протокола.';
rsProtIDRefersAnotherProtocol = 'Идентификатор относится к другому протоколу.';
rsProtTypeIsIncorrect = 'Тип протокола задан неверно.';
rsProtNotSupport = 'Протокол не поддерживается.';
rsChannelIsNotActive = 'Канал не открыт.';
rsClassNotImplemented = 'Класс не реализован';
rsCMSFileNotFound = 'Файл %s не найден.';
rsCMSBadID = 'Идентификатор выходит за допустимый диапазон.';
rsCMSBadID1 = 'Идентификатор хоста(%d) должен находиться в диапазоне от %d до %d';
rsCMSFileNotFound1 = 'Файл не найден.';
rsCMSLoad = 'Загрузка конфигурации';
rsCMSLoadErrorGetConfPath = 'Не удалось получить путь к файлу конфигурации системы.';
rsCMSLoadErrorCodePageF = 'Кодовая страница конфигурации (%s) не соответствует требуемой - %s';
rsCMSLoadErrorCodePage = 'Кодовая страница конфигурации не соответствует требуемой.';
rsCMSLoadErrorRootNameF = 'Корневой тег %s не соответствует требуемому %s';
rsCMSLoadErrorRootName = 'Корневой тег не соответствует требуемому.';
rsCMSLoadErrorHostListNotFound = 'Не найден тег списка хостов.';
rsCMSLoadErrorHostListIsEmpty = 'Список хстов пуст.';
rsCMSLoadErrorIPListIsEmpty = 'Список хстов пуст.';
rsCMSLoadErrorHostTegNotFound = 'Не найден тег хоста для данного устройства.';
rsCMSLoadErrorIDCSTegNotFound = 'Тег подсистемы сбора первичной информации(IDCS) отсутствует.';
rsCMSLoadErrorProtListNotFound = 'Отсутствует тег списка протоколов.';
rsCMSLoadErrorSvrProtListNotFound = 'Отсутствует список ServerProtocolList.';
rsCMSLoadErrorRmtProtListNotFound = 'Отсутствует список RemoteProtocolList.';
rsCMSLoadErrorChanListNotFound = 'Отсутствует тег списка каналов.';
rsCMSLoadErrorSvrChanListNotFound = 'Отсутствует список ServerChannelList.';
rsCMSLoadErrorRmtChanListNotFound = 'Отсутствует список RemoteChannelList.';
rsCMSLoadErrorSvrDevListNotFound = 'Отсутствует список ServerDeviceList.';
rsCMSLoadErrorRmtDevListNotFound = 'Отсутствует список RemoteDeviceList.';
rsCMSLoadErrorModuleListNotFound = 'Отсутствует список ModuleList.';
rsCMSLoadErrorRSModbusRTUNotFound = 'Отсутствует конфигурация модуля RSModbusRTU.';
rsSysGetMem = 'Ошибка выделения памяти';
rsObjectNotAssigned = 'Не задан узел XML для загрузки параметров объекта наблюдения';
rsErrObjectParamInvalid = 'Ошибка в параметрах объекта наблюдения';
rsObjectListNotAssigned = 'Не задан узел XML для загрузки параметров списка объектов наблюдения';
rsErrObjectListParamInvalid = 'Ошибка в параметрах списка объектов наблюдения';
RS_MB_ERR_CUSTOM = 'Ошибка Modbus: %s';
RS_MB_ILLEGAL_FUNCTION = 'Недопустимый тип функции, полученных в запросе.';
RS_MB_ILLEGAL_DATA_ADDRESS = 'Недопустимый адрес данных, полученный в запросе.';
RS_MB_ILLEGAL_DATA_VALUE = 'Недопустимые значения, полученные в поле данных запроса.';
RS_MB_SLAVE_DEVICE_FAILURE = 'Неустранимая ошибка при обработке устройством полученного запроса.';
RS_MB_ACKNOWLEDGE = 'Запрос принят. Выполняется длительная операция.';
RS_MB_SLAVE_DEVICE_BUSY = 'Устройство занято. Повторите запрос позже.';
RS_MB_MEMORY_PARITY_ERROR = 'При чтении файла обнаружена ошибка четности памяти.';
RS_MB_GATWAY_PATH_UNAVAILABLE = 'Ошибка маршрутизации.';
RS_MB_GATWAY_TARGET_DEVICE_FAILED_RESPOND = 'Запрашиваемое устройство не ответило.';
RS_MB_UNINSPACTED = 'Нераспознанная ошибка.';
RS_MASTER_BUFF_NOT_ASSIGNET = 'Передан пустой буфер.';
RS_MASTER_GET_MEMORY = 'Системная ошибка. Код ошибки: %d. - %s';
RS_MASTER_CRC = 'Ошибка расчета CRC16 полученного пакета.';
RS_MASTER_WORD_READ = 'Передано нечетное количество байт.';
RS_MASTER_F3_LEN = 'Неверная длина пакета.';
RS_MASTER_QUANTITY = 'Количество записанных регистров превышает допустимое.';
RS_MASTER_DEVICE_ADDRESS = 'Пакет предназначен другому устройству.';
RS_MASTER_FIFO_COUNT = 'Количество FIFO регистров превышает допустимое.';
RS_MASTER_MEI = 'Функция 43. Данный MEI не поддерживается.';
RS_MASTER_RDIC = 'Данный код чтения устройства не реализован.';
RS_MASTER_MOREFOLLOWS = 'Недопустимое значение MoreFollows.';
RS_MASTER_FUNCTION_CODE = 'Неверный код функции в ответном сообщении.';
RS_MASTER_F72_CHKRKEY = 'Ключ переданный в ответе не соответствует ожидаемому.';
RS_MASTER_F72_QUANTITY = 'Количество регистров в ответе выходит за допустимый диапазон.';
RS_MASTER_F72_CRC = 'Ошибка CRC блока данных.';
rsExceptXmlNotAssigned = 'Объект XML документа не задан.';
rsExceptXlmNoNode = '%s Тег %s отсутствует в документе';
rsExceptXlmNoAttr = '%s Тег %s. Отсутствует обязательный атрибут %s';
rsExceptSyetemType = '%s Данный компилятор раcсчитан на тип системы %s. В конфигурационном файле содержится иной тип - %s';
rsExceptSessionID = 'Идентификатор сессии не задан';
rsExceptXMLAttrVal = '%s Тег %s. Атрибут %s имеет недопустимое значение %s';
rsExceptAddDevAlreadyExists = 'Устройство с адресом %d уже существует.';
rsExceptNeitherFunctioIsNotSet = 'Ни одна функция не установлена';
implementation
end.
|
{***************************************}
{ Типы и константы ядра }
{ Written by Kurnosov M. }
{***************************************}
unit Types;
interface
Const
MAX_COUNT_ARGS = 10; { макс. кол-во аргументов в проц - TProc }
Type
_PString = ^String;
{ ------------------------------------------------------------ }
{ Структура под Стек }
{ ------------------------------------------------------------ }
PStack = ^TStack;
TStack = Record
Name : String;
selType : Byte; { Селектор типа : }
{ 1 - Строка }
{ 2 - Целое число }
{ 3 - Лог. велечина }
Str : String;
Int : Longint; {Integer;}
Bool : Boolean;
End; { TStack }
{ ------------------------------------------------------------ }
{ Структура под результат выражения. Базовые типы }
{ ------------------------------------------------------------ }
TResult = Record
selType : Byte; { Селектор типа : }
{ 1 - Строка }
{ 2 - Целое число }
{ 3 - Лог. велечина }
Str : String;
Int : Longint; {Integer;}
Bool : Boolean;
End; { TResult }
{ ------------------------------------------------------------ }
{ структура под процедуры и функции }
{ ------------------------------------------------------------ }
TFunction = Record
Name : String; { имя процедуры или функции. }
Fun : Boolean; { True - фун. False - проц. }
{ имена аргументов }
Args : Array [1..MAX_COUNT_ARGS] of String;
CountArgs : Byte; { кол-во аргументов. }
StartLine : Word; { Номер строки в SourceCode }
{ указывает на начало кода }
{ проц-ы. }
Result : TResult; { Возращаемое значение функцией }
End; { TFunction }
implementation
end.
|
unit ProgrammUnit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.OleServer, AlienRFID2_TLB,
Vcl.ExtCtrls, Vcl.StdCtrls, ActiveX, Vcl.ComCtrls, Vcl.Buttons;
type
TProgrammForm = class(TForm)
mReader: TclsReader;
Timer1: TTimer;
GroupBox1: TGroupBox;
TagIdEdit: TEdit;
EPCEdit: TEdit;
ErrorReadingLabel: TLabel;
EPCStringEdit: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
ProgrammingGroupBox: TGroupBox;
AntennaRadioGroup: TRadioGroup;
GroupBox3: TGroupBox;
TrackBar1: TTrackBar;
AntennaPowerLabel: TLabel;
VersionLabel: TLabel;
TypeLabel: TLabel;
Label5: TLabel;
Label6: TLabel;
EPCWriteEdit: TEdit;
EPCStringWriteEdit: TEdit;
WriteButton: TBitBtn;
ErrorWritingLabel: TLabel;
procedure FormActivate(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure EPCEditChange(Sender: TObject);
procedure EPCWriteEditChange(Sender: TObject);
procedure EPCStringWriteEditChange(Sender: TObject);
procedure EPCWriteEditKeyPress(Sender: TObject; var Key: Char);
procedure TrackBar1Change(Sender: TObject);
procedure WriteButtonClick(Sender: TObject);
private
{ Private declarations }
FProgrammMode:boolean;
procedure RefreshControls;
procedure setProgrammMode(const Value: boolean);
procedure verifyTag;
procedure GetTagList;
public
{ Public declarations }
property ProgrammMode:boolean read FProgrammMode write setProgrammMode;
end;
var
ProgrammForm: TProgrammForm;
implementation
{$R *.dfm}
uses CommonUnit, StrUtils;
procedure TProgrammForm.EPCEditChange(Sender: TObject);
begin
if ActiveControl=EPCEdit then
EPCStringEdit.Text:=HexToString(EPCEdit.text);
end;
procedure TProgrammForm.EPCStringWriteEditChange(Sender: TObject);
begin
if ActiveControl=EPCStringWriteEdit then
EPCWriteEdit.Text:=StringToHex(EPCStringWriteEdit.text);
end;
procedure TProgrammForm.EPCWriteEditChange(Sender: TObject);
begin
if ActiveControl=EPCWriteEdit then
EPCStringWriteEdit.Text:=HexToString(EPCWriteEdit.text);
end;
procedure TProgrammForm.EPCWriteEditKeyPress(Sender: TObject; var Key: Char);
begin
Key:=ValidHexKey(Key);
end;
procedure TProgrammForm.FormActivate(Sender: TObject);
begin
if mReader.IsConnected then
begin
ProgrammMode:=true;
VerifyTag;
RefreshControls;
EPCWriteEdit.Text:=EPCEdit.Text;
end;
end;
procedure TProgrammForm.RefreshControls;
var readerVersion,readerType:String;
SafeArray: PSafeArray;
Antenna:boolean;
iLow, iHigh : Integer;
AntCount:integer;
i:integer;
progAntenna:WideString;
antennaPower:Integer;
begin
if not(mReader.isConnected) then
begin
VersionLabel.Caption:='Reader not connected';
VersionLabel.Visible:=true;
TypeLabel.Visible:=false;
ProgrammingGroupBox.Enabled:=false;
exit;
end;
ProgrammingGroupBox.Enabled:=true;
readerVersion:=mReader.ReaderVersion;
readerType:=mReader.ReaderType;
VersionLabel.Caption:=readerVersion;
VersionLabel.Visible:=true;
TypeLabel.Caption:=readerType;
TypeLabel.Visible:=true;
SafeArray:=mReader.GetAllAntennaStatus;
if SafeArray<>nil then
begin
SafeArrayGetLBound(SafeArray,1,iLow);
SafeArrayGetUBound(SafeArray,1,iHigh);
AntCount:=iHigh-iLow+1;
AntennaRadioGroup.Items.Clear;
for i:=0 to AntCount-1 do
begin
SafeArrayGetElement(SafeArray,i,Antenna);
if Antenna then
if (mReader.IsAntennaConnected(IntToStr(i))) then
AntennaRadioGroup.Items.add(IntToStr(i));
end;
end;
progAntenna:=mReader.ProgAntenna;
try
AntennaRadioGroup.ItemIndex:=StrToInt(progAntenna);
except
AntennaRadioGroup.ItemIndex:=-1;
end;
antennaPower:= mReader.GetAntennaPower(progAntenna);
AntennaPowerLabel.Caption:='RF Power '+IntToStr(antennaPower)+' %';
trackBar1.Position:=antennaPower;
end;
procedure TProgrammForm.setProgrammMode(const Value: boolean);
begin
if not(mReader.IsConnected) then exit;
if Value then
begin
mReader.Function_:='Programmer';
Timer1.Enabled:=true;
end
else
begin
mReader.Function_:='Reader';
Timer1.Enabled:=false;
end;
FProgrammMode := Value;
end;
procedure TProgrammForm.Timer1Timer(Sender: TObject);
begin
VerifyTag;
end;
procedure TProgrammForm.TrackBar1Change(Sender: TObject);
var Antenna:String;
antennaPower:Integer;
begin
if ActiveControl=TrackBar1 then
begin
Antenna:=AntennaRadioGroup.Items[AntennaRadioGroup.ItemIndex];
mReader.SetAntennaPower(Antenna, TrackBar1.Position);
antennaPower:= mReader.GetAntennaPower(Antenna);
AntennaPowerLabel.Caption:='RF Power '+IntToStr(antennaPower)+' %';
trackBar1.Position:=antennaPower;
end;
end;
procedure TProgrammForm.verifyTag;
var tagResponse,TagID, TagInfo:String;
len:Integer;
begin
try
tagResponse:=mReader.G2Read(eG2Bank_EPC, '2', '6');
len:=Length(tagResponse);
if (len >= 35) then
tagID:=copy(tagResponse,1,36)
else
tagID:=copy(tagResponse,1,24);
TagIDEdit.Text:=trim(tagID);
GetTagList;
ErrorReadingLabel.Caption:='';
except
on ex:Exception do
begin
TagIDEdit.Text:='';
ErrorReadingLabel.Caption:=ex.Message;
end;
end;
end;
procedure TProgrammForm.WriteButtonClick(Sender: TObject);
var data:String;
i:integer;
resultData:String;
status:String;
begin
data:=EPCWriteEdit.text;
data:=ReplaceStr(data,' ','');
resultData:='';
for I := 1 to length (data) div 2 do
resultData:= resultData+Copy(data,(I-1)*2+1,2)+' ';
resultData:=trim(resultData);
status:='';
try
status:= mReader.ProgramTag(resultData);
except
on E:Exception do status:=e.Message;
end;
ErrorWritingLabel.Caption:=status;
ErrorWritingLabel.visible:=true;
end;
procedure TProgrammForm.GetTagList;
var inString:string;
result:boolean;
sTagList:TStringList;
i:integer;
SafeArray: PSafeArray;
TagInfo:ITagInfo;
TagInfoArray:array of ITagInfo;
iLow, iHigh : Integer;
tagsCount:integer;
s:String;
begin
if not mReader.IsConnected then
begin
exit;
end;
mReader.TagListFormat:='Text';
mReader.TagListFormat:='XML';
inString:=mReader.TagList;
if (inString<>'') and (pos('No Tags',inString)=0) then
begin
mReader.ParseXMLTagList(inString,SafeArray,false);
if SafeArray<>nil then
begin
SafeArrayGetLBound(SafeArray,1,iLow);
SafeArrayGetUBound(SafeArray,1,iHigh);
tagsCount:=iHigh-iLow+1;
i:=0;
if tagsCount>0 then
begin
SafeArrayGetElement(SafeArray,i,TagInfo);
EPCEdit.Text:=trim(TagInfo.TagID);
EPCStringEdit.Text:=HexToString(EPCEdit.text);
if tagsCount>1 then
ErrorReadingLabel.Caption:='Plase leave only ONE tag near antenna';
end;
WriteButton.enabled:=tagsCount=1;
end;
end;
application.ProcessMessages;
end;
end.
|
{------------------------------------
功能说明:扩展工厂
创建日期:2010/06/08
作者:WZW
版权:WZW
-------------------------------------}
unit SysFactoryEx;
interface
uses
Classes,
SysUtils,
FactoryIntf,
SvcInfoIntf;
type
//基类
TBaseFactoryEx = class(TFactory, ISvcInfoEx)
private
FIIDList: TStrings;
protected
{ISvcInfoEx}
procedure GetSvcInfo(Intf: ISvcInfoGetter); virtual;
public
constructor Create(const IIDs: array of TGUID);
destructor Destroy; override;
{Inherited}
function GetIntf(const IID: TGUID; out Obj): HResult; override;
procedure ReleaseIntf; override;
function Supports(const IntfName: string): Boolean; override;
procedure EnumKeys(Intf: IEnumKey); override;
end;
TSingletonFactoryEx = class(TBaseFactoryEx)
private
FIntfCreatorFunc: TIntfCreatorFunc;
FIntfRelease: Boolean;
protected
FIntfRef: IInterface;
FInstance: TObject;
procedure GetSvcInfo(Intf: ISvcInfoGetter); override;
function GetObj(out Obj: TObject; out AutoFree: Boolean): Boolean; override;
public
constructor Create(IIDs: array of TGUID; IntfCreatorFunc: TIntfCreatorFunc;
IntfRelease: Boolean = False);
destructor Destroy; override;
function GetIntf(const IID: TGUID; out Obj): HResult; override;
procedure ReleaseIntf; override;
end;
TObjFactoryEx = class(TSingletonFactoryEx)
private
FOwnsObj: Boolean;
protected
public
constructor Create(const IIDs: array of TGUID; Instance: TObject; OwnsObj:
Boolean = False; IntfRelease: Boolean = False);
destructor Destroy; override;
{Inherited}
//function GetIntf(const IID : TGUID; out Obj):HResult;override;
procedure ReleaseIntf; override;
end;
implementation
uses
SysFactoryMgr,
SysMsg;
{ TBaseFactoryEx }
constructor TBaseFactoryEx.Create(const IIDs: array of TGUID);
var
i: Integer;
IIDStr: string;
begin
FIIDList := TStringList.Create;
for i := low(IIDs) to high(IIDs) do
begin
IIDStr := GUIDToString(IIDs[i]);
if FactoryManager.Exists(IIDStr) then
raise Exception.CreateFmt(Err_IntfExists, [IIDStr]);
FIIDList.Add(IIDStr);
end;
FactoryManager.RegisterFactory(self);
end;
function TBaseFactoryEx.GetIntf(const IID: TGUID; out Obj): HResult;
begin
Result := E_NOINTERFACE;
end;
destructor TBaseFactoryEx.Destroy;
begin
FactoryManager.UnRegisterFactory(self);
FIIDList.Free;
inherited;
end;
procedure TBaseFactoryEx.EnumKeys(Intf: IEnumKey);
var
i: Integer;
begin
if Assigned(Intf) then
begin
for i := 0 to FIIDList.Count - 1 do
Intf.EnumKey(FIIDList[i]);
end;
end;
procedure TBaseFactoryEx.GetSvcInfo(Intf: ISvcInfoGetter);
begin
end;
procedure TBaseFactoryEx.ReleaseIntf;
begin
end;
function TBaseFactoryEx.Supports(const IntfName: string): Boolean;
begin
Result := FIIDList.IndexOf(IntfName) <> -1;
end;
{ TSingletonFactoryEx }
constructor TSingletonFactoryEx.Create(IIDs: array of TGUID; IntfCreatorFunc:
TIntfCreatorFunc; IntfRelease: Boolean);
begin
if length(IIDs) = 0 then
raise Exception.Create(Err_IIDsParamIsEmpty);
FInstance := nil;
FIntfRef := nil;
FIntfRelease := IntfRelease;
FIntfCreatorFunc := IntfCreatorFunc;
inherited Create(IIDs);
end;
function TSingletonFactoryEx.GetIntf(const IID: TGUID; out Obj): HResult;
begin
//if not Assigned(FIntfCreatorFunc) then//不能这样,因为后代TObjFactoryEx时FIntfCreatorFunc为空
// raise Exception.CreateFmt(Err_IntfCreatorFuncIsNil,[GUIDToString(IID)]);
Result := E_NOINTERFACE;
if FIntfRef = nil then
begin
FInstance := FIntfCreatorFunc(Self.FParam);
if FInstance <> nil then
begin
if FInstance.GetInterface(IID, FIntfRef) then
begin
Result := S_OK;
IInterface(Obj) := FIntfRef;
end
else
raise Exception.CreateFmt(Err_IntfNotSupport, [GUIDToString(IID)]);
end;
end
else
begin
Result := FIntfRef.QueryInterface(IID, Obj);
end;
end;
function TSingletonFactoryEx.GetObj(out Obj: TObject; out AutoFree: Boolean):
Boolean;
begin
Obj := Self.FInstance;
AutoFree := False;
Result := True;
end;
destructor TSingletonFactoryEx.Destroy;
begin
inherited;
end;
procedure TSingletonFactoryEx.GetSvcInfo(Intf: ISvcInfoGetter);
var
SvcInfoIntf: ISvcInfo;
SvcInfoIntfEx: ISvcInfoEx;
SvcInfoRec: TSvcInfoRec;
i: Integer;
begin
SvcInfoIntf := nil;
if FInstance = nil then
begin
FInstance := FIntfCreatorFunc(self.FParam);
if FInstance = nil then
exit;
FInstance.GetInterface(IInterface, FIntfRef);
end;
if FInstance.GetInterface(ISvcInfoEx, SvcInfoIntfEx) then
SvcInfoIntfEx.GetSvcInfo(Intf)
else
begin
if FInstance.GetInterface(ISvcInfo, SvcInfoIntf) then
begin
with SvcInfoRec do
begin
//GUID :=GUIDToString(self.FIntfGUID);
ModuleName := SvcInfoIntf.GetModuleName;
Title := SvcInfoIntf.GetTitle;
Version := SvcInfoIntf.GetVersion;
Comments := SvcInfoIntf.GetComments;
end;
end;
for i := 0 to self.FIIDList.Count - 1 do
begin
SvcInfoRec.GUID := self.FIIDList[i];
if SvcInfoIntf = nil then
begin
with SvcInfoRec do
begin
ModuleName := '';
Title := '';
Version := '';
Comments := '';
end;
end;
Intf.SvcInfo(SvcInfoRec);
end;
end;
end;
procedure TSingletonFactoryEx.ReleaseIntf;
begin
if (FIntfRef = nil) or (FInstance = nil) then
exit;
if (FInstance is TInterfacedObject) or FIntfRelease then
FIntfRef := nil
else
begin
FInstance.Free;
FIntfRef := nil;
end;
FInstance := nil;
end;
{ TObjFactoryEx }
constructor TObjFactoryEx.Create(const IIDs: array of TGUID; Instance: TObject;
OwnsObj: Boolean; IntfRelease: Boolean);
begin
if length(IIDs) = 0 then
raise Exception.Create(Err_IIDsParamIsEmpty);
if Instance = nil then
raise Exception.CreateFmt(Err_InstanceIsNil, [GUIDToString(IIDs[0])]);
inherited Create(IIDs, nil, IntfRelease); //往上后FIntfRef会被赋为nil
FOwnsObj := OwnsObj or IntfRelease or (Instance is TInterfacedObject);
FInstance := Instance;
FInstance.GetInterface(IInterface, FIntfRef);
end;
destructor TObjFactoryEx.Destroy;
begin
inherited;
end;
procedure TObjFactoryEx.ReleaseIntf;
begin
if FOwnsObj then
inherited;
end;
end.
|
unit Tools;
(*****************************************************************************
Prozessprogrammierung SS08
Aufgabe: Muehle
Diesen Unit enthaelt universelle Hilfsroutinen.
Autor: Alexander Bertram (B_TInf 2616)
*****************************************************************************)
interface
uses
RTTextIO,
Types, SysMB, SysStat, PTypes;
{ Wandelt eine Ganzzahl in einen String um. }
function IntToStr(I: integer; Width: word): string;
{ Entfernt alle Leerzeichen aus einem String. }
function Trim(S: string): string;
{ Gibt eine Meldung aus und speichert ein Ereignis in der Exitsemaphore ab. }
procedure Die(ErrorMessage: string);
{ Wandelt einen String in Grossbuchstaben um. }
function StrUpCase(S: string): string;
{ Wandelt einen String in einen Integer um. }
function StrToInt(S: string; var I: integer): boolean;
{ Wandelt einen String in ein Byte um. }
function StrToByte(S: string; var B: byte): boolean;
{ Wandelt einen String in einen Spieler um. }
function StrToPlayer(S: string; var P: TPlayer): boolean;
{ Wandelt einen Spieler in einen String um. }
function PlayerToStr(P: TPlayer): string;
{ Wandelt einen String in eine Bedenkzeit um. }
function StrToTimeLimit(S: string; var TL: TTimeLimit): boolean;
{ Wandelt eine Farbe in einen String um. }
function ColorToStr(Color: byte): string;
{ Sorgt fuer das Anzeigen einer Systemstatusmeldung. }
procedure ShowSystemStatus(S: string);
{ Liefert eine Zufallszahl im Bereich 0 <= X < Range. }
function GetRandomWord(Range: word): word;
{ Konvertiert einen Spieler in einen Besitzer. }
function PlayerToOwner(P: TPlayer): TOwner;
{ Berechnet ausgehend von einer Spielfeldposition die linke Nachbarposition. }
function GetLeftFieldPos(F: TField; var FP: TFieldPos): boolean;
{ Berechnet ausgehend von einer Spielfeldposition die rechte
Nachbarposition. }
function GetRightFieldPos(F: TField; var FP: TFieldPos): boolean;
{ Berechnet ausgehend von einer Spielfeldposition die obere Nachbarposition. }
function GetUpperFieldPos(F: TField; var FP: TFieldPos): boolean;
{ Berechnet ausgehend von einer Spielfeldposition die untere
Nachbarposition. }
function GetLowerFieldPos(F: TField; var FP: TFieldPos): boolean;
{ Berechnet die erste gueltige Position in einer Zeile. }
function GetFirstXPos(F: TField; var FP: TFieldPos): boolean;
{ Berechnet die erste gueltige Position in einer Spalte. }
function GetFirstYPos(F: TField; var FP: TFieldPos): boolean;
{ Berechnet die Spielerphase anhand der Anzahl der Spielsteine. }
function GetPlayerStage(PlacedTC, CapturedTC: TTokenCount): TPlayerStage;
{ Ausgabe der Position als String. }
function FieldPosToStr(FP: TFieldPos): string;
{ Sendet eine Debugmedldung an den Logger, wenn der Compilerschalter DEBUG
definiert ist. }
procedure Debug(S: string);
{ Umwandlung von Besitzer zum Spieler. }
function OwnerToPlayer(O: TOwner): TPlayer;
{ Bereitet Zugdaten zum Schreiben in die Logdatei vor und sendet diese an
den Logger. }
procedure LogMove(P: TPlayer; MD: TMoveData);
{ Liefert den anderen Spieler zurueck. }
function GetOtherPlayer(CurrentPlayer: TPlayer): TPlayer;
{ Sendet eine Logmeldung an den Logger. }
procedure Log(S: string);
implementation
uses
RTKernel,
Semas, Logger, LoggerMB;
function IntToStr(I: integer; Width: word): string;
(*****************************************************************************
Beschreibung:
Wandelt eine Ganzzahl in einen String um.
In:
I: integer: Zahl, die umgewandelt werden soll
Width: word: Laenge des Resultatstrings. Ist Width groesser als
Stellenanzahl von I, wird der String von links mit '0' aufgefuellt.
Out:
Zahl als String
*****************************************************************************)
var
S: string;
begin
{ Zahl umwandeln }
Str(I, S);
{ Mit '0' auffuellen }
while Length(s) < Width do
S := '0' + S;
IntToStr := S;
end;
procedure Debug(S: string);
(*****************************************************************************
Beschreibung:
Sendet eine Debugmedldung an den Logger, wenn der Compilerschalter DEBUG
definiert ist.
In:
S: string: Meldung
Out:
-
*****************************************************************************)
{$IFDEF DEBUG}
var
LoggerMessage: TLoggerMessage;
{$ENDIF}
begin
{$IFDEF DEBUG}
LoggerMessage.Kind := lomkLog;
{ Taskhandle der aufrufenden Task mitsenden }
LoggerMessage.Sender := CurrentTaskHandle;
LoggerMessage.Message := Message;
{ Nachricht in der Loggermailbox ablegen }
LoggerMB.Put(Logger.Mailbox, LoggerMessage);
{$ENDIF}
end;
function Trim(S: string): string;
(*****************************************************************************
Beschreibung:
Entfernt alle Leerzeichen aus einem String.
In:
S: string: String, aus dem die Leerzeichen entfernt werden sollen
Out:
-
*****************************************************************************)
var
i: word;
begin
i := 1;
{ String zeichnenweise durchlaufen }
while i <= Length(S) do
begin
{ Auf Leerzeichen pruefen }
if S[i] = ' ' then
{ Loeschen }
Delete(S, i, 1)
else
{ Zaehler inkrementieren }
Inc(i);
end;
Trim := S;
end;
function StrToInt(S: string; var I: integer): boolean;
(*****************************************************************************
Beschreibung:
Wandelt einen String in einen Integer um.
In:
S: string: String, der die Zahl darstellt
I: integer: Integer, in dem das Ergebnis gespeichert wird
Out:
True, wenn die Umwandlung erfolgreich war
*****************************************************************************)
var
C: integer;
begin
{ Umwandeln }
Val(S, I, C);
{ Rueckgabewert berechnen }
StrToInt := c = 0;
end;
function StrToByte(S: string; var B: byte): boolean;
(*****************************************************************************
Beschreibung:
Wandelt einen String in ein Byte um.
In:
S: string: String, der die Zahl enthaelt
B: byte: Byte, in dem das Ergebnis gespeichert wird
Out:
True, wenn Umwandlung erfolgreich war
*****************************************************************************)
var
I,
C: integer;
begin
StrToByte := false;
{ Umwandeln }
Val(s, i, c);
{ Wertberich ueberpruefen }
if (c = 0) and (i >= Low(byte)) and (i <= High(byte)) then
begin
B := I;
{ Rueckgabewert setzen }
StrToByte := true;
end;
end;
procedure Die(ErrorMessage: string);
(*****************************************************************************
Beschreibung:
Gibt eine Meldung aus und speichert ein Ereignis in der Exitsemaphore ab.
In:
ErrorMessage: string: Meldung, die ausgegeben wird
Out:
-
*****************************************************************************)
begin
WriteLn(ErrorMessage);
Signal(ExitSemaphore);
end;
function StrUpCase(S: string): string;
(*****************************************************************************
Beschreibung:
Wandelt einen String in Grossbuchstaben um.
In:
S: string: String, der umgewandelt werden soll
Out:
String in Grossbuchstaben
*****************************************************************************)
var
i: integer;
begin
{ String zeichenweise durchlaufen }
for i := 1 to Length(s) do
{ Jede Stelle umwandeln }
StrUpCase[i] := UpCase(S[i]);
StrUpCase := S;
end;
function StrToPlayer(S: string; var P: TPlayer): boolean;
(*****************************************************************************
Beschreibung:
Wandelt einen String in einen Spieler um.
In:
S: string: String, der den Spieler enthaelt
Player: TPlayer: Spieler
Out:
True, wenn Umwandlung geklappt hat
*****************************************************************************)
begin
StrToPlayer := false;
{ String in Grossbuchstaben umwandeln }
S := StrUpCase(s);
{ Pruefen, welchen Spieler der String enthaelt und Rueckgabewert setzen }
if S = 'USER' then
begin
StrToPlayer := true;
P := User;
end
else if s = 'CPU' then
begin
StrToPlayer := true;
P := CPU;
end;
end;
function PlayerToStr(P: TPlayer): string;
(*****************************************************************************
Beschreibung:
Wandelt einen Spieler in einen String um.
In:
Player: TPlayer: Spieler, der umgewandelt werden soll
Out:
Spieler als String
*****************************************************************************)
begin
{ Spieler auswerten und Rueckgabewert setzen }
if P = User then
PlayerToStr := cUserTaskName
else if P = CPU then
PlayerToStr := cCPUTaskName
else
PlayerToStr := 'Unknown player';
end;
function StrToTimeLimit(S: string; var TL: TTimeLimit): boolean;
(*****************************************************************************
Beschreibung:
Wandelt einen String in eine Bedenkzeit um.
In:
S: string: String, der die Bedenkzeit enthaelt
TimeLimit: TTimeLimit: Bendenkzeit
Out:
True, wenn erfolgreich
*****************************************************************************)
var
I, C: integer;
begin
StrToTimeLimit := false;
{ Umwandeln }
Val(S, I, C);
{ Werteberich ueberpruefen und Rueckgabewert setzen }
if (c = 0) and (i >= Low(TTimeLimit)) and (i <= High(TTimeLimit)) then
begin
TL := i;
StrToTimeLimit := true;
end;
end;
function ColorToStr(Color: byte): string;
(*****************************************************************************
Beschreibung:
Wandelt eine Farbe in einen String um.
In:
Color: byte: Farbe, die umgewandelt werden soll
Out:
Farbe als String
*****************************************************************************)
type
{ Farben als Aufzaehlungstyp }
TColor = (Black, Blue, Green, Cyan, Red, Magenta, Brown, Gray, DarkGray,
LightBlue, LightGreen, LightCyan, LightRed, LightMagenta, Yellow, White);
TColorStrings = array[TColor] of string;
const
{ Farben als Strings }
ColorStrings: TColorStrings = ('Black', 'Blue', 'Green', 'Cyan', 'Red',
'Magenta', 'Brown', 'Gray', 'DarkGray', 'LightBlue', 'LightGreen',
'LightCyan', 'LightRed', 'LightMagenta', 'Yellow', 'White');
begin
ColorToStr := 'Unknown Color';
{ Farbe auswerten und Rueckgabewert setzen }
if (TColor(Color) >= Low(TColor)) and (TColor(Color) <= High(TColor)) then
ColorToStr := ColorStrings[TColor(Color)];
end;
procedure ShowSystemStatus(S: string);
(*****************************************************************************
Beschreibung:
Sorgt fuer das Anzeigen einer Systemstatusmeldung.
In:
Meldung, die angezeigt werden soll
Out:
-
*****************************************************************************)
var
SystemStatusMessage: TSystemStatusMessage;
begin
{ Nachrichtart setzen und in der Mailbox der Systemstatustask ablegen }
SystemStatusMessage.Kind := ssmkSystemStatus;
SystemStatusMessage.Message := S;
SysMB.Put(SysStat.Mailbox, SystemStatusMessage);
end;
function GetRandomWord(Range: word): word;
(*****************************************************************************
Beschreibung:
Liefert eine Zufallszahl im Bereich 0 <= X < Range.
In:
Range: word: Wertebereich fuer die Zufallszahl
Out:
Zufallszahl
*****************************************************************************)
begin
Wait(RandomWordSemaphore);
GetRandomWord := Random(Range);
Signal(RandomWordSemaphore);
end;
function PlayerToOwner(P: TPlayer): TOwner;
(*****************************************************************************
Beschreibung:
Konvertiert einen Spieler in einen Besitzer.
In:
P: TPlayer: Spieler
Out:
Entsprechender Besitzer
*****************************************************************************)
begin
{ Spieler auswerten und den entsprechenden Besitzer ermitteln }
case P of
User:
PlayerToOwner := oUser;
CPU:
PlayerToOwner := oCPU;
end;
end;
function GetLeftFieldPos(F: TField; var FP: TFieldPos): boolean;
(*****************************************************************************
Beschreibung:
Berechnet ausgehend von einer Spielfeldposition die linke Nachbarposition.
In:
F: TField: Spielfeld
FP: TFieldPos: Ausgangsposition
Out:
True, wenn Nachbarposition gefunden
FP: TFieldPos: Neue Spielfeldposition
*****************************************************************************)
var
TmpFP: TFieldPos;
begin
GetLeftFieldPos := false;
{ Position zwischenspeichern }
TmpFP := FP;
{ Pruefen, ob sich die Ausgangsposition am linken Rand befindet }
if (FP.X > Low(TFieldWidth)) and
{ Mittlere Zeile gesondert behandeln, wenn die Ausgangsspalte auf der
rechten Kante des inneren Qudrates liegt }
not ((FP.Y = cFieldSquareCount) and (FP.X = cFieldSquareCount + 1)) then
begin
{ Eine Position nach links }
Dec(FP.X);
{ Naechstlinke gueltige Position suchen und Rueckgabewert setzen }
while (FP.X > Low(TFieldWidth)) and not F.Pos[FP.X, FP.Y].Valid do
Dec(FP.X);
GetLeftFieldPos := F.Pos[FP.X, FP.Y].Valid;
end;
{ Wenn nicht erfolgreich, Ausgangsposition wiederherstellen }
if not F.Pos[FP.X, FP.Y].Valid then
FP := TmpFP;
end;
function GetRightFieldPos(F: TField; var FP: TFieldPos): boolean;
(*****************************************************************************
Beschreibung:
Berechnet ausgehend von einer Spielfeldposition die rechte
Nachbarposition.
In:
F: TField: Spielfeld
FP: TFieldPos: Ausgangsposition
Out:
True, wenn Nachbarposition gefunden
FP: TFieldPos: Neue Spielfeldposition
*****************************************************************************)
var
TmpFP: TFieldPos;
begin
GetRightFieldPos := false;
{ Position zwischenspeichern }
TmpFP := FP;
{ Pruefen, ob sich die Ausgangsposition am rechten Rand befindet }
if (FP.X < High(TFieldWidth) - 1) and
{ Mittlere Zeile gesondert behandeln, wenn die Ausgangsspalte auf der
linken Kante des inneren Qudrates liegt }
not ((FP.Y = cFieldSquareCount) and (FP.X = cFieldSquareCount - 1)) then
begin
{ Eine Position nach rechts }
Inc(FP.X);
{ Naechsrechte gueltige Position suchen und Rueckgabewert setzen }
while (FP.X < High(TFieldWidth) - 1) and not
F.Pos[FP.X, FP.Y].Valid do
begin
Inc(FP.X);
end;
GetRightFieldPos := F.Pos[FP.X, FP.Y].Valid;
end;
{ Wenn nicht erfolgreich, Ausgangsposition wiederherstellen }
if not F.Pos[FP.X, FP.Y].Valid then
FP := TmpFP;
end;
function GetUpperFieldPos(F: TField; var FP: TFieldPos): boolean;
(*****************************************************************************
Beschreibung:
Berechnet ausgehend von einer Spielfeldposition die obere Nachbarposition.
In:
F: TField: Spielfeld
FP: TFieldPos: Ausgangsposition
Out:
True, wenn Nachbarposition gefunden
FP: TFieldPos: Neue Spielfeldposition
*****************************************************************************)
var
TmpFP: TFieldPos;
begin
GetUpperFieldPos := false;
{ Position zwischenspeichern }
TmpFP := FP;
{ Pruefen, ob sich die Ausgangsposition am oberen Rand befindet }
if (FP.Y > Low(TFieldHeight)) and
{ Mittlere Spalte gesondert behandeln, wenn die Ausgangszeile auf der
unteren Kante des inneren Qudrates liegt }
not ((FP.X = cFieldSquareCount) and (FP.Y = cFieldSquareCount + 1)) then
begin
{ Eine Position nach oben }
Dec(FP.Y);
{ Naechstobere gueltige Position suchen und Rueckgabewert setzen }
while (FP.Y > Low(TFieldHeight)) and not F.Pos[FP.X, FP.Y].Valid do
begin
Dec(FP.Y);
end;
GetUpperFieldPos := F.Pos[FP.X, FP.Y].Valid;
end;
{ Wenn nicht erfolgreich, Ausgangsposition wiederherstellen }
if not F.Pos[FP.X, FP.Y].Valid then
FP := TmpFP;
end;
function GetLowerFieldPos(F: TField; var FP: TFieldPos): boolean;
(*****************************************************************************
Beschreibung:
Berechnet ausgehend von einer Spielfeldposition die untere
Nachbarposition.
In:
F: TField: Spielfeld
FP: TFieldPos: Ausgangsposition
Out:
True, wenn Nachbarposition gefunden
FP: TFieldPos: Neue Spielfeldposition
*****************************************************************************)
var
TmpFP: TFieldPos;
begin
GetLowerFieldPos := false;
{ Position zwischenspeichern }
TmpFP := FP;
{ Pruefen, ob sich die Ausgangsposition am unteren Rand befindet }
if (FP.Y < High(TFieldHeight) - 1) and
{ Mittlere Spalte gesondert behandeln, wenn die Ausgangszeile auf der
oberen Kante des inneren Qudrates liegt }
not ((FP.X = cFieldSquareCount) and (FP.Y = cFieldSquareCount - 1)) then
begin
{ Eine Position nach unten }
Inc(FP.Y);
{ Naechstuntere gueltige Position suchen und Rueckgabewert setzen }
while (FP.Y < High(TFieldHeight) - 1) and not
F.Pos[FP.X, FP.Y].Valid do
begin
Inc(FP.Y);
end;
GetLowerFieldPos := F.Pos[FP.X, FP.Y].Valid;
end;
{ Wenn nicht erfolgreich, Ausgangsposition wiederherstellen }
if not F.Pos[FP.X, FP.Y].Valid then
FP := TmpFP;
end;
function GetFirstXPos(F: TField; var FP: TFieldPos): boolean;
(*****************************************************************************
Beschreibung:
Berechnet die erste gueltige Position in einer Zeile.
In:
F: TField: Spielfeld
FP: TFieldPos: Ausgangsposition
Out:
True, wenn Position gefunden
*****************************************************************************)
begin
{ Pruefen, ob die Ausgangsposition auf der mittleren Zeile in der rechten
Haelfte liegt }
if (FP.Y = cFieldSquareCount) and (FP.X >= cFieldSquareCount) then
{ Position auf die rechte Kante des inneren Quadrates setzen }
FP.X := cFieldSquareCount
else
{ Position auf linke Kante setzen }
FP.X := Low(TFieldWidth);
{ Pruefen ob Position gueltig und Rueckgabewert setzen }
if F.Pos[FP.X, FP.Y].Valid then
GetFirstXPos := true
else
{ Naechstrechte Position suchen }
GetFirstXPos := GetRightFieldPos(F, FP);
end;
function GetFirstYPos(F: TField; var FP: TFieldPos): boolean;
(*****************************************************************************
Beschreibung:
Berechnet die erste gueltige Position in einer Spalte.
In:
F: TField: Spielfeld
FP: TFieldPos: Ausgangsposition
Out:
True, wenn Position gefunden
*****************************************************************************)
begin
{ Pruefen, ob die Ausgangsposition auf der mittleren Spalte in der unteren
Haelfte liegt }
if (FP.X = cFieldSquareCount) and (FP.Y >= High(TFieldSquareCount)) then
{ Position auf die untere Kante des inneren Quadrates setzen }
FP.Y := High(TFieldSquareCount)
else
{ Position auf obere Kante setzen }
FP.Y := Low(TFieldHeight);
{ Pruefen ob Position gueltig und Rueckgabewert setzen }
if F.Pos[FP.X, FP.Y].Valid then
GetFirstYPos := true
else
{ Naechstuntere Position suchen }
GetFirstYPos := GetLowerFieldPos(F, FP);
end;
function GetPlayerStage(PlacedTC, CapturedTC: TTokenCount): TPlayerStage;
(*****************************************************************************
Beschreibung:
Berechnet die Spielerphase anhand der Anzahl der Spielsteine.
In:
PlacedTC: TTokenCount: Gesetzte Spielsteine
CapturedTC: TTokenCount: Geschlagene Spielsteine
Out:
Spielerphase
*****************************************************************************)
begin
{ Noch nicht alle Spielsteine gesetzt }
if PlacedTC < cTokenCount then
{ Setzphase }
GetPlayerStage := psPlace
{ Genug Steine zum Springen verloren }
else if cTokenCount - CapturedTC = cFieldSquareCount then
{ Sprungphase }
GetPlayerStage := psFly
else
{ Ziehphase }
GetPlayerStage := psMove;
end;
function FieldPosToStr(FP: TFieldPos): string;
(*****************************************************************************
Beschreibung:
Ausgabe der Position als String.
In:
FP: TFieldPos: Position
Out:
Position als String
*****************************************************************************)
begin
FieldPosToStr := Chr(Ord('a') + FP.X) + Chr(Ord('1') + FP.Y);
end;
function OwnerToPlayer(O: TOwner): TPlayer;
(*****************************************************************************
Beschreibung:
Umwandlung von Besitzer zum Spieler.
In:
O: TOwner: Besitzer
Out:
Enstprechneder Spieler
*****************************************************************************)
begin
{ Besitzer auswerten und entsprecheneden Spieler als Rueckgabewert }
if O = oUser then
OwnerToPlayer := User
else if O = oCPU then
OwnerToPlayer := CPU;
end;
procedure LogMove(P: TPlayer; MD: TMoveData);
(*****************************************************************************
Beschreibung:
Bereitet Zugdaten zum Schreiben in die Logdatei vor und sendet diese an
den Logger.
In:
P: TPlayer: Spieler, der gezogen hat
MD: TMoveData: Zugdaten
Out:
-
*****************************************************************************)
var
LM: TLoggerMessage;
begin
{ Nachrichtenart als Logmeldung markieren }
LM.Kind := lomkLog;
{ Erstes Zeichen des Spielernamens stellt den ziehenden Spieler in der
Logdatei dar }
LM.Message := Copy(PlayerToStr(P), 1, 1) + ' ';
case MD.Kind of
{ Spieler konnte nicht ziehen oder schlagen }
mkNoMove:
LM.Message := LM.Message + '.';
{ Spieler hat gesetzt }
mkPlace:
LM.Message := LM.Message + '* ' + FieldPosToStr(MD.TargetFP);
{ Spieler hat gezogen }
mkMove:
LM.Message := LM.Message + ' ' + FieldPosToStr(MD.SourceFP) + ' ' +
FieldPosToStr(MD.TargetFP);
{ Spieler hat geschlagen }
mkCapture:
LM.Message := LM.Message + 'x ' + FieldPosToStr(MD.SourceFP);
{ Dem Spieler wurde ein Stein geklaut }
mkSteal:
LM.Message := LM.Message + '- ' + FieldPosToStr(MD.SourceFP);
end;
{ Zug als String in die Logmailbox ablegen }
LoggerMB.Put(Logger.Mailbox, LM);
end;
function GetOtherPlayer(CurrentPlayer: TPlayer): TPlayer;
(*****************************************************************************
Beschreibung:
Liefert den anderen Spieler zurueck.
In:
CurrentPlayer: TPlayer: Aktueller Spieler
Out:
Anderer Spieler
*****************************************************************************)
begin
{ Aktuellen Spieler auswerten und den anderen zurueck liefern }
if CurrentPlayer = High(TPlayer) then
GetOtherPlayer := Low(TPlayer)
else
GetOtherPlayer := Succ(CurrentPlayer);
end;
procedure Log(S: string);
(*****************************************************************************
Beschreibung:
Sendet eine Logmeldung an den Logger.
In:
S: string: Meldung
Out:
-
*****************************************************************************)
var
LM: TLoggerMessage;
begin
{ Nachricht als Logmeldung markieren }
LM.Kind := lomkLog;
LM.Message := S;
{ Nachricht in der Loggermailbox ablegen }
LoggerMB.Put(Logger.Mailbox, LM);
end;
end. |
{*******************************************************************************
Title: T2Ti ERP
Description: Controller relacionado à tabela [ECF_CONFIGURACAO]
The MIT License
Copyright: Copyright (C) 2010 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com</p>
Albert Eije (T2Ti.COM)
@version 2.0
*******************************************************************************}
unit EcfConfiguracaoController;
interface
uses
Classes, SysUtils, DBClient, DB, Windows, Forms, Rtti, Atributos,
VO, EcfConfiguracaoVO, EcfPosicaoComponentesVO, Generics.Collections;
type
TEcfConfiguracaoController = class(TPersistent)
private
public
class function ConsultaObjeto(pFiltro: String): TEcfConfiguracaoVO;
class procedure GravarPosicaoComponentes(pListaPosicaoComponentes: TObjectList<TEcfPosicaoComponentesVO>);
end;
implementation
uses T2TiORM;
class function TEcfConfiguracaoController.ConsultaObjeto(pFiltro: String): TEcfConfiguracaoVO;
begin
try
Result := TT2TiORM.ConsultarUmObjeto<TEcfConfiguracaoVO>(pFiltro, True);
finally
end;
end;
class procedure TEcfConfiguracaoController.GravarPosicaoComponentes(pListaPosicaoComponentes: TObjectList<TEcfPosicaoComponentesVO>);
var
I: Integer;
PosicaoComponenteVO: TEcfPosicaoComponentesVO;
Filtro: String;
begin
try
for I := 0 to pListaPosicaoComponentes.Count - 1 do
begin
Filtro := 'ID_ECF_RESOLUCAO = ' + pListaPosicaoComponentes.Items[I].IdEcfResolucao.ToString + ' and NOME = ' + QuotedStr(pListaPosicaoComponentes.Items[I].Nome);
PosicaoComponenteVO := TT2TiORM.ConsultarUmObjeto<TEcfPosicaoComponentesVO>(Filtro, True);
if Assigned(PosicaoComponenteVO) then
begin
pListaPosicaoComponentes.Items[I].Id := PosicaoComponenteVO.Id;
if PosicaoComponenteVO.ToJSONString <> pListaPosicaoComponentes.Items[I].ToJSONString then
TT2TiORM.Alterar(pListaPosicaoComponentes.Items[I]);
FreeAndNil(PosicaoComponenteVO);
end;
end;
finally
end;
end;
initialization
Classes.RegisterClass(TEcfConfiguracaoController);
finalization
Classes.UnRegisterClass(TEcfConfiguracaoController);
end.
|
unit TestHttpClient;
interface
uses
TestFramework, HttpClient, NetHttpClient;
type
THttpClientTest = class(TTestCase)
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure GetContentByURL;
procedure RaisesAnExceptionWhenServerIsDown;
end;
implementation
{ THttpClientTest }
procedure THttpClientTest.GetContentByURL;
var
response: string;
begin
response := DefaultHttpClient.GetPageByURL('http://static.feed.rbc.ru/rbc/logical/footer/news.rss');
CheckNotEquals(0, Pos('<rss', response), 'Response doesnt contain RSS feed');
end;
procedure THttpClientTest.RaisesAnExceptionWhenServerIsDown;
begin
ExpectedException := EHttpClientException;
DefaultHttpClient.GetPageByURL('http://127.0.0.1:9919/');
end;
procedure THttpClientTest.SetUp;
begin
inherited;
DefaultHttpClient := TOwnNetHttpClient.Create;
end;
procedure THttpClientTest.TearDown;
begin
inherited;
DefaultHttpClient := nil;
end;
initialization
RegisterTest(THttpClientTest.Suite);
end.
|
unit UPF_Plugin_Loader;
uses mteFunctions;
// Init global variables:
var
// Main function:
Int_CurrentQL, Int_FilesInThisQL, Int_SigsInThisQL, Int_Loop_Main: integer;
Arr_Sigs, Arr_SigHomes, Arr_FilesInQL, Arr_SigsInQL: TStringList;
// File creation/modification:
File_CurrentQL, Entry_Decription: IInterface;
Int_LoopMasters: integer;
Arr_AddAllMasters: TStringList;
// Sig finder sub function:
Int_LoopSigs, Int_Loop_FindSigInFile: integer;
Int_CurrentSigCount, Int_BestSigPos, Int_BestSigCount: integer;
File_FindSigInFile, El_SigMaster: IInterface;
Str_BestSigFileList, StrCurrentSigFileList: string;
function Initialize: integer; begin
// Startup message:
ClearMessages();
AddMessage( ' ' );
AddMessage('===========================================================');
AddMessage(' STARTING ZEDIT PLUGIN LOADER GENERATOR');
AddMessage('===========================================================');
AddMessage( ' ' );
// Init variables:
InitSigs();
Arr_FilesInQL := TStringList.Create;
Arr_SigsInQL := TStringList.Create;
Int_CurrentQL := -1;
Quickloader_StartNext();
// Start at QL0:
for Int_Loop_Main := 0 to Pred(Arr_Sigs.Count) do begin
// Get the next best sig to add:
GetBestNextSig();
// Add to the QL:
Int_FilesInThisQL := Int_FilesInThisQL+Int_BestSigCount;
Int_SigsInThisQL := Int_SigsInThisQL+1;
if Str_BestSigFileList <> '' then
Arr_FilesInQL[Int_CurrentQL] := Arr_FilesInQL[Int_CurrentQL]+Str_BestSigFileList;
Arr_SigsInQL[Int_CurrentQL] := Arr_SigsInQL[Int_CurrentQL]+','+Arr_Sigs[Int_BestSigPos];
Arr_SigHomes[Int_BestSigPos] := Int_CurrentQL;
// Output a message showing progress:
AddMessage( ' ' + Arr_Sigs[Int_BestSigPos]+' added to Quickloader' + IntToStr(Int_CurrentQL) + ', now at ' + IntToStr(Int_SigsInThisQL) + ' sigs/' + IntToStr(Int_FilesInThisQL) + ' files.' );
end;
// Create the final QL:
Quickloader_Finish();
// Finale message:
AddMessage( ' ' );
AddMessage('===========================================================');
AddMessage(' FINISHED ZEDIT PLUGIN LOADER GENERATOR');
AddMessage('===========================================================');
end;
function Quickloader_StartNext(): null; begin
Arr_FilesInQL.Add('');
Arr_SigsInQL.Add('');
Int_CurrentQL := Int_CurrentQL+1;
Int_FilesInThisQL := 0;
Int_SigsInThisQL := 0;
end;
function Quickloader_Finish(): null; begin
// Display something to the screen:
AddMessage( ' ' );
AddMessage('-----------------------------------------------------------');
AddMessage( ' ' );
AddMessage( 'Finished calculating Quickloader' + IntToStr(Int_CurrentQL) );
AddMessage( ' ' );
AddMessage( IntToStr(Int_SigsInThisQL) + ' sigs: ' + Arr_SigsInQL[Int_CurrentQL]);
AddMessage( ' ' );
AddMessage( IntToStr(Int_FilesInThisQL) + ' files: ' + Arr_FilesInQL[Int_CurrentQL]);
AddMessage( ' ' );
// Create the file:
AddMessage( 'Creating QuickLoader plugin...' );
File_CurrentQL := FileByName('ZKVSortLoader' + IntToStr(Int_CurrentQL) + '.esp');
if GetLoadOrder(File_CurrentQL) < 0 then File_CurrentQL := AddNewFileName('ZKVSortLoader' + IntToStr(Int_CurrentQL) + '.esp',true);
AddMessage( ' ' );
// Set the description:
AddMessage( 'Setting description...' );
Entry_Decription := Add(ElementByIndex(File_CurrentQL,0), 'SNAM', false);
SetEditValue(Entry_Decription, 'ZKVSortLoader:' + Arr_SigsInQL[Int_CurrentQL]);
AddMessage( ' ' );
// Add the masters:
AddMessage( 'Adding ' + IntToStr(Int_FilesInThisQL) + ' files as masters...' );
Arr_AddAllMasters := TStringList.Create;
Arr_AddAllMasters.Delimiter := ';';
Arr_AddAllMasters.StrictDelimiter := True;
Arr_AddAllMasters.DelimitedText := Arr_FilesInQL[Int_CurrentQL];
for Int_LoopMasters := 0 to Pred(Arr_AddAllMasters.Count) do begin
if Arr_AddAllMasters[Int_LoopMasters] <> '' then
AddMasterIfMissing(File_CurrentQL,Arr_AddAllMasters[Int_LoopMasters]);
end;
AddMessage( ' ' );
// Display something to the screen:
AddMessage( 'Finished creation Quickloader' + IntToStr(Int_CurrentQL) );
AddMessage( ' ' );
AddMessage('-----------------------------------------------------------');
AddMessage( ' ' );
end;
function GetBestNextSig(): null; begin
Int_BestSigCount := 9999;
for Int_LoopSigs := 0 to Pred(Arr_Sigs.Count) do begin
// Does this signature already have a home? Move on.
if Arr_SigHomes[Int_LoopSigs] <> -1 then
Continue;
// Count files with overwriting records of this sig:
Int_CurrentSigCount:=0;
StrCurrentSigFileList:='';
for Int_Loop_FindSigInFile := 1 to Pred(FileCount) do begin
// Which file are we working with?
File_FindSigInFile := FileByIndex(Int_Loop_FindSigInFile);
// Does this file have this sig type?:
if Assigned(GroupBySignature(File_FindSigInFile,Arr_Sigs[Int_LoopSigs])) then begin
// Bail if there's no conflict here:
El_SigMaster:=ElementByIndex(GroupBySignature(File_FindSigInFile,Arr_Sigs[Int_LoopSigs]),0);
if Equals(MasterOrSelf(El_SigMaster),El_SigMaster) then
Continue;
// Still here? Valid file/sig/conflict. Take note of it and all masters:
AddFileAndMasters(Int_Loop_FindSigInFile);
end;
// Already have more files than a better alternative? Stop trying:
if Int_CurrentSigCount>Int_BestSigCount then break;
end;
// Remember this one if it's the highest homeless so far:
if (Int_CurrentSigCount<Int_BestSigCount) then begin
Int_BestSigCount:=Int_CurrentSigCount;
Int_BestSigPos:=Int_LoopSigs;
Str_BestSigFileList:=StrCurrentSigFileList;
// If it's zero or one, it's free/cheap lunch. Take it!
if Int_CurrentSigCount<2 then
exit;
end;
end;
// Did the best option bust the limit? Make a new QL:
if Int_CurrentSigCount+Int_FilesInThisQL>200 then begin
Quickloader_Finish();
Quickloader_StartNext();
end;
end;
Function AddFileAndMasters(int_FilePosToAdd: integer): null;
var
Arr_MastersList: IInterface;
Int_MasterLoop: integer;
begin
// Don't add duplicate entries:
if Pos(';' + GetFileName(FileByIndex(int_FilePosToAdd)),Arr_FilesInQL[Int_CurrentQL]+StrCurrentSigFileList) > 0 then
exit;
// Add this plug-in to the list:
Int_CurrentSigCount:=Int_CurrentSigCount+1;
StrCurrentSigFileList:=StrCurrentSigFileList+';'+GetFileName(FileByIndex(int_FilePosToAdd));
// Already have more files than a better alternative? Stop trying:
if Int_CurrentSigCount>Int_BestSigCount then exit;
// And iterate its masters, doing the same:
Arr_MastersList := ElementByPath(ElementByIndex(FileByIndex(int_FilePosToAdd),0),'Master Files');
for Int_MasterLoop := 0 to ElementCount(Arr_MastersList) - 1 do AddFileAndMasters( GetLoadOrder( FileByName( geev(ElementByIndex(Arr_MastersList, Int_MasterLoop),'MAST') ) ) + 1 );
end;
function InitSigs(): null; begin
// Define the signatures to find:
Arr_Sigs := TStringList.Create;
Arr_Sigs.Add('ALCH');
Arr_Sigs.Add('AMMO');
Arr_Sigs.Add('ARMO');
Arr_Sigs.Add('KYWD');
Arr_Sigs.Add('SPEL');
Arr_Sigs.Add('WEAP');
Arr_Sigs.Add('BOOK');
Arr_Sigs.Add('MISC');
Arr_Sigs.Add('SLGM');
// Start with no sigs having homes:
Arr_SigHomes := TStringList.Create;
for Int_LoopSigs := 0 to Pred(Arr_Sigs.Count) do begin
Arr_SigHomes.Add(-1);
end;
end;
end.
|
unit AveragingForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Math;
type
TAveraging_Form = class(TForm)
RadioGroup1: TRadioGroup;
GroupBox1: TGroupBox;
LabeledEdit2: TLabeledEdit;
LabeledEdit3: TLabeledEdit;
GroupBox2: TGroupBox;
Panel1: TPanel;
Button1: TButton;
Button2: TButton;
Edit1: TEdit;
GroupBox4: TGroupBox;
Label3: TLabel;
Label4: TLabel;
Button4: TButton;
procedure Button2Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
function Arithmetic_Average(Track_Number: Smallint):Real;
function Geometric_Average(Track_Number: Smallint):Real;
function Harmonic_Average(Track_Number: Smallint):Real;
procedure Button4Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Averaging_Form: TAveraging_Form;
Start_Depth, Stop_Depth: Single;
Track_Number: Smallint;
implementation
uses Main_Form, TeEngine, SelectLog;
{$R *.dfm}
procedure TAveraging_Form.Button2Click(Sender: TObject);
begin
Close;
end;
procedure TAveraging_Form.Button1Click(Sender: TObject);
var
Error_Code:Integer;
Temp_Value:Single;
begin
if Track_Number=-1 then
begin
MessageDlg('Please select a track for averaging!', mtError, [mbOk], 0);
Exit;
end;
Val(LabeledEdit2.Text, Temp_Value, Error_Code);
if Error_Code<>0 then
begin
MessageDlg('Please enter a valid number for start depth!', mtError, [mbOk], 0);
Exit;
end
else
Start_Depth:=Temp_Value;
Val(LabeledEdit3.Text, Temp_Value, Error_Code);
if Error_Code<>0 then
begin
MessageDlg('Please enter a valid number for stop depth!', mtError, [mbOk], 0);
Exit;
end
else
Stop_Depth:=Temp_Value;
Case RadioGroup1.ItemIndex of
0:begin
Edit1.Text:=FloatToStr(RoundTo(Arithmetic_Average(Track_Number),-8));
end;
1:begin
Edit1.Text:=FloatToStr(RoundTo(Geometric_Average(Track_Number),-8));
end;
2:begin
Edit1.Text:=FloatToStr(RoundTo(Harmonic_Average(Track_Number),-8));
end;
end;
end;
function TAveraging_Form.Arithmetic_Average(Track_Number: Smallint): Real;
var
i: Smallint;
Temp_Value: Real;
Sum_Value:Real;
Depth_Value:Real;
No_Values:Integer;
begin
try
Sum_Value:=0;
No_Values:=0;
with MainForm do
begin
for i:=0 to Charts[Track_Number].Series[0].XValues.Count-1 do
begin
Temp_Value:=Charts[Track_Number].Series[0].XValue[i];
Depth_Value:=Charts[Track_Number].Series[0].YValue[i];
if (Depth_Value>=Start_Depth)and(Depth_Value<=Stop_Depth) then
begin
if Temp_Value<>LasFiles[0].NullValue then
begin
Sum_Value:=Sum_Value+Temp_Value;
Inc(No_Values);
end;
end;
end;
if No_Values>0 then
Arithmetic_Average:=Sum_Value/No_Values
else
Arithmetic_Average:=-999;
end;
except
Arithmetic_Average:=-999;
end;
end;
function TAveraging_Form.Geometric_Average(Track_Number: Smallint): Real;
var
i: Smallint;
Temp_Value: Real;
Depth_Value:Real;
Multiplication_Value:Extended;
No_Values:Integer;
Log_Power: Smallint;
begin
try
Multiplication_Value:=1;
No_Values:=0;
Log_Power:=0;
with MainForm do
begin
Temp_Value:=Charts[Track_Number].Series[0].MaxXValue;
if Temp_value>0 then
Log_Power:=Trunc(Log10(Temp_Value));
for i:=0 to Charts[Track_Number].Series[0].XValues.Count-1 do
begin
Temp_Value:=Charts[Track_Number].Series[0].XValue[i];
Depth_Value:=Charts[Track_Number].Series[0].YValue[i];
if (Depth_Value>=Start_Depth)and(Depth_Value<=Stop_Depth) then
begin
if (Temp_Value<>LasFiles[0].NullValue)and(Temp_Value>0) then
begin
Multiplication_Value:=Multiplication_Value*Temp_Value/Power(10, Log_Power);
Inc(No_Values);
end;
end;
end;
if No_Values>0 then
Geometric_Average:=Power(Multiplication_Value,1/No_Values)*Power(10, Log_Power)
else
Geometric_Average:=-999;
end;
except
Geometric_Average:=-999;
end;
end;
function TAveraging_Form.Harmonic_Average(Track_Number: Smallint): Real;
var
i: Smallint;
Temp_Value: Real;
Depth_Value:Real;
Sum_Value:Real;
No_Values:Integer;
begin
try
Sum_Value:=0;
No_Values:=0;
with MainForm do
begin
for i:=0 to Charts[Track_Number].Series[0].XValues.Count-1 do
begin
Temp_Value:=Charts[Track_Number].Series[0].XValue[i];
Depth_Value:=Charts[Track_Number].Series[0].YValue[i];
if (Depth_Value>=Start_Depth)and(Depth_Value<=Stop_Depth) then
begin
if (Temp_Value<>LasFiles[0].NullValue)and(Temp_Value<>0) then
begin
Sum_Value:=Sum_Value+1/Temp_Value;
Inc(No_Values);
end;
end;
end;
if No_Values>0 then
Harmonic_Average:=No_Values/Sum_Value
else
Harmonic_Average:=-999;
end;
except
Harmonic_Average:=-999;
end;
end;
procedure TAveraging_Form.Button4Click(Sender: TObject);
begin
Select_Log:=TSelect_Log.Create(Self);
Select_Log.ShowModal;
Track_Number:=Select_Log.Selected_Track_Number;
if Select_Log.Selected_Track_Number<>-1 then
begin
Track_Number:=Select_Log.Selected_Track_Number;
Label4.Caption:=MainForm.Charts[Track_Number].Axes.Top.Title.Caption;
end;
Select_Log.Free;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.