text stringlengths 14 6.51M |
|---|
unit Unit1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Edit;
type
TForm1 = class(TForm)
Edit1: TEdit;
Button1: TButton;
Label1: TLabel;
Button2: TButton;
Button3: TButton;
Label2: TLabel;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses FMX.Consts;
{$R *.fmx}
const
SMsgDlgConfirm = 'Confirmação';
procedure TForm1.Button1Click(Sender: TObject);
begin
Label1.Text := 'Welcome to XE4... ' + Edit1.Text;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
ShowMessage(Label1.Text);
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
if MessageDlg('Escolha uma opção', TMsgDlgType.mtConfirmation,
[TMsgDlgBtn.mbYes, TMsgDlgBtn.mbNo], 0) = mrYes then
label2.Text := 'SIM'
else
label2.Text := 'NÃO';
end;
end.
|
unit ufrmMasterDialog;
interface
uses
Windows, Messages, SysUtils, Variants, Graphics, Controls, Forms,
Dialogs, ufraFooterDialog3Button, ExtCtrls, ActnList, System.Actions,
System.Classes, Vcl.StdCtrls, uDXUtils, uDMReport;
type
TfrmMasterDialog = class(TForm)
pnlBody: TPanel;
footerDialogMaster: TfraFooterDialog3Button;
actlstMasterDialog: TActionList;
actDelete: TAction;
actSave: TAction;
actCancel: TAction;
actPrint: TAction;
procedure actCancelExecute(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
FDialogCompany: Integer;
FDialogUnit: Integer;
TList: TStrings;
procedure Authenticate;
procedure GetAndRunButton(AButtonName: string); dynamic;
procedure GetUserModule;
protected
public
FDialogUnitCOde: string;
FDialogUnitName: string;
{ Public declarations }
FLoginFullname : string;
FLoginRole : string;
FLoginUsername : string;
FLoginId : Integer;
FLoginUnitId : Integer;
FMasterIsStore : Integer;
FLoginIsStore : Integer;
FFilePathReport : String;
procedure CetakSlip(APeriodeAwal, APeriodeAkhir: TDatetime; ANoBukti : String);
virtual;
procedure SetDialogCompany(const Value: Integer);
procedure SetDialogUnit(const Value: Integer);
property DialogCompany: Integer read FDialogCompany write SetDialogCompany;
property DialogUnit: Integer read FDialogUnit write SetDialogUnit;
end;
TMasterDlgClass = class of TfrmMasterDialog;
var
frmMasterDialog: TfrmMasterDialog;
implementation
uses udmMain, uAppUtils, uConstanta;
{$R *.dfm}
procedure TfrmMasterDialog.actCancelExecute(Sender: TObject);
begin
Self.Close;
end;
procedure TfrmMasterDialog.Authenticate;
var
i: word;
idx: integer;
begin
GetUserModule;
for i := 0 to ComponentCount-1 do
begin
if Components[i] is TAction then
begin
idx := TList.IndexOf(LowerCase(Components[i].Name));
if idx <> -1 then
(Components[i] as TAction).Enabled := true
else
(Components[i] as TAction).Enabled := false;
end;
end;
end;
procedure TfrmMasterDialog.CetakSlip(APeriodeAwal, APeriodeAkhir: TDatetime;
ANoBukti : String);
begin
end;
procedure TfrmMasterDialog.FormClose(Sender: TObject; var Action: TCloseAction);
begin
// blocke dulu, ketika berhasil simpan langsung tutup seharusny tapi malah muncul confirm
// if not TAppUtils.Confirm(CONF_VALIDATE_FOR_CLOSE) then
// begin
// Action := caNone;
// exit;
// end;
inherited;
end;
procedure TfrmMasterDialog.GetAndRunButton(AButtonName: string);
var
i,j: word;
// btnFoo: TsuiButton;
begin
for i:=0 to ComponentCount-1 do
if (Components[i] is TfraFooterDialog3Button) then
begin
for j:=0 to components[i].ComponentCount-1 do
if (components[i].Components[j].Name = AButtonName) then
begin
// btnFoo := components[i].Components[j] as TsuiButton;
// btnFoo.Click;
exit;
end;
end;
end;
procedure TfrmMasterDialog.FormCreate(Sender: TObject);
begin
TList := TStringList.Create;
FormatSettings.DecimalSeparator := '.';
FormatSettings.ThousandSeparator := ',';
FormatSettings.CurrencyString := 'Rp';
Self.AssignKeyDownEvent;
end;
procedure TfrmMasterDialog.FormKeyDown(Sender: TObject; var Key: Word; Shift:
TShiftState);
begin
//inherited
if(Key = VK_DELETE)and(ssctrl in Shift) then actDelete.Execute;
if(Key = VK_RETURN)and(ssctrl in Shift) then
begin
actSave.Execute;
Key := VK_CANCEL;
end;
if(Key = VK_ESCAPE) then
begin
If TAppUtils.Confirm('Anda yakin ingin menutup form ini?') then
actCancel.Execute;
end;
end;
procedure TfrmMasterDialog.GetUserModule;
var
sTipe: string;
sSQL : string;
strNama : string;
begin
strNama := Name;
sTipe := 'View';
sSQL := 'SELECT MOD.MOD_ACTION '
+ ' FROM AUT$MENU_STRUCTURE MS '
+ ' LEFT OUTER JOIN AUT$MENU M ON (MS.MENUS_ID = M.MENU_ID) '
+ ' AND (MS.MENUS_UNT_ID = M.MENU_UNT_ID) '
+ ' LEFT OUTER JOIN AUT$USER_GROUP UG ON (M.MENU_GRO_ID = UG.UG_GRO_ID) '
+ ' AND (M.MENU_GRO_UNT_ID = UG.UG_GRO_UNT_ID) '
+ ' LEFT OUTER JOIN AUT$USER U ON (UG.UG_USR_ID = U.USR_ID) '
+ ' AND (UG.UG_USR_UNT_ID = U.USR_UNT_ID) '
+ ' INNER JOIN AUT$MODULE MOD ON (MS.MENUS_MOD_ID = MOD.MOD_ID) '
+ ' AND (MS.MENUS_MOD_UNT_ID = MOD.MOD_UNT_ID) '
+ ' WHERE U.USR_USERNAME = '+ QuotedStr(FLoginUsername)
+ ' AND U.USR_UNT_ID = '+ IntToStr(FLoginUnitId)
+ ' AND MOD.MOD_LABEL <> ' + QuotedStr(sTipe)
+ ' AND UPPER(MOD.MOD_NAME) = ' + QuotedStr(UpperCase(strNama));
{
with dmMain.qrMultiPurpose do
begin
SQL.Text := sSQL;
Open;
while not Eof do
begin
TList.Add(LowerCase(Fields[0].AsString));
Next;
end;
end;
}
end;
procedure TfrmMasterDialog.SetDialogCompany(const Value: Integer);
begin
FDialogCompany := Value;
end;
procedure TfrmMasterDialog.SetDialogUnit(const Value: Integer);
begin
FDialogUnit := Value;
end;
end.
|
{$I-,Q-,R-,S-}
{28¦ Diga Cheese Korea 2002
----------------------------------------------------------------------
Había una vez un pedazo grande de queso, vivía en él un ácaro del
queso llamada Amelia Acaro del Queso. Amelia estaba realmente contenta
porque ella estaba rodeada por los más deliciosos quesos que ella pudo
haber comido. Sin embargo, ella sentía que había algo que le faltaba a
su vida.
Una mañana, meintras soñaba con quesos fue interrumpida por un ruido
que jamás había oido. Pero ella inmediatamente se da cuenta que esto
era el sonido de un ácaro de queso macho rullendo en el mismo pedazo
de queso! (determinando el género del ácaro del queso justo por el
sonido de esta rodeadura no es un método fácil, pero todos los ácaros
de queso lo pueden hacer. Esto es porque sus padres lo hacen).
Nada puede detener a Amelia ahora. Ella tenía que conocer lo más
pronto posible al ácaro. Por lo tanto ella tiene que encontrar el
camino más rápido para llegar al otro ácaro. Amelia puede roer
complemante un 1 mm de queso en diez segundos. Para reunirse con el
otro ácaro por el camino directo puede no ser rápido. El queso en que
Amelia vive está lleno de huecos. Estos huecos, los cuales son
burbujas de aire atrapados en el queso son esféricos para la mayor
parte. Pero ocasionalmente estos huecos esféricos se superponen,
creando huecos compuestos de todos los tipos. Pasando a través de un
hueco en el queso Amelia toma un tiempo esencialmente cero, dado que
ella puede volar desde un extremo al otro instántaneamente. Así ella
puede aprovechar viajar a través de huecos para llegar al otro ácaro
rápidamente.
Para este problema, usted escribirá un programa que dado la
localización de ambos ácaros y los huecos en el queso, determinar el
menor tiempo que se toma Amelia para alcanzar al otro ácaro. Para
resolver este problema, usted puede asumir que el queso tiene un largo
infinito. Esto es porque el queso es tan largo como nunca permita que
Amelia abandone el queso al alcanzar el otro ácaro (especialmente
puesto que el ácaro de queso comilón pueda comersela a ella). Usted
también puede asumir que el otro ácaro espera ansiosamente el arribo
de Amelia y no se moverá mientras que Amelia está en el camino.
Entrada
La entrada es mediante el fichero texto ACARO.IN con la descripción
siguiente:
. La primera línea contiene un simple entero N (0 <= N <= 100) , el
número de huecos en el queso. En las siguientes N líneas hay 4
enteros separados por un espacio en blanco cada uno Xi, Yi, Zi y Ri.
Estos describen el centro (Xi, Yi, Zi) y el radio Ri (Ri > 0) de los
huecos. Todos los valores están expresados en milímetros. La
descripción concluye con dos líneas conteniendo 3 enteros cada una.
La primera línea contiene los valores Xa, Ya y Za; la posicióm de
Amelia en el queso, la segunda línea contiene los valores Xb, Yb y
Zb las posiciones del otro ácaro.
Salida
La salida es hacia el fichero texto ACARO.OUT con una sola línea con
un solo valor entero que representa el menor tiempo en segundos que
toma Amelia en llegar al otro ácaro, redondeado al entero cercano.
Ejemplos de Entrada y Salida:
Ejemplo #1 Ejemplo #2
+------------+ +-----------+ +----------+ +-----------+
¦ ACARO.IN ¦ ¦ ACARO.OUT ¦ ¦ ACARO.IN ¦ ¦ ACARO.OUT ¦
+------------¦ +-----------¦ +----------¦ +-----------¦
¦ 1 ¦ ¦ 100 ¦ ¦ 1 ¦ ¦ 20 ¦
¦ 20 20 20 1 ¦ +-----------+ ¦ 5 0 0 4 ¦ +-----------+
¦ 0 0 0 ¦ ¦ 0 0 0 ¦
¦ 0 0 10 ¦ ¦ 10 0 0 ¦
+------------+ +----------+
}
{ Ford }
const
max = 102;
var
fe,fs : text;
n,i,j : byte;
k : real;
a : array[1..max,1..4] of integer;
cost : array[1..max,1..max] of real;
d : array[0..max] of real;
procedure open;
begin
assign(fe,'acaro.in'); reset(fe);
assign(fs,'acaro.out'); rewrite(fs);
readln(fe,n);
for i:=2 to n+1 do
readln(fe,a[i,1],a[i,2],a[i,3],a[i,4]);
readln(fe,a[1,1],a[1,2],a[1,3]);
n:=n+2;
readln(fe,a[n,1],a[n,2],a[n,3]);
close(fe);
end;
function dist(x,y,z,k,x1,y1,z1,k1 : real) : real;
var
r1,r2,r3,best : real;
begin
r1:=abs(x-x1); r2:=abs(y-y1); r3:=abs(z-z1);
best:=sqrt(sqr(r1)+sqr(r2)+sqr(r3));
best:=best-k-k1;
if best > 0 then dist:=best
else dist:=0;
end;
procedure calcula;
begin
for i:=1 to n do
for j:=1 to i-1 do
begin
k:=dist(a[i,1],a[i,2],a[i,3],a[i,4],a[j,1],a[j,2],a[j,3],a[j,4]);
cost[i,j]:=k;
cost[j,i]:=k;
end;
end;
procedure ford(ini : byte);
var
cp,ch,x : byte;
sav : array[boolean,1..max] of byte;
s : boolean;
mk : array[1..max] of boolean;
begin
d[ini]:=0; s:=true; cp:=1;
sav[s,1]:=1; ch:=0;
while cp > 0 do
begin
fillchar(mk,sizeof(mk),false);
for i:=1 to cp do
begin
x:=sav[s,i];
for j:=1 to n do
begin
k:=cost[x,j] + d[x];
if d[j] > k then
begin
d[j]:=k;
if not mk[j] then
begin
mk[j]:=true;
inc(ch);
sav[not s,ch]:=j;
end;
end;
end;
end;
cp:=ch;
ch:=0;
s:=not s;
end;
end;
procedure work;
begin
calcula;
for i:=1 to n do
d[i]:=500000;
ford(1);
end;
procedure closer;
begin
writeln(fs,d[n]*10:0:0);
close(fs);
end;
begin
open;
work;
closer;
end.
|
unit unt_server;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, process;
function ExecuteScript(AScript: string): TStringList;
function ExecuteCmd(ACmd: string): TStringList;
implementation
function Execute(AScript: string): TStringList;
const
READ_BYTES = 2048;
var
memoryStream: TMemoryStream;
proc: TProcess;
numBytes: longint;
bytesRead: longint;
cmd: string;
begin
memoryStream := TMemoryStream.Create;
bytesRead := 0;
proc := TProcess.Create(nil);
cmd := ExtractFilePath(ParamStr(0)) + 'script/' + AScript;
WriteLn(cmd);
proc.CommandLine := cmd;
proc.CurrentDirectory := ExtractFilePath(ParamStr(0));
proc.Options := [poUsePipes];
proc.Execute;
while True do
begin
memoryStream.SetSize(bytesRead + READ_BYTES);
numBytes := proc.Output.Read((memoryStream.Memory + bytesRead)^, READ_BYTES);
if numBytes > 0 then
begin
Inc(bytesRead, numBytes);
end
else
begin
Break;
end;
end;
memoryStream.SetSize(bytesRead);
Result := TStringList.Create;
Result.LoadFromStream(memoryStream);
proc.Free;
memoryStream.Free;
end;
function ExecuteScript(AScript: string): TStringList;
begin
end;
function ExecuteCmd(ACmd: string): TStringList;
var
proc: TProcess;
begin
WriteLn(ACmd);
proc := TProcess.Create(nil);
proc.CurrentDirectory := ExtractFilePath(ParamStr(0));
proc.CommandLine := ACmd;
proc.Options := [poWaitOnExit, poUsePipes];
proc.Execute;
Result := TStringList.Create;
Result.LoadFromStream(proc.Output);
proc.Free;
end;
end.
|
unit uMainForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ScrollBox,
FMX.Memo, FMX.StdCtrls, FMX.Maps, FMX.Layouts, FMX.Controls.Presentation,
System.Sensors, System.Sensors.Components, IPPeerClient, REST.Client,
Data.Bind.Components, Data.Bind.ObjectScope;
type
TForm2 = class(TForm)
TopToolBar: TToolBar;
Label1: TLabel;
BottomToolBar: TToolBar;
GridPanelLayout1: TGridPanelLayout;
SpeedButton1: TSpeedButton;
SpeedButton2: TSpeedButton;
SpeedButton3: TSpeedButton;
MapView1: TMapView;
Panel1: TPanel;
Memo1: TMemo;
LocationSensor1: TLocationSensor;
RESTClient1: TRESTClient;
RESTRequest1: TRESTRequest;
RESTResponse1: TRESTResponse;
procedure FormShow(Sender: TObject);
procedure LocationSensor1LocationChanged(Sender: TObject;
const OldLocation, NewLocation: TLocationCoord2D);
procedure SpeedButton1Click(Sender: TObject);
procedure SpeedButton2Click(Sender: TObject);
procedure SpeedButton3Click(Sender: TObject);
procedure MapView1MapClick(const Position: TMapCoordinate);
private
{ Private declarations }
procedure GetSunriseSunset(const Lat, Lng: string);
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
uses System.Threading, REST.Types;
{$R *.fmx}
procedure TForm2.FormShow(Sender: TObject);
begin
LocationSensor1.Active := True;
end;
procedure TForm2.GetSunriseSunset(const Lat, Lng: string);
var aTask: ITask;
begin
aTask := TTask.Create(
procedure ()
begin
TThread.Synchronize(nil,
procedure
begin
Form2.Memo1.Lines.Clear;
Form2.Memo1.Lines.Add('# Latitude: ' + Lat);
Form2.Memo1.Lines.Add('# Longitude: ' + Lng);
end
);
RESTRequest1.Params[0].Value := Lat;
RESTRequest1.Params[1].Value := Lng;
RESTRequest1.Params[2].Value := 'today';
RESTRequest1.Execute;
if RESTResponse1.StatusCode = 200 then
TThread.Synchronize(nil,
procedure
begin
Form2.Memo1.Lines.Add('JSONText: ');
Form2.Memo1.Lines.Add(Form2.RESTResponse1.JSONText);
end
);
end);
aTask.Start;
end;
procedure TForm2.LocationSensor1LocationChanged(Sender: TObject;
const OldLocation, NewLocation: TLocationCoord2D);
var
mCenter: TMapCoordinate;
begin
mCenter := TMapCoordinate.Create(NewLocation.Latitude, NewLocation.Longitude);
MapView1.Location := mCenter;
end;
procedure TForm2.MapView1MapClick(const Position: TMapCoordinate);
var
MyMarker: TMapMarkerDescriptor;
begin
MyMarker := TMapMarkerDescriptor.Create(Position, 'MyMarker');
MyMarker.Draggable := True;
MyMarker.Visible := True;
MapView1.AddMarker(MyMarker);
GetSunriseSunset(Position.Latitude.ToString, Position.Longitude.ToString);
end;
procedure TForm2.SpeedButton1Click(Sender: TObject);
begin
MapView1.MapType := TMapType.Normal;
end;
procedure TForm2.SpeedButton2Click(Sender: TObject);
begin
MapView1.MapType := TMapType.Satellite;
end;
procedure TForm2.SpeedButton3Click(Sender: TObject);
begin
MapView1.MapType := TMapType.Hybrid;
end;
end.
|
unit UUserDll;
(*====================================================================
User DLL access
======================================================================*)
interface
uses
{$ifdef mswindows}
Windows,
{$ELSE}
LCLIntf, LCLType, LMessages;
{$ENDIF}
var
UserCommand: procedure(hAppWnd: HWND;
pszParams: PChar;
pszPath: PChar;
pszPathInArchive: PChar;
dwTime: DWORD;
dwSize: DWORD;
dwAttrib: DWORD;
pszDescription: PChar;
pszTempFolder: PChar;
dwDiskBaseAttrib: DWORD;
pReserved: Pointer); stdcall;
function LoadUserDll(sDllPath: AnsiString): boolean;
procedure FreeUserDll();
implementation
uses UDebugLog;
var
g_hUserDll: THandle;
//-----------------------------------------------------------------------------
function LoadUserDll(sDllPath: AnsiString): boolean;
begin
{$ifdef mswindows}
Result := false;
g_hUserDll := LoadLibrary(PChar(sDllPath));
if g_hUserDll = 0 then
begin
LOG('Cannot load %s', [sDllPath]);
exit;
end;
@UserCommand := GetProcAddress(g_hUserDll, PChar('UserCommand'));
if @UserCommand = nil then
begin
LOG('Cannot loacte UserCommand in %s', [sDllPath]);
FreeUserDll();
exit;
end;
{$endif}
Result := true;
end;
//-----------------------------------------------------------------------------
procedure FreeUserDll();
begin
///FreeLibrary(g_hUserDll);
g_hUserDll := 0;
end;
//-----------------------------------------------------------------------------
begin
g_hUserDll := 0;
end.
|
unit LrTagParser;
interface
uses
SysUtils, Classes, Contnrs, LrParser;
const
idText = 0;
idTag = 1;
idSpace = 2;
idDelim = 3;
idAttr = 4;
idName = 5;
idValue = 6;
type
TLrTagToken = class(TLrParsedToken)
private
FNameCount: Integer;
protected
function GetElement: string;
function GetName: string;
function GetNamedValues(inName: string): string;
function GetNames(inIndex: Integer): string;
function GetText: string; override;
function GetValue: string;
function GetValues(inIndex: Integer): string;
procedure SetElement(const Value: string);
procedure SetName(const Value: string);
procedure SetNamedValues(inName: string; const inValue: string);
procedure SetNames(inIndex: Integer; const Value: string);
procedure SetText(const Value: string); override;
procedure SetValue(const Value: string);
procedure SetValues(inIndex: Integer; const Value: string);
protected
procedure AddToken(inKind: Integer; const inText: string);
procedure AfterParse;
procedure CountKinds;
function NameIndexToTokenIndex(inIndex: Integer): Integer;
public
constructor Create; override;
function IndexOfName(const inName: string): Integer;
function IsEndTag: Boolean;
function IsSingle: Boolean;
property Element: string read GetElement write SetElement;
property Name: string read GetName write SetName;
property NameCount: Integer read FNameCount;
property NamedValues[inName: string]: string read GetNamedValues
write SetNamedValues;
property Names[inIndex: Integer]: string read GetNames write SetNames;
property Value: string read GetValue write SetValue;
property Values[inIndex: Integer]: string read GetValues write SetValues;
end;
//
TLrTagParser = class(TLrTokenParser)
private
FNextAttrKind: Integer;
protected
procedure AttrState;
procedure SpaceState;
procedure QuoteState;
public
procedure ParseText(const inText: string); override;
end;
//
TLrTaggedDocumentParser = class(TLrTokenParser)
protected
function CreateToken(inKind: Integer = idText): TLrToken; override;
procedure TagState;
procedure TextState;
public
procedure ParseText(const inText: string); override;
end;
//
TLrTaggedDocument = class(TLrParsedToken)
private
FTag: TLrTagToken;
FTagCount: Integer;
protected
function GetTags(inIndex: Integer): TLrTagToken;
procedure SetTags(inIndex: Integer; const Value: TLrTagToken);
procedure SetTagCount(const Value: Integer);
procedure SetText(const Value: string); override;
protected
function TagIndex(inIndex: Integer): Integer;
procedure CountTags;
procedure ParseText(const inText: string);
public
function NextTag(var ioIndex: Integer): Boolean; overload;
function NextTag(var ioIndex: Integer;
out outToken: TLrTagToken): Boolean; overload;
procedure Indent(inStrings: TStrings);
property TagCount: Integer read FTagCount write SetTagCount;
property Tags[inIndex: Integer]: TLrTagToken read GetTags
write SetTags;
property Tag: TLrTagToken read FTag;
end;
const
htName = 'name';
htValue = 'value';
implementation
function IsAlpha(inChar: char): Boolean;
begin
Result := ((inChar >= 'a') and (inChar <= 'z'))
or ((inChar >= 'A') and (inChar <= 'Z'));
end;
function IsSpace(inChar: char): Boolean;
begin
Result := (inChar = ' ') or (inChar = #13) or (inChar = #10)
or (inChar = #9);
end;
{ TLrTagToken }
constructor TLrTagToken.Create;
begin
inherited;
Enabled := true;
end;
procedure TLrTagToken.AfterParse;
var
i: Integer;
begin
for i := 0 to Pred(Count) do
with Tokens[i] do
case Kind of
idSpace: FTokens[i] := nil;
idName: Text := LowerCase(Text);
idValue: Text := StringReplace(Text, '"', '', [ rfReplaceAll ]);
end;
Element := LowerCase(Element);
FTokens.Pack;
CountKinds;
end;
procedure TLrTagToken.CountKinds;
var
i: Integer;
begin
FNameCount := 0;
for i := 0 to Pred(Count) do
case Tokens[i].Kind of
idName: Inc(FNameCount);
end;
end;
function TLrTagToken.GetText: string;
var
i: Integer;
begin
// if not Enabled then
// Result := ''
// else
if Count < 3 then
Result := inherited GetText
else begin
Result := Tokens[0].Text + Tokens[1].Text;
for i := 2 to Pred(Pred(Count)) do
if Tokens[i].Kind = idValue then
Result := Result + '="' + Tokens[i].Text + '"'
else
Result := Result + ' ' + Tokens[i].Text;
Result := Result + Tokens[Count - 1].Text;
end;
end;
function TLrTagToken.GetElement: string;
begin
if Count < 2 then
Result := ''
else
Result := LowerCase(Tokens[1].Text);
end;
procedure TLrTagToken.SetElement(const Value: string);
begin
if Count > 1 then
Tokens[1].Text := Value;
end;
function TLrTagToken.IsSingle: Boolean;
begin
if Count < 3 then
Result := false
else
Result := Tokens[Count - 2].Text = '/';
end;
function TLrTagToken.IsEndTag: Boolean;
begin
Result := (Element <> '') and (Element[1] = '/');
end;
procedure TLrTagToken.SetText(const Value: string);
begin
with TLrTagParser.Create do
try
Token := Self;
ParseText(Value);
finally
Free;
end;
AfterParse;
end;
procedure TLrTagToken.AddToken(inKind: Integer; const inText: string);
var
t: TLrToken;
begin
t := TLrToken.Create;
t.Kind := inKind;
t.Text := inText;
FTokens.Insert(Count - 1, t);
end;
function TLrTagToken.IndexOfName(const inName: string): Integer;
var
i: Integer;
begin
for i := 0 to Pred(Count) do
with Tokens[i] do
if (Kind = idName) and (Text = inName) then
begin
Result := i;
exit;
end;
Result := -1;
end;
function TLrTagToken.GetNamedValues(inName: string): string;
var
i: Integer;
begin
i := IndexOfName(inName);
if (i < 0) or (i + 1 >= Count) then
Result := ''
else
Result := Tokens[i + 1].Text;
end;
procedure TLrTagToken.SetNamedValues(inName: string; const inValue: string);
var
i: Integer;
begin
i := IndexOfName(inName);
if (i < 0) then
begin
AddToken(idName, inName);
AddToken(idValue, inValue);
end
else if (i + 1 < Count) then
Tokens[i + 1].Text := inValue
else
AddToken(idValue, inValue);
end;
function TLrTagToken.NameIndexToTokenIndex(inIndex: Integer): Integer;
var
i: Integer;
begin
for i := 0 to Pred(Count) do
if (Tokens[i].Kind = idName) then
begin
if inIndex = 0 then
begin
Result := i;
exit;
end;
Dec(inIndex);
end;
Result := -1;
end;
function TLrTagToken.GetNames(inIndex: Integer): string;
var
i: Integer;
begin
i := NameIndexToTokenIndex(inIndex);
if (i < 0) then
Result := ''
else
Result := Tokens[i].Text;
end;
function TLrTagToken.GetValues(inIndex: Integer): string;
var
i: Integer;
begin
i := NameIndexToTokenIndex(inIndex);
if (i < 0) or (i + 1 >= Count)then
Result := ''
else
Result := Tokens[i + 1].Text;
end;
procedure TLrTagToken.SetNames(inIndex: Integer; const Value: string);
var
i: Integer;
begin
i := NameIndexToTokenIndex(inIndex);
if (i >= 0) then
Tokens[i].Text := Value;
end;
procedure TLrTagToken.SetValues(inIndex: Integer; const Value: string);
var
i: Integer;
begin
i := NameIndexToTokenIndex(inIndex);
if (i >= 0) and (i + 1 < Count)then
Tokens[i + 1].Text := Value;
end;
function TLrTagToken.GetName: string;
begin
Result := NamedValues[htName];
end;
function TLrTagToken.GetValue: string;
begin
Result := NamedValues[htValue];
end;
procedure TLrTagToken.SetName(const Value: string);
begin
NamedValues[htName] := Value;
end;
procedure TLrTagToken.SetValue(const Value: string);
begin
NamedValues[htValue] := Value;
end;
{ TLrTagParser }
procedure TLrTagParser.SpaceState;
begin
if (FChar = #0) then
DiscardToken
else if (FChar = '<') or (FChar = '>') then
begin
DiscardToken;
EndTokenInclude(idDelim);
end
else if (FChar = '"') then
begin
DiscardToken;
FState := QuoteState;
end
else if (FChar = '=') then
begin
DiscardToken;
DiscardChar;
if LastToken <> nil then
LastToken.Kind := idName;
FNextAttrKind := idValue;
end
else if not IsSpace(FChar) then
begin
DiscardToken;
FState := AttrState;
end;
end;
procedure TLrTagParser.AttrState;
begin
if (FChar = #0) then
begin
EndTokenNoInclude(FNextAttrKind);
end
else if (FChar = '>') then
begin
EndTokenNoInclude(FNextAttrKind);
EndTokenInclude(idDelim);
FState := SpaceState;
FNextAttrKind := idAttr;
end
else if (FChar = '"') then
begin
FState := QuoteState;
end
else if (FChar = '=') then
begin
EndTokenNoInclude(idName);
DiscardChar;
FNextAttrKind := idValue;
//FState := AttrState;
end
else if IsSpace(FChar) then
begin
EndTokenNoInclude(FNextAttrKind);
if (FNextAttrKind <> idValue) then
FNextAttrKind := idAttr;
FState := SpaceState;
end;
end;
procedure TLrTagParser.QuoteState;
begin
if (FChar = #0) then
begin
EndTokenNoInclude(FNextAttrKind);
with Token do
Tokens[Count - 1].Text := Tokens[Count - 1].Text + '"';
end
else if (FChar = '"') then
begin
EndTokenInclude(FNextAttrKind);
FNextAttrKind := idAttr;
FState := SpaceState;
end;
end;
procedure TLrTagParser.ParseText(const inText: string);
begin
FNextAttrKind := idAttr;
FState := SpaceState;
inherited;
end;
{ TLrTaggedDocumentParser }
function TLrTaggedDocumentParser.CreateToken(inKind: Integer): TLrToken;
begin
case inKind of
idTag: Result := TLrTagToken.Create;
else Result := TLrToken.Create;
end;
Result.Kind := inKind;
end;
procedure TLrTaggedDocumentParser.TagState;
begin
if (FChar = '>') or (FChar = #0) then
begin
EndTokenInclude(idTag);
FState := TextState;
end;
end;
procedure TLrTaggedDocumentParser.TextState;
begin
if (FP^ = '<') or (FChar = #0) then
begin
EndTokenNoInclude;
FState := TagState;
end;
end;
procedure TLrTaggedDocumentParser.ParseText(const inText: string);
begin
FState := TextState;
inherited;
end;
{ TLrTaggedDocument }
procedure TLrTaggedDocument.ParseText(const inText: string);
begin
with TLrTaggedDocumentParser.Create do
try
Token := Self;
ParseText(inText);
finally
Free;
end;
CountTags;
end;
procedure TLrTaggedDocument.SetText(const Value: string);
begin
//inherited;
ParseText(Value);
end;
procedure TLrTaggedDocument.CountTags;
var
i: Integer;
begin
FTagCount := 0;
for i := 0 to Pred(Count) do
if Tokens[i].Kind = idTag then
Inc(FTagCount);
end;
function TLrTaggedDocument.TagIndex(inIndex: Integer): Integer;
var
i: Integer;
begin
for i := 0 to Pred(Count) do
if Tokens[i].Kind = idTag then
begin
if inIndex = 0 then
begin
Result := i;
exit;
end;
Dec(inIndex);
end;
Result := -1;
end;
function TLrTaggedDocument.GetTags(inIndex: Integer): TLrTagToken;
var
i: Integer;
begin
i := TagIndex(inIndex);
if i < 0 then
Result := nil
else
Result := TLrTagToken(Tokens[i]);
end;
procedure TLrTaggedDocument.SetTags(inIndex: Integer;
const Value: TLrTagToken);
var
i: Integer;
begin
i := TagIndex(inIndex);
if i >= 0 then
Tokens[i] := Value;
end;
function TLrTaggedDocument.NextTag(var ioIndex: Integer;
out outToken: TLrTagToken): Boolean;
begin
outToken := nil;
while (outToken = nil) and (ioIndex < Count) do
begin
if Tokens[ioIndex].Kind = idTag then
outToken := TLrTagToken(Tokens[ioIndex]);
Inc(ioIndex);
end;
Result := (outToken <> nil);
end;
function TLrTaggedDocument.NextTag(var ioIndex: Integer): Boolean;
begin
FTag := nil;
while (FTag = nil) and (ioIndex < Count) do
begin
if Tokens[ioIndex].Kind = idTag then
FTag := TLrTagToken(Tokens[ioIndex]);
Inc(ioIndex);
end;
Result := (FTag <> nil);
end;
procedure TLrTaggedDocument.SetTagCount(const Value: Integer);
begin
FTagCount := Value;
end;
procedure TLrTaggedDocument.Indent(inStrings: TStrings);
var
stack: array of string;
indent, s: string;
sp, i: Integer;
tag: TLrTagToken;
procedure Push(const inElt: string);
begin
SetLength(stack, sp + 1);
stack[sp] := inElt;
Inc(sp);
indent := StringOfChar(' ', sp * 2);
end;
procedure Pop(const inElt: string);
begin
while (sp > 0) do
begin
Dec(sp);
if stack[sp] = inElt then
break;
end;
SetLength(stack, sp);
indent := StringOfChar(' ', sp * 2);
end;
procedure Put;
begin
s := Trim(Tokens[i].Text);
if s <> '' then
inStrings.Add(indent + s);
end;
begin
indent := '';
sp := 0;
for i := 0 to Pred(Count) do
case Tokens[i].Kind of
idSpace: ;
idTag:
begin
tag := TLrTagToken(Tokens[i]);
if tag.IsEndTag then
begin
Pop(Copy(tag.Element, 2, MAXINT));
Put;
end
else begin
Put;
if not tag.IsSingle then
Push(tag.Element);
end;
indent := StringOfChar(' ', sp * 2);
end;
else Put;
end;
end;
end.
|
unit uDM;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, IniFiles, DB, ADODB, PowerADOQuery,
LookUpADOQuery;
const
INI_FILE = 'MRPuppyTracker.ini';
type
TMRDatabase = class
private
fDatabaseName : String;
fServer : String;
fUser : String;
fPW : String;
public
property DatabaseName : String read fDatabaseName write fDatabaseName;
property Server : String read fServer write fServer;
property User : String read fUser write fUser;
property PW : String read fPW write fPW;
end;
TMRLocalDatabase = class
private
fLocalDatabaseName : String;
fLocalServer : String;
fLocalUser : String;
fLocalPW : String;
public
property LocalDatabaseName : String read fLocalDatabaseName write fLocalDatabaseName;
property LocalServer : String read fLocalServer write fLocalServer;
property LocalUser : String read fLocalUser write fLocalUser;
property LocalPW : String read fLocalPW write fLocalPW;
end;
TDM = class(TDataModule)
ADOPetConnection : TADOConnection;
quPuppy: TADODataSet;
quPuppyBreed_Code: TWideStringField;
quPuppyBreed_Name: TWideStringField;
quPuppyReference_No: TIntegerField;
quPuppyWeight: TFloatField;
quPuppyColor: TWideStringField;
quPuppyPur_Price: TBCDField;
quPuppyRegular_Price: TBCDField;
quPuppySales_Price: TBCDField;
MRDBInventoryConnection: TADOConnection;
quCmdFree: TADOCommand;
spGetNextID: TADOStoredProc;
quModel: TADODataSet;
quModelModel: TStringField;
quModelIDModel: TIntegerField;
quInvoice: TADODataSet;
quIDCustomers: TADODataSet;
quCmdFreePet: TADOCommand;
quIDCustomersCustomer_Id: TWideStringField;
quIDCustomersName: TWideStringField;
quIDCustomersFirstName: TWideStringField;
quInvoiceItem: TADODataSet;
quInvoiceItemSalePrice: TBCDField;
quInvoiceItemModel: TStringField;
quInvoiceItemInvoiceDate: TDateTimeField;
ADOPuppyHistory: TADOConnection;
quCmdFreeHistory: TADOCommand;
quMaxPuppyExport: TADODataSet;
quMaxPuppyExportExpr1000: TIntegerField;
quInvoiceItemCostPrice: TBCDField;
quListPuppyExport: TADODataSet;
quListPuppyModel: TADODataSet;
DsquListPuppyExport: TDataSource;
DsquListPuppyModel: TDataSource;
quListPuppyExportIDPuppyExport: TAutoIncField;
quListPuppyExportDateExport: TDateTimeField;
quListPuppyModelIDPuppyModel: TAutoIncField;
quListPuppyModelIDPuppyExport: TIntegerField;
quListPuppyModelPuppyModel: TWideStringField;
quListPuppyModelPuppyDescription: TWideStringField;
quListPuppyModelCostPrice: TBCDField;
quListPuppyModelSalePrice: TBCDField;
quListPuppyModelStatus: TIntegerField;
cmdInsertQty: TADOCommand;
quLookUpStore: TLookUpADOQuery;
quLookUpStoreIDStore: TIntegerField;
quLookUpStoreName: TStringField;
dsLookUpStore: TDataSource;
quLookUpCategory: TLookUpADOQuery;
dsLookUpCategory: TDataSource;
quLookUpCategoryIDGroup: TIntegerField;
quLookUpCategoryName: TStringField;
quFindCategory: TADODataSet;
quFindCategoryIDGroup: TIntegerField;
quFindCategoryName: TStringField;
quCustomers: TADODataSet;
quInvoicePessoaFirstName: TStringField;
quInvoicePessoaLastName: TStringField;
quInvoiceEndereco: TStringField;
quInvoiceCidade: TStringField;
quInvoiceIDEstado: TStringField;
quInvoiceCEP: TStringField;
quInvoiceFax: TStringField;
quInvoiceOBS: TStringField;
quInvoiceEmail: TStringField;
quInvoicePais: TStringField;
quCustomersCustomer_Id: TWideStringField;
quCustomersName: TWideStringField;
quCustomersFirstName: TWideStringField;
quCustomersZip: TWideStringField;
quDelHistoryDate: TADODataSet;
quInvoiceItemQty: TFloatField;
quPuppySex: TWideStringField;
quPuppyChip_No: TWideStringField;
quInvoiceItemModelID: TIntegerField;
quPuppySale_Price: TBCDField;
MRDBSalesConnection: TADOConnection;
quInvoiceTelefone: TStringField;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
fLocalPath : String;
fPetFile : String;
fPetExeRepFile: String;
fPetNumCop : String;
fDefaultCateg : Integer;
fDefaultStore : Integer;
fPetRepExeVer : Integer;
fUseDebug, fSaveSerialNum: Boolean;
procedure SetPetFile(aPetFile:String);
procedure SetCategory(IDCateg:Integer);
procedure SetStore(IDStore:Integer);
function GetConnection:String;
procedure SetPetExeRepFile(aPetExeRepFile:String);
procedure SetPetNumCop(aPetNumCop:String);
function GetIniFile(sSection, sKey : String):String;
procedure SetIniFileString(sSection, sKey : String; Text : String);
procedure SetPetRepExeVer(const Value: Integer);
procedure SetUseDebug(const Value: Boolean);
procedure SetSaveSerialNum(const Value: Boolean);
function GetlocalConnection: String;
public
fMRDatabase : TMRDatabase;
fMRLocalDatabase : TMRLocalDatabase;
fPetInfo : TInifile;
fDelHistory : Integer;
property LocalPath : String read fLocalPath;
property PetFile : String read fPetFile write SetPetFile;
property PetExeRepFile: String read fPetExeRepFile write SetPetExeRepFile;
property PetNumCop : String read fPetNumCop write SetPetNumCop;
property PetRepExeVer : Integer read fPetRepExeVer write SetPetRepExeVer;
property UseDebug : Boolean read fUseDebug write SetUseDebug;
property SaveSerialNum : Boolean read fSaveSerialNum write SetSaveSerialNum;
property DefaultCateg : Integer read fDefaultCateg write SetCategory;
property DefaultStore : Integer read fDefaultStore write SetStore;
property DelHistory : Integer read fDelHistory;
function PetConnectionOpen:Boolean;
function PetConnectionClose:Boolean;
function MRInventoryConnectionOpen:Boolean;
function MRInventoryConnectionClose:Boolean;
function MRSalesConnectionOpen:Boolean;
function MRSalesConnectionClose:Boolean;
function GetNextID(const sTabela: String): LongInt;
procedure RunSQL(SQL:String);
procedure RunSQL_Pet(SQL: String);
procedure RunSQL_History(SQL: String);
procedure BuildConnection;
procedure SetConnection(sServer, sDB, sUser, sPW : String);
procedure SetLocalConnection(sServer, sDB, sUser, sPW: String);
function GetSalesPerson(Invoice: String): String;
end;
var
DM: TDM;
implementation
uses uEncryptFunctions;
{$R *.dfm}
{ TDM }
function TDM.PetConnectionClose: Boolean;
begin
with ADOPetConnection do
if Connected then
try
Close;
Result := True;
except
on E: Exception do
begin
Result := False;
ShowMessage(E.Message);
end;
end;
end;
function TDM.PetConnectionOpen: Boolean;
begin
with ADOPetConnection do
if not Connected then
try
ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source='+fPetFile+';Persist Security Info=False';
Open;
Result := True;
except
on E: Exception do
begin
Result := False;
ShowMessage(E.Message);
end;
end;
end;
procedure TDM.DataModuleCreate(Sender: TObject);
begin
fMRDatabase := TMRDatabase.Create;
fMRLocalDatabase := TMRLocalDatabase.Create;
fLocalPath := ExtractFilePath(Application.ExeName);
fPetInfo := TIniFile.Create(fLocalPath + INI_FILE);
fPetFile := fPetInfo.ReadString('PetSetting', 'FilePath', '');
fPetExeRepFile := fPetInfo.ReadString('PetSetting', 'FileExeRepPath', '');
fPetNumCop := fPetInfo.ReadString('PetSetting', 'FileNumCop', '');
BuildConnection;
fDefaultCateg := fPetInfo.ReadInteger('Defaults', 'IDCategory', 1);
fPetRepExeVer := fPetInfo.ReadInteger('PetSetting', 'ExeRepVer', 1);
fDefaultStore := fPetInfo.ReadInteger('Defaults', 'IDStore', 1);
fDelHistory := fPetInfo.ReadInteger('History', 'ClearDays', 1);
fUseDebug := fPetInfo.ReadBool('Defaults', 'UseDebug', true);
fSaveSerialNum := fPetInfo.ReadBool('Defaults', 'SaveSerialNum', true);
ADOPuppyHistory.ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source='+fLocalPath+'PuppyHistory.mdb'+';Persist Security Info=False';
ADOPuppyHistory.Open;
quListPuppyExport.Open;
quListPuppyModel.Open;
end;
procedure TDM.DataModuleDestroy(Sender: TObject);
begin
FreeAndNil(fPetInfo);
FreeAndNil(fMRDatabase);
FreeAndNil(fMRlocalDatabase);
end;
procedure TDM.SetPetFile(aPetFile: String);
begin
fPetFile := aPetFile;
fPetInfo.WriteString('PetSetting', 'FilePath', aPetFile);
end;
function TDM.MRInventoryConnectionClose: Boolean;
begin
with MRDBInventoryConnection do
if Connected then
try
Close;
Result := True;
except
on E: Exception do
begin
Result := False;
ShowMessage(E.Message);
end;
end;
end;
function TDM.MRInventoryConnectionOpen: Boolean;
begin
with MRDBInventoryConnection do
if not Connected then
try
ConnectionString := GetConnection;
Open;
Result := True;
except
on E: Exception do
begin
Result := False;
ShowMessage(E.Message);
end;
end;
end;
function TDM.GetConnection: String;
begin
Result := 'Provider=SQLOLEDB.1;Password='+fMRDatabase.PW+';Persist Security Info=True;'+
'User ID='+fMRDatabase.User+';Initial Catalog='+fMRDatabase.DatabaseName+
';Data Source='+fMRDatabase.Server+';Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=DESENV001;Use Encryption for Data=False;Tag with column collation when possible=False';
end;
function TDM.GetlocalConnection: String;
begin
Result := 'Provider=SQLOLEDB.1;Password='+fMRLocalDatabase.LocalPW+';Persist Security Info=True;'+
'User ID='+fMRLocalDatabase.LocalUser+';Initial Catalog='+fMRLocalDatabase.LocalDatabaseName+
';Data Source='+fMRLocalDatabase.LocalServer+';Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=DESENV001;Use Encryption for Data=False;Tag with column collation when possible=False';
end;
function TDM.GetNextID(const sTabela: String): LongInt;
begin
with spGetNextID do
begin
Parameters.ParamByName('@Tabela').Value := sTabela;
ExecProc;
Result := Parameters.ParamByName('@NovoCodigo').Value;
end;
end;
procedure TDM.RunSQL(SQL: String);
begin
with quCmdFree do
begin
CommandText := SQL;
Execute;
end;
end;
procedure TDM.SetCategory(IDCateg: Integer);
begin
fDefaultCateg := IDCateg;
fPetInfo.WriteInteger('Defaults', 'IDCategory', IDCateg);
end;
procedure TDM.SetStore(IDStore: Integer);
begin
fDefaultStore := IDStore;
fPetInfo.WriteInteger('Defaults', 'IDStore', IDStore);
end;
procedure TDM.RunSQL_PET(SQL: String);
begin
with quCmdFreePet do
begin
CommandText := SQL;
Execute;
end;
end;
procedure TDM.RunSQL_History(SQL: String);
begin
with quCmdFreeHistory do
begin
CommandText := SQL;
Execute;
end;
end;
procedure TDM.BuildConnection;
begin
fMRDatabase.DatabaseName := DecodeServerInfo(GetIniFile('MRSetting','Database'), 'Database', CIPHER_TEXT_STEALING, FMT_UU);
fMRDatabase.Server := DecodeServerInfo(GetIniFile('MRSetting','Server'), 'Server', CIPHER_TEXT_STEALING, FMT_UU);
fMRDatabase.User := DecodeServerInfo(GetIniFile('MRSetting','User'), 'User', CIPHER_TEXT_STEALING, FMT_UU);
fMRDatabase.PW := DecodeServerInfo(GetIniFile('MRSetting','PW'), 'PW', CIPHER_TEXT_STEALING, FMT_UU);
fMRLocalDatabase.LocalDatabaseName := DecodeServerInfo(GetIniFile('MRSetting','LocalDatabase'), 'LocalDatabase', CIPHER_TEXT_STEALING, FMT_UU);
fMRLocalDatabase.LocalServer := DecodeServerInfo(GetIniFile('MRSetting','LocalServer'), 'LocalServer', CIPHER_TEXT_STEALING, FMT_UU);
fMRLocalDatabase.LocalUser := DecodeServerInfo(GetIniFile('MRSetting','LocalUser'), 'LocalUser', CIPHER_TEXT_STEALING, FMT_UU);
fMRLocalDatabase.LocalPW := DecodeServerInfo(GetIniFile('MRSetting','LocalPW'), 'LocalPW', CIPHER_TEXT_STEALING, FMT_UU);
end;
procedure TDM.SetPetExeRepFile(aPetExeRepFile: String);
begin
fPetExeRepFile := aPetExeRepFile;
fPetInfo.WriteString('PetSetting', 'FileExeRepPath', aPetExeRepFile);
end;
procedure TDM.SetPetNumCop(aPetNumCop: String);
begin
fPetNumCop := aPetNumCop;
fPetInfo.WriteString('PetSetting', 'FileNumCop', aPetNumCop);
end;
procedure TDM.SetConnection(sServer, sDB, sUser, sPW: String);
begin
sDB := EncodeServerInfo(sDB, 'Database', CIPHER_TEXT_STEALING, FMT_UU);
sServer := EncodeServerInfo(sServer, 'Server', CIPHER_TEXT_STEALING, FMT_UU);
sUser := EncodeServerInfo(sUser, 'User', CIPHER_TEXT_STEALING, FMT_UU);
sPW := EncodeServerInfo(sPW, 'PW', CIPHER_TEXT_STEALING, FMT_UU);
SetIniFileString('MRSetting','Database', sDB);
SetIniFileString('MRSetting','Server', sServer);
SetIniFileString('MRSetting','User', sUser);
SetIniFileString('MRSetting','PW', sPW);
BuildConnection;
end;
procedure TDM.SetLocalConnection(sServer, sDB, sUser, sPW: String);
begin
sDB := EncodeServerInfo(sDB, 'LocalDatabase', CIPHER_TEXT_STEALING, FMT_UU);
sServer := EncodeServerInfo(sServer, 'LocalServer', CIPHER_TEXT_STEALING, FMT_UU);
sUser := EncodeServerInfo(sUser, 'LocalUser', CIPHER_TEXT_STEALING, FMT_UU);
sPW := EncodeServerInfo(sPW, 'LocalPW', CIPHER_TEXT_STEALING, FMT_UU);
SetIniFileString('MRSetting','LocalDatabase', sDB);
SetIniFileString('MRSetting','LocalServer', sServer);
SetIniFileString('MRSetting','LocalUser', sUser);
SetIniFileString('MRSetting','LocalPW', sPW);
BuildConnection;
end;
function TDM.GetIniFile(sSection, sKey: String): String;
begin
Result := fPetInfo.ReadString(sSection, sKey, '');
end;
procedure TDM.SetIniFileString(sSection, sKey, Text: String);
begin
fPetInfo.WriteString(sSection, sKey, Text);
end;
procedure TDM.SetPetRepExeVer(const Value: Integer);
begin
fPetRepExeVer := Value;
fPetInfo.WriteInteger('PetSetting', 'ExeRepVer', fPetRepExeVer);
end;
procedure TDM.SetUseDebug(const Value: Boolean);
begin
fUseDebug := Value;
fPetInfo.WriteBool('Defaults', 'UseDebug', fUseDebug);
end;
function TDM.GetSalesPerson(Invoice :String): String;
var
qrySalesPerson : TADOQuery;
begin
qrySalesPerson := TADOQuery.Create(self);
try
with qrySalesPerson do
begin
qrySalesPerson.Connection := MRDBSalesConnection;
SQL.Text := 'SELECT '+
' TOP 1 P.Pessoa '+
'FROM '+
' Invoice I (NOLOCK) '+
' JOIN vw_Rep_InventoryMov IMV (NOLOCK) ON (I.IDInvoice = IMV.IDDocument and IMV.IDInventMovType = 1) '+
' JOIN Model M (NOLOCK) ON (IMV.IDModel = M.IDModel) '+
' JOIN TabGroup TB (NOLOCK) ON (M.GroupID = TB.IDGroup) '+
' JOIN Pessoa P (NOLOCK) ON (P.IDPESSOA = IMV.IDComission) '+
'WHERE '+
' I.IDInvoice = ' + Invoice +
' AND '+
' TB.PuppyTracker = 1 ';
Open;
Result := copy(FieldByName('Pessoa').AsString,1,50);
end;
finally
FreeAndNil(qrySalesPerson);
end;
end;
procedure TDM.SetSaveSerialNum(const Value: Boolean);
begin
fSaveSerialNum := Value;
fPetInfo.WriteBool('Defaults', 'SaveSerialNum', fSaveSerialNum);
end;
function TDM.MRSalesConnectionClose: Boolean;
begin
with MRDBSalesConnection do
if Connected then
try
Close;
Result := True;
except
on E: Exception do
begin
Result := False;
ShowMessage(E.Message);
end;
end;
end;
function TDM.MRSalesConnectionOpen: Boolean;
begin
with MRDBSalesConnection do
if not Connected then
try
ConnectionString := GetLocalConnection;
Open;
Result := True;
except
on E: Exception do
begin
Result := False;
ShowMessage(E.Message);
end;
end;
end;
end.
|
unit uNewPajak;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, uTSBaseClass,
uNewUnit, DB;
type
TNewPajak = class(TSBaseClass)
private
FID: string;
FIsDefault: Integer;
FKode: string;
FNama: string;
FPPN: Double;
FPPNBM: Double;
function FLoadFromDB( aSQL : String ): Boolean;
public
constructor Create(aOwner : TComponent); override;
destructor Destroy; override;
procedure ClearProperties;
function ExecuteCustomSQLTask: Boolean;
function ExecuteCustomSQLTaskPrior: Boolean;
function CustomTableName: string;
function GenerateInterbaseMetaData: Tstrings;
function ExecuteGenerateSQL: Boolean;
function GetFieldNameFor_ID: string; dynamic;
function GetFieldNameFor_IsDefault: string; dynamic;
function GetFieldNameFor_Kode: string; dynamic;
function GetFieldNameFor_Nama: string; dynamic;
function GetFieldNameFor_PPN: string; dynamic;
function GetFieldNameFor_PPNBM: string; dynamic;
function GetGeneratorName: string;
function GetHeaderFlag: Integer;
function LoadByID(aID: string): Boolean;
function LoadByKode(aKode: string): Boolean;
function RemoveFromDB: Boolean;
procedure UpdateData(aID: string; aIsDefault: Integer; aKode, aNama: string;
aPPN, aPPNBM: Double);
property ID: string read FID write FID;
property IsDefault: Integer read FIsDefault write FIsDefault;
property Kode: string read FKode write FKode;
property Nama: string read FNama write FNama;
property PPN: Double read FPPN write FPPN;
property PPNBM: Double read FPPNBM write FPPNBM;
end;
function GetDataPajak(unt:Integer): TDataSet;
function GetListPajakByUnitId(aUnit_ID: Integer=0): TDataSet;
function GetDefaultPajak(aUnit_ID: Integer=0): string;
implementation
uses FireDAC.Comp.Client, FireDAC.Stan.Error, udmMain;
function GetDataPajak(unt:Integer): TDataSet;
var
SQL_GET_LIST_PAJAK, SQL_GET_LIST_PAJAK_BY_UNT: String;
begin
if unt=0 then
begin
SQL_GET_LIST_PAJAK :=
'SELECT PJK_ID,PJK_CODE,PJK_NAME,PJK_PPN,PJK_PPNBM ' +
'FROM REF$PAJAK ' +
' ORDER BY PJK_CODE';
Result := cOpenQuery(SQL_GET_LIST_PAJAK);
end
else
begin
SQL_GET_LIST_PAJAK_BY_UNT :=
'SELECT PJK_ID,PJK_CODE,PJK_NAME,PJK_PPN,PJK_PPNBM ' +
'FROM REF$PAJAK ' +
' ORDER BY PJK_CODE';
Result := cOpenQuery(SQL_GET_LIST_PAJAK_BY_UNT);
end;
end;
function GetListPajakByUnitId(aUnit_ID: Integer=0): TDataSet;
var
sSQL: String;
begin
sSQL :=
'SELECT PJK_ID, PJK_CODE, PJK_NAME, PJK_PPN FROM REF$PAJAK ';
Result := cOpenQuery(sSQL);
end;
function GetDefaultPajak(aUnit_ID: Integer=0): string;
var aSQL: String;
begin
aSQL :=
'SELECT PJK.PJK_NAME FROM REF$PAJAK PJK ' +
'WHERE PJK.PJK_IS_DEFAULT = 1 ';
Result := cOpenQuery(aSQL).FieldByName('PJK_NAME').AsString;
end;
{
******************************* TNewBarangPajak ********************************
}
constructor TNewPajak.Create(aOwner : TComponent);
begin
inherited create(aOwner);
ClearProperties;
end;
destructor TNewPajak.Destroy;
begin
inherited Destroy;
end;
procedure TNewPajak.ClearProperties;
begin
ID := '';
IsDefault := 0;
Kode := '';
Nama := '';
PPN := 0;
PPNBM := 0;
end;
function TNewPajak.ExecuteCustomSQLTask: Boolean;
begin
result := True;
end;
function TNewPajak.ExecuteCustomSQLTaskPrior: Boolean;
begin
result := True;
end;
function TNewPajak.CustomTableName: string;
begin
result := 'REF$PAJAK';
end;
function TNewPajak.FLoadFromDB( aSQL : String ): Boolean;
begin
result := false;
State := csNone;
ClearProperties;
with cOpenQuery(aSQL) do
Begin
if not EOF then
begin
FID := FieldByName(GetFieldNameFor_ID).AsString;
FIsDefault := FieldByName(GetFieldNameFor_IsDefault).asInteger;
FKode := FieldByName(GetFieldNameFor_Kode).asString;
FNama := FieldByName(GetFieldNameFor_Nama).asString;
FPPN := FieldByName(GetFieldNameFor_PPN).asFloat;
FPPNBM := FieldByName(GetFieldNameFor_PPNBM).asFloat;
Self.State := csLoaded;
Result := True;
end;
Free;
End;
end;
function TNewPajak.GenerateInterbaseMetaData: Tstrings;
begin
result := TstringList.create;
result.Append( '' );
result.Append( 'Create Table TNewBarangPajak ( ' );
result.Append( 'TRMSBaseClass_ID Integer not null, ' );
result.Append( 'ID Integer Not Null Unique, ' );
result.Append( 'IsDefault Integer Not Null , ' );
result.Append( 'Kode Varchar(30) Not Null Unique, ' );
result.Append( 'Nama Varchar(30) Not Null , ' );
result.Append( 'NewUnit_ID Integer Not Null, ' );
result.Append( 'PPN double precision Not Null , ' );
result.Append( 'PPNBM double precision Not Null , ' );
result.Append( 'Stamp TimeStamp ' );
result.Append( ' ); ' );
end;
function TNewPajak.ExecuteGenerateSQL: Boolean;
var
S: string;
begin
result := False;
// DecimalSeparator := '.';
if State = csNone then
Begin
raise Exception.create('Tidak bisa generate dalam Mode csNone')
end;
if not ExecuteCustomSQLTaskPrior then
begin
cRollbackTrans;
Exit;
end
else begin
// If FID <= 0 then
If FID = '' then
begin
// FID := cGetNextID(GetFieldNameFor_ID, CustomTableName);
fid := cGetNextIDGUIDToString;
S := 'Insert into ' + CustomTableName
+ ' ( ' + GetFieldNameFor_ID
+ ', ' + GetFieldNameFor_IsDefault
+ ', ' + GetFieldNameFor_Kode
+ ', ' + GetFieldNameFor_Nama
+ ', ' + GetFieldNameFor_PPN
+ ', ' + GetFieldNameFor_PPNBM
+ ') values ('
+ QuotedStr( FID) + ', '
+ IntToStr( FIsDefault) + ', '
+ QuotedStr(FKode ) + ','
+ QuotedStr(FNama ) + ','
+ FormatFloat('0.00', FPPN) + ', '
+ FormatFloat('0.00', FPPNBM) + ');'
end else
begin
S := 'Update ' + CustomTableName + ' set ' + GetFieldNameFor_Kode + ' = ' + QuotedStr(FKode)
+ ' , ' + GetFieldNameFor_IsDefault + ' = ' + IntToStr( FIsDefault)
+ ' , ' + GetFieldNameFor_Kode + ' = ' + QuotedStr( FKode )
+ ' , ' + GetFieldNameFor_Nama + ' = ' + QuotedStr( FNama )
+ ' , ' + GetFieldNameFor_PPN + ' = ' + FormatFloat('0.00', FPPN)
+ ' , ' + GetFieldNameFor_PPNBM + ' = ' + FormatFloat('0.00', FPPNBM)
+ ' Where ' + GetFieldNameFor_ID + ' = ' + QuotedStr(FID)
+ ';';
end;
if not cExecSQL(S, dbtPOS, False) then
begin
cRollbackTrans;
Exit;
end
else
Result := ExecuteCustomSQLTask;
end;
end;
function TNewPajak.GetFieldNameFor_ID: string;
begin
// Result := 'PJK_ID';// <<-- Rubah string ini untuk mapping
Result := 'REF$PAJAK_ID';
end;
function TNewPajak.GetFieldNameFor_IsDefault: string;
begin
Result := 'PJK_IS_DEFAULT';// <<-- Rubah string ini untuk mapping
end;
function TNewPajak.GetFieldNameFor_Kode: string;
begin
Result := 'PJK_CODE';// <<-- Rubah string ini untuk mapping
end;
function TNewPajak.GetFieldNameFor_Nama: string;
begin
Result := 'PJK_NAME';// <<-- Rubah string ini untuk mapping
end;
function TNewPajak.GetFieldNameFor_PPN: string;
begin
Result := 'PJK_PPN';// <<-- Rubah string ini untuk mapping
end;
function TNewPajak.GetFieldNameFor_PPNBM: string;
begin
Result := 'PJK_PPNBM';// <<-- Rubah string ini untuk mapping
end;
function TNewPajak.GetGeneratorName: string;
begin
Result := 'gen_ref$pajak_id ';
end;
function TNewPajak.GetHeaderFlag: Integer;
begin
result := 1425;
end;
function TNewPajak.LoadByID(aID: string): Boolean;
begin
result := FloadFromDB('Select * from ' + CustomTableName
+ ' Where ' + GetFieldNameFor_ID + ' = ' + QuotedStr(aID));
end;
function TNewPajak.LoadByKode(aKode: string): Boolean;
begin
result := FloadFromDB('Select * from ' + CustomTableName
+ ' Where ' + GetFieldNameFor_Kode + ' = ' + QuotedStr(aKode));
end;
function TNewPajak.RemoveFromDB: Boolean;
var
sSQL: string;
begin
Result := False ;
sSQL := ' delete from ' + CustomTableName
+ ' where ' + GetFieldNameFor_ID + ' = ' + QuotedStr(ID);
if cExecSQL(sSQL,dbtPOS, False) then
Result := True; //SimpanBlob(sSQL,GetHeaderFlag);
end;
procedure TNewPajak.UpdateData(aID: string; aIsDefault: Integer; aKode, aNama:
string; aPPN, aPPNBM: Double);
begin
FID := aID;
FIsDefault := aIsDefault;
FKode := trim(aKode);
FNama := trim(aNama);
FPPN := aPPN;
FPPNBM := aPPNBM;
State := csCreated;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLWindowsFont<p>
TFont Import into a BitmapFont using variable width...<p>
<b>History : </b><font size=-1><ul>
<li>25/01/10 - Yar - Bugfix in LoadWindowsFont with zero width of char
(thanks olkondr)
Replace Char to AnsiChar
<li>11/11/09 - DaStr - Added Delphi 2009 compatibility (thanks mal)
<li>17/03/07 - DaStr - Dropped Kylix support in favor of FPC (BugTracekrID=1681585)
<li>12/15/04 - Eugene Kryukov - Added TGLStoredBitmapFont
<li>03/07/04 - LR - Added ifdef for Graphics uses
<li>29/09/02 - EG - Fixed transparency, style fixes, prop defaults fixed,
dropped interface dependency, texture size auto computed,
fixed italics spacing, uses LUM+ALPHA texture
<li>06/09/02 - JAJ - Fixed alot of bugs... Expecially designtime updating bugs..
<li>12/08/02 - JAJ - Made into a standalone unit...
</ul></font>
}
unit GLWindowsFont;
interface
{$include GLScene.inc}
uses
GLBitmapFont, Classes, GLScene, GLTexture, Graphics, GLCrossPlatform;
type
// TGLWindowsBitmapFont
//
{: A bitmap font automatically built from a TFont.<p>
It works like a TGLBitmapfont, you set ranges and which chars are assigned
to which indexes, however here you also set the Font property to any TFont
available to the system and it renders in GLScene as close to that font
as posible, on some font types this is 100% on some a slight difference
in spacing can occur at most 1 pixel per char on some char combinations.<p>
Ranges must be sorted in ascending ASCII order and should not overlap.
As the font texture is automatically layed out, the Ranges StartGlyphIdx
property is ignored and replaced appropriately. }
TGLWindowsBitmapFont = class (TGLCustomBitmapFont)
private
{ Private Declarations }
FFont : TFont;
protected
{ Protected Declarations }
procedure SetFont(value : TFont);
procedure LoadWindowsFont; virtual;
function StoreRanges : Boolean;
procedure PrepareImage; override;
function TextureFormat : Integer; override;
public
{ Public Declarations }
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure NotifyChange(Sender : TObject); override;
function FontTextureWidth : Integer;
function FontTextureHeight : Integer;
property Glyphs;
published
{ Published Declarations }
{: The font used to prepare the texture.<p>
Note: the font color is ignored. }
property Font : TFont read FFont write SetFont;
property MagFilter;
property MinFilter;
property Ranges stored StoreRanges;
end;
{: Inheritance from TGLWindowsBitmapFont which can load from file.<p>
}
TGLStoredBitmapFont = class (TGLWindowsBitmapFont)
private
FLoaded: boolean;
protected
public
{ Public Declarations }
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure NotifyChange(Sender : TObject); override;
procedure LoadWindowsFont; override;
procedure LoadFromFile(AFileName: string);
procedure SaveToFile(AFileName: string);
published
{ Published Declarations }
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
uses SysUtils, GLVectorGeometry, OpenGL1x, OpenGLTokens, ApplicationFileIO;
// ------------------
// ------------------ TGLWindowsBitmapFont ------------------
// ------------------
// Create
//
constructor TGLWindowsBitmapFont.Create(AOwner: TComponent);
begin
inherited;
FFont:=TFont.Create;
FFont.Color:=clWhite;
FFont.OnChange:=NotifyChange;
GlyphsAlpha:=tiaAlphaFromIntensity;
Ranges.Add(' ', '}');
LoadWindowsFont;
end;
// Destroy
//
destructor TGLWindowsBitmapFont.Destroy;
begin
FFont.Free;
inherited;
end;
// FontTextureWidth
//
function TGLWindowsBitmapFont.FontTextureWidth : Integer;
begin
Result:=Glyphs.Width;
end;
// FontTextureHeight
//
function TGLWindowsBitmapFont.FontTextureHeight : Integer;
begin
Result:=Glyphs.Height;
end;
// SetFont
//
procedure TGLWindowsBitmapFont.SetFont(value: TFont);
begin
FFont.Assign(value);
end;
// NotifyChange
//
procedure TGLWindowsBitmapFont.NotifyChange(Sender : TObject);
begin
FreeTextureHandle;
InvalidateUsers;
inherited;
end;
// LoadWindowsFont
//
procedure TGLWindowsBitmapFont.LoadWindowsFont;
var
textureWidth, textureHeight : Integer;
function ComputeCharRects(x, y : Integer; canvas : TCanvas) : Integer;
var
px, py, cw, n : Integer;
rect : TGLRect;
begin
Result:=0;
n:=0;
px:=0;
py:=0;
while n < GLS_FONT_CHARS_COUNT do begin
cw:=CharWidths[n];
if cw>0 then begin
Inc(cw, 2);
if Assigned(canvas) then begin
SetCharRects(n, VectorMake((px+1.05)/textureWidth,
(textureHeight-(py+0.05))/textureHeight,
(px+cw-1.05)/textureWidth,
(textureHeight-(py+CharHeight-0.05))/textureHeight));
rect.Left:=px;
rect.Top:=py;
rect.Right:=px+cw;
rect.Bottom:=py+CharHeight;
// Draw the Char, the trailing space is to properly handle the italics.
canvas.TextRect(rect, px+1, py+1, AnsiChar(n)+' ');
end;
if ((n < GLS_FONT_CHARS_COUNT - 1) and (px+cw+CharWidths[n+1]+2<=x)) or (n = GLS_FONT_CHARS_COUNT - 1) then
Inc(px, cw)
else begin
px:=0;
Inc(py, CharHeight);
if py+CharHeight>y then Break;
end;
Inc(Result);
end;
Inc(n);
end;
end;
var
bitmap : TGLBitMap;
fontRange : TBitmapFontRange;
ch : AnsiChar;
x, y, i, cw : Integer;
nbChars, n : Integer;
texMem, bestTexMem : Integer;
begin
InvalidateUsers;
bitmap:=Glyphs.Bitmap;
Glyphs.OnChange:=nil;
bitmap.PixelFormat:=glpf32bit;
with bitmap.Canvas do begin
Font:=Self.Font;
Font.Color:=clWhite;
// get characters dimensions for the font
CharWidth:=Round(2+MaxInteger(TextWidth('M'), TextWidth('W'), TextWidth('_')));
CharHeight:=2+TextHeight('"_pI|,');
if fsItalic in Font.Style then begin
// italics aren't properly acknowledged in font width
HSpaceFix:=-(CharWidth div 3);
CharWidth:=CharWidth-HSpaceFix;
end else HSpaceFix:=0;
end;
nbChars:=Ranges.CharacterCount;
// Retrieve width of all characters (texture width)
ResetCharWidths(0);
for i:=0 to Ranges.Count-1 do
begin
fontRange:=Ranges.Items[i];
for ch:=fontRange.StartASCII to fontRange.StopASCII do
begin
cw:=bitmap.Canvas.TextWidth(ch)-HSpaceFix;
SetCharWidths(Integer(ch), cw);
if cw=0 then
Dec(nbChars);
end;
end;
// compute texture size: look for best fill ratio
// and as square a texture as possible
bestTexMem:=MaxInt;
textureWidth:=0;
textureHeight:=0;
y:=64; while y<=512 do begin
x:=64; while x<=512 do begin
// compute the number of characters that fit
n:=ComputeCharRects(x, y, nil);
if n=nbChars then begin
texMem:=x*y;
if (texMem<bestTexMem) or ((texMem=bestTexMem) and (Abs(x-y)<Abs(textureWidth-textureHeight))) then begin
textureWidth:=x;
textureHeight:=y;
bestTexMem:=texMem;
end;
end;
x:=2*x;
end;
y:=y*2;
end;
if bestTexMem=MaxInt then begin
Font.Size:=6;
raise Exception.Create('Characters are too large or too many. Unable to create font texture.');
end;
bitmap.Width:=textureWidth;
bitmap.Height:=textureHeight;
with bitmap.Canvas do
begin
Brush.Style:=bsSolid;
Brush.Color:=clBlack;
FillRect(Rect(0, 0, textureWidth, textureHeight));
end;
ComputeCharRects(textureWidth, textureHeight, bitmap.Canvas);
Glyphs.OnChange:=OnGlyphsChanged;
end;
// StoreRanges
//
function TGLWindowsBitmapFont.StoreRanges : Boolean;
begin
Result:=(Ranges.Count<>1) or (Ranges[0].StartASCII<>' ') or (Ranges[0].StopASCII<>'}');
end;
// PrepareImage
//
procedure TGLWindowsBitmapFont.PrepareImage;
begin
LoadWindowsFont;
inherited;
end;
// TextureFormat
//
function TGLWindowsBitmapFont.TextureFormat : Integer;
begin
Result:=GL_ALPHA;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
{ TGLStoredBitmapFont }
constructor TGLStoredBitmapFont.Create(AOwner: TComponent);
begin
inherited;
end;
destructor TGLStoredBitmapFont.Destroy;
begin
inherited;
end;
procedure TGLStoredBitmapFont.NotifyChange(Sender: TObject);
begin
inherited;
end;
procedure TGLStoredBitmapFont.LoadFromFile(AFileName: string);
var
S: TStream;
Count, i: integer;
F1, F2, F3, F4: single;
I1: integer;
Bmp: TBitmap;
begin
if FileStreamExists(AFileName) then
begin
S := CreateFileStream(AFileName, fmOpenRead);
try
FLoaded := true;
{ Load Glyphs }
Bmp := TBitmap.Create;
Bmp.LoadFromStream(S);
Glyphs.Assign(Bmp);
Bmp.Free;
FreeTextureHandle;
InvalidateUsers;
{ Load font settings }
// char props
S.Read(I1, SizeOf(CharWidth));
CharWidth := I1;
S.Read(I1, SizeOf(CharHeight));
CharHeight := I1;
// char rects
S.Read(Count, SizeOf(Count));
SetLength(FCharRects, Count);
for i := 0 to High(FCharRects) do
begin
S.Read(F1, SizeOf(FCharRects[i][0]));
S.Read(F2, SizeOf(FCharRects[i][1]));
S.Read(F3, SizeOf(FCharRects[i][2]));
S.Read(F4, SizeOf(FCharRects[i][3]));
SetCharRects(i, VectorMake(F1, F2, F3, F4));
end;
// char wds
S.Read(Count, SizeOf(Count));
for i := 0 to High(CharWidths) do
begin
S.Read(I1, SizeOf(CharWidths[i]));
SetCharWidths(i, I1);
end;
finally
S.Free;
end;
end;
end;
procedure TGLStoredBitmapFont.SaveToFile(AFileName: string);
var
S: TStream;
i, Count: integer;
Bmp: TBitmap;
begin
if Glyphs.Graphic = nil then Exit;
S := CreateFileStream(AFileName, fmCreate);
try
{ Save glyphs }
Bmp := TBitmap.Create;
Bmp.Assign(Glyphs.Graphic);
Bmp.SaveToStream(S);
Bmp.Free;
{ Save settings }
// char props
S.Write(CharWidth, SizeOf(CharWidth));
S.Write(CharHeight, SizeOf(CharHeight));
// char rects
Count := Length(FCharRects);
S.Write(Count, SizeOf(Count));
for i := 0 to High(FCharRects) do
begin
S.Write(FCharRects[i][0], SizeOf(FCharRects[i][0]));
S.Write(FCharRects[i][1], SizeOf(FCharRects[i][1]));
S.Write(FCharRects[i][2], SizeOf(FCharRects[i][2]));
S.Write(FCharRects[i][3], SizeOf(FCharRects[i][3]));
end;
// char wds
Count := Length(CharWidths);
S.Write(Count, SizeOf(Count));
for i := 0 to High(CharWidths) do
S.Write(CharWidths[i], SizeOf(CharWidths[i]));
finally
S.Free;
end;
end;
procedure TGLStoredBitmapFont.LoadWindowsFont;
begin
if not FLoaded then
inherited ;
end;
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// class registrations
RegisterClasses([TGLWindowsBitmapFont, TGLStoredBitmapFont]);
end.
|
{
This module collects the basic data types and operations used in the TP
Lex program, and other basic stuff that does not belong anywhere else:
- Lex input and output files and corresponding bookkeeping information
used by the parser
- symbolic character constants
- dynamically allocated strings and character classes
- integer sets
- generic quicksort and hash table routines
- utilities for list-generating
- other tiny utilities
Copyright (c) 1990-92 Albert Graef <ag@muwiinfa.geschichte.uni-mainz.de>
Copyright (C) 1996 Berend de Boer <berend@pobox.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
$Revision: 2 $
$Modtime: 96-08-01 10:21 $
$History: LEXBASE.PAS $
*
* ***************** Version 2 *****************
* User: Berend Date: 96-10-10 Time: 21:16
* Updated in $/Lex and Yacc/tply
* Updated for protected mode, windows and Delphi 1.X and 2.X.
}
unit LexBase;
interface
const
(* symbolic character constants: *)
bs = #8; (* backspace character *)
tab = #9; (* tab character *)
nl = #10; (* newline character *)
cr = #13; (* carriage return *)
ff = #12; (* form feed character *)
var
(* Filenames: *)
lfilename : String;
pasfilename : String;
lstfilename : String;
codfilename : String;
codfilepath : String; { Under linux, binary and conf file
are not in the same path}
(* Lex input, output, list and code template file: *)
yyin, yylst, yyout, yycod : Text;
(* the following values are initialized and updated by the parser: *)
line : String; (* current input line *)
lno : Integer; (* current line number *)
const
max_elems = 200; (* maximum size of integer sets *)
type
(* String and character class pointers: *)
StrPtr = ^String;
CClass = set of Char;
CClassPtr = ^CClass;
(* Sorted integer sets: *)
IntSet = array [0..max_elems] of Integer;
(* word 0 is size *)
IntSetPtr = ^IntSet;
(* Regular expressions: *)
RegExpr = ^Node;
NodeType = (mark_node, (* marker node *)
char_node, (* character node *)
str_node, (* string node *)
cclass_node, (* character class node *)
star_node, (* star node *)
plus_node, (* plus node *)
opt_node, (* option node *)
cat_node, (* concatenation node *)
alt_node); (* alternatives node (|) *)
Node = record case node_type : NodeType of
mark_node : (rule, pos : Integer);
char_node : (c : Char);
str_node : (str : StrPtr);
cclass_node : (cc : CClassPtr);
star_node, plus_node, opt_node : (r : RegExpr);
cat_node, alt_node : (r1, r2 : RegExpr);
end;
(* Some standard character classes: *)
const
letters : CClass = ['A'..'Z','a'..'z','_'];
digits : CClass = ['0'..'9'];
alphanums : CClass = ['A'..'Z','a'..'z','_','0'..'9'];
(* Operations: *)
(* Strings and character classes: *)
function newStr(str : String) : StrPtr;
(* creates a string pointer (only the space actually needed for the given
string is allocated) *)
function newCClass(cc : CClass) : CClassPtr;
(* creates a CClass pointer *)
(* Integer sets (set arguments are passed by reference even if they are not
modified, for greater efficiency): *)
procedure empty(var M : IntSet);
(* initializes M as empty *)
procedure singleton(var M : IntSet; i : Integer);
(* initializes M as a singleton set containing the element i *)
procedure include(var M : IntSet; i : Integer);
(* include i in M *)
procedure exclude(var M : IntSet; i : Integer);
(* exclude i from M *)
procedure setunion(var M, N : IntSet);
(* adds N to M *)
procedure setminus(var M, N : IntSet);
(* removes N from M *)
procedure intersect(var M, N : IntSet);
(* removes from M all elements NOT in N *)
function size(var M : IntSet) : Integer;
(* cardinality of set M *)
function member(i : Integer; var M : IntSet) : Boolean;
(* tests for membership of i in M *)
function isempty(var M : IntSet) : Boolean;
(* checks whether M is an empty set *)
function equal(var M, N : IntSet) : Boolean;
(* checks whether M and N are equal *)
function subseteq(var M, N : IntSet) : Boolean;
(* checks whether M is a subset of N *)
function newIntSet : IntSetPtr;
(* creates a pointer to an empty integer set *)
(* Constructors for regular expressions: *)
const epsExpr : RegExpr = nil;
(* empty regular expression *)
function markExpr(rule, pos : Integer) : RegExpr;
(* markers are used to denote endmarkers of rules, as well as other
special positions in rules, e.g. the position of the lookahead
operator; they are considered nullable; by convention, we use
the following pos numbers:
- 0: endmarker position
- 1: lookahead operator position *)
function charExpr(c : Char) : RegExpr;
(* character c *)
function strExpr(str : StrPtr) : RegExpr;
(* "str" *)
function cclassExpr(cc : CClassPtr) : RegExpr;
(* [str] where str are the literals in cc *)
function starExpr(r : RegExpr) : RegExpr;
(* r* *)
function plusExpr(r : RegExpr) : RegExpr;
(* r+ *)
function optExpr(r : RegExpr) : RegExpr;
(* r? *)
function mnExpr(r : RegExpr; m, n : Integer) : RegExpr;
(* constructor expanding expression r{m,n} to the corresponding
alt expression r^m|...|r^n *)
function catExpr(r1, r2 : RegExpr) : RegExpr;
(* r1r2 *)
function altExpr(r1, r2 : RegExpr) : RegExpr;
(* r1|r2 *)
(* Unifiers for regular expressions:
The following predicates check whether the specified regular
expression r is of the denoted type; if the predicate succeeds,
the other arguments of the predicate are instantiated to the
corresponding values. *)
function is_epsExpr(r : RegExpr) : Boolean;
(* empty regular expression *)
function is_markExpr(r : RegExpr; var rule, pos : Integer) : Boolean;
(* marker expression *)
function is_charExpr(r : RegExpr; var c : Char) : Boolean;
(* character c *)
function is_strExpr(r : RegExpr; var str : StrPtr) : Boolean;
(* "str" *)
function is_cclassExpr(r : RegExpr; var cc : CClassPtr) : Boolean;
(* [str] where str are the literals in cc *)
function is_starExpr(r : RegExpr; var r1 : RegExpr) : Boolean;
(* r1* *)
function is_plusExpr(r : RegExpr; var r1 : RegExpr) : Boolean;
(* r1+ *)
function is_optExpr(r : RegExpr; var r1 : RegExpr) : Boolean;
(* r1? *)
function is_catExpr(r : RegExpr; var r1, r2 : RegExpr) : Boolean;
(* r1r2 *)
function is_altExpr(r : RegExpr; var r1, r2 : RegExpr) : Boolean;
(* r1|r2 *)
(* Quicksort: *)
type
OrderPredicate = function (i, j : Integer) : Boolean;
SwapProc = procedure (i, j : Integer);
procedure quicksort(lo, hi: Integer;
less : OrderPredicate;
swap : SwapProc);
(* General inplace sorting procedure based on the quicksort algorithm.
This procedure can be applied to any sequential data structure;
only the corresponding routines less which compares, and swap which
swaps two elements i,j of the target data structure, must be
supplied as appropriate for the target data structure.
- lo, hi: the lower and higher indices, indicating the elements to
be sorted
- less(i, j): should return true if element no. i `is less than'
element no. j, and false otherwise; any total quasi-ordering may
be supplied here (if neither less(i, j) nor less(j, i) then elements
i and j are assumed to be `equal').
- swap(i, j): should swap the elements with index i and j *)
(* Generic hash table routines (based on quadratic rehashing; hence the
table size must be a prime number): *)
type
TableLookupProc = function(k : Integer) : String;
TableEntryProc = procedure(k : Integer; symbol : String);
function key(symbol : String;
table_size : Integer;
lookup : TableLookupProc;
entry : TableEntryProc) : Integer;
(* returns a hash table key for symbol; inserts the symbol into the
table if necessary
- table_size is the symbol table size and must be a fixed prime number
- lookup is the table lookup procedure which should return the string
at key k in the table ('' if entry is empty)
- entry is the table entry procedure which is assumed to store the
given symbol at the given location *)
function definedKey(symbol : String;
table_size : Integer;
lookup : TableLookupProc) : Boolean;
(* checks the table to see if symbol is in the table *)
(* Utility routines: *)
function min(i, j : Integer) : Integer;
function max(i, j : Integer) : Integer;
(* minimum and maximum of two integers *)
function nchars(cc : CClass) : Integer;
(* returns the cardinality (number of characters) of a character class *)
function upper(str : String) : String;
(* returns str converted to uppercase *)
function strip(str : String) : String;
(* returns str with leading and trailing blanks stripped off *)
function blankStr(str : String) : String;
(* returns string of same length as str, with all non-whitespace characters
replaced by blanks *)
function intStr(i : Integer) : String;
(* returns the string representation of i *)
function isInt(str : String; var i : Integer) : Boolean;
(* checks whether str represents an integer; if so, returns the
value of it in i *)
function path(filename : String) : String;
(* returns the path in filename *)
function root(filename : String) : String;
(* returns root (i.e. extension stripped from filename) of
filename *)
function addExt(filename, ext : String) : String;
(* if filename has no extension and last filename character is not '.',
add extension ext to filename *)
function file_size(filename : String) : LongInt;
(* determines file size in bytes *)
(* Utility functions for list generating routines: *)
function charStr(c : char; reserved : CClass) : String;
(* returns a print name for character c, using the standard escape
conventions; reserved is the class of `reserved' special characters
which should be quoted with \ (\ itself is always quoted) *)
function singleQuoteStr(str : String) : String;
(* returns print name of str enclosed in single quotes, using the
standard escape conventions *)
function doubleQuoteStr(str : String) : String;
(* returns print name of str enclosed in double quotes, using the
standard escape conventions *)
function cclassStr(cc : CClass) : String;
(* returns print name of character class cc, using the standard escape
conventions; if cc contains more than 128 elements, the complement
notation (^) is used; if cc is the class of all (non-null) characters
except newline, the period notation is used *)
function cclassOrCharStr(cc : CClass) : String;
(* returns a print name for character class cc (either cclassStr, or,
if cc contains only one element, character in single quotes) *)
function regExprStr(r : RegExpr) : String;
(* unparses a regular expression *)
implementation
uses LexMsgs;
(* String and character class pointers: *)
function newStr(str : String) : StrPtr;
var strp : StrPtr;
begin
getmem(strp, succ(length(str)));
move(str, strp^, succ(length(str)));
newStr := strp;
end(*newStr*);
function newCClass(cc : CClass) : CClassPtr;
var ccp : CClassPtr;
begin
new(ccp);
ccp^ := cc;
newCClass := ccp;
end(*newCClass*);
(* Integer sets: *)
procedure empty(var M : IntSet);
begin
M[0] := 0;
end(*empty*);
procedure singleton(var M : IntSet; i : Integer);
begin
M[0] := 1; M[1] := i;
end(*singleton*);
procedure include(var M : IntSet; i : Integer);
var l, r, k : Integer;
begin
(* binary search: *)
l := 1; r := M[0];
k := l + (r-l) div 2;
while (l<r) and (M[k]<>i) do
begin
if M[k]<i then
l := succ(k)
else
r := pred(k);
k := l + (r-l) div 2;
end;
if (k>M[0]) or (M[k]<>i) then
begin
if M[0]>=max_elems then fatal(intset_overflow);
if (k<=M[0]) and (M[k]<i) then
begin
move(M[k+1], M[k+2], (M[0]-k)*sizeOf(Integer));
M[k+1] := i;
end
else
begin
move(M[k], M[k+1], (M[0]-k+1)*sizeOf(Integer));
M[k] := i;
end;
inc(M[0]);
end;
end(*include*);
procedure exclude(var M : IntSet; i : Integer);
var l, r, k : Integer;
begin
(* binary search: *)
l := 1; r := M[0];
k := l + (r-l) div 2;
while (l<r) and (M[k]<>i) do
begin
if M[k]<i then
l := succ(k)
else
r := pred(k);
k := l + (r-l) div 2;
end;
if (k<=M[0]) and (M[k]=i) then
begin
move(M[k+1], M[k], (M[0]-k)*sizeOf(Integer));
dec(M[0]);
end;
end(*exclude*);
procedure setunion(var M, N : IntSet);
var
K : IntSet;
i, j, i_M, i_N : Integer;
begin
(* merge sort: *)
i := 0; i_M := 1; i_N := 1;
while (i_M<=M[0]) and (i_N<=N[0]) do
begin
inc(i);
if i>max_elems then fatal(intset_overflow);
if M[i_M]<N[i_N] then
begin
K[i] := M[i_M]; inc(i_M);
end
else if N[i_N]<M[i_M] then
begin
K[i] := N[i_N]; inc(i_N);
end
else
begin
K[i] := M[i_M]; inc(i_M); inc(i_N);
end
end;
for j := i_M to M[0] do
begin
inc(i);
if i>max_elems then fatal(intset_overflow);
K[i] := M[j];
end;
for j := i_N to N[0] do
begin
inc(i);
if i>max_elems then fatal(intset_overflow);
K[i] := N[j];
end;
K[0] := i;
move(K, M, succ(i)*sizeOf(Integer));
end(*setunion*);
procedure setminus(var M, N : IntSet);
var
K : IntSet;
i, i_M, i_N : Integer;
begin
i := 0; i_N := 1;
for i_M := 1 to M[0] do
begin
while (i_N<=N[0]) and (N[i_N]<M[i_M]) do inc(i_N);
if (i_N>N[0]) or (N[i_N]>M[i_M]) then
begin
inc(i);
K[i] := M[i_M];
end
else
inc(i_N);
end;
K[0] := i;
move(K, M, succ(i)*sizeOf(Integer));
end(*setminus*);
procedure intersect(var M, N : IntSet);
var
K : IntSet;
i, i_M, i_N : Integer;
begin
i := 0; i_N := 1;
for i_M := 1 to M[0] do
begin
while (i_N<=N[0]) and (N[i_N]<M[i_M]) do inc(i_N);
if (i_N<=N[0]) and (N[i_N]=M[i_M]) then
begin
inc(i);
K[i] := M[i_M];
inc(i_N);
end
end;
K[0] := i;
move(K, M, succ(i)*sizeOf(Integer));
end(*intersect*);
function size(var M : IntSet) : Integer;
begin
size := M[0]
end(*size*);
function member(i : Integer; var M : IntSet) : Boolean;
var l, r, k : Integer;
begin
(* binary search: *)
l := 1; r := M[0];
k := l + (r-l) div 2;
while (l<r) and (M[k]<>i) do
begin
if M[k]<i then
l := succ(k)
else
r := pred(k);
k := l + (r-l) div 2;
end;
member := (k<=M[0]) and (M[k]=i);
end(*member*);
function isempty(var M : IntSet) : Boolean;
begin
isempty := M[0]=0
end(*isempty*);
function equal(var M, N : IntSet) : Boolean;
var i : Integer;
begin
if M[0]<>N[0] then
equal := false
else
begin
for i := 1 to M[0] do
if M[i]<>N[i] then
begin
equal := false;
exit
end;
equal := true
end
end(*equal*);
function subseteq(var M, N : IntSet) : Boolean;
var
i_M, i_N : Integer;
begin
if M[0]>N[0] then
subseteq := false
else
begin
i_N := 1;
for i_M := 1 to M[0] do
begin
while (i_N<=N[0]) and (N[i_N]<M[i_M]) do inc(i_N);
if (i_N>N[0]) or (N[i_N]>M[i_M]) then
begin
subseteq := false;
exit
end
else
inc(i_N);
end;
subseteq := true
end;
end(*subseteq*);
function newIntSet : IntSetPtr;
var
MP : IntSetPtr;
begin
getmem(MP, (max_elems+1)*sizeOf(Integer));
MP^[0] := 0;
newIntSet := MP
end(*newIntSet*);
(* Constructors for regular expressions: *)
function newExpr(node_type : NodeType; n : Integer) : RegExpr;
(* returns new RegExpr node (n: number of bytes to allocate) *)
var x : RegExpr;
begin
getmem(x, sizeOf(NodeType)+n);
x^.node_type := node_type;
newExpr := x
end(*newExpr*);
function markExpr(rule, pos : Integer) : RegExpr;
var x : RegExpr;
begin
x := newExpr(mark_node, 2*sizeOf(Integer));
x^.rule := rule;
x^.pos := pos;
markExpr := x
end(*markExpr*);
function charExpr(c : Char) : RegExpr;
var x : RegExpr;
begin
x := newExpr(char_node, sizeOf(Char));
x^.c := c;
charExpr := x
end(*charExpr*);
function strExpr(str : StrPtr) : RegExpr;
var x : RegExpr;
begin
x := newExpr(str_node, sizeOf(StrPtr));
x^.str := str;
strExpr := x
end(*strExpr*);
function cclassExpr(cc : CClassPtr) : RegExpr;
var x : RegExpr;
begin
x := newExpr(cclass_node, sizeOf(CClassPtr));
x^.cc := cc;
cclassExpr := x
end(*cclassExpr*);
function starExpr(r : RegExpr) : RegExpr;
var x : RegExpr;
begin
x := newExpr(star_node, sizeOf(RegExpr));
x^.r := r;
starExpr := x
end(*starExpr*);
function plusExpr(r : RegExpr) : RegExpr;
var x : RegExpr;
begin
x := newExpr(plus_node, sizeOf(RegExpr));
x^.r := r;
plusExpr := x
end(*plusExpr*);
function optExpr(r : RegExpr) : RegExpr;
var x : RegExpr;
begin
x := newExpr(opt_node, sizeOf(RegExpr));
x^.r := r;
optExpr := x
end(*optExpr*);
function mnExpr(r : RegExpr; m, n : Integer) : RegExpr;
var
ri, rmn : RegExpr;
i : Integer;
begin
if (m>n) or (n=0) then
mnExpr := epsExpr
else
begin
(* construct r^m: *)
if m=0 then
ri := epsExpr
else
begin
ri := r;
for i := 2 to m do
ri := catExpr(ri, r);
end;
(* construct r{m,n}: *)
rmn := ri; (* r{m,n} := r^m *)
for i := m+1 to n do
begin
if is_epsExpr(ri) then
ri := r
else
ri := catExpr(ri, r);
rmn := altExpr(rmn, ri) (* r{m,n} := r{m,n} | r^i,
i=m+1,...,n *)
end;
mnExpr := rmn
end
end(*mnExpr*);
function catExpr(r1, r2 : RegExpr) : RegExpr;
var x : RegExpr;
begin
x := newExpr(cat_node, 2*sizeOf(RegExpr));
x^.r1 := r1;
x^.r2 := r2;
catExpr := x
end(*catExpr*);
function altExpr(r1, r2 : RegExpr) : RegExpr;
var x : RegExpr;
begin
x := newExpr(alt_node, 2*sizeOf(RegExpr));
x^.r1 := r1;
x^.r2 := r2;
altExpr := x
end(*altExpr*);
(* Unifiers for regular expressions: *)
function is_epsExpr(r : RegExpr) : Boolean;
begin
is_epsExpr := r=epsExpr
end(*is_epsExpr*);
function is_markExpr(r : RegExpr; var rule, pos : Integer) : Boolean;
begin
if r=epsExpr then
is_markExpr := false
else if r^.node_type=mark_node then
begin
is_markExpr := true;
rule := r^.rule;
pos := r^.pos;
end
else
is_markExpr := false
end(*is_markExpr*);
function is_charExpr(r : RegExpr; var c : Char) : Boolean;
begin
if r=epsExpr then
is_charExpr := false
else if r^.node_type=char_node then
begin
is_charExpr := true;
c := r^.c
end
else
is_charExpr := false
end(*is_charExpr*);
function is_strExpr(r : RegExpr; var str : StrPtr) : Boolean;
begin
if r=epsExpr then
is_strExpr := false
else if r^.node_type=str_node then
begin
is_strExpr := true;
str := r^.str;
end
else
is_strExpr := false
end(*is_strExpr*);
function is_cclassExpr(r : RegExpr; var cc : CClassPtr) : Boolean;
begin
if r=epsExpr then
is_cclassExpr := false
else if r^.node_type=cclass_node then
begin
is_cclassExpr := true;
cc := r^.cc
end
else
is_cclassExpr := false
end(*is_cclassExpr*);
function is_starExpr(r : RegExpr; var r1 : RegExpr) : Boolean;
begin
if r=epsExpr then
is_starExpr := false
else if r^.node_type=star_node then
begin
is_starExpr := true;
r1 := r^.r
end
else
is_starExpr := false
end(*is_starExpr*);
function is_plusExpr(r : RegExpr; var r1 : RegExpr) : Boolean;
begin
if r=epsExpr then
is_plusExpr := false
else if r^.node_type=plus_node then
begin
is_plusExpr := true;
r1 := r^.r
end
else
is_plusExpr := false
end(*is_plusExpr*);
function is_optExpr(r : RegExpr; var r1 : RegExpr) : Boolean;
begin
if r=epsExpr then
is_optExpr := false
else if r^.node_type=opt_node then
begin
is_optExpr := true;
r1 := r^.r
end
else
is_optExpr := false
end(*is_optExpr*);
function is_catExpr(r : RegExpr; var r1, r2 : RegExpr) : Boolean;
begin
if r=epsExpr then
is_catExpr := false
else if r^.node_type=cat_node then
begin
is_catExpr := true;
r1 := r^.r1;
r2 := r^.r2
end
else
is_catExpr := false
end(*is_catExpr*);
function is_altExpr(r : RegExpr; var r1, r2 : RegExpr) : Boolean;
begin
if r=epsExpr then
is_altExpr := false
else if r^.node_type=alt_node then
begin
is_altExpr := true;
r1 := r^.r1;
r2 := r^.r2
end
else
is_altExpr := false
end(*is_altExpr*);
(* Quicksort: *)
procedure quicksort(lo, hi: Integer;
less : OrderPredicate;
swap : SwapProc);
(* derived from the quicksort routine in QSORT.PAS in the Turbo Pascal
distribution *)
procedure sort(l, r: Integer);
var i, j, k : Integer;
begin
i := l; j := r; k := (l+r) DIV 2;
repeat
while less(i, k) do inc(i);
while less(k, j) do dec(j);
if i<=j then
begin
swap(i, j);
if k=i then k := j (* pivot element swapped! *)
else if k=j then k := i;
inc(i); dec(j);
end;
until i>j;
if l<j then sort(l,j);
if i<r then sort(i,r);
end(*sort*);
begin
if lo<hi then sort(lo,hi);
end(*quicksort*);
(* Generic hash table routines: *)
function hash(str : String; table_size : Integer) : Integer;
(* computes a hash key for str *)
var i, key : Integer;
begin
key := 0;
for i := 1 to length(str) do
inc(key, ord(str[i]));
hash := key mod table_size + 1;
end(*hash*);
procedure newPos(var pos, incr, count : Integer; table_size : Integer);
(* computes a new position in the table (quadratic collision strategy)
- pos: current position (+inc)
- incr: current increment (+2)
- count: current number of collisions (+1)
quadratic collision formula for position of str after n collisions:
pos(str, n) = (hash(str)+n^2) mod table_size +1
note that n^2-(n-1)^2 = 2n-1 <=> n^2 = (n-1)^2 + (2n-1) for n>0,
i.e. the increment inc=2n-1 increments by two in each collision *)
begin
inc(count);
inc(pos, incr);
if pos>table_size then pos := pos mod table_size + 1;
inc(incr, 2)
end(*newPos*);
function key(symbol : String;
table_size : Integer;
lookup : TableLookupProc;
entry : TableEntryProc) : Integer;
var pos, incr, count : Integer;
begin
pos := hash(symbol, table_size);
incr := 1;
count := 0;
while count<=table_size do
if lookup(pos)='' then
begin
entry(pos, symbol);
key := pos;
exit
end
else if lookup(pos)=symbol then
begin
key := pos;
exit
end
else
newPos(pos, incr, count, table_size);
fatal(sym_table_overflow)
end(*key*);
function definedKey(symbol : String;
table_size : Integer;
lookup : TableLookupProc) : Boolean;
var pos, incr, count : Integer;
begin
pos := hash(symbol, table_size);
incr := 1;
count := 0;
while count<=table_size do
if lookup(pos)='' then
begin
definedKey := false;
exit
end
else if lookup(pos)=symbol then
begin
definedKey := true;
exit
end
else
newPos(pos, incr, count, table_size);
definedKey := false
end(*definedKey*);
(* Utility routines: *)
function min(i, j : Integer) : Integer;
begin
if i<j then
min := i
else
min := j
end(*min*);
function max(i, j : Integer) : Integer;
begin
if i>j then
max := i
else
max := j
end(*max*);
function nchars(cc : CClass) : Integer;
var
c : Char;
count : Integer;
begin
count := 0;
for c := #0 to #255 do if c in cc then inc(count);
nchars := count;
end(*nchars*);
function upper(str : String) : String;
var i : Integer;
begin
for i := 1 to length(str) do
str[i] := upCase(str[i]);
upper := str
end(*upper*);
function strip(str : String) : String;
begin
while (length(str)>0) and ((str[1]=' ') or (str[1]=tab)) do
delete(str, 1, 1);
while (length(str)>0) and
((str[length(str)]= ' ') or
(str[length(str)]=tab)) do
delete(str, length(str), 1);
strip := str;
end(*strip*);
function blankStr(str : String) : String;
var i : Integer;
begin
for i := 1 to length(str) do
if str[i]<>tab then str[i] := ' ';
blankStr := str;
end(*blankStr*);
function intStr(i : Integer) : String;
var s : String;
begin
str(i, s);
intStr := s
end(*intStr*);
function isInt(str : String; var i : Integer) : Boolean;
var res : Integer;
begin
val(str, i, res);
isInt := res = 0;
end(*isInt*);
function path(filename : String) : String;
var i : Integer;
begin
i := length(filename);
while (i>0) and (filename[i]<>'\') and (filename[i]<>':') do
dec(i);
path := copy(filename, 1, i);
end(*path*);
function root(filename : String) : String;
var
i : Integer;
begin
root := filename;
for i := length(filename) downto 1 do
case filename[i] of
'.' :
begin
root := copy(filename, 1, i-1);
exit
end;
'\': exit;
else
end;
end(*addExt*);
function addExt(filename, ext : String) : String;
(* implemented with goto for maximum efficiency *)
label x;
var
i : Integer;
begin
addExt := filename;
for i := length(filename) downto 1 do
case filename[i] of
'.' : exit;
'\': goto x;
else
end;
x : addExt := filename+'.'+ext
end(*addExt*);
function file_size(filename : String) : LongInt;
var f : File;
begin
assign(f, filename);
reset(f, 1);
if ioresult=0 then
file_size := fileSize(f)
else
file_size := 0;
close(f);
end(*file_size*);
(* Utility functions for list generating routines: *)
function charStr(c : char; reserved : CClass) : String;
function octStr(c : char) : String;
(* return octal string representation of character c *)
begin
octStr := intStr(ord(c) div 64)+intStr((ord(c) mod 64) div 8)+
intStr(ord(c) mod 8);
end(*octStr*);
begin
case c of
#0..#7, (* nonprintable characters *)
#11,#14..#31,
#127..#255 : charStr := '\'+octStr(c);
bs : charStr := '\b';
tab : charStr := '\t';
nl : charStr := '\n';
cr : charStr := '\c';
ff : charStr := '\f';
'\' : charStr := '\\';
else if c in reserved then
charStr := '\'+c
else
charStr := c
end
end(*charStr*);
function singleQuoteStr(str : String) : String;
var
i : Integer;
str1 : String;
begin
str1 := '';
for i := 1 to length(str) do
str1 := str1+charStr(str[i], ['''']);
singleQuoteStr := ''''+str1+''''
end(*singleQuoteStr*);
function doubleQuoteStr(str : String) : String;
var
i : Integer;
str1 : String;
begin
str1 := '';
for i := 1 to length(str) do
str1 := str1+charStr(str[i], ['"']);
doubleQuoteStr := '"'+str1+'"'
end(*doubleQuoteStr*);
function cclassStr(cc : CClass) : String;
const
reserved : CClass = ['^','-',']'];
MaxChar = #255;
var
c1, c2 : Char;
str : String;
Quit: Boolean;
begin
if cc=[#1..#255]-[nl] then
cclassStr := '.'
else
begin
str := '';
if nchars(cc)>128 then
begin
str := '^';
cc := [#0..#255]-cc;
end;
c1 := chr(0);
Quit := False;
while not Quit do begin
if c1 in cc then begin
c2 := c1;
while (c2<MaxChar) and (succ(c2) in cc) do
c2 := succ(c2);
if c1=c2
then str := str+charStr(c1, reserved)
else
if c2=succ(c1)
then str := str+charStr(c1, reserved)+charStr(c2, reserved)
else str := str+charStr(c1, reserved)+'-'+charStr(c2, reserved);
c1 := c2;
end;
Quit := c1 = MaxChar;
if not Quit then
c1 := Succ(c1);
end; { of while }
cclassStr := '['+str+']'
end
end(*cclassStr*);
function cclassOrCharStr(cc : CClass) : String;
var count : Integer;
c, c1 : Char;
begin
count := 0;
for c := #0 to #255 do
if c in cc then
begin
c1 := c;
inc(count);
if count>1 then
begin
cclassOrCharStr := cclassStr(cc);
exit;
end;
end;
if count=1 then
cclassOrCharStr := singleQuoteStr(c1)
else
cclassOrCharStr := '[]';
end(*cclassOrCharStr*);
function regExprStr(r : RegExpr) : String;
function unparseExpr(r : RegExpr) : String;
var rule_no, pos : Integer;
c : Char;
str : StrPtr;
cc : CClassPtr;
r1, r2 : RegExpr;
begin
if is_epsExpr(r) then
unparseExpr := ''
else if is_markExpr(r, rule_no, pos) then
unparseExpr := '#('+intStr(rule_no)+','+intStr(pos)+')'
else if is_charExpr(r, c) then
unparseExpr := charStr(c, [ '"','.','^','$','[',']','*','+','?',
'{','}','|','(',')','/','<','>'])
else if is_strExpr(r, str) then
unparseExpr := doubleQuoteStr(str^)
else if is_cclassExpr(r, cc) then
unparseExpr := cclassStr(cc^)
else if is_starExpr(r, r1) then
unparseExpr := unparseExpr(r1)+'*'
else if is_plusExpr(r, r1) then
unparseExpr := unparseExpr(r1)+'+'
else if is_optExpr(r, r1) then
unparseExpr := unparseExpr(r1)+'?'
else if is_catExpr(r, r1, r2) then
unparseExpr := '('+unparseExpr(r1)+unparseExpr(r2)+')'
else if is_altExpr(r, r1, r2) then
unparseExpr := '('+unparseExpr(r1)+'|'+unparseExpr(r2)+')'
else
fatal('invalid expression');
end(*unparseExpr*);
begin
regExprStr := unparseExpr(r);
end(*regExprStr*);
end(*LexBase*). |
unit UConfigBase;
interface
uses
Vcl.ExtCtrls, System.SysUtils, Ils.Kafka;
type
TConfigBase = class;
TConfigEvent = procedure(ASender: TConfigBase) of object;
TConfigBaseAbstract = class
protected
function Reload: Boolean; virtual; abstract;
function CheckNeedReload: Boolean; virtual; abstract;
function GetModifiedDateTime: TDateTime; virtual; abstract;
function GetModifiedCount: Integer; virtual; abstract;
end;
TConfigBase = class(TConfigBaseAbstract)
protected
FCheckTimer: TTimer;
FLastLoadedVersionDT: TDateTime;
FLastLoadedVersionCount: Integer;
FCurrentVersionDT: TDateTime;
FCurrentVersionCount: Integer;
FLogCB: TLogFunc;
FOnConfigChange: TConfigEvent;
procedure ChangedNotify;
procedure OnCheckTimer(Sender: TObject);
procedure SetInterval(const Value: Integer);
function GetInterval: Integer;
procedure Load;
function CheckNeedReload: Boolean; override;
public
constructor Create(
const AConfigChangeCB: TConfigEvent;
const ALogCB: TLogFunc = nil;
const ACheckInterval: Integer = 1000); virtual;
destructor Destroy; override;
end;
implementation
{ TConfigBase }
procedure TConfigBase.ChangedNotify;
begin
if Assigned(FOnConfigChange) then
FOnConfigChange(Self);
end;
function TConfigBase.CheckNeedReload: Boolean;
begin
FCurrentVersionDT := GetModifiedDateTime;
FCurrentVersionCount := GetModifiedCount;
Result := (FCurrentVersionDT <> FLastLoadedVersionDT) or (FCurrentVersionCount <> FLastLoadedVersionCount);
end;
constructor TConfigBase.Create(const AConfigChangeCB: TConfigEvent; const ALogCB: TLogFunc; const ACheckInterval: Integer);
begin
FCheckTimer := TTimer.Create(nil);
FCheckTimer.OnTimer := OnCheckTimer;
FCheckTimer.Interval := ACheckInterval;
FOnConfigChange := AConfigChangeCB;
FLogCB := ALogCB;
FCheckTimer.Enabled := True;
end;
destructor TConfigBase.Destroy;
begin
FCheckTimer.Free;
inherited;
end;
procedure TConfigBase.Load;
begin
if CheckNeedReload then
begin
if ((FLastLoadedVersionDT < FCurrentVersionDT) or (FLastLoadedVersionCount <> FCurrentVersionCount)) and Reload then
begin
FLastLoadedVersionDT := FCurrentVersionDT;
FLastLoadedVersionCount := FCurrentVersionCount;
ChangedNotify;
end;
end;
end;
procedure TConfigBase.OnCheckTimer(Sender: TObject);
begin
FCheckTimer.Enabled := False;
try
Load;
finally
FCheckTimer.Enabled := True;
end;
end;
function TConfigBase.GetInterval: Integer;
begin
Result := FCheckTimer.Interval;
end;
procedure TConfigBase.SetInterval(const Value: Integer);
begin
FCheckTimer.Interval := Value;
end;
end.
|
unit InformePorFechas_ViewModel_Implementation;
interface
uses
Informe_Model,Informe_ViewModel_Implementation;
type
TInformePorFechas_ViewModel = class(TInforme_ViewModel)
private
{ Private declarations }
fDesdeFecha: TDateTime;
fHastaFecha: TDateTime;
procedure SetDesdeFecha(const Value: TDateTime);
procedure SetHastaFecha(const Value: TDateTime);
protected
function GetEmitirInformeOK: boolean; override;
function ModelClass:TdmInforme_Model_Class; override;
function PropiedadesParaModelo:TInforme_Propiedades; override;
procedure AsignacionesIniciales; override;
public
procedure Actualizar; virtual;
property DesdeFecha:TDateTime read fDesdeFecha write SetDesdeFecha;
property HastaFecha:TDateTime read fHastaFecha write SetHastaFecha;
end;
implementation
uses
InformePorFechas_Model,
SysUtils;
procedure TInformePorFechas_ViewModel.Actualizar;
begin
inherited;
end;
procedure TInformePorFechas_ViewModel.AsignacionesIniciales;
begin
fDesdeFecha:=Date;
fHastaFecha:=Date;
inherited;
end;
function TInformePorFechas_ViewModel.GetEmitirInformeOK: boolean;
begin
result:=(DesdeFecha<=HastaFecha)
and inherited GetEmitirInformeOK;
end;
function TInformePorFechas_ViewModel.ModelClass: TdmInforme_Model_Class;
begin
result:=TdmInformePorFechas_Model;
end;
function TInformePorFechas_ViewModel.PropiedadesParaModelo: TInforme_Propiedades;
var
Props: TInformePorFechas_Propiedades;
begin
Props:=TInformePorFechas_Propiedades.Create;
try
Props.DesdeFecha:=DesdeFecha;
Props.HastaFecha:=HastaFecha;
result:=Props;
except
Props.Free;
raise;
end;
end;
procedure TInformePorFechas_ViewModel.SetDesdeFecha(const Value: TDateTime);
begin
if fDesdeFecha<>Value then begin
fDesdeFecha:=Value;
CambioPropiedades;
end;
end;
procedure TInformePorFechas_ViewModel.SetHastaFecha(const Value: TDateTime);
begin
if fHastaFecha<>Value then begin
fHastaFecha:=Value;
CambioPropiedades;
end;
end;
end.
|
unit MustacheTests;
{$mode objfpc}{$H+}
interface
uses
TestFramework, HandlebarsTestCase;
type
TCommentsTests = class(THandlebarsTestCase)
published
procedure TestInline;
procedure TestMultiline;
procedure TestStandalone;
procedure TestIndentedStandalone;
procedure TestStandaloneLineEndings;
procedure TestStandaloneWithoutPreviousLine;
procedure TestStandaloneWithoutNewline;
procedure TestMultilineStandalone;
procedure TestIndentedMultilineStandalone;
procedure TestIndentedInline;
procedure TestSurroundingWhitespace;
end;
TDelimitersTests = class(THandlebarsTestCase)
published
procedure TestPairBehavior;
procedure TestSpecialCharacters;
procedure TestSections;
procedure TestInvertedSections;
procedure TestPartialInheritence;
procedure TestPostPartialBehavior;
procedure TestSurroundingWhitespace;
procedure TestOutlyingWhitespaceInline;
procedure TestStandaloneTag;
procedure TestIndentedStandaloneTag;
procedure TestStandaloneLineEndings;
procedure TestStandaloneWithoutPreviousLine;
procedure TestStandaloneWithoutNewline;
procedure TestPairwithPadding;
end;
TInterpolationTests = class(THandlebarsTestCase)
published
procedure TestNoInterpolation;
procedure TestBasicInterpolation;
procedure TestHTMLEscaping;
procedure TestTripleMustache;
procedure TestAmpersand;
procedure TestBasicIntegerInterpolation;
procedure TestTripleMustacheIntegerInterpolation;
procedure TestAmpersandIntegerInterpolation;
procedure TestBasicDecimalInterpolation;
procedure TestTripleMustacheDecimalInterpolation;
procedure TestAmpersandDecimalInterpolation;
procedure TestBasicContextMissInterpolation;
procedure TestTripleMustacheContextMissInterpolation;
procedure TestAmpersandContextMissInterpolation;
procedure TestDottedNamesBasicInterpolation;
procedure TestDottedNamesTripleMustacheInterpolation;
procedure TestDottedNamesAmpersandInterpolation;
procedure TestDottedNamesArbitraryDepth;
procedure TestDottedNamesBrokenChains;
procedure TestDottedNamesBrokenChainResolution;
procedure TestDottedNamesInitialResolution;
procedure TestInterpolationSurroundingWhitespace;
procedure TestTripleMustacheSurroundingWhitespace;
procedure TestAmpersandSurroundingWhitespace;
procedure TestInterpolationStandalone;
procedure TestTripleMustacheStandalone;
procedure TestAmpersandStandalone;
procedure TestInterpolationWithPadding;
procedure TestTripleMustacheWithPadding;
procedure TestAmpersandWithPadding;
end;
TInvertedTests = class(THandlebarsTestCase)
published
procedure TestFalsey;
procedure TestTruthy;
procedure TestContext;
procedure TestList;
procedure TestEmptyList;
procedure TestDoubled;
procedure TestNestedFalsey;
procedure TestNestedTruthy;
procedure TestContextMisses;
procedure TestDottedNamesTruthy;
procedure TestDottedNamesFalsey;
procedure TestDottedNamesBrokenChains;
procedure TestSurroundingWhitespace;
procedure TestInternalWhitespace;
procedure TestIndentedInlineSections;
procedure TestStandaloneLines;
procedure TestStandaloneIndentedLines;
procedure TestStandaloneLineEndings;
procedure TestStandaloneWithoutPreviousLine;
procedure TestStandaloneWithoutNewline;
procedure TestPadding;
end;
TPartialsTests = class(THandlebarsTestCase)
published
procedure TestBasicBehavior;
procedure TestFailedLookup;
procedure TestContext;
procedure TestRecursion;
procedure TestSurroundingWhitespace;
procedure TestInlineIndentation;
procedure TestStandaloneLineEndings;
procedure TestStandaloneWithoutPreviousLine;
procedure TestStandaloneWithoutNewline;
procedure TestStandaloneIndentation;
procedure TestPaddingWhitespace;
end;
TSectionsTests = class(THandlebarsTestCase)
published
procedure TestTruthy;
procedure TestFalsey;
procedure TestContext;
procedure TestDeeplyNestedContexts;
procedure TestList;
procedure TestEmptyList;
procedure TestDoubled;
procedure TestNestedTruthy;
procedure TestNestedFalsey;
procedure TestContextMisses;
procedure TestImplicitIteratorString;
procedure TestImplicitIteratorInteger;
procedure TestImplicitIteratorDecimal;
procedure TestDottedNamesTruthy;
procedure TestDottedNamesFalsey;
procedure TestDottedNamesBrokenChains;
procedure TestSurroundingWhitespace;
procedure TestInternalWhitespace;
procedure TestIndentedInlineSections;
procedure TestStandaloneLines;
procedure TestIndentedStandaloneLines;
procedure TestStandaloneLineEndings;
procedure TestStandaloneWithoutPreviousLine;
procedure TestStandaloneWithoutNewline;
procedure TestPadding;
end;
TLambdasTests = class(THandlebarsTestCase)
published
procedure TestInterpolation;
procedure TestInterpolationExpansion;
procedure TestInterpolationAlternateDelimiters;
procedure TestInterpolationMultipleCalls;
procedure TestEscaping;
procedure TestSection;
procedure TestSectionExpansion;
procedure TestSectionAlternateDelimiters;
procedure TestSectionMultipleCalls;
procedure TestInvertedSection;
end;
implementation
procedure TCommentsTests.TestInline;
begin
CheckRender('12345{{! Comment Block! }}67890','{}','1234567890')
end;
procedure TCommentsTests.TestMultiline;
begin
CheckRender('12345{{!'+ LineEnding +' This is a'+ LineEnding +' multi-line comment...'+ LineEnding +'}}67890'+ LineEnding +'','{}','1234567890'+ LineEnding +'')
end;
procedure TCommentsTests.TestStandalone;
begin
CheckRender('Begin.'+ LineEnding +'{{! Comment Block! }}'+ LineEnding +'End.'+ LineEnding +'','{}','Begin.'+ LineEnding +'End.'+ LineEnding +'')
end;
procedure TCommentsTests.TestIndentedStandalone;
begin
CheckRender('Begin.'+ LineEnding +' {{! Indented Comment Block! }}'+ LineEnding +'End.'+ LineEnding +'','{}','Begin.'+ LineEnding +'End.'+ LineEnding +'')
end;
procedure TCommentsTests.TestStandaloneLineEndings;
begin
CheckRender('|'+ LineEnding +'{{! Standalone Comment }}'+ LineEnding +'|','{}','|'+ LineEnding +'|')
end;
procedure TCommentsTests.TestStandaloneWithoutPreviousLine;
begin
CheckRender(' {{! I''m Still Standalone }}'+ LineEnding +'!','{}','!')
end;
procedure TCommentsTests.TestStandaloneWithoutNewline;
begin
CheckRender('!'+ LineEnding +' {{! I''m Still Standalone }}','{}','!'+ LineEnding +'')
end;
procedure TCommentsTests.TestMultilineStandalone;
begin
CheckRender('Begin.'+ LineEnding +'{{!'+ LineEnding +'Something''s going on here...'+ LineEnding +'}}'+ LineEnding +'End.'+ LineEnding +'','{}','Begin.'+ LineEnding +'End.'+ LineEnding +'')
end;
procedure TCommentsTests.TestIndentedMultilineStandalone;
begin
CheckRender('Begin.'+ LineEnding +' {{!'+ LineEnding +' Something''s going on here...'+ LineEnding +' }}'+ LineEnding +'End.'+ LineEnding +'','{}','Begin.'+ LineEnding +'End.'+ LineEnding +'')
end;
procedure TCommentsTests.TestIndentedInline;
begin
CheckRender(' 12 {{! 34 }}'+ LineEnding +'','{}',' 12 '+ LineEnding +'')
end;
procedure TCommentsTests.TestSurroundingWhitespace;
begin
CheckRender('12345 {{! Comment Block! }} 67890','{}','12345 67890')
end;
procedure TDelimitersTests.TestPairBehavior;
begin
CheckRender('{{=<% %>=}}(<%text%>)','{ "text" : "Hey!" }','(Hey!)')
end;
procedure TDelimitersTests.TestSpecialCharacters;
begin
CheckRender('({{=[ ]=}}[text])','{ "text" : "It worked!" }','(It worked!)')
end;
procedure TDelimitersTests.TestSections;
begin
CheckRender('['+ LineEnding +'{{#section}}'+ LineEnding +' {{data}}'+ LineEnding +' |data|'+ LineEnding +'{{/section}}'+ LineEnding +''+ LineEnding +'{{= | | =}}'+ LineEnding +'|#section|'+ LineEnding +' {{data}}'+ LineEnding +' |data|'+ LineEnding +'|/section|'+ LineEnding +']'+ LineEnding +'','{ "section" : true, "data" : "I got interpolated." }','['+ LineEnding +' I got interpolated.'+ LineEnding +' |data|'+ LineEnding +''+ LineEnding +' {{data}}'+ LineEnding +' I got interpolated.'+ LineEnding +']'+ LineEnding +'')
end;
procedure TDelimitersTests.TestInvertedSections;
begin
CheckRender('['+ LineEnding +'{{^section}}'+ LineEnding +' {{data}}'+ LineEnding +' |data|'+ LineEnding +'{{/section}}'+ LineEnding +''+ LineEnding +'{{= | | =}}'+ LineEnding +'|^section|'+ LineEnding +' {{data}}'+ LineEnding +' |data|'+ LineEnding +'|/section|'+ LineEnding +']'+ LineEnding +'','{ "section" : false, "data" : "I got interpolated." }','['+ LineEnding +' I got interpolated.'+ LineEnding +' |data|'+ LineEnding +''+ LineEnding +' {{data}}'+ LineEnding +' I got interpolated.'+ LineEnding +']'+ LineEnding +'')
end;
procedure TDelimitersTests.TestPartialInheritence;
begin
CheckRender('[ {{>include}} ]'+ LineEnding +'{{= | | =}}'+ LineEnding +'[ |>include| ]'+ LineEnding +'','{ "value" : "yes" }','[ .yes. ]'+ LineEnding +'[ .yes. ]'+ LineEnding +'')
end;
procedure TDelimitersTests.TestPostPartialBehavior;
begin
CheckRender('[ {{>include}} ]'+ LineEnding +'[ .{{value}}. .|value|. ]'+ LineEnding +'','{ "value" : "yes" }','[ .yes. .yes. ]'+ LineEnding +'[ .yes. .|value|. ]'+ LineEnding +'')
end;
procedure TDelimitersTests.TestSurroundingWhitespace;
begin
CheckRender('| {{=@ @=}} |','{}','| |')
end;
procedure TDelimitersTests.TestOutlyingWhitespaceInline;
begin
CheckRender(' | {{=@ @=}}'+ LineEnding +'','{}',' | '+ LineEnding +'')
end;
procedure TDelimitersTests.TestStandaloneTag;
begin
CheckRender('Begin.'+ LineEnding +'{{=@ @=}}'+ LineEnding +'End.'+ LineEnding +'','{}','Begin.'+ LineEnding +'End.'+ LineEnding +'')
end;
procedure TDelimitersTests.TestIndentedStandaloneTag;
begin
CheckRender('Begin.'+ LineEnding +' {{=@ @=}}'+ LineEnding +'End.'+ LineEnding +'','{}','Begin.'+ LineEnding +'End.'+ LineEnding +'')
end;
procedure TDelimitersTests.TestStandaloneLineEndings;
begin
CheckRender('|'+ LineEnding +'{{= @ @ =}}'+ LineEnding +'|','{}','|'+ LineEnding +'|')
end;
procedure TDelimitersTests.TestStandaloneWithoutPreviousLine;
begin
CheckRender(' {{=@ @=}}'+ LineEnding +'=','{}','=')
end;
procedure TDelimitersTests.TestStandaloneWithoutNewline;
begin
CheckRender('='+ LineEnding +' {{=@ @=}}','{}','='+ LineEnding +'')
end;
procedure TDelimitersTests.TestPairwithPadding;
begin
CheckRender('|{{= @ @ =}}|','{}','||')
end;
procedure TInterpolationTests.TestNoInterpolation;
begin
CheckRender('Hello from {Mustache}!'+ LineEnding +'','{}','Hello from {Mustache}!'+ LineEnding +'')
end;
procedure TInterpolationTests.TestBasicInterpolation;
begin
CheckRender('Hello, {{subject}}!'+ LineEnding +'','{ "subject" : "world" }','Hello, world!'+ LineEnding +'')
end;
procedure TInterpolationTests.TestHTMLEscaping;
begin
CheckRender('These characters should be HTML escaped: {{forbidden}}'+ LineEnding +'','{ "forbidden" : "& \" < >" }','These characters should be HTML escaped: & " < >'+ LineEnding +'')
end;
procedure TInterpolationTests.TestTripleMustache;
begin
CheckRender('These characters should not be HTML escaped: {{{forbidden}}}'+ LineEnding +'','{ "forbidden" : "& \" < >" }','These characters should not be HTML escaped: & " < >'+ LineEnding +'')
end;
procedure TInterpolationTests.TestAmpersand;
begin
CheckRender('These characters should not be HTML escaped: {{&forbidden}}'+ LineEnding +'','{ "forbidden" : "& \" < >" }','These characters should not be HTML escaped: & " < >'+ LineEnding +'')
end;
procedure TInterpolationTests.TestBasicIntegerInterpolation;
begin
CheckRender('"{{mph}} miles an hour!"','{ "mph" : 85 }','"85 miles an hour!"')
end;
procedure TInterpolationTests.TestTripleMustacheIntegerInterpolation;
begin
CheckRender('"{{{mph}}} miles an hour!"','{ "mph" : 85 }','"85 miles an hour!"')
end;
procedure TInterpolationTests.TestAmpersandIntegerInterpolation;
begin
CheckRender('"{{&mph}} miles an hour!"','{ "mph" : 85 }','"85 miles an hour!"')
end;
procedure TInterpolationTests.TestBasicDecimalInterpolation;
begin
CheckRender('"{{power}} jiggawatts!"','{ "power" : 1.21000000000000E+000 }','"1.21 jiggawatts!"')
end;
procedure TInterpolationTests.TestTripleMustacheDecimalInterpolation;
begin
CheckRender('"{{{power}}} jiggawatts!"','{ "power" : 1.21000000000000E+000 }','"1.21 jiggawatts!"')
end;
procedure TInterpolationTests.TestAmpersandDecimalInterpolation;
begin
CheckRender('"{{&power}} jiggawatts!"','{ "power" : 1.21000000000000E+000 }','"1.21 jiggawatts!"')
end;
procedure TInterpolationTests.TestBasicContextMissInterpolation;
begin
CheckRender('I ({{cannot}}) be seen!','{}','I () be seen!')
end;
procedure TInterpolationTests.TestTripleMustacheContextMissInterpolation;
begin
CheckRender('I ({{{cannot}}}) be seen!','{}','I () be seen!')
end;
procedure TInterpolationTests.TestAmpersandContextMissInterpolation;
begin
CheckRender('I ({{&cannot}}) be seen!','{}','I () be seen!')
end;
procedure TInterpolationTests.TestDottedNamesBasicInterpolation;
begin
CheckRender('"{{person.name}}" == "{{#person}}{{name}}{{/person}}"','{ "person" : { "name" : "Joe" } }','"Joe" == "Joe"')
end;
procedure TInterpolationTests.TestDottedNamesTripleMustacheInterpolation;
begin
CheckRender('"{{{person.name}}}" == "{{#person}}{{{name}}}{{/person}}"','{ "person" : { "name" : "Joe" } }','"Joe" == "Joe"')
end;
procedure TInterpolationTests.TestDottedNamesAmpersandInterpolation;
begin
CheckRender('"{{&person.name}}" == "{{#person}}{{&name}}{{/person}}"','{ "person" : { "name" : "Joe" } }','"Joe" == "Joe"')
end;
procedure TInterpolationTests.TestDottedNamesArbitraryDepth;
begin
CheckRender('"{{a.b.c.d.e.name}}" == "Phil"','{ "a" : { "b" : { "c" : { "d" : { "e" : { "name" : "Phil" } } } } } }','"Phil" == "Phil"')
end;
procedure TInterpolationTests.TestDottedNamesBrokenChains;
begin
CheckRender('"{{a.b.c}}" == ""','{ "a" : {} }','"" == ""')
end;
procedure TInterpolationTests.TestDottedNamesBrokenChainResolution;
begin
CheckRender('"{{a.b.c.name}}" == ""','{ "a" : { "b" : {} }, "c" : { "name" : "Jim" } }','"" == ""')
end;
procedure TInterpolationTests.TestDottedNamesInitialResolution;
begin
CheckRender('"{{#a}}{{b.c.d.e.name}}{{/a}}" == "Phil"','{ "a" : { "b" : { "c" : { "d" : { "e" : { "name" : "Phil" } } } } }, "b" : { "c" : { "d" : { "e" : { "name" : "Wrong" } } } } }','"Phil" == "Phil"')
end;
procedure TInterpolationTests.TestInterpolationSurroundingWhitespace;
begin
CheckRender('| {{string}} |','{ "string" : "---" }','| --- |')
end;
procedure TInterpolationTests.TestTripleMustacheSurroundingWhitespace;
begin
CheckRender('| {{{string}}} |','{ "string" : "---" }','| --- |')
end;
procedure TInterpolationTests.TestAmpersandSurroundingWhitespace;
begin
CheckRender('| {{&string}} |','{ "string" : "---" }','| --- |')
end;
procedure TInterpolationTests.TestInterpolationStandalone;
begin
CheckRender(' {{string}}'+ LineEnding +'','{ "string" : "---" }',' ---'+ LineEnding +'')
end;
procedure TInterpolationTests.TestTripleMustacheStandalone;
begin
CheckRender(' {{{string}}}'+ LineEnding +'','{ "string" : "---" }',' ---'+ LineEnding +'')
end;
procedure TInterpolationTests.TestAmpersandStandalone;
begin
CheckRender(' {{&string}}'+ LineEnding +'','{ "string" : "---" }',' ---'+ LineEnding +'')
end;
procedure TInterpolationTests.TestInterpolationWithPadding;
begin
CheckRender('|{{ string }}|','{ "string" : "---" }','|---|')
end;
procedure TInterpolationTests.TestTripleMustacheWithPadding;
begin
CheckRender('|{{{ string }}}|','{ "string" : "---" }','|---|')
end;
procedure TInterpolationTests.TestAmpersandWithPadding;
begin
CheckRender('|{{& string }}|','{ "string" : "---" }','|---|')
end;
procedure TInvertedTests.TestFalsey;
begin
CheckRender('"{{^boolean}}This should be rendered.{{/boolean}}"','{ "boolean" : false }','"This should be rendered."')
end;
procedure TInvertedTests.TestTruthy;
begin
CheckRender('"{{^boolean}}This should not be rendered.{{/boolean}}"','{ "boolean" : true }','""')
end;
procedure TInvertedTests.TestContext;
begin
CheckRender('"{{^context}}Hi {{name}}.{{/context}}"','{ "context" : { "name" : "Joe" } }','""')
end;
procedure TInvertedTests.TestList;
begin
CheckRender('"{{^list}}{{n}}{{/list}}"','{ "list" : [{ "n" : 1 }, { "n" : 2 }, { "n" : 3 }] }','""')
end;
procedure TInvertedTests.TestEmptyList;
begin
CheckRender('"{{^list}}Yay lists!{{/list}}"','{ "list" : [] }','"Yay lists!"')
end;
procedure TInvertedTests.TestDoubled;
begin
CheckRender('{{^bool}}'+ LineEnding +'* first'+ LineEnding +'{{/bool}}'+ LineEnding +'* {{two}}'+ LineEnding +'{{^bool}}'+ LineEnding +'* third'+ LineEnding +'{{/bool}}'+ LineEnding +'','{ "two" : "second", "bool" : false }','* first'+ LineEnding +'* second'+ LineEnding +'* third'+ LineEnding +'')
end;
procedure TInvertedTests.TestNestedFalsey;
begin
CheckRender('| A {{^bool}}B {{^bool}}C{{/bool}} D{{/bool}} E |','{ "bool" : false }','| A B C D E |')
end;
procedure TInvertedTests.TestNestedTruthy;
begin
CheckRender('| A {{^bool}}B {{^bool}}C{{/bool}} D{{/bool}} E |','{ "bool" : true }','| A E |')
end;
procedure TInvertedTests.TestContextMisses;
begin
CheckRender('[{{^missing}}Cannot find key ''missing''!{{/missing}}]','{}','[Cannot find key ''missing''!]')
end;
procedure TInvertedTests.TestDottedNamesTruthy;
begin
CheckRender('"{{^a.b.c}}Not Here{{/a.b.c}}" == ""','{ "a" : { "b" : { "c" : true } } }','"" == ""')
end;
procedure TInvertedTests.TestDottedNamesFalsey;
begin
CheckRender('"{{^a.b.c}}Not Here{{/a.b.c}}" == "Not Here"','{ "a" : { "b" : { "c" : false } } }','"Not Here" == "Not Here"')
end;
procedure TInvertedTests.TestDottedNamesBrokenChains;
begin
CheckRender('"{{^a.b.c}}Not Here{{/a.b.c}}" == "Not Here"','{ "a" : {} }','"Not Here" == "Not Here"')
end;
procedure TInvertedTests.TestSurroundingWhitespace;
begin
CheckRender(' | {{^boolean}} | {{/boolean}} | '+ LineEnding +'','{ "boolean" : false }',' | | | '+ LineEnding +'')
end;
procedure TInvertedTests.TestInternalWhitespace;
begin
CheckRender(' | {{^boolean}} {{! Important Whitespace }}'+ LineEnding +' {{/boolean}} | '+ LineEnding +'','{ "boolean" : false }',' | '+ LineEnding +' | '+ LineEnding +'')
end;
procedure TInvertedTests.TestIndentedInlineSections;
begin
CheckRender(' {{^boolean}}NO{{/boolean}}'+ LineEnding +' {{^boolean}}WAY{{/boolean}}'+ LineEnding +'','{ "boolean" : false }',' NO'+ LineEnding +' WAY'+ LineEnding +'')
end;
procedure TInvertedTests.TestStandaloneLines;
begin
CheckRender('| This Is'+ LineEnding +'{{^boolean}}'+ LineEnding +'|'+ LineEnding +'{{/boolean}}'+ LineEnding +'| A Line'+ LineEnding +'','{ "boolean" : false }','| This Is'+ LineEnding +'|'+ LineEnding +'| A Line'+ LineEnding +'')
end;
procedure TInvertedTests.TestStandaloneIndentedLines;
begin
CheckRender('| This Is'+ LineEnding +' {{^boolean}}'+ LineEnding +'|'+ LineEnding +' {{/boolean}}'+ LineEnding +'| A Line'+ LineEnding +'','{ "boolean" : false }','| This Is'+ LineEnding +'|'+ LineEnding +'| A Line'+ LineEnding +'')
end;
procedure TInvertedTests.TestStandaloneLineEndings;
begin
CheckRender('|'+ LineEnding +'{{^boolean}}'+ LineEnding +'{{/boolean}}'+ LineEnding +'|','{ "boolean" : false }','|'+ LineEnding +'|')
end;
procedure TInvertedTests.TestStandaloneWithoutPreviousLine;
begin
CheckRender(' {{^boolean}}'+ LineEnding +'^{{/boolean}}'+ LineEnding +'/','{ "boolean" : false }','^'+ LineEnding +'/')
end;
procedure TInvertedTests.TestStandaloneWithoutNewline;
begin
CheckRender('^{{^boolean}}'+ LineEnding +'/'+ LineEnding +' {{/boolean}}','{ "boolean" : false }','^'+ LineEnding +'/'+ LineEnding +'')
end;
procedure TInvertedTests.TestPadding;
begin
CheckRender('|{{^ boolean }}={{/ boolean }}|','{ "boolean" : false }','|=|')
end;
procedure TPartialsTests.TestBasicBehavior;
begin
CheckRender('"{{>text}}"','{}','"from partial"')
end;
procedure TPartialsTests.TestFailedLookup;
begin
CheckRender('"{{>text}}"','{}','""')
end;
procedure TPartialsTests.TestContext;
begin
CheckRender('"{{>partial}}"','{ "text" : "content" }','"*content*"')
end;
procedure TPartialsTests.TestRecursion;
begin
CheckRender('{{>node}}','{ "content" : "X", "nodes" : [{ "content" : "Y", "nodes" : [] }] }','X<Y<>>')
end;
procedure TPartialsTests.TestSurroundingWhitespace;
begin
CheckRender('| {{>partial}} |','{}','| | |')
end;
procedure TPartialsTests.TestInlineIndentation;
begin
CheckRender(' {{data}} {{> partial}}'+ LineEnding +'','{ "data" : "|" }',' | >'+ LineEnding +'>'+ LineEnding +'')
end;
procedure TPartialsTests.TestStandaloneLineEndings;
begin
CheckRender('|'+ LineEnding +'{{>partial}}'+ LineEnding +'|','{}','|'+ LineEnding +'>|')
end;
procedure TPartialsTests.TestStandaloneWithoutPreviousLine;
begin
CheckRender(' {{>partial}}'+ LineEnding +'>','{}',' >'+ LineEnding +' >>')
end;
procedure TPartialsTests.TestStandaloneWithoutNewline;
begin
CheckRender('>'+ LineEnding +' {{>partial}}','{}','>'+ LineEnding +' >'+ LineEnding +' >')
end;
procedure TPartialsTests.TestStandaloneIndentation;
begin
CheckRender('\'+ LineEnding +' {{>partial}}'+ LineEnding +'/'+ LineEnding +'','{ "content" : "<\n->" }','\'+ LineEnding +' |'+ LineEnding +' <'+ LineEnding +'->'+ LineEnding +' |'+ LineEnding +'/'+ LineEnding +'')
end;
procedure TPartialsTests.TestPaddingWhitespace;
begin
CheckRender('|{{> partial }}|','{ "boolean" : true }','|[]|')
end;
procedure TSectionsTests.TestTruthy;
begin
CheckRender('"{{#boolean}}This should be rendered.{{/boolean}}"','{ "boolean" : true }','"This should be rendered."')
end;
procedure TSectionsTests.TestFalsey;
begin
CheckRender('"{{#boolean}}This should not be rendered.{{/boolean}}"','{ "boolean" : false }','""')
end;
procedure TSectionsTests.TestContext;
begin
CheckRender('"{{#context}}Hi {{name}}.{{/context}}"','{ "context" : { "name" : "Joe" } }','"Hi Joe."')
end;
procedure TSectionsTests.TestDeeplyNestedContexts;
begin
CheckRender('{{#a}}'+ LineEnding +'{{one}}'+ LineEnding +'{{#b}}'+ LineEnding +'{{one}}{{two}}{{one}}'+ LineEnding +'{{#c}}'+ LineEnding +'{{one}}{{two}}{{three}}{{two}}{{one}}'+ LineEnding +'{{#d}}'+ LineEnding +'{{one}}{{two}}{{three}}{{four}}{{three}}{{two}}{{one}}'+ LineEnding +'{{#e}}'+ LineEnding +'{{one}}{{two}}{{three}}{{four}}{{five}}{{four}}{{three}}{{two}}{{one}}'+ LineEnding +'{{/e}}'+ LineEnding +'{{one}}{{two}}{{three}}{{four}}{{three}}{{two}}{{one}}'+ LineEnding +'{{/d}}'+ LineEnding +'{{one}}{{two}}{{three}}{{two}}{{one}}'+ LineEnding +'{{/c}}'+ LineEnding +'{{one}}{{two}}{{one}}'+ LineEnding +'{{/b}}'+ LineEnding +'{{one}}'+ LineEnding +'{{/a}}'+ LineEnding +'','{ "a" : { "one" : 1 }, "b" : { "two" : 2 }, "c" : { "three" : 3 }, "d" : { "four" : 4 }, "e" : { "five" : 5 } }','1'+ LineEnding +'121'+ LineEnding +'12321'+ LineEnding +'1234321'+ LineEnding +'123454321'+ LineEnding +'1234321'+ LineEnding +'12321'+ LineEnding +'121'+ LineEnding +'1'+ LineEnding +'')
end;
procedure TSectionsTests.TestList;
begin
CheckRender('"{{#list}}{{item}}{{/list}}"','{ "list" : [{ "item" : 1 }, { "item" : 2 }, { "item" : 3 }] }','"123"')
end;
procedure TSectionsTests.TestEmptyList;
begin
CheckRender('"{{#list}}Yay lists!{{/list}}"','{ "list" : [] }','""')
end;
procedure TSectionsTests.TestDoubled;
begin
CheckRender('{{#bool}}'+ LineEnding +'* first'+ LineEnding +'{{/bool}}'+ LineEnding +'* {{two}}'+ LineEnding +'{{#bool}}'+ LineEnding +'* third'+ LineEnding +'{{/bool}}'+ LineEnding +'','{ "two" : "second", "bool" : true }','* first'+ LineEnding +'* second'+ LineEnding +'* third'+ LineEnding +'')
end;
procedure TSectionsTests.TestNestedTruthy;
begin
CheckRender('| A {{#bool}}B {{#bool}}C{{/bool}} D{{/bool}} E |','{ "bool" : true }','| A B C D E |')
end;
procedure TSectionsTests.TestNestedFalsey;
begin
CheckRender('| A {{#bool}}B {{#bool}}C{{/bool}} D{{/bool}} E |','{ "bool" : false }','| A E |')
end;
procedure TSectionsTests.TestContextMisses;
begin
CheckRender('[{{#missing}}Found key ''missing''!{{/missing}}]','{}','[]')
end;
procedure TSectionsTests.TestImplicitIteratorString;
begin
CheckRender('"{{#list}}({{.}}){{/list}}"','{ "list" : ["a", "b", "c", "d", "e"] }','"(a)(b)(c)(d)(e)"')
end;
procedure TSectionsTests.TestImplicitIteratorInteger;
begin
CheckRender('"{{#list}}({{.}}){{/list}}"','{ "list" : [1, 2, 3, 4, 5] }','"(1)(2)(3)(4)(5)"')
end;
procedure TSectionsTests.TestImplicitIteratorDecimal;
begin
CheckRender('"{{#list}}({{.}}){{/list}}"','{ "list" : [1.10000000000000E+000, 2.20000000000000E+000, 3.30000000000000E+000, 4.40000000000000E+000, 5.50000000000000E+000] }','"(1.1)(2.2)(3.3)(4.4)(5.5)"')
end;
procedure TSectionsTests.TestDottedNamesTruthy;
begin
CheckRender('"{{#a.b.c}}Here{{/a.b.c}}" == "Here"','{ "a" : { "b" : { "c" : true } } }','"Here" == "Here"')
end;
procedure TSectionsTests.TestDottedNamesFalsey;
begin
CheckRender('"{{#a.b.c}}Here{{/a.b.c}}" == ""','{ "a" : { "b" : { "c" : false } } }','"" == ""')
end;
procedure TSectionsTests.TestDottedNamesBrokenChains;
begin
CheckRender('"{{#a.b.c}}Here{{/a.b.c}}" == ""','{ "a" : {} }','"" == ""')
end;
procedure TSectionsTests.TestSurroundingWhitespace;
begin
CheckRender(' | {{#boolean}} | {{/boolean}} | '+ LineEnding +'','{ "boolean" : true }',' | | | '+ LineEnding +'')
end;
procedure TSectionsTests.TestInternalWhitespace;
begin
CheckRender(' | {{#boolean}} {{! Important Whitespace }}'+ LineEnding +' {{/boolean}} | '+ LineEnding +'','{ "boolean" : true }',' | '+ LineEnding +' | '+ LineEnding +'')
end;
procedure TSectionsTests.TestIndentedInlineSections;
begin
CheckRender(' {{#boolean}}YES{{/boolean}}'+ LineEnding +' {{#boolean}}GOOD{{/boolean}}'+ LineEnding +'','{ "boolean" : true }',' YES'+ LineEnding +' GOOD'+ LineEnding +'')
end;
procedure TSectionsTests.TestStandaloneLines;
begin
CheckRender('| This Is'+ LineEnding +'{{#boolean}}'+ LineEnding +'|'+ LineEnding +'{{/boolean}}'+ LineEnding +'| A Line'+ LineEnding +'','{ "boolean" : true }','| This Is'+ LineEnding +'|'+ LineEnding +'| A Line'+ LineEnding +'')
end;
procedure TSectionsTests.TestIndentedStandaloneLines;
begin
CheckRender('| This Is'+ LineEnding +' {{#boolean}}'+ LineEnding +'|'+ LineEnding +' {{/boolean}}'+ LineEnding +'| A Line'+ LineEnding +'','{ "boolean" : true }','| This Is'+ LineEnding +'|'+ LineEnding +'| A Line'+ LineEnding +'')
end;
procedure TSectionsTests.TestStandaloneLineEndings;
begin
CheckRender('|'+ LineEnding +'{{#boolean}}'+ LineEnding +'{{/boolean}}'+ LineEnding +'|','{ "boolean" : true }','|'+ LineEnding +'|')
end;
procedure TSectionsTests.TestStandaloneWithoutPreviousLine;
begin
CheckRender(' {{#boolean}}'+ LineEnding +'#{{/boolean}}'+ LineEnding +'/','{ "boolean" : true }','#'+ LineEnding +'/')
end;
procedure TSectionsTests.TestStandaloneWithoutNewline;
begin
CheckRender('#{{#boolean}}'+ LineEnding +'/'+ LineEnding +' {{/boolean}}','{ "boolean" : true }','#'+ LineEnding +'/'+ LineEnding +'')
end;
procedure TSectionsTests.TestPadding;
begin
CheckRender('|{{# boolean }}={{/ boolean }}|','{ "boolean" : true }','|=|')
end;
procedure TLambdasTests.TestInterpolation;
begin
CheckRender('Hello, {{lambda}}!','{ "lambda" : { "php" : "return \"world\";", "clojure" : "(fn [] \"world\")", "__tag__" : "code", "perl" : "sub { \"world\" }", "python" : "lambda: \"world\"", "ruby" : "proc { \"world\" }", "js" : "function() { return \"world\" }" } }','Hello, world!')
end;
procedure TLambdasTests.TestInterpolationExpansion;
begin
CheckRender('Hello, {{lambda}}!','{ "planet" : "world", "lambda" : { "php" : "return \"{{planet}}\";", "clojure" : "(fn [] \"{{planet}}\")", "__tag__" : "code", "perl" : "sub { \"{{planet}}\" }", "python" : "lambda: \"{{planet}}\"", "ruby" : "proc { \"{{planet}}\" }", "js" : "function() { return \"{{planet}}\" }" } }','Hello, world!')
end;
procedure TLambdasTests.TestInterpolationAlternateDelimiters;
begin
CheckRender('{{= | | =}}'+ LineEnding +'Hello, (|&lambda|)!','{ "planet" : "world", "lambda" : { "php" : "return \"|planet| => {{planet}}\";", "clojure" : "(fn [] \"|planet| => {{planet}}\")", "__tag__" : "code", "perl" : "sub { \"|planet| => {{planet}}\" }", "python" : "lambda: \"|planet| => {{planet}}\"", "ruby" : "proc { \"|planet| => {{planet}}\" }", "js" : "function() { return \"|planet| => {{planet}}\" }" } }','Hello, (|planet| => world)!')
end;
procedure TLambdasTests.TestInterpolationMultipleCalls;
begin
CheckRender('{{lambda}} == {{{lambda}}} == {{lambda}}','{ "lambda" : { "php" : "global $calls; return ++$calls;", "clojure" : "(def g (atom 0)) (fn [] (swap! g inc))", "__tag__" : "code", "perl" : "sub { no strict; $calls += 1 }", "python" : "lambda: globals().update(calls=globals().get(\"calls\",0)+1) or calls", "ruby" : "proc { $calls ||= 0; $calls += 1 }", "js" : "function() { return (g=(function(){return this})()).calls=(g.calls||0)+1 }" } }','1 == 2 == 3')
end;
procedure TLambdasTests.TestEscaping;
begin
CheckRender('<{{lambda}}{{{lambda}}}','{ "lambda" : { "php" : "return \">\";", "clojure" : "(fn [] \">\")", "__tag__" : "code", "perl" : "sub { \">\" }", "python" : "lambda: \">\"", "ruby" : "proc { \">\" }", "js" : "function() { return \">\" }" } }','<>>')
end;
procedure TLambdasTests.TestSection;
begin
CheckRender('<{{#lambda}}{{x}}{{/lambda}}>','{ "x" : "Error!", "lambda" : { "php" : "return ($text == \"{{x}}\") ? \"yes\" : \"no\";", "clojure" : "(fn [text] (if (= text \"{{x}}\") \"yes\" \"no\"))", "__tag__" : "code", "perl" : "sub { $_[0] eq \"{{x}}\" ? \"yes\" : \"no\" }", "python" : "lambda text: text == \"{{x}}\" and \"yes\" or \"no\"", "ruby" : "proc { |text| text == \"{{x}}\" ? \"yes\" : \"no\" }", "js" : "function(txt) { return (txt == \"{{x}}\" ? \"yes\" : \"no\") }" } }','<yes>')
end;
procedure TLambdasTests.TestSectionExpansion;
begin
CheckRender('<{{#lambda}}-{{/lambda}}>','{ "planet" : "Earth", "lambda" : { "php" : "return $text . \"{{planet}}\" . $text;", "clojure" : "(fn [text] (str text \"{{planet}}\" text))", "__tag__" : "code", "perl" : "sub { $_[0] . \"{{planet}}\" . $_[0] }", "python" : "lambda text: \"%s{{planet}}%s\" % (text, text)", "ruby" : "proc { |text| \"#{text}{{planet}}#{text}\" }", "js" : "function(txt) { return txt + \"{{planet}}\" + txt }" } }','<-Earth->')
end;
procedure TLambdasTests.TestSectionAlternateDelimiters;
begin
CheckRender('{{= | | =}}<|#lambda|-|/lambda|>','{ "planet" : "Earth", "lambda" : { "php" : "return $text . \"{{planet}} => |planet|\" . $text;", "clojure" : "(fn [text] (str text \"{{planet}} => |planet|\" text))", "__tag__" : "code", "perl" : "sub { $_[0] . \"{{planet}} => |planet|\" . $_[0] }", "python" : "lambda text: \"%s{{planet}} => |planet|%s\" % (text, text)", "ruby" : "proc { |text| \"#{text}{{planet}} => |planet|#{text}\" }", "js" : "function(txt) { return txt + \"{{planet}} => |planet|\" + txt }" } }','<-{{planet}} => Earth->')
end;
procedure TLambdasTests.TestSectionMultipleCalls;
begin
CheckRender('{{#lambda}}FILE{{/lambda}} != {{#lambda}}LINE{{/lambda}}','{ "lambda" : { "php" : "return \"__\" . $text . \"__\";", "clojure" : "(fn [text] (str \"__\" text \"__\"))", "__tag__" : "code", "perl" : "sub { \"__\" . $_[0] . \"__\" }", "python" : "lambda text: \"__%s__\" % (text)", "ruby" : "proc { |text| \"__#{text}__\" }", "js" : "function(txt) { return \"__\" + txt + \"__\" }" } }','__FILE__ != __LINE__')
end;
procedure TLambdasTests.TestInvertedSection;
begin
CheckRender('<{{^lambda}}{{static}}{{/lambda}}>','{ "static" : "static", "lambda" : { "php" : "return false;", "clojure" : "(fn [text] false)", "__tag__" : "code", "perl" : "sub { 0 }", "python" : "lambda text: 0", "ruby" : "proc { |text| false }", "js" : "function(txt) { return false }" } }','<>')
end;
initialization
RegisterTest('Mustache', TCommentsTests.Suite);
RegisterTest('Mustache', TDelimitersTests.Suite);
RegisterTest('Mustache', TInterpolationTests.Suite);
RegisterTest('Mustache', TInvertedTests.Suite);
RegisterTest('Mustache', TPartialsTests.Suite);
RegisterTest('Mustache', TSectionsTests.Suite);
RegisterTest('Mustache', TLambdasTests.Suite);
end.
|
unit UFiles;
//------------------------------------------------------------------------------
// модуль реализует класс доступа к файлам
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
interface
uses
SysUtils, Windows;
//------------------------------------------------------------------------------
type
//------------------------------------------------------------------------------
//! режим открытия файла
//------------------------------------------------------------------------------
TFileAccessMode = (famRead, famReadStrict, famWrite, famWriteStrict);
//------------------------------------------------------------------------------
//! класс доступа к файлам
//------------------------------------------------------------------------------
TFileHandler = class
private
//! windows handle
FHandle: THandle;
//! режим открытия
FMode: TFileAccessMode;
//! текущий размер
FSize: Int64;
//! текущая позиция
FPosition: Int64;
//!
procedure Set_Size(
ASize: Int64
);
//!
procedure Set_Position(
APosition: Int64
);
public
//! размер
property Size: Int64 read FSize write Set_Size;
//! позиция
property Position: Int64 read FPosition write Set_Position;
//!
constructor Create(
const AFileName: string;
const AMode: TFileAccessMode
);
//!
destructor Destroy(); override;
//! чтение из памяти в файл
//! = запись в наш файл
procedure ReadFromMem(
const AMem: Pointer;
const ASize: DWORD
);
//! запись в память из файла
//! = чтение из нашего файла
procedure WriteToMem(
const AMem: Pointer;
const ASize: DWORD
);
//! чтение из внешнего файла в файл
//! = запись в наш файл
procedure ReadFromFile(
const AFileName: string
);
//! запись во внешний файл из файла
//! = чтение из нашего файла
procedure WriteToFile(
const AFileName: string
);
//! переименование файла - делает несколько попыток (CTryCount)
//! классовая ф.
{!
@return
Вернёт True при успешном переименовании, иначе False
}
class function RenameFile(
const AFrom: string;
const ATo: string
): Boolean;
//! удаление файла - делает несколько попыток (CTryCount)
//! классовая ф.
{!
@return
Вернёт True при успешном удалении, иначе False
}
class function DeleteFile(
const AFileName: string
): Boolean;
//! получить размер файла
//! классовая ф.
{!
@return
Вернёт размер файла при успешном его определении, иначе -1
}
class function GetFileSize(
const AFileName: string
): Int64;
//! попытаться открыть файл конечное число (COpenCount) раз
//! классовая ф.
{!
@param in
AFileName - полный путь к файлу
@param in
AMode - режим открытия файла
@param out
RFile - класс файла
@param out
RErrorMes - сообщение об ошибке
@return
Вернет True при успешном открытии, иначе - False
}
class function TryCreate(
const AFileName: string;
const AMode: TFileAccessMode;
var RFile: TFileHandler;
var RErrorMes: string
): Boolean;
end;
//------------------------------------------------------------------------------
implementation
const
//------------------------------------------------------------------------------
//! количество попыток для переименования и удаления
//------------------------------------------------------------------------------
CTryCount = 10;
//------------------------------------------------------------------------------
//! количество попыток для открытия/создания
//------------------------------------------------------------------------------
COpenCount = 100;
//------------------------------------------------------------------------------
//! размер буфера (= размеру страницы)
//------------------------------------------------------------------------------
CThreshold = 4096;
//------------------------------------------------------------------------------
//! размер буфера как Int64
//------------------------------------------------------------------------------
CThresholdL: Int64 = CThreshold;
//------------------------------------------------------------------------------
//! сообщения об ошибках
//------------------------------------------------------------------------------
CFHWrongOperation: string = 'Операция противоречит режиму открытия файла';
CFHWriteError: string = 'Ошибка записи в файл: записано меньше запрошенного';
CFHReadError: string = 'Ошибка чтения из файла: прочитано меньше запрошенного';
CFHReadSizeError: string = 'Попытка задания размера для файла на чтение';
CFHReadPositionError: string = 'Попытка задания позиции более размера для файла на чтение'#13#10'( %u / %u )';
//------------------------------------------------------------------------------
type
//------------------------------------------------------------------------------
//! для функции GetFileSize
//------------------------------------------------------------------------------
TRecordQWord = packed record
case Boolean of
False: (QW: UInt64);
True: (DW0, DW1: Uint32);
end;
//------------------------------------------------------------------------------
// TFileHandler
//------------------------------------------------------------------------------
constructor TFileHandler.Create(
const AFileName: string;
const AMode: TFileAccessMode
);
var
//!
AccessR: DWORD;
//!
ShareR: DWORD;
//!
Position: DWORD;
//!
ErrorCode: DWORD;
//------------------------------------------------------------------------------
begin
inherited Create();
//
FMode := AMode;
//
if (AMode = famRead) or (AMode = famReadStrict) then
begin
AccessR := GENERIC_READ;
Position := FILE_BEGIN; // по-умолчанию читаем сначала
end
else
begin // (AMode = famWrite) or (AMode = famWriteStrict) // и другого не дано, чтобы там компилятор себе не думал
AccessR := GENERIC_WRITE;
Position := FILE_END; // по-умолчанию пишем в конец
end;
//
ShareR := 0;
case AMode of
famRead: ShareR := FILE_SHARE_WRITE or FILE_SHARE_READ;
famWrite: ShareR := FILE_SHARE_READ or FILE_SHARE_DELETE;
end;
//
FHandle := CreateFile(
PChar(AFileName),
AccessR,
ShareR,
nil,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
// FILE_ATTRIBUTE_NORMAL or FILE_FLAG_WRITE_THROUGH, // немедленно записывать на диск <- !!! НЕ ИСПОЛЬЗОВАТЬ !!!
0
);
//
ErrorCode := GetLastError();
if (FHandle = INVALID_HANDLE_VALUE) then
RaiseLastOSError(ErrorCode);
// берём размер
if not SetFilePointerEx(FHandle, 0, @FSize, FILE_END) then
RaiseLastOSError();
// устанавливаем позицию
if not SetFilePointerEx(FHandle, 0, @FPosition, Position) then
RaiseLastOSError();
end;
destructor TFileHandler.Destroy();
begin
if (FHandle <> INVALID_HANDLE_VALUE) and (FHandle <> 0) then
CloseHandle(FHandle);
//
inherited Destroy();
end;
procedure TFileHandler.Set_Size(
ASize: Int64
);
begin
if (FMode = famRead) or (FMode = famReadStrict) then
raise Exception.Create(CFHReadSizeError);
if not SetFilePointerEx(FHandle, ASize, @FPosition, FILE_BEGIN) then
RaiseLastOSError();
if not SetEndOfFile(FHandle) then
RaiseLastOSError();
end;
procedure TFileHandler.Set_Position(
APosition: Int64
);
begin
if (FMode = famRead) or (FMode = famReadStrict) then
begin
if (APosition > FSize) then // отсутствие проверки на равенство - не ошибка
raise Exception.CreateFmt(CFHReadPositionError, [APosition, FSize]);
end;
if not SetFilePointerEx(FHandle, APosition, @FPosition, FILE_BEGIN) then
RaiseLastOSError();
end;
procedure TFileHandler.ReadFromMem(
const AMem: Pointer;
const ASize: DWORD
);
var
//!
Actual: DWORD;
//------------------------------------------------------------------------------
begin
if (FMode = famRead) or (FMode = famReadStrict) then
raise Exception.Create(CFHWrongOperation);
if not Windows.WriteFile(FHandle, AMem^, ASize, Actual, nil) then
RaiseLastOSError();
if (ASize <> Actual) then
raise Exception.Create(CFHWriteError);
FPosition := FPosition + Int64(ASize);
if (FSize < FPosition) then
FSize := FPosition;
end;
procedure TFileHandler.WriteToMem(
const AMem: Pointer;
const ASize: DWORD
);
var
//!
Actual: DWORD;
//------------------------------------------------------------------------------
begin
if (FMode = famWrite) or (FMode = famWriteStrict) then
raise Exception.Create(CFHWrongOperation);
if not Windows.ReadFile(FHandle, AMem^, ASize, Actual, nil) then
RaiseLastOSError();
if (ASize <> Actual) then
raise Exception.Create(CFHReadError);
FPosition := FPosition + Int64(ASize);
end;
procedure TFileHandler.ReadFromFile(
const AFileName: string
);
var
//!
FileInput: TFileHandler;
//!
Buffer: Pointer;
//!
Rem: Integer;
//------------------------------------------------------------------------------
begin
if (FMode = famRead) or (FMode = famReadStrict) then
raise Exception.Create(CFHWrongOperation);
FileInput := TFileHandler.Create(AFileName, famReadStrict);
try
GetMem(Buffer, CThreshold);
try
while (FileInput.Size - FileInput.Position > CThresholdL) do
begin
FileInput.WriteToMem(Buffer, CThreshold);
ReadFromMem(Buffer, CThreshold);
end;
Rem := Integer(FileInput.Size - FileInput.Position);
FileInput.WriteToMem(Buffer, Rem);
ReadFromMem(Buffer, Rem);
finally
FreeMem(Buffer);
end;
finally
FileInput.Free();
end;
end;
procedure TFileHandler.WriteToFile(
const AFileName: string
);
var
//!
FileOutput: TFileHandler;
//!
Buffer: Pointer;
//!
Rem: Integer;
//------------------------------------------------------------------------------
begin
if (FMode = famWrite) or (FMode = famWriteStrict) then
raise Exception.Create(CFHWrongOperation);
FileOutput := TFileHandler.Create(AFileName, famWriteStrict);
try
GetMem(Buffer, CThreshold);
try
Position := 0; // пишем всегда весь файл
while (Size - Position > CThresholdL) do
begin
WriteToMem(Buffer, CThreshold);
FileOutput.ReadFromMem(Buffer, CThreshold);
end;
Rem := Integer(Size - Position);
WriteToMem(Buffer, Rem);
FileOutput.ReadFromMem(Buffer, Rem);
finally
FreeMem(Buffer);
end;
finally
FileOutput.Free();
end;
end;
class function TFileHandler.RenameFile(
const AFrom: string;
const ATo: string
): Boolean;
var
//!
Conter: Integer;
//------------------------------------------------------------------------------
begin
Result := False;
if not SysUtils.FileExists(AFrom) then Exit;
if SysUtils.FileExists(ATo) then Exit;
Conter := CTryCount;
repeat
if SysUtils.RenameFile(AFrom, ATo) then Exit(True);
Dec(Conter);
Windows.Sleep(1); // ждём не менее цикла
until (Conter = 0);
end;
class function TFileHandler.DeleteFile(
const AFileName: string
): Boolean;
var
//!
Conter: Integer;
//------------------------------------------------------------------------------
begin
Result := True;
if not SysUtils.FileExists(AFileName) then Exit;
Conter := CTryCount;
repeat
if SysUtils.DeleteFile(AFileName) then Exit;
Dec(Conter);
Windows.Sleep(1); // ждём не менее цикла
until (Conter = 0);
Result := False;
end;
class function TFileHandler.GetFileSize(
const AFileName: string
): Int64;
var
//!
FileAttr: TWin32FileAttributeData;
//!
Rez: TRecordQWord;
//------------------------------------------------------------------------------
begin
Result := -1;
if (AFileName = '') then Exit;
if not Windows.GetFileAttributesEx(PChar(AFileName), GetFileExInfoStandard, @FileAttr) then Exit;
Rez.DW0 := FileAttr.nFileSizeLow;
Rez.DW1 := FileAttr.nFileSizeHigh;
Result := Rez.QW;
end;
class function TFileHandler.TryCreate(
const AFileName: string;
const AMode: TFileAccessMode;
var RFile: TFileHandler;
var RErrorMes: string
): Boolean;
var
//!
Counter: Integer;
//------------------------------------------------------------------------------
begin
Result := False;
RFile := nil;
RErrorMes := '';
for Counter := 0 to COpenCount do
begin
try
RFile := TFileHandler.Create(AFileName, AMode);
Exit(True);
except
on Ex: Exception do
begin
RErrorMes := Ex.Message;
Windows.Sleep(1); // ждём не менее цикла
end;
end;
end;
end;
end.
|
unit uFrameObjectFilter;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, Menus, StdCtrls, cxButtons,
cxDropDownEdit, cxCalendar, cxTextEdit, cxCurrencyEdit, cxMaskEdit,
cxButtonEdit, cxContainer, cxEdit, cxGroupBox, cxPC, cxControls, uParams,
cxCheckBox, cxDBEdit, ExtCtrls, dxBar, ImgList, cxGraphics, cxClasses,
cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, DB, ADODB, uDlgObjectFilterTypeSelector;
type
TFrameObjectFilter = class(TFrame)
ScrollBox: TScrollBox;
pnlButtons: TPanel;
pcPropsFilter: TcxPageControl;
tsCommon: TcxTabSheet;
Label13: TLabel;
Label14: TLabel;
Label15: TLabel;
Label17: TLabel;
Label2: TLabel;
Label3: TLabel;
Label6: TLabel;
Label7: TLabel;
Label44: TLabel;
Label45: TLabel;
Label46: TLabel;
Label4: TLabel;
Label5: TLabel;
Label25: TLabel;
Label26: TLabel;
Label27: TLabel;
Label28: TLabel;
Label29: TLabel;
cxGroupBox8: TcxGroupBox;
Label30: TLabel;
Label32: TLabel;
Label1: TLabel;
beRegion: TcxButtonEdit;
beSettlement: TcxButtonEdit;
beStreet: TcxButtonEdit;
cxGroupBox9: TcxGroupBox;
Label18: TLabel;
Label19: TLabel;
Label20: TLabel;
Label10: TLabel;
Label11: TLabel;
Label12: TLabel;
Label16: TLabel;
Label21: TLabel;
Label22: TLabel;
ceBalansCost1: TcxCurrencyEdit;
ceBalansCost2: TcxCurrencyEdit;
ceWear1: TcxCurrencyEdit;
ceWear2: TcxCurrencyEdit;
ceRemainder1: TcxCurrencyEdit;
ceRemainder2: TcxCurrencyEdit;
teReestrNum: TcxTextEdit;
deDate1: TcxDateEdit;
deDate2: TcxDateEdit;
beOKOF: TcxButtonEdit;
teInventNum: TcxTextEdit;
ceAmort1: TcxCurrencyEdit;
ceAmort2: TcxCurrencyEdit;
cePeriod1: TcxCurrencyEdit;
cePeriod2: TcxCurrencyEdit;
teInventNumEnterprise: TcxTextEdit;
deInWorkDate1: TcxDateEdit;
deInWorkDate2: TcxDateEdit;
cbInKazna: TcxCheckBox;
beObjectType: TcxButtonEdit;
tsConstract: TcxTabSheet;
cxGroupBox10: TcxGroupBox;
Label58: TLabel;
Label59: TLabel;
Label60: TLabel;
Label61: TLabel;
Label62: TLabel;
Label31: TLabel;
Label33: TLabel;
Label36: TLabel;
teContractNum: TcxTextEdit;
beType: TcxButtonEdit;
beWho1: TcxButtonEdit;
beWho2: TcxButtonEdit;
deContractDate1: TcxDateEdit;
deContractDate2: TcxDateEdit;
beContract: TcxButtonEdit;
cxGroupBox12: TcxGroupBox;
Label69: TLabel;
Label70: TLabel;
Label71: TLabel;
Label72: TLabel;
Label73: TLabel;
Label34: TLabel;
Label35: TLabel;
teFoundationNum: TcxTextEdit;
deFoundationDate1: TcxDateEdit;
deFoundationDate2: TcxDateEdit;
beFoundationType: TcxButtonEdit;
teFoundationName: TcxTextEdit;
teFoundationComment: TcxTextEdit;
teOKOF: TcxTextEdit;
Label8: TLabel;
beStatus: TcxButtonEdit;
Label9: TLabel;
beView: TcxButtonEdit;
Label23: TLabel;
teName: TcxTextEdit;
Label24: TLabel;
teAddress: TcxTextEdit;
Label37: TLabel;
Label38: TLabel;
Label39: TLabel;
Label40: TLabel;
teComment: TcxTextEdit;
Label41: TLabel;
Label42: TLabel;
Label43: TLabel;
Label47: TLabel;
Bevel1: TBevel;
BarManagerFilter: TdxBarManager;
bbApplyFilter: TdxBarButton;
bbDropFilter: TdxBarButton;
BarManagerFilterBar1: TdxBar;
ilFilter: TcxImageList;
Label48: TLabel;
cbDepartment: TcxComboBox;
Label49: TLabel;
teImportFrom: TcxTextEdit;
Label50: TLabel;
cbRegistered: TcxCheckBox;
private
{ Private declarations }
protected
dlgObjectFilterTypeSelector: TDlgObjectFilterTypeSelector;
procedure btnDropFilterClick(Sender: TObject); virtual;
procedure beOKOFPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); virtual;
procedure beContractPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); virtual;
procedure bePropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); virtual;
procedure beObjectTypePropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); virtual;
procedure cbDepartmentPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); virtual;
public
ObjectType_IDs: variant;
OKOF_ID: variant;
Region_ID: variant;
Settlement_ID: variant;
Street_ID: variant;
procedure OKOFPropertiesButtonClick(AButtonIndex: Integer); virtual;
procedure RegionPropertiesButtonClick(AButtonIndex: Integer); virtual;
function CreateFilterParams: TParamCollection; virtual;
procedure ClearFilter; virtual;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
implementation
uses uAccess, uFrmOKOF, uUserBook, uCommonUtils, uDlgObject_selector,
uMain;
{$R *.dfm}
{ TFrameObjectFilter }
constructor TFrameObjectFilter.Create(AOwner: TComponent);
begin
inherited;
beOKOF.Properties.OnButtonClick:=beOKOFPropertiesButtonClick;
beContract.Properties.OnButtonClick:=beContractPropertiesButtonClick;
beObjectType.Properties.OnButtonClick:=beObjectTypePropertiesButtonClick;
bbDropFilter.OnClick:=btnDropFilterClick;
beRegion.Properties.OnButtonClick:=bePropertiesButtonClick;
beSettlement.Properties.OnButtonClick:=bePropertiesButtonClick;
beStreet.Properties.OnButtonClick:=bePropertiesButtonClick;
beType.Properties.OnButtonClick:=bePropertiesButtonClick;
beWho1.Properties.OnButtonClick:=bePropertiesButtonClick;
beWho2.Properties.OnButtonClick:=bePropertiesButtonClick;
beStatus.Properties.OnButtonClick:=bePropertiesButtonClick;
beView.Properties.OnButtonClick:=bePropertiesButtonClick;
beFoundationType.Properties.OnButtonClick:=bePropertiesButtonClick;
cbDepartment.Properties.OnButtonClick:=cbDepartmentPropertiesButtonClick;
dlgObjectFilterTypeSelector:=nil;
end;
function TFrameObjectFilter.CreateFilterParams: TParamCollection;
var
p: TParamCollection;
begin
result:=TParamCollection.Create(TParamItem);
p:=result;
p[beObjectType.HelpKeyword].Value:=ObjectType_IDs;
p[teReestrNum.HelpKeyword].Value:=StrToVariant(teReestrNum.Text);
p[cbDepartment.HelpKeyword].Value:=IntToVariant(cbDepartment.ItemIndex+1);
p[beStatus.HelpKeyword].Value:=IntToVariant(beStatus.HelpContext);
p[beView.HelpKeyword].Value:=IntToVariant(beView.HelpContext);
p[teName.HelpKeyword].Value:=StrToVariant(teName.Text);
p[teInventNum.HelpKeyword].Value:=StrToVariant(teInventNum.Text);
p[teInventNumEnterprise.HelpKeyword].Value:=StrToVariant(teInventNumEnterprise.Text);
p[ceAmort1.HelpKeyword].Value:=FloatToVariant(ceAmort1.Value);
p[ceAmort2.HelpKeyword].Value:=FloatToVariant(ceAmort2.Value);
p[cePeriod1.HelpKeyword].Value:=FloatToVariant(cePeriod1.Value);
p[cePeriod2.HelpKeyword].Value:=FloatToVariant(cePeriod2.Value);
p[deDate1.HelpKeyword].Value:=DateToVariant(deDate1.Date);
p[deDate2.HelpKeyword].Value:=DateToVariant(deDate2.Date);
p[beOKOF.HelpKeyword].Value:=IntToVariant(beOKOF.HelpContext);
p[deInWorkDate1.HelpKeyword].Value:=DateToVariant(deInWorkDate1.Date);
p[deInWorkDate2.HelpKeyword].Value:=DateToVariant(deInWorkDate2.Date);
p[cbInKazna.HelpKeyword].Value:=BooleanToVariant(cbInKazna.Checked, cbInKazna.State = cbsGrayed);
p[teComment.HelpKeyword].Value:=StrToVariant(teComment.Text);
p[beRegion.HelpKeyword].Value:=IntToVariant(beRegion.HelpContext);
p[beSettlement.HelpKeyword].Value:=IntToVariant(beSettlement.HelpContext);
p[beStreet.HelpKeyword].Value:=IntToVariant(beStreet.HelpContext);
p[teAddress.HelpKeyword].Value:=StrToVariant(teAddress.Text);
p[ceBalansCost1.HelpKeyword].Value:=FloatToVariant(ceBalansCost1.Value);
p[ceBalansCost2.HelpKeyword].Value:=FloatToVariant(ceBalansCost2.Value);
p[ceWear1.HelpKeyword].Value:=FloatToVariant(ceWear1.Value);
p[ceWear2.HelpKeyword].Value:=FloatToVariant(ceWear2.Value);
p[ceRemainder1.HelpKeyword].Value:=FloatToVariant(ceRemainder1.Value);
p[ceRemainder1.HelpKeyword].Value:=FloatToVariant(ceRemainder1.Value);
//Закрепление объекта
p[beContract.HelpKeyword].Value:=IntToVariant(beContract.HelpContext);
p[beContract.HelpKeyword+'_IsNull'].Value:=BooleanToVariant(beContract.HelpContext=-1, false);
p[teContractNum.HelpKeyword].Value:=StrToVariant(teContractNum.Text);
p[deContractDate1.HelpKeyword].Value:=DateToVariant(deContractDate1.Date);
p[deContractDate2.HelpKeyword].Value:=DateToVariant(deContractDate2.Date);
p[beType.HelpKeyword].Value:=IntToVariant(beType.HelpContext);
p[beWho1.HelpKeyword].Value:=IntToVariant(beWho1.HelpContext);
p[beWho2.HelpKeyword].Value:=IntToVariant(beWho2.HelpContext);
p[teFoundationNum.HelpKeyword].Value:=StrToVariant(teFoundationNum.Text);
p[deFoundationDate1.HelpKeyword].Value:=DateToVariant(deFoundationDate1.Date);
p[deFoundationDate2.HelpKeyword].Value:=DateToVariant(deFoundationDate2.Date);
p[beFoundationType.HelpKeyword].Value:=IntToVariant(beFoundationType.HelpContext);
p[teFoundationName.HelpKeyword].Value:=StrToVariant(teFoundationName.Text);
p[teFoundationComment.HelpKeyword].Value:=StrToVariant(teFoundationComment.Text);
p[teImportFrom.HelpKeyword].Value:=StrToVariant(teImportFrom.Text);
p[cbRegistered.HelpKeyword].Value:=BooleanToVariant(cbRegistered.Checked, cbRegistered.State = cbsGrayed);
end;
procedure TFrameObjectFilter.OKOFPropertiesButtonClick(
AButtonIndex: Integer);
var
a: TAccessSelectorForm;
p: TParamCollection;
begin
if AButtonIndex = 0 then begin
OKOF_ID:=null;
beOKOF.Text:='';
end;
if AButtonIndex = 1 then begin
a:=TAccessSelectorForm.Create;
a.ObjectID:=9;
a.FormClass:=TfrmOKOF;
p:=TParamCollection.Create(TParamItem);
try
p.Add('код_ОКОФ').Value:=OKOF_ID;
p.Add('Код');
p.Add('Наименование');
if a.ShowModal(p, null)<>mrOK then exit;
OKOF_ID:=p['код_ОКОФ'].Value;
beOKOF.Text:=p['Код'].Value;
finally
p.Free;
end;
end;
end;
procedure TFrameObjectFilter.RegionPropertiesButtonClick(
AButtonIndex: Integer);
var
a: TAccessBook;
begin
if AButtonIndex = 0 then begin
Region_ID:=null;
beRegion.Text:='';
end;
if AButtonIndex = 1 then begin
a:=TAccessBook.Create;
try
a.ObjectID:=50;
if a.ShowModal(Region_ID, false, false)<>mrOK then exit;
Region_ID:=(a.UserBook as TUserBook).PrimaryKeyValue;
beRegion.Text:=(a.UserBook as TUserBook).FieldValue['Район.Район'];
finally
a.Free;
end;
end;
end;
procedure TFrameObjectFilter.bePropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
a: TAccessSelectorForm;
be: TcxButtonEdit;
rk: variant;
begin
be:=Sender as TcxButtonEdit;
if AButtonIndex = 0 then begin
be.HelpContext:=0;
be.Text:='';
end;
if AButtonIndex = 1 then begin
a:=TAccessSelectorForm.Create;
try
a.ObjectID:=be.Tag;
rk:=null;
if be.HelpContext>0 then
rk:=be.HelpContext;
if a.ShowModal(nil, rk)<>mrOK then exit;
be.HelpContext:=a.PrimaryKeyValue;
be.Text:=a.CurRecordValues[be.Properties.ImeName].Value;
finally
a.Free;
end;
end;
end;
procedure TFrameObjectFilter.beOKOFPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
a: TAccessSelectorForm;
p: TParamCollection;
begin
if AButtonIndex = 0 then begin
beOKOF.HelpContext:=0;
beOKOF.Text:='';
teOKOF.Text:='';
end;
if AButtonIndex = 1 then begin
a:=TAccessSelectorForm.Create;
a.ObjectID:=9;
a.FormClass:=TfrmOKOF;
p:=TParamCollection.Create(TParamItem);
try
p.Add('код_ОКОФ').Value:=beOKOF.HelpContext;
p.Add('Код');
p.Add('Наименование');
if a.ShowModal(p, null)<>mrOK then exit;
beOKOF.HelpContext:=p['код_ОКОФ'].Value;
beOKOF.Text:=p['Код'].Value;
teOKOF.Text:=p['Наименование'].Value;
finally
p.Free;
end;
end;
end;
procedure TFrameObjectFilter.beContractPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
a: TAccessSelectorForm;
p: TParamCollection;
st: string;
p1: string;
begin
if AButtonIndex=0 then begin
beContract.HelpContext:=0;
beContract.Text:='';
end;
if AButtonIndex=1 then begin
a:=TAccessSelectorForm.Create;
try
a.ObjectID:=205;
p:=TParamCollection.Create(TParamItem);
try
p['код_Договор'].Value:=beContract.HelpContext;
if a.ShowModal(p, null)<>mrOK then exit;
finally
p.Free;
end;
if VarIsNullMy(a.CurRecordValues['Дата заключения'].Value) then
p1:='н/д'
else
p1:=DateToStr(a.CurRecordValues['Дата заключения'].Value);
st:='№ '+nz(a.CurRecordValues['Номер'].Value, 'н/д')+' от '+p1;
beContract.Text:=st;
beContract.HelpContext:=a.PrimaryKeyValue;
finally
a.Free;
end;
end;
if AButtonIndex=2 then begin
beContract.HelpContext:=-1;
beContract.Text:='<не закреплен>';
end;
end;
procedure TFrameObjectFilter.beObjectTypePropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
ids: string;
begin
if AButtonIndex=0 then begin
ObjectType_IDs:=null;
beObjectType.Text:='';
if Assigned(dlgObjectFilterTypeSelector) then begin
dlgObjectFilterTypeSelector.Free;
dlgObjectFilterTypeSelector:=nil;
end;
end;
if AButtonIndex=1 then begin
if not Assigned(dlgObjectFilterTypeSelector) then
dlgObjectFilterTypeSelector:=TdlgObjectFilterTypeSelector.Create(nil);
// dlgObjectFilterTypeSelector.Query.First;
if dlgObjectFilterTypeSelector.ShowModal<>mrOK then exit;
ids:=dlgObjectFilterTypeSelector.SelectedIDs;
ObjectType_IDs:=ids;
if dlgObjectFilterTypeSelector.SelectedCount=0 then
beObjectTypePropertiesButtonClick(Sender, 0)
else
if dlgObjectFilterTypeSelector.SelectedCount=1 then
beObjectType.Text:=dlgObjectFilterTypeSelector.SelectedName
else
beObjectType.Text:='<выбрано типов: '+IntToStr(dlgObjectFilterTypeSelector.SelectedCount)+'>';
{ dlg:=TdlgObject_selector.Create(nil);
try
dlg.FrameObjects.CreateTree(-1, 'объект', true);
if dlg.ShowModal<>mrOK then exit;
beObjectType.Text:=dlg.SelectedObjectName;
beObjectType.HelpContext:=dlg.SelectedObjectID;
finally
dlg.Free;
end}
end;
end;
procedure TFrameObjectFilter.ClearFilter;
begin
ObjectType_IDs:=null;
OKOF_ID:=null;
Region_ID:=null;
Settlement_ID:=null;
Street_ID:=null;
beObjectType.Text:='';
teReestrNum.Text:='';
cbDepartment.ItemIndex:=-1;
beStatus.Text:='';
beView.Text:='';
teName.Text:='';
teInventNum.Text:='';
teInventNumEnterprise.Text:='';
ceAmort1.Text:='';
ceAmort2.Text:='';
cePeriod1.Text:='';
cePeriod2.Text:='';
deDate1.Text:='';
deDate2.Text:='';
beOKOF.Text:='';
deInWorkDate1.Text:='';
deInWorkDate2.Text:='';
cbInKazna.State:=cbsGrayed;
teComment.Text:='';
beRegion.Text:='';
beSettlement.Text:='';
beStreet.Text:='';
teAddress.Text:='';
ceBalansCost1.Text:='';
ceBalansCost2.Text:='';
ceWear1.Text:='';
ceWear2.Text:='';
ceRemainder1.Text:='';
ceRemainder1.Text:='';
//Закрепление объекта
beContract.Text:='';
teContractNum.Text:='';
deContractDate1.Text:='';
deContractDate2.Text:='';
beType.Text:='';
beWho1.Text:='';
beWho2.Text:='';
teFoundationNum.Text:='';
deFoundationDate1.Text:='';
deFoundationDate2.Text:='';
beFoundationType.Text:='';
teFoundationName.Text:='';
teFoundationComment.Text:='';
teImportFrom.Text:='';
beObjectType.HelpContext:=0;
teReestrNum.HelpContext:=0;
beStatus.HelpContext:=0;
beView.HelpContext:=0;
teName.HelpContext:=0;
teInventNum.HelpContext:=0;
teInventNumEnterprise.HelpContext:=0;
ceAmort1.HelpContext:=0;
ceAmort2.HelpContext:=0;
cePeriod1.HelpContext:=0;
cePeriod2.HelpContext:=0;
deDate1.HelpContext:=0;
deDate2.HelpContext:=0;
beOKOF.HelpContext:=0;
deInWorkDate1.HelpContext:=0;
deInWorkDate2.HelpContext:=0;
cbInKazna.State:=cbsGrayed;
teComment.HelpContext:=0;
beRegion.HelpContext:=0;
beSettlement.HelpContext:=0;
beStreet.HelpContext:=0;
teAddress.HelpContext:=0;
ceBalansCost1.HelpContext:=0;
ceBalansCost2.HelpContext:=0;
ceWear1.HelpContext:=0;
ceWear2.HelpContext:=0;
ceRemainder1.HelpContext:=0;
ceRemainder1.HelpContext:=0;
//Закрепление объекта
beContract.HelpContext:=0;
teContractNum.HelpContext:=0;
deContractDate1.HelpContext:=0;
deContractDate2.HelpContext:=0;
beType.HelpContext:=0;
beWho1.HelpContext:=0;
beWho2.HelpContext:=0;
teFoundationNum.HelpContext:=0;
deFoundationDate1.HelpContext:=0;
deFoundationDate2.HelpContext:=0;
beFoundationType.HelpContext:=0;
teFoundationName.HelpContext:=0;
teFoundationComment.HelpContext:=0;
teImportFrom.HelpContext:=0;
cbRegistered.State:=cbsGrayed;
end;
procedure TFrameObjectFilter.btnDropFilterClick(Sender: TObject);
begin
ClearFilter;
end;
procedure TFrameObjectFilter.cbDepartmentPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
begin
if AButtonIndex=0 then
cbDepartment.ItemIndex:=-1;
end;
destructor TFrameObjectFilter.Destroy;
begin
if Assigned(dlgObjectFilterTypeSelector) then
dlgObjectFilterTypeSelector.Free;
inherited;
end;
end.
|
program SimonFramework;
Uses sysutils, Crt, Classes;
var ChoiceNum : integer;
name : string;
score : integer;
scores: array[1..10,1..2] of integer;
Colors : Array[1..4] of string;
ColorTally : string;
TempString, TempString2 : string;
time : LongWord;
menu : integer;
Procedure GenSettings; forward;
Procedure GenLeaderboard; forward;
Procedure GenMenu; forward;
Procedure ChangeDelay();
begin
write('Enter the time in seconds you wish to change the Delay Time to: ');
readln(time);
time:=time*1000;
GenSettings();
end;
Procedure ShowColor(color : string; no : integer);
begin
ClrScr();
if color = 'Green' then
TextColor(Green);
if color = 'Red' then
TextColor(Red);
if color = 'Yellow' then
TextColor(Yellow);
if color = 'Blue' then
TextColor(Blue);
writeln('('+IntToStr(no)+')'+color+#13#10);
Sleep(time);
ClrScr();
end;
function OccurrencesOfChar(const S: string; const C: char): integer;
var
i: Integer;
begin
result := 0;
for i := 1 to Length(S) do
if S[i] = C then
inc(result);
end;
Procedure StartRound(round : integer);
var color : string;
ColorInput : string;
index : integer;
begin
Randomize;
color := Colors[Random(4)+1];
if round = 1 then
begin
ColorTally:=color;
end
else
begin
ColorTally:= Concat(ColorTally,',',color);
end;
writeln(#13#10+'Round '+IntToStr(round));
Sleep(time);
for index := 1 to (OccurrencesOfChar(ColorTally, ',')+1) do
begin
if round > 1 then
begin
if index = 1 then
begin
TempString:=Copy(ColorTally, 0, Pos(',', ColorTally)-1);
TempString2:=Copy(ColorTally, Pos(',', ColorTally)+1, Length(ColorTally)-Pos(',', ColorTally));
TempString2:=Concat(TempString2,',',color);
ShowColor(TempString, index);
end
else
begin
TempString:=Copy(TempString2, 0, Pos(',', TempString2)-1);
TempString2:=Copy(TempString2, Pos(',', TempString2)+1, Length(TempString2)-Pos(',', TempString2));
ShowColor(TempString, index);
end;
end
else if round = 1 then
TempString:=ColorTally;
ShowColor(TempString, index);
end;
TextColor(White);
if round = 1 then
begin
write('Enter color(e.g. Blue): ')
end
else
begin
write('Enter colors(e.g. Blue,Green): ')
end;
readln(ColorInput);
if ColorInput = ColorTally then
begin
round:= round + 1;
StartRound(round)
end
else
begin
writeln('Wrong!')
end;
end;
Procedure GameSetup();
var round : integer = 1;
begin
Colors[1]:='Green';
Colors[2]:='Red';
Colors[3]:='Yellow';
Colors[4]:='Blue';
StartRound(round);
end;
Procedure MenuChoice();
begin
if menu = 1 then
begin
write('Enter your option as a integer: ');
readln(ChoiceNum);
if ChoiceNum = 1 then
begin
GameSetup()
end
else if ChoiceNum = 2 then
begin
GenSettings()
end
else if ChoiceNum = 3 then
begin
GenLeaderboard()
end
else
begin
writeln('Invalid entry, please check your input.'+#13#10);
MenuChoice();
end;
end;
if menu = 2 then
begin
write('Enter the setting you wish to change as a integer or type 0 to return '+#13#10+'to the Menu: ');
readln(ChoiceNum);
if ChoiceNum = 0 then
begin
GenMenu();
MenuChoice()
end
else if ChoiceNum = 1 then
begin
ChangeDelay()
end
else if ChoiceNum = 2 then
begin
GenSettings()
end
else if ChoiceNum = 3 then
begin
GenLeaderboard()
end
else
begin
writeln('Invalid entry, please check your input.'+#13#10);
MenuChoice();
end;
end;
end;
Procedure GenSettings();
begin
clrscr();
menu:=2;
writeln('.:*~*:._.:*~*:._.:*~*:._.:*~*:.'+#13#10);
writeln(' _____ _ _ _'+#13#10+'/ ___| | | | | (_)'+#13#10+'\ `--. ___| |_| |_ _ _ __ __ _ ___'+#13#10+' `--. \/ _ \ __| __| | ''_ \ / _` / __|'+#13#10+'/\__/ / __/ |_| |_| | | | | (_| \__ \'+#13#10+'\____/ \___|\__|\__|_|_| |_|\__, |___/'+#13#10+' __/ |'+#13#10+' |___/ ');
writeln(' (1) Delay Time (Time color is shown before dissapearing.) : '+FloatToStr(time/1000)+' Secs'+#13#10+' (2) N/A '+#13#10+' (3) N/A '+#13#10);
writeln('.:*~*:._.:*~*:._.:*~*:._.:*~*:.'+#13#10);
MenuChoice();
end;
Procedure GenLeaderboard();
begin
readln;
end;
Procedure GenMenu();
begin
menu:=1;
writeln('.:*~*:._.:*~*:._.:*~*:._.:*~*:.'+#13#10);
writeln(' ___ ___ _____ _ _ _ _'+#13#10+' | \/ || ___| \ | | | | |'+#13#10+' | . . || |__ | \| | | | |'+#13#10+' | |\/| || __|| . ` | | | |'+#13#10+' | | | || |___| |\ | |_| |'+#13#10+' \_| |_/\____/\_| \_/\___/'+#13#10);
writeln(' (1) Play'+#13#10+' (2) Settings '+#13#10+' (3) Leaderboards '+#13#10);
writeln('.:*~*:._.:*~*:._.:*~*:._.:*~*:.'+#13#10);
end;
begin
time:= 1000;
GenMenu();
MenuChoice();
readln;
end.
|
unit hashtable;
// When compiling with freePascal, use -S2 switch (-Sd won't work)
// TODO: see if making it compatible with -Sd is possible and / or necessary
//
// (incomplete) rip-off of java hashtable
//=============================================================================
interface
//=============================================================================
uses comparable, sysutils;
type
THashEntry = class(TComparable)
private
fkey: TComparable;
fvalue: TObject;
protected
function compareObjects(object2: TComparable): integer; override;
public
next: THashEntry;
function hashCode: Int64; override;
function getKey: TComparable;
function getValue: TObject;
procedure setValue(avalue: TObject);
property key: TComparable read getKey;
property value: TObject read getValue write setValue;
constructor create(akey: TComparable; avalue: TObject);
end;
THashEntryClass = class of THashEntry;
THashEntryFactory = class(TObject)
private
fHashClass: THashEntryClass;
public
function getEntry(key: TComparable; value: TObject): THashEntry; virtual;
constructor create(hashEntryClass: THashEntryClass);
end;
TMapIterator = class (TObject)
public
procedure next; virtual; abstract;
procedure remove; virtual; abstract;
function hasNext: Boolean; virtual; abstract;
function getKey: TComparable; virtual; abstract;
function getValue: TObject; virtual; abstract;
function validEntry: Boolean; virtual; abstract;
procedure setValue(value: TObject); virtual; abstract;
function isValid: Boolean; virtual; abstract;
property key: TComparable read getKey;
property value: TObject read getValue write setValue;
end;
{$IFNDEF FPC}
THashEntryTable = array of THashEntry;
HashEntryTablePtr = ^THashEntryTable;
{$ELSE FPC}
HashEntryTablePtr = ^THashEntry;
{$ENDIF}
THashTable = class (TObject)
protected
fTable: HashEntryTablePtr;
fEntryFactory: THashEntryFactory;
fModCount: integer;
fCapacity: integer;
fThreshHold: integer;
fLoadFactor: real;
fCount : integer;
fOwnKeys : Boolean;
function hashToIndex(key: TComparable): integer;
procedure rehash; virtual;
// there's a potential for memory leak here
// - if key already in the table, it does not get re-inserted.
// function setvalue returns false if this happens, so key may be freed
// if necessary but procedure fsetvalue does not free keys.
// SO: don't use values property unless you're managing _all_ keys
// somewhere outsite of the hash table
// CORRECTION: if ownKeys is set, fSetvalue will free the key, so there's
// no leak
// Another possibility for a leak - what happens if the value that is
// already in the table is not managed outside? Should be deleted, but how?
procedure fSetValue(key: TComparable; value: TObject); virtual;
procedure clearTable(deleteValues: Boolean);
public
function getIterator: TMapIterator; virtual;
function containsKey(key: TComparable): Boolean; virtual;
function containsValue(value: TObject): Boolean; virtual;
function getValue(key: TComparable): TObject; virtual;
function setValue(key: TComparable; value: TObject): Boolean; virtual;
function remove(key: TComparable): TObject; virtual;
function getCount: integer; virtual;
property values[key: TComparable]: TObject read getValue write fsetValue;
property count: integer read getCount;
{$IFNDEF FPC}
constructor create(initialcapacity: integer = 10; loadfactor: real = 0.75;
entryfactory: THashEntryFactory = nil; ownKeys: Boolean = true);
{$ELSE FPC}
constructor create(initialcapacity: integer; loadfactor: real;
entryfactory: THashEntryFactory; ownKeys: Boolean); overload;
constructor create; overload;
{$ENDIF}
destructor destroy; override;
procedure clear; virtual;
procedure deleteAll; virtual;
end;
THashTableIterator = class(TMapIterator)
protected
fIndex: integer;
fEntry: THashEntry;
fModCount: integer;
fIsRemoved: Boolean;
fCurrent: integer;
fHashTable: THashTable;
public
constructor create(table: THashTable);
procedure next; override;
procedure remove; override;
function hasNext: Boolean; override;
function getKey: TComparable; override;
function getValue: TObject; override;
procedure setValue(avalue: TObject); override;
function validEntry: Boolean; override;
function isValid: Boolean; override;
end;
//=============================================================================
implementation
//=============================================================================
//---------------------------------------------------------------------------
// array get/put methods - pointer functions
//---------------------------------------------------------------------------
{$IFNDEF FPC}
//delphi implementation, uses dynamic arrays
function getNewEntryTable(size: integer): HashEntryTablePtr;
begin
new(result);
setLength(result^, size);
end;
procedure freeEntryTable(table: HashEntryTablePtr; oldSize: integer);
begin
setLength(table^, 0);
dispose(table);
end;
function arrayGet(arr: HashEntryTablePtr; index: integer): THashEntry;
begin
result := arr^[index];
end;
procedure arrayPut(arr: HashEntryTablePtr; index: integer; value: THashEntry);
begin
arr^[index] := value;
end;
{$ELSE FPC}
// freepascal implementaion, uses pointers as arrays
function getNewEntryTable(size: integer): HashEntryTablePtr;
var
i: Integer;
begin
getmem(result, size * sizeOf(THashEntry));
//set all positions to nil
for i := 0 to size - 1 do
begin
(result + i)^ := nil;
end;
end;
procedure freeEntryTable(table: HashEntryTablePtr; oldSize: integer);
begin
freemem(table, oldSize * sizeOf(THashEntry));
end;
function arrayGet(arr: HashEntryTablePtr; index: integer): THashEntry;
begin
result := (arr + index)^; //arr[index];
end;
procedure arrayPut(arr: HashEntryTablePtr; index: integer; value: THashEntry);
begin
(arr + index)^ := value; //arr[index] := value;
end;
{$ENDIF FPC}
function equal(item1, item2 :TObject): Boolean;
begin
if ((item1 = nil) or (item1 is TComparable)) and ((item2 = nil) or (item2 is TComparable)) then
result := comparable.equal(TComparable(item1), TComparable(item2))
else
result := false;
end;
constructor THashEntryFactory.create(hashEntryClass: THashEntryClass);
begin
inherited create;
fHashClass := hashEntryClass;
end;
function THashEntryFactory.getEntry(key: TComparable; value: TObject): THashEntry;
begin
result := fHashClass.create(key, value);
end;
//---------------------------------------------------------------------------
// THashEntry
//---------------------------------------------------------------------------
function THashEntry.compareObjects(object2: TComparable): integer;
begin
throwComparableException(object2, self.ClassType);
// this is not really important so we'll just make it compare keys
result := compare(fkey, THashEntry(object2).key);
end;
function THashEntry.hashCode: Int64;
begin
// for our purposes the hash code of the key is good enough
result := key.hashCode;
end;
function THashEntry.getKey: TComparable;
begin
result := fKey;
end;
function THashEntry.getValue: TObject;
begin
result := fValue;
end;
procedure THashEntry.setValue(avalue: TObject);
begin
fValue := avalue;
end;
constructor THashEntry.create(akey: TComparable; avalue: TObject);
begin
inherited create;
fKey := akey;
fValue := avalue;
next := nil;
end;
//---------------------------------------------------------------------------
// hashtable
//---------------------------------------------------------------------------
function THashTable.hashToIndex(key: TComparable): integer;
begin
result := Integer(abs(key.hashCode) mod fCapacity);
end;
procedure THashTable.rehash;
var
oldCapacity: integer;
oldTable: HashEntryTablePtr;
newCapacity: integer;
newTable: HashEntryTablePtr;
i: integer;
index: integer;
entry, oldentry: THashEntry;
begin
oldCapacity := fCapacity;
newCapacity := oldCapacity * 2 + 1;
newTable := getNewEntryTable(newCapacity);
inc(fModCount);
oldTable := fTable;
fTable := newTable;
fCapacity := newCapacity;
fThreshHold := Integer(round(newCapacity * fLoadFactor));
try
for i := 0 to oldCapacity - 1 do begin
oldEntry := arrayGet(oldTable, i);
while oldEntry <> nil do begin
entry := oldEntry;
oldEntry := oldEntry.next;
index := hashToIndex(entry.key);
entry.next := arrayGet(fTable, index);
arrayPut(fTable, index, entry);
end;
end;
finally
freeEntryTable(oldTable, oldCapacity);
end;
end;
procedure THashTable.fSetValue(key: TComparable; value: TObject);
begin
setValue(key, value);
end;
function THashTable.getIterator: TMapIterator;
begin
result := THashTableIterator.create(self);
end;
function THashTable.containsKey(key: TComparable): Boolean;
var
idx: integer;
entry: THashEntry;
begin
idx := hashToIndex(key);
result := false;
entry := arrayGet(fTable, idx);
while (entry <> nil) and not result do begin
result := equal(key, entry.key);
entry := entry.next;
end;
end;
function THashTable.containsValue(value: TObject): Boolean;
var
idx: integer;
entry: THashEntry;
begin
result := false;
for idx := 0 to fCapacity - 1 do begin
entry := arrayGet(fTable, idx);
while (entry <> nil) and not result do begin
result := equal(value, entry.value);
entry := entry.next;
end;
if result then break;
end;
end;
function THashTable.getValue(key: TComparable): TObject;
var
idx: integer;
entry: THashEntry;
begin
idx := hashToIndex(key);
result := nil;
entry := arrayGet(fTable, idx);
while (entry <> nil) do begin
if equal(key, entry.key) then begin
result := entry.value;
break;
end;
entry := entry.next;
end;
end;
function THashTable.setValue(key: TComparable; value: TObject): Boolean;
var
idx: integer;
entry: THashEntry;
begin
// {$IFDEF TRACE}
// TraceEnter('hashtable', 'THashTable.setValue');
// Trace('hashtable', 'Info', 'THashTable.setValue', 'fTable = ' + HexStr(fTable));
// {$ENDIF}
// first try to find key in the table and replace the value
idx := hashToIndex(key);
// {$IFDEF TRACE}
// Trace('hashtable', 'Info', 'THashTable.setValue', 'idx = ' + IntToStr(idx));
// {$ENDIF}
entry := arrayGet(fTable, idx);
// {$IFDEF TRACE}
// Trace('hashtable', 'Info', 'THashTable.setValue', 'entry = ' + HexStr(entry));
// {$ENDIF}
while entry <> nil do
begin
if equal(key, entry.key) then
begin
// {$IFDEF TRACE}
// Trace('hashtable', 'Info', 'THashTable.setValue', 'Found Matching');
// {$ENDIF}
result := false;
entry.value := value;
if fOwnKeys then key.free;
exit;
end;
entry := entry.next;
end;
// {$IFDEF TRACE}
// Trace('hashtable', 'Info', 'THashTable.setValue', 'Done checking... inserting');
// {$ENDIF}
// inserting new key-value pair
inc(fModCount);
if fcount > fThreshHold then
rehash;
idx := hashToIndex(key);
entry := fEntryFactory.getEntry(key, value);
entry.next := arrayGet(ftable ,idx);
arrayPut(ftable, idx, entry);
inc(fcount);
result := true;
// {$IFDEF TRACE}
// TraceExit('hashtable', 'THashTable.setValue');
// {$ENDIF}
end;
function THashTable.remove(key: TComparable): TObject;
var
idx: integer;
entry: THashEntry;
preventry: THashEntry;
begin
idx := hashToIndex(key);
entry := arrayGet(fTable, idx);
result := nil;
prevEntry := nil;
while entry <> nil do begin
if equal(key, entry.key) then begin
inc(fModCount);
result := entry.value;
if fOwnKeys then if entry.key <> key then key.free; //test this!
if fOwnKeys then entry.key.free;
if prevEntry = nil then
arrayPut(fTable, idx, entry.next)
else
prevEntry.next := entry.next;
entry.free;
dec(fCount);
break;
end;
preventry := entry;
entry := entry.next;
end;
end;
function THashTable.getCount: integer;
begin
result := fCount;
end;
{$IFDEF FPC}
constructor THashTable.create(initialcapacity: integer; loadfactor: real;
entryfactory: THashEntryFactory; ownKeys: Boolean);
begin
inherited create;
fLoadFactor := loadfactor;
fOwnKeys := ownKeys;
if entryFactory = nil then
fEntryFactory := THashEntryFactory.create(THashEntry)
else
fEntryFactory := entryfactory;
fTable := getNewEntryTable(initialCapacity);
fCapacity := initialcapacity;
fThreshHold := Integer(round(fCapacity * fLoadFactor));
fCount := 0;
fModCount := 0;
end;
constructor THashTable.create;
begin
create(10, 0.75, nil, true);
end;
{$ELSE FPC}
constructor THashTable.create(initialcapacity: integer = 10; loadfactor: real = 0.75;
entryfactory: THashEntryFactory = nil; ownKeys: Boolean = true);
begin
inherited create;
fLoadFactor := loadfactor;
fOwnKeys := ownKeys;
if entryFactory = nil then
fEntryFactory := THashEntryFactory.create(THashEntry)
else
fEntryFactory := entryfactory;
fTable := getNewEntryTable(initialCapacity);
fCapacity := initialcapacity;
fThreshHold := round(fCapacity * fLoadFactor);
fCount := 0;
fModCount := 0;
end;
{$ENDIF}
destructor THashTable.destroy;
begin
clear;
freeEntryTable(fTable, fCapacity);
fEntryFactory.free;
inherited;
end;
procedure THashTable.clear;
begin
clearTable(false);
end;
procedure THashTable.deleteAll;
begin
clearTable(true);
end;
procedure THashTable.clearTable(deleteValues: Boolean);
var
idx: integer;
entry: THashEntry;
temp : THashEntry;
begin
for idx := 0 to fCapacity - 1 do begin
entry := arrayGet(ftable, idx);
while entry <> nil do begin
temp := entry;
entry := entry.next;
if fOwnKeys then
temp.key.free;
if deleteValues then
temp.value.free;
temp.free;
end;
arrayPut(fTable, idx, nil);
end;
end;
//* iterator *
constructor THashTableIterator.create(table: THashTable);
var
i: integer;
begin
inherited create;
fHashTable := table;
fModCount := table.fModCount;
fIsRemoved := false;
fCurrent := 0;
fEntry := nil;
// get first element
if fHashTable.count > 0 then
for i := 0 to fHashTable.fCapacity - 1 do begin
fEntry := arrayGet(fHashTable.ftable, i);
if fEntry <> nil then begin
fIndex := i;
break;
end;
end;
end;
procedure THashTableIterator.next;
var
i: integer;
begin
if fModCount <> fHashtable.fModCount then
raise exception.create('Iterator no longer valid');
if fIsRemoved then
fisRemoved := false
else if fCurrent < fHashTable.count then begin
fEntry := fEntry.next;
if fEntry = nil then
for i := fIndex + 1 to fHashTable.fCapacity - 1 do
if arrayGet(fHashTable.fTable, i) <> nil then begin
fEntry := arrayGet(fHashTable.fTable, i);
fIndex := i;
break;
end;
if fEntry <> nil then
inc(fCurrent);
end;
end;
function THashTableIterator.isValid: Boolean;
begin
result := fModCount = fHashTable.fModCount;
end;
procedure THashTableIterator.remove;
var
oldEntry: THashEntry;
i: integer;
begin
if fModCount <> fHashtable.fModCount then
raise exception.create('Iterator no longer valid');
if fIsRemoved or (fEntry = nil) then exit;
oldEntry := fEntry;
if fCurrent < fHashTable.count then begin
fEntry := fEntry.next;
if fEntry = nil then begin
for i := fIndex + 1 to fHashTable.fCapacity - 1 do
if arrayGet(fHashTable.fTable, i) <> nil then begin
fEntry := arrayGet(fHashTable.fTable, i);
fIndex := i;
break;
end;
end;
end;
fHashTable.remove(oldEntry.key);
fIsRemoved := true;
fModCount := fHashTable.fmodCount;
end;
function THashTableIterator.hasNext: Boolean;
begin
if fModCount <> fHashtable.fModCount then
raise exception.create('Iterator no longer valid');
result := (fCurrent < (fHashTable.count - 1)) or (fIsRemoved and (fCurrent < fHashTable.count));
end;
function THashTableIterator.getKey: TComparable;
begin
if fModCount <> fHashtable.fModCount then
raise exception.create('Iterator no longer valid');
if not (fIsRemoved or (fEntry = nil)) then
result := fEntry.key
else
result := nil;
end;
procedure THashTableIterator.setValue(avalue: TObject);
begin
// NOTE! at this point, dealing with the value that is being replaced is
// the responsibility of the user
if not isValid then
raise exception.create('Iterator no longer valid');
if validEntry then
fEntry.value := avalue
else
raise exception.create('The entry is not valid');
end;
function THashTableIterator.getValue: TObject;
begin
if fModCount <> fHashtable.fModCount then
raise exception.create('Iterator no longer valid');
if not (fIsRemoved or (fEntry = nil)) then
result := fEntry.value
else
result := nil;
end;
function THashTableIterator.validEntry: Boolean;
begin
if fModCount <> fHashtable.fModCount then
raise exception.create('Iterator no longer valid');
result := (fEntry <> nil) and (fCurrent < fHashTable.count) and not fIsRemoved;
end;
end.
|
unit E_Logger;
//------------------------------------------------------------------------------
// Модуль реализует класс логирования
//------------------------------------------------------------------------------
// Потоко-безопасный логгер
//
// Запись в файл лога ToLog() добавляет запись в лог;
// Запись в файл лога ошибок ErrorToLog() добавляет запись в лог ошибок (суффикс имени файла "_ERR")
//
// В конструктор передаются 3 параметра:
// ALogFileName - ПОЛНЫЙ путь И ИМЯ файла лога (!однако расширение всегда берётся стандартное!)
// для базового лога можно использовать аргумент ParamStr( 0 )
//
// ASizeLimit - размер файла лога (в байтах)
// после превышения размера текущий файл переименовывается в архивный, а запись продолжается в новый
// не рекомендуется делать файлы более 10 (лучше 5) мегабайт, т.к. медленно открываются блокнотом
//
// ANumLimit - кол-во архивных файлов логов
// совсем старые файлы удаляются
// не может быть менее 1 файла!
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
interface
uses
SysUtils, SyncObjs, Windows, Math,
C_FileNames, E_Files, E_UtilsStr, E_UtilsFiles;
//------------------------------------------------------------------------------
type
//------------------------------------------------------------------------------
//! класс логирования
//------------------------------------------------------------------------------
TLogger = class sealed
strict private
//!
FFileName: string;
//!
FErrorFileName: string;
//!
FLocker: TCriticalSection;
//!
FSizeLimit: DWORD;
//!
FNumLimit: DWORD;
//!
procedure ArchLog(
const AFileName: string
);
public
//!
constructor Create(
const ALogFileName: string;
const ASizeLimit: DWORD;
const ANumLimit: DWORD
);
//!
destructor Destroy(); override;
//!
procedure ToLog(
const AMessage: string
);
//!
procedure ErrorToLog(
const AMessage: string
);
end;
//------------------------------------------------------------------------------
//! класс логирования в один файл для нескольких приложений
//------------------------------------------------------------------------------
TMultiAppLogger = class sealed
strict private
//!
FFileName: string;
//!
FErrorFileName: string;
//!
FLocker: TCriticalSection;
//!
FSizeLimit: DWORD;
//!
FNumLimit: DWORD;
//!
procedure ArchLog(
const AFileName: string
);
public
//!
constructor Create(
const ALogFileName: string;
const ASizeLimit: DWORD;
const ANumLimit: DWORD
);
//!
destructor Destroy(); override;
//!
procedure ToLog(
const AMessage: string
);
//!
procedure ErrorToLog(
const AMessage: string
);
end;
//------------------------------------------------------------------------------
//! класс логирования с архивацией в отдельный каталог
//------------------------------------------------------------------------------
TArchLogger = class sealed
strict private
//!
FFileName: string;
//!
FErrorFileName: string;
//!
FArchPath: string;
//!
FLocker: TCriticalSection;
//!
FSizeLimit: DWORD;
//!
procedure ArchLog(
const AFileName: string
);
public
//!
constructor Create(
const ALogFileName: string;
const ASizeLimit: DWORD;
const AArchPath: string
);
//!
destructor Destroy(); override;
//!
procedure ToLog(
const AMessage: string
);
//!
procedure ErrorToLog(
const AMessage: string
);
end;
//------------------------------------------------------------------------------
implementation
const
//------------------------------------------------------------------------------
//! сообщение об ошибке
//------------------------------------------------------------------------------
CLLogNameError: string = 'Некорректное имя файла лога';
//------------------------------------------------------------------------------
//! формат даты/времени файла архива
//------------------------------------------------------------------------------
CArchFile: string = '"_"yyyymmdd"_"hhnn';
//------------------------------------------------------------------------------
//! шаблон формата даты/времени файла архива для поиска
//------------------------------------------------------------------------------
CArchFileForFind: string = '_????????_????';
//------------------------------------------------------------------------------
//! шаблон формата строки лога
//------------------------------------------------------------------------------
CLogStrFormat: string = '%s %s'#13#10;
//------------------------------------------------------------------------------
// TLogger
//------------------------------------------------------------------------------
constructor TLogger.Create(
const ALogFileName: string;
const ASizeLimit: DWORD;
const ANumLimit: DWORD
);
var
//!
LStr: string;
//!
LFileH: THandle;
//!
LError: DWORD;
//!
LExtPos: Integer;
//------------------------------------------------------------------------------
begin
inherited Create();
//
FSizeLimit := ASizeLimit;
FNumLimit := ANumLimit;
// файл лога и файл лога ошибок
LStr := ChangeFileExt( ALogFileName, CLogDefExtDotted );
LExtPos := PosLastDelimiter( LStr, CExtDelim );
if ( LExtPos = 0 ) then
raise Exception.Create( CLLogNameError );
FFileName := LStr;
FErrorFileName := Copy( LStr, 1, LExtPos - 1 ) + CErrorLogSuffix + CLogDefExtDotted;
// для проверки на правильность имени откроем файл
LFileH := CreateFile(
PChar( FFileName ),
GENERIC_WRITE,
FILE_SHARE_READ or FILE_SHARE_DELETE,
nil,
CREATE_NEW,
FILE_ATTRIBUTE_NORMAL,
0
);
if ( LFileH = INVALID_HANDLE_VALUE ) then
begin
LError := GetLastError();
if ( LError <> ERROR_FILE_EXISTS ) then // если это просто "файл уже существует" - то всё ок
RaiseLastOSError( LError );
end
else
CloseHandle( LFileH ); // закроем файл - на данный момент он нам не нужен
// создаём рабочие компоненты
FLocker := TCriticalSection.Create();
end;
destructor TLogger.Destroy();
begin
FLocker.Free();
//
inherited Destroy();
end;
procedure TLogger.ArchLog(
const AFileName: string
);
var
//!
LStr: string;
//!
LFileH: THandle;
//!
LFileSizeLow: DWORD;
//!
LFileSizeHigh: DWORD;
//!
LCurFileWriteDTDOS: Integer;
//!
LCurFileWriteDT: TDateTime;
//!
LMinFileWriteDT: TDateTime;
//!
LNum: DWORD;
//!
LSearchRec: TWIN32FindData;
//------------------------------------------------------------------------------
begin
// проверяем размер
LFileH := CreateFile(
PChar( AFileName ),
0,
FILE_SHARE_READ or FILE_SHARE_DELETE or FILE_SHARE_WRITE,
nil,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
0
);
if ( LFileH <> INVALID_HANDLE_VALUE ) then
begin
LFileSizeLow := GetFileSize( LFileH, @LFileSizeHigh );
CloseHandle( LFileH );
if ( LFileSizeLow <> INVALID_FILE_SIZE ) then
begin
if ( LFileSizeLow > FSizeLimit ) or ( LFileSizeHigh <> 0 ) then
begin
LStr := Copy( AFileName, 1, PosLastDelimiter( AFileName, CExtDelim ) - 1 ) + FormatDateTime( CArchFile, Now() ) + CLogDefExtDotted;
MoveFile( PChar( AFileName ), PChar( LStr ) );
end;
end;
end;
// проверяем количество
LStr := Copy( AFileName, 1, PosLastDelimiter( AFileName, CExtDelim ) - 1 ) + CArchFileForFind + CLogDefExtDotted;
LFileH := Windows.FindFirstFile( PChar( LStr ), LSearchRec );
if ( LFileH <> INVALID_HANDLE_VALUE ) then
begin
LNum := 1;
LMinFileWriteDT := Infinity;
repeat
// эти две строки - конвертация даты-времени последней записи в файл в тип TDateTime
FileTimeToDosDateTime( LSearchRec.ftLastWriteTime, LongRec( LCurFileWriteDTDOS ).Hi, LongRec( LCurFileWriteDTDOS ).Lo );
LCurFileWriteDT := FileDateToDateTime ( LCurFileWriteDTDOS );
//
if ( LMinFileWriteDT > LCurFileWriteDT ) then
begin
LMinFileWriteDT := LCurFileWriteDT;
LStr := QExtractFilePath( AFileName ) + string( LSearchRec.cFileName );
end;
if not Windows.FindNextFile( LFileH, LSearchRec ) then Break;
Inc( LNum );
until False;
Windows.FindClose( LFileH );
if ( LNum > FNumLimit ) then
DeleteFile( PChar( LStr ) );
end;
end;
procedure TLogger.ToLog(
const AMessage: string
);
var
//!
LFormatted: string;
//!
LFile: TFileHandler;
//------------------------------------------------------------------------------
begin
if ( AMessage = '' ) then Exit;
try
FLocker.Acquire();
try
// проверка
ArchLog( FFileName );
// форматируем
LFormatted := Format( CLogStrFormat, [FormatDateTime( CDateTimeFormat, Now() ), AMessage] );
// пишем
LFile := TFileHandler.Create( FFileName, famWrite );
try
LFile.ReadFromMem( @LFormatted[1], Length( LFormatted ) * SizeOf( Char ) );
finally
LFile.Free();
end;
finally
FLocker.Release();
end;
except
// игнорируем все ошибки
end;
end;
procedure TLogger.ErrorToLog(
const AMessage: string
);
var
//!
LFormatted: string;
//!
LFile: TFileHandler;
//------------------------------------------------------------------------------
begin
if ( AMessage = '' ) then Exit;
try
FLocker.Acquire();
try
// проверка
ArchLog( FErrorFileName );
// форматируем
LFormatted := Format( CLogStrFormat, [FormatDateTime( CDateTimeFormat, Now() ), AMessage] );
LFile := TFileHandler.Create( FErrorFileName, famWrite );
try
LFile.ReadFromMem( @LFormatted[1], Length( LFormatted ) * SizeOf( Char ) );
finally
LFile.Free();
end;
finally
FLocker.Release();
end;
except
// игнорируем все ошибки
end;
end;
//------------------------------------------------------------------------------
// TMultiAppLogger
//------------------------------------------------------------------------------
constructor TMultiAppLogger.Create(
const ALogFileName: string;
const ASizeLimit: DWORD;
const ANumLimit: DWORD
);
var
//!
LStr: string;
//!
LFileH: THandle;
//!
LError: DWORD;
//!
LExtPos: Integer;
//------------------------------------------------------------------------------
begin
inherited Create();
//
FSizeLimit := ASizeLimit;
FNumLimit := ANumLimit;
// файл лога и файл лога ошибок
LStr := ChangeFileExt( ALogFileName, CLogDefExtDotted );
LExtPos := PosLastDelimiter( LStr, CExtDelim );
if ( LExtPos = 0 ) then
raise Exception.Create( CLLogNameError );
FFileName := LStr;
FErrorFileName := Copy( LStr, 1, LExtPos - 1 ) + CErrorLogSuffix + CLogDefExtDotted;
// для проверки на правильность имени откроем файл
LFileH := CreateFile(
PChar( FFileName ),
GENERIC_WRITE,
FILE_SHARE_READ or FILE_SHARE_DELETE,
nil,
CREATE_NEW,
FILE_ATTRIBUTE_NORMAL,
0
);
if ( LFileH = INVALID_HANDLE_VALUE ) then
begin
LError := GetLastError();
if ( LError <> ERROR_FILE_EXISTS ) then // если это просто "файл уже существует" - то всё ок
RaiseLastOSError( LError );
end
else
CloseHandle( LFileH ); // закроем файл - на данный момент он нам не нужен
// создаём рабочие компоненты
FLocker := TCriticalSection.Create();
end;
destructor TMultiAppLogger.Destroy();
begin
inherited Destroy();
end;
procedure TMultiAppLogger.ArchLog(
const AFileName: string
);
var
//!
LStr: string;
//!
LFileH: THandle;
//!
LFileSizeLow: DWORD;
//!
LFileSizeHigh: DWORD;
//!
LCurFileWriteDTDOS: Integer;
//!
LCurFileWriteDT: TDateTime;
//!
LMinFileWriteDT: TDateTime;
//!
LNum: DWORD;
//!
LSearchRec: TWIN32FindData;
//------------------------------------------------------------------------------
begin
// проверяем размер
LFileH := CreateFile(
PChar( AFileName ),
0,
FILE_SHARE_READ or FILE_SHARE_DELETE or FILE_SHARE_WRITE,
nil,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
0
);
if ( LFileH <> INVALID_HANDLE_VALUE ) then
begin
LFileSizeLow := GetFileSize( LFileH, @LFileSizeHigh );
CloseHandle( LFileH );
if ( LFileSizeLow <> INVALID_FILE_SIZE ) then
begin
if ( LFileSizeLow > FSizeLimit ) or ( LFileSizeHigh <> 0 ) then
begin
LStr := Copy( AFileName, 1, PosLastDelimiter( AFileName, CExtDelim ) - 1 ) + FormatDateTime( CArchFile, Now() ) + CLogDefExtDotted;
MoveFile( PChar( AFileName ), PChar( LStr ) );
end;
end;
end;
// проверяем количество
LStr := Copy( AFileName, 1, PosLastDelimiter( AFileName, CExtDelim ) - 1 ) + CArchFileForFind + CLogDefExtDotted;
LFileH := Windows.FindFirstFile( PChar( LStr ), LSearchRec );
if ( LFileH <> INVALID_HANDLE_VALUE ) then
begin
LNum := 1;
LMinFileWriteDT := Infinity;
repeat
// эти две строки - конвертация даты-времени последней записи в файл в тип TDateTime
FileTimeToDosDateTime( LSearchRec.ftLastWriteTime, LongRec( LCurFileWriteDTDOS ).Hi, LongRec( LCurFileWriteDTDOS ).Lo );
LCurFileWriteDT := FileDateToDateTime ( LCurFileWriteDTDOS );
//
if ( LMinFileWriteDT > LCurFileWriteDT ) then
begin
LMinFileWriteDT := LCurFileWriteDT;
LStr := QExtractFilePath( AFileName ) + string( LSearchRec.cFileName );
end;
if not Windows.FindNextFile( LFileH, LSearchRec ) then Break;
Inc( LNum );
until False;
Windows.FindClose( LFileH );
if ( LNum > FNumLimit ) then
DeleteFile( PChar( LStr ) );
end;
end;
procedure TMultiAppLogger.ToLog(
const AMessage: string
);
var
//!
LFormatted: string;
//!
LFile: TFileHandler;
//!
LFlag: Boolean;
//------------------------------------------------------------------------------
begin
if ( AMessage = '' ) then Exit;
LFile := nil;
try
FLocker.Acquire();
try
// проверка
ArchLog( FFileName );
// форматируем
LFormatted := Format( CLogStrFormat, [FormatDateTime( CDateTimeFormat, Now() ), AMessage] );
// !!! ЭКСПЕРИМЕНТАЛЬНО !!! может в бесконечный цикл !!!
LFlag := True;
while LFlag do
begin
try
LFile := TFileHandler.Create( FFileName, famWrite );
LFlag := False;
except
//
end;
Windows.Sleep( 0 );
end;
LFlag := True;
while LFlag do
begin
try
LFile.ReadFromMem( @LFormatted[1], Length( LFormatted ) * SizeOf( Char ) );
LFlag := False;
except
//
end;
Windows.Sleep( 0 );
end;
// !!!
LFile.Free();
finally
FLocker.Release();
end;
except
// игнорируем все ошибки
end;
end;
procedure TMultiAppLogger.ErrorToLog(
const AMessage: string
);
var
//!
LFormatted: string;
//!
LFile: TFileHandler;
//!
LFlag: Boolean;
//------------------------------------------------------------------------------
begin
if ( AMessage = '' ) then Exit;
LFile := nil;
try
FLocker.Acquire();
try
// проверка
ArchLog( FErrorFileName );
// форматируем
LFormatted := Format( CLogStrFormat, [FormatDateTime( CDateTimeFormat, Now() ), AMessage] );
// !!! ЭКСПЕРИМЕНТАЛЬНО !!! может в бесконечный цикл !!!
LFlag := True;
while LFlag do
begin
try
LFile := TFileHandler.Create( FErrorFileName, famWrite );
LFlag := False;
except
//
end;
Windows.Sleep( 0 );
end;
LFlag := True;
while LFlag do
begin
try
LFile.ReadFromMem( @LFormatted[1], Length( LFormatted ) * SizeOf( Char ) );
LFlag := False;
except
//
end;
Windows.Sleep( 0 );
end;
// !!!
LFile.Free();
finally
FLocker.Release();
end;
except
// игнорируем все ошибки
end;
end;
//------------------------------------------------------------------------------
// TArchLogger
//------------------------------------------------------------------------------
constructor TArchLogger.Create(
const ALogFileName: string;
const ASizeLimit: DWORD;
const AArchPath: string
);
var
//!
LStr: string;
//!
LFileH: THandle;
//!
LError: DWORD;
//!
LExtPos: Integer;
//------------------------------------------------------------------------------
begin
inherited Create();
//
FSizeLimit := ASizeLimit;
FArchPath := AArchPath;
// файл лога и файл лога ошибок
LStr := ChangeFileExt( ALogFileName, CLogDefExtDotted );
LExtPos := PosLastDelimiter( LStr, CExtDelim );
if ( LExtPos = 0 ) then
raise Exception.Create( CLLogNameError );
FFileName := LStr;
FErrorFileName := Copy( LStr, 1, LExtPos - 1 ) + CErrorLogSuffix + CLogDefExtDotted;
// для проверки на правильность имени откроем файл
LFileH := CreateFile(
PChar( FFileName ),
GENERIC_WRITE,
FILE_SHARE_READ or FILE_SHARE_DELETE,
nil,
CREATE_NEW,
FILE_ATTRIBUTE_NORMAL,
0
);
if ( LFileH = INVALID_HANDLE_VALUE ) then
begin
LError := GetLastError();
if ( LError <> ERROR_FILE_EXISTS ) then // если это просто "файл уже существует" - то всё ок
RaiseLastOSError( LError );
end
else
CloseHandle( LFileH ); // закроем файл - на данный момент он нам не нужен
// создаём рабочие компоненты
FLocker := TCriticalSection.Create();
end;
destructor TArchLogger.Destroy();
begin
FLocker.Free();
//
inherited Destroy();
end;
procedure TArchLogger.ArchLog(
const AFileName: string
);
label R;
var
//! размер файла
FileSize: Int64;
//!
CurFileWriteDT: TDateTime;
//!
MinFileWriteDT: TDateTime;
//! имя файла без пути и расширения
PureFileName: string;
//! путь и имя файла в архиве
FileDestName: string;
//! шаблон поиска в архиве
FileTemplate: string;
//! путь и имя файла дл удаления
FileToDelete: string;
//! дескриптор файла при поиске
FileH: THandle;
//! запись поиска
SearchRec: TWIN32FindData;
//! для конвертации даты-времени записи в файл
CurFileWriteDTDOS: Integer;
//!
Counter: DWORD;
//------------------------------------------------------------------------------
begin
// проверяем размер
FileSize := TFileHandler.GetFileSize( AFileName );
if ( FileSize < Int64( FSizeLimit ) ) then Exit;
// размер превышен - перемещаем
PureFileName := QExcludeFileExt( QExcludeFilePath( AFileName ) );
FileDestName := FArchPath + PureFileName + FormatDateTime( CArchFile, Now() ) + CLogDefExtDotted;
MoveFileEx( PChar( AFileName ), PChar( FileDestName ), MOVEFILE_COPY_ALLOWED or MOVEFILE_WRITE_THROUGH );
// проверяем количество (уже в папке архива)
FileTemplate := FArchPath + PureFileName + CArchFileForFind + CLogDefExtDotted;
R:
FileH := Windows.FindFirstFile( PChar( FileTemplate ), SearchRec );
if ( FileH = INVALID_HANDLE_VALUE ) then Exit;
Counter := 1;
MinFileWriteDT := Infinity;
repeat
// эти две строки - конвертация даты-времени последней записи в файл в тип TDateTime
FileTimeToDosDateTime( SearchRec.ftLastWriteTime, LongRec( CurFileWriteDTDOS ).Hi, LongRec( CurFileWriteDTDOS ).Lo );
CurFileWriteDT := FileDateToDateTime ( CurFileWriteDTDOS );
//
if ( MinFileWriteDT > CurFileWriteDT ) then
begin
MinFileWriteDT := CurFileWriteDT;
FileToDelete := FArchPath + string( SearchRec.cFileName );
end;
if not Windows.FindNextFile( FileH, SearchRec ) then Break;
Inc( Counter );
until False;
Windows.FindClose( FileH );
//
if ( Counter > 1 ) then
begin
// удаляем архив
DeleteFile( PChar( FileToDelete ) );
// повторить до удаления всех ненужных архивов
goto R;
end;
end;
procedure TArchLogger.ToLog(
const AMessage: string
);
var
//!
LFormatted: string;
//!
LFile: TFileHandler;
//------------------------------------------------------------------------------
begin
if ( AMessage = '' ) then Exit;
try
FLocker.Acquire();
try
// проверка
ArchLog( FFileName );
// форматируем
LFormatted := Format( CLogStrFormat, [FormatDateTime( CDateTimeFormat, Now() ), AMessage] );
// пишем
LFile := TFileHandler.Create( FFileName, famWrite );
try
LFile.ReadFromMem( @LFormatted[1], Length( LFormatted ) * SizeOf( Char ) );
finally
LFile.Free();
end;
finally
FLocker.Release();
end;
except
// игнорируем все ошибки
end;
end;
procedure TArchLogger.ErrorToLog(
const AMessage: string
);
var
//!
LFormatted: string;
//!
LFile: TFileHandler;
//------------------------------------------------------------------------------
begin
if ( AMessage = '' ) then Exit;
try
FLocker.Acquire();
try
// проверка
ArchLog( FErrorFileName );
// форматируем
LFormatted := Format( CLogStrFormat, [FormatDateTime( CDateTimeFormat, Now() ), AMessage] );
LFile := TFileHandler.Create( FErrorFileName, famWrite );
try
LFile.ReadFromMem( @LFormatted[1], Length( LFormatted ) * SizeOf( Char ) );
finally
LFile.Free();
end;
finally
FLocker.Release();
end;
except
// игнорируем все ошибки
end;
end;
end.
|
unit CatClipboardListener;
{
Catarinka Clipboard Listener
Copyright (c) 2012-2020 Syhunt Informatica
License: 3-clause BSD
See https://github.com/felipedaragon/catarinka/ for details
}
// Works with Vista and later
// Before Vista, you should be using SetClipboardViewer() instead of AddClipboardFormatListener()
interface
uses
Windows, Messages, Classes, SysUtils;
type
{ TClipboardListener }
TClipboardListener = class(TObject)
strict private
FOnClipboardChange: TNotifyEvent;
FWnd: HWND;
procedure WindowProc(var Msg: TMessage);
public
constructor Create;
destructor Destroy; override;
property OnClipboardChange: TNotifyEvent read FOnClipboardChange
write FOnClipboardChange;
end;
implementation
constructor TClipboardListener.Create;
begin
inherited;
FWnd := AllocateHWnd(WindowProc);
if not AddClipboardFormatListener(FWnd) then
RaiseLastOSError;
end;
destructor TClipboardListener.Destroy;
begin
if FWnd <> 0 then
begin
RemoveClipboardFormatListener(FWnd);
DeallocateHWnd(FWnd);
end;
inherited;
end;
procedure TClipboardListener.WindowProc(var Msg: TMessage);
begin
if (Msg.msg = WM_CLIPBOARDUPDATE) and Assigned(FOnClipboardChange) then
begin
Msg.Result := 0;
FOnClipboardChange(Self);
end;
end;
end. |
(*
Category: SWAG Title: DATA TYPE & COMPARE ROUTINES
Original name: 0018.PAS
Description: Variable Number Parameter
Author: JANOS SZAMOSFALVI
Date: 01-27-94 12:24
*)
{
|│-> You can allocate some memory and put all your parameters there, then
|│-> pass a pointer which points to this memory block. You have to
|│-> setup some convention if you want to pass different types, or
|│-> parameters with different length.
|│
|│Well how do I do that in Pascal- I really think that I might be better
|│off making the function in C and then compiling it out to an object file
|│and then linking it into pascal
Mixed language programming is tricky and difficult unless the
compilers explicitely support it.
|│but I am not sure that that will even
|│work I might just abandon Pascal and learn C
Good luck! <evil grin>
|│(even though the SYNTAX rules for C are based on Pascal anyhow)
^^^^^^^^^^^^^^^
Hmmmm.....
Anyway, here's a quick and dirty example (untested) about passing
pointers and variable # of parameters.
}
PROGRAM Pass_Pointer; {Compiled with TP _3.01A_}
TYPE
Short_String = STRING[15];
CONST
max_count = 13;
terminator : Short_String = #0#0#0#0#0#0#0#0#0#0#0#0#0#0#0;
TYPE
String_Array = ARRAY [0..max_count] OF Short_String;
Pointer = ^String_Array;
VAR
star : Pointer;
sstr : Short_String;
count, i : INTEGER;
PROCEDURE Receiver (P : pointer);
BEGIN
i := 0;
WHILE (P^[i] <> terminator) AND (i < max_count) DO BEGIN
writeln(P^[i]);
i := i + 1;
END;
END;
BEGIN
count := 0;
New (star);
REPEAT
write('Enter a short string: ');
readln(sstr);
star^[count] := sstr;
count := count + 1;
UNTIL (sstr = '') OR (count >= max_count);
IF count < max_count THEN
star^[count - 1] := terminator;
Receiver(star);
END.
|
unit uFrmQuickEntryListUpdate;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uFrmParentQuickEntryList, cxStyles, cxCustomData,
cxGraphics, cxFilter, cxData, cxEdit, DB, cxDBData, cxGridTableView,
DBClient, siComp, siLangRT, StdCtrls, Buttons, PanelRights, cxGridLevel,
cxGridCustomTableView, cxGridDBTableView, cxClasses, cxControls,
cxGridCustomView, cxGrid, LblEffct, ExtCtrls;
type
TFrmQuickEntryListUpdate = class(TFrmParentQuickEntryList)
grdModelListDBUpdate: TcxGridDBColumn;
btSelectAll: TSpeedButton;
btUnSelectAll: TSpeedButton;
cdsModelUpdate: TBooleanField;
cdsModelDateLastCost: TDateTimeField;
cdsModelIDUserLastSellingPrice: TIntegerField;
cdsModelDateLastSellingPrice: TDateTimeField;
procedure btSaveClick(Sender: TObject);
procedure btSelectAllClick(Sender: TObject);
procedure btUnSelectAllClick(Sender: TObject);
procedure cdsModelVendorCostChange(Sender: TField);
procedure cdsModelSellingPriceChange(Sender: TField);
private
procedure UpdateModels;
procedure SetSelectAll(Value: Boolean);
procedure UpdateKitPromoPrice(IDModel: Integer; CostPrice: Currency);
protected
procedure RefreshInfo; override;
public
end;
var
FrmQuickEntryListUpdate: TFrmQuickEntryListUpdate;
implementation
uses uDM, uSystemConst, uContentClasses, uObjectServices, uMsgBox, uMsgConstant,
uCDSFunctions;
{$R *.dfm}
{ TFrmQuickEntryListUpdate }
procedure TFrmQuickEntryListUpdate.UpdateModels;
var
ModelService: TMRModelService;
Model: TModel;
i: integer;
begin
try
ModelService := TMRModelService.Create;
Model := TModel.Create;
Model.Category := TCategory.Create;
Model.ModelGroup := TModelGroup.Create;
Model.ModelSubGroup := TModelSubGroup.Create;
Model.Manufacturer := TManufacturer.Create;
ModelService.SQLConnection := DM.ADODBConnect;
grdModelListDB.Preview.Visible := False;
with cdsModel do
if not IsEmpty then
try
DisableControls;
Filter := 'Update = 1';
Filtered := True;
First;
while not Eof do
begin
if ValidateFields then
begin
//Model
Model.IDModel := FieldByName('IDModel').AsInteger;
Model.Model := FieldByName('Model').AsString;
Model.Description := FieldByName('Description').AsString;
Model.CaseQty := FieldByName('CaseQty').AsFloat;
Model.SellingPrice := FieldByName('SellingPrice').AsCurrency;
Model.SuggRetail := FieldByName('SuggRetail').AsCurrency;
Model.VendorCost := FieldByName('VendorCost').AsCurrency;
Model.Markup := FieldByName('Markup').AsFloat;
Model.IDUserLastSellingPrice := FieldByName('IDUserLastSellingPrice').AsInteger;
Model.DateLastCost := FieldByName('DateLastCost').AsDateTime;
Model.DateLastSellingPrice := FieldByName('DateLastSellingPrice').AsDateTime;
Model.Category.IDGroup := FieldByName('IDGroup').AsInteger;
Model.ModelGroup.IDModelGroup := FieldByName('IDModelGroup').AsInteger;
Model.ModelSubGroup.IDModelSubGroup := FieldByName('IDModelSubGroup').AsInteger;
Model.Manufacturer.IDManufacturer := FieldByName('IDManufacturer').AsInteger;
//Update
ModelService.Update(Model);
// Update KitModel
UpdateKitPromoPrice(Model.IDModel, Model.VendorCost);
//Deleta o registro do cds
Delete;
end
else
Next;
end;
finally
Filter := '';
Filtered := False;
EnableControls;
end;
finally
FreeAndNil(Model.Category);
FreeAndNil(Model.ModelGroup);
FreeAndNil(Model.ModelSubGroup);
FreeAndNil(Model.Manufacturer);
FreeAndNil(Model);
FreeAndNil(ModelService);
if grdModelListDB.Preview.Visible then
ModalResult := mrNone
else
cdsModel.Close;
end;
end;
procedure TFrmQuickEntryListUpdate.UpdateKitPromoPrice(IDModel: Integer; CostPrice: Currency);
var
KitModelService: TMRKitModelService;
KitModel: TKitModel;
begin
with DM.quFreeSQL do
try
if Active then
Close;
SQL.Text := ' SELECT Qty, MarginPerc FROM KitModel WHERE IDModel = ' + IntToStr(IDModel) + ' AND ISNULL(MarginPerc, 0) <> 0 ';
Open;
if not(IsEmpty) then
try
KitModelService := TMRKitModelService.Create();
KitModel := TKitModel.Create();
KitModelService.SQLConnection := DM.quFreeSQL.Connection;
First;
While not Eof do
begin
// Campos necessários
KitModel.IDModel := IDModel;
KitModel.Qty := FieldByName('Qty').AsFloat;
KitModel.SellingPrice := DM.FDMCalcPrice.GetMarginPrice(CostPrice, FieldByName('MarginPerc').AsFloat);
KitModel.MarginPerc := FieldByName('MarginPerc').AsFloat;
//Update
KitModelService.Update(KitModel);
Next;
end;
finally
FreeAndNil(KitModel);
FreeAndNil(KitModelService);
end;
finally
Close;
end;
end;
procedure TFrmQuickEntryListUpdate.btSaveClick(Sender: TObject);
begin
UpdateModels;
end;
procedure TFrmQuickEntryListUpdate.btSelectAllClick(Sender: TObject);
begin
SetSelectAll(True);
end;
procedure TFrmQuickEntryListUpdate.SetSelectAll(Value: Boolean);
begin
with cdsModel do
try
Cursor := crHourGlass;
if Active then
begin
DisableControls;
First;
while not EOF do
begin
Edit;
FieldByName('Update').AsBoolean := Value;
Post;
Next;
end;
First;
end;
finally
EnableControls;
Cursor := crDefault;
end;
end;
procedure TFrmQuickEntryListUpdate.btUnSelectAllClick(Sender: TObject);
begin
inherited;
SetSelectAll(False);
end;
procedure TFrmQuickEntryListUpdate.cdsModelVendorCostChange(Sender: TField);
begin
inherited;
cdsModel.FieldByName('DateLastCost').Value := Now;
end;
procedure TFrmQuickEntryListUpdate.cdsModelSellingPriceChange(
Sender: TField);
begin
inherited;
cdsModel.FieldByName('DateLastSellingPrice').Value := Now;
cdsModel.FieldByName('IDUserLastSellingPrice').Value := DM.fUser.ID;
end;
procedure TFrmQuickEntryListUpdate.RefreshInfo;
begin
inherited;
cdsModel.FieldByName('DateLastSellingPrice').Value := Now;
cdsModel.FieldByName('IDUserLastSellingPrice').Value := DM.fUser.ID;
end;
end.
|
unit TALG;
{Modul z algorytmamy sortuvan'}
interface
uses
TCOM;
procedure Alg454(var a: arr);
procedure Alg459(var a: arr);
procedure Alg4522(var a: arr);
procedure Alg4523(var a: arr);
implementation
type
TArr=array[1..m] of word;
var
Stolb:TArr;
{Procedura zapysuvannia j-stovchyku, k-peperizu tryvymirnogo masuvu v dodatkovyy
vektor Stovb }
procedure InclDod(k,j:word);
var i:word;
begin
for i:=1 to m do
Stolb[i]:=A[k,i,j];
end;
{Procedura povernennia elementiv z dodatkovogo
vektoru Stovb u pochatkovyy masyv}
procedure ExclDod(k,j:word);
var i:word;
begin
for i:=1 to m do
A[k,i,j]:=Stolb[i];
end;
{Prysvouvannia elementam stobchyka outp elementiv stovbchyka inp}
procedure Change(k,inp,outp:word);
var i:word;
begin
for i:=1 to m do
A[k,i,outp]:=A[k,i,inp];
end;
procedure Alg454(var a: arr);
var
X:word;
i,j,k,L,R,h:word;
begin
for h:=1 to p do
begin
NewSum(h);
for i:=2 to n do
begin
X:=Sum[i];
InclDod(h,i);
L:=1; R:=i;
while l<R do
begin
j:=(L+R) div 2;
if X>=Sum[j] then
L:=j+1
else
R:=j;
end;
for k:=i-1 downto R do
begin
Sum[k+1]:=Sum[k];
Change(h,k,k+1);
end;
Sum[R]:=X;
ExclDod(h,R);
end;
end;
end;
procedure Alg459(var a: arr);
var
k,i,Min,s,Imin:word;
begin
for k:=1 to p do
begin
NewSum(k);
for s:=1 to n-1 do
begin
Min:=Sum[s];
InclDod(k,s);
Imin:=s;
for i:=s+1 to n do
if Sum[i]<Min then
begin
Min:=Sum[i];
InclDod(k,i);
Imin:=i
end;
if Imin<>s then
begin
Sum[Imin]:=Sum[s];
Change(k,s,Imin);
Sum[s]:=Min;
ExclDod(k,s);
end;
end;
end;
end;
procedure Alg4522(var a: arr);
const
max_t=(n-1) div 4 + 1;
var
H:array[1..max_t] of word;
B,i,j,k,r,v,t:word;
begin
if n<4 then t:=1
else t:=trunc(ln(n)/ln(2))-1;
H[t]:=1;
for i:= t-1 downto 1 do H[i]:=2*H[i+1]+1;
for r:=1 to p do
begin
NewSum(r);
for v:=1 to t do
begin
k:=H[v];
for i:=k+1 to n do
begin
B:=Sum[i];
InclDod(r,i);
j:=i;
while (j>k)and(B<Sum[j-k]) do
begin
Sum[j]:=Sum[j-k];
Change(r,j-k,j);
j:=j-k;
end;
Sum[j]:=B;
ExclDod(r,j);
end;
end;
end;
end;
procedure Alg4523(var a: arr);
var k:word;
procedure QSort(k,L,R:word);
var
B,Tmp,i,j:word;
begin
B:=Sum[(L+R) div 2];
i:=L;
j:=R;
while i<=j do
begin
while Sum[i]<B do i:=i+1;
while Sum[j]>B do j:=j-1;
if i<=j then
begin
Tmp:=Sum[i];
InclDod(k,i);
Sum[i]:=Sum[j];
Change(k,j,i);
Sum[j]:=Tmp;
ExclDod(k,j);
i:=i+1;
j:=j-1;
end;
end;
if L<j then QSort(k,L,j);
if i<R then QSort(k,i,R);
end;
begin
for k:=1 to p do
begin
NewSum(k);
QSort(k,1,n);
end;
end;
end. |
unit Utils.General;
interface
uses
Vcl.Forms;
type
TFrameClass = class of Vcl.Forms.TFrame;
TValidateLibrary = class
class function CheckEmail(const Value: string): Boolean;
class function CheckIBAN(const Value: string): Boolean;
class function IsNotEmpty(const Value: string): Boolean;
end;
implementation
uses
System.RegularExpressions;
class function TValidateLibrary.CheckEmail(const Value: string): Boolean;
const
EMAIL_REGEX = '^((?>[a-zA-Z\d!#$%&''*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-\x7f])' +
'[^"\\]|\\[\x01-\x7f])*"\x20*)*(?<angle><))?((?!\.)' +
'(?>\.?[a-zA-Z\d!#$%&''*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x7f])' +
'[^"\\]|\\[\x01-\x7f])*")@(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]' +
'{2,}|\[(((?(?<!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d))' +
'{4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|\\' +
'[\x01-\x7f])+)\])(?(angle)>)$';
begin
Result := System.RegularExpressions.TRegEx.IsMatch(Value, EMAIL_REGEX);
end;
class function TValidateLibrary.CheckIBAN(const Value: string): Boolean;
begin
{ TODO: DopisaŠ weryfikacje IBAN }
Result := Value <> '';
end;
class function TValidateLibrary.IsNotEmpty(const Value: string): Boolean;
begin
Result := Value <> '';
end;
end.
|
unit FreeOTFEExplorerWebDAV;
interface
uses
Classes,
IdContext,
IdCustomHTTPServer,
SDFilesystem, SDUGeneral,
SDUWebDAV,
Windows;
type
TRequestedItem = record
Filename: Ansistring;
IsFile: Boolean;
Size: ULONGLONG;
end;
PRequestedItem = ^TRequestedItem;
TFreeOTFEExplorerWebDAV = class (TSDUWebDAV)
PROTECTED
FReturnGarbage: Boolean;
FRequestedItems: TStringList;
procedure SetReturnGarbage(newValue: Boolean);
procedure Overwrite(pItem: PRequestedItem);
procedure AddRequestedItemToList(const filename: String; const isFile: Boolean;
itemSize: ULONGLONG);
function GetRequestedItemFromList(const filename: String): PRequestedItem;
function GetPropFindXMLSingle_FSGetItem(fileOrDir: String; var item: TSDDirItem): Boolean;
OVERRIDE;
function GetPropFindXMLSingle_FSGetItem_Dummy(fileOrDir: String;
var item: TSDDirItem): Boolean;
function GetPropFindXMLSingle_Dummy(host: String; fileOrDir: String): String;
// Overridden inherited...
procedure DoCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo;
AResponseInfo: TIdHTTPResponseInfo); OVERRIDE;
procedure DoCommandDELETE(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo;
AResponseInfo: TIdHTTPResponseInfo); OVERRIDE;
procedure DoCommandMOVE(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo;
AResponseInfo: TIdHTTPResponseInfo); OVERRIDE;
procedure DoCommandPUT(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo;
AResponseInfo: TIdHTTPResponseInfo); OVERRIDE;
procedure DoCommandPROPFIND(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo;
AResponseInfo: TIdHTTPResponseInfo); OVERRIDE;
procedure DoCommandPROPPATCH(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo;
AResponseInfo: TIdHTTPResponseInfo); OVERRIDE;
PUBLIC
constructor Create(AOwner: TComponent); OVERRIDE;
destructor Destroy(); OVERRIDE;
property ReturnGarbage: Boolean Read FReturnGarbage Write SetReturnGarbage;
property RequestedItems: TStringList Read FRequestedItems;
procedure ClearDownRequestedItemsList();
end;
implementation
uses
SDUClasses, SDUHTTPServer,
Shredder,
SysUtils;
{$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
SECTOR_SIZE = 512;
constructor TFreeOTFEExplorerWebDAV.Create(AOwner: TComponent);
begin
inherited;
ReturnGarbage := False;
FRequestedItems := TStringList.Create();
FRequestedItems.Sorted := True;
end;
destructor TFreeOTFEExplorerWebDAV.Destroy();
begin
ClearDownRequestedItemsList();
FRequestedItems.Free();
inherited;
end;
function TFreeOTFEExplorerWebDAV.GetRequestedItemFromList(const filename: String): PRequestedItem;
var
idx: Integer;
useFilename: String;
begin
Result := nil;
useFilename := filename;
if not (FileSystem.CaseSensitive) then begin
useFilename := uppercase(useFilename);
end;
idx := FRequestedItems.IndexOf(useFilename);
if (idx >= 0) then begin
Result := PRequestedItem(FRequestedItems.Objects[idx]);
end;
end;
procedure TFreeOTFEExplorerWebDAV.AddRequestedItemToList(const filename: String;
const isFile: Boolean; itemSize: ULONGLONG);
var
pItem: PRequestedItem;
begin
pItem := GetRequestedItemFromList(filename);
if (pItem = nil) then begin
new(pItem);
// Note: This IS case sensitive - and should be as WebDAV is
FRequestedItems.AddObject(filename, TObject(pItem));
end;
pItem.Filename := filename;
pItem.IsFile := isFile;
pItem.Size := itemSize;
end;
procedure TFreeOTFEExplorerWebDAV.ClearDownRequestedItemsList();
var
pItem: PRequestedItem;
i: Integer;
begin
// Destroy all associated objects
for i := 0 to (FRequestedItems.Count - 1) do begin
pItem := PRequestedItem(FRequestedItems.Objects[i]);
Overwrite(pItem);
Dispose(pItem);
end;
Shredder.Overwrite(FRequestedItems);
FRequestedItems.Clear();
end;
procedure TFreeOTFEExplorerWebDAV.SetReturnGarbage(newValue: Boolean);
begin
if newValue then begin
if (Filesystem <> nil) then begin
Filesystem.ReadOnly := True;
end;
end;
FReturnGarbage := newValue;
end;
procedure TFreeOTFEExplorerWebDAV.Overwrite(pItem: PRequestedItem);
begin
Shredder.Overwrite(pItem.Filename);
pItem.IsFile := False;
pItem.Size := 0;
end;
procedure TFreeOTFEExplorerWebDAV.DoCommandGet(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
var
garbageContent: TSDUMemoryStream;
useSize: ULONGLONG;
pItem: PRequestedItem;
localFilename: String;
// ptrMem: Pointer;
ptrByte: PByte;
begin
localFilename := HTTPReqDocToLocalFile(ARequestInfo.Document);
if (not (ReturnGarbage) or (ARequestInfo.Command <> HTTPCMD_GET)) then begin
inherited;
if (AResponseInfo.ResponseNo = HTTPSTATUS_OK) then begin
if (AResponseInfo.ContentStream <> nil) then begin
AddRequestedItemToList(
localFilename,
FileSystem.FileExists(localFilename),
AResponseInfo.ContentStream.Size
);
end;
end;
end else begin
useSize := 0;
pItem := GetRequestedItemFromList(localFilename);
if (pItem <> nil) then begin
useSize := pItem.Size;
end;
// Round up to nearest SECTOR_SIZE byte boundry
// Note: This sets useSize to SECTOR_SIZE at the minimum - not zero; that's
// OK though, and probably better than setting it to 0
useSize := useSize + (ULONGLONG(SECTOR_SIZE) - ULONGLONG((useSize mod SECTOR_SIZE)));
garbageContent := TSDUMemoryStream.Create();
garbageContent.SetSize(useSize);
if (useSize > 0) then begin
garbageContent.Position := 0;
ptrByte := garbageContent.memory;
FillChar(ptrByte^, useSize, 0);
end;
garbageContent.Position := 0;
AResponseInfo.ContentStream := garbageContent;
// The response object frees off "fileContent"
AResponseInfo.FreeContentStream := True;
AResponseInfo.ResponseNo := HTTPSTATUS_OK;
end;
end;
function TFreeOTFEExplorerWebDAV.GetPropFindXMLSingle_Dummy(host: String;
fileOrDir: String): String;
const
LOCALE_ENGLISH_UNITED_STATES = 1033;
var
item: TSDDirItem;
begin
Result := '';
item := TSDDirItem.Create();
try
GetPropFindXMLSingle_FSGetItem_Dummy(fileOrDir, item);
Result := GetPropFindXMLSingle(host, fileOrDir, item);
finally
item.Free();
end;
end;
procedure TFreeOTFEExplorerWebDAV.DoCommandPROPFIND(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
var
localFilename: String;
outputXML: String;
begin
if ReturnGarbage then begin
// Generate generic "OK" reply
AResponseInfo.ResponseNo := HTTPSTATUS_OK;
localFilename := HTTPReqDocToLocalFile(ARequestInfo.Document);
// lplp - implement functionality so that can take a list of properties interested in
AddDebugLog('+++localFilename@@:' + localFilename);
outputXML := GetPropFindXMLSingle_Dummy(ARequestInfo.Host, localFilename);
outputXML := '<?xml version="1.0"?>' + SDUCRLF +
//x '<D:multistatus xmlns:D="DAV:">'+SDUCRLF+
// urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882 detailed at: http://xml.coverpages.org/xmlData980105.html and inclued in IIS responses
'<D:multistatus xmlns:D="DAV:" xmlns:b="urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/">'
+
SDUCRLF + outputXML + SDUCRLF + '</D:multistatus>';
AResponseInfo.ResponseNo := HTTPSTATUS_MULTI_STATUS;
AResponseInfo.ResponseText := HTTPSTATUS_TEXT_MULTI_STATUS;
AResponseInfo.ContentType := 'text/xml';
// outputXML := CompressXML(outputXML);
AResponseInfo.ContentText := outputXML;
AddDebugLog('XML:');
AddDebugLog(outputXML);
end else begin
inherited;
end;
end;
procedure TFreeOTFEExplorerWebDAV.DoCommandPROPPATCH(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
begin
if ReturnGarbage then begin
// Just ignore request, and say it was handled
AResponseInfo.ResponseNo := HTTPSTATUS_OK;
end else begin
inherited;
end;
end;
procedure TFreeOTFEExplorerWebDAV.DoCommandPUT(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
var
localFilename: String;
useSize: ULONGLONG;
begin
if ReturnGarbage then begin
// Just ignore request, and say it was stored
AResponseInfo.ResponseNo := HTTPSTATUS_OK;
end else begin
inherited;
if (AResponseInfo.ResponseNo = HTTPSTATUS_OK) then begin
localFilename := HTTPReqDocToLocalFile(ARequestInfo.Document);
// Sanity check - if poststream is nil, create zero length stream and use
// that instead
useSize := 0;
if (ARequestInfo.PostStream <> nil) then begin
useSize := ARequestInfo.PostStream.Size;
end;
AddRequestedItemToList(
localFilename,
True,
useSize
);
end;
end;
end;
procedure TFreeOTFEExplorerWebDAV.DoCommandDELETE(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
begin
if ReturnGarbage then begin
// Just ignore request, and say it was deleted
AResponseInfo.ResponseNo := HTTPSTATUS_OK;
end else begin
inherited;
end;
end;
procedure TFreeOTFEExplorerWebDAV.DoCommandMOVE(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
begin
if ReturnGarbage then begin
// Just ignore request, and say it was deleted
AResponseInfo.ResponseNo := HTTPSTATUS_OK;
end else begin
inherited;
end;
end;
function TFreeOTFEExplorerWebDAV.GetPropFindXMLSingle_FSGetItem(fileOrDir: String;
var item: TSDDirItem): Boolean;
begin
Result := inherited GetPropFindXMLSingle_FSGetItem(fileOrDir, item);
if ReturnGarbage and Result then begin
item.TimestampLastModified := DateTimeToTimeStamp(now());
end;
end;
function TFreeOTFEExplorerWebDAV.GetPropFindXMLSingle_FSGetItem_Dummy(fileOrDir: String;
var item: TSDDirItem): Boolean;
begin
item.Filename := ExtractFilename(fileOrDir);
item.Size := SECTOR_SIZE;
item.IsFile := True;
item.IsDirectory := False;
item.TimestampLastModified := DateTimeToTimeStamp(now());
// item.CreationDate := DateTimeToTimeStamp(now());
item.IsHidden := False;
Result := True;
end;
end.
|
unit ibSHTable;
interface
uses
SysUtils, Classes, Controls, Contnrs, Forms,
SHDesignIntf,
ibSHDesignIntf, ibSHDBObject;
type
TibBTTable = class(TibBTDBObject, IibSHTable)
private
FDecodeDomains: Boolean;
FWithoutComputed: Boolean;
FRecordCount: Integer;
FChangeCount: Integer;
FFieldList: TComponentList;
FConstraintList: TComponentList;
FIndexList: TComponentList;
FTriggerList: TComponentList;
FData: TSHComponent;
FExternalFile:string;
function GetDecodeDomains: Boolean;
procedure SetDecodeDomains(Value: Boolean);
function GetWithoutComputed: Boolean;
procedure SetWithoutComputed(Value: Boolean);
function GetRecordCountFrmt: string;
function GetChangeCountFrmt: string;
function GetField(Index: Integer): IibSHField;
function GetConstraint(Index: Integer): IibSHConstraint;
function GetIndex(Index: Integer): IibSHIndex;
function GetTrigger(Index: Integer): IibSHTrigger;
procedure SetRecordCount;
procedure SetChangeCount;
function GetData: IibSHData;
function GetExternalFile: string;
procedure SetExternalFile(const Value: string);
protected
function QueryInterface(const IID: TGUID; out Obj): HResult; override; stdcall;
procedure SetOwnerIID(Value: TGUID); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Refresh; override;
property DecodeDomains: Boolean read GetDecodeDomains write SetDecodeDomains;
property WithoutComputed: Boolean read GetWithoutComputed write SetWithoutComputed;
property RecordCountFrmt: string read GetRecordCountFrmt;
property ChangeCountFrmt: string read GetChangeCountFrmt;
property Data: IibSHData read GetData;
published
property Description;
property Fields;
property Constraints;
property Indices;
property Triggers;
property OwnerName;
end;
TibBTSystemTable = class(TibBTTable, IibSHSystemTable)
public
constructor Create(AOwner: TComponent); override;
end;
TibBTSystemTableTmp = class(TibBTSystemTable, IibSHSystemTableTmp)
end;
implementation
uses
ibSHConsts, ibSHSQLs, ibSHValues;
{ TibBTTable }
constructor TibBTTable.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDecodeDomains := False;
FWithoutComputed := False;
FRecordCount := -1;
FChangeCount := -1;
FFieldList := TComponentList.Create;
FConstraintList := TComponentList.Create;
FIndexList := TComponentList.Create;
FTriggerList := TComponentList.Create;
end;
destructor TibBTTable.Destroy;
begin
if Assigned(FData) then FData.Free;
FFieldList.Free;
FConstraintList.Free;
FIndexList.Free;
FTriggerList.Free;
inherited Destroy;
end;
procedure TibBTTable.Refresh;
begin
FFieldList.Clear;
FConstraintList.Clear;
FIndexList.Clear;
FTriggerList.Clear;
inherited Refresh;
end;
function TibBTTable.GetDecodeDomains: Boolean;
begin
Result := FDecodeDomains;
end;
procedure TibBTTable.SetDecodeDomains(Value: Boolean);
begin
FDecodeDomains := Value;
end;
function TibBTTable.GetWithoutComputed: Boolean;
begin
Result := FWithoutComputed;
end;
procedure TibBTTable.SetWithoutComputed(Value: Boolean);
begin
FWithoutComputed := Value;
end;
function TibBTTable.GetRecordCountFrmt: string;
begin
case FRecordCount of
-1: Result := Format('%s', [EmptyStr]);
0: Result := Format('%s', [SEmpty]);
else
Result := FormatFloat('###,###,###,###', FRecordCount);
end;
end;
function TibBTTable.GetChangeCountFrmt: string;
begin
case FChangeCount of
-1: Result := Format('%s', [EmptyStr]);
else
Result := Format('%d (%d left)', [FChangeCount, 255 - FChangeCount]);
end;
end;
function TibBTTable.GetField(Index: Integer): IibSHField;
begin
Assert(Index <= Pred(Fields.Count), 'Index out of bounds');
Supports(CreateParam(FFieldList, IibSHField, Index), IibSHField, Result);
end;
function TibBTTable.GetConstraint(Index: Integer): IibSHConstraint;
begin
Assert(Index <= Pred(Constraints.Count), 'Index out of bounds');
Supports(CreateParam(FConstraintList, IibSHConstraint, Index), IibSHConstraint, Result);
if Assigned(Result) and (Result.State = csUnknown) then
begin
Result.Caption := Constraints[Index];
Result.State := csSource;
Result.TableName := Self.Caption;
Result.SourceDDL.Text := DDLGenerator.GetDDLText(Result);
end;
end;
function TibBTTable.GetIndex(Index: Integer): IibSHIndex;
begin
Assert(Index <= Pred(Indices.Count), 'Index out of bounds');
Supports(CreateParam(FIndexList, IibSHIndex, Index), IibSHIndex, Result);
if Assigned(Result) and (Result.State = csUnknown) then
begin
Result.Caption := Indices[Index];
Result.State := csSource;
Result.SourceDDL.Text := DDLGenerator.GetDDLText(Result);
end;
end;
function TibBTTable.GetTrigger(Index: Integer): IibSHTrigger;
begin
Assert(Index <= Pred(Triggers.Count), 'Index out of bounds');
Supports(CreateParam(FTriggerList, IibSHTrigger, Index), IibSHTrigger, Result);
if Assigned(Result) and (Result.State = csUnknown) then
begin
Result.Caption := Triggers[Index];
Result.State := csSource;
Result.SourceDDL.Text := DDLGenerator.GetDDLText(Result);
end;
end;
procedure TibBTTable.SetRecordCount;
var
S: string;
vCodeNormalizer: IibSHCodeNormalizer;
begin
S := Self.Caption;
if Supports(Designer.GetDemon(IibSHCodeNormalizer), IibSHCodeNormalizer, vCodeNormalizer) then
S := vCodeNormalizer.MetadataNameToSourceDDL(BTCLDatabase, S);
try
Screen.Cursor := crHourGlass;
if BTCLDatabase.DRVQuery.ExecSQL(Format(FormatSQL(SQL_GET_RECORD_COUNT), [S]), [], False) then
FRecordCount := BTCLDatabase.DRVQuery.GetFieldIntValue(0);
finally
BTCLDatabase.DRVQuery.Transaction.Commit;
Screen.Cursor := crDefault;
end;
end;
procedure TibBTTable.SetChangeCount;
var
S: string;
vCodeNormalizer: IibSHCodeNormalizer;
begin
S := Self.Caption;
if Supports(Designer.GetDemon(IibSHCodeNormalizer), IibSHCodeNormalizer, vCodeNormalizer) then
S := vCodeNormalizer.MetadataNameToSourceDDL(BTCLDatabase, S);
try
Screen.Cursor := crHourGlass;
if BTCLDatabase.DRVQuery.ExecSQL(FormatSQL(SQL_GET_CHANGE_COUNT), [S], False) then
FChangeCount := BTCLDatabase.DRVQuery.GetFieldIntValue(0);
finally
BTCLDatabase.DRVQuery.Transaction.Commit;
Screen.Cursor := crDefault;
end;
end;
function TibBTTable.GetData: IibSHData;
begin
Supports(FData, IibSHData, Result);
end;
function TibBTTable.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
if IsEqualGUID(IID, IibSHData) then
begin
IInterface(Obj) := Data;
if Pointer(Obj) <> nil then
Result := S_OK
else
Result := E_NOINTERFACE;
end
else
Result := inherited QueryInterface(IID, Obj);
end;
procedure TibBTTable.SetOwnerIID(Value: TGUID);
var
vComponentClass: TSHComponentClass;
begin
if not IsEqualGUID(OwnerIID, Value) then
begin
inherited SetOwnerIID(Value);
if Assigned(FData) then FData.Free;
vComponentClass := Designer.GetComponent(IibSHData);
if Assigned(vComponentClass) then
FData := vComponentClass.Create(Self);
end;
end;
function TibBTTable.GetExternalFile: string;
begin
Result:=FExternalFile
end;
procedure TibBTTable.SetExternalFile(const Value: string);
begin
FExternalFile:=Value
end;
{ TibBTSystemTable }
constructor TibBTSystemTable.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
System := True;
end;
end.
|
//
// Generated by JavaToPas v1.5 20180804 - 083257
////////////////////////////////////////////////////////////////////////////////
unit java.util.concurrent.locks.AbstractQueuedSynchronizer;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
java.util.concurrent.TimeUnit;
type
JAbstractQueuedSynchronizer_ConditionObject = interface; // merged
JAbstractQueuedSynchronizer = interface;
JAbstractQueuedSynchronizerClass = interface(JObjectClass)
['{C276B47E-3AFE-439B-948F-FE0967288166}']
function getExclusiveQueuedThreads : JCollection; cdecl; // ()Ljava/util/Collection; A: $11
function getFirstQueuedThread : JThread; cdecl; // ()Ljava/lang/Thread; A: $11
function getQueueLength : Integer; cdecl; // ()I A: $11
function getQueuedThreads : JCollection; cdecl; // ()Ljava/util/Collection; A: $11
function getSharedQueuedThreads : JCollection; cdecl; // ()Ljava/util/Collection; A: $11
function getWaitQueueLength(condition : JAbstractQueuedSynchronizer_ConditionObject) : Integer; cdecl;// (Ljava/util/concurrent/locks/AbstractQueuedSynchronizer$ConditionObject;)I A: $11
function getWaitingThreads(condition : JAbstractQueuedSynchronizer_ConditionObject) : JCollection; cdecl;// (Ljava/util/concurrent/locks/AbstractQueuedSynchronizer$ConditionObject;)Ljava/util/Collection; A: $11
function hasContended : boolean; cdecl; // ()Z A: $11
function hasQueuedPredecessors : boolean; cdecl; // ()Z A: $11
function hasQueuedThreads : boolean; cdecl; // ()Z A: $11
function hasWaiters(condition : JAbstractQueuedSynchronizer_ConditionObject) : boolean; cdecl;// (Ljava/util/concurrent/locks/AbstractQueuedSynchronizer$ConditionObject;)Z A: $11
function isQueued(thread : JThread) : boolean; cdecl; // (Ljava/lang/Thread;)Z A: $11
function owns(condition : JAbstractQueuedSynchronizer_ConditionObject) : boolean; cdecl;// (Ljava/util/concurrent/locks/AbstractQueuedSynchronizer$ConditionObject;)Z A: $11
function release(arg : Integer) : boolean; cdecl; // (I)Z A: $11
function releaseShared(arg : Integer) : boolean; cdecl; // (I)Z A: $11
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
function tryAcquireNanos(arg : Integer; nanosTimeout : Int64) : boolean; cdecl;// (IJ)Z A: $11
function tryAcquireSharedNanos(arg : Integer; nanosTimeout : Int64) : boolean; cdecl;// (IJ)Z A: $11
procedure acquire(arg : Integer) ; cdecl; // (I)V A: $11
procedure acquireInterruptibly(arg : Integer) ; cdecl; // (I)V A: $11
procedure acquireShared(arg : Integer) ; cdecl; // (I)V A: $11
procedure acquireSharedInterruptibly(arg : Integer) ; cdecl; // (I)V A: $11
end;
[JavaSignature('java/util/concurrent/locks/AbstractQueuedSynchronizer$ConditionObject')]
JAbstractQueuedSynchronizer = interface(JObject)
['{82BE4785-D7A5-40BA-85C0-FB998BBEB0F0}']
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
end;
TJAbstractQueuedSynchronizer = class(TJavaGenericImport<JAbstractQueuedSynchronizerClass, JAbstractQueuedSynchronizer>)
end;
// Merged from: .\java.util.concurrent.locks.AbstractQueuedSynchronizer_ConditionObject.pas
JAbstractQueuedSynchronizer_ConditionObjectClass = interface(JObjectClass)
['{4A974450-AE65-4C41-B9D3-AED172303C32}']
function await(time : Int64; &unit : JTimeUnit) : boolean; cdecl; overload; // (JLjava/util/concurrent/TimeUnit;)Z A: $11
function awaitNanos(nanosTimeout : Int64) : Int64; cdecl; // (J)J A: $11
function awaitUntil(deadline : JDate) : boolean; cdecl; // (Ljava/util/Date;)Z A: $11
function init(this$0 : JAbstractQueuedSynchronizer) : JAbstractQueuedSynchronizer_ConditionObject; cdecl;// (Ljava/util/concurrent/locks/AbstractQueuedSynchronizer;)V A: $1
procedure await ; cdecl; overload; // ()V A: $11
procedure awaitUninterruptibly ; cdecl; // ()V A: $11
procedure signal ; cdecl; // ()V A: $11
procedure signalAll ; cdecl; // ()V A: $11
end;
[JavaSignature('java/util/concurrent/locks/AbstractQueuedSynchronizer_ConditionObject')]
JAbstractQueuedSynchronizer_ConditionObject = interface(JObject)
['{DC83F412-C467-45BA-A4A2-B2123CDA49C2}']
end;
TJAbstractQueuedSynchronizer_ConditionObject = class(TJavaGenericImport<JAbstractQueuedSynchronizer_ConditionObjectClass, JAbstractQueuedSynchronizer_ConditionObject>)
end;
implementation
end.
|
{ *********************************************************************** }
{ }
{ Author: Yanniel Alvarez Alfonso }
{ Description: Synchronization Classes }
{ Copyright (c) ????-2012 Pinogy Corporation }
{ }
{ *********************************************************************** }
unit DBUtils;
interface
uses
DB, ADODB, SysUtils, Dialogs, Variants,
ZAbstractConnection,
ZConnection, ZAbstractRODataset, ZAbstractDataset, ZDataset;
function InsertQuery(aQuery: TADOQuery; aSQL: string): boolean; overload;
function SelectSQL(aQuery: TADOQuery; aSQL: string) : Boolean; overload;
function InsertQuery(aQuery: TZQuery; aSQL: string; out aErrMessage: string): boolean; overload;
function SelectSQL(aQuery: TZQuery; aSQL: string; out aErrMessage: string) : Boolean; overload;
function SmartQuery(aQuery: TZQuery; aSQL: string; out aErrMessage: string) : Boolean;
function DataSet2TSV(aQuery: TDataSet; aFileName: String): Boolean;
function DatabaseExists(aQuery: TADOQuery; aDatabaseName: String): Boolean;
function CreateDatabase(aQuery: TADOQuery; aDatabaseName: String): Boolean;
implementation
function InsertQuery(aQuery: TADOQuery; aSQL: string): boolean;
begin
Result:= True;
try
if aQuery.Active then aQuery.Close;
aQuery.SQL.Clear;
aQuery.SQL.Add(aSQL);
aQuery.ExecSQL;
except
Result:= False;
end;
end;
function SelectSQL(aQuery: TADOQuery; aSQL: string) : Boolean;
begin
Result:= True;
try
if aQuery.Active then aQuery.Close;
aQuery.SQL.Clear;
aQuery.SQL.Add(aSQL);
aQuery.Active:= True;
except
Result:= False;
end;
end;
function InsertQuery(aQuery: TZQuery; aSQL: string; out aErrMessage: string): boolean;
begin
Result:= True;
try
if aQuery.Active then aQuery.Close;
aQuery.SQL.Clear;
aQuery.SQL.Add(aSQL);
aQuery.ExecSQL;
except
on E: Exception do
begin
aErrMessage:= E.Message;
Result:= False;
end;
end;
end;
function SelectSQL(aQuery: TZQuery; aSQL: string; out aErrMessage: string) : Boolean;
begin
Result:= True;
try
if aQuery.Active then aQuery.Close;
aQuery.SQL.Clear;
aQuery.SQL.Add(aSQL);
aQuery.Active:= True;
except
on E: Exception do
begin
aErrMessage:= E.Message;
Result:= False;
end;
end;
end;
function SmartQuery(aQuery: TZQuery; aSQL: string; out aErrMessage: string) : Boolean;
var
tempQry: string;
begin
Result:= False;
tempQry:= LowerCase(aSQL);
if (Pos('update ', tempQry) > 0) or
(Pos('update'#10, tempQry) > 0) or
(Pos('update'#13#10, tempQry) > 0) or
(Pos('insert ', tempQry) > 0) or
(Pos('insert'#10, tempQry) > 0) or
(Pos('insert'#13#10, tempQry) > 0) or
(Pos('delete ', tempQry) > 0) or
(Pos('delete'#10, tempQry) > 0) or
(Pos('delete'#13#10, tempQry) > 0) then
begin
Result:= InsertQuery(aQuery, aSQL, aErrMessage);
end else if (Pos('select ', tempQry) > 0) or
(Pos('select'#10, tempQry) > 0) or
(Pos('select'#13#10, tempQry) > 0) then
begin
Result:= SelectSQL(aQuery, aSQL, aErrMessage);
end;
end;
function DataSet2TSV(aQuery: TDataSet; aFileName: String): Boolean;
const
BUFFER_SIZE = 10 * 1024; // 10 kb
var
tsv_File: TextFile;
i: Integer;
Buffer: array[0.. BUFFER_SIZE - 1] of byte;
ADOQuery: TADOQuery;
key,
value: string;
begin
Result:= True;
try
AssignFile(tsv_File, aFileName);
SetTextBuf(tsv_File, Buffer);
Rewrite(tsv_File);
aQuery.DisableControls;
aQuery.Open;
try
if aQuery is TADOQuery then
begin
//*** Optimization just for TADOQuery. - BEGIN - ***
//*** It is much faster to use ADORecordset for this task ***
ADOQuery:= TADOQuery(aQuery);
for i:= 0 to ADOQuery.FieldCount - 1 do // printout the columns header
begin
if i > 0 then Write(tsv_File, #9);
Write(tsv_File, ADOQuery.Fields[i].FieldName);
end;
Writeln(tsv_File, '');
while not ADOQuery.Recordset.EOF do
begin
for i:= 0 to ADOQuery.FieldCount - 1 do
begin
if i > 0 then Write(tsv_File, #9);
begin
key:= ADOQuery.Fields[i].FieldName;
value:= VarToStr(ADOQuery.Recordset.Fields[key].Value);
Write(tsv_File, value);
end;
end;
Writeln(tsv_File, '');
ADOQuery.Recordset.MoveNext;
end;
//*** Optimization just for TADOQuery. - END - ***
end
else
begin
// *** Other type of DataSets - BEGIN- ***
for i:= 0 to aQuery.FieldCount - 1 do // printout the columns header
begin
if i > 0 then Write(tsv_File, #9);
Write(tsv_File, aQuery.Fields[i].FieldName);
end;
Writeln(tsv_File, '');
while not aQuery.EOF do
begin
for i:= 0 to aQuery.FieldCount - 1 do
begin
if i > 0 then Write(tsv_File, #9);
Write(tsv_File, aQuery.Fields[i].AsString);
end;
Writeln(tsv_File, '');
aQuery.Next;
end;
// *** Other type of DataSets - END- ***
end;
finally
aQuery.Close;
aQuery.EnableControls;
end;
CloseFile(tsv_File);
except
Result:= False;
end;
end;
function DatabaseExists(aQuery: TADOQuery; aDatabaseName: String): Boolean;
begin
Result:= False;
if Trim(aDatabaseName) = '' then Exit;
if not Assigned(aQuery) then Exit;
if not Assigned(aQuery.Connection) then Exit;
SelectSQL(aQuery, Format('select COUNT(*) from sys.databases where name=%s',[QuotedStr(aDatabaseName)]));
if aQuery.RecNo > 0 then
Result:= aQuery.Fields[0].AsInteger > 0;
end;
function CreateDatabase(aQuery: TADOQuery; aDatabaseName: String): Boolean;
begin
Result:= False;
if Trim(aDatabaseName) = '' then Exit;
if not Assigned(aQuery) then Exit;
if not Assigned(aQuery.Connection) then Exit;
aQuery.Close;
aQuery.SQL.Text:=Format('Create Database %s',[aDatabaseName]);
aQuery.ExecSQL;
aQuery.Close;
end;
end.
|
unit uftp;
interface
uses
windows,
wininet,
UnitDiversos,
UnitServerUtils;
type
tProgressProc = procedure(afile: string; Done, Total: cardinal; var abort:boolean) of object;
const
BlockSize = 1024;
type
tFtpAccess = class(tObject)
private
fSession: hINTERNET;
fConnect: hInternet;
fOnProgress: tProgressProc;
fConnected: boolean;
fSiteName: string;
fUsername: string;
fPassword: string;
public
constructor create(SiteName,UserName,Password: string; Port: integer);
destructor Destroy; override;
function GetDir: string;
function SetDir(WebDir: string): boolean;
function GetFile(WebName: string): string;
function PutFile(Source, RemoteName: string): boolean;
function FileSize(WebName: string): integer;
function DeleteFile(WebName: string): boolean;
property connected: boolean read fConnected;
property onProgress: tProgressProc read fOnProgress write fOnProgress;
end;
implementation
//####################### tFtpAccess ##############################
constructor tFtpAccess.create(SiteName, UserName, Password: string; Port: integer);
var
appName: string;
begin
fSiteName := SiteName;
fUsername := UserName;
fPassword := Password;
appName := extractFileName(paramstr(0));
fSession := InternetOpen(pchar(appName),
INTERNET_OPEN_TYPE_PRECONFIG,
nil,
nil,
0);
if assigned(fSession) then
fConnect := InternetConnect(fsession,
pchar(fSiteName),
Port,
pchar(fUserName),
pchar(fPassword),
INTERNET_SERVICE_FTP,
INTERNET_FLAG_PASSIVE,
0);
fConnected := assigned(fSession) and assigned(fConnect);
end { Create };
destructor tFtpAccess.Destroy;
begin
if fConnected then
InternetCloseHandle(fConnect);
if assigned(fSession) then
InternetCloseHandle(fSession);
inherited;
end { Destroy };
function tFtpAccess.GetDir: string;
var
buffer: array[0..MAX_PATH] of char;
bfsize: cardinal;
begin
result := '';
if fConnected then
begin
fillchar(buffer,MAX_PATH,0);
bfSize := MAX_PATH;
if ftpGetCurrentDirectory(fConnect,buffer,bfSize) then
result := buffer;
end;
end { GetDir };
function tFtpAccess.SetDir(WebDir: string): boolean;
begin
result := fConnected and
FtpSetCurrentDirectory(fConnect,pchar(WebDir));
end { SetDir };
function tFtpAccess.DeleteFile(WebName: string): boolean;
begin
result := fConnected and
FtpDeleteFile(fConnect,pchar(Webname));
end { DeleteFile };
//======================================================
// FileSize - Returns -1 if file doesn't exist
// max file size here is maxint
//------------------------------------------------------
function tFtpAccess.FileSize(WebName: string): integer;
var
f: hINTERNET;
begin
result := -1;
if fConnected then
begin
f := ftpOpenfile(fConnect,
Pchar(WebName),
GENERIC_READ,
FTP_TRANSFER_TYPE_BINARY,
0);
if assigned(f) then
try
result := ftpGetFileSize(f,nil);
finally
InternetClosehandle(f);
end;
end;
end { FileSize };
function tFtpAccess.GetFile(WebName: string): string;
var
f: HInternet;
size: integer;
ndx: integer;
amtRead: cardinal;
abort: boolean;
avail: cardinal;
ok: boolean;
toRead: cardinal;
begin
abort := false;
result := '';
if fConnected then
begin
f := ftpOpenfile(fConnect,
pchar(WebName),
GENERIC_READ,
FTP_TRANSFER_TYPE_BINARY,
0);
if assigned(f) then
try
size := ftpGetFileSize(f,nil);
setlength(result,size);
fillchar(result[1],size,0);
ndx := 1;
avail := size;
repeat
toRead := Avail;
if toread>Blocksize then toRead := BlockSize;
amtRead := 0;
if InternetReadFile(f,@result[ndx],toRead,AmtRead) then
begin
dec(avail,AmtRead);
inc(ndx,AmtRead);
if assigned(fOnProgress) then
fOnProgress(WebName,ndx,size,abort);
end;
until (avail = 0) or (ndx>= size);
finally
InternetCloseHandle(f);
end;
end;
end { GetFile };
function tFtpAccess.PutFile(Source, RemoteName: string): boolean;
var
f: HInternet;
size: integer;
ndx: integer;
ToWrite: cardinal;
Written: cardinal;
abort: boolean;
begin
abort := false;
result := false;
if fConnected and (length(Source)>0) then
begin
f := ftpOpenfile(fConnect,
pchar(RemoteName),
GENERIC_WRITE,
FTP_TRANSFER_TYPE_BINARY,
0);
if assigned(f) then
try
size := length(source);
ndx := 1;
repeat
toWrite := Size - ndx + 1;
if toWrite>Blocksize then
toWrite := blocksize;
written := 0;
if InternetWriteFile(f,@source[ndx],toWrite,Written) then
begin
inc(ndx,Written);
if assigned(fOnProgress) then
fOnProgress(RemoteName,ndx,size,abort);
end;
until (Written < Blocksize) or (ndx>size);
result := true;
finally
InternetCloseHandle(f);
end;
end;
end { PutFile };
end. |
{################################################}
{# Program Calc2 #}
{# | | _ |V| _|\| _ __ _ _ #}
{# |__|_||<(/_ | |(_| |(/_|||(/_(/_ #}
{# 2014 #}
{################################################}
{# Jednoduchá reprezentace kalkulačky #}
{# načte dvě čísla od uživatele a provede #}
{# všechny operace (součet, rozdíl, součin ...) #}
{# využívá uložení mezivýsledku do proměnné #}
{################################################}
Program calc;
var
a, b: integer;
vysledek : integer;
begin
writeln('toto je kalkulacka.');
writeln('zadej dve cisla:');
readln(a);
readln(b);
{taky jde pouzit readln(a,b); }
{funkcne jde o to stejne }
writeln('vysledky jsou:');
vysledek := a+b;
writeln('soucet: ', vysledek);
vysledek := a-b;
writeln('rozdil: ', vysledek);
vysledek := a*b;
writeln('soucin: ', vysledek);
readln;
end. |
unit o_func;
interface
{$WARN SYMBOL_PLATFORM OFF}
{$WARN UNIT_PLATFORM OFF}
// In dieser Unit befinden sich Befehle, die dazu dienen die Delphi Funktionen
// zu erweitern.
// Das Präfix nf_ steht für new|frontiers und beinhaltet, dass es sich hierbei
// um eine Globale new|frontiers Funktion handelt.
// Wichtig: Diese Funktionen sind alle Projektunabhängig.
// Hier sollten keine Projetspezifische Funktionen geschrieben werden.
// In Optima gibt es dafür die Unit f_Optima
// Es sollten nur Delphi-Standard Units eingebunden werden.
uses
SysUtils, Classes, Windows;
type
Tnf_func = class
public
class function IndexOfArray(aValue: string; aArray: array of String): Integer;
class function TextCoder(aValue: string; aPassword: Integer; aDecode: Boolean): string;
class function StrToInt(const aValue: string; const aDefault: Integer = 0): Integer;
class function BoolToStr(const aValue: Boolean): string;
class function GetIntFromStr(const aValue: string; const aDefault: Integer = -1): Integer;
class function FillStr(const aValue: string; const aLength: Integer;
const aFillStr: string; const aRight: Boolean = false): string;
class procedure SplittStrByLength(const aValue: string; const aLength: Integer; aStrings: TStrings);
class function InsertBetween(aStr, aValue: string; aPos: Integer): string;
end;
implementation
// Den Indexwert aus einem Array Lesen
class function Tnf_func.IndexOfArray(aValue: string; aArray: array of String): Integer;
var
i1: Integer;
begin
Result := low(aArray);
for i1 := low(aArray) to high(aArray) do
begin
if AnsiCompareText(aValue, aArray[i1]) = 0 then
begin
Result := i1;
exit;
end;
end;
end;
class function Tnf_func.InsertBetween(aStr, aValue: string; aPos: Integer): string;
var
s1: string;
s2: string;
begin
s1 := copy(aStr, 1, aPos);
s2 := copy(aStr, aPos+1, Length(aStr));
Result := s1 + aValue + s2;
end;
// Einfaches Verschlüsseln und Entschlüsseln eines Textes
class function Tnf_func.TextCoder(aValue: string; aPassword: Integer; aDecode: Boolean): string;
var
i, c, x: Integer;
begin
if aDecode then x := -1 else x := 1;
RandSeed := aPassword;
Result := '';
for i := 1 to length(aValue) do
begin
c := ord(aValue[i]);
if c in [32..122] then
begin
c := c+(x*Random(90));
if (c<32) or (c>122) then c := c-(x*91);
end;
Result := Result + chr(c);
end;
end;
// Einen Stringwert in einen Integerwert wandeln
// Sollte dies scheitern, dann einen bestimmten Wert zurückgeben (Default = 0).
class function Tnf_func.StrToInt(const aValue: string; const aDefault: Integer = 0): Integer;
begin
if TryStrToInt(aValue, Result) then
exit;
Result := aDefault;
end;
// Einen Boolschenwert in einen String mit '0' oder '1' wandeln
class function Tnf_func.BoolToStr(const aValue: Boolean): string;
begin
if aValue then
Result := '1'
else
Result := '0';
end;
// Nur die Zahlen aus einen String lesen
class function Tnf_func.GetIntFromStr(const aValue: string; const aDefault: Integer = -1): Integer;
var
i1 : Integer;
s : string;
begin
s := '';
for i1 := 1 to Length(aValue) do
begin
if (aValue[i1] >= '0')
and (aValue[i1] <= '9') then
s := s + aValue[i1];
end;
Result := Tnf_func.StrToInt(s, aDefault);
end;
// Füllt einen String mit Strings auf bis Stringlänge erreicht ist.
// Im Defaultwert ist Auffüllen nach Links vorgegeben.
class function Tnf_func.FillStr(const aValue: string; const aLength: Integer;
const aFillStr: string; const aRight: Boolean = false): string;
begin
Result := aValue;
while Length(Result) < aLength do
begin
if aRight then
Result := Result + aFillStr
else
Result := aFillStr + Result;
end;
end;
// Einen String bei einer bestimmten Länge aufspalten.
class procedure Tnf_func.SplittStrByLength(const aValue: string; const aLength: Integer; aStrings: TStrings);
var
s: string;
begin
aStrings.Clear;
s := aValue;
while s > '' do
begin
aStrings.add(copy(s, 1, aLength));
delete(s, 1, aLength);
end;
end;
end.
|
unit runprocess;
{$mode objfpc}{$H+}
interface
uses
classes,
SysUtils,
process;
function setwindowtoalldesktops(winstr : string) : boolean;
function RunCommandAndCaptureOut
(cmd: string; catchOut: boolean; var outlines: TStringList;
var report: string; showcmd: integer; var ExitCode: longint): boolean;
implementation
function setwindowtoalldesktops(winstr : string) : boolean;
{$IFDEF LINUX}
var
slist : TStringlist;
report : string;
exitcode : integer;
{$ENDIF LINUX}
begin
{$IFDEF LINUX}
slist := TStringlist.create;
result := RunCommandAndCaptureOut('wmctrl -r '+winstr+' -t -2',
false , slist , report, 0, exitcode);
slist.free;
{$ELSE LINUX}
Result := true;
{$ENDIF LINUX}
end;
function RunCommandAndCaptureOut
(cmd: string; catchOut: boolean; var outlines: TStringList;
var report: string; showcmd: integer; var ExitCode: longint): boolean;
const
ReadBufferSize = 2048;
var
//myStringlist : TStringlist;
S: TStringList;
M: TMemoryStream;
FpcProcess: TProcess;
n: longint;
BytesRead: longint;
begin
Result := True;
try
try
M := TMemoryStream.Create;
BytesRead := 0;
FpcProcess := process.TProcess.Create(nil);
FpcProcess.CommandLine := cmd;
FpcProcess.Options := [poUsePipes, poStderrToOutput];
FpcProcess.ShowWindow := swoMinimize;
FpcProcess.Execute;
//Logdatei.DependentAdd('RunCommandAndCaptureOut: started: ' + cmd, LLdebug2);
while FpcProcess.Running do
begin
// stellt sicher, dass wir Platz haben
M.SetSize(BytesRead + ReadBufferSize);
// versuche, es zu lesen
if FpcProcess.Output.NumBytesAvailable > 0 then
begin
n := FpcProcess.Output.Read((M.Memory + BytesRead)^, ReadBufferSize);
//Logdatei.DependentAdd('RunCommandAndCaptureOut: read: ' +
// IntToStr(n) + ' bytes', LLdebug2);
if n > 0 then
begin
Inc(BytesRead, n);
//Logdatei.DependentAdd('RunCommandAndCaptureOut: read: ' +
// IntToStr(n) + ' bytes', LLdebug2);
//Write('.')
end;
end
else
begin
// keine Daten, warte 100 ms
//Logdatei.DependentAdd('RunCommandAndCaptureOut: no data - waiting....',
// LLdebug2);
Sleep(100);
end;
end;
exitCode := FpcProcess.ExitCode;
// lese den letzten Teil
repeat
// stellt sicher, dass wir Platz haben
M.SetSize(BytesRead + ReadBufferSize);
if FpcProcess.Output.NumBytesAvailable > 0 then
begin
// versuche es zu lesen
n := FpcProcess.Output.Read((M.Memory + BytesRead)^, ReadBufferSize);
if n > 0 then
begin
Inc(BytesRead, n);
//Logdatei.DependentAdd('RunCommandAndCaptureOut: read: ' +
//IntToStr(n) + ' bytes', LLdebug2);
//Write('.');
end;
end
else
n := 0;
until n <= 0;
//if BytesRead > 0 then WriteLn;
M.SetSize(BytesRead);
//Logdatei.DependentAdd('RunCommandAndCaptureOut: -- executed --', LLdebug2);
//WriteLn('-- executed --');
S := TStringList.Create;
S.LoadFromStream(M);
//Logdatei.DependentAdd('RunCommandAndCaptureOut: -- linecount = ' +
// IntToStr(S.Count), LLdebug2);
//WriteLn('-- linecount = ', S.Count, ' --');
for n := 0 to S.Count - 1 do
begin
//WriteLn('| ', S[n]);
outlines.Add(S[n]);
end;
//WriteLn('-- end --');
//LogDatei.log('ExitCode ' + IntToStr(exitCode), LLInfo);
except
on e: Exception do
begin
//LogDatei.log('Exception in RunCommandAndCaptureOut: ' + e.message, LLError);
Result := False;
end;
end;
finally
S.Free;
FpcProcess.Free;
M.Free;
end;
end;
end.
|
unit Produto.Model;
interface
uses Produto.Model.Interf, TESTPRODUTO.Entidade.Model,
ormbr.container.objectset.interfaces, ormbr.Factory.Interfaces;
type
TProdutoModel = class(TInterfacedObject, IProdutoModel)
private
FConexao: IDBConnection;
FEntidade: TTESTPRODUTO;
FDao: IContainerObjectSet<TTESTPRODUTO>;
public
constructor Create;
destructor Destroy; override;
class function New: IProdutoModel;
function Entidade: TTESTPRODUTO; overload;
function Entidade(AValue: TTESTPRODUTO): IProdutoModel; overload;
function DAO: IContainerObjectSet<TTESTPRODUTO>;
end;
implementation
{ TProdutoModel }
uses FacadeController, ormbr.container.objectset;
constructor TProdutoModel.Create;
begin
FConexao := TFacadeController.New.ConexaoController.conexaoAtual;
FDao := TContainerObjectSet<TTESTPRODUTO>.Create(FConexao, 1);
end;
function TProdutoModel.DAO: IContainerObjectSet<TTESTPRODUTO>;
begin
Result := FDao;
end;
destructor TProdutoModel.Destroy;
begin
inherited;
end;
function TProdutoModel.Entidade: TTESTPRODUTO;
begin
Result := FEntidade;
end;
function TProdutoModel.Entidade(AValue: TTESTPRODUTO): IProdutoModel;
begin
Result := Self;
FEntidade := AValue;
end;
class function TProdutoModel.New: IProdutoModel;
begin
Result := Self.Create;
end;
end.
|
unit FileManager;
{$mode delphi}
interface
uses
Classes, LogMgr;
type
//////////////////////////////////////////
FZActualizingStatus=(FZ_ACTUALIZING_BEGIN, FZ_ACTUALIZING_IN_PROGRESS, FZ_ACTUALIZING_VERIFYING_START, FZ_ACTUALIZING_VERIFYING, FZ_ACTUALIZING_FINISHED, FZ_ACTUALIZING_FAILED );
FZFileActualizingProgressInfo = record
status:FZActualizingStatus;
total_mod_size:int64;
total_up_to_date_size:int64;
estimated_dl_size:int64;
total_downloaded:int64;
end;
FZFileActualizingCallback=function(info:FZFileActualizingProgressInfo; userdata:pointer):boolean; //return false if need to stop downloading
//////////////////////////////////////////
//FZ_FILE_ACTION_UNDEFINED - неопределенное состояние, при актуализации удаляется
//FZ_FILE_ACTION_NO - файл находится в списке синхронизируемых, после проверки состояние признано не требующим обновления
//FZ_FILE_ACTION_DOWNLOAD - файл в списке синхронизируемых, требуется перезагрузка файла
//FZ_FILE_ACTION_IGNORE - файл не участвует в синхронизации, никакие действия с ним не производятся
FZFileItemAction = ( FZ_FILE_ACTION_UNDEFINED, FZ_FILE_ACTION_NO, FZ_FILE_ACTION_DOWNLOAD, FZ_FILE_ACTION_IGNORE, FZ_FILE_ACTION_VERIFY );
FZDlMode = (FZ_DL_MODE_CURL, FZ_DL_MODE_GAMESPY);
FZCheckParams = record
size:cardinal;
crc32:cardinal;
md5:string;
end;
pFZCheckParams = ^FZCheckParams;
FZFileItemData = record
name:string;
url:string; // учитывается только при FZ_FILE_ACTION_DOWNLOAD
compression_type:cardinal;
required_action:FZFileItemAction;
real:FZCheckParams;
target:FZCheckParams; // учитывается только при FZ_FILE_ACTION_DOWNLOAD
description:string;
end;
pFZFileItemData = ^FZFileItemData;
{ FZFiles }
FZFiles = class
protected
_parent_path:string;
_files:TList;
_callback:FZFileActualizingCallback;
_cb_userdata:pointer;
_mode:FZDlMode;
function _ScanDir(dir_path:string):boolean; //сканирует поддиректорию
function _CreateFileData(name: string; url: string; compression:cardinal; need_checks:FZCheckParams; description:string): pFZFileItemData; //создает новую запись о файле и добавляет в список
public
constructor Create();
destructor Destroy(); override;
procedure Clear(); //полная очистка данных списка
procedure Dump(severity:FZLogMessageSeverity=FZ_LOG_INFO); //вывод текущего состояния списка, отладочная опция
function ScanPath(dir_path:string):boolean; //построение списка файлов в указанной директории и ее поддиректориях для последующей актуализации
function UpdateFileInfo(filename: string; url: string; description:string; compression_type:cardinal; targetParams:FZCheckParams):boolean; //обновить сведения о целевых параметрах файла
function ActualizeFiles():boolean; //актуализировать игровые данные
procedure SortBySize(); //отсортировать (по размеру) для оптимизации скорости скачивания
function AddIgnoredFile(filename:string):boolean; //добавить игнорируемый файл; вызывать после того, как все UpdateFileInfo выполнены
procedure SetCallback(cb:FZFileActualizingCallback; userdata:pointer); //добавить колбэк на обновление состояния синхронизации
function EntriesCount():integer; //число записей о синхронизируемых файлах
function GetEntry(i:cardinal):FZFileItemData; //получить копию информации об указанном файле
procedure DeleteEntry(i:cardinal); //удалить запись об синхронизации
procedure UpdateEntryAction(i:cardinal; action:FZFileItemAction ); //обновить действие для файла
procedure SetDlMode(mode:FZDlMode);
procedure Copy(from:FZFiles);
end;
function GetFileChecks(path:string; out_check_params:pFZCheckParams; needMD5:boolean):boolean;
function IsDummy(c:FZCheckParams):boolean;
function GetDummyChecks():FZCheckParams;
function CompareFiles(c1:FZCheckParams; c2:FZCheckParams):boolean;
implementation
uses sysutils, windows, HttpDownloader, FastMd5, FastCrc;
const
FM_LBL:string='[FM]';
function DirExists(dir:string):boolean;
var
ftyp:cardinal;
begin
ftyp := GetFileAttributes(PAnsiChar(dir));
result:=false;
if (ftyp = $FFFFFFFF ) then exit;
result:=(ftyp and FILE_ATTRIBUTE_DIRECTORY) <> 0;
end;
function ProvideDirPath(path:string):boolean;
var
processed_part:string;
i:integer;
status:boolean;
begin
result:=true;
processed_part:='';
for i:=1 to length(path) do begin
if (path[i]='\') or (path[i] = '/') then begin
if (length(processed_part) > 2) or ((length(processed_part)=2) and (processed_part[2] <> ':')) then begin
if not DirExists(processed_part) then begin
status:=CreateDirectory(PAnsiChar(processed_part), nil);
if not status then begin
result:=false;
break;
end;
end;
end;
end;
processed_part := processed_part+path[i];
end;
if result and (path[length(path)]<>'/') and (path[length(path)]<>'\') then begin
result:=CreateDirectory(PAnsiChar(processed_part), nil);
end;
end;
function GetDummyChecks():FZCheckParams;
begin
result.crc32:=0;
result.size:=0;
result.md5:='';
end;
function IsDummy(c:FZCheckParams):boolean;
begin
result:=(c.crc32=0) and (c.size=0) and (length(c.md5)=0);
end;
function CompareFiles(c1:FZCheckParams; c2:FZCheckParams):boolean;
begin
result:=(c1.crc32=c2.crc32) and (c1.size=c2.size) and (c1.md5=c2.md5);
end;
function GetFileChecks(path:string; out_check_params:pFZCheckParams; needMD5:boolean):boolean;
var
file_handle:cardinal;
ptr:PChar;
readbytes:cardinal;
md5_ctx:TMD5Context;
crc32_ctx:TCRC32Context;
const
WORK_SIZE:cardinal=1*1024*1024;
begin
FZLogMgr.Get.Write('Calculating checks for '+path, FZ_LOG_DBG);
result:=false;
out_check_params.crc32:=0;
out_check_params.md5:='';
readbytes:=0;
file_handle:=CreateFile(PAnsiChar(path), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL or FILE_FLAG_SEQUENTIAL_SCAN, 0);
if (file_handle<>INVALID_HANDLE_VALUE) then begin
out_check_params.size:=GetFileSize(file_handle, nil);
end else begin
FZLogMgr.Get.Write('Cannot read file, exiting', FZ_LOG_DBG);
exit;
end;
if out_check_params.size = 0 then begin
CloseHandle(file_handle);
result:=true;
exit;
end;
GetMem(ptr, WORK_SIZE);
if (ptr<>nil) then begin
md5_ctx:=MD5Start();
crc32_ctx:=CRC32Start();
while ReadFile(file_handle, ptr[0], WORK_SIZE, readbytes, nil) and (WORK_SIZE=readbytes) do begin
if needMD5 then MD5Next(md5_ctx, ptr, WORK_SIZE div MD5BlockSize());
CRC32Update(crc32_ctx, ptr, WORK_SIZE);
end;
if needMD5 then out_check_params.md5:=MD5End(md5_ctx, ptr, readbytes);
out_check_params.crc32:=CRC32End(crc32_ctx, ptr, readbytes);
FreeMem(ptr);
end else begin
FZLogMgr.Get.Write('Cannot allocate memory, exiting', FZ_LOG_ERROR);
exit;
end;
FZLogMgr.Get.Write('File size is '+inttostr(out_check_params.size)+', crc32='+inttohex(out_check_params.crc32,8)+', md5=['+out_check_params.md5+']', FZ_LOG_DBG);
CloseHandle(file_handle);
result:=true;
end;
{ FZFiles }
function FZFiles._ScanDir(dir_path: string): boolean;
var
hndl:THandle;
data:WIN32_FIND_DATA;
name:string;
begin
result:=false;
name:=_parent_path+dir_path+'*.*';
hndl:=FindFirstFile(PAnsiChar(name), @data);
if hndl = INVALID_HANDLE_VALUE then exit;
result:=true;
repeat
name := PAnsiChar(@data.cFileName[0]);
if (name = '.') or (name='..') then continue;
if (data.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY <> 0) then begin
_ScanDir(dir_path+name+'\');
end else begin
_CreateFileData(dir_path+name, '', 0, GetDummyChecks(), '');
FZLogMgr.Get.Write(FM_LBL+dir_path+name, FZ_LOG_DBG);
end;
until not FindNextFile(hndl, @data);
FindClose(hndl);
end;
function FZFiles._CreateFileData(name: string; url: string; compression:cardinal; need_checks:FZCheckParams; description:string): pFZFileItemData;
begin
New(result);
result.name:=trim(name);
result.url:=trim(url);
result.compression_type:=compression;
result.required_action:=FZ_FILE_ACTION_UNDEFINED;
result.target:=need_checks;
result.real:=GetDummyChecks();
result.description:=trim(description);
_files.Add(result);
end;
constructor FZFiles.Create();
begin
inherited Create();
_files:=TList.Create();
_callback:=nil;
_cb_userdata:=nil;
_mode:=FZ_DL_MODE_CURL;
end;
destructor FZFiles.Destroy();
begin
Clear();
_files.Free();
inherited;
end;
procedure FZFiles.Clear();
var
ptr:pFZFileItemData;
i:integer;
begin
_parent_path:='';
for i:=0 to _files.Count-1 do begin
if _files.Items[i] <> nil then begin
ptr:=_files.Items[i];
_files.Items[i]:=nil;
Dispose(ptr);
end;
end;
_files.Clear();
end;
procedure FZFiles.Dump(severity:FZLogMessageSeverity=FZ_LOG_INFO);
var
ptr:pFZFileItemData;
i:integer;
begin
FZLogMgr.Get.Write(FM_LBL+'=======File list dump start=======', severity);
for i:=0 to _files.Count-1 do begin
if _files.Items[i] <> nil then begin
ptr:=_files.Items[i];
FZLogMgr.Get.Write(FM_LBL+ptr.name+', action='+inttostr(cardinal(ptr.required_action))+
', size '+inttostr(ptr.real.size)+'('+inttostr(ptr.target.size)+
'), crc32 '+inttohex(ptr.real.crc32,8)+'('+inttohex(ptr.target.crc32,8)+
'), url='+ptr.url, severity);
end;
end;
FZLogMgr.Get.Write(FM_LBL+'=======File list dump end=======', severity);
end;
function FZFiles.ScanPath(dir_path: string):boolean;
begin
result:=true;
Clear();
FZLogMgr.Get.Write(FM_LBL+'=======Scanning directory=======', FZ_LOG_DBG);
if (dir_path[length(dir_path)]<>'\') and (dir_path[length(dir_path)]<>'/') then begin
dir_path:=dir_path+'\';
end;
_parent_path := dir_path;
_ScanDir('');
FZLogMgr.Get.Write(FM_LBL+'=======Scanning finished=======', FZ_LOG_DBG);
end;
function FZFiles.UpdateFileInfo(filename: string; url: string; description:string; compression_type:cardinal; targetParams:FZCheckParams):boolean;
var
i:integer;
filedata:pFZFileItemData;
begin
FZLogMgr.Get.Write(FM_LBL+'Updating file info for '+filename+
', size='+inttostr(targetParams.size)+
', crc='+inttohex(targetParams.crc32, 8)+
', md5=['+targetParams.md5+']'+
', url='+url+
', compression '+inttostr(compression_type), FZ_LOG_INFO);
result:=false;
filename:=trim(filename);
if Pos('..', filename)>0 then begin
FZLogMgr.Get.Write(FM_LBL+'File path cannot contain ".."', FZ_LOG_ERROR);
exit;
end;
//Пробуем найти файл среди существующих
filedata:=nil;
for i:=0 to _files.Count-1 do begin
if (_files.Items[i]<>nil) and (pFZFileItemData(_files.Items[i]).name=filename) then begin
filedata:=_files.Items[i];
break;
end;
end;
if (filedata=nil) then begin
//Файла нет в списке. Однозначно надо качать.
filedata:=_CreateFileData(filename, url, compression_type, targetParams, description);
filedata.required_action:=FZ_FILE_ACTION_DOWNLOAD;
FZLogMgr.Get.Write(FM_LBL+'Created new file list entry', FZ_LOG_INFO );
end else begin
//Файл есть в списке. Проверяем.
if IsDummy(filedata.real) then begin
//посчитаем его CRC32, если ранее не считался
if not GetFileChecks(_parent_path+filedata.name, @filedata.real, length(targetParams.md5)>0 ) then begin
filedata.real.crc32:=0;
filedata.real.size:=0;
filedata.real.md5:='';
end;
FZLogMgr.Get.Write(FM_LBL+'Current file info: CRC32='+inttohex(filedata.real.crc32, 8)+', size='+inttostr(filedata.real.size)+', md5=['+filedata.real.md5+']', FZ_LOG_INFO );
end;
if length(description)>0 then begin
filedata.description:=description;
end;
if CompareFiles(filedata.real, targetParams) then begin
filedata.required_action:=FZ_FILE_ACTION_NO;
FZLogMgr.Get.Write(FM_LBL+'Entry exists, file up-to-date', FZ_LOG_INFO );
end else begin
filedata.required_action:=FZ_FILE_ACTION_DOWNLOAD;
FZLogMgr.Get.Write(FM_LBL+'Entry exists, file outdated', FZ_LOG_INFO );
end;
filedata.target:=targetParams;
filedata.url:=url;
filedata.compression_type:=compression_type;
end;
result:=true;
end;
procedure FZFiles.SortBySize();
var
i,j,max:integer;
tmp:pFZFileItemData;
begin
if _files.Count<2 then exit;
//сортируем так, чтобы самые большие файлы оказались в конце
for i:=_files.Count-1 downto 1 do begin
max:=i;
for j:=i-1 downto 0 do begin
//Ищем самый большой файл
if (_files.Items[j]=nil) then continue;
if (_files.Items[max] = nil) or (pFZFileItemData(_files.Items[max]).target.size < (pFZFileItemData(_files.Items[j])).target.size) then begin
max:=j;
end;
end;
if i <> max then begin
tmp:=_files.Items[i];
_files.Items[i]:=_files.items[max];
_files.Items[max]:=tmp;
end;
end;
end;
function FZFiles.ActualizeFiles(): boolean;
var
i, last_file_index:integer;
filedata:pFZFileItemData;
downloaders:array of FZFileDownloader;
total_dl_size, total_actual_size, downloaded_now, downloaded_total:int64;
finished:boolean;
str:string;
thread:FZDownloaderThread;
cb_info:FZFileActualizingProgressInfo;
const
MAX_ACTIVE_DOWNLOADERS:cardinal=4; //for safety
begin
filedata:=nil;
total_dl_size:=0;
total_actual_size:=0;
downloaded_total:=0;
result:=false;
for i:=_files.Count-1 downto 0 do begin
filedata:=_files.Items[i];
if filedata=nil then continue;
if filedata.required_action=FZ_FILE_ACTION_UNDEFINED then begin
//такого файла не было в списке. Сносим.
FZLogMgr.Get.Write(FM_LBL+'Deleting file '+filedata.name, FZ_LOG_INFO);
if not Windows.DeleteFile(PAnsiChar(_parent_path+filedata.name)) then begin
FZLogMgr.Get.Write(FM_LBL+'Failed to delete '+filedata.name, FZ_LOG_ERROR);
exit;
end;
Dispose(filedata);
_files.Delete(i);
end else if filedata.required_action=FZ_FILE_ACTION_DOWNLOAD then begin
total_dl_size:=total_dl_size+filedata.target.size;
str:=_parent_path+filedata.name;
while (str[length(str)]<>'\') and (str[length(str)]<>'/') do begin
str:=leftstr(str,length(str)-1);
end;
if not ProvideDirPath(str) then begin
FZLogMgr.Get.Write(FM_LBL+'Cannot create directory '+str, FZ_LOG_ERROR);
exit;
end;
end else if filedata.required_action=FZ_FILE_ACTION_NO then begin
total_actual_size:=total_actual_size+filedata.target.size;
end else if filedata.required_action=FZ_FILE_ACTION_IGNORE then begin
FZLogMgr.Get.Write(FM_LBL+'Ignoring file '+filedata.name, FZ_LOG_INFO);
end else begin
FZLogMgr.Get.Write(FM_LBL+'Unknown action for '+filedata.name, FZ_LOG_ERROR);
exit;
end;
end;
FZLogMgr.Get.Write(FM_LBL+'Total up-to-date size '+inttostr(total_actual_size), FZ_LOG_INFO);
FZLogMgr.Get.Write(FM_LBL+'Total downloads size '+inttostr(total_dl_size), FZ_LOG_INFO);
FZLogMgr.Get.Write(FM_LBL+'Starting downloads', FZ_LOG_INFO);
result:=true;
//Вызовем колбэк для сообщения о начале стадии загрузки
cb_info.total_downloaded:=0;
cb_info.status:=FZ_ACTUALIZING_BEGIN;
cb_info.estimated_dl_size:=total_dl_size;
cb_info.total_up_to_date_size:=total_actual_size;
cb_info.total_mod_size:=total_dl_size+total_actual_size;
if (@_callback<>nil) then begin
result := _callback(cb_info, _cb_userdata)
end;
//Начнем загрузку
if _mode=FZ_DL_MODE_GAMESPY then begin
thread:=FZGameSpyDownloaderThread.Create();
end else begin
thread:=FZCurlDownloaderThread.Create();
end;
setlength(downloaders, MAX_ACTIVE_DOWNLOADERS);
last_file_index:=_files.Count-1;
finished:=false;
downloaded_total:=0;
cb_info.status:=FZ_ACTUALIZING_IN_PROGRESS;
while ( not finished ) do begin
if not result then begin
//Загрузка прервана.
FZLogMgr.Get.Write(FM_LBL+'Actualizing cancelled', FZ_LOG_ERROR);
break;
end;
finished:=true; //флаг сбросится при активной загрузке
downloaded_now:=0;
//смотрим на текущий статус слотов загрузки
for i:=0 to length(downloaders)-1 do begin
if (downloaders[i]=nil) then begin
//Слот свободен. Поставим туда что-нибудь, если найдем
while last_file_index>=0 do begin
filedata:=_files.Items[last_file_index];
last_file_index:=last_file_index-1; //сдвигаем индекс на необработанный файл
if (filedata<>nil) and (filedata.required_action=FZ_FILE_ACTION_DOWNLOAD) then begin
//файл для загрузки найден, помещаем его в слот.
FZLogMgr.Get.Write(FM_LBL+'Starting download of '+filedata.url, FZ_LOG_INFO);
finished:=false;
downloaders[i]:=thread.CreateDownloader(filedata.url, _parent_path+filedata.name, filedata.compression_type);
result:=downloaders[i].StartAsyncDownload();
if not result then begin
FZLogMgr.Get.Write(FM_LBL+'Cannot start download for '+filedata.url, FZ_LOG_ERROR);
end else begin
filedata.required_action:=FZ_FILE_ACTION_VERIFY;
end;
break;
end;
end;
end else if downloaders[i].IsBusy() then begin
//Слот активен. Обновим информацию о прогрессе
finished:=false;
downloaded_now:=downloaded_now+downloaders[i].DownloadedBytes();
end else begin
//Слот завершил работу. Освободим его.
FZLogMgr.Get.Write(FM_LBL+'Need free slot contained '+downloaders[i].GetFilename(), FZ_LOG_INFO);
result:=downloaders[i].IsSuccessful();
downloaded_total:=downloaded_total+downloaders[i].DownloadedBytes();
if not result then begin
FZLogMgr.Get.Write(FM_LBL+'Download failed for '+downloaders[i].GetFilename(), FZ_LOG_ERROR);
end;
downloaders[i].Free();
downloaders[i]:=nil;
//но могут быть еще файлы в очереди на загрузку, поэтому, не спешим выставлять в true
finished:=false;
end;
end;
//Вызовем колбэк прогресса
cb_info.total_downloaded:=downloaded_now+downloaded_total;
if (@_callback<>nil) then begin
result := _callback(cb_info, _cb_userdata);
end;
if result then Sleep(100);
end;
//Останавливаем всех их
FZLogMgr.Get.Write(FM_LBL+'Request stop', FZ_LOG_INFO);
for i:=0 to length(downloaders)-1 do begin
if downloaders[i]<>nil then begin
downloaders[i].RequestStop();
end;
end;
//и удаляем их
FZLogMgr.Get.Write(FM_LBL+'Delete downloaders', FZ_LOG_INFO);
for i:=0 to length(downloaders)-1 do begin
if downloaders[i]<>nil then begin
downloaders[i].Free();
end;
end;
setlength(downloaders,0);
thread.Free();
if result then begin
//убедимся, что все требуемое скачалось корректно
if (total_dl_size>0) then begin
FZLogMgr.Get.Write(FM_LBL+'Verifying downloaded', FZ_LOG_INFO);
cb_info.status:=FZ_ACTUALIZING_VERIFYING_START;
cb_info.total_downloaded:=0;
result := _callback(cb_info, _cb_userdata);
for i:=_files.Count-1 downto 0 do begin
if not result then break;
filedata:=_files.Items[i];
if (filedata<>nil) and (filedata.required_action=FZ_FILE_ACTION_VERIFY) then begin
if GetFileChecks(_parent_path+filedata.name, @filedata.real, length(filedata.target.md5)>0) then begin
if not CompareFiles(filedata.real, filedata.target) then begin
FZLogMgr.Get.Write(FM_LBL+'File NOT synchronized: '+filedata.name, FZ_LOG_ERROR);
filedata.required_action:=FZ_FILE_ACTION_DOWNLOAD;
result:=false;
end;
end else begin
FZLogMgr.Get.Write(FM_LBL+'Cannot check '+filedata.name, FZ_LOG_ERROR);
filedata.required_action:=FZ_FILE_ACTION_DOWNLOAD;
result:=false;
end;
end else if (filedata<>nil) and (filedata.required_action=FZ_FILE_ACTION_DOWNLOAD) then begin
FZLogMgr.Get.Write(FM_LBL+'File '+filedata.name+' has FZ_FILE_ACTION_DOWNLOAD state after successful synchronization??? A bug suspected!', FZ_LOG_ERROR);
result:=false;
end;
if result then begin
cb_info.status:=FZ_ACTUALIZING_VERIFYING;
cb_info.total_downloaded:=cb_info.total_downloaded+filedata.target.size;
result := _callback(cb_info, _cb_userdata)
end;
end;
end;
//вызываем колбэк окончания
if result then begin
FZLogMgr.Get.Write(FM_LBL+'Run finish callback', FZ_LOG_INFO);
cb_info.status:=FZ_ACTUALIZING_FINISHED;
cb_info.total_downloaded:=downloaded_total;
result := _callback(cb_info, _cb_userdata)
end else begin
FZLogMgr.Get.Write(FM_LBL+'Run fail callback', FZ_LOG_INFO);
cb_info.status:=FZ_ACTUALIZING_FAILED;
cb_info.total_downloaded:=0;
_callback(cb_info, _cb_userdata)
end;
FZLogMgr.Get.Write(FM_LBL+'All downloads finished', FZ_LOG_INFO);
end;
end;
function FZFiles.AddIgnoredFile(filename: string): boolean;
var
i:integer;
filedata:pFZFileItemData;
begin
//Пробуем найти файл среди существующих
filedata:=nil;
for i:=0 to _files.Count-1 do begin
if (_files.Items[i]<>nil) and (pFZFileItemData(_files.Items[i]).name=filename) then begin
filedata:=_files.Items[i];
break;
end;
end;
if filedata<>nil then begin
filedata.required_action:=FZ_FILE_ACTION_IGNORE;
end;
result:=true;
end;
procedure FZFiles.SetCallback(cb: FZFileActualizingCallback; userdata: pointer);
begin
_cb_userdata:=userdata;
_callback:=cb;
end;
function FZFiles.EntriesCount(): integer;
begin
result:=_files.Count;
end;
function FZFiles.GetEntry(i: cardinal): FZFileItemData;
var
filedata:pFZFileItemData;
begin
if (int64(i)<int64(_files.Count)) then begin
filedata:=_files.Items[i];
if filedata<>nil then begin
result:=filedata^;
end;
end;
end;
procedure FZFiles.DeleteEntry(i: cardinal);
var
filedata:pFZFileItemData;
begin
if (int64(i)<int64(_files.Count)) then begin
filedata:=_files.Items[i];
Dispose(filedata);
_files.Delete(i);
end;
end;
procedure FZFiles.UpdateEntryAction(i: cardinal; action: FZFileItemAction);
var
filedata:pFZFileItemData;
begin
if (int64(i)<int64(_files.Count)) then begin
filedata:=_files.Items[i];
filedata.required_action:=action;
end;
end;
procedure FZFiles.SetDlMode(mode: FZDlMode);
begin
_mode:=mode;
end;
procedure FZFiles.Copy(from: FZFiles);
var
i:integer;
filedata:pFZFileItemData;
begin
Clear();
_cb_userdata:=from._cb_userdata;
_callback:=from._callback;
_parent_path:=from._parent_path;
_mode:=from._mode;
for i:=0 to from._files.Count-1 do begin
New(filedata);
filedata^ := pFZFileItemData(from._files.Items[i])^;
_files.Add(filedata);
end;
end;
end.
|
(*
Category: SWAG Title: STRING HANDLING ROUTINES
Original name: 0018.PAS
Description: Three ways to Uppercase
Author: SWAG SUPPORT TEAM
Date: 05-31-93 07:16
*)
{
Three ways to convert a string to uppercase (without international support).
}
{$R-,S-,I- }
Procedure UpCaseStr0(Var s : String);
Var
i : Integer;
Begin
For i := 1 to Length(s) Do
s[i] := UpCase(s[i]);
end; { UpCaseStr0 }
Procedure UpCaseStr1(Var s : String);
Var
i, len : Integer;
Begin
i := 0;
len := Ord(s[0]);
Repeat
Inc(i);
If i > len Then
Break;
If s[i] in ['a'..'z'] Then
Dec(s[i], 32);
Until False;
end; { UpCaseStr1 }
(*
* Note: this ASM syntax is not allowed in FreePascal
*
Procedure UpCaseStr2(Var s : String); Assembler;
ASM
PUSH DS
LDS SI, s
LES DI, s
CLD
XOR AH, AH
LODSB
STOSB
XCHG AX, CX
JCXZ @2
@1: LODSB
SUB AL, 'a'
CMP AL, 'z'-'a'+1
SBB AH, AH
AND AH, 'a'-'A'
SUB AL, AH
ADD AL, 'a'
STOSB
LOOP @1
@2: POP DS
end; { UpCaseStr2 }
*)
(*
Procedure Size Execution timing*
(bytes) (seconds)
UpCaseStr0 76 4.32 = 1.00
UpCaseStr1 67 2.76 = 0.63
UpCaseStr2 39 1.31 = 0.30
*30,000 times on a 40 MHz 386
Wilbert
*)
var
s1, s2: string;
begin
s1 := 'HeLlo';
UpCaseStr0(s1);
WriteLn(s1);
s2 := 'HeLlo';
UpCaseStr1(s2);
WriteLn(s2);
end.
|
unit ExtMenu;
// Generated by ExtToPascal v.0.9.8, at 3/5/2010 11:59:34
// from "C:\Trabalho\ext\docs\output" detected as ExtJS v.3
interface
uses
StrUtils, ExtPascal, ExtPascalUtils, Ext;
type
TExtMenuMenuMgrSingleton = class;
TExtMenuBaseItem = class;
TExtMenuSeparator = class;
TExtMenuTextItem = class;
TExtMenuItem = class;
TExtMenuCheckItem = class;
TExtMenuMenu = class;
TExtMenuColorMenu = class;
TExtMenuDateMenu = class;
TExtMenuMenuMgrSingleton = class(TExtFunction)
public
class function JSClassName: string; override;
function Get(Menu: string): TExtFunction; overload;
function Get(Menu: TExtObject): TExtFunction; overload;
function HideAll: TExtFunction;
end;
// Procedural types for events TExtMenuBaseItem
TExtMenuBaseItemOnActivate = procedure(This: TExtMenuBaseItem) of object;
TExtMenuBaseItemOnClick = procedure(This: TExtMenuBaseItem; E: TExtEventObjectSingleton)
of object;
TExtMenuBaseItemOnDeactivate = procedure(This: TExtMenuBaseItem) of object;
TExtMenuBaseItem = class(TExtComponent)
private
FActiveClass: string; // 'x-menu-item-active'
FCanActivate: Boolean;
FClickHideDelay: Integer; // 1
FHandler: TExtFunction;
FHideOnClick: Boolean; // true
FScope: TExtObject;
FParentMenu: TExtMenuMenu;
FOnActivate: TExtMenuBaseItemOnActivate;
FOnClick: TExtMenuBaseItemOnClick;
FOnDeactivate: TExtMenuBaseItemOnDeactivate;
procedure SetFActiveClass(Value: string);
procedure SetFCanActivate(Value: Boolean);
procedure SetFClickHideDelay(Value: Integer);
procedure _SetHandler(const AValue: TExtFunction);
procedure SetFHideOnClick(Value: Boolean);
procedure SetFScope(Value: TExtObject);
procedure SetFParentMenu(Value: TExtMenuMenu);
procedure SetFOnActivate(Value: TExtMenuBaseItemOnActivate);
procedure SetFOnClick(Value: TExtMenuBaseItemOnClick);
procedure SetFOnDeactivate(Value: TExtMenuBaseItemOnDeactivate);
protected
procedure InitDefaults; override;
procedure HandleEvent(const AEvtName: string); override;
public
class function JSClassName: string; override;
function SetHandler(const AHandler: TExtFunction; const AScope: TExtObject): TExtFunction;
property ActiveClass: string read FActiveClass write SetFActiveClass;
property CanActivate: Boolean read FCanActivate write SetFCanActivate;
property ClickHideDelay: Integer read FClickHideDelay write SetFClickHideDelay;
property Handler: TExtFunction read FHandler write _SetHandler;
property HideOnClick: Boolean read FHideOnClick write SetFHideOnClick;
property Scope: TExtObject read FScope write SetFScope;
property ParentMenu: TExtMenuMenu read FParentMenu write SetFParentMenu;
property OnActivate: TExtMenuBaseItemOnActivate read FOnActivate write SetFOnActivate;
property OnClick: TExtMenuBaseItemOnClick read FOnClick write SetFOnClick;
property OnDeactivate: TExtMenuBaseItemOnDeactivate read FOnDeactivate
write SetFOnDeactivate;
end;
TExtMenuSeparator = class(TExtMenuBaseItem)
private
FHideOnClick: Boolean;
FItemCls: string; // 'x-menu-sep'
procedure SetFHideOnClick(Value: Boolean);
procedure SetFItemCls(Value: string);
protected
procedure InitDefaults; override;
public
class function JSClassName: string; override;
property HideOnClick: Boolean read FHideOnClick write SetFHideOnClick;
property ItemCls: string read FItemCls write SetFItemCls;
end;
TExtMenuTextItem = class(TExtMenuBaseItem)
private
FHideOnClick: Boolean;
FItemCls: string; // 'x-menu-text'
FText: string;
procedure SetFHideOnClick(Value: Boolean);
procedure SetFItemCls(Value: string);
procedure SetFText(Value: string);
protected
procedure InitDefaults; override;
public
class function JSClassName: string; override;
property HideOnClick: Boolean read FHideOnClick write SetFHideOnClick;
property ItemCls: string read FItemCls write SetFItemCls;
property Text: string read FText write SetFText;
end;
TExtMenuItem = class(TExtMenuBaseItem)
private
FCanActivate: Boolean; // true
FHref: string; // '#'
FHrefTarget: string;
FIcon: string;
FIconCls: string;
FItemCls: string; // 'x-menu-item'
FMenu: TExtMenuMenu;
FShowDelay: Integer; // 200
FText: string;
FMenu_: TExtMenuMenu;
procedure SetFCanActivate(Value: Boolean);
procedure SetFHref(Value: string);
procedure SetFHrefTarget(Value: string);
procedure SetFIcon(Value: string);
procedure SetIconCls(const AValue: string);
procedure SetFItemCls(Value: string);
procedure SetMenu(AValue: TExtMenuMenu);
procedure SetFShowDelay(Value: Integer);
procedure SetText(const AValue: string);
procedure SetFMenu_(Value: TExtMenuMenu);
protected
procedure InitDefaults; override;
public
class function JSClassName: string; override;
function SetIconClass(Cls: string): TExtFunction;
property CanActivate: Boolean read FCanActivate write SetFCanActivate;
property Href: string read FHref write SetFHref;
property HrefTarget: string read FHrefTarget write SetFHrefTarget;
property Icon: string read FIcon write SetFIcon;
property IconCls: string read FIconCls write SetIconCls;
property ItemCls: string read FItemCls write SetFItemCls;
property Menu: TExtMenuMenu read FMenu write SetMenu;
property ShowDelay: Integer read FShowDelay write SetFShowDelay;
property Text: string read FText write SetText;
property Menu_: TExtMenuMenu read FMenu_ write SetFMenu_;
end;
// Procedural types for events TExtMenuCheckItem
TExtMenuCheckItemOnBeforecheckchange = procedure(This: TExtMenuCheckItem;
Checked: Boolean) of object;
TExtMenuCheckItemOnCheckchange = procedure(This: TExtMenuCheckItem; Checked: Boolean)
of object;
TExtMenuCheckItem = class(TExtMenuItem)
private
FChecked: Boolean;
FGroup: string;
FGroupClass: string; // 'x-menu-group-item'
FItemCls: string; // 'x-menu-item x-menu-check-item'
FOnBeforecheckchange: TExtMenuCheckItemOnBeforecheckchange;
FOnCheckchange: TExtMenuCheckItemOnCheckchange;
procedure _SetChecked(const AValue: Boolean);
procedure SetFGroup(Value: string);
procedure SetFGroupClass(Value: string);
procedure SetFItemCls(Value: string);
procedure SetFOnBeforecheckchange(Value: TExtMenuCheckItemOnBeforecheckchange);
procedure SetFOnCheckchange(Value: TExtMenuCheckItemOnCheckchange);
protected
procedure InitDefaults; override;
procedure HandleEvent(const AEvtName: string); override;
public
class function JSClassName: string; override;
function CheckHandler(This: TExtMenuCheckItem; Checked: Boolean): TExtFunction;
function SetChecked(const AChecked: Boolean; const ASuppressEvent: Boolean = False): TExtFunction;
property Checked: Boolean read FChecked write _SetChecked;
property Group: string read FGroup write SetFGroup;
property GroupClass: string read FGroupClass write SetFGroupClass;
property ItemCls: string read FItemCls write SetFItemCls;
property OnBeforecheckchange: TExtMenuCheckItemOnBeforecheckchange
read FOnBeforecheckchange write SetFOnBeforecheckchange;
property OnCheckchange: TExtMenuCheckItemOnCheckchange read FOnCheckchange
write SetFOnCheckchange;
end;
// Procedural types for events TExtMenuMenu
TExtMenuMenuOnClick = procedure(This: TExtMenuMenu; MenuItem: TExtMenuItem;
E: TExtEventObjectSingleton) of object;
TExtMenuMenuOnItemclick = procedure(BaseItem: TExtMenuBaseItem;
E: TExtEventObjectSingleton) of object;
TExtMenuMenuOnMouseout = procedure(This: TExtMenuMenu; E: TExtEventObjectSingleton;
MenuItem: TExtMenuItem) of object;
TExtMenuMenuOnMouseover = procedure(This: TExtMenuMenu; E: TExtEventObjectSingleton;
MenuItem: TExtMenuItem) of object;
TExtMenuMenu = class(TExtContainer)
private
FAllowOtherMenus: Boolean;
FDefaultAlign: string; // 'tl-bl?'
FDefaultOffsets: TExtObjectList;
FDefaults: TExtObject;
FEnableScrolling: Boolean; // true
FFloating: Boolean;
FIgnoreParentClicks: Boolean;
FItems: TExtObjectList;
FLayout: string;
FLayoutObject: TExtObject;
FMaxHeight: Integer;
FMinWidth: Integer; // 120
FPlain: Boolean;
FScrollIncrement: Integer; // 24
FShadow: Boolean;
FShadowString: string;
FShowSeparator: Boolean; // true
FSubMenuAlign: string; // 'tl-tr?'
FZIndex: Integer;
FOnClick: TExtMenuMenuOnClick;
FOnItemclick: TExtMenuMenuOnItemclick;
FOnMouseout: TExtMenuMenuOnMouseout;
FOnMouseover: TExtMenuMenuOnMouseover;
procedure SetFAllowOtherMenus(Value: Boolean);
procedure SetFDefaultAlign(Value: string);
procedure SetFDefaultOffsets(Value: TExtObjectList);
procedure SetFDefaults(Value: TExtObject);
procedure SetFEnableScrolling(Value: Boolean);
procedure SetFFloating(Value: Boolean);
procedure SetFIgnoreParentClicks(Value: Boolean);
procedure SetFItems(Value: TExtObjectList);
procedure SetFLayout(Value: string);
procedure SetFLayoutObject(Value: TExtObject);
procedure SetFMaxHeight(Value: Integer);
procedure SetFMinWidth(Value: Integer);
procedure SetFPlain(Value: Boolean);
procedure SetFScrollIncrement(Value: Integer);
procedure SetFShadow(Value: Boolean);
procedure SetFShadowString(Value: string);
procedure SetFShowSeparator(Value: Boolean);
procedure SetFSubMenuAlign(Value: string);
procedure SetFZIndex(Value: Integer);
procedure SetFOnClick(Value: TExtMenuMenuOnClick);
procedure SetFOnItemclick(Value: TExtMenuMenuOnItemclick);
procedure SetFOnMouseout(Value: TExtMenuMenuOnMouseout);
procedure SetFOnMouseover(Value: TExtMenuMenuOnMouseover);
protected
procedure InitDefaults; override;
procedure HandleEvent(const AEvtName: string); override;
public
class function JSClassName: string; override;
function AddElement(El: string): TExtFunction;
function AddItem(Item: TExtMenuItem): TExtFunction;
function AddMenuItem(Config: TExtObject = nil): TExtFunction;
function AddSeparator: TExtFunction;
function AddText(Text: string): TExtFunction;
function Hide(Deep: Boolean = false): TExtFunction;
function Show(Element: string; Position: string = ''; ParentMenu: TExtMenuMenu = nil)
: TExtFunction;
function ShowAt(XyPosition: TExtObjectList; ParentMenu: TExtMenuMenu = nil)
: TExtFunction;
property AllowOtherMenus: Boolean read FAllowOtherMenus write SetFAllowOtherMenus;
property DefaultAlign: string read FDefaultAlign write SetFDefaultAlign;
property DefaultOffsets: TExtObjectList read FDefaultOffsets write SetFDefaultOffsets;
property Defaults: TExtObject read FDefaults write SetFDefaults;
property EnableScrolling: Boolean read FEnableScrolling write SetFEnableScrolling;
property Floating: Boolean read FFloating write SetFFloating;
property IgnoreParentClicks: Boolean read FIgnoreParentClicks
write SetFIgnoreParentClicks;
property Items: TExtObjectList read FItems write SetFItems;
property Layout: string read FLayout write SetFLayout;
property LayoutObject: TExtObject read FLayoutObject write SetFLayoutObject;
property MaxHeight: Integer read FMaxHeight write SetFMaxHeight;
property MinWidth: Integer read FMinWidth write SetFMinWidth;
property Plain: Boolean read FPlain write SetFPlain;
property ScrollIncrement: Integer read FScrollIncrement write SetFScrollIncrement;
property Shadow: Boolean read FShadow write SetFShadow;
property ShadowString: string read FShadowString write SetFShadowString;
property ShowSeparator: Boolean read FShowSeparator write SetFShowSeparator;
property SubMenuAlign: string read FSubMenuAlign write SetFSubMenuAlign;
property ZIndex: Integer read FZIndex write SetFZIndex;
property OnClick: TExtMenuMenuOnClick read FOnClick write SetFOnClick;
property OnItemclick: TExtMenuMenuOnItemclick read FOnItemclick write SetFOnItemclick;
property OnMouseout: TExtMenuMenuOnMouseout read FOnMouseout write SetFOnMouseout;
property OnMouseover: TExtMenuMenuOnMouseover read FOnMouseover write SetFOnMouseover;
end;
// Procedural types for events TExtMenuColorMenu
TExtMenuColorMenuOnSelect = procedure(Palette: TExtColorPalette; Color: string)
of object;
TExtMenuColorMenu = class(TExtMenuMenu)
private
FHandler: TExtFunction;
FHideOnClick: Boolean;
FPaletteId: string;
FScope: TExtObject;
FPalette: TExtColorPalette;
FOnSelect: TExtMenuColorMenuOnSelect;
procedure SetFHandler(Value: TExtFunction);
procedure SetFHideOnClick(Value: Boolean);
procedure SetFPaletteId(Value: string);
procedure SetFScope(Value: TExtObject);
procedure SetFPalette(Value: TExtColorPalette);
procedure SetFOnSelect(Value: TExtMenuColorMenuOnSelect);
protected
procedure InitDefaults; override;
procedure HandleEvent(const AEvtName: string); override;
public
class function JSClassName: string; override;
property Handler: TExtFunction read FHandler write SetFHandler;
property HideOnClick: Boolean read FHideOnClick write SetFHideOnClick;
property PaletteId: string read FPaletteId write SetFPaletteId;
property Scope: TExtObject read FScope write SetFScope;
property Palette: TExtColorPalette read FPalette write SetFPalette;
property OnSelect: TExtMenuColorMenuOnSelect read FOnSelect write SetFOnSelect;
end;
// Procedural types for events TExtMenuDateMenu
TExtMenuDateMenuOnSelect = procedure(Picker: TExtDatePicker; Date: TDateTime) of object;
TExtMenuDateMenu = class(TExtMenuMenu)
private
FHandler: TExtFunction;
FHideOnClick: Boolean;
FPickerId: string;
FScope: TExtObject;
FPicker: TExtDatePicker;
FOnSelect: TExtMenuDateMenuOnSelect;
procedure SetFHandler(Value: TExtFunction);
procedure SetFHideOnClick(Value: Boolean);
procedure SetFPickerId(Value: string);
procedure SetFScope(Value: TExtObject);
procedure SetFPicker(Value: TExtDatePicker);
procedure SetFOnSelect(Value: TExtMenuDateMenuOnSelect);
protected
procedure InitDefaults; override;
procedure HandleEvent(const AEvtName: string); override;
public
class function JSClassName: string; override;
property Handler: TExtFunction read FHandler write SetFHandler;
property HideOnClick: Boolean read FHideOnClick write SetFHideOnClick;
property PickerId: string read FPickerId write SetFPickerId;
property Scope: TExtObject read FScope write SetFScope;
property Picker: TExtDatePicker read FPicker write SetFPicker;
property OnSelect: TExtMenuDateMenuOnSelect read FOnSelect write SetFOnSelect;
end;
function ExtMenuMenuMgr: TExtMenuMenuMgrSingleton;
implementation
function ExtMenuMenuMgr: TExtMenuMenuMgrSingleton;
begin
if (Session <> nil) then
Result := Session.GetSingleton<TExtMenuMenuMgrSingleton>(TExtMenuMenuMgrSingleton.JSClassName)
else
Result := nil;
end;
class function TExtMenuMenuMgrSingleton.JSClassName: string;
begin
Result := 'Ext.menu.MenuMgr';
end;
function TExtMenuMenuMgrSingleton.Get(Menu: string): TExtFunction;
begin
JSCode(JSName + '.get(' + VarToJSON([Menu]) + ');', 'TExtMenuMenuMgrSingleton');
Result := Self;
end;
function TExtMenuMenuMgrSingleton.Get(Menu: TExtObject): TExtFunction;
begin
JSCode(JSName + '.get(' + VarToJSON([Menu, false]) + ');', 'TExtMenuMenuMgrSingleton');
Result := Self;
end;
function TExtMenuMenuMgrSingleton.HideAll: TExtFunction;
begin
JSCode(JSName + '.hideAll();', 'TExtMenuMenuMgrSingleton');
Result := Self;
end;
procedure TExtMenuBaseItem.SetFActiveClass(Value: string);
begin
FActiveClass := Value;
JSCode('activeClass:' + VarToJSON([Value]));
end;
procedure TExtMenuBaseItem.SetFCanActivate(Value: Boolean);
begin
FCanActivate := Value;
JSCode('canActivate:' + VarToJSON([Value]));
end;
procedure TExtMenuBaseItem.SetFClickHideDelay(Value: Integer);
begin
FClickHideDelay := Value;
JSCode('clickHideDelay:' + VarToJSON([Value]));
end;
procedure TExtMenuBaseItem._SetHandler(const AValue: TExtFunction);
begin
FHandler.Free;
FHandler := AValue;
ExtSession.ResponseItems.SetConfigItem(Self, 'handler', 'setHandler', [AValue, True]);
end;
procedure TExtMenuBaseItem.SetFHideOnClick(Value: Boolean);
begin
FHideOnClick := Value;
JSCode('hideOnClick:' + VarToJSON([Value]));
end;
procedure TExtMenuBaseItem.SetFScope(Value: TExtObject);
begin
FScope := Value;
JSCode('scope:' + VarToJSON([Value, false]));
end;
procedure TExtMenuBaseItem.SetFParentMenu(Value: TExtMenuMenu);
begin
FParentMenu := Value;
JSCode(JSName + '.parentMenu=' + VarToJSON([Value, false]) + ';');
end;
procedure TExtMenuBaseItem.SetFOnActivate(Value: TExtMenuBaseItemOnActivate);
begin
if Assigned(FOnActivate) then
JSCode(JSName + '.events ["activate"].listeners=[];');
if Assigned(Value) then
on('activate', Ajax('activate', ['This', '%0.nm'], true));
FOnActivate := Value;
end;
procedure TExtMenuBaseItem.SetFOnClick(Value: TExtMenuBaseItemOnClick);
begin
if Assigned(FOnClick) then
JSCode(JSName + '.events ["click"].listeners=[];');
if Assigned(Value) then
on('click', Ajax('click', ['This', '%0.nm', 'E', '%1.nm'], true));
FOnClick := Value;
end;
procedure TExtMenuBaseItem.SetFOnDeactivate(Value: TExtMenuBaseItemOnDeactivate);
begin
if Assigned(FOnDeactivate) then
JSCode(JSName + '.events ["deactivate"].listeners=[];');
if Assigned(Value) then
on('deactivate', Ajax('deactivate', ['This', '%0.nm'], true));
FOnDeactivate := Value;
end;
class function TExtMenuBaseItem.JSClassName: string;
begin
Result := 'Ext.menu.BaseItem';
end;
procedure TExtMenuBaseItem.InitDefaults;
begin
inherited;
FActiveClass := 'x-menu-item-active';
FClickHideDelay := 1;
FHideOnClick := true;
FScope := TExtObject.CreateInternal(Self, 'scope');
FParentMenu := TExtMenuMenu.CreateInternal(Self, 'parentMenu');
end;
function TExtMenuBaseItem.SetHandler(const AHandler: TExtFunction; const AScope: TExtObject): TExtFunction;
begin
FHandler.Free;
FHandler := AHandler;
ExtSession.ResponseItems.CallMethod(Self, 'setHandler', [AHandler, True, AScope, False]);
Result := Self;
end;
procedure TExtMenuBaseItem.HandleEvent(const AEvtName: string);
begin
inherited;
if (AEvtName = 'activate') and Assigned(FOnActivate) then
FOnActivate(TExtMenuBaseItem(ParamAsObject('This')))
else if (AEvtName = 'click') and Assigned(FOnClick) then
FOnClick(TExtMenuBaseItem(ParamAsObject('This')), ExtEventObject)
else if (AEvtName = 'deactivate') and Assigned(FOnDeactivate) then
FOnDeactivate(TExtMenuBaseItem(ParamAsObject('This')));
end;
procedure TExtMenuSeparator.SetFHideOnClick(Value: Boolean);
begin
FHideOnClick := Value;
JSCode('hideOnClick:' + VarToJSON([Value]));
end;
procedure TExtMenuSeparator.SetFItemCls(Value: string);
begin
FItemCls := Value;
JSCode('itemCls:' + VarToJSON([Value]));
end;
class function TExtMenuSeparator.JSClassName: string;
begin
Result := 'Ext.menu.Separator';
end;
procedure TExtMenuSeparator.InitDefaults;
begin
inherited;
FItemCls := 'x-menu-sep';
end;
procedure TExtMenuTextItem.SetFHideOnClick(Value: Boolean);
begin
FHideOnClick := Value;
JSCode('hideOnClick:' + VarToJSON([Value]));
end;
procedure TExtMenuTextItem.SetFItemCls(Value: string);
begin
FItemCls := Value;
JSCode('itemCls:' + VarToJSON([Value]));
end;
procedure TExtMenuTextItem.SetFText(Value: string);
begin
FText := Value;
JSCode('text:' + VarToJSON([Value]));
end;
class function TExtMenuTextItem.JSClassName: string;
begin
Result := 'Ext.menu.TextItem';
end;
procedure TExtMenuTextItem.InitDefaults;
begin
inherited;
FItemCls := 'x-menu-text';
end;
procedure TExtMenuItem.SetFCanActivate(Value: Boolean);
begin
FCanActivate := Value;
JSCode('canActivate:' + VarToJSON([Value]));
end;
procedure TExtMenuItem.SetFHref(Value: string);
begin
FHref := Value;
JSCode('href:' + VarToJSON([Value]));
end;
procedure TExtMenuItem.SetFHrefTarget(Value: string);
begin
FHrefTarget := Value;
JSCode('hrefTarget:' + VarToJSON([Value]));
end;
procedure TExtMenuItem.SetFIcon(Value: string);
begin
FIcon := Value;
JSCode('icon:' + VarToJSON([Value]));
end;
procedure TExtMenuItem.SetIconCls(const AValue: string);
begin
FIconCls := AValue;
ExtSession.ResponseItems.SetConfigItem(Self, 'iconCls', [AValue]);
end;
procedure TExtMenuItem.SetFItemCls(Value: string);
begin
FItemCls := Value;
JSCode('itemCls:' + VarToJSON([Value]));
end;
procedure TExtMenuItem.SetMenu(AValue: TExtMenuMenu);
begin
FMenu.Free;
FMenu := AValue;
ExtSession.ResponseItems.SetConfigItem(Self, 'menu', [AValue, False]);
end;
procedure TExtMenuItem.SetFShowDelay(Value: Integer);
begin
FShowDelay := Value;
JSCode('showDelay:' + VarToJSON([Value]));
end;
procedure TExtMenuItem.SetText(const AValue: string);
begin
FText := AValue;
ExtSession.ResponseItems.SetConfigItem(Self, 'text', 'setText', [AValue]);
end;
procedure TExtMenuItem.SetFMenu_(Value: TExtMenuMenu);
begin
FMenu_ := Value;
JSCode(JSName + '.menu=' + VarToJSON([Value, false]) + ';');
end;
class function TExtMenuItem.JSClassName: string;
begin
Result := 'Ext.menu.Item';
end;
procedure TExtMenuItem.InitDefaults;
begin
inherited;
FCanActivate := true;
FHref := '#';
FItemCls := 'x-menu-item';
FMenu := TExtMenuMenu.CreateInternal(Self, 'menu');
FShowDelay := 200;
FMenu_ := TExtMenuMenu.CreateInternal(Self, 'menu');
end;
function TExtMenuItem.SetIconClass(Cls: string): TExtFunction;
begin
JSCode(JSName + '.setIconClass(' + VarToJSON([Cls]) + ');', 'TExtMenuItem');
Result := Self;
end;
procedure TExtMenuCheckItem._SetChecked(const AValue: Boolean);
begin
FChecked := AValue;
ExtSession.ResponseItems.SetConfigItem(Self, 'checked', 'setChacked', [AValue]);
end;
procedure TExtMenuCheckItem.SetFGroup(Value: string);
begin
FGroup := Value;
JSCode('group:' + VarToJSON([Value]));
end;
procedure TExtMenuCheckItem.SetFGroupClass(Value: string);
begin
FGroupClass := Value;
JSCode('groupClass:' + VarToJSON([Value]));
end;
procedure TExtMenuCheckItem.SetFItemCls(Value: string);
begin
FItemCls := Value;
JSCode('itemCls:' + VarToJSON([Value]));
end;
procedure TExtMenuCheckItem.SetFOnBeforecheckchange
(Value: TExtMenuCheckItemOnBeforecheckchange);
begin
if Assigned(FOnBeforecheckchange) then
JSCode(JSName + '.events ["beforecheckchange"].listeners=[];');
if Assigned(Value) then
on('beforecheckchange', Ajax('beforecheckchange', ['This', '%0.nm', 'Checked',
'%1'], true));
FOnBeforecheckchange := Value;
end;
procedure TExtMenuCheckItem.SetFOnCheckchange(Value: TExtMenuCheckItemOnCheckchange);
begin
if Assigned(FOnCheckchange) then
JSCode(JSName + '.events ["checkchange"].listeners=[];');
if Assigned(Value) then
on('checkchange', Ajax('checkchange', ['This', '%0.nm', 'Checked', '%1'], true));
FOnCheckchange := Value;
end;
class function TExtMenuCheckItem.JSClassName: string;
begin
Result := 'Ext.menu.CheckItem';
end;
procedure TExtMenuCheckItem.InitDefaults;
begin
inherited;
FGroupClass := 'x-menu-group-item';
FItemCls := 'x-menu-item x-menu-check-item';
end;
function TExtMenuCheckItem.CheckHandler(This: TExtMenuCheckItem; Checked: Boolean)
: TExtFunction;
begin
JSCode(JSName + '.checkHandler(' + VarToJSON([This, false, Checked]) + ');',
'TExtMenuCheckItem');
Result := Self;
end;
function TExtMenuCheckItem.SetChecked(const AChecked: Boolean; const ASuppressEvent: Boolean): TExtFunction;
begin
FChecked := AChecked;
ExtSession.ResponseItems.CallMethod(Self, 'setChacked', [AChecked, ASuppressEvent]);
Result := Self;
end;
procedure TExtMenuCheckItem.HandleEvent(const AEvtName: string);
begin
inherited;
if (AEvtName = 'beforecheckchange') and Assigned(FOnBeforecheckchange) then
FOnBeforecheckchange(TExtMenuCheckItem(ParamAsObject('This')),
ParamAsBoolean('Checked'))
else if (AEvtName = 'checkchange') and Assigned(FOnCheckchange) then
FOnCheckchange(TExtMenuCheckItem(ParamAsObject('This')), ParamAsBoolean('Checked'));
end;
procedure TExtMenuMenu.SetFAllowOtherMenus(Value: Boolean);
begin
FAllowOtherMenus := Value;
JSCode('allowOtherMenus:' + VarToJSON([Value]));
end;
procedure TExtMenuMenu.SetFDefaultAlign(Value: string);
begin
FDefaultAlign := Value;
JSCode('defaultAlign:' + VarToJSON([Value]));
end;
procedure TExtMenuMenu.SetFDefaultOffsets(Value: TExtObjectList);
begin
FDefaultOffsets := Value;
JSCode('defaultOffsets:' + VarToJSON([Value, false]));
end;
procedure TExtMenuMenu.SetFDefaults(Value: TExtObject);
begin
FDefaults := Value;
JSCode('defaults:' + VarToJSON([Value, false]));
end;
procedure TExtMenuMenu.SetFEnableScrolling(Value: Boolean);
begin
FEnableScrolling := Value;
JSCode('enableScrolling:' + VarToJSON([Value]));
end;
procedure TExtMenuMenu.SetFFloating(Value: Boolean);
begin
FFloating := Value;
JSCode('floating:' + VarToJSON([Value]));
end;
procedure TExtMenuMenu.SetFIgnoreParentClicks(Value: Boolean);
begin
FIgnoreParentClicks := Value;
JSCode('ignoreParentClicks:' + VarToJSON([Value]));
end;
procedure TExtMenuMenu.SetFItems(Value: TExtObjectList);
begin
FItems := Value;
JSCode('items:' + VarToJSON([Value, false]));
end;
procedure TExtMenuMenu.SetFLayout(Value: string);
begin
FLayout := Value;
JSCode('layout:' + VarToJSON([Value]));
end;
procedure TExtMenuMenu.SetFLayoutObject(Value: TExtObject);
begin
FLayoutObject := Value;
JSCode('layout:' + VarToJSON([Value, false]));
end;
procedure TExtMenuMenu.SetFMaxHeight(Value: Integer);
begin
FMaxHeight := Value;
JSCode('maxHeight:' + VarToJSON([Value]));
end;
procedure TExtMenuMenu.SetFMinWidth(Value: Integer);
begin
FMinWidth := Value;
JSCode('minWidth:' + VarToJSON([Value]));
end;
procedure TExtMenuMenu.SetFPlain(Value: Boolean);
begin
FPlain := Value;
JSCode('plain:' + VarToJSON([Value]));
end;
procedure TExtMenuMenu.SetFScrollIncrement(Value: Integer);
begin
FScrollIncrement := Value;
JSCode('scrollIncrement:' + VarToJSON([Value]));
end;
procedure TExtMenuMenu.SetFShadow(Value: Boolean);
begin
FShadow := Value;
JSCode('shadow:' + VarToJSON([Value]));
end;
procedure TExtMenuMenu.SetFShadowString(Value: string);
begin
FShadowString := Value;
JSCode('shadow:' + VarToJSON([Value]));
end;
procedure TExtMenuMenu.SetFShowSeparator(Value: Boolean);
begin
FShowSeparator := Value;
JSCode('showSeparator:' + VarToJSON([Value]));
end;
procedure TExtMenuMenu.SetFSubMenuAlign(Value: string);
begin
FSubMenuAlign := Value;
JSCode('subMenuAlign:' + VarToJSON([Value]));
end;
procedure TExtMenuMenu.SetFZIndex(Value: Integer);
begin
FZIndex := Value;
JSCode('zIndex:' + VarToJSON([Value]));
end;
procedure TExtMenuMenu.SetFOnClick(Value: TExtMenuMenuOnClick);
begin
if Assigned(FOnClick) then
JSCode(JSName + '.events ["click"].listeners=[];');
if Assigned(Value) then
on('click', Ajax('click', ['This', '%0.nm', 'MenuItem', '%1.nm', 'E',
'%2.nm'], true));
FOnClick := Value;
end;
procedure TExtMenuMenu.SetFOnItemclick(Value: TExtMenuMenuOnItemclick);
begin
if Assigned(FOnItemclick) then
JSCode(JSName + '.events ["itemclick"].listeners=[];');
if Assigned(Value) then
on('itemclick', Ajax('itemclick', ['BaseItem', '%0.nm', 'E', '%1.nm'], true));
FOnItemclick := Value;
end;
procedure TExtMenuMenu.SetFOnMouseout(Value: TExtMenuMenuOnMouseout);
begin
if Assigned(FOnMouseout) then
JSCode(JSName + '.events ["mouseout"].listeners=[];');
if Assigned(Value) then
on('mouseout', Ajax('mouseout', ['This', '%0.nm', 'E', '%1.nm', 'MenuItem',
'%2.nm'], true));
FOnMouseout := Value;
end;
procedure TExtMenuMenu.SetFOnMouseover(Value: TExtMenuMenuOnMouseover);
begin
if Assigned(FOnMouseover) then
JSCode(JSName + '.events ["mouseover"].listeners=[];');
if Assigned(Value) then
on('mouseover', Ajax('mouseover', ['This', '%0.nm', 'E', '%1.nm', 'MenuItem',
'%2.nm'], true));
FOnMouseover := Value;
end;
class function TExtMenuMenu.JSClassName: string;
begin
Result := 'Ext.menu.Menu';
end;
procedure TExtMenuMenu.InitDefaults;
begin
inherited;
FDefaultAlign := 'tl-bl?';
FDefaultOffsets := TExtObjectList.CreateAsAttribute(Self, 'defaultOffsets');
FDefaults := TExtObject.CreateInternal(Self, 'defaults');
FEnableScrolling := true;
FItems := TExtObjectList.CreateAsAttribute(Self, 'items');
FLayoutObject := TExtObject.CreateInternal(Self, 'layout');
FMinWidth := 120;
FScrollIncrement := 24;
FShowSeparator := true;
FSubMenuAlign := 'tl-tr?';
end;
function TExtMenuMenu.AddElement(El: string): TExtFunction;
begin
JSCode(JSName + '.addElement(' + VarToJSON([El]) + ');', 'TExtMenuMenu');
Result := Self;
end;
function TExtMenuMenu.AddItem(Item: TExtMenuItem): TExtFunction;
begin
JSCode(JSName + '.addItem(' + VarToJSON([Item, false]) + ');', 'TExtMenuMenu');
Result := Self;
end;
function TExtMenuMenu.AddMenuItem(Config: TExtObject = nil): TExtFunction;
begin
JSCode(JSName + '.addMenuItem(' + VarToJSON([Config, false]) + ');', 'TExtMenuMenu');
Result := Self;
end;
function TExtMenuMenu.AddSeparator: TExtFunction;
begin
JSCode(JSName + '.addSeparator();', 'TExtMenuMenu');
Result := Self;
end;
function TExtMenuMenu.AddText(Text: string): TExtFunction;
begin
JSCode(JSName + '.addText(' + VarToJSON([Text]) + ');', 'TExtMenuMenu');
Result := Self;
end;
function TExtMenuMenu.Hide(Deep: Boolean = false): TExtFunction;
begin
JSCode(JSName + '.hide(' + VarToJSON([Deep]) + ');', 'TExtMenuMenu');
Result := Self;
end;
function TExtMenuMenu.Show(Element: string; Position: string = '';
ParentMenu: TExtMenuMenu = nil): TExtFunction;
begin
JSCode(JSName + '.show(' + VarToJSON([Element, Position, ParentMenu, false]) + ');',
'TExtMenuMenu');
Result := Self;
end;
function TExtMenuMenu.ShowAt(XyPosition: TExtObjectList; ParentMenu: TExtMenuMenu = nil)
: TExtFunction;
begin
JSCode(JSName + '.showAt(' + VarToJSON(XyPosition) + ',' + VarToJSON([ParentMenu, false]
) + ');', 'TExtMenuMenu');
Result := Self;
end;
procedure TExtMenuMenu.HandleEvent(const AEvtName: string);
begin
inherited;
if (AEvtName = 'click') and Assigned(FOnClick) then
FOnClick(TExtMenuMenu(ParamAsObject('This')), TExtMenuItem(ParamAsObject('MenuItem')),
ExtEventObject)
else if (AEvtName = 'itemclick') and Assigned(FOnItemclick) then
FOnItemclick(TExtMenuBaseItem(ParamAsObject('BaseItem')), ExtEventObject)
else if (AEvtName = 'mouseout') and Assigned(FOnMouseout) then
FOnMouseout(TExtMenuMenu(ParamAsObject('This')), ExtEventObject,
TExtMenuItem(ParamAsObject('MenuItem')))
else if (AEvtName = 'mouseover') and Assigned(FOnMouseover) then
FOnMouseover(TExtMenuMenu(ParamAsObject('This')), ExtEventObject,
TExtMenuItem(ParamAsObject('MenuItem')));
end;
procedure TExtMenuColorMenu.SetFHandler(Value: TExtFunction);
begin
FHandler := Value;
JSCode('handler:' + VarToJSON([Value, true]));
end;
procedure TExtMenuColorMenu.SetFHideOnClick(Value: Boolean);
begin
FHideOnClick := Value;
JSCode('hideOnClick:' + VarToJSON([Value]));
end;
procedure TExtMenuColorMenu.SetFPaletteId(Value: string);
begin
FPaletteId := Value;
JSCode('paletteId:' + VarToJSON([Value]));
end;
procedure TExtMenuColorMenu.SetFScope(Value: TExtObject);
begin
FScope := Value;
JSCode('scope:' + VarToJSON([Value, false]));
end;
procedure TExtMenuColorMenu.SetFPalette(Value: TExtColorPalette);
begin
FPalette := Value;
JSCode(JSName + '.palette=' + VarToJSON([Value, false]) + ';');
end;
procedure TExtMenuColorMenu.SetFOnSelect(Value: TExtMenuColorMenuOnSelect);
begin
if Assigned(FOnSelect) then
JSCode(JSName + '.events ["select"].listeners=[];');
if Assigned(Value) then
on('select', Ajax('select', ['Palette', '%0.nm', 'Color', '%1'], true));
FOnSelect := Value;
end;
class function TExtMenuColorMenu.JSClassName: string;
begin
Result := 'Ext.menu.ColorMenu';
end;
procedure TExtMenuColorMenu.InitDefaults;
begin
inherited;
FScope := TExtObject.CreateInternal(Self, 'scope');
FPalette := TExtColorPalette.CreateInternal(Self, 'palette');
end;
procedure TExtMenuColorMenu.HandleEvent(const AEvtName: string);
begin
inherited;
if (AEvtName = 'select') and Assigned(FOnSelect) then
FOnSelect(TExtColorPalette(ParamAsObject('Palette')), ParamAsString('Color'));
end;
procedure TExtMenuDateMenu.SetFHandler(Value: TExtFunction);
begin
FHandler := Value;
JSCode('handler:' + VarToJSON([Value, true]));
end;
procedure TExtMenuDateMenu.SetFHideOnClick(Value: Boolean);
begin
FHideOnClick := Value;
JSCode('hideOnClick:' + VarToJSON([Value]));
end;
procedure TExtMenuDateMenu.SetFPickerId(Value: string);
begin
FPickerId := Value;
JSCode('pickerId:' + VarToJSON([Value]));
end;
procedure TExtMenuDateMenu.SetFScope(Value: TExtObject);
begin
FScope := Value;
JSCode('scope:' + VarToJSON([Value, false]));
end;
procedure TExtMenuDateMenu.SetFPicker(Value: TExtDatePicker);
begin
FPicker := Value;
JSCode(JSName + '.picker=' + VarToJSON([Value, false]) + ';');
end;
procedure TExtMenuDateMenu.SetFOnSelect(Value: TExtMenuDateMenuOnSelect);
begin
if Assigned(FOnSelect) then
JSCode(JSName + '.events ["select"].listeners=[];');
if Assigned(Value) then
on('select', Ajax('select', ['Picker', '%0.nm', 'Date', '%1'], true));
FOnSelect := Value;
end;
class function TExtMenuDateMenu.JSClassName: string;
begin
Result := 'Ext.menu.DateMenu';
end;
procedure TExtMenuDateMenu.InitDefaults;
begin
inherited;
FScope := TExtObject.CreateInternal(Self, 'scope');
FPicker := TExtDatePicker.CreateInternal(Self, 'picker');
end;
procedure TExtMenuDateMenu.HandleEvent(const AEvtName: string);
begin
inherited;
if (AEvtName = 'select') and Assigned(FOnSelect) then
FOnSelect(TExtDatePicker(ParamAsObject('Picker')), ParamAsTDateTime('Date'));
end;
end.
|
namespace org.me.listviewapp;
interface
uses
java.util,
android.app,
android.os,
android.content,
android.view,
android.widget,
android.util;
type
ArrayAdapterWithSections<T> = class(ArrayAdapter<T>, SectionIndexer)
private
elements: array of String;
alphaIndex: TreeMap<String, Integer>;
sections: array of String;
javaSections: array of Object;
const Tag = 'ArrayAdapterWithSections';
public
constructor (ctx: Context; resource, textViewResourceId: Integer; objects: array of T);
method GetPositionForSection(section: Integer): Integer;
method GetSectionForPosition(position: Integer): Integer;
method GetSections: array of Object;
end;
implementation
constructor ArrayAdapterWithSections<T>(ctx: Context; resource, textViewResourceId: Integer; objects: array of T);
begin
inherited;
elements := new String[objects.length];
for i: Integer := 0 to objects.length - 1 do
elements[i] := objects[i].toString;
//Make a map holding location of 1st occurrence of each alphabet letter
alphaIndex := new TreeMap<String, Integer>();
//Start from the end and work backwards finding location of 1st item for each letter
for i: Integer := 0 to elements.length - 1 do
begin
var newKey := elements[i].substring(0, 1);
if not alphaIndex.containsKey(newKey) then
alphaIndex.put(newKey, i);
end;
sections := alphaIndex.keySet.toArray(new String[alphaIndex.keySet.size]);
//Now set up the Java Object sections that we need to return
javaSections := new Object[sections.length];
for i: Integer := 0 to sections.length - 1 do
javaSections[i] := sections[i];
end;
method ArrayAdapterWithSections<T>.GetPositionForSection(section: Integer): Integer;
begin
Result := -1;
if alphaIndex.containsKey(sections[section]) then
Result := alphaIndex[sections[section]];
end;
method ArrayAdapterWithSections<T>.GetSectionForPosition(position: Integer): Integer;
begin
exit 0 //Not called
end;
method ArrayAdapterWithSections<T>.GetSections: array of Object;
begin
exit javaSections
end;
end. |
object VAGetOptions: TVAGetOptions
Left = 270
Top = 122
BorderStyle = bsDialog
Caption = 'VAGetOptions'
ClientHeight = 317
ClientWidth = 385
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
Position = poMainFormCenter
PixelsPerInch = 96
TextHeight = 13
object cbOverlap: TCheckBoxV
Left = 9
Top = 17
Width = 161
Height = 17
Alignment = taLeftJustify
Caption = 'Accept overlap'
TabOrder = 0
UpdateVarOnToggle = False
end
object Bok: TButton
Left = 109
Top = 275
Width = 69
Height = 24
Caption = 'OK'
ModalResult = 1
TabOrder = 1
end
object Bcancel: TButton
Left = 196
Top = 275
Width = 69
Height = 24
Caption = 'Cancel'
ModalResult = 2
TabOrder = 2
end
object GroupBox1: TGroupBox
Left = 7
Top = 134
Width = 179
Height = 124
Caption = 'Margins (%)'
TabOrder = 3
object Label1: TLabel
Left = 19
Top = 23
Width = 18
Height = 13
Caption = 'Left'
end
object Label2: TLabel
Left = 19
Top = 44
Width = 25
Height = 13
Caption = 'Right'
end
object Label3: TLabel
Left = 19
Top = 68
Width = 19
Height = 13
Caption = 'Top'
end
object Label4: TLabel
Left = 19
Top = 92
Width = 33
Height = 13
Caption = 'Bottom'
end
object enLeft: TeditNum
Left = 90
Top = 17
Width = 73
Height = 21
TabOrder = 0
Tnum = G_byte
Max = 255.000000000000000000
UpdateVarOnExit = False
Decimal = 0
Dxu = 1.000000000000000000
end
object enRight: TeditNum
Left = 90
Top = 40
Width = 73
Height = 21
TabOrder = 1
Tnum = G_byte
Max = 255.000000000000000000
UpdateVarOnExit = False
Decimal = 0
Dxu = 1.000000000000000000
end
object enTop: TeditNum
Left = 90
Top = 63
Width = 73
Height = 21
TabOrder = 2
Tnum = G_byte
Max = 255.000000000000000000
UpdateVarOnExit = False
Decimal = 0
Dxu = 1.000000000000000000
end
object enBottom: TeditNum
Left = 90
Top = 87
Width = 73
Height = 21
TabOrder = 3
Tnum = G_byte
Max = 255.000000000000000000
UpdateVarOnExit = False
Decimal = 0
Dxu = 1.000000000000000000
end
end
object GroupBox2: TGroupBox
Left = 7
Top = 42
Width = 179
Height = 82
Caption = 'Waterfall'
TabOrder = 4
object enDx: TLabel
Left = 19
Top = 24
Width = 30
Height = 13
Caption = 'Dx (%)'
end
object Label8: TLabel
Left = 19
Top = 48
Width = 30
Height = 13
Caption = 'Dy (%)'
end
object enDeltaX: TeditNum
Left = 89
Top = 22
Width = 73
Height = 21
TabOrder = 0
Tnum = G_byte
Max = 255.000000000000000000
UpdateVarOnExit = False
Decimal = 0
Dxu = 1.000000000000000000
end
object enDeltaY: TeditNum
Left = 89
Top = 44
Width = 73
Height = 21
TabOrder = 1
Tnum = G_byte
Max = 255.000000000000000000
UpdateVarOnExit = False
Decimal = 0
Dxu = 1.000000000000000000
end
end
object GroupBox3: TGroupBox
Left = 194
Top = 7
Width = 182
Height = 168
Caption = 'Grid coordinates'
TabOrder = 5
object Label5: TLabel
Left = 19
Top = 23
Width = 19
Height = 13
Caption = 'Imin'
end
object Label6: TLabel
Left = 19
Top = 44
Width = 22
Height = 13
Caption = 'Imax'
end
object Label7: TLabel
Left = 19
Top = 68
Width = 21
Height = 13
Caption = 'Jmin'
end
object Label9: TLabel
Left = 19
Top = 92
Width = 24
Height = 13
Caption = 'Jmax'
end
object enIdispMin: TeditNum
Left = 75
Top = 17
Width = 91
Height = 21
TabOrder = 0
Tnum = G_byte
Max = 255.000000000000000000
UpdateVarOnExit = False
Decimal = 0
Dxu = 1.000000000000000000
end
object enIdispMax: TeditNum
Left = 75
Top = 40
Width = 91
Height = 21
TabOrder = 1
Tnum = G_byte
Max = 255.000000000000000000
UpdateVarOnExit = False
Decimal = 0
Dxu = 1.000000000000000000
end
object enJdispMin: TeditNum
Left = 75
Top = 63
Width = 91
Height = 21
TabOrder = 2
Tnum = G_byte
Max = 255.000000000000000000
UpdateVarOnExit = False
Decimal = 0
Dxu = 1.000000000000000000
end
object enJdispMax: TeditNum
Left = 75
Top = 87
Width = 91
Height = 21
TabOrder = 3
Tnum = G_byte
Max = 255.000000000000000000
UpdateVarOnExit = False
Decimal = 0
Dxu = 1.000000000000000000
end
object Button1: TButton
Left = 20
Top = 112
Width = 88
Height = 20
Caption = 'Autoscale I'
TabOrder = 4
OnClick = Button1Click
end
object Button2: TButton
Left = 20
Top = 136
Width = 88
Height = 20
Caption = 'Autoscale J'
TabOrder = 5
OnClick = Button2Click
end
end
object GroupBox4: TGroupBox
Left = 195
Top = 181
Width = 181
Height = 78
Caption = 'Intervals between objects'
TabOrder = 6
object Label10: TLabel
Left = 19
Top = 27
Width = 30
Height = 13
Caption = 'Dx (%)'
end
object Label11: TLabel
Left = 19
Top = 48
Width = 30
Height = 13
Caption = 'Dy (%)'
end
object enDxInt: TeditNum
Left = 90
Top = 21
Width = 73
Height = 21
TabOrder = 0
Tnum = G_byte
Max = 255.000000000000000000
UpdateVarOnExit = False
Decimal = 0
Dxu = 1.000000000000000000
end
object enDyInt: TeditNum
Left = 90
Top = 44
Width = 73
Height = 21
TabOrder = 1
Tnum = G_byte
Max = 255.000000000000000000
UpdateVarOnExit = False
Decimal = 0
Dxu = 1.000000000000000000
end
end
end
|
unit MeshSmoothVertexColours;
interface
uses MeshProcessingBase, Mesh, BasicMathsTypes, BasicDataTypes, NeighborDetector,
MeshColourCalculator, LOD;
{$INCLUDE source/Global_Conditionals.inc}
type
TMeshSmoothVertexColours = class (TMeshProcessingBase)
protected
procedure MeshSmoothOperation(var _Colours: TAVector4f; const _Vertices: TAVector3f; _NumVertices: integer; const _Faces: auint32; _NumFaces,_VerticesPerFace: integer; const _NeighborDetector: TNeighborDetector; const _VertexEquivalences: auint32; var _Calculator: TMeshColourCalculator);
procedure DoMeshProcessing(var _Mesh: TMesh); override;
public
DistanceFunction: TDistanceFunc;
constructor Create(var _LOD: TLOD); override;
end;
implementation
uses MeshPluginBase, GLConstants, NeighborhoodDataPlugin, MeshBRepGeometry,
DistanceFormulas;
constructor TMeshSmoothVertexColours.Create(var _LOD: TLOD);
begin
inherited Create(_LOD);
DistanceFunction := GetLinearDistance;
end;
procedure TMeshSmoothVertexColours.DoMeshProcessing(var _Mesh: TMesh);
var
Calculator : TMeshColourCalculator;
NeighborhoodPlugin: PMeshPluginBase;
NeighborDetector: TNeighborDetector;
VertexEquivalences: auint32;
NumVertices,MyNumFaces: integer;
MyFaces: auint32;
MyFaceColours: TAVector4f;
begin
Calculator := TMeshColourCalculator.Create;
NeighborhoodPlugin := _Mesh.GetPlugin(C_MPL_NEIGHBOOR);
_Mesh.Geometry.GoToFirstElement;
if NeighborhoodPlugin <> nil then
begin
if TNeighborhoodDataPlugin(NeighborhoodPlugin^).UseQuadFaces then
begin
NeighborDetector := TNeighborhoodDataPlugin(NeighborhoodPlugin^).QuadFaceNeighbors;
MyFaces := TNeighborhoodDataPlugin(NeighborhoodPlugin^).QuadFaces;
MyNumFaces := (High(MyFaces)+1) div (_Mesh.Geometry.Current^ as TMeshBRepGeometry).VerticesPerFace;
MyFaceColours := TNeighborhoodDataPlugin(NeighborhoodPlugin^).QuadFaceColours;
end
else
begin
NeighborDetector := TNeighborhoodDataPlugin(NeighborhoodPlugin^).FaceNeighbors;
_Mesh.Geometry.GoToFirstElement;
MyFaces := (_Mesh.Geometry.Current^ as TMeshBRepGeometry).Faces;
MyNumFaces := (_Mesh.Geometry.Current^ as TMeshBRepGeometry).NumFaces;
MyFaceColours := (_Mesh.Geometry.Current^ as TMeshBRepGeometry).Colours;
end;
VertexEquivalences := TNeighborhoodDataPlugin(NeighborhoodPlugin^).VertexEquivalences;
NumVertices := TNeighborhoodDataPlugin(NeighborhoodPlugin^).InitialVertexCount;
end
else
begin
NeighborDetector := TNeighborDetector.Create(C_NEIGHBTYPE_VERTEX_FACE);
NeighborDetector.BuildUpData(_Mesh.Geometry,High(_Mesh.Vertices)+1);
VertexEquivalences := nil;
NumVertices := High(_Mesh.Vertices)+1;
MyFaces := (_Mesh.Geometry.Current^ as TMeshBRepGeometry).Faces;
MyNumFaces := (_Mesh.Geometry.Current^ as TMeshBRepGeometry).NumFaces;
MyFaceColours := (_Mesh.Geometry.Current^ as TMeshBRepGeometry).Colours;
end;
MeshSmoothOperation(_Mesh.Colours,_Mesh.Vertices,NumVertices,MyFaces,MyNumFaces,(_Mesh.Geometry.Current^ as TMeshBRepGeometry).VerticesPerFace,NeighborDetector,VertexEquivalences,Calculator);
if NeighborhoodPlugin = nil then
begin
NeighborDetector.Free;
end;
Calculator.Free;
_Mesh.ForceRefresh;
end;
procedure TMeshSmoothVertexColours.MeshSmoothOperation(var _Colours: TAVector4f; const _Vertices: TAVector3f; _NumVertices: integer; const _Faces: auint32; _NumFaces,_VerticesPerFace: integer; const _NeighborDetector: TNeighborDetector; const _VertexEquivalences: auint32; var _Calculator: TMeshColourCalculator);
var
OriginalColours,FaceColours : TAVector4f;
begin
SetLength(OriginalColours,High(_Colours)+1);
SetLength(FaceColours,_NumFaces);
// Reset values.
BackupVector4f(_Colours,OriginalColours);
_Calculator.GetFaceColoursFromVertexes(OriginalColours,FaceColours,_Faces,_VerticesPerFace);
_Calculator.GetVertexColoursFromFaces(_Colours,FaceColours,_Vertices,_NumVertices,_Faces,_VerticesPerFace,_NeighborDetector,_VertexEquivalences,DistanceFunction);
FilterAndFixColours(_Colours);
// Free memory
SetLength(FaceColours,0);
SetLength(OriginalColours,0);
end;
end.
|
unit uGroupsRepository;
interface
uses
Generics.Defaults,
System.SysUtils,
Vcl.Graphics,
Vcl.Imaging.Jpeg,
Dmitry.Utils.System,
uConstants,
uMemory,
uDBEntities,
uDBContext,
uDBClasses;
type
TGroupsRepository = class(TBaseRepository<TGroup>, IGroupsRepository)
public
function Add(Group: TGroup): Boolean;
function Delete(Group: TGroup): Boolean;
function FindCodeByName(GroupName: string): string;
function FindNameByCode(GroupCode: string): string;
function GetByCode(GroupCode: string; LoadImage: Boolean): TGroup;
function GetByName(GroupName: string; LoadImage: Boolean): TGroup;
function Update(Group: TGroup): Boolean;
function GetAll(LoadImages: Boolean; SortByName: Boolean; UseInclude: Boolean = False): TGroups;
function HasGroupWithCode(GroupCode: string): Boolean;
function HasGroupWithName(GroupName: string): Boolean;
end;
implementation
{ TGroupsRepository }
function TGroupsRepository.Add(Group: TGroup): Boolean;
var
IC: TInsertCommand;
begin
Result := False;
if HasGroupWithName(Group.GroupName) or HasGroupWithCode(Group.GroupCode) then
Exit;
IC := Context.CreateInsert(GroupsTableName);
try
IC.AddParameter(TStringParameter.Create('GroupCode', Group.GroupCode));
IC.AddParameter(TStringParameter.Create('GroupName', Group.GroupName));
IC.AddParameter(TStringParameter.Create('GroupComment', Group.GroupComment));
IC.AddParameter(TStringParameter.Create('GroupKW', Group.GroupKeyWords));
IC.AddParameter(TBooleanParameter.Create('GroupAddKW', Group.AutoAddKeyWords));
IC.AddParameter(TDateTimeParameter.Create('GroupDate', IIF(Group.GroupDate = 0, Now, Group.GroupDate)));
IC.AddParameter(TStringParameter.Create('GroupFaces', Group.GroupFaces));
IC.AddParameter(TStringParameter.Create('RelatedGroups', Group.RelatedGroups));
IC.AddParameter(TBooleanParameter.Create('IncludeInQuickList', Group.IncludeInQuickList));
IC.AddParameter(TIntegerParameter.Create('GroupAccess', Group.GroupAccess));
if (Group.GroupImage <> nil) and not Group.GroupImage.Empty then
IC.AddParameter(TJpegParameter.Create('GroupImage', Group.GroupImage));
Result := IC.Execute > 0;
finally
F(IC);
end;
end;
function TGroupsRepository.Delete(Group: TGroup): Boolean;
var
DC: TDeleteCommand;
begin
DC := Context.CreateDelete(GroupsTableName);
try
DC.AddWhereParameter(TStringParameter.Create('GroupCode', Group.GroupCode, paLike));
DC.Execute;
Result := True;
finally
F(DC);
end;
end;
function TGroupsRepository.FindNameByCode(GroupCode: string): string;
var
SC: TSelectCommand;
begin
Result := '';
SC := Context.CreateSelect(GroupsTableName);
try
SC.AddParameter(TStringParameter.Create('GroupName'));
SC.AddWhereParameter(TStringParameter.Create('GroupCode', GroupCode));
if SC.Execute > 0 then
Result := SC.DS.FieldByName('GroupName').AsString;
finally
F(SC);
end;
end;
function TGroupsRepository.FindCodeByName(GroupName: string): string;
var
SC: TSelectCommand;
begin
Result := '';
SC := Context.CreateSelect(GroupsTableName);
try
SC.AddParameter(TStringParameter.Create('GroupCode'));
SC.AddWhereParameter(TStringParameter.Create('GroupName', GroupName, paLike));
if SC.Execute > 0 then
Result := SC.DS.FieldByName('GroupCode').AsString;
finally
F(SC);
end;
end;
function TGroupsRepository.GetAll(LoadImages, SortByName, UseInclude: Boolean): TGroups;
var
SC: TSelectCommand;
Group: TGroup;
begin
Result := TGroups.Create;
SC := Context.CreateSelect(GroupsTableName);
try
SC.AddParameter(TAllParameter.Create);
SC.AddWhereParameter(TCustomConditionParameter.Create('1 = 1'));
if UseInclude then
SC.AddWhereParameter(TBooleanParameter.Create('IncludeInQuickList', True));
if SC.Execute > 0 then
begin
SC.DS.First;
repeat
Group := TGroup.Create;
Group.ReadFromDS(SC.DS);
Result.Add(Group);
SC.DS.Next;
until SC.DS.Eof;
end;
finally
F(SC);
end;
if SortByName then
Result.Sort(TComparer<TGroup>.Construct(
function (const L, R: TGroup): Integer
begin
Result := AnsiCompareStr(L.GroupName, R.GroupName);
end
));
end;
function TGroupsRepository.GetByCode(GroupCode: string; LoadImage: Boolean): TGroup;
var
SC: TSelectCommand;
begin
Result := nil;
SC := Context.CreateSelect(GroupsTableName);
try
SC.AddParameter(TStringParameter.Create('ID'));
SC.AddParameter(TStringParameter.Create('GroupCode'));
SC.AddParameter(TStringParameter.Create('GroupName'));
SC.AddParameter(TDateTimeParameter.Create('GroupDate'));
SC.AddParameter(TStringParameter.Create('GroupComment'));
SC.AddParameter(TIntegerParameter.Create('GroupAccess'));
SC.AddParameter(TStringParameter.Create('GroupFaces'));
SC.AddParameter(TStringParameter.Create('GroupKW'));
SC.AddParameter(TBooleanParameter.Create('GroupAddKW', False));
SC.AddParameter(TStringParameter.Create('RelatedGroups'));
SC.AddParameter(TBooleanParameter.Create('IncludeInQuickList', False));
if LoadImage then
SC.AddParameter(TCustomFieldParameter.Create('[GroupImage]'));
SC.AddWhereParameter(TStringParameter.Create('GroupCode', GroupCode, paLike));
if SC.Execute > 0 then
begin
Result := TGroup.Create;
Result.ReadFromDS(SC.DS);
end;
finally
F(SC);
end;
end;
function TGroupsRepository.GetByName(GroupName: string; LoadImage: Boolean): TGroup;
var
SC: TSelectCommand;
begin
Result := nil;
SC := Context.CreateSelect(GroupsTableName);
try
SC.AddParameter(TStringParameter.Create('ID'));
SC.AddParameter(TStringParameter.Create('GroupCode'));
SC.AddParameter(TStringParameter.Create('GroupName'));
SC.AddParameter(TDateTimeParameter.Create('GroupDate'));
SC.AddParameter(TStringParameter.Create('GroupComment'));
SC.AddParameter(TIntegerParameter.Create('GroupAccess'));
SC.AddParameter(TStringParameter.Create('GroupFaces'));
SC.AddParameter(TStringParameter.Create('GroupKW'));
SC.AddParameter(TBooleanParameter.Create('GroupAddKW', False));
SC.AddParameter(TStringParameter.Create('RelatedGroups'));
SC.AddParameter(TBooleanParameter.Create('IncludeInQuickList', False));
if LoadImage then
SC.AddParameter(TCustomFieldParameter.Create('[GroupImage]'));
SC.AddWhereParameter(TStringParameter.Create('GroupName', GroupName, paLike));
if SC.Execute > 0 then
begin
Result := TGroup.Create;
Result.ReadFromDS(SC.DS);
end;
finally
F(SC);
end;
end;
function TGroupsRepository.HasGroupWithCode(GroupCode: string): Boolean;
var
SC: TSelectCommand;
begin
SC := Context.CreateSelect(GroupsTableName);
try
SC.AddParameter(TCustomFieldParameter.Create('1'));
SC.AddWhereParameter(TStringParameter.Create('GroupCode', GroupCode));
Result := SC.Execute > 0;
finally
F(SC);
end;
end;
function TGroupsRepository.HasGroupWithName(GroupName: string): Boolean;
var
SC: TSelectCommand;
begin
SC := Context.CreateSelect(GroupsTableName);
try
SC.AddParameter(TCustomFieldParameter.Create('1'));
SC.AddWhereParameter(TStringParameter.Create('GroupName', GroupName, paLike));
Result := SC.Execute > 0;
finally
F(SC);
end;
end;
function TGroupsRepository.Update(Group: TGroup): Boolean;
var
SC: TSelectCommand;
UC: TUpdateCommand;
GroupDate: TDateTime;
begin
Result := False;
SC := Context.CreateSelect(GroupsTableName);
try
SC.AddParameter(TCustomFieldParameter.Create('[ID]'));
SC.AddWhereParameter(TStringParameter.Create('GroupCode', Group.GroupCode));
try
SC.Execute;
except
Exit;
end;
if SC.RecordCount > 0 then
begin
UC := Context.CreateUpdate(GroupsTableName);
try
UC.AddParameter(TStringParameter.Create('GroupName', Group.GroupName));
UC.AddParameter(TIntegerParameter.Create('GroupAccess', Group.GroupAccess));
if Group.GroupImage <> nil then
UC.AddParameter(TJpegParameter.Create('GroupImage', Group.GroupImage));
UC.AddParameter(TStringParameter.Create('GroupComment', Group.GroupComment));
UC.AddParameter(TStringParameter.Create('GroupFaces', Group.GroupFaces));
if Group.GroupDate = 0 then
GroupDate := Now
else
GroupDate := Group.GroupDate;
UC.AddParameter(TDateTimeParameter.Create('GroupDate', GroupDate));
UC.AddParameter(TBooleanParameter.Create('GroupAddKW', Group.AutoAddKeyWords));
UC.AddParameter(TStringParameter.Create('GroupKW', Group.GroupKeyWords));
UC.AddParameter(TStringParameter.Create('RelatedGroups', Group.RelatedGroups));
UC.AddParameter(TBooleanParameter.Create('IncludeInQuickList', Group.IncludeInQuickList));
UC.AddWhereParameter(TIntegerParameter.Create('ID', SC.DS.FindField('ID').AsInteger));
UC.Execute;
Result := True;
finally
F(UC);
end;
end;
finally
F(SC);
end;
end;
end.
|
unit htComponent;
interface
uses
Classes,
htInterfaces, htMarkup;
type
ThtComponent = class(TComponent, IhtComponent, IhtGenerator)
private
FPriority: Integer;
protected
function GetPriority: Integer;
procedure SetPriority(const Value: Integer);
public
procedure Generate(inMarkup: ThtMarkup); virtual;
published
property Priority: Integer read GetPriority write SetPriority;
end;
implementation
{ ThtComponent }
function ThtComponent.GetPriority: Integer;
begin
Result := FPriority;
end;
procedure ThtComponent.SetPriority(const Value: Integer);
begin
FPriority := Value;
end;
procedure ThtComponent.Generate(inMarkup: ThtMarkup);
begin
//
end;
end.
|
program polynomials (input, output);
const
VName = 'x';
type
OperationType = (opAdd, opSub);
StringType = string;
TermPtr = ^Term;
Term = record
Next : TermPtr;
Degree,
Coefficient : integer;
end;
Polynomial = record
PolyName : StringType;
First : TermPtr;
end;
var
P, Q : Polynomial;
procedure UpCaseChr(var c : char);
begin
if c in ['a'..'z']
then c := chr( ord(c)-ord('a')+ord('A') );
end;
procedure UpCase(var s : StringType);
var
i : integer;
begin
for i := 1 to length(s) do
if s[i] in ['a'..'z']
then s[i] := chr( ord(s[i])-ord('a')+ord('A') );
end;
function YesOrNo(s : StringType) : boolean;
var
ch : char;
begin
writeln;
repeat
write(s, '(Y/N)');
readln(ch);
UpCaseChr(ch);
until ch in ['Y', 'N'];
YesOrNo := (ch = 'Y');
end;
function TermInit (aDegree, aCoefficient : integer) : TermPtr;
var
theTerm : TermPtr;
begin
new(theTerm);
with theTerm^ do begin
Next := NIL;
Degree := aDegree;
Coefficient := aCoefficient;
end;
TermInit := theTerm;
end;
procedure PolyInit(aName : StringType; var aPoly : Polynomial);
begin
with aPoly do begin
First := NIL;
PolyName := aName;
end;
end;
function PolyGetFirst(aPoly : Polynomial) : TermPtr;
begin
PolyGetFirst := aPoly.First;
end;
procedure PolySetFirst(aTerm : TermPtr; var aPoly : Polynomial);
begin
aPoly.First := aTerm;
end;
function PolyIsEmpty(aPoly : Polynomial) : boolean;
begin
PolyIsEmpty := (PolyGetFirst(aPoly) = NIL);
end;
procedure PolyPrint(aPoly : Polynomial);
var
tmpTerm : TermPtr;
firstPlus : boolean;
begin
write(aPoly.PolyName, '(', VName, ') =');
if PolyIsEmpty(aPoly)
then writeln(' 0')
else begin
firstPlus := TRUE;
tmpTerm := PolyGetFirst(aPoly);
while tmpTerm <> NIL do begin
if tmpTerm^.Coefficient < 0
then write(' - ')
else if not firstPlus
then write(' + ')
else write(' ');
if (abs(tmpTerm^.Coefficient) <> 1) or (tmpTerm^.Degree = 0)
then write(abs(tmpTerm^.Coefficient):1);
if tmpTerm^.Degree > 0
then begin
write(VName);
if tmpTerm^.Degree > 1
then write('^',tmpTerm^.Degree:1);
end;
tmpTerm := tmpTerm^.Next;
firstPlus := FALSE;
end;
writeln;
end;
end;
procedure PolyInsert(aTerm : TermPtr; var aPoly : Polynomial);
var
tmpTerm : TermPtr;
begin
if aTerm <> NIL
then begin
if PolyIsEmpty(aPoly)
then PolySetFirst(aTerm, aPoly)
else begin
tmpTerm := PolyGetFirst(aPoly);
if (tmpTerm^.Degree > aTerm^.Degree)
then begin
aTerm^.Next := tmpTerm;
PolySetFirst(aTerm, aPoly);
end
else begin
while (tmpTerm^.Next <> NIL) and
(tmpTerm^.Next^.Degree < aTerm^.Degree) do
tmpTerm := tmpTerm^.Next;
aTerm^.Next := tmpTerm^.Next;
tmpTerm^.Next := aTerm;
end;
end;
end;
end;
procedure PolyDelete(aTerm : TermPtr; var aPoly : Polynomial);
var
tmpTerm : TermPtr;
begin
if aTerm <> NIL
then begin
tmpTerm := PolyGetFirst(aPoly);
if (tmpTerm = aTerm)
then PolySetFirst(tmpTerm^.Next, aPoly)
else begin
while (tmpTerm <> NIL) and (tmpTerm^.Next <> aTerm) do
tmpTerm := tmpTerm^.Next;
if tmpTerm <> NIL
then tmpTerm^.Next := tmpTerm^.Next^.Next;
end;
aTerm^.Next := NIL;
end;
end;
function PolyFind(aDegree : integer; aPoly : Polynomial) : TermPtr;
var
tmpTerm : TermPtr;
begin
tmpTerm := PolyGetFirst(aPoly);
while (tmpTerm <> NIL) and (tmpTerm^.Degree < aDegree) do
tmpTerm := tmpTerm^.Next;
if (tmpTerm <> NIL) and (tmpTerm^.Degree <> aDegree)
then tmpTerm := NIL;
PolyFind := tmpTerm;
end;
procedure PolyDone(var aPoly : Polynomial);
var
tmpTerm1, tmpTerm2 : TermPtr;
begin
tmpTerm1 := PolyGetFirst(aPoly);
while (tmpTerm1 <> NIL) do begin
tmpTerm2 := tmpTerm1;
tmpTerm1 := tmpTerm1^.Next;
dispose(tmpTerm2);
end;
end;
procedure PolynomialsInit;
begin
writeln;
writeln;
writeln('***************** W E L C O M E **********************');
writeln;
writeln(' Welcome to "Polynomials" program!');
writeln;
writeln;
PolyInit('P', P);
PolyInit('Q', Q);
end;
procedure EnterPolynomial(var aPoly : Polynomial);
const
endChar = '#';
helpChar = '?';
var
s : StringType;
quit : boolean;
procedure ReadTerm(s : StringType;var aP : Polynomial);
var
Degr, Coef : integer;
tmpTerm : TermPtr;
function ParseTerm(s : StringType; var d, c : integer) : boolean;
var
ss : StringType;
ps : integer;
begin
ParseTerm := FALSE;
ps := Index(s, ',');
if ps <> 0
then begin
ss := substr(s, 1, ps-1);
readv(ss, d, Error := CONTINUE);
if statusv = 0
then begin
ss := substr(s, ps+1, length(s)-ps);
readv(ss, c, Error := CONTINUE);
if statusv = 0
then ParseTerm := TRUE;
end;
end;
end;
begin
if not ParseTerm(s, Degr, Coef)
then writeln('Illegal input. Try again.')
else if Degr < 0
then writeln('the degree has to be not less than zero.')
else begin
tmpTerm := PolyFind(Degr, aP);
if tmpTerm <> NIL
then begin
if Coef = 0
then begin
writeln('The term ',
tmpTerm^.Coefficient:1, VName,
'^', tmpTerm^.Degree:1,
' wil be erased.');
if YesOrNo('Are you sure?')
then PolyDelete(tmpTerm, aP);
end
else begin
writeln('The term ',
tmpTerm^.Coefficient:1, VName,
'^', tmpTerm^.Degree:1,
' wil be replaced by ',
Coef:1, VName, '^', Degr:1, '.');
if YesOrNo('Are you sure?')
then begin
tmpTerm^.Degree := Degr;
tmpTerm^.Coefficient := Coef;
end;
end;
end
else begin
if Coef = 0
then
writeln('the coefficient cann''t be equal to zero.')
else begin
tmpTerm := TermInit(Degr, Coef);
PolyInsert(tmpTerm, aP);
end;
end;
end;
end;
procedure Help;
begin
writeln;
writeln('Input the pair "degree, coefficient"');
writeln(' or');
writeln('"#" at the end of polynomial');
writeln;
end;
begin
writeln;
writeln('Input polynomial:');
quit := FALSE;
repeat
write('(type ', helpChar, ' for help)>>');
readln(s);
if length(s) <> 0
then begin
case s[1] of
endChar :
quit := TRUE;
helpChar :
Help;
otherwise
ReadTerm(s, aPoly);
end;
end;
until quit;
PolyPrint(aPoly);
end;
procedure PerformOperation(var aP, aQ : Polynomial; op : OperationType);
var
QTerm, PTerm : TermPtr;
begin
while not PolyIsEmpty(aQ) do begin
QTerm := PolyGetFirst(aQ);
PolyDelete(QTerm, aQ);
if op = opSub
then QTerm^.Coefficient := -QTerm^.Coefficient;
PTerm := PolyFind(QTerm^.Degree, aP);
if PTerm <> NIL
then begin
PolyDelete(PTerm, aP);
PTerm^.Coefficient := PTerm^.Coefficient+QTerm^.Coefficient;
dispose(QTerm);
if PTerm^.Coefficient <> 0
then PolyInsert(PTerm, aP)
else dispose(PTerm);
end
else PolyInsert(QTerm, aP);
end;
writeln;
writeln('The result is');
PolyPrint(aP);
end;
function GetOperation(aP, aQ : Polynomial) : OperationType;
const
addChar = '+';
subChar = '-';
var
ch : char;
begin
repeat
writeln;
writeln('Which operation you want to compute?');
writeln(' ', addChar, ' : ', aP.PolyName, '(', VName, ') = ',
aP.PolyName, '(', VName, ') + ', aQ.PolyName, '(', VName, ')');
writeln(' ', subChar, ' : ', aP.PolyName, '(', VName, ') = ',
aP.PolyName, '(', VName, ') - ', aQ.PolyName, '(', VName, ')');
write('>>');
readln(ch);
until ch in [subChar, addChar];
case ch of
subChar : GetOperation := opSub;
addChar : GetOperation := opAdd;
end;
end;
procedure PolynomialsRun;
begin
EnterPolynomial(P);
repeat
EnterPolynomial(Q);
PerformOperation(P, Q, GetOperation(P, Q));
until not YesOrNo('Another polynomial?');
end;
procedure PolynomialsDone;
begin
writeln('Good bye...');
PolyDone(P);
PolyDone(Q);
end;
begin { Polynomials program body }
PolynomialsInit;
PolynomialsRun;
PolynomialsDone;
end. { Polynomials program }
|
unit MouseRNG;
// Description: MouseRNG Component
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Classes, Controls, Dialogs,
extctrls, Forms, Graphics, Messages, SysUtils, Windows;
const
// The distance the cursor has to be moved in either the X or Y direction
// before the new mouse co-ordinates are taken as another "sample"
// DANGER - If this is set too high, then as the mouse moves, samples will
// be the mouse cursor co-ordinates may end up only incrementing my
// "MIN_DIFF" each time a sample is taken
// DANGER - If this is set to 1, then with some mice, the mouse pointer moves
// "on it's own" when left alone, and the mouse pointer may
// oscillate between two adjacent pixels
// Set this value to 2 to reduce the risk of this happening
MIN_DIFF = 2;
// This specifies how many of the least significant bits from the X & Y
// co-ordinates will be used as random data.
// If this is set too high, then
// If this is set too low, then the user has to move the mouse a greater
// distance between samples, otherwise the higher bits in the sample won't
// change.
// A setting of 1 will use the LSB of the mouse's X, Y co-ordinates
BITS_PER_SAMPLE = 1;
// This specifies the time interval (in ms) between taking samples of the
// mouse's position
TIMER_INTERVAL = 100;
// The different border styles available
BorderStyles: array [TBorderStyle] of DWORD = (0, WS_BORDER);
type
// Callback for random data generated
TDEBUGSampleTakenEvent = procedure(Sender: TObject; X, Y: Integer) of object;
TBitGeneratedEvent = procedure(Sender: TObject; random: Byte) of object;
TByteGeneratedEvent = procedure(Sender: TObject; random: Byte) of object;
// This is used to form the linked list of points for displayed lines
PPointList = ^TPointList;
TPointList = packed record
Point: TPoint;
Prev: PPointList;
Next: PPointList;
end;
TMouseRNG = class (TCustomControl)
private
// This stores the random data as it is generated
RandomByte: Byte;
// This stores the number of random bits in RandomByte
RandomByteBits: Integer;
// Storage for when the mouse move event is triggered
LastMouseX: Integer;
LastMouseY: Integer;
// The linked list of points on the canvas
PointCount: Cardinal;
LinesListHead: PPointList;
LinesListTail: PPointList;
// Style information
FBorderStyle: TBorderStyle;
FTrailLines: Cardinal;
FLineWidth: Cardinal;
FLineColor: TColor;
// Callbacks
FOnDEBUGSampleTaken: TDEBUGSampleTakenEvent;
FOnBitGenerated: TBitGeneratedEvent;
FOnByteGenerated: TByteGeneratedEvent;
protected
procedure CreateParams(var Params: TCreateParams); override;
procedure TimerFired(Sender: TObject);
procedure SetEnabled(Value: Boolean); override;
procedure SetBorderStyle(Style: TBorderStyle);
procedure SetLineWidth(Width: Cardinal);
procedure SetLineColor(color: TColor);
// Linked list of points on the canvas handling
procedure StoreNewPoint(X, Y: Integer);
procedure RemoveLastPoint();
// When new mouse cursor co-ordinates are taken
procedure ProcessSample(X, Y: Integer);
public
Timer: TTimer;
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure Repaint(); override;
procedure Paint(); override;
function CanResize(var NewWidth, NewHeight: Integer): Boolean; override;
// Clear display and internal RNG state
procedure Clear();
// Clear display only
procedure ClearDisplay();
published
// The number of lines shown
// Set to 0 to prevent lines from being displayed
property TrailLines: Cardinal Read FTrailLines Write FTrailLines;
property LineWidth: Cardinal Read FLineWidth Write SetLineWidth;
property LineColor: TColor Read FLineColor Write SetLineColor;
property Align;
property Anchors;
property BorderStyle: TBorderStyle Read FBorderStyle Write SetBorderStyle default bsSingle;
// N/A property Caption;
property Color;
property Constraints;
property Ctl3D;
property UseDockManager default True;
property DockSite;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property ParentColor;
property ParentCtl3D;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property Visible;
property OnCanResize;
property OnClick;
property OnConstrainedResize;
property OnContextPopup;
property OnDockDrop;
property OnDockOver;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnGetSiteInfo;
property OnMouseDown;
property OnMouseUp;
property OnResize;
property OnStartDock;
property OnStartDrag;
property OnUnDock;
property OnDEBUGSampleTakenEvent: TDEBUGSampleTakenEvent
Read FOnDEBUGSampleTaken Write FOnDEBUGSampleTaken;
// Note: You can receive callbacks when each bit is generated, or when
// every 8 bits. Note that the random data supplied by
// FOnByteGenerated is the same as the supplied by FOnBitGenerated,
// it's only buffered and delivered in blocks of 8 bits
property OnBitGenerated: TBitGeneratedEvent Read FOnBitGenerated Write FOnBitGenerated;
property OnByteGenerated: TByteGeneratedEvent Read FOnByteGenerated Write FOnByteGenerated;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('SDeanSecurity', [TMouseRNG]);
end;
constructor TMouseRNG.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Color := clWindow;
TabStop := False;
ParentColor := False;
BorderStyle := bsSingle;
TrailLines := 5;
LineWidth := 5;
LineColor := clNavy;
Timer := TTimer.Create(self);
Timer.Enabled := False;
Timer.Interval := TIMER_INTERVAL;
Timer.OnTimer := TimerFired;
LinesListHead := nil;
LinesListTail := nil;
PointCount := 0;
// Initially, there are no mouse co-ordinates taken
LastMouseX := -1;
LastMouseY := -1;
// Cleardown the random bytes store
RandomByte := 0;
RandomByteBits := 0;
// Setup the inital size of the component
// 128 is chosen for this, as it's likely that the BITS_PER_SAMPLE rules
// will suit it, even for large values of BITS_PER_SAMPLE (like 4 or 5)
SetBounds(Left, Top, 128, 128);
Enabled := False;
end;
destructor TMouseRNG.Destroy();
begin
Timer.Enabled := False;
Timer.Free();
Enabled := False;
// Cleardown any points, overwriting them as we do so
while (PointCount > 0) do begin
RemoveLastPoint();
end;
inherited Destroy();
end;
procedure TMouseRNG.TimerFired(Sender: TObject);
var
changed: Boolean;
begin
changed := False;
// Handle the situation in which no mouse co-ordinates have yet been taken
if (LastMouseX > -1) and (LastMouseY > -1) then begin
// If there are no points, we have a new one
if (PointCount = 0) then begin
changed := True;
end else begin
// If the mouse cursor has moved a significant difference, use the new
// co-ordinates
// Both the X *and* Y mouse co-ordinates must have changed, to prevent
// the user from generating non-random data by simply moving the mouse in
// just a horizontal (or vertical) motion, in which case the X (or Y)
// position would change, but the Y (or X) position would remain
// relativly the same. This would only generate 1/2 as much random data
// The effects of the following code are trivial to see; simply waggle
// the mouse back and forth horizontally; instead of seeing a new dark
// line appearing (indicating that the sample has been taken), the
// inverse coloured line appears, indicating the mouse pointer
if ((LastMouseX > (LinesListHead.Point.X + MIN_DIFF)) or
(LastMouseX < (LinesListHead.Point.X - MIN_DIFF)) and (LastMouseY >
(LinesListHead.Point.Y + MIN_DIFF)) or (LastMouseY < (LinesListHead.Point.Y - MIN_DIFF)))
then begin
changed := True;
end;
end;
end;
if (not (changed)) then begin
// User hasn't moved cursor - delete oldest line until we catch up with
// the cursor
if ((LinesListTail <> LinesListHead) and (LinesListTail <> nil)) then begin
Canvas.Pen.Mode := pmMergeNotPen;
Canvas.MoveTo(LinesListTail.Point.X, LinesListTail.Point.Y);
Canvas.LineTo(LinesListTail.Next.Point.X, LinesListTail.Next.Point.Y);
RemoveLastPoint();
end;
end else begin
// AT THIS POINT, WE USE LastMouseX AND LastMouseY AS THE CO-ORDS TO USE
// Store the position
StoreNewPoint(LastMouseX, LastMouseY);
// User moved cursor - don't delete any more lines unless the max number
// of lines which may be displayed is exceeded
if ((PointCount + 1 > TrailLines) and (PointCount > 1)) then begin
Canvas.Pen.Mode := pmMergeNotPen;
Canvas.MoveTo(LinesListTail.Point.X, LinesListTail.Point.Y);
Canvas.LineTo(LinesListTail.Next.Point.X, LinesListTail.Next.Point.Y);
RemoveLastPoint();
end;
// Draw newest line
if (TrailLines > 0) and (PointCount > 1) then begin
Canvas.Pen.Mode := pmCopy;
Canvas.MoveTo(LinesListHead.Prev.Point.X, LinesListHead.Prev.Point.Y);
Canvas.LineTo(LinesListHead.Point.X, LinesListHead.Point.Y);
end;
ProcessSample(LastMouseX, LastMouseY);
end;
end;
procedure TMouseRNG.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
inherited MouseMove(Shift, X, Y);
if (TrailLines > 0) and (PointCount >= 1) then begin
Canvas.Pen.Mode := pmXor;
Canvas.MoveTo(LinesListHead.Point.X, LinesListHead.Point.Y);
Canvas.LineTo(LastMouseX, LastMouseY);
end;
LastMouseX := X;
LastMouseY := Y;
if (TrailLines > 0) and (PointCount >= 1) then begin
Canvas.Pen.Mode := pmXor;
Canvas.MoveTo(LinesListHead.Point.X, LinesListHead.Point.Y);
Canvas.LineTo(LastMouseX, LastMouseY);
end;
end;
procedure TMouseRNG.SetEnabled(Value: Boolean);
var
oldEnabled: Boolean;
begin
oldEnabled := Enabled;
inherited SetEnabled(Value);
Timer.Enabled := Value;
// Only clear the display on an enabled->disabled, or disabled->enabled
// change.
// (i.e. If this is called with TRUE, when it's already enabled, do not
// clear the display)
if (oldEnabled <> Value) then begin
ClearDisplay();
end;
end;
procedure TMouseRNG.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
if (FBorderStyle = bsSingle) then begin
Params.Style := Params.Style or WS_BORDER;
end else begin
Params.Style := Params.Style and not (WS_BORDER);
end;
end;
procedure TMouseRNG.SetBorderStyle(Style: TBorderStyle);
begin
if (Style <> FBorderStyle) then begin
FBorderStyle := Style;
{ Create new window handle for the control. }
RecreateWnd;
end;
end;
procedure TMouseRNG.Clear();
begin
ClearDisplay();
// Clear internal RNG state
RandomByte := 0;
RandomByteBits := 0;
end;
procedure TMouseRNG.ClearDisplay();
begin
// Clear any lines on the display
// We surround the Canvas blanking with "parent<>nil" to avoid getting
// "Control '' has no parent window" errors when the component is dropped
// onto a form
if (parent <> nil) then begin
Canvas.Brush.Color := Color;
Canvas.FillRect(Rect(0, 0, Width, Height));
end;
// Because the display's been cleared, the chase position can be set to the
// current position
// Delete all lines
if (LinesListHead <> nil) then begin
while (LinesListTail <> LinesListHead) do begin
RemoveLastPoint();
end;
end;
end;
// Repaint? No, we just clear the display
// This is done so that if the user switches task, then switches back again
// all trails are gone
procedure TMouseRNG.Repaint();
begin
inherited Repaint();
ClearDisplay();
end;
// Paint? No, same as Repaint()
procedure TMouseRNG.Paint();
begin
inherited Paint();
ClearDisplay();
end;
// Remove the last point from the tail of the linked list of points
procedure TMouseRNG.RemoveLastPoint();
var
tmpPoint: PPointList;
begin
if (LinesListTail <> nil) then begin
tmpPoint := LinesListTail;
LinesListTail := LinesListTail.Next;
if (LinesListTail <> nil) then begin
LinesListTail.Prev := nil;
end;
// Overwrite position before discarding record
tmpPoint.Point.X := 0;
tmpPoint.Point.Y := 0;
Dispose(tmpPoint);
Dec(PointCount);
end;
if (LinesListTail = nil) then begin
LinesListHead := nil;
end;
end;
// Add a new last point onto the head of the linked list of points
procedure TMouseRNG.StoreNewPoint(X, Y: Integer);
var
tmpPoint: PPointList;
begin
tmpPoint := new(PPointList);
tmpPoint.Point.X := X;
tmpPoint.Point.Y := Y;
tmpPoint.Next := nil;
tmpPoint.Prev := LinesListHead;
if (LinesListHead <> nil) then begin
LinesListHead.Next := tmpPoint;
end;
LinesListHead := tmpPoint;
Inc(PointCount);
if (LinesListTail = nil) then begin
LinesListTail := LinesListHead;
end;
end;
procedure TMouseRNG.ProcessSample(X, Y: Integer);
var
i: Integer;
begin
if ((Enabled) and (Assigned(FOnDEBUGSampleTaken))) then
FOnDEBUGSampleTaken(self, X, Y);
// This stores the random data as it is generated
for i := 1 to BITS_PER_SAMPLE do begin
RandomByte := RandomByte shl 1;
RandomByte := RandomByte + (X and 1);
Inc(RandomByteBits);
if ((Enabled) and (Assigned(FOnBitGenerated))) then begin
FOnBitGenerated(self, X and $01);
end;
RandomByte := RandomByte shl 1;
RandomByte := RandomByte + (Y and 1);
Inc(RandomByteBits);
if ((Enabled) and (Assigned(FOnBitGenerated))) then
FOnBitGenerated(self, Y and $01);
X := X shr 1;
Y := Y shr 1;
end;
if (RandomByteBits >= 8) then begin
if ((Enabled) and (Assigned(FOnByteGenerated))) then
FOnByteGenerated(self, RandomByte);
RandomByteBits := 0;
RandomByte := 0;
end;
end;
procedure TMouseRNG.SetLineWidth(Width: Cardinal);
begin
FLineWidth := Width;
Canvas.Pen.Width := FLineWidth;
end;
procedure TMouseRNG.SetLineColor(color: TColor);
begin
FLineColor := color;
Canvas.Pen.Color := FLineColor;
end;
function TMouseRNG.CanResize(var NewWidth, NewHeight: Integer): Boolean;
var
retVal: Boolean;
multiple: Integer;
i: Integer;
begin
retVal := inherited CanResize(NewWidth, NewHeight);
if (retVal) then begin
// If a border is selected, decrement the size of the window by 2 pixels in
// either direction, for the purposes of these calculations
if (BorderStyle = bsSingle) then begin
NewWidth := NewWidth - 2;
NewHeight := NewHeight - 2;
end;
multiple := 1;
for i := 1 to BITS_PER_SAMPLE do begin
multiple := multiple * 2;
end;
NewWidth := (NewWidth div multiple) * multiple;
NewHeight := (NewHeight div multiple) * multiple;
// We have a minimum size that we will allow; twice the multiple
if (NewWidth < (multiple * 2)) then begin
NewWidth := multiple * 2;
end;
// We have a minimum size that we will allow; twice the multiple
if (NewHeight < (multiple * 2)) then begin
NewHeight := multiple * 2;
end;
// If a border is selected, increment the size of the window by 2 pixels in
// either direction
if (BorderStyle = bsSingle) then begin
NewWidth := NewWidth + 2;
NewHeight := NewHeight + 2;
end;
end;
Result := retVal;
end;
end.
|
(*****
DLLTOOLS µ¥Ôª
*****)
unit dlltools;
interface
Uses Windows, Classes, Sysutils, imagehlp ;
type
TDLLExportCallback = function (const name: String; ordinal: Integer;
address: Pointer): Boolean of Object;
{ Note: address is a RVA here, not a usable virtual address! }
DLLToolsError = Class( Exception );
Procedure ListDLLExports( const filename: String; callback:
TDLLExportCallback );
Procedure DumpExportDirectory( Const ExportDirectory: TImageExportDirectory;
lines: TStrings; const Image: LoadedImage );
Function RVAToPchar( rva: DWORD; const Image: LoadedImage ): PChar;
Function RVAToPointer( rva: DWORD; const Image: LoadedImage ): Pointer;
implementation
resourcestring
eDLLNotFound =
'ListDLLExports: DLL %s does not exist!';
{+----------------------------------------------------------------------
| Procedure EnumExports
|
| Parameters :
| ExportDirectory: IMAGE_EXPORT_DIRECTORY record to enumerate
| image : LOADED_IMAGE record for the DLL the export directory belongs
| to.
| callback : callback function to hand the found exports to, must not be
Nil
| Description:
| The export directory of a PE image contains three RVAs that point at
tables
| which describe the exported functions. The first is an array of RVAs
that
| refer to the exported function names, these we translate to PChars to
| get the exported name. The second array is an array of Word that
contains
| the export ordinal for the matching entry in the names array. The
ordinal
| is biased, that is we have to add the ExportDirectory.Base value to it
to
| get the actual export ordinal. The biased ordinal serves as index for
the
| third array, which is an array of RVAs that give the position of the
| function code in the image. We don't translate these RVAs since the DLL
| is not relocated since we load it via MapAndLoad. The function array is
| usually much larger than the names array, since the ordinals for the
| exported functions do not have to be in sequence, there can be (and
| frequently are) gaps in the sequence, for which the matching entries in
the
| function RVA array are garbage.
| Error Conditions: none
| Created: 9.1.2000 by P. Below
+----------------------------------------------------------------------}
Procedure EnumExports( const ExportDirectory : TImageExportDirectory ;
const image : LoadedImage ;
callback : TDLLExportCallback ) ;
Type
TDWordArray = Array [0..$FFFFF] of DWORD;
Var
i: Cardinal;
pNameRVAs, pFunctionRVas: ^TDWordArray;
pOrdinals: ^TWordArray;
name: String;
address: Pointer;
ordinal: Word;
Begin { EnumExports }
pNameRVAs :=
RVAToPointer( DWORD(ExportDirectory.AddressOfNames), image );
pFunctionRVAs :=
RVAToPointer( DWORD(ExportDirectory.AddressOfFunctions), image );
pOrdinals :=
RVAToPointer( DWORD(ExportDirectory.AddressOfNameOrdinals), image );
For i:= 0 to Pred( ExportDirectory.NumberOfNames ) Do Begin
name := RVAToPChar( pNameRVAs^[i], image );
ordinal := pOrdinals^[i];
address := Pointer( pFunctionRVAs^[ ordinal ] );
If not callback( name, ordinal+ExportDirectory.Base, address ) Then
Exit;
End; { For }
End; { EnumExports }
{+----------------------------------------------------------------------
| Procedure ListDLLExports
|
| Parameters :
| filename : full pathname of DLL to examine
| callback : callback to hand the found exports to, must not be Nil
| Description:
| Loads the passed DLL using the LoadImage function, finds the exported
| names table and reads it. Each found entry is handed to the callback
| for further processing, until no more entries remain or the callback
| returns false. Note that the address passed to the callback for a
exported
| function is an RVA, so not identical to the address the function would
| have in a properly loaded and relocated DLL!
| Error Conditions:
| Exceptions are raised if
| - the passed DLL does not exist or could not be loaded
| - no callback was passed (only if assertions are on)
| - an API function failed
| Created: 9.1.2000 by P. Below
+----------------------------------------------------------------------}
Procedure ListDLLExports( const filename : String ; callback :
TDLLExportCallback ) ;
Var
imageinfo: LoadedImage;
pExportDirectory: PImageExportDirectory;
dirsize: Cardinal;
Begin { ListDLLExports }
Assert( Assigned( callback ));
If not FileExists( filename ) Then
raise DLLToolsError.CreateFmt( eDLLnotFound, [filename] );
If MapAndLoad( PChar( filename ), nil, @imageinfo, true, true ) Then
try
pExportDirectory :=
ImageDirectoryEntryToData(
imageinfo.MappedAddress, false,
IMAGE_DIRECTORY_ENTRY_EXPORT, dirsize );
If pExportDirectory = Nil Then
RaiseLastWin32Error
Else
EnumExports( pExportDirectory^, imageinfo, callback );
finally
UnMapAndLoad( @imageinfo );
end
Else
RaiseLastWin32Error;
End; { ListDLLExports }
{+----------------------------------------------------------------------
| Procedure DumpExportDirectory
|
| Parameters :
| ExportDirectory: a IMAGE_EXPORT_DIRECTORY record
| lines : a TStrings descendend to put the info into, must not be Nil
| Description:
| Dumps the fields of the passed structure to the passed strings
descendent
| as strings.
| Error Conditions:
| will raise an exception if lines is Nil and assertions are enabled.
| Created: 9.1.2000 by P. Below
+----------------------------------------------------------------------}
Procedure DumpExportDirectory( Const ExportDirectory : TImageExportDirectory;
lines : TStrings; const Image: LoadedImage ) ;
Begin { DumpExportDirectory }
Assert( Assigned( lines ));
lines.add( 'Dump of IMAGE_EXPORT_DIRECTORY' );
lines.add( format('Characteristics: %d',
[ExportDirectory.Characteristics]));
lines.add( format('TimeDateStamp: %d',
[ExportDirectory.TimeDateStamp]));
lines.add( format('Version: %d.%d',
[ExportDirectory.MajorVersion,
ExportDirectory.MinorVersion]));
lines.add( format('Name (RVA): %x',
[ExportDirectory.Name]));
lines.add( format('Name (translated): %s',
[RVAToPchar( ExportDirectory.name, Image )]));
lines.add( format('Base: %d',
[ExportDirectory.Base]));
lines.add( format('NumberOfFunctions: %d',
[ExportDirectory.NumberOfFunctions]));
lines.add( format('NumberOfNames: %d',
[ExportDirectory.NumberOfNames]));
lines.add( format('AddressOfFunctions (RVA): %p',
[Pointer(ExportDirectory.AddressOfFunctions)]));
lines.add( format('AddressOfNames (RVA): %p',
[Pointer(ExportDirectory.AddressOfNames)]));
lines.add( format('AddressOfNameOrdinals (RVA): %p',
[Pointer(ExportDirectory.AddressOfNameOrdinals)]));
End; { DumpExportDirectory }
{+--------------------------------------------------------------------
| Function RVAToPointer
|
| Parameters :
| rva : a relative virtual address to translate
| Image : LOADED_IMAGE structure for the image the RVA relates to
| Returns : translated address
| Description:
| Uses the ImageRVAToVA function to translate the RVA to a virtual
| address.
| Error Conditions:
| Will raise an exception if the translation failed
| Created: 9.1.2000 by P. Below
+----------------------------------------------------------------------}
Function RVAToPointer( rva : DWORD ; const Image : LoadedImage ) : Pointer;
var
pDummy: PImageSectionHeader;
Begin { RVAToPchar }
pDummy := nil;
Result :=
ImageRvaToVa( Image.FileHeader, Image.MappedAddress, rva,
pDummy );
If Result = Nil Then
RaiseLastWin32Error;
End; { RVAToPointer }
{+----------------------------------------------------------------------
| Function RVAToPchar
|
| Parameters :
| rva : a relative virtual address to translate
| Image : LOADED_IMAGE structure for the image the RVA relates to
| Returns : translated address
| Description:
| Uses the RVAToPointer function to translate the RVA to a virtual
| address. Note that we do not check that the address does indeed point
| to a zero-terminated string!
| Error Conditions:
| Will raise an exception if the translation failed
| Created: 9.1.2000 by P. Below
+----------------------------------------------------------------------}
Function RVAToPchar( rva : DWORD ; const Image : LoadedImage ) : PChar ;
Begin { RVAToPchar }
Result := RVAToPointer( rva, image );
End; { RVAToPchar }
end.[@more@]
|
unit Spielen_Form;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, Mask, ComCtrls, Menus, Grids, Spielen_Klassen;
type
TFmSpielen = class(TForm)
eName: TEdit;
eAlter: TEdit;
eBafoeg: TEdit;
eFach: TEdit;
cbTaetigkeit: TComboBox;
eBeruf: TEdit;
eGehalt: TEdit;
btnCreate: TButton;
lstTaetigkeit: TListView;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure cbTaetigkeitChange(Sender: TObject);
procedure btnCreateClick(Sender: TObject);
private
procedure ListFuellen(mensch: TMensch);
{ Private-Deklarationen }
public
{ Public-Deklarationen }
end;
var
FmSpielen: TFmSpielen;
implementation
var
studenten: array of TStudent;
berufstaetige: array of TBerufstaetig;
{$R *.DFM}
procedure TFmSpielen.ListFuellen(mensch: TMensch);
var
item : TListItem;
begin
Item := lstTaetigkeit.Items.Add;
if mensch is TStudent then
begin
item.Caption := mensch.Name;;
item.SubItems.Add(IntToStr(mensch.Alter));
item.SubItems.Add('studierend');
item.SubItems.Add((mensch as TStudent).Fach);
item.SubItems.Add(FloatToStr((mensch as TStudent).Einkommen));
end
else if mensch is TBerufstaetig then
begin
item.Caption := mensch.Name;;
item.SubItems.Add(IntToStr(mensch.Alter));
item.SubItems.Add('berufstaetig');
item.SubItems.Add((mensch as TBerufstaetig).Branche);
item.SubItems.Add(FloatToStr((mensch as TBerufstaetig).Einkommen));
end;
end;
// Constructoraufruf und Labels fuellen
procedure TFmSpielen.FormCreate(Sender: TObject);
begin
cbTaetigkeit.Items.Append('studierend');
cbTaetigkeit.Items.Append('berufstätig');
end;
// Destruktoraufruf
procedure TFmSpielen.FormClose(Sender: TObject; var Action: TCloseAction);
var
idx: Integer;
begin
if length(studenten) > 0 then
begin
setlength(studenten, length(studenten));
for idx:=0 to length(studenten)-1 do
studenten[idx].Free;
end;
if length(berufstaetige) > 0 then
begin
setlength(berufstaetige, length(berufstaetige));
for idx:=0 to length(berufstaetige)-1 do
berufstaetige[idx].Free;
end;
end;
procedure TFmSpielen.cbTaetigkeitChange(Sender: TObject);
begin
if cbTaetigkeit.ItemIndex = 0 then
begin
eFach.Visible := True;
eBafoeg.Visible := True;
eBeruf.Visible := False;
eGehalt.Visible := False;
btnCreate.Enabled := True;
end
else if cbTaetigkeit.ItemIndex = 1 then
begin
eBeruf.Visible := True;
eGehalt.Visible := True;
eFach.Visible := False;
eBafoeg.Visible := False;
btnCreate.Enabled := True;
end
else
begin
eBeruf.Visible := False;
eGehalt.Visible := False;
eFach.Visible := False;
eBafoeg.Visible := False;
btnCreate.Enabled := False;
end;
end;
procedure TFmSpielen.btnCreateClick(Sender: TObject);
var
idx: integer;
begin
if cbTaetigkeit.ItemIndex = 0 then
begin
setlength(studenten, length(studenten)+1);
idx := length(studenten)-1;
studenten[idx] := TStudent.Create(eName.Text, StrToInt(eAlter.Text), eFach.Text, StrToFloat(eBafoeg.Text));
ListFuellen(studenten[idx]);
end
else if cbTaetigkeit.ItemIndex = 1 then
begin
setlength(berufstaetige, length(berufstaetige)+1);
idx := length(berufstaetige)-1;
berufstaetige[idx] := TBerufstaetig.Create(eName.Text, StrToInt(eAlter.Text), eBeruf.Text, StrToFloat(eGehalt.Text));
ListFuellen(berufstaetige[idx]);
end;
end;
end.
|
unit QueueForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ExtCtrls, TLHelp32;
type
TForm7 = class(TForm)
RemoveFromQueue: TButton;
HideBt: TButton;
QueueList: TListBox;
MoveDownBt: TButton;
MoveUPBt: TButton;
RunDownloadBt: TButton;
RunAllDownloadBt: TButton;
QueueDownload: TTimer;
Panel1: TPanel;
ClearBt: TButton;
AutoRunQueue: TTimer;
BatchListBt: TButton;
SaveBatch: TSaveDialog;
procedure MoveUPBtClick(Sender: TObject);
procedure MoveDownBtClick(Sender: TObject);
procedure HideBtClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure RemoveFromQueueClick(Sender: TObject);
procedure QueueListClick(Sender: TObject);
procedure RunDownloadBtClick(Sender: TObject);
procedure RunAllDownloadBtClick(Sender: TObject);
procedure QueueDownloadTimer(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ClearBtClick(Sender: TObject);
procedure AutoRunQueueTimer(Sender: TObject);
procedure BatchListBtClick(Sender: TObject);
private
{ Private declarations }
public
procedure AddItemToDownload(Item : String; Param : String);
procedure RedrawList;
procedure AddCapitalsToList;
procedure AddHorizontalScrollToList;
procedure RelockButtons;
procedure LockButtonsP;
procedure LockButtonsQueueRunning;
procedure UnlockButtons;
end;
var
Form7: TForm7;
WhichItem, TWitchItem : Integer;
HowManyItemsTogether : Integer;
LockButtons : Boolean;
WhichItemStatus, TWitchItemStatus : Integer;
URLs : TStringList;
DownloadList : TStringList;
HistoryList : TStringList;
BatchList : TStringList;
QueueRunning : Boolean;
implementation
{$R *.dfm}
uses MainForm, ConsoleForm, LogForm;
function processExists(exeFileName: string): boolean;
var
ContinueLoop: BOOL;
FSnapshotHandle: THandle;
FProcessEntry32: TProcessEntry32;
begin
FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
FProcessEntry32.dwSize := SizeOf(FProcessEntry32);
ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
Result := false;
while Integer(ContinueLoop) <> 0 do
begin
if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile))
= UpperCase(exeFileName)) or (UpperCase(FProcessEntry32.szExeFile)
= UpperCase(exeFileName))) then
begin
Result := True;
end;
ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
end;
CloseHandle(FSnapshotHandle);
end;
procedure TForm7.LockButtonsP;
begin
LogWindow.LogAdd('[SCRIPT] LockButtonsP: Locked');
LockButtons := True;
MoveUPbt.Enabled := False;
MoveDownBt.Enabled := False;
RemoveFromQueue.Enabled := False;
RunDownloadBt.Enabled := False;
RunAllDownloadBt.Enabled := False;
end;
procedure TForm7.LockButtonsQueueRunning;
begin
LogWindow.LogAdd('[SCRIPT] LockButtonsQueueRunning: Locked');
MoveUPbt.Enabled := False;
MoveDownBt.Enabled := False;
RunDownloadBt.Enabled := False;
RunAllDownloadBt.Enabled := False;
end;
procedure TForm7.UnlockButtons;
begin
LogWindow.LogAdd('[SCRIPT] UnlockButtons: Unlocked');
LockButtons := False;
RunDownloadBt.Enabled := True;
RunAllDownloadBt.Enabled := True;
RelockButtons;
end;
procedure TForm7.RelockButtons;
begin
LogWindow.LogAdd('[SCRIPT] RelockButtons: Relocking UPBt, DownBt, RMQueue');
if QueueRunning then
begin
if (QueueList.ItemIndex+1) = WhichItemStatus then
begin
MoveUpBt.Enabled := False;
MoveDownBt.Enabled := False;
RemoveFromQueue.Enabled := False;
end else
if QueueList.ItemIndex = WhichItemStatus then
begin
MoveUpBt.Enabled := False;
MoveDownBt.Enabled := True;
RemoveFromQueue.Enabled := True;
end else
if (QueueList.ItemIndex+1) < WhichItemStatus then
begin
MoveUpBt.Enabled := False;
MoveDownBt.Enabled := False;
RemoveFromQueue.Enabled := False;
end else
if (QueueList.ItemIndex+1) > WhichItemStatus then
begin
MoveUpBt.Enabled := True;
MoveDownBt.Enabled := True;
RemoveFromQueue.Enabled := True;
end;
end
// tryb normalnego sprawdzania
else
begin
if QueueList.ItemIndex = -1 then
begin
MoveUPbt.Enabled := False;
MoveDownBt.Enabled := False;
RemoveFromQueue.Enabled := False;
Exit;
end;
if QueueList.ItemIndex = 0 then
begin
MoveUpBt.Enabled := False;
MoveDownBt.Enabled := True;
RemoveFromQueue.Enabled := True;
Exit;
end;
if QueueList.ItemIndex = QueueList.Count-1 then
begin
MoveUpBt.Enabled := True;
MoveDownBt.Enabled := False;
RemoveFromQueue.Enabled := True;
Exit;
end;
if (QueueList.ItemIndex < QueueList.Count-1) or (QueueList.ItemIndex > QueueList.Count-1) then
begin
MoveUpBt.Enabled := True;
MoveDownBt.Enabled := True;
RemoveFromQueue.Enabled := True;
end;
end;
end;
// http://www.scalabium.com/faq/dct0010.htm
procedure TForm7.AddHorizontalScrollToList;
var i, intWidth, intMaxWidth: Integer;
begin
LogWindow.LogAdd('[SCRIPT] RedrawList: Rendering horizontal scrollbar');
intMaxWidth := 0;
for i := 0 to QueueList.Items.Count-1 do
begin
intWidth := QueueList.Canvas.TextWidth(QueueList.Items.Strings[i] + 'x');
if intMaxWidth < intWidth then
intMaxWidth := intWidth;
end;
SendMessage(QueueList.Handle, LB_SETHORIZONTALEXTENT, intMaxWidth, 0);
end;
procedure TForm7.AddCapitalsToList;
var
I : Integer;
DS : String;
begin
LogWindow.LogAdd('[SCRIPT] RedrawList: Redrawing list with AddCapitals');
for I := 0 to QueueList.Items.Count - 1 do
begin
if WhichItemStatus = (I+1) then DS := '>> Processing: ' else
if WhichItemStatus < (I+1) then DS := 'Queued: ' else
if WhichItemStatus > (I+1) then DS := 'Processed: ';
QueueList.Items[I] := IntToStr(I+1) + '. ' + DS + URLs.Strings[I] + ' | ' + DownloadList.Strings[I];
end;
AddHorizontalScrollToList;
end;
procedure TForm7.RedrawList;
var
I : Integer;
begin
LogWindow.LogAdd('[SCRIPT] RedrawList: Redrawing list with DownloadList');
QueueList.Clear;
for I := 0 to DownloadList.Count-1 do
QueueList.Items.Add(URLs.Strings[I] + ' // ' + DownloadList.Strings[I]);
AddCapitalsToList;
end;
procedure TForm7.AddItemToDownload(Item: string; Param : String);
begin
// add item to download from main form
// and add it to array
DownloadList.Add(Param);
QueueList.Items.Add(Param);
{Unit2.Status := '[queue] Getting name of ' + Item;
Form5.RunDosInMemo(PathToYoutubedl, ' -e "' + Item + '"',
procedure(const Line: PAnsiChar)
begin
// this writes command effect to memo
URLs.Add(String(Line) + ' ' + Item);
end);
Unit2.Status := 'Ready';}
URLs.Add(Item);
RedrawList;
end;
procedure TForm7.AutoRunQueueTimer(Sender: TObject);
begin
if QueueList.Count >= 1 then
begin
if QueueRunning then
begin
AutoRunQueue.Enabled := False;
end else
begin
LogWindow.LogAdd('[SCRIPT] AutoRunQueue: Script is getting ready');
MainForm.Status := 'Running download script';
LockButtonsQueueRunning;
WhichItem := 0;
WhichItemStatus := 1;
LogWindow.LogAdd('[SCRIPT] AutoRunQueue: Succesfuly resetted values');
HowManyItemsTogether := QueueList.Count;
LogWindow.LogAdd('[SCRIPT] AutoRunQueue: Calling QueueDownload');
QueueDownload.Enabled := True;
end;
end;
end;
procedure TForm7.BatchListBtClick(Sender: TObject);
var
HowManyItemsBatch : Integer;
I : Integer;
begin
HowManyItemsBatch := DownloadList.Count;
BatchList := TStringList.Create;
BatchList.Add('@echo off');
BatchList.Add('echo Downloading ' + IntToStr(HowManyItemsBatch) + ' items...');
for I := 0 to DownloadList.Count-1 do
begin
BatchList.Add('echo Downloading ' + IntToStr(I+1) + ' of ' + IntToStr(HowManyItemsBatch));
BatchList.Add(MainForm.PathToYoutubedl + ' ' + DownloadList.Strings[I]);
BatchList.Add('cls');
end;
BatchList.Add('echo Downloaded ' + IntToStr(HowManyItemsBatch) + ' item(s)!');
BatchList.Add('pause>nul');
BatchList.SaveToFile(ExtractFilePath(Application.ExeName) + 'batch.txt');
SaveBatch.InitialDir := ExtractFilePath(Application.ExeName);
if SaveBatch.Execute() then
BatchList.SaveToFile(SaveBatch.FileName + '.bat');
end;
procedure TForm7.ClearBtClick(Sender: TObject);
begin
URLs.Clear;
DownloadList.Clear;
QueueList.Clear;
HistoryList.Clear;
end;
procedure TForm7.RunAllDownloadBtClick(Sender: TObject);
begin
QueueDownload.Enabled := True;
QueueRunning := True;
LockButtonsQueueRunning;
WhichItem := 0;
WhichItemStatus := 1;
HowManyItemsTogether := QueueList.Count;
Form7.Hide;
if MainForm.ConsoleInWindowedMode then Form1.ConsoleSheet.Show else Form5.Show;
end;
procedure TForm7.FormClose(Sender: TObject; var Action: TCloseAction);
{var
I:Integer;
SaveModule : TStringList;}
begin
{
SaveModule := TStringList.Create;
for I:=0 to Length(Downloads)-1 do
SaveModule.Add(Downloads[I]);
SaveModule.SaveToFile(ExtractFilePath(Application.ExeName) + 'queue.his');
}
{
for I := 0 to Length(Downloads) do
SaveLoad.Lines.Strings[I] := Downloads[I];
SaveLoad.Lines.SaveToFile(ExtractFilePath(Application.ExeName) + 'queue.txt');
}
end;
procedure TForm7.FormCreate(Sender: TObject);
{var
I : Integer;
SaveModule : TStringList;}
begin
URLs := TStringList.Create;
DownloadList := TStringList.Create;
HistoryList := TStringList.Create;
if not LockButtons then RelockButtons else LockButtonsP;
{
if FileExists(ExtractFilePath(Application.ExeName) + 'queue.his') then
begin
SaveModule := TStringList.Create;
SaveModule.LoadFromFile(ExtractFilePath(Application.ExeName) + 'queue.his');
SetLength(Downloads, SaveModule.Count);
for I := 0 to SaveModule.Count-1 do
Downloads[I] := SaveModule.Strings[I];
RedrawList;
end;
if FileExists(ExtractFilePath(Application.ExeName + 'queuehistory.his')) then
begin
HistoryList.Items.LoadFromFile(ExtractFilePath(Application.ExeName) + 'queuehistory.his');
end;
}
end;
procedure TForm7.HideBtClick(Sender: TObject);
begin
Form7.Hide;
end;
procedure TForm7.MoveDownBtClick(Sender: TObject);
begin
// moving item down
DownloadList.Exchange(QueueList.ItemIndex, QueueList.ItemIndex + 1);
URLs.Exchange(QueueList.ItemIndex, QueueList.ItemIndex + 1);
RedrawList;
end;
procedure TForm7.MoveUPBtClick(Sender: TObject);
begin
// moving item up
DownloadList.Exchange(QueueList.ItemIndex, QueueList.ItemIndex - 1);
URLs.Exchange(QueueList.ItemIndex, QueueList.ItemIndex - 1);
RedrawList;
end;
procedure TForm7.QueueDownloadTimer(Sender: TObject);
var
HowManyItems : Integer;
begin
HowManyItems := QueueList.Count - 1;
HowManyItemsTogether := QueueList.Count;
if WhichItem > HowManyItems then
begin
LogWindow.LogAdd('[SCRIPT] QueueDownload: Download looks finished, sending message');
MainForm.Status := 'Downloaded ' + IntToStr(HowManyItemsTogether) + ' items.';
Form1.MainConsoleMessager('Downloaded queued items.', false);
LogWindow.LogAdd('[SCRIPT] QueueDownload: Cleaning values');
UnlockButtons;
URLs.Clear;
DownloadList.Clear;
QueueList.Clear;
LogWindow.LogAdd('[SCRIPT] QueueDownload: Disabling QueueDownload');
QueueDownload.Enabled := False;
QueueRunning := False;
LogWindow.LogAdd('[SCRIPT] AddToQueue: Running script AutoRunQueue');
AutoRunQueue.Enabled := True;
end else
if not processExists('youtube-dl.exe') then
begin
RedrawList;
QueueRunning := True;
LogWindow.LogAdd('[SCRIPT] QueueDownload: Running external download');
Form1.RunExternalDownload(DownloadList.Strings[WhichItem], WhichItemStatus, HowManyItemsTogether);
Inc(WhichItem);
Inc(WhichItemStatus);
end;
end;
procedure TForm7.QueueListClick(Sender: TObject);
begin
if not LockButtons then RelockButtons else LockButtonsP;
end;
procedure TForm7.RemoveFromQueueClick(Sender: TObject);
begin
URLs.Delete(QueueList.ItemIndex);
DownloadList.Delete(QueueList.ItemIndex);
RedrawList;
end;
procedure TForm7.RunDownloadBtClick(Sender: TObject);
begin
if not QueueList.ItemIndex = -1 then
begin
LogWindow.LogAdd('[SCRIPT] RunOneDownloadFromQueue: Running');
QueueRunning := True;
LogWindow.LogAdd('[SCRIPT] RunOneDownloadFromQueue: Sending to external download');
Form1.RunExternalDownload(DownloadList.Strings[QueueList.ItemIndex], 0, 1);
Form7.Hide;
end
else
MessageBox(Handle, PChar('Select something!'), PChar('Error'), MB_OK + MB_ICONERROR);
end;
end.
|
(*
Copyright (c) 2016 Darian Miller
All rights reserved.
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, and/or sell copies of the
Software, and to permit persons to whom the Software is furnished to do so, provided that the above copyright notice(s) and this permission notice
appear in all copies of the Software and that both the above copyright notice(s) and this permission notice appear in supporting documentation.
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 OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE
LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other
dealings in this Software without prior written authorization of the copyright holder.
As of January 2016, latest version available online at:
https://github.com/darianmiller/dxLib_Tests
*)
unit dxLib_Test_RTTI_SetDefaults;
interface
{$I '..\Dependencies\dxLib\Source\dxLib.inc'}
uses
TestFramework,
{$IFDEF DX_UnitScopeNames}
System.Classes,
System.TypInfo,
{$ELSE}
Classes,
TypInfo,
{$ENDIF}
dxLib_RTTI;
type
TExampleEnum = (myOne, myTwo, myThree, myFour, myFive, mySix, mySeven);
TExampleSet = set of TExampleEnum;
const
DELPHI_DEFAULT_CHAR = #0;
DELPHI_DEFAULT_WIDECHAR = #0;
DELPHI_DEFAULT_INTEGER = 0;
DELPHI_DEFAULT_INT64 = 0;
DELPHI_DEFAULT_BYTE = 0;
DELPHI_DEFAULT_ExampleEnum = myOne;
DELPHI_DEFAULT_ExampleSet = [];
CUSTOM_DEFAULT_CHAR = 'A';
CUSTOM_DEFAULT_WIDECHAR = 'B';
CUSTOM_DEFAULT_INTEGER = MaxInt;
//note: Int64 property defaults fail to compile with constant values > MaxInt
CUSTOM_DEFAULT_INT64 = -1;
CUSTOM_DEFAULT_BYTE = 1;
CUSTOM_DEFAULT_ExampleEnum = mySix;
CUSTOM_DEFAULT_ExampleSet = [myTwo, mySeven];
type
TExampleClass = Class(TPersistent)
private
fCharNoDefault:Char;
fCharWithDefault:Char;
fWideCharNoDefault:WideChar;
fWideCharWithDefault:WideChar;
fIntegerNoDefault:Integer;
fIntegerWithDefault:Integer;
fInt64NoDefault:Int64;
fInt64WithDefault:Int64;
fByteNoDefault:Byte;
fByteWithDefault:Byte;
fEnumNoDefault:TExampleEnum;
fEnumWithDefault:TExampleEnum;
fSetNoDefault:TExampleSet;
fSetWithDefault:TExampleSet;
published
property CharNoDefault:Char Read fCharNoDefault Write fCharNoDefault;
property CharWithDefault:Char Read fCharWithDefault Write fCharWithDefault default CUSTOM_DEFAULT_CHAR;
property WideCharNoDefault:WideChar Read fWideCharNoDefault Write fWideCharNoDefault;
property WideCharWithDefault:WideChar Read fWideCharWithDefault Write fWideCharWithDefault default CUSTOM_DEFAULT_WIDECHAR;
property IntegerNoDefault:Integer Read fIntegerNoDefault Write fIntegerNoDefault;
property IntegerWithDefault:Integer Read fIntegerWithDefault Write fIntegerWithDefault default CUSTOM_DEFAULT_INTEGER;
property Int64NoDefault:Int64 Read fInt64NoDefault Write fInt64NoDefault;
property Int64WithDefault:Int64 Read fInt64WithDefault Write fInt64WithDefault default CUSTOM_DEFAULT_INT64;
property ByteNoDefault:Byte Read fByteNoDefault Write fByteNoDefault;
property ByteWithDefault:Byte Read fByteWithDefault Write fByteWithDefault default CUSTOM_DEFAULT_BYTE;
property EnumNoDefault:TExampleEnum Read fEnumNoDefault Write fEnumNoDefault;
property EnumWithDefault:TExampleEnum Read fEnumWithDefault Write fEnumWithDefault default CUSTOM_DEFAULT_ExampleEnum;
property SetNoDefault:TExampleSet Read fSetNoDefault Write fSetNoDefault;
property SetWithDefault:TExampleSet Read fSetWithDefault Write fSetWithDefault default CUSTOM_DEFAULT_ExampleSet;
end;
TestSetPublishedPropertyDefaultsViaRTTI = class(TTestCase)
private
fExampleClass:TExampleClass;
protected
procedure SetUp(); override;
procedure TearDown(); override;
published
procedure TestDefaultStorageSpecifiers();
procedure TestCharNoDefault();
procedure TestCharWithDefault();
procedure TestWideCharNoDefault();
procedure TestWideCharWithDefault();
procedure TestIntegerNoDefault();
procedure TestIntegerWithDefault();
procedure TestInt64NoDefault();
procedure TestInt64WithDefault();
procedure TestByteNoDefault();
procedure TestByteWithDefault();
procedure TestEnumNoDefault();
procedure TestEnumWithDefault();
procedure TestSetNoDefault();
procedure TestSetWithDefault();
end;
implementation
//'Default' property values not supported when creating an instance directly
//DOC: The optional stored, default, and nodefault directives are called storage specifiers.
//They have no effect on program behavior, but control whether or not to save the values of published properties IN FORM FILES
procedure TestSetPublishedPropertyDefaultsViaRTTI.TestDefaultStorageSpecifiers();
var
vExampleClass:TExampleClass;
begin
//Validate normal Delphi usage (without call to SetPublishedPropertyDefaultsViaRTTI)
vExampleClass := TExampleClass.Create();
try
//defaults should be unused
CheckTrue(vExampleClass.CharNoDefault = vExampleClass.CharWithDefault);
CheckTrue(vExampleClass.WideCharNoDefault = vExampleClass.WideCharWithDefault);
CheckTrue(vExampleClass.IntegerNoDefault = vExampleClass.IntegerWithDefault);
CheckTrue(vExampleClass.Int64NoDefault = vExampleClass.Int64WithDefault);
CheckTrue(vExampleClass.ByteNoDefault = vExampleClass.ByteWithDefault);
CheckTrue(vExampleClass.EnumNoDefault = vExampleClass.EnumWithDefault);
CheckTrue(vExampleClass.SetNoDefault = vExampleClass.SetWithDefault);
finally
vExampleClass.Free();
end;
end;
procedure TestSetPublishedPropertyDefaultsViaRTTI.Setup();
begin
inherited;
fExampleClass := TExampleClass.Create();
SetPublishedPropertyDefaultsViaRTTI(fExampleClass);
end;
procedure TestSetPublishedPropertyDefaultsViaRTTI.Teardown();
begin
fExampleClass.Free();
inherited;
end;
procedure TestSetPublishedPropertyDefaultsViaRTTI.TestCharNoDefault();
begin
Check(fExampleClass.CharNoDefault = DELPHI_DEFAULT_CHAR); //validate expected Delphi behavior
end;
procedure TestSetPublishedPropertyDefaultsViaRTTI.TestCharWithDefault();
begin
Check(fExampleClass.CharWithDefault = CUSTOM_DEFAULT_CHAR); //validate new behavior: 'default' value set by SetPublishedPropertyDefaultsViaRTTI
end;
procedure TestSetPublishedPropertyDefaultsViaRTTI.TestWideCharNoDefault();
begin
Check(fExampleClass.WideCharNoDefault = DELPHI_DEFAULT_WIDECHAR); //validate expected Delphi behavior
end;
procedure TestSetPublishedPropertyDefaultsViaRTTI.TestWideCharWithDefault();
begin
Check(fExampleClass.WideCharWithDefault = CUSTOM_DEFAULT_WIDECHAR); //validate new behavior: 'default' value set by SetPublishedPropertyDefaultsViaRTTI
end;
procedure TestSetPublishedPropertyDefaultsViaRTTI.TestIntegerNoDefault();
begin
Check(fExampleClass.IntegerNoDefault = DELPHI_DEFAULT_INTEGER); //validate expected Delphi behavior
end;
procedure TestSetPublishedPropertyDefaultsViaRTTI.TestIntegerWithDefault();
begin
Check(fExampleClass.IntegerWithDefault = CUSTOM_DEFAULT_INTEGER); //validate new behavior: 'default' value set by SetPublishedPropertyDefaultsViaRTTI
end;
procedure TestSetPublishedPropertyDefaultsViaRTTI.TestInt64NoDefault();
begin
Check(fExampleClass.Int64NoDefault = DELPHI_DEFAULT_INT64); //validate expected Delphi behavior
end;
procedure TestSetPublishedPropertyDefaultsViaRTTI.TestInt64WithDefault();
begin
Check(fExampleClass.Int64WithDefault = CUSTOM_DEFAULT_INT64); //validate new behavior: 'default' value set by SetPublishedPropertyDefaultsViaRTTI
end;
procedure TestSetPublishedPropertyDefaultsViaRTTI.TestByteNoDefault();
begin
Check(fExampleClass.ByteNoDefault = DELPHI_DEFAULT_BYTE); //validate expected Delphi behavior
end;
procedure TestSetPublishedPropertyDefaultsViaRTTI.TestByteWithDefault();
begin
Check(fExampleClass.ByteWithDefault = CUSTOM_DEFAULT_BYTE); //validate new behavior: 'default' value set by SetPublishedPropertyDefaultsViaRTTI
end;
procedure TestSetPublishedPropertyDefaultsViaRTTI.TestEnumNoDefault;
begin
Check(fExampleClass.EnumNoDefault = DELPHI_DEFAULT_ExampleEnum); //validate expected Delphi behavior
end;
procedure TestSetPublishedPropertyDefaultsViaRTTI.TestEnumWithDefault;
begin
Check(fExampleClass.EnumWithDefault = CUSTOM_DEFAULT_ExampleEnum); //validate new behavior: 'default' value set by SetPublishedPropertyDefaultsViaRTTI
end;
procedure TestSetPublishedPropertyDefaultsViaRTTI.TestSetNoDefault;
begin
Check(fExampleClass.SetNoDefault = DELPHI_DEFAULT_ExampleSet); //validate expected Delphi behavior
end;
procedure TestSetPublishedPropertyDefaultsViaRTTI.TestSetWithDefault;
begin
Check(fExampleClass.SetWithDefault = CUSTOM_DEFAULT_ExampleSet); //validate new behavior: 'default' value set by SetPublishedPropertyDefaultsViaRTTI
end;
initialization
RegisterTest(TestSetPublishedPropertyDefaultsViaRTTI.Suite);
end.
|
unit fReloj;
interface
uses
System.DateUtils, TZDB, tReloj,
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.Controls.Presentation, FMX.Layouts, FMX.MultiView;
type
TfraReloj = class(TFrame)
lblReloj: TLabel;
lblZona: TLabel;
sbtQuitar: TSpeedButton;
layQuitar: TLayout;
procedure sbtQuitarClick(Sender: TObject);
procedure FrameResize(Sender: TObject);
procedure lblRelojClick(Sender: TObject);
private
tReloj:TThreadReloj;
FZonaHorario: string;
FZona: TBundledTimeZone;
FDeteniendo: Boolean;
procedure onReloj(Sender:TObject);
function getZonaVisible: boolean;
procedure setZonaVisible(const Value: boolean);
function getQuitarVisible: boolean;
procedure setQuitarVisible(const Value: boolean);
procedure setZonaHorario(const Value: string);
public
constructor Create(AOwner:TComponent); override;
destructor Destroy; override;
procedure Detener;
property Deteniendo:Boolean Read FDeteniendo;
property ZonaVisible:boolean read getZonaVisible write setZonaVisible;
property QuitarVisible:boolean read getQuitarVisible write setQuitarVisible;
property ZonaHoraria:string read FZonaHorario write setZonaHorario;
end;
implementation
{$R *.fmx}
uses
uGral, fMain, fSeleccionarZonaHoraria;
{ TfraReloj }
constructor TfraReloj.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Height := 50;
Anchors := [TAnchorKind.akLeft, TAnchorKind.akTop, TAnchorKind.akRight];
FDeteniendo := False;
FZona := TBundledTimeZone.GetTimeZone('America/Mexico_City');
setZonaHorario('America/Mexico_City');
tReloj := TThreadReloj.Create(True);
tReloj.OnTimer := onReloj;
tReloj.Start;
onReloj(nil);
end;
destructor TfraReloj.Destroy;
begin
Detener;
inherited Destroy;
end;
procedure TfraReloj.Detener;
begin
FDeteniendo := True;
tReloj.Terminate;
end;
procedure TfraReloj.FrameResize(Sender: TObject);
begin
sbtQuitar.Height := Height;
end;
function TfraReloj.getQuitarVisible: boolean;
begin
Result := sbtQuitar.Visible;
end;
function TfraReloj.getZonaVisible: boolean;
begin
Result := lblZona.Visible;
end;
procedure TfraReloj.lblRelojClick(Sender: TObject);
begin
frmZonaHoraria := TfrmZonaHoraria.Create(Self);
{$ifdef MSWINDOWS}
if ispositiveresult(frmZonaHoraria.ShowModal) then begin
ZonaHoraria := frmZonaHoraria.Zona;
end; {if}
{$else}
frmZonaHoraria.ShowModal(procedure (AModalResult:TModalResult)
begin
if IsPositiveResult(AModalResult) then
ZonaHoraria := frmZonaHoraria.Zona;
end
);
{$endif}
end;
procedure TfraReloj.onReloj(Sender: TObject);
var
tz2: TBundledTimeZone;
UTCtime, tz2time: TDatetime;
begin
if FDeteniendo then
Exit;
UTCtime := FZona.ToUniversalTime(Now);
tz2 := TBundledTimeZone.GetTimeZone(ZonaHoraria);
tz2time := tz2.ToLocalTime(UTCtime);
lblReloj.Text := FormatDateTime(FormatoHora, tz2time);
//lblReloj.Text := FormatDateTime(FormatoHora, UTCtime);
end;
procedure TfraReloj.sbtQuitarClick(Sender: TObject);
begin
Detener;
Owner.DisposeOf;
end;
procedure TfraReloj.setQuitarVisible(const Value: boolean);
begin
layQuitar.Visible := Value;
end;
procedure TfraReloj.setZonaHorario(const Value: string);
begin
FZonaHorario := Value;
lblZona.Text := Format('%s (%s)', [Value, FZona.Abbreviation]);
end;
procedure TfraReloj.setZonaVisible(const Value: boolean);
begin
lblZona.Visible := True;
end;
end.
|
{ *********************************************************************** }
{ }
{ GUI Hangman }
{ Version 1.0 - First release of program }
{ Last Revised: 27nd of July 2004 }
{ Copyright (c) 2004 Chris Alley }
{ }
{ *********************************************************************** }
unit UReports;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, UPlayerReport, UGameReport, UAllGamesReport,
UDataModule, UConstantsAndTypes;
type
TReportsDialog = class(TForm)
ReportTypeRadioGroup: TRadioGroup;
PrintPreviewButton: TButton;
CloseButton: TButton;
procedure FormCreate(Sender: TObject);
procedure PrintPreviewButtonClick(Sender: TObject);
private
{ Private declarations }
procedure DisplayPlayerReport;
procedure DisplayGameReport;
procedure DisplayAllGamesReport;
procedure SetPlayerReportToDefault(var PlayerReportForm: TPlayerReportForm);
procedure SetGameReportToDefault(var GameReportForm: TGameReportForm);
public
{ Public declarations }
PlayerLogin: string;
end;
implementation
{$R *.dfm}
procedure TReportsDialog.DisplayAllGamesReport;
{ Modally creates and displays the All Games Report. }
var
AllGamesReportForm: TAllGamesReportForm;
begin
Self.PrintPreviewButton.Enabled := False;
AllGamesReportForm := UAllGamesReport.TAllGamesReportForm.Create(Self);
AllGamesReportForm.AllGamesQuickRep.PreviewModal;
AllGamesReportForm.Release;
Self.PrintPreviewButton.Enabled := True;
end;
procedure TReportsDialog.DisplayGameReport;
{ Modally creates and displays the Game Report. }
var
GameReportForm: TGameReportForm;
GamesPlayed, AverageScore, ChampionScore: integer;
CurrentChampion, DatePlayed: string;
begin
Self.PrintPreviewButton.Enabled := False;
GameReportForm := UGameReport.TGameReportForm.Create(Self);
SetGameReportToDefault(GameReportForm);
// Get and display Easy game statistics.
HangmanDataModule.GetGameStatistics(Easy, GamesPlayed, AverageScore,
CurrentChampion, ChampionScore, DatePlayed);
GameReportForm.EasyGamesPlayedQRLabel.Caption := IntToStr(GamesPlayed);
GameReportForm.EasyAverageScoreQRLabel.Caption := IntToStr(AverageScore);
GameReportForm.EasyCurrentChampionQRLabel.Caption := CurrentChampion;
GameReportForm.EasyChampionScoreQRLabel.Caption := IntToStr(ChampionScore);
GameReportForm.EasyDatePlayedQRLabel.Caption := DatePlayed;
// Get and display Normal game statistics.
HangmanDataModule.GetGameStatistics(Normal, GamesPlayed, AverageScore,
CurrentChampion, ChampionScore, DatePlayed);
GameReportForm.NormalGamesPlayedQRLabel.Caption := IntToStr(GamesPlayed);
GameReportForm.NormalAverageScoreQRLabel.Caption := IntToStr(AverageScore);
GameReportForm.NormalCurrentChampionQRLabel.Caption := CurrentChampion;
GameReportForm.NormalChampionScoreQRLabel.Caption := IntToStr(ChampionScore);
GameReportForm.NormalDatePlayedQRLabel.Caption := DatePlayed;
// Get and display Hard game statistics.
HangmanDataModule.GetGameStatistics(Hard, GamesPlayed, AverageScore,
CurrentChampion, ChampionScore, DatePlayed);
GameReportForm.HardGamesPlayedQRLabel.Caption := IntToStr(GamesPlayed);
GameReportForm.HardAverageScoreQRLabel.Caption := IntToStr(AverageScore);
GameReportForm.HardCurrentChampionQRLabel.Caption := CurrentChampion;
GameReportForm.HardChampionScoreQRLabel.Caption := IntToStr(ChampionScore);
GameReportForm.HardDatePlayedQRLabel.Caption := DatePlayed;
GameReportForm.GameQuickRep.PreviewModal;
GameReportForm.Release;
Self.PrintPreviewButton.Enabled := True;
end;
procedure TReportsDialog.DisplayPlayerReport;
{ Modally creates and displays the Player Report. }
var
PlayerReportForm: TPlayerReportForm;
GamesPlayed, AverageScore, BestScore: integer;
begin
Self.PrintPreviewButton.Enabled := False;
PlayerReportForm := TPlayerReportForm.Create(Self);
SetPlayerReportToDefault(PlayerReportForm);
// Get and display player's Easy statistics.
HangmanDataModule.GetIndividualGameStatistics(PlayerLogin, Easy, GamesPlayed,
AverageScore, BestScore);
PlayerReportForm.EasyGamesPlayedQRLabel.Caption := IntToStr(GamesPlayed);
PlayerReportForm.EasyAverageScoreQRLabel.Caption := IntToStr(AverageScore);
PlayerReportForm.EasyBestScoreQRLabel.Caption := IntToStr(BestScore);
// Get and display player's Normal statistics.
HangmanDataModule.GetIndividualGameStatistics(PlayerLogin, Normal,
GamesPlayed, AverageScore, BestScore);
PlayerReportForm.NormalGamesPlayedQRLabel.Caption := IntToStr(GamesPlayed);
PlayerReportForm.NormalAverageScoreQRLabel.Caption := IntToStr(AverageScore);
PlayerReportForm.NormalBestScoreQRLabel.Caption := IntToStr(BestScore);
// Get and display player's Hard statistics.
HangmanDataModule.GetIndividualGameStatistics(PlayerLogin, Hard, GamesPlayed,
AverageScore, BestScore);
PlayerReportForm.HardGamesPlayedQRLabel.Caption := IntToStr(GamesPlayed);
PlayerReportForm.HardAverageScoreQRLabel.Caption := IntToStr(AverageScore);
PlayerReportForm.HardBestScoreQRLabel.Caption := IntToStr(BestScore);
PlayerReportForm.PlayerQuickRep.PreviewModal;
PlayerReportForm.Release;
Self.PrintPreviewButton.Enabled := True;
end;
procedure TReportsDialog.FormCreate(Sender: TObject);
{ Sets various settings and components to default. }
begin
Self.ReportTypeRadioGroup.ItemIndex := 0;
Self.PrintPreviewButton.Default := True;
end;
procedure TReportsDialog.PrintPreviewButtonClick(Sender: TObject);
{ Displays a report depending on which radio button was selected. }
begin
case Self.ReportTypeRadioGroup.ItemIndex of
0: Self.DisplayPlayerReport;
1: Self.DisplayGameReport;
2: Self.DisplayAllGamesReport;
end;
end;
procedure TReportsDialog.SetGameReportToDefault(var GameReportForm:
TGameReportForm);
{ Sets various labels and captions on the Game Report to default. }
begin
GameReportForm.EasyQRLabel.Caption := Easy;
GameReportForm.EasyGamesPlayedQRLabel.Caption := '';
GameReportForm.EasyAverageScoreQRLabel.Caption := '';
GameReportForm.EasyCurrentChampionQRLabel.Caption := '';
GameReportForm.EasyChampionScoreQRLabel.Caption := '';
GameReportForm.EasyDatePlayedQRLabel.Caption := '';
GameReportForm.NormalQRLabel.Caption := Normal;
GameReportForm.NormalGamesPlayedQRLabel.Caption := '';
GameReportForm.NormalAverageScoreQRLabel.Caption := '';
GameReportForm.NormalCurrentChampionQRLabel.Caption := '';
GameReportForm.NormalChampionScoreQRLabel.Caption := '';
GameReportForm.NormalDatePlayedQRLabel.Caption := '';
GameReportForm.HardQRLabel.Caption := Hard;
GameReportForm.HardGamesPlayedQRLabel.Caption := '';
GameReportForm.HardAverageScoreQRLabel.Caption := '';
GameReportForm.HardCurrentChampionQRLabel.Caption := '';
GameReportForm.HardChampionScoreQRLabel.Caption := '';
GameReportForm.HardDatePlayedQRLabel.Caption := '';
end;
procedure TReportsDialog.SetPlayerReportToDefault(var PlayerReportForm:
TPlayerReportForm);
{ Sets various labels and captions on the Player Report to default. }
var
PlayerFirstName, PlayerLastName: string;
begin
HangmanDataModule.GetPlayerFirstAndLastNames(PlayerLogin, PlayerFirstName,
PlayerLastName);
PlayerReportForm.PlayerLoginQRLabel.Caption := '...for ' + PlayerFirstName +
' ' + PlayerLastName;
PlayerReportForm.EasyQRLabel.Caption := Easy;
PlayerReportForm.EasyGamesPlayedQRLabel.Caption := '';
PlayerReportForm.EasyAverageScoreQRLabel.Caption := '';
PlayerReportForm.EasyBestScoreQRLabel.Caption := '';
PlayerReportForm.NormalQRLabel.Caption := Normal;
PlayerReportForm.NormalGamesPlayedQRLabel.Caption := '';
PlayerReportForm.NormalAverageScoreQRLabel.Caption := '';
PlayerReportForm.NormalBestScoreQRLabel.Caption := '';
PlayerReportForm.HardQRLabel.Caption := Hard;
PlayerReportForm.HardGamesPlayedQRLabel.Caption := '' ;
PlayerReportForm.HardAverageScoreQRLabel.Caption := '';
PlayerReportForm.HardBestScoreQRLabel.Caption := '';
end;
end.
|
unit WebSocketServer;
interface
uses
System.SysUtils, System.Generics.Collections,
IdCustomTCPServer, IdTCPConnection, IdContext, IdIOHandler, IdGlobal, IdCoderMIME, IdHashSHA,
IdSSL, IdSSLOpenSSL;
type
TWebSocketServer = class(TIdCustomTCPServer)
private
IdServerIOHandlerSSLOpenSSL: TIdServerIOHandlerSSLOpenSSL;
HashSHA1: TIdHashSHA1;
protected
procedure DoConnect(AContext: TIdContext); override;
function DoExecute(AContext: TIdContext): Boolean; override;
public
procedure InitSSL(AIdServerIOHandlerSSLOpenSSL: TIdServerIOHandlerSSLOpenSSL);
property OnExecute;
constructor Create;
destructor Destroy; override;
end;
TWebSocketIOHandlerHelper = class(TIdIOHandler)
public
function ReadBytes: TArray<byte>;
function ReadString: string;
procedure WriteBytes(RawData: TArray<byte>);
procedure WriteString(const str: string);
end;
implementation
function HeadersParse(const msg: string): TDictionary<string, string>;
var
lines: TArray<string>;
line: string;
SplittedLine: TArray<string>;
begin
result := TDictionary<string, string>.Create;
lines := msg.Split([#13#10]);
for line in lines do
begin
SplittedLine := line.Split([': ']);
if Length(SplittedLine) > 1 then
result.AddOrSetValue(Trim(SplittedLine[0]), Trim(SplittedLine[1]));
end;
end;
{ TWebSocketServer }
constructor TWebSocketServer.Create;
begin
inherited Create;
HashSHA1 := TIdHashSHA1.Create;
IdServerIOHandlerSSLOpenSSL := nil;
end;
destructor TWebSocketServer.Destroy;
begin
HashSHA1.DisposeOf;
inherited;
end;
procedure TWebSocketServer.InitSSL(AIdServerIOHandlerSSLOpenSSL: TIdServerIOHandlerSSLOpenSSL);
var
CurrentActive: boolean;
begin
CurrentActive := Active;
if CurrentActive then
Active := false;
IdServerIOHandlerSSLOpenSSL := AIdServerIOHandlerSSLOpenSSL;
IOHandler := AIdServerIOHandlerSSLOpenSSL;
if CurrentActive then
Active := true;
end;
procedure TWebSocketServer.DoConnect(AContext: TIdContext);
begin
if AContext.Connection.IOHandler is TIdSSLIOHandlerSocketBase then
TIdSSLIOHandlerSocketBase(AContext.Connection.IOHandler).PassThrough := false;
// Mark connection as "not handshaked"
AContext.Connection.IOHandler.Tag := -1;
inherited;
end;
function TWebSocketServer.DoExecute(AContext: TIdContext): Boolean;
var
c: TIdIOHandler;
Bytes: TArray<byte>;
msg, SecWebSocketKey, Hash: string;
ParsedHeaders: TDictionary<string, string>;
begin
c := AContext.Connection.IOHandler;
// Handshake
if c.Tag = -1 then
begin
c.CheckForDataOnSource(10);
if not c.InputBufferIsEmpty then
begin
// Read string and parse HTTP headers
try
c.InputBuffer.ExtractToBytes(TIdBytes(Bytes));
msg := IndyTextEncoding_UTF8.GetString(TIdBytes(Bytes));
except
end;
ParsedHeaders := HeadersParse(msg);
if ParsedHeaders.ContainsKey('Upgrade') and (ParsedHeaders['Upgrade'] = 'websocket') and
ParsedHeaders.ContainsKey('Sec-WebSocket-Key') then
begin
// Handle handshake request
// https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers
SecWebSocketKey := ParsedHeaders['Sec-WebSocket-Key'];
// Send handshake response
Hash := TIdEncoderMIME.EncodeBytes(
HashSHA1.HashString(SecWebSocketKey + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'));
try
c.Write('HTTP/1.1 101 Switching Protocols'#13#10
+ 'Upgrade: websocket'#13#10
+ 'Connection: Upgrade'#13#10
+ 'Sec-WebSocket-Accept: ' + Hash
+ #13#10#13#10, IndyTextEncoding_UTF8);
except
end;
// Mark IOHandler as handshaked
c.Tag := 1;
end;
ParsedHeaders.DisposeOf;
end;
end;
Result := inherited;
end;
{ TWebSocketIOHandlerHelper }
function TWebSocketIOHandlerHelper.ReadBytes: TArray<byte>;
var
l: byte;
b: array [0..7] of byte;
i, DecodedSize: int64;
Mask: array [0..3] of byte;
begin
// https://stackoverflow.com/questions/8125507/how-can-i-send-and-receive-websocket-messages-on-the-server-side
try
if ReadByte = $81 then
begin
l := ReadByte;
case l of
$FE:
begin
b[1] := ReadByte; b[0] := ReadByte;
b[2] := 0; b[3] := 0; b[4] := 0; b[5] := 0; b[6] := 0; b[7] := 0;
DecodedSize := Int64(b);
end;
$FF:
begin
b[7] := ReadByte; b[6] := ReadByte; b[5] := ReadByte; b[4] := ReadByte;
b[3] := ReadByte; b[2] := ReadByte; b[1] := ReadByte; b[0] := ReadByte;
DecodedSize := Int64(b);
end;
else
DecodedSize := l - 128;
end;
Mask[0] := ReadByte; Mask[1] := ReadByte; Mask[2] := ReadByte; Mask[3] := ReadByte;
if DecodedSize < 1 then
begin
result := [];
exit;
end;
SetLength(result, DecodedSize);
inherited ReadBytes(TIdBytes(result), DecodedSize, False);
for i := 0 to DecodedSize - 1 do
result[i] := result[i] xor Mask[i mod 4];
end;
except
end;
end;
procedure TWebSocketIOHandlerHelper.WriteBytes(RawData: TArray<byte>);
var
Msg: TArray<byte>;
begin
// https://stackoverflow.com/questions/8125507/how-can-i-send-and-receive-websocket-messages-on-the-server-side
Msg := [$81];
if Length(RawData) <= 125 then
Msg := Msg + [Length(RawData)]
else if (Length(RawData) >= 126) and (Length(RawData) <= 65535) then
Msg := Msg + [126, (Length(RawData) shr 8) and 255, Length(RawData) and 255]
else
Msg := Msg + [127, (int64(Length(RawData)) shr 56) and 255, (int64(Length(RawData)) shr 48) and 255,
(int64(Length(RawData)) shr 40) and 255, (int64(Length(RawData)) shr 32) and 255,
(Length(RawData) shr 24) and 255, (Length(RawData) shr 16) and 255, (Length(RawData) shr 8) and 255, Length(RawData) and 255];
Msg := Msg + RawData;
try
Write(TIdBytes(Msg), Length(Msg));
except
end;
end;
function TWebSocketIOHandlerHelper.ReadString: string;
begin
result := IndyTextEncoding_UTF8.GetString(TIdBytes(ReadBytes));
end;
procedure TWebSocketIOHandlerHelper.WriteString(const str: string);
begin
WriteBytes(TArray<byte>(IndyTextEncoding_UTF8.GetBytes(str)));
end;
end.
|
unit XMLReport;
interface
uses
System.Classes, Xml.xmldom, Xml.XMLIntf, Xml.Win.msxmldom, Xml.XMLDoc;
type
TReportSection = class;
TReportSections = class;
TSectionAttribute = class;
TSectionAttributes = class;
TXMLReport = class(TComponent)
private
fXMLText: TStrings;
fXMLVersion: string;
fXMLEncoding: string;
fXSLFileName: string;
fFileName: string;
fSections: TReportSections;
fUsedXSL: boolean;
fTempPath: string;
function GetXMLReport: TStrings;
procedure SetFileName(const Value: string);
protected
procedure GetChilds(ASections: TReportSections; ANode: IXMLNode);
procedure SaveToFileP(const AFileName: string = ''; const aTempFlag: boolean = false);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure SaveToFile(const AFileName: string = '');
property XMLReport: TStrings read GetXMLReport;
published
property FileName: string read fFileName write SetFileName;
property Sections: TReportSections read fSections write fSections;
property TempPath: string read fTempPath write fTempPath;
property UsedXSL: boolean read fUsedXSL write fUsedXSL;
property XMLVersion: string read fXMLVersion write fXMLVersion;
property XMLEncoding: string read fXMLEncoding write fXMLEncoding;
property XSLFileName: string read fXSLFileName write fXSLFileName;
end;
TReportSection = class(TCollectionItem)
private
fName: string;
fCaption: string;
fAttributes: TSectionAttributes;
fSections: TReportSections;
fShowCaption: boolean;
protected
function GetDisplayName: string; override;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
published
property Caption: string read fCaption write fCaption;
property Name: string read fName write fName;
property Attributes: TSectionAttributes read fAttributes write fAttributes;
property Sections: TReportSections read fSections write fSections;
property ShowCaption: boolean read fShowCaption write fShowCaption;
end;
TReportSections = class(TCollection)
private
fOwner: TPersistent;
fName: string;
function GetItem(Index: Integer): TReportSection;
procedure SetItem(Index: Integer; const Value: TReportSection);
protected
function GetOwner: TPersistent; override;
public
constructor Create(AOwner: TPersistent);
function Add: TReportSection;
function AddItem(Item: TReportSection; Index: Integer): TReportSection;
function Insert(Index: Integer): TReportSection;
function FindByName(const aName: string): TReportSection;
property Items[Index: Integer]: TReportSection read GetItem write SetItem; default;
published
property Name: string read fName write fName;
end;
TSectionAttribute = class(TCollectionItem)
private
fName: string;
fValue: string;
protected
function GetDisplayName: string; override;
public
constructor Create(Collection: TCollection); override;
procedure Assign(Source: TPersistent); override;
published
property Value: string read fValue write fValue;
property Name: string read fName write fName;
end;
TSectionAttributes = class(TCollection)
private
fOwner: TPersistent;
function GetItem(Index: Integer): TSectionAttribute;
procedure SetItem(Index: Integer; const Value: TSectionAttribute);
protected
function GetOwner: TPersistent; override;
public
constructor Create(AOwner: TPersistent);
function Add: TSectionAttribute;
function AddItem(Item: TSectionAttribute; Index: Integer): TSectionAttribute;
function Insert(Index: Integer): TSectionAttribute;
function FindByName(const aName: string): TSectionAttribute;
property Items[Index: Integer]: TSectionAttribute read GetItem write SetItem; default;
end;
implementation
uses
System.SysUtils;
resourcestring
sReportName = 'REPORT';
sReportSectionName = 'ReportSection';
sSectionAttributeName = 'SectionAttribute';
sXMLVersionDefault = '1.0';
sXMLEncodingDefault = 'utf-8';
sXMLProcessingInstrXSL = 'xml-stylesheet';
sXMLProcessingInstrXSLText = 'type = "text/xsl" href="%s"';
sTmpName = 'report.tmp';
{ TXMLReport }
constructor TXMLReport.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
fXMLText := TStringList.Create;
fXMLVersion := sXMLVersionDefault;
fXMLEncoding := sXMLEncodingDefault;
fSections := TReportSections.Create(Self);
fSections.Name := sReportName;
fUsedXSL := True;
fFileName := '';
fXSLFileName := '';
fTempPath := '';
end;
destructor TXMLReport.Destroy;
begin
fSections.Free;
fXMLText.Free;
inherited;
end;
procedure TXMLReport.GetChilds(ASections: TReportSections; ANode: IXMLNode);
var
i, j: integer;
iChildNode: IXMLNode;
begin
for i := 0 to ASections.Count-1 do
begin
iChildNode := ANode.AddChild(ASections[i].Name);
with iChildNode do
begin
if ASections[i].ShowCaption then
Attributes['Caption'] := ASections[i].Caption;
for j := 0 to ASections[i].Attributes.Count-1 do
Attributes[ASections[i].Attributes[j].Name] := ASections[i].Attributes[j].Value;
if ASections[i].Sections.Count > 0 then
GetChilds(ASections[i].Sections, iChildNode);
end;
end;
end;
function TXMLReport.GetXMLReport: TStrings;
begin
fXMLText.Clear;
Result := fXMLText;
SaveToFileP(sTmpName,true);
fXMLText.LoadFromFile(fTempPath+sTmpName);
DeleteFile(fTempPath+sTmpName);
end;
procedure TXMLReport.SaveToFile(const AFileName: string);
begin
SaveToFileP(AFileName);
end;
procedure TXMLReport.SaveToFileP(const AFileName: string; const aTempFlag: boolean);
var
iNode: IXMLNode;
fXMLDoc: TXMLDocument;
begin
fXMLDoc := TXMLDocument.Create(Self);
try
fXMLDoc.Active := true;
fXMLDoc.Encoding := fXMLEncoding;
fXMLDoc.Version := fXMLVersion;
fXMLDoc.Options := fXMLDoc.Options + [doNodeAutoIndent] - [doAutoSave];
if fFileName <> '' then
fXMLDoc.FileName := fFileName;
if (AFileName <> '') and (fFileName <> AFileName) then
fXMLDoc.FileName := AFileName;
//add xslt
if fUsedXSL then
begin
iNode := fXMLDoc.CreateNode(sXMLProcessingInstrXSL, ntProcessingInstr,
format(sXMLProcessingInstrXSLText, [fXSLFileName]));
fXMLDoc.ChildNodes.Add(iNode);
end;
//add body report
iNode := fXMLDoc.AddChild(fSections.Name);
//add sections
GetChilds(fSections,iNode);
//get xml
if not ((csDesigning in ComponentState) or (csDesignInstance in ComponentState)) then
begin
if aTempFlag then
begin
if fTempPath <> '' then
fTempPath := IncludeTrailingPathDelimiter(fTempPath);
fXMLDoc.SaveToFile(fTempPath+sTmpName);
end else
fXMLDoc.SaveToFile();
end;
finally
fXMLDoc.Free;
end;
end;
procedure TXMLReport.SetFileName(const Value: string);
begin
fFileName := Value;
if fXSLFileName = '' then
fXSLFileName := ChangeFileExt(fFileName,'.xsl');
end;
{ TReportSection }
procedure TReportSection.Assign(Source: TPersistent);
begin
if Source is TReportSection then
begin
fName := TReportSection(Source).fName;
fCaption := TReportSection(Source).fCaption;
fShowCaption := TReportSection(Source).fShowCaption;
fAttributes.Assign(TReportSection(Source).fAttributes);
fSections.Assign(TReportSection(Source).fSections);
end
else
inherited Assign(Source);
end;
constructor TReportSection.Create(Collection: TCollection);
begin
inherited Create(Collection);
fName := sReportSectionName + IntToStr(Collection.Count);
fCaption := '';
fAttributes := TSectionAttributes.Create(Self);
fSections := TReportSections.Create(Self);
fShowCaption := True;
end;
destructor TReportSection.Destroy;
begin
fAttributes.Free;
fSections.Free;
inherited;
end;
function TReportSection.GetDisplayName: string;
begin
if Trim(fCaption) <> '' then
Result := fCaption
else if Trim(fName) <> '' then
Result := fName
else
Result := inherited GetDisplayName;
end;
{ TReportSections }
function TReportSections.Add: TReportSection;
begin
Result := AddItem(nil, -1);
end;
function TReportSections.AddItem(Item: TReportSection; Index: Integer): TReportSection;
begin
if Item = nil then
begin
Result := TReportSection.Create(Self);
end
else
begin
Result := Item;
if Assigned(Item) then
begin
Result.Collection := Self;
if Index < Count then
Index := Count - 1;
Result.Index := Index;
end;
end;
end;
constructor TReportSections.Create(AOwner: TPersistent);
begin
fOwner := AOwner;
fName := '';
inherited Create(TReportSection);
end;
function TReportSections.FindByName(const aName: string): TReportSection;
var
i: Integer;
begin
Result := nil;
for i := 0 to Self.Count - 1 do
if AnsiUpperCase(GetItem(i).Name) = AnsiUpperCase(aName) then
Result := GetItem(i);
end;
function TReportSections.GetItem(Index: Integer): TReportSection;
begin
Result := TReportSection(inherited GetItem(Index));
end;
function TReportSections.GetOwner: TPersistent;
begin
Result := fOwner;
end;
function TReportSections.Insert(Index: Integer): TReportSection;
begin
Result := AddItem(nil, Index);
end;
procedure TReportSections.SetItem(Index: Integer; const Value: TReportSection);
begin
TReportSection(Items[Index]).Assign(Value);
end;
{ TSectionAttribute }
procedure TSectionAttribute.Assign(Source: TPersistent);
begin
if Source is TSectionAttribute then
begin
fName := TSectionAttribute(Source).fName;
fValue := TSectionAttribute(Source).fValue;
end
else
inherited Assign(Source);
end;
constructor TSectionAttribute.Create(Collection: TCollection);
begin
inherited Create(Collection);
fName := sSectionAttributeName + IntToStr(Collection.Count);
fValue := '';
end;
function TSectionAttribute.GetDisplayName: string;
begin
if Trim(fName) <> '' then
Result := fName
else
Result := inherited GetDisplayName;
end;
{ TSectionAttributes }
function TSectionAttributes.Add: TSectionAttribute;
begin
Result := AddItem(nil, -1);
end;
function TSectionAttributes.AddItem(Item: TSectionAttribute; Index: Integer): TSectionAttribute;
begin
if Item = nil then
begin
Result := TSectionAttribute.Create(Self);
end
else
begin
Result := Item;
if Assigned(Item) then
begin
Result.Collection := Self;
if Index < Count then
Index := Count - 1;
Result.Index := Index;
end;
end;
end;
constructor TSectionAttributes.Create(AOwner: TPersistent);
begin
fOwner := AOwner;
inherited Create(TSectionAttribute);
end;
function TSectionAttributes.FindByName(const aName: string): TSectionAttribute;
var
i: Integer;
begin
Result := nil;
for i := 0 to Self.Count - 1 do
if AnsiUpperCase(GetItem(i).Name) = AnsiUpperCase(aName) then
Result := GetItem(i);
end;
function TSectionAttributes.GetItem(Index: Integer): TSectionAttribute;
begin
Result := TSectionAttribute(inherited GetItem(Index));
end;
function TSectionAttributes.GetOwner: TPersistent;
begin
Result := fOwner;
end;
function TSectionAttributes.Insert(Index: Integer): TSectionAttribute;
begin
Result := AddItem(nil, Index);
end;
procedure TSectionAttributes.SetItem(Index: Integer; const Value: TSectionAttribute);
begin
TSectionAttribute(Items[Index]).Assign(Value);
end;
end.
|
{******************************************************************************}
{ }
{ WiRL: RESTful Library for Delphi }
{ }
{ Copyright (c) 2015-2021 WiRL Team }
{ }
{ https://github.com/delphi-blocks/WiRL }
{ }
{******************************************************************************}
unit WiRL.Core.JSON;
interface
uses
System.JSON, System.SysUtils, System.Classes, System.Generics.Collections;
type
TJSONAncestor = System.JSON.TJSONAncestor;
TJSONPair = System.JSON.TJSONPair;
TJSONValue = System.JSON.TJSONValue;
TJSONTrue = System.JSON.TJSONTrue;
TJSONFalse = System.JSON.TJSONFalse;
TJSONString = System.JSON.TJSONString;
TJSONNumber = System.JSON.TJSONNumber;
TJSONObject = System.JSON.TJSONObject;
TJSONNull = System.JSON.TJSONNull;
TJSONArray = System.JSON.TJSONArray;
TJSONHelper = class
public
class function Print(AJSONValue: TJSONValue; APretty: Boolean): string; static;
class procedure PrintToWriter(AJSONValue: TJSONValue; AWriter: TTextWriter; APretty: Boolean); overload; static;
class procedure PrintToWriter(const AJSONString: string; AWriter: TTextWriter; APretty: Boolean); overload; static;
class function PrettyPrint(const AJSONString: string): string; static;
class function ToJSON(AJSONValue: TJSONValue): string; static;
class function StringArrayToJsonArray(const values: TArray<string>): string; static;
class procedure JSONCopyFrom(ASource, ADestination: TJSONObject); static;
class function BooleanToTJSON(AValue: Boolean): TJSONValue;
class function DateToJSON(ADate: TDateTime; AInputIsUTC: Boolean = True): string; static;
class function JSONToDate(const ADate: string; AReturnUTC: Boolean = True): TDateTime; static;
end;
implementation
uses
System.DateUtils,
System.Variants,
WiRL.Core.Utils;
{ TJSONHelper }
class function TJSONHelper.BooleanToTJSON(AValue: Boolean): TJSONValue;
begin
if AValue then
Result := TJSONTrue.Create
else
Result := TJSONFalse.Create;
end;
class function TJSONHelper.DateToJSON(ADate: TDateTime; AInputIsUTC: Boolean = True): string;
begin
Result := '';
if ADate <> 0 then
Result := DateToISO8601(ADate, AInputIsUTC);
end;
class function TJSONHelper.JSONToDate(const ADate: string; AReturnUTC: Boolean = True): TDateTime;
begin
Result := 0.0;
if ADate<>'' then
Result := ISO8601ToDate(ADate, AReturnUTC);
end;
class function TJSONHelper.ToJSON(AJSONValue: TJSONValue): string;
var
LBytes: TBytes;
begin
SetLength(LBytes, AJSONValue.ToString.Length * 6);
SetLength(LBytes, AJSONValue.ToBytes(LBytes, 0));
Result := TEncoding.Default.GetString(LBytes);
end;
class function TJSONHelper.StringArrayToJsonArray(const values: TArray<string>): string;
var
LArray: TJSONArray;
LIndex: Integer;
begin
LArray := TJSONArray.Create;
try
for LIndex := 0 to High(values) do
LArray.Add(values[LIndex]);
Result := ToJSON(LArray);
finally
LArray.Free;
end;
end;
class procedure TJSONHelper.JSONCopyFrom(ASource, ADestination: TJSONObject);
var
LPairSrc, LPairDst: TJSONPair;
begin
for LPairSrc in ASource do
begin
LPairDst := ADestination.Get(LPairSrc.JsonString.Value);
if Assigned(LPairDst) then
// Replace the JSON Value (the previous is freed by the TJSONPair object)
LPairDst.JsonValue := TJSONValue(LPairSrc.JsonValue.Clone)
else
ADestination.AddPair(TJSONPair(LPairSrc.Clone));
end;
end;
class function TJSONHelper.PrettyPrint(const AJSONString: string): string;
var
LWriter: TStringWriter;
begin
LWriter := TStringWriter.Create;
try
PrintToWriter(AJSONString, LWriter, True);
Result := LWriter.ToString;
finally
LWriter.Free;
end;
end;
class function TJSONHelper.Print(AJSONValue: TJSONValue; APretty: Boolean): string;
var
LWriter: TStringWriter;
begin
LWriter := TStringWriter.Create;
try
PrintToWriter(AJSONValue, LWriter, APretty);
Result := LWriter.ToString;
finally
LWriter.Free;
end;
end;
class procedure TJSONHelper.PrintToWriter(AJSONValue: TJSONValue;
AWriter: TTextWriter; APretty: Boolean);
begin
PrintToWriter(AJSONValue.ToJSON, AWriter, APretty);
end;
class procedure TJSONHelper.PrintToWriter(const AJSONString: string; AWriter:
TTextWriter; APretty: Boolean);
var
LChar: Char;
LOffset: Integer;
LIndex: Integer;
LOutsideString: Boolean;
function Spaces(AOffset: Integer): string;
begin
Result := StringOfChar(#32, AOffset * 2);
end;
begin
if not APretty then
begin
AWriter.Write(AJSONString);
Exit;
end;
LOffset := 0;
LOutsideString := True;
for LIndex := 0 to Length(AJSONString) - 1 do
begin
LChar := AJSONString.Chars[LIndex];
if LChar = '"' then
LOutsideString := not LOutsideString;
if LOutsideString and (LChar = '{') then
begin
Inc(LOffset);
AWriter.Write(LChar);
AWriter.Write(sLineBreak);
AWriter.Write(Spaces(LOffset));
end
else if LOutsideString and (LChar = '}') then
begin
Dec(LOffset);
AWriter.Write(sLineBreak);
AWriter.Write(Spaces(LOffset));
AWriter.Write(LChar);
end
else if LOutsideString and (LChar = ',') then
begin
AWriter.Write(LChar);
AWriter.Write(sLineBreak);
AWriter.Write(Spaces(LOffset));
end
else if LOutsideString and (LChar = '[') then
begin
Inc(LOffset);
AWriter.Write(LChar);
AWriter.Write(sLineBreak);
AWriter.Write(Spaces(LOffset));
end
else if LOutsideString and (LChar = ']') then
begin
Dec(LOffset);
AWriter.Write(sLineBreak);
AWriter.Write(Spaces(LOffset));
AWriter.Write(LChar);
end
else if LOutsideString and (LChar = ':') then
begin
AWriter.Write(LChar);
AWriter.Write(' ');
end
else
AWriter.Write(LChar);
end;
end;
end.
|
unit Fornecedor.Controller;
interface
uses Fornecedor.Controller.Interf, Fornecedor.Model.Interf,
TPAGFORNECEDOR.Entidade.Model, System.SysUtils;
type
TFornecedorController = class(TInterfacedObject, IFornecedorController)
private
FFornecedorModel: IFornecedorModel;
FRegistro: TTPAGFORNECEDOR;
public
constructor Create;
destructor Destroy; override;
class function New: IFornecedorController;
function incluir: IFornecedorOperacaoIncluirController;
function alterar: IFornecedorOperacaoAlterarController;
function excluir: IFornecedorOperacaoExcluirController;
function duplicar: IFornecedorOperacaoDuplicarController;
function localizar(AValue: string): IFornecedorController;
function localizarPeloCNPJ(AValue: string): IFornecedorController;
function idFornecedor: string;
function nomeFantasia: string;
function cnpj: string;
function ie: string;
function telefone: string;
function email: string;
end;
implementation
{ TFornecedorController }
uses FacadeModel, FornecedorOperacaoIncluir.Controller,
FornecedorOperacaoAlterar.Controller, FornecedorOperacaoDuplicar.Controller,
FornecedorOperacaoExcluir.Controller;
function TFornecedorController.alterar: IFornecedorOperacaoAlterarController;
begin
Result := TFornecedorOperacaoAlterarController.New
.fornecedorModel(FFornecedorModel)
.fornecedorSelecionado(FRegistro)
end;
function TFornecedorController.cnpj: string;
begin
Result := FRegistro.cnpj;
end;
constructor TFornecedorController.Create;
begin
FFornecedorModel := TFacadeModel.New.ModulosFacadeModel.pagarFactoryModel.
Fornecedor;
end;
destructor TFornecedorController.Destroy;
begin
inherited;
end;
function TFornecedorController.duplicar: IFornecedorOperacaoDuplicarController;
begin
Result := TFornecedorOperacaoDuplicarController.New
.fornecedorModel(FFornecedorModel)
end;
function TFornecedorController.email: string;
begin
Result := FRegistro.email;
end;
function TFornecedorController.excluir: IFornecedorOperacaoExcluirController;
begin
Result := TFornecedorOperacaoExcluirController.New
.fornecedorModel(FFornecedorModel)
.fornecedorSelecionado(FRegistro)
end;
function TFornecedorController.idFornecedor: string;
begin
Result := IntToStr(FRegistro.idFornecedor);
end;
function TFornecedorController.ie: string;
begin
Result := FRegistro.ie;
end;
function TFornecedorController.incluir: IFornecedorOperacaoIncluirController;
begin
Result := TFornecedorOperacaoIncluirController.New
.fornecedorModel(FFornecedorModel)
end;
function TFornecedorController.localizar(AValue: string): IFornecedorController;
begin
Result := Self;
FRegistro := FFornecedorModel
.DAO
.FindWhere('CODIGO=' + QuotedStr(AValue),'NOMEFANTASIA')
.Items[0];
end;
function TFornecedorController.localizarPeloCNPJ(AValue: string): IFornecedorController;
begin
Result := Self;
FRegistro := FFornecedorModel
.DAO
.FindWhere('CNPJ=' + QuotedStr(AValue),'NOMEFANTASIA')
.Items[0];
end;
class function TFornecedorController.New: IFornecedorController;
begin
Result := Self.Create;
end;
function TFornecedorController.nomeFantasia: string;
begin
Result := FRegistro.nomeFantasia;
end;
function TFornecedorController.telefone: string;
begin
Result := FRegistro.telefone;
end;
end.
|
unit uFuncoes;
interface
uses
FMX.Edit, FMX.Forms, FMX.Objects, IdHTTP, IdFTPCommon, IdTCPConnection, IdTCPClient, IdFTP, FMX.DateTimeCtrls, GuiaAlvo.Controller.DataModuleDados, Guia.Controle;
function preencheCEP(vCep : String; vForm: TForm) : Boolean;
procedure pLoadImage(pImage : TImage; pImagem : String);
procedure ViewSenha(AImage : TImage; AView : Boolean);
function SendSMS(vCelular, vMsg: String): Boolean;
function ApenasNumeros(S: String): String;
function ValidaEMail(const Value: string): Boolean;
procedure Loading(AMsg : String; AExibe : Boolean = True);
function GeraCodigo : String;
function ValidarCelular(ACel : String) : Boolean;
function StrToBoolValue(AValue, ATrue, AFalse : String) : Boolean;
function BoolToStrValue(AValue : Boolean) : String;
procedure NextField(Key : Word; ANext : TEdit);
procedure IsImageChecked(AChkImage : TImage) ;
procedure ConectaFTP(gFTP: TIdFtp);
procedure ReplicaHoras(Sender: TObject);
function PreencheHoras : Boolean;
function SizeImgPx(fImagem : String) : String;
function RemoveAcento(const pText: string): string;
function ValidaHoras(AForm : TForm) : Boolean;
function geraHoraBD(ASemana : String; AForm : TForm) : String;
const
fIconViewSenha : String = 'ViewSenha';
fIconUnViewSenha : String = 'UnViewSenha';
smSemana : Array[1..7] of String = ('Seg','Ter','Qua','Qui','Sex','Sab','Dom');
smStatusHr : Array[1..5] of String = ('edtAbre','edtPara','edtVolta','edtFecha','chkFechado');
ASem : Array [1..6] of String = ('Ter','Qua','Qui','Sex','Sab','Dom');
implementation
uses
System.Classes, System.Types, System.SysUtils, FMX.StdCtrls, FMX.Ani,
System.UITypes, FMX.Graphics, GuiaAlvo.View.Principal;
function geraHoraBD(ASemana : String; AForm : TForm) : String;
var
i : Integer;
ARes : String;
begin
for i := 1 to 4 do
ARes := ARes + FormatDateTime('hh:mm', TTimeEdit(AForm.FindComponent(smStatusHr[i] + ASemana)).Time);
ARes := ARes + TImage(AForm.FindComponent(smStatusHr[5] + ASemana)).Tag.ToString;
Result := ARes;
end;
function RemoveAcento(const pText: string): string;
type
USAscii20127 = type AnsiString(20127);
begin
Result := String(USAscii20127(pText));
end;
procedure SeparaHoras(AValor, pSem : String);
var
i, j, AIndex : Integer;
begin
AIndex := 1;
for i := 1 to 5 do //Conta os Campos
begin
if i = 5 then //Verifica se Ú o ultimo valor
begin
if Copy(AValor,Length(AValor),1) = '0' then
begin
TImage(frmGestorClient.FindComponent(smStatusHr[i] + pSem)).Bitmap := frmGestorClient.imgchbUnchecked.Bitmap;
TImage(frmGestorClient.FindComponent(smStatusHr[i] + pSem)).Tag := 0;
end
else
begin
TImage(frmGestorClient.FindComponent(smStatusHr[i] + pSem)).Bitmap := frmGestorClient.imgchbChecked.Bitmap;
TImage(frmGestorClient.FindComponent(smStatusHr[i] + pSem)).Tag := 1;
end;
end
else
begin
TTimeEdit(frmGestorClient.FindComponent(smStatusHr[i] + pSem)).Time := StrToTime(Copy(AValor, AIndex, 5));
AIndex := AIndex + 5;
end;
end;
end;
function PreencheHoras : Boolean;
var
i : Integer;
ACampo, AHora : String;
ARes : Integer;
begin
ARes := 0;
ACampo := 'HR%sCOM';
for i := 1 to 7 do
begin
AHora := dmGeralClient.memFichaComercio.FieldByName('HR' + UpperCase(smSemana[i]) + 'COM').AsString;
if Copy(AHora,1,Length(AHora) - 1) = '00:0000:0000:0000:00' then
ARes := ARes + 1;
SeparaHoras(dmGeralClient.memFichaComercio.FieldByName('HR' + UpperCase(smSemana[i]) + 'COM').AsString, smSemana[i]);
end;
if ARes = 7 then
Result := False else
Result := True;
end;
function SizeImgPx(fImagem : String) : String;
var
vImagem : TBitmap;
vLargura, vAltura : Integer;
begin
vImagem := TBitmap.Create();
vImagem.LoadFromFile(fImagem);
vAltura := vImagem.Height;
vLargura := vImagem.Width;
Result := vLargura.ToString+'x'+vAltura.ToString;
end;
procedure ConectaFTP(gFTP: TIdFtp);
begin
if not gFTP.Connected then
begin
gFTP.Disconnect;
gFTP.host := ctrHOSTFTP; // Enderešo do servidor FTP
gFTP.port := ctrPORTAFTP;
gFTP.username := ctrUSUARIOFTP; // Parametro nome usuario servidor FTP
gFTP.password := ctrSENHAFTP; // Parametro senha servidor FTP
gFTP.Connect();
AssErt(gFTP.Connected);
end;
end;
procedure ReplicaHoras(Sender: TObject);
var
i : Integer;
ACampo : String;
AValor : TTime;
begin
ACampo := Copy(TSpeedButton(Sender).Name,5,Length(TSpeedButton(Sender).Name));
AValor := TTimeEdit(frmGestorClient.FindComponent('edt' + ACampo + 'Seg')).Time;
for i := 1 to 6 do
TTimeEdit(frmGestorClient.FindComponent('edt' + ACampo + ASem[i])).Time := AValor;
end;
function ValidaHoras(AForm : TForm) : Boolean;
var
i, j : Integer;
ACampo : String;
AAbre, APara, AVolta, AFecha : TTime;
AFechado : Integer;
ARes : Boolean;
begin
ARes := True;
ACampo := 'HR%sCOM';
for i := 1 to 7 do
begin
AAbre := TTimeEdit(AForm.FindComponent(smStatusHr[1] + smSemana[i])).Time;
APara := TTimeEdit(AForm.FindComponent(smStatusHr[2] + smSemana[i])).Time;
AVolta := TTimeEdit(AForm.FindComponent(smStatusHr[3] + smSemana[i])).Time;
AFecha := TTimeEdit(AForm.FindComponent(smStatusHr[4] + smSemana[i])).Time;
AFechado := TImage(AForm.FindComponent(smStatusHr[5] + smSemana[i])).Tag;
if AFechado = 0 then
if (APara < AAbre) or (AVolta < APara) then
ARes := False;
end;
Result := ARes;
end;
procedure IsImageChecked(AChkImage : TImage);
begin
case AChkImage.Tag of
0 : begin
AChkImage.Tag := 1;
AChkimage.Bitmap := frmGestorClient.imgchbChecked.Bitmap;
end;
1 : begin
AChkImage.Tag := 0;
AChkimage.Bitmap := frmGestorClient.imgchbUnchecked.Bitmap;
end;
end;
end;
procedure NextField(Key : Word; ANext : TEdit);
begin
if Key = vkReturn then ANext.SetFocus;
end;
function StrToBoolValue(AValue, ATrue, AFalse : String) : Boolean;
begin
If AValue = ATrue then Result := True;
If AValue = AFalse then Result := False;
end;
function BoolToStrValue(AValue : Boolean) : String;
begin
case AValue of
True : Result := 'T';
False : Result := 'F';
end;
end;
function ValidarCelular(ACel : String) : Boolean;
var
AAuxCel : String;
begin
AAuxCel := ApenasNumeros(ACel);
if Length(AAuxCel) = 11 then
AAuxCel := Copy(AAuxCel,3,Length(AAuxCel));
if (Length(AAuxCel) <> 9) or (Length(AAuxCel) <> 11) then
begin
Result := False;
Exit;
end
else
begin
if Copy(AAuxCel,1,1) > '5' then
Result := True else
Result := False;
end;
end;
function GeraCodigo : String;
begin
Randomize;
Result := FormatFloat('000000',Random(999999));
end;
procedure Loading(AMsg : String; AExibe : Boolean = True);
begin
TLabel(Screen.ActiveForm.FindComponent('lblMsgLoading')).Text := AMsg;
TFloatAnimation(Screen.ActiveForm.FindComponent('faArcAzul')).Enabled := AExibe;
TFloatAnimation(Screen.ActiveForm.FindComponent('faArcCinza')).Enabled := AExibe;
TRectangle(Screen.ActiveForm.FindComponent('recmodal')).Visible := AExibe;
TRectangle(Screen.ActiveForm.FindComponent('recloading')).Visible := AExibe;
end;
function ValidaEmail(const Value: string): Boolean;
function CheckAllowed(const s: string): Boolean;
var
i: Integer;
begin
Result := False;
for i := 1 to Length(s) do
if not(s[i] in ['a' .. 'z', 'A' .. 'Z', '0' .. '9', '_', '-', '.']) then
Exit;
Result := true;
end;
var
i: Integer;
NamePart, ServerPart: string;
begin
Result := False;
i := Pos('@', Value);
if i = 0 then
Exit;
NamePart := Copy(Value, 1, i - 1);
ServerPart := Copy(Value, i + 1, Length(Value));
if (Length(NamePart) = 0) or ((Length(ServerPart) < 5)) then
Exit;
i := Pos('.', ServerPart);
if (i = 0) or (i > (Length(ServerPart) - 2)) then
Exit;
Result := CheckAllowed(NamePart) and CheckAllowed(ServerPart);
end;
function ApenasNumeros(S: String): String;
var
vText: PChar;
begin
vText := PChar(S);
Result := '';
while (vText^ <> #0) do
begin
{$IFDEF UNICODE}
if CharInSet(vText^, ['0' .. '9']) then
{$ELSE}
if vText^ in ['0' .. '9'] then
{$ENDIF}
Result := Result + vText^;
Inc(vText);
end;
end;
function SendSMS(vCelular, vMsg: String): Boolean;
var
vLista: TStringList;
vIdHTTP: TIdHTTP;
begin
Result := True;
vLista := TStringList.Create;
vIdHTTP := TIdHTTP.Create(nil);
Try
Try
vLista.Add('metodo=envio');
vLista.Add('usuario=souza@vikmar.com.br');
vLista.Add('senha=Mjs19770');
vLista.Add('celular=' + vCelular);
vLista.Add('mensagem=' + vMsg);
vIdHTTP.Post
('http://www.iagentesms.com.br/webservices/http.php', vLista);
Except
Result := False;
end;
Finally
FreeAndNil(vIdHTTP);
end;
end;
function preencheCEP(vCep : String; vForm: TForm) : Boolean;
begin
dmGeralClient.ConsultaCep(vCep);
if dmGeralClient.fdmemCep.RecordCount > 0 then
begin
TEdit(vForm.FindComponent('edtLogradouro')).Text := dmGeralClient.fdmemCeplogradouro.Text;
TEdit(vForm.FindComponent('edtBairro')).Text := dmGeralClient.fdmemCepbairro.Text;
TEdit(vForm.FindComponent('edtCidade')).Text := dmGeralClient.fdmemCeplocalidade.Text;
TEdit(vForm.FindComponent('edtUF')).Text := dmGeralClient.fdmemCepuf.Text;
Result := True;
end
else
begin
Result := False;
end;
end;
procedure ViewSenha(AImage : TImage; AView : Boolean);
begin
case AView of
True : pLoadImage(AImage, fIconViewSenha);
False : pLoadImage(AImage, fIconUnViewSenha);
end;
end;
procedure pLoadImage(pImage : TImage; pImagem : String);
var
InStream: TResourceStream;
begin
InStream := TResourceStream.Create(HInstance, pImagem, RT_RCDATA);
try
pImage.Bitmap.LoadFromStream(InStream);
finally
InStream.Free;
end;
end;
end.
|
unit CCJSO_HeaderHistory;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,
CCJSO_DM, ExtCtrls, ActnList, ComCtrls, ToolWin, StdCtrls;
type
TfrmCCJSO_HeaderHistory = class(TForm)
pnlHeader: TPanel;
pnlControl: TPanel;
pnlControl_Tool: TPanel;
pnlControl_Show: TPanel;
pnlRecord: TPanel;
aList: TActionList;
aExit: TAction;
rbarControl: TToolBar;
tbtnControl_Exit: TToolButton;
lblSActionName: TLabel;
lblSActionCode: TLabel;
lblSUser: TLabel;
lblSBeginDate: TLabel;
lblSEndDate: TLabel;
lblSActionFoundation: TLabel;
lblSDriver: TLabel;
lblIAllowBeOpen: TLabel;
lblWaitingTimeMinute: TLabel;
lblSNOTE: TLabel;
edSActionName: TEdit;
edSActionCode: TEdit;
edSUser: TEdit;
edSBeginDate: TEdit;
edSEndDate: TEdit;
edSActionFoundation: TEdit;
edSDriver: TEdit;
edIAllowBeOpen: TEdit;
edWaitingTimeMinute: TEdit;
edSNOTE: TMemo;
procedure FormCreate(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure aExitExecute(Sender: TObject);
private
{ Private declarations }
ISignActive : integer;
RecHist : TJSORecHist;
procedure ShowGets;
procedure InitFields;
public
{ Public declarations }
procedure SetRec(Parm : TJSORecHist);
end;
var
frmCCJSO_HeaderHistory: TfrmCCJSO_HeaderHistory;
implementation
uses UCCenterJournalNetZkz;
{$R *.dfm}
procedure TfrmCCJSO_HeaderHistory.FormCreate(Sender: TObject);
begin
ISignActive := 0;
end;
procedure TfrmCCJSO_HeaderHistory.FormActivate(Sender: TObject);
begin
if ISignActive = 0 then begin
{ Иконка формы }
FCCenterJournalNetZkz.imgMain.GetIcon(367,self.Icon);
pnlHeader.Caption := ' Заказ № ' + IntToStr(RecHist.NOrder);
InitFields;
{ Форма активна }
ISignActive := 1;
ShowGets;
end;
end;
procedure TfrmCCJSO_HeaderHistory.ShowGets;
begin
if ISignActive = 1 then begin
end;
end;
procedure TfrmCCJSO_HeaderHistory.SetRec(Parm : TJSORecHist); begin RecHist := Parm; end;
procedure TfrmCCJSO_HeaderHistory.InitFields;
begin
edSActionCode.Text := RecHist.SActionCode;
edSActionName.Text := RecHist.SActionName;
edSUser.Text := RecHist.SUser;
edSBeginDate.Text := RecHist.SBeginDate;
edSEndDate.Text := RecHist.SEndDate;
edSActionFoundation.Text := RecHist.SActionFoundation;
edSDriver.Text := RecHist.SDriver;
edSNOTE.Text := RecHist.SNOTE;
edIAllowBeOpen.Text := IntToStr(RecHist.IAllowBeOpen);
edWaitingTimeMinute.Text := IntToStr(RecHist.WaitingTimeMinute);
end;
procedure TfrmCCJSO_HeaderHistory.aExitExecute(Sender: TObject);
begin
Self.Close;
end;
end.
|
unit uFaceDetection;
interface
uses
System.Types,
System.SysUtils,
System.Classes,
System.SyncObjs,
Winapi.Windows,
Vcl.Graphics,
OpenCV.Core,
OpenCV.ImgProc,
OpenCV.Utils,
OpenCV.ObjDetect,
OpenCV.Legacy,
UnitDBDeclare,
uRuntime,
uMemory,
u2DUtils,
uSettings;
const
CascadesDirectoryMask = 'Cascades';
type
TFaceDetectionResultItem = class
private
FData: TClonableObject;
procedure SetData(const Value: TClonableObject);
function GetImageSize: TSize;
function GetRect: TRect;
procedure SetRect(const Value: TRect);
public
X: Integer;
Y: Integer;
Width: Integer;
Height: Integer;
ImageWidth: Integer;
ImageHeight: Integer;
Page: Integer;
function Copy: TFaceDetectionResultItem;
constructor Create;
destructor Destroy; override;
procedure RotateLeft;
procedure RotateRight;
function EqualsTo(Item: TFaceDetectionResultItem): Boolean;
function InTheSameArea80(RI: TFaceDetectionResultItem): Boolean;
property Data: TClonableObject read FData write SetData;
property ImageSize: TSize read GetImageSize;
property Rect: TRect read GetRect write SetRect;
end;
TFaceDetectionResult = class
private
FList: TList;
FPage: Integer;
FSize: Int64;
FDateModified: TDateTime;
FPersistanceFileName: string;
FTagEx: string;
function GetItem(Index: Integer): TFaceDetectionResultItem;
function GetCount: Integer;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure Assign(Source: TFaceDetectionResult);
procedure DeleteAt(I: Integer);
procedure Remove(Item: TFaceDetectionResultItem);
function AddFace(X, Y, Width, Height, ImageWidth, ImageHeight, Page: Integer): TFaceDetectionResultItem;
procedure Add(Face: TFaceDetectionResultItem);
procedure RotateLeft;
procedure RotateRight;
property Items[Index: Integer]: TFaceDetectionResultItem read GetItem; default;
property Count: Integer read GetCount;
property Page: Integer read FPage write FPage;
property Size: Int64 read FSize write FSize;
property DateModified: TDateTime read FDateModified write FDateModified;
property PersistanceFileName: string read FPersistanceFileName write FPersistanceFileName;
property TagEx: string read FTagEx write FTagEx;
end;
TCascadeData = class
FileName: string;
Cascade: PCvHaarClassifierCascade;
end;
TFaceDetectionManager = class
private
FSync: TCriticalSection;
FCascades: TList;
procedure Init;
function GetIsActive: Boolean;
function GetCascadeByFileName(FileName: string): PCvHaarClassifierCascade;
public
procedure FacesDetection(Bitmap: TBitmap; Page: Integer; var Faces: TFaceDetectionResult; Method: string); overload;
procedure FacesDetection(Image: pIplImage; Page: Integer; var Faces: TFaceDetectionResult; Method: string); overload;
constructor Create;
destructor Destroy; override;
property IsActive: Boolean read GetIsActive;
property Cascades[FileName: string]: PCvHaarClassifierCascade read GetCascadeByFileName;
end;
function FaceDetectionManager: TFaceDetectionManager;
function PxMultiply(P: TPoint; OriginalSize: TSize; Image: TBitmap): TPoint; overload;
function PxMultiply(P: TPoint; Image: TBitmap; OriginalSize: TSize): TPoint; overload;
function PxMultiply(P: TPoint; FromSize, ToSize: TSize): TPoint; overload;
implementation
var
FManager: TFaceDetectionManager = nil;
GlobalSync: TCriticalSection = nil;
function FaceDetectionManager: TFaceDetectionManager;
begin
GlobalSync.Enter;
try
if FManager = nil then
FManager := TFaceDetectionManager.Create;
Result := FManager;
finally
GlobalSync.Leave;
end;
end;
procedure InitCVLib;
begin
LoadOpenCV;
end;
{ TFaceDetectionResult }
procedure TFaceDetectionResult.Add(Face: TFaceDetectionResultItem);
begin
FList.Add(Face);
end;
function TFaceDetectionResult.AddFace(X, Y, Width, Height, ImageWidth, ImageHeight, Page: Integer): TFaceDetectionResultItem;
begin
Result := TFaceDetectionResultItem.Create;
FList.Add(Result);
Result.X := X;
Result.Y := Y;
Result.Width := Width;
Result.Height := Height;
Result.ImageWidth := ImageWidth;
Result.ImageHeight := ImageHeight;
Result.Page := Page;
end;
procedure TFaceDetectionResult.Assign(Source: TFaceDetectionResult);
var
I: Integer;
begin
Clear;
FPage := Source.Page;
FPersistanceFileName := Source.FPersistanceFileName;
for I := 0 to Source.Count - 1 do
FList.Add(Source[I].Copy);
end;
procedure TFaceDetectionResult.Clear;
begin
FreeList(FList, False);
end;
constructor TFaceDetectionResult.Create;
begin
FPersistanceFileName := '';
FList := TList.Create;
end;
procedure TFaceDetectionResult.DeleteAt(I: Integer);
begin
Items[I].Free;
FList.Delete(I);
end;
destructor TFaceDetectionResult.Destroy;
begin
FreeList(FList);
inherited;
end;
function TFaceDetectionResult.GetCount: Integer;
begin
Result := FList.Count;
end;
function TFaceDetectionResult.GetItem(Index: Integer): TFaceDetectionResultItem;
begin
Result := FList[Index];
end;
procedure TFaceDetectionResult.Remove(Item: TFaceDetectionResultItem);
begin
FList.Remove(Item);
F(Item);
end;
procedure TFaceDetectionResult.RotateLeft;
var
I: Integer;
begin
for I := 0 to FList.Count - 1 do
TFaceDetectionResultItem(FList[I]).RotateLeft;
end;
procedure TFaceDetectionResult.RotateRight;
var
I: Integer;
begin
for I := 0 to FList.Count - 1 do
TFaceDetectionResultItem(FList[I]).RotateRight;
end;
{ TFaceDetectionManager }
constructor TFaceDetectionManager.Create;
begin
FSync := TCriticalSection.Create;
FCascades := TList.Create;
Init;
end;
destructor TFaceDetectionManager.Destroy;
begin
F(FSync);
FreeList(FCascades);
inherited;
end;
procedure TFaceDetectionManager.Init;
begin
InitCVLib;
end;
procedure TFaceDetectionManager.FacesDetection(Image: pIplImage; Page: Integer; var Faces: TFaceDetectionResult; Method: string);
var
StorageType: Integer;
Storage: PCvMemStorage;
I, J: LongInt;
ImSize, MaxSize: TCvSize;
R: PCvRect;
FacesSeq: PCvSeq;
RctIn, RctOut: TRect;
FCascadeFaces: PCvHaarClassifierCascade;
GrayImage: pIplImage;
begin
GrayImage := cvCreateImage(CvSize(Image.width, Image.height), image.depth, 1);
try
cvCvtColor(Image, GrayImage, CV_BGR2GRAY);
FCascadeFaces := Cascades[Method];
if FCascadeFaces = nil then
Exit;
FSync.Enter;
try
StorageType := 0;
Storage := CvCreateMemStorage(StorageType);
//* detect faces */
ImSize := FCascadeFaces.Orig_window_size;
MaxSize.width := Image.Width;
MaxSize.height := Image.Height;
FacesSeq := cvHaarDetectObjects(GrayImage, FCascadeFaces, Storage, 1.2, 2, CV_HAAR_DO_CANNY_PRUNING, ImSize, MaxSize);
if (FacesSeq = nil) or (FacesSeq.total = 0) then
Exit;
for I := 0 to FacesSeq.total - 1 do
begin
R := PCvRect(CvGetSeqElem(FacesSeq, I));
Faces.AddFace(R.X, R.Y, R.Width, R.Height, Image.Width, Image.Height, Page);
end;
for I := Faces.Count - 1 downto 0 do
begin
for J := Faces.Count - 1 downto 0 do
if I <> J then
begin
RctIn := Rect(Faces[I].X, Faces[I].Y, Faces[I].X + Faces[I].Width, Faces[I].Y + Faces[I].Height);
RctOut := Rect(Faces[J].X, Faces[J].Y, Faces[J].X + Faces[J].Width, Faces[J].Y + Faces[J].Height);
if RectInRectPercent(RctOut, RctIn) > 25 then
begin
Faces.DeleteAt(I);
Break;
end;
end;
end;
Faces.FPage := Page;
finally
FSync.Leave;
end;
finally
cvReleaseImage(GrayImage);
end;
end;
procedure TFaceDetectionManager.FacesDetection(Bitmap: TBitmap; Page: Integer; var Faces: TFaceDetectionResult; Method: string);
var
Img: PIplImage;
ImSize: TCvSize;
begin
ImSize.Width := Bitmap.Width;
ImSize.Height := Bitmap.Height;
Img := CvCreateImage(ImSize, 8, 3);
try
Bitmap2IplImage(Img, Bitmap);
FacesDetection(Img, Page, Faces, Method);
finally
cvResetImageROI(img);
end;
end;
function TFaceDetectionManager.GetCascadeByFileName(
FileName: string): PCvHaarClassifierCascade;
var
I: Integer;
FaceDetectionSeqFileName: string;
CD: TCascadeData;
begin
Result := nil;
for I := 0 to FCascades.Count - 1 do
begin
if TCascadeData(FCascades[I]).FileName = FileName then
begin
Result := TCascadeData(FCascades[I]).Cascade;
Exit;
end;
end;
if LoadOpenCV then
begin
FaceDetectionSeqFileName := ExtractFilePath(ParamStr(0)) + CascadesDirectoryMask + '\' + FileName;
CD := TCascadeData.Create;
FCascades.Add(CD);
CD.FileName := FileName;
CD.Cascade := CvLoad(PAnsiChar(AnsiString(FaceDetectionSeqFileName)), nil, nil, nil);
Result := CD.Cascade;
end;
end;
function TFaceDetectionManager.GetIsActive: Boolean;
begin
Result := (HasOpenCV or FolderView) and AppSettings.Readbool('Options', 'ViewerFaceDetection', True);
end;
{ TFaceDetectionResultItem }
function TFaceDetectionResultItem.Copy: TFaceDetectionResultItem;
begin
Result := TFaceDetectionResultItem.Create;
Result.X := X;
Result.Y := Y;
Result.Width := Width;
Result.Height := Height;
Result.ImageWidth := ImageWidth;
Result.ImageHeight := ImageHeight;
Result.Page := Page;
if Data <> nil then
Result.Data := Data.Clone;
end;
constructor TFaceDetectionResultItem.Create;
begin
FData := nil;
X := 0;
Y := 0;
Width := 0;
Height := 0;
end;
destructor TFaceDetectionResultItem.Destroy;
begin
F(FData);
inherited;
end;
function TFaceDetectionResultItem.EqualsTo(Item: TFaceDetectionResultItem): Boolean;
begin
Result := (X = Item.X) and (Y = Item.Y) and (Width = Item.Width) and (Height = Item.Height) and (ImageWidth = Item.ImageWidth) and (ImageHeight = Item.ImageHeight) and (Page = Item.Page);
end;
function TFaceDetectionResultItem.GetImageSize: TSize;
begin
Result.cx := ImageWidth;
Result.cy := ImageHeight;
end;
procedure TFaceDetectionResultItem.RotateRight;
var
NW, NH, NImageW, NImageH, NX, NY: Integer;
begin
NImageH := ImageWidth;
NImageW := ImageHeight;
NW := Height;
NH := Width;
NX := ImageHeight - Y - Height;
NY := X;
ImageWidth := NImageW;
ImageHeight := NImageH;
Width := NW;
Height := NH;
X := NX;
Y := NY;
end;
procedure TFaceDetectionResultItem.RotateLeft;
var
NW, NH, NImageW, NImageH, NX, NY: Integer;
begin
NImageH := ImageWidth;
NImageW := ImageHeight;
NW := Height;
NH := Width;
NX := Y;
NY := ImageWidth - X - Width;
ImageWidth := NImageW;
ImageHeight := NImageH;
Width := NW;
Height := NH;
X := NX;
Y := NY;
end;
function TFaceDetectionResultItem.GetRect: TRect;
begin
Result := System.Classes.Rect(X, Y, X + Width, Y + Height);
end;
function TFaceDetectionResultItem.InTheSameArea80(
RI: TFaceDetectionResultItem): Boolean;
var
RA, RF: TRect;
begin
RA.Left := Round(Self.X * 1000 / Self.ImageWidth);
RA.Top := Round(Self.Y * 1000 / Self.ImageHeight);
RA.Right := Round((Self.X + Self.Width) * 1000 / Self.ImageWidth);
RA.Bottom := Round((Self.Y + Self.Height) * 1000 / Self.ImageHeight);
RF.Left := Round(RI.X * 1000 / RI.ImageWidth);
RF.Top := Round(RI.Y * 1000 / RI.ImageHeight);
RF.Right := Round((RI.X + RI.Width) * 1000 / RI.ImageWidth);
RF.Bottom := Round((RI.Y + RI.Height) * 1000 / RI.ImageHeight);
Result := RectIntersectWithRectPercent(RA, RF) > 80;
end;
procedure TFaceDetectionResultItem.SetData(const Value: TClonableObject);
begin
F(FData);
FData := Value;
end;
procedure TFaceDetectionResultItem.SetRect(const Value: TRect);
begin
X := Value.Left;
Y := Value.Top;
Width := Value.Right - Value.Left;
Height := Value.Bottom - Value.Top;
end;
//functions
function PxMultiply(P: TPoint; FromSize, ToSize: TSize): TPoint; overload;
begin
Result := P;
if (FromSize.cx <> 0) and (FromSize.cy <> 0) then
begin
Result.X := Round(P.X * ToSize.Width / FromSize.cx);
Result.Y := Round(P.Y * ToSize.Height / FromSize.cy);
end;
end;
function PxMultiply(P: TPoint; OriginalSize: TSize; Image: TBitmap): TPoint; overload;
begin
Result := P;
if (OriginalSize.cx <> 0) and (OriginalSize.cy <> 0) then
begin
Result.X := Round(P.X * Image.Width / OriginalSize.cx);
Result.Y := Round(P.Y * Image.Height / OriginalSize.cy);
end;
end;
function PxMultiply(P: TPoint; Image: TBitmap; OriginalSize: TSize): TPoint; overload;
begin
Result := P;
if (Image.Width <> 0) and (Image.Height <> 0) then
begin
Result.X := Round(P.X * OriginalSize.cx / Image.Width);
Result.Y := Round(P.Y * OriginalSize.cy / Image.Height);
end;
end;
initialization
GlobalSync := TCriticalSection.Create;
finalization
F(FManager);
F(GlobalSync);
end.
|
//------------------------------------------------------------------------------
//Database UNIT
//------------------------------------------------------------------------------
// What it does-
// This is the base database class, which all other database implementations
// are derived.
//
// Changes -
// February 1st, 2008
//
//------------------------------------------------------------------------------
unit Database;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
{RTL/VCL}
{Project}
DatabaseOptions,
AccountQueries,
CharacterQueries,
FriendQueries,
MobQueries,
MapQueries,
MailQueries,
ItemQueries,
CharacterConstantQueries,
{3rd Party}
IdThread,
ZConnection,
ZSqlUpdate
;
type
//------------------------------------------------------------------------------
//TDatabase CLASS
//------------------------------------------------------------------------------
TDatabase = class(TObject)
public
AccountConnection : TZConnection;
GameConnection : TZConnection;
Options : TDatabaseOptions;
Account : TAccountQueries;
Character : TCharacterQueries;
Friend : TFriendQueries;
Map : TMapQueries;
Mail : TMailQueries;
Mob : TMobQueries;
Items : TItemQueries;
CharacterConstant: TCharacterConstantQueries;
Constructor Create();
Destructor Destroy
(
);override;
Procedure Connect(
);
Procedure Disconnect(
);
Procedure LoadOptions(
);
end;
//------------------------------------------------------------------------------
implementation
uses
{RTL/VCL}
SysUtils,
{Project}
Main,
Globals
{3rd Party}
//none
;
//------------------------------------------------------------------------------
//Create CONSTRUCTOR
//------------------------------------------------------------------------------
// What it does-
// Builds our object.
//
// Changes -
// February 1st, 2008 - RaX - Created
//
//------------------------------------------------------------------------------
Constructor TDatabase.Create();
Begin
Inherited Create;
LoadOptions;
AccountConnection := TZConnection.Create(nil);
AccountConnection.Protocol := Options.AccountConfig.Protocol;
AccountConnection.HostName := Options.AccountConfig.Host;
AccountConnection.Port := Options.AccountConfig.Port;
AccountConnection.Database := Options.AccountConfig.Database;
AccountConnection.User := Options.AccountConfig.User;
AccountConnection.Password := Options.AccountConfig.Pass;
GameConnection := TZConnection.Create(nil);
GameConnection.Protocol := Options.GameConfig.Protocol;
GameConnection.HostName := Options.GameConfig.Host;
GameConnection.Port := Options.GameConfig.Port;
GameConnection.Database := Options.GameConfig.Database;
GameConnection.User := Options.GameConfig.User;
GameConnection.Password := Options.GameConfig.Pass;
Account := TAccountQueries.Create(AccountConnection);
Character := TCharacterQueries.Create(GameConnection);
Friend := TFriendQueries.Create(GameConnection);
Map := TMapQueries.Create(GameConnection);
CharacterConstant := TCharacterConstantQueries.Create(GameConnection);
Mail := TMailQueries.Create(GameConnection);
Mob := TMobQueries.Create(GameConnection);
Items := TItemQueries.Create(GameConnection);
End;{Create}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Destroy DESTRUCTOR
//------------------------------------------------------------------------------
// What it does-
// Frees up our custom properties.
//
// Changes -
// February 1st, 2008 - RaX - Created.
//
//------------------------------------------------------------------------------
Destructor TDatabase.Destroy(
);
begin
Disconnect();
Account.Free;
Character.Free;
Friend.Free;
Map.Free;
CharacterConstant.Free;
Mail.Free;
Mob.Free;
Items.Free;
AccountConnection.Free;
GameConnection.Free;
Options.Save;
Options.Free;
Inherited;
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Connect PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Connects to the database.
//
// Changes -
// February 1st, 2008 - RaX - Created.
//
//------------------------------------------------------------------------------
Procedure TDatabase.Connect(
);
begin
try
if NOT AccountConnection.Connected then
begin
AccountConnection.Connect();
end;
except
on E : Exception do
begin
Console.Message('Could not connect to '+AccountConnection.Protocol+
' database "'+AccountConnection.Database+'" on server at "'+
AccountConnection.HostName+':'+IntToStr(AccountConnection.Port)+
'". Error Message :: '+E.Message,
'Database', MS_ERROR
);
AccountConnection.Disconnect;
MainProc.ContinueLoading := false;
end;
end;
try
if NOT GameConnection.Connected then
begin
GameConnection.Connect();
end;
except
on E : Exception do
begin
Console.Message('Could not connect to '+GameConnection.Protocol+
' database "'+GameConnection.Database+'" on server at "'+
GameConnection.HostName+':'+IntToStr(GameConnection.Port)+
'". Error Message :: '+E.Message,
'Database', MS_ERROR
);
GameConnection.Disconnect;
MainProc.ContinueLoading := false;
end;
end;
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Disconnect PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Disconnects from the database.
//
// Changes -
// February 1st, 2008 - RaX - Created.
//
//------------------------------------------------------------------------------
Procedure TDatabase.Disconnect(
);
begin
if AccountConnection.Connected then
begin
AccountConnection.Disconnect();
end;
if GameConnection.Connected then
begin
GameConnection.Disconnect();
end;
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//LoadDatabaseOptions PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Creates and Loads the inifile.
//
// Changes -
// March 27th, 2007 - RaX - Created.
//
//------------------------------------------------------------------------------
Procedure TDatabase.LoadOptions;
begin
Options := TDatabaseOptions.Create(MainProc.Options.ConfigDirectory+'/Database.ini');
Options.Load;
end;{LoadDatabaseOptions}
//------------------------------------------------------------------------------
end.
|
unit IP_API;
{**************************************************************************}
{
{ Delphi Win32 DLL Import Unit for SoftWareKey.com InstantPLUS API
{ C, cdecl calling conventions
{
{**************************************************************************}
interface
uses
Wintypes, WinProcs;
{///**Function Declarations** }
function WR_LFGetString(flags: LongInt;
var_no: LongInt;
buffer: PChar): LongInt; cdecl ;
function WR_LFGetNum(flags: LongInt;
var_no: LongInt;
var value: LongInt): LongInt; cdecl ;
function WR_LFGetDate(flags: LongInt;
var_no: LongInt;
var month_hours: LongInt;
var day_minutes: LongInt;
var year_seconds: LongInt): LongInt; cdecl ;
function WR_LFSetString(flags: LongInt;
var_no: LongInt;
buffer: PChar): LongInt; cdecl ;
function WR_LFSetNum(flags: LongInt;
var_no: LongInt;
value: LongInt): LongInt; cdecl ;
function WR_LFSetDate(flags: LongInt;
var_no: LongInt;
month_hours: LongInt;
day_minutes: LongInt;
year_seconds: LongInt): LongInt; cdecl ;
function WR_Activate(flags: LongInt;
action: LongInt;
action_flags: LongInt;
hWnd: HWND): LongInt; cdecl ;
function WR_TrialRunsLeft(flags: LongInt;
var runsleft: LongInt): LongInt; cdecl ;
function WR_TrialDaysLeft(flags: LongInt;
var daysleft: LongInt): LongInt; cdecl ;
function WR_IsTrial(flags: LongInt): LongInt; cdecl ;
function WR_GetLFHandle(var lfhandle: LongInt): LongInt; cdecl ;
function WR_GetLicenseID(var licenseid: LongInt): LongInt; cdecl ;
function WR_GetPassword(password: PChar): LongInt; cdecl ;
function WR_ExpireType(flags: LongInt;
str1: PChar): LongInt; cdecl ;
function WR_DeactivateLicense(flags: LongInt): LongInt; cdecl ;
function WR_GetProductID(flags: LongInt;
var number: LongInt): LongInt; cdecl ;
function WR_GetProdOptionID(flags: LongInt;
var number: LongInt): LongInt; cdecl ;
function WR_GetPurchaseUrl(flags: LongInt;
str1: PChar): LongInt; cdecl ;
function WR_IsJustActivated(flags: LongInt): LongInt; cdecl ;
function WR_Close(flags: LongInt): LongInt; cdecl ;
implementation
function WR_LFGetString; external 'fake.dll' name 'n1';
function WR_LFGetNum; external 'fake.dll' name 'n2';
function WR_LFGetDate; external 'fake.dll' name 'n3';
function WR_LFSetString; external 'fake.dll' name 'n4';
function WR_LFSetNum; external 'fake.dll' name 'n5';
function WR_LFSetDate; external 'fake.dll' name 'n6';
function WR_Activate; external 'fake.dll' name 'n7';
function WR_TrialRunsLeft; external 'fake.dll' name 'n8';
function WR_TrialDaysLeft; external 'fake.dll' name 'n9';
function WR_IsTrial; external 'fake.dll' name 'n10';
function WR_GetLFHandle; external 'fake.dll' name 'n17';
function WR_GetLicenseID; external 'fake.dll' name 'n18';
function WR_GetPassword; external 'fake.dll' name 'n19';
function WR_ExpireType; external 'fake.dll' name 'r14';
function WR_DeactivateLicense; external 'fake.dll' name 'n25';
function WR_GetProductID; external 'fake.dll' name 'r4';
function WR_GetProdOptionID; external 'fake.dll' name 'r5';
function WR_GetPurchaseUrl; external 'fake.dll' name 'r15';
function WR_IsJustActivated; external 'fake.dll' name 'r2';
function WR_Close; external 'fake.dll' name 'r1';
end.
|
unit modellingUnit;
interface
uses
SysUtils,ActiveX,Windows,Classes,XMLDoc,XMLIntf,BalancerModelMVStudiumMetaFunctions;
type
direction = (left,right);
modellingThread = class(TThread)
private
//Путь до файла с настройками
pathToFile:string;
//Параметры объекта
shankLength: Double;
shankLengthFromCarrigeToBottom: Double;
shankMass: Double;
lengthToCargo: Double;
cargoMass: Double;
//Параметры управления
carriageFrequency: Double;
carriageAmplitude: Double;
carriagePrehistoryDirection: direction;
//Параметры моделирования
SamplingInterval: Double;
endTime: Double;
currentTime: Double;
startPhaseShift: Double;
resultsList: TList;
protected
ConnectionWithDllObject: ConnectionWithDllClass;
procedure Execute; override;
public
constructor Create(CreateSuspennded: Boolean;const pathToFileInp: string); overload;
destructor Destroy; override;
procedure initializeModellDLL;
procedure phaseShift;
procedure loadSettingsAndParametrsFromFile;
procedure logToFile;
procedure modelStepAndSaveResults;
end;
implementation
uses Math;
{ Important: Methods and properties of objects in visual components can only be
used in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure MyThread.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end; }
{ MyThread }
constructor modellingThread.Create(CreateSuspennded: Boolean;const
pathToFileInp: string);
begin
//Путь до файла с настройками
pathToFile:=pathToFileInp;
//Класс обертка для использования MVStudium dll
try
ConnectionWithDllObject:=ConnectionWithDllClass.Create();
except
on E:exception do
begin
EndThread(4);
end;
end;
resultsList:=TList.Create;
inherited Create(CreateSuspennded);
end;
destructor modellingThread.Destroy;
var
i: Integer;
begin
for i := 0 to resultsList.Count-1 do
begin
TObject(resultsList[i]).Free;
end;
resultsList.Clear;
resultsList.Free;
ConnectionWithDllObject.Destroy();
inherited;
end;
procedure modellingThread.Execute;
begin
loadSettingsAndParametrsFromFile (); //Считать параметры из файла настроек
initializeModellDLL(); //Инициализировать соединение с моделью
phaseShift;
while(currentTime<endTime) do //Шаги окончены?
begin
modelStepAndSaveResults(); //Моделировать один шаг
currentTime:=currentTime+SamplingInterval/1000;
end;
logToFile(); //Записать в файл
Destroy; //Высвободить ресурсы
EndThread(0); //Завершить поток
//PostThreadMessage
end;
procedure modellingThread.initializeModellDLL;
var a:Double;
begin
//Открыть соединение с DLL
ConnectionWithDllObject.openConnectionWithDll;
//Сначала перезапуск системы
ConnectionWithDllObject.restartSystem;
//Потом установим параметры
//Стержень
ConnectionWithDllObject.setShankLength(shankLength);
ConnectionWithDllObject.setShankLengthFromCarrigeToBottom(shankLengthFromCarrigeToBottom);
ConnectionWithDllObject.setShankLengthFromCarrigeToBottom(shankLengthFromCarrigeToBottom);
ConnectionWithDllObject.setShankMass(shankMass);
a :=ConnectionWithDllObject.getShankMass;
//Груз
ConnectionWithDllObject.setLengthToCargo(lengthToCargo);
ConnectionWithDllObject.setCargoMass(cargoMass);
end;
procedure modellingThread.phaseShift;
begin
if carriagePrehistoryDirection=right then //Если двигаемся вправо то сдвиг по фазе на пол периода
begin
startPhaseShift:=pi/2;
end
else
begin
startPhaseShift:=0;
end;
end;
procedure modellingThread.loadSettingsAndParametrsFromFile;
var xmldcmnt1 : IXMLDocument;
begin
CoInitialize (NIL);
xmldcmnt1:=TXMLDocument.create(nil);
//А файл вообще существует ли?
try
xmldcmnt1.LoadFromFile('test.xml');
except
xmldcmnt1:=nil;
Destroy();
EndThread(1);
exit;
end;
//Параметры системы из файла.
try
xmldcmnt1.Active := true;
//Стержень
//Длинна
shankLength:=StrToFloat(xmldcmnt1.DocumentElement.ChildNodes['balancerParametrs'].ChildNodes['shank'].ChildNodes['shankLength'].Text);
shankLengthFromCarrigeToBottom:=StrToFloat(xmldcmnt1.DocumentElement.ChildNodes['balancerParametrs'].ChildNodes['shank'].ChildNodes['shankLengthFromCarrigeToBottom'].Text);
//Масса
shankMass:=StrToFloat(xmldcmnt1.DocumentElement.ChildNodes['balancerParametrs'].ChildNodes['shank'].ChildNodes['shankMass'].Text);
//Груз
//Расстояние
lengthToCargo:=StrToFloat(xmldcmnt1.DocumentElement.ChildNodes['balancerParametrs'].ChildNodes['cargo'].childNodes['lengthToCargo'].Text);
//Масса
cargoMass:=StrToFloat(xmldcmnt1.DocumentElement.ChildNodes['balancerParametrs'].ChildNodes['cargo'].childNodes['cargoWeight'].Text);
//Параметры управления
carriageAmplitude:=StrToFloat(xmldcmnt1.DocumentElement.ChildNodes['balancerParametrs'].ChildNodes['carriage'].childNodes['carriageAmplitude'].Text);
carriageFrequency:=StrToFloat(xmldcmnt1.DocumentElement.ChildNodes['balancerParametrs'].ChildNodes['carriage'].childNodes['carriageFrequency'].Text);
if(xmldcmnt1.DocumentElement.ChildNodes['balancerParametrs'].ChildNodes['carriage'].childNodes['carriagePrehistoryDirection'].Text='left') then
begin
carriagePrehistoryDirection:= left;
end
else
begin
carriagePrehistoryDirection:= right;
end;
//Параметры моделирования
SamplingInterval:=StrToFloat(xmldcmnt1.DocumentElement.ChildNodes['modellingParametrs'].ChildNodes['samplingInterval'].Text);
endTime:=StrToFloat(xmldcmnt1.DocumentElement.ChildNodes['modellingParametrs'].ChildNodes['endTime'].Text);
except
xmldcmnt1.Active := false;
xmldcmnt1:=nil;
Destroy();
EndThread(2);
exit;
end;
xmldcmnt1.Active := false;
xmldcmnt1:=nil;
CoUninitialize;
end;
procedure modellingThread.logToFile;
begin
// TODO -cMM: modellingThread.logToFile default body inserted
end;
procedure modellingThread.modelStepAndSaveResults;
var
resultContainerClassObject: resultContainerClass;
begin
// kvant:=tInp*dPeriodDiscretizInp/1000;
// sinz:=carriageAmplitude*sin(carriageFrequency*(2*pi)*currentTime);
//Моделирование шага
ConnectionWithDllObject.setSinz(carriageAmplitude*sin(carriageFrequency*(2*pi)*currentTime+startPhaseShift));//Задаем управление
ConnectionWithDllObject.RunToTime(SamplingInterval/1000); //В секундах
resultContainerClassObject:=resultContainerClass.create();
resultContainerClassObject.sinZ:=carriageAmplitude*sin(carriageFrequency*(2*pi)*currentTime+startPhaseShift);
resultContainerClassObject.shankTopX:= ConnectionWithDllObject.getShankTopX;
resultContainerClassObject.shankTopY:= ConnectionWithDllObject.getShankTopY;
resultContainerClassObject.shankBottomY:= ConnectionWithDllObject.getShankBottomY;
resultContainerClassObject.shankBottomX:= ConnectionWithDllObject.getShankBottomX;
resultContainerClassObject.carriageX:= ConnectionWithDllObject.getCarriageX;
resultContainerClassObject.cargoX:= ConnectionWithDllObject.getCargoX;
resultContainerClassObject.cargoY:= ConnectionWithDllObject.getCargoY;
resultContainerClassObject.balancerAngle:= ConnectionWithDllObject.getBalancerAngle;
resultsList.Add(resultContainerClassObject);
//Сохранение результатов
// resultTimeModelir[i]:=i*dPeriodDiscretiz/1000;
// resultGradModelir[i]:=SvazSDllClassObject.GetMaiatnikAngle;
// resultXKaretkaModelir[i]:=SvazSDllClassObject.GetXKar;
// resultXGryzaModelir[i]:=SvazSDllClassObject.GetXGryza;
// resultYGryzaModelir[i]:=SvazSDllClassObject.GetYGryza;
// resultXVerxaModelir[i]:=SvazSDllClassObject.GetXVerxa;
// resultYVerxaModelir[i]:=SvazSDllClassObject.GetYVerxa;
// resultXNizaModelir[i]:=SvazSDllClassObject.GetXNiza;
// resultYNizaModelir[i]:=SvazSDllClassObject.GetYNiza;
//ConnectionWithDllObject.runToTime();
// TODO -cMM: modellingThread.modelStepAndSaveResults default body inserted
end;
end.
|
unit uPlotForms;
{
*****************************************************************************
* This file is part of Multiple Acronym Math and Audio Plot - MAAPlot *
* *
* See the file COPYING. *
* for details about the copyright. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* *
* MAAplot for Lazarus/fpc *
* (C) 2014 Stefan Junghans *
*****************************************************************************
}
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, uPlotClass, StdCtrls, Controls, ExtCtrls, Graphics,
Dialogs, Spin, uPlotStyles, uPlotAxis, uPlotRect, types, useriesmarkers,
CheckLst, uPlotDataTypes, uPlotInterpolator, uPlotHIDHandler;
// TODO: make more modular
// move buttons to base class
// evtl. destroy unneeded forms ?
// make forms nicer !
type
THelperFormPlotOptions = class;
THelperFormSeriesManualScale = class;
THelperFormSeriesStyleChoose = class;
THelperFormSeriesMarkersChoose = class;
THelperFormPlotRectStyleChoose = class;
THelperFormAxesStyleChoose = class;
{ THelperForms } //=====================================================-
THelperForms = class(THelperFormsBase)
private
FBtnOK, FBtnClose: TButton;
protected
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure OnButton(Sender: TObject);virtual;
procedure Apply(Sender: TObject); virtual;
procedure Done; virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
{ THelperFormsPlot }
THelperFormsPlot = class(THelperForms)
private
FfrmPlotOptions: THelperFormPlotOptions;
protected
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure PlotOptionsShow;
end;
{ THelperFormExportOptions }
{ THelperFormPlotOptions }
THelperFormPlotOptions = class(THelperForms)
private
Fgb_MouseActions: TGroupBox;
Fcb_Zoom: TComboBox;
Flbl_Zoom: TLabel;
Fcb_Pan: TComboBox;
Flbl_Pan: TLabel;
Fcb_AdHocMarker: TComboBox;
Flbl_AdHocMarker: TLabel;
// export size
Fgb_exportsize: TGroupBox;
Fed_sizeX, Fed_sizeY: TSpinEdit;
Flbl_sizedelimiter: TLabel;
// color scheme
Fcb_PrinterFriendly: TCheckBox;
// background
Fbtn_color: TColorButton;
procedure _ComboDropDown(Sender: TObject);
procedure _ComboChange(Sender: TObject);
protected
procedure InitForm;
procedure Apply(Sender: TObject);override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
{ THelperFormsSeries } //=====================================================-
THelperFormsSeries = class(THelperForms)
private
FfrmManualScale: THelperFormSeriesManualScale;
FfrmStyleChoose: THelperFormSeriesStyleChoose;
FfrmMarkersChoose: THelperFormSeriesMarkersChoose;
protected
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure SeriesManualScale(ASeriesIndex: Integer);
procedure SeriesStyleChoose(ASeriesIndex: Integer);
procedure SeriesMarkersChoose(ASeriesIndex: Integer);
end;
{ THelperFormManualScale } //-------------------------------------------------
THelperFormSeriesManualScale = class(THelperFormsSeries)
private
FActiveSeriesManualScale: integer;
FEdXmin, FEdXmax, FEdYmin, FEdYmax, FEdZmin, FEdZmax: TLabeledEdit;
Fed_SeriesName: TEdit;
protected
procedure InitForm(ASeriesIndex: Integer);
procedure Apply(Sender: TObject); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
{ THelperFormSeriesStyleChoose } //-------------------------------------------
THelperFormSeriesStyleChoose = class(THelperFormsSeries)
private
FInitInProgress: Boolean;
FActiveSeriesStyleChoose: integer;
Flbl_style, Flbl_stylepoints, Flbl_stylellines: TLabel;
Flbl_sizepoints, Flbl_sizelines: TLabel;
Fcb_style, Fcb_stylepoints, Fcb_stylellines: TComboBox;
Fed_sizepoints, Fed_sizelines: TSpinEdit;
//------------------------
Fcb_interpolate: TCheckBox;
Fcb_Ipol_AxisMode: TComboBox;
Fcb_Ipol_Mode: TComboBox;
Fshp: TShape; //------------------------
Flbl_seriesname, Flbl_units: TLabel;
Fed_seriesname, FedXunit, FedYunit, FedZunit: TEdit;
// components for colored axes
Fcb_drawcolored: TCheckBox;
Fcb_coloraxes: TComboBox;
procedure EnableControlsLineStyle(AVisible: Boolean);
protected
procedure InitForm(ASeriesIndex:Integer);
procedure Apply(Sender: TObject);override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
{ THelperFormSeriesStyleChoose } //-------------------------------------------
{ THelperFormSeriesMarkersChoose }
THelperFormSeriesMarkersChoose = class(THelperFormsSeries)
private
FInitInProgress: Boolean;
FActiveSeriesMarkersChoose: integer;
Flbl_mkrIndex, Flbl_mkrType, Flbl_mkrMode,
Flbl_diameter, Flbl_linewidth: TLabel;
Fcb_mkrIndex: TComboBox;
Fbtn_Addmarker: TButton;
Fbtn_RemoveMarker: TButton;
Fcb_mkrType, Fcb_mkrMode: TComboBox;
Fcb_mkrStyle: TCheckListBox;
Fed_diameter, Fed_linewidth: TSpinEdit;
//Fshp: TShape; //------------------------
Fbtn_color, Fbtn_backgndcolor: TColorButton;
Fed_markeralpha, Fed_backgndalpha: TSpinEdit;
Flbl_XIndex: TLabel;
Fed_Xindex: TSpinEdit;
Flbl_XYZValues: TLabel;
Fed_XValue, Fed_YValue, Fed_ZValue: TEdit;
procedure _PropertyChanged(Sender: TObject);
procedure AddRemoveMarker(Sender: TObject);
procedure ShowMarkerProperties(AMarkerIndex: Integer);
procedure ApplyMarkerProperties(AMarkerIndex: Integer);
protected
procedure InitForm(ASeriesIndex:Integer);
procedure Apply(Sender: TObject);override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
{ THelperFormsPlotRect } //===================================================
THelperFormsPlotRect = class(THelperForms)
private
FActivePlotRect: integer;
FfrmPlotRectStyleChoose: THelperFormPlotRectStyleChoose;
protected
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure PlotRectStyleChoose(APlotRectIndex: Integer);
end;
{ THelperFormPlotRectStyleChoose } //-----------------------------------------
THelperFormPlotRectStyleChoose = class(THelperFormsPlotRect)
private
Fcb_legend, Fcb_colorscale: TCheckBox;
Fcb_axes: TComboBox;
Fbtn_color: TColorButton;
protected
procedure Apply(Sender: TObject);override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure InitForm(APlotRectIndex:Integer);
end;
{ THelperFormsAxes } //===================================================
THelperFormsAxes = class(THelperForms)
private
FActiveAxis: integer;
FfrmAxesStyleChoose: THelperFormAxesStyleChoose;
protected
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AxesStyleChoose(AAxis: Integer);
end;
{ THelperFormPlotRectStyleChoose } //-----------------------------------------
{ THelperFormAxesStyleChoose }
THelperFormAxesStyleChoose = class(THelperFormsAxes)
private
Fcb_logscale: TCheckBox;
Fed_logbase: TSpinEdit;
Fcb_innerticks, Fcb_innersubticks, Fcb_InnerTicks3D: TCheckBox;
//Fshp: TShape; //------------------------
Flbl_numformat: TLabel;
Fed_axisname: TLabeledEdit;
Fcb_numberformat: TComboBox;
Fbtn_color: TColorButton;
protected
procedure Apply(Sender: TObject);override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure InitForm(AAxis:Integer);
end;
implementation
uses
uPlotSeries;
{THelperForms}
procedure THelperForms.FormClose(Sender: TObject; var CloseAction: TCloseAction
);
begin
CloseAction := caHide;
end;
procedure THelperForms.OnButton(Sender: TObject);
begin
IF TButton(Sender) = FBtnOK THEN BEGIN
Apply(Sender);
END ELSE BEGIN
Done;
END;
end;
procedure THelperForms.Apply(Sender:TObject);
begin
// do nothing in base class
end;
procedure THelperForms.Done;
begin
OnClose := @FormClose;
Self.Close;
end;
constructor THelperForms.Create(AOwner: TComponent);
const
cBUTTON_GEN_SPACE = 20;
begin
inherited Create(AOwner);
// generic buttons
FBtnOK := TButton.Create(Self);
FBtnOK.Parent := Self;
FBtnOK.Caption := 'Apply';
FBtnOK.OnClick := @OnButton;
FBtnOK.BorderSpacing.Around := cBUTTON_GEN_SPACE;
FBtnOK.AnchorSide[akLeft].Control := Self;
FBtnOK.AnchorSide[akLeft].Side := asrLeft;
FBtnOK.AnchorSide[akBottom].Control := Self;
FBtnOK.AnchorSide[akBottom].Side := asrBottom;
FBtnOK.Anchors := [akBottom, akLeft];
FBtnClose := TButton.Create(Self);
FBtnClose.Parent := Self;
FBtnClose.Caption := 'Close';
FBtnClose.OnClick := @OnButton;
FBtnClose.BorderSpacing.Around := cBUTTON_GEN_SPACE;
FBtnClose.AnchorSide[akLeft].Control := FBtnOK;
FBtnClose.AnchorSide[akLeft].Side := asrRight;
FBtnClose.AnchorSide[akBottom].Control := Self;
FBtnClose.AnchorSide[akBottom].Side := asrBottom;
FBtnClose.Anchors := [akBottom, akLeft];
end;
destructor THelperForms.Destroy;
begin
//FBtnClose.Free;
//FBtnOK.Free;
inherited Destroy;
end;
{ THelperFormsExport }
{===========================================================================}
constructor THelperFormsPlot.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
destructor THelperFormsPlot.Destroy;
begin
IF FfrmPlotOptions <> nil THEN FfrmPlotOptions.Free;
inherited Destroy;
end;
procedure THelperFormsPlot.PlotOptionsShow;
begin
IF FfrmPlotOptions = nil THEN FfrmPlotOptions := THelperFormPlotOptions.Create(OwnerPlot);
//FfrmManualScale.Owner := Self;
FfrmPlotOptions.InitForm;
FfrmPlotOptions.Show;
end;
{ THelperFormExportOptions }
procedure THelperFormPlotOptions._ComboDropDown(Sender: TObject);
var
vStates: THIDMouseStates;
vState: THIDMouseState;
vHIDAction: THIDAction;
//vLoop: Integer;
//vOldState: THIDMouseState;
begin
if Sender = Fcb_Zoom then vHIDAction:=haZoom else
if Sender = Fcb_Pan then vHIDAction:=haPan else
if Sender = Fcb_AdHocMarker then vHIDAction:=haAdHocMarker;
OwnerPlot.HIDHandler.GetHIDActionStatesAvail(vHIDAction, vStates);
//vOldState := OwnerPlot.HIDHandler.GetHIDActionState(vHIDAction, vOldState);
TComboBox(Sender).Clear;
//for vLoop:=0 to length(vStates)-1 do begin
for vState in vStates do begin
TComboBox(Sender).Items.Add(cHID_MOUSESTATE_Names[vState]);
end;
end;
procedure THelperFormPlotOptions._ComboChange(Sender: TObject);
var
vState: THIDMouseState;
vHIDAction: THIDAction;
vLoop: Integer;
begin
if Sender = Fcb_Zoom then vHIDAction:=haZoom else
if Sender = Fcb_Pan then vHIDAction:=haPan else
if Sender = Fcb_AdHocMarker then vHIDAction:=haAdHocMarker;
for vLoop := 0 to ord(high(THIDMouseState)) do begin
if TComboBox(Sender).Items[TComboBox(Sender).ItemIndex] = cHID_MOUSESTATE_Names[THIDMouseState(vLoop)] then begin
vState := THIDMouseState(vLoop);
break;
end;
end;
OwnerPlot.HIDHandler.SetHIDAction(vHIDAction, vState);
end;
procedure THelperFormPlotOptions.InitForm;
var
vState: THIDMouseState;
begin
Fed_sizeX.Value := OwnerPlot.ExportSize.cx;
Fed_sizeY.Value := OwnerPlot.ExportSize.cy;
Fcb_PrinterFriendly.Checked := OwnerPlot.ExportPrinterFriedlyColors;
//Frg_MouseZoom.ItemIndex := Integer(OwnerPlot.MouseWheelZoomButtonPan = true);
//for vLoop:=0 to length(vStates)-1 do begin
OwnerPlot.HIDHandler.GetHIDActionState(haZoom, vState);
Fcb_Zoom.Text := (cHID_MOUSESTATE_Names[vState]);
OwnerPlot.HIDHandler.GetHIDActionState(haPan, vState);
Fcb_Pan.Text := (cHID_MOUSESTATE_Names[vState]);
OwnerPlot.HIDHandler.GetHIDActionState(haAdHocMarker, vState);
Fcb_AdHocMarker.Text := (cHID_MOUSESTATE_Names[vState]);
Fbtn_color.ButtonColor := OwnerPlot.BackgroundColor;
end;
procedure THelperFormPlotOptions.Apply(Sender: TObject);
var
vSize: TSize;
begin
vSize.cx := Fed_sizeX.Value;
vSize.cy := Fed_sizeY.Value;
OwnerPlot.ExportSize := vSize;
OwnerPlot.ExportPrinterFriedlyColors := Fcb_PrinterFriendly.Checked;
//OwnerPlot.MouseWheelZoomButtonPan := Frg_MouseZoom.ItemIndex = 1;
if Sender = Fbtn_color then begin
OwnerPlot.BackgroundColor := Fbtn_color.ButtonColor;
OwnerPlot.Repaint;
end;
inherited Apply(Sender);
end;
constructor THelperFormPlotOptions.Create(AOwner: TComponent);
const
cBORDERSPACE = 12;
begin
inherited Create(AOwner);
OwnerPlot := TPlot(AOwner);
Self.Height := 360;
Self.Width := 320;
Self.Caption := 'Plot options';
// export size
//Fed_sizeX, Fed_sizeY: TSpinEdit;
//Flbl_sizedelimiter: TLabel;
// Mouse options
Fgb_MouseActions := TGroupBox.Create(Self);
with Fgb_MouseActions do begin
Parent := Self;
Visible := TRUE;
AnchorSide[akLeft].Side:=asrLeft;
AnchorSide[akLeft].Control:=Self;
AnchorSide[akRight].Side:=asrRight;
AnchorSide[akRight].Control:=Self;
AnchorSide[akTop].Side:=asrTop;
AnchorSide[akTop].Control:=Self;
Anchors:=[akLeft, akTop, akRight];
BorderSpacing.Around := cBORDERSPACE;
Caption := 'Mouse actions';
end;
Flbl_Zoom := TLabel.Create(Self);
with Flbl_Zoom do begin
Parent := Self;
Visible := TRUE;
AnchorSide[akLeft].Side:=asrLeft;
AnchorSide[akLeft].Control:=Fgb_MouseActions;
AnchorSide[akTop].Side:=asrTop;
AnchorSide[akTop].Control:=Fgb_MouseActions;
Anchors:=[akLeft, akTop];
Text := 'Zoom plot';
BorderSpacing.Left:=6;
BorderSpacing.Top:=28;
end;
Fcb_Zoom := TComboBox.Create(Self);
with Fcb_Zoom do begin
Parent := Self;
Visible := TRUE;
AnchorSide[akLeft].Side:=asrRight;
AnchorSide[akLeft].Control:=Flbl_Zoom;
AnchorSide[akTop].Side:=asrCenter;
AnchorSide[akTop].Control:=Flbl_Zoom;
AnchorSide[akRight].Side:=asrRight;
AnchorSide[akRight].Control:=Fgb_MouseActions;
Anchors:=[akLeft, akTop, akRight];
BorderSpacing.Left := 3 *cBORDERSPACE;
BorderSpacing.Right := 6;
OnChange:= @_ComboChange;
OnDropDown:= @_ComboDropDown;
end;
Flbl_Pan := TLabel.Create(Self);
with Flbl_Pan do begin
Parent := Self;
Visible := TRUE;
AnchorSide[akLeft].Side:=asrLeft;
AnchorSide[akLeft].Control:=Flbl_Zoom;
AnchorSide[akTop].Side:=asrBottom;
AnchorSide[akTop].Control:=Flbl_Zoom;
Anchors:=[akLeft, akTop];
Text := 'Pan plot';
BorderSpacing.Top:=cBORDERSPACE;
end;
Fcb_Pan := TComboBox.Create(Self);
with Fcb_Pan do begin
Parent := Self;
Visible := TRUE;
AnchorSide[akLeft].Side:=asrLeft;
AnchorSide[akLeft].Control:=Fcb_Zoom;
AnchorSide[akTop].Side:=asrCenter;
AnchorSide[akTop].Control:=Flbl_Pan;
AnchorSide[akRight].Side:=asrRight;
AnchorSide[akRight].Control:=Fcb_Zoom;
Anchors:=[akLeft, akTop, akRight];
OnChange:= @_ComboChange;
OnDropDown:= @_ComboDropDown;
end;
Flbl_AdHocMarker := TLabel.Create(Self);
with Flbl_AdHocMarker do begin
Parent := Self;
Visible := TRUE;
AnchorSide[akLeft].Side:=asrLeft;
AnchorSide[akLeft].Control:=Flbl_Pan;
AnchorSide[akTop].Side:=asrBottom;
AnchorSide[akTop].Control:=Flbl_Pan;
Anchors:=[akLeft, akTop];
Text := 'Ad hoc marker';
BorderSpacing.Top:=cBORDERSPACE;
end;
Fcb_AdHocMarker := TComboBox.Create(Self);
with Fcb_AdHocMarker do begin
Parent := Self;
Visible := TRUE;
AnchorSide[akLeft].Side:=asrLeft;
AnchorSide[akLeft].Control:=Fcb_Zoom;
AnchorSide[akTop].Side:=asrCenter;
AnchorSide[akTop].Control:=Flbl_AdHocMarker;
AnchorSide[akRight].Side:=asrRight;
AnchorSide[akRight].Control:=Fcb_Zoom;
Anchors:=[akLeft, akTop, akRight];
OnChange:= @_ComboChange;
OnDropDown:= @_ComboDropDown;
end;
// Export options --------------
Fgb_exportsize := TGroupBox.Create(Self); // colorbutton, fixed to form
Fgb_exportsize.Parent := Self;
Fgb_exportsize.Visible := TRUE;
Fgb_exportsize.AnchorSide[akLeft].Side:=asrLeft;
Fgb_exportsize.AnchorSide[akLeft].Control:=Self;
Fgb_exportsize.AnchorSide[akRight].Side:=asrRight;
Fgb_exportsize.AnchorSide[akRight].Control:=Self;
Fgb_exportsize.AnchorSide[akTop].Side:=asrBottom;
Fgb_exportsize.AnchorSide[akTop].Control:=Fgb_MouseActions;
Fgb_exportsize.Anchors:=[akLeft, akTop, akRight];
Fgb_exportsize.BorderSpacing.Around := cBORDERSPACE;
Fgb_exportsize.Caption := 'Export Size [width] x [height] in px';
//Fgb_exportsize.AutoSize:=true;
Fed_sizeX := TSpinEdit.Create(Self);
Fed_sizeX.Parent := Fgb_exportsize;
Fed_sizeX.Visible := TRUE;
Fed_sizeX.AnchorSide[akLeft].Side:=asrLeft;
Fed_sizeX.AnchorSide[akLeft].Control:=Fgb_exportsize;
Fed_sizeX.AnchorSide[akTop].Side:=asrTop;
Fed_sizeX.AnchorSide[akTop].Control:=Fgb_exportsize;
Fed_sizeX.Anchors:=[akLeft,akTop];
Fed_sizeX.BorderSpacing.Around := cBORDERSPACE;
Fed_sizeX.Caption := 'sizeX';
Fed_sizeX.MinValue := 1;
Fed_sizeX.MaxValue := 8192;
Fed_sizeX.Value := 1024;
Flbl_sizedelimiter := TLabel.Create(Self); // label 'X'
Flbl_sizedelimiter.Parent := Fgb_exportsize;
Flbl_sizedelimiter.Visible := TRUE;
Flbl_sizedelimiter.AnchorSide[akLeft].Side:=asrRight;
Flbl_sizedelimiter.AnchorSide[akLeft].Control:=Fed_sizeX;
Flbl_sizedelimiter.AnchorSide[akTop].Side:=asrTop;
Flbl_sizedelimiter.AnchorSide[akTop].Control:=Fed_sizeX;
Flbl_sizedelimiter.Anchors:=[akLeft,akTop];
Flbl_sizedelimiter.BorderSpacing.Left := cBORDERSPACE;
Flbl_sizedelimiter.BorderSpacing.Top := 0;
Flbl_sizedelimiter.Caption := 'x';
Fed_sizeY := TSpinEdit.Create(Self);
Fed_sizeY.Parent := Fgb_exportsize;
Fed_sizeY.Visible := TRUE;
Fed_sizeY.AnchorSide[akLeft].Side:=asrRight;
Fed_sizeY.AnchorSide[akLeft].Control:=Flbl_sizedelimiter;
Fed_sizeY.AnchorSide[akTop].Side:=asrTop;
Fed_sizeY.AnchorSide[akTop].Control:=Fed_sizeX;
Fed_sizeY.Anchors:=[akLeft,akTop];
Fed_sizeY.BorderSpacing.Left := cBORDERSPACE;
Fed_sizeY.BorderSpacing.Top := 0;
//Fed_sizeY.Caption := 'sizeX';
Fed_sizeY.MinValue := 1;
Fed_sizeY.MaxValue := 8192;
Fed_sizeY.Value := 768;
// Checkbox Colorscheme printerfriendly
Fcb_PrinterFriendly := TCheckBox.Create(Self);
Fcb_PrinterFriendly.Parent := Fgb_exportsize;
Fcb_PrinterFriendly.Visible := TRUE;
Fcb_PrinterFriendly.Checked := FALSE;
Fcb_PrinterFriendly.AnchorSide[akLeft].Side:=asrLeft;
Fcb_PrinterFriendly.AnchorSide[akLeft].Control:=Fed_sizeX;
Fcb_PrinterFriendly.AnchorSide[akTop].Side:=asrBottom;
Fcb_PrinterFriendly.AnchorSide[akTop].Control:=Fed_sizeX;
Fcb_PrinterFriendly.Anchors:=[akLeft, akTop];
//Fcb_PrinterFriendly.BorderSpacing.Around := cBORDERSPACE;
Fcb_PrinterFriendly.BorderSpacing.Top := cBORDERSPACE;
Fcb_PrinterFriendly.Caption := 'Use printer friendly colors';
//Fcb_legend.OnClick := @Apply;
// general style (color)
Fbtn_color := TColorButton.Create(Self);
with Fbtn_color do begin
Parent := Self;
BorderSpacing.Top := cBORDERSPACE;
AnchorSide[akLeft].Side := asrLeft;
AnchorSide[akLeft].Control := Fgb_exportsize;
AnchorSide[akTop].Side := asrBottom;
AnchorSide[akTop].Control := Fgb_exportsize;
Anchors := [akLeft, akTop];
//Top := 28;
Width := 132;
//BorderSpacing.Around := cBorderSpace;
Caption := 'Background';
OnColorChanged := @Apply;
end;
Fbtn_color.Top := 28;
Fbtn_color.Width := 132;
Fbtn_color.BorderSpacing.Around := cBorderSpace;
Fbtn_color.Caption := 'Background';
Fbtn_color.OnColorChanged := @Apply;
end;
destructor THelperFormPlotOptions.Destroy;
begin
Self.Hide;
inherited Destroy;
end;
{ THelperFormsSeries }
{===========================================================================}
constructor THelperFormsSeries.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
destructor THelperFormsSeries.Destroy;
begin
// TODO: destroy eventual existing forms
IF FfrmManualScale <> nil THEN FfrmManualScale.Free;
IF FfrmStyleChoose <> nil THEN FfrmStyleChoose.Free;
IF FfrmMarkersChoose <> nil THEN FfrmMarkersChoose.Free;
inherited Destroy;
end;
procedure THelperFormsSeries.SeriesManualScale(ASeriesIndex: Integer);
begin
IF FfrmManualScale = nil THEN FfrmManualScale := THelperFormSeriesManualScale.Create(OwnerPlot);
//FfrmManualScale.Owner := Self;
FfrmManualScale.InitForm(ASeriesIndex);
FfrmManualScale.Show;
end;
procedure THelperFormsSeries.SeriesStyleChoose(ASeriesIndex: Integer);
begin
IF FfrmStyleChoose = nil THEN FfrmStyleChoose := THelperFormSeriesStyleChoose.Create(OwnerPlot);
FfrmStyleChoose.InitForm(ASeriesIndex);
FfrmStyleChoose.Show;
end;
procedure THelperFormsSeries.SeriesMarkersChoose(ASeriesIndex: Integer);
begin
IF FfrmMarkersChoose = nil THEN FfrmMarkersChoose := THelperFormSeriesMarkersChoose.Create(OwnerPlot);
FfrmMarkersChoose.InitForm(ASeriesIndex);
FfrmMarkersChoose.Show;
end;
{ THelperFormSeriesManualScale }
{===========================================================================}
procedure THelperFormSeriesManualScale.Apply(Sender:TObject);
var
vViewRangeX, vViewRangeY, vViewRangeZ: TValueRange;
begin
vViewRangeX.min := StrToFloatDef(FEdXmin.Caption, 0);
vViewRangeX.max := StrToFloatDef(FEdXmax.Caption, 0);
TPlotAxisBase(OwnerPlot.Axis[TPlotSeries(OwnerPlot.Series[FActiveSeriesManualScale]).XAxis]).ViewRange := vViewRangeX;
vViewRangeY.min := StrToFloatDef(FEdYmin.Caption, 0);
vViewRangeY.max := StrToFloatDef(FEdYmax.Caption, 0);
TPlotAxisBase(OwnerPlot.Axis[TPlotSeries(OwnerPlot.Series[FActiveSeriesManualScale]).YAxis]).ViewRange := vViewRangeY;
IF FEdZmin.Enabled THEN BEGIN
vViewRangeZ.min := StrToFloatDef(FEdZmin.Caption, 0);
vViewRangeZ.max := StrToFloatDef(FEdZmax.Caption, 0);
TPlotAxisBase(OwnerPlot.Axis[TXYZPlotSeries(OwnerPlot.Series[FActiveSeriesManualScale]).ZAxis]).ViewRange := vViewRangeZ;
END;
OwnerPlot.Repaint;
end;
constructor THelperFormSeriesManualScale.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
OwnerPlot := TPlot(AOwner);
Self.Height := 240;
Self.Width := 220;
Self.Caption := 'Series scale';
Fed_SeriesName := TEdit.Create(Self);
with Fed_SeriesName do begin
Parent := Self;
BorderSpacing.Around := 6;
AnchorSide[akLeft].Side := asrLeft;
AnchorSide[akLeft].Control := Self;
AnchorSide[akRight].Side := asrRight;
AnchorSide[akRight].Control := Self;
AnchorSide[akTop].Side := asrTop;
AnchorSide[akTop].Control := Self;
Anchors:=[akLeft]+[akTop]+[akRight];
Caption := 'series';
Enabled:=false;
end;
// X controls
FEdXmin := TLabeledEdit.Create(Self);
FEdXmin.Parent := Self;
FEdXmin.BorderSpacing.Left := 20;
FEdXmin.BorderSpacing.Top := 0;
FEdXmin.Top := 50;
FEdXmin.AnchorSide[akLeft].Side := asrLeft;
FEdXmin.AnchorSide[akLeft].Control := Self;
//FEdXmin.AnchorSide[akTop].Side := asrTop;
//FEdXmin.AnchorSide[akTop].Control := Self;
FEdXmin.LabelPosition := lpAbove;
FEdXmin.LabelSpacing := 3;
FEdXmin.EditLabel.Caption := 'Xmin';
FEdXmax := TLabeledEdit.Create(Self);
FEdXmax.Parent := Self;
FEdXmax.BorderSpacing.Left := 20;
FEdXmax.BorderSpacing.Top := 0;
FEdXmax.AnchorSide[akLeft].Side := asrRight;
FEdXmax.AnchorSide[akLeft].Control := FEdXmin;
FEdXmax.AnchorSide[akTop].Side := asrTop;
FEdXmax.AnchorSide[akTop].Control := FEdXmin;
FEdXmax.LabelPosition := lpAbove;
FEdXmax.LabelSpacing := 3;
FEdXmax.EditLabel.Caption := 'Xmax';
// Y controls
FEdYmin := TLabeledEdit.Create(Self);
FEdYmin.Parent := Self;
FEdYmin.BorderSpacing.Left := 20;
FEdYmin.BorderSpacing.Top := 0;
FEdYmin.Top := 100;
FEdYmin.AnchorSide[akLeft].Side := asrLeft;
FEdYmin.AnchorSide[akLeft].Control := Self;
//FEdYmin.AnchorSide[akTop].Side := asrTop;
//FEdYmin.AnchorSide[akTop].Control := FEdXmin;
FEdYmin.LabelPosition := lpAbove;
FEdYmin.LabelSpacing := 3;
FEdYmin.EditLabel.Caption := 'Ymin';
FEdYmax := TLabeledEdit.Create(Self);
FEdYmax.Parent := Self;
FEdYmax.BorderSpacing.Left := 20;
FEdYmax.BorderSpacing.Top := 00;
FEdYmax.AnchorSide[akLeft].Side := asrRight;
FEdYmax.AnchorSide[akLeft].Control := FEdYmin;
FEdYmax.AnchorSide[akTop].Side := asrTop;
FEdYmax.AnchorSide[akTop].Control := FEdYmin;
FEdYmax.LabelPosition := lpAbove;
FEdYmax.LabelSpacing := 3;
FEdYmax.EditLabel.Caption := 'Ymax';
// Z controls
FEdZmin := TLabeledEdit.Create(Self);
FEdZmin.Parent := Self;
FEdZmin.BorderSpacing.Left := 20;
FEdZmin.BorderSpacing.Top := 00;
FEdZmin.Top := 150;
FEdZmin.AnchorSide[akLeft].Side := asrLeft;
FEdZmin.AnchorSide[akLeft].Control := Self;
//FEdZmin.AnchorSide[akTop].Side := asrTop;
//FEdZmin.AnchorSide[akTop].Control := FEdYmin;
FEdZmin.LabelPosition := lpAbove;
FEdZmin.LabelSpacing := 3;
FEdZmin.EditLabel.Caption := 'Zmin';
FEdZmax := TLabeledEdit.Create(Self);
FEdZmax.Parent := Self;
FEdZmax.BorderSpacing.Left := 20;
FEdZmax.BorderSpacing.Top := 00;
FEdZmax.AnchorSide[akLeft].Side := asrRight;
FEdZmax.AnchorSide[akLeft].Control := FEdZmin;
FEdZmax.AnchorSide[akTop].Side := asrTop;
FEdZmax.AnchorSide[akTop].Control := FEdZmin;
FEdZmax.LabelPosition := lpAbove;
FEdZmax.LabelSpacing := 3;
FEdZmax.EditLabel.Caption := 'Zmax';
end;
destructor THelperFormSeriesManualScale.Destroy;
begin
Self.Hide;
inherited Destroy;
end;
procedure THelperFormSeriesManualScale.InitForm(ASeriesIndex: Integer);
var
vViewRangeX, vViewRangeY, vViewRangeZ: TValueRange;
begin
FActiveSeriesManualScale := ASeriesIndex;
Fed_SeriesName.Caption := TPlotSeries(OwnerPlot.Series[FActiveSeriesManualScale]).Caption;
// init Z axis controls
FEdZmin.Caption := ''; FEdZmax.Caption := '';
FEdZmin.Enabled := FALSE; FEdZmax.Enabled := FALSE;
IF ( (OwnerPlot.Series[ASeriesIndex] is TXYPlotSeries) and
( not (OwnerPlot.Series[ASeriesIndex].IsFastSeries)) ) THEN BEGIN
vViewRangeX := TPlotAxisBase(OwnerPlot.Axis[TPlotSeries(OwnerPlot.Series[FActiveSeriesManualScale]).XAxis]).ViewRange;
vViewRangeY := TPlotAxisBase(OwnerPlot.Axis[TPlotSeries(OwnerPlot.Series[FActiveSeriesManualScale]).YAxis]).ViewRange;
END;
IF ( (OwnerPlot.Series[ASeriesIndex] is TXYZPlotSeries) and
( not (OwnerPlot.Series[ASeriesIndex].IsFastSeries)) ) THEN BEGIN
vViewRangeZ := TPlotAxisBase(OwnerPlot.Axis[TXYZPlotSeries(OwnerPlot.Series[FActiveSeriesManualScale]).ZAxis]).ViewRange;
FEdZmin.Caption := FloatToStr(vViewRangeZ.min);
FEdZmax.Caption := FloatToStr(vViewRangeZ.max);
FEdZmin.Enabled := TRUE; FEdZmax.Enabled := TRUE;
END;
IF (OwnerPlot.Series[ASeriesIndex] is TXYWFPlotSeries ) THEN BEGIN
vViewRangeX := TPlotAxisBase(OwnerPlot.Axis[TXYWFPlotSeries(OwnerPlot.Series[FActiveSeriesManualScale]).XAxis]).ViewRange;
vViewRangeY := TPlotAxisBase(OwnerPlot.Axis[TXYWFPlotSeries(OwnerPlot.Series[FActiveSeriesManualScale]).YAxis]).ViewRange;
vViewRangeZ := TPlotAxisBase(OwnerPlot.Axis[TXYWFPlotSeries(OwnerPlot.Series[FActiveSeriesManualScale]).ZAxis]).ViewRange;
FEdZmin.Caption := FloatToStr(vViewRangeZ.min);
FEdZmax.Caption := FloatToStr(vViewRangeZ.max);
FEdZmin.Enabled := TRUE; FEdZmax.Enabled := TRUE;
END;
IF ( OwnerPlot.Series[ASeriesIndex] is TXYSpectrumPlotSeries ) THEN BEGIN
vViewRangeX := TPlotAxisBase(OwnerPlot.Axis[TPlotSeries(OwnerPlot.Series[FActiveSeriesManualScale]).XAxis]).ViewRange;
vViewRangeY := TPlotAxisBase(OwnerPlot.Axis[TPlotSeries(OwnerPlot.Series[FActiveSeriesManualScale]).YAxis]).ViewRange;
END;
FEdXmin.Caption := FloatToStr(vViewRangeX.min);
FEdXmax.Caption := FloatToStr(vViewRangeX.max);
FEdYmin.Caption := FloatToStr(vViewRangeY.min);
FEdYmax.Caption := FloatToStr(vViewRangeY.max);
Self.Show;
end;
{ THelperFormSeriesStyleChoose }
{===========================================================================}
procedure THelperFormSeriesStyleChoose.EnableControlsLineStyle(AVisible: Boolean
);
begin
Fed_sizelines.Enabled := AVisible;
Fed_sizelines.Visible := AVisible;
Flbl_sizelines.Visible := AVisible;
Fcb_stylellines.Visible := AVisible;
Flbl_stylellines.Visible := AVisible;
end;
procedure THelperFormSeriesStyleChoose.Apply(Sender:TObject);
var
vOldColor: TColor;
vShape: TPointStyleShape;
vAxisString, vIndexString: string; // TODO: modularize this parser, see uPlotClass helpers and below !
vAxisIndex: integer;
begin
IF FInitInProgress THEN exit; // needed because events are fired during init form (series caption bug !)
vAxisString := ''; vIndexString := ''; vAxisIndex := -1;
// change style
IF Sender = Fcb_style THEN
begin
vOldColor := TPlotStyle(OwnerPlot.Series[FActiveSeriesStyleChoose].Style).Color;
IF Fcb_style.ItemIndex = 0 THEN BEGIN
OwnerPlot.Series[FActiveSeriesStyleChoose].Style := TSeriesStylePoints.Create;
EnableControlsLineStyle(FALSE);
END ELSE
IF Fcb_style.ItemIndex = 1 THEN BEGIN
OwnerPlot.Series[FActiveSeriesStyleChoose].Style := TSeriesStyleLines.Create;
EnableControlsLineStyle(TRUE);
END;
TPlotStyle(OwnerPlot.Series[FActiveSeriesStyleChoose].Style).Color := vOldColor;
end;
// set size
//IF (Sender = Fed_sizepoints) OR (Sender = Fed_sizelines) OR (Sender = Fcb_stylepoints) OR (Sender = Fcb_stylellines) THEN
begin
IF OwnerPlot.Series[FActiveSeriesStyleChoose].Style.ClassNameIs('TSeriesStyleLines') THEN
TSeriesStyleLines(OwnerPlot.Series[FActiveSeriesStyleChoose].Style).LineWidth := Fed_sizelines.Value;
IF OwnerPlot.Series[FActiveSeriesStyleChoose].Style is TSeriesStylePoints THEN begin
TSeriesStylePoints(OwnerPlot.Series[FActiveSeriesStyleChoose].Style).Diameter := Fed_sizepoints.Value;
vShape := TPointStyleShape(Fcb_stylepoints.ItemIndex);
TSeriesStylePoints(OwnerPlot.Series[FActiveSeriesStyleChoose].Style).Shape := vShape;
end;
end;
// seriesname
TPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]).Caption := Fed_seriesname.Caption;
// unit names
// there is not setter implemented for UnitString !! therefore use Add method
// FedXunit.Caption := TPlotSeries(OwnerPlot.Series[FActiveSeries]).UnitString[TPlotSeries(OwnerPlot.Series[FActiveSeries]).XAxis];
TPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]).AddUnit('x',FedXunit.Caption);
TPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]).AddUnit('Y',FedYunit.Caption);
TPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]).AddUnit('Z',FedZunit.Caption); // semms to be hardened for 3 units in 2D series
// color an axis ?
// ColorScale : attention: the axis to scale is a colorscale property
// which series to draw colored referred to an axis is a series property !
//
// parse ComboBox content : // TODO: modularize this parser, see uPlotClass helpers and below !
IF Fcb_coloraxes.ItemIndex > -1 THEN vAxisString := Fcb_coloraxes.Items[Fcb_coloraxes.ItemIndex];
vIndexString := vAxisString[1];
IF (Length(vAxisString)>1) THEN
IF (vAxisString[2] in ['0'..'9']) THEN vIndexString := vIndexString + vAxisString[2];
vAxisIndex := StrToIntDef(vIndexString, -1); //StrToIntDef(vIndexString,-1);
// end parser
IF Fcb_drawcolored. Checked THEN TPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]).ColoredAxis := vAxisIndex
ELSE TPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]).ColoredAxis := -1; //-1 means none is colored
// Interpolation
TPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]).Interpolate := Fcb_interpolate.Checked;
if TPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]).Interpolator <> nil then begin
TInterpolator_PixelXY( TPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]).Interpolator).IpolMode := TIpolMode(Fcb_Ipol_Mode.ItemIndex);
TInterpolator_PixelXY( TPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]).Interpolator).IpolAxisMode := TIpolAxisMode(Fcb_Ipol_AxisMode.ItemIndex);
end;
OwnerPlot.Repaint;
end;
constructor THelperFormSeriesStyleChoose.Create(AOwner: TComponent);
var
vLoop: integer;
const
cHspace = 12;
cVspace = 8;
cLeft = 16;
begin
inherited Create(AOwner);
FInitInProgress:=TRUE;
OwnerPlot := TPlot(AOwner);
Self.Height := 280;
Self.Width := 340;
Self.Caption := 'Series properties';
// LineStyle / PointStyle
// --- combos -------------------------------------
Fcb_style := TComboBox.Create(Self); // combobox style, fixed to form
Fcb_style.Parent := Self;
Fcb_style.Visible := TRUE;
Fcb_style.AnchorSide[akLeft].Side:=asrLeft;
Fcb_style.AnchorSide[akLeft].Control:=Self;
Fcb_style.Anchors:=Fcb_style.Anchors+[akLeft];
Fcb_style.Top := 28;
Fcb_style.BorderSpacing.Left := cLeft;
Fcb_style.Items.Add('Points');
Fcb_style.Items.Add('Lines');
Fcb_style.ItemIndex := -1;
Fcb_style.OnChange := @Apply;
Fcb_stylepoints := TComboBox.Create(Self); // combobox pointstyle
Fcb_stylepoints.Parent := Self;
Fcb_stylepoints.Visible := TRUE;
Fcb_stylepoints.AnchorParallel(akTop,0,Fcb_style);
Fcb_stylepoints.AnchorToNeighbour(akLeft,cHspace,Fcb_style);
for vLoop := ord(shapeDot) to ord(shapeMarkerTriangle) do begin
Fcb_stylepoints.Items.Add(TPointStyleShapeName[TPointStyleShape(vLoop)]);
end;
//Fcb_stylepoints.Items.Add('Dots');
//Fcb_stylepoints.Items.Add('Crosses');
Fcb_stylepoints.ItemIndex := 0;
Fcb_stylepoints.OnChange := @Apply;
Fcb_stylellines := TComboBox.Create(Self); // combobox linestyle
Fcb_stylellines.Parent := Self;
Fcb_stylellines.Visible := TRUE;
Fcb_stylellines.AnchorParallel(akTop,0,Fcb_stylepoints);
Fcb_stylellines.AnchorToNeighbour(akLeft,cHspace,Fcb_stylepoints);
Fcb_stylellines.Items.Add('Lines');
Fcb_stylellines.ItemIndex := 0;
Fcb_stylellines.OnChange := @Apply;
Flbl_style := TLabel.Create(Self); // label style
Flbl_style.Parent := Self;
Flbl_style.Visible := TRUE;
Flbl_style.Caption := 'Style';
Flbl_style.AnchorToNeighbour(akBottom,0,Fcb_style);
Flbl_style.AnchorParallel(akLeft,0,Fcb_style);
Flbl_stylepoints := TLabel.Create(Self); // label pointstyle
Flbl_stylepoints.Parent := Self;
Flbl_stylepoints.Visible := TRUE;
Flbl_stylepoints.Caption := 'Pointstyle';
Flbl_stylepoints.AnchorToNeighbour(akBottom,0,Fcb_stylepoints);
Flbl_stylepoints.AnchorParallel(akLeft,0,Fcb_stylepoints); ;
//Flbl_stylepoints.BorderSpacing.Left := 20;
Flbl_stylellines := TLabel.Create(Self); // label linestyle
Flbl_stylellines.Parent := Self;
Flbl_stylellines.Visible := TRUE;
Flbl_stylellines.Caption := 'Linestyle';
Flbl_stylellines.AnchorToNeighbour(akBottom,0,Fcb_stylellines);
Flbl_stylellines.AnchorParallel(akLeft,0,Fcb_stylellines);
//Flbl_stylepoints.BorderSpacing.Left := 20;
//--edits ----------------------------------
Flbl_sizepoints := TLabel.Create(Self); // label size
Flbl_sizepoints.Parent := Self;
Flbl_sizepoints.Visible := TRUE;
Flbl_sizepoints.Caption := 'Size';
Flbl_sizepoints.AnchorToNeighbour(akTop,cVspace,Fcb_stylepoints);
Flbl_sizepoints.AnchorParallel(akLeft,0,Fcb_stylepoints);
Fed_sizepoints := TSpinEdit.Create(Self); // spinedit size
Fed_sizepoints.Parent := Self;
Fed_sizepoints.Visible := TRUE;
Fed_sizepoints.AnchorToNeighbour(akTop,8,Flbl_sizepoints);
Fed_sizepoints.AnchorParallel(akLeft,0,Flbl_sizepoints);
Fed_sizepoints.OnChange := @Apply;
Fed_sizepoints.Value := 1;
Fed_sizepoints.MinValue := 1;
Fed_sizepoints.MaxValue := 13;
Fed_sizepoints.Increment := 2;
Flbl_sizelines := TLabel.Create(Self); // label size
Flbl_sizelines.Parent := Self;
Flbl_sizelines.Visible := TRUE;
Flbl_sizelines.Caption := 'Size';
Flbl_sizelines.AnchorToNeighbour(akTop,cVspace,Fcb_stylellines);
Flbl_sizelines.AnchorParallel(akLeft,0,Fcb_stylellines);
Fed_sizelines := TSpinEdit.Create(Self); // spinedit size
Fed_sizelines.Parent := Self;
Fed_sizelines.Visible := TRUE;
Fed_sizelines.AnchorToNeighbour(akTop,8,Flbl_sizelines);
Fed_sizelines.AnchorParallel(akLeft,0,Flbl_sizelines);
Fed_sizelines.OnChange := @Apply;
Fed_sizelines.Value := 1;
Fed_sizelines.MinValue := 1;
Fed_sizelines.MaxValue := 9;
Fed_sizelines.Increment := 1;
// interpolate
Fcb_interpolate := TCheckBox.Create(Self);
with Fcb_interpolate do begin
Parent := Self;
Visible := TRUE;
Checked := FALSE;
AnchorSide[akLeft].Side:=asrLeft;
AnchorSide[akLeft].Control:=Fcb_style;
AnchorSide[akTop].Side:=asrBottom;
AnchorSide[akTop].Control:=Fed_sizepoints;
Anchors:=[akLeft]+[akTop];
BorderSpacing.Top := cVspace;
Caption := 'Interpolate';
end;
Fcb_Ipol_Mode := TComboBox.Create(Self);
with Fcb_Ipol_Mode do begin
Parent := Self;
Visible := TRUE;
AnchorSide[akLeft].Side:=asrRight;
AnchorSide[akLeft].Control:=Fcb_interpolate;
AnchorSide[akTop].Side:=asrCenter;
AnchorSide[akTop].Control:=Fcb_interpolate;
Anchors:=[akLeft]+[akTop];
Items.Add('step');
Items.Add('linear');
ItemIndex:=1;
end;
Fcb_Ipol_AxisMode := TComboBox.Create(Self);
with Fcb_Ipol_AxisMode do begin
Parent := Self;
Visible := TRUE;
AnchorSide[akLeft].Side:=asrRight;
AnchorSide[akLeft].Control:=Fcb_Ipol_Mode;
AnchorSide[akTop].Side:=asrCenter;
AnchorSide[akTop].Control:=Fcb_interpolate;
Anchors:=[akLeft]+[akTop];
Items.Add('X only');
Items.Add('XY');
ItemIndex:=1;
end;
// --name and units // shape splitter
Fshp := TShape.Create(Self);
Fshp.Parent := Self;
Fshp.Visible := TRUE;
Fshp.Pen.Width := 4;
Fshp.Pen.Color := clGray;
Fshp.Height := 4;
//Fshp.AnchorToNeighbour(akTop,cVspace,Fed_sizepoints);
Fshp.AnchorSide[akLeft].Control := Self;
Fshp.AnchorSide[akLeft].Side := asrLeft;
Fshp.AnchorSide[akRight].Control := Self;
Fshp.AnchorSide[akRight].Side := asrRight;
Fshp.AnchorSideTop.Control := Fcb_interpolate;
Fshp.AnchorSideTop.Side := asrBottom;
Fshp.Anchors := [akTop, akLeft, akRight];
Fshp.BorderSpacing.Around := 6;
Flbl_seriesname := TLabel.Create(Self); // label seriesname
Flbl_seriesname.Parent := Self;
Flbl_seriesname.Visible := TRUE;
Flbl_seriesname.Caption := 'Name of Series';
Flbl_seriesname.AnchorToNeighbour(akTop,cVspace,Fshp);
Flbl_seriesname.AnchorParallel(akLeft,0,Fshp);
Fed_seriesname := TEdit.Create(Self); // edit seriesname
Fed_seriesname.Parent := Self;
Fed_seriesname.Visible := TRUE;
Fed_seriesname.AnchorSide[akLeft].Control := Flbl_seriesname;
Fed_seriesname.AnchorSide[akLeft].Side := asrRight;
Fed_seriesname.AnchorSide[akRight].Control := Self;
Fed_seriesname.AnchorSide[akRight].Side := asrRight;
Fed_seriesname.AnchorSide[akTop].Control := Flbl_seriesname;
Fed_seriesname.AnchorSide[akTop].Side := asrCenter;
Fed_seriesname.Anchors := [akTop, akLeft, akRight];
Fed_seriesname.BorderSpacing.Around := 6;
Flbl_units := TLabel.Create(Self); // label seriesname
Flbl_units.Parent := Self;
Flbl_units.Visible := TRUE;
Flbl_units.Caption := 'Units (XYZ)';
Flbl_units.AnchorToNeighbour(akTop,cVspace,Flbl_seriesname);
Flbl_units.AnchorParallel(akLeft,0,Flbl_seriesname);
FedXunit := TEdit.Create(Self); // edit Xunit
FedXunit.Parent := Self;
FedXunit.Visible := TRUE;
FedXunit.AnchorSide[akTop].Control := Flbl_units;
FedXunit.AnchorSide[akTop].Side := asrCenter;
FedXunit.AnchorSide[akLeft].Control := Flbl_units;
FedXunit.AnchorSide[akLeft].Side := asrRight;
FedXunit.Anchors := [akLeft, akTop];
FedXunit.BorderSpacing.Around := 6;
FedYunit := TEdit.Create(Self); // edit Xunit
FedYunit.Parent := Self;
FedYunit.Visible := TRUE;
FedYunit.AnchorSide[akTop].Control := Flbl_units;
FedYunit.AnchorSide[akTop].Side := asrCenter;
FedYunit.AnchorSide[akLeft].Control := FedXunit;
FedYunit.AnchorSide[akLeft].Side := asrRight;
FedYunit.Anchors := [akLeft, akTop];
FedYunit.BorderSpacing.Around := 6;
FedZunit := TEdit.Create(Self); // edit Xunit
FedZunit.Parent := Self;
FedZunit.Visible := TRUE;
FedZunit.AnchorSide[akTop].Control := Flbl_units;
FedZunit.AnchorSide[akTop].Side := asrCenter;
FedZunit.AnchorSide[akLeft].Control := FedYunit;
FedZunit.AnchorSide[akLeft].Side := asrRight;
FedZunit.Anchors := [akLeft, akTop];
FedZunit.BorderSpacing.Around := 6;
// colored axes
Fcb_drawcolored := TCheckBox.Create(Self);
Fcb_drawcolored.Parent := Self;
Fcb_drawcolored.Visible := TRUE;
Fcb_drawcolored.Checked := FALSE;
Fcb_drawcolored.AnchorSide[akLeft].Side:=asrLeft;
Fcb_drawcolored.AnchorSide[akLeft].Control:=Self;
Fcb_drawcolored.AnchorSide[akTop].Side:=asrBottom;
Fcb_drawcolored.AnchorSide[akTop].Control:=Flbl_units;
Fcb_drawcolored.Anchors:=Fcb_drawcolored.Anchors+[akLeft]+[akTop];
Fcb_drawcolored.BorderSpacing.Around := cVspace;
Fcb_drawcolored.Caption := 'Draw color-scaled axis:';
//Fcb_drawcolored.OnClick := @Apply;
Fcb_coloraxes := TComboBox.Create(Self);
Fcb_coloraxes.Parent := Self;
Fcb_coloraxes.Visible := TRUE;
Fcb_coloraxes.AnchorSide[akLeft].Side:=asrRight;
Fcb_coloraxes.AnchorSide[akLeft].Control:=Fcb_drawcolored;
Fcb_coloraxes.AnchorSide[akTop].Side:=asrCenter;
Fcb_coloraxes.AnchorSide[akTop].Control:=Fcb_drawcolored;
Fcb_coloraxes.Anchors:=Fcb_coloraxes.Anchors+[akLeft]+[akTop];
Fcb_coloraxes.BorderSpacing.Around := cVspace;
//Fcb_coloraxes.OnChange := @Apply;
end;
destructor THelperFormSeriesStyleChoose.Destroy;
begin
Self.Close;
inherited Destroy;
end;
procedure THelperFormSeriesStyleChoose.InitForm(ASeriesIndex:Integer);
var
vShape: TPointStyleShape;
begin
FInitInProgress:=TRUE;
FActiveSeriesStyleChoose := ASeriesIndex;
// init controls - lines/points
IF OwnerPlot.Series[FActiveSeriesStyleChoose].Style is TSeriesStyleLines THEN begin
Fcb_style.ItemIndex := 1;
Fed_sizepoints.Value := TSeriesStylePoints(OwnerPlot.Series[FActiveSeriesStyleChoose].Style).Diameter;
Fed_sizelines.Value := TSeriesStyleLines(OwnerPlot.Series[FActiveSeriesStyleChoose].Style).LineWidth;
end ELSE
IF OwnerPlot.Series[FActiveSeriesStyleChoose].Style.ClassNameIs('TSeriesStylePoints') THEN begin
Fcb_style.ItemIndex := 0;
Fed_sizepoints.Value := TSeriesStylePoints(OwnerPlot.Series[FActiveSeriesStyleChoose].Style).Diameter;
// shapes
vShape := TSeriesStylePoints(OwnerPlot.Series[FActiveSeriesStyleChoose].Style).Shape;
Fcb_stylepoints.ItemIndex := ord(vShape);
end;
//
// deactivate unused controls - lines/points
IF OwnerPlot.Series[FActiveSeriesStyleChoose].Style.ClassNameIs('TSeriesStyleLines') THEN
EnableControlsLineStyle(TRUE) ELSE
EnableControlsLineStyle(FALSE);
// seriesname
Fed_seriesname.Caption := TPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]).Caption;
// unitnames
FedXunit.Caption := TPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]).UnitString[TPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]).XAxis];
FedYunit.Caption := TPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]).UnitString[TPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]).YAxis];
IF TPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]) is TXYZPlotSeries THEN
FedZunit.Caption := TPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]).UnitString[TXYZPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]).ZAxis]; // TODO !
// Combo Axes
// empty
with Fcb_coloraxes.Items do begin
while Count > 0 do begin
Fcb_coloraxes.Items.Delete(0);
end;
end;
// refill
// add items; axes used by the series for colorscale
Fcb_coloraxes.Items.Add( IntToStr(TPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]).XAxis) + ' - X axis' );
IF TPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]) is TXYPlotSeries THEN
Fcb_coloraxes.Items.Add( IntToStr(TPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]).YAxis) + ' - Y axis' );
IF TPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]) is TXYZPlotSeries THEN
Fcb_coloraxes.Items.Add( IntToStr(TXYZPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]).ZAxis) + ' - Z axis' );
// choose itemindex for correct value
//IF TPlotSeries(OwnerPlot.Series[FActiveSeries]).ColoredAxis =
// TPlotSeries(OwnerPlot.Series[FActiveSeries]).XAxis THEN Fcb_coloraxes.ItemIndex := 0;
Fcb_coloraxes.ItemIndex := 0; // default to X-axis; every series has an X-axsi (Todo refactoring OwnerAxis to XAxis)
IF TPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]).ColoredAxis =
TPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]).YAxis THEN Fcb_coloraxes.ItemIndex := 1;
IF TPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]) is TXYZPlotSeries THEN begin
IF TPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]).ColoredAxis =
TXYZPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]).ZAxis THEN Fcb_coloraxes.ItemIndex := 2;
end;
//
// 22.03.13
// do not autoapply until series-caption bug is evaluated:
// series caption changes unwantedly when this menu is used with autoapply
// maybe some init problem with Create or during InitForm ??
//Fcb_style.OnChange := @Apply;
//Fcb_stylepoints.OnChange := @Apply;
//Fcb_stylellines.OnChange := @Apply;
//Fed_sizepoints.OnChange := @Apply;
//Fed_sizelines.OnChange := @Apply;
//Fcb_drawcolored.OnClick := @Apply;
//Fcb_coloraxes.OnChange := @Apply;
// interpolation
Fcb_interpolate.Checked := TPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]).Interpolate;
if TPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]).Interpolator <> nil then begin
Fcb_Ipol_Mode.ItemIndex := ord( TInterpolator_PixelXY( TPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]).Interpolator).IpolMode );
Fcb_Ipol_AxisMode.ItemIndex := ord( TInterpolator_PixelXY( TPlotSeries(OwnerPlot.Series[FActiveSeriesStyleChoose]).Interpolator).IpolAxisMode );
end;
FInitInProgress:=FALSE;
Self.Show;
//MessageDlg('StyleChoose','TODO: Choose style here', mtInformation, [mbOK],0);
end;
{ THelperFormSeriesMarkersChoose }
procedure THelperFormSeriesMarkersChoose._PropertyChanged(Sender: TObject);
begin
IF Sender = Fcb_mkrIndex THEN BEGIN
ShowMarkerProperties(Fcb_mkrIndex.ItemIndex);
END;
end;
procedure THelperFormSeriesMarkersChoose.AddRemoveMarker(Sender: TObject);
var
vMarkerIndex: Integer;
vMarkerContainer: TMarkerContainer;
begin
vMarkerContainer := TPlotSeries(OwnerPlot.Series[FActiveSeriesMarkersChoose]).MarkerContainer;
if Sender = Fbtn_Addmarker then begin
vMarkerIndex := vMarkerContainer.AddMarker;
Fcb_mkrIndex.Items.Add(IntToStr(vMarkerIndex));
InitForm(FActiveSeriesMarkersChoose);
ShowMarkerProperties(vMarkerIndex);
end else
if Sender = Fbtn_Removemarker then begin
vMarkerIndex := vMarkerContainer.RemoveMarker(vMarkerContainer.Marker[Fcb_mkrIndex.ItemIndex]);
Fcb_mkrIndex.Items.Delete(vMarkerIndex);
InitForm(FActiveSeriesMarkersChoose);
ShowMarkerProperties(vMarkerIndex-1);
end;
end;
procedure THelperFormSeriesMarkersChoose.ShowMarkerProperties(
AMarkerIndex: Integer);
var
vLoop: Integer;
vMarkShapes: set of TMarkerShape;
vMarkerContainer: TMarkerContainer;
begin
vMarkerContainer := TPlotSeries(OwnerPlot.Series[FActiveSeriesMarkersChoose]).MarkerContainer;
if (AMarkerIndex < 0) or (AMarkerIndex > vMarkerContainer.MarkerCount-1) then begin
Fcb_mkrIndex.ItemIndex := -1;
Fcb_mkrType.ItemIndex := -1;
Fcb_mkrMode.ItemIndex := -1;
for vLoop:=0 to Fcb_mkrStyle.Items.Count-1 do begin
Fcb_mkrStyle.Checked[vLoop] := false;
end;
Fed_diameter.Value := 11;
Fed_linewidth.Value := 1;
Fbtn_color.ButtonColor :=clRed;
Fed_markeralpha.Value := 255;
Fbtn_backgndcolor.ButtonColor :=clCream;
Fed_backgndalpha.Value:= 255;
Fed_Xindex.Value := 0;
Fed_XValue.Text := '0';
Fed_YValue.Text := '0';
Fed_ZValue.Text := '0';
exit;
end;
Fcb_mkrIndex.ItemIndex := AMarkerIndex;
Fcb_mkrType.ItemIndex := ord(vMarkerContainer.Marker[AMarkerIndex].MarkerType);
Fcb_mkrMode.ItemIndex := ord(vMarkerContainer.Marker[AMarkerIndex].MarkerMode);
vMarkShapes := vMarkerContainer.Marker[AMarkerIndex].VisualParams.StyleParams.MarkShapes;
for vLoop:=0 to Fcb_mkrStyle.Items.Count-1 do begin
Fcb_mkrStyle.Checked[vLoop] := TMarkerShape(vLoop) in vMarkShapes;
end;
Fed_diameter.Value := vMarkerContainer.Marker[AMarkerIndex].VisualParams.StyleParams.Diameter;
Fed_linewidth.Value := vMarkerContainer.Marker[AMarkerIndex].VisualParams.StyleParams.LineWidth;
Fbtn_color.ButtonColor :=vMarkerContainer.Marker[AMarkerIndex].VisualParams.StyleParams.Color;
Fed_markeralpha.Value := (vMarkerContainer.Marker[AMarkerIndex].VisualParams.StyleParams.Alpha DIV 255);
Fbtn_backgndcolor.ButtonColor :=vMarkerContainer.Marker[AMarkerIndex].VisualParams.StyleParams.BackGndColor;
Fed_backgndalpha.Value := (vMarkerContainer.Marker[AMarkerIndex].VisualParams.StyleParams.BackGndAlpha DIV 255);
Fed_Xindex.Value := vMarkerContainer.Marker[AMarkerIndex].Index ;
Fed_XValue.Text := FloatToStrF(vMarkerContainer.Marker[AMarkerIndex].FixedValueXYZ.X, ffFixed,4,4);
Fed_YValue.Text := FloatToStrF(vMarkerContainer.Marker[AMarkerIndex].FixedValueXYZ.Y, ffFixed,4,4);
Fed_ZValue.Text := FloatToStrF(vMarkerContainer.Marker[AMarkerIndex].FixedValueXYZ.Z, ffFixed,4,4);
end;
procedure THelperFormSeriesMarkersChoose.ApplyMarkerProperties(
AMarkerIndex: Integer);
var
vLoop: Integer;
vMarkShapes: set of TMarkerShape;
vMarkerContainer: TMarkerContainer;
//vStyleParams: TMarkerStyleParams;
vVisualParams: TMarkerVisualParams;
vXYZValue: TXYZValue;
begin
if Fcb_mkrIndex.ItemIndex <> AMarkerIndex then begin
EPlot.Create('MarkerIndex shown and demanded for apply do not match !');
exit;
end;
vMarkerContainer := TPlotSeries(OwnerPlot.Series[FActiveSeriesMarkersChoose]).MarkerContainer;
vMarkerContainer.Marker[AMarkerIndex].MarkerType := TMarkerType(Fcb_mkrType.ItemIndex) ;
vMarkerContainer.Marker[AMarkerIndex].MarkerMode := TMarkerMode(Fcb_mkrMode.ItemIndex) ;
vMarkShapes:=[];
for vLoop:=0 to Fcb_mkrStyle.Items.Count-1 do begin
if Fcb_mkrStyle.Checked[vLoop] then include(vMarkShapes, TMarkerShape(vLoop));
end;
vVisualParams := vMarkerContainer.Marker[AMarkerIndex].VisualParams;
with vVisualParams.StyleParams do begin
MarkShapes := vMarkShapes;
Diameter := Fed_diameter.Value;
LineWidth := Fed_linewidth.Value;
Color := Fbtn_color.ButtonColor;
Alpha := Fed_markeralpha.Value * 255;
BackGndColor := Fbtn_backgndcolor.ButtonColor;
BackGndAlpha := Fed_backgndalpha.Value * 255;
end;
vMarkerContainer.Marker[AMarkerIndex].VisualParams := vVisualParams;
vMarkerContainer.Marker[AMarkerIndex].Index := Fed_Xindex.Value ;
vXYZValue.X := StrToFloatDef(Fed_XValue.Text, 0);
vXYZValue.Y := StrToFloatDef(Fed_YValue.Text, 0);
vXYZValue.Z := StrToFloatDef(Fed_ZValue.Text, 0);
vMarkerContainer.Marker[AMarkerIndex].FixedValueXYZ := vXYZValue;
end;
procedure THelperFormSeriesMarkersChoose.InitForm(ASeriesIndex: Integer);
var
vLoop: Integer;
vMarkerCount: Integer;
vMarkerContainer: TMarkerContainer;
begin
FInitInProgress:=TRUE;
FActiveSeriesMarkersChoose := ASeriesIndex;
vMarkerContainer := TPlotSeries(OwnerPlot.Series[FActiveSeriesMarkersChoose]).MarkerContainer;
vMarkerCount := vMarkerContainer.MarkerCount;
while (Fcb_mkrType.Items.Count > 0) do Fcb_mkrType.Items.Delete(0);
for vLoop := ord(Low(TMarkerType)) to ord(high(TMarkerType)) do
Fcb_mkrType.Items.Add(cMARKER_TYPE_NAMES[TMarkerType(vLoop)]);
while (Fcb_mkrMode.Items.Count > 0) do Fcb_mkrMode.Items.Delete(0);
for vLoop := ord(Low(TMarkerMode)) to ord(high(TMarkerMode)) do
Fcb_mkrMode.Items.Add(cMARKER_MODE_NAMES[TMarkerMode(vLoop)]);
while (Fcb_mkrStyle.Items.Count > 0) do Fcb_mkrStyle.Items.Delete(0);
for vLoop := ord(Low(TMarkerShape)) to ord(high(TMarkerShape)) do
Fcb_mkrStyle.Items.Add(cMARKER_SHAPE_NAMES[TMarkerShape(vLoop)]);
while (Fcb_mkrIndex.Items.Count > 0) do Fcb_mkrIndex.Items.Delete(0);
IF vMarkerCount > 0 THEN begin
for vLoop:=0 to vMarkerContainer.MarkerCount-1 do
Fcb_mkrIndex.Items.Add(IntToStr(vLoop));
ShowMarkerProperties(0);
end;
FInitInProgress:=FALSE;
Self.Show;
end;
procedure THelperFormSeriesMarkersChoose.Apply(Sender: TObject);
begin
// TODO: application handling better !
ApplyMarkerProperties(Fcb_mkrIndex.ItemIndex);
inherited Apply(Sender);
end;
constructor THelperFormSeriesMarkersChoose.Create(AOwner: TComponent);
const
cVSPACE = 6;
cLEFT = 6;
begin
inherited Create(AOwner);
OwnerPlot := TPlot(AOwner);
Self.Height := 280;
Self.Width := 340;
Self.Caption := 'Marker properties';
Flbl_mkrIndex := TLabel.Create(Self); // Checkbox Index
with Flbl_mkrIndex do begin
Parent := Self;
BorderSpacing.Left:=cLEFT;
BorderSpacing.Top:=cVSPACE;
AnchorSide[akLeft].Side := asrLeft;
AnchorSide[akLeft].Control := Self;
AnchorSide[akTop].Side := asrTop;
AnchorSide[akTop].Control := Self;
Anchors := [akLeft, akTop];
Caption := 'Marker: ';
end;
Fcb_mkrIndex := TComboBox.Create(Self);
with Fcb_mkrIndex do begin
Parent := Self;
AnchorSide[akLeft].Side := asrRight;
AnchorSide[akLeft].Control := Flbl_mkrIndex;
//AnchorSide[akRight].Side := asrLeft;
//AnchorSide[akRight].Control := Flbl_mkrStyle;
AnchorSide[akTop].Side := asrCenter;
AnchorSide[akTop].Control := Flbl_mkrIndex;
Anchors := [akLeft, akTop];
//OnChange:=@Apply;
OnChange:=@_PropertyChanged;
end;
Fbtn_RemoveMarker := TButton.Create(self);
with Fbtn_RemoveMarker do begin
Parent := Self;
BorderSpacing.Left:=cLEFT;
AnchorSide[akLeft].Side := asrRight;
AnchorSide[akLeft].Control := Fcb_mkrIndex;
//AnchorSide[akRight].Side := asrLeft;
//AnchorSide[akRight].Control := Flbl_mkrStyle;
AnchorSide[akTop].Side := asrCenter;
AnchorSide[akTop].Control := Flbl_mkrIndex;
Anchors := [akLeft, akTop];
Caption := 'Remove';
OnClick := @AddRemoveMarker;
end;
Fbtn_Addmarker := TButton.Create(self);
with Fbtn_Addmarker do begin
Parent := Self;
BorderSpacing.Left:=cLEFT;
AnchorSide[akLeft].Side := asrRight;
AnchorSide[akLeft].Control := Fbtn_RemoveMarker;
//AnchorSide[akRight].Side := asrLeft;
//AnchorSide[akRight].Control := Flbl_mkrStyle;
AnchorSide[akTop].Side := asrCenter;
AnchorSide[akTop].Control := Flbl_mkrIndex;
Anchors := [akLeft, akTop];
Caption := 'New marker';
OnClick := @AddRemoveMarker;
end;
// labels line 1
Flbl_mkrType := TLabel.Create(Self);
with Flbl_mkrType do begin
Parent := Self;
BorderSpacing.Top := cVSPACE;
AnchorSide[akLeft].Side := asrLeft;
AnchorSide[akLeft].Control := Flbl_mkrIndex;
AnchorSide[akTop].Side := asrBottom;
AnchorSide[akTop].Control := Flbl_mkrIndex;
Anchors := [akLeft, akTop];
Caption := 'Type';
end;
Flbl_mkrMode := TLabel.Create(Self);
with Flbl_mkrMode do begin
Parent := Self;
BorderSpacing.Left := 72;
AnchorSide[akLeft].Side := asrRight;
AnchorSide[akLeft].Control := Flbl_mkrType;
AnchorSide[akTop].Side := asrCenter;
AnchorSide[akTop].Control := Flbl_mkrType;
Anchors := [akLeft, akTop];
Caption := 'Mode';
end;
Fcb_mkrMode := TComboBox.Create(Self);
with Fcb_mkrMode do begin
Parent := Self;
AnchorSide[akLeft].Side := asrLeft;
AnchorSide[akLeft].Control := Flbl_mkrMode;
//AnchorSide[akRight].Side := asrLeft;
//AnchorSide[akRight].Control := Flbl_mkrStyle;
AnchorSide[akTop].Side := asrBottom;
AnchorSide[akTop].Control := Flbl_mkrMode;
Anchors := [akLeft, akTop];
AutoSize:=true;
//OnChange:=@Apply;
end;
Fcb_mkrType := TComboBox.Create(Self);
with Fcb_mkrType do begin
Parent := Self;
BorderSpacing.Right := 4;
//AnchorSide[akLeft].Side := asrLeft;
//AnchorSide[akLeft].Control := Flbl_mkrType;
AnchorSide[akRight].Side := asrLeft;
AnchorSide[akRight].Control := Fcb_mkrMode;
AnchorSide[akTop].Side := asrBottom;
AnchorSide[akTop].Control := Flbl_mkrType;
Anchors := [akTop, akRight];
//OnChange:=@Apply;
AutoSize:=true;
//Width:=72;
end;
// line 3 index
Flbl_XIndex := TLabel.Create(Self);
with Flbl_XIndex do begin
Parent := Self;
BorderSpacing.Top := cVSPACE;
AnchorSide[akLeft].Side := asrLeft;
AnchorSide[akLeft].Control := Flbl_mkrIndex;
AnchorSide[akTop].Side := asrBottom;
AnchorSide[akTop].Control := Fcb_mkrType;
Anchors := [akLeft, akTop];
Caption := 'Index';
end;
Fed_Xindex := TSpinEdit.Create(Self);
with Fed_Xindex do begin
Parent := Self;
AnchorSide[akLeft].Side := asrRight;
AnchorSide[akLeft].Control := Flbl_XIndex;
AnchorSide[akTop].Side := asrCenter;
AnchorSide[akTop].Control := Flbl_XIndex;
Anchors := [akLeft, akTop];
MinValue := 0;
MaxValue := 15; // TODO
Value := 0;
OnChange:=@Apply;
end;
// line 4 values
Flbl_XYZValues := TLabel.Create(Self);
with Flbl_XYZValues do begin
Parent := Self;
BorderSpacing.Top := cVSPACE;
AnchorSide[akLeft].Side := asrLeft;
AnchorSide[akLeft].Control := Flbl_mkrIndex;
AnchorSide[akTop].Side := asrBottom;
AnchorSide[akTop].Control := Flbl_XIndex;
Anchors := [akLeft, akTop];
Caption := 'Fixed X Y Z';
end;
Fed_XValue := TEdit.Create(Self);
with Fed_XValue do begin
Parent := Self;
AnchorSide[akLeft].Side := asrRight;
AnchorSide[akLeft].Control := Flbl_XYZValues;
AnchorSide[akTop].Side := asrCenter;
AnchorSide[akTop].Control := Flbl_XYZValues;
Anchors := [akLeft, akTop];
Text:='';
end;
Fed_YValue := TEdit.Create(Self);
with Fed_YValue do begin
Parent := Self;
AnchorSide[akLeft].Side := asrRight;
AnchorSide[akLeft].Control := Fed_XValue;
AnchorSide[akTop].Side := asrCenter;
AnchorSide[akTop].Control := Flbl_XYZValues;
Anchors := [akLeft, akTop];
Text:='';
end;
Fed_ZValue := TEdit.Create(Self);
with Fed_ZValue do begin
Parent := Self;
AnchorSide[akLeft].Side := asrRight;
AnchorSide[akLeft].Control := Fed_YValue;
AnchorSide[akTop].Side := asrCenter;
AnchorSide[akTop].Control := Flbl_XYZValues;
Anchors := [akLeft, akTop];
Text:='';
end;
// line 5 diamteer / linwidth
Flbl_diameter := TLabel.Create(Self);
with Flbl_diameter do begin
Parent := Self;
BorderSpacing.Top := 2* cVSPACE;
AnchorSide[akLeft].Side := asrLeft;
AnchorSide[akLeft].Control := Flbl_mkrIndex;
AnchorSide[akTop].Side := asrBottom;
AnchorSide[akTop].Control := Flbl_XYZValues;
Anchors := [akLeft, akTop];
Caption := 'Diameter';
end;
Fed_diameter := TSpinEdit.Create(Self);
with Fed_diameter do begin
Parent := Self;
AnchorSide[akLeft].Side := asrRight;
AnchorSide[akLeft].Control := Flbl_diameter;
AnchorSide[akTop].Side := asrCenter;
AnchorSide[akTop].Control := Flbl_diameter;
Anchors := [akLeft, akTop];
MinValue := 0;
MaxValue := 21;
Value := 11;
end;
Flbl_linewidth := TLabel.Create(Self);
with Flbl_linewidth do begin
Parent := Self;
AnchorSide[akLeft].Side := asrRight;
AnchorSide[akLeft].Control := Fed_diameter;
AnchorSide[akTop].Side := asrCenter;
AnchorSide[akTop].Control := Flbl_diameter;
Anchors := [akLeft, akTop];
Caption := 'Linewidth';
end;
Fed_linewidth := TSpinEdit.Create(Self);
with Fed_linewidth do begin
Parent := Self;
AnchorSide[akLeft].Side := asrRight;
AnchorSide[akLeft].Control := Flbl_linewidth;
AnchorSide[akTop].Side := asrCenter;
AnchorSide[akTop].Control := Flbl_diameter;
Anchors := [akLeft, akTop];
MinValue := 0;
MaxValue := 15;
Value := 1;
end;
// line 6 colors
Fbtn_color := TColorButton.Create(Self);
with Fbtn_color do begin
Parent := Self;
BorderSpacing.Top := cVSPACE;
AnchorSide[akLeft].Side := asrLeft;
AnchorSide[akLeft].Control := Flbl_mkrIndex;
AnchorSide[akTop].Side := asrBottom;
AnchorSide[akTop].Control := Flbl_diameter;
Anchors := [akLeft, akTop];
Caption:='Marker';
Width:=96;
end;
Fbtn_backgndcolor := TColorButton.Create(Self);
with Fbtn_backgndcolor do begin
Parent := Self;
BorderSpacing.Top := cVSPACE;
AnchorSide[akLeft].Side := asrLeft;
AnchorSide[akLeft].Control := Fbtn_color;
AnchorSide[akTop].Side := asrBottom;
AnchorSide[akTop].Control := Fbtn_color;
Anchors := [akLeft, akTop];
Caption:='Background';
Width:=96;
end;
Fed_markeralpha := TSpinEdit.Create(Self);
with Fed_markeralpha do begin
Parent := Self;
AnchorSide[akLeft].Side := asrRight;
AnchorSide[akLeft].Control := Fbtn_color;
AnchorSide[akTop].Side := asrCenter;
AnchorSide[akTop].Control := Fbtn_color;
Anchors := [akLeft, akTop];
MinValue := 0;
MaxValue := 255;
Value := 255;
end;
Fed_backgndalpha := TSpinEdit.Create(Self);
with Fed_backgndalpha do begin
Parent := Self;
AnchorSide[akLeft].Side := asrRight;
AnchorSide[akLeft].Control := Fbtn_backgndcolor;
AnchorSide[akTop].Side := asrCenter;
AnchorSide[akTop].Control := Fbtn_backgndcolor;
Anchors := [akLeft, akTop];
MinValue := 0;
MaxValue := 255;
Value := 255;
end;
Fcb_mkrStyle := TCheckListBox.Create(Self);
with Fcb_mkrStyle do begin
Parent := Self;
AnchorSide[akLeft].Side := asrRight;
AnchorSide[akLeft].Control := Fbtn_color;
//AnchorSide[akRight].Side := asrRight;
//AnchorSide[akRight].Control := self;
AnchorSide[akTop].Side := asrTop;
AnchorSide[akTop].Control := Fbtn_color;
AnchorSide[akLeft].Side := asrRight;
AnchorSide[akLeft].Control := Fed_markeralpha;
Anchors := [akLeft, akTop];
//AutoSize:=true;
//OnChange:=@Apply;
end;
end;
destructor THelperFormSeriesMarkersChoose.Destroy;
begin
inherited Destroy;
end;
{ THelperFormsPlotRect }
{===========================================================================}
constructor THelperFormsPlotRect.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
destructor THelperFormsPlotRect.Destroy;
begin
IF FfrmPlotRectStyleChoose <> nil THEN FfrmPlotRectStyleChoose.Free;
inherited Destroy;
end;
procedure THelperFormsPlotRect.PlotRectStyleChoose(APlotRectIndex: Integer);
begin
IF FfrmPlotRectStyleChoose = nil THEN FfrmPlotRectStyleChoose := THelperFormPlotRectStyleChoose.Create(OwnerPlot);
FfrmPlotRectStyleChoose.InitForm(APlotRectIndex);
end;
{ THelperFormPlotRectStyleChoose }
{===========================================================================}
procedure THelperFormPlotRectStyleChoose.Apply(Sender: TObject);
var
vAxisString, vIndexString: string; // TODO: modularize this parser, see uPlotClass helpers
vAxisIndex: integer;
begin
vAxisString := '0';
// Background Color
IF Sender = Fbtn_color THEN begin
//writeln('color3 after apply', ColorToString(Fbtn_color.ButtonColor) );
TPlotRect(OwnerPlot.PlotRect[FActivePlotRect]).Style.Brush.Color := Fbtn_color.ButtonColor;
//writeln('color3 Brush.color', ColorToString(TPlotRect(OwnerPlot.PlotRect[FActivePlotRect]).Style.Brush.Color) );
end;
// Legend
TPlotRect(OwnerPlot.PlotRect[FActivePlotRect]).ShowLegend := Fcb_legend.Checked;
// ColorScale : attention: the axis to scale is a colorscale property
// which series to draw colored referred to an axis is a series property !
TPlotRect(OwnerPlot.PlotRect[FActivePlotRect]).ShowColorScale := Fcb_colorscale.Checked;
//
IF Fcb_axes.ItemIndex > -1 THEN vAxisString := Fcb_axes.Items[Fcb_axes.ItemIndex];
vIndexString := vAxisString[1];
IF (Length(vAxisString)>1) THEN
IF (vAxisString[2] in ['0'..'9']) THEN vIndexString := vIndexString + vAxisString[2];
vAxisIndex := StrToIntDef(vIndexString, -1); //StrToIntDef(vIndexString,-1);
TPlotRect(OwnerPlot.PlotRect[FActivePlotRect]).ColorScaleRect.ScaleAxisIndex := vAxisIndex;
OwnerPlot.Repaint;
end;
constructor THelperFormPlotRectStyleChoose.Create(AOwner: TComponent);
const
cBorderSpace = 36;
begin
inherited Create(AOwner);
OwnerPlot := TPlot(AOwner);
Self.Height := 260;
Self.Width := 340;
Self.Caption := 'PlotRect properties';
// colorbutton
Fbtn_color := TColorButton.Create(Self); // colorbutton, fixed to form
Fbtn_color.Parent := Self;
Fbtn_color.Visible := TRUE;
Fbtn_color.AnchorSide[akLeft].Side:=asrLeft;
Fbtn_color.AnchorSide[akLeft].Control:=Self;
Fbtn_color.Anchors:=Fbtn_color.Anchors+[akLeft];
Fbtn_color.Top := 28;
Fbtn_color.Width := 132;
Fbtn_color.BorderSpacing.Around := cBorderSpace;
Fbtn_color.Caption := 'Background';
Fbtn_color.OnColorChanged := @Apply;
Fcb_legend := TCheckBox.Create(Self);
Fcb_legend.Parent := Self;
Fcb_legend.Visible := TRUE;
Fcb_legend.Checked := FALSE;
Fcb_legend.AnchorSide[akLeft].Side:=asrLeft;
Fcb_legend.AnchorSide[akLeft].Control:=Self;
Fcb_legend.AnchorSide[akTop].Side:=asrBottom;
Fcb_legend.AnchorSide[akTop].Control:=Fbtn_color;
Fcb_legend.Anchors:=Fcb_legend.Anchors+[akLeft]+[akTop];
Fcb_legend.BorderSpacing.Around := cBorderSpace;
Fcb_legend.Caption := 'Show a legend';
Fcb_legend.OnClick := @Apply;
Fcb_colorscale := TCheckBox.Create(Self);
Fcb_colorscale.Parent := Self;
Fcb_colorscale.Visible := TRUE;
Fcb_colorscale.Checked := FALSE;
Fcb_colorscale.AnchorSide[akLeft].Side:=asrLeft;
Fcb_colorscale.AnchorSide[akLeft].Control:=Self;
Fcb_colorscale.AnchorSide[akTop].Side:=asrBottom;
Fcb_colorscale.AnchorSide[akTop].Control:=Fcb_legend;
Fcb_colorscale.Anchors:=Fcb_colorscale.Anchors+[akLeft]+[akTop];
Fcb_colorscale.BorderSpacing.Around := cBorderSpace;
Fcb_colorscale.Caption := 'Show a ColorScale for axis:';
Fcb_colorscale.OnClick := @Apply;
Fcb_axes := TComboBox.Create(Self);
Fcb_axes.Parent := Self;
Fcb_axes.Visible := TRUE;
Fcb_axes.AnchorSide[akLeft].Side:=asrRight;
Fcb_axes.AnchorSide[akLeft].Control:=Fcb_colorscale;
Fcb_axes.AnchorSide[akTop].Side:=asrCenter;
Fcb_axes.AnchorSide[akTop].Control:=Fcb_colorscale;
Fcb_axes.BorderSpacing.Around := cBorderSpace;
Fcb_axes.OnChange := @Apply;
// colorscale adjustments
TPlotRect(OwnerPlot.PlotRect[FActivePlotRect]).ColorScaleRect.ColorScaleOrientation := aoVertical;
TPlotRect(OwnerPlot.PlotRect[FActivePlotRect]).ColorScaleRect.ColorScaleWidth := 12;
TPlotRect(OwnerPlot.PlotRect[FActivePlotRect]).ColorScaleRect.AutoShrink := TRUE;
end;
destructor THelperFormPlotRectStyleChoose.Destroy;
begin
inherited Destroy;
end;
procedure THelperFormPlotRectStyleChoose.InitForm(APlotRectIndex: Integer);
var
vLoop: integer;
vIndex: integer;
vCBstring: string;
begin
vLoop := 0; vIndex := 0; vCBstring := '';
FActivePlotRect := APlotRectIndex;
Fbtn_color.ButtonColor := TPlotRect(OwnerPlot.PlotRect[FActivePlotRect]).Style.Brush.Color;
// Combo Axes
// empty
with Fcb_axes.Items do begin
while Count > 0 do begin
Fcb_axes.Items.Delete(0);
end;
end;
// refill
with TPlotRect(OwnerPlot.PlotRect[FActivePlotRect]).SeriesContainedIdx do try
for vLoop := Count-1 downto 0 do begin
//vSeriesIndex := TPlotSeries(Series[PtrInt(Items[vLoop])]).SeriesIndex;
// find axes indices
// X
vCBstring := '';
vIndex := (TPlotSeries(OwnerPlot.Series[PInteger(Items[vLoop])^]).XAxis);
vCBstring := IntToStr(vIndex) + ' - ' +
TPlotAxis(OwnerPlot.Axis[TPlotSeries(OwnerPlot.Series[PInteger(Items[vLoop])^]).XAxis]).AxisLabel;
Fcb_axes.Items.Add(vCBstring);
IF TPlotSeries(OwnerPlot.Series[PInteger(Items[vLoop])^]).ColoredAxis = vIndex THEN Fcb_axes.ItemIndex := 0;
// Y
vCBstring := '';
vIndex := (TPlotSeries(OwnerPlot.Series[PInteger(Items[vLoop])^]).YAxis);
vCBstring := IntToStr(vIndex) + ' - ' +
TPlotAxis(OwnerPlot.Axis[TPlotSeries(OwnerPlot.Series[PInteger(Items[vLoop])^]).YAxis]).AxisLabel;
Fcb_axes.Items.Add(vCBstring);
IF TPlotSeries(OwnerPlot.Series[PInteger(Items[vLoop])^]).ColoredAxis = vIndex THEN Fcb_axes.ItemIndex := 1;
// Z
IF TPlotSeries(OwnerPlot.Series[PInteger(Items[vLoop])^]) is TXYZPlotSeries THEN begin
vCBstring := '';
vIndex := (TXYZPlotSeries(OwnerPlot.Series[PInteger(Items[vLoop])^]).ZAxis);
vCBstring := IntToStr(vIndex) + ' - ' +
TPlotAxis(OwnerPlot.Axis[TXYZPlotSeries(OwnerPlot.Series[PInteger(Items[vLoop])^]).ZAxis]).AxisLabel;
Fcb_axes.Items.Add(vCBstring);
IF TPlotSeries(OwnerPlot.Series[PInteger(Items[vLoop])^]).ColoredAxis = vIndex THEN Fcb_axes.ItemIndex := 2;
end;
end;
finally
while Count > 0 do begin
Dispose(Pinteger(Items[0]));
Delete(0);
end;
Free;
end;
// Combo axes end
// do we have legend and colorscale enabled ?
Fcb_colorscale.Checked := TPlotRect(OwnerPlot.PlotRect[FActivePlotRect]).ShowColorScale;
Fcb_legend.Checked := TPlotRect(OwnerPlot.PlotRect[FActivePlotRect]).ShowLegend;
Self.Show;
end;
{ THelperFormsAxes }
{===========================================================================}
constructor THelperFormsAxes.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
destructor THelperFormsAxes.Destroy;
begin
IF FfrmAxesStyleChoose <> nil THEN FfrmAxesStyleChoose.Free;
inherited Destroy;
end;
procedure THelperFormsAxes.AxesStyleChoose(AAxis: Integer);
begin
IF FfrmAxesStyleChoose = nil THEN FfrmAxesStyleChoose := THelperFormAxesStyleChoose.Create(OwnerPlot);
FfrmAxesStyleChoose.InitForm(AAxis);
end;
{ THelperFormAxesStyleChoose }
{===========================================================================}
procedure THelperFormAxesStyleChoose.Apply(Sender: TObject);
begin
TPlotAxis(OwnerPlot.Axis[FActiveAxis]).AxisLabel := Fed_axisname.Caption;
TPlotAxis(OwnerPlot.Axis[FActiveAxis]).NumberFormat := TNumberFormat(Fcb_numberformat.ItemIndex);
TPlotAxis(OwnerPlot.Axis[FActiveAxis]).LogScale := Fcb_logscale.Checked ;
TPlotAxis(OwnerPlot.Axis[FActiveAxis]).LogBase := Fed_logbase.Value;
TAxisStyle(TPlotAxis(OwnerPlot.Axis[FActiveAxis]).Style).Color := Fbtn_color.ButtonColor;
TAxisStyle(TPlotAxis(OwnerPlot.Axis[FActiveAxis]).TickStyle).Color := Fbtn_color.ButtonColor;
TAxisStyle(TPlotAxis(OwnerPlot.Axis[FActiveAxis]).SubTickStyle).Color := Fbtn_color.ButtonColor;
TPlotAxis(OwnerPlot.Axis[FActiveAxis]).InnerTicks := Fcb_innerticks.Checked;
TPlotAxis(OwnerPlot.Axis[FActiveAxis]).InnerSubTicks := Fcb_innersubticks.Checked;
TPlotAxis(OwnerPlot.Axis[FActiveAxis]).Inner3DTicks := Fcb_InnerTicks3D.Checked;
OwnerPlot.Repaint;
end;
constructor THelperFormAxesStyleChoose.Create(AOwner: TComponent);
var
vLoop: integer;
const
cBorderSpace = 22;
cLblSpace = 8;
begin
inherited Create(AOwner);
OwnerPlot := TPlot(AOwner);
Self.Height := 340;
Self.Width := 340;
Self.Caption := 'Axis properties';
//// colorbutton
Fbtn_color := TColorButton.Create(Self); // colorbutton, fixed to form
Fbtn_color.Parent := Self;
Fbtn_color.Visible := TRUE;
Fbtn_color.AnchorSide[akLeft].Side:=asrLeft;
Fbtn_color.AnchorSide[akLeft].Control:=Self;
Fbtn_color.Anchors:=Fbtn_color.Anchors+[akLeft];
Fbtn_color.Top := 28;
Fbtn_color.Width := 132;
Fbtn_color.BorderSpacing.Around := cBorderSpace;
Fbtn_color.Caption := 'Color';
//Fbtn_color.OnColorChanged := @Apply;
//
Fed_axisname := TLabeledEdit.Create(Self); // Label and edit for axisname
//Fed_axisname := TEdit.Create(Self); // Label and edit for axisname
Fed_axisname.Parent := Self;
Fed_axisname.Visible:=TRUE;
Fed_axisname.Enabled:=TRUE;
Fed_axisname.BorderSpacing.Left := 20;
Fed_axisname.BorderSpacing.Top := 00;
Fed_axisname.AnchorSide[akLeft].Side := asrRight;
Fed_axisname.AnchorSide[akLeft].Control := Fbtn_color;
Fed_axisname.AnchorSide[akRight].Side := asrRight;
Fed_axisname.AnchorSide[akRight].Control := Self;
Fed_axisname.AnchorSide[akTop].Side := asrCenter;
Fed_axisname.AnchorSide[akTop].Control := Fbtn_color;
Fed_axisname.Anchors:=Fed_axisname.Anchors+[akLeft]+[akTop]+[akRight];
Fed_axisname.BorderSpacing.Right := cBorderSpace;
Fed_axisname.Text := '';
Fed_axisname.LabelPosition := lpAbove;
Fed_axisname.LabelSpacing := 3;
Fed_axisname.EditLabel.Caption := 'Axis Caption';
//
Fcb_innerticks := TCheckBox.Create(Self); // checkbox InnerTicks
with Fcb_innerticks do begin
Parent := Self;
Visible := TRUE;
Checked := FALSE;
AnchorSide[akLeft].Side:=asrLeft;
AnchorSide[akLeft].Control:=Self;
AnchorSide[akTop].Side:=asrBottom;
AnchorSide[akTop].Control:=Fbtn_color;
Anchors:=Fcb_innerticks.Anchors+[akLeft]+[akTop];
BorderSpacing.Around := cBorderSpace;
Caption := 'Show ticklines';
//Fcb_innerticks.OnClick := @Apply;
end;
//
Fcb_innersubticks := TCheckBox.Create(Self); // checkbox InnerSubTicks
Fcb_innersubticks.Parent := Self;
Fcb_innersubticks.Visible := TRUE;
Fcb_innersubticks.Checked := FALSE;
Fcb_innersubticks.AnchorSide[akLeft].Side:=asrRight;
Fcb_innersubticks.AnchorSide[akLeft].Control:=Fcb_innerticks;
//Fcb_innersubticks.AnchorSide[akRight].Side:=asrRight;
//Fcb_innersubticks.AnchorSide[akRight].Control:=Self;
Fcb_innersubticks.AnchorSide[akTop].Side:=asrCenter;
Fcb_innersubticks.AnchorSide[akTop].Control:=Fcb_innerticks;
Fcb_innersubticks.Anchors:=Fcb_innersubticks.Anchors+[akLeft]+[akTop]; //+[akRight];
Fcb_innersubticks.BorderSpacing.Around := cBorderSpace;
Fcb_innersubticks.Caption := 'Show subticklines';
//Fcb_innersubticks.OnClick := @Apply;
Fcb_InnerTicks3D := TCheckBox.Create(Self); // checkbox InnerTicks3D
with Fcb_InnerTicks3D do begin
Parent := Self;
Visible := TRUE;
Checked := FALSE;
AnchorSide[akLeft].Side:=asrRight;
AnchorSide[akLeft].Control:=Fcb_innersubticks;
AnchorSide[akTop].Side:=asrCenter;
AnchorSide[akTop].Control:=Fcb_innersubticks;
Anchors:=Fcb_innerticks.Anchors+[akLeft]+[akTop];
BorderSpacing.Around := cBorderSpace;
Caption := '3D ticks';
//Fcb_innerticks.OnClick := @Apply;
end;
//
Fcb_logscale := TCheckBox.Create(Self); // checkbox LogScale
Fcb_logscale.Parent := Self;
Fcb_logscale.Visible := TRUE;
Fcb_logscale.Checked := FALSE;
Fcb_logscale.AnchorSide[akLeft].Side:=asrLeft;
Fcb_logscale.AnchorSide[akLeft].Control:=Self;
Fcb_logscale.AnchorSide[akTop].Side:=asrBottom;
Fcb_logscale.AnchorSide[akTop].Control:=Fcb_innerticks;
Fcb_logscale.Anchors:=Fcb_logscale.Anchors+[akLeft]+[akTop];
Fcb_logscale.BorderSpacing.Around := cBorderSpace;
Fcb_logscale.Caption := 'LogScale with LogBase -->';
//Fcb_logscale.OnClick := @Apply;
//
Fed_logbase := TSpinEdit.Create(Self); // spinedit LogBase
Fed_logbase.Parent := Self;
Fed_logbase.Visible := TRUE;
Fed_logbase.AnchorSide[akLeft].Side:=asrRight;
Fed_logbase.AnchorSide[akLeft].Control:=Fcb_logscale;
Fed_logbase.AnchorSide[akTop].Side:=asrCenter;
Fed_logbase.AnchorSide[akTop].Control:=Fcb_logscale;
Fed_logbase.Anchors:=Fed_logbase.Anchors+[akLeft]+[akTop];
//Fed_logbase.OnChange := @Apply;
Fed_logbase.Value := 10;
Fed_logbase.MinValue := 2;
Fed_logbase.MaxValue := 20;
Fed_logbase.Increment := 1;
//
Flbl_numformat := TLabel.Create(Self); // label size
Flbl_numformat.Parent := Self;
Flbl_numformat.Visible := TRUE;
Flbl_numformat.Caption := 'Numberformat';
Flbl_numformat.AnchorSide[akLeft].Side:=asrLeft;
Flbl_numformat.AnchorSide[akLeft].Control:=Self;
Flbl_numformat.AnchorSide[akTop].Side:=asrBottom;
Flbl_numformat.AnchorSide[akTop].Control:=Fcb_logscale;
Flbl_numformat.Anchors:=Flbl_numformat.Anchors+[akLeft]+[akTop];
Flbl_numformat.BorderSpacing.Left := cBorderSpace;
//
Fcb_numberformat := TComboBox.Create(Self); // combo NumberFormat
Fcb_numberformat.Parent := Self;
Fcb_numberformat.Visible := TRUE;
Fcb_numberformat.AnchorSide[akLeft].Side:=asrLeft;
Fcb_numberformat.AnchorSide[akLeft].Control:=Self;
Fcb_numberformat.AnchorSide[akRight].Side:=asrRight;
Fcb_numberformat.AnchorSide[akRight].Control:=Self;
Fcb_numberformat.AnchorSide[akTop].Side:=asrBottom;
Fcb_numberformat.AnchorSide[akTop].Control:=Flbl_numformat;
Fcb_numberformat.Anchors:=Fcb_numberformat.Anchors+[akLeft]+[akTop]+[akRight];
Fcb_numberformat.BorderSpacing.Left := cBorderSpace;
Fcb_numberformat.BorderSpacing.Right := cBorderSpace;
Fcb_numberformat.BorderSpacing.Top := cLblSpace;
//Fcb_numberformat.OnChange := @Apply;
for vLoop := ord(nfPlain) to ord(nfEngineeringPrefix) do begin
Fcb_numberformat.Items.Add(TNumberFormatName[TNumberFormat(vLoop)]);
end;
end;
destructor THelperFormAxesStyleChoose.Destroy;
begin
inherited Destroy;
end;
procedure THelperFormAxesStyleChoose.InitForm(AAxis: Integer);
begin
FActiveAxis := AAxis;
Fcb_InnerTicks3D.Enabled := (TPlotAxis(OwnerPlot.Axis[FActiveAxis]).Get3DGridAxis <> -1);
Fcb_InnerTicks3D.Checked := TPlotAxis(OwnerPlot.Axis[FActiveAxis]).Inner3DTicks;
Fcb_numberformat.ItemIndex := ord(TPlotAxis(OwnerPlot.Axis[FActiveAxis]).NumberFormat);
Fbtn_color.ButtonColor := TAxisStyle(TPlotAxis(OwnerPlot.Axis[FActiveAxis]).Style).Color;
Fed_axisname.Text := TPlotAxis(OwnerPlot.Axis[FActiveAxis]).AxisLabel;
Fcb_numberformat.ItemIndex := ord( TPlotAxis(OwnerPlot.Axis[FActiveAxis]).NumberFormat );
Fcb_logscale.Checked := TPlotAxis(OwnerPlot.Axis[FActiveAxis]).LogScale;
Fed_logbase.Value := round ( TPlotAxis(OwnerPlot.Axis[FActiveAxis]).LogBase );
Fcb_innerticks.Checked := TPlotAxis(OwnerPlot.Axis[FActiveAxis]).InnerTicks;
Fcb_innersubticks.Checked := TPlotAxis(OwnerPlot.Axis[FActiveAxis]).InnerSubTicks;
Self.Show;
end;
end.
|
unit Work.ImportReadReports;
interface
uses
Plus.TWork,
ExtGUI.ListBox.Books,
Data.Main;
type
TImportReadReportsWork = class (TWork)
private
FBooksConfig: TBooksListBoxConfigurator;
procedure DoImportReaderReports;
procedure SetBooksConfig(const Value: TBooksListBoxConfigurator);
public
procedure Execute; override;
property BooksConfig: TBooksListBoxConfigurator read FBooksConfig write SetBooksConfig;
end;
implementation
{ TImportReadReportsWork }
uses
System.JSON,
System.Variants,
System.SysUtils,
Vcl.Forms,
ClientAPI.Readers,
Messaging.EventBus,
Model.Book,
Model.ReaderReport,
Consts.Application,
Helper.DataSet,
Helper.TApplication;
procedure TImportReadReportsWork.DoImportReaderReports;
var
jsData: TJSONArray;
I: Integer;
ReaderReport: TReaderReport;
Book: TBook;
Ratings: array of string;
ReaderId: Variant;
AMessage: TEventMessage;
begin
jsData := ImportReaderReportsFromWebService(Client_API_Token);
try
for i := 0 to jsData.Count - 1 do
begin
// ----------------------------------------------------
// Validate ReadeReport (JSON) and insert into the Database
// Read JSON object
ReaderReport := TReaderReport.Create;
try
ReaderReport.LoadFromJSON(jsData.Items[i] as TJSONObject);
Book := FBooksConfig.GetBookList(blkAll).FindByISBN(ReaderReport.BookISBN);
if Assigned(Book) then
begin
ReaderId := DataModMain.FindReaderByEmil(ReaderReport.Email);
if VarIsNull(ReaderId) then
begin
ReaderId := DataModMain.dsReaders.GetMaxValue('ReaderId') + 1;
// Fields: ReaderId, FirstName, LastName, Email, Company, BooksRead,
// LastReport, ReadersCreated
DataModMain.dsReaders.AppendRecord([ReaderId, ReaderReport.FirstName,
ReaderReport.LastName, ReaderReport.Email, ReaderReport.Company, 1,
ReaderReport.ReportedDate, Now()]);
end;
// Append report into the database:
// Fields: ReaderId, ISBN, Rating, Oppinion, Reported
DataModMain.dsReports.AppendRecord([ReaderId, ReaderReport.BookISBN,
ReaderReport.Rating, ReaderReport.Oppinion,
ReaderReport.ReportedDate]);
// ----------------------------------------------------------------
if Application.IsDeveloperMode then
Insert([ReaderReport.Rating.ToString], Ratings, maxInt);
end
else
raise Exception.Create('Invalid book isbn');
finally
ReaderReport.Free;
end;
end;
if Application.IsDeveloperMode then
begin
AMessage.TagString := string.Join(' ,', Ratings);
TEventBus._Post (EB_ImportReaderReports_LogInfo, AMessage);
end;
finally
jsData.Free;
end;
WorkDone;
end;
procedure TImportReadReportsWork.Execute;
begin
inherited;
DoImportReaderReports;
end;
procedure TImportReadReportsWork.SetBooksConfig(
const Value: TBooksListBoxConfigurator);
begin
FBooksConfig := Value;
end;
end.
|
unit ManagedRecordsUnit1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ScrollBox,
FMX.Memo, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Memo.Types;
type
// This is a custom managed record
// The Initialize and Finalize are both called automatically
TMyRecord = record
Value: Integer;
class operator Initialize(out Dest: TMyRecord);
class operator Finalize(var Dest: TMyRecord);
end;
TForm1 = class(TForm)
GoButton: TButton;
Memo1: TMemo;
MaterialOxfordBlueSB: TStyleBook;
procedure GoButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
// The Initialize is called when the record declaration is in scope
class operator TMyRecord.Initialize(out Dest: TMyRecord);
begin
Dest.Value := 10;
Form1.Memo1.Lines.Append('Record created @' + IntToHex(Integer(Pointer(@Dest))));
end;
// The Finalize is called when the record goes out of scope
class operator TMyRecord.Finalize(var Dest: TMyRecord);
begin
Form1.Memo1.Lines.Append('Record destroyed @' + IntToHex(Integer(Pointer(@Dest))));
end;
procedure TForm1.GoButtonClick(Sender: TObject);
begin
Memo1.Lines.Append('Before scope');
begin
var LMyRecord: TMyRecord;
Memo1.Lines.Append('After declare');
// Since it is a record there is no need to call create!
Memo1.Lines.Append('Initial value: ' + LMyRecord.Value.ToString);
LMyRecord.Value := 20;
Memo1.Lines.Append('Changed value: ' + LMyRecord.Value.ToString);
Memo1.Lines.Append('After use');
end;
// It was automatically Finalized when it went out of scope!
Memo1.Lines.Append('After scope');
end;
end.
|
{ *************************************************************************** }
{ }
{ Delphi and Kylix Cross-Platform Visual Component Library }
{ }
{ Copyright (c) 2000-2002 Borland Software Corporation }
{ }
{ This file may be distributed and/or modified under the terms of the GNU }
{ General Public License (GPL) version 2 as published by the Free Software }
{ Foundation and appearing at http://www.borland.com/kylix/gpl.html. }
{ }
{ Licensees holding a valid Borland No-Nonsense License for this Software may }
{ use this file in accordance with such license, which appears in the file }
{ license.txt that came with this Software. }
{ }
{ Русификация: 2001-02 Polaris Software }
{ http://polesoft.da.ru }
{ *************************************************************************** }
unit QConsts;
interface
const
// Delphi mime types
SDelphiBitmap = 'image/delphi.bitmap';
SDelphiComponent = 'application/delphi.component';
SDelphiPicture = 'image/delphi.picture';
SDelphiDrawing = 'image/delphi.drawing';
{$IFNDEF VER140}
SBitmapExt = 'BMP';
{$ENDIF}
resourcestring
SInvalidCreateWidget = 'Класс %s не может создать QT widget';
STooManyMessageBoxButtons = 'Определено слишком много кнопок для окна сообщения';
SmkcBkSp = 'Backspace';
SmkcTab = 'Tab';
SmkcBackTab = 'BackTab';
SmkcEsc = 'Esc';
SmkcReturn = 'Return';
SmkcEnter = 'Enter';
SmkcSpace = 'Space';
SmkcPgUp = 'PgUp';
SmkcPgDn = 'PgDn';
SmkcEnd = 'End';
SmkcHome = 'Home';
SmkcLeft = 'Left';
SmkcUp = 'Up';
SmkcRight = 'Right';
SmkcDown = 'Down';
SmkcIns = 'Ins';
SmkcDel = 'Del';
SmkcShift = 'Shift+';
SmkcCtrl = 'Ctrl+';
SmkcAlt = 'Alt+';
SOpenFileTitle = 'Открыть';
{$IFDEF VER140}
SAssignError = 'Не могу значение %s присвоить %s';
SFCreateError = 'Не могу создать файл %s';
SFOpenError = 'Не могу открыть файл %s';
SReadError = 'Ошибка чтения потока';
SWriteError = 'Ошибка записи потока';
SMemoryStreamError = 'Не хватает памяти при расширении memory stream';
SCantWriteResourceStreamError = 'Не могу записывать в поток ресурсов "только для чтения"';
{$ENDIF}
SDuplicateReference = 'WriteObject вызван дважды для одного и того же экземпляра';
{$IFDEF VER140}
SClassNotFound = 'Класс %s не найден';
SInvalidImage = 'Неверный формат потока';
SResNotFound = 'Ресурс %s не найден';
{$ENDIF}
SClassMismatch = 'Неверный класс ресурса %s';
{$IFDEF VER140}
SListIndexError = 'Индекс списка вышел за границы (%d)';
SListCapacityError = 'Размер списка вышел за границы (%d)';
SListCountError = 'Счетчик списка вышел за границы (%d)';
SSortedListError = 'Операция недопустима для отсортированного списка строк';
SDuplicateString = 'Список строк не допускает дубликатов';
{$ENDIF}
SInvalidTabIndex = 'Tab индекс вышел за границы';
SInvalidTabPosition = 'Позиция tab несовместима с текущим стилем tab';
SInvalidTabStyle = 'Cтиль tab несовместим с текущей позицией tab';
{$IFDEF VER140}
SDuplicateName = 'Компонент с именем %s уже существует';
SInvalidName = '''''%s'''' недопустимо в качестве имени компонента';
SDuplicateClass = 'Класс с именем %s уже существует';
SNoComSupport = '%s не зарегистрирован как COM класс';
SInvalidInteger = '''''%s'''' - неверное целое число';
SLineTooLong = 'Строка слишком длинная';
SInvalidPropertyValue = 'Неверное значение свойства';
SInvalidPropertyPath = 'Неверный путь к свойству';
SInvalidPropertyType = 'Неверный тип свойства: %s';
SInvalidPropertyElement = 'Неверный элемент свойства: %s';
SUnknownProperty = 'Свойство не существует';
SReadOnlyProperty = 'Свойство только для чтения';
SPropertyException = 'Ошибка чтения %s%s%s: %s';
SAncestorNotFound = 'Предок для ''%s'' не найден';
{$ENDIF}
SInvalidBitmap = 'Изображение Bitmap имеет неверный формат';
SInvalidIcon = 'Иконка (Icon) имеет неверный формат';
SInvalidPixelFormat = 'Неверный точечный (pixel) формат';
SBitmapEmpty = 'Изображение Bitmap пустое';
SScanLine = 'Scan line индекс вышел за границы';
SChangeIconSize = 'Не могу изменить размер иконки';
SUnknownExtension = 'Неизвестное расширение файла изображения (.%s)';
SUnknownClipboardFormat = 'Неподдерживаемый формат буфера обмена';
SOutOfResources = 'Не хватает системных ресурсов';
SNoCanvasHandle = 'Canvas не позволяет рисовать';
SInvalidCanvasState = 'Неверный запрос состояния canvas';
SInvalidImageSize = 'Неверный размер изображения';
SInvalidWidgetHandle = 'Неверный дескриптор widget';
SInvalidColorDepth = 'Глубина цвета должна быть 1, 8 или 32 bpp';
{$IFNDEF VER140}
SInvalidXImage = 'Неверный XImage';
{$ENDIF}
STooManyImages = 'Слишком много изображений';
SWidgetCreate = 'Ошибка создания widget';
SCannotFocus = 'Не могу передать фокус ввода отключенному или невидимому окну (%s)';
SParentRequired = 'Элемент управления ''%s'' не имеет родительского widget';
SParentGivenNotAParent = 'Данный родитель не является родителем ''%s''';
SVisibleChanged = 'Не могу изменить Visible в OnShow или OnHide';
SCannotShowModal = 'Не могу сделать видимым модальное окно';
SScrollBarRange = 'Свойство Scrollbar вышло за границы';
SPropertyOutOfRange = 'Свойство %s вышло за границы';
SMenuIndexError = 'Индекс меню вышел за границы';
SMenuReinserted = 'Меню вставлено дважды';
SNoMenuRecursion = 'Рекурсия при вставке меню не поддерживается';
SMenuNotFound = 'Подменю - не в меню';
SMenuSetFormError = 'TMenu.SetForm: аргумент должен быть TCustomForm';
SNoTimers = 'Нет доступных таймеров';
{$IFDEF VER140}
SNotPrinting = 'Принтер не находится сейчас в состоянии печати';
SPrinting = 'Идет печать...';
{$ENDIF}
SNoAdapter = 'Нет доступного адаптера принтера для печати';
SPrinterIndexError = 'Индекс принтера вышел за границы';
SInvalidPrinter = 'Выбран неверный принтер';
SDeviceOnPort = '%s on %s';
SGroupIndexTooLow = 'GroupIndex не может быть меньше, чем GroupIndex предыдущего пункта меню';
SNoMDIForm = 'Не могу создать форму. Нет активных MDI форм';
SNotAnMDIForm = 'Неверный MDIParent для класса %s';
SMDIChildNotVisible = 'Не могу скрыть дочернюю MDI форму';
{$IFDEF VER140}
SRegisterError = 'Неверная регистрация компонента';
{$ENDIF}
SImageCanvasNeedsBitmap = 'Можно редактировать только изображения, которые содержат bitmap';
SControlParentSetToSelf = 'Элемент управления не может быть родителем самого себя';
SOKButton = 'OK';
SCancelButton = 'Отмена';
SYesButton = '&Да';
SNoButton = '&Нет';
SHelpButton = '&Справка';
SCloseButton = '&Закрыть';
SIgnoreButton = 'Про&должить';
SRetryButton = '&Повторить';
SAbortButton = 'Прервать';
SAllButton = '&Все';
SCannotDragForm = 'Не могу перемещать форму';
SPutObjectError = 'PutObject для неопределенного типа';
SFB = 'FB';
SFG = 'FG';
SBG = 'BG';
SVIcons = 'Иконки';
SVBitmaps = 'Bitmaps';
SVPixmaps = 'Pixmaps';
SVPNGs = 'PNGs';
SDrawings = 'Рисунки';
{$IFNDEF VER140}
SVJpegs = 'Jpegs';
{$ENDIF}
{$IFDEF VER140}
SGridTooLarge = 'Таблица (Grid) слишком большая для работы';
STooManyDeleted = 'Удаляется слишком много строк или столбцов';
SIndexOutOfRange = 'Индекс Grid вышел за границы';
SFixedColTooBig = 'Число фиксированных столбцов должно быть меньше общего числа столбцов';
SFixedRowTooBig = 'Число фиксированных строк должно быть меньше общего числа строк';
SInvalidStringGridOp = 'Не могу вставить или удалить строки из таблицы (grid)';
SParseError = '%s в строке %d';
SIdentifierExpected = 'Ожидается идентификатор';
SStringExpected = 'Ожидается строка';
SNumberExpected = 'Ожидается число';
SCharExpected = 'Ожидается ''''%s''''';
SSymbolExpected = 'Ожидается %s';
{$ENDIF}
SInvalidNumber = 'Неверное числовое значение';
{$IFDEF VER140}
SInvalidString = 'Неверная строковая константа';
SInvalidProperty = 'Неверное значение свойства';
SInvalidBinary = 'Неверное двоичное значение';
{$ENDIF}
SInvalidCurrentItem = 'Неверное значение для текущего элемента';
{$IFDEF VER140}
SMaskErr = 'Введено неверное значение';
SMaskEditErr = 'Введено неверное значение. Нажмите Esc для отмены изменений';
{$ENDIF}
SMsgDlgWarning = 'Предупреждение';
SMsgDlgError = 'Ошибка';
SMsgDlgInformation = 'Информация';
SMsgDlgConfirm = 'Подтверждение';
SMsgDlgYes = '&Да';
SMsgDlgNo = '&Нет';
SMsgDlgOK = 'OK';
SMsgDlgCancel = 'Отмена';
SMsgDlgHelp = '&Справка';
SMsgDlgHelpNone = 'Справка недоступна';
SMsgDlgHelpHelp = 'Справка';
SMsgDlgAbort = 'П&рервать';
SMsgDlgRetry = '&Повторить';
SMsgDlgIgnore = 'Про&должить';
SMsgDlgAll = '&Все';
SMsgDlgNoToAll = 'Н&ет для всех';
SMsgDlgYesToAll = 'Д&а для всех';
srUnknown = '(Неизвестно)';
srNone = '(Нет)';
SOutOfRange = 'Значение должно быть между %d и %d';
SCannotCreateName = 'Не могу создать имя метода по умолчанию для компонента без имени';
SUnnamed = 'Безымянный';
{$IFDEF VER140}
SDateEncodeError = 'Неверный аргумент для формирования даты';
STimeEncodeError = 'Неверный аргумент для формирования времени';
SInvalidDate = '''''%s'''' - неверная дата';
SInvalidTime = '''''%s'''' - неверное время';
SInvalidDateTime = '''''%s'''' - неверные дата и время';
SInvalidFileName = 'Неверное имя файла - %s';
SDefaultFilter = 'Все файлы (*.*)|*.*';
{$ENDIF}
SInsertLineError = 'Невозможно вставить строку';
SConfirmCreateDir = 'Указанная папка не существует. Создать ее?';
SSelectDirCap = 'Выбор папки';
{$IFNDEF VER140}
SCannotCreateDirName = 'Не могу создать папку "%s".';
SAccessDeniedTo = 'Доступ к "%s" запрещен';
SCannotReadDirectory = 'Не могу прочитать папку:' + sLineBreak + '"%s"';
SDirectoryNotEmpty = 'Папка "%s" - не пустая.';
SNotASubDir = '"%s" - не подкаталог "%s"';
{$ENDIF}
{$IFDEF VER140}
SCannotCreateDir = 'Не могу создать папку';
{$ENDIF}
SDirNameCap = '&Имя папки:';
SDrivesCap = '&Устройства:';
SDirsCap = '&Папки:';
SFilesCap = '&Файлы: (*.*)';
SNetworkCap = '&Сеть...';
{$IFNDEF VER140}
SInvalidDirectory = 'Не могу прочитать папку "%s".';
SNewFolder = 'Новая папка';
SFileNameNotFound = '"%s"'#10'Файл не найден.';
SAlreadyExists = 'Файл с таким именем уже существует. Пожалуйста, укажите '+
'другое имя файла.';
SConfirmDeleteTitle = 'Подтвеждение удаления файла';
SConfirmDeleteMany = 'Вы уверены, что хотите удалить эти %d пункта(ов)?';
SConfirmDeleteOne = 'Вы уверены, что хотите удалить "%s"?';
SContinueDelete = 'Продолжить операцию удаления?';
SAdditional = 'Дополнительно';
SName = 'Имя';
SSize = 'Размер';
SType = 'Тип';
SDate = 'Дата изменения';
SAttributes = 'Атрибуты';
{$IFDEF LINUX}
SOwner = 'Хозяин';
SGroup = 'Группа';
SDefaultFilter = 'Все файлы (*)|*|';
{$ENDIF}
{$IFDEF MSWINDOWS}
SPermissions = 'Атрибуты';
SDefaultFilter = 'Все файлы (*.*)|*.*|';
SVolume = 'Том';
SFreeSpace = 'Свободно';
SAnyKnownDrive = ' неизвестный диск';
SMegs = '%d МБ';
{$ENDIF}
SDirectory = 'Папка';
SFile = 'Файл';
SLinkTo = 'Ссылка на ';
{$ENDIF}
SInvalidClipFmt = 'Неверный формат буфера обмена';
SIconToClipboard = 'Буфер обмена не поддерживает иконки';
SCannotOpenClipboard = 'Не могу открыть буфер обмена';
{$IFDEF VER140}
SInvalidActionRegistration = 'Неверная регистрация действия (action)';
SInvalidActionUnregistration = 'Неверная отмена регистрации действия (action)';
SInvalidActionEnumeration = 'Неверный перечень действий (action)';
SInvalidActionCreation = 'Неверное создание действия (action)';
{$ENDIF}
SDefault = 'Default';
SInvalidMemoSize = 'Текст превысил емкость memo';
SCustomColors = 'Custom Colors';
SInvalidPrinterOp = 'Операция не поддерживается на выбранном принтере';
SNoDefaultPrinter = 'Нет выбранного по умолчанию принтера';
{$IFDEF VER140}
SIniFileWriteError = 'Не могу записать в %s';
SBitsIndexError = 'Индекс Bits вышел за границы';
{$ENDIF}
SUntitled = '(Без имени)';
SDuplicateMenus = 'Меню ''%s'' уже используется другой формой';
SPictureLabel = 'Картинка:';
SPictureDesc = ' (%dx%d)';
SPreviewLabel = 'Просмотр';
{$IFNDEF VER140}
SNoPreview = 'Нет доступного Просмотра';
{$ENDIF}
SBoldItalicFont = 'Bold Italic';
SBoldFont = 'Bold';
SItalicFont = 'Italic';
SRegularFont = 'Regular';
SPropertiesVerb = 'Свойства';
{$IFDEF VER140}
sAsyncSocketError = 'Ошибка asynchronous socket %d';
sNoAddress = 'Не определен адрес';
sCannotListenOnOpen = 'Не могу прослушивать открытый socket';
sCannotCreateSocket = 'Не могу создать новый socket';
sSocketAlreadyOpen = 'Socket уже открыт';
sCantChangeWhileActive = 'Не могу изменить значение пока socket активен';
sSocketMustBeBlocking = 'Socket должен быть в режиме блокировки';
sSocketIOError = '%s ошибка %d, %s';
sSocketRead = 'Read';
sSocketWrite = 'Write';
{$ENDIF}
SAllCommands = 'All Commands';
{$IFDEF VER140}
SDuplicateItem = 'Список не допускает дубликатов ($0%x)';
{$ENDIF}
SDuplicatePropertyCategory = 'Категория свойства, названная %s, уже создана';
SUnknownPropertyCategory = 'Категория свойства не создана (%s)';
{$IFDEF VER140}
SInvalidMask = '''%s'' - неверная маска в позиции %d';
{$ENDIF}
SInvalidFilter = 'Фильтром свойств может быть только имя, класс или тип по базе (%d:%d)';
SInvalidCategory = 'Категории должны определять свои имя и описание';
sOperationNotAllowed = 'Операция не допустима во время отправки событий приложения';
STextNotFound = 'Текст не найден: "%s"';
SImageIndexError = 'Неверный индекс ImageList';
SReplaceImage = 'Невозможно заменить изображение';
SInvalidImageType = 'Неверный тип изображения';
SInvalidImageDimensions = 'Ширина и высота изображения должны совпадать';
SInvalidImageDimension = 'Неверное измерение изображения';
SErrorResizingImageList = 'Ошибка изменения размеров ImageList';
SInvalidRangeError = 'Диапазон от %d до %d - неверный';
SInvalidMimeSourceStream = 'Формат MimeSource должен иметь связанный с данными поток (stream)';
SMimeNotSupportedForIcon = 'Формат Mime не поддерживается для TIcon';
SOpen = 'Открыть';
{$IFDEF VER140}
SSave = 'Сохранить как';
{$ELSE}
SSave = 'Сохранить';
SSaveAs = 'Сохранить как';
{$ENDIF}
SFindWhat = '&Найти:';
SWholeWord = '&Только целые слова';
SMatchCase = 'С у&четом регистра';
SFindNext = 'Найти &далее';
SCancel = 'Отмена';
SHelp = 'Справка';
SFindTitle = 'Поиск';
SDirection = 'Направление';
SUp = '&Вверх';
SDown = 'Вн&из';
SReplaceWith = 'За&менить на:';
SReplace = '&Заменить';
SReplaceTitle = 'Замена';
SReplaceAll = 'Заменить в&се';
SOverwriteCaption = 'Сохранить %s как';
{$IFDEF VER140}
SOverwriteText = '%s уже создан.'#13'Хотите заменить его?';
SFileMustExist = '%s'#13'Файл не найден.'#13'Пожалуйста, проверьте правильность '+
'данного имени файла.';
SPathMustExist = '%s'#13'Путь не найден.'#13'Пожалуйста, проверьте правильность '+
'данного пути.';
{$ELSE}
SOverwriteText = '"%s" уже создан.' + sLineBreak + 'Хотите заменить его?';
SFileMustExist = '"%s"' + sLineBreak + 'Файл не найден.' + sLineBreak + 'Пожалуйста, проверьте правильность '+
'данного имени файла.';
SPathMustExist = '"%s"' + sLineBreak + 'Путь не найден.' + sLineBreak + 'Пожалуйста, проверьте правильность '+
'данного пути.';
SDriveNotFound = 'Диск %s не существует.' + sLineBreak + 'Пожалуйста, проверьте правильность '+
'данного диска.';
{$ENDIF}
SUnknownImageFormat = 'Формат изображения не распознан';
SInvalidHandle = 'Неверное значение дескриптора (handle) для %s';
SUnableToWrite = 'Не могу записать bitmap';
sAllFilter = 'Все';
sInvalidSetClipped = 'Не могу установить свойство Clipped во время рисования';
sInvalidLCDValue = 'Неверное значение LCDNumber';
sTabFailDelete = 'Не удалось удалить страницу (tab) с индексом %d';
sPageIndexError = 'Неверное значение PageIndex (%d). PageIndex должен быть ' +
'между 0 и %d';
sInvalidLevel = 'Присваивание неверного уровня элемента';
sInvalidLevelEx = 'Неверный уровень (%d) для элемента "%s"';
sTabMustBeMultiLine = 'MultiLine должно быть True, когда TabPosition равно tpLeft или tpRight';
sStatusBarContainsControl = '%s уже в StatusBar';
sListRadioItemBadParent = 'Пункты Radio должны иметь Controller как родителя';
sOwnerNotCustomHeaderSections = 'Владелец - не TCustomHeaderSection';
sHeaderSectionOwnerNotHeaderControl = 'Владелец Header Section должен быть TCustomHeaderControl';
SUndo = 'Отменить';
SRedo = 'Повторить';
SLine = '-';
SCut = 'Вырезать';
SCopy = 'Копировать';
SPaste = 'Вставить';
SClear = 'Очистить';
SSelectAll = 'Выбрать все';
{$IFNDEF VER140}
SBadMovieFormat = 'Неизвестный видеоформат';
SMovieEmpty = 'Видео не загружено';
SLoadingEllipsis = 'Загрузка...';
SNoAppInLib = 'Фатальная ошибка: Не могу создать объект приложения в разделенном (shared) объекте или библиотеке.';
SDuplicateApp = 'Фатальная ошибка: Не могу создать более одного экземпляра TApplication';
{$ENDIF}
implementation
end.
|
unit htGeneric;
interface
uses
SysUtils, Classes, Controls, Graphics,
LrGraphics, LrTextPainter,
htControls, htMarkup;
type
ThtGeneric = class(ThtGraphicControl)
private
FHAlign: TLrHAlign;
protected
procedure Generate(const inContainer: string;
inMarkup: ThtMarkup); override;
procedure GenerateStyles(const inContainer: string;
inMarkup: ThtMarkup);
procedure SetHAlign(const Value: TLrHAlign);
procedure StylePaint; override;
public
constructor Create(inOwner: TComponent); override;
destructor Destroy; override;
published
property Align;
property HAlign: TLrHAlign read FHAlign write SetHAlign;
property Outline;
property Style;
end;
implementation
uses
htPaint;
{ ThtGeneric }
constructor ThtGeneric.Create(inOwner: TComponent);
begin
inherited;
end;
destructor ThtGeneric.Destroy;
begin
inherited;
end;
procedure ThtGeneric.SetHAlign(const Value: TLrHAlign);
begin
FHAlign := Value;
Invalidate;
end;
procedure ThtGeneric.StylePaint;
begin
htPaintHash(Canvas, ClientRect, clSilver);
inherited;
end;
procedure ThtGeneric.GenerateStyles(const inContainer: string;
inMarkup: ThtMarkup);
var
s: string;
begin
s := CtrlStyle.InlineAttribute;
if (s <> '') then
inMarkup.Styles.Add(Format('#%s { %s }', [ inContainer, s ]));
end;
procedure ThtGeneric.Generate(const inContainer: string;
inMarkup: ThtMarkup);
begin
GenerateStyles(inContainer, inMarkup);
inMarkup.Add(Caption);
end;
end.
|
UNIT JsEdit1;
interface
uses
SysUtils, Classes, Controls, StdCtrls, Graphics, Windows, Messages, Forms, contnrs,
Dialogs, Buttons, math, ibquery;
//type
//JsEditInterface = interface
// ['{37F2C629-0DF6-43FF-B1FC-4A7419DB893E}']
// function GetValorDelimitadoSQL: String;
//end;
type
TtipoEntrada = (teTexto, teNumero);
JsEdit = class(TEdit)
private
FOldBackColor : TColor;
FColorOnEnter : TColor;
valida : boolean;
UsarCadastro, UsarGeneratorCad : boolean;
tipo : TtipoEntrada;
property OldBackColor : TColor read FOldBackColor write FOldBackColor;
protected
FAlignment: TAlignment;
procedure DoEnter; override;
procedure DoExit; override;
procedure CreateParams(var Params: TCreateParams); override;
procedure SetAlignment(const Value: TAlignment);
public
func : boolean;
num :integer;
form, tipoBancoDados,Ulterro : string;
class function getCamposNomes(formi : string) : String;
function ContaComponentesPorForm(form:string) : integer;
constructor Create(AOwner:TComponent);override;
procedure KeyPress(var Key: Char); override;
procedure KeyDown(var Key: Word; shift : TShiftState);override;
function GetValorInteiro() : Integer;
class function verSeExisteNoBD(cod, primarykey, tabela : String) : boolean;
class function validaNome(const ent : string) : String;
class function RemoveAcento(Str: string): string;
class function DeletaChar(sub:string;texto:string):string;
class function RetornaIndiceDoUltimoCampo(formi:string) : Integer;
class function RetornaIndiceDoPrimeiroCampo(formi:string) : Integer;
class function Retorna_Indice_Do_PrimeiroCampo_Ativado(formi:string) : Integer;
//class function retornaIndice(param:integer;ulti:Integer;prim:integer):integer;
class function GetValorInteiroDoPrimeiroCampo(formi:string) : Integer;
class function ConteudoDelimitado(campo : TObject) : String;
class procedure LiberaMemoria(form:tform);
class procedure LimpaCampos(form:string);
class procedure SetFocusNoPrimeiroCampo(comp:string);
class procedure SetFocusNoUltimoCampo;
class procedure AdicionaBotao(Botao : TBitBtn);
class procedure SetFocusNoPrimeiroBotao();
class function GetPrimeiroCampo(formi:string) : JsEdit;
class function GetPrimeiroBotao(form:string) : TBitBtn;
class function GetUltimoBotao(form:string) : TBitBtn;
class function GravaNoBD(form:tform; usaGen : boolean = true; genName : string = ''; msgErro : boolean = true) : string;
class function SelecionaDoBD(formi:string; msg :boolean = true; condicao : String = '') : boolean;
class function NovoCodigo(formi:string; genName : String = '') : integer;
class function AchaProximo(comp:TComponent) : TComponent;
class function UltimoCodigoDaTabela(formi:string; genName : String = '') : integer;
class procedure SetTabelaDoBd(form:tform;tabela1 : string; query1 : tibquery; primarykey1 : String = '');
class procedure AdicionaComponente(componente : TObject);
class procedure RecuperaValorDoCampo(campo : TCustomEdit; query : tibquery);
class function GetLista() : TObjectList;
class function StrNum(lin : String) : String;
class function GetValorNumericoAsString(lin : String) : String;
class function ExcluiDoBD(formi:string; condicao:string = '') : boolean;
class function Incrementa_Generator(Gen_name : string; valor_incremento : integer) : string;
published
//property Alignment : TAlignment read FAlignment write SetAlignment;
property AddLista :boolean read func write func default true;
property UsarCadastros :boolean read UsarCadastro write UsarCadastro default true;
property UsarGeneratorCadastro :boolean read UsarGeneratorCad write UsarGeneratorCad default true;
property FormularioComp: string read form write form;
property ColorOnEnter : TColor read FColorOnEnter write FColorOnEnter default clWhite;
property ValidaCampo : boolean read valida write valida default false;
property Indice :integer read num write num;
property TipoDeDado : TtipoEntrada read tipo write tipo;
end;
procedure Register;
implementation
uses DB, StrUtils, JsEditNumero1;
//Uma variável qualquer declarada aqui é entendida como atributo da classe
var lista,botoes : TObjectList;tabelas, primarykey:Tstringlist; primeiroBotao, ultimoBotao : TBitBtn;
primeiroCampo : TObject; tabela,formulario : string; query : tibquery;conta,n:integer;
procedure Register;
begin
RegisterComponents('JsEdit', [JsEdit]);
end;
constructor JsEdit.Create(AOwner: TComponent);
begin
Inherited;
UsarCadastro := true;
UsarGeneratorCad := true;
FColorOnEnter := clWhite;
func := true;
FAlignment := taLeftJustify;
if self.ClassName = 'JsEditNumero' then FAlignment := taRightJustify;
RecreateWnd;
self.TipoDeDado := teTexto;
if self.ClassName = 'JsEditInteiro' then self.TipoDeDado := teNumero;
if self.ClassName = 'JsEditNumero' then self.TipoDeDado := teNumero;
self.tipo := teNumero;
self.form := self.Owner.Name;
Self.CharCase := ecUpperCase;
if func then AdicionaComponente(Self);
//Color := FColorOnEnter;
end;
class function jsedit.Incrementa_Generator(Gen_name : string; valor_incremento : integer) : string;
begin
query.Close;
Application.HelpFile := 'FB';
if Application.HelpFile = 'PG' then begin
Gen_name := Gen_name + '_gen';
if valor_incremento = 0 then begin
Query.SQL.Text := ('SELECT last_value as venda FROM ' + Gen_name);
end
else Query.SQL.Text := ('select nextval('+ QuotedStr(Gen_name)+') as venda');
end
else if Application.HelpFile = 'FB' then query.SQL.Text :=('select gen_id('+ Gen_name +','+ IntToStr(valor_incremento) +') as venda from rdb$database');
//query.SQL.text := ('select gen_id('+ Gen_name +','+ IntToStr(valor_incremento) +') as venda from rdb$database');
query.Open;
Result := '';
Result := query.fieldbyname('venda').AsString;
query.Close;
end;
class function jsedit.RetornaIndiceDoUltimoCampo(formi:string) : Integer;
var i : integer;
begin
Result := -1;
if not Assigned(lista) then lista := TObjectList.Create;
if lista.Count = 0 then exit;
for i := lista.Count-1 downto 0 do
begin
if not Assigned(lista.Items[i]) then lista.Delete(i)
else
begin
try
if Assigned(lista.Items[i]) then begin
if (formi = tedit(lista.Items[i]).Owner.Name) then begin
result := i;
break ;
end;
end;
finally
end;
end;
end;
end;
class function jsedit.RetornaIndiceDoPrimeiroCampo(formi : string) : Integer;
var i : integer;
begin
if not Assigned(lista) then lista := TObjectList.Create;
result := -1;
if lista = nil then exit;
for i := 0 to lista.Count - 1 do
begin
try
if (formi = tEdit(lista.Items[i]).Owner.Name) then begin
result := i;
break ;
end;
finally
end;
end;
end;
class function jsedit.Retorna_Indice_Do_PrimeiroCampo_Ativado(formi:string) : Integer;
var i : integer;
begin
result := 0;
if lista <> nil then
begin
for i := 0 to lista.Count - 1 do
begin
try
if (formi = tEdit(lista.Items[i]).Owner.Name) and (tEdit(lista.Items[i]).Enabled) then begin
result := i;
break ;
end;
finally
end;
end;
end;
end;
function jsedit.ContaComponentesPorForm(form:string) : integer;
var i : integer;
begin
result := 0;
for i := 0 to lista.Count -1 do
begin
try
if form = self.form then result := Result+1;
finally
end;
end;
end;
class function JsEdit.AchaProximo(comp:TComponent) : TComponent;
var i, atual, fim: integer;
begin
atual := 9999;
fim := lista.Count -1;
//ShowMessage('22=' + IntToStr(fim));
for i := 0 to fim do
begin
//se o formulario do componente atual é igual ao formulario do componente q foi passado como parametro
try
//ShowMessage('33=' + TEdit(lista.Items[i]).Name);
if (TEdit(lista.Items[i]).Owner.Name = TEdit(comp).owner.Name) then begin
//quando o contador for maior que o componente atual
if i > atual then
begin
//se estiver habilitado dá o focus e para o loop
if (TEdit(lista.Items[i]).Enabled) and (TEdit(lista.Items[i]).Visible) then
begin
Tedit(lista.Items[i]).SetFocus;
//Tedit(lista.Items[i]).SelLength := Length(Tedit(lista.Items[i]).Text);
//Tedit(lista.Items[i]).SelStart := 0;
break;
end;
end;
//comparacao para encontrar o componente atual
if tedit(lista.Items[i]).Name = tedit(comp).Name then
begin
//se o contador (i) é igual ao ultimo entao dá o focus no primeiro botao
if i = RetornaIndiceDoUltimoCampo(jsedit(comp).owner.Name) then
begin
if GetPrimeiroBotao(comp.Owner.Name)<> nil then begin
if GetPrimeiroBotao(comp.Owner.Name) <> nil then
GetPrimeiroBotao(comp.Owner.Name).SetFocus;
end;
end;
atual := i;
end;
end;
finally
end;
end;
end;
procedure JsEdit.SetAlignment(const Value: TAlignment);
begin
// if FAlignment <> Value then
// begin
FAlignment := Value;
RecreateWnd;
// end;
end; (*SetAlignment*)
procedure JsEdit.CreateParams(var Params: TCreateParams);
const
Alignments: array[TAlignment] of DWORD = (ES_LEFT, ES_RIGHT, ES_CENTER);
begin
inherited CreateParams(Params);
with Params do
Style := Style or Alignments[FAlignment];
end; (*CreateParams*)
class procedure JsEdit.AdicionaComponente(componente : TObject);
begin
if lista = nil then lista := TObjectList.Create;
lista.Add(componente);
end;
procedure JsEdit.KeyPress(var Key: Char);
var ok : boolean;
begin
inherited KeyPress(Key);
if self.func then
begin
ok := true;
//se foi pressionado enter, se é o primeiro campo, se está em branco e se é um JsEditInteiro - preenche com 0
if (Key = #13) and (self = lista.Items[RetornaIndiceDoPrimeiroCampo(self.Owner.Name)]) and (Self.Text = '') and (UsarCadastro) then
//and (Self.ClassName = 'JsEditInteiro') then
begin
Self.Text := '0';
end;
//se foi pressionado enter, se é o primeiro campo, e se está preenchido
if (Key = #13) and (self = lista.Items[RetornaIndiceDoPrimeiroCampo(self.Owner.Name)]) and (Self.Text <> '0') and (Self.ClassName = 'JsEditInteiro') and (UsarCadastro) then
begin
ok := SelecionaDoBD(self.Owner.Name);
if ok = false then begin
key := #0;
exit;
end;
end;
if (Key = #13) then
begin
//se valida campo, não deixa passar em branco
if (Self.valida) and (Self.Text = '') then
begin
ShowMessage('Campo de preenchimento obrigatório');
Self.SetFocus;
exit;
end;
if ok then begin
if func then AchaProximo(self);
end
else
Key := #0;
end;
try
if ((Key = #27) and (self <> JsEdit(lista.Items[RetornaIndiceDoPrimeiroCampo(self.Owner.Name)]))) then //and (func)
begin
LimpaCampos(self.Owner.Name);
end;
except
end;
end;
end;
procedure JsEdit.KeyDown(var Key: Word; shift : TShiftState);
begin
inherited;
//teclas PgUp e PgDown - passam o foco para o çprimeiro botão
if ((Key = 33) or (Key = 34)) then
begin
if GetPrimeiroBotao(self.Owner.Name)<>nil then GetPrimeiroBotao(self.Owner.Name).SetFocus;
end;
//seta acima - sobe até o primeiro componente
if (Key = 38) then begin
if TEdit(lista.Items[RetornaIndiceDoPrimeiroCampo(self.Owner.Name)]).Enabled then primeiroCampo := lista.Items[RetornaIndiceDoPrimeiroCampo(self.Owner.Name)] else
primeiroCampo := lista.Items[Retorna_Indice_Do_PrimeiroCampo_Ativado(self.Owner.Name)];
if (TComponent(self) <> TComponent(primeiroCampo)) then
begin
try
PostMessage((Owner as TWinControl).Handle, WM_NEXTDLGCTL, 1, 0);
except
end;
end;
end;
//seta abaixo - não passa do primeiro e nem do último para baixo
if ((Key = 40) and (TComponent(self) <> TComponent(lista.Items[RetornaIndiceDoUltimoCampo(self.owner.Name)]))) then
begin
PostMessage((Owner as TWinControl).Handle, WM_NEXTDLGCTL, 0, 0);
end;
end;
procedure JsEdit.DoEnter;
begin
//if (Color = clWindow) then FColorOnEnter := clMoneyGreen;
OldBackColor := Color;
Color := FColorOnEnter;
inherited;
end;
procedure JsEdit.DoExit;
begin
Color := OldBackColor;
inherited;
end;
class procedure JsEdit.LiberaMemoria(form : tform);
var
i, a : integer;
listatemp : TObjectList;
botoestemp : TObjectList;
begin
if not Assigned(lista) then lista := TObjectList.Create;
if not Assigned(botoes) then botoes := TObjectList.Create;
//varre a lista de traz pra frente excluindo os componentes
a := 0;
try
if lista <> nil then
begin
for i := lista.Count-1 downto 0 do begin
try
if tform(lista.Items[i]).Owner.Name = form.Name then begin
lista.Delete(i);
end;
except
on e:exception do begin
//ShowMessage('erro1:' + e.Message + #13 + 'idx=' + IntToStr(i));
end;
end;
end;
if Assigned(botoes) then begin
for i := botoes.Count-1 downto 0 do
begin
try
if TBitBtn(botoes.Items[i]).Owner.Name = form.Name then begin
botoes.Delete(i);
end;
except
on e:exception do begin
//ShowMessage('erro2:' + e.Message);
end;
end;
end;
end;
end;
finally
end;
end;
class procedure JsEdit.SetFocusNoPrimeiroCampo(comp:string);
var i : integer;
begin
//self.GetPrimeiroCampo(comp).SetFocus;
//exit;
for i := 0 to lista.Count-1 do
begin
try
if comp = jsedit(lista.Items[i]).Owner.Name then begin
if not tedit(lista.Items[i]).Visible then
begin
tedit(lista.Items[i + 1]).SetFocus;
exit;
end;
tedit(lista.Items[i]).Enabled := true;
tedit(lista.Items[i]).SetFocus;
break ;
end;
finally
end;
end;
{ JsEdit(lista.First).enabled := true;
JsEdit(lista.First).SetFocus;}
end;
class procedure JsEdit.SetFocusNoUltimoCampo;
var i : integer;
begin
for i := lista.Count-1 downto 0 do
begin
try
if formulario = tedit(lista.Items[i]).Owner.Name then begin
tedit(lista.Items[i]).Enabled := true;
tedit(lista.Items[i]).SetFocus;
break ;
end;
finally
end;
end;
end;
class procedure JsEdit.SetFocusNoPrimeiroBotao();
begin
if primeiroBotao <> nil then primeiroBotao.SetFocus;
end;
class procedure jsedit.LimpaCampos(form:string);
var
ini, fim : integer;
tipo, decimais : String;
begin
fim := RetornaIndiceDoUltimoCampo(form);
ini := RetornaIndiceDoPrimeiroCampo(form);
if ini = -1 then exit;
for ini := ini to fim do
begin
try
tipo := lista.Items[ini].ClassName;
JsEdit(lista.Items[ini]).Text := '';
if tipo = 'JsEditData' then
JsEdit(lista.Items[ini]).Text := '__/__/____';
if tipo = 'JsEditCPF' then
JsEdit(lista.Items[ini]).Text := '___.___.___-__';
if tipo = 'JsEditCNPJ' then
JsEdit(lista.Items[ini]).Text := '__.___.___/___-___';
if tipo = 'JsEditNumero' then begin
DECIMAIS := '00';
if JsEditNumero(lista.Items[ini]).decimal = 6 then DECIMAIS := '000000'
else if JsEditNumero(lista.Items[ini]).decimal = 5 then DECIMAIS := '00000'
else if JsEditNumero(lista.Items[ini]).decimal = 4 then DECIMAIS := '0000'
else if JsEditNumero(lista.Items[ini]).decimal = 3 then DECIMAIS := '000'
else if JsEditNumero(lista.Items[ini]).decimal = 2 then DECIMAIS := '00';
JsEditNumero(lista.Items[ini]).deci := false;
IF POS(UpperCase(JsEdit(lista.Items[ini]).Name), 'P_COMPRA|QUANT') > 0 THEN DECIMAIS := '000';
JsEdit(lista.Items[ini]).Text := '0,' + decimais;
end;
finally
end;
end;
SetFocusNoPrimeiroCampo(form);
end;
//procedure JsEdit.KeyUp(var Key: Word; shift : TShiftState);
//begin
//end;
class procedure JsEdit.AdicionaBotao(botao : TBitBtn);
begin
if botoes = nil then botoes := TObjectList.Create;
botoes.Add(Botao);
{ if primeiroBotao = nil then primeiroBotao := botao;
ultimoBotao := botao;
}end;
class function JsEdit.GetPrimeiroBotao(form:string) : TBitBtn;
var i : Integer;
begin
Result := nil;
if botoes <> nil then
begin
for i := 0 to botoes.Count - 1 do
begin
try
if TBitBtn(botoes.Items[i]).Owner.Name = form then
begin
result := TBitBtn(botoes.Items[i]);
break;
end;
finally
end;
end;
end;
// result := primeiroBotao;
end;
class function JsEdit.GetUltimoBotao(form:string) : TBitBtn;
var i : Integer;
begin
if botoes <> nil then
begin
for i := botoes.Count - 1 downto 0 do
begin
try
if TBitBtn(botoes.Items[i]).Owner.Name = form then
begin
result := TBitBtn(botoes.Items[i]);
break;
end;
finally
end;
end;
end;
// result := ultimoBotao;
end;
class function JsEdit.GetPrimeiroCampo(formi:string) : JsEdit;
var i :integer;
begin
// varre a lista e retorna o primeiro componente do formulario e sai do loop
result := nil;
if lista <> nil then
begin
for i := 0 to lista.Count-1 do
begin
try
if formi = jsedit(lista.Items[i]).owner.Name then begin
result := JsEdit(lista.Items[i]);
break;
end;
finally
end;
end;
end;
end;
class function JsEdit.GravaNoBD(form:tform; usaGen : boolean = true; genName : string = ''; msgErro : boolean = true) : string;
var
ini, fim, ultCod, codAtual, tmp : integer; stringSql, PKTabela,
sqlUpdate, condicao : String;
arq : TStringList;
begin
//ultima atualização tirar verificação de código (codatual >= 0)and(codatual<=ultcod)
tabela := LowerCase(tabelas.Values[form.Name]);
codAtual := GetValorInteiroDoPrimeiroCampo(form.Name);
Result := '';
condicao := '';
if usaGen then
begin
ultCod := UltimoCodigoDaTabela(form.Name,genName);
if (codAtual = 0) then
begin
JsEdit(lista.Items[RetornaIndiceDoPrimeiroCampo(form.Name)]).Text := inttostr(JsEdit.NovoCodigo(form.Name,genName));
end;
end;
Result := JsEdit(lista.Items[RetornaIndiceDoPrimeiroCampo(form.Name)]).Text;
//stringSql := 'update or insert into ' + tabela + ' ( ';
stringSql := 'insert into ' + tabela + ' ( ';
sqlUpdate := 'update ' + tabela + ' set ';
//fim = ao indice do ultimo campo do formulario na lista
fim := RetornaIndiceDoUltimoCampo(form.Name);
//pega os nomes dos campos
tmp := RetornaIndiceDoPrimeiroCampo(form.Name);
for ini := tmp + 1 to fim do begin
if (JsEdit(lista.Items[ini]).Enabled) or (ini = tmp) then begin
sqlUpdate := sqlUpdate + JsEdit(lista.Items[ini]).Name + ' = ' +
JsEdit.ConteudoDelimitado(lista.Items[ini]);
if (ini <> fim) then sqlUpdate := sqlUpdate + ', ';
end;
end;
//fim = ao indice do ultimo campo do formulario na lista
fim := RetornaIndiceDoUltimoCampo(form.Name);
//pega os nomes dos campos
tmp := RetornaIndiceDoPrimeiroCampo(form.Name);
for ini := tmp to fim do
begin
if (JsEdit(lista.Items[ini]).Enabled) or (ini = tmp) then
begin
stringSql := stringSql + JsEdit(lista.Items[ini]).Name;
if (ini <> fim) then stringSql := stringSql + ', ';
end;
end;
stringSql := stringSql + ' ) values (';
//pega os conteúdos dos campos
for ini := tmp to fim do
begin
if (JsEdit(lista.Items[ini]).Enabled) or (ini = tmp) then
begin
stringSql := stringSql + JsEdit.ConteudoDelimitado(lista.Items[ini]);
if (ini <> fim) then stringSql := stringSql + ', ';
end;
end;
stringSql := stringSql + ' )';
if primarykey.Values[form.Name] <> '' then begin
condicao := ' where ' + primarykey.Values[form.Name] + ' = ' + Result;
PKTabela := primarykey.Values[form.Name];
end;
if condicao = '' then begin
condicao := ' where ' + JsEdit(lista.Items[RetornaIndiceDoPrimeiroCampo(form.Name)]).Name + ' = ' +
JsEdit(lista.Items[RetornaIndiceDoPrimeiroCampo(form.Name)]).Text;
PKTabela := JsEdit(lista.Items[RetornaIndiceDoPrimeiroCampo(form.Name)]).Name;
end;
sqlUpdate := sqlUpdate + condicao;
{if primarykey.Values[form.Name] <> '' then
begin
stringSql := stringSql + ' matching('+ primarykey.Values[form.Name] +')';
end;}
query.Close;
if verSeExisteNoBD(Result, PKTabela, tabela) then query.SQL.Text := sqlUpdate
else query.SQL.Text := (stringSql);
arq := TStringList.Create;
arq.Text := sqlUpdate;
arq.Text := arq.Text + #13 + #13 + stringSql;
arq.SaveToFile(ExtractFileDir(ParamStr(0)) + '\sql.text');
arq.Free;
if query.Transaction.InTransaction then query.Transaction.Commit;
if msgErro = false then begin
query.ExecSQL;
end
else begin
try
query.ExecSQL;
except
on e:exception do begin
MessageDlg(e.Message + #13 + #13 + stringSql, mtError, [mbOK], 1);
exit;
end;
end;
end;
if query.Transaction.InTransaction then query.Transaction.Commit;
LimpaCampos(form.Name);
end;
class function JsEdit.ConteudoDelimitado(campo : TObject) : String;
var atual : TCustomEdit;
begin
atual := TCustomEdit(campo);
result := #39 + validaNome(atual.text) + #39;
if campo.ClassName = 'JsEditInteiro' then begin
if(atual.Text = '') then result := '0' else result := atual.Text;
if JsEdit(atual).tipo = teTexto then begin
Result := QuotedStr(Result);
end
end;
if campo.ClassName = 'JsEditData' then
begin
if pos('_',atual.Text) > 0 then Result := #39+'01.01.1900'+#39
else result := #39 + copy(atual.Text, 1, 2) + '.' + copy(atual.Text, 4, 2) + '.' + copy(atual.Text, 7, 4) + #39;;
end;
if campo.ClassName = 'JsEditNumero' then
begin
result := (GetValorNumericoAsString(atual.Text));
end;
end;
class function JsEdit.GetValorNumericoAsString(lin : String) : String;
var pos, fim : integer; ret : String;
begin
fim := length(lin);
for pos := 1 to fim do
begin
if (lin[pos] in ['0'..'9', '-']) then ret := ret + lin[pos];
if (lin[pos] = ',') then ret := ret + '.';
end;
result := ret;
end;
//devolve apenas dígitos de 0 a 9 de uma string
class function JsEdit.StrNum(lin : String) : String;
var pos, fim : integer; ret : String;
begin
fim := length(lin);
for pos := 1 to fim do
begin
if (lin[pos] in ['0'..'9']) then ret := ret + lin[pos];
end;
result := ret;
end;
class function JsEdit.NovoCodigo(formi:string; genName : String = '') : integer;
var novoCod : integer;
begin
if genName = '' then genName := tabelas.Values[formi];
Result := StrToInt(Incrementa_Generator(genName, 1));
exit;
if genName = '' then genName := tabelas.Values[formi];
query.SQL.Clear;
query.SQL.add('select gen_id('+LowerCase(genName)+',1) as cod from RDB$DATABASE');
query.Open;
Result := query.fieldbyname('cod').AsInteger;
query.Close;
query.SQL.Clear;
{novoCod := 0;
tabela := LowerCase(tabelas.Values[formi]);
while true do
begin
try
query.Transaction.Active := true;
query.SQL.Clear;
query.SQL.Add('update controle set codigo = codigo + 1 where tabela = :tab');
query.ParamByName('tab').AsString := tabela;
query.Open;
query.SQL.Clear;
query.SQL.Add('select codigo from controle where tabela = :tab WITH LOCK');
query.ParamByName('tab').AsString := tabela;
query.Open;
novoCod := query.fieldbyname('codigo').Asinteger;
query.ApplyUpdates;
query.Close;
query.Transaction.Commit;
query.Transaction.Active := false;
break;
except
query.Transaction.Rollback;
query.Close;
query.Transaction.Active := false;
end;;
end;
result := novoCod;}
end;
class function JsEdit.ExcluiDoBD(formi:string; condicao:string = '') : boolean;
var nome : String; cod : integer; ok : boolean;
begin
ok := false;
tabela := LowerCase(tabelas.Values[formi]);
nome := JsEdit(lista.Items[RetornaIndiceDoPrimeiroCampo(formi)]).Text;
if nome = '' then cod := 0 else cod := strtoint(nome);
nome := JsEdit(lista.Items[RetornaIndiceDoPrimeiroCampo(formi) + 1]).Text;
if cod <> 0 then
begin
if MessageDlg('Confirma Exclusão de ' + nome + ' codigo ' + inttostr(cod) + ' da tabela ' + tabela + '?', mtInformation, [mbYes, mbNo], 0) = mrYes then
begin
if condicao = '' then condicao := 'cod = :codl';
query.Close;
//query.Transaction.Active := true;
query.SQL.Clear;
query.SQL.Add('delete from ' + tabela + ' where '+ condicao );
if Pos(':', condicao) > 0 then query.ParamByName('codl').AsInteger := cod;
query.ExecSQL;
query.Close;
query.Transaction.Commit;
//query.Transaction.Active := false;
LimpaCampos(formi);
ok := true;
end;
end;
if (not ok) then SetFocusNoPrimeiroCampo('');
result := ok;
end;
class function JsEdit.UltimoCodigoDaTabela(formi:string; genName : String = '') : integer;
var ultCod : integer;
begin
{query.Close;
query.SQL.Clear;
query.SQL.Add('select max(cod) as cod from ' + tabelas.Values[formi]);
query.Open;
ultCod := query.fieldbyname('cod').Asinteger;
query.Close;}
if genName = '' then genName := tabelas.Values[formi];
ultCod := StrToInt(Incrementa_Generator(genName, 0));
result := ultCod;
end;
function JsEdit.GetValorInteiro() : Integer;
var cod : Integer;
begin
if (self.Text = '') then cod := 0 else
cod := strtoint(Self.Text);
result := cod;
end;
class function JsEdit.GetValorInteiroDoPrimeiroCampo(formi:string) : Integer;
var cod : Integer;
begin
try
if StrNum(JsEdit.GetPrimeiroCampo(formi).Text) <> '0' then result := StrToInt(JsEdit.GetPrimeiroCampo(formi).Text)
else result := 0;
except
end;
end;
class function JsEdit.SelecionaDoBD(formi:string; msg :boolean = true; condicao : String = '') : boolean;
var
cod, ini, fim : integer;
begin
cod := JsEdit.GetValorInteiroDoPrimeiroCampo(formi);
query.SQL.Clear;
if primarykey.Values[formi] <> '' then
begin
if condicao = '' then condicao := '('+primarykey.Values[formi]+' = :codigo)';
end
else
begin
if condicao = '' then condicao := '(cod = :codigo)';
end;
//if condicao = '(cod = :codigo)' then condicao := '(cod = '+StrNum(IntToStr(cod))+')';
//query.SQL.Text := ('select '+getCamposNomes(formi)+' from ' + tabelas.Values[formi] + ' where ' + condicao);
query.SQL.Text := ('select * from ' + tabelas.Values[formi] + ' where ' + condicao);
if pos(':codigo', condicao) > 0 then query.ParamByName('codigo').AsInteger := cod;
try
query.Open;
except
on e:exception do
begin
ShowMessage(formi);
exit;
end;
end;
if query.IsEmpty then
begin
if msg then
begin
ShowMessage('Código não encontrado: ' + inttostr(cod));
LimpaCampos(formi);
end;
query.close;
result := false;
end
else
begin
fim := RetornaIndiceDoUltimoCampo(formi);
//pega os nomes dos campos
for ini := RetornaIndiceDoPrimeiroCampo(formi) to fim do
begin
RecuperaValorDoCampo(TCustomEdit(lista.Items[ini]), query);
end;
query.close;
result := true;
end;
end;
class procedure JsEdit.SetTabelaDoBd(form:tform;tabela1 : string; query1 : tibquery; primarykey1 : String = '');
begin
if not Assigned(tabelas) then tabelas := TStringList.Create;
if not Assigned(primarykey) then primarykey := TStringList.Create;
if tabelas.Values[form.Name]='' then tabelas.Add(form.Name+'='+tabela1);
if primarykey1 <> '' then primarykey.Values[form.Name] := primarykey1;
query := query1;
end;
class procedure JsEdit.RecuperaValorDoCampo(campo : TCustomEdit; query : tibquery);
var ret, nomeDoCampo, nomeDaClasse, DECIMAIS : String;
begin
nomeDoCampo := campo.Name;
DECIMAIS := '00';
nomeDaClasse := campo.ClassName;
ret := query.FieldByName(nomeDoCampo).AsString;
if (nomeDaClasse = 'JsEditNumero') then
begin
nomeDoCampo := UpperCase(nomeDoCampo);
if JsEditNumero(campo).decimal = 6 then DECIMAIS := '000000'
else if JsEditNumero(campo).decimal = 5 then DECIMAIS := '00000'
else if JsEditNumero(campo).decimal = 4 then DECIMAIS := '0000'
else if JsEditNumero(campo).decimal = 3 then DECIMAIS := '000'
else if JsEditNumero(campo).decimal = 2 then DECIMAIS := '00';
IF POS(nomeDoCampo, 'P_COMPRA|P_VENDA|QUANT') > 0 THEN DECIMAIS := '000';
ret := FormatCurr('#,###,###0.' + DECIMAIS, query.FieldByName(nomeDoCampo).AsCurrency);
// if (query.FieldByName(nomeDoCampo).AsString = '') or (query.FieldByName(nomeDoCampo).AsString = '0') then ret := '0,00'
// else ret := query.FieldByName(nomeDoCampo).AsString;
end;
if (nomeDaClasse = 'JsEditInteiro') then
begin
if (query.FieldByName(nomeDoCampo).AsString = '') then ret := '0';
end;
if (nomeDaClasse = 'JsEditData') then
ret := FormatDateTime('dd/mm/yyyy', query.FieldByName(nomeDoCampo).AsDateTime);
campo.Text := ret;
end;
class function JsEdit.GetLista() : TObjectList;
begin
result := lista;
end;
class function JsEdit.DeletaChar(sub:string;texto:string):string;
var i:integer;
begin
Result :='';
for i := 1 to length(texto) do
begin
//ShowMessage(texto[i]);
if sub<>texto[i] then Result := Result + texto[i];
end;
end;
class function JsEdit.RemoveAcento(Str: string): string;
const
ComAcento = 'àâêôûãõáéíóúçüÀÂÊÔÛÃÕÁÉÍÓÚÇÜ';
SemAcento = 'aaeouaoaeioucuAAEOUAOAEIOUCU';
var
x: Integer;
begin;
for x := 1 to Length(Str) do
if Pos(Str[x],ComAcento) <> 0 then
Str[x] := SemAcento[Pos(Str[x], ComAcento)];
Result := Str;
end;
class function JsEdit.validaNome(const ent : string) : String;
begin
Result := RemoveAcento(ent);
Result := DeletaChar(#39, Result);
Result := DeletaChar('"', Result );
end;
class function JsEdit.getCamposNomes(formi : string) : String;
var
ini, fim : integer;
begin
fim := RetornaIndiceDoUltimoCampo(formi);
//fim := StrToInt(InputBox('','',''));
Result := '';
//pega os nomes dos campos
for ini := RetornaIndiceDoPrimeiroCampo(formi) to fim do
begin
Result := Result + TCustomEdit(lista.Items[ini]).Name + IfThen(ini <> fim, ',', '');
end;
end;
class function JsEdit.verSeExisteNoBD(cod, primarykey, tabela : String) : boolean;
begin
Result := false;
query.Close;
query.SQL.Text := 'select ' + primarykey + ' from ' + tabela + ' where ' + primarykey +
' = ' + cod;
query.Open;
if query.IsEmpty then begin
Result := false;
end
else Result := true;
end;
end.
|
unit UniteTestReponse;
interface
uses sysutils, TestFrameWork, uniteProtocole, uniteRequete, uniteReponse;
type
TestReponse = class (TTestCase)
published
procedure testReponseCreate;
end;
implementation
procedure TestReponse.testReponseCreate;
var
reponseHTTP:Reponse;
begin
reponseHTTP:=Reponse.create('1', '2', 3, '4', '5');
if reponseHTTP.getAdresseDemandeur <> '1' then
fail('Premier paramètre eronné (adresseDemandeur)');
if reponseHTTP.getVersionProtocole <> '2' then
fail('Deuxième paramètre eronné (versionProtocole)');
if reponseHTTP.getCodeReponse <> 3 then
fail('troisième paramètre erroné (codeReponse)');
if reponseHTTP.getMessage <> '4' then
fail('Quatrième paramètre erroné (message)');
if reponseHTTP.getReponseHtml <> '5' then
fail('Cinquième paramètre erroné (reponseHtml)');
end; //Suggestion : un seul fail, un seul message délivré résumant les méthodes get ayant retourné un résultat erroné. (if getBob <> 'bob' then Erreurs:= Erreurs+' bob'... fail('Échec sur : ' + Erreurs). Permettrait de ne pas répéter des tests séparés sur les accesseurs.
initialization
TestFrameWork.RegisterTest(TestReponse.Suite);
end.
|
unit epanet2;
{$MODE Delphi}
{ Declarations of imported procedures from the EPANET PROGRAMMERs TOOLKIT }
{ (EPANET2.DLL) }
{Last updated on 10/25/00}
interface
const
{ These are codes used by the DLL functions }
EN_ELEVATION = 0; { Node parameters }
EN_BASEDEMAND = 1;
EN_PATTERN = 2;
EN_EMITTER = 3;
EN_INITQUAL = 4;
EN_SOURCEQUAL = 5;
EN_SOURCEPAT = 6;
EN_SOURCETYPE = 7;
EN_TANKLEVEL = 8;
EN_DEMAND = 9;
EN_HEAD = 10;
EN_PRESSURE = 11;
EN_QUALITY = 12;
EN_SOURCEMASS = 13;
EN_DIAMETER = 0; { Link parameters }
EN_LENGTH = 1;
EN_ROUGHNESS = 2;
EN_MINORLOSS = 3;
EN_INITSTATUS = 4;
EN_INITSETTING = 5;
EN_KBULK = 6;
EN_KWALL = 7;
EN_FLOW = 8;
EN_VELOCITY = 9;
EN_HEADLOSS = 10;
EN_STATUS = 11;
EN_SETTING = 12;
EN_ENERGY = 13;
EN_DURATION = 0; { Time parameters }
EN_HYDSTEP = 1;
EN_QUALSTEP = 2;
EN_PATTERNSTEP = 3;
EN_PATTERNSTART = 4;
EN_REPORTSTEP = 5;
EN_REPORTSTART = 6;
EN_RULESTEP = 7;
EN_STATISTIC = 8;
EN_PERIODS = 9;
EN_NODECOUNT = 0; { Component counts }
EN_TANKCOUNT = 1;
EN_LINKCOUNT = 2;
EN_PATCOUNT = 3;
EN_CURVECOUNT = 4;
EN_CONTROLCOUNT = 5;
EN_JUNCTION = 0; { Node types }
EN_RESERVOIR = 1;
EN_TANK = 2;
EN_CVPIPE = 0; { Link types }
EN_PIPE = 1;
EN_PUMP = 2;
EN_PRV = 3;
EN_PSV = 4;
EN_PBV = 5;
EN_FCV = 6;
EN_TCV = 7;
EN_GPV = 8;
EN_NONE = 0; { Quality analysis types }
EN_CHEM = 1;
EN_AGE = 2;
EN_TRACE = 3;
EN_CONCEN = 0; { Source quality types }
EN_MASS = 1;
EN_SETPOINT = 2;
EN_FLOWPACED = 3;
EN_CFS = 0; { Flow units types }
EN_GPM = 1;
EN_MGD = 2;
EN_IMGD = 3;
EN_AFD = 4;
EN_LPS = 5;
EN_LPM = 6;
EN_MLD = 7;
EN_CMH = 8;
EN_CMD = 9;
EN_TRIALS = 0; { Option types }
EN_ACCURACY = 1;
EN_TOLERANCE = 2;
EN_EMITEXPON = 3;
EN_DEMANDMULT = 4;
EN_LOWLEVEL = 0; { Control types }
EN_HILEVEL = 1;
EN_TIMER = 2;
EN_TIMEOFDAY = 3;
EN_AVERAGE = 1; { Time statistic types }
EN_MINIMUM = 2;
EN_MAXIMUM = 3;
EN_RANGE = 4;
EN_NOSAVE = 0; { Save-results-to-file flag }
EN_SAVE = 1;
EN_INITFLOW = 10; { Re-initialize flow flag }
function ENepanet(F1: Pchar; F2: Pchar; F3: Pchar; F4: Pointer): Integer; stdcall;
function ENopen(F1: Pchar; F2: Pchar; F3: Pchar): Integer; stdcall;
function ENsaveinpfile(F: Pchar): Integer; stdcall;
function ENclose: Integer; stdcall;
function ENsolveH: Integer; stdcall;
function ENsaveH: Integer; stdcall;
function ENopenH: Integer; stdcall;
function ENinitH(SaveFlag: Integer): Integer; stdcall;
function ENrunH(var T: LongInt): Integer; stdcall;
function ENnextH(var Tstep: LongInt): Integer; stdcall;
function ENcloseH: Integer; stdcall;
function ENsavehydfile(F: Pchar): Integer; stdcall;
function ENusehydfile(F: Pchar): Integer; stdcall;
function ENsolveQ: Integer; stdcall;
function ENopenQ: Integer; stdcall;
function ENinitQ(SaveFlag: Integer): Integer; stdcall;
function ENrunQ(var T: LongInt): Integer; stdcall;
function ENnextQ(var Tstep: LongInt): Integer; stdcall;
function ENstepQ(var Tleft: LongInt): Integer; stdcall;
function ENcloseQ: Integer; stdcall;
function ENwriteline(S: Pchar): Integer; stdcall;
function ENreport: Integer; stdcall;
function ENresetreport: Integer; stdcall;
function ENsetreport(S: Pchar): Integer; stdcall;
function ENgetcontrol(Cindex: Integer; var Ctype: Integer; var Lindex: Integer; var Setting: Single;
var Nindex: Integer; var Level: Single): Integer; stdcall;
function ENgetcount(Code: Integer; var Count: Integer): Integer; stdcall;
function ENgetoption(Code: Integer; var Value: Single): Integer; stdcall;
function ENgettimeparam(Code: Integer; var Value: LongInt): Integer; stdcall;
function ENgetflowunits(var Code: Integer): Integer; stdcall;
function ENgetpatternindex(ID: Pchar; var Index: Integer): Integer; stdcall;
function ENgetpatternid(Index: Integer; ID: Pchar): Integer; stdcall;
function ENgetpatternlen(Index: Integer; var Len: Integer): Integer; stdcall;
function ENgetpatternvalue(Index: Integer; Period: Integer; var Value: Single): Integer; stdcall;
function ENgetqualtype(var QualCode: Integer; var TraceNode: Integer): Integer; stdcall;
function ENgeterror(ErrCode: Integer; ErrMsg: Pchar; N: Integer): Integer; stdcall;
function ENgetnodeindex(ID: Pchar; var Index: Integer): Integer; stdcall;
function ENgetnodeid(Index: Integer; ID: Pchar): Integer; stdcall;
function ENgetnodetype(Index: Integer; var Code: Integer): Integer; stdcall;
function ENgetnodevalue(Index: Integer; Code: Integer; var Value: Single): Integer; stdcall;
function ENgetlinkindex(ID: Pchar; var Index: Integer): Integer; stdcall;
function ENgetlinkid(Index: Integer; ID: Pchar): Integer; stdcall;
function ENgetlinktype(Index: Integer; var Code: Integer): Integer; stdcall;
function ENgetlinknodes(Index: Integer; var Node1: Integer; var Node2: Integer): Integer; stdcall;
function ENgetlinkvalue(Index: Integer; Code: Integer; var Value: Single): Integer; stdcall;
function ENgetversion(var Value: Integer): Integer; stdcall;
function ENsetcontrol(Cindex: Integer; Ctype: Integer; Lindex: Integer; Setting: Single;
Nindex: Integer; Level: Single): Integer; stdcall;
function ENsetnodevalue(Index: Integer; Code: Integer; Value: Single): Integer; stdcall;
function ENsetlinkvalue(Index: Integer; Code: Integer; Value: Single): Integer; stdcall;
function ENsetpattern(Index: Integer; F: array of Single; N: Integer): Integer; stdcall;
function ENsetpatternvalue(Index: Integer; Period: Integer; Value: Single): Integer; stdcall;
function ENsettimeparam(Code: Integer; Value: LongInt): Integer; stdcall;
function ENsetoption(Code: Integer; Value: Single): Integer; stdcall;
function ENsetstatusreport(Code: Integer): Integer; stdcall;
function ENsetqualtype(QualCode: Integer; ChemName: Pchar; ChemUnits: Pchar; TraceNodeID: Pchar): Integer; stdcall;
implementation
function ENepanet; external 'EPANET2.DLL';
function ENopen; external 'EPANET2.DLL';
function ENsaveinpfile; external 'EPANET2.DLL';
function ENclose; external 'EPANET2.DLL';
function ENsolveH; external 'EPANET2.DLL';
function ENsaveH; external 'EPANET2.DLL';
function ENopenH; external 'EPANET2.DLL';
function ENinitH; external 'EPANET2.DLL';
function ENrunH; external 'EPANET2.DLL';
function ENnextH; external 'EPANET2.DLL';
function ENcloseH; external 'EPANET2.DLL';
function ENsavehydfile; external 'EPANET2.DLL';
function ENusehydfile; external 'EPANET2.DLL';
function ENsolveQ; external 'EPANET2.DLL';
function ENopenQ; external 'EPANET2.DLL';
function ENinitQ; external 'EPANET2.DLL';
function ENrunQ; external 'EPANET2.DLL';
function ENnextQ; external 'EPANET2.DLL';
function ENstepQ; external 'EPANET2.DLL';
function ENcloseQ; external 'EPANET2.DLL';
function ENwriteline; external 'EPANET2.DLL';
function ENreport; external 'EPANET2.DLL';
function ENresetreport; external 'EPANET2.DLL';
function ENsetreport; external 'EPANET2.DLL';
function ENgetcontrol; external 'EPANET2.DLL';
function ENgetcount; external 'EPANET2.DLL';
function ENgetoption; external 'EPANET2.DLL';
function ENgettimeparam; external 'EPANET2.DLL';
function ENgetflowunits; external 'EPANET2.DLL';
function ENgetpatternindex; external 'EPANET2.DLL';
function ENgetpatternid; external 'EPANET2.DLL';
function ENgetpatternlen; external 'EPANET2.DLL';
function ENgetpatternvalue; external 'EPANET2.DLL';
function ENgetqualtype; external 'EPANET2.DLL';
function ENgeterror; external 'EPANET2.DLL';
function ENgetnodeindex; external 'EPANET2.DLL';
function ENgetnodeid; external 'EPANET2.DLL';
function ENgetnodetype; external 'EPANET2.DLL';
function ENgetnodevalue; external 'EPANET2.DLL';
function ENgetlinkindex; external 'EPANET2.DLL';
function ENgetlinkid; external 'EPANET2.DLL';
function ENgetlinktype; external 'EPANET2.DLL';
function ENgetlinknodes; external 'EPANET2.DLL';
function ENgetlinkvalue; external 'EPANET2.DLL';
function ENgetversion; external 'EPANET2.DLL';
function ENsetcontrol; external 'EPANET2.DLL';
function ENsetnodevalue; external 'EPANET2.DLL';
function ENsetlinkvalue; external 'EPANET2.DLL';
function ENsetpattern; external 'EPANET2.DLL';
function ENsetpatternvalue; external 'EPANET2.DLL';
function ENsettimeparam; external 'EPANET2.DLL';
function ENsetoption; external 'EPANET2.DLL';
function ENsetstatusreport; external 'EPANET2.DLL';
function ENsetqualtype; external 'EPANET2.DLL';
end.
|
unit ContourExport;
interface
uses Classes, FastGeo, QuadtreeClass, RealListUnit, AbstractGridUnit,
DataSetUnit, SysUtils, GoPhastTypes, ContourUnit, ValueArrayStorageUnit;
type
TPointList = class(TObject)
private
FPoints: array of TPoint2D;
strict private
FCount: integer;
procedure Grow;
function GetCapacity: integer;
function GetPoint(Index: integer): TPoint2D;
procedure SetCapacity(const Value: integer);
procedure SetPoint(Index: integer; const Value: TPoint2D);
public
function Add(Point: TPoint2D): integer;
property Capacity: integer read GetCapacity write SetCapacity;
property Count: integer read FCount;
property Points[Index: integer]: TPoint2D read GetPoint write SetPoint;
procedure Insert(Position: integer; Point: TPoint2D);
end;
TContourExtractor = class(TCustomContourCreator)
private
FQuadTree: TRbwQuadTree;
// @name contains instances of @link(TPointList).
// @name is instantiated as a TObjectList.
// @name is filled in @link(ImportSegments).
FPointLists: TList;
FEpsilon: Real;
FModelGrid: TCustomModelGrid;
FAlgorithm: TContourAlg;
// @name is the event handler for TContourCreator.OnExtractSegments
procedure ImportSegments(Sender: TObject; const Segments: TLine2DArray);
procedure InitializeQuadTree;
procedure InitializeEpsilon;
public
procedure CreateShapes(ValueList: TValueArrayStorage; DataArray: TDataArray;
FileName: string; LabelSpacing: integer);
{ TODO -cRefactor : Consider replacing Model with an interface. }
//
Constructor Create(Model: TBaseModel);
Destructor Destroy; override;
end;
procedure GlobalImportSegments(Sender: TObject;
const Segments: TLine2DArray; Epsilon: Real;
QuadTree: TRbwQuadTree; PointLists: TList);
procedure GlobalInitializeQuadTree(var QuadTree: TRbwQuadTree;
ModelGrid: TCustomModelGrid);
procedure GlobalInitializeEpsilon(var Epsilon: Real; ModelGrid: TCustomModelGrid);
implementation
uses
PhastModelUnit, frmGoPhastUnit, Contnrs, Math,
ShapefileUnit, XBase1, frmExportShapefileUnit, RbwParser, ModelMuseUtilities,
LineStorage, SutraMeshUnit;
procedure GlobalImportSegments(Sender: TObject;
const Segments: TLine2DArray; Epsilon: Real;
QuadTree: TRbwQuadTree; PointLists: TList);
var
Index: Integer;
Segment: TLine2D;
Line1, Line2, Line3: TPointList;
X1, Y1: double;
X2, Y2: double;
APoint: TPoint2D;
PointIndex: Integer;
APointer: Pointer;
function SamePoint(X1, X2, Y1, Y2: double): boolean;
begin
result := Sqr(X1-X2) + Sqr(Y1-Y2) < Epsilon;
end;
begin
for Index := 0 to Length(Segments) - 1 do
begin
Segment := Segments[Index];
if SamePoint(Segment[1].x, Segment[2].x, Segment[1].y, Segment[2].y) then
begin
Continue;
end;
X1 := Segment[1].x;
Y1 := Segment[1].y;
if QuadTree.Count > 0 then
begin
QuadTree.FirstNearestPoint(X1, Y1, APointer);
Line1 := APointer;
end
else
begin
Line1 := nil;
end;
if Line1 <> nil then
begin
if not SamePoint(X1, Segment[1].x, Y1, Segment[1].Y) then
begin
Line1 := nil;
end;
end;
X2 := Segment[2].x;
Y2 := Segment[2].y;
if QuadTree.Count > 0 then
begin
QuadTree.FirstNearestPoint(X2, Y2, APointer);
Line2 := APointer;
end
else
begin
Line2 := nil;
end;
if Line2 <> nil then
begin
if not SamePoint(X2, Segment[2].x, Y2, Segment[2].Y) then
begin
Line2 := nil;
end;
end;
if (Line1 = nil) and (Line2 = nil) then
begin
Line1 := TPointList.Create;
PointLists.Add(Line1);
Line1.Add(Segment[1]);
Line1.Add(Segment[2]);
QuadTree.AddPoint(Segment[1].x, Segment[1].y, Line1);
QuadTree.AddPoint(Segment[2].x, Segment[2].y, Line1);
end
else if (Line1 = nil) then
begin
APoint := Line2.Points[Line2.Count-1];
if SamePoint(Segment[2].x, APoint.x, Segment[2].y, APoint.y) then
begin
Line2.Add(Segment[1]);
end
else
begin
APoint := Line2.Points[0];
Assert(SamePoint(Segment[2].x, APoint.x, Segment[2].y, APoint.y));
Line2.Insert(0, Segment[1]);
end;
QuadTree.RemovePoint(X2, Y2, Line2);
QuadTree.AddPoint(Segment[1].x, Segment[1].y, Line2);
end
else if (Line2 = nil) then
begin
APoint := Line1.Points[Line1.Count-1];
if SamePoint(Segment[1].x, APoint.x, Segment[1].y, APoint.y) then
begin
Line1.Add(Segment[2]);
end
else
begin
APoint := Line1.Points[0];
Assert(SamePoint(Segment[1].x, APoint.x, Segment[1].y, APoint.y));
Line1.Insert(0, Segment[2]);
end;
QuadTree.RemovePoint(X1, Y1, Line1);
QuadTree.AddPoint(Segment[2].x, Segment[2].y, Line1);
end
else if (Line2 = Line1) then
begin
APoint := Line1.Points[Line1.Count-1];
if SamePoint(Segment[1].x, APoint.x, Segment[1].y, APoint.y) then
begin
Line1.Add(Segment[2]);
end
else
begin
APoint := Line1.Points[0];
Assert(SamePoint(Segment[1].x, APoint.x, Segment[1].y, APoint.y));
Line1.Insert(0, Segment[2]);
end;
QuadTree.RemovePoint(X1, Y1, Line1);
QuadTree.RemovePoint(X2, Y2, Line1);
end
else
begin
APoint := Line1.Points[Line1.Count-1];
if (SamePoint(Segment[1].x, APoint.x, Segment[1].y, APoint.y))
or (SamePoint(Segment[2].x, APoint.x, Segment[2].y, APoint.y)) then
begin
// Add to end of line 1
if Line1.Capacity < Line1.Count + Line2.Count then
begin
Line1.Capacity := Line1.Count + Line2.Count
end;
APoint := Line2.Points[Line2.Count-1];
if (SamePoint(Segment[1].x, APoint.x, Segment[1].y, APoint.y))
or (SamePoint(Segment[2].x, APoint.x, Segment[2].y, APoint.y)) then
begin
APoint := Line2.Points[0];
QuadTree.RemovePoint(APoint.x, APoint.y, Line2);
// Add end of line 2 to end of line 1
for PointIndex := Line2.Count - 1 downto 0 do
begin
Line1.Add(Line2.Points[PointIndex]);
end;
end
else
begin
APoint := Line2.Points[Line2.Count - 1];
QuadTree.RemovePoint(APoint.x, APoint.y, Line2);
// Join beginning of line 2 to end of line 1
for PointIndex := 0 to Line2.Count - 1 do
begin
Line1.Add(Line2.Points[PointIndex]);
end;
end;
QuadTree.RemovePoint(X1, Y1, Line1);
QuadTree.RemovePoint(X2, Y2, Line2);
QuadTree.AddPoint(APoint.x, APoint.y, Line1);
PointLists.Remove(Line2);
end
else
begin
APoint := Line2.Points[Line2.Count-1];
if (SamePoint(Segment[1].x, APoint.x, Segment[1].y, APoint.y))
or (SamePoint(Segment[2].x, APoint.x, Segment[2].y, APoint.y)) then
begin
// Add beginning of line 1 to end of line2
if Line2.Capacity < Line1.Count + Line2.Count then
begin
Line2.Capacity := Line1.Count + Line2.Count;
end;
APoint := Line1.Points[Line1.Count - 1];
QuadTree.RemovePoint(APoint.x, APoint.y, Line1);
for PointIndex := 0 to Line1.Count - 1 do
begin
Line2.Add(Line1.Points[PointIndex]);
end;
QuadTree.RemovePoint(X1, Y1, Line1);
QuadTree.RemovePoint(X2, Y2, Line2);
QuadTree.AddPoint(APoint.x, APoint.y, Line2);
PointLists.Remove(Line1);
end
else
begin
// Join beginning of line 1 to beginning of line 2
Line3 := TPointList.Create;
PointLists.Add(Line3);
Line3.Capacity := Line1.Count + Line2.Count;
for PointIndex := Line1.Count - 1 downto 0 do
begin
Line3.Add(Line1.Points[PointIndex]);
end;
for PointIndex := 0 to Line2.Count - 1 do
begin
Line3.Add(Line2.Points[PointIndex]);
end;
QuadTree.RemovePoint(X1, Y1, Line1);
QuadTree.RemovePoint(X2, Y2, Line2);
APoint := Line1.Points[Line1.Count - 1];
QuadTree.RemovePoint(APoint.x, APoint.y, Line1);
QuadTree.AddPoint(APoint.x, APoint.y, Line3);
APoint := Line2.Points[Line2.Count - 1];
QuadTree.RemovePoint(APoint.x, APoint.y, Line2);
QuadTree.AddPoint(APoint.x, APoint.y, Line3);
PointLists.Remove(Line1);
PointLists.Remove(Line2);
end;
end;
end;
end;
end;
procedure GlobalInitializeQuadTree(var QuadTree: TRbwQuadTree;
ModelGrid: TCustomModelGrid);
var
CornerPoint: TPoint2d;
XMin, XMax, YMin, YMax: double;
begin
if QuadTree = nil then
begin
QuadTree := TRbwQuadTree.Create(nil);
CornerPoint := ModelGrid.TwoDElementCorner(0,0);
XMin := CornerPoint.x;
XMax := XMin;
YMin := CornerPoint.y;
YMax := YMin;
CornerPoint := ModelGrid.TwoDElementCorner(ModelGrid.ColumnCount,0);
XMin := Min(XMin, CornerPoint.x);
XMax := Max(XMax, CornerPoint.x);
YMin := Min(YMin, CornerPoint.y);
YMax := Max(YMax, CornerPoint.y);
CornerPoint := ModelGrid.TwoDElementCorner(ModelGrid.ColumnCount,ModelGrid.RowCount);
XMin := Min(XMin, CornerPoint.x);
XMax := Max(XMax, CornerPoint.x);
YMin := Min(YMin, CornerPoint.y);
YMax := Max(YMax, CornerPoint.y);
CornerPoint := ModelGrid.TwoDElementCorner(0,ModelGrid.RowCount);
XMin := Min(XMin, CornerPoint.x);
XMax := Max(XMax, CornerPoint.x);
YMin := Min(YMin, CornerPoint.y);
YMax := Max(YMax, CornerPoint.y);
QuadTree.XMin := XMin;
QuadTree.XMax := XMax;
QuadTree.YMin := YMin;
QuadTree.YMax := YMax;
end
else
begin
QuadTree.Clear;
end;
end;
{ TPointList }
function TPointList.Add(Point: TPoint2D): integer;
begin
if FCount = Capacity then
begin
Grow;
end;
FPoints[FCount] := Point;
result := FCount;
Inc(FCount);
end;
function TPointList.GetCapacity: integer;
begin
result := Length(FPoints);
end;
function TPointList.GetPoint(Index: integer): TPoint2D;
begin
result := FPoints[Index];
end;
procedure TPointList.Grow;
var
Delta: Integer;
LocalCapacity: integer;
begin
LocalCapacity := Capacity;
if LocalCapacity < 16 then
begin
Delta := 4;
end
else
begin
Delta := LocalCapacity div 4;
end;
Capacity := LocalCapacity + Delta;
end;
procedure TPointList.Insert(Position: integer; Point: TPoint2D);
var
Index: Integer;
begin
if Count = Capacity then
begin
Grow;
end;
if Position = Count then
begin
Add(Point);
end
else
begin
for Index := FCount - 1 downto Position do
begin
FPoints[Index+1] := FPoints[Index];
end;
FPoints[Position] := Point;
Inc(FCount);
end;
end;
procedure TPointList.SetCapacity(const Value: integer);
begin
SetLength(FPoints, Value);
end;
procedure TPointList.SetPoint(Index: integer; const Value: TPoint2D);
begin
FPoints[Index] := Value;
end;
{ TContourExtractor }
constructor TContourExtractor.Create(Model: TBaseModel);
var
LocalModel: TPhastModel;
begin
LocalModel := (Model as TPhastModel);
FModelGrid := LocalModel.Grid;
Mesh := LocalModel.Mesh;
end;
procedure TContourExtractor.CreateShapes(ValueList: TValueArrayStorage;
DataArray: TDataArray; FileName: string; LabelSpacing: integer);
var
ContourCreator: TContourCreator;
ValueIndex: Integer;
PointListIndex: Integer;
PointList: TPointList;
PointIndex: Integer;
PointsForShape: TList;
ShapeFileWriter: TShapefileGeometryWriter;
Shape: TShapeObject;
PPoint: TPoint2DPtr;
Fields: TStringList;
FieldName: AnsiString;
ShapeDataBase: TXBase;
FieldDescription: AnsiString;
MinValue, MaxValue: double;
DSValues: TStringList;
FieldFormat: AnsiString;
Contours: TContours;
C: TRealArray;
APlot: TLineList;
ContVals: TRealList;
AContourLine: TLine;
// ContourIndex: Integer;
Location: TLocation;
FieldNames: TStringList;
procedure MakeShapesFromContourLines;
var
ContourIndex: integer;
PointIndex: integer;
begin
if PlotList.Count = 0 then
begin
Exit;
end;
Assert(PlotList.Count = 1);
APlot := PlotList[0];
APlot.MergeLines;
ShapeFileWriter.Capacity := APlot.Count;
for ContourIndex := 0 to APlot.Count - 1 do
begin
AContourLine := APlot[ContourIndex];
if AContourLine.Count = 0 then
begin
Continue;
end;
ValueIndex := ContVals.IndexOfClosest(
AContourLine.ContourLevel);
Shape := TShapeObject.Create;
try
Shape.FNumPoints := AContourLine.Count;
Shape.FShapeType := stPolyLine;
SetLength(Shape.FPoints, AContourLine.Count);
Shape.FNumParts := 1;
SetLength(Shape.FParts, 1);
Shape.FParts[0] := 0;
SetLength(Shape.FPartTypes, 0);
for PointIndex := 0 to AContourLine.Count - 1 do
begin
Location := AContourLine[PointIndex];
Shape.FPoints[PointIndex].X := Location.x;
Shape.FPoints[PointIndex].Y := Location.y;
end;
ShapeFileWriter.AddShape(Shape);
ShapeDataBase.AppendBlank;
case DataArray.DataType of
rdtDouble:
ShapeDataBase.UpdFieldNum(FieldName,
ValueList.RealValues[ValueIndex]);
rdtInteger:
ShapeDataBase.UpdFieldInt(FieldName,
ValueList.IntValues[ValueIndex]);
rdtBoolean:
if ValueList.BooleanValues[ValueIndex] then
begin
ShapeDataBase.UpdFieldInt(FieldName, 1);
end
else
begin
ShapeDataBase.UpdFieldInt(FieldName, 0);
end;
rdtString:
ShapeDataBase.UpdFieldStr(FieldName,
AnsiString(ValueList.StringValues[ValueIndex]));
else
Assert(False);
end;
ShapeDataBase.PostChanges;
except
Shape.Free;
raise;
end
end
end;
begin
DataSet := DataArray;
FAlgorithm := DataSet.ContourAlg;
// {$IFDEF SUTRA}
// if (DataSet.Model as TCustomModel).ModelSelection = msSutra22 then
// begin
// FAlgorithm := caACM626
// end;
// {$ENDIF}
if Assigned(FModelGrid) then
begin
Grid := FModelGrid.ContourGrid(DataArray.EvaluatedAt,
frmGoPhast.PhastModel.ModelSelection, vdTop, FModelGrid.SelectedLayer);
end
else
begin
Assert(Assigned(Mesh));
end;
// case FAlgorithm of
// caSimple:
// begin
// if Assigned(Grid) then
// begin
// ActiveDataSet := frmGoPhast.PhastModel.DataArrayManager.
// GetDataSetByName(rsActive);
// Assert(Assigned(ActiveDataSet));
// end
// else
// begin
// Assert(Assigned(Mesh));
// end;
// end;
// caACM626:
// begin
if Assigned(Grid) then
begin
ActiveDataSet := frmGoPhast.PhastModel.DataArrayManager.
GetDataSetByName(rsActive);
Assert(Assigned(ActiveDataSet));
end
else
begin
Assert(Assigned(Mesh));
end;
// end
// else Assert(False);
// end;
ViewDirection := vdTop;
// Assert(Grid <> nil);
Assert(ValueList.Count > 0);
Contours := DataSet.Contours;
DSValues := TStringList.Create;
try
case FAlgorithm of
caSimple:
begin
if Assigned(Grid) then
begin
AssignGridValues(MinValue, MaxValue, FModelGrid.SelectedLayer,
DSValues, vdTop);
end
else
begin
AssignTriangulationValuesFromMesh(MinValue, MaxValue,
(Mesh as TSutraMesh3D).SelectedLayer, DSValues, vdTop);
end;
end;
caACM626:
begin
if Assigned(Grid) then
begin
AssignTriangulationValuesFromGrid(MinValue, MaxValue,
FModelGrid.SelectedLayer, DSValues, vdTop);
end
else
begin
AssignTriangulationValuesFromMesh(MinValue, MaxValue,
(Mesh as TSutraMesh3D).SelectedLayer, DSValues, vdTop);
end;
end;
else Assert(False);
end;
ShapeDataBase := TXBase.Create(nil);
try
Fields := TStringList.Create;
FieldNames := TStringList.Create;
try
FieldName := AnsiString(UpperCase(Copy(DataArray.Name, 1, 10)));
FieldName := FixShapeFileFieldName(FieldName, FieldNames);
FieldNames.Add(string(FieldName));
case DataArray.DataType of
rdtDouble:
FieldFormat := 'N18,10';
rdtInteger:
FieldFormat := 'N';
rdtBoolean:
FieldFormat := 'N';
rdtString:
FieldFormat := 'C18';
else
Assert(False);
end;
FieldDescription := FieldName + '=' + FieldFormat;
Fields.Add(string(FieldDescription));
InitializeDataBase(FileName, ShapeDataBase, Fields);
finally
Fields.Free;
FieldNames.Free;
end;
ShapeFileWriter := TShapefileGeometryWriter.Create(stPolyLine, True);
try
case FAlgorithm of
caSimple:
begin
if Assigned(Grid) then
begin
FPointLists:= TObjectList.Create;
ContourCreator:= TContourCreator.Create(LabelSpacing);
try
InitializeEpsilon;
ContourCreator.EvaluatedAt := DataArray.EvaluatedAt;
ContourCreator.Grid := Grid;
ContourCreator.OnExtractSegments := ImportSegments;
Assert(ValueList.Count = Length(Contours.ContourValues));
for ValueIndex := 0 to ValueList.Count - 1 do
begin
ContourCreator.Value := Contours.ContourValues[ValueIndex];
InitializeQuadTree;
FPointLists.Clear;
ContourCreator.ExtractContour;
if (FPointLists.Count> 0) then
begin
ShapeFileWriter.Capacity := ShapeFileWriter.Capacity
+ FPointLists.Count;
for PointListIndex := 0 to FPointLists.Count - 1 do
begin
PointsForShape := TList.Create;
try
PointList := FPointLists[PointListIndex];
for PointIndex := 0 to PointList.Count - 1 do
begin
if (PointIndex > 0) and (PointIndex < PointList.Count - 1) then
begin
if not Collinear(PointList.Points[PointIndex-1],
PointList.Points[PointIndex],
PointList.Points[PointIndex+1]) then
begin
PointsForShape.Add(@PointList.FPoints[PointIndex])
end;
end
else
begin
PointsForShape.Add(@PointList.FPoints[PointIndex])
end;
end;
if PointsForShape.Count > 0 then
begin
Shape := TShapeObject.Create;
try
Shape.FNumPoints := PointsForShape.Count;
Shape.FShapeType := stPolyLine;
SetLength(Shape.FPoints, PointsForShape.Count);
Shape.FNumParts := 1;
SetLength(Shape.FParts, 1);
Shape.FParts[0] := 0;
SetLength(Shape.FPartTypes, 0);
for PointIndex := 0 to PointsForShape.Count - 1 do
begin
PPoint := PointsForShape[PointIndex];
Shape.FPoints[PointIndex].X := PPoint.x;
Shape.FPoints[PointIndex].Y := PPoint.y;
end;
ShapeFileWriter.AddShape(Shape);
ShapeDataBase.AppendBlank;
case DataArray.DataType of
rdtDouble:
ShapeDataBase.UpdFieldNum(FieldName, ValueList.RealValues[ValueIndex]);
rdtInteger:
ShapeDataBase.UpdFieldInt(FieldName, ValueList.IntValues[ValueIndex]);
rdtBoolean:
if ValueList.BooleanValues[ValueIndex] then
begin
ShapeDataBase.UpdFieldInt(FieldName, 1);
end
else
begin
ShapeDataBase.UpdFieldInt(FieldName, 0);
end;
rdtString:
ShapeDataBase.UpdFieldStr(FieldName, AnsiString(ValueList.StringValues[ValueIndex]));
else
Assert(False);
end;
ShapeDataBase.PostChanges;
except
Shape.Free;
raise;
end;
end;
finally
PointsForShape.Free;
end;
end;
end;
end;
// ShapeFileWriter.WriteToFile(FileName, ChangeFileExt(FileName, '.shx'));
finally
ContourCreator.Free;
FPointLists.Free;
end;
end
else
begin
ContVals := TRealList.Create;
try
ContVals.Capacity := ValueList.Count;
for ValueIndex := 0 to ValueList.Count - 1 do
begin
ContVals.Add(Contours.ContourValues[ValueIndex]);
end;
CreateSimpleContoursFromMesh(Contours.ContourValues);
MakeShapesFromContourLines;
finally
ContVals.Free;
end;
end;
end;
caACM626:
begin
ContVals := TRealList.Create;
try
ContVals.Capacity := ValueList.Count;
SetLength(C, ValueList.Count);
for ValueIndex := 0 to ValueList.Count - 1 do
begin
C[ValueIndex] := Contours.ContourValues[ValueIndex];
ContVals.Add(Contours.ContourValues[ValueIndex]);
end;
PerformAlg626(C);
MakeShapesFromContourLines;
finally
ContVals.Free;
end;
end
else Assert(False);
end;
ShapeFileWriter.WriteToFile(FileName, ChangeFileExt(FileName, '.shx'));
finally
ShapeFileWriter.Free;
end;
finally
ShapeDataBase.Active := False;
ShapeDataBase.Free;
end;
finally
DSValues.Free;
end;
end;
destructor TContourExtractor.Destroy;
begin
FQuadTree.Free;
inherited;
end;
procedure TContourExtractor.ImportSegments(Sender: TObject;
const Segments: TLine2DArray);
begin
GlobalImportSegments(Sender, Segments, FEpsilon, FQuadTree, FPointLists);
end;
procedure TContourExtractor.InitializeEpsilon;
begin
GlobalInitializeEpsilon(FEpsilon, FModelGrid);
end;
procedure TContourExtractor.InitializeQuadTree;
begin
GlobalInitializeQuadTree(FQuadTree, FModelGrid);
end;
procedure GlobalInitializeEpsilon(var Epsilon: Real; ModelGrid: TCustomModelGrid);
var
Index: Integer;
begin
Epsilon := ModelGrid.ColumnWidth[0];
for Index := 1 to ModelGrid.ColumnCount - 1 do
begin
Epsilon := Min(Epsilon, ModelGrid.ColumnWidth[Index]);
end;
for Index := 0 to ModelGrid.RowCount - 1 do
begin
Epsilon := Min(Epsilon, ModelGrid.RowWidth[Index]);
end;
Epsilon := Sqr(Epsilon / 4);
end;
end.
|
unit OTFEFreeOTFE_LUKSAPI;
// Description:
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
windows, // Required for DWORD
SDUEndianIntegers,
DriverAPI;
const
// The LUKS version we support.
LUKS_VER_SUPPORTED = 1;
// Size (in bytes) of a LUKS header, as defined by the LUKS specification
LUKS_HEADER_BYTES = 592;
LUKS_MAGIC : Ansistring = 'LUKS'+Ansichar($BA)+Ansichar($BE);
LUKS_DIGESTSIZE = 20;
LUKS_SALTSIZE = 32;
LUKS_NUMKEYS = 8;
LUKS_MKD_ITER = 10;
LUKS_KEY_DISABLED = $0000DEAD;
LUKS_KEY_ENABLED = $00AC71F3;
LUKS_STRIPES = 4000;
LUKS_MAGIC_L = 6;
LUKS_CIPHERNAME_L = 32;
LUKS_CIPHERMODE_L = 32;
LUKS_HASHSPEC_L = 32;
UUID_STRING_L = 40;
LUKS_SECTOR_SIZE = 512; // In *bytes*
type
// Delphi-facing struct; cleaned up version of the "raw" version
TLUKSKeySlot = record
active: boolean;
iterations: DWORD;
salt: array [0..(LUKS_SALTSIZE-1)] of byte;
key_material_offset: DWORD;
stripes: DWORD;
end;
// Raw structure, as it appears within volume files
TLUKSKeySlotRaw = record
active : TSDUBigEndian32;
iterations : TSDUBigEndian32;
salt : array [0..(LUKS_SALTSIZE-1)] of byte;
key_material_offset: TSDUBigEndian32;
stripes : TSDUBigEndian32;
end;
// Delphi-facing struct; cleaned up version of the "raw" version
TLUKSHeader = record
magic: string;
version: WORD;
cipher_name: string;
cipher_mode: string;
hash_spec: string;
payload_offset: DWORD;
key_bytes: DWORD; // In *bytes*
mk_digest: array [0..(LUKS_DIGESTSIZE-1)] of byte;
mk_digest_salt: array [0..(LUKS_SALTSIZE-1)] of byte;
mk_digest_iter: DWORD;
uuid: TGUID;
keySlot: array [0..(LUKS_NUMKEYS-1)] of TLUKSKeySlot; // Note: Indexes from 1
cypherKernelModeDeviceName: string;
cypherGUID: TGUID;
hashKernelModeDeviceName: string;
hashGUID: TGUID;
sectorIVGenMethod: TFreeOTFESectorIVGenMethod;
IVHashKernelModeDeviceName: string;
IVHashGUID: TGUID;
IVCypherKernelModeDeviceName: string;
IVCypherGUID: TGUID;
end;
// Raw structure, as it appears within volume files
TLUKSHeaderRaw = record
magic : array [0..(LUKS_MAGIC_L-1)] of byte;
version : array [0..1] of byte; // Stored as big endian
cipher_name : array [0..(LUKS_CIPHERNAME_L-1)] of Ansichar;
cipher_mode : array [0..(LUKS_CIPHERMODE_L-1)] of Ansichar;
hash_spec : array [0..(LUKS_HASHSPEC_L-1)] of Ansichar;
payload_offset: TSDUBigEndian32;
key_bytes : TSDUBigEndian32;
mk_digest : array [0..(LUKS_DIGESTSIZE-1)] of byte;
mk_digest_salt: array [0..(LUKS_SALTSIZE-1)] of byte;
mk_digest_iter: TSDUBigEndian32;
uuid : array [0..(UUID_STRING_L-1)] of Ansichar;
keySlot : array [0..(LUKS_NUMKEYS-1)] of TLUKSKeySlotRaw; // Note: Indexes from 0
end;
implementation
END.
|
unit ThComponent;
interface
uses
SysUtils, Classes;
type
TThComponent = class(TComponent)
protected
procedure ChangeComponentProp(var ioComponent; const inValue: TComponent);
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
procedure UnassignComponent(AComponent: TComponent); virtual;
public
procedure LoadFromFile(const inFilename: string);
procedure LoadFromStream(inStream: TStream);
procedure LoadFromText(inOptsText: string);
procedure SaveToFile(const inFilename: string);
procedure SaveToStream(inStream: TStream);
function SaveToText: string;
end;
implementation
{ TThComponent }
procedure TThComponent.ChangeComponentProp(var ioComponent;
const inValue: TComponent);
begin
if TComponent(ioComponent) <> nil then
TComponent(ioComponent).RemoveFreeNotification(Self);
TComponent(ioComponent) := inValue;
if TComponent(ioComponent) <> nil then
TComponent(ioComponent).FreeNotification(Self);
end;
{
procedure TThComponent.ChangeComponentProp(var ioComponent: TComponent;
const inValue: TComponent);
begin
if ioComponent <> nil then
ioComponent.RemoveFreeNotification(Self);
ioComponent := inValue;
if ioComponent <> nil then
ioComponent.FreeNotification(Self);
end;
}
procedure TThComponent.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation = opRemove) then
UnassignComponent(AComponent);
end;
procedure TThComponent.UnassignComponent(AComponent: TComponent);
begin
//
end;
procedure TThComponent.SaveToStream(inStream: TStream);
var
ms: TMemoryStream;
begin
ms := TMemoryStream.Create;
try
ms.WriteComponent(Self);
ms.Position := 0;
ObjectBinaryToText(ms, inStream);
finally
ms.Free;
end;
end;
function TThComponent.SaveToText: string;
var
ss: TStringStream;
begin
ss := TStringStream.Create('');
try
SaveToStream(ss);
Result := ss.DataString;
finally
ss.Free;
end;
end;
procedure TThComponent.SaveToFile(const inFilename: string);
var
fs: TFileStream;
begin
fs := TFileStream.Create(inFilename, fmCreate);
try
SaveToStream(fs);
finally
fs.Free;
end;
end;
procedure TThComponent.LoadFromStream(inStream: TStream);
var
ms: TMemoryStream;
begin
ms := TMemoryStream.Create;
try
ObjectTextToBinary(inStream, ms);
ms.Position := 0;
ms.ReadComponent(Self);
finally
ms.Free;
end;
end;
procedure TThComponent.LoadFromText(inOptsText: string);
var
ss: TStringStream;
begin
ss := TStringStream.Create(inOptsText);
try
LoadFromStream(ss);
finally
ss.Free;
end;
end;
procedure TThComponent.LoadFromFile(const inFilename: string);
var
fs: TFileStream;
begin
if FileExists(inFilename) then
begin
fs := TFileStream.Create(inFilename, fmOpenRead);
try
LoadFromStream(fs);
finally
fs.Free;
end;
end;
end;
end.
|
unit DSA.Sorts.IndexHeapSort;
interface
uses
System.SysUtils,
DSA.Interfaces.Comparer,
DSA.Utils,
DSA.Tree.IndexHeap;
type
TIndexHeapSort<T> = class
private type
TArr_T = TArray<T>;
ICmp_T = IComparer<T>;
TIndexHeap_T = TIndexHeap<T>;
public
class procedure Sort(var arr: TArr_T; cmp: ICmp_T);
end;
procedure Main;
implementation
uses
DSA.Sorts.HeapSort,
DSA.Sorts.QuickSort,
DSA.Sorts.MergeSort;
type
TIndexHeapSort_int = TIndexHeapSort<integer>;
THeapSort_int = THeapSort<integer>;
TMergeSort_int = TMergeSort<integer>;
TQuickSort_int = TQuickSort<integer>;
procedure Main;
var
sourceArr, targetArr: TArray_int;
n, swapTimes: integer;
begin
n := 1000000;
WriteLn('Test for random array, size = ', n, ', random range [0, ', n, ']');
with TSortTestHelper_int.Create do
begin
sourceArr := GenerateRandomArray(n, n);
targetArr := CopyArray(sourceArr);
TestSort('MergeSort'#9#9, targetArr, TMergeSort_int.Sort);
targetArr := CopyArray(sourceArr);
TestSort('QuickSort3Ways'#9#9, targetArr, TQuickSort_int.Sort3Ways);
targetArr := CopyArray(sourceArr);
TestSort('HeapSort'#9#9, targetArr, THeapSort_int.Sort);
targetArr := CopyArray(sourceArr);
TestSort('HeapSort_Adv'#9#9, targetArr, THeapSort_int.Sort_Adv);
targetArr := CopyArray(sourceArr);
TestSort('IndexHeapSort'#9#9, targetArr, TIndexHeapSort_int.Sort);
Free;
end;
swapTimes := 100;
WriteLn('Test for nearly ordered array, size = ', n, ', swap time = ',
swapTimes);
with TSortTestHelper_int.Create do
begin
sourceArr := GenerateNearlyOrderedArray(n, swapTimes);
targetArr := CopyArray(sourceArr);
TestSort('MergeSort'#9#9, targetArr, TMergeSort_int.Sort);
targetArr := CopyArray(sourceArr);
TestSort('QuickSort3Ways'#9#9, targetArr, TQuickSort_int.Sort3Ways);
targetArr := CopyArray(sourceArr);
TestSort('HeapSort'#9#9, targetArr, THeapSort_int.Sort);
targetArr := CopyArray(sourceArr);
TestSort('HeapSort_Adv'#9#9, targetArr, THeapSort_int.Sort_Adv);
targetArr := CopyArray(sourceArr);
TestSort('IndexHeapSort'#9#9, targetArr, TIndexHeapSort_int.Sort);
Free;
end;
WriteLn('Test for random array, size = ', n, ', random range [0, ', 10, ']');
with TSortTestHelper_int.Create do
begin
sourceArr := GenerateRandomArray(n, 10);
targetArr := CopyArray(sourceArr);
TestSort('MergeSort'#9#9, targetArr, TMergeSort_int.Sort);
targetArr := CopyArray(sourceArr);
TestSort('QuickSort3Ways'#9#9, targetArr, TQuickSort_int.Sort3Ways);
targetArr := CopyArray(sourceArr);
TestSort('HeapSort'#9#9, targetArr, THeapSort_int.Sort);
targetArr := CopyArray(sourceArr);
TestSort('HeapSort_Adv'#9#9, targetArr, THeapSort_int.Sort_Adv);
targetArr := CopyArray(sourceArr);
TestSort('IndexHeapSort'#9#9, targetArr, TIndexHeapSort_int.Sort);
Free;
end;
end;
{ TIndexHeapSort<T> }
class procedure TIndexHeapSort<T>.Sort(var arr: TArr_T; cmp: ICmp_T);
var
IH_Max: TIndexHeap_T;
i: integer;
begin
IH_Max := TIndexHeap_T.Create(arr, cmp, THeapkind.Min);
for i := 0 to Length(arr) - 1 do
arr[i] := IH_Max.ExtractFirst;
FreeAndNil(IH_Max);
end;
end.
|
unit ufrmSignUp;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ExtDlgs,
Vcl.Imaging.jpeg, Vcl.Imaging.pngimage, uJSONUser;
type
TfrmSignUp = class(TForm)
pnlImgLogin: TGridPanel;
pnlImage: TPanel;
pnlBody: TGridPanel;
pnlUser: TPanel;
lblUser: TLabel;
pnlEnter: TPanel;
pnlSignUp: TPanel;
pnlEdtUserBorder: TPanel;
pnlEdtUser: TPanel;
edtUser: TEdit;
imgUser: TImage;
pnlPassword: TPanel;
lblPassword: TLabel;
pnlEdtPasswordBorder: TPanel;
pnlEdtPassword: TPanel;
imgPassword: TImage;
edtPassword: TEdit;
imgEdit: TImage;
dlgImage: TOpenDialog;
pnlCircle: TPanel;
imgLogin: TImage;
procedure edtUserEnter(Sender: TObject);
procedure edtUserExit(Sender: TObject);
procedure edtPasswordEnter(Sender: TObject);
procedure edtPasswordExit(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure pnlSignUpMouseEnter(Sender: TObject);
procedure pnlSignUpMouseLeave(Sender: TObject);
procedure imgLoginMouseEnter(Sender: TObject);
procedure imgLoginMouseLeave(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure imgLoginClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure pnlSignUpClick(Sender: TObject);
procedure edtUserChange(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
FTop, FLeft, FHeight, FWidth: Integer;
BMP: TBitmap;
JPG: TJPEGImage;
PNG: TPngImage;
FUser: TUsersClass;
Path: TFileName;
FMaxLength: Integer;
function Save(const User: TUsersClass): Boolean;
public
{ Public declarations }
property MaxLength: Integer read FMaxLength write FMaxLength;
end;
var
frmSignUp: TfrmSignUp;
implementation
{$R *.dfm}
procedure TfrmSignUp.edtPasswordEnter(Sender: TObject);
begin
pnlEdtPasswordBorder.Color := clHighlight;
if (edtPassword.Text = 'Password') then
edtPassword.Clear;
end;
procedure TfrmSignUp.edtPasswordExit(Sender: TObject);
begin
pnlEdtPasswordBorder.Color := clBtnFace;
if (edtPassword.Text = EmptyStr) then
edtPassword.Text := 'Password';
end;
procedure TfrmSignUp.edtUserChange(Sender: TObject);
begin
if (lblUser.Caption = 'Username exists') then
begin
if not FileExists(Path + '\' + edtUser.Text) then
begin
lblUser.Caption := 'User name or Email Adress';
lblUser.Font.Color := clGray;
end;
end;
end;
procedure TfrmSignUp.edtUserEnter(Sender: TObject);
begin
pnlEdtUserBorder.Color := clHighlight;
if (edtUser.Text = 'Username') then
edtUser.Clear;
end;
procedure TfrmSignUp.edtUserExit(Sender: TObject);
begin
pnlEdtUserBorder.Color := clBtnFace;
if (edtUser.Text = EmptyStr) then
edtUser.Text := 'Username';
end;
procedure TfrmSignUp.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if Assigned(BMP) then
FreeAndNil(BMP);
if Assigned(PNG) then
FreeAndNil(PNG);
if Assigned(JPG) then
FreeAndNil(JPG);
end;
procedure TfrmSignUp.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if (Key = VK_ESCAPE) then
Self.Close;
end;
procedure TfrmSignUp.FormKeyPress(Sender: TObject; var Key: Char);
begin
if (Key = #13) then
Perform(WM_NEXTDLGCTL,0,0);
end;
procedure TfrmSignUp.FormShow(Sender: TObject);
var
BX: TRect;
mdo: HRGN;
begin
edtUser.MaxLength := FMaxLength;
Path := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'users';
FTop := imgEdit.Top;
FLeft := imgEdit.Left;
FHeight := imgEdit.Height;
FWidth := imgEdit.Width;
with pnlCircle do
begin
BX := ClientRect;
mdo := CreateRoundRectRgn(BX.Left, BX.Top, BX.Right,
BX.Bottom, 75, 75);
Perform(EM_GETRECT, 0, lParam(@BX));
InflateRect(BX, 10, 10);
Perform(EM_SETRECTNP, 0, lParam(@BX));
SetWindowRgn(Handle, mdo, True);
Invalidate;
end;
end;
procedure TfrmSignUp.imgLoginClick(Sender: TObject);
begin
if dlgImage.Execute() then
begin
if (ExtractFileExt(dlgImage.FileName) = '.bmp') then
begin
if Assigned(BMP) then
FreeAndNil(BMP);
BMP := TBitmap.Create;
BMP.LoadFromFile(dlgImage.FileName);
imgLogin.Picture.Graphic := BMP;
end
else if (ExtractFileExt(dlgImage.FileName) = '.png') then
begin
if Assigned(PNG) then
FreeAndNil(PNG);
PNG := TPngImage.Create;
PNG.LoadFromFile(dlgImage.FileName);
imgLogin.Picture.Graphic := PNG;
end
else if (ExtractFileExt(dlgImage.FileName) = '.jpeg') or
((ExtractFileExt(dlgImage.FileName) = '.jpg')) then
begin
if Assigned(JPG) then
FreeAndNil(JPG);
JPG := TJPEGImage.Create;
JPG.LoadFromFile(dlgImage.FileName);
imgLogin.Picture.Graphic := JPG;
end;
end;
end;
procedure TfrmSignUp.imgLoginMouseEnter(Sender: TObject);
begin
imgEdit.Left := FLeft - 2;
imgEdit.Top := FTop - 2;
imgEdit.Height := FHeight + 4;
imgEdit.Width := FWidth + 4;
end;
procedure TfrmSignUp.imgLoginMouseLeave(Sender: TObject);
begin
imgEdit.Left := FLeft;
imgEdit.Top := FTop;
imgEdit.Height := FHeight;
imgEdit.Width := FWidth;
end;
function TfrmSignUp.Save(const User: TUsersClass): Boolean;
var
Attributes: Integer;
lFile: TStringList;
begin
if not FileExists(Path + '\' + User.user.name) then
begin
try
Attributes := faArchive + faHidden + faReadOnly;
lFile := TStringList.Create;
try
lFile.Add(User.ToJsonString);
lFile.SaveToFile(Path + '\' + User.user.name);
FileSetAttr(Path + '\' + User.user.name, Attributes);
finally
FreeAndNil(lFile);
end;
Result := True;
except
Result := False;
end;
end
else
begin
lblUser.Caption := 'Username exists';
lblUser.Font.Color := clRed;
Result := False;
end;
end;
procedure TfrmSignUp.pnlSignUpClick(Sender: TObject);
var
lExit: Boolean;
begin
lExit := False;
if (edtUser.Text = EmptyStr) or (edtUser.Text = 'Username') then
begin
lblUser.Caption := 'Enter username';
lblUser.Font.Color := clRed;
lExit := True;
end
else
begin
lblUser.Caption := 'User name or Email Adress';
lblUser.Font.Color := clGray;
end;
if (edtPassword.Text = EmptyStr) or (edtPassword.Text = 'Password') then
begin
lblPassword.Caption := 'Enter password';
lblPassword.Font.Color := clRed;
lExit := True;
end
else
begin
lblPassword.Caption := 'Password';
lblPassword.Font.Color := clGray;
end;
if not(lExit) then
begin
FUser := TUsersClass.Create;
try
FUser.user.name := edtUser.Text;
FUser.user.password := edtPassword.Text;
FUser.user.path := dlgImage.FileName;
if Save(FUser) then
Self.Close;
finally
FreeAndNil(FUser);
end;
end;
end;
procedure TfrmSignUp.pnlSignUpMouseEnter(Sender: TObject);
begin
pnlSignUp.Cursor := crHandPoint;
pnlSignUp.Margins.Left := 8;
pnlSignUp.Margins.Top := 8;
pnlSignUp.Margins.Right := 8;
pnlSignUp.Margins.Bottom := 8;
end;
procedure TfrmSignUp.pnlSignUpMouseLeave(Sender: TObject);
begin
pnlSignUp.Cursor := crDefault;
pnlSignUp.Margins.Left := 10;
pnlSignUp.Margins.Top := 10;
pnlSignUp.Margins.Right := 10;
pnlSignUp.Margins.Bottom := 10;
end;
end.
|
unit MulOpFhtTest;
interface
uses
DUnitX.TestFramework,
Math,
uEnums,
TestHelper,
uIntXLibTypes,
uIntX;
type
[TestFixture]
TMulOpFhtTest = class(TObject)
private
F_length: Integer;
const
StartLength = Integer(256);
LengthIncrement = Integer(101);
RepeatCount = Integer(10);
RandomStartLength = Integer(256);
RandomEndLength = Integer(1000);
RandomRepeatCount = Integer(50);
function GetAllOneDigits(mlength: Integer): TIntXLibUInt32Array;
function GetRandomDigits(mlength: Integer): TIntXLibUInt32Array; overload;
function GetRandomDigits(): TIntXLibUInt32Array; overload;
public
[Setup]
procedure Setup;
[Test]
procedure CompareWithClassic();
[Test]
procedure SmallLargeCompareWithClassic();
[Test]
procedure CompareWithClassicRandom();
end;
implementation
procedure TMulOpFhtTest.Setup;
begin
F_length := StartLength;
Randomize;
end;
function TMulOpFhtTest.GetAllOneDigits(mlength: Integer): TIntXLibUInt32Array;
var
i: Integer;
begin
SetLength(result, mlength);
for i := 0 to Pred(Length(result)) do
begin
result[i] := $7F7F7F7F;
end;
end;
function TMulOpFhtTest.GetRandomDigits(mlength: Integer): TIntXLibUInt32Array;
var
i: Integer;
begin
SetLength(result, mlength);
for i := 0 to Pred(Length(result)) do
begin
result[i] := UInt32(Random(RandomEndLength) + 1) * UInt32(2);
end;
end;
function TMulOpFhtTest.GetRandomDigits(): TIntXLibUInt32Array;
begin
result := GetRandomDigits(RandomRange(RandomStartLength, RandomEndLength));
end;
[Test]
procedure TMulOpFhtTest.CompareWithClassic();
var
x, classic, fht: TIntX;
begin
TTestHelper.Repeater(RepeatCount,
procedure
begin
x := TIntX.Create(GetAllOneDigits(F_length), True);
classic := TIntX.Multiply(x, x, TMultiplyMode.mmClassic);
fht := TIntX.Multiply(x, x, TMultiplyMode.mmAutoFht);
Assert.IsTrue(classic = fht);
F_length := F_length + LengthIncrement;
end);
end;
[Test]
procedure TMulOpFhtTest.SmallLargeCompareWithClassic();
var
x, y, classic, fht: TIntX;
begin
x := TIntX.Create(GetAllOneDigits(50000), False);
y := TIntX.Create(GetAllOneDigits(512), False);
classic := TIntX.Multiply(x, y, TMultiplyMode.mmClassic);
fht := TIntX.Multiply(x, y, TMultiplyMode.mmAutoFht);
Assert.IsTrue(classic = fht);
end;
[Test]
procedure TMulOpFhtTest.CompareWithClassicRandom();
var
x, classic, fht: TIntX;
begin
TTestHelper.Repeater(RandomRepeatCount,
procedure
begin
x := TIntX.Create(GetRandomDigits(), False);
classic := TIntX.Multiply(x, x, TMultiplyMode.mmClassic);
fht := TIntX.Multiply(x, x, TMultiplyMode.mmAutoFht);
Assert.IsTrue(classic = fht);
end);
end;
initialization
TDUnitX.RegisterTestFixture(TMulOpFhtTest);
end.
|
unit URepositorioUnidadeMedida;
interface
uses
UEntidade
, URepositorioDB
, UUnidadeMedida
, SqlExpr
;
type
TRepositorioUnidadeMedida = class(TRepositorioDB<TUNIDADEMEDIDA >)
public
constructor Create;
procedure AtribuiDBParaEntidade(const coUnidadeMedida : TUNIDADEMEDIDA ); override;
procedure AtribuiEntidadeParaDB(const coUnidadeMedida : TUNIDADEMEDIDA ;
const coSQLQuery: TSQLQuery); override;
end;
implementation
uses
UDM
, SysUtils
;
{ TRepositorioUnidadeMedida }
procedure TRepositorioUnidadeMedida.AtribuiDBParaEntidade(
const coUnidadeMedida: TUNIDADEMEDIDA);
begin
inherited;
with FSQLSelect do
begin
coUnidadeMedida.DESCRICAO := FieldByName(FLD_UNIDADEMEDIDA_DESCRICAO).AsString;
coUnidadeMedida.SIGLA := FieldByName(FLD_UNIDADEMEDIDA_SIGLA).AsString;
end;
end;
procedure TRepositorioUnidadeMedida.AtribuiEntidadeParaDB(
const coUnidadeMedida: TUNIDADEMEDIDA; const coSQLQuery: TSQLQuery);
begin
inherited;
with coSQLQuery do
begin
ParamByName(FLD_UNIDADEMEDIDA_DESCRICAO).AsString := coUnidadeMedida.DESCRICAO;
ParamByName(FLD_UNIDADEMEDIDA_SIGLA).AsString := coUnidadeMedida.SIGLA;
end;
end;
constructor TRepositorioUnidadeMedida.Create;
begin
inherited Create(TUNIDADEMEDIDA, TBL_UNIADEMEDIDA, FLD_ENTIDADE_ID, STR_UNIDADEMEDIDA);
end;
end.
|
unit TpLabel;
interface
uses
Windows, Classes, Controls, StdCtrls, ExtCtrls, Graphics, Messages, SysUtils,
Types,
ThTag, ThAttributeList, ThAnchor, ThLabel,
TpControls, TpAnchor;
type
TTpLabel = class(TThLabel)
private
FOnGenerate: TTpEvent;
protected
function CreateAnchor: TThAnchor; override;
procedure LabelTag(inTag: TThTag); override;
published
property OnGenerate: TTpEvent read FOnGenerate write FOnGenerate;
end;
//
TTpText = class(TThText)
private
FOnGenerate: TTpEvent;
protected
procedure LabelTag(inTag: TThTag); override;
published
property OnGenerate: TTpEvent read FOnGenerate write FOnGenerate;
end;
implementation
{ TTpLabel }
function TTpLabel.CreateAnchor: TThAnchor;
begin
Result := TTpAnchor.Create(Self);
end;
procedure TTpLabel.LabelTag(inTag: TThTag);
begin
inherited;
with inTag do
begin
Add(tpClass, 'TTpLabel');
Add('tpName', Name);
Add('tpOnGenerate', OnGenerate);
end;
end;
{ TTpText }
procedure TTpText.LabelTag(inTag: TThTag);
begin
inherited;
with inTag do
begin
Add(tpClass, 'TTpLabel');
Add('tpName', Name);
Add('tpOnGenerate', OnGenerate);
end;
end;
end.
|
unit LifeUnitFmx;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Objects,
FMX.StdCtrls, LifeEngine, FMX.Controls.Presentation;
const
BoardSize: TSize = (cx: 500; cy: 500);
type
TForm5 = class(TForm)
PaintBox1: TPaintBox;
HorzScrollBar: TScrollBar;
VertScrollBar: TScrollBar;
OpenDialog1: TOpenDialog;
Panel1: TPanel;
Parallel: TCheckBox;
StartStop: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
procedure FormResize(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormDestroy(Sender: TObject);
procedure PaintBox1Paint(Sender: TObject; Canvas: TCanvas);
procedure Button2Click(Sender: TObject);
procedure ParallelChange(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure HorzScrollBarChange(Sender: TObject);
procedure VertScrollBarChange(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure StartStopClick(Sender: TObject);
procedure PaintBox1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single);
procedure PaintBox1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);
private
var
FLifeEngine: TLifeEngine;
FLifeBoard: TLifeBoard;
FGensPerSecond, FMaxGensPerSecond: Double;
FViewOffset, FViewSize: TPoint;
procedure LifeEngineUpdate(Sender: TObject);
public
{ Public declarations }
end;
var
Form5: TForm5;
implementation
uses
System.Math;
{$R *.fmx}
procedure TForm5.Button2Click(Sender: TObject);
begin
if not FLifeEngine.Running then
begin
FLifeEngine.Clear;
FLifeBoard := FLifeEngine.LifeBoard;
FormResize(Sender);
PaintBox1.InvalidateRect(PaintBox1.BoundsRect);
end;
end;
procedure TForm5.Button3Click(Sender: TObject);
begin
HorzScrollBar.Value := (Length(FLifeBoard) - FViewSize.X) / 2;
VertScrollBar.Value := (Length(FLifeBoard[0]) - FViewSize.Y) / 2;
end;
procedure TForm5.Button4Click(Sender: TObject);
begin
if OpenDialog1.Execute then
FLifeEngine.LoadPattern(OpenDialog1.FileName);
end;
procedure TForm5.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
if FLifeEngine.Running then
FLifeEngine.Stop;
CanClose := not FLifeEngine.Running;
end;
procedure TForm5.FormCreate(Sender: TObject);
begin
FLifeEngine := TLifeEngine.Create(BoardSize);
FLifeEngine.OnUpdate := LifeEngineUpdate;
FLifeBoard := FLifeEngine.LifeBoard;
FLifeEngine.UpdateRate := 30;
FormResize(Sender);
LifeEngineUpdate(Sender);
end;
procedure TForm5.FormDestroy(Sender: TObject);
begin
FLifeEngine.Free;
end;
procedure TForm5.FormResize(Sender: TObject);
begin
PaintBox1.Width := ClientWidth - (600 - 561);
PaintBox1.Height := ClientHeight - (400 - 289);
HorzScrollBar.Width := PaintBox1.Width;
HorzScrollBar.Position.Y := PaintBox1.Position.Y + PaintBox1.Height + 8;
VertScrollBar.Height := PaintBox1.Height;
VertScrollBar.Position.X := PaintBox1.Position.X + PaintBox1.Width + 8;
FViewSize := TPoint.Create(Trunc(PaintBox1.Width - 10) div 10, Trunc(PaintBox1.Height - 10) div 10);
HorzScrollBar.Max := Length(FLifeBoard){ - FViewSize.X};
HorzScrollBar.ViewportSize := FViewSize.X;
VertScrollBar.Max := Length(FLifeBoard[0]){ - FViewSize.Y};
VertScrollBar.ViewportSize := FViewSize.Y;
end;
procedure TForm5.HorzScrollBarChange(Sender: TObject);
begin
FViewOffset.X := Trunc(HorzScrollBar.Value);
PaintBox1.InvalidateRect(PaintBox1.BoundsRect);
end;
procedure TForm5.LifeEngineUpdate(Sender: TObject);
begin
FLifeBoard := FLifeEngine.LifeBoard;
FGensPerSecond := FLifeEngine.GensPerSecond;
FMaxGensPerSecond := FLifeEngine.MaxGensPerSecond;
Label1.Text := Format('%f Generations Per Second', [FGensPerSecond]);
Label2.Text := Format('%f Max Generations Per Second', [FMaxGensPerSecond]);
Label4.Text := Format('%d Total Generations', [FLifeEngine.GenerationCount]);
PaintBox1.InvalidateRect(PaintBox1.BoundsRect);
end;
procedure TForm5.PaintBox1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);
var
Row, Column: Integer;
begin
if not FLifeEngine.Running and (Button = TMouseButton.mbLeft) then
begin
Row := Trunc(Y) div 10;
Column := Trunc(X) div 10;
if (Row >= 0) and (Row <= FViewSize.Y) and
(Column >= 0) and (Column <= FViewSize.X) then
begin
FLifeBoard[FViewOffset.X + Column, FViewOffset.Y + Row] :=
FLifeBoard[FViewOffset.X + Column, FViewOffset.Y + Row] xor 1;
PaintBox1.InvalidateRect(TRectF.Create(Column + 10, Row * 10, Column * 10 + 11, Row * 10 + 11));
end;
Label3.Text := Format('%d, %d', [FViewOffset.X + Column, FViewOffset.Y + Row]);
end;
end;
procedure TForm5.PaintBox1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single);
begin
Label3.Text := Format('%d, %d', [FViewOffset.X + Trunc(X) div 10, FViewOffset.Y + Trunc(Y) div 10]);
end;
procedure TForm5.PaintBox1Paint(Sender: TObject; Canvas: TCanvas);
var
I, J: Integer;
begin
PaintBox1.Canvas.Stroke.Color := TAlphaColorRec.Black;
PaintBox1.Canvas.Stroke.Kind := TBrushKind.bkSolid;
PaintBox1.Canvas.StrokeThickness := 1.0;
PaintBox1.Canvas.Fill.Color := TAlphaColorRec.Black;
PaintBox1.Canvas.Stroke.Kind := TBrushKind.bkSolid;
PaintBox1.Canvas.StrokeDash := TStrokeDash.sdSolid;
PaintBox1.Canvas.StrokeCap := TStrokeCap.scFlat;
PaintBox1.Canvas.StrokeJoin := TStrokeJoin.sjMiter;
if Length(FLifeBoard) > 0 then
for I := 0 to FViewSize.X - 1 do
for J := 0 to FViewSize.Y - 1 do
begin
if FLifeBoard[Min(FViewOffset.X + I, High(FLifeBoard)), Min(FViewOffset.Y + J, High(FLifeBoard[0]))] <> 0 then
with PaintBox1.Canvas do
begin
FillRect(TRectF.Create(I * 10, J * 10, I * 10 + 11, J * 10 + 11), 0.0, 0.0, [TCorner.crTopLeft..TCorner.crBottomRight], 1.0, TCornerType.ctRound);
end else
with PaintBox1.Canvas do
begin
DrawRect(TRectF.Create(I * 10, J * 10, I * 10 + 11, J * 10 + 11), 0.0, 0.0, [TCorner.crTopLeft..TCorner.crBottomRight], 1.0, TCornerType.ctRound);
end;
end;
end;
procedure TForm5.ParallelChange(Sender: TObject);
begin
if FLifeEngine <> nil then
FLifeEngine.Parallel := Parallel.IsChecked;
end;
procedure TForm5.StartStopClick(Sender: TObject);
begin
if not FLifeEngine.Running then
begin
FLifeEngine.Start;
StartStop.Text := 'Stop';
end else
begin
FLifeEngine.Stop;
StartStop.Text := 'Start';
end;
end;
procedure TForm5.VertScrollBarChange(Sender: TObject);
begin
FViewOffset.Y := Trunc(VertScrollBar.Value);
PaintBox1.InvalidateRect(PaintBox1.BoundsRect);
end;
end.
|
unit OutraThreadU;
interface
uses
{SafeMessageThreadU,}
System.Classes,
Winapi.Windows;
type
TOutraThread = class({TSafeMessage}TThread)
private
m_nMainThreadID : Cardinal;
procedure MessageLoop;
procedure MessageHandler(MsgRec : TMsg);
public
constructor Create(nMainThreadID: Cardinal); overload;
destructor Destroy; override;
procedure Execute; override;
end;
implementation
uses
ConstantsU,
Horse,
MainU,
System.SysUtils;
constructor TOutraThread.Create(nMainThreadID: Cardinal);
begin
inherited Create(True{, nil});
m_nMainThreadID := nMainThreadID;
end;
destructor TOutraThread.Destroy;
begin
inherited;
end;
procedure TOutraThread.Execute;
begin
MessageLoop;
end;
procedure TOutraThread.MessageLoop;
var
MsgRec : TMsg;
begin
while (not Terminated) and (GetMessage(MsgRec, 0, 0, 0)) do
begin
try
TranslateMessage(MsgRec);
MessageHandler(MsgRec);
DispatchMessage(MsgRec);
except
on E : Exception do
raise Exception.Create('TOutraThread.MessageLoop: '+IntToStr(MsgRec.message)+' : '+E.ClassName+' : '+E.Message);
end;
end;
end;
//{$DEFINE OPTION1}
procedure TOutraThread.MessageHandler(MsgRec : TMsg);
var
Res : THorseResponse;
begin
try
if (MsgRec.message = c_nPingMsgID) then
begin
{$IFDEF OPTION1}
// opcao 1: responder direto aqui
Res := THorseResponse(MsgRec.lParam);
Res.Send('pong');
{$ELSE}
// opcao 2: enviar para thread principal
{Safe}PostThreadMessage(m_nMainThreadID, c_nPingMsgID, WParam(MsgRec.lParam), LParam(PChar('pong')))
{$ENDIF}
end;
except
on E : Exception do
raise Exception.Create('TOutraThread.MessageHandler: '+IntToStr(MsgRec.message)+' : '+E.ClassName+' : '+E.Message);
end;
end;
end.
|
unit uDMExportTextFile;
interface
uses
SysUtils, Classes, ADODB, DBClient, DB, uDMGlobal, Variants;
type
TDMExportTextFile = class(TDataModule)
qryInsConfigExport: TADOQuery;
qryUpdConfigExport: TADOQuery;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
FSQLConnection: TADOConnection;
FTextFile: TClientDataSet;
FLog: TStringList;
function InsertConfigExport(AIDPessoa: Integer; ADelimiterSeparator,
ADecimalSeparator, AHeaderConfig, AFileFormat: String;
AHeaderFile : Boolean; AExportType: Smallint) : Boolean;
function UpdadeConfigExport(IDConfigExport: Integer; ADelimiterSeparator,
ADecimalSeparator, AHeaderConfig, AFileFormat: String;
AHeaderFile : Boolean) : Boolean;
public
property SQLConnection: TADOConnection read FSQLConnection write FSQLConnection;
property TextFile: TClientDataSet read FTextFile write FTextFile;
property Log: TStringList read FLog write FLog;
procedure ExportFile; virtual;
function CreateConfigExport(AIDPessoa: Integer; ADelimiterSeparator,
ADecimalSeparator, AHeaderConfig, AFileFormat: String;
AHeaderFile : Boolean; AExportType: Smallint) : Boolean;
function GetConfigExport(AIDPessoa: Integer; AExportType: Smallint;
var ADelimiterSeparator, ADecimalSeparator, AHeaderConfig, AFileFormat: String;
var AHeaderFile : WordBool) : Boolean;
end;
implementation
uses
Dialogs, uSystemConst;
{$R *.dfm}
{ TDMExportTextFile }
procedure TDMExportTextFile.ExportFile;
begin
end;
procedure TDMExportTextFile.DataModuleCreate(Sender: TObject);
begin
FTextFile := TClientDataSet.Create(nil);
FLog := TStringList.Create;
end;
procedure TDMExportTextFile.DataModuleDestroy(Sender: TObject);
begin
FreeAndNil(FTextFile);
FreeAndNil(FLog);
end;
function TDMExportTextFile.InsertConfigExport(AIDPessoa: Integer;
ADelimiterSeparator, ADecimalSeparator, AHeaderConfig,
AFileFormat: String; AHeaderFile: Boolean;
AExportType: Smallint): Boolean;
var
NewId : integer;
begin
Result := True;
qryInsConfigExport.Connection := SQLConnection;
try
NewId := DMGlobal.GetNextCode('Sis_ConfigExport', 'IDConfigExport', SQLConnection);
with qryInsConfigExport do
try
Parameters.ParamByName('IDConfigExport').Value := NewId;
if (AIDPessoa <> 0) then
Parameters.ParamByName('IDPessoa').Value := AIDPessoa
else
Parameters.ParamByName('IDPessoa').Value := null;
Parameters.ParamByName('DelimiterSeparator').Value := ADelimiterSeparator;
Parameters.ParamByName('DecimalSeparator').Value := ADecimalSeparator;
Parameters.ParamByName('HeaderConfig').Value := AHeaderConfig;
Parameters.ParamByName('FileFormat').Value := AFileFormat;
Parameters.ParamByName('HeaderFile').Value := AHeaderFile;
Parameters.ParamByName('ExportType').Value := AExportType;
ExecSQL;
finally
qryInsConfigExport.Close;
end;
except
on E: Exception do
begin
Log.Add(Format('Error: %s', [E.Message]));
Result := False;
end;
end;
end;
function TDMExportTextFile.UpdadeConfigExport(IDConfigExport: Integer;
ADelimiterSeparator, ADecimalSeparator, AHeaderConfig,
AFileFormat: String; AHeaderFile: Boolean): Boolean;
begin
Result := True;
qryUpdConfigExport.Connection := SQLConnection;
try
with qryUpdConfigExport do
try
Parameters.ParamByName('DelimiterSeparator').Value := ADelimiterSeparator;
Parameters.ParamByName('DecimalSeparator').Value := ADecimalSeparator;
Parameters.ParamByName('HeaderConfig').Value := AHeaderConfig;
Parameters.ParamByName('FileFormat').Value := AFileFormat;
Parameters.ParamByName('HeaderFile').Value := AHeaderFile;
Parameters.ParamByName('IDConfigExport').Value := IDConfigExport;
ExecSQL;
finally
qryUpdConfigExport.Close;
end;
except
on E: Exception do
begin
Log.Add(Format('Error: %s', [E.Message]));
Result := False;
end;
end;
end;
function TDMExportTextFile.CreateConfigExport(AIDPessoa: Integer;
ADelimiterSeparator, ADecimalSeparator, AHeaderConfig,
AFileFormat: String; AHeaderFile: Boolean;
AExportType: Smallint): Boolean;
begin
DMGlobal.qryFreeSQL.Connection := SQLConnection;
with DMGlobal.qryFreeSQL do
begin
if Active then
Close;
if (AExportType = EXPORT_TYPE_PO) then
SQL.Text := 'SELECT IDConfigExport '+
' FROM Sis_ConfigExport '+
' WHERE ExportType = ' + InttoStr(AExportType)+
' and IDPessoa = ' + InttoStr(AIDPessoa)
else
SQL.Text := 'SELECT IDConfigExport '+
' FROM Sis_ConfigExport '+
' WHERE ExportType = ' + InttoStr(AExportType);
try
Open;
if IsEmpty then
Result := InsertConfigExport(AIDPessoa, ADelimiterSeparator,
ADecimalSeparator, AHeaderConfig,
AFileFormat, AHeaderFile, AExportType)
else
Result := UpdadeConfigExport(FieldByName('IDConfigExport').AsInteger,
ADelimiterSeparator, ADecimalSeparator,
AHeaderConfig, AFileFormat, AHeaderFile);
finally
Close;
end;
end;
end;
function TDMExportTextFile.GetConfigExport(AIDPessoa: Integer;
AExportType: Smallint; var ADelimiterSeparator, ADecimalSeparator,
AHeaderConfig, AFileFormat: String; var AHeaderFile: WordBool): Boolean;
begin
Result := False;
DMGlobal.qryFreeSQL.Connection := SQLConnection;
with DMGlobal.qryFreeSQL do
begin
if Active then
Close;
if (AExportType = EXPORT_TYPE_PO) then
SQL.Text := 'SELECT DelimiterSeparator, DecimalSeparator, '+
' HeaderConfig, FileFormat, HeaderFile '+
' FROM Sis_ConfigExport '+
' WHERE ExportType = ' + InttoStr(AExportType)+
' and IDPessoa = ' + InttoStr(AIDPessoa)
else
SQL.Text := 'SELECT DelimiterSeparator, DecimalSeparator, '+
' HeaderConfig, FileFormat, HeaderFile '+
' FROM Sis_ConfigExport '+
' WHERE ExportType = ' + InttoStr(AExportType);
try
Open;
ADelimiterSeparator := '';
ADecimalSeparator := '';
AHeaderConfig := '';
AFileFormat := '';
AHeaderFile := false;
if not IsEmpty then
begin
ADelimiterSeparator := FieldByName('DelimiterSeparator').AsString;
ADecimalSeparator := FieldByName('DecimalSeparator').AsString;
AHeaderConfig := FieldByName('HeaderConfig').AsString;
AFileFormat := FieldByName('FileFormat').AsString;
AHeaderFile := FieldByName('HeaderFile').AsBoolean;
Result := True;
end
finally
Close;
end;
end;
end;
end.
|
unit uEncontro;
interface
type
TImpressaoEncontro = class
private
FNomePessoa: string;
FModelo: string;
FNumeroFicha: Integer;
FAno: Integer;
FLetra: string;
procedure SetAno(const Value: Integer);
procedure SetLetra(const Value: string);
procedure SetModelo(const Value: string);
procedure SetNomePessoa(const Value: string);
procedure SetNumeroFicha(const Value: Integer);
public
property Letra: string read FLetra write SetLetra;
property NomePessoa: string read FNomePessoa write SetNomePessoa;
property Modelo: string read FModelo write SetModelo;
property Ano: Integer read FAno write SetAno;
property NumeroFicha: Integer read FNumeroFicha write SetNumeroFicha;
end;
implementation
{ TImpressaoEncontro }
procedure TImpressaoEncontro.SetAno(const Value: Integer);
begin
FAno := Value;
end;
procedure TImpressaoEncontro.SetLetra(const Value: string);
begin
FLetra := Value;
end;
procedure TImpressaoEncontro.SetModelo(const Value: string);
begin
FModelo := Value;
end;
procedure TImpressaoEncontro.SetNomePessoa(const Value: string);
begin
FNomePessoa := Value;
end;
procedure TImpressaoEncontro.SetNumeroFicha(const Value: Integer);
begin
FNumeroFicha := Value;
end;
end.
|
unit uFrmAssociateDepartment;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, PAIDETODOS, Buttons, StdCtrls, CheckLst, siComp, siLangRT,
LblEffct, ExtCtrls, DB, ADODB, PowerADOQuery, ComCtrls;
type
TFrmAssociateDepartment = class(TFrmParent)
clbDepartment: TCheckListBox;
btUnSelectAll: TSpeedButton;
btSelectAll: TSpeedButton;
quDepartment: TPowerADOQuery;
btApply: TButton;
pbProcess: TProgressBar;
procedure btSelectAllClick(Sender: TObject);
procedure btUnSelectAllClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btApplyClick(Sender: TObject);
private
FDataSetInventory: TPowerADOQuery;
FIDDepartmentList: TStrings;
procedure LoadDepartmentList;
procedure DoAssociateDepartment(AIDStore, AIDModel: Integer; AIDDepartmentList: String);
procedure DeleteModelDepartment(AIDStore, AIDModel: Integer; AIDDepartmentList: String);
procedure InsertInventory(AIDStore, AIDModel: Integer);
procedure InsertModelDepartment(AIDStore, AIDModel: Integer; AIDDepartmentList: String);
function GetDepartmentList: String;
function HasDepartmentSelected: Boolean;
public
procedure Start(ADataSetInventory: TPowerADOQuery);
end;
implementation
uses uDM, uMsgBox, uMsgConstant;
{$R *.dfm}
procedure TFrmAssociateDepartment.btSelectAllClick(Sender: TObject);
var
i: Integer;
begin
inherited;
with clbDepartment do
for I := 0 to Pred(Items.Count) do
Checked[I] := True;
end;
procedure TFrmAssociateDepartment.btUnSelectAllClick(Sender: TObject);
var
i: Integer;
begin
inherited;
with clbDepartment do
for I := 0 to Pred(Items.Count) do
Checked[I] := False;
end;
function TFrmAssociateDepartment.GetDepartmentList: String;
var
i: Integer;
begin
Result:= '';
for i := 0 to clbDepartment.Items.Count - 1 do
if clbDepartment.Checked[i] then
if Result = '' then
Result:= FIDDepartmentList[i]
else
Result:= Result + ', ' + FIDDepartmentList[i];
end;
function TFrmAssociateDepartment.HasDepartmentSelected: Boolean;
var
i: Integer;
begin
Result:= false;
for i := 0 to clbDepartment.Items.Count - 1 do
if clbDepartment.Checked[i] then
begin
Result:= true;
break;
end;
end;
procedure TFrmAssociateDepartment.LoadDepartmentList;
begin
with quDepartment do
begin
First;
FIDDepartmentList.Clear;
clbDepartment.Clear;
while not Eof do
begin
clbDepartment.Items.Add(FieldByName('Department').AsString);
FIDDepartmentList.Add(FieldByName('IDDepartment').AsString);
Next;
end;
end;
end;
procedure TFrmAssociateDepartment.FormCreate(Sender: TObject);
begin
inherited;
FIDDepartmentList := TStringList.Create;
end;
procedure TFrmAssociateDepartment.FormDestroy(Sender: TObject);
begin
inherited;
FreeAndNil(FIDDepartmentList);
end;
procedure TFrmAssociateDepartment.Start(ADataSetInventory: TPowerADOQuery);
begin
FDataSetInventory := ADataSetInventory;
quDepartment.Open;
LoadDepartmentList;
ShowModal;
quDepartment.Close;
end;
procedure TFrmAssociateDepartment.btApplyClick(Sender: TObject);
var
sIDDepartmentList: String;
begin
if not HasDepartmentSelected then
begin
MsgBox(MSG_INF_SELECT_DEPARTMENT, vbInformation + vbOKOnly);
ModalResult := mrNone;
Exit;
end;
sIDDepartmentList := GetDepartmentList;
with FDataSetInventory do
try
DM.ADODBConnect.BeginTrans;
Screen.Cursor := crHourGlass;
DisableControls;
pbProcess.Max := RecordCount;
try
First;
pbProcess.Position := 0;
while not Eof do
begin
DoAssociateDepartment(FieldByName('StoreID').AsInteger,
FieldByName('ModelID').AsInteger,
sIDDepartmentList);
pbProcess.Position := pbProcess.Position + 1;
Next;
end;
DM.ADODBConnect.CommitTrans;
inherited;
except
DM.ADODBConnect.RollbackTrans;
MsgBox(MSG_CRT_ASSOCIATING_DEPARTMENT, vbCritical + vbOKOnly);
ModalResult := mrNone;
end;
finally
EnableControls;
Screen.Cursor := crDefault;
end;
end;
procedure TFrmAssociateDepartment.DoAssociateDepartment(AIDStore,
AIDModel: Integer; AIDDepartmentList: String);
begin
DeleteModelDepartment(AIDStore, AIDModel, AIDDepartmentList);
InsertInventory(AIDStore, AIDModel);
InsertModelDepartment(AIDStore, AIDModel, AIDDepartmentList);
end;
procedure TFrmAssociateDepartment.DeleteModelDepartment(AIDStore,
AIDModel: Integer; AIDDepartmentList: String);
begin
with DM.quFreeSQL do
try
if Active then
Close;
SQL.Clear;
SQL.Add('DELETE Inv_ModelDepartment');
SQL.Add('WHERE StoreID = ' + IntToStr(AIDStore));
SQL.Add('AND ModelID = ' + IntToStr(AIDModel));
SQL.Add('AND IDDepartment IN (' + AIDDepartmentList + ')');
ExecSQL;
finally
Close;
end;
end;
procedure TFrmAssociateDepartment.InsertInventory(AIDStore,
AIDModel: Integer);
var
iIDInventory: Integer;
begin
with DM.quFreeSQL do
try
if Active then
Close;
SQL.Clear;
SQL.Add('SELECT IDInventory');
SQL.Add('FROM Inventory');
SQL.Add('WHERE StoreID = ' + IntToStr(AIDStore));
SQL.Add('AND ModelID = ' + IntToStr(AIDModel));
Open;
if IsEmpty then
begin
iIDInventory := DM.GetNextID('Inventory.IDInventory');
SQL.Clear;
SQL.Add('INSERT INTO Inventory (IDInventory, StoreID, ModelID, AvgCostTotal)');
SQL.Add('VALUES (' + IntToStr(iIDInventory) + ', ' + IntToStr(AIDStore) + ', ' + IntToStr(AIDModel) + ', 0)');
ExecSQL;
end;
finally
Close;
end;
end;
procedure TFrmAssociateDepartment.InsertModelDepartment(AIDStore,
AIDModel: Integer; AIDDepartmentList: String);
begin
with DM.quFreeSQL do
try
if Active then
Close;
SQL.Clear;
SQL.Add('INSERT INTO Inv_ModelDepartment (StoreID, ModelID, IDDepartment)');
SQL.Add('(SELECT StoreID, ModelID, IDDepartment');
SQL.Add('FROM Inv_Department, Inventory');
SQL.Add('WHERE IDDepartment IN (' + AIDDepartmentList + ')');
SQL.Add('AND StoreID = ' + IntToStr(AIDStore));
SQL.Add('AND ModelID = ' + IntToStr(AIDModel) + ')');
ExecSQL;
finally
Close;
end;
end;
end.
|
{: Simple projective shadows.<p>
The TGLShadowPlane component allows to render simple projective shadows.
They have the benefit of being quite fast, but as the name says, your shadows
will be projected only on a plane and must be (entirely) on the same side
of the plane as the light (the side pointed by the plane's direction).<p>
Note that stenciling is required for proper operation (it is an option of
the Viewer.Buffer.ContextOptions), which should be available on all modern
graphics hardware. When stenciling is not activated, the ShadowPlane will
use opaque shadows and you may see shadows appear beyond the plane limits...<p>
The higher quality lighting on the marble planes is obtained by specifying
Tiles in the plane and removing 'psSingleQuad' from the style. Lighting
is computed per-vertex, this changes increase drastically the number of
vertices that make up the planes, thus allowing for better lighting.
}
unit Unit1;
interface
uses
SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, GLShadowPlane, GLScene, GLViewer, GLObjects,
GLCadencer, StdCtrls, GLVectorGeometry, ExtCtrls, GLTexture, GLGeomObjects,
GLCrossPlatform, GLMaterial, GLCoordinates, GLBaseClasses;
type
TForm1 = class(TForm)
GLSceneViewer1: TGLSceneViewer;
GLScene1: TGLScene;
DCShadowing: TGLDummyCube;
GLLightSource1: TGLLightSource;
Cube1: TGLCube;
Sphere1: TGLSphere;
GLCamera1: TGLCamera;
GLCadencer1: TGLCadencer;
DCLight: TGLDummyCube;
Sphere2: TGLSphere;
Torus1: TGLTorus;
DCCameraTarget: TGLDummyCube;
GLShadowPlane1: TGLShadowPlane;
Timer1: TTimer;
Panel1: TPanel;
CBShadows: TCheckBox;
CBStencil: TCheckBox;
GLShadowPlane2: TGLShadowPlane;
GLMaterialLibrary: TGLMaterialLibrary;
GLShadowPlane3: TGLShadowPlane;
procedure GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
procedure FormCreate(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure CBShadowsClick(Sender: TObject);
procedure CBStencilClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
uses
GLUtils;
procedure TForm1.FormCreate(Sender: TObject);
begin
SetGLSceneMediaDir();
GLMaterialLibrary.Materials[0].Material.Texture.Image.LoadFromFile('beigemarble.jpg');
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
begin
DCLight.PitchAngle:=Sin(newTime)*60;
DCShadowing.TurnAngle:=newTime*10;
end;
procedure TForm1.CBShadowsClick(Sender: TObject);
begin
if CBShadows.Checked then
GLShadowPlane1.ShadowedLight:=GLLightSource1
else GLShadowPlane1.ShadowedLight:=nil;
GLShadowPlane2.ShadowedLight:=GLShadowPlane1.ShadowedLight;
GLShadowPlane3.ShadowedLight:=GLShadowPlane1.ShadowedLight;
end;
procedure TForm1.CBStencilClick(Sender: TObject);
begin
if CBStencil.Checked then
GLShadowPlane1.ShadowOptions:=[spoUseStencil, spoScissor]
else GLShadowPlane1.ShadowOptions:=[spoScissor];
GLShadowPlane2.ShadowOptions:=GLShadowPlane1.ShadowOptions;
GLShadowPlane3.ShadowOptions:=GLShadowPlane1.ShadowOptions;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
Caption:=Format('%.1f FPS', [GLSceneViewer1.FramesPerSecond]);
GLSceneViewer1.ResetPerformanceMonitor;
end;
end.
|
unit Response.Intf;
interface
uses System.SysUtils, System.JSON,System.Classes;
type
IResponse = interface
['{450B980A-74B2-4204-BE86-E1D62200EDF5}']
function Content: string;
function JSONText:string;
function ContentLength: Cardinal;
function ContentType: string;
function ContentEncoding: string;
function StatusCode: Integer;
function ErrorMessage: string;
function RawBytes: TBytes;
function JSONValue: TJSONValue;
function Headers: TStrings;
procedure RootElement(const PRootElement:String);
end;
implementation
end.
|
unit UFrmPaiCadastro;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UFrmPai, Vcl.Buttons, Vcl.ExtCtrls,
Vcl.StdCtrls, Vcl.Mask, JvExMask, JvToolEdit, JvBaseEdits, Data.DB, UDMPai;
type
TFrmPaiCadastro = class(TFrmPai)
pnlTop: TPanel;
Panel1: TPanel;
btnConsulta: TBitBtn;
btnGravar: TBitBtn;
btnCancelar: TBitBtn;
btnExcluir: TBitBtn;
btnIncluir: TBitBtn;
edtCodigo: TJvCalcEdit;
pnlNavegacao: TPanel;
btnPrimeiro: TBitBtn;
btnUltimo: TBitBtn;
btnProximo: TBitBtn;
btnAnterior: TBitBtn;
DS: TDataSource;
procedure pnlTopExit(Sender: TObject);
procedure DSStateChange(Sender: TObject);
procedure btnIncluirClick(Sender: TObject);
procedure btnExcluirClick(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure btnGravarClick(Sender: TObject);
procedure DSDataChange(Sender: TObject; Field: TField);
procedure btnPrimeiroClick(Sender: TObject);
procedure btnAnteriorClick(Sender: TObject);
procedure btnProximoClick(Sender: TObject);
procedure btnUltimoClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
FDMCadastro: TDMPai;
public
{ Public declarations }
property DMCadastro: TDMPai read FDMCadastro write FDMCadastro;
procedure AbrirCDS(Codigo: Integer);
procedure NavegarRegistro(Sentido: Integer);
end;
var
FrmPaiCadastro: TFrmPaiCadastro;
implementation
uses
Datasnap.DBClient, UDMConexao;
{$R *.dfm}
{ TFrmPaiCadastro }
procedure TFrmPaiCadastro.AbrirCDS(Codigo: Integer);
begin
if ((Codigo = 0) or (Codigo = DMCadastro.CodigoAtual)) then
Exit;
DMCadastro.CDS_Cadastro.Close;
DMCadastro.CDS_Cadastro.FetchParams;
DMCadastro.CDS_Cadastro.Params[0].AsInteger := Codigo;
DMCadastro.CDS_Cadastro.Open;
end;
procedure TFrmPaiCadastro.btnAnteriorClick(Sender: TObject);
begin
inherited;
NavegarRegistro(1);
end;
procedure TFrmPaiCadastro.btnCancelarClick(Sender: TObject);
begin
inherited;
if MessageDlg('Deseja Cancelar?', mtInformation, mbYesNo, 0) = mrYes then
DMCadastro.CDS_Cadastro.CancelUpdates;
end;
procedure TFrmPaiCadastro.btnExcluirClick(Sender: TObject);
begin
inherited;
if MessageDlg('Deseja realmente Excluir o registro?', mtInformation, mbYesNo, 0) = mrYes then
begin
DMCadastro.CDS_Cadastro.Delete;
DMCadastro.CDS_Cadastro.ApplyUpdates(0);
end;
end;
procedure TFrmPaiCadastro.btnGravarClick(Sender: TObject);
begin
inherited;
try
DMCadastro.CDS_Cadastro.ApplyUpdates(0);
except on E: Exception do
raise Exception.Create('Erro ao tentar Gravar!' + E.Message);
end;
end;
procedure TFrmPaiCadastro.btnIncluirClick(Sender: TObject);
begin
inherited;
try
if not DMCadastro.CDS_Cadastro.Active then
DMCadastro.CDS_Cadastro.Open;
DMCadastro.CDS_Cadastro.Insert;
except on E: Exception do
raise Exception.Create('Erro ao tentar Incluir Registro!' + E.Message);
end;
end;
procedure TFrmPaiCadastro.btnPrimeiroClick(Sender: TObject);
begin
inherited;
NavegarRegistro(0);
end;
procedure TFrmPaiCadastro.btnProximoClick(Sender: TObject);
begin
inherited;
NavegarRegistro(2);
end;
procedure TFrmPaiCadastro.btnUltimoClick(Sender: TObject);
begin
inherited;
NavegarRegistro(3);
end;
procedure TFrmPaiCadastro.DSDataChange(Sender: TObject; Field: TField);
begin
inherited;
if Assigned(DMCadastro) then
begin
edtCodigo.Text := DMCadastro.CDS_Cadastro.FieldByName(DMCadastro.ClasseFilha.CampoChave).AsString;
DMCadastro.CodigoAtual := DMCadastro.CDS_Cadastro.FieldByName(DMCadastro.ClasseFilha.CampoChave).AsInteger;
end;
end;
procedure TFrmPaiCadastro.DSStateChange(Sender: TObject);
begin
inherited;
btnIncluir.Enabled := DS.State in [dsBrowse, dsInactive];
btnExcluir.Enabled := DS.State in [dsBrowse];
btnGravar.Enabled := DS.State in [dsEdit, dsInsert];
btnCancelar.Enabled := DS.State in [dsEdit, dsInsert];
btnConsulta.Enabled := DS.State in [dsBrowse, dsInactive];
pnlTop.Enabled := DS.State in [dsBrowse, dsInactive];
end;
procedure TFrmPaiCadastro.FormClose(Sender: TObject; var Action: TCloseAction);
begin
inherited;
DS.DataSet.Close;
DMCadastro.CodigoAtual := 0;
end;
procedure TFrmPaiCadastro.FormShow(Sender: TObject);
begin
inherited;
edtCodigo.Text := IntToStr(DMCadastro.CodigoAtual);
end;
procedure TFrmPaiCadastro.NavegarRegistro(Sentido: Integer);
var
SQL: String;
CDSTemp: TClientDataSet;
begin
CDSTemp := TClientDataSet.Create(Self);
try
with DMCadastro, ClasseFilha do
begin
case Sentido of
0: SQL := 'SELECT MIN(' + CampoChave + ') AS CODIGO FROM ' + TabelaPrincipal;
1: SQL := 'SELECT MAX(' + CampoChave + ') AS CODIGO FROM ' + TabelaPrincipal
+ ' WHERE ' + CampoChave + ' < ' + IntToStr(CodigoAtual);
2: SQL := 'SELECT MIN(' + CampoChave + ') AS CODIGO FROM ' + TabelaPrincipal
+ ' WHERE ' + CampoChave + ' > ' + IntToStr(CodigoAtual);
3: SQL := 'SELECT MAX('+CampoChave+') AS CODIGO FROM '+TabelaPrincipal;
end;
CDSTemp.Data := DMConexao.ExecuteReader(SQL);
if not CDSTemp.IsEmpty then
AbrirCDS(CDSTemp.FieldByName('CODIGO').AsInteger)
else
edtCodigo.Text := IntToStr(CodigoAtual);
end;
finally
CDSTemp.Free;
end;
end;
procedure TFrmPaiCadastro.pnlTopExit(Sender: TObject);
begin
inherited;
if edtCodigo.Text <> '' then
AbrirCDS(edtCodigo.AsInteger);
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
SynEditHighlighter, SynHighlighterPython, SynEditPythonBehaviour, SynEdit,
SynHighlighterJava, StdCtrls, ExtCtrls, SynEditTypes;
type
TForm1 = class(TForm)
Editor: TSynEdit;
SynJavaSyn1: TSynJavaSyn;
Panel1: TPanel;
Button2: TButton;
OpenDialog1: TOpenDialog;
Button1: TButton;
procedure EditorPaintTransient(Sender: TObject; Canvas: TCanvas;
TransientType: TTransientType);
procedure Button2Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
FBracketFG: TColor;
FBracketBG: TColor;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.EditorPaintTransient(Sender: TObject; Canvas: TCanvas;
TransientType: TTransientType);
const AllBrackets = ['{','[','(','<','}',']',')','>'];
var Editor: TSynEdit;
OpenChars: array[0..2] of Char;
CloseChars: array[0..2] of Char;
function CharToPixels(P: TBufferCoord): TPoint;
begin
Result:=Editor.RowColumnToPixels(Editor.BufferToDisplayPos(P));
end;
var P: TBufferCoord;
Pix: TPoint;
D : TDisplayCoord;
S: String;
I: Integer;
Attri: TSynHighlighterAttributes;
start: Integer;
TmpCharA, TmpCharB: Char;
begin
if TSynEdit(Sender).SelAvail then exit;
Editor := TSynEdit(Sender);
//if you had a highlighter that used a markup language, like html or xml, then you would want to highlight
//the greater and less than signs as well as illustrated below
// if (Editor.Highlighter = shHTML) or (Editor.Highlighter = shXML) then
// inc(ArrayLength);
for i := 0 to 2 do
case i of
0: begin OpenChars[i] := '('; CloseChars[i] := ')'; end;
1: begin OpenChars[i] := '{'; CloseChars[i] := '}'; end;
2: begin OpenChars[i] := '['; CloseChars[i] := ']'; end;
3: begin OpenChars[i] := '<'; CloseChars[i] := '>'; end;
end;
P := Editor.CaretXY;
D := Editor.DisplayXY;
Start := Editor.SelStart;
if (Start > 0) and (Start <= length(Editor.Text)) then
TmpCharA := Editor.Text[Start]
else TmpCharA := #0;
if (Start < length(Editor.Text)) then
TmpCharB := Editor.Text[Start + 1]
else TmpCharB := #0;
if not(TmpCharA in AllBrackets) and not(TmpCharB in AllBrackets) then exit;
S := TmpCharB;
if not(TmpCharB in AllBrackets) then
begin
P.Char := P.Char - 1;
S := TmpCharA;
end;
Editor.GetHighlighterAttriAtRowCol(P, S, Attri);
if (Editor.Highlighter.SymbolAttribute = Attri) then
begin
for i := low(OpenChars) to High(OpenChars) do
begin
if (S = OpenChars[i]) or (S = CloseChars[i]) then
begin
Pix := CharToPixels(P);
Editor.Canvas.Brush.Style := bsSolid;//Clear;
Editor.Canvas.Font.Assign(Editor.Font);
Editor.Canvas.Font.Style := Attri.Style;
if (TransientType = ttAfter) then
begin
Editor.Canvas.Font.Color := FBracketFG;
Editor.Canvas.Brush.Color := FBracketBG;
end else begin
Editor.Canvas.Font.Color := Attri.Foreground;
Editor.Canvas.Brush.Color := Attri.Background;
end;
if Editor.Canvas.Font.Color = clNone then
Editor.Canvas.Font.Color := Editor.Font.Color;
if Editor.Canvas.Brush.Color = clNone then
Editor.Canvas.Brush.Color := Editor.Color;
if Pix.X > Editor.GutterWidth then
begin
Editor.Canvas.TextOut(Pix.X, Pix.Y, S);
end;
P := Editor.GetMatchingBracketEx(P);
if (P.Char > 0) and (P.Line > 0) then
begin
Pix := CharToPixels(P);
if Pix.X > Editor.GutterWidth then
begin
if S = OpenChars[i] then
Editor.Canvas.TextOut(Pix.X, Pix.Y, CloseChars[i])
else Editor.Canvas.TextOut(Pix.X, Pix.Y, OpenChars[i]);
end;
end;
end; //if
end;//for i :=
Editor.Canvas.Brush.Style := bsSolid;
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
if OpenDialog1.Execute then
Editor.Lines.LoadFromFile(OpenDialog1.Filename);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Editor.Text := SynJavaSyn1.SampleSource;
FBracketFG := clRed;
FBracketBG := clNone;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
SynJavaSyn1.Enabled := not(SynJavaSyn1.Enabled);
Editor.Repaint;
end;
end.
|
{: The fire special effect basic sample.<p>
If you look at the code you won't see anything fancy. The FireFX is a dynamic
special effect (driven by a cadencer). Making use of it means two things :<br>
- dropping a FirexFXManager, this one controls fire particle systems aspects<br>
- adding a FireFX effect to the object you want to see burning (here, a sphere)<br>
You may have multiple objects sharing the same FireFXManager, this means they
will all look the same, but also that the particle system calculations are
made only once.<p>
This effect looks cool but is fill-rate hungry, but un-textured fillrate
hungry, ie. video card memory bandwith is not an issue. Anyway, you can
always make it look nice with smaller and/or less particles.
}
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages,
System.SysUtils, System.Classes, System.Math,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.ComCtrls, Vcl.StdCtrls, Vcl.ExtCtrls,
GLFireFX, GLCadencer, GLScene, GLObjects, GLBehaviours,
GLVectorGeometry, GLWin32Viewer, GLGeomObjects,
GLCoordinates, GLCrossPlatform, GLBaseClasses;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
GLCadencer1: TGLCadencer;
GLFireFXManager1: TGLFireFXManager;
GLCamera1: TGLCamera;
Sphere1: TGLSphere;
GLLightSource2: TGLLightSource;
Timer1: TTimer;
Panel1: TPanel;
TrackBar1: TTrackBar;
Timer2: TTimer;
TrackBar2: TTrackBar;
TrackBar3: TTrackBar;
TrackBar4: TTrackBar;
TrackBar6: TTrackBar;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label6: TLabel;
TrackBar7: TTrackBar;
Label7: TLabel;
TrackBar8: TTrackBar;
Label5: TLabel;
TrackBar5: TTrackBar;
Label8: TLabel;
TrackBar9: TTrackBar;
Button1: TButton;
Button2: TButton;
procedure GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure Timer1Timer(Sender: TObject);
procedure FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
procedure TrackBar1Change(Sender: TObject);
procedure TrackBar2Change(Sender: TObject);
procedure TrackBar3Change(Sender: TObject);
procedure TrackBar4Change(Sender: TObject);
procedure TrackBar5Change(Sender: TObject);
procedure TrackBar6Change(Sender: TObject);
procedure TrackBar7Change(Sender: TObject);
procedure TrackBar8Change(Sender: TObject);
procedure TrackBar9Change(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Déclarations privées }
public
{ Déclarations publiques }
mx, my : Integer;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
mx:=x; my:=y;
end;
procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
if Shift<>[] then
GLCamera1.MoveAroundTarget(my-y, mx-x);
mx:=x; my:=y;
GLCadencer1.Progress;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
Caption:=Format('Fire Demo '+ '%.1f FPS', [GLSceneViewer1.FramesPerSecond]);
GLSceneViewer1.ResetPerformanceMonitor;
end;
procedure TForm1.FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
begin
GLCamera1.AdjustDistanceToTarget(Power(1.1, WheelDelta/120));
end;
procedure TForm1.TrackBar1Change(Sender: TObject);
begin
GLFireFXManager1.FireDensity:= TrackBar1.Position*0.1;
end;
procedure TForm1.TrackBar2Change(Sender: TObject);
begin
GLFireFXManager1.FireBurst:= TrackBar2.Position;
end;
procedure TForm1.TrackBar3Change(Sender: TObject);
begin
GLFireFXManager1.FireCrown:= TrackBar3.Position*0.1;
end;
procedure TForm1.TrackBar4Change(Sender: TObject);
begin
GLFireFXManager1.FireEvaporation:= TrackBar4.Position*0.1;
end;
procedure TForm1.TrackBar5Change(Sender: TObject);
begin
GLFireFXManager1.FireRadius:= TrackBar5.Position*0.3;
end;
procedure TForm1.TrackBar6Change(Sender: TObject);
begin
GLFireFXManager1.ParticleSize:= TrackBar6.Position*0.1;
end;
procedure TForm1.TrackBar7Change(Sender: TObject);
begin
GLFireFXManager1.ParticleLife:= TrackBar7.Position+1;
end;
procedure TForm1.TrackBar8Change(Sender: TObject);
begin
GLFireFXManager1.ParticleInterval:= TrackBar8.Position*0.004;
end;
procedure TForm1.TrackBar9Change(Sender: TObject);
begin
GLFireFXManager1.FireDir.Z:=-TrackBar9.Position*0.1;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
GLFireFXManager1.IsotropicExplosion(1,15,1);
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
GLFireFXManager1.RingExplosion(1,15,1 ,XVector, ZVector);
end;
end.
|
unit Range;
{ a modal dialog used for setting the date range for the survey usage dialog }
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Mask, ComCtrls;
type
TfrmRange = class(TForm)
lblEnd: TLabel;
lblStart: TLabel;
lblInterval: TLabel;
spnInterval: TUpDown;
btnCancel: TButton;
btnOK: TButton;
edtStart: TMaskEdit;
edtEnd: TMaskEdit;
edtInterval: TMaskEdit;
procedure OKClick(Sender: TObject);
procedure RangeEnter(Sender: TObject);
procedure IntervalEnter(Sender: TObject);
procedure CancelClick(Sender: TObject);
private
procedure EnableInterval( vEnable : Boolean );
public
{ Public declarations }
end;
var
frmRange: TfrmRange;
implementation
uses Data;
{$R *.DFM}
{ BUTTON METHODS }
{ sets the range from the entered values:
1. closes the query
2. passes in the entered values as paramaters
3. opens the query
4. closes the dialog }
procedure TfrmRange.OKClick(Sender: TObject);
begin
with modLibrary.wqryClient do
begin
modLibrary.wtblUsage.DisableControls;
try
Close;
if lblInterval.Enabled then
begin
if edtInterval.Text = '' then
ParamByName( 'start' ).AsDate := 0
else
ParamByName( 'start' ).AsDate := ( Date - ( StrToInt( edtInterval.Text ) * 30.5 ) );
ParamByName( 'end' ).AsDate := Date;
end
else
begin
ParamByName( 'start' ).AsDate := StrToDate( edtStart.Text );
ParamByName( 'end' ).AsDate := StrToDate( edtEnd.Text );
end;
Open;
finally
modLibrary.wtblUsage.EnableControls;
end;
end;
Close;
end;
procedure TfrmRange.CancelClick(Sender: TObject);
begin
Close;
end;
{ COMPONENT HANDLERS }
procedure TfrmRange.RangeEnter(Sender: TObject);
begin
EnableInterval( False );
end;
procedure TfrmRange.IntervalEnter(Sender: TObject);
begin
EnableInterval( True );
end;
{ GENERAL METHODS }
{ switches between interval and start/end for entering values }
procedure TfrmRange.EnableInterval( vEnable : Boolean );
begin
if vEnable then
begin
edtStart.Clear;
edtEnd.Clear;
spnInterval.Position := 12;
end
else
begin
edtInterval.Clear;
edtEnd.Text := DateToStr( Date );
end;
lblStart.Enabled := not vEnable;
lblEnd.Enabled := not vEnable;
lblInterval.Enabled := vEnable;
end;
end.
|
unit uModelBaseType;
interface
uses
Classes, Windows, SysUtils, DBClient, uPubFun, uParamObject, uBaseInfoDef, uDefCom, uBusinessLayerPlugin,
uModelParent, uModelBaseTypeIntf;
type
TModelBaseItype = class(TModelBaseType, IModelBaseTypeItype) //基本信息-加载包处理领域
private
protected
function GetSaveProcName: string; override;
function CheckData(AParamList: TParamObject; var Msg: string): Boolean; virtual; //检查数据
public
destructor Destroy; override;
end;
TModelBasePtype = class(TModelBaseType, IModelBaseTypePtype) //基本信息-商品处理领域
private
function SaveOneUnitInfo(aUnitInfo :TParamObject): Integer;
function GetUnitInfo(aPtypeId :string; ACdsU: TClientDataSet): Integer;
protected
function GetSaveProcName: string; override;
function CheckData(AParamList: TParamObject; var Msg: string): Boolean; override; //检查数据
public
destructor Destroy; override;
end;
TModelBaseBtype = class(TModelBaseType, IModelBaseTypeBtype) //基本信息-单位处理领域
private
protected
function GetSaveProcName: string; override;
public
end;
TModelBaseEtype = class(TModelBaseType, IModelBaseTypeEtype) //基本信息-职员处理领域
private
protected
function GetSaveProcName: string; override;
public
end;
TModelBaseDtype = class(TModelBaseType, IModelBaseTypeDtype) //基本信息-部门处理领域
private
protected
function GetSaveProcName: string; override;
public
end;
TModelBaseKtype = class(TModelBaseType, IModelBaseTypeKtype) //基本信息-仓库处理领域
private
protected
function GetSaveProcName: string; override;
public
end;
implementation
uses uModelFunCom;
{ TBusinessBasicLtype }
function TModelBaseItype.CheckData(AParamList: TParamObject;
var Msg: string): Boolean;
begin
end;
destructor TModelBaseItype.Destroy;
begin
inherited;
end;
function TModelBaseItype.GetSaveProcName: string;
begin
Result := inherited GetSaveProcName;
case Self.DataChangeType of
dctAdd, dctAddCopy, dctClass:
begin
Result := 'pbx_Base_InsertI'; //增加
end;
dctModif:
begin
Result := 'pbx_Base_UpdateI'; //修改
end;
end;
end;
{ TModelBasePtype }
function TModelBasePtype.CheckData(AParamList: TParamObject;
var Msg: string): Boolean;
begin
Result := False;
if not IsNumberic(AParamList.AsString('@UsefulLifeday')) then
begin
Msg := '有效期必须是数字!';
Exit;
end;
Result := True;
end;
destructor TModelBasePtype.Destroy;
begin
inherited;
end;
function TModelBasePtype.GetSaveProcName: string;
begin
Result := inherited GetSaveProcName;
case Self.DataChangeType of
dctAdd, dctAddCopy, dctClass:
begin
Result := 'pbx_Base_InsertP'; //增加
end;
dctModif:
begin
Result := 'pbx_Base_UpdateP'; //修改
end;
end;
end;
function TModelBasePtype.GetUnitInfo(aPtypeId: string;
ACdsU: TClientDataSet): Integer;
var
aSQL: string;
begin
aSQL := 'SELECT * FROM tbx_Base_PtypeUnit WHERE PTypeId = ' + QuotedStr(aPtypeId) + ' ORDER BY OrdId';
gMFCom.QuerySQL(aSQL, ACdsU);
end;
function TModelBasePtype.SaveOneUnitInfo(aUnitInfo: TParamObject): Integer;
var
aRet: Integer;
begin
aRet := gMFCom.ExecProcByName('pbx_Base_SavePTypeUnit', aUnitInfo);
end;
{ TModelBaseBtype }
function TModelBaseBtype.GetSaveProcName: string;
begin
Result := inherited GetSaveProcName;
case Self.DataChangeType of
dctAdd, dctAddCopy, dctClass:
begin
Result := 'pbx_Base_InsertB'; //增加
end;
dctModif:
begin
Result := 'pbx_Base_UpdateB'; //修改
end;
end;
end;
{ TModelBaseDtype }
function TModelBaseDtype.GetSaveProcName: string;
begin
Result := inherited GetSaveProcName;
case Self.DataChangeType of
dctAdd, dctAddCopy, dctClass:
begin
Result := 'pbx_Base_InsertD'; //增加
end;
dctModif:
begin
Result := 'pbx_Base_UpdateD'; //修改
end;
end;
end;
{ TModelBaseEtype }
function TModelBaseEtype.GetSaveProcName: string;
begin
Result := inherited GetSaveProcName;
case Self.DataChangeType of
dctAdd, dctAddCopy, dctClass:
begin
Result := 'pbx_Base_InsertE'; //增加
end;
dctModif:
begin
Result := 'pbx_Base_UpdateE'; //修改
end;
end;
end;
{ TModelBaseKtype }
function TModelBaseKtype.GetSaveProcName: string;
begin
Result := inherited GetSaveProcName;
case Self.DataChangeType of
dctAdd, dctAddCopy, dctClass:
begin
Result := 'pbx_Base_InsertK'; //增加
end;
dctModif:
begin
Result := 'pbx_Base_UpdateK'; //修改
end;
end;
end;
initialization
gClassIntfManage.addClass(TModelBaseItype, IModelBaseTypeItype);
gClassIntfManage.addClass(TModelBasePtype, IModelBaseTypePtype);
gClassIntfManage.addClass(TModelBaseBtype, IModelBaseTypeBtype);
gClassIntfManage.addClass(TModelBaseEtype, IModelBaseTypeEtype);
gClassIntfManage.addClass(TModelBaseDtype, IModelBaseTypeDtype);
gClassIntfManage.addClass(TModelBaseKtype, IModelBaseTypeKtype);
end.
|
unit mpRPC;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, mpgui, FPJSON, jsonparser, mpCoin, mpRed, mpBlock,nosodebug,
nosogeneral, nosocrypto, nosounit, nosoconsensus;
Procedure SetRPCPort(LineText:string);
Procedure setRPCpassword(newpassword:string);
Procedure SetRPCOn();
Procedure SetRPCOff();
// *** RPC PARSE FUNCTIONS ***
function IsValidJSON (MyJSONstring:string):boolean;
Function GetJSONErrorString(ErrorCode:integer):string;
function GetJSONErrorCode(ErrorCode, JSONIdNumber:integer):string;
function GetJSONResponse(ResultToSend:string;JSONIdNumber:integer):string;
function ParseRPCJSON(jsonreceived:string):string;
function ObjectFromString(MyString:string): string;
function RPC_AddressBalance(NosoPParams:string):string;
function RPC_OrderInfo(NosoPParams:string):string;
function RPC_Blockinfo(NosoPParams:string):string;
function RPC_Mininginfo(NosoPParams:string):string;
function RPC_Mainnetinfo(NosoPParams:string):string;
function RPC_PendingOrders(NosoPParams:string):string;
function RPC_GetPeers(NosoPParams:string):string;
function RPC_BlockOrders(NosoPParams:string):string;
function RPC_Blockmns(NosoPParams:string):string;
function RPC_NewAddress(NosoPParams:string):string;
Function RPC_ValidateAddress(NosoPParams:string):string;
function RPC_SendFunds(NosoPParams:string):string;
implementation
Uses
MasterPaskalForm,mpparser, mpDisk, mpProtocol;
// Sets RPC port
Procedure SetRPCPort(LineText:string);
var
value : integer;
Begin
value := StrToIntDef(parameter(LineText,1),0);
if ((value <=0) or (value >65535)) then
begin
AddLineToDebugLog('console','Invalid value');
end
else if Form1.RPCServer.Active then
AddLineToDebugLog('console','Can not change the RPC port when it is active')
else
begin
RPCPort := value;
AddLineToDebugLog('console','RPC port set to: '+IntToStr(value));
S_AdvOpt := true;
end;
End;
Procedure setRPCpassword(newpassword:string);
var
counter : integer;
oldpassword : string;
Begin
oldpassword := RPCPass;
trim(newpassword);
RPCPass := newpassword;
End;
// Turn on RPC server
Procedure SetRPCOn();
Begin
if not Form1.RPCServer.Active then
begin
TRY
Form1.RPCServer.Bindings.Clear;
Form1.RPCServer.DefaultPort:=RPCPort;
Form1.RPCServer.Active:=true;
G_Launching := true;
form1.CB_RPC_ON.Checked:=true;
G_Launching := false;
AddLineToDebugLog('console','RPC server ENABLED');
EXCEPT on E:Exception do
begin
AddLineToDebugLog('console','Unable to start RPC port');
G_Launching := true;
form1.CB_RPC_ON.Checked:=false;
G_Launching := false;
end;
END; {TRY}
end
else AddLineToDebugLog('console','RPC server already ENABLED');
End;
// Turns off RPC server
Procedure SetRPCOff();
Begin
if Form1.RPCServer.Active then
begin
Form1.RPCServer.Active:=false;
AddLineToDebugLog('console','RPC server DISABLED');
G_Launching := true;
form1.CB_RPC_ON.Checked:=false;
G_Launching := false;
end
else AddLineToDebugLog('console','RPC server already DISABLED');
End;
// ***************************
// *** RPC PARSE FUNCTIONS ***
// ***************************
// Returns if a string is a valid JSON data
function IsValidJSON (MyJSONstring:string):boolean;
var
MyData: TJSONData;
begin
result := true;
Try
MyData := GetJSON(MyJSONstring);
Mydata.free;
except on E:ejsonparser do
result := false;
end;
end;
// Returns the string of each error code
Function GetJSONErrorString(ErrorCode:integer):string;
Begin
if ErrorCode = 400 then result := 'Bad Request'
else if ErrorCode = 401 then result := 'Invalid JSON request'
else if ErrorCode = 402 then result := 'Invalid method'
else if ErrorCode = 407 then result := 'Send funds failed'
else if ErrorCode = 498 then result := 'Not authorized'
else if ErrorCode = 499 then result := 'Unexpected error'
{...}
else result := 'Unknown error code';
End;
// Returns a valid error JSON String
function GetJSONErrorCode(ErrorCode, JSONIdNumber:integer):string;
var
JSONResultado,JSONErrorObj: TJSONObject;
Begin
result := '';
JSONResultado := TJSONObject.Create;
JSONErrorObj := TJSONObject.Create;
TRY
JSONResultado.Add('jsonrpc', TJSONString.Create('2.0'));
JSONErrorObj.Add('code', TJSONIntegerNumber.Create(ErrorCode));
JSONErrorObj.Add('message', TJSONString.Create(GetJSONErrorString(ErrorCode)));
JSONResultado.Add('error',JSONErrorObj);
JSONResultado.Add('id', TJSONIntegerNumber.Create(JSONIdNumber));
EXCEPT ON E:Exception do
AddLineToDebugLog('exceps',FormatDateTime('dd mm YYYY HH:MM:SS.zzz', Now)+' -> '+'Error on GetJSONErrorCode: '+E.Message)
END; {TRY}
result := JSONResultado.AsJSON;
JSONResultado.Free;
End;
// Returns a valid response JSON string
function GetJSONResponse(ResultToSend:string;JSONIdNumber:integer):string;
var
JSONResultado, Resultado: TJSONObject;
paramsarray : TJSONArray;
myParams: TStringArray;
counter : integer;
Errored : boolean = false;
Begin
result := '';
paramsarray := TJSONArray.Create;
if length(ResultToSend)>0 then myParams:= ResultToSend.Split(' ');
JSONResultado := TJSONObject.Create;
TRY
JSONResultado.Add('jsonrpc', TJSONString.Create('2.0'));
if length(myparams) > 0 then
for counter := low(myParams) to high(myParams) do
if myParams[counter] <>'' then
begin
paramsarray.Add(GetJSON(ObjectFromString(myParams[counter])));
end;
SetLength(MyParams, 0);
JSONResultado.Add('result', paramsarray);
JSONResultado.Add('id', TJSONIntegerNumber.Create(JSONIdNumber));
EXCEPT ON E:Exception do
begin
result := GetJSONErrorCode(499,JSONIdNumber);
JSONResultado.Free;
paramsarray.Free;
Errored := true;
AddLineToDebugLog('exceps',FormatDateTime('dd mm YYYY HH:MM:SS.zzz', Now)+' -> '+'Error on GetJSONResponse: '+E.Message);
end;
END; {TRY}
if not errored then result := JSONResultado.AsJSON;
JSONResultado.Free;
End;
function ObjectFromString(MyString:string): string;
var
resultado: TJSONObject;
orderobject : TJSONObject;
objecttype : string;
blockorders, Newaddresses : integer;
ordersarray : TJSONArray;
counter : integer;
Begin
resultado := TJSONObject.Create;
MyString := StringReplace(MyString,#127,' ',[rfReplaceAll, rfIgnoreCase]);
objecttype := parameter(mystring,0);
if objecttype = 'test' then
begin
resultado.Add('result','testok');
end
else if objecttype = 'balance' then
begin
resultado.Add('valid',StrToBool(parameter(mystring,1)));
resultado.Add('address', TJSONString.Create(parameter(mystring,2)));
if parameter(mystring,3)='null' then resultado.Add('alias',TJSONNull.Create)
else resultado.Add('alias',parameter(mystring,3));
resultado.Add('balance', TJSONInt64Number.Create(StrToInt64(parameter(mystring,4))));
resultado.Add('incoming', TJSONInt64Number.Create(StrToInt64(parameter(mystring,5))));
resultado.Add('outgoing', TJSONInt64Number.Create(StrToInt64(parameter(mystring,6))));
end
else if objecttype = 'orderinfo' then
begin
resultado.Add('valid',StrToBool(parameter(mystring,1)));
if StrToBool(parameter(mystring,1)) then
begin
orderobject := TJSONObject.Create;
orderobject.Add('orderid',parameter(mystring,2));
orderobject.Add('timestamp',StrToInt64(parameter(mystring,3)));
orderobject.Add('block',StrToInt64(parameter(mystring,4)));
orderobject.Add('type',parameter(mystring,5));
orderobject.Add('trfrs',StrToInt(parameter(mystring,6)));
orderobject.Add('receiver',parameter(mystring,7));
orderobject.Add('amount',StrToInt64(parameter(mystring,8)));
orderobject.Add('fee',StrToInt64(parameter(mystring,9)));
if parameter(mystring,10)='null' then orderobject.Add('reference',TJSONNull.Create)
else orderobject.Add('reference',parameter(mystring,10));
orderobject.Add('sender',parameter(mystring,11));
resultado.Add('order',orderobject)
end
else resultado.Add('order',TJSONNull.Create)
end
else if objecttype = 'blockinfo' then
begin
resultado.Add('valid',StrToBool(parameter(mystring,1)));
resultado.Add('number',StrToIntDef(parameter(mystring,2),-1));
resultado.Add('timestart',StrToInt64Def(parameter(mystring,3),-1));
resultado.Add('timeend',StrToInt64Def(parameter(mystring,4),-1));
resultado.Add('timetotal',StrToIntDef(parameter(mystring,5),-1));
resultado.Add('last20',StrToIntDef(parameter(mystring,6),-1));
resultado.Add('totaltransactions',StrToIntDef(parameter(mystring,7),-1));
resultado.Add('difficulty',StrToIntDef(parameter(mystring,8),-1));
resultado.Add('target',parameter(mystring,9));
resultado.Add('solution',parameter(mystring,10));
resultado.Add('lastblockhash',parameter(mystring,11));
resultado.Add('nextdifficult',StrToIntDef(parameter(mystring,12),-1));
resultado.Add('miner',parameter(mystring,13));
resultado.Add('feespaid',StrToInt64Def(parameter(mystring,14),-1));
resultado.Add('reward',StrToInt64Def(parameter(mystring,15),-1));
resultado.Add('hash',parameter(mystring,16));
end
else if objecttype = 'mininginfo' then
begin
resultado.Add('block',StrToInt(parameter(mystring,1)));
resultado.Add('target',parameter(mystring,2));
resultado.Add('miner',parameter(mystring,3));
resultado.Add('diff',parameter(mystring,4));
resultado.Add('hash',parameter(mystring,5));
end
else if objecttype = 'pendingorders' then
begin
counter := 1;
ordersarray := TJSONArray.Create;
while parameter(mystring,counter) <> '' do
begin
ordersarray.Add(parameter(mystring,counter));
Inc(Counter);
end;
resultado.Add('pendings',ordersarray);
end
else if objecttype = 'peers' then
begin
counter := 1;
ordersarray := TJSONArray.Create;
while parameter(mystring,counter) <> '' do
begin
ordersarray.Add(parameter(mystring,counter));
Inc(Counter);
end;
resultado.Add('peers',ordersarray);
end
else if objecttype = 'mainnetinfo' then
begin
resultado.Add('lastblock',StrToIntDef(parameter(mystring,1),0));
resultado.Add('lastblockhash',parameter(mystring,2));
resultado.Add('headershash',parameter(mystring,3));
resultado.Add('sumaryhash',parameter(mystring,4));
resultado.Add('pending',StrToInt(parameter(mystring,5)));
resultado.Add('supply',StrToInt64Def(parameter(mystring,6),0));
end
else if objecttype = 'blockorder' then
begin
resultado.Add('valid',StrToBool(parameter(mystring,1)));
resultado.Add('block',StrToIntDef(parameter(mystring,2),-1));
blockorders := StrToIntDef(parameter(mystring,3),0);
ordersarray := TJSONArray.Create;
if blockorders>0 then
begin
for counter := 0 to blockorders-1 do
begin
orderobject:=TJSONObject.Create;
orderobject.Add('orderid',parameter(mystring,4+(counter*10)));
orderobject.Add('timestamp',StrToIntDef(parameter(mystring,5+(counter*10)),0));
orderobject.Add('block',StrToIntDef(parameter(mystring,6+(counter*10)),0));
orderobject.Add('type',parameter(mystring,7+(counter*10)));
orderobject.Add('trfrs',StrToIntDef(parameter(mystring,8+(counter*10)),0));
orderobject.Add('receiver',parameter(mystring,9+(counter*10)));
orderobject.Add('amount',StrToInt64Def(parameter(mystring,10+(counter*10)),0));
orderobject.Add('fee',StrToIntDef(parameter(mystring,11+(counter*10)),0));
orderobject.Add('reference',parameter(mystring,12+(counter*10)));
orderobject.Add('sender',parameter(mystring,13+(counter*10)));
ordersarray.Add(orderobject);
end;
end;
resultado.Add('orders',ordersarray);
end
else if objecttype = 'blockmns' then
begin
resultado.Add('valid',StrToBool(parameter(mystring,1)));
resultado.Add('block',StrToIntDef(parameter(mystring,2),-1));
resultado.Add('count',StrToIntDef(parameter(mystring,3),-1));
resultado.Add('reward',StrToInt64Def(parameter(mystring,4),-1));
resultado.Add('total',StrToInt64Def(parameter(mystring,5),-1));
resultado.Add('addresses',parameter(mystring,6));
end
else if objecttype = 'newaddress' then
begin
//resultado.Add('valid',StrToBool(parameter(mystring,1)));
Newaddresses := StrToIntDef(parameter(mystring,2),1);
//resultado.Add('number',Newaddresses);
ordersarray := TJSONArray.Create;
for counter := 1 to Newaddresses do
begin
ordersarray.Add(parameter(mystring,2+counter));
end;
resultado.Add('addresses',ordersarray);
end
else if objecttype = 'sendfunds' then
begin
if parameter(mystring,1) = 'ERROR' then
begin
resultado.Add('valid',false);
resultado.add('result',StrToIntDef(parameter(mystring,2),-1));
end
else
begin
resultado.Add('valid',True);
resultado.Add('result',parameter(mystring,1));
end
end
else if objecttype = 'islocaladdress' then
begin
resultado.Add('result',StrToBool(parameter(mystring,1)))
end;
result := resultado.AsJSON;
resultado.free;
End;
// Parses a incoming JSON string
function ParseRPCJSON(jsonreceived:string):string;
var
jData : TJSONData;
jObject : TJSONObject;
method : string;
params: TJSONArray;
jsonID : integer;
NosoPParams: String = '';
counter : integer;
Begin
Result := '';
if not IsValidJSON(jsonreceived) then result := GetJSONErrorCode(401,-1)
else
begin
jData := GetJSON(jsonreceived);
try
jObject := TJSONObject(jData);
method := jObject.Strings['method'];
params := jObject.Arrays['params'];
jsonid := jObject.Integers['id'];
for counter := 0 to params.Count-1 do
NosoPParams:= NosoPParams+' '+params[counter].AsString;
NosoPParams:= Trim(NosoPParams);
//AddLineToDebugLog('console',jsonreceived);
//AddLineToDebugLog('console','NosoPParams: '+NosoPParams);
if method = 'test' then result := GetJSONResponse('test',jsonid)
else if method = 'getaddressbalance' then result := GetJSONResponse(RPC_AddressBalance(NosoPParams),jsonid)
else if method = 'getorderinfo' then result := GetJSONResponse(RPC_OrderInfo(NosoPParams),jsonid)
else if method = 'getblocksinfo' then result := GetJSONResponse(RPC_Blockinfo(NosoPParams),jsonid)
else if method = 'getmininginfo' then result := GetJSONResponse(RPC_Mininginfo(NosoPParams),jsonid)
else if method = 'getmainnetinfo' then result := GetJSONResponse(RPC_Mainnetinfo(NosoPParams),jsonid)
else if method = 'getpendingorders' then result := GetJSONResponse(RPC_PendingOrders(NosoPParams),jsonid)
else if method = 'getpeers' then result := GetJSONResponse(RPC_GetPeers(NosoPParams),jsonid)
else if method = 'getblockorders' then result := GetJSONResponse(RPC_BlockOrders(NosoPParams),jsonid)
else if method = 'getblockmns' then result := GetJSONResponse(RPC_BlockMNs(NosoPParams),jsonid)
else if method = 'getnewaddress' then result := GetJSONResponse(RPC_NewAddress(NosoPParams),jsonid)
else if method = 'islocaladdress' then result := GetJSONResponse(RPC_ValidateAddress(NosoPParams),jsonid)
else if method = 'sendfunds' then result := GetJSONResponse(RPC_SendFunds(NosoPParams),jsonid)
else result := GetJSONErrorCode(402,-1);
Except on E:Exception do
AddLineToDebugLog('exceps',FormatDateTime('dd mm YYYY HH:MM:SS.zzz', Now)+' -> '+'JSON RPC error: '+E.Message);
end;
jData.Free;
end;
End;
// GET DATA FUNCTIONS
function RPC_AddressBalance(NosoPParams:string):string;
var
ThisAddress: string;
counter : integer = 0;
Balance, incoming, outgoing : int64;
addalias : string = '';
sumposition : integer = 0;
valid : string;
LRecord : TSummaryData;
Begin
result := '';
if NosoPParams <> '' then
begin
Repeat
ThisAddress := parameter(NosoPParams,counter);
if ThisAddress<> '' then
begin
if IsValidHashAddress(ThisAddress) then sumposition := GetIndexPosition(ThisAddress,LRecord)
else
begin
sumposition := GetIndexPosition(ThisAddress,LRecord,true);
ThisAddress := LRecord.Hash;
end;
if ThisAddress <>'' then
begin
if sumposition<0 then
begin
balance :=-1;incoming := -1;outgoing := -1;
addalias := 'null'; valid := 'false';
end
else
begin
Balance := GetAddressBalanceIndexed(ThisAddress);
incoming := GetAddressIncomingpays(ThisAddress);
outgoing := GetAddressPendingPays(ThisAddress);
addalias := LRecord.Custom;
if addalias = '' then addalias := 'null';
valid := 'true';
end;
result := result+format('balance'#127'%s'#127'%s'#127'%s'#127'%d'#127'%d'#127'%d ',[valid,ThisAddress,addalias,balance,incoming,outgoing]);
end;
end;
counter+=1;
until ThisAddress = '';
trim(result);
end;
End;
function RPC_OrderInfo(NosoPParams:string):string;
var
thisOr : TOrderGroup;
validID : string = 'true';
Begin
AddLineToDebugLog('events',TimeToStr(now)+'GetOrderDetails requested: '+NosoPParams);
NosoPParams := Trim(NosoPParams);
ThisOr := Default(TOrderGroup);
if NosoPParams='' then
begin
validID := 'false';
result := format('orderinfo'#127'%s'#127'%s'#127+
'%d'#127'%d'#127'%s'#127+
'%d'#127'%s'#127'%d'#127+
'%d'#127'%s'#127'%s'#127,
[validid,NosoPParams,
thisor.timestamp,thisor.block,thisor.OrderType,
thisor.OrderLines,thisor.Receiver,thisor.AmmountTrf,
thisor.AmmountFee,thisor.reference,thisor.sender]);
exit;
end;
thisor := GetOrderDetails(NosoPParams);
if thisor.OrderID = '' then validID := 'false';
result := format('orderinfo'#127'%s'#127'%s'#127+
'%d'#127'%d'#127'%s'#127+
'%d'#127'%s'#127'%d'#127+
'%d'#127'%s'#127'%s'#127,
[validid,NosoPParams,
thisor.timestamp,thisor.block,thisor.OrderType,
thisor.OrderLines,thisor.Receiver,thisor.AmmountTrf,
thisor.AmmountFee,thisor.reference,thisor.sender]);
End;
function RPC_Blockinfo(NosoPParams:string):string;
var
thisblock : string;
counter : integer = 0;
Begin
result := '';
if NosoPParams <> '' then
begin
Repeat
thisblock := parameter(NosoPParams,counter);
if thisblock <>'' then
begin
if ((StrToIntDef(thisblock,-1)>=0) and (StrToIntDef(thisblock,-1)<=MyLastblock)) then
begin
result := result+'blockinfo'#127'true'#127+GetBlockHeaders(StrToIntDef(thisblock,-1))+' ';
end
else result := result+'blockinfo'#127'false'#127+thisblock+#127'-1'#127'-1'#127'-1'#127'-1'#127'-1'#127'-1'#127'-1'#127'null'#127'null'#127'null'#127'-1'#127'null'#127'-1'#127'-1'#127'null ';
end;
counter+=1;
until thisblock = '';
trim(result);
end;
End;
function RPC_Mininginfo(NosoPParams:string):string;
Begin
result := format('mininginfo'#127'%d'#127'%s'#127'%s'#127'%s'#127'%s'#127,[mylastblock+1,MyLastBlockHash,GetNMSData.miner,GetNMSData.Diff, GetNMSData.Hash]);
//AddLineToDebugLog('console','Resultado:'+result);
End;
function RPC_Mainnetinfo(NosoPParams:string):string;
Begin
result := format('mainnetinfo'#127'%s'#127'%s'#127'%s'#127'%s'#127'%s'#127'%d',
[GetConsensus(2),Copy(GetConsensus(10),0,5),copy(GetConsensus(15),0,5),copy(GetConsensus(17),0,5),
GetConsensus(3),GetSupply(StrToIntDef(GetConsensus(2),0))]);
End;
function RPC_PendingOrders(NosoPParams:string):string;
var
LData : String;
Begin
LData :=PendingRawInfo;
LData := StringReplace(LData,' ',#127,[rfReplaceAll, rfIgnoreCase]);
result := format('pendingorders'#127'%s',[LData]);
End;
function RPC_GetPeers(NosoPParams:string):string;
var
LData : String;
Begin
LData := GetConnectedPeers;
LData := StringReplace(LData,' ',#127,[rfReplaceAll, rfIgnoreCase]);
result := format('peers'#127'%s',[LData]);
End;
function RPC_BlockOrders(NosoPParams:string):string;
var
blocknumber : integer;
ArraTrxs : TBlockOrdersArray;
counter : integer;
Thisorderinfo : string;
arrayOrds : array of TOrderGroup;
Procedure AddOrder(order:TOrderData);
var
cont : integer;
existed : boolean = false;
begin
if length(arrayOrds)>0 then
begin
for cont := 0 to length(arrayOrds)-1 do
begin
if arrayords[cont].OrderID = order.OrderID then
begin
arrayords[cont].AmmountTrf:=arrayords[cont].AmmountTrf+order.AmmountTrf;
arrayords[cont].AmmountFee:=arrayords[cont].AmmountFee+order.AmmountFee;
arrayords[cont].sender :=arrayords[cont].sender+
format('[%s,%d,%d]',[order.Address,order.AmmountTrf,order.AmmountFee]);
arrayords[cont].OrderLines+=1;
existed := true;
break;
end;
end;
end;
if not Existed then
begin
setlength(arrayords,length(arrayords)+1);
arrayords[length(arrayords)-1].OrderID:=order.OrderID;
arrayords[length(arrayords)-1].TimeStamp:=order.TimeStamp;
arrayords[length(arrayords)-1].Block:=order.Block;
arrayords[length(arrayords)-1].OrderType:=order.OrderType;
arrayords[length(arrayords)-1].OrderLines:=1;
arrayords[length(arrayords)-1].Receiver:=order.Receiver;
arrayords[length(arrayords)-1].AmmountTrf:=order.AmmountTrf;
arrayords[length(arrayords)-1].AmmountFee:=order.AmmountFee;
arrayords[length(arrayords)-1].Reference:=order.Reference;
if order.OrderLines=1 then
arrayords[length(arrayords)-1].sender:=order.sender
else arrayords[length(arrayords)-1].sender:=arrayords[length(arrayords)-1].sender+
format('[%s,%d,%d]',[order.Address,order.AmmountTrf,order.AmmountFee]);
end;
end;
Begin
result := '';
setlength(arrayOrds,0);
blocknumber := StrToIntDef(NosoPParams,-1);
if ((blocknumber<0) or (blocknumber>MyLastblock)) then
result := 'blockorder'#127'false'#127+NosoPParams+#127'0'
else
begin
ArraTrxs := GetBlockTrxs(BlockNumber);
result := 'blockorder'#127'true'#127+NosoPParams+#127;
if length(ArraTrxs) > 0 then
begin
for counter := 0 to length(ArraTrxs)-1 do
AddOrder(ArraTrxs[counter]);
result := result+IntToStr(length(arrayOrds))+#127;
for counter := 0 to length(arrayOrds)-1 do
begin
thisorderinfo := format('%s'#127'%d'#127'%d'#127'%s'#127'%d'#127'%s'#127'%d'#127'%d'#127'%s'#127'%s'#127,
[ arrayOrds[counter].OrderID,arrayOrds[counter].TimeStamp,arrayOrds[counter].Block,
arrayOrds[counter].OrderType,arrayOrds[counter].OrderLines,arrayOrds[counter].Receiver,
arrayOrds[counter].AmmountTrf,arrayOrds[counter].AmmountFee,arrayOrds[counter].Reference,
arrayOrds[counter].sender]);
result := result+thisorderinfo;
end;
end
else result := result+'0'#127;
trim(result);
end;
End;
function RPC_Blockmns(NosoPParams:string):string;
var
blocknumber : integer;
ArrayMNs : BlockArraysPos;
MNsReward : int64;
MNsCount, Totalpaid : int64;
counter : integer;
AddressesString : string = '';
Begin
result := '';
blocknumber := StrToIntDef(NosoPParams,-1);
if ((blocknumber<48010) or (blocknumber>MyLastblock)) then
result := 'blockmns'#127'false'#127+NosoPParams+#127'0'#127'0'#127'0'
else
begin
ArrayMNs := GetBlockMNs(blocknumber);
MNsReward := StrToInt64Def(ArrayMNs[length(ArrayMNs)-1].address,0);
SetLength(ArrayMNs,length(ArrayMNs)-1);
MNSCount := length(ArrayMNs);
TotalPAid := MNSCount * MNsReward;
for counter := 0 to MNsCount-1 do
AddressesString := AddressesString+ArrayMNs[counter].address+' ';
AddressesString := Trim(AddressesString);
AddressesString := StringReplace(AddressesString,' ',',',[rfReplaceAll, rfIgnoreCase]);
result := 'blockmns'#127'true'#127+blocknumber.ToString+#127+MNSCount.ToString+#127+
MNsReward.ToString+#127+TotalPAid.ToString+#127+AddressesString;
end;
End;
function RPC_NewAddress(NosoPParams:string):string;
var
TotalNumber : integer;
counter : integer;
NewAddress : WalletData;
PubKey,PriKey : string;
Begin
TotalNumber := StrToIntDef(NosoPParams,1);
if TotalNumber > 100 then TotalNumber := 100;
//AddLineToDebugLog('console','TotalNewAddresses: '+IntToStr(TotalNumber));
result := 'newaddress'#127'true'#127+IntToStr(TotalNumber)+#127;
for counter := 1 to totalnumber do
begin
SetLength(ListaDirecciones,Length(ListaDirecciones)+1);
NewAddress := Default(WalletData);
NewAddress.Hash:=GenerateNewAddress(PubKey,PriKey);
NewAddress.PublicKey:=pubkey;
NewAddress.PrivateKey:=PriKey;
ListaDirecciones[Length(ListaDirecciones)-1] := NewAddress;
if RPCSaveNew then SaveWalletBak(NewAddress);
Result := result+NewAddress.Hash+#127;
end;
trim(result);
S_Wallet := true;
U_DirPanel := true;
//AddLineToDebugLog('console',result);
End;
Function RPC_ValidateAddress(NosoPParams:string):string;
Begin
If ValidateAddressOnDisk(Parameter(NosoPParams,0)) then
result := 'islocaladdress'#127'True'
else result := 'islocaladdress'#127'False';
End;
function RPC_SendFunds(NosoPParams:string):string;
var
destination, reference : string;
amount : int64;
resultado : string;
ErrorCode : integer;
Begin
destination := Parameter(NosoPParams,0);
amount := StrToInt64Def(Parameter(NosoPParams,1),0);
reference := Parameter(NosoPParams,2); if reference = '' then reference := 'null';
//AddLineToDebugLog('console','Send to '+destination+' '+int2curr(amount)+' with reference: '+reference);
Resultado := SendFunds('sendto '+destination+' '+IntToStr(amount)+' '+Reference);
if ( (Resultado <>'') and (Parameter(Resultado,0)<>'ERROR') and (copy(resultado,0,2)='OR')) then
begin
result := 'sendfunds'#127+resultado;
end
else if (Parameter(Resultado,0)='ERROR') then
begin
ErrorCode := StrToIntDef(Parameter(Resultado,1),0);
result := 'sendfunds'#127+'ERROR'#127+IntToStr(ErrorCode);
end
else
begin
result := 'sendfunds'#127+'ERROR'#127+'999';
end;
End;
END. // END UNIT
|
unit uConstanta;
interface
uses Windows, SysUtils, Classes, Messages;
const
// core
CONFIG_FILE = 'config.ini';
DB_HO = 'DBHO';
DB_STORE = 'DBSTORE';
DEBUG = 'DEBUG';
REFRESH_SERVER = 'REFRESH_SERVER';
LOCAL_CLIENT = 'LOCAL_CLIENT';
PATH_FILE_NOTA = 'PATH_FILE_NOTA';
PATH_TEMPLATE = 'PATH_REPORT';
// error message
ER_EMPTY = ' Tidak Boleh Kosong';
ER_EXIST = ' Sudah Ada';
ER_STOPPED = 'Process stopped. ';
ER_PO_IS_NOT_EXIST = 'Nomor PO Tida Ditemukan!';
ER_INSERT_FAILED = 'Gagal Menyimpan Data';
ER_UPDATE_FAILED = 'Gagal Mengubah Data';
ER_DELETE_FAILED = 'Gagal Menghapus Data';
ER_QUERY_FAILED = 'Gagal Eksekusi Query';
ER_SP_FAILED = 'Gagal Eksekusi Stored Procedure';
ER_QTY_NOT_ALLOWED = 'Qty Tidak Diperbolehkan';
ER_SO_NOT_SPECIFIC = '"Create SO for" must be specific.';
ER_BRG_NOT_SPECIFIC = 'Produk Harus Specific';
ER_SAVE_DO = 'Gagal Simpan DO';
ER_DO_BONUS = 'Gagal Simpan DO Bonus';
ER_SHIFT_NOT_FOUND = 'Shift name not found.';
ER_TRANSACT_NOT_FOUND = 'Transaction number not found.';
ER_FAILED_INSERT_PO_ASSGROS = 'Input PO from trader failed.';
ER_UNIT_NOT_SPECIFIC = 'Unit Belum Dipilih';
ER_COMPANY_NOT_SPECIFIC = 'Company Belum Dipilih';
ER_UNIT_OR_COMPANY_NOT_SPECIFIC = 'Company Atau Unit Belum Dipilih';
ER_NOT_FOUND = 'Tidak Ditemukan';
ER_TOTAL_ALLOCATION = 'Total Alokasi Harus 100';
ER_TAX_EXPIRED = 'Tax is Expired, Please Renew.';
ER_SUBSIDY_TELAH_DIGUNAKAN = 'Subsidy can not delete, because already used ';
ER_VIOLATION_FOREIGN_KEY = 'Could not delete data. It has already used';
ERR_CODE_VIOLATION=335544466;
ER_FISCAL_PERIODE_INACTIVE = 'Fiscal Periode Is Inactive';
// confirm
CONF_ADD_SUCCESSFULLY = 'Berhasil Menyimpan Data';
CONF_EDIT_SUCCESSFULLY = 'Berhasil Mengubah Data';
CONF_DELETE_SUCCESSFULLY = 'Berhasil Menghapus Data';
CONF_VALIDATE_SUCCESSFULLY = 'Berhasil Validasi';
CONF_COULD_NOT_EDIT = 'Data Tidak Bisa Diedit';
CONF_COULD_NOT_DELETE = 'Data Tidak Bisa Dihapus';
CONF_TOTAL_AGREEMENT = 'Total Agreement Tidak Cukup';
SAVE_DO_SUCCESSFULLY = 'DO saved successfully.';
SAVE_DO_EXPIRED = 'PO updated successfully.';
SAVE_SERVICE_LEVEL_SUCCESSFULLY = 'Service Level saved successfully.';
SAVE_CN_SUCCESSFULLY = 'Credit Note saved successfully.';
SAVE_DN_SUCCESSFULLY = 'Debit Note saved successfully.';
SAVE_RETUR_SUCCESSFULLY = 'Retur saved successfully.';
PRINT_NP_SUCCESSFULLY = 'NP printed successfully.';
PRINT_CN_SUCCESSFULLY = 'CN printed successfully.';
PRINT_DN_SUCCESSFULLY = 'DN printed successfully.';
PRINT_PAYMENT_RETUR_NOTA = 'Payment Retur Nota printed successfully.';
GENERATE_PO_SUCCESSFULLY = 'PO generated successfully.';
GENERATE_SYNC_SUCCESSFULLY = 'Synchronize generated successfully.';
GENERATE_SYNC_FINISH = 'Synchronize finish.';
GENERATE_SYNC_FINISH_WARNING = 'Export failed.';
IMPORT_SYNC_SUCCESSFULLY = 'Synchronizing is done successfully.';
IMPORT_SYNC_ERROR = 'Synchronizing is done with error.';
ACTIVATE_POS_SUCCESSFULLY = 'POS Activated successfully.';
PRODUCT_NOT_FOUND = 'Product not found.';
PRINT_DO_FOR_ASSGROS_SUCCESSFULLY = 'DO For Assgrss printed successfully.';
PO_APPROVED_SUCCESSFULLY = 'PO approved successfully';
PO_CHANGED_SUCCESSFULLY = 'PO changed successfully';
PO_CANCELLED_SUCCESSFULLY = 'PO canceled successfully';
// db
DEBUG_MODE_ON = true;
DEBUG_MODE_OFF = false;
// micellanious
CN_RECV_DESCRIPTION = 'CN Receive';
DN_RECV_DESCRIPTION = 'DN Receive';
PO_DESCRIPTION_EXPIRED = 'Valid Date was expired';
PO_DESCRIPTION_RECEIVED = 'Valid Date was received';
PO_DESCRIPTION_GENERATED = 'PO generated';
DO_DESCRIPTION_RECEIVED = 'Delivery Order was received';
TRANSACTION_NUMBER_CANT_BE_DELETED = 'Transaction could not be deleted';
TRANSACTION_NUMBER_CANT_BE_EDITED = 'Transaction could not be edited';
// BEGINNING BALANCE
BEGINNING_BALANCE_MODAL = 200000;
// loading caption
USER_MENU_LOADING = 'Please wait. Creating user menu ...';
USER_LOGIN_LOADING = 'Please wait. Authorizing user ...';
FORM_LOADING = 'Please wait. Form loading ...';
// button show message
BUTTON_CAPTION1 = 'Yes';
BUTTON_CAPTION2 = 'No';
BUTTON_CAPTION3 = 'Cancel';
MESSAGE_CAPTION = 'Head Office - ';
// sync
SYNC_LOCAL_DIR = 'sinkronisasi\sync\';
SYNC_XMLFILENAME = 'sync.xml';
REFERENCES_TABLE = 'references';
IGRA_TABLE = 'igra';
RECEIVING_TABLE = 'receiving';
SYNC_SESSION_FILE = '_session.xml';
//default number
INVOICE_NO = '/INV/MG/';
ACCRUAL_NO = '/ACR/MG/';
//Finance
AP_PAYMENT_DAY_1 = '3';
AP_PAYMENT_DAY_2 = '5'; {Note: 1 -> Sunday, 7 --> Saturday}
//Jurnal
CONF_JURNAL_ALREADY_POSTED = 'The Jurnal has already posted';
PROC_REVERSE_JOUNAL = 'Reverse Journal';
//Message Constant
STORE_PARAM = 2010;
GORO_MAIN_MESSAGE = WM_USER + 7251;
GORO_HO_MAIN_FORM_CHX_COMP_ID = GORO_MAIN_MESSAGE + 1;
GORO_HO_MAIN_FORM_CHX_UNIT_ID = GORO_MAIN_MESSAGE + 2;
TABLE_NODE = 'table';
RECORD_NODE = 'record';
TYPE_NODE = 'type';
SQL_NODE = 'sql';
ATT_RECORD_NODE = 'no';
DELIMITER_ASSIGN = '=';
DELIMITER_COMMA = ',';
INSERT_TYPE = 'insert';
UPDATE_TYPE = 'update';
DELETE_TYPE = 'delete';
// MESSAGE CONSTANTA
WM_REFRESH_SERVER_MESSAGE = WM_USER + 1000;
WM_STORE_MESSAGE = WM_USER + 2000;
STORE_POS_TRANS_BOTOL = STORE_PARAM + 1;
STORE_POS_TRANS_VOUCHER = STORE_PARAM + 2;
STORE_POS_RESET_CASHIER = STORE_PARAM + 3;
STORE_REFRESH_TRANS_BOTOL = STORE_PARAM + 4;
STORE_REFRESH_VOUCHER = STORE_PARAM + 5;
STORE_REFRESH_RESET_CASHIER = STORE_PARAM + 8;
REFRESH_SERVER_UP = STORE_PARAM + 6;
REFRESH_SERVER_DOWN = STORE_PARAM + 7;
// PO
LEAD_TIME = 7;
INT_MAX_ROW_PO = 20;
// LIST MEMBERSHIP
JENIS_BAYAR_KARTU_BARU = 'BIAYA KARTU BARU';
JENIS_BAYAR_PERPANJANGAN_KARTU = 'BIAYA PERPANJANGAN KARTU';
MSG_SUPPLIER = WM_USER + 200;
SUPLIER_REFRESH_UNIT = MSG_SUPPLIER + 1;
//Product
PROD_CODE_LENGTH = 6; //maximum 9 digit ya, integer safe
implementation
end.
|
unit TypeReestr_Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Ibase,TiCommonStyles, ExtCtrls, cxStyles, cxCustomData,
cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, dxBar,
dxBarExtItems, cxGridLevel, cxClasses, cxControls, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid,TiCommonProc;
type
TTypeReestrMainForm = class(TForm)
TypeReestrGridDBTableView: TcxGridDBTableView;
TypeReestrGridLevel: TcxGridLevel;
TypeReestrGrid: TcxGrid;
dxBarManager1: TdxBarManager;
SelectButton: TdxBarLargeButton;
ExitButton: TdxBarLargeButton;
TypeReestrGridDBTableViewDB_NameNotes: TcxGridDBColumn;
procedure ExitButtonClick(Sender: TObject);
procedure SelectButtonClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure TypeReestrGridDBTableViewDblClick(Sender: TObject);
private
PRes :Variant;
pLanguageIndex :Byte;
pStylesDM :TStyleDM;
PDb_Handle :TISC_DB_HANDLE;
public
constructor Create(AOwner:TComponent;Db_Handle:TISC_DB_HANDLE);reintroduce;
property Res:Variant read PRes;
end;
var
TypeReestrMainForm: TTypeReestrMainForm;
implementation
uses TypeReestr_DM;
{$R *.dfm}
constructor TTypeReestrMainForm.Create(AOwner:TComponent;Db_Handle:TISC_DB_HANDLE);
begin
inherited Create(AOwner);
PDb_Handle := Db_Handle;
TypeReestrDM := TTypeReestrDM.Create(AOwner,Db_Handle);
//******************************************************************************
pLanguageIndex := LanguageIndex;
Caption := GetConst('SpecialNotes',tcForm);
SelectButton.Caption := GetConst('Select',tcButton);
ExitButton.Caption := GetConst('Exit',tcButton);
//******************************************************************************
pStylesDM := TStyleDM.Create(Self);
TypeReestrGridDBTableView.Styles.StyleSheet := pStylesDM.GridTableViewStyleSheetDevExpress;
//******************************************************************************
TypeReestrDM.TypeReestrDSet.Close;
TypeReestrDM.TypeReestrDSet.SelectSQL.Text:='select * from TI_SP_TYPE_REESTR';
TypeReestrDM.TypeReestrDSet.Open;
end;
procedure TTypeReestrMainForm.ExitButtonClick(Sender: TObject);
begin
Close;
end;
procedure TTypeReestrMainForm.SelectButtonClick(Sender: TObject);
begin
PRes := VarArrayCreate([0,3], varVariant);
PRes[0] := TypeReestrDM.TypeReestrDSet['ID_TYPE_REESTR'];
PRes[1] := TypeReestrDM.TypeReestrDSet['NAME_TYPE_REESTR'];
ModalResult:=mrYes;
end;
procedure TTypeReestrMainForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
TypeReestrDM.Free;
end;
procedure TTypeReestrMainForm.TypeReestrGridDBTableViewDblClick(
Sender: TObject);
begin
SelectButton.Click;
end;
end.
|
unit Search;
{ data module for the rubicon search components and accompanying tables }
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
taRubicn, DB, DBTables, taPhase, ComCtrls, Wwdatsrc, Wwtable;
type
TmodSearch = class(TDataModule)
srcMatch: TDataSource;
rubMake: TMakeDictionary;
rubProgress: TMakeProgress;
rubSearch: TSearchDictionary;
tblWords: TTable;
tblMatch: TTable;
procedure MakeProcessField(Sender: TObject; Field: TField; Location: Longint);
procedure DuringSearch(Sender: TObject);
procedure modSearchCreate(Sender: TObject);
procedure modSearchDestroy(Sender: TObject);
procedure tblMatchLevelQuestGetText(Sender: TField; var Text: String;
DisplayText: Boolean);
procedure tblMatchLevelQuestSetText(Sender: TField;
const Text: String);
procedure tblMatchCalcFields(DataSet: TDataSet);
private
public
end;
var
modSearch: TmodSearch;
f:textfile;
implementation
uses common, Data, Browse, Lookup, Find;
{$R *.DFM}
{ adds question text to the word table for later searching:
1. moves to the question text record using the core passed in via Field (from question)
2. puts contents of blob field into a hidden rich edit on the Browse form
3. processes the words in the rich edit as a list }
procedure TmodSearch.MakeProcessField(Sender: TObject; Field: TField; Location: Longint);
var s : string;
sl : tStringList;
procedure mydelete(var s:string;i1,i2:integer);
begin
delete(s,i1,i2);
end;
begin
sl := tStringList.create;
if (Field.Name='wtblQuestionShort') or (Field.Name='wtblQuestionDescription') then begin
sl.add(field.asString);
rubMake.ProcessList(sl,Location, true);
end;
with modLookup.tblQstnText do
if (Field.Name='wtblQuestionCore') and
(Locate('Core;LangID', VarArrayOf([Field.AsInteger, 1]), [])) then begin
s := modLookup.tblQstnTextText.AsString;
WHILE pos('\PROTECT',UPPERCASE(S))>0 DO
mydelete(S,pos('\PROTECT',UPPERCASE(S)),8);
sl.add( s );
rubMake.ProcessList( sl, Location, True);
{frmLibrary.rtfWords.lines.clear;
frmLibrary.rtfWords.Lines.Add( modLookup.tblQstnTextText.AsString );
rubMake.ProcessList( frmLibrary.rtfWords.Lines, Location, True );}
end;
sl.free;
end;
{ supposed to allow for aborting a search, but only seems to be called at begin and end of
the search (documentation states called intermitently) }
procedure TmodSearch.DuringSearch(Sender: TObject);
begin
Application.ProcessMessages;
if frmFind.vAbort then with rubSearch do State := State + [ dsAbort ];
end;
procedure TmodSearch.modSearchCreate(Sender: TObject);
begin
try
tblMatch.databasename := aliaspath('PRIV');
except
tblmatch.databasename := 'c:\windows\temp';
end;
assignfile(f,'c:\protect.txt');
rewrite(f);
end;
procedure TmodSearch.modSearchDestroy(Sender: TObject);
begin
closefile(f);
deldotstar(tblmatch.databasename+'\Match.*');
end;
procedure TmodSearch.tblMatchLevelQuestGetText(Sender: TField;
var Text: String; DisplayText: Boolean);
begin
case sender.asinteger of
1 : text := 'Key';
2 : text := 'Core';
3 : text := 'Drill down';
4 : text := 'Behavioral';
else
text := 'No level defined';
end;
end;
procedure TmodSearch.tblMatchLevelQuestSetText(Sender: TField;
const Text: String);
begin
if uppercase(text) = 'KEY' then
sender.value := 1
else if uppercase(text) = 'CORE' then
sender.value := 2
else if uppercase(text) = 'DRILL DOWN' then
sender.value := 3
else if uppercase(text) = 'BEHAVIORAL' then
sender.value := 4
else
sender.value := 0;
end;
procedure TmodSearch.tblMatchCalcFields(DataSet: TDataSet);
begin
with modLookup do begin
DataSet[ 'Review' ] := ( tblQstnText.Locate( 'Core', tblMatch.fieldbyname('Core').Value, [ ] ) or
tblScaleText.Locate( 'Scale', tblMatch.fieldbyname('Scale').Value, [ ] ) or
tblHeadText.Locate( 'HeadID', tblMatch.fieldbyname('HeadID').Value, [ ] ));
with tblQstnText do begin
filter := 'LangID <> 1';
dataset[ 'Languages' ] := '';
if Locate( 'Core', tblMatch.fieldbyname('Core').Value, [ ] ) then
while (not eof) and (fieldbyname('Core').Value = tblMatch.fieldbyname('Core').Value) do begin
if modlibrary.tblLanguage.Locate( 'LangID', Fieldbyname('LangID').Value, [ ]) then
DataSet[ 'Languages' ] := DataSet[ 'Languages' ] + modLibrary.tblLanguageLanguage.AsString + ' '
else
DataSet[ 'Languages' ] := DataSet[ 'Languages' ] + '{' + Fieldbyname('LangID').AsString + '}';
next;
end;
filter := 'Review';
end;
end;
end;
end.
|
namespace VirtualProperties;
interface
uses
System.Windows.Forms,
System.Drawing,
VirtualProperties.VirtualPropertiesClasses;
type
MainForm = class(System.Windows.Forms.Form)
{$REGION Windows Form Designer generated fields}
private
button1: System.Windows.Forms.Button;
components: System.ComponentModel.Container := nil;
method button1_Click(sender: System.Object; e: System.EventArgs);
method InitializeComponent;
{$ENDREGION}
protected
method Dispose(aDisposing: Boolean); override;
public
constructor;
class method Main;
end;
implementation
{$REGION Construction and Disposition}
constructor MainForm;
begin
InitializeComponent();
end;
method MainForm.Dispose(aDisposing: boolean);
begin
if aDisposing then begin
if assigned(components) then
components.Dispose();
end;
inherited Dispose(aDisposing);
end;
{$ENDREGION}
{$REGION Windows Form Designer generated code}
method MainForm.InitializeComponent;
begin
var resources: System.ComponentModel.ComponentResourceManager := new System.ComponentModel.ComponentResourceManager(typeOf(MainForm));
self.button1 := new System.Windows.Forms.Button();
self.SuspendLayout();
//
// button1
//
self.button1.Location := new System.Drawing.Point(42, 45);
self.button1.Name := 'button1';
self.button1.Size := new System.Drawing.Size(150, 23);
self.button1.TabIndex := 0;
self.button1.Text := 'Test Virtual Property';
self.button1.Click += new System.EventHandler(@self.button1_Click);
//
// MainForm
//
self.ClientSize := new System.Drawing.Size(234, 112);
self.Controls.Add(self.button1);
self.FormBorderStyle := System.Windows.Forms.FormBorderStyle.FixedDialog;
self.Icon := (resources.GetObject('$this.Icon') as System.Drawing.Icon);
self.MaximizeBox := false;
self.Name := 'MainForm';
self.Text := 'VirtualProperties Sample';
self.ResumeLayout(false);
end;
{$ENDREGION}
{$REGION Application Entry Point}
[STAThread]
class method MainForm.Main;
begin
Application.EnableVisualStyles();
try
with lForm := new MainForm() do
Application.Run(lForm);
except
on E: Exception do begin
MessageBox.Show(E.Message);
end;
end;
end;
{$ENDREGION}
method MainForm.button1_Click(sender: System.Object; e: System.EventArgs);
var
//base: BaseClass;
first: FirstDescendant;
second: SecondDescendant;
begin
{ Cannot create this class because it has abstract properties }
//base := new BaseClass;
//base.Name := 'Jack';
first := new FirstDescendant;
first.Name := 'John';
MessageBox.Show('first.Name is '+first.Name);
second := new SecondDescendant;
second.Name := 'Claire';
MessageBox.Show('second.Name is '+(second as IHasName).Name);
end;
end. |
unit DAW.Tools;
interface
uses
System.Win.Registry;
type
TDawTools = class
private
class var
FAdbExe: string;
class function ReadFromRegAdbExe: string;
public
class function CompilerVersionToProduct(const AVer: Single): Integer;
class function AdbExe: string;
class function AdbPath: string;
class function GetInTag(AInput, AStartTag, AEndTag: string): TArray<string>;
class procedure SaveData(const AName, AValue: string);
class function LoadData(const AName: string): string;
end;
implementation
uses
Winapi.Windows,
System.Generics.Collections,
System.SysUtils;
{ TDawTools }
class function TDawTools.AdbExe: string;
begin
if not FileExists(FAdbExe) then
FAdbExe := ReadFromRegAdbExe;
Result := FAdbExe;
end;
class function TDawTools.AdbPath: string;
begin
Result := ExtractFilePath(AdbExe);
end;
class function TDawTools.CompilerVersionToProduct(const AVer: Single): Integer;
begin
if AVer < 30.0 then
raise Exception.Create('Unsupported IDE version.');
Result := Round(AVer) - 13;
end;
class function TDawTools.GetInTag(AInput, AStartTag, AEndTag: string): TArray<string>;
var
LData: TList<string>;
LInpCash: string;
var
start: Integer;
count: Integer;
ForAdd: string;
begin
LInpCash := AInput;
LData := TList<string>.Create;
try
while not LInpCash.IsEmpty do
begin
start := LInpCash.indexOf(AStartTag); // + ;
if start < 0 then
Break;
Inc(start, AStartTag.Length);
LInpCash := LInpCash.Substring(start);
count := LInpCash.indexOf(AEndTag);
if (count < 0) then
count := LInpCash.Length;
ForAdd := LInpCash.Substring(0, count);
LData.Add(ForAdd);
LInpCash := LInpCash.Substring(count);
end;
Result := LData.ToArray;
finally
LData.Free;
end;
end;
class function TDawTools.LoadData(const AName: string): string;
const
REG_KEY = '\Software\rareMax\DAW\';
var
Reg: TRegistry;
begin
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_CURRENT_USER;
if Reg.OpenKey(REG_KEY, False) then
Result := Reg.ReadString(AName);
finally
Reg.Free;
end;
end;
class function TDawTools.ReadFromRegAdbExe: string;
const
REG_KEY = '\Software\Embarcadero\BDS\%d.0\PlatformSDKs\';
var
Reg: TRegistry;
tmpVer: Integer;
tmpSdk: string;
begin
Result := 'Cant find path :(';
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_CURRENT_USER;
tmpVer := CompilerVersionToProduct(CompilerVersion);
if Reg.OpenKeyReadOnly(Format(REG_KEY, [tmpVer])) then
begin
tmpSdk := Reg.ReadString('Default_Android');
if Reg.OpenKeyReadOnly(tmpSdk) then
begin
Result := Reg.ReadString('SDKAdbPath');
end;
end;
finally
Reg.Free;
end;
end;
class procedure TDawTools.SaveData(const AName, AValue: string);
const
REG_KEY = '\Software\rareMax\DAW\';
var
Reg: TRegistry;
begin
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_CURRENT_USER;
if Reg.OpenKey(REG_KEY, True) then
Reg.WriteString(AName, AValue);
finally
Reg.Free;
end;
end;
end.
|
unit md4;
interface
uses SysUtils, Windows;
const
MD4_BLOCK_SIZE = 16 * 4;
MD4_LENGTH_SIZE = 2 * 4;
type
MD4State = record
A, B, C, D: cardinal;
end;
MD4Context = record
wwSize: int64;
wwRemSize: int64;
lpRemData: array[1..MD4_BLOCK_SIZE] of byte;
State: MD4State;
end;
MD4Digest = array[0..15] of byte;
procedure MD4Init(var Context: MD4Context);
procedure MD4Final(var Context: MD4Context; var Digest: MD4Digest);
procedure MD4Update(var Context: MD4Context; lpData: PAnsiChar; wwDataSize: int64);
function SameMd4(a, b: MD4Digest): boolean; inline;
function Md4ToString(md4: MD4Digest): string;
implementation
////////////////////////////////////////////////////////////////////////////////
type
MD4Block = array[0..15] of cardinal;
PMD4Block = ^MD4Block;
procedure MD4_ProcessBlock( lpX: pdword; var State: MD4State );
var OldState: MD4State;
X: PMD4Block;
function F(X, Y, Z: cardinal): cardinal;
begin
Result := (X and Y) or ((not X) and Z);
end;
function G(X, Y, Z: cardinal): cardinal;
begin
Result := (X and Y) or (X and Z) or (Z and Y);
end;
function H(X, Y, Z: cardinal): cardinal;
begin
Result := X xor Y xor Z;
end;
procedure S_1( var a, b, c, d: cardinal; k, s: byte );
begin
a := (a + F(b, c, d) + X^[k]);
a := ( a shl s ) or ( a shr (32-s) );
end;
procedure S_2( var a, b, c, d: cardinal; k, s: byte );
begin
a := (a + G(b, c, d) + X^[k] + $5A827999);
a := ( a shl s ) or ( a shr (32-s) );
end;
procedure S_3( var a, b, c, d: cardinal; k, s: byte );
begin
a := (a + H(b, c, d) + X^[k] + $6ED9EBA1);
a := ( a shl s ) or ( a shr (32-s) );
end;
begin
OldState := State;
X := PMD4Block(lpX);
with State do begin
//Round 1
S_1( A,B,C,D, 0, 3 );
S_1( D,A,B,C, 1, 7 );
S_1( C,D,A,B, 2, 11 );
S_1( B,C,D,A, 3, 19 );
S_1( A,B,C,D, 4, 3 );
S_1( D,A,B,C, 5, 7 );
S_1( C,D,A,B, 6, 11 );
S_1( B,C,D,A, 7, 19 );
S_1( A,B,C,D, 8, 3 );
S_1( D,A,B,C, 9, 7 );
S_1( C,D,A,B, 10, 11 );
S_1( B,C,D,A, 11, 19 );
S_1( A,B,C,D, 12, 3 );
S_1( D,A,B,C, 13, 7 );
S_1( C,D,A,B, 14, 11 );
S_1( B,C,D,A, 15, 19 );
//Round 2
S_2( A,B,C,D, 0, 3 );
S_2( D,A,B,C, 4, 5 );
S_2( C,D,A,B, 8, 9 );
S_2( B,C,D,A, 12, 13 );
S_2( A,B,C,D, 1, 3 );
S_2( D,A,B,C, 5, 5 );
S_2( C,D,A,B, 9, 9 );
S_2( B,C,D,A, 13, 13 );
S_2( A,B,C,D, 2, 3 );
S_2( D,A,B,C, 6, 5 );
S_2( C,D,A,B, 10, 9 );
S_2( B,C,D,A, 14, 13 );
S_2( A,B,C,D, 3, 3 );
S_2( D,A,B,C, 7, 5 );
S_2( C,D,A,B, 11, 9 );
S_2( B,C,D,A, 15, 13 );
// Round 3
S_3( A,B,C,D, 0, 3 );
S_3( D,A,B,C, 8, 9 );
S_3( C,D,A,B, 4, 11 );
S_3( B,C,D,A, 12, 15 );
S_3( A,B,C,D, 2, 3 );
S_3( D,A,B,C, 10, 9 );
S_3( C,D,A,B, 6, 11 );
S_3( B,C,D,A, 14, 15 );
S_3( A,B,C,D, 1, 3 );
S_3( D,A,B,C, 9, 9 );
S_3( C,D,A,B, 5, 11 );
S_3( B,C,D,A, 13, 15 );
S_3( A,B,C,D, 3, 3 );
S_3( D,A,B,C, 11, 9 );
S_3( C,D,A,B, 7, 11 );
S_3( B,C,D,A, 15, 15 );
end;
Inc(State.A, OldState.A);
Inc(State.B, OldState.B);
Inc(State.C, OldState.C);
Inc(State.D, OldState.D);
end;
////////////////////////////////////////////////////////////////////////////////
procedure MD4Init( var Context: MD4Context );
begin
with Context do begin
wwSize := 0;
wwRemSize := 0;
State.A := $67452301;
State.B := $EFCDAB89;
State.C := $98BADCFE;
State.D := $10325476;
end;
end;
procedure MD4Update( var Context: MD4Context; lpData: PAnsiChar; wwDataSize: int64 );
begin
with Context do begin
Inc(wwSize, wwDataSize);
//First pass - check if there's unused data from previous sessions
if( wwRemSize + wwDataSize >= MD4_BLOCK_SIZE )
and( wwRemSize > 0 )then begin
Dec( wwDataSize, MD4_BLOCK_SIZE-wwRemSize );
CopyMemory( @lpRemData[wwRemSize+1], lpData, MD4_BLOCK_SIZE - wwRemSize );
MD4_ProcessBlock( @lpRemData[1], State );
Inc( lpData, MD4_BLOCK_SIZE - wwRemSize );
wwRemSize := 0;
end;
//Further passes - use the data without copying
while( wwDataSize >= MD4_BLOCK_SIZE ) do begin
Dec( wwDataSize, MD4_BLOCK_SIZE );
MD4_ProcessBlock( pdword(lpData), State );
Inc( lpData, MD4_BLOCK_SIZE );
end;
//Save the remaining data for the next updates
if( wwDataSize > 0 )then begin
CopyMemory( @lpRemData[wwRemSize+1], lpData, wwDataSize );
wwRemSize := wwRemSize + wwDataSize;
end;
end;
end;
procedure MD4Final( var Context: MD4Context; var Digest: MD4Digest );
var dwRem: cardinal;
lpDta: array of byte;
begin
with Context do begin
//Calculate zeroes count
dwRem := (wwSize+1) mod MD4_BLOCK_SIZE;
if( dwRem <= MD4_BLOCK_SIZE - MD4_LENGTH_SIZE )then
dwRem := MD4_BLOCK_SIZE - MD4_LENGTH_SIZE - dwRem
else
dwRem := 2*MD4_BLOCK_SIZE - MD4_LENGTH_SIZE - dwRem;
//Create appendix array
SetLength( lpDta, 1+dwRem+MD4_LENGTH_SIZE );
lpDta[0] := $80;
ZeroMemory( @lpDta[1], dwRem );
pint64(@lpDta[1+dwRem])^ := wwSize*8; // Length in bits
//Process appendix array
MD4Update( Context, @lpDta[0], 1+dwRem+MD4_LENGTH_SIZE );
//Create digest
CopyMemory( @Digest[0], @State, sizeof(Digest) );
end;
end;
function SameMd4(a, b: MD4Digest): boolean; inline;
begin
Result := CompareMem(@a, @b, SizeOf(a));
end;
function Md4ToString(md4: MD4Digest): string;
var i: integer;
begin
Result := '';
for i := 0 to Length(md4) - 1 do
Result := Result + IntToHex(md4[i], 2);
end;
end.
|
unit CCJRMO_State;
{**********************************
* © PgkSoft 24.12.2015
* Журнал заказов редких лекарста
* Установка состояния заказа:
* - закрытие,
* - открытие
**********************************}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, ToolWin, ExtCtrls, ActnList, DB, ADODB;
type
TfrmCCJRMO_State = class(TForm)
pnlTop: TPanel;
pnlTop_Order: TPanel;
pnlTop_Price: TPanel;
pnlTop_Client: TPanel;
pnlTool: TPanel;
pnlTool_Bar: TPanel;
tlbarControl: TToolBar;
tlbtnOk: TToolButton;
tlbtnExit: TToolButton;
pnlTool_Show: TPanel;
pnlState: TPanel;
Label1: TLabel;
Label2: TLabel;
edFoundation: TEdit;
btnSlFoundation: TButton;
edOrderStatus: TEdit;
btnSlDrivers: TButton;
aMain: TActionList;
aMain_Ok: TAction;
aMain_Exit: TAction;
aMain_SlFoundation: TAction;
aMain_SlOrderStatus: TAction;
spFindStatus: TADOStoredProc;
spGetStateJRMO: TADOStoredProc;
spJRMOSetState: TADOStoredProc;
procedure FormCreate(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure aMain_OkExecute(Sender: TObject);
procedure aMain_ExitExecute(Sender: TObject);
procedure aMain_SlFoundationExecute(Sender: TObject);
procedure aMain_SlOrderStatusExecute(Sender: TObject);
procedure edFoundationChange(Sender: TObject);
procedure edOrderStatusChange(Sender: TObject);
private
{ Private declarations }
{ Private declarations }
ISignActive : integer;
Mode : integer;
ISignAllowTheActionOrder : smallint;
NRN : integer; { Номер заказа }
NUSER : integer;
OrderPrice : real;
OrderClient : string;
CodeAction : string;
procedure ShowGets;
procedure CheckStateOrder;
public
{ Public declarations }
procedure SetMode(Parm : integer);
procedure SetRN(Parm : integer);
procedure SetPrice(Parm : real);
procedure SetClient(Parm : string);
procedure SetUser(Parm : integer);
end;
var
frmCCJRMO_State: TfrmCCJRMO_State;
const
cJRMOStateOpen = 1; { Открытие заказа }
cJRMOStateClose = 2; { Закрытие заказа }
implementation
uses
Util,
UMain, UCCenterJournalNetZkz, UReference;
{$R *.dfm}
procedure TfrmCCJRMO_State.FormCreate(Sender: TObject);
begin
{ Инициализация }
ISignActive := 0;
Mode := 0;
ISignAllowTheActionOrder := 1;
NRN := 0;
NUSER := 0;
OrderPrice := 0;
OrderClient := '';
CodeAction := '';
end;
procedure TfrmCCJRMO_State.FormActivate(Sender: TObject);
var
SCaption : string;
begin
if ISignActive = 0 then begin
{ Инициализация }
case Mode of
cJRMOStateOpen: begin
CodeAction := 'JRMO_Open';
self.Caption := 'Открытие заказа';
FCCenterJournalNetZkz.imgMain.GetIcon(133,self.Icon)
end;
cJRMOStateClose: begin
CodeAction := 'JRMO_Close';
self.Caption := 'Закрытие заказа';
FCCenterJournalNetZkz.imgMain.GetIcon(134,self.Icon)
end;
else begin
ShowMessage('Незарегистрированный режим работы');
self.Close;
end;
end;
{ Отображаем реквизиты заказа }
SCaption := 'Заказ № ' + VarToStr(NRN);
pnlTop_Order.Caption := SCaption; pnlTop_Order.Width := TextPixWidth(SCaption, pnlTop_Order.Font) + 20;
SCaption := 'Сумма ' + VarToStr(OrderPrice);
pnlTop_Price.Caption := SCaption; pnlTop_Price.Width := TextPixWidth(SCaption, pnlTop_Price.Font) + 20;
SCaption := OrderClient;
pnlTop_Client.Caption := SCaption; pnlTop_Client.Width := TextPixWidth(SCaption, pnlTop_Client.Font) + 10;
{ Форма активна }
ISignActive := 1;
{ Контроль для многопользовательского режима }
CheckStateOrder;
{ Актуализация состояния элементов управления }
ShowGets;
end;
end;
procedure TfrmCCJRMO_State.ShowGets;
begin
if ISignActive = 1 then begin
{ Доступ к элементам управления }
if (length(edFoundation.Text) = 0)
or
(
(Mode = cJRMOStateClose) and
(length(edOrderStatus.Text) = 0)
)
then begin
aMain_Ok.Enabled := false;
end else begin
aMain_Ok.Enabled := true;
end;
{ Обязательные поля для ввода }
if (length(edFoundation.Text) = 0) then edFoundation.Color := TColor(clYellow) else edFoundation.Color := TColor(clWindow);
if (Mode = cJRMOStateClose) and (length(edOrderStatus.Text) = 0)
then edOrderStatus.Color := TColor(clYellow)
else edOrderStatus.Color := TColor(clWindow);
end;
end;
procedure TfrmCCJRMO_State.SetMode(Parm : integer); begin Mode := Parm; end;
procedure TfrmCCJRMO_State.SetRN(Parm : integer); begin NRN := Parm; end;
procedure TfrmCCJRMO_State.SetPrice(Parm : real); begin OrderPrice := Parm; end;
procedure TfrmCCJRMO_State.SetClient(Parm : string); begin OrderClient := Parm; end;
procedure TfrmCCJRMO_State.SetUser(Parm : integer); begin NUSER := Parm; end;
procedure TfrmCCJRMO_State.CheckStateOrder;
var
IErr : integer;
SErr : string;
SCloseDate : string;
begin
if (Mode = cJRMOStateClose) or (Mode = cJRMOStateOpen) then begin
ISignAllowTheActionOrder := 1;
spGetStateJRMO.Parameters.ParamValues['@Order'] := NRN;
spGetStateJRMO.ExecProc;
IErr := spGetStateJRMO.Parameters.ParamValues['@RETURN_VALUE'];
if IErr <> 0 then begin
SErr := spGetStateJRMO.Parameters.ParamValues['@SErr'];
ShowMessage(SErr);
ISignAllowTheActionOrder := 0;
self.Close;
end else begin
SCloseDate := spGetStateJRMO.Parameters.ParamValues['@SCloseDate'];
if (Mode = cJRMOStateClose) and (length(SCloseDate) <> 0) then begin
ShowMessage('Заказ уже находится в состоянии <Закрыт>');
ISignAllowTheActionOrder := 0;
self.Close;
end else
if (Mode = cJRMOStateOpen) and (length(SCloseDate) = 0) then begin
ShowMessage('Заказ уже находится в состоянии <Открыт>');
ISignAllowTheActionOrder := 0;
self.Close;
end;
end;
end;
end;
procedure TfrmCCJRMO_State.aMain_OkExecute(Sender: TObject);
var
IErr : integer;
SErr : string;
begin
{ Контроль для многопользовательского режима }
CheckStateOrder;
if ISignAllowTheActionOrder = 1 then begin
if MessageDLG('Подтвердите выполнение действия',mtConfirmation,[mbYes,mbNo],0) = mrNo then exit;
try
spJRMOSetState.Parameters.ParamValues['@Order'] := NRN;
spJRMOSetState.Parameters.ParamValues['@CodeAction'] := CodeAction;
spJRMOSetState.Parameters.ParamValues['@USER'] := NUSER;
spJRMOSetState.Parameters.ParamValues['@Foundation'] := edFoundation.Text;
spJRMOSetState.Parameters.ParamValues['@StatusName'] := edOrderStatus.Text;
spJRMOSetState.ExecProc;
IErr := spJRMOSetState.Parameters.ParamValues['@RETURN_VALUE'];
if IErr <> 0 then begin
SErr := spJRMOSetState.Parameters.ParamValues['@SErr'];
ShowMessage(SErr);
end else begin
self.Close;
end;
except
on e:Exception do begin
ShowMessage(e.Message);
end;
end;
end;
end;
procedure TfrmCCJRMO_State.aMain_ExitExecute(Sender: TObject);
begin
self.Close;
end;
procedure TfrmCCJRMO_State.aMain_SlFoundationExecute(Sender: TObject);
var
DescrSelect : string;
begin
try
frmReference := TfrmReference.Create(Self);
frmReference.SetMode(cFReferenceModeSelect);
frmReference.SetReferenceIndex(cFReferenceActionFoundation);
try
frmReference.ShowModal;
DescrSelect := frmReference.GetDescrSelect;
if length(DescrSelect) > 0 then edFoundation.Text := DescrSelect;
finally
frmReference.Free;
end;
except
end;
end;
procedure TfrmCCJRMO_State.aMain_SlOrderStatusExecute(Sender: TObject);
var
DescrSelect : string;
begin
try
frmReference := TfrmReference.Create(Self);
frmReference.SetMode(cFReferenceModeSelect);
frmReference.SetReferenceIndex(cFReferenceOrderStatus);
frmReference.SetReadOnly(cFReferenceNoReadOnly);
try
frmReference.ShowModal;
DescrSelect := frmReference.GetDescrSelect;
if length(DescrSelect) > 0 then edOrderStatus.Text := DescrSelect;
finally
frmReference.Free;
end;
except
end;
end;
procedure TfrmCCJRMO_State.edFoundationChange(Sender: TObject);
var
RnStatus : integer;
IErr : integer;
SErr : string;
begin
{ Поиск аналогичного наименования статуса заказа }
RnStatus := 0;
IErr := 0;
SErr := '';
if length(trim(edFoundation.text)) <> 0 then begin
try
spFindStatus.Parameters.ParamValues['@Descr'] := edFoundation.Text;
spFindStatus.ExecProc;
IErr := spFindStatus.Parameters.ParamValues['@RETURN_VALUE'];
if IErr = 0 then begin
RnStatus := spFindStatus.Parameters.ParamValues['@NRN_OUT'];
end else begin
SErr := spFindStatus.Parameters.ParamValues['@SErr'];
ShowMessage(SErr);
end;
except
on e:Exception do begin
ShowMessage(e.Message);
end;
end;
end;
if RnStatus <> 0 then edOrderStatus.Text := edFoundation.Text;
ShowGets;
end;
procedure TfrmCCJRMO_State.edOrderStatusChange(Sender: TObject);
begin
ShowGets;
end;
end.
|
unit NSqlDbRegistry;
{$I ..\NSql.Inc}
interface
uses
NSqlIntf;
type
ISqlDbRegistry = interface
['{DB11FD4F-121E-4A42-87E7-EA4A5B3871C6}']
procedure Register(const Name: UnicodeString; DBHandler: IDbHandler);
function ByName(const Name: UnicodeString): IDbHandler;
function IsRegistered(const Name: UnicodeString; out DBHandler: IDbHandler): Boolean;
procedure UnregisterAll;
end;
function CreateSqlDbRegistry: ISqlDbRegistry;
implementation
uses
NSqlSys,
{$IFDEF NSQL_XE2UP}
System.SysUtils;
{$ELSE}
SysUtils;
{$ENDIF}
type
TDBHandlerRec = record
Name: UnicodeString;
Handler: IDbHandler;
end;
TSqlDbRegistry = class(TInterfacedObject, ISqlDbRegistry)
private
FList: array of TDBHandlerRec;
protected
{ ISqlDbRegistry }
procedure Register(const Name: UnicodeString; DBHandler: IDbHandler);
function ByName(const Name: UnicodeString): IDbHandler;
function IsRegistered(const Name: UnicodeString; out DBHandler: IDbHandler): Boolean;
procedure UnregisterAll;
end;
function CreateSqlDbRegistry: ISqlDbRegistry;
begin
Result := TSqlDbRegistry.Create;
end;
{ TSqlDbRegistry }
procedure TSqlDbRegistry.Register(const Name: UnicodeString;
DBHandler: IDbHandler);
var
Handler: IDbHandler;
begin
if IsRegistered(Name, Handler) then
raise Exception.CreateFmt('Database "%s" already registered in SqlDbRegistry', [Name]);
// Assert(not IsRegistered(Name, Handler), Name);
SetLength(FList, Length(FList) + 1);
FList[High(FList)].Name := Name;
FList[High(FList)].Handler := DBHandler;
end;
function TSqlDbRegistry.ByName(const Name: UnicodeString): IDbHandler;
begin
if not IsRegistered(Name, Result) then
raise Exception.CreateFmt('Database %s is not registered', [Name]);
end;
function TSqlDbRegistry.IsRegistered(const Name: UnicodeString;
out DBHandler: IDbHandler): Boolean;
var
I: Integer;
begin
for I := 0 to High(FList) do
if NSqlSameTextUnicode(FList[I].Name, Name) then
begin
Result := True;
DBHandler := FList[I].Handler;
Exit;
end;
Result := False;
end;
procedure TSqlDbRegistry.UnregisterAll;
begin
FList := nil;
end;
end.
|
{: This sample mixes two textures by using multitexturing.<p>
Multitexturing requires at least two materials in the material library:<ul>
<li>a base material: determines the basic properties, incl. blending, colors
and lighting-related properties
<li>a second material: determines the second texture (color and other
properties are ignored)
</ul><p>
This structure allows reuse of second textures among a variety of materials,
this is particularly usefull for details maps, which are usually just "noise"
to be applied on different base textures. You can also use it to reuse a basic
standard lighting map throughout many objects, thus reducing texture memory
needs (many shadows can be derived from a few deformed basic maps).<p>
The texture matrix (scale, offset) are adjusted independantly for the two
textures, in this sample, the TrackBar adjusts an isotropic scaling.<p>
When multi-texturing, never forget that both texture modes (decal, modulate etc.)
are honoured. For instance, if you "Decal" a non-transparent second texture,
the base texture will be completely replaced!
}
unit Main;
interface
uses
SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
GLScene, GLObjects, GLTexture, ComCtrls, StdCtrls, ExtCtrls,
ExtDlgs, GLLCLViewer, GLMaterial, GLCoordinates, GLCrossPlatform,
GLBaseClasses;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
Plane1: TGLPlane;
GLCamera1: TGLCamera;
GLMaterialLibrary1: TGLMaterialLibrary;
Image1: TImage;
Image2: TImage;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
TrackBar1: TTrackBar;
Label4: TLabel;
OpenPictureDialog1: TOpenPictureDialog;
CBClampTex2: TCheckBox;
procedure FormCreate(Sender: TObject);
procedure Image1Click(Sender: TObject);
procedure Image2Click(Sender: TObject);
procedure TrackBar1Change(Sender: TObject);
procedure CBClampTex2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
uses
GLUtils;
procedure TForm1.FormCreate(Sender: TObject);
begin
SetGLSceneMediaDir();
// prepare images to merge in the multitexture
with GLMaterialLibrary1 do
begin
Image1.Picture.LoadFromFile('ashwood.jpg');
Materials[0].Material.Texture.Image.Assign(Image1.Picture);
Image2.Picture.LoadFromFile('Flare1.bmp');
Materials[1].Material.Texture.Image.Assign(Image2.Picture);
end;
end;
procedure TForm1.Image1Click(Sender: TObject);
begin
// load a new Image1
if OpenPictureDialog1.Execute then
begin
Image1.Picture.LoadFromFile(OpenPictureDialog1.FileName);
GLMaterialLibrary1.Materials[0].Material.Texture.Image.Assign(Image1.Picture);
end;
end;
procedure TForm1.Image2Click(Sender: TObject);
begin
// load a new Image2
if OpenPictureDialog1.Execute then
begin
Image2.Picture.LoadFromFile(OpenPictureDialog1.FileName);
GLMaterialLibrary1.Materials[1].Material.Texture.Image.Assign(Image2.Picture);
end;
end;
procedure TForm1.TrackBar1Change(Sender: TObject);
begin
// adjust scale
with GLMaterialLibrary1.Materials[1].TextureScale do
begin
X := TrackBar1.Position / 10;
Y := TrackBar1.Position / 10;
end;
end;
procedure TForm1.CBClampTex2Click(Sender: TObject);
begin
with GLMaterialLibrary1.Materials[1].Material.Texture do
if CBClampTex2.Checked then
TextureWrap := twNone
else
TextureWrap := twBoth;
end;
end.
|
unit FormAutoNormals;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Voxel_Engine, Voxel_Tools, Voxel, VoxelUndoEngine, Voxel_AutoNormals;
const
// I've found these magic numbers in the sphere area:
// sqrt(NumNormals / (4 * pi) = MagicNumber
// NumNormals is 244 for RA2 and 36 for TS.
// It technically finds the ray of the sphere.
TS_MAGIC_NUMBER = 1.6925687506432688608442383546829;
RA2_MAGIC_NUMBER = 3.5449077018110320545963349666812;
RANGE_DEFAULT = 1;
RANGE_CUSTOM = 2;
AUTONORMALS_TANGENT = '8.4';
AUTONORMALS_INFLUENCE = '7.1';
AUTONORMALS_CUBED = '5.6';
AUTONORMALS_6FACED = '1.1';
type
TFrmAutoNormals = class(TForm)
GbNormalizationMethod: TGroupBox;
RbInfluence: TRadioButton;
RbCubed: TRadioButton;
Rb6Faced: TRadioButton;
GbInfluenceOptions: TGroupBox;
LbRange: TListBox;
Label1: TLabel;
Label2: TLabel;
EdRange: TEdit;
Label3: TLabel;
CbSmoothMe: TCheckBox;
BtOK: TButton;
BtCancel: TButton;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
CbInfluenceMap: TCheckBox;
BtTips: TButton;
CbPixelsZeroOnly: TCheckBox;
CbIncreaseContrast: TCheckBox;
Label7: TLabel;
EdContrast: TEdit;
EdSmooth: TEdit;
Label8: TLabel;
RbTangent: TRadioButton;
RbHBD: TRadioButton;
procedure RbHBDClick(Sender: TObject);
procedure RbTangentClick(Sender: TObject);
procedure BtTipsClick(Sender: TObject);
procedure BtOKClick(Sender: TObject);
procedure Rb6FacedClick(Sender: TObject);
procedure RbCubedClick(Sender: TObject);
procedure RbInfluenceClick(Sender: TObject);
procedure EdRangeChange(Sender: TObject);
procedure LbRangeClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure BtCancelClick(Sender: TObject);
private
{ Private declarations }
procedure ShowInfluenceOptions(value : boolean);
public
{ Public declarations }
MyVoxel : TVoxelSection;
end;
implementation
{$R *.dfm}
uses FormMain;
procedure TFrmAutoNormals.ShowInfluenceOptions(value : boolean);
begin
GbInfluenceOptions.Enabled := value;
LbRange.Enabled := value;
EdRange.Enabled := value and (LbRange.ItemIndex = RANGE_CUSTOM);
CbSmoothMe.Enabled := value and (not RbTangent.Checked) and (not RbHBD.Checked);
CbInfluenceMap.Enabled := value and RbCubed.Checked;
CbIncreaseContrast.Enabled := value and RbInfluence.Checked;
EdContrast.Enabled := value and (not RbTangent.Checked) and (not RbHBD.Checked);
EdSmooth.Enabled := value and (not RbTangent.Checked);
CbPixelsZeroOnly.Enabled := value and (not RbTangent.Checked) and (not RbHBD.Checked);
if RbInfluence.Checked then
begin
CbIncreaseContrast.Caption := 'Stretch Influence Map';
CbIncreaseContrast.Enabled := true;
end
else if RbTangent.Checked then
begin
CbIncreaseContrast.Caption := 'Treat Descontinuities';
CbIncreaseContrast.Enabled := true;
end
else
begin
CbIncreaseContrast.Caption := 'Stretch Influence Map';
CbIncreaseContrast.Enabled := false;
end;
end;
procedure TFrmAutoNormals.FormShow(Sender: TObject);
begin
case Configuration.ANType of
0:
begin
RbTangent.Checked := true;
RbTangentClick(Sender);
end;
1:
begin
RbInfluence.Checked := true;
RbInfluenceClick(Sender);
end;
2:
begin
RbCubed.Checked := true;
RbCubedClick(Sender);
end;
3:
begin
Rb6Faced.Checked := true;
Rb6FacedClick(Sender);
end;
4:
begin
RbHBD.Checked := true;
RbHBDClick(Sender);
end;
end;
EdRange.Text := FloatToStr(Configuration.ANNormalizationRange);
if Configuration.ANNormalizationRange = TS_MAGIC_NUMBER then
begin
LbRange.ItemIndex := 0;
end
else if Configuration.ANNormalizationRange = RA2_MAGIC_NUMBER then
begin
LbRange.ItemIndex := 1;
end
else
begin
LbRange.ItemIndex := RANGE_CUSTOM;
end;
CbSmoothMe.Checked := Configuration.ANSmoothMyNormals;
CbInfluenceMap.Checked := Configuration.ANInfluenceMap;
CbPixelsZeroOnly.Checked := Configuration.ANNewPixels;
CbIncreaseContrast.Checked := Configuration.ANStretch;
EdSmooth.Text := FloatToStr(Configuration.ANSmoothLevel);
EdContrast.Text := FloatToStr(Configuration.ANContrastLevel);
//RbTangent.Checked := true;
//ShowInfluenceOptions(true);
//LbRange.ItemIndex := RANGE_DEFAULT;
//LbRangeClick(Sender);
Caption := 'AutoNormals ' + AUTONORMALS_TANGENT;
RbTangent.Caption := 'Tangent Plane Auto Normals (v' + AUTONORMALS_TANGENT + ', recommended)';
RbInfluence.Caption := 'Influence Auto Normals (v' + AUTONORMALS_INFLUENCE + ')';
RbCubed.Caption := 'Cubed Auto Normals (v' + AUTONORMALS_CUBED + ')';
Rb6Faced.Caption := '6-Faced Auto Normals (v' + AUTONORMALS_6FACED + ')';
RbHBD.Caption := 'HBD AutoNormals (Quick`n`Good.)';
//GbInfluenceOptions.Caption := 'Tangent Plane Normalizer Options..';
end;
procedure TFrmAutoNormals.LbRangeClick(Sender: TObject);
begin
if LbRange.ItemIndex = -1 then
LbRange.ItemIndex := RANGE_DEFAULT;
case (LbRange.ItemIndex) of
0: EdRange.Text := FloatToStr(TS_MAGIC_NUMBER);
1: EdRange.Text := FloatToStr(RA2_MAGIC_NUMBER);
end;
EdRange.Enabled := (LbRange.ItemIndex = RANGE_CUSTOM);
end;
procedure TFrmAutoNormals.EdRangeChange(Sender: TObject);
var
Range : single;
Contrast : integer;
Smooth : single;
begin
BtOK.Enabled := true;
Range := StrToFloatDef(EdRange.Text,0);
Contrast := StrToIntDef(EdContrast.Text,1);
Smooth := StrToFloatDef(EdSmooth.Text,1);
if (Range < 1) or (Contrast < 1) or (Smooth < 1) then
BtOK.Enabled := false;
end;
procedure TFrmAutoNormals.RbTangentClick(Sender: TObject);
begin
ShowInfluenceOptions(RbTangent.Checked);
Configuration.ANType := 0;
GbInfluenceOptions.Caption := 'Tangent Plane Normalizer Options..';
end;
procedure TFrmAutoNormals.RbInfluenceClick(Sender: TObject);
begin
ShowInfluenceOptions(RbInfluence.Checked);
Configuration.ANType := 1;
GbInfluenceOptions.Caption := 'Influence Normalizer Options..';
end;
procedure TFrmAutoNormals.RbCubedClick(Sender: TObject);
begin
ShowInfluenceOptions(RbCubed.Checked);
Configuration.ANType := 2;
GbInfluenceOptions.Caption := 'Smooth Cubed Normalizer Options..';
end;
procedure TFrmAutoNormals.Rb6FacedClick(Sender: TObject);
begin
ShowInfluenceOptions(not Rb6Faced.Checked);
Configuration.ANType := 3;
GbInfluenceOptions.Caption := '6-Faced Normalizer Options..';
end;
procedure TFrmAutoNormals.RbHBDClick(Sender: TObject);
begin
ShowInfluenceOptions(RbHBD.Checked);
Configuration.ANType := 4;
GbInfluenceOptions.Caption := 'HBD Normalizer Options..';
end;
procedure TFrmAutoNormals.BtCancelClick(Sender: TObject);
begin
close;
end;
procedure TFrmAutoNormals.BtOKClick(Sender: TObject);
var
Res : TApplyNormalsResult;
Range,Smooth : single;
Contrast : integer;
AutoNormalsApplied: boolean;
begin
AutoNormalsApplied := false;
BtOK.Enabled := false;
If RbTangent.Checked then
begin
Range := StrToFloatDef(EdRange.Text,0);
if Range < 1 then
begin
MessageBox(0,pchar('Range Value Is Invalid. It Must Be Positive and Higher Than 1. Using 3.54 (Default).'),'Auto Normals Warning',0);
Range := RA2_MAGIC_NUMBER;
end;
AutoNormalsApplied := true;
CreateVXLRestorePoint(FrmMain.Document.ActiveSection^,Undo);
FrmMain.UpdateUndo_RedoState;
Res := AcharNormais(MyVoxel,Range,CbIncreaseContrast.Checked);
MessageBox(0,pchar('AutoNormals v' + AUTONORMALS_TANGENT + #13#13 + 'Total: ' + inttostr(Res.applied) + ' voxels modified.'),'Tangent Plane Auto Normal Results',0);
end
else If RbInfluence.Checked then
begin
Range := StrToFloatDef(EdRange.Text,0);
Contrast := StrToIntDef(EdContrast.Text,1);
if CbSmoothMe.Checked and CbSmoothMe.Enabled then
begin
Smooth := StrToFloatDef(EdSmooth.Text,1);
if (Smooth < 1) and CbSmoothMe.Checked and CbSmoothMe.Enabled then
begin
MessageBox(0,pchar('Smooth Value Is Invalid. It Must Be Positive, Integer and Higher Or Equal Than 1. Using 1 (Default).'),'Auto Normals Warning',0);
Smooth := 1;
end;
end
else
Smooth := Range;
if Range < 1 then
begin
MessageBox(0,pchar('Range Value Is Invalid. It Must Be Positive and Higher Than 1. Using 3.54 (Default).'),'Auto Normals Warning',0);
Range := RA2_MAGIC_NUMBER;
end;
if Contrast < 1 then
begin
MessageBox(0,pchar('Contrast Value Is Invalid. It Must Be Positive, Integer and Higher Or Equal Than 1. Using 1 (Default).'),'Auto Normals Warning',0);
Contrast := 1;
end;
AutoNormalsApplied := true;
CreateVXLRestorePoint(FrmMain.Document.ActiveSection^,Undo);
FrmMain.UpdateUndo_RedoState;
Res := ApplyInfluenceNormals(MyVoxel,Range,Smooth,Contrast,CbSmoothMe.Checked,CbPixelsZeroOnly.checked,CbIncreaseContrast.checked);
MessageBox(0,pchar('AutoNormals v' + AUTONORMALS_INFLUENCE + #13#13 + 'Total: ' + inttostr(Res.applied) + ' voxels modified.'),'Influence Auto Normal Results',0);
end
else if RbCubed.Checked then
begin
Range := StrToFloatDef(EdRange.Text,0);
Contrast := StrToIntDef(EdContrast.Text,1);
if CbSmoothMe.Checked and CbSmoothMe.Enabled then
begin
Smooth := StrToFloatDef(EdSmooth.Text,1);
if (Smooth < 1) and CbSmoothMe.Checked and CbSmoothMe.Enabled then
begin
MessageBox(0,pchar('Smooth Value Is Invalid. It Must Be Positive, Integer and Higher Or Equal Than 1. Using 1 (Default).'),'Auto Normals Warning',0);
Smooth := 1;
end;
end
else
Smooth := Range;
if Range < 1 then
begin
MessageBox(0,pchar('Range Value Is Invalid. It Must Be Positive and Higher Than 1. Using 3.54 (Default).'),'Auto Normals Warning',0);
Range := RA2_MAGIC_NUMBER;
end;
if Contrast < 1 then
begin
MessageBox(0,pchar('Contrast Value Is Invalid. It Must Be Positive, Integer and Higher Or Equal Than 1. Using 1 (Default).'),'Auto Normals Warning',0);
Contrast := 1;
end;
AutoNormalsApplied := true;
CreateVXLRestorePoint(FrmMain.Document.ActiveSection^,Undo);
FrmMain.UpdateUndo_RedoState;
Res := ApplyCubedNormals(MyVoxel,Range,Smooth,Contrast,CbSmoothMe.Checked,CbInfluenceMap.Checked,CbPixelsZeroOnly.checked);
MessageBox(0,pchar('AutoNormals v' + AUTONORMALS_CUBED + #13#13 + 'Total: ' + inttostr(Res.applied) + ' voxels modified.'),'Cubed Auto Normal Results',0);
end
else if RbHBD.Checked then
begin
Range := StrToFloatDef(EdRange.Text,0);
if Range < 1 then
begin
MessageBox(0,pchar('Range Value Is Invalid. It Must Be Positive and Higher Than 1. Using 3.54 (Default).'),'Auto Normals Warning',0);
Range := RA2_MAGIC_NUMBER;
end;
Smooth := StrToFloatDef(EdSmooth.Text,1);
if (Smooth < 1) then
begin
MessageBox(0,pchar('Smooth Value Is Invalid. It Must Be Positive, Integer and Higher Or Equal Than 1. Using 1 (Default).'),'Auto Normals Warning',0);
Smooth := 1;
end
else
Smooth := Range;
AutoNormalsApplied := true;
CreateVXLRestorePoint(FrmMain.Document.ActiveSection^,Undo);
FrmMain.UpdateUndo_RedoState;
velAutoNormals2(MyVoxel, Range, Smooth);
ShowMessage('AutoNormals HBD' + #13#13 + 'Operation Completed!');
end
else
begin
AutoNormalsApplied := true;
CreateVXLRestorePoint(FrmMain.Document.ActiveSection^,Undo);
FrmMain.UpdateUndo_RedoState;
Res := ApplyNormals(MyVoxel);
if Res.confused > 0 then
begin
MessageBox(0,pchar('AutoNormals v' + AUTONORMALS_6FACED + #13#13 + 'Total: ' + inttostr(Res.applied + Res.confused) + #13 +'Applied: ' + inttostr(Res.applied) + #13 + 'Confused: ' +inttostr(Res.confused) + #13 + #13 + 'Some were Confused, This may mean there are redundant voxels.'),'6-Faced Auto Normal Results',0);
if FrmMain.p_Frm3DPreview <> nil then
begin
FrmMain.p_Frm3DPreview^.Visible := false;
end;
FrmMain.RemoveRedundantVoxels1Click(Sender);
if FrmMain.p_Frm3DPreview <> nil then
begin
FrmMain.p_Frm3DPreview^.Visible := true;
end;
end
else
begin
MessageBox(0,pchar('AutoNormals v' + AUTONORMALS_6FACED + #13#13 + 'Total: ' + inttostr(Res.applied + Res.confused) + #13 +'Applied: ' + inttostr(Res.applied) + #13 + 'Confused: ' +inttostr(Res.confused)),'6-Faced Auto Normal Results',0);
end;
end;
// Update configurations.
if AutoNormalsApplied = true then
begin
Configuration.ANSmoothMyNormals := CbSmoothMe.Checked;
Configuration.ANInfluenceMap := CbInfluenceMap.Checked;
Configuration.ANNewPixels := CbPixelsZeroOnly.Checked;
Configuration.ANStretch := CbIncreaseContrast.Checked;
Configuration.ANNormalizationRange := StrToFloatDef(EdRange.Text, 0);
Configuration.ANSmoothLevel := StrToFloatDef(EdSmooth.Text, 1);
Configuration.ANContrastLevel := StrToFloatDef(EdContrast.Text, 1);
FrmMain.SetVoxelChanged(true);
FrmMain.Refreshall;
Close;
end
else
begin
BtOK.Enabled := true;
end;
end;
procedure TFrmAutoNormals.BtTipsClick(Sender: TObject);
begin
FrmMain.OpenHyperLink('http://www.ppmsite.com/index.php?go=normalstips');
end;
end.
|
unit uValidaDocs;
//------------------------------------------------------------------------------
interface
function ValidaCPF(aCPF: string): Boolean;
function ValidaCNPJ(aCNPJ: string): Boolean;
function LeftStr(const AText: AnsiString; const ACount: Integer): AnsiString;
function RightStr(const AText: AnsiString; const ACount: Integer): AnsiString;
//------------------------------------------------------------------------------
implementation
uses SysUtils, uStringFunctions;
function ValidaCPF(aCPF: string): Boolean;
var
cControle: string;
nDigito, nIni, nFim, I, J: Byte;
nSoma: Integer;
iTemp: integer;
function InListInvalid(const cpf: string): Boolean;
const
CPF_Invalid: array[0..9] of string = (
'00000000000', '11111111111', '22222222222',
'33333333333', '44444444444', '55555555555',
'66666666666', '77777777777', '88888888888',
'99999999999');
var
i: Integer;
begin
Result := False;
for i := 0 to High(CPF_Invalid) do
if cpf = CPF_Invalid[i] then
begin
Result := True;
Exit;
end;
end;
begin
nDigito := 14;
cControle := '';
nIni := 2;
nFim := 10;
aCPF := Trim(aCPF);
Result := False;
if Length(aCPF) = 11 then
begin
if not InListInvalid(aCPF) then
begin
for I := 1 to 2 do
begin
nSoma := 0;
for J := nIni to nFim do
begin
iTemp := StrToIntDef(Copy(aCPF, J - I, 1), -1);
if iTemp = -1 then
Exit;
Inc(nSoma, iTemp * (nFim + 1 + I - J));
end;
if I = 2 then
Inc(nSoma, (2 * nDigito));
nDigito := (nSoma * 10) mod 11;
if nDigito = 10 then
nDigito := 0;
cControle := cControle + Copy(IntToStr(nDigito), 1, 1);
nIni := 03;
nFim := 11;
end;
Result := Copy(aCPF, Succ(Length(aCPF)-2), 2) = cControle;
end;
end;
end;
function ValidaCNPJ(aCNPJ: string): Boolean;
var
nSoma1, nSoma2: Integer;
I, nDigito1, nDigito2: Byte;
V: array[1..14] of Byte;
begin
aCNPJ := Trim(aCNPJ);
Result := False;
if Length(aCNPJ) = 14 then
begin
for I := 1 to 14 do
V[I] := StrToInt(Copy(aCNPJ, I, 1));
nSoma1 := (V[12] * 2) + (V[11] * 3) + (V[10] * 4) + (V[09] * 5) +
(V[08] * 6) + (V[07] * 7) + (V[06] * 8) + (V[05] * 9) +
(V[04] * 2) + (V[03] * 3) + (V[02] * 4) + (V[01] * 5);
nSoma2 := nSoma1 mod 11;
if (nSoma2 = 0) or (nSoma2 = 1) then
nDigito1 := 0
else
nDigito1 := 11 - nSoma2;
nSoma1 := (V[13] * 2) + (V[12] * 3) + (V[11] * 4) + (V[10] * 5) +
(V[09] * 6) + (V[08] * 7) + (V[07] * 8) + (V[06] * 9) +
(V[05] * 2) + (V[04] * 3) + (V[03] * 4) + (V[02] * 5) +
(V[01] * 6);
nSoma2 := nSoma1 mod 11;
if (nSoma2 = 0) or (nSoma2 = 1) then
nDigito2 := 0
else
nDigito2 := 11 - nSoma2;
Result := (LeftStr(IntToStr(nDigito1), 1) + LeftStr(IntToStr(nDigito2), 1)) = RightStr(aCNPJ, 2);
end;
end;
function LeftStr(const AText: AnsiString; const ACount: Integer): AnsiString;
begin
Result := Copy(WideString(AText), 1, ACount);
end;
function RightStr(const AText: AnsiString; const ACount: Integer): AnsiString;
begin
Result := Copy(WideString(AText), Length(WideString(AText)) + 1 - ACount, ACount);
end;
end.
|
unit UExport;
(*====================================================================
Implementation of the export to text format
======================================================================*)
interface
uses Classes, UStream, UStringList, UApiTypes, UBaseTypes;
const
c_DatabaseName = 1;
c_DatabasePath = 2;
c_NumberOfDisks = 3;
c_DiskName = 4;
c_DiskSizeKb = 5;
c_DiskFreeKb = 6;
c_DiskFreePercent = 7;
c_Folders = 8;
c_Files = 9;
c_Archives = 10;
c_TotalFilesInArchives = 11;
c_TotalFoldersInArchives = 12;
c_TotalDataSize = 13;
c_OriginalPath = 14;
c_Volumelabel = 15;
c_PhysSize = 16;
c_ArchSize = 17;
c_ScanDate = 18;
c_PathToFolder = 19;
c_FolderName = 20;
c_FolderDataSize = 21;
c_FilesInFolder = 22;
c_FoldersInFolder = 23;
c_PhysFolderDataSize = 24;
c_PhysFilesInFolder = 25;
c_PhysFoldersInFolder = 26;
c_FileName = 27;
c_FileSize = 28;
c_FileDate = 29;
c_FileTime = 30;
c_ShortDesc = 31;
c_Desc = 32;
c_CrLf = 33;
c_Tab = 34;
c_Space = 35;
c_FirstId = c_DatabaseName;
c_LastId = c_Space;
type
TIdValue = record
sId : AnsiString;
sValue: AnsiString;
end;
TDBaseExport = object
private
sIdentifierBegin : AnsiString;
sIdentifierEnd : AnsiString;
iMaxDescLines : integer;
iMaxDescSize : integer;
iFileColumns : integer;
IdValues : array [c_FirstId..c_LastId] of TIdValue;
sSecDatabaseBegin : AnsiString; // level 1
sSecDiskBegin : AnsiString; // level 2
sSecFolderBegin : AnsiString; // level 3
sSecFirstColumnBegin : AnsiString; // level 4
sSecEachColumnBegin : AnsiString; // level 4
sSecFile : AnsiString; // level 5
sSecDesc : AnsiString; // level 5
sSecEachColumnEnd : AnsiString; // level 4
sSecLastColumnEnd : AnsiString; // level 4
sSecFolderEnd : AnsiString; // level 3
sSecDiskEnd : AnsiString; // level 2
sSecDatabaseEnd : AnsiString; // level 1
ExportFile : TQBufStream;
///FilesList : TQStringList; {for capturing and sorting files}
FilesList : TStringList; {for capturing and sorting files}
DBaseHandle : PDBaseHandle;
procedure CheckSection(var sTrimmedLine, sLine: AnsiString);
procedure DispatchSettings(var sOneLine: AnsiString);
procedure SetIdentifiers;
procedure LoCaseSections;
procedure FillOneFile(var POneFile: TPOneFile);
procedure WriteFiles;
procedure WriteSection(var sSection: AnsiString);
procedure LoCaseOneSection(var sSection: AnsiString);
procedure ClearValuesLevel1;
procedure ClearValuesLevel2;
procedure ClearValuesLevel3;
procedure ClearValuesLevel4;
public
bFormatVerified : boolean;
sDefaultExt : AnsiString;
sFileFilter : AnsiString;
sExcludeChars : AnsiString;
sReplaceChars : AnsiString;
iWritten : integer;
iFileCounter : integer;
eInSection : (secSettings,
secDatabaseBegin,
secDiskBegin,
secFolderBegin,
secFirstColumnBegin,
secEachColumnBegin,
secFile,
secDesc,
secEachColumnEnd,
secLastColumnEnd,
secFolderEnd,
secDiskEnd,
secDatabaseEnd);
procedure Init(FormatFileName: ShortString; aDBaseHandle: PDBaseHandle);
procedure OpenOutputFile(FileName: ShortString);
procedure CloseOutputFile;
function ConvertChars(S: String): String;
procedure OnDatabaseBegin;
procedure OnDatabaseEnd;
procedure OnDiskBegin;
procedure OnDiskEnd;
procedure OnFolderBegin;
procedure OnFolderEnd;
procedure OnFirstColumnBegin;
procedure OnEachColumnBegin;
procedure OnFile;
procedure OnEachColumnEnd;
procedure OnLastColumnEnd;
procedure WriteOneFile(var POneFile: TPOneFile);
end;
var
DBaseExport: TDBaseExport;
implementation
uses SysUtils,
UTypes, ULang, UCollections, UBaseUtils, LConvEncoding,
UApi, {FDBase} FMain;
//--------------------------------------------------------------------
procedure ReplaceStr(var St: AnsiString; OrigSt, NewStr: AnsiString);
var i: integer;
begin
i := pos(OrigSt, St);
while i > 0 do
begin
delete(St, i, length(OrigSt));
insert(NewStr, St, i);
i := pos(OrigSt, St);
end;
end;
//-------------------------------------------------------------------
// determines in which section of the format file we are
procedure TDBaseExport.CheckSection(var sTrimmedLine, sLine: AnsiString);
begin
if sTrimmedLine = sIdentifierBegin + 'on database begin' + sIdentifierEnd then
begin
eInSection := secDatabaseBegin;
sLine := '';
exit;
end;
if sTrimmedLine = sIdentifierBegin + 'on database end' + sIdentifierEnd then
begin
eInSection := secDatabaseEnd;
sLine := '';
exit;
end;
if sTrimmedLine = sIdentifierBegin + 'on disk begin' + sIdentifierEnd then
begin
eInSection := secDiskBegin;
sLine := '';
exit;
end;
if sTrimmedLine = sIdentifierBegin + 'on disk end' + sIdentifierEnd then
begin
eInSection := secDiskEnd;
sLine := '';
exit;
end;
if sTrimmedLine = sIdentifierBegin + 'on folder begin' + sIdentifierEnd then
begin
eInSection := secFolderBegin;
sLine := '';
exit;
end;
if sTrimmedLine = sIdentifierBegin + 'on folder end' + sIdentifierEnd then
begin
eInSection := secFolderEnd;
sLine := '';
exit;
end;
if sTrimmedLine = sIdentifierBegin + 'on first column begin' + sIdentifierEnd then
begin
eInSection := secFirstColumnBegin;
sLine := '';
exit;
end;
if sTrimmedLine = sIdentifierBegin + 'on each column begin' + sIdentifierEnd then
begin
eInSection := secEachColumnBegin;
sLine := '';
exit;
end;
if sTrimmedLine = sIdentifierBegin + 'on file' + sIdentifierEnd then
begin
eInSection := secFile;
sLine := '';
exit;
end;
if sTrimmedLine = sIdentifierBegin + 'on description' + sIdentifierEnd then
begin
eInSection := secDesc;
sLine := '';
exit;
end;
if sTrimmedLine = sIdentifierBegin + 'on each column end' + sIdentifierEnd then
begin
eInSection := secEachColumnEnd;
sLine := '';
exit;
end;
if sTrimmedLine = sIdentifierBegin + 'on last column end' + sIdentifierEnd then
begin
eInSection := secLastColumnEnd;
sLine := '';
exit;
end;
end;
//-------------------------------------------------------------------
// Gets the settings from the format file
procedure TDBaseExport.DispatchSettings(var sOneLine: AnsiString);
var
sLoCaseLine : AnsiString;
sOneLineCopy: AnsiString;
i : integer;
begin
sOneLineCopy := sOneLine;
sLoCaseLine := AnsiLowerCase(sOneLine);
i := pos('identifierbegin', sLoCaseLine);
if i > 0 then
begin
delete(sLoCaseLine, 1, i-1+length('identifierbegin'));
sLoCaseLine := TrimLeft(sLoCaseLine);
delete(sLoCaseLine, 1, 1); // delete the '='
sIdentifierBegin := Trim(sLoCaseLine);
end;
i := pos('identifierend', sLoCaseLine);
if i > 0 then
begin
delete(sLoCaseLine, 1, i-1+length('identifierend'));
sLoCaseLine := TrimLeft(sLoCaseLine);
delete(sLoCaseLine, 1, 1); // delete the '='
sIdentifierEnd := Trim(sLoCaseLine);
end;
i := pos('maxdesclines', sLoCaseLine);
if i > 0 then
begin
delete(sLoCaseLine, 1, i-1+length('maxdesclines'));
sLoCaseLine := TrimLeft(sLoCaseLine);
delete(sLoCaseLine, 1, 1); // delete the '='
try
iMaxDescLines := StrToInt(Trim(sLoCaseLine));
except
on EConvertError do iMaxDescLines := 0;
end;
end;
i := pos('maxdescsize', sLoCaseLine);
if i > 0 then
begin
delete(sLoCaseLine, 1, i-1+length('maxdescsize'));
sLoCaseLine := TrimLeft(sLoCaseLine);
delete(sLoCaseLine, 1, 1); // delete the '='
try
iMaxDescSize := StrToInt(Trim(sLoCaseLine));
except
on EConvertError do iMaxDescSize := 0;
end;
end;
i := pos('filecolumns', sLoCaseLine);
if i > 0 then
begin
delete(sLoCaseLine, 1, i-1+length('filecolumns'));
sLoCaseLine := TrimLeft(sLoCaseLine);
delete(sLoCaseLine, 1, 1); // delete the '='
try
iFileColumns := StrToInt(Trim(sLoCaseLine));
except
on EConvertError do iFileColumns := 1;
end;
end;
i := pos('defaultext', sLoCaseLine);
if i > 0 then
begin
delete(sLoCaseLine, 1, i-1+length('defaultext'));
delete(sOneLineCopy, 1, i-1+length('defaultext'));
sLoCaseLine := TrimLeft(sLoCaseLine);
sOneLineCopy := TrimLeft(sOneLineCopy);
delete(sLoCaseLine, 1, 1); // delete the '='
delete(sOneLineCopy, 1, 1);
sLoCaseLine := Trim(sLoCaseLine);
sOneLineCopy := Trim(sOneLineCopy);
sDefaultExt := sOneLineCopy;
end;
i := pos('filefilter', sLoCaseLine);
if i > 0 then
begin
delete(sLoCaseLine, 1, i-1+length('filefilter'));
delete(sOneLineCopy, 1, i-1+length('filefilter'));
sLoCaseLine := TrimLeft(sLoCaseLine);
sOneLineCopy := TrimLeft(sOneLineCopy);
delete(sLoCaseLine, 1, 1); // delete the '='
delete(sOneLineCopy, 1, 1);
sLoCaseLine := Trim(sLoCaseLine);
sOneLineCopy := Trim(sOneLineCopy);
sFileFilter := sOneLineCopy;
end;
i := pos('excludechars', sLoCaseLine);
if i > 0 then
begin
delete(sLoCaseLine, 1, i-1+length('excludechars'));
delete(sOneLineCopy, 1, i-1+length('excludechars'));
sLoCaseLine := TrimLeft(sLoCaseLine);
sOneLineCopy := TrimLeft(sOneLineCopy);
delete(sLoCaseLine, 1, 1); // delete the '='
delete(sOneLineCopy, 1, 1);
sLoCaseLine := Trim(sLoCaseLine);
sOneLineCopy := Trim(sOneLineCopy);
sExcludeChars := sExcludeChars + sOneLineCopy;
end;
i := pos('replacechar', sLoCaseLine);
if i > 0 then
begin
delete(sLoCaseLine, 1, i-1+length('replacechar'));
delete(sOneLineCopy, 1, i-1+length('replacechar'));
sLoCaseLine := TrimLeft(sLoCaseLine);
sOneLineCopy := TrimLeft(sOneLineCopy);
delete(sLoCaseLine, 1, 1); // delete the '='
delete(sOneLineCopy, 1, 1);
sLoCaseLine := Trim(sLoCaseLine);
sOneLineCopy := Trim(sOneLineCopy);
if length(sOneLineCopy) = 1 then sOneLineCopy := sOneLineCopy + ' ';
sReplaceChars := sReplaceChars + sOneLineCopy;
end;
end;
//-------------------------------------------------------------------
// Builds the list of tags used in the format file
procedure TDBaseExport.SetIdentifiers;
begin
IdValues[c_DatabaseName ].sId := sIdentifierBegin + 'databasename' + sIdentifierEnd;
IdValues[c_DatabasePath ].sId := sIdentifierBegin + 'databasepath' + sIdentifierEnd;
IdValues[c_NumberOfDisks ].sId := sIdentifierBegin + 'numberofdisks' + sIdentifierEnd;
IdValues[c_DiskName ].sId := sIdentifierBegin + 'diskname' + sIdentifierEnd;
IdValues[c_DiskSizeKb ].sId := sIdentifierBegin + 'disksizekb' + sIdentifierEnd;
IdValues[c_DiskFreeKb ].sId := sIdentifierBegin + 'diskfreekb' + sIdentifierEnd;
IdValues[c_DiskFreePercent ].sId := sIdentifierBegin + 'diskfreepercent' + sIdentifierEnd;
IdValues[c_Folders ].sId := sIdentifierBegin + 'folders' + sIdentifierEnd;
IdValues[c_Files ].sId := sIdentifierBegin + 'files' + sIdentifierEnd;
IdValues[c_Archives ].sId := sIdentifierBegin + 'archives' + sIdentifierEnd;
IdValues[c_TotalFilesInArchives ].sId := sIdentifierBegin + 'totalfilesinarchives' + sIdentifierEnd;
IdValues[c_TotalFoldersInArchives].sId := sIdentifierBegin + 'totalfoldersinarchives' + sIdentifierEnd;
IdValues[c_TotalDataSize ].sId := sIdentifierBegin + 'totaldatasize' + sIdentifierEnd;
IdValues[c_OriginalPath ].sId := sIdentifierBegin + 'originalpath' + sIdentifierEnd;
IdValues[c_VolumeLabel ].sId := sIdentifierBegin + 'volumelabel' + sIdentifierEnd;
IdValues[c_PhysSize ].sId := sIdentifierBegin + 'physsize' + sIdentifierEnd;
IdValues[c_ArchSize ].sId := sIdentifierBegin + 'archsize' + sIdentifierEnd;
IdValues[c_ScanDate ].sId := sIdentifierBegin + 'scandate' + sIdentifierEnd;
IdValues[c_PathToFolder ].sId := sIdentifierBegin + 'pathtofolder' + sIdentifierEnd;
IdValues[c_FolderName ].sId := sIdentifierBegin + 'foldername' + sIdentifierEnd;
IdValues[c_FolderDataSize ].sId := sIdentifierBegin + 'folderdatasize' + sIdentifierEnd;
IdValues[c_FilesInFolder ].sId := sIdentifierBegin + 'filesinfolder' + sIdentifierEnd;
IdValues[c_FoldersInFolder ].sId := sIdentifierBegin + 'foldersinfolder' + sIdentifierEnd;
IdValues[c_PhysFolderDataSize ].sId := sIdentifierBegin + 'physfolderdatasize' + sIdentifierEnd;
IdValues[c_PhysFilesInFolder ].sId := sIdentifierBegin + 'physfilesinfolder' + sIdentifierEnd;
IdValues[c_PhysFoldersInFolder ].sId := sIdentifierBegin + 'physfoldersinfolder' + sIdentifierEnd;
IdValues[c_FileName ].sId := sIdentifierBegin + 'filename' + sIdentifierEnd;
IdValues[c_FileSize ].sId := sIdentifierBegin + 'filesize' + sIdentifierEnd;
IdValues[c_FileDate ].sId := sIdentifierBegin + 'filedate' + sIdentifierEnd;
IdValues[c_FileTime ].sId := sIdentifierBegin + 'filetime' + sIdentifierEnd;
IdValues[c_ShortDesc ].sId := sIdentifierBegin + 'shortdesc' + sIdentifierEnd;
IdValues[c_Desc ].sId := sIdentifierBegin + 'desc' + sIdentifierEnd;
IdValues[c_CrLf ].sId := sIdentifierBegin + 'crlf' + sIdentifierEnd;
IdValues[c_Tab ].sId := sIdentifierBegin + 'tab' + sIdentifierEnd;
IdValues[c_Space ].sId := sIdentifierBegin + 'space' + sIdentifierEnd;
end;
//-------------------------------------------------------------------
// Converts all the sections to lower case
procedure TDBaseExport.LoCaseSections;
begin
LoCaseOneSection(sSecDatabaseBegin);
LoCaseOneSection(sSecDiskBegin);
LoCaseOneSection(sSecFolderBegin);
LoCaseOneSection(sSecFirstColumnBegin);
LoCaseOneSection(sSecEachColumnBegin);
LoCaseOneSection(sSecFile);
LoCaseOneSection(sSecDesc);
LoCaseOneSection(sSecEachColumnEnd);
LoCaseOneSection(sSecLastColumnEnd);
LoCaseOneSection(sSecFolderEnd);
LoCaseOneSection(sSecDiskEnd);
LoCaseOneSection(sSecDatabaseEnd);
end;
//-------------------------------------------------------------------
// Converst one section to lower case
procedure TDBaseExport.LoCaseOneSection(var sSection: AnsiString);
var
i : integer;
iIdPos : integer;
iIndex : integer;
sLoCaseSection: AnsiString;
begin
sLoCaseSection := AnsiLowerCase(sSection);
for iIndex := c_FirstId to c_LastId do
begin
iIdPos := Pos(IdValues[iIndex].sId, sLoCaseSection);
while (iIdPos > 0) do
begin
for i := iIdPos to iIdPos + length(IdValues[iIndex].sId) - 1 do
begin
sSection[i] := sLoCaseSection[i];
sLoCaseSection[i] := #1; // erase so it is not find in next iteration
end;
iIdPos := Pos(IdValues[iIndex].sId, sLoCaseSection);
end;
end;
end;
//-------------------------------------------------------------------
// Replaces all tags in one section and writes it to the output file
procedure TDBaseExport.WriteSection(var sSection: AnsiString);
var
iIdPos : integer;
iIndex : integer;
sSectionCopy: AnsiString;
begin
if sSection = '' then exit;
sSectionCopy := sSection;
for iIndex := c_FirstId to c_LastId do
begin
iIdPos := Pos(IdValues[iIndex].sId, sSectionCopy);
while (iIdPos > 0) do
begin
delete(sSectionCopy, iIdPos, length(IdValues[iIndex].sId));
insert(IdValues[iIndex].sValue, sSectionCopy, iIdPos);
iIdPos := Pos(IdValues[iIndex].sId, sSectionCopy);
end;
end;
ExportFile.Write(sSectionCopy[1], length(sSectionCopy));
inc(iWritten, length(sSectionCopy));
end;
//-------------------------------------------------------------------
procedure TDBaseExport.ClearValuesLevel1;
begin
IdValues[c_DatabaseName ].sValue := '';
IdValues[c_DatabasePath ].sValue := '';
IdValues[c_NumberOfDisks ].sValue := '';
IdValues[c_CrLf ].sValue := #13#10;
IdValues[c_Tab ].sValue := #9;
IdValues[c_Space ].sValue := ' ';
end;
//-------------------------------------------------------------------
procedure TDBaseExport.ClearValuesLevel2;
begin
IdValues[c_DiskName ].sValue := '';
IdValues[c_DiskSizeKb ].sValue := '';
IdValues[c_DiskFreeKb ].sValue := '';
IdValues[c_DiskFreePercent ].sValue := '';
IdValues[c_Folders ].sValue := '';
IdValues[c_Files ].sValue := '';
IdValues[c_Archives ].sValue := '';
IdValues[c_TotalFilesInArchives ].sValue := '';
IdValues[c_TotalFoldersInArchives].sValue := '';
IdValues[c_TotalDataSize ].sValue := '';
IdValues[c_OriginalPath ].sValue := '';
IdValues[c_VolumeLabel ].sValue := '';
IdValues[c_PhysSize ].sValue := '';
IdValues[c_ArchSize ].sValue := '';
IdValues[c_ScanDate ].sValue := '';
end;
//-------------------------------------------------------------------
procedure TDBaseExport.ClearValuesLevel3;
begin
IdValues[c_PathToFolder ].sValue := '';
IdValues[c_FolderName ].sValue := '';
IdValues[c_FolderDataSize ].sValue := '';
IdValues[c_FilesInFolder ].sValue := '';
IdValues[c_FoldersInFolder ].sValue := '';
IdValues[c_PhysFolderDataSize ].sValue := '';
IdValues[c_PhysFilesInFolder ].sValue := '';
IdValues[c_PhysFoldersInFolder ].sValue := '';
end;
//-------------------------------------------------------------------
procedure TDBaseExport.ClearValuesLevel4;
begin
IdValues[c_FileName ].sValue := '';
IdValues[c_FileSize ].sValue := '';
IdValues[c_FileDate ].sValue := '';
IdValues[c_FileTime ].sValue := '';
IdValues[c_ShortDesc ].sValue := '';
IdValues[c_Desc ].sValue := '';
end;
//-------------------------------------------------------------------
procedure TDBaseExport.Init(FormatFileName: ShortString; aDBaseHandle: PDBaseHandle);
var
F : TQBufStream;
pBuffer : PChar;
sBuffer : AnsiString;
sOneLine : AnsiString;
sTrimmedLine : AnsiString;
BufSize : Integer;
TmpBuf : array[0..255] of char;
i : integer;
begin
iMaxDescLines := 0;
iMaxDescSize := 0;
iFileColumns := 1;
bFormatVerified := false;
sIdentifierBegin := '<<';
sIdentifierEnd := '>>';
eInSection := secSettings;
sDefaultExt := 'txt';
sFileFilter := '';
sExcludeChars := '';
sReplaceChars := '';
iWritten := 0;
iFileCounter := 0;
DBaseHandle := aDBaseHandle;
ClearValuesLevel1;
ClearValuesLevel2;
ClearValuesLevel3;
ClearValuesLevel4;
sSecDatabaseBegin := '';
sSecDiskBegin := '';
sSecFolderBegin := '';
sSecFirstColumnBegin := '';
sSecEachColumnBegin := '';
sSecFile := '';
sSecDesc := '';
sSecEachColumnEnd := '';
sSecLastColumnEnd := '';
sSecFolderEnd := '';
sSecDiskEnd := '';
sSecDatabaseEnd := '';
///FilesList := TQStringList.Create;
FilesList := TStringList.Create;
FilesList.Sorted := true;
///FilesList.Duplicates := qdupAccept;
FilesList.Duplicates := dupAccept;
F.Init(StrPCopy(TmpBuf, FormatFileName), stOpenReadNonExclusive);
BufSize := F.GetSize;
GetMem(pBuffer, BufSize+2);
F.Read(pBuffer^, BufSize);
F.Done;
PBuffer[BufSize] := #0;
sBuffer := AdjustLineBreaks(StrPas(pBuffer));
sBuffer := StrPas(pBuffer);
FreeMem(PBuffer, BufSize+2);
while Length(sBuffer) > 0 do
begin
///i := Pos(#$D#$A, sBuffer);
i := Pos(#$A, sBuffer);
if i > 0
then
begin
sOneLine := copy(sBuffer, 1, i-1);
ReplaceStr(sOneLine,#$D,'');
//ReplaceStr(sOneLine,#10,'');
///delete(sBuffer, 1, i+1);
delete(sBuffer, 1, i);
end
else
begin
sOneLine := sBuffer;
sBuffer := '';
end;
// now we have one line here, check, if it begins with //
sOneLine := TrimRight(sOneLine);
sTrimmedLine := AnsiLowerCase(TrimLeft(sOneLine));
if pos('//', sTrimmedLine) <> 1 then // whole line is not comment
begin
i := pos('//', sOneLine);
if i>0 then SetLength(sOneLine, i-1);
CheckSection(sTrimmedLine, sOneLine);
if eInSection = secSettings
then
begin
if pos('diskbase export format', sTrimmedLine) > 0 then bFormatVerified := true;
DispatchSettings(sOneLine);
end
else // we are in section
begin
case eInSection of
secDatabaseBegin: sSecDatabaseBegin := sSecDatabaseBegin + sOneLine;
secDatabaseEnd: sSecDatabaseEnd := sSecDatabaseEnd + sOneLine;
secDiskBegin: sSecDiskBegin := sSecDiskBegin + sOneLine;
secDiskEnd: sSecDiskEnd := sSecDiskEnd + sOneLine;
secFolderBegin: sSecFolderBegin := sSecFolderBegin + sOneLine;
secFolderEnd: sSecFolderEnd := sSecFolderEnd + sOneLine;
secFirstColumnBegin:sSecFirstColumnBegin := sSecFirstColumnBegin + sOneLine;
secEachColumnBegin: sSecEachColumnBegin := sSecEachColumnBegin + sOneLine;
secFile: sSecFile := sSecFile + sOneLine;
secDesc: sSecDesc := sSecDesc + sOneLine;
secEachColumnEnd: sSecEachColumnEnd := sSecEachColumnEnd + sOneLine;
secLastColumnEnd: sSecLastColumnEnd := sSecLastColumnEnd + sOneLine;
end;
end;
end; // if
end; // while
SetIdentifiers;
LoCaseSections;
end;
//-------------------------------------------------------------------
procedure TDBaseExport.OpenOutputFile(FileName: ShortString);
var
TmpStrArr : array[0..256] of char;
begin
ExportFile.Init(StrPCopy(TmpStrArr, FileName), stCreate);
end;
//-------------------------------------------------------------------
procedure TDBaseExport.CloseOutputFile;
begin
ExportFile.Done;
FreeListObjects(FilesList);
FilesList.Free;
end;
//-------------------------------------------------------------------
// Delets chars specified in ExcludeChars and replaces chars specified in
// ReplaceChars
function TDBaseExport.ConvertChars(S: String): String;
var
i, j: integer;
begin
if (sExcludeChars = '') and (sReplaceChars = '') then
begin
Result := S;
// convert to unix utf8
//Result := CP1250ToUtf8(s);
//
exit;
end;
for i := 1 to length(sExcludeChars) do
for j := 1 to length(S) do
if S[j] = sExcludeChars[i] then S[j] := ' ';
for i := 1 to length(sReplaceChars) div 2 do
for j := 1 to length(S) do
if S[j] = sReplaceChars[2*(i-1)+1] then S[j] := sReplaceChars[2*(i-1)+2];
Result := S;
end;
//-------------------------------------------------------------------
// Follwoing prodeures are called from IterateFiles to produce the output
//-------------------------------------------------------------------
procedure TDBaseExport.OnDatabaseBegin;
begin
ClearValuesLevel1;
ClearValuesLevel2;
ClearValuesLevel3;
ClearValuesLevel4;
IdValues[c_DatabaseName ].sValue := ConvertChars(gDatabaseData.sDatabaseName);
IdValues[c_DatabasePath ].sValue := ConvertChars(gDatabaseData.sDatabasePath);
IdValues[c_NumberOfDisks].sValue := ConvertChars(IntToStr(gDatabaseData.iNumberOfDisks));
WriteSection(sSecDatabaseBegin);
end;
//-------------------------------------------------------------------
procedure TDBaseExport.OnDatabaseEnd;
begin
WriteSection(sSecDatabaseEnd);
end;
//-------------------------------------------------------------------
procedure TDBaseExport.OnDiskBegin;
var
TmpComp: comp;
begin
ClearValuesLevel2;
ClearValuesLevel3;
ClearValuesLevel4;
IdValues[c_DiskName ].sValue := ConvertChars(gDiskData.sDiskName);
IdValues[c_Folders ].sValue := ConvertChars(FormatNumber(gDiskData.iFolders));
IdValues[c_Files ].sValue := ConvertChars(FormatNumber(gDiskData.iFiles));
//IdValues[c_DiskName ].sValue := CP1250ToUtf8(ConvertChars(gDiskData.sDiskName));
//IdValues[c_Folders ].sValue := CP1250ToUtf8(ConvertChars(FormatNumber(gDiskData.iFolders)));
//IdValues[c_Files ].sValue := CP1250ToUtf8(ConvertChars(FormatNumber(gDiskData.iFiles)));
IdValues[c_Archives ].sValue := ConvertChars(FormatNumber(gDiskData.iArchives));
IdValues[c_TotalFilesInArchives ].sValue := ConvertChars(FormatNumber(gDiskData.iTotalFilesInArchives));
IdValues[c_TotalFoldersInArchives].sValue := ConvertChars(FormatNumber(gDiskData.iTotalFoldersInArchives));
IdValues[c_OriginalPath ].sValue := ConvertChars(gDiskData.sOriginalPath);
IdValues[c_VolumeLabel ].sValue := ConvertChars(gDiskData.sVolumelabel);
TmpComp := gDiskData.iDiskSizeKb;
IdValues[c_DiskSizeKb].sValue := ConvertChars(FormatBigSize(TmpComp * 1024));
TmpComp := gDiskData.iDiskFreeKb;
IdValues[c_DiskFreeKb].sValue := ConvertChars(FormatBigSize(TmpComp * 1024));
if (gDiskData.iDiskSizeKb = 0)
then IdValues[c_DiskFreePercent].sValue := '0%'
else IdValues[c_DiskFreePercent].sValue := IntToStr((gDiskData.iDiskFreeKb*100) div gDiskData.iDiskSizeKb) + '%';
IdValues[c_TotalDataSize ].sValue := ConvertChars(FormatBigSize(gDiskData.TotalDataSize));
IdValues[c_PhysSize ].sValue := ConvertChars(FormatBigSize(gDiskData.PhysSize));
IdValues[c_ArchSize ].sValue := ConvertChars(FormatBigSize(gDiskData.ArchSize));
IdValues[c_ScanDate ].sValue := ConvertChars(DosDateToStr(gDiskData.iScanDate) + ' ' + DosTimeToStr(gDiskData.iScanDate, false));
WriteSection(sSecDiskBegin);
end;
//-------------------------------------------------------------------
procedure TDBaseExport.OnDiskEnd;
begin
WriteSection(sSecDiskEnd);
end;
//-------------------------------------------------------------------
procedure TDBaseExport.OnFolderBegin;
begin
ClearValuesLevel3;
ClearValuesLevel4;
IdValues[c_PathToFolder ].sValue := ConvertChars(gFolderData.sPathToFolder);
IdValues[c_FolderName ].sValue := ConvertChars(gFolderData.sFolderName);
IdValues[c_FolderDataSize ].sValue := ConvertChars(FormatBigSize(gFolderData.FolderDataSize));
IdValues[c_FilesInFolder ].sValue := ConvertChars(FormatNumber(gFolderData.iFilesInFolder));
IdValues[c_FoldersInFolder ].sValue := ConvertChars(FormatNumber(gFolderData.iFoldersInFolder));
IdValues[c_PhysFolderDataSize ].sValue := ConvertChars(FormatBigSize(gFolderData.PhysFolderDataSize));
IdValues[c_PhysFilesInFolder ].sValue := ConvertChars(FormatNumber(gFolderData.iPhysFilesInFolder));
IdValues[c_PhysFoldersInFolder ].sValue := ConvertChars(FormatNumber(gFolderData.iPhysFoldersInFolder));
WriteSection(sSecFolderBegin);
end;
//-------------------------------------------------------------------
procedure TDBaseExport.OnFolderEnd;
begin
WriteFiles;
WriteSection(sSecFolderEnd);
end;
//-------------------------------------------------------------------
procedure TDBaseExport.OnFirstColumnBegin;
begin
WriteSection(sSecFirstColumnBegin);
end;
//-------------------------------------------------------------------
procedure TDBaseExport.OnEachColumnBegin;
begin
WriteSection(sSecEachColumnBegin);
end;
//-------------------------------------------------------------------
procedure TDBaseExport.OnFile;
var
OneFileLine: TOneFileLine; // pointer
begin
OneFileLine := TOneFileLine.Create(gFileData.OneFile);
FilesList.AddObject(GetSortString(gFileData.OneFile, OneFileLine.FileType,
gFormatSettings.SortCrit,
gFormatSettings.bReversedSort),
OneFileLine);
end;
//-------------------------------------------------------------------
// Used for immediate export of the file without putting it to
// the FileList
procedure TDBaseExport.WriteOneFile(var POneFile: TPOneFile);
begin
ClearValuesLevel3;
ClearValuesLevel4;
// disk name and folder name are changing in File Found List
IdValues[c_DiskName ].sValue := ConvertChars(gDiskData.sDiskName);
IdValues[c_FolderName].sValue := ConvertChars(gFolderData.sFolderName);
FillOneFile(POneFile);
WriteSection(sSecFile);
if POneFile^.Description <> 0 then WriteSection(sSecDesc);
inc(iFileCounter);
end;
//-------------------------------------------------------------------
procedure TDBaseExport.FillOneFile(var POneFile: TPOneFile);
var
sShortDesc : ShortString;
pBuffer : PChar;
sTmp : AnsiString;
i : integer;
iCrLfCounter : integer;
begin
IdValues[c_FileName ].sValue := ConvertChars(POneFile^.LongName +
POneFile^.Ext);
if (POneFile^.LongName = '..')
then
IdValues[c_FileSize].sValue := ''
else
if POneFile^.Attr and faDirectory = faDirectory
then IdValues[c_FileSize].sValue := ConvertChars(lsFolder)
else IdValues[c_FileSize].sValue := ConvertChars(FormatSize(POneFile^.Size,
gFormatSettings.bShowInKb));
if POneFile^.Time <> 0
then
begin
IdValues[c_FileTime ].sValue := ConvertChars(DosTimeToStr(POneFile^.Time,
gFormatSettings.bShowSeconds));
IdValues[c_FileDate ].sValue := ConvertChars(DosDateToStr(POneFile^.Time));
end
else
begin
IdValues[c_FileTime ].sValue := '';
IdValues[c_FileDate ].sValue := '';
end;
IdValues[c_ShortDesc].sValue := '';
IdValues[c_Desc ].sValue := '';
if POneFile^.Description <> 0 then
begin
sShortDesc[0] := #0;
QI_GetShortDesc(DBaseHandle, POneFile^.Description, sShortDesc);
IdValues[c_ShortDesc].sValue := ConvertChars(sShortDesc);
QI_LoadDescToBuf(DBaseHandle, POneFile^.Description, pBuffer);
sTmp := AdjustLineBreaks(StrPas(pBuffer));
StrDispose(pBuffer);
if (iMaxDescLines > 0) then
begin
i := 1;
iCrLfCounter := 0;
while i <= length(sTmp) do
begin
if (sTmp[i] = #13) then inc(iCrLfCounter);
if iCrLfCounter >= iMaxDescLines then break;
inc(i);
end;
if (iCrLfCounter >= iMaxDescLines) and (i > 1) and (i < length(sTmp)) then
SetLength(sTmp, i-1);
end;
if (iMaxDescSize > 0) and (iMaxDescSize < length(sTmp)) then
SetLength(sTmp, iMaxDescSize);
IdValues[c_Desc].sValue := ConvertChars(sTmp);
end;
end;
//-------------------------------------------------------------------
procedure TDBaseExport.WriteFiles;
var
OneFileLine : TOneFileLine;
Index : Integer;
iFilesInColumn: integer;
begin
iFilesInColumn := (FilesList.Count + iFileColumns - 1) div iFileColumns;
for Index := 0 to pred(FilesList.Count) do
begin
ClearValuesLevel4;
OneFileLine := TOneFileLine(FilesList.Objects[Index]);
FillOneFile(OneFileLine.POneFile);
if (Index = 0) then OnFirstColumnBegin;
if (Index = 0) or ((Index mod iFilesInColumn) = 0) then OnEachColumnBegin;
WriteSection(sSecFile);
if OneFileLine.POneFile^.Description <> 0 then WriteSection(sSecDesc);
if (Index = pred(FilesList.Count)) or (((Index+1) mod iFilesInColumn) = 0)
then OnEachColumnEnd;
if (Index = pred(FilesList.Count)) then OnLastColumnEnd;
inc(iFileCounter);
end;
FreeListObjects(FilesList);
FilesList.Clear;
end;
//-------------------------------------------------------------------
procedure TDBaseExport.OnEachColumnEnd;
begin
WriteSection(sSecEachColumnEnd);
end;
//-------------------------------------------------------------------
procedure TDBaseExport.OnLastColumnEnd;
begin
WriteSection(sSecLastColumnEnd);
end;
//-------------------------------------------------------------------
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.