text stringlengths 14 6.51M |
|---|
unit Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, Spin, Math, jpeg, Buttons;
const // Constante HelpText : le texte d'aide du programme ^^
HelpText='Ce programme vous permettra d''approximer Pi graçe à une méthode statistique dite de "rapport d''aire".'
+ chr(13)
+ 'Cette technique consiste à établir un rapport entre l''aire d''un carré, l''aire d''un cercle (ou un quadrant de cercle) et la distribution aléatoire de points dans le carré et le quadrant superposés.'
+ chr(13)
+ 'En effet, la formule de l''aire du cercle étant RPi² (ici R vaudra toujours pour plus de convénience) - ou celle du quadrant Pi/4, et celle du carré C² (soit 1), on obtient un rapport Pi/1 ou Pi/4/1.'
+ 'Si l''on considère que les points aléatoires répartis sur le cercle et le carré reflètent l''aire du carré et du cercle, on peut obtenir un rapport : Points dans le cercle/Points totaux = Pi/4, donc Points dans le cercle/Points totaux *4 = Pi.'
+ 'On peut donc approximer Pi statistiquement. Notez que si l''on définissait un Offset (un nombre de points totaux) égal à plus l''infini, statistiquement' + ', chaque aire serait totalement remplie de points, et par conséquent, on obtiendrait la valeur exacte de Pi.'
+ chr(13)
+ chr(13)
+ 'Définissez un nombre de points (noté Offset) pour approximer Pi - un nombre compris entre 1000 et 50000 sera adapté, car moins de 1000 points donnent une approximation imprécise' + ' de Pi, et plus de 50000 points rendent le calcul trop long. Gardez cependant en mémoire qu''il est possible d''obtenir la valeur exacte de Pi à partir de 500 points.'
+ 'Choisissez si vous désirez travailler sur un cercle ou un quadrant, puis choisissez si vous voulez voir des gros points ou ' + 'des petits points (les petits points sont plus rapidement dessinés que les gros points), et enfin choisissez si vous voulez voir les points apparaître l''un après l''autre (attention : cela ralentit le processus considérablement).'
+ 'Cliquez sur Calculer Pi (notez que vous pouvez cliquer sur Quitter à tout moment et interrompre' + ' le calcul). Une fois Pi calculé, le résultat s''affiche en vert si il est très proche de Pi, sinon il reste en blanc. Il peut être nécessaire de réessayer deux ou trois fois pour obtenir une valeur de Pi précise.'
+ 'La boîte d''informations située à l''extrême bas du panneau de contrôle vous informe à tout moment sur l''opération en cours.';
type
TMainForm = class(TForm)
DrawPanel: TPanel;
Img: TImage;
ControlPanel: TPanel;
TitleLabel: TLabel;
HeaderLabel: TLabel;
StatBox: TGroupBox;
OffsetLbl: TLabel;
OffsetValue: TSpinEdit;
RealtimeCheck: TCheckBox;
ResultBox: TGroupBox;
Res_NbLbl: TLabel;
Res_TickLbl: TLabel;
Res_PiLbl: TLabel;
ResEdit: TEdit;
GoBtn: TButton;
QuitBtn: TButton;
OperBox: TGroupBox;
OperLbl: TLabel;
ExactPi: TLabel;
Panel1: TPanel;
Image1: TImage;
UseCircle: TRadioButton;
UseArc: TRadioButton;
BigPointsBox: TCheckBox;
HelpBtn: TSpeedButton;
procedure FormCreate(Sender: TObject);
procedure QuitBtnClick(Sender: TObject);
procedure GoBtnClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure HelpBtnClick(Sender: TObject);
private
{ Déclarations privées }
public
{ Déclarations publiques }
procedure CleanImg;
procedure DrawArc;
procedure DrawCircle;
function DrawPt(X, Y: Integer): Boolean; // Dessine le point, et renvoie True si dans le quadrant ou le cercle
procedure DrawPoints;
function ProcessPi: Single;
end;
var
MainForm: TMainForm;
EndApp: Boolean; // Si il veut quitter l'application
NbPoints, NbIn: Integer; // Nombre de points totaux puis le nombre de points dans le quadrant
Realtime, BigPoints: Boolean; // Si le dessin se fait en temps réel
implementation
{$R *.dfm}
function DistanceOf(A, B: TPoint): Single; // Distance entre deux points
Var
MX, MY: Integer;
begin
MX := (A.X - B.X);
MY := (A.Y - B.Y);
Result := Sqrt(MX*MX + MY*MY);
// Sqr() est moins rapide qu'une pure multiplication
// On stocke MX et MY en mémoire car on les utilise 2 fois
end;
function InRange(Radius: Integer; Center, APoint: TPoint): Boolean; // Si un point APoint est dans un cercle de rayon Radius et de centre Center
begin
Result := (DistanceOf(APoint, Center) <= Radius);
// Si la distance du point au centre du cercle est inférieure au rayon ...
// ... alors il est dans le cercle (j'espère du moins ...)
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
EndApp := False;
Randseed := GetTickCount;
DoubleBuffered := True;
ControlPanel.DoubleBuffered := True;
ResultBox.DoubleBuffered := True;
StatBox.DoubleBuffered := True;
DrawPanel.DoubleBuffered := True;
ExactPi.Caption := 'Pi exact : ' + FloatToStr(Pi);
end;
procedure TMainForm.QuitBtnClick(Sender: TObject);
begin
Close;
end;
procedure TMainForm.GoBtnClick(Sender: TObject);
Var
S, E: Integer;
Res: Double;
begin
if (RealTimeCheck.Checked) and (OffsetValue.Value > 2500) then
if MessageDlg('Le dessin en temps réel risque d''être long avec plus de 2500 points. Continuer ?', mtWarning, [mbYes, mbNo], 0) = mrNo then Exit;
S := GetTickCount;
NbIn := 0;
NbPoints := OffsetValue.Value;
RealTime := RealTimeCheck.Checked;
BigPoints := BigPointsBox.Checked;
OperLbl.Caption := 'Effaçage du dessin précédent';
Application.ProcessMessages;
CleanImg;
case UseArc.Checked of
False:
begin
OperLbl.Caption := 'Dessin du cercle';
Application.ProcessMessages;
DrawCircle;
end;
True:
begin
OperLbl.Caption := 'Dessin du quadrant de cercle';
Application.ProcessMessages;
DrawArc;
end;
end;
OperLbl.Caption := 'Dessin des points';
Application.ProcessMessages;
DrawPoints;
OperLbl.Caption := 'Calcul approximatif de Pi';
Application.ProcessMessages;
Res := ProcessPi;
E := GetTickCount;
Res_NbLbl.Caption := 'Avec ' + IntToStr(NbPoints) + ' points ...';
Res_TickLbl.Caption := '... en ' + IntToStr(E - S) + ' millisecondes !';
OperLbl.Caption := 'Fin du calcul - Prêt !';
ResEdit.Text := FloatToStr(Res);
if Abs(Pi - Res) < 0.01 then ResEdit.Color := clGreen else ResEdit.Color := clWhite;
end;
procedure TMainForm.CleanImg;
begin
BitBlt(Img.Canvas.Handle, 0, 0, 401, 401, Img.Canvas.Handle, 0, 0, WHITENESS);
end;
procedure TMainForm.DrawArc;
Var
R: TRect;
begin
R.TopLeft := Point(-400, 0);
R.BottomRight := Point(400, 800);
Img.Canvas.Brush.Color := clWhite;
Img.Canvas.Pen.Color := clBlack;
Img.Canvas.Ellipse(R);
end;
procedure TMainForm.DrawCircle;
begin
Img.Canvas.Brush.Color := clWhite;
Img.Canvas.Pen.Color := clBlack;
Img.Canvas.Ellipse(Img.ClientRect);
end;
function TMainForm.DrawPt(X, Y: Integer): Boolean;
Var
Range: Integer;
Center: TPoint;
begin
case UseArc.Checked of
False:
begin
Range := 200;
Center := Point(200, 200);
end;
True:
begin
Range := 400;
Center := Point(0, 400);
end;
end;
Result := InRange(Range, Center, Point(X, Y));
case BigPoints of
False:
case Result of
False: Img.Canvas.Pixels[X, Y] := clBlack;
True: Img.Canvas.Pixels[X, Y] := clRed;
end;
True:
begin
case Result of
False: Img.Canvas.Pen.Color := clBlack;
True: Img.Canvas.Pen.Color := clRed;
end;
Img.Canvas.Brush.Color := Img.Canvas.Pen.Color;
Img.Canvas.Ellipse(X - 2, Y - 2, X + 2, Y + 2);
end;
end;
end;
procedure TMainForm.DrawPoints;
Var
I: Integer;
begin
for I := 1 to NbPoints do
begin
if EndApp then break;
if RealTime then Application.ProcessMessages;
if DrawPt(random(401), random(401)) then asm INC NbIn end; // Utilisation de l'asm pour aller encore plus vite :)
end;
end;
function TMainForm.ProcessPi: Single;
begin
Result := (NbIn/NbPoints)*4;
end;
procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
EndApp := True;
end;
procedure TMainForm.HelpBtnClick(Sender: TObject);
begin
MessageDlg(HelpText, mtInformation, [mbOK], 0);
end;
end.
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////// RAISONNEMENT POUR TROUVER UNE VALEUR APPROXIMATIVE DE PI //////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
{On utilise ici la statistique : on peut concevoir que la totalité des points
représente ici l'aire du carré, et que les points dans le quadrant représentent
l'aire du quadrant - or on sait que l'aire d'un quadrant est celle d'un cercle
divisée par 4 - soit Pi/4. Si on considère que le carré a une aire de 1 (soit
des dimensions de 1x1). On peut donc en déduire que le rapport :
Points dans le quadrant L'aire du quadrant
_______________________ équivaut statistiquement à __________________
Points totaux L'aire du carré
Comme l'aire du quadrant est égale à Pi/4, et que l'aire du carré est égale à 1
comme dit plus haut, alors :
Points dans le quadrant
_______________________ = Pi/4
Points totaux
On a juste a effectuer la division des points dans le quadrant sur les points totaux
(notons le résultat R), on obtient alors :
R = Pi/4
Donc, 4R = Pi
Si l'on résume :
Points dans le quadrant
_______________________ x 4 = Pi
Points totaux
Bien sûr ce ne sont que des statistiques : donc plus le nombre de points totaux (Offset)
est élevé, plus la statistique est précise.
}
|
unit Interfaces.Box;
interface
uses
System.Classes,
System.Types,
Vcl.ExtCtrls;
type
IBox = Interface(IInterface)
['{2D0FD04F-D399-40D1-ACF4-86B24EB2230A}']
function Position(const Value: TPoint): IBox; overload;
function Position: TPoint; overload;
function Owner(const Value: TGridPanel): IBox; overload;
function Owner: TGridPanel; overload;
function Key(const Value: Integer): IBox; overload;
function Key: Integer; overload;
function CreateImages: IBox;
function ChangeParent: IBox;
End;
implementation
end.
|
unit InflatablesList_HTML_Document;
{$INCLUDE '.\InflatablesList_defs.inc'}
interface
uses
Classes,
AuxTypes, CountedDynArrayObject, CountedDynArrayUnicodeChar,
InflatablesList_Types,
InflatablesList_HTML_TagAttributeArray;
type
TILHTMLElementNode = class(TObject)
private
fParent: TILHTMLElementNode;
fName: TILReconvString;
fOpen: Boolean;
fAttributes: TILTagAttributeCountedDynArray;
fTextArr: TCountedDynArrayUnicodeChar;
fText: TILReconvString;
fNestedText: TILReconvString;
fElements: TObjectCountedDynArray;
Function GetAttributeCount: Integer;
Function GetAttribute(Index: Integer): TILHTMLTagAttribute;
Function GetElementCount: Integer;
Function GetElement(Index: Integer): TILHTMLElementNode;
public
constructor Create(Parent: TILHTMLElementNode; const Name: TILReconvString);
constructor CreateAsCopy(Parent: TILHTMLElementNode; Source: TILHTMLElementNode; UniqueCopy: Boolean);
destructor Destroy; override;
procedure Close; virtual;
procedure TextFinalize; virtual;
Function AttributeIndexOfName(const Name: String): Integer; virtual;
Function AttributeIndexOfValue(const Value: String): Integer; virtual;
Function AttributeIndexOf(const Name, Value: String): Integer; virtual;
Function AttributeAdd(const Name,Value: String): Integer; virtual;
procedure AttributeDelete(Index: Integer); virtual;
procedure TextAppend(const Str: UnicodeString); overload; virtual;
procedure TextAppend(const Chr: UnicodeChar); overload; virtual;
Function ElementIndexOf(const Name: String): Integer; virtual;
Function ElementAdd(Element: TILHTMLElementNode): Integer; virtual;
procedure ElementDelete(Index: Integer); virtual;
Function GetSubElementsCount: Integer; virtual;
Function GetLevel: Integer; virtual;
Function Find(Stage: TObject; IncludeSelf: Boolean; var Storage: TObjectCountedDynArray): Integer; virtual;
procedure List(Strs: TStrings); virtual;
property Parent: TILHTMLElementNode read fParent;
property Open: Boolean read fOpen;
property Name: TILReconvString read fName;
property AttributeCount: Integer read GetAttributeCount;
property Attributes[Index: Integer]: TILHTMLTagAttribute read GetAttribute;
property Text: TILReconvString read fText;
property NestedText: TILReconvString read fNestedText;
property ElementCount: Integer read GetElementCount;
property Elements[Index: Integer]: TILHTMLElementNode read GetElement; default;
end;
TILHTMLDocument = class(TILHTMLElementNode);
TILHTMLElements = array of TILHTMLElementNode;
implementation
uses
SysUtils,
StrRect,
InflatablesList_Utils,
InflatablesList_HTML_ElementFinder;
Function TILHTMLElementNode.GetAttributeCount: Integer;
begin
Result := CDA_Count(fAttributes);
end;
//------------------------------------------------------------------------------
Function TILHTMLElementNode.GetAttribute(Index: Integer): TILHTMLTagAttribute;
begin
If (Index >= CDA_Low(fAttributes)) and (Index <= CDA_High(fAttributes)) then
Result := CDA_GetItem(fAttributes,Index)
else
raise Exception.CreateFmt('TILHTMLElementNode.GetAttribute: Index (%d) out of bounds.',[Index]);
end;
//------------------------------------------------------------------------------
Function TILHTMLElementNode.GetElementCount: Integer;
begin
Result := CDA_Count(fElements);
end;
//------------------------------------------------------------------------------
Function TILHTMLElementNode.GetElement(Index: Integer): TILHTMLElementNode;
begin
If (Index >= CDA_Low(fElements)) and (Index <= CDA_High(fElements)) then
Result := TILHTMLElementNode(CDA_GetItem(fElements,Index))
else
raise Exception.CreateFmt('TILHTMLElementNode.GetElement: Index (%d) out of bounds.',[Index]);
end;
//==============================================================================
constructor TILHTMLElementNode.Create(Parent: TILHTMLElementNode; const Name: TILReconvString);
begin
inherited Create;
fParent := Parent;
fName := IL_ThreadSafeCopy(Name);
fOpen := True;
CDA_Init(fAttributes);
CDA_Init(fTextArr);
fText := IL_ReconvString('');
fNestedText := IL_ReconvString('');
CDA_Init(fElements);
end;
//------------------------------------------------------------------------------
constructor TILHTMLElementNode.CreateAsCopy(Parent: TILHTMLElementNode; Source: TILHTMLElementNode; UniqueCopy: Boolean);
var
Temp: UnicodeString;
i: Integer;
begin
Create(Parent,Source.Name);
fOpen := Source.Open;
Source.TextFinalize;
// copy attributes
For i := 0 to Pred(Source.AttributeCount) do
CDA_Add(fAttributes,IL_ThreadSafeCopy(Source.Attributes[i]));
fText := IL_ThreadSafeCopy(Source.Text);
fNestedText := IL_ThreadSafeCopy(Source.NestedText);
CDA_Clear(fTextArr);
Temp := StrToUnicode(fText.Str);
For i := 1 to Length(Temp) do
CDA_Add(fTextArr,Temp[i]);
// copy elements
For i := 0 to Pred(Source.ElementCount) do
CDA_Add(fElements,TILHTMLElementNode.CreateAsCopy(Self,Source.Elements[i],True));
end;
//------------------------------------------------------------------------------
destructor TILHTMLElementNode.Destroy;
var
i: Integer;
begin
CDA_Clear(fAttributes);
CDA_Clear(fTextArr);
For i := CDA_Low(fElements) to CDA_High(fElements) do
FreeAndNil(CDA_GetItemPtr(fElements,i)^);
CDA_Clear(fElements);
inherited;
end;
//------------------------------------------------------------------------------
procedure TILHTMLElementNode.Close;
var
i: Integer;
begin
// close all subelements
For i := CDA_Low(fElements) to CDA_High(fElements) do
TILHTMLElementNode(CDA_GetItem(fElements,i)).Close;
fOpen := False;
end;
//------------------------------------------------------------------------------
procedure TILHTMLElementNode.TextFinalize;
var
Temp: UnicodeString;
i: Integer;
Nested: String;
begin
// finalize all subnodes
For i := CDA_Low(fElements) to CDA_High(fElements) do
TILHTMLElementNode(CDA_GetItem(fElements,i)).TextFinalize;
// finalize local text
SetLength(Temp,CDA_Count(fTextArr));
For i := CDA_Low(fTextArr) to CDA_High(fTextArr) do
Temp[i + 1] := CDA_GetItem(fTextArr,i);
fText := IL_ReconvString(UnicodeToStr(Temp));
// build nested text
Nested := fText.Str;
For i := CDA_Low(fElements) to CDA_High(fElements) do
Nested := Nested + TILHTMLElementNode(CDA_GetItem(fElements,i)).NestedText.Str;
fNestedText := IL_ReconvString(Nested);
end;
//------------------------------------------------------------------------------
Function TILHTMLElementNode.AttributeIndexOfName(const Name: String): Integer;
var
i: Integer;
begin
Result := -1;
For i := CDA_Low(fAttributes) to CDA_High(fAttributes) do
If IL_SameText(CDA_GetItem(fAttributes,i).Name.Str,Name) then
begin
Result := i;
Break{For i};
end;
end;
//------------------------------------------------------------------------------
Function TILHTMLElementNode.AttributeIndexOfValue(const Value: String): Integer;
var
i: Integer;
begin
Result := -1;
For i := CDA_Low(fAttributes) to CDA_High(fAttributes) do
If IL_SameText(CDA_GetItem(fAttributes,i).Value.Str,Value) then
begin
Result := i;
Break{For i};
end;
end;
//------------------------------------------------------------------------------
Function TILHTMLElementNode.AttributeIndexOf(const Name, Value: String): Integer;
var
i: Integer;
begin
Result := -1;
For i := CDA_Low(fAttributes) to CDA_High(fAttributes) do
If IL_SameText(CDA_GetItem(fAttributes,i).Name.Str,Name) and
IL_SameText(CDA_GetItem(fAttributes,i).Value.Str,Value) then
begin
Result := i;
Break{For i};
end;
end;
//------------------------------------------------------------------------------
Function TILHTMLElementNode.AttributeAdd(const Name,Value: String): Integer;
var
Temp: TILHTMLTagAttribute;
begin
Temp.Name := IL_ReconvString(Name);
Temp.Value := IL_ReconvString(Value);
Result := CDA_Add(fAttributes,Temp);
end;
//------------------------------------------------------------------------------
procedure TILHTMLElementNode.AttributeDelete(Index: Integer);
begin
If (Index >= CDA_Low(fAttributes)) and (Index <= CDA_High(fAttributes)) then
CDA_Delete(fAttributes,Index)
else
raise Exception.CreateFmt('TILHTMLElementNode.AttributeDelete: Index (%d) out of bounds.',[Index]);
end;
//------------------------------------------------------------------------------
procedure TILHTMLElementNode.TextAppend(const Str: UnicodeString);
var
i: Integer;
begin
For i := 1 to Length(Str) do
CDA_Add(fTextArr,Str[i]);
end;
//------------------------------------------------------------------------------
procedure TILHTMLElementNode.TextAppend(const Chr: UnicodeChar);
begin
CDA_Add(fTextArr,Chr);
end;
//------------------------------------------------------------------------------
Function TILHTMLElementNode.ElementIndexOf(const Name: String): Integer;
var
i: Integer;
begin
Result := -1;
For i := CDA_Low(fElements) to CDA_High(fElements) do
If IL_SameText(TILHTMLElementNode(CDA_GetItem(fElements,i)).Name.Str,Name) then
begin
Result := i;
Break{For i};
end;
end;
//------------------------------------------------------------------------------
Function TILHTMLElementNode.ElementAdd(Element: TILHTMLElementNode): Integer;
begin
Result := CDA_Add(fElements,Element);
end;
//------------------------------------------------------------------------------
procedure TILHTMLElementNode.ElementDelete(Index: Integer);
begin
If (Index >= CDA_Low(fElements)) and (Index <= CDA_High(fElements)) then
begin
FreeAndNil(CDA_GetItemPtr(fElements,Index)^);
CDA_Delete(fElements,Index);
end
else raise Exception.CreateFmt('TILHTMLElementNode.ElementDelete: Index (%d) out of bounds.',[Index]);
end;
//------------------------------------------------------------------------------
Function TILHTMLElementNode.GetSubElementsCount: Integer;
var
i: Integer;
begin
Result := CDA_Count(fElements);
For i := CDA_Low(fElements) to CDA_High(fElements) do
Inc(Result,TILHTMLElementNode(CDA_GetItem(fElements,i)).GetSubElementsCount);
end;
//------------------------------------------------------------------------------
Function TILHTMLElementNode.GetLevel: Integer;
begin
If Assigned(fParent) then
Result := fParent.GetLevel + 1
else
Result := 0;
end;
//------------------------------------------------------------------------------
Function TILHTMLElementNode.Find(Stage: TObject; IncludeSelf: Boolean; var Storage: TObjectCountedDynArray): Integer;
var
FinderStage: TILElementFinderStage;
i: Integer;
begin
Result := 0;
FinderStage := Stage as TILElementFinderStage;
FinderStage.ReInit;
If IncludeSelf then
If FinderStage.Compare(Self) then
begin
CDA_Add(Storage,Self);
Inc(Result);
end;
For i := CDA_Low(fElements) to CDA_High(fElements) do
begin
FinderStage.ReInit;
If FinderStage.Compare(TILHTMLElementNode(CDA_GetItem(fElements,i))) then
begin
CDA_Add(Storage,CDA_GetItem(fElements,i));
Inc(Result);
end;
// recurse
Inc(Result,TILHTMLElementNode(CDA_GetItem(fElements,i)).Find(Stage,False,Storage));
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLElementNode.List(Strs: TStrings);
var
i: Integer;
begin
Strs.Add(IL_Format('%s<%s>',[IL_StringOfChar(' ',GetLevel * 2),fName.Str]));
For i := CDA_Low(fAttributes) to CDA_High(fAttributes) do
Strs.Add(StringOfChar(' ',GetLevel * 2) + IL_Format(' %s="%s"',
[CDA_GetItem(fAttributes,i).Name.Str,CDA_GetItem(fAttributes,i).Value.Str]));
For i := CDA_Low(fElements) to CDA_High(fElements) do
TILHTMLElementNode(CDA_GetItem(fElements,i)).List(Strs);
If CDA_Count(fElements) > 0 then
Strs.Add(IL_Format('%s</%s>',[IL_StringOfChar(' ',GetLevel * 2),fName.Str]));
end;
end.
|
unit uFrmMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, StrUtils;
type
TfrmMain = class(TForm)
mmoSQLList: TMemo;
btnDo: TButton;
procedure btnDoClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
{-------------------------------------------------------------------------------
过程名: MakeFileList 遍历文件夹及子文件夹
作者: SWGWEB
日期: 2007.11.25
参数: Path,FileExt:string 1.需要遍历的目录 2.要遍历的文件扩展名
返回值: TStringList
Eg:ListBox1.Items:= MakeFileList( 'E:\极品飞车','.exe') ;
ListBox1.Items:= MakeFileList( 'E:\极品飞车','.*') ;
-------------------------------------------------------------------------------}
function MakeFileList(Path, FileExt: string): TStringList;
var
sch : TSearchrec;
begin
Result := TStringlist.Create;
if rightStr(trim(Path), 1) <> '\' then
Path := trim(Path) + '\'
else
Path := trim(Path);
if not DirectoryExists(Path) then
begin
Result.Clear;
exit;
end;
if FindFirst(Path + '*', faAnyfile, sch) = 0 then
begin
repeat
Application.ProcessMessages;
if ((sch.Name = '.') or (sch.Name = '..')) then
Continue;
if DirectoryExists(Path + sch.Name) then
begin
Result.AddStrings(MakeFileList(Path + sch.Name, FileExt));
end
else
begin
if (UpperCase(extractfileext(Path + sch.Name)) = UpperCase(FileExt)) or
(FileExt = '.*') then
Result.Add(Path + sch.Name);
end;
until FindNext(sch) <> 0;
SysUtils.FindClose(sch);
end;
end;
procedure TfrmMain.btnDoClick(Sender: TObject);
var
aFileList, aOneFile, aHBFile: TStringlist;
aFile: TFileStream;
aExePath, aFilePath: string;
i: Integer;
begin
aExePath := ExtractFilePath(ParamStr(0));
aFileList := MakeFileList(aExePath + 'DBSQL\Function', '.*');
aFileList.AddStrings(MakeFileList(aExePath + 'DBSQL\Procedure', '.*'));
aOneFile := TStringList.Create;
aHBFile := TStringList.Create;
try
aHBFile.Clear;
mmoSQLList.Clear;
mmoSQLList.Lines.Add('日志:');
for i := 0 to aFileList.Count - 1 do
begin
aFilePath := aFileList[i];
aOneFile.LoadFromFile(aFilePath);
aHBFile.AddStrings(aOneFile);
aHBFile.Add('');
aHBFile.Add('');
aHBFile.Add('');
mmoSQLList.Lines.Add(aFilePath + '已合并');
end;
aHBFile.SaveToFile(aExePath + 'xxSelf.Sql');
Application.MessageBox('合并完成','提示', mrNone);
Close;
finally
aHBFile.Free;
aOneFile.Free;
aFileList.Free;
end;
end;
end.
|
unit UEngineArchivesExt;
(*====================================================================
Functions for accessing RAR and ACE archives via DLLs from RAR and ACE
======================================================================*)
interface
const
ERAR_END_ARCHIVE = 10;
ERAR_NO_MEMORY = 11;
ERAR_BAD_DATA = 12;
ERAR_BAD_ARCHIVE = 13;
ERAR_UNKNOWN_FORMAT = 14;
ERAR_EOPEN = 15;
ERAR_ECREATE = 16;
ERAR_ECLOSE = 17;
ERAR_EREAD = 18;
ERAR_EWRITE = 19;
ERAR_SMALL_BUF = 20;
ERAR_UNKNOWN = 21;
RAR_OM_LIST = 0;
RAR_OM_EXTRACT = 1;
RAR_SKIP = 0;
RAR_TEST = 1;
RAR_EXTRACT = 2;
RAR_VOL_ASK = 0;
RAR_VOL_NOTIFY = 1;
type
TRarOpenArchiveData = record
ArcName : PChar;
OpenMode : longword;
OpenResult: longword;
CmtBuf : PChar;
CmtBufSize: longword;
CmtSize : longword;
CmtState : longword;
end;
TRarHeaderData = record
ArcName : array[0..259] of char;
FileName : array[0..259] of char;
Flags : longword;
PackSize : longword;
UnpSize : longword;
HostOS : longword;
FileCRC : longword;
FileTime : longword;
UnpVer : longword;
Method : longword;
FileAttr : longword;
CmtBuf : pChar;
CmtBufSize: longword;
CmtSize : longword;
CmtState : longword;
end;
TRarOpenArchive = function (var ArchiveData: TRarOpenArchiveData): longword; stdcall;
TRarCloseArchive = function (hArcData: longword): longint; stdcall;
TRarReadHeader = function (hArcData: longword; var HeaderData: TRarHeaderData): longint; stdcall;
TRarProcessFile = function (hArcData: longword; Operation: longint;
DestPath: pChar; DestName: pChar): longint; stdcall;
TRarGetDllVersion = function (): longint; stdcall;
var
RarOpenArchive : TRarOpenArchive;
RarCloseArchive : TRarCloseArchive;
RarReadHeader : TRarReadHeader;
RarProcessFile : TRarProcessFile;
RarGetDllVersion: TRarGetDllVersion;
function UnRarDllLoaded(): boolean;
//-----------------------------------------------------------------------------
implementation
uses
{$ifdef mswindows}
Windows
{$ELSE}
LCLIntf, LCLType, LMessages, ComCtrls,
{$ENDIF}
SysUtils, UBaseUtils;
var
DllHandle: THandle;
RarOpenArchiveData: TRarOpenArchiveData;
RarHeaderData : TRarHeaderData;
DllName: String;
ZString: array[0..256] of char;
iRarDllLoaded : integer;
iVersion: longint;
iAceDllLoaded : integer;
//-----------------------------------------------------------------------------
function UnRarDllLoaded(): boolean;
begin
Result := false;
{$ifdef mswindows}
if (iRarDllLoaded = -1) then // we did not try it yet
begin
iRarDllLoaded := 0;
DllName := 'unrar.dll';
DllHandle := LoadLibrary(StrPCopy(ZString, GetProgramDir + DllName));
if DllHandle <= 32 then exit;
@RarOpenArchive := GetProcAddress(DllHandle, 'RAROpenArchive' );
@RarCloseArchive := GetProcAddress(DllHandle, 'RARCloseArchive');
@RarReadHeader := GetProcAddress(DllHandle, 'RARReadHeader' );
@RarProcessFile := GetProcAddress(DllHandle, 'RARProcessFile' );
@RarGetDllVersion:= GetProcAddress(DllHandle, 'RARGetDllVersion');
if ((@RarOpenArchive = nil) or
(@RarCloseArchive = nil) or
(@RarReadHeader = nil) or
(@RarProcessFile = nil) or
(@RarGetDllVersion= nil)) then
begin
FreeLibrary(DllHandle);
exit;
end;
iRarDllLoaded := 1;
iVersion := RarGetDllVersion;
end;
Result := iRarDllLoaded = 1;
{$endif}
end;
//-----------------------------------------------------------------------------
begin
iRarDllLoaded := -1;
iAceDllLoaded := -1;
end.
|
unit HS4Bind.Send;
interface
uses
RESTRequest4D,
HS4Bind.Interfaces,
System.Classes,
Vcl.ExtCtrls;
type
THS4BindSend = class(TInterfacedObject, iHS4BindSend)
private
FParent : iHS4Bind;
FFileName : String;
FContentType : String;
FFileStream : TBytesStream;
FEndPoint : string;
FContent : string;
FPath : string;
public
constructor Create(Parent : iHS4Bind);
destructor Destroy; override;
class function New (aParent : iHS4Bind): iHS4BindSend;
function Send : iHS4BindSend;
function FileName( aValue : String ) : iHS4BindSend;
function ContentType( aValue : String ) : iHS4BindSend;
function EndPoint(aValue : string) : iHS4BindSend;
function Path(aValue : string) : iHS4BindSend;
function FileStream( aValue : TBytesStream ) : iHS4BindSend; overload;
function FileStream( aValue : TImage ) : iHS4BindSend; overload;
function ToString : string;
end;
implementation
{ THS4BindSend }
function THS4BindSend.ContentType(aValue: String): iHS4BindSend;
begin
Result:= Self;
FContentType:= aValue;
end;
constructor THS4BindSend.Create(Parent : iHS4Bind);
begin
FParent:= Parent;
end;
destructor THS4BindSend.Destroy;
begin
inherited;
end;
function THS4BindSend.EndPoint(aValue: string): iHS4BindSend;
begin
result:= self;
FEndPoint:= aValue;
end;
function THS4BindSend.FileName(aValue: String): iHS4BindSend;
begin
Result:= Self;
FFileName:= aValue;
end;
function THS4BindSend.FileStream(aValue: TBytesStream): iHS4BindSend;
begin
Result := Self;
FFileStream := aValue;
end;
function THS4BindSend.FileStream(aValue: TImage): iHS4BindSend;
begin
Result := Self;
if not Assigned(FFileStream) then
FFileStream := TBytesStream.Create();
{$IFDEF HAS_FMX}
aValue.Bitmap.SaveToStream(FFileStream);
{$ELSE}
aValue.Picture.SaveToStream(FFileStream);
{$ENDIF}
end;
class function THS4BindSend.New(aParent : iHS4Bind): iHS4BindSend;
begin
Result:= Self.Create(aParent);
end;
function THS4BindSend.Path(aValue: string): iHS4BindSend;
begin
Result:= Self;
FPath:= aValue;
end;
function THS4BindSend.Send : iHS4BindSend;
var
LResponse: IResponse;
lHost : string;
begin
Result:= Self;
lHost:= copy(FParent.Credential.BaseURL,(pos('//',FParent.Credential.BaseURL)+2), length(FParent.Credential.BaseURL));
lHost:= copy(lHost,0,(pos(':',lHost)-1));
LResponse :=
TRequest.New.BaseURL(FParent.Credential.BaseURL+FEndPoint)
.ContentType(FContentType)
.AddHeader('FileName', FFileName)
.AddHeader('Path', FPath)
.AddHeader('Host', lHost)
.Accept('*/*')
.AddBody(FFileStream)
.Post;
if LResponse.StatusCode = 201 then
FContent:= FParent.Credential.BaseURL + LResponse.Content;
end;
function THS4BindSend.ToString: string;
begin
Result:= FContent;
end;
end.
|
unit fmForma20;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, cxLabel, cxControls, cxContainer, cxEdit, cxTextEdit,
cxMaskEdit, cxButtonEdit, cxLookAndFeelPainters, StdCtrls, cxButtons,
cxDropDownEdit, cxCalendar, ActnList, IBase, uCommonSp,
Asup_LoaderPrintDocs_Types, Asup_LoaderPrintDocs_Proc,
Asup_LoaderPrintDocs_WaitForm, ASUP_LoaderPrintDocs_Consts,
ASUP_LoaderPrintDocs_Messages, cxMRUEdit, cxCheckBox, DB, FIBDatabase,
pFIBDatabase, FIBDataSet, pFIBDataSet, cxLookupEdit, cxDBLookupEdit,
cxDBLookupComboBox, cxSpinEdit, uFControl, uLabeledFControl,
uSpravControl, uCharControl, uIntControl;
type
TFormOptions = class(TForm)
Bevel1: TBevel;
YesBtn: TcxButton;
CancelBtn: TcxButton;
ActionList: TActionList;
YesAction: TAction;
CancelAction: TAction;
DesRep: TAction;
EditDepartment: TcxButtonEdit;
LabelDepartment: TcxLabel;
CheckBoxWithChild: TcxCheckBox;
DSet: TpFIBDataSet;
Bevel2: TBevel;
LabelDateBeg: TcxLabel;
DateEditBeg: TcxDateEdit;
LabelDateEnd: TcxLabel;
DateEditEnd: TcxDateEdit;
FontBtn: TcxButton;
FontAction: TAction;
FontDialogs: TFontDialog;
procedure CancelActionExecute(Sender: TObject);
procedure YesActionExecute(Sender: TObject);
procedure DesRepExecute(Sender: TObject);
procedure EditDepartmentPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure FontActionExecute(Sender: TObject);
private
PDb_Handle:TISC_DB_HANDLE;
PId_Depratment:integer;
PFontNames:string;
PFontSizes:integer;
PFontColors:TColor;
PFontStyles:TFontStyles;
PDesignRep: Boolean;
public
constructor Create(AParameter:TSimpleParam);reintroduce;
property Id_Department:integer read PId_Depratment;
property FontNames:string read PFontNames;
property FontSizes:integer read PFontSizes;
property FontColors:TColor read PFontColors;
property FontStyles:TFontStyles read PFontStyles;
property DesignRep:Boolean read PDesignRep write PDesignRep;
end;
implementation
uses dmForma20;
{$R *.dfm}
constructor TFormOptions.Create(AParameter:TSimpleParam);
var Year, Month, Day: Word; str:string;
begin
inherited Create(AParameter.Owner);
PDb_Handle:=DM.DB.Handle;
Caption := 'Інформація про закінчення трудових договорів ПВС (форма №20)';
YesBtn.Caption := YesBtn_Caption;
CancelBtn.Caption := CancelBtn_Caption;
FontBtn.Caption := FontBtn_Caption;
YesBtn.Hint := YesBtn.Caption;
CancelBtn.Hint := CancelBtn.Caption;
FontBtn.Hint := FontBtn.Caption;
LabelDepartment.Caption := Label_Department_Caption;
CheckBoxWithChild.Properties.Caption := CheckBoxWithChild_Caption;
PId_Depratment:=-255;
PFontNames:='Times New Roman';
PFontSizes:=-255;
PFontColors:=clDefault;
PDesignRep:=false;
LabelDateBeg.Caption := Label_DateBeg_Caption;
LabelDateEnd.Caption := Label_DateEnd_Caption;
//*******************************************
DecodeDate(Date,Year, Month, Day);
if (Month<9) then Year:=Year-1;
str:='01.09.'+inttostr(year);
DateEditBeg.Date:=strtodate(str);
DecodeDate(Date,Year, Month, Day);
if (Month>=9) then Year:=Year+1;
str:='30.06.'+inttostr(year);
DateEditEnd.Date:=strtodate(str);
//*******************************************
DSet.SQLs.SelectSQL.Text := 'SELECT CURRENT_DEPARTMENT, FIRM_NAME FROM INI_ASUP_CONSTS';
DSet.Database:=DM.DB;
DSet.Transaction:=DM.ReadTransaction;
DSet.UpdateTransaction:=DM.ReadTransaction;
DSet.Open;
EditDepartment.Text:= DSet.FieldValues['FIRM_NAME'];
PId_Depratment:=DSet.FieldValues['CURRENT_DEPARTMENT'];
end;
procedure TFormOptions.CancelActionExecute(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TFormOptions.YesActionExecute(Sender: TObject);
begin
if EditDepartment.Text='' then
begin
AsupShowMessage(Error_Caption,E_NotSelectDepartment_Text,mtWarning,[mbOK]);
Exit;
end;
ModalResult := mrYes;
end;
procedure TFormOptions.EditDepartmentPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var sp: TSprav;
begin
sp := GetSprav('SpDepartment');
if sp <> nil then
begin
// заполнить входные параметры
with sp.Input do
begin
Append;
FieldValues['DBHandle'] := Integer(PDb_Handle);
FieldValues['ShowStyle'] := 0;
FieldValues['Select'] := 1;
FieldValues['Actual_Date'] := DateEditEnd.Date;
Post;
end;
end;
sp.Show;
if sp.Output = nil then
ShowMessage('Не обрано жодного підрозділу!')
else
if not sp.Output.IsEmpty then
begin
EditDepartment.Text := varToStr(sp.Output['NAME_FULL']);
PId_Depratment:=sp.Output['ID_DEPARTMENT'];
end;
sp.Free;
end;
procedure TFormOptions.DesRepExecute(Sender: TObject);
begin
PDesignRep:=not PDesignRep;
end;
procedure TFormOptions.FontActionExecute(Sender: TObject);
begin
if FontDialogs.Execute
then
begin
PFontNames := FontDialogs.Font.Name;
PFontSizes := FontDialogs.Font.Size;
PFontColors := FontDialogs.Font.Color;
PFontStyles := FontDialogs.Font.Style;
end;
end;
end.
|
{$I CetusOptions.inc}
unit ctsUtils;
interface
function OutRange(const aIndex, aLow, aHight: LongInt): Boolean;
implementation
function OutRange(const aIndex, aLow, aHight: LongInt): Boolean;
begin
Result := (aIndex < 0) or (aIndex >= aHight);
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Core.Spec.FileEntry;
interface
uses
JsonDataObjects,
Spring.Collections,
DPM.Core.Logging,
DPM.Core.Spec.Interfaces,
DPM.Core.Spec.Node;
type
TSpecFileEntry = class(TSpecNode, ISpecFileEntry)
private
protected
//making these protected to simplify clone;
FSource : string;
FDestination : string;
FExclude : IList<string>;
FFlatten : boolean;
FIgnore : boolean;
function LoadFromJson(const jsonObject : TJsonObject) : Boolean; override;
function GetSource : string;
function GetDestination : string;
function GetExclude : IList<string>;
function GetFlatten : Boolean;
procedure SetSource(const value : string);
procedure SetDestination(const value : string);
function GetIgnore : boolean;
constructor CreateClone(const logger : ILogger; const src : string; const dest : string; const exclude : IList<string>; const flatten : boolean; const ignore : boolean); virtual;
function Clone : ISpecFileEntry;
public
constructor Create(const logger : ILogger); override;
end;
implementation
uses
System.SysUtils;
{ TSpecFileEntry }
function TSpecFileEntry.Clone : ISpecFileEntry;
begin
result := TSpecFileEntry.CreateClone(logger, FSource, FDestination, FExclude, FFlatten, FIgnore);
end;
constructor TSpecFileEntry.Create(const logger : ILogger);
begin
inherited Create(Logger);
FExclude := TCollections.CreateList < string > ;
end;
constructor TSpecFileEntry.CreateClone(const logger : ILogger; const src, dest : string; const exclude : IList<string> ; const flatten : boolean; const ignore : boolean);
begin
inherited Create(logger);
FSource := src;
FDestination := dest;
FExclude := TCollections.CreateList < string > ;
FExclude.AddRange(exclude);
FFlatten := flatten;
FIgnore := ignore;
end;
function TSpecFileEntry.GetExclude : IList<string>;
begin
result := FExclude;
end;
function TSpecFileEntry.GetFlatten : Boolean;
begin
result := FFlatten;
end;
function TSpecFileEntry.GetIgnore : boolean;
begin
result := FIgnore;
end;
function TSpecFileEntry.GetSource : string;
begin
result := FSource;
end;
function TSpecFileEntry.GetDestination : string;
begin
result := FDestination;
end;
function TSpecFileEntry.LoadFromJson(const jsonObject : TJsonObject) : Boolean;
var
excludeArray : TJsonArray;
entry : string;
i : Integer;
begin
result := true;
FSource := jsonObject.S['src'];
if FSource = '' then
begin
result := false;
Logger.Error('Required attribute [src] is missing');
end;
if not jsonObject.Contains('dest') then
begin
result := false;
Logger.Error('Required attribute [dest] is missing for [' + FSource + ']');
FDestination := '';
end
else
FDestination := jsonObject.S['dest'];
FFlatten := jsonObject.B['flatten'];
FIgnore := jsonObject.B['ignore'];
if jsonObject.Contains('exclude') then
begin
excludeArray := jsonObject.A['exclude']; //this is causing an av!
for i := 0 to excludeArray.Count - 1 do
begin
entry := excludeArray.S[i];
if entry <> '' then
FExclude.Add(entry);
end;
end;
end;
procedure TSpecFileEntry.SetSource(const value : string);
begin
FSource := value;
end;
procedure TSpecFileEntry.SetDestination(const value : string);
begin
FDestination := value;
end;
end.
|
unit ibSHDDLCompiler;
interface
uses
SysUtils, Classes, Dialogs, Types,
SynEditTypes,
SHDesignIntf, SHOptionsIntf, pSHIntf,
ibSHDesignIntf, ibSHDriverIntf, ibSHConsts, ibSHComponent;
type
TibBTDDLCompiler = class(TibBTComponent, IibSHDDLCompiler)
private
FDDLParser: TComponent;
FDRVQueryIntf: IibSHDRVQuery;
FErrorText: string;
FErrorLine: Integer;
FErrorColumn: Integer;
FDDLHistory: IibSHDDLHistory;
function GetErrorCoord(AErrorText: string): TBufferCoord;
function GetDDLHistory: IibSHDDLHistory;
protected
function GetDDLParser: ISHDDLParser;
function GetErrorText: string;
function GetErrorLine: Integer;
function GetErrorColumn: Integer;
procedure AddToHistory(AText: string);
property DDLHistory: IibSHDDLHistory read GetDDLHistory;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
function Compile(const Intf: IInterface; ADDL: string): Boolean;
procedure AfterCommit(Sender: TObject; SenderClosing: Boolean = False);
procedure AfterRollback(Sender: TObject; SenderClosing: Boolean = False);
property DDLParser: ISHDDLParser read GetDDLParser;
property DRVQuery: IibSHDRVQuery read FDRVQueryIntf;
end;
implementation
{ TibBTDDLCompiler }
constructor TibBTDDLCompiler.Create(AOwner: TComponent);
var
vComponentClass: TSHComponentClass;
begin
inherited Create(AOwner);
vComponentClass := Designer.GetComponent(IibSHDDLParser);
if Assigned(vComponentClass) then FDDLParser := vComponentClass.Create(nil);
end;
destructor TibBTDDLCompiler.Destroy;
begin
FDRVQueryIntf := nil;
FDDLParser.Free;
inherited Destroy;
end;
procedure TibBTDDLCompiler.Notification(AComponent: TComponent;
Operation: TOperation);
begin
if (Operation = opRemove) then
begin
if AComponent.IsImplementorOf(FDDLHistory) then FDDLHistory := nil;
end;
inherited Notification(AComponent, Operation);
end;
function TibBTDDLCompiler.GetErrorCoord(AErrorText: string): TBufferCoord;
var
vPos: Integer;
vCoordString: string;
begin
Result := TBufferCoord(Point(0, -1));
vPos := Pos('- line ', AErrorText);
if vPos = 0 then
begin
vPos := Pos('At line ', AErrorText);
if vPos > 0 then
Inc(vPos);
end;
if vPos > 0 then
begin
Inc(vPos, 7);
vCoordString := EmptyStr;
while (vPos < Length(AErrorText)) and (AErrorText[vPos] in Digits) do
begin
vCoordString := vCoordString + AErrorText[vPos];
Result.Line := StrToIntDef(vCoordString, -1);
Inc(vPos);
end;
vPos := Pos(', char ', AErrorText);
if vPos = 0 then
begin
vPos := Pos(', column ', AErrorText);
if vPos > 0 then
Inc(vPos, 2);
end;
Inc(vPos, 7);
vCoordString := EmptyStr;
while (vPos < Length(AErrorText)) and (AErrorText[vPos] in Digits) do
begin
vCoordString := vCoordString + AErrorText[vPos];
Result.Char := StrToIntDef(vCoordString, -1);
Inc(vPos);
end;
end;
end;
function TibBTDDLCompiler.GetDDLHistory: IibSHDDLHistory;
var
vHistoryComponent: TSHComponent;
vHistoryComponentClass: TSHComponentClass;
vSHSystemOptions: ISHSystemOptions;
begin
if not Assigned(FDDLHistory) then
begin
if not Supports(Designer.FindComponent(OwnerIID, IibSHDDLHistory), IibSHDDLHistory, FDDLHistory) then
begin
vHistoryComponentClass := Designer.GetComponent(IibSHDDLHistory);
if Assigned(vHistoryComponentClass) then
begin
vHistoryComponent := vHistoryComponentClass.Create(nil);
vHistoryComponent.OwnerIID := OwnerIID;
if Supports(vHistoryComponent, IibSHDDLHistory, FDDLHistory) then
begin
if Assigned(FDDLHistory.BTCLDatabase) and
Supports(Designer.GetOptions(ISHSystemOptions), ISHSystemOptions, vSHSystemOptions) and
(not vSHSystemOptions.UseWorkspaces) then
vHistoryComponent.Caption := Format('%s for %s', [Designer.GetComponent(IibSHDDLHistory).GetHintClassFnc, FDDLHistory.BTCLDatabase.Alias])
else
vHistoryComponent.Caption := Designer.GetComponent(IibSHDDLHistory).GetHintClassFnc;
end;
end;
end;
ReferenceInterface(FDDLHistory, opInsert);
end;
Result := FDDLHistory;
end;
function TibBTDDLCompiler.GetDDLParser: ISHDDLParser;
begin
Supports(FDDLParser, IibSHDDLParser, Result);
end;
function TibBTDDLCompiler.GetErrorText: string;
begin
Result := FErrorText;
end;
function TibBTDDLCompiler.GetErrorLine: Integer;
begin
Result := FErrorLine;
end;
function TibBTDDLCompiler.GetErrorColumn: Integer;
begin
Result := FErrorColumn;
end;
procedure TibBTDDLCompiler.AddToHistory(AText: string);
begin
if Assigned(DDLHistory) then
DDLHistory.AddStatement(AText);
end;
function TibBTDDLCompiler.Compile(const Intf: IInterface; ADDL: string): Boolean;
var
I: Integer;
vErrorCoord: TBufferCoord;
s:string;
begin
FErrorText := EmptyStr;
FErrorLine := -1;
FErrorColumn := -1;
Supports(Intf, IibSHDRVQuery, FDRVQueryIntf);
try
Result := Assigned(DRVQuery) and (Length(ADDL) > 0) and DDLParser.Parse(ADDL);
if Result then
begin
if DDLParser.Count > 0 then
begin
for I := 0 to Pred(DDLParser.Count) do
begin
if DDLParser.IsDataSQL(I) and Assigned(DRVQuery) then
begin
{ DEPRECATED - DDL Form не обрабатывает в скрипте COMMIT, ROLLBACK, RECONNECT
if (DDLParser.StatementState(I) = csUnknown) and
SameText(DDLParser.StatementObjectName(I), 'COMMIT') then
begin
DRVQuery.Transaction.Commit;
FErrorText := DRVQuery.Transaction.ErrorText;
if Length(FErrorText) = 0 then
begin
if Assigned(DDLHistory) then DDLHistory.CommitNewStatements;
end
else
if Assigned(DDLHistory) then DDLHistory.RollbackNewStatements;
end else
if (DDLParser.StatementState(I) = csUnknown) and
SameText(DDLParser.StatementObjectName(I), 'ROLLBACK') then
begin
DRVQuery.Transaction.Rollback;
FErrorText := DRVQuery.Transaction.ErrorText;
if Assigned(DDLHistory) then DDLHistory.RollbackNewStatements;
end else
if (DDLParser.StatementState(I) = csUnknown) and
SameText(DDLParser.StatementObjectName(I), 'RECONNECT') then
begin
if DRVQuery.Transaction.InTransaction then
begin
DRVQuery.Transaction.Rollback;
FErrorText := DRVQuery.Transaction.ErrorText;
if Assigned(DDLHistory) then DDLHistory.RollbackNewStatements;
end;
if Length(FErrorText) = 0 then
begin
DRVQuery.Database.Reconnect;
FErrorText := DRVQuery.Database.ErrorText;
end;
end else
begin}
s:= DDLParser.Statements[I];
DRVQuery.ExecSQL(s, [], False);
if Assigned(DRVQuery) then FErrorText := DRVQuery.ErrorText;
{end;}
Result := Length(FErrorText) = 0;
if not Result then
begin
vErrorCoord := GetErrorCoord(FErrorText);
if (vErrorCoord.Char <> 0) or (vErrorCoord.Line <> -1) then
begin
if (I >= 0) and (I < DDLParser.Count) then
begin
if vErrorCoord.Line = 1 then
vErrorCoord.Char := vErrorCoord.Char + DDLParser.StatementsCoord(I).Left - 1;
vErrorCoord.Line := vErrorCoord.Line + DDLParser.StatementsCoord(I).Top;
FErrorLine := vErrorCoord.Line;
FErrorColumn := vErrorCoord.Char;
end
else
begin
FErrorLine := 1;
FErrorColumn := 1;
end;
end;
Break;
end
else
begin
AddToHistory(DDLParser.Statements[I]);
end;
end else
begin
Result := False;
FErrorText := Format('Invalid DDL statement.', []);
end;
end
end else
begin
Result := False;
FErrorText := Format('Statement list is empty.', []);
end;
end else
FErrorText := DDLParser.ErrorText;
finally
FDRVQueryIntf := nil;
end;
end;
procedure TibBTDDLCompiler.AfterCommit(Sender: TObject; SenderClosing: Boolean = False);
var
I: Integer;
DDLInfo: IibSHDDLInfo;
DBObject: IibSHDBObject;
DBFactory: IibSHDBObjectFactory;
ProposalHintRetriever: IpSHProposalHintRetriever;
RunCommands: ISHRunCommands;
SHIndex: IibSHIndex;
SHTrigger: IibSHTrigger;
TableName: string;
TableForm: string;
Table: TSHComponent;
DBTable: IibSHTable;
DBView: IibSHView;
function GetNormalizeName(const ACaption: string): string;
var
vCodeNormalizer: IibSHCodeNormalizer;
begin
Result := ACaption;
if Supports(Designer.GetDemon(IibSHCodeNormalizer), IibSHCodeNormalizer, vCodeNormalizer) then
Result := vCodeNormalizer.InputValueToMetadata(DDLInfo.BTCLDatabase, Result);
end;
begin
TableName := EmptyStr;
TableForm := EmptyStr;
//
// Получаем DDLInfo интерфейс объекта
//
Supports(Sender, IibSHDDLInfo, DDLInfo);
Assert(DDLInfo <> nil, 'DDLCompiler.AfterCommit: DDLInfo = nil');
//
// Получаем DB интерфейс объекта (только от редакторов DB объектов)
//
Supports(Sender, IibSHDBObject, DBObject);
Supports(Sender, IibSHIndex, SHIndex);
Supports(Sender, IibSHTrigger, SHTrigger);
//
// Синхронизируем внутренние списки имен BTCLDatabase
//
for I := 0 to Pred(DDLParser.Count) do
case DDLParser.StatementState(I) of
csCreate: DDLInfo.BTCLDatabase.ChangeNameList(DDLParser.StatementObjectType(I), GetNormalizeName(DDLParser.StatementObjectName(I)), opInsert);
csDrop: DDLInfo.BTCLDatabase.ChangeNameList(DDLParser.StatementObjectType(I), GetNormalizeName(DDLParser.StatementObjectName(I)), opRemove);
end;
//
// Отработка рефреша SourceDDL при ALTER DB объекта
//
if Assigned(DBObject) and (DBObject.State = csAlter) and not DBObject.Embedded then
begin
for I := 0 to Pred((Sender as TSHComponent).ComponentForms.Count) do
begin
RunCommands := nil;
Supports((Sender as TSHComponent).ComponentForms[I], ISHRunCommands, RunCommands);
if AnsiSameText(TSHComponentForm((Sender as TSHComponent).ComponentForms[I]).CallString, SCallSourceDDL) then
if Assigned(RunCommands) and RunCommands.CanRefresh then RunCommands.Refresh;
end;
end;
//
// Синхронизация ограничений, индексов и триггеров с оной таблицей
//
if Assigned(SHIndex ) then
begin
TableName := SHIndex.TableName;
TableForm := SCallIndices;
end;
if Assigned(SHTrigger) then
begin
TableName := SHTrigger.TableName;
TableForm := SCallTriggers;
end;
if (Length(TableName) > 0) and not DBObject.Embedded then
begin
Table := Designer.FindComponent(DBObject.OwnerIID, IibSHTable, TableName);
if not Assigned(Table) and Assigned(SHTrigger) then
Table := Designer.FindComponent(DBObject.OwnerIID, IibSHView, TableName);
if Assigned(Table) then
for I := 0 to Pred(Table.ComponentForms.Count) do
begin
RunCommands := nil;
Supports(Table.ComponentForms[I], ISHRunCommands, RunCommands);
if AnsiSameText(TSHComponentForm(Table.ComponentForms[I]).CallString, TableForm) then
if Assigned(RunCommands) and RunCommands.CanRefresh then RunCommands.Refresh;
end;
end;
//
// Удаление из IDE индексов и триггеров для таблицы, при удалении оной, если те были загружены
//
if Assigned(DBObject) and (DBObject.State = csDrop) and Supports(Sender, IibSHTable, DBTable) then
begin
for I := 0 to Pred(DBTable.Indices.Count) do
if Designer.DestroyComponent(Designer.FindComponent(DBObject.OwnerIID, IibSHIndex, DBTable.Indices[I])) then
DBObject.BTCLDatabase.ChangeNameList(IibSHIndex, DBTable.Indices[I], opRemove);
for I := 0 to Pred(DBTable.Triggers.Count) do
if Designer.DestroyComponent(Designer.FindComponent(DBObject.OwnerIID, IibSHTrigger, DBTable.Triggers[I])) then
DBObject.BTCLDatabase.ChangeNameList(IibSHTrigger, DBTable.Triggers[I], opRemove);
end;
//
// Удаление из IDE триггеров для вьюхи, при удалении оной, если те были загружены
//
if Assigned(DBObject) and (DBObject.State = csDrop) and Supports(Sender, IibSHView, DBView) then
begin
for I := 0 to Pred(DBView.Triggers.Count) do
if Designer.DestroyComponent(Designer.FindComponent(DBObject.OwnerIID, IibSHTrigger, DBView.Triggers[I])) then
DBObject.BTCLDatabase.ChangeNameList(IibSHTrigger, DBView.Triggers[I], opRemove);
end;
//
// Отработка переоткрытия DB объектов
//
if Assigned(DBObject) and not SenderClosing and Supports(Designer.GetFactory(IibSHDBObject), IibSHDBObjectFactory, DBFactory) then
begin
if not DBObject.Embedded then
case DBObject.State of
csCreate, csRecreate:
for I := 0 to Pred(DDLParser.Count) do
if (DDLParser.StatementState(I) = csCreate) and
IsEqualGUID(DBObject.ClassIID, DDLParser.StatementObjectType(I)) then
begin
DBFactory.SuspendedDestroyCreateComponent(Sender as TSHComponent, DBObject.BTCLDatabase.InstanceIID, DBObject.ClassIID, GetNormalizeName(DDLParser.StatementObjectName(I)));
Break;
end;
csDrop:
DBFactory.SuspendedDestroyCreateComponent(Sender as TSHComponent, IUnknown, IUnknown, EmptyStr);
end;
//
// Чтобы не выпадал вопрос из GetCanDestroy() DB объекта
//
if SenderClosing or ((DBObject.State = csCreate) or (DBObject.State = csRecreate)) then
DBObject.State := csUnknown;
if DBObject.Embedded then DBObject.State := csSource;
end;
//
// Очищаем плюсовый кеш метаданных
//
DDLInfo.BTCLDatabase.DRVDatabase.ClearCache;
//
// Нотифицируем механизм получения выпадающих значений в текстовых редакторах
//
if Supports(Designer.GetDemon(IpSHProposalHintRetriever), IpSHProposalHintRetriever, ProposalHintRetriever) then
ProposalHintRetriever.AfterCompile(Sender);
//
// Нотифицируем DDL историю для сохранения и отображения в редакторе выполненных
// стейтментов
//
if Assigned(DDLHistory) then DDLHistory.CommitNewStatements;
end;
procedure TibBTDDLCompiler.AfterRollback(Sender: TObject; SenderClosing: Boolean = False);
begin
//
// Нотифицируем DDL историю для отмены сохранения и отображения в редакторе
// не подтвержденных стейтментов
//
if Assigned(DDLHistory) then DDLHistory.RollbackNewStatements;
end;
end.
|
unit Sample;
interface
//http://www.maxmind.com/download/geoip/database/
function LookupCountry(IP: string): string;
//function LookupCity(IP: string): string;
//function LookupOrg(IP: string): string;
implementation
uses GeoIP;
function LookupCountry(IP: string): string;
var
GeoIP: TGeoIP;
GeoIPCountry: TGeoIPCountry;
begin
GeoIP := TGeoIP.Create('GeoIP.dat');
try
if GeoIP.GetCountry(IP, GeoIPCountry) = GEOIP_SUCCESS then
begin
Result := GeoIPCountry.CountryCode + ' - ' + GeoIPCountry.CountryName;
end
else
begin
Result := 'ERROR - ERROR';
end;
finally
GeoIP.Free;
end;
end;
{
function LookupCity(IP: string): string;
var
GeoIP: TGeoIP;
GeoIPCity: TGeoIPCity;
begin
GeoIP := TGeoIP.Create('GeoIPCity.dat');
try
if GeoIP.GetCity(IP, GeoIPCity) = GEOIP_SUCCESS then
begin
Result := GeoIPCity.City + ', ' + GeoIPCity.Region + ', ' + GeoIPCity.CountryName;
end
else
begin
Result := 'ERROR';
end;
finally
GeoIP.Free;
end;
end;
function LookupOrg(IP: string): string;
var
GeoIP: TGeoIP;
GeoIPOrg: TGeoIPOrg;
begin
GeoIP := TGeoIP.Create('GeoIPOrg.dat');
try
if GeoIP.GetOrg(IP, GeoIPOrg) = GEOIP_SUCCESS then
begin
Result := GeoIPOrg.Name;
end
else
begin
Result := 'ERROR';
end;
finally
GeoIP.Free;
end;
end;
}
end.
|
unit Chapter09._04_Solution2;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
Math,
DeepStar.Utils;
/// 198. House Robber
/// https://leetcode.com/problems/house-robber/description/
/// 动态规划
/// 时间复杂度: O(n^2)
/// 空间复杂度: O(n)
type
TSolution = class(TObject)
public
function rob(nums: TArr_int): integer;
end;
procedure Main;
implementation
procedure Main;
begin
with TSolution.Create do
begin
WriteLn(rob([1, 2, 3, 1]));
WriteLn(rob([2, 7, 9, 3, 1]));
Free;
end;
end;
{ TSolution }
function TSolution.rob(nums: TArr_int): integer;
var
// memo[i] 表示考虑抢劫 nums[i...n) 所能获得的最大收益
memo: TArr_int;
n, i, j: integer;
begin
n := Length(nums);
if n = 0 then
Exit(0);
SetLength(memo, n);
memo[n - 1] := nums[n - 1];
for i := n - 2 downto 0 do
begin
for j := i to n - 1 do
begin
if j + 2 < n then
memo[i] := Max(memo[i], nums[j] + memo[j + 2])
else
memo[i] := Max(memo[i], nums[j] + 0);
end;
end;
Result := memo[0];
end;
end.
|
unit preamble;
{$X+}
{ Interpret preamble paragraph, compose PMX preamble }
interface uses globals;
function thisCase: boolean;
procedure preambleDefaults;
procedure interpretCommands;
procedure doPreamble;
procedure doPMXpreamble;
procedure respace;
procedure restyle;
function startString(voice: voice_index0): string;
procedure augmentPreamble(control_para: boolean);
function omitLine(line: paragraph_index): boolean;
procedure nonMusic;
procedure setOnly(line: string);
function isCommand(command: string): boolean;
const known = true;
implementation uses control, mtxline, strings, files, status, utility;
const blank = ' ';
colon = ':';
semicolon = ';';
comma = ',';
known_styles: integer = 12;
max_styles = 24;
warn_redefine: boolean = false;
type command_type =
( none, title, composer, pmx, tex, options, msize, bars, shortnote,
style, sharps, flats, meter, space, pages, systems, width, height,
enable, disable, range, name, indent,
poet, part, only, octave, start );
line_type = ( unknown, colon_line, command_line, comment_line,
plain_line );
style_index = 1..max_styles;
style_index0 = 0..max_styles;
const c1 = title; cn = start;
commands: array[command_type] of string[16] =
( 'NONE', 'TITLE', 'COMPOSER', 'PMX', 'TEX', 'OPTIONS',
'SIZE', 'BARS/LINE', 'SHORT',
'STYLE', 'SHARPS', 'FLATS', 'METER', 'SPACE', 'PAGES', 'SYSTEMS', 'WIDTH',
'HEIGHT', 'ENABLE', 'DISABLE', 'RANGE',
'NAME', 'INDENT', 'POET', 'PART', 'ONLY', 'OCTAVE', 'START');
cline: array[command_type] of string =
( '', '', '', '', '', '', '', '', '1/4', (* short *)
'', '0', '', 'C', '', '1', '1', (* systems *)
'190mm', '260mm', '', '', '', '', '', '', '', '', '', '' );
redefined: array[command_type] of boolean =
( false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false );
(** Known styles *)
known_style: array[style_index] of string = (
'SATB: Voices S,A T,B; Choral; Clefs G F',
'SATB4: Voices S A T B; Choral; Clefs G G G8 F',
'SINGER: Voices Voice; Vocal; Clefs G',
'PIANO: Voices RH LH; Continuo; Clefs G F',
'ORGAN: Voices RH LH Ped; Continuo; Clefs G F F',
'SOLO: Voices V; Clefs G',
'DUET: Voices V1 Vc; Clefs G F',
'TRIO: Voices V1 Va Vc; Clefs G C F',
'QUARTET: Voices V1 V2 Va Vc; Clefs G G C F',
'QUINTET: Voices V1 V2 Va Vc1 Vc2; Clefs G G C F F',
'SEXTET: Voices V1 V2 Va1 Va2 Vc1 Vc2; Clefs G G C C F F',
'SEPTET: Voices V1 V2 Va1 Va2 Vc1 Vc2 Cb; Clefs G G C C F F F',
'', '', '', '', '', '', '', '', '', '', '', '');
var old_known_styles: style_index;
style_used: array[style_index] of boolean;
omit_line: array[paragraph_index] of boolean;
orig_style_line: array[style_index] of style_index0;
orig_range_line: integer;
var nclefs, n_pages, n_systems, n_sharps, ngroups: integer;
part_line, title_line, composer_line, pmx_line, options_line,
start_line, voices, clefs: string;
group_start, group_stop: array[1..maxgroups] of integer;
instr_name: array[stave_index] of string[40];
style_supplied: boolean;
{ ------------------ Styles ------------------ }
function voiceCount(s: string): voice_index0;
var i, l: integer;
begin l:=length(s); for i:=1 to l do if s[i]=comma then s[i]:=blank;
voiceCount:=wordCount(s);
end;
function findStyle(s: string): style_index0;
var i: style_index0;
begin
i:=0; s:=s+colon; findStyle:=0;
while i<known_styles do
begin inc(i);
if startsWithIgnoreCase(known_style[i],s) then
begin findStyle:=i; exit; end;
end;
end;
procedure addStyle (S: string);
var sn: style_index0;
begin
sn:=findStyle(NextWord(S,colon,dummy));
if sn>0 then known_style[sn] := S
else if known_styles < max_styles then
begin inc(known_styles);
known_style[known_styles] := S;
end
else error('Can''t add another style - table full',print);
end;
procedure readStyles;
var eofstyle: boolean;
S: string;
l: style_index0;
begin if styleFileFound then eofstyle:=true else eofstyle := eof(stylefile);
l:=0;
while not eofstyle do
begin readln(stylefile,S); if S<>'' then
begin addStyle(S); inc(l); orig_style_line[known_styles]:=l; end;
eofstyle := eof(stylefile);
end;
end;
procedure applyStyle(s, stylename: string;
first_inst, first_stave: stave_index);
var clef, subline, subcommand: string;
i, last_inst, last_stave: stave_index0;
continuo, toosoon, vocal: boolean;
begin last_inst:=first_inst-1;
toosoon := false; continuo:=false; vocal := false;
subline:=GetNextWord(s,blank,colon);
while s<>'' do
begin subline:=GetNextWord(s,semicolon,dummy);
i:=curtail(subline,semicolon);
subcommand:=GetNextWord(subline,blank,dummy);
if equalsIgnoreCase(subcommand,'VOICES') then
begin voices:=voices+' '+subline;
last_stave := first_stave + wordCount(subline) - 1;
last_inst := first_inst + voiceCount(subline) - 1;
end
else if equalsIgnoreCase(subcommand,'CLEFS')
then
begin clef:=subline; clefs:=clefs+' '+clef; end
else if equalsIgnoreCase(subcommand,'VOCAL') then
if last_inst<first_inst then toosoon:=true
else begin some_vocal := true; vocal := true;
for i:=first_inst to last_inst do setVocal(i,true);
end
else if equalsIgnoreCase(subcommand,'CHORAL') or
equalsIgnoreCase(subcommand,'GROUP') then
if last_inst<first_inst then toosoon:=true
else begin
if equalsIgnoreCase(subcommand,'CHORAL') then
begin some_vocal := true; vocal := true;
for i:=first_inst to last_inst do setVocal(i,true);
end;
if ngroups=maxgroups then error('Too many groups',print)
else begin inc(ngroups);
group_start[ngroups] := first_stave;
group_stop[ngroups] := last_stave;
end
end
else if equalsIgnoreCase(subcommand,'CONTINUO') then continuo := true
else error('Subcommand ' + subcommand + ' in STYLE unknown',print);
if toosoon then
error('You must first give VOICES before specifying ' + subcommand,
print);
end;
if vocal and continuo then error(
'A continuo instrument may not be vocal',print);
if wordCount(clef)<>last_stave-first_stave+1 then error(
'Number of clefs does not match number of voices',print);
if (first_stave=last_stave) or continuo
then instr_name[first_stave]:=stylename
else for i:=first_stave to last_stave do instr_name[i]:='';
if continuo then
begin inc(ninstr); stave[ninstr] := first_stave;
for i:=first_stave to last_stave do instr[i]:=ninstr;
end
else for i:=first_stave to last_stave do
begin inc(ninstr); stave[ninstr] := i; instr[i] := ninstr;
end;
end;
procedure applyStyles;
var n1, n2, sn: integer;
s: string;
begin voices:=''; clefs:=''; ninstr:=0;
while cline[style]<>'' do
begin n1:=voiceCount(voices)+1;
n2:=wordCount(voices)+1;
s:=GetNextWord(cline[style],blank,comma);
curtail(s,comma);
sn:=findStyle(s); if sn=0 then error ('Style ' + s +' unknown',print);
line_no := orig_style_line[sn]; applyStyle(known_style[sn],s,n1,n2);
style_used[sn] := true;
end;
end;
{ ------------------------------------------------------------- }
procedure wipeCommands;
var c: command_type;
begin for c:=c1 to cn do cline[c]:='';
end;
function omitLine(line: paragraph_index): boolean;
begin omitLine := (line>0) and omit_line[line]
end;
procedure setName;
var i: integer;
begin if not redefined[name] then exit;
setFeature('instrumentNames',true);
for i:=1 to ninstr do
instr_name[i] := getNextWord(cline[name],blank,dummy);
end;
procedure setIndent;
begin if redefined[indent] then fracindent := cline[indent];
end;
procedure setInitOctave;
begin if redefined[octave] then initOctaves(cline[octave]);
end;
procedure setVoices(var line: string);
var k: integer;
s, w: string;
procedure checkLabel(w: string);
var j: voice_index;
begin
for j:=1 to nvoices do if w=voice_label[j] then
begin warning('Voice label '+w+' not unique',print); exit;
end;
if length(w)>2 then exit;
if pos1(w[1],'CLU')>0 then
if length(w)>1 then if pos1(w[2],'123456789')=0 then exit
else
else
else if pos1(w[1],'123456789')=0 then exit;
error('Voice label '+w+' conflicts with reserved label',print);
end;
begin nvoices:=0; nstaves:=0;
repeat s:=GetNextWord(line,blank,dummy);
if length(s)>0 then
begin inc(nstaves); k:=0;
first_on_stave[nstaves] := nvoices + 1;
repeat
w:=GetNextWord(s,blank,comma); curtail(w, comma);
if w<>'' then
begin
inc(k); if k<=2 then
begin inc(nvoices); checkLabel(w);
voice_label[nvoices]:=w;
if instr_name[nstaves]='' then instr_name[nstaves]:=w;
setStavePos(nvoices,nstaves,k);
end
end;
until w='';
if k>2 then error('More than two voices per stave: ' + s,print);
if k=2 then instr_name[nstaves]:='\mtxTwoInstruments{'
+ voice_label[nvoices-1] + '}{'+ voice_label[nvoices] + '}';
number_on_stave[nstaves] := k;
end
until length(line)=0;
for k:=1 to nvoices do selected[k]:=true;
end;
procedure setClefs(line: string);
var s: string;
begin
nclefs:=0;
repeat
s:=getnextword(line,blank,dummy);
if s<>'' then
begin inc(nclefs);
if length(s)=1 then clef[nclefs]:=s[1] else clef[nclefs]:=s[2];
end;
until s='';
end;
procedure setDimension(line: string; lno: command_type);
var l, n, p: integer;
begin
if line = '' then exit;
l := length(line);
n := 0;
p := 0;
repeat n := n+1;
if line[n]='.' then p:=p+1;
until (n>l) or not ((line[n]='.') or (line[n]>='0') and (line[n]<='9'));
if (n=p) or (p>1) or
not ((line[n]='i') or (line[n]='m') or (line[n]='p')) then
error('Dimension must be a number followed by in, mm or pt',print);
cline[lno] := 'w' + substr(line,1,n);
end;
procedure setSize(line: string);
var i: stave_index0;
word: string;
begin i:=0;
while i<ninstr do
begin word:=GetNextWord(line,blank,dummy);
if word='' then break;
inc(i); getNum(word,musicsize);
stave_size[i] := musicsize;
end;
if not (musicsize in [16,20]) then
for i:=1 to ninstr do
if stave_size[i] = unspec then stave_size[i] := musicsize;
if musicsize<16 then musicsize:=16
else if musicsize>20 then musicsize:=20;
end;
function findCommand(var command: string): command_type;
var j: command_type;
begin curtail(command,':');
if equalsIgnoreCase(command,'STYLE') then style_supplied := true;
for j:=c1 to cn do if equalsIgnoreCase(command,commands[j]) then
begin findCommand:=j; exit; end;
findCommand:=none;
end;
function isCommand(command: string): boolean;
begin isCommand:=findCommand(command)<>none end;
function mustAppend(command: command_type): boolean;
begin mustAppend := command=tex end;
procedure doEnable(var line: string; choice: boolean);
var word: string;
begin
repeat word:=GetNextWord(line,blank,dummy);
if word<>'' then if not setFeature(word,choice) then
Error('No such feature: '+word,not print)
until word=''
end;
procedure setRange(line: string);
var v,p: integer;
vl: string;
begin
line_no := orig_range_line;
for v:=1 to nvoices do
begin vl := voice_label[v];
p:=pos(vl+'=',line);
if p>0 then
begin
if length(line)<p+6 then
error('At least five characters must follow "'+vl+'="',
print);
defineRange(v,substr(line,p+1+length(vl),5));
end
else begin
warning('No range defined for voice '+vl,print);
defineRange(v,'');
end
end;
end;
{ TODO: This procedure should test for assertions in a comment
or be removed }
function isAssertion(var line: string): boolean;
begin
isAssertion := false
end;
function doCommand(line: string): line_type;
var command: string;
last_command: command_type;
starts_with_note: boolean;
begin
if (line[1]=comment) and not isAssertion(line) then
begin doCommand:=comment_line; exit; end;
starts_with_note := maybeMusicLine(line);
command:=GetNextWord(line,blank,colon);
if endsWith(command,colon) then
begin last_command:=findCommand(command);
doCommand:=command_line;
if last_command = enable then doEnable(line,true)
else if last_command = disable then doEnable(line,false)
else if last_command = range then orig_range_line := line_no;
if last_command<>none then
begin
if mustAppend(last_command) and redefined[last_command] then
begin
if length(cline[last_command])+length(line)>254 then
error('Total length of preamble command '+commands[last_command]+
' must not exceed 255',not print);
cline[last_command]:=cline[last_command]+#10+line
end
else
begin cline[last_command]:=line;
if warn_redefine and redefined[last_command] then
warning('You have redefined preamble command '+command,print);
end;
if last_command=start then start_line:=line;
redefined[last_command]:=true;
end
else begin doCommand:=colon_line; addStyle(command+colon+' '+line);
orig_style_line[known_styles] := line_no;
end
end
else if starts_with_note then doCommand:=plain_line
else doCommand:=unknown;
end;
procedure setOnly(line: string);
var num, num1, num2, l: integer;
s: string;
begin if line='' then exit;
if startsWithIgnoreCase(line,'only') then GetNextWord(line,colon,dummy);
for l:=1 to lines_in_paragraph do omit_line[l]:=true;
repeat s:=GetNextWord(line,blank,comma); if s='' then exit;
curtail(s, comma);
if pos1('-',s)=0 then
begin getNum(s,num);
if (num>0) and (num<=lines_in_paragraph) then omit_line[num]:=false
else warning('Invalid line number in Only: is skipped',print);
end else
begin getTwoNums(s,num1,num2);
if (num1>0) and (num2<=lines_in_paragraph) then
for num:=num1 to num2 do omit_line[num]:=false
else warning('Invalid line range in Only: is skipped',print);
end;
until false;
end;
procedure interpretCommands;
var i, num, den, nbars: integer;
begin
title_line := cline[title];
part_line := cline[part];
if (cline[poet]<>'') or (cline[composer]<>'') then
composer_line:='\mtxComposerLine{'+cline[poet]+'}{'+cline[composer]+'}'
else composer_line:='';
pmx_line := cline[pmx];
options_line := GetNextWord(cline[options],blank,dummy);
for i:=1 to known_styles do style_used[i] := false;
applyStyles; setVoices(voices);
for i:=old_known_styles+1 to known_styles do
if not style_used[i] then
begin warning('The following style was supplied but not used',not print);
writeln(known_style[i]);
end;
setClefs(clefs);
if not redefined[meter] then warning(
'You have not defined Meter, assuming "'+cline[meter]+'" ',not print);
getMeter(cline[meter],meternum, meterdenom, pmnum, pmdenom);
setDefaultDuration(meterdenom);
if (meternum=0) and
not (redefined[pages] or redefined[systems] or redefined[bars])
then begin cline[bars] := '1'; redefined[bars]:=true; end;
if redefined[pages] or redefined[systems] then
begin if redefined[bars] then
warning('BARS/LINE ignored since you specified PAGES or SYSTEMS',print);
if redefined[systems] then getNum(cline[systems],n_systems)
else warning('PAGES specified but not SYSTEMS',not print);
if redefined[pages] then getNum(cline[pages],n_pages)
else warning('SYSTEMS specified but not PAGES',not print);
end
else if redefined[bars] then
begin getNum(cline[bars],nbars); if nbars>0 then
begin n_pages:=0; n_systems:=nbars end;
end;
getNum(cline[sharps],n_sharps);
setSpace(cline[space]);
setSize(cline[msize]);
getTwoNums(cline[shortnote],num, den); if den=0 then den:=1;
short_note := (num*64) div den;
if cline[flats]<>'' then
begin getNum(cline[flats],n_sharps); n_sharps:=-n_sharps; end;
setName; setIndent; setInitOctave; setOnly(cline[only]);
setRange(cline[range]);
setDimension(cline[width],width);
setDimension(cline[height],height);
if options_line <>'' then begin
warning('"Options" is cryptic and obsolescent.', not print);
writeln(' Use "Enable" and "Disable" instead.')
end;
for i:=1 to length(options_line) do processOption(options_line[i]);
end;
procedure preambleDefaults;
var i: integer;
begin
xmtrnum0:=0; fracindent:='0'; musicsize:=20; start_line:='';
some_vocal:=false; ngroups:=0;
style_supplied := false;
for i:=1 to maxvoices do setVocal(i,false);
for i:=1 to maxstaves do stave_size[i]:=unspec;
for i:=0 to maxstaves do nspace[i]:=unspec;
{ next line seems to be spurious. 0.63a RDT }
{ begin nspace[i]:=unspec; stave_size[i]:=unspec; end; }
n_pages:=1; n_systems:=1;
readStyles; old_known_styles := known_styles;
for i:=1 to lines_in_paragraph do omit_line[i]:=false;
end;
procedure preambleGuess(maybe_voices: voice_index);
begin
case maybe_voices of
1: cline[style] := 'Solo';
2: cline[style] := 'Duet';
3: cline[style] := 'Trio';
4: cline[style] := 'Quartet';
5: cline[style] := 'Quintet';
6: cline[style] := 'Sextet';
7: cline[style] := 'Septet';
else begin error('I cannot guess a style',not print); exit; end;
end;
writeln('I guess this piece is a ',cline[style],
' for strings in C major.');
writeln(' Why not provide a STYLE in the setup paragraph to make sure?');
end;
{ ------------------------------------------------------------------ }
procedure nonMusic;
var i: paragraph_index;
begin for i:=1 to para_len do doCommand(P[i]);
setOnly(cline[only]); wipeCommands;
end;
function thisCase: boolean;
begin thisCase:=true;
if not startsWithIgnoreCase(P[1],'case:') then exit;
thisCase:=(choice<>' ') and (pos1(choice,P[1])>0); P[1]:='%';
end;
procedure augmentPreamble(control_para: boolean);
var i: paragraph_index;
l: line_type;
s: array[line_type] of integer;
begin
if not thisCase then exit;
for l:=unknown to plain_line do s[l]:=0;
for i:=1 to para_len do
begin line_no:=orig_line_no[i]; l:=doCommand(P[i]);
inc(s[l]);
if (l=comment_line) and (P[i,2]=comment)
then begin predelete(P[i],2); putLine(P[i]); end;
if not control_para and (l=unknown) then
error('Unidentifiable line',print);
end;
if not control_para and (s[command_line]>0) and (s[plain_line]>0)
then error('Mixture of preamble commands and music',not print);
end;
procedure doPreamble;
var i: paragraph_index;
maybe_voices: voice_index0;
begin maybe_voices:=0;
if not style_supplied then
begin {augmentPreamble(not known);}
if not style_supplied then warning('No STYLE supplied',not print);
for i:=1 to para_len do if maybeMusicLine(P[i]) then
inc(maybe_voices);
if maybe_voices>0 then preambleGuess(maybe_voices)
else error('No voices found',not print);
end
end;
procedure respace;
var i, j: stave_index;
begin
for i:=ninstr downto 2 do
begin j:=ninstr-i+1;
if nspace[j]<>unspec then TeXtype2('\mtxInterInstrument{'+toString(i-1)+
'}{'+toString(nspace[j])+'}');
end;
if nspace[ninstr]<>unspec then TeXtype2('\mtxStaffBottom{'+
toString(nspace[ninstr])+'}');
must_respace:=false;
end;
procedure restyle;
begin
must_restyle:=false;
end;
function clefno ( cl: char ): integer;
begin
case cl of
'G','0','t','8': clefno:=0;
's','1': clefno:=1;
'm','2': clefno:=2;
'a','3': clefno:=3;
'n','4': clefno:=4;
'r','5': clefno:=5;
'F','b','6': clefno:=6;
'C': clefno:=3;
else
begin warning('Unknown clef code "' + cl + '" - replaced by treble',print);
clefno:=0;
end;
end
end;
procedure doTenorClefs;
var i: voice_index;
c: char;
begin for i:=1 to nclefs do
begin
c:=clef[i]; if (c='8') or (c='t') then
putLine('\\mtxTenorClef{' + toString(PMXinstr(i)) + '}\' );
end;
end;
procedure insertTeX;
begin
if redefined[tex] then TeXtype2(cline[tex]);
end;
procedure doPMXpreamble;
const clefcode: string[8]='0123456';
var i, j: integer;
clefs: string;
function pmxMeter: string;
var denom, num: integer;
begin if meternum=0 then
begin num := beatsPerLine; {* denom := 0; *}
old_meter_word := meterChange(num,meterdenom,true);
end
else begin num := meternum; {* denom := pmdenom; *} end;
{ CMO: unconditonally assign value of pmdenom to denom }
denom := pmdenom;
pmxMeter := toString(num) + ' ' + toString(PMXmeterdenom(meterdenom)) +
' ' + toString(pmnum) + ' ' + toString(denom);
end;
function sizecode(k: integer): string;
begin sizecode:='\mtxNormalSize';
case k of
13: if musicsize=20 then sizecode:='\mtxTinySize' else sizecode:='\mtxSmallSize';
16: if musicsize=20 then sizecode:='\mtxSmallSize';
20: if musicsize=16 then sizecode:='\mtxLargeSize';
24: if musicsize=20 then sizecode:='\mtxLargeSize' else sizecode:='\mtxHugeSize';
29: sizecode:='\mtxHugeSize';
else error('Valid sizes are 13, 16, 20, 24, 29',print);
end;
end;
begin
if composer_line <> '' then putline(composer_line);
if title_line <> '' then putline('\mtxTitleLine{'+title_line+'}');
putLine('---');
if instrumentNames and not redefined[indent] then fracindent:='0.12';
write(outfile, nstaves);
write(outfile, ' ', -ninstr);
stave[ninstr+1]:=nstaves+1;
for j:=ninstr downto 1 do write(outfile, ' ', stave[j+1] - stave[j]);
writeln(outfile, ' ', pmxMeter, ' ',xmtrnum0:8:5, ' ',n_sharps,
' ', n_pages, ' ',n_systems, ' ',musicsize, ' ',fracindent);
for i:=1 to ninstr do if not instrumentNames then putLine('')
else putLine('\mtxInstrName{'+instr_name[ninstr+1-i]+'}');
clefs:='';
for i:=nclefs downto 1 do clefs:=clefs+clefcode[1+clefno(clef[i])];
putLine(clefs);
if texdir='' then texdir := './';
putLine(texdir);
pmx_preamble_done:=true; insertTeX; respace;
for j:=1 to ngroups do
writeln(outfile,'\\mtxGroup{'+toString(j)+'}{'
+toString(ninstr+1-group_start[j])+'}{'
+toString(ninstr+1-group_stop[j])+'}\');
for j:=1 to ninstr do
if (stave_size[j]<>unspec) then
putLine(
'\\mtxSetSize{'+toString(ninstr+1-j)+'}{'+sizecode(stave_size[j])+'}\');
if part_line <> '' then
begin putLine('Ti'); putLine(part_line); end;
if composer_line <> '' then
begin putLine('Tc'); putLine('\mtxPoetComposer'); end;
if title_line <> '' then
begin write(outfile,'Tt');
if nspace[0] <> unspec then write(outfile,toString(nspace[0]));
writeln(outfile);
putLine('\mtxTitle');
end;
if pmx_line <> '' then putLine(pmx_line);
doTenorClefs;
if cline[width] <> '' then putLine(cline[width]);
wipeCommands;
end;
function startString(voice: voice_index0): string;
var s, w: string;
j: voice_index;
begin s:=start_line;
for j:=1 to voice do w:=getNextWord(s,dummy,';');
curtail(w,';'); if w<>'' then startString:=w+' ' else startString:=w;
end;
end.
|
unit UDAreaFormat;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, UCrpe32;
type
TCrpeAreaFormatDlg = class(TForm)
pnlAreaFormat: TPanel;
lblArea: TLabel;
cbPrintAtBottomOfPage: TCheckBox;
cbNewPageBefore: TCheckBox;
cbNewPageAfter: TCheckBox;
cbResetPageNAfter: TCheckBox;
cbKeepTogether: TCheckBox;
cbHide: TCheckBox;
cbSuppress: TCheckBox;
lbAreas: TListBox;
btnOk: TButton;
btnClear: TButton;
sbSuppress: TSpeedButton;
sbPrintAtBottomOfPage: TSpeedButton;
sbNewPageBefore: TSpeedButton;
sbNewPageAfter: TSpeedButton;
sbResetPageNAfter: TSpeedButton;
sbKeepTogether: TSpeedButton;
sbHide: TSpeedButton;
sbFormulaRed: TSpeedButton;
sbFormulaBlue: TSpeedButton;
lblCount: TLabel;
editCount: TEdit;
editNSections: TEdit;
lblNSections: TLabel;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure btnClearClick(Sender: TObject);
procedure lbAreasClick(Sender: TObject);
procedure cbCommonClick(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure UpdateAreaFormat;
procedure sbFormulaButtonClick(Sender: TObject);
procedure InitializeControls(OnOff: boolean);
private
{ Private declarations }
public
{ Public declarations }
Cr : TCrpe;
AreaIndex : smallint;
end;
var
CrpeAreaFormatDlg: TCrpeAreaFormatDlg;
bAreaFormat : boolean;
implementation
{$R *.DFM}
uses UCrpeUtl, UDFormulaEdit;
{------------------------------------------------------------------------------}
{ FormCreate procedure }
{------------------------------------------------------------------------------}
procedure TCrpeAreaFormatDlg.FormCreate(Sender: TObject);
begin
LoadFormPos(Self);
AreaIndex := -1;
btnOk.Tag := 1;
bAreaFormat := True;
end;
{------------------------------------------------------------------------------}
{ FormShow procedure }
{------------------------------------------------------------------------------}
procedure TCrpeAreaFormatDlg.FormShow(Sender: TObject);
begin
UpdateAreaFormat;
end;
{------------------------------------------------------------------------------}
{ UpdateAreaFormat procedure }
{------------------------------------------------------------------------------}
procedure TCrpeAreaFormatDlg.UpdateAreaFormat;
var
OnOff : boolean;
begin
AreaIndex := -1;
{Enable/Disable controls}
if IsStrEmpty(Cr.ReportName) then
OnOff := False
else
begin
OnOff := (Cr.AreaFormat.Count > 0);
{Get AreaFormat Index}
if OnOff then
begin
if Cr.AreaFormat.ItemIndex > -1 then
AreaIndex := Cr.AreaFormat.ItemIndex
else
AreaIndex := 0;
end;
end;
InitializeControls(OnOff);
{Update list box}
if OnOff = True then
begin
lbAreas.Items.AddStrings(Cr.AreaFormat.Names);
editCount.Text := IntToStr(Cr.AreaFormat.Count);
lbAreas.ItemIndex := AreaIndex;
lbAreasClick(self);
end;
end;
{------------------------------------------------------------------------------}
{ InitializeControls }
{------------------------------------------------------------------------------}
procedure TCrpeAreaFormatDlg.InitializeControls(OnOff: boolean);
var
i : integer;
begin
{Enable/Disable the Form Controls}
for i := 0 to ComponentCount - 1 do
begin
if TComponent(Components[i]).Tag = 0 then
begin
if Components[i] is TButton then
TButton(Components[i]).Enabled := OnOff;
if Components[i] is TSpeedButton then
TSpeedButton(Components[i]).Enabled := OnOff;
if Components[i] is TCheckBox then
TCheckBox(Components[i]).Enabled := OnOff;
if Components[i] is TListBox then
begin
TListBox(Components[i]).Clear;
TListBox(Components[i]).Color := ColorState(OnOff);
TListBox(Components[i]).Enabled := OnOff;
end;
end;
end;
end;
{------------------------------------------------------------------------------}
{ lbAFSectionClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeAreaFormatDlg.lbAreasClick(Sender: TObject);
const
aSection : array[0..3] of string = ('PH','PF','RH','RF');
var
sTmp : string;
i : integer;
s1 : string;
begin
AreaIndex := lbAreas.ItemIndex;
{Disable events}
for i := 0 to ComponentCount - 1 do
begin
if Components[i] is TCheckBox then
TCheckBox(Components[i]).OnClick := nil;
end;
cbSuppress.Checked := Cr.AreaFormat[AreaIndex].Suppress;
cbHide.Checked := Cr.AreaFormat.Item.Hide;
cbPrintAtBottomOfPage.Checked := Cr.AreaFormat.Item.PrintAtBottomOfPage;
cbNewPageBefore.Checked := Cr.AreaFormat.Item.NewPageBefore;
cbNewPageAfter.Checked := Cr.AreaFormat.Item.NewPageAfter;
cbResetPageNAfter.Checked := Cr.AreaFormat.Item.ResetPageNAfter;
cbKeepTogether.Checked := Cr.AreaFormat.Item.KeepTogether;
editNSections.Text := IntToStr(Cr.AreaFormat.Item.NSections);
{Disable inapplicable items for the section}
sTmp := Copy(Cr.AreaFormat.Area, 1, 2);
sTmp := UpperCase(sTmp);
{if the Section is Report Header...}
if (sTmp = 'RH') then
begin
{disable New Page Before}
cbNewPageBefore.Enabled := False;
{enable the other 4 options if needed}
{Hide}
if cbHide.Enabled = False then
cbHide.Enabled := True;
{PrintAtBottomOfPage}
if cbPrintAtBottomOfPage.Enabled = False then
cbPrintAtBottomOfPage.Enabled := True;
{NewPageAfter}
if cbNewPageAfter.Enabled = False then
cbNewPageAfter.Enabled := True;
{KeepTogether}
if cbKeepTogether.Enabled = False then
cbKeepTogether.Enabled := True;
end
{if the Section is Report Footer...}
else if (sTmp = 'RF') then
begin
{disable NewPageAfter}
cbNewPageAfter.Enabled := False;
{enable the other 4 options if needed}
{Hide}
if cbHide.Enabled = False then
cbHide.Enabled := True;
{PrintAtBottomOfPage}
if cbPrintAtBottomOfPage.Enabled = False then
cbPrintAtBottomOfPage.Enabled := True;
{KeepTogether}
if cbKeepTogether.Enabled = False then
cbKeepTogether.Enabled := True;
{NewPageBefore}
if cbNewPageBefore.Enabled = False then
cbNewPageBefore.Enabled := True;
end
{if the Section is Page Header or Page Footer...}
else if (sTmp = 'PH') or (sTmp = 'PF') then
begin
{Disable: Hide, PrintAtBottomOfPage, NewPageAfter,
NewPageBefore, KeepTogether}
cbHide.Enabled := False;
cbPrintAtBottomOfPage.Enabled := False;
cbNewPageAfter.Enabled := False;
cbNewPageBefore.Enabled := False;
cbKeepTogether.Enabled := False;
end
else
begin
{enable the 5 options as required}
{Hide}
if cbHide.Enabled = False then
cbHide.Enabled := True;
{PrintAtBottomOfPage}
if cbPrintAtBottomOfPage.Enabled = False then
cbPrintAtBottomOfPage.Enabled := True;
{NewPageAfter}
if cbNewPageAfter.Enabled = False then
cbNewPageAfter.Enabled := True;
{NewPageBefore}
if cbNewPageBefore.Enabled = False then
cbNewPageBefore.Enabled := True;
{KeepTogether}
if cbKeepTogether.Enabled = False then
cbKeepTogether.Enabled := True;
end;
{Set Formula Button glyphs: check first 5 for PH/PF, RH/RF}
{NewPageBefore}
if Pos(UpperCase(Cr.AreaFormat.Area), 'PHPFRH') = 0 then
begin
if not sbNewPageBefore.Enabled then
sbNewPageBefore.Enabled := True;
{If formula has text...}
s1 := RTrimList(Cr.AreaFormat.Item.Formulas.NewPageBefore);
if Length(s1) > 0 then
begin
if sbNewPageBefore.Tag <> 1 then
begin
sbNewPageBefore.Glyph := sbFormulaRed.Glyph;
sbNewPageBefore.Tag := 1;
end;
end
else
begin
if sbNewPageBefore.Tag <> 0 then
begin
sbNewPageBefore.Glyph := sbFormulaBlue.Glyph;
sbNewPageBefore.Tag := 0;
end;
end;
end
else
begin
if sbNewPageBefore.Enabled then
sbNewPageBefore.Enabled := False;
end;
{NewPageAfter}
if Pos(UpperCase(Cr.AreaFormat.Area), 'PHPFRF') = 0 then
begin
if not sbNewPageAfter.Enabled then
sbNewPageAfter.Enabled := True;
s1 := RTrimList(Cr.AreaFormat.Item.Formulas.NewPageAfter);
if Length(s1) > 0 then
begin
if sbNewPageAfter.Tag <> 1 then
begin
sbNewPageAfter.Glyph := sbFormulaRed.Glyph;
sbNewPageAfter.Tag := 1;
end;
end
else
begin
if sbNewPageAfter.Tag <> 0 then
begin
sbNewPageAfter.Glyph := sbFormulaBlue.Glyph;
sbNewPageAfter.Tag := 0;
end;
end;
end
else
begin
if sbNewPageAfter.Enabled then
sbNewPageAfter.Enabled := False;
end;
{KeepTogether}
if Pos(UpperCase(Cr.AreaFormat.Area), 'PHPF') = 0 then
begin
if not sbKeepTogether.Enabled then
sbKeepTogether.Enabled := True;
s1 := RTrimList(Cr.AreaFormat.Item.Formulas.KeepTogether);
if Length(s1) > 0 then
begin
if sbKeepTogether.Tag <> 1 then
begin
sbKeepTogether.Glyph := sbFormulaRed.Glyph;
sbKeepTogether.Tag := 1;
end;
end
else
begin
if sbKeepTogether.Tag <> 0 then
begin
sbKeepTogether.Glyph := sbFormulaBlue.Glyph;
sbKeepTogether.Tag := 0;
end;
end;
end
else
begin
if sbKeepTogether.Enabled then
sbKeepTogether.Enabled := False;
end;
{PrintAtBottomOfPage}
if Pos(UpperCase(Cr.AreaFormat.Area), 'PHPF') = 0 then
begin
if not sbPrintAtBottomOfPage.Enabled then
sbPrintAtBottomOfPage.Enabled := True;
s1 := RTrimList(Cr.AreaFormat.Item.Formulas.PrintAtBottomOfPage);
if Length(s1) > 0 then
begin
if sbPrintAtBottomOfPage.Tag <> 1 then
begin
sbPrintAtBottomOfPage.Glyph := sbFormulaRed.Glyph;
sbPrintAtBottomOfPage.Tag := 1;
end;
end
else
begin
if sbPrintAtBottomOfPage.Tag <> 0 then
begin
sbPrintAtBottomOfPage.Glyph := sbFormulaBlue.Glyph;
sbPrintAtBottomOfPage.Tag := 0;
end;
end;
end
else
begin
if sbPrintAtBottomOfPage.Enabled then
sbPrintAtBottomOfPage.Enabled := False;
end;
{Hide}
if Pos(UpperCase(Cr.AreaFormat.Area), 'PHPF') = 0 then
begin
if not sbHide.Enabled then
sbHide.Enabled := True;
s1 := RTrimList(Cr.AreaFormat.Item.Formulas.Hide);
if Length(s1) > 0 then
begin
if sbHide.Tag <> 1 then
begin
sbHide.Glyph := sbFormulaRed.Glyph;
sbHide.Tag := 1;
end;
end
else
begin
if sbHide.Tag <> 0 then
begin
sbHide.Glyph := sbFormulaBlue.Glyph;
sbHide.Tag := 0;
end;
end;
end
else
begin
if sbHide.Enabled then
sbHide.Enabled := False;
end;
{Suppress}
s1 := RTrimList(Cr.AreaFormat.Item.Formulas.Suppress);
if Length(s1) > 0 then
begin
if sbSuppress.Tag <> 1 then
begin
sbSuppress.Glyph := sbFormulaRed.Glyph;
sbSuppress.Tag := 1;
end;
end
else
begin
if sbSuppress.Tag <> 0 then
begin
sbSuppress.Glyph := sbFormulaBlue.Glyph;
sbSuppress.Tag := 0;
end;
end;
{ResetPageNAfter}
s1 := RTrimList(Cr.AreaFormat.Item.Formulas.ResetPageNAfter);
if Length(s1) > 0 then
begin
if sbResetPageNAfter.Tag <> 1 then
begin
sbResetPageNAfter.Glyph := sbFormulaRed.Glyph;
sbResetPageNAfter.Tag := 1;
end;
end
else
begin
if sbResetPageNAfter.Tag <> 0 then
begin
sbResetPageNAfter.Glyph := sbFormulaBlue.Glyph;
sbResetPageNAfter.Tag := 0;
end;
end;
{Enable events}
for i := 0 to ComponentCount - 1 do
begin
if Components[i] is TCheckBox then
TCheckBox(Components[i]).OnClick := cbCommonClick;
end;
end;
{------------------------------------------------------------------------------}
{ sbFormulaButtonClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeAreaFormatDlg.sbFormulaButtonClick(Sender: TObject);
var
sFormula : TStrings;
begin
if not (Sender is TSpeedButton) then
Exit;
{Set Crpe Formulas to chosen item}
if TSpeedButton(Sender) = sbPrintAtBottomOfPage then
sFormula := Cr.AreaFormat.Item.Formulas.PrintAtBottomOfPage
else if TSpeedButton(Sender) = sbNewPageBefore then
sFormula := Cr.AreaFormat.Item.Formulas.NewPageBefore
else if TSpeedButton(Sender) = sbNewPageAfter then
sFormula := Cr.AreaFormat.Item.Formulas.NewPageAfter
else if TSpeedButton(Sender) = sbResetPageNAfter then
sFormula := Cr.AreaFormat.Item.Formulas.ResetPageNAfter
else if TSpeedButton(Sender) = sbKeepTogether then
sFormula := Cr.AreaFormat.Item.Formulas.KeepTogether
else if TSpeedButton(Sender) = sbHide then
sFormula := Cr.AreaFormat.Item.Formulas.Hide
else
{Default to Suppress}
sFormula := Cr.AreaFormat.Item.Formulas.Suppress;
{Create the Formula editing form}
CrpeFormulaEditDlg := TCrpeFormulaEditDlg.Create(Application);
CrpeFormulaEditDlg.SenderList := sFormula;
CrpeFormulaEditDlg.Caption := TSpeedButton(Sender).Hint;
CrpeFormulaEditDlg.ShowModal;
{Update the main form}
lbAreasClick(Self);
end;
{------------------------------------------------------------------------------}
{ cbCommonClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeAreaFormatDlg.cbCommonClick(Sender: TObject);
begin
if not (Sender is TCheckBox) then
Exit;
{Update the VCL}
if TCheckBox(Sender).Name = 'cbSuppress' then
Cr.AreaFormat.Item.Suppress := TCheckBox(Sender).Checked
else if TCheckBox(Sender).Name = 'cbHide' then
Cr.AreaFormat.Item.Hide := TCheckBox(Sender).Checked
else if TCheckBox(Sender).Name = 'cbPrintAtBottomOfPage' then
Cr.AreaFormat.Item.PrintAtBottomOfPage := TCheckBox(Sender).Checked
else if TCheckBox(Sender).Name = 'cbNewPageBefore' then
Cr.AreaFormat.Item.NewPageBefore := TCheckBox(Sender).Checked
else if TCheckBox(Sender).Name = 'cbNewPageAfter' then
Cr.AreaFormat.Item.NewPageAfter := TCheckBox(Sender).Checked
else if TCheckBox(Sender).Name = 'cbResetPageNAfter' then
Cr.AreaFormat.Item.ResetPageNAfter := TCheckBox(Sender).Checked
else if TCheckBox(Sender).Name = 'cbKeepTogether' then
Cr.AreaFormat.Item.KeepTogether := TCheckBox(Sender).Checked;
end;
{------------------------------------------------------------------------------}
{ btnClearClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeAreaFormatDlg.btnClearClick(Sender: TObject);
begin
Cr.AreaFormat.Clear;
UpdateAreaFormat;
end;
{------------------------------------------------------------------------------}
{ btnOkClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeAreaFormatDlg.btnOkClick(Sender: TObject);
begin
SaveFormPos(Self);
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose procedure }
{------------------------------------------------------------------------------}
procedure TCrpeAreaFormatDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
bAreaFormat := False;
Release;
end;
end.
|
unit uVSRuleReader;
interface
uses
Classes,Contnrs,xmldom, XMLIntf, msxmldom,XMLDoc,
uVSRules,uVSSimpleExpress,uVSCombExpress;
type
TVSRuleReader = class
private
m_XMLDoc : IXMLDocument;
m_RuleList : TList;
m_ExpressList : array of TVSExpression;
protected
procedure LoadRuleInfo(Node : IXMLNode;Rule : TVSRule);
procedure LoadExpression(Node : IXMLNode;out Express : TVSExpression);
procedure LoadCompExpression(Node : IXMLNode;Express : TVSCompExpression);
procedure LoadOrderExpression(Node : IXMLNode;Express : TVSOrderExpression);
procedure LoadOffsetExpression(Node : IXMLNode;Express : TVSOffsetExpression);
procedure LoadCompBehindExpression(Node : IXMLNode;Express : TVSCompBehindExpression);
procedure LoadSimpleConditionExpression(Node:IXMLNode;Express : TVSSimpleConditionExpression);
procedure LoadCombAndExpression(Node : IXMLNode;Express : TVSCombAndExpression);
procedure LoadCombOrExpression(Node : IXMLNode;Express : TVSCombOrExpression);
procedure LoadCombOrderExpression(Node : IXMLNode;Express : TVSCombOrderExpression);
procedure LoadCombIntervalExpression(Node : IXMLNode;Express : TVSCombIntervalExpression);
procedure LoadCombNoIntervalExpression(Node : IXMLNode;Express : TVSCombNoIntervalExpression);
//根据已生成的表达式ID获取表达式
function FindExpress(ExpressID : string) : TVSExpression;
public
procedure LoadFromXML(XMLFile : string);
public
constructor Create(RuleList : TObjectList);
destructor Destroy;override;
end;
implementation
{ TVSRuleReader }
constructor TVSRuleReader.Create(RuleList: TObjectList);
begin
m_RuleList := RuleList;
end;
destructor TVSRuleReader.Destroy;
begin
m_XMLDoc := nil;
inherited;
end;
function TVSRuleReader.FindExpress(ExpressID: string): TVSExpression;
var
i: Integer;
begin
result := nil;
if ExpressID = '' then exit;
for i := 0 to length(m_ExpressList) - 1 do
begin
if m_ExpressList[i] <> nil then
begin
if m_ExpressList[i].ExpressID = ExpressID then
begin
Result := m_ExpressList[i];
break;
end;
end;
end;
end;
procedure TVSRuleReader.LoadCombAndExpression(Node: IXMLNode;
Express: TVSCombAndExpression);
var
i: Integer;
subNode : IXMLNode;
exp : TVSExpression;
begin
for i := 0 to Node.ChildNodes.Count - 1 do
begin
subNode := Node.ChildNodes[i];
LoadExpression(subNode,exp);
if exp <> nil then
begin
Express.Expressions.Add(exp);
end;
end;
end;
procedure TVSRuleReader.LoadCombIntervalExpression(Node: IXMLNode;
Express: TVSCombIntervalExpression);
var
exp : TVSExpression;
subNode : IXMLNode;
begin
Express.MatchFirst := Node.Attributes['MatchFirst'];
Express.MatchMatch := Node.Attributes['MatchMatch'];
Express.ReturnType := Node.Attributes['ReturnType'];
subNode := node.ChildNodes.FindNode('BeginExpress');
if subNode <> nil then
begin
LoadExpression(subNode,exp);
if exp <> nil then
begin
Express.BeginExpression := exp;
end;
end;
subNode := node.ChildNodes.FindNode('Expression');
if subNode <> nil then
begin
LoadExpression(subNode,exp);
if exp <> nil then
begin
Express.Expression := exp;
end;
end;
subNode := node.ChildNodes.FindNode('EndExpress');
if subNode <> nil then
begin
LoadExpression(subNode,exp);
if exp <> nil then
begin
Express.EndExpression := exp;
end;
end;
end;
procedure TVSRuleReader.LoadCombNoIntervalExpression(Node: IXMLNode;
Express: TVSCombNoIntervalExpression);
var
exp : TVSExpression;
subNode : IXMLNode;
begin
subNode := node.ChildNodes.FindNode('BeginExpress');
if subNode <> nil then
begin
LoadExpression(subNode,exp);
if exp <> nil then
begin
Express.BeginExpression := exp;
end;
end;
subNode := node.ChildNodes.FindNode('Expression');
if subNode <> nil then
begin
LoadExpression(subNode,exp);
if exp <> nil then
begin
Express.Expression := exp;
end;
end;
subNode := node.ChildNodes.FindNode('EndExpress');
if subNode <> nil then
begin
LoadExpression(subNode,exp);
if exp <> nil then
begin
Express.EndExpression := exp;
end;
end;
end;
procedure TVSRuleReader.LoadCombOrderExpression(Node: IXMLNode;
Express: TVSCombOrderExpression);
var
i: Integer;
subNode : IXMLNode;
exp : TVSExpression;
begin
Express.MatchedIndex := Node.Attributes['MatchedIndex'];
Express.BeginIndex := Node.Attributes['BeginIndex'];
Express.EndIndex := Node.Attributes['EndIndex'];
for i := 0 to Node.ChildNodes.Count - 1 do
begin
subNode := Node.ChildNodes[i];
LoadExpression(subNode,exp);
if exp <> nil then
begin
Express.Expressions.Add(exp);
end;
end;
end;
procedure TVSRuleReader.LoadCombOrExpression(Node: IXMLNode;
Express: TVSCombOrExpression);
var
i: Integer;
subNode : IXMLNode;
exp : TVSExpression;
begin
for i := 0 to Node.ChildNodes.Count - 1 do
begin
subNode := Node.ChildNodes[i];
LoadExpression(subNode,exp);
if exp <> nil then
begin
Express.Expressions.Add(exp);
end;
end;
end;
procedure TVSRuleReader.LoadCompBehindExpression(Node: IXMLNode;
Express: TVSCompBehindExpression);
begin
Express.Key := Node.Attributes['Key'];
Express.OperatorSignal := Node.Attributes['OperatorSignal'];
Express.Value := Node.Attributes['Value'];
Express.CompDataType := Node.Attributes['CompDataType'];
Express.FrontExp := FindExpress(Node.Attributes['FrontExp']);
Express.BehindExp := FindExpress(Node.Attributes['BehindExp']);
end;
procedure TVSRuleReader.LoadCompExpression(Node: IXMLNode;
Express: TVSCompExpression);
begin
Express.Key := Node.Attributes['Key'];
Express.OperatorSignal := Node.Attributes['OperatorSignal'];
Express.Value := Node.Attributes['Value'];
end;
procedure TVSRuleReader.LoadExpression(Node: IXMLNode;out Express: TVSExpression);
begin
Express := nil;
try
if node.Attributes['Type'] = 'TVSCompExpression' then
begin
Express := TVSCompExpression.Create;
LoadCompExpression(Node,TVSCompExpression(Express));
exit;
end;
if node.Attributes['Type'] = 'TVSOrderExpression' then
begin
Express := TVSOrderExpression.Create;
LoadOrderExpression(Node,TVSOrderExpression(Express));
exit;
end;
if node.Attributes['Type'] = 'TVSOffsetExpression' then
begin
Express := TVSOffsetExpression.Create;
LoadOffsetExpression(Node,TVSOffsetExpression(Express));
exit;
end;
if node.Attributes['Type'] = 'TVSCompBehindExpression' then
begin
Express := TVSCompBehindExpression.Create;
LoadCompBehindExpression(Node,TVSCompBehindExpression(Express));
exit;
end;
if node.Attributes['Type'] = 'TVSCombAndExpression' then
begin
Express := TVSCombAndExpression.Create;
LoadCombAndExpression(Node,TVSCombAndExpression(Express));
exit;
end;
if node.Attributes['Type'] = 'TVSCombOrExpression' then
begin
Express := TVSCombOrExpression.Create;
LoadCombOrExpression(Node,TVSCombOrExpression(Express));
exit;
end;
if node.Attributes['Type'] = 'TVSCombOrderExpression' then
begin
Express := TVSCombOrderExpression.Create;
LoadCombOrderExpression(Node,TVSCombOrderExpression(Express));
exit;
end;
if node.Attributes['Type'] = 'TVSCombIntervalExpression' then
begin
Express := TVSCombIntervalExpression.Create;
LoadCombIntervalExpression(Node,TVSCombIntervalExpression(Express));
exit;
end;
if node.Attributes['Type'] = 'TVSCombNoIntervalExpression' then
begin
Express := TVSCombNoIntervalExpression.Create;
LoadCombNoIntervalExpression(Node,TVSCombNoIntervalExpression(Express));
exit;
end;
if node.Attributes['Type'] = 'TVSSimpleConditionExpression' then
begin
Express := TVSSimpleConditionExpression.Create;
LoadSimpleConditionExpression(Node,TVSSimpleConditionExpression(Express));
exit;
end;
finally
if Express <> nil then
begin
if node.HasAttribute('ExpressID') then
begin
express.ExpressID := node.Attributes['ExpressID'];
end;
if node.HasAttribute('Title') then
begin
express.Title := node.Attributes['Title'];
end;
SetLength(m_ExpressList,length(m_ExpressList) + 1);
m_ExpressList[length(m_ExpressList) - 1] := Express;
end;
end;
end;
procedure TVSRuleReader.LoadFromXML(XMLFile: string);
var
root,node,subNode : IXMLNode;
rule : TVSRule;
exp : TVSExpression;
i: Integer;
begin
m_XMLDoc := NewXMLDocument();
try
m_XMLDoc.LoadFromFile(XMLFile);
root := m_XMLDoc.DocumentElement;
if (root.NodeName <> 'RunrecordRules') then exit;
for i := 0 to root.ChildNodes.Count - 1 do
begin
node := root.ChildNodes[i];
rule := TVSRule.Create;
SetLength(m_ExpressList,0);
LoadRuleInfo(node,rule);
subNode := node.ChildNodes.FindNode('HeadExpression');
if subNode <> nil then
begin
LoadExpression(subNode,exp);
if exp <> nil then
begin
rule.HeadExpression := exp;
end;
end;
subNode := node.ChildNodes.FindNode('RootExpression');
begin
LoadExpression(subNode,exp);
if exp <> nil then
begin
rule.RootExpression := exp;
end;
end;
SetLength(m_ExpressList,0);
m_RuleList.Add(rule);
end;
finally
m_xmlDoc := nil;
end;
end;
procedure TVSRuleReader.LoadOffsetExpression(Node: IXMLNode;
Express: TVSOffsetExpression);
begin
Express.Key := Node.Attributes['Key'];
Express.Order := Node.Attributes['Order'];
Express.Value := Node.Attributes['Order'];
Express.IncludeEqual := Node.Attributes['IncludeEqual'];
Express.BreakLimit := Node.Attributes['BreakLimit'];
end;
procedure TVSRuleReader.LoadOrderExpression(Node: IXMLNode;
Express: TVSOrderExpression);
begin
Express.Key := Node.Attributes['Key'];
Express.Order := Node.Attributes['Order'];
end;
procedure TVSRuleReader.LoadRuleInfo(Node: IXMLNode; Rule: TVSRule);
begin
Rule.Title := Node.Attributes['Title'];
Rule.ID := Node.Attributes['ID'];
end;
procedure TVSRuleReader.LoadSimpleConditionExpression(Node: IXMLNode;
Express: TVSSimpleConditionExpression);
var
exp : TVSExpression;
subNode : IXMLNode;
begin
subNode := node.ChildNodes.FindNode('Expression');
if subNode <> nil then
begin
LoadExpression(subNode,exp);
if exp <> nil then
begin
Express.Expression := exp;
end;
end;
end;
end.
|
unit uCommonDB;
interface
uses DB, uCommonDBParams, NagScreenUnit;
type
TCommonDBTransaction = class;
TCommonDB = class(TObject)
public
procedure SetHandle(const Handle); virtual; abstract;
procedure GetHandle(var Handle: Integer); virtual; abstract;
function GetTransaction: TCommonDBTransaction; virtual; abstract;
end;
TCommonDBTransaction = class(TObject)
protected
function GetInTransaction: Boolean; virtual; abstract;
function GetNativeTransaction: TObject; virtual; abstract;
public
procedure Start; virtual; abstract;
procedure Rollback; virtual; abstract;
procedure Commit; virtual; abstract;
property InTransaction: Boolean read GetInTransaction;
procedure ExecQuery(SQL: string); virtual; abstract;
function QueryData(SQL: string): TDataSet; virtual; abstract;
procedure NewSQL(query: TDataSet; SQL: string); virtual; abstract;
procedure RemoveDataSet(query: TDataSet); virtual; abstract;
property NativeTransaction: TObject read GetNativeTransaction;
end;
TDBCenter = class(TObject)
private
FDB: TCommonDB;
FWriteTransaction: TCommonDBTransaction;
FReadTransaction: TCommonDBTransaction;
FParams: TCommonDBParams;
FDataSets: array of TDataSet;
FOriginalSQLs: array of string;
FFields: array of string;
FQuoteStrs: array of Boolean;
function ReadValue(s: string): Variant;
procedure SetValue(s: string; value: Variant);
public
ShowNagScreen: Boolean;
constructor Create(DB: TCommonDB);
destructor Destroy; override;
procedure ExecQuery(Transaction: TCommonDBTransaction; SQL: string;
ParamsToSubstitute: string = '';
QuoteStr: Boolean = True); overload;
function QueryData(Transaction: TCommonDBTransaction; SQL: string;
ParamsToSubstitute: string = '';
QuoteStr: Boolean = True): TDataSet; overload;
procedure ExecWithResult(Transaction: TCommonDBTransaction;
SQL: string; ParamsToSubstitute: string = '';
QuoteStr: Boolean = True); overload;
procedure ExecQuery(SQL: string; ParamsToSubstitute: string = '';
QuoteStr: Boolean = True); overload;
function QueryData(SQL: string; ParamsToSubstitute: string = '';
QuoteStr: Boolean = True): TDataSet; overload;
procedure ExecWithResult(SQL: string; ParamsToSubstitute: string = '';
QuoteStr: Boolean = True); overload;
procedure StoreFields(query: TDataSet; fields: string);
procedure Reopen(query: TDataSet);
procedure Seek(query: TDataSet; fields: string);
procedure Refresh(query: TDataSet; fields: string);
procedure Rebind(query: TDataSet);
procedure RemoveDataset(Transaction: TCommonDBTransaction; query: TDataSet); overload;
procedure RemoveDataset(query: TDataSet); overload;
property DB: TCommonDB read FDB;
property WriteTransaction: TCommonDBTransaction read FWriteTransaction;
property ReadTransaction: TCommonDBTransaction read FReadTransaction;
property Params: TCommonDBParams read FParams;
property ParamValues[s: string]: Variant read ReadValue write SetValue; default;
end;
implementation
uses SysUtils;
procedure TDBCenter.RemoveDataset(Transaction: TCommonDBTransaction; query: TDataSet);
begin
Transaction.RemoveDataSet(query);
if query <> nil then query.Free;
end;
procedure TDBCenter.RemoveDataset(query: TDataSet);
begin
RemoveDataSet(ReadTransaction, query);
end;
procedure TDBCenter.Rebind(query: TDataSet);
var
i: Integer;
new_sql: string;
begin
for i := 0 to High(FDataSets) do
if query = FDataSets[i] then
begin
new_sql := FParams.Substitute(FOriginalSQLs[i], FFields[i], FQuoteStrs[i]);
ReadTransaction.NewSQL(query, new_sql);
end;
end;
procedure TDBCenter.Refresh(query: TDataSet; fields: string);
begin
StoreFields(query, fields);
ReOpen(query);
Seek(query, fields);
end;
procedure TDBCenter.Seek(query: TDataSet; fields: string);
var
loc_fields: string;
values: array of Variant;
p: Integer;
fieldName: string;
begin
loc_fields := StringReplace(fields, ',', ';', [rfReplaceAll]);
SetLength(values, 0);
fields := Trim(fields) + ',';
repeat
p := Pos(',', fields);
fieldName := Copy(fields, 1, p - 1);
fields := Trim(Copy(fields, p + 1, Length(fields)));
SetLength(values, Length(values) + 1);
values[High(values)] := Params[fieldName];
until fields = '';
query.Locate(loc_fields, values, [])
end;
procedure TDBCenter.Reopen(query: TDataSet);
begin
query.Close;
query.Open;
end;
procedure TDBCenter.StoreFields(query: TDataSet; fields: string);
begin
FParams.StoreFields(query, fields);
end;
procedure TDBCenter.ExecWithResult(Transaction: TCommonDBTransaction;
SQL: string; ParamsToSubstitute: string = ''; QuoteStr: Boolean = True);
var
result_sql: string;
result: TDataSet;
inTran: Boolean;
i: Integer;
field: TField;
begin
if Trim(ParamsToSubstitute) = '' then
result_sql := SQL
else
result_sql := FParams.Substitute(SQL, ParamsToSubstitute, QuoteStr);
inTran := Transaction.InTransaction;
if not inTran then Transaction.Start;
result := Transaction.QueryData(result_sql);
for i := 0 to result.FieldCount - 1 do
begin
field := result.Fields[i];
Params[field.FieldName] := field.Value;
end;
if not inTran then Transaction.Commit;
end;
procedure TDBCenter.ExecWithResult(SQL: string; ParamsToSubstitute: string = '';
QuoteStr: Boolean = True);
begin
ExecWithResult(WriteTransaction, SQL, ParamsToSubstitute, QuoteStr);
end;
function TDBCenter.QueryData(Transaction: TCommonDBTransaction; SQL: string;
ParamsToSubstitute: string = ''; QuoteStr: Boolean = True): TDataSet;
var
result_sql: string;
NagScreen: TNagScreen;
begin
if ShowNagScreen then
begin
NagScreen := TNagScreen.Create(nil);
NagScreen.Show;
NagScreen.SetStatusText('Отримуються дані з бази даних, зачекайте...');
end;
try
if Trim(ParamsToSubstitute) = '' then
result_sql := SQL
else
result_sql := FParams.Substitute(SQL, ParamsToSubstitute, QuoteStr);
Result := Transaction.QueryData(result_sql);
SetLength(FDataSets, Length(FDataSets) + 1);
SetLength(FOriginalSQLs, Length(FOriginalSQLs) + 1);
SetLength(FFields, Length(FFields) + 1);
SetLength(FQuoteStrs, Length(FQuoteStrs) + 1);
FDataSets[High(FDataSets)] := Result;
FOriginalSQLs[High(FOriginalSQLs)] := SQL;
FFields[High(FFields)] := ParamsToSubstitute;
FQuoteStrs[High(FQuoteStrs)] := QuoteStr;
finally
if ShowNagScreen then NagScreen.Free;
end;
end;
function TDBCenter.QueryData(SQL: string; ParamsToSubstitute: string = '';
QuoteStr: Boolean = True): TDataSet;
begin
Result := QueryData(ReadTransaction, SQL, ParamsToSubstitute, QuoteStr);
end;
procedure TDBCenter.ExecQuery(Transaction: TCommonDBTransaction; SQL: string;
ParamsToSubstitute: string = ''; QuoteStr: Boolean = True);
var
result_sql: string;
begin
if Trim(ParamsToSubstitute) = '' then
result_sql := SQL
else
result_sql := FParams.Substitute(SQL, ParamsToSubstitute, QuoteStr);
Transaction.ExecQuery(result_sql);
end;
procedure TDBCenter.ExecQuery(SQL: string; ParamsToSubstitute: string = '';
QuoteStr: Boolean = True);
begin
ExecQuery(WriteTransaction, SQL, ParamsToSubstitute, QuoteStr);
end;
constructor TDBCenter.Create(DB: TCommonDB);
begin
inherited Create;
FDB := DB;
FWriteTransaction := DB.GetTransaction;
FReadTransaction := DB.GetTransaction;
FParams := TCommonDBParams.Create;
end;
destructor TDBCenter.Destroy;
begin
FParams.Free;
FReadTransaction.Free;
FWriteTransaction.Free;
FDB.Free;
inherited Destroy;
end;
function TDBCenter.ReadValue(s: string): Variant;
begin
Result := FParams[s];
end;
procedure TDBCenter.SetValue(s: string; value: Variant);
begin
FParams[s] := value;
end;
end.
|
unit CFPopupEdit;
interface
uses
Windows, Classes, Controls, CFButtonEdit, CFControl, CFPopupForm;
type
TCFPopupEdit = class(TCFButtonEdit)
private
FPopup: TCFPopupForm;
procedure DoPopupControl;
function GetPopupControl: TWinControl;
procedure SetPopupControl(const Value: TWinControl);
protected
procedure DoButtonClick; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Popup;
procedure ClosePopup;
published
property PopupControl: TWinControl read GetPopupControl write SetPopupControl;
end;
implementation
{ TCFPopupEdit }
procedure TCFPopupEdit.ClosePopup;
begin
FPopup.ClosePopup(False);
end;
constructor TCFPopupEdit.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FPopup := TCFPopupForm.Create(Self);
Height := 20;
end;
destructor TCFPopupEdit.Destroy;
begin
FPopup.Free;
inherited Destroy;
end;
procedure TCFPopupEdit.DoButtonClick;
begin
inherited DoButtonClick;
if not (csDesigning in ComponentState) then
begin
if ReadOnly then Exit;
DoPopupControl;
end;
end;
procedure TCFPopupEdit.DoPopupControl;
begin
FPopup.Popup(Self);
end;
function TCFPopupEdit.GetPopupControl: TWinControl;
begin
Result := FPopup.PopupControl;
end;
procedure TCFPopupEdit.Popup;
begin
DoButtonClick;
end;
procedure TCFPopupEdit.SetPopupControl(const Value: TWinControl);
begin
FPopup.PopupControl := Value;
end;
end.
|
(*
Unité : UTimer.pas
Date : 28/10/2002
Auteur : Sébastien TIMONER (sebastien@timoner.com)
Description : Timer utilisant l'api SetWaitableTimer, permettant d'avoir
un timer beaucoup plus fiable que le TTimer de delphi
*)
unit UTimer;
interface
uses
SysUtils,
Windows,
Classes,
SyncObjs;
type
TWaitableTime = class(TForm)
private
FStartEvent: TEvent;
FStopEvent: TEvent;
FKillEvent: TEvent;
FIntervalle: integer;
FTimer:THandle;
FOnTimer: TNotifyEvent;
FTickCount: integer;
FTickLock: TCriticalSection;
FStartTick:Cardinal;
FCounterTick:integer;
FNow:boolean;
procedure SetIntervalle(const Value: integer); // millisecondes
procedure DoOnTimer;
function GetTickCount: integer;
procedure SetTickCount(const Value: integer);
procedure IncTickCount;
protected
procedure Execute; override;
public
constructor Create;
destructor Destroy; override;
procedure Start(const ANow:boolean=True);
procedure Stop;
procedure Kill;
property Intervalle: integer read FIntervalle write SetIntervalle;
property OnTimer: TNotifyEvent read FOnTimer write FOnTimer;
property TickCount: integer read GetTickCount write SetTickCount;
end;
implementation
{ TWaitableTime }
constructor TWaitableTime.Create;
begin
inherited create(True);
FStartEvent:=TEvent.Create(nil,false,false,'');
FStopEvent:=TEvent.Create(nil,false,false,'');
FKillEvent:=TEvent.Create(nil,false,false,'');
FTimer:=CreateWaitableTimer(nil,false,nil);
FTickLock:=TCriticalSection.Create;
Resume;
end;
destructor TWaitableTime.Destroy;
begin
FTickLock.Free;
FStartEvent.Free;
FStopEvent.Free;
FKillEvent.Free;
CloseHandle(FTimer);
inherited;
end;
procedure TWaitableTime.DoOnTimer;
begin
if assigned(FOnTimer) then FOnTimer(self);
end;
procedure TWaitableTime.Execute;
var
_Event:Array [0..3] of THandle;
_starttime:int64;
begin
_Event[0]:=FStartEvent.Handle;
_Event[1]:=FStopEvent.Handle;
_Event[2]:=FTimer;
_Event[3]:=FKillEvent.Handle;
while not Terminated do
begin
case WaitForMultipleObjects(4,@_Event,False,INFINITE) of
WAIT_OBJECT_0:
begin
TickCount:=0;
FStartTick:=windows.GetTickCount;
FCounterTick:=0;
if FNow then _StartTime:=-10000
else _starttime:=-(FIntervalle * 10000);
SetWaitableTimer(FTimer,_starttime,FIntervalle,nil,nil,True);
end;
WAIT_OBJECT_0+1:
begin
CancelWaitableTimer(FTimer);
end;
WAIT_OBJECT_0+2:
begin
IncTickCount;
DoOnTimer;
end;
WAIT_OBJECT_0+3:
begin
CancelWaitableTimer(FTimer);
Terminate;
end;
end;
end;
end;
function TWaitableTime.GetTickCount: integer;
begin
FTickLock.Acquire;
try
Result := FTickCount;
finally
FTickLock.Release;
end;
end;
procedure TWaitableTime.IncTickCount;
var
_cardinal:Cardinal;
begin
FTickLock.Acquire;
try
inc(FTickCount);
inc(FCounterTick);
if ((FCounterTick mod 5)=0) then
begin
_cardinal:=Windows.GetTickCount;
if _cardinal>FStartTick then
_cardinal:=(abs(_cardinal-FStartTick)) div Intervalle
else
_cardinal:=abs((high(cardinal)-FStartTick+_cardinal)) div Intervalle;
if _cardinal<=2147483647 then
FTickCount:=integer(_cardinal)
else
FTickCount:=high(integer);
end;
finally
FTickLock.Release;
end;
end;
procedure TWaitableTime.Kill;
begin
FKillEvent.SetEvent;
end;
procedure TWaitableTime.SetIntervalle(const Value: integer);
begin
FIntervalle:=Value;
end;
procedure TWaitableTime.SetTickCount(const Value: integer);
begin
FTickLock.Acquire;
try
FTickCount := Value;
finally
FTickLock.Release;
end;
end;
procedure TWaitableTime.Start(const ANow:boolean);
begin
FNow:=ANow;
FStartEvent.SetEvent;
end;
procedure TWaitableTime.Stop;
begin
FStopEvent.SetEvent;
end;
end.
|
unit Management;
interface
uses
idSNTP,
Winapi.Windows, Winapi.WinSock2, System.SysUtils;
function getInternetDateTime: TDateTime;
Var
WSAData: TWSAData;
SNTPClient : TIdSNTP;
implementation
procedure Startup;
begin
if WSAStartup($0101, WSAData) <> 0
then raise Exception.Create('WSAStartup');
end;
procedure Cleanup;
begin
if WSACleanup() <> 0then
raise Exception.Create('WSACleanup');
end;
function getInternetDateTime : TDateTime;
var
SNTPClient: TIdSNTP;
begin
Result := 0;
SNTPClient := TIdSNTP.Create();
Startup();
try
SNTPClient.Host := 'time.windows.com';
Result := SNTPClient.DateTime;
finally
SNTPClient.Free;
end;
Cleanup();
end;
end.
|
namespace Main;
interface
implementation
uses
System.Collections.ObjectModel, // Note: this sample requires Beta 2 of the .NET Framework 2.0
System.Collections.Generic;
method GenericMethod;
var
x: array of Integer;
y: ReadOnlyCollection<Integer>;
z: IList<String>;
begin
x := [123,43,2,11];
y := &Array.AsReadonly<Integer>(x);
Console.Writeline('Readonly collection:');
for each s in y do
Console.Writeline(s);
z := &Array.AsReadOnly<String>(['Welcome', 'to', 'Generics']);
for each s: String in z do
Console.Write(s+' ');
end;
method GenericClass;
var
ListA: List<Integer>;
ListB: List<String>;
o: Object;
begin
// instantiating generic types
ListA := new List<Integer>;
ListB := new List<String>;
// calling methods
ListA.Add(123);
ListA.Add(65);
//ListA.Add('bla'); // x is typesafe, so this line will not compile
ListB.Add('Hello');
ListB.Add('World');
// accessing index properties
for i: Integer := 0 to ListA.Count-1 do
Console.WriteLine((i+ListA[i]).ToString);
for i: Integer := 0 to ListB.Count-1 do
Console.Write(ListB[i]+' ');
// casting to back generic types
o := ListA;
ListA := List<Integer>(o);
//y := List<Integer>(o); // compiler error: differently typed instances are not assignment compatible.
ListB := List<String>(o); // will equal to nil
Console.Writeline;
end;
method Main;
begin
GenericClass();
GenericMethod();
Console.ReadKey;
end;
end. |
unit NewFrontiers.Reflection.ValueConvert;
interface
uses System.TypInfo, System.Rtti;
type
TTypeKindSet = set of TTypeKind;
TValueConverter = class
public
class function convertTo(aValue: TValue; aTarget: PTypeInfo): TValue;
end;
implementation
uses SysUtils;
{ TValueConverter }
class function TValueConverter.convertTo(aValue: TValue;
aTarget: PTypeInfo): TValue;
var
ordinalSet, stringSet, floatSet: TTypeKindSet;
begin
if (aValue.Kind = aTarget.Kind) then
begin
result := aValue;
exit;
end;
ordinalSet := [tkInteger, tkInt64, tkChar, tkEnumeration];
stringSet := [tkString, tkUString];
floatSet := [tkFloat];
result := TValue.Empty;
// Quelle: Ordinal
if (aValue.Kind in ordinalSet) then
begin
// Ziel: Ordinal
if (aTarget.Kind in ordinalSet) then
result := TValue.FromOrdinal(aTarget, aValue.AsOrdinal)
// Ziel String
else if (aTarget.Kind in stringSet) then
result := TValue.From<string>(IntToStr(aValue.asOrdinal))
end
// Quelle: String
else if (aValue.Kind in stringSet) then
begin
// ZIel: Ordinal
if (aTarget.Kind in ordinalSet) then
result := TValue.From<integer>(StrToInt(aValue.AsString))
else if (aTarget.Kind in floatSet) and (aTarget.Name = 'TDateTime') then
result := TValue.From<Extended>(StrToDateTime(aValue.AsString))
else if (aTarget.Kind in floatSet) then
result := TValue.From<Extended>(StrToFloat(aValue.AsString));
end
// Quelle: DateTime
else if (aValue.Kind in floatSet) and (aValue.TypeInfo.Name = 'TDateTime') then
begin
if (aTarget.Kind in stringSet) then
result := TValue.From<string>(DateTimeToStr(aValue.AsExtended));
end
// Quelle: Float
else if (aValue.Kind in floatSet) then
begin
if (aTarget.Kind in stringSet) then
result := TValue.From<string>(FloatToStr(aValue.AsExtended));
end;
end;
end.
|
(***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is TurboPower Async Professional
*
* The Initial Developer of the Original Code is
* TurboPower Software
*
* Portions created by the Initial Developer are Copyright (C) 1991-2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** *)
{*********************************************************}
{* ADPBOOK.PAS 4.06 *}
{*********************************************************}
{* Deprecated phone book database *}
{*********************************************************}
{Global defines potentially affecting this unit}
{$I ..\..\includes\AWDEFINE.INC}
{Options required for this unit}
{$G+,X+,F-,V-,P-,T-,B-}
unit AdPBook;
{-Ini database descendant for storing phonebooks}
interface
uses
SysUtils,
Windows,
Classes,
ooMisc,
AdDataB,
AdIniDB;
const
{length of name and phone number fields for phonebook}
NameLen = 21;
PhoneNumLen = 21;
type
PPhonebookEntry = ^TPhonebookEntry;
TPhonebookEntry = packed record
Name : String[NameLen];
Number : String[PhoneNumLen];
end;
TApdPhonebook = class(TApdCustomIniDBase)
public
constructor Create(AOwner : TComponent); override;
protected
{.Z+}
procedure DefineProperties(Filer : TFiler); override;
{.Z-}
published
property FileName;
end;
implementation
procedure TApdPhonebook.DefineProperties(Filer : TFiler);
begin
CustComponent := True;
inherited DefineProperties(Filer);
end;
constructor TApdPhonebook.Create(AOwner : TComponent);
var
FL : TDBFieldList;
begin
inherited Create(AOwner);
{create the field list}
FL := TDBFieldList.Create;
FL.Add(TDBFieldInfo.CreateString('Name', NameLen));
FL.Add(TDBFieldInfo.CreateString('Number', PhoneNumLen));
{set the field list}
FieldList := FL;
FL.Free;
IndexedField := 'Name';
end;
end.
|
{
Role
Draw shapes using the mouse actions.
}
unit ThDrawObject;
interface
uses
System.Classes,
System.Generics.Collections,
GR32, GR32_Polygons, GR32_VectorUtils,
clipper,
ThTypes, ThClasses, ThItemStyle,
ThCanvasEventProcessor,
ThItem, ThShapeItem, ThItemCollections;
type
TThCustomDrawObject = class(TThInterfacedObject, IThDrawObject)
private
FDrawStyle: IThDrawStyle;
protected
FMouseDowned: Boolean;
public
constructor Create(AStyle: IThDrawStyle); virtual;
procedure Draw(Bitmap: TBitmap32; AScale, AOffset: TFloatPoint); virtual;
procedure MouseDown(const APoint: TFloatPoint; AShift: TShiftState); virtual;
procedure MouseMove(const APoint: TFloatPoint; AShift: TShiftState); virtual;
procedure MouseUp(const APoint: TFloatPoint; AShift: TShiftState); virtual;
function GetItemInstance: IThItem; virtual;
property DrawStyle: IThDrawStyle read FDrawStyle write FDrawStyle;
end;
// 자유선으로 그리기 객체(Free draw object)
TThPenDrawObject = class(TThCustomDrawObject)
private
FPenItem: TThPenItem;
FPath: TList<TFloatPoint>;
FPolyPolyPath: TPaths;
FPolyPoly: TThPolyPoly;
public
constructor Create(AStyle: IThDrawStyle); override;
destructor Destroy; override;
procedure MouseDown(const APoint: TFloatPoint; AShift: TShiftState); override;
procedure MouseMove(const APoint: TFloatPoint; AShift: TShiftState); override;
procedure MouseUp(const APoint: TFloatPoint; AShift: TShiftState); override;
procedure Draw(Bitmap: TBitmap32; AScale, AOffset: TFloatPoint); override;
function GetItemInstance: IThItem; override;
end;
// 지우개 베이스 클래스
TThCustomEraserObject = class(TThCustomDrawObject)
private
FItemList: TThItemList;
function GetDrawStyle: TThEraserStyle;
property DrawStyle: TThEraserStyle read GetDrawStyle;
protected
FPos: TFloatPoint;
public
constructor Create(AStyle: IThDrawStyle; AItems: TThItemList); reintroduce;
procedure Draw(Bitmap: TBitmap32; AScale, AOffset: TFloatPoint); override;
end;
// 지나간 객체 지우개(Passed objects eraser)
TThObjectEraserObject = class(TThCustomEraserObject)
public
procedure MouseDown(const APoint: TFloatPoint; AShift: TShiftState); override;
procedure MouseMove(const APoint: TFloatPoint; AShift: TShiftState); override;
procedure MouseUp(const APoint: TFloatPoint; AShift: TShiftState); override;
end;
// Shape (multi)select
// Select > Move, Delete, Resize, Link
TThShapeDrawObject = class(TThCustomDrawObject)
private
FMouseProcessor: TThShapeDrawMouseProcessor;
FItemList: TThItemList;
FSelectedItems: TThSelectedItems;
FShapeId: string;
procedure SetShapeId(const Value: string);
public
constructor Create(AItems: TThItemList); reintroduce;
destructor Destroy; override;
procedure MouseDown(const APoint: TFloatPoint; AShift: TShiftState); override;
procedure MouseMove(const APoint: TFloatPoint; AShift: TShiftState); override;
procedure MouseUp(const APoint: TFloatPoint; AShift: TShiftState); override;
procedure DeleteSelectedItems;
property ShapeId: string read FShapeId write SetShapeId;
end;
implementation
uses
// Winapi.Windows, // ODS
Vcl.Forms, System.UITypes,
ThUtils,
System.SysUtils,
System.Math;
{ TThDrawObject }
constructor TThCustomDrawObject.Create(AStyle: IThDrawStyle);
begin
FDrawStyle := AStyle;
end;
procedure TThCustomDrawObject.MouseDown;
begin
FMouseDowned := True;
end;
procedure TThCustomDrawObject.MouseMove(const APoint: TFloatPoint;
AShift: TShiftState);
begin
end;
procedure TThCustomDrawObject.MouseUp;
begin
FMouseDowned := False;
end;
function TThCustomDrawObject.GetItemInstance: IThItem;
begin
Result := nil;
end;
procedure TThCustomDrawObject.Draw(Bitmap: TBitmap32; AScale, AOffset: TFloatPoint);
begin
end;
{ TThPenObject }
constructor TThPenDrawObject.Create(AStyle: IThDrawStyle);
begin
inherited;
FPath := TList<TFloatPoint>.Create;
end;
destructor TThPenDrawObject.Destroy;
begin
FPath.Free;
inherited;
end;
procedure TThPenDrawObject.MouseDown(const APoint: TFloatPoint; AShift: TShiftState);
var
LPoly: TThPoly;
begin
inherited;
FPenItem := TThPenItem.Create;
FPenItem.SetStyle(FDrawStyle);
FPath.Add(APoint);
LPoly := Circle(APoint, FPenItem.Thickness / 2);
FPolyPoly := GR32_VectorUtils.PolyPolygon(LPoly);
FPolyPolyPath := AAFloatPoint2AAPoint(FPolyPoly, 3);
end;
procedure TThPenDrawObject.MouseMove(const APoint: TFloatPoint; AShift: TShiftState);
var
Poly: TThPoly;
PolyPath: TPath;
LastPt: TFloatPoint; // Adjusted point
begin
inherited;
if FMouseDowned then
begin
FPath.Add(APoint);
LastPt := FPath.Items[FPath.Count-2];
Poly := BuildPolyline([LastPt, APoint], FPenItem.Thickness, jsRound, esRound);
PolyPath := AAFloatPoint2AAPoint(Poly, 3);
with TClipper.Create do
try
AddPaths(FPolyPolyPath, ptSubject, True);
AddPath(PolyPath, ptClip, True);
Execute(ctUnion, FPolyPolyPath, pftNonZero);
finally
Free;
end;
FPolyPoly := AAPoint2AAFloatPoint(FPolyPolyPath, 3);
end;
end;
procedure TThPenDrawObject.MouseUp;
begin
inherited;
FPath.Clear;
FPolyPolyPath := nil;
FPolyPoly := nil;
FPenItem := nil;
end;
procedure TThPenDrawObject.Draw(Bitmap: TBitmap32; AScale, AOffset: TFloatPoint);
begin
if Assigned(FPenItem) then
FPenItem.DrawPoly(Bitmap, AScale, AOffset, FPath.ToArray, FPolyPoly);
end;
function TThPenDrawObject.GetItemInstance: IThItem;
begin
Result := FPenItem;
FPenItem := nil;
end;
{ TThEraserDrawObject }
constructor TThCustomEraserObject.Create(AStyle: IThDrawStyle;
AItems: TThItemList);
begin
if not Assigned(AStyle) then
AStyle := TThEraserStyle.Create;
inherited Create(AStyle);
FItemList := AItems;
end;
procedure TThCustomEraserObject.Draw(Bitmap: TBitmap32; AScale,
AOffset: TFloatPoint);
var
Poly: TThPoly;
begin
Poly := Circle(FPos, DrawStyle.Thickness / 2);
PolylineFS(Bitmap, Poly, clBlack32, True);
end;
function TThCustomEraserObject.GetDrawStyle: TThEraserStyle;
begin
Result := TThEraserStyle(FDrawStyle);
end;
{ TThObjectEraserObject }
procedure TThObjectEraserObject.MouseDown(const APoint: TFloatPoint; AShift: TShiftState);
begin
inherited;
FPos := APoint;
MouseMove(APoint, AShift);
end;
procedure TThObjectEraserObject.MouseMove(const APoint: TFloatPoint; AShift: TShiftState);
var
I: Integer;
Poly: TThPoly;
LItems: TArray<IThItem>;
begin
inherited;
if FMouseDowned then
begin
FPos := APoint;
Poly := Circle(APoint, DrawStyle.Thickness / 2);
LItems := FItemList.GetPolyInItems(Poly);
for I := 0 to Length(LItems) - 1 do
TThPenItem(LItems[I]).IsDeletion := True;
end;
end;
procedure TThObjectEraserObject.MouseUp(const APoint: TFloatPoint; AShift: TShiftState);
var
I: Integer;
Item: IThItem;
begin
inherited;
for I := FItemList.Count - 1 downto 0 do
begin
Item := FItemList[I];
if TThPenItem(Item).IsDeletion then
FItemList.Delete(I);
end;
end;
{ TThShapeDrawObject }
constructor TThShapeDrawObject.Create(AItems: TThItemList);
begin
inherited Create(TThShapeStyle.Create);
FItemList := AItems;
FSelectedItems := TThSelectedItems.Create;
FMouseProcessor := TThShapeDrawMouseProcessor.Create(FItemList, FSelectedItems);
end;
destructor TThShapeDrawObject.Destroy;
begin
FMouseProcessor.Free;
FSelectedItems.Free;
inherited;
end;
procedure TThShapeDrawObject.MouseDown(const APoint: TFloatPoint; AShift: TShiftState);
begin
inherited;
FMouseProcessor.MouseDown(APoint, AShift);
end;
procedure TThShapeDrawObject.MouseMove(const APoint: TFloatPoint;
AShift: TShiftState);
begin
inherited;
FMouseProcessor.MouseMove(APoint, AShift);
end;
procedure TThShapeDrawObject.MouseUp(const APoint: TFloatPoint; AShift: TShiftState);
begin
inherited;
FMouseProcessor.MouseUp(APoint, AShift);
end;
procedure TThShapeDrawObject.SetShapeId(const Value: string);
begin
FShapeId := Value;
FMouseProcessor.ShapeId := Value;
end;
procedure TThShapeDrawObject.DeleteSelectedItems;
var
I: Integer;
Item: IThSelectableItem;
Item1, Item2: IInterface;
begin
// FSelectedItem := nil;
for Item in FSelectedItems do
begin
// FSelectedItems.Item(IThSelectableItem)으로
// FItemList.Item(IThItem) 삭제(Remove) 시
// 포인터가 달라 지워지지않음
// 객체(또는 IInterface)로 전환 후 비교 후 삭제필요(ㅠㅜㅠㅜ)
// https://blog.excastle.com/2008/05/10/interfaces-and-reference-equality-beware/
// FItems.Remove(Item as IThItem);
for I := FItemList.Count - 1 downto 0 do
begin
Item1 := FItemList[I] as IInterface;
Item2 := Item as IInterface;
if Item1 = Item2 then
FItemList.Delete(I);
end;
end;
FSelectedItems.Clear;
end;
end.
|
{
Clever Internet Suite Version 6.2
Copyright (C) 1999 - 2006 Clever Components
www.CleverComponents.com
}
unit clProgressBar;
interface
{$I clVer.inc}
uses
Classes, clDC, clMultiDC, clDCUtils, Graphics, Windows, {$IFDEF DEMO}Forms,{$ENDIF} Controls;
type
TclDrawPaintOption = (dpDrawTotal, dpDrawItems);
TclDrawPaintOptions = set of TclDrawPaintOption;
TclDrawOrientation = (doHorisontal, doVertical);
TclDrawStyle = (ds3D, dsFlat);
TclBorderStyle = (bsNone, bsFrame);
TclStatusColor = array[TclProcessStatus] of TColor;
TclProgressBarItemType = (gitFrame, gitBackGround, gitProcessTotal, gitProcessItem);
TclColorScheme = (csSchemeCustom, csScheme1, csScheme2, csScheme3);
TclProgressBarCustomDraw = procedure (Sender: TObject; AItemType: TclProgressBarItemType;
ACanvas: TCanvas; ARect: TRect; AColor: TColor; var Handled: Boolean) of object;
TclProgressBarPaint = procedure (Sender: TObject; var AState: TclResourceStateList) of object;
TclProgressBar = class;
TclDrawColors = class;
TclStatusColors = class(TPersistent)
private
FOwner: TclDrawColors;
FStatusColor: TclStatusColor;
function GetStatusColor(const Index: Integer): TColor;
procedure SetStatusColor(const Index: Integer; const Value: TColor);
protected
procedure SetStatusColors(AStatusColor: TclStatusColor);
public
constructor Create(AOwner: TclDrawColors);
procedure Assign(Source: TPersistent); override;
function GetStatusColors(): TclStatusColor;
published
property StatusUnknown: TColor index psUnknown read GetStatusColor write SetStatusColor;
property StatusSuccess: TColor index psSuccess read GetStatusColor write SetStatusColor;
property StatusFailed: TColor index psFailed read GetStatusColor write SetStatusColor;
property StatusErrors: TColor index psErrors read GetStatusColor write SetStatusColor;
property StatusProcess: TColor index psProcess read GetStatusColor write SetStatusColor;
property StatusTerminated: TColor index psTerminated read GetStatusColor write SetStatusColor;
end;
TclDrawColors = class(TPersistent)
private
FBackGround: TColor;
FOwner: TclProgressBar;
FScheme: TclColorScheme;
FFrame: TColor;
FItemColors: TclStatusColors;
FTotalColors: TclStatusColors;
procedure SetBackGround(const Value: TColor);
procedure SetScheme(const Value: TclColorScheme);
procedure SetColorsByScheme;
procedure SetFrame(const Value: TColor);
procedure SetItemColors(const Value: TclStatusColors);
procedure SetTotalColors(const Value: TclStatusColors);
function ColorsStored(AColor1, AColor2: TclStatusColor): Boolean;
function ItemColorsStored: Boolean;
function TotalColorsStored: Boolean;
function BackGroundStored: Boolean;
function FrameStored: Boolean;
protected
procedure Changed(); virtual;
procedure SetCustomScheme;
public
constructor Create(AOwner: TclProgressBar);
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
published
property BackGround: TColor read FBackGround write SetBackGround stored BackGroundStored;
property Frame: TColor read FFrame write SetFrame stored FrameStored;
property Scheme: TclColorScheme read FScheme write SetScheme default csScheme1;
property ItemColors: TclStatusColors read FItemColors write SetItemColors stored ItemColorsStored;
property TotalColors: TclStatusColors read FTotalColors write SetTotalColors stored TotalColorsStored;
end;
TclProgressBarNotifier = class(TclControlNotifier)
private
FProgressBar: TclProgressBar;
FLastItem: TclInternetItem;
function GetLastState(): TclResourceStateList;
protected
procedure DoResourceStateChanged(Item: TclInternetItem); override;
procedure DoItemDeleted(Item: TclInternetItem); override;
public
constructor Create(AControl: TclCustomInternetControl; AProgressBar: TclProgressBar);
end;
TclProgressBar = class(TGraphicControl)
private
FOptions: TclDrawPaintOptions;
FOrientation: TclDrawOrientation;
FColors: TclDrawColors;
FProgressSplit: Integer;
FOnChanged: TNotifyEvent;
FOnCustomDraw: TclProgressBarCustomDraw;
FInternetControl: TclCustomInternetControl;
FNotifier: TclProgressBarNotifier;
FStyle: TclDrawStyle;
FBorderStyle: TclBorderStyle;
FOnPaint: TclProgressBarPaint;
procedure DrawBackGround(ACanvas: TCanvas; ARect: TRect);
procedure DrawFrame(ACanvas: TCanvas; ARect: TRect);
procedure DrawProgressItems(AState: TclResourceStateList; ACanvas: TCanvas; ARect: TRect);
procedure DrawTotalProgress(AState: TclResourceStateList; ACanvas: TCanvas; ARect: TRect);
procedure DrawProgressItem(AState: TclResourceStateList; AItem: TclResourceStateItem;
ACanvas: TCanvas; ARect: TRect);
procedure PaintRect(ACanvas: TCanvas; ARect: TRect; AColor: TColor);
function GetShadowColor(ABaseColor: TColor; AOffset: Integer): TColor;
function GetProgressPixels(AProgress, ATotal, APixelRange: Integer): Integer;
procedure PaintHorisontalRect(ACanvas: TCanvas; ARect: TRect; AColor: TColor);
procedure PaintVerticalRect(ACanvas: TCanvas; ARect: TRect; AColor: TColor);
procedure SetProgressSplit(const Value: Integer);
procedure SetOptions(const Value: TclDrawPaintOptions);
procedure SetOrientation(const Value: TclDrawOrientation);
procedure SetStyle(const Value: TclDrawStyle);
procedure SetColors(const Value: TclDrawColors);
procedure SetInternetControl(const Value: TclCustomInternetControl);
procedure ClearNotifier();
function GetLastState(): TclResourceStateList;
procedure SetBorderStyle(const Value: TclBorderStyle);
protected
procedure NotifyChanged; virtual;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure Changed; virtual;
procedure DoPaint(var AState: TclResourceStateList); virtual;
procedure CustomDraw(AItemType: TclProgressBarItemType;
ACanvas: TCanvas; ARect: TRect; AColor: TColor; var Handled: Boolean); virtual;
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure Draw(AState: TclResourceStateList; ACanvas: TCanvas; ARect: TRect);
published
property Options: TclDrawPaintOptions read FOptions write SetOptions default [dpDrawTotal, dpDrawItems];
property Orientation: TclDrawOrientation read FOrientation write SetOrientation default doHorisontal;
property Style: TclDrawStyle read FStyle write SetStyle default ds3D;
property BorderStyle: TclBorderStyle read FBorderStyle write SetBorderStyle default bsFrame;
property Colors: TclDrawColors read FColors write SetColors;
property ProgressSplit: Integer read FProgressSplit write SetProgressSplit default 25;
property InternetControl: TclCustomInternetControl read FInternetControl write SetInternetControl;
property Align;
property Visible;
property OnChanged: TNotifyEvent read FOnChanged write FOnChanged;
property OnCustomDraw: TclProgressBarCustomDraw read FOnCustomDraw write FOnCustomDraw;
property OnPaint: TclProgressBarPaint read FOnPaint write FOnPaint;
end;
implementation
{$IFDEF DELPHI6}
uses
Types;
{$ENDIF}
const
BackGroundColorSchemes: array[TclColorScheme] of TColor = (
0,
clWhite,
{$IFDEF DELPHI6}clCream{$ELSE}TColor($F0FBFF){$ENDIF},
TColor($E55500)
);
FrameColorSchemes: array[TclColorScheme] of TColor = (
0,
clBlue,
{$IFDEF DELPHI6}clSkyBlue{$ELSE}TColor($F0CAA6){$ENDIF},
TColor($298514)
);
ItemColorSchemes: array[TclColorScheme] of TclStatusColor = (
(0, 0, 0, 0, 0, 0),
(clBlue, clBlue, clRed, clYellow, clBlue, clBlue),
{$IFDEF DELPHI6}
(clSkyBlue, clSkyBlue, clLtGray, clLtGray, clSkyBlue, clSkyBlue)
{$ELSE}
(TColor($F0CAA6), TColor($F0CAA6), clLtGray, clLtGray, TColor($F0CAA6), TColor($F0CAA6))
{$ENDIF},
(TColor($298514), TColor($298514), TColor($170DD6), TColor($0BC5F4), TColor($298514), TColor($298514))
);
TotalColorSchemes: array[TclColorScheme] of TclStatusColor = (
(0, 0, 0, 0, 0, 0),
(clGreen, clGreen, clRed, clYellow, clGreen, clGreen),
{$IFDEF DELPHI6}
(clSkyBlue, clSkyBlue, clLtGray, clLtGray, clSkyBlue, clSkyBlue)
{$ELSE}
(TColor($F0CAA6), TColor($F0CAA6), clLtGray, clLtGray, TColor($F0CAA6), TColor($F0CAA6))
{$ENDIF},
(TColor($296514), TColor($296514), TColor($170DD6), TColor($0BC5F4), TColor($296514), TColor($296514))
);
{ TclProgressBar }
procedure TclProgressBar.DrawBackGround(ACanvas: TCanvas; ARect: TRect);
var
Handled: Boolean;
begin
Handled := False;
CustomDraw(gitBackGround, ACanvas, ARect, Colors.BackGround, Handled);
if not Handled then
begin
ACanvas.Brush.Color := Colors.BackGround;
ACanvas.FillRect(ARect);
end;
end;
procedure TclProgressBar.DrawFrame(ACanvas: TCanvas; ARect: TRect);
var
Handled: Boolean;
begin
Handled := False;
CustomDraw(gitFrame, ACanvas, ARect, Colors.Frame, Handled);
if not Handled then
begin
ACanvas.Brush.Color := Colors.Frame;
ACanvas.FrameRect(ARect);
end;
end;
function TclProgressBar.GetShadowColor(ABaseColor: TColor; AOffset: Integer): TColor;
function GetCorrectValue(AValue, AOffset: Integer): Integer;
begin
Result := AValue;
if ((Result + AOffset) > -1) and ((Result + AOffset) < 256) then
begin
Result := AValue + AOffset;
end;
end;
begin
if (ABaseColor and (not $FFFFFF)) > 0 then
begin
Result := ABaseColor;
end else
begin
Result := RGB(
GetCorrectValue(GetRValue(ABaseColor), AOffset),
GetCorrectValue(GetGValue(ABaseColor), AOffset),
GetCorrectValue(GetBValue(ABaseColor), AOffset));
end;
end;
procedure TclProgressBar.PaintRect(ACanvas: TCanvas; ARect: TRect; AColor: TColor);
begin
if Orientation = doHorisontal then
begin
PaintHorisontalRect(ACanvas, ARect, AColor);
end else
begin
PaintVerticalRect(ACanvas, ARect, AColor);
end;
end;
procedure TclProgressBar.PaintHorisontalRect(ACanvas: TCanvas; ARect: TRect; AColor: TColor);
var
R: TRect;
begin
if (Style = ds3D) and ((ARect.Bottom - ARect.Top) > 2) then
begin
R := ARect;
R.Bottom := R.Top + 2;
ACanvas.Brush.Color := GetShadowColor(AColor, 30);
ACanvas.FillRect(R);
OffsetRect(R, 0, 2);
ACanvas.Brush.Color := GetShadowColor(AColor, 10);
ACanvas.FillRect(R);
R := ARect;
R.Top := R.Bottom - 2;
ACanvas.Brush.Color := GetShadowColor(AColor, -30);
ACanvas.FillRect(R);
OffsetRect(R, 0, - 2);
ACanvas.Brush.Color := GetShadowColor(AColor, -10);
ACanvas.FillRect(R);
R := ARect;
InflateRect(R, 0, - 4);
end else
begin
R := ARect;
end;
ACanvas.Brush.Color := AColor;
ACanvas.FillRect(R);
end;
procedure TclProgressBar.PaintVerticalRect(ACanvas: TCanvas; ARect: TRect; AColor: TColor);
var
R: TRect;
begin
if (Style = ds3D) and ((ARect.Right - ARect.Left) > 2) then
begin
R := ARect;
R.Right := R.Left + 2;
ACanvas.Brush.Color := GetShadowColor(AColor, 30);
ACanvas.FillRect(R);
OffsetRect(R, 2, 0);
ACanvas.Brush.Color := GetShadowColor(AColor, 10);
ACanvas.FillRect(R);
R := ARect;
R.Left := R.Right - 2;
ACanvas.Brush.Color := GetShadowColor(AColor, -30);
ACanvas.FillRect(R);
OffsetRect(R, - 2, 0);
ACanvas.Brush.Color := GetShadowColor(AColor, -10);
ACanvas.FillRect(R);
R := ARect;
InflateRect(R, - 4, 0);
end else
begin
R := ARect;
end;
ACanvas.Brush.Color := AColor;
ACanvas.FillRect(R);
end;
function TclProgressBar.GetProgressPixels(AProgress, ATotal, APixelRange: Integer): Integer;
begin
Result := Round((AProgress / ATotal) * APixelRange);
end;
procedure TclProgressBar.DrawTotalProgress(AState: TclResourceStateList; ACanvas: TCanvas; ARect: TRect);
var
old: Integer;
R: TRect;
Handled: Boolean;
begin
R := ARect;
if (Orientation = doHorisontal) then
begin
old := R.Right;
R.Right := R.Left + GetProgressPixels(AState.BytesProceed, AState.ResourceSize, ARect.Right - ARect.Left);
if (R.Right <> R.Left) and (R.Right <> old) then
begin
R.Right := R.Right + 1;
end;
end else
begin
old := R.Top;
R.Top := R.Bottom - GetProgressPixels(AState.BytesProceed, AState.ResourceSize, ARect.Bottom - ARect.Top);
if (R.Top <> R.Bottom) and (R.Top <> old) then
begin
R.Top := R.Top - 1;
end;
end;
Handled := False;
CustomDraw(gitProcessTotal, ACanvas, R, Colors.TotalColors.GetStatusColors()[AState.LastStatus], Handled);
if not Handled then
begin
PaintRect(ACanvas, R, Colors.TotalColors.GetStatusColors()[AState.LastStatus]);
end;
end;
procedure TclProgressBar.DrawProgressItem(AState: TclResourceStateList; AItem: TclResourceStateItem;
ACanvas: TCanvas; ARect: TRect);
var
old: Integer;
R: TRect;
Handled: Boolean;
begin
R := ARect;
if (Orientation = doHorisontal) then
begin
R.Left := R.Left + GetProgressPixels(AItem.ResourcePos, AState.ResourceSize, ARect.Right - ARect.Left);
old := R.Right;
R.Right := R.Left + GetProgressPixels(AItem.BytesProceed, AState.ResourceSize, ARect.Right - ARect.Left);
if (R.Right <> R.Left) and (R.Right <> old) then
begin
R.Right := R.Right + 1;
end;
end else
begin
R.Bottom := R.Bottom - GetProgressPixels(AItem.ResourcePos, AState.ResourceSize, ARect.Bottom - ARect.Top);
old := R.Top;
R.Top := R.Bottom - GetProgressPixels(AItem.BytesProceed, AState.ResourceSize, ARect.Bottom - ARect.Top);
if (R.Top <> R.Bottom) and (R.Top <> old) then
begin
R.Top := R.Top - 1;
end;
end;
Handled := False;
CustomDraw(gitProcessTotal, ACanvas, R, Colors.ItemColors.GetStatusColors()[AItem.Status], Handled);
if not Handled then
begin
PaintRect(ACanvas, R, Colors.ItemColors.GetStatusColors()[AItem.Status]);
end;
end;
procedure TclProgressBar.DrawProgressItems(AState: TclResourceStateList; ACanvas: TCanvas; ARect: TRect);
var
i: Integer;
begin
for i := 0 to AState.Count - 1 do
begin
DrawProgressItem(AState, AState[i], ACanvas, ARect);
end;
end;
procedure TclProgressBar.Draw(AState: TclResourceStateList; ACanvas: TCanvas; ARect: TRect);
var
R, RatedRect: TRect;
BackBmp: Graphics.TBitmap;
begin
{$IFDEF DEMO}
{$IFNDEF STANDALONEDEMO}
if FindWindow('TAppBuilder', nil) = 0 then
begin
MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' +
'Please visit www.clevercomponents.com to purchase your ' +
'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST);
ExitProcess(1);
end;
{$ENDIF}
{$ENDIF}
BackBmp := Graphics.TBitmap.Create();
try
RatedRect := ARect;
OffsetRect(RatedRect, -RatedRect.Left, -RatedRect.Top);
BackBmp.Handle := CreateCompatibleBitmap(ACanvas.Handle, RatedRect.Right, RatedRect.Bottom);
if (BorderStyle = bsFrame) then
begin
DrawFrame(BackBmp.Canvas, RatedRect);
InflateRect(RatedRect, -1, -1);
end;
DrawBackGround(BackBmp.Canvas, RatedRect);
if (AState <> nil) and (AState.ResourceSize > 0) then
begin
R := RatedRect;
if (dpDrawItems in Options) then
begin
if (Orientation = doHorisontal) then
begin
R.Bottom := R.Bottom - GetProgressPixels(100 - FProgressSplit, 100, RatedRect.Bottom);
end else
begin
R.Right := R.Right - GetProgressPixels(100 - FProgressSplit, 100, RatedRect.Right);
end;
end;
if (dpDrawTotal in Options) then
begin
DrawTotalProgress(AState, BackBmp.Canvas, R);
end;
if (dpDrawTotal in Options) then
begin
if (Orientation = doHorisontal) then
begin
R.Top := R.Bottom;
R.Bottom := RatedRect.Bottom;
end else
begin
R.Left := R.Right;
R.Right := RatedRect.Right;
end;
end else
begin
R := RatedRect;
end;
if (dpDrawItems in Options) then
begin
DrawProgressItems(AState, BackBmp.Canvas, R);
end;
end;
ACanvas.Draw(ARect.Left, ARect.Top, BackBmp);
finally
BackBmp.Free();
end;
end;
constructor TclProgressBar.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FColors := TclDrawColors.Create(Self);
FOptions := [dpDrawTotal, dpDrawItems];
FOrientation := doHorisontal;
FStyle := ds3D;
FBorderStyle := bsFrame;
FProgressSplit := 25;
Width := 150;
Height := GetSystemMetrics(SM_CYVSCROLL);
end;
procedure TclProgressBar.SetColors(const Value: TclDrawColors);
begin
FColors.Assign(Value);
end;
destructor TclProgressBar.Destroy();
begin
ClearNotifier();
FColors.Free();
inherited Destroy();
end;
procedure TclProgressBar.SetProgressSplit(const Value: Integer);
begin
if (FProgressSplit <> Value)
and (Value >= 0) and (Value <= 100) then
begin
FProgressSplit := Value;
NotifyChanged();
end;
end;
procedure TclProgressBar.Changed;
begin
if Assigned(FOnChanged) then
begin
FOnChanged(Self);
end;
end;
procedure TclProgressBar.SetOptions(const Value: TclDrawPaintOptions);
begin
if (FOptions <> Value) then
begin
FOptions := Value;
NotifyChanged();
end;
end;
procedure TclProgressBar.SetOrientation(const Value: TclDrawOrientation);
begin
if (FOrientation <> Value) then
begin
FOrientation := Value;
NotifyChanged();
end;
end;
procedure TclProgressBar.CustomDraw(AItemType: TclProgressBarItemType;
ACanvas: TCanvas; ARect: TRect; AColor: TColor; var Handled: Boolean);
begin
if Assigned(FOnCustomDraw) then
begin
FOnCustomDraw(Self, AItemType, ACanvas, ARect, AColor, Handled);
end;
end;
procedure TclProgressBar.Paint();
var
state: TclResourceStateList;
begin
if not (csLoading in ComponentState)
and (Visible or (csDesigning in ComponentState))
and (Parent <> nil) and Parent.HandleAllocated then
begin
state := nil;
DoPaint(state);
if (state = nil) then
begin
state := GetLastState();
end;
Draw(state, Canvas, GetClientRect());
end;
end;
function TclProgressBar.GetLastState(): TclResourceStateList;
begin
Result := nil;
if (FNotifier <> nil) then
begin
Result := FNotifier.GetLastState();
end;
end;
procedure TclProgressBar.Notification(AComponent: TComponent; Operation: TOperation);
begin
if (AComponent = FInternetControl) and (Operation = opRemove) then
begin
InternetControl := nil;
end;
inherited Notification(AComponent, Operation);
end;
procedure TclProgressBar.ClearNotifier();
begin
FNotifier.Free();
FNotifier := nil;
end;
procedure TclProgressBar.SetInternetControl(const Value: TclCustomInternetControl);
begin
if (FInternetControl <> Value) then
begin
FInternetControl := Value;
ClearNotifier();
if (FInternetControl <> nil) then
begin
FInternetControl.FreeNotification(Self);
FNotifier := TclProgressBarNotifier.Create(FInternetControl, Self);
end;
end;
end;
procedure TclProgressBar.NotifyChanged;
begin
Paint();
Changed();
end;
procedure TclProgressBar.SetStyle(const Value: TclDrawStyle);
begin
if (FStyle <> Value) then
begin
FStyle := Value;
NotifyChanged();
end;
end;
procedure TclProgressBar.SetBorderStyle(const Value: TclBorderStyle);
begin
if (FBorderStyle <> Value) then
begin
FBorderStyle := Value;
NotifyChanged();
end;
end;
procedure TclProgressBar.DoPaint(var AState: TclResourceStateList);
begin
if Assigned(OnPaint) then
begin
OnPaint(Self, AState);
end;
end;
{ TclDrawColors }
procedure TclDrawColors.Assign(Source: TPersistent);
var
Src: TclDrawColors;
begin
if (Source is TclDrawColors) then
begin
Src := (Source as TclDrawColors);
FFrame := Src.Frame;
FBackGround := Src.BackGround;
FTotalColors.Assign(Src.TotalColors);
FItemColors.Assign(Src.ItemColors);
FScheme := Src.Scheme;
Changed();
end else
begin
inherited Assign(Source);
end;
end;
procedure TclDrawColors.Changed;
begin
if (FOwner <> nil) then
begin
FOwner.NotifyChanged();
end;
end;
constructor TclDrawColors.Create(AOwner: TclProgressBar);
begin
inherited Create();
FTotalColors := TclStatusColors.Create(Self);
FItemColors := TclStatusColors.Create(Self);
FOwner := AOwner;
FScheme := csScheme1;
SetColorsByScheme();
end;
procedure TclDrawColors.SetBackGround(const Value: TColor);
begin
if (FBackGround <> Value) then
begin
FBackGround := Value;
SetCustomScheme();
Changed();
end;
end;
procedure TclDrawColors.SetScheme(const Value: TclColorScheme);
begin
if (FScheme <> Value) and (Value <> csSchemeCustom) then
begin
FScheme := Value;
SetColorsByScheme();
Changed();
end;
end;
procedure TclDrawColors.SetColorsByScheme();
begin
FFrame := FrameColorSchemes[FScheme];
FBackGround := BackGroundColorSchemes[FScheme];
FItemColors.SetStatusColors(ItemColorSchemes[FScheme]);
FTotalColors.SetStatusColors(TotalColorSchemes[FScheme]);
end;
procedure TclDrawColors.SetFrame(const Value: TColor);
begin
if (FFrame <> Value) then
begin
FFrame := Value;
SetCustomScheme();
Changed();
end;
end;
procedure TclDrawColors.SetItemColors(const Value: TclStatusColors);
begin
FItemColors.Assign(Value);
SetCustomScheme();
end;
procedure TclDrawColors.SetTotalColors(const Value: TclStatusColors);
begin
FTotalColors.Assign(Value);
SetCustomScheme();
end;
destructor TclDrawColors.Destroy;
begin
FItemColors.Free();
FTotalColors.Free();
inherited Destroy();
end;
procedure TclDrawColors.SetCustomScheme;
begin
FScheme := csSchemeCustom;
end;
function TclDrawColors.ColorsStored(AColor1, AColor2: TclStatusColor): Boolean;
var
i: TclProcessStatus;
begin
for i := Low(TclStatusColor) to High(TclStatusColor) do
begin
Result := (AColor1[i] <> AColor2[i]);
if Result then Exit;
end;
Result := False;
end;
function TclDrawColors.ItemColorsStored: Boolean;
begin
Result := ColorsStored(ItemColors.GetStatusColors(), ItemColorSchemes[FScheme]);
end;
function TclDrawColors.TotalColorsStored: Boolean;
begin
Result := ColorsStored(TotalColors.GetStatusColors(), TotalColorSchemes[FScheme]);
end;
function TclDrawColors.BackGroundStored: Boolean;
begin
Result := (FBackGround <> BackGroundColorSchemes[FScheme]);
end;
function TclDrawColors.FrameStored: Boolean;
begin
Result := (FFrame <> FrameColorSchemes[FScheme]);
end;
{ TclProgressBarNotifier }
constructor TclProgressBarNotifier.Create(AControl: TclCustomInternetControl; AProgressBar: TclProgressBar);
begin
inherited Create(AControl);
FProgressBar := AProgressBar;
Assert(FProgressBar <> nil);
end;
procedure TclProgressBarNotifier.DoItemDeleted(Item: TclInternetItem);
begin
if (FLastItem = Item) then
begin
FLastItem := nil;
end;
inherited DoItemDeleted(Item);
end;
procedure TclProgressBarNotifier.DoResourceStateChanged(Item: TclInternetItem);
begin
FLastItem := Item;
FProgressBar.NotifyChanged();
end;
function TclProgressBarNotifier.GetLastState(): TclResourceStateList;
begin
Result := nil;
if (FLastItem <> nil) then
begin
Result := FLastItem.ResourceState;
end;
end;
{ TclStatusColors }
procedure TclStatusColors.Assign(Source: TPersistent);
begin
if (Source is TclStatusColors) then
begin
FStatusColor := (Source as TclStatusColors).GetStatusColors();
FOwner.Changed();
end else
begin
inherited Assign(Source);
end;
end;
constructor TclStatusColors.Create(AOwner: TclDrawColors);
begin
inherited Create();
FOwner := AOwner;
end;
function TclStatusColors.GetStatusColor(const Index: Integer): TColor;
begin
Result := FStatusColor[TclProcessStatus(Index)];
end;
function TclStatusColors.GetStatusColors: TclStatusColor;
begin
Result := FStatusColor;
end;
procedure TclStatusColors.SetStatusColors(AStatusColor: TclStatusColor);
begin
FStatusColor := AStatusColor;
end;
procedure TclStatusColors.SetStatusColor(const Index: Integer; const Value: TColor);
begin
if (FStatusColor[TclProcessStatus(Index)] <> Value) then
begin
FStatusColor[TclProcessStatus(Index)] := Value;
FOwner.SetCustomScheme();
FOwner.Changed();
end;
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: Controller do lado Cliente relacionado à tabela [EMPRESA]
The MIT License
Copyright: Copyright (C) 2010 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 1.0
*******************************************************************************}
unit EmpresaController;
{$MODE Delphi}
interface
uses
Classes, Dialogs, SysUtils, DB, LCLIntf, LCLType, LMessages, Forms, Controller,
EmpresaVO, VO, ZDataset;
type
TEmpresaController = class(TController)
private
public
class function Consulta(pFiltro: String; pPagina: String): TZQuery;
class function ConsultaObjeto(pFiltro: String): TEmpresaVO;
end;
implementation
uses UDataModule, T2TiORM, EmpresaEnderecoVO;
var
ObjetoLocal: TEmpresaVO;
class function TEmpresaController.Consulta(pFiltro: String; pPagina: String): TZQuery;
begin
try
ObjetoLocal := TEmpresaVO.Create;
Result := TT2TiORM.Consultar(ObjetoLocal, pFiltro, pPagina);
finally
ObjetoLocal.Free;
end;
end;
class function TEmpresaController.ConsultaObjeto(pFiltro: String): TEmpresaVO;
var
I: Integer;
begin
try
Result := TEmpresaVO.Create;
Result := TEmpresaVO(TT2TiORM.ConsultarUmObjeto(Result, pFiltro, True));
Filtro := 'ID_EMPRESA = ' + IntToStr(Result.Id);
// Objetos Vinculados
// Listas
Result.ListaEmpresaEnderecoVO := TListaEmpresaEnderecoVO(TT2TiORM.Consultar(TEmpresaEnderecoVO.Create, Filtro, True));
for I := 0 to Result.ListaEmpresaEnderecoVO.Count - 1 do
begin
if Result.ListaEmpresaEnderecoVO[I].Principal = 'S' then
begin
Result.EnderecoPrincipal := Result.ListaEmpresaEnderecoVO[I];
end;
end;
finally
end;
end;
initialization
Classes.RegisterClass(TEmpresaController);
finalization
Classes.UnRegisterClass(TEmpresaController);
end.
|
unit TestUPrecoGasController;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, DB, DBXJSON, UPrecoGasController, ConexaoBD, Generics.Collections,
UController, Classes, SysUtils, DBClient, UPrecoGasVO, DBXCommon, SQLExpr;
type
// Test methods for class TPrecoGasController
TestTPrecoGasController = class(TTestCase)
strict private
FPrecoGasController: TPrecoGasController;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestConsultarPorId;
end;
implementation
procedure TestTPrecoGasController.SetUp;
begin
FPrecoGasController := TPrecoGasController.Create;
end;
procedure TestTPrecoGasController.TearDown;
begin
FPrecoGasController.Free;
FPrecoGasController := nil;
end;
procedure TestTPrecoGasController.TestConsultarPorId;
var
ReturnValue: TPrecoGasVO;
// id: Integer;
begin
ReturnValue := FPrecoGasController.ConsultarPorId(1);
if(returnvalue <> nil) then
check(true,'Preço Gás pesquisado com sucesso!')
else
check(true,'Preço Gás não encontrado!');
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTPrecoGasController.Suite);
end.
|
unit StringUtils;
interface
function StrZero(number, width: Integer): string;
implementation
function StrZero(number, width: Integer): string;
begin
Str(number, Result);
while (Length(Result) < width) do
Insert('0', Result, 1);
end;
end.
|
unit Geo.Hash;
//------------------------------------------------------------------------------
// реализация гео-хэширования
//------------------------------------------------------------------------------
// набор фунций для гео-кодирования и декодирования
//
// подробное описания функций - перед ними
//
// ВАЖНО: все функции используют только общемировые ([-90;90],[-180;180]) координаты
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
interface
uses
SysUtils, StrUtils, Math,
Geo.Pos;
//------------------------------------------------------------------------------
type
TGeoHashValue = UInt32;//UInt64;
TGeoHashStringFormat = (gfPath, gfSpeed, gfTypeAndZone, gfType, gfZone, gfLandMark, gfPointsArray);
const
CGeoHashStringFormatInfoLen: array[TGeoHashStringFormat] of Integer = (0, 3, 18, 2, 16, 19, 0);
CGeoHashStringFormatInfoPref: array[TGeoHashStringFormat] of string = ('GW', 'SL', 'TZ', 'TL', 'ZZ', 'LM', 'PA');
type
TGeoPathPoint = record
p: TGeoPos; //point
s: Integer; //speed
t: Integer; //type
z: UInt64; //zone
f: UInt64; //feature
c: Boolean; //cross
end;
TGeoPathPointArray = TArray<TGeoPathPoint>;
//------------------------------------------------------------------------------
//! статический класс-инкапсулятор
//------------------------------------------------------------------------------
TGeoHash = class
public
//------------------------------------------------------------------------------
//! функция кодирования точки в бинарный гео-хэш
//------------------------------------------------------------------------------
class function EncodePointBin(
const ALat: Double;
const ALong: Double
): Int64;
//------------------------------------------------------------------------------
//! функция кодирования точки в строковый гео-хэш
//! APrec - кол-во символов
//! !!! APrec ДОЛЖНО БЫТЬ в интервале 1-12, ПРОВЕРКИ НЕТ !!!
//------------------------------------------------------------------------------
class function EncodePointString(
const ALat: Double;
const ALong: Double;
const APrec: Integer
): string; overload;
class function EncodePointString(
const APos: TGeoPos;
const APrec: Integer
): string; overload;
//------------------------------------------------------------------------------
//! функция конвертации бинарного гео-хэша в строковый
//! APrec - кол-во символов
//! !!! APrec ДОЛЖНО БЫТЬ в интервале 1-12, ПРОВЕРКИ НЕТ !!!
//------------------------------------------------------------------------------
class function ConvertBinToString(
const AHash: Int64;
const APrec: Integer
): string;
//------------------------------------------------------------------------------
//! функция конвертации строкового гео-хэша в бинарный
//! !!! длина строки ДОЛЖНА БЫТЬ в интервале 1-12, ПРОВЕРКИ НЕТ !!!
//------------------------------------------------------------------------------
class function ConvertStringToBin(
const AHash: string
): Int64;
//------------------------------------------------------------------------------
//! процедура декодирования бинарного гео-хэша в точку
//------------------------------------------------------------------------------
class procedure DecodePointBin(
const AHash: Int64;
var RLat: Double;
var RLong: Double
); overload;
//------------------------------------------------------------------------------
//! процедура декодирования бинарного гео-хэша в точку
//------------------------------------------------------------------------------
class function DecodePointBin(
const AHash: Int64
):TGeoPos; overload;
//------------------------------------------------------------------------------
//! функция декодирования строкового гео-хэша в точку
//! !!! кол-во символов в строке ДОЛЖНО БЫТЬ в интервале 1-12, ПРОВЕРКИ НЕТ !!!
//! return: true - если декодирование успешно; false - если нет
//------------------------------------------------------------------------------
class function DecodePointString(
const AHash: string;
var RLat: Double;
var RLong: Double
): Boolean; overload;
//------------------------------------------------------------------------------
//! функция декодирования строкового гео-хэша в точку
//! !!! кол-во символов в строке ДОЛЖНО БЫТЬ в интервале 1-12, ПРОВЕРКИ НЕТ !!!
//! return: TGeoPos
//------------------------------------------------------------------------------
class function DecodePointString(
const AHash: string
): TGeoPos; overload;
//------------------------------------------------------------------------------
//! функция кодирования массива точек в строку гео-хэша
//! !!! строка будет содержать префикс GW + один хэш = 12 символов !!!
//------------------------------------------------------------------------------
class function EncodeArrayWorld(
const ACoords: TGeoPosArray;
const AFormat: TGeoHashStringFormat = gfPath
): string;
//------------------------------------------------------------------------------
//! функция кодирования массива точек в строку гео-хэша
//! префикса нет
//------------------------------------------------------------------------------
class function EncodeArrayAny(
const ACoords: TGeoPosArray;
const APrec: Integer
): string;
//------------------------------------------------------------------------------
//! функция кодирования массива точек в строку гео-хэша
//! префикс и формат зависят от параметра AFormat
//------------------------------------------------------------------------------
class function EncodeArrayAnyFormat(
const ACoords: TGeoPathPointArray;
const APrec: Integer;
const AFormat: TGeoHashStringFormat
): string;
//------------------------------------------------------------------------------
//! функция декодирования строки гео-хэша в массив точек
//! !!! строка должна содержать префикс GW + один хэш = 12 символов !!!
//! return: true - если декодирование успешно; false - если нет
//------------------------------------------------------------------------------
class function DecodeArrayWorld(
const AHash: string;
var RCoords: TGeoPosArray
): Boolean;
//------------------------------------------------------------------------------
//! функция декодирования строки гео-хэша в массив точек
//! префикса нет
//! return: true - если декодирование успешно; false - если нет
//------------------------------------------------------------------------------
class function DecodeArrayAny(
const AHash: string;
const APrec: Integer;
var RCoords: TGeoPosArray
): Boolean;
class procedure GetAreaBoundingBox(out aBoundMin, aBoundMax: TGeoPos);
class function EncodePoint(const aPoint: TGeoPos; const aPrecision: Integer): TGeoHashValue; overload;
class function EncodePoint(const aLatitude, aLongitude: Double; const aPrecision: Integer): TGeoHashValue; overload;
class function EncodePoint(const aPoint, aBoundMin, aBoundMax: TGeoPos; const aPrecision: Integer): TGeoHashValue; overload;
class function DecodePoint(
const aHash: TGeoHashValue; const aBoundMin, aBoundMax: TGeoPos;
const aPrecision: Integer; var aPoint, aPointBoundMin, aPointBoundMax: TGeoPos): Boolean; overload;
class function DecodePoint(const aHash: TGeoHashValue; var aCoords: TGeoPos; const aPrecision: Integer): Boolean; overload;
// > 0 - слева, < 0 - справа, = 0 - на векторе
class function PosPointFromVector(APointVector, BPointVector, CPoint: TGeoPos): integer; //overload;
class function GeoHashStringFormat(const AFormat: Integer): TGeoHashStringFormat;
end;
//------------------------------------------------------------------------------
implementation
const
//------------------------------------------------------------------------------
//! массив конвертации букв в номера
//------------------------------------------------------------------------------
CHashFromLetters: array[48..122] of Integer = (
0, 1, 2, 3, 4, 5, 6, 7, // 30-37, '0'..'7'
8, 9, -1, -1, -1, -1, -1, -1, // 38-3F, '8','9'
-1, -1, 10, 11, 12, 13, 14, 15, // 40-47, 'B'..'G'
16, -1, 17, 18, -1, 19, 20, -1, // 48-4F, 'H','J','K','M','N'
21, 22, 23, 24, 25, 26, 27, 28, // 50-57, 'P'..'W'
29, 30, 31, -1, -1, -1, -1, -1, // 58-5F, 'X'..'Z'
-1, -1, 10, 11, 12, 13, 14, 15, // 60-67, 'b'..'g'
16, -1, 17, 18, -1, 19, 20, -1, // 68-6F, 'h','j','k','m','n'
21, 22, 23, 24, 25, 26, 27, 28, // 70-77, 'p'..'w'
29, 30, 31 // 78-7A, 'x'..'z'
);
//------------------------------------------------------------------------------
//! массив конвертации номеров в буквы
//------------------------------------------------------------------------------
CHashToLetters: array[0..31] of Char = (
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
);
//------------------------------------------------------------------------------
//! конвертируем букву в номер
//------------------------------------------------------------------------------
function Letter2Num(
const ALetter: Char
): Integer;
begin
if (Ord(ALetter) < Low(CHashFromLetters)) or (Ord(ALetter) > High(CHashFromLetters)) then
Result := -1
else
Result := CHashFromLetters[Ord(ALetter)];
end;
//------------------------------------------------------------------------------
//! TGeoHash
//------------------------------------------------------------------------------
class function TGeoHash.EncodePointBin(
const ALat: Double;
const ALong: Double
): Int64;
var
//!
WorkBoundMin, WorkBoundMax: TGeoPos;
//!
LatiMid, LongiMid: Double;
//!
I: Integer;
//------------------------------------------------------------------------------
begin
WorkBoundMin.Latitude := -90;
WorkBoundMin.Longitude := -180;
WorkBoundMax.Latitude := 90;
WorkBoundMax.Longitude := 180;
Result := 0;
for I := 59 downto 0 do
begin
Result := Result shl 1;
if Odd(I) then
begin
LongiMid := (WorkBoundMin.Longitude + WorkBoundMax.Longitude) * 0.5;
if (ALong >= LongiMid) then
begin
Inc(Result);
WorkBoundMin.Longitude := LongiMid;
end
else
WorkBoundMax.Longitude := LongiMid;
end
else
begin
LatiMid := (WorkBoundMin.Latitude + WorkBoundMax.Latitude) * 0.5;
if (ALat >= LatiMid) then
begin
Inc(Result);
WorkBoundMin.Latitude := LatiMid;
end
else
WorkBoundMax.Latitude := LatiMid;
end;
end;
end;
class function TGeoHash.EncodePointString(
const ALat: Double;
const ALong: Double;
const APrec: Integer
): string;
begin
Result := ConvertBinToString(EncodePointBin(ALat, ALong), APrec);
end;
class function TGeoHash.EncodePointString(
const APos: TGeoPos;
const APrec: Integer
): string;
begin
Result := EncodePointString(APos.Latitude, APos.Longitude, APrec);
end;
class function TGeoHash.ConvertBinToString(
const AHash: Int64;
const APrec: Integer
): string;
var
//!
Temp64: Int64;
//!
I: Integer;
//!
Rez: array[0..12] of Char;
//------------------------------------------------------------------------------
begin
FillChar(Rez, SizeOf(Rez), 0);
Temp64 := AHash shr ((12 - APrec) * 5);
for I := APrec - 1 downto 0 do
begin
Rez[I] := CHashToLetters[Temp64 and $1f];
Temp64 := Temp64 shr 5;
end;
Result := string(Rez);
end;
class function TGeoHash.ConvertStringToBin(
const AHash: string
): Int64;
var
//!
C: Char;
//!
CRep: Integer;
//------------------------------------------------------------------------------
begin
Result := 0;
for C in AHash do
begin
CRep := Letter2Num(C);
if (CRep = -1) then
Exit(0);
Result := Result shl 5;
Result := Result + CRep;
end;
Result := Result shl ((12 - Length(AHash)) * 5);
end;
class procedure TGeoHash.DecodePointBin(
const AHash: Int64;
var RLat: Double;
var RLong: Double
);
var
//!
WorkHash: Int64;
//!
WorkBoundMin, WorkBoundMax: TGeoPos;
//!
LatiMid, LongiMid: Double;
//!
I: Integer;
//------------------------------------------------------------------------------
begin
WorkHash := AHash shl 4;
WorkBoundMin.Latitude := -90;
WorkBoundMin.Longitude := -180;
WorkBoundMax.Latitude := 90;
WorkBoundMax.Longitude := 180;
for I := 59 downto 0 do
begin
if Odd(I) then
begin
LongiMid := (WorkBoundMin.Longitude + WorkBoundMax.Longitude) * 0.5;
if (WorkHash < 0) then
WorkBoundMin.Longitude := LongiMid
else
WorkBoundMax.Longitude := LongiMid;
end
else
begin
LatiMid := (WorkBoundMin.Latitude + WorkBoundMax.Latitude) * 0.5;
if (WorkHash < 0) then
WorkBoundMin.Latitude := LatiMid
else
WorkBoundMax.Latitude := LatiMid;
end;
WorkHash := WorkHash shl 1;
end;
RLat := (WorkBoundMin.Latitude + WorkBoundMax.Latitude) * 0.5;
RLong := (WorkBoundMin.Longitude + WorkBoundMax.Longitude) * 0.5;
end;
class function TGeoHash.DecodePointBin(
const AHash: Int64
):TGeoPos;
begin
DecodePointBin(AHash, Result.Latitude, Result.Longitude);
end;
class function TGeoHash.DecodePointString(
const AHash: string;
var RLat: Double;
var RLong: Double
): Boolean;
var
//!
WorkBoundMin, WorkBoundMax: TGeoPos;
//!
LatiMid, LongiMid: Double;
//!
BinHash: Integer;
//!
BitPos: Integer;
//!
EvenBit: Boolean;
//!
I: Integer;
//------------------------------------------------------------------------------
begin
Result := False;
WorkBoundMin.Latitude := -90;
WorkBoundMin.Longitude := -180;
WorkBoundMax.Latitude := 90;
WorkBoundMax.Longitude := 180;
EvenBit := False;
for I := 1 to Length(AHash) do
begin
BinHash := Letter2Num(AHash[I]);
if (BinHash = -1) then Exit;
for BitPos := 4 downto 0 do
begin
EvenBit := not EvenBit;
if EvenBit then
begin
LongiMid := (WorkBoundMin.Longitude + WorkBoundMax.Longitude) * 0.5;
if Odd(BinHash shr BitPos) then
WorkBoundMin.Longitude := LongiMid
else
WorkBoundMax.Longitude := LongiMid;
end
else
begin
LatiMid := (WorkBoundMin.Latitude + WorkBoundMax.Latitude) * 0.5;
if Odd(BinHash shr BitPos) then
WorkBoundMin.Latitude := LatiMid
else
WorkBoundMax.Latitude := LatiMid;
end;
end;
end;
RLat := (WorkBoundMin.Latitude + WorkBoundMax.Latitude) * 0.5;
RLong := (WorkBoundMin.Longitude + WorkBoundMax.Longitude) * 0.5;
Result := True;
end;
class function TGeoHash.DecodePointString(
const AHash: string
): TGeoPos;
begin
DecodePointString(AHash, Result.Latitude, Result.Longitude);
end;
class function TGeoHash.EncodeArrayWorld(
const ACoords: TGeoPosArray;
const AFormat: TGeoHashStringFormat
): string;
var
//!
TempStr: string;
//!
MoveFrom, MoveTo: Pointer;
//!
I: Integer;
APrefix: string;
//------------------------------------------------------------------------------
begin
APrefix := CGeoHashStringFormatInfoPref[AFormat];
Result := '';
if Length(ACoords) = 0 then
Exit;
Result := APrefix;
SetLength(Result, Length(ACoords) * 12 + 2);
for I := Low(ACoords) to High(ACoords) do
begin
TempStr := EncodePointString(ACoords[I].Latitude, ACoords[I].Longitude, 12);
MoveFrom := @(TempStr[1]);
MoveTo := @(Result[I * 12 + 3]);
Move(MoveFrom^, MoveTo^, 12 * SizeOf(Char));
end;
end;
class function TGeoHash.EncodeArrayAny(
const ACoords: TGeoPosArray;
const APrec: Integer
): string;
var
//!
TempStr: string;
//!
MoveFrom, MoveTo: Pointer;
//!
I: Integer;
//------------------------------------------------------------------------------
begin
SetLength(Result, Length(ACoords) * APrec);
for I := Low(ACoords) to High(ACoords) do
begin
TempStr := EncodePointString(ACoords[I].Latitude, ACoords[I].Longitude, APrec);
MoveFrom := @(TempStr[1]);
MoveTo := @(Result[I * APrec + 1]);
Move(MoveFrom^, MoveTo^, APrec * SizeOf(Char));
end;
end;
class function TGeoHash.EncodeArrayAnyFormat(const ACoords: TGeoPathPointArray;
const APrec: Integer; const AFormat: TGeoHashStringFormat): string;
var
//!
TempStr: string;
//!
MoveFrom, MoveTo: Pointer;
//!
I: Integer;
//!
PrefixLen: Integer;
PointLen: Integer;
AltInfoLen: Integer;
AltInfo: string;
//------------------------------------------------------------------------------
begin
case AFormat of
gfPath: begin
Result := 'GW';
AltInfoLen := CGeoHashStringFormatInfoLen[AFormat];//0;
PointLen := APrec + AltInfoLen;
end;
gfSpeed: begin
Result := 'SL';
AltInfoLen := CGeoHashStringFormatInfoLen[AFormat];//3; //speed = 000
PointLen := APrec + AltInfoLen;
end;
gfType: begin
Result := 'TL';
AltInfoLen := CGeoHashStringFormatInfoLen[AFormat];//2; //speed = 000
PointLen := APrec + AltInfoLen;
end;
gfZone: begin
Result := 'ZZ';
AltInfoLen := CGeoHashStringFormatInfoLen[AFormat];//16; //zone = 0000000000000000
PointLen := APrec + AltInfoLen;
end;
gfTypeAndZone: begin
Result := 'TZ';
AltInfoLen := CGeoHashStringFormatInfoLen[AFormat];//2 + 16; //type = 00, zone=0000000000000000
PointLen := APrec + AltInfoLen;
end;
gfLandMark: begin
Result := 'LM';
AltInfoLen := CGeoHashStringFormatInfoLen[AFormat];//1+2+16; //1 = landmark, type = 00, zone=0000000000000000
PointLen := APrec + AltInfoLen;
end;
else begin
Result := 'GW';
AltInfoLen := 0;
PointLen := APrec + AltInfoLen;
end;
end;
PrefixLen := Length(Result);
SetLength(Result, Length(ACoords) * PointLen - AltInfoLen + PrefixLen);
for I := Low(ACoords) to High(ACoords) do
begin
AltInfo := '';
if I > Low(ACoords) then
case AFormat of
gfSpeed: AltInfo := Format('%.3d', [ACoords[I].s]);
gfType: AltInfo := Format('%.2d', [ACoords[I].t]);
gfZone: AltInfo := IntToHex(ACoords[I].z, 16);
gfTypeAndZone: AltInfo := IntToHex(ACoords[I].t, 2) + IntToHex(ACoords[I].z, 16); //2 - type, 16 - zone
gfLandMark: AltInfo := IfThen(ACoords[I].c, 'Z', 'N') + IntToHex(ACoords[I].t, 2) + IntToHex(ACoords[I].z, 16); //1 - landmark, 2 - type, 16 - zone
end;
TempStr := AltInfo + EncodePointString(ACoords[I].p.Latitude, ACoords[I].p.Longitude, APrec);
MoveFrom := @(TempStr[1]);
MoveTo := @(Result[IfThen(I=0, 0, (I-1)*PointLen+APrec) + PrefixLen + 1]);
// MoveTo := @(Result[I * PointLen + PrefixLen + 1]);
Move(MoveFrom^, MoveTo^, IfThen(I=0, APrec, PointLen) * SizeOf(Char));
end;
end;
class function TGeoHash.DecodeArrayWorld(
const AHash: string;
var RCoords: TGeoPosArray
): Boolean;
var
WorkStr: string;
HashType: string;
InfoLen: integer;
I: Integer;
SFormat: TGeoHashStringFormat;
//------------------------------------------------------------------------------
begin
SetLength(RCoords, 0);
if (Length(AHash) = 2) then Exit(True);
Result := False;
if (Length(AHash) < 2) then Exit;
HashType := copy(AHash, 1, 2);
InfoLen := 0;
for SFormat := Low(CGeoHashStringFormatInfoPref) to High(CGeoHashStringFormatInfoPref) do
if HashType = CGeoHashStringFormatInfoPref[SFormat] then
InfoLen := 12 + CGeoHashStringFormatInfoLen[SFormat];
if InfoLen = 0 then Exit;
if (((Length(AHash) - 2 - 12) mod InfoLen) <> 0) then Exit;
WorkStr := Copy(AHash, 3, MaxInt);
SetLength(RCoords, ((Length(WorkStr)-12) div InfoLen)+1);
for I := Low(RCoords) to High(RCoords) do
begin
if not DecodePointString(
Copy(WorkStr, I * InfoLen + 1, 12),
RCoords[I].Latitude,
RCoords[I].Longitude
) then Exit;
end;
Result := True;
end;
class function TGeoHash.DecodeArrayAny(
const AHash: string;
const APrec: Integer;
var RCoords: TGeoPosArray
): Boolean;
var
//!
I: Integer;
//------------------------------------------------------------------------------
begin
SetLength(RCoords, 0);
Result := False;
if ((APrec < 1) or (APrec > 12)) then Exit;
if ((Length(AHash) mod APrec) <> 0) then Exit;
SetLength(RCoords, (Length(AHash) div APrec));
for I := Low(RCoords) to High(RCoords) do
begin
if not DecodePointString(
Copy(AHash, (I + 1) * APrec, APrec),
RCoords[I].Latitude,
RCoords[I].Longitude
) then Exit;
end;
Result := True;
end;
class function TGeoHash.EncodePoint(const aPoint, aBoundMin, aBoundMax: TGeoPos; const aPrecision: Integer): TGeoHashValue;
var
WorkBoundMin, WorkBoundMax: TGeoPos;
LatiMid, LongiMid: Double;
i: Integer;
EvenBit: Boolean;
begin
WorkBoundMin := aBoundMin;
WorkBoundMax := aBoundMax;
Result := 0;
EvenBit := False;
i := 0;
while (i < aPrecision) do
begin
Result := Result shl 1;
EvenBit := not EvenBit;
if EvenBit then
begin
LongiMid := (WorkBoundMin.Longitude + WorkBoundMax.Longitude) * 0.5;
if (aPoint.Longitude >= LongiMid) then
begin
Inc(Result);
WorkBoundMin.Longitude := LongiMid;
end
else
WorkBoundMax.Longitude := LongiMid;
end
else
begin
LatiMid := (WorkBoundMin.Latitude + WorkBoundMax.Latitude) * 0.5;
if (aPoint.Latitude >= LatiMid) then
begin
Inc(Result);
WorkBoundMin.Latitude := LatiMid;
end
else
WorkBoundMax.Latitude := LatiMid;
end;
Inc(i);
end;
end;
class function TGeoHash.EncodePoint(const aPoint: TGeoPos; const aPrecision: Integer): TGeoHashValue;
var
BoundMin, BoundMax: TGeoPos;
begin
GetAreaBoundingBox(BoundMin, BoundMax);
Result := EncodePoint(aPoint, BoundMin, BoundMax, aPrecision);
end;
class function TGeoHash.EncodePoint(const aLatitude, aLongitude: Double; const aPrecision: Integer): TGeoHashValue;
begin
Result := EncodePoint(TGeoPos.Create(aLatitude, aLongitude), aPrecision);
end;
class function TGeoHash.DecodePoint(const aHash: TGeoHashValue;
var aCoords: TGeoPos; const aPrecision: Integer): Boolean;
var
BoundMin, BoundMax: TGeoPos;
PointBoundMin, PointBoundMax: TGeoPos;
begin
GetAreaBoundingBox(BoundMin, BoundMax);
Result := DecodePoint(aHash, BoundMin, BoundMax, aPrecision, aCoords, PointBoundMin, PointBoundMax);
end;
class function TGeoHash.DecodePoint(const aHash: TGeoHashValue; const aBoundMin,
aBoundMax: TGeoPos; const aPrecision: Integer; var aPoint, aPointBoundMin,
aPointBoundMax: TGeoPos): Boolean;
var
LatiMid, LongiMid: Double;
BitPos: Integer;
BitX: Integer;
EvenBit: Boolean;
begin
aPointBoundMin := aBoundMin;
aPointBoundMax := aBoundMax;
EvenBit := False;
for BitPos := aPrecision - 1 downto 0 do
begin
BitX := (aHash shr BitPos) and 1;
EvenBit := not EvenBit;
if EvenBit then
begin
LongiMid := (aPointBoundMin.Longitude + aPointBoundMax.Longitude) * 0.5;
if BitX <> 0 then
aPointBoundMin.Longitude := LongiMid
else
aPointBoundMax.Longitude := LongiMid;
end
else
begin
LatiMid := (aPointBoundMin.Latitude + aPointBoundMax.Latitude) * 0.5;
if BitX <> 0 then
aPointBoundMin.Latitude := LatiMid
else
aPointBoundMax.Latitude := LatiMid;
end;
end;
aPoint.Latitude := ( aPointBoundMin.Latitude + aPointBoundMax.Latitude ) * 0.5;
aPoint.Longitude := ( aPointBoundMin.Longitude + aPointBoundMax.Longitude ) * 0.5;
Result := True;
end;
class function TGeoHash.PosPointFromVector(APointVector, BPointVector, CPoint: TGeoPos): integer;
var
s: Double;
begin
s := (BPointVector.Longitude - APointVector.Longitude) *
(CPoint.Latitude - APointVector.Latitude) -
(BPointVector.Latitude - APointVector.Latitude) *
(CPoint.Longitude - APointVector.Longitude);
{
aLinesSort.Estimation := (P1.Longitude - pRight.Point.Longitude) *
(pCenter.Point.Latitude - pRight.Point.Latitude) -
(P1.Latitude - pRight.Point.Latitude) *
(pCenter.Point.Longitude - pRight.Point.Longitude);
}
if s > 0 then
Result := 1
else
if s < 0 then
Result := -1
else
Result := 0;
end;
class function TGeoHash.GeoHashStringFormat(
const AFormat: Integer): TGeoHashStringFormat;
begin
Result := gfPath;
if (AFormat >= Ord(Low(TGeoHashStringFormat))) and (AFormat <= Ord(High(TGeoHashStringFormat))) then
Result := TGeoHashStringFormat(AFormat);
end;
class procedure TGeoHash.GetAreaBoundingBox(out aBoundMin, aBoundMax: TGeoPos);
begin
{ aBoundMin := TGeoPos.Create(-90, -180);
aBoundMax := TGeoPos.Create(90, 180);}
aBoundMin.Latitude := -90;
aBoundMin.Longitude := -180;
aBoundMax.Latitude := 90;
aBoundMax.Longitude := 180;
end;
end.
|
unit uFormNewShtat;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, uFloatControl, uDateControl, uFControl,
uLabeledFControl, uCharControl, uFormControl, uInvisControl, uLogicCheck;
type
TfmFormNewShtat = class(TForm)
OkButton: TBitBtn;
CancelButton: TBitBtn;
qFCharControl1: TqFCharControl;
Date_Beg: TqFDateControl;
Date_End: TqFDateControl;
Inc_Percent: TqFFloatControl;
Label1: TLabel;
FormControl: TqFFormControl;
OLD_SR: TqFInvisControl;
qFLogicCheck1: TqFLogicCheck;
procedure FormControlNewRecordAfterPrepare(Sender: TObject);
procedure OkButtonClick(Sender: TObject);
procedure qFLogicCheck1Check(Sender: TObject; var Error: String);
private
{ Private declarations }
public
{ Public declarations }
end;
var
fmFormNewShtat: TfmFormNewShtat;
implementation
{$R *.dfm}
uses DateUtils, qFTools;
procedure TfmFormNewShtat.FormControlNewRecordAfterPrepare(
Sender: TObject);
begin
Date_Beg.Value := EncodeDate(YearOf(Date), 1, 1);
Date_End.Value := EncodeDate(YearOf(Date), 12, 31);
Inc_Percent.Value := 0;
end;
procedure TfmFormNewShtat.OkButtonClick(Sender: TObject);
begin
FormControl.Ok;
end;
procedure TfmFormNewShtat.qFLogicCheck1Check(Sender: TObject;
var Error: String);
begin
if qFConfirm('Справді бажаєте створити новий документ ШР?') then
Error := ''
else Error := 'Відмінено користувачем!';
end;
end.
|
// ----------- Parse::Easy::Runtime -----------
// https://github.com/MahdiSafsafi/Parse-Easy
// --------------------------------------------
unit Parse.Easy.Parser.Action;
interface
uses
System.Classes,
System.SysUtils;
type
TActionType = (atUnkown,atShift, atReduce, atJump);
TAction = class(TObject)
private
FType: TActionType;
FValue: Integer;
public
constructor Create(AType: TActionType; AValue: Integer); virtual;
property ActionType: TActionType read FType;
property ActionValue: Integer read FValue;
end;
implementation
{ TAction }
constructor TAction.Create(AType: TActionType; AValue: Integer);
begin
FType := AType;
FValue := AValue;
end;
end.
|
{***********************************************
* *
* *
* 这个模块是用来获取CPU、硬盘序列号,CPU的*
* *
* 速率、显示器的刷新率网卡的MAC地址等信息 *
* *
* *
* 2005.03.18 祝云飞 *
*************************************************}
unit HardInfo;
interface
uses
Windows, SysUtils, Nb30, MSI_CPU, MSI_Storage;
const
ID_BIT = $200000; // EFLAGS ID bit
type
TCPUID = array[1..4] of Longint;
TVendor = array[0..11] of char;
function IsCPUID_Available: Boolean; register; //判断CPU序列号是否可用函数
function GetCPUID: TCPUID; assembler; register; //获取CPU序列号函数
function GetCPUVendor: TVendor; assembler; register; //获取CPU生产厂家函数
function GetCPUInfo: string; //CPU序列号(格式化成字符串)
function GetCPUSpeed: Double; //获取CPU速度函数
function GetDisplayFrequency: Integer; //获取显示器刷新率
function GetScsisn: string; //获取IDE硬盘序列号函数
function MonthMaxDay(year, month: Integer): Integer; //获取某年某月的最大天数
function GetAdapterMac(ANo: Integer): string;
function MacAddress: string;//网卡Mac地址 20080703
function GetCPUInfo_: string;
function GetDiskSerialNumber: string;
implementation
//网卡Mac地址
function MacAddress: string;
var
Lib: Cardinal;
Func: function(GUID: PGUID): Longint; stdcall;
GUID1, GUID2: TGUID;
begin
Result := '';
Lib := LoadLibrary('rpcrt4.dll');
if Lib <> 0 then
begin
if Win32Platform <>VER_PLATFORM_WIN32_NT then
@Func := GetProcAddress(Lib, 'UuidCreate')
else @Func := GetProcAddress(Lib, 'UuidCreateSequential');
if Assigned(Func) then
begin
if (Func(@GUID1) = 0) and
(Func(@GUID2) = 0) and
(GUID1.D4[2] = GUID2.D4[2]) and
(GUID1.D4[3] = GUID2.D4[3]) and
(GUID1.D4[4] = GUID2.D4[4]) and
(GUID1.D4[5] = GUID2.D4[5]) and
(GUID1.D4[6] = GUID2.D4[6]) and
(GUID1.D4[7] = GUID2.D4[7]) then
begin
Result :=
IntToHex(GUID1.D4[2], 2) + '-' +
IntToHex(GUID1.D4[3], 2) + '-' +
IntToHex(GUID1.D4[4], 2) + '-' +
IntToHex(GUID1.D4[5], 2) + '-' +
IntToHex(GUID1.D4[6], 2) + '-' +
IntToHex(GUID1.D4[7], 2);
end;
end;
FreeLibrary(Lib);
end;
end;
function GetDiskSerialNumber: string;
var
Storage: TStorage;
begin
Result := '';
Storage := TStorage.Create;
Storage.GetInfo;
if Storage.DeviceCount > 0 then begin
Result := Storage.Devices[0].SerialNumber;
end;
Storage.Free;
end;
function GetCPUInfo_: string;
var
CPU: TCPU;
begin
CPU := TCPU.Create;
CPU.GetInfo();
Result := CPU.SerialNumber;
CPU.Free;
end;
function IsCPUID_Available: Boolean; register;
asm
PUSHFD {direct access to flags no possible, only via stack}
POP EAX {flags to EAX}
MOV EDX,EAX {save current flags}
XOR EAX,ID_BIT {not ID bit}
PUSH EAX {onto stack}
POPFD {from stack to flags, with not ID bit}
PUSHFD {back to stack}
POP EAX {get back to EAX}
XOR EAX,EDX {check if ID bit affected}
JZ @exit {no, CPUID not availavle}
MOV AL,True {Result=True}
@exit:
end;
function GetCPUID: TCPUID; assembler; register;
asm
PUSH EBX {Save affected register}
PUSH EDI
MOV EDI,EAX {@Resukt}
MOV EAX,1
DW $A20F {CPUID Command}
STOSD {CPUID[1]}
MOV EAX,EBX
STOSD {CPUID[2]}
MOV EAX,ECX
STOSD {CPUID[3]}
MOV EAX,EDX
STOSD {CPUID[4]}
POP EDI {Restore registers}
POP EBX
end;
function GetCPUVendor: TVendor; assembler; register;
//获取CPU生产厂家函数
//调用方法:EDIT.TEXT:='Current CPU Vendor:'+GetCPUVendor;
asm
PUSH EBX {Save affected register}
PUSH EDI
MOV EDI,EAX {@Result (TVendor)}
MOV EAX,0
DW $A20F {CPUID Command}
MOV EAX,EBX
XCHG EBX,ECX {save ECX result}
MOV ECX,4
@1:
STOSB
SHR EAX,8
LOOP @1
MOV EAX,EDX
MOV ECX,4
@2:
STOSB
SHR EAX,8
LOOP @2
MOV EAX,EBX
MOV ECX,4
@3:
STOSB
SHR EAX,8
LOOP @3
POP EDI {Restore registers}
POP EBX
end;
function GetCPUInfo: string;
var
CPUID: TCPUID;
I: Integer;
S: TVendor;
begin
for I := Low(CPUID) to High(CPUID) do CPUID[I] := -1;
if IsCPUID_Available then begin
CPUID := GetCPUID;
S := GetCPUVendor;
Result := IntToHex(CPUID[1], 8)
+ '-' + IntToHex(CPUID[2], 8)
+ '-' + IntToHex(CPUID[3], 8)
+ '-' + IntToHex(CPUID[4], 8);
end
else Result := 'CPUID not available';
end;
function GetCPUSpeed: Double;
//获取CPU速率函数
//调用方法:EDIT.TEXT:='Current CPU Speed:'+floattostr(GetCPUSpeed)+'MHz';
const
DelayTime = 500; // 时间单位是毫秒
var
TimerHi, TimerLo: DWORD;
PriorityClass, Priority: Integer;
begin
PriorityClass := GetPriorityClass(GetCurrentProcess);
Priority := GetThreadPriority(GetCurrentThread);
SetPriorityClass(GetCurrentProcess, REALTIME_PRIORITY_CLASS);
SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_TIME_CRITICAL);
Sleep(10);
asm
dw 310Fh // rdtsc
mov TimerLo, eax
mov TimerHi, edx
end;
Sleep(DelayTime);
asm
dw 310Fh // rdtsc
sub eax, TimerLo
sbb edx, TimerHi
mov TimerLo, eax
mov TimerHi, edx
end;
SetThreadPriority(GetCurrentThread, Priority);
SetPriorityClass(GetCurrentProcess, PriorityClass);
Result := TimerLo / (1000.0 * DelayTime);
end;
function GetDisplayFrequency: Integer;
// 这个函数返回的显示刷新率是以Hz为单位的
//调用方法:EDIT.TEXT:='Current DisplayFrequency:'+inttostr(GetDisplayFrequency)+' Hz';
var
DeviceMode: TDeviceMode;
begin
EnumDisplaySettings(nil, Cardinal(-1), DeviceMode);
Result := DeviceMode.dmDisplayFrequency;
end;
//你给我加分吧,下面是我用于测硬盘序列号的,可以对付IDE / SCSI的。
//用getscsisn既可得到硬盘序列号
function GetIdeDiskSerialNumber: pchar;
//获取第一个IDE硬盘的序列号
//调用方法:EDIT.TEXT:='HardDriver SerialNumber:'+strpas(GetIdeSerialNumber);
const IDENTIFY_BUFFER_SIZE = 512;
type
TIDERegs = packed record
bFeaturesReg: BYTE; // Used for specifying SMART "commands".
bSectorCountReg: BYTE; // IDE sector count register
bSectorNumberReg: BYTE; // IDE sector number register
bCylLowReg: BYTE; // IDE low order cylinder value
bCylHighReg: BYTE; // IDE high order cylinder value
bDriveHeadReg: BYTE; // IDE drive/head register
bCommandReg: BYTE; // Actual IDE command.
bReserved: BYTE; // reserved for future use. Must be zero.
end;
TSendCmdInParams = packed record
// Buffer size in bytes
cBufferSize: DWORD;
// Structure with drive register values.
irDriveRegs: TIDERegs;
// Physical drive number to send command to (0,1,2,3).
bDriveNumber: BYTE;
bReserved: array[0..2] of BYTE;
dwReserved: array[0..3] of DWORD;
bBuffer: array[0..0] of BYTE; // Input buffer.
end;
TIdSector = packed record
wGenConfig: Word;
wNumCyls: Word;
wReserved: Word;
wNumHeads: Word;
wBytesPerTrack: Word;
wBytesPerSector: Word;
wSectorsPerTrack: Word;
wVendorUnique: array[0..2] of Word;
sSerialNumber: array[0..19] of char;
wBufferType: Word;
wBufferSize: Word;
wECCSize: Word;
sFirmwareRev: array[0..7] of char;
sModelNumber: array[0..39] of char;
wMoreVendorUnique: Word;
wDoubleWordIO: Word;
wCapabilities: Word;
wReserved1: Word;
wPIOTiming: Word;
wDMATiming: Word;
wBS: Word;
wNumCurrentCyls: Word;
wNumCurrentHeads: Word;
wNumCurrentSectorsPerTrack: Word;
ulCurrentSectorCapacity: DWORD;
wMultSectorStuff: Word;
ulTotalAddressableSectors: DWORD;
wSingleWordDMA: Word;
wMultiWordDMA: Word;
bReserved: array[0..127] of BYTE;
end;
PIdSector = ^TIdSector;
TDriverStatus = packed record
// 驱动器返回的错误代码,无错则返回0
bDriverError: BYTE;
// IDE出错寄存器的内容,只有当bDriverError 为 SMART_IDE_ERROR 时有效
bIDEStatus: BYTE;
bReserved: array[0..1] of BYTE;
dwReserved: array[0..1] of DWORD;
end;
TSendCmdOutParams = packed record
// bBuffer的大小
cBufferSize: DWORD;
// 驱动器状态
DriverStatus: TDriverStatus;
// 用于保存从驱动器读出的数据的缓冲区,实际长度由cBufferSize决定
bBuffer: array[0..0] of BYTE;
end;
var hDevice: THandle;
cbBytesReturned: DWORD;
SCIP: TSendCmdInParams;
aIdOutCmd: array[0..(SizeOf(TSendCmdOutParams) + IDENTIFY_BUFFER_SIZE - 1) - 1] of BYTE;
IdOutCmd: TSendCmdOutParams absolute aIdOutCmd;
procedure ChangeByteOrder(var Data; Size: Integer);
var ptr: pchar;
I: Integer;
c: char;
begin
ptr := @Data;
for I := 0 to (Size shr 1) - 1 do begin
c := ptr^;
ptr^ := (ptr + 1)^;
(ptr + 1)^ := c;
Inc(ptr, 2);
end;
end;
begin
Result := ''; // 如果出错则返回空串
try
if SysUtils.Win32Platform = VER_PLATFORM_WIN32_NT then begin // Windows NT, Windows 2000
// 提示! 改变名称可适用于其它驱动器,如第二个驱动器: '\\.\PhysicalDrive1\'
hDevice := CreateFile('\\.\PhysicalDrive0', GENERIC_READ or GENERIC_WRITE,
FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, 0, 0);
end else // Version Windows 95 OSR2, Windows 98
hDevice := CreateFile('\\.\SMARTVSD', 0, 0, nil, CREATE_NEW, 0, 0);
if hDevice = INVALID_HANDLE_VALUE then Exit;
try
FillChar(SCIP, SizeOf(TSendCmdInParams) - 1, #0);
FillChar(aIdOutCmd, SizeOf(aIdOutCmd), #0);
cbBytesReturned := 0;
// Set up data structures for IDENTIFY command.
with SCIP do begin
cBufferSize := IDENTIFY_BUFFER_SIZE;
// bDriveNumber := 0;
with irDriveRegs do begin
bSectorCountReg := 1;
bSectorNumberReg := 1;
// if Win32Platform=VER_PLATFORM_WIN32_NT then bDriveHeadReg := $A0
// else bDriveHeadReg := $A0 or ((bDriveNum and 1) shl 4);
bDriveHeadReg := $A0;
bCommandReg := $EC;
end;
end;
if not DeviceIoControl(hDevice, $0007C088, @SCIP, SizeOf(TSendCmdInParams) - 1,
@aIdOutCmd, SizeOf(aIdOutCmd), cbBytesReturned, nil) then Exit;
finally
CloseHandle(hDevice);
end;
with PIdSector(@IdOutCmd.bBuffer)^ do begin
ChangeByteOrder(sSerialNumber, SizeOf(sSerialNumber));
(pchar(@sSerialNumber) + SizeOf(sSerialNumber))^ := #0;
Result := pchar(@sSerialNumber);
end;
except
end;
// 更多关于 S.M.A.R.T. ioctl 的信息可查看:
// http://www.microsoft.com/hwdev/download/respec/iocltapi.rtf
// MSDN库中也有一些简单的例子
// Windows Development -> Win32 Device Driver Kit ->
// SAMPLE: SmartApp.exe Accesses SMART stats in IDE drives
// 还可以查看 http://www.mtgroup.ru/~alexk
// IdeInfo.zip - 一个简单的使用了S.M.A.R.T. Ioctl API的Delphi应用程序
// 注意:
// WinNT/Win2000 - 你必须拥有对硬盘的读/写访问权限
// Win98
// SMARTVSD.VXD 必须安装到 \windows\system\iosubsys
// (不要忘记在复制后重新启动系统)
end;
function ScsiHddSerialNumber(DeviceHandle: THandle): string;
{$ALIGN ON}
type
TScsiPassThrough = record
Length: Word;
ScsiStatus: BYTE;
PathId: BYTE;
TargetId: BYTE;
Lun: BYTE;
CdbLength: BYTE;
SenseInfoLength: BYTE;
DataIn: BYTE;
DataTransferLength: ULONG;
TimeOutValue: ULONG;
DataBufferOffset: DWORD;
SenseInfoOffset: ULONG;
Cdb: array[0..15] of BYTE;
end;
TScsiPassThroughWithBuffers = record
spt: TScsiPassThrough;
bSenseBuf: array[0..31] of BYTE;
bDataBuf: array[0..191] of BYTE;
end;
{ALIGN OFF}
var dwReturned: DWORD;
len: DWORD;
Buffer: array[0..255] of BYTE;
sptwb: TScsiPassThroughWithBuffers absolute Buffer;
begin
Result := '';
Try
FillChar(Buffer, SizeOf(Buffer), #0);
with sptwb.spt do begin
Length := SizeOf(TScsiPassThrough);
CdbLength := 6; // CDB6GENERIC_LENGTH
SenseInfoLength := 24;
DataIn := 1; // SCSI_IOCTL_DATA_IN
DataTransferLength := 192;
TimeOutValue := 2;
DataBufferOffset := pchar(@sptwb.bDataBuf) - pchar(@sptwb);
SenseInfoOffset := pchar(@sptwb.bSenseBuf) - pchar(@sptwb);
Cdb[0] := $12; // OperationCode := SCSIOP_INQUIRY;
Cdb[1] := $01; // Flags := CDB_INQUIRY_EVPD; Vital product data
Cdb[2] := $80; // PageCode Unit serial number
Cdb[4] := 192; // AllocationLength
end;
len := sptwb.spt.DataBufferOffset + sptwb.spt.DataTransferLength;
if DeviceIoControl(DeviceHandle, $0004D004, @sptwb, SizeOf
(TScsiPassThrough), @sptwb, len, dwReturned, nil)
and ((pchar(@sptwb.bDataBuf) + 1)^ = #$80)
then
SetString(Result, pchar(@sptwb.bDataBuf) + 4,
Ord((pchar(@sptwb.bDataBuf) + 3)^));
except
end;
end;
function GetDeviceHandle(sDeviceName: string): THandle;
begin
Result := CreateFile(pchar('\\.\' + sDeviceName),
GENERIC_READ or GENERIC_WRITE,
FILE_SHARE_READ or FILE_SHARE_WRITE,
nil, OPEN_EXISTING, 0, 0)
end;
//(3)取 第一分区(C:\) 序列号
function GetVolumeSerialNumber: string;
var
I, j: Integer;
SerialNum: DWORD;
a, b: DWORD;
Buffer1: array[0..255] of char; //缓冲区
begin
// 取第一分区盘符
GetSystemDirectory(Buffer1, SizeOf(Buffer1));
for I := 0 to 255 do
if Buffer1[I] = ':' then begin
break;
end;
for j := I + 2 to 255 do
Buffer1[j] := #0;
//取 第一分区(C:\) 序列号
if GetVolumeInformation(Buffer1, nil, 0, @SerialNum, b, a, nil, 0) then
Result := IntToStr(SerialNum)
else Result := '';
end;
function GetScsisn: string;
var
sSerNum, sDeviceName: string;
// rc: DWORD;
hDevice: THandle;
begin
sDeviceName := 'C:';
hDevice := GetDeviceHandle(sDeviceName);
if hDevice <> INVALID_HANDLE_VALUE then try
sSerNum := Trim(GetIdeDiskSerialNumber);
if sSerNum = '' then
sSerNum := Trim(ScsiHddSerialNumber(hDevice));
Result := sSerNum;
finally
CloseHandle(hDevice);
end;
end;
function MonthMaxDay(year, month: Integer): Integer; //获取某年某月最大天数
begin
case month of
1, 3, 5, 7, 8, 10, 12: Result := 31; //如是1、3、5、7、8、10、12则最大为31天
2: if (year mod 4 = 0) and (year mod 100 <> 0) or (year mod 400 = 0) then Result := 29
else Result := 28; //如是闰年2月则29天,否则2月最大为28天
else Result := 30; //其它的4、6、9、11则最大天数为30天
end;
end;
function GetAdapterMac(ANo: Integer): string;
//获取网卡的MAC地址
var
Ncb: TNcb;
Adapter: TAdapterStatus;
Lanaenum: TLanaenum;
IntIdx: Integer; //
cRc: char;
StrTemp: string;
begin
Result := '';
try
ZeroMemory(@Ncb, SizeOf(Ncb));
Ncb.ncb_command := Chr(NCbenum);
NetBios(@Ncb);
Ncb.ncb_buffer := @Lanaenum; //再处理enum命令
Ncb.ncb_length := SizeOf(Lanaenum);
cRc := NetBios(@Ncb);
if Ord(cRc) <> 0 then Exit;
ZeroMemory(@Ncb, SizeOf(Ncb)); //适配器清零
Ncb.ncb_command := Chr(NcbReset);
Ncb.ncb_lana_num := Lanaenum.lana[ANo];
cRc := NetBios(@Ncb);
if Ord(cRc) <> 0 then Exit;
//得到适配器状态
ZeroMemory(@Ncb, SizeOf(Ncb));
Ncb.ncb_command := Chr(NcbAstat);
Ncb.ncb_lana_num := Lanaenum.lana[ANo];
StrPcopy(Ncb.ncb_callname, '*');
Ncb.ncb_buffer := @Adapter;
Ncb.ncb_length := SizeOf(Adapter);
NetBios(@Ncb);
//将mac地址转换成字符串输出
StrTemp := '';
for IntIdx := 0 to 5 do
StrTemp := StrTemp + IntToHex(Integer(Adapter.adapter_address[IntIdx]), 2);
Result := StrTemp;
finally
end;
end;
end.
|
unit rECS;
interface
uses SysUtils, Windows, Classes, Forms, ORFn, rCore, uConst, ORClasses, ORNet, uCore;
type
TECSReport = Class(TObject)
private
FReportHandle: string; // PCE report or Patient Summary report
FReportType : string; // D: display P: print
FPrintDEV : string; // if Print, the print device IEN
FReportStart : string; // Start Date
FReportEnd : string; // End Date
FNeedReason : string; // Need procedure reason ?
FECSPermit : boolean; // Authorized use of ECS
public
constructor Create;
property ReportHandle: string read FReportHandle write FReportHandle;
property ReportType : string read FReportType write FReportType;
property ReportStart : string read FReportStart write FReportStart;
property ReportEnd : string read FReportEnd write FReportEnd;
property PrintDEV : string read FPrintDEV write FPrintDEV;
property NeedReason : string read FNeedReason write FNeedReason;
property ECSPermit : boolean read FECSPermit write FECSPermit;
end;
function GetVisitID: string;
function GetDivisionID: string;
function IsESSOInstalled: boolean;
procedure SaveUserPath(APathInfo: string; var CurPath: string);
procedure FormatECSDate(ADTStr: string; var AnECSRpt: TECSReport);
procedure LoadECSReportText(Dest: TStrings; AnECSRpt: TECSReport);
procedure PrintECSReportToDevice(AnECSRpt: TECSReport);
implementation
uses TRPCB;
constructor TECSReport.Create;
begin
ReportHandle := '';
ReportType := '';
ReportStart := '';
ReportEnd := '';
PrintDEV := '';
FNeedReason := '';
ECSPermit := False;
end;
function IsESSOInstalled: boolean;
var
rtn: integer;
begin
Result := False;
rtn := StrToIntDef(SCallV('ORECS01 CHKESSO',[nil]),0);
if rtn > 0 then
Result := True;
end;
function GetVisitID: string;
var
vsitStr: string;
begin
vsitStr := Encounter.VisitStr + ';' + Patient.DFN;
Result := SCallV('ORECS01 VSITID',[vsitStr]);
end;
function GetDivisionID: string;
var
divID: string;
begin
divID := SCallV('ORECS01 GETDIV',[nil]);
Result := divID;
end;
procedure SaveUserPath(APathInfo: string; var CurPath: string);
begin
CurPath := SCallV('ORECS01 SAVPATH',[APathInfo]);
end;
procedure FormatECSDate(ADTStr: string; var AnECSRpt: TECSReport);
var
x,DaysBack :string;
Alpha, Omega: double;
begin
Alpha := 0;
Omega := 0;
if CharAt(ADTStr, 1) = 'T' then
begin
Alpha := StrToFMDateTime(Piece(ADTStr,';',1));
Omega := StrToFMDateTime(Piece(ADTStr,';',2));
end;
if CharAt(ADTStr, 1) = 'd' then
begin
x := Piece(ADTStr,';',1);
DaysBack := Copy(x, 2, Length(x));
Alpha := StrToFMDateTime('T-' + DaysBack);
Omega := StrToFMDateTime('T');
end;
AnECSRpt.ReportStart := FloatToStr(Alpha);
AnECSRpt.ReportEnd := FloatToStr(Omega);
end;
procedure LoadECSReportText(Dest: TStrings; AnECSRpt: TECSReport);
var
userid: string;
begin
with RPCBrokerv do
begin
ClearParameters := True;
RemoteProcedure := 'ORECS01 ECRPT';
Param[0].PType := list;
Param[0].Mult['"ECHNDL"'] := AnECSRpt.ReportHandle;
Param[0].Mult['"ECPTYP"'] := AnECSRpt.ReportType;
Param[0].Mult['"ECDEV"'] := AnECSRpt.PrintDEV;
Param[0].Mult['"ECDFN"'] := Patient.DFN;
Param[0].Mult['"ECSD"'] := AnECSRpt.ReportStart;
Param[0].Mult['"ECED"'] := AnECSRpt.ReportEnd;
Param[0].Mult['"ECRY"'] := AnECSRpt.NeedReason;
Param[0].Mult['"ECDUZ"'] := userid;
CallBroker;
end;
QuickCopy(RPCBrokerV.Results,Dest);
end;
procedure PrintECSReportToDevice(AnECSRpt: TECSReport);
var
userid: string;
begin
userid := IntToStr(User.DUZ);
with RPCBrokerV do
begin
clearParameters := True;
RemoteProcedure := 'ORECS01 ECPRINT';
Param[0].PType := List;
Param[0].Mult['"ECHNDL"'] := AnECSRpt.ReportHandle;
Param[0].Mult['"ECPTYP"'] := AnECSRpt.ReportType;
Param[0].Mult['"ECDEV"'] := AnECSRpt.PrintDEV;
Param[0].Mult['"ECDFN"'] := Patient.DFN;
Param[0].Mult['"ECSD"'] := AnECSRpt.ReportStart;
Param[0].Mult['"ECED"'] := AnECSRpt.ReportEnd;
Param[0].Mult['"ECRY"'] := AnECSRpt.NeedReason;
Param[0].Mult['"ECDUZ"'] := userid;
CallBroker;
end;
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.Imaging.pngimage, Vcl.ExtCtrls, Vcl.StdCtrls;
type
TForm1 = class(TForm)
Image1: TImage;
Label1: TLabel;
Image2: TImage;
Label2: TLabel;
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
procedure UpdateItems;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
NtBase,
NtGraphic,
NtLanguageDlg;
procedure TForm1.UpdateItems;
var
png: TPngImage;
begin
// Set the PNG image and assign it to Image2
png := TPngImage.Create;
try
// A helper from NtGraphics.pas. Load image from custom resource (added through Images.rc file)
png.LoadResource('IMAGE', 'Car');
Image2.Picture.Graphic := png;
finally
png.Free;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
UpdateItems;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
// Show a language select dialog and turn on the selected language
if TNtLanguageDialog.Select('en', '', lnBoth) then
begin
// Language has been changed.
// Properties that were set on run time must be reset.
UpdateItems;
end;
end;
end.
|
unit USVGGraphics32;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,UMatrix,USVG,GR32, GR32_Image, GR32_Layers,GR32_Transforms,
GR32_VectorUtils,GR32_Polygons, GR32_Paths, GR32_Brushes,GR32_ColorGradients,
UPolylines;
type
TGradMat=class
public
UrlRef:TGradMat;
Colors: TArrayGradientColor;
IsRadialGradient:boolean;
Matrix:TMatrix;
//Linear
FLinearStart: TSvgPoint;
FLinearEnd: TSvgPoint;
//Radial
Focal:TSvgPoint;
Center:TSvgPoint;
Radius:Single;
function CreateTable(Alpha:byte):TColor32LookupTable;
end;
TStrokeBrush=class(GR32_Brushes.TStrokeBrush)
public
procedure PolyPolygonFS(Renderer: TCustomPolygonRenderer;
const Points: TArrayOfArrayOfFloatPoint;
const ClipRect: TFloatRect; Transformation: TTransformation;
Closed: Boolean); override;
end;
TDashedBrush=class(TStrokeBrush)
private
FDashArray: TArrayOfFloat;
public
DashOffset: TFloat;
Pathlength: TFloat;
procedure SetDashArray(const ADashArray: array of TFloat);
procedure PolyPolygonFS(Renderer: TCustomPolygonRenderer;
const Points: TArrayOfArrayOfFloatPoint;
const ClipRect: TFloatRect; Transformation: TTransformation;
Closed: Boolean); override;
end;
TClipRendrer=class(TPolygonRenderer32VPR)
public
Enabled:boolean;
PathRect:TFloatRect;
//clip before transform
procedure PolyPolygonFS(const Points: TArrayOfArrayOfFloatPoint;
const ClipRect: TFloatRect; Transformation: TTransformation);override;
end;
TSVGLoader=class(TSVGLoaderBase)
protected
FClipRendrer:TClipRendrer;
FUrlColors:TStringHashEx;
FGradFillList:TList;
FBitmap32:TBitmap32;
FCanvas:TCanvas32;
FSolid: TSolidBrush;
FStroke: TStrokeBrush;
FDashed: TDashedBrush;
FMatrix:TAffineTransformation;
procedure Rectangle(const APos,Size,Radius:TSvgPoint);override;
procedure Ellipse(const Center,Radius:TSvgPoint);override;
procedure Poly(const Pts:array of TSvgPoint;AClosed:boolean);override;
procedure Path(const Pts: array of TSvgPoint;const PtTypes: array of TPathSegType);override;
procedure Line(const P1,P2:TSvgPoint);override;
procedure Text(const AStr:string;const APos:TSvgPoint;AFont:TFont;const InlineSize:Extended);override;
function BuildGradientBase(const AName, AUrl: string;const Items: TArrayGradientColor;Mat:PMatrix): TGradMat;
function TryUrlFill(AColor: integer; var P:TGradMat): boolean;
function Preparefiller(AFillData:TGradMat;Alpha:byte):TCustomPolygonFiller;
procedure BeforeProcessNode(NK:TSVGNode);override;
procedure AfterProcessNode(NK:TSVGNode);override;
procedure BuildLinearGradient(const AName,AUrl:string;const Pt1,Pt2:TSvgPoint;
const Items:TArrayGradientColor;MAt:PMatrix);override;
function GetColorUrl(const AName:string):integer;override;
procedure BuildRadialGradient(const AName,AUrl:string;const AFocal,ACenter:TSvgPoint;ARadius:Single;
const Items:TArrayGradientColor;Mat:PMatrix);override;
public
constructor Create(ABitmap32:TBitmap32);
destructor Destroy();override;
end;
implementation
uses math,USVGStack,GR32_Text_VCL,UTxtToPath;
const SVG_GR32:array[svgButt..svgNonZero]of integer=(
Ord(esButt),Ord(esSquare),Ord(esRound),
Ord(jsMiter),Ord(jsBevel),Ord(jsRound),
Ord(pfAlternate),Ord(pfWinding));
function GrFPoint(const Pt:TSvgPoint):TFloatPoint;
begin
Result.X :=Pt.X;
Result.Y :=Pt.Y;
end;
function IsClosedPath(const APath:TArrayOfFloatPoint):boolean;
var
P1,P2:TFloatPoint;
L:integer;
begin
Result:=False;
L:=Length(APath);
if L < 2 then
Exit;
P1:=APath[0];
P2:=APath[L-1];
Result:=(P1.X=P2.X)and(P1.Y=P2.Y);
end;
function ClipPolyPolygon(const Points:TArrayOfArrayOfFloatPoint;const ARect:TFloatRect):TArrayofArrayOfFloatpoint;
var
I:integer;
begin
Setlength(Result,Length(Points));
for I := 0 to Length(Points) - 1 do
Result[I]:=ClipPolygon(Points[I],ARect);
end;
{ TStrokeBrush }
procedure TStrokeBrush.PolyPolygonFS(Renderer: TCustomPolygonRenderer;
const Points: TArrayOfArrayOfFloatPoint; const ClipRect: TFloatRect;
Transformation: TTransformation; Closed: Boolean);
var
APoints: TArrayOfArrayOfFloatPoint;
begin
APoints := SVGBuildPolyPolyLine(Points,StrokeWidth, JoinStyle,
EndStyle, MiterLimit);
UpdateRenderer(Renderer);
Renderer.PolyPolygonFS(APoints, ClipRect, Transformation);
end;
{ TDashedBrush }
procedure TDashedBrush.PolyPolygonFS(Renderer: TCustomPolygonRenderer;
const Points: TArrayOfArrayOfFloatPoint; const ClipRect: TFloatRect;
Transformation: TTransformation; Closed: Boolean);
var
I: Integer;
Pts:TArrayOfFloatPoint;
R:TArrayOfArrayOfFloatPoint;
begin
for I := 0 to High(Points) do
begin
Pts:=Points[I];
R:=SVGBuildDashedLine(Pts, FDashArray, DashOffset,IsClosedPath(Pts),Pathlength);
inherited PolyPolygonFS(
Renderer, R,
ClipRect, Transformation, False);
end;
end;
procedure TDashedBrush.SetDashArray(const ADashArray: array of TFloat);
var
L: Integer;
begin
L := Length(ADashArray);
SetLength(FDashArray, L);
Move(ADashArray[0], FDashArray[0], L * SizeOf(TFloat));
Changed;
end;
{ TClipRendrer }
procedure TClipRendrer.PolyPolygonFS(const Points: TArrayOfArrayOfFloatPoint;
const ClipRect: TFloatRect; Transformation: TTransformation);
var
Polys:TArrayOfArrayOfFloatPoint;
begin
if Enabled then
begin
Polys:=ClipPolyPolygon(Points,PathRect);
inherited PolyPolygonFS(Polys,ClipRect,Transformation);
end else
inherited PolyPolygonFS(Points,ClipRect,Transformation);
end;
procedure TSVGLoader.Text(const AStr: string; const APos: TSvgPoint;
AFont: TFont; const InlineSize: Extended);
var
R:TFloatRect;
Glyphs:TArrayOfGlyphs;
I,J :integer;
Path:TArrayOfArrayOfFloatPoint;
Ph:TArrayOfFloatPoint;
Align:TTxtAlignement;
W:TFloat;
begin
case FStk.TxtAlign of
svgCenter:Align:=tacCenter;
svgRight:Align:=tacRight;
svgJustified:Align:=tacJustify;
else
Align:=tacLeft;
end;
R.TopLeft:=GrFPoint(APos);
R.BottomRight:=FloatPoint(APos.X+InlineSize,APos.Y);
case FStk.TxtAnchor of
svgMiddle:begin
W:=InlineSize / 2;
R:=FloatRect(APos.X-W,APos.Y,APos.X+W,APos.Y);
Align:=tacCenter;
end;
svgEnd:begin
R:=FloatRect(APos.X-InlineSize,APos.Y,APos.X,APos.Y);
Align:=tacRight;
end;
end;
Glyphs:=ScriptToPath(AStr,AFont,R,Align);
for I := 0 to Length(Glyphs) - 1 do
begin
Path:=Glyphs[I];
for J := 0 to Length(Path) - 1 do //self intersect may occure
FCanvas.Polygon(Path[J]);
end;
end;
function TSVGLoader.TryUrlFill(AColor:integer;var P:TGradMat):boolean;
var
idx:integer;
begin
P:=nil;
Result:=((AColor and $FF000000)<> 0 )and((AColor shr 24 )=$25);
if Result then
begin
idx:= AColor and $FFFFFF;
Result:=(idx >0)and (Idx < FGradFillList.Count);
if Result then
P :=FGradFillList[idx];
end;
end;
procedure TSVGLoader.Path(const Pts: array of TSvgPoint;
const PtTypes: array of TPathSegType);
var
I,L,J:integer;
Start,P,C1,C2:TFloatPoint;
begin
L:=Length(Pts);
if L < 2 then
Exit;
J:=0;
FCanvas.BeginUpdate();
for I := 0 to Length(PtTypes)-1 do
case PtTypes[I] of
psMoveTo:begin
P:= GrFPoint(Pts[J]);
Start:=P;
inc(J);
FCanvas.MoveTo(Start);
end;
psLineTo:begin
P:= GrFPoint(Pts[J]);
FCanvas.LineTo(P);
inc(J);
end;
psBezierTo:begin
C1:=GrFPoint(Pts[J]);
C2:=GrFPoint(Pts[J+1]);
P :=GrFPoint(Pts[J+2]);
FCanvas.CurveTo(C1,C2,P);
inc(J,3);
end;
psClose:begin
FCanvas.EndPath(True)
end;
end;
FCanvas.EndPath();
FCanvas.EndUpdate();
end;
procedure TSVGLoader.Poly(const Pts: array of TSvgPoint; AClosed: boolean);
var
I,L:integer;
begin
L:=Length(Pts);
if L < 2 then
Exit;
with Pts[0] do
FCanvas.MoveTo(X,Y);
for I:=1 to L-1 do
with Pts[I] do
FCanvas.LineTo(X,Y);
if AClosed then
begin
with Pts[0] do
FCanvas.LineTo(X,Y);
end;
FCanvas.EndPath(AClosed);
end;
procedure TSVGLoader.Rectangle(const APos, Size, Radius: TSvgPoint);
begin
if (Radius.X=0)or (Radius.Y=0) then
FCanvas.Rectangle(FloatRect(APos.X,APos.Y,APos.X+Size.X,APos.Y+Size.Y))
else
FCanvas.RoundRect(FloatRect(APos.X,APos.Y,APos.X+Size.X,APos.Y+Size.Y),Radius.X);
end;
procedure TSVGLoader.Ellipse(const Center, Radius: TSvgPoint);
begin
FCanvas.Ellipse(Center.X,center.Y,Radius.X,Radius.Y);
end;
procedure TSVGLoader.Line(const P1, P2: TSvgPoint);
begin
FCanvas.MoveTo(P1.X,P1.Y);
FCanvas.LineTo(P2.X,P2.Y);
FCanvas.EndPath();
end;
function TSVGLoader.Preparefiller(AFillData:TGradMat;Alpha:byte):TCustomPolygonFiller;
var
LinearFiller:TCustomLinearGradientPolygonFiller;
RadGradFiller:TSVGRadialGradientPolygonFiller;
D:TFloatRect;
Mx:TFloatMatrix;
begin
if AFillData.Matrix.A[2,2]=1 then //has a valid matrix
begin
FMatrix.Push();
move(AFillData.Matrix,Mx,SizeOf(TFloatMatrix));
Mx:=Mult(FMatrix.Matrix,Mx);
FMatrix.Clear(Mx);
end;
if AFillData.IsRadialGradient then
begin
RadGradFiller:=TSVGRadialGradientPolygonFiller.Create(AFillData.CreateTable(Alpha));
Result:=RadGradFiller;
with AFillData do
begin
D.TopLeft:= FMatrix.Transform(FloatPoint(Center.X - Radius , Center.Y - Radius));
D.BottomRight:=FMatrix.Transform(FloatPoint(Center.X+ Radius, Center.Y+Radius));
end;
RadGradFiller.EllipseBounds:=D;
RadGradFiller.FocalPoint := FMatrix.Transform(GrFPoint(AFillData.Focal));
end else begin
LinearFiller := TLinearGradientPolygonFiller.Create(AFillData.CreateTable(Alpha));
Result:=LinearFiller;
LinearFiller.StartPoint := FMatrix.Transform(GrFPoint(AFillData.FLinearStart));
LinearFiller.EndPoint :=FMatrix.Transform(GrFPoint(AFillData.FLinearEnd));
end;
if AFillData.Matrix.A[2,2]=1 then //has a valid matrix
FMatrix.Pop();
end;
procedure TSVGLoader.BeforeProcessNode(NK: TSVGNode);
var
alpha1,alpha2:integer;
FillData:TGradMat;
Mx:TFloatMatrix;
Brush:TStrokeBrush;
C:TColor32;
S:string;
begin
if NK=snSvg then
begin
C:=SetAlpha(Color32(BGColor),0);
FBitmap32.SetSize(Ceil(FC.Size.x),Ceil(FC.Size.y));
FBitmap32.Clear(C);
end;
if not(NK in[snRect,snLine,snCircle,snEllipse,snPolyLine,snPolygon,snPath,snText]) then
Exit;
FCanvas.BeginUpdate();
alpha1:= Round(255*FStk.FillOpacity);
alpha2:= Round(255*FStk.PenOpacity);
move(FStk.Matrix,Mx,SizeOf(TFloatMatrix));
FMatrix.Clear(Mx);
FSolid.Visible :=FStk.FillColor <> clNone;
FSolid.Filler:=nil;
if FSolid.Visible then
begin
FSolid.FillColor:=SetAlpha(Color32(FStk.FillColor),alpha1);
FSolid.FillMode:=TPolyFillMode(SVG_GR32[FStk.FillMode]);
if TryUrlFill(FStk.FillColor,FillData) then
FSolid.Filler:= Preparefiller(FillData,alpha1);
end;
FDashed.Visible :=FStk.PenColor <> clNone;;
FStroke.Visible :=FDashed.Visible;
FStroke.Filler:=nil;
FDashed.Filler:=nil;
if not FDashed.Visible then
Exit;
FDashed.Visible :=Length(FStk.PenDashArray) <> 0;
FStroke.Visible :=not FDashed.Visible;
if FDashed.Visible then
begin
Brush:=FDashed;
FDashed.DashOffset:=FStk.PenDashOffset;
FDashed.SetDashArray(FStk.PenDashArray);
FDashed.Pathlength:=0;
S:=FC.Attrs.Values['pathlength'];
if S <> '' then
FDashed.Pathlength:=SVGParseValue(S,False);
end else
Brush:=FStroke;
if Brush.Visible then
begin
Brush.StrokeWidth:=FStk.PenWidth;
Brush.FillColor:=SetAlpha(Color32(FStk.PenColor),alpha2);
Brush.EndStyle :=TEndStyle(SVG_GR32[FStk.LineCap]);
Brush.JoinStyle :=TJoinStyle(SVG_GR32[FStk.LineJoin]);
Brush.MiterLimit:=Max( FStk.MiterLimit,1);
if TryUrlFill(FStk.PenColor,FillData) then
brush.Filler:= Preparefiller(FillData,alpha2);
end;
end;
procedure TSVGLoader.AfterProcessNode(NK: TSVGNode);
procedure FreeFiller(Brush:TSolidBrush);
begin
if Assigned(Brush.Filler) then
begin
Brush.Filler.Free;
Brush.Filler:=nil;
end;
end;
var
R:TFloatRect;
begin
if not(NK in[snRect,snLine,snCircle,snEllipse,snPolyLine,snPolygon,snPath,snText]) then
Exit;
if FStk.Display=svgNone then
FCanvas.Clear();
FClipRendrer.Enabled:=FC.UseClip;
if FC.UseClip then
with FC.ClipRect do
begin
R:=FloatRect(X,Y,W,H);
FClipRendrer.PathRect:= R;
end;
FCanvas.EndUpdate();
FCanvas.Clear();
FreeFiller(FSolid);
FreeFiller(FStroke);
FreeFiller(FDashed);
FClipRendrer.Enabled:=False;
end;
constructor TSVGLoader.Create(ABitmap32:TBitmap32);
begin
inherited Create();
FBitmap32 :=ABitmap32;
FCanvas:= TCanvas32.Create(ABitmap32);
FSolid := TSolidBrush(FCanvas.Brushes.Add(TSolidBrush));
FStroke:= TStrokeBrush(FCanvas.Brushes.Add(TStrokeBrush));
FDashed:= TDashedBrush(FCanvas.Brushes.Add(TDashedBrush));
FUrlColors:=TStringHashEx.Create;
FGradFillList:=TList.Create;
FDashed.Visible:=false;
// FStroke.Visible:=false;
FGradFillList.Add(nil);//invalid filler
FMatrix:=TAffineTransformation.Create;
FCanvas.Transformation:=FMatrix;
FClipRendrer:=TClipRendrer.Create();
FCanvas.Renderer:=FClipRendrer;
end;
destructor TSVGLoader.Destroy;
var
i:integer;
begin
for I:=0 to FGradFillList.Count-1 do
begin
TObject(FGradFillList[I]).Free;
end;
FGradFillList.Free;
FCanvas.Free;
FMatrix.Free;
inherited;
end;
function TSVGLoader.GetColorUrl(const AName: string): integer;
begin
Result:=FUrlColors.ValueOf(Uppercase(AName));
end;
function TSVGLoader.BuildGradientBase(const AName, AUrl: string;const Items: TArrayGradientColor;Mat:PMatrix):TGradMat;
var
GradMat:TGradMat;
iD:integer;
begin
GradMat:=nil;
if (AName <> '')and TryUrlFill(GetColorUrl(AName),Result) then //prev declaration
Result.Colors:=Items
else begin
if (AUrl <> '')and not TryUrlFill(GetColorUrl(AUrl),GradMat) then
begin
GradMat:=TGradMat.Create();
iD:=FGradFillList.Add(GradMat)or $25000000;
FUrlColors.Add(Uppercase(AUrl),iD);
end;
Result:=TGradMat.Create();
Result.UrlRef:=GradMat;
iD:=FGradFillList.Add(Result)or $25000000;
FUrlColors.Add(Uppercase(AName),iD);
Result.Colors:=Items;
if Assigned(Mat) then
Result.Matrix:=Mat^;
end;
end;
procedure TSVGLoader.BuildLinearGradient(const AName, AUrl: string;const Pt1,Pt2:TSvgPoint;
const Items:TArrayGradientColor;Mat:PMatrix);
begin
with BuildGradientBase(AName,AUrl,Items,Mat) do
begin
FLinearStart:=Pt1;
FLinearEnd :=Pt2;
end;
end;
procedure TSVGLoader.BuildRadialGradient(const AName,AUrl:string;const AFocal,ACenter:TSvgPoint;ARadius:Single;
const Items:TArrayGradientColor;Mat:PMatrix);
begin
with BuildGradientBase(AName,AUrl,Items,Mat) do
begin
IsRadialGradient:=True;
Focal:=AFocal;
Center:=ACenter;
Radius:=ARadius;
end;
end;
function TGradMat.CreateTable(Alpha:byte):TColor32LookupTable;
var
I:integer;
Gradient: TColor32Gradient;
GradMat:TGradMat;
begin
GradMat:=Self;
if assigned(UrlRef) then
GradMat:= UrlRef;
Result := TColor32LookupTable.Create;
Gradient := TColor32Gradient.Create;
try
with GradMat do
for I:= 0 to Length(Colors)-1do
with Colors[I] do
Gradient.AddColorStop(mLGOffset,
GR32.SetAlpha( GR32.Color32(mLGStopColor),Round(mLGStopOpacity*Alpha)));
Gradient.FillColorLookUpTable(Result);
finally
Gradient.Free;
end;
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [VIEW_COMPRA_MAPA_COMPARATIVO]
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit ViewCompraMapaComparativoVO;
{$mode objfpc}{$H+}
interface
uses
VO, Classes, SysUtils, FGL;
type
TViewCompraMapaComparativoVO = class(TVO)
private
FID_COMPRA_COTACAO: Integer;
FID_COMPRA_FORNECEDOR_COTACAO: Integer;
FID_COMPRA_COTACAO_DETALHE: Integer;
FID_PRODUTO: Integer;
FID_FORNECEDOR: Integer;
FPRODUTO_NOME: String;
FFORNECEDOR_NOME: String;
FQUANTIDADE: Extended;
FQUANTIDADE_PEDIDA: Extended;
FVALOR_UNITARIO: Extended;
FVALOR_SUBTOTAL: Extended;
FTAXA_DESCONTO: Extended;
FVALOR_DESCONTO: Extended;
FVALOR_TOTAL: Extended;
//Transientes
published
property IdCompraCotacao: Integer read FID_COMPRA_COTACAO write FID_COMPRA_COTACAO;
property IdCompraFornecedorCotacao: Integer read FID_COMPRA_FORNECEDOR_COTACAO write FID_COMPRA_FORNECEDOR_COTACAO;
property IdCompraCotacaoDetalhe: Integer read FID_COMPRA_COTACAO_DETALHE write FID_COMPRA_COTACAO_DETALHE;
property IdProduto: Integer read FID_PRODUTO write FID_PRODUTO;
property IdFornecedor: Integer read FID_FORNECEDOR write FID_FORNECEDOR;
property ProdutoNome: String read FPRODUTO_NOME write FPRODUTO_NOME;
property FornecedorNome: String read FFORNECEDOR_NOME write FFORNECEDOR_NOME;
property Quantidade: Extended read FQUANTIDADE write FQUANTIDADE;
property QuantidadePedida: Extended read FQUANTIDADE_PEDIDA write FQUANTIDADE_PEDIDA;
property ValorUnitario: Extended read FVALOR_UNITARIO write FVALOR_UNITARIO;
property ValorSubtotal: Extended read FVALOR_SUBTOTAL write FVALOR_SUBTOTAL;
property TaxaDesconto: Extended read FTAXA_DESCONTO write FTAXA_DESCONTO;
property ValorDesconto: Extended read FVALOR_DESCONTO write FVALOR_DESCONTO;
property ValorTotal: Extended read FVALOR_TOTAL write FVALOR_TOTAL;
//Transientes
end;
TListaViewCompraMapaComparativoVO = specialize TFPGObjectList<TViewCompraMapaComparativoVO>;
implementation
initialization
Classes.RegisterClass(TViewCompraMapaComparativoVO);
finalization
Classes.UnRegisterClass(TViewCompraMapaComparativoVO);
end.
|
unit MainUnit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, System.Generics.Collections,
ComObj, ActionsUnit, ActiveX, SPIClient_TLB, Vcl.Menus;
type
TfrmMain = class(TForm)
pnlSettings: TPanel;
lblSettings: TLabel;
lblPosID: TLabel;
edtPosID: TEdit;
lblEftposAddress: TLabel;
edtEftposAddress: TEdit;
pnlStatus: TPanel;
lblStatusHead: TLabel;
lblStatus: TLabel;
btnPair: TButton;
pnlReceipt: TPanel;
lblReceipt: TLabel;
richEdtReceipt: TRichEdit;
btnRefund: TButton;
pnlTableActions: TPanel;
pnlOtherActions: TPanel;
radioReceipt: TRadioGroup;
radioSign: TRadioGroup;
btnListTables: TButton;
btnGetBill: TButton;
btnSecrets: TButton;
edtSecrets: TEdit;
lblSecrets: TLabel;
btnSave: TButton;
procedure btnPairClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnRefundClick(Sender: TObject);
procedure btnSettleClick(Sender: TObject);
procedure btnPurchaseClick(Sender: TObject);
procedure btnOpenClick(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure btnPrintBillClick(Sender: TObject);
procedure btnListTablesClick(Sender: TObject);
procedure btnGetBillClick(Sender: TObject);
procedure btnSecretsClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
private
public
procedure OpenTable;
procedure CloseTable;
procedure AddToTable;
procedure PrintBill(billId: WideString);
procedure GetBill;
end;
type
TMyWorkerThread = class(TThread)
public
procedure Execute; override;
end;
type
TBill = class(TObject)
BillId: WideString;
TableId: WideString;
TotalAmount: Integer;
OutstandingAmount: Integer;
tippedAmount: Integer;
end;
type
TBillsStore = record
BillId: string[255];
Bill: TBill;
end;
type
TTableToBillMapping = record
TableId: string[255];
BillId: string[255];
end;
type
TAssemblyBillDataStore = record
BillId: string[255];
BillData: string[255];
end;
var
frmMain: TfrmMain;
frmActions: TfrmActions;
ComWrapper: SPIClient_TLB.ComWrapper;
Spi: SPIClient_TLB.Spi;
_posId, _eftposAddress: WideString;
SpiSecrets: SPIClient_TLB.Secrets;
UseSynchronize, UseQueue: Boolean;
SpiPayAtTable: SPIClient_TLB.SpiPayAtTable;
billsStoreDict: TDictionary<WideString, TBill>;
tableToBillMappingDict: TDictionary<WideString, Widestring>;
assemblyBillDataStoreDict: TDictionary<WideString, Widestring>;
implementation
{$R *.dfm}
function BillToString(newBill: TBill): WideString;
var
totalAmount, outstandingAmount, tippedAmount: Single;
begin
totalAmount := newBill.TotalAmount / 100;
outstandingAmount := newBill.OutstandingAmount / 100;
tippedAmount := newBill.tippedAmount / 100;
Result := newBill.BillId + ' - Table:' + newBill.TableId + 'Total:$' +
CurrToStr(totalAmount) + ' Outstanding:$' +
CurrToStr(outstandingAmount) + ' Tips:$' + CurrToStr(tippedAmount);
end;
procedure Split(Delimiter: Char; Str: string; ListOfStrings: TStrings) ;
begin
ListOfStrings.Clear;
ListOfStrings.Delimiter := Delimiter;
ListOfStrings.StrictDelimiter := True; // Requires D2006 or newer.
ListOfStrings.DelimitedText := Str;
end;
function FormExists(apForm: TForm): boolean;
var
i: Word;
begin
Result := False;
for i := 0 to Screen.FormCount - 1 do
if Screen.Forms[i] = apForm then
begin
Result := True;
Break;
end;
end;
procedure PersistState;
var
billsStoreFile: File of TBillsStore;
tableToBillMappingFile: File of TTableToBillMapping;
assemblyBillDataStoreFile: File of TAssemblyBillDataStore;
billRecord: TBillsStore;
tableToBillMappingRecord: TTableToBillMapping;
assemblyBillDataRecord: TAssemblyBillDataStore;
billRecordItem: TPair<WideString, TBill>;
tableToBillMappingRecordItem: TPair<WideString, WideString>;
assemblyBillDataRecordItem: TPair<WideString, WideString>;
begin
if (billsStoreDict <> nil) Then
begin
AssignFile(billsStoreFile, 'billsStore.bin');
ReWrite(billsStoreFile);
for billRecordItem in billsStoreDict do
begin
billRecord.BillId := billRecordItem.Key;
billRecord.Bill := billRecordItem.Value;
Write(billsStoreFile, billRecord);
end;
CloseFile(billsStoreFile);
AssignFile(tableToBillMappingFile, 'tableToBillMapping.bin');
ReWrite(tableToBillMappingFile);
for tableToBillMappingRecordItem in tableToBillMappingDict do
begin
tableToBillMappingRecord.TableId := tableToBillMappingRecordItem.Key;
tableToBillMappingRecord.BillId := tableToBillMappingRecordItem.Value;
Write(tableToBillMappingFile, tableToBillMappingRecord);
end;
CloseFile(tableToBillMappingFile);
AssignFile(assemblyBillDataStoreFile, 'assemblyBillDataStore.bin');
ReWrite(assemblyBillDataStoreFile);
for assemblyBillDataRecordItem in assemblyBillDataStoreDict do
begin
assemblyBillDataRecord.BillId := assemblyBillDataRecordItem.Key;
assemblyBillDataRecord.BillData:= assemblyBillDataRecordItem.Value;
Write(assemblyBillDataStoreFile, assemblyBillDataRecord);
end;
CloseFile(assemblyBillDataStoreFile);
end;
end;
procedure LoadPersistedState;
var
billsStoreFile: File of TBillsStore;
tableToBillMappingFile: File of TTableToBillMapping;
assemblyBillDataStoreFile: File of TAssemblyBillDataStore;
billsStore: TBillsStore;
tableToBillMapping: TTableToBillMapping;
assemblyBillDataStore: TAssemblyBillDataStore;
OutPutList: TStringList;
begin
billsStoreDict := TDictionary<WideString, TBill>.Create;
tableToBillMappingDict := TDictionary<WideString, WideString>.Create;
assemblyBillDataStoreDict := TDictionary<WideString, WideString>.Create;
if (frmMain.edtSecrets.Text <> '') then
begin
OutPutList := TStringList.Create;
Split(':', frmMain.edtSecrets.Text, OutPutList);
SpiSecrets := ComWrapper.SecretsInit(OutPutList[0], OutPutList[1]);
if (FileExists('tableToBillMapping.bin')) then
begin
AssignFile(billsStoreFile, 'billsStore.bin');
FileMode := fmOpenRead;
Reset(billsStoreFile);
while not Eof(billsStoreFile) do
begin
Read(billsStoreFile, billsStore);
billsStoreDict.Add(billsStore.BillId, billsStore.Bill);
end;
CloseFile(billsStoreFile);
AssignFile(tableToBillMappingFile, 'tableToBillMapping.bin');
FileMode := fmOpenRead;
Reset(tableToBillMappingFile);
while not Eof(tableToBillMappingFile) do
begin
Read(tableToBillMappingFile, tableToBillMapping);
tableToBillMappingDict.Add(tableToBillMapping.TableId,
tableToBillMapping.BillId);
end;
CloseFile(tableToBillMappingFile);
AssignFile(assemblyBillDataStoreFile, 'assemblyBillDataStore.bin');
FileMode := fmOpenRead;
Reset(assemblyBillDataStoreFile);
while not Eof(assemblyBillDataStoreFile) do
begin
Read(assemblyBillDataStoreFile, assemblyBillDataStore);
assemblyBillDataStoreDict.Add(assemblyBillDataStore.BillId,
assemblyBillDataStore.BillData);
end;
CloseFile(assemblyBillDataStoreFile);
end;
end;
end;
procedure PrintFlowInfo;
var
purchaseResponse: SPIClient_TLB.PurchaseResponse;
refundResponse: SPIClient_TLB.RefundResponse;
settleResponse: SPIClient_TLB.Settlement;
amountCents: Single;
begin
purchaseResponse := CreateComObject(CLASS_PurchaseResponse)
AS SPIClient_TLB.PurchaseResponse;
refundResponse := CreateComObject(CLASS_RefundResponse)
AS SPIClient_TLB.RefundResponse;
settleResponse := CreateComObject(CLASS_Settlement)
AS SPIClient_TLB.Settlement;
if (Spi.CurrentFlow = SpiFlow_Pairing) then
begin
frmActions.lblFlowMessage.Caption := spi.CurrentPairingFlowState.Message;
frmActions.richEdtFlow.Lines.Add('### PAIRING PROCESS UPDATE ###');
frmActions.richEdtFlow.Lines.Add('# ' +
spi.CurrentPairingFlowState.Message);
frmActions.richEdtFlow.Lines.Add('# Finished? ' +
BoolToStr(spi.CurrentPairingFlowState.Finished));
frmActions.richEdtFlow.Lines.Add('# Successful? ' +
BoolToStr(spi.CurrentPairingFlowState.Successful));
frmActions.richEdtFlow.Lines.Add('# Confirmation Code: ' +
spi.CurrentPairingFlowState.ConfirmationCode);
frmActions.richEdtFlow.Lines.Add('# Waiting Confirm from Eftpos? ' +
BoolToStr(spi.CurrentPairingFlowState.AwaitingCheckFromEftpos));
frmActions.richEdtFlow.Lines.Add('# Waiting Confirm from POS? ' +
BoolToStr(spi.CurrentPairingFlowState.AwaitingCheckFromPos));
end;
if (Spi.CurrentFlow = SpiFlow_Transaction) then
begin
frmActions.lblFlowMessage.Caption := Spi.CurrentTxFlowState.DisplayMessage;
frmActions.richEdtFlow.Lines.Add('### TX PROCESS UPDATE ###');
frmActions.richEdtFlow.Lines.Add('# ' +
Spi.CurrentTxFlowState.DisplayMessage);
frmActions.richEdtFlow.Lines.Add('# Id: ' +
Spi.CurrentTxFlowState.PosRefId);
frmActions.richEdtFlow.Lines.Add('# Type: ' +
ComWrapper.GetTransactionTypeEnumName(Spi.CurrentTxFlowState.type_));
amountCents := Spi.CurrentTxFlowState.amountCents / 100;
frmActions.richEdtFlow.Lines.Add('# Request Amount: ' +
CurrToStr(amountCents));
frmActions.richEdtFlow.Lines.Add('# Waiting For Signature: ' +
BoolToStr(Spi.CurrentTxFlowState.AwaitingSignatureCheck));
frmActions.richEdtFlow.Lines.Add('# Attempting to Cancel : ' +
BoolToStr(Spi.CurrentTxFlowState.AttemptingToCancel));
frmActions.richEdtFlow.Lines.Add('# Finished: ' +
BoolToStr(Spi.CurrentTxFlowState.Finished));
frmActions.richEdtFlow.Lines.Add('# Success: ' +
ComWrapper.GetSuccessStateEnumName(Spi.CurrentTxFlowState.Success));
If (Spi.CurrentTxFlowState.Finished) then
begin
case Spi.CurrentTxFlowState.Success of
SuccessState_Success:
case Spi.CurrentTxFlowState.type_ of
TransactionType_Purchase:
begin
frmActions.richEdtFlow.Lines.Add('# WOOHOO - WE GOT PAID!');
purchaseResponse := ComWrapper.PurchaseResponseInit(
Spi.CurrentTxFlowState.Response);
frmActions.richEdtFlow.Lines.Add('# Response: ' +
purchaseResponse.GetResponseText);
frmActions.richEdtFlow.Lines.Add('# RRN: ' +
purchaseResponse.GetRRN);
frmActions.richEdtFlow.Lines.Add('# Scheme: ' +
purchaseResponse.SchemeName);
frmActions.richEdtFlow.Lines.Add('# Customer Receipt:');
frmMain.richEdtReceipt.Lines.Add
(TrimLeft(purchaseResponse.GetCustomerReceipt));
frmActions.richEdtFlow.Lines.Add('# PURCHASE: ' +
IntToStr(purchaseResponse.GetPurchaseAmount));
frmActions.richEdtFlow.Lines.Add('# TIP: ' +
IntToStr(purchaseResponse.GetTipAmount));
frmActions.richEdtFlow.Lines.Add('# CASHOUT: ' +
IntToStr(purchaseResponse.GetCashoutAmount));
frmActions.richEdtFlow.Lines.Add('# BANKED NON-CASH AMOUNT: ' +
IntToStr(purchaseResponse.GetBankNonCashAmount));
frmActions.richEdtFlow.Lines.Add('# BANKED CASH AMOUNT: ' +
IntToStr(purchaseResponse.GetBankCashAmount));
end;
TransactionType_Refund:
begin
frmActions.richEdtFlow.Lines.Add('# REFUND GIVEN- OH WELL!');
refundResponse := ComWrapper.RefundResponseInit(
Spi.CurrentTxFlowState.Response);
frmActions.richEdtFlow.Lines.Add('# Response: ' +
refundResponse.GetResponseText);
frmActions.richEdtFlow.Lines.Add('# RRN: ' +
refundResponse.GetRRN);
frmActions.richEdtFlow.Lines.Add('# Scheme: ' +
refundResponse.SchemeName);
frmActions.richEdtFlow.Lines.Add('# Customer Receipt:');
frmMain.richEdtReceipt.Lines.Add
(TrimLeft(refundResponse.GetCustomerReceipt));
end;
TransactionType_Settle:
begin
frmActions.richEdtFlow.Lines.Add('# SETTLEMENT SUCCESSFUL!');
if (Spi.CurrentTxFlowState.Response <> nil) then
begin
settleResponse := ComWrapper.SettlementInit(
Spi.CurrentTxFlowState.Response);
frmActions.richEdtFlow.Lines.Add('# Response: ' +
settleResponse.GetResponseText);
frmActions.richEdtFlow.Lines.Add('# Merchant Receipt:');
frmMain.richEdtReceipt.Lines.Add
(TrimLeft(settleResponse.GetReceipt));
end;
end;
end;
SuccessState_Failed:
case Spi.CurrentTxFlowState.type_ of
TransactionType_Purchase:
begin
frmActions.richEdtFlow.Lines.Add('# WE DID NOT GET PAID :(');
if (Spi.CurrentTxFlowState.Response <> nil) then
begin
purchaseResponse := ComWrapper.PurchaseResponseInit(
Spi.CurrentTxFlowState.Response);
frmActions.richEdtFlow.Lines.Add('# Error: ' +
Spi.CurrentTxFlowState.Response.GetError);
frmActions.richEdtFlow.Lines.Add('# Response: ' +
purchaseResponse.GetResponseText);
frmActions.richEdtFlow.Lines.Add('# RRN: ' +
purchaseResponse.GetRRN);
frmActions.richEdtFlow.Lines.Add('# Scheme: ' +
purchaseResponse.SchemeName);
frmActions.richEdtFlow.Lines.Add('# Customer Receipt:');
frmMain.richEdtReceipt.Lines.Add
(TrimLeft(purchaseResponse.GetCustomerReceipt));
end;
end;
TransactionType_Refund:
begin
frmActions.richEdtFlow.Lines.Add('# REFUND FAILED!');
if (Spi.CurrentTxFlowState.Response <> nil) then
begin
frmActions.richEdtFlow.Lines.Add('# Error: ' +
Spi.CurrentTxFlowState.Response.GetError);
refundResponse := ComWrapper.RefundResponseInit(
Spi.CurrentTxFlowState.Response);
frmActions.richEdtFlow.Lines.Add('# Response: ' +
refundResponse.GetResponseText);
frmActions.richEdtFlow.Lines.Add('# RRN: ' +
refundResponse.GetRRN);
frmActions.richEdtFlow.Lines.Add('# Scheme: ' +
refundResponse.SchemeName);
frmActions.richEdtFlow.Lines.Add('# Customer Receipt:');
frmMain.richEdtReceipt.Lines.Add
(TrimLeft(refundResponse.GetCustomerReceipt));
end;
end;
TransactionType_Settle:
begin
frmActions.richEdtFlow.Lines.Add('# SETTLEMENT FAILED!');
if (Spi.CurrentTxFlowState.Response <> nil) then
begin
settleResponse := ComWrapper.SettlementInit(
Spi.CurrentTxFlowState.Response);
frmActions.richEdtFlow.Lines.Add('# Response: ' +
settleResponse.GetResponseText);
frmActions.richEdtFlow.Lines.Add('# Error: ' +
Spi.CurrentTxFlowState.Response.GetError);
frmActions.richEdtFlow.Lines.Add('# Merchant Receipt:');
frmMain.richEdtReceipt.Lines.Add(
TrimLeft(settleResponse.GetReceipt));
end;
end;
end;
SuccessState_Unknown:
case Spi.CurrentTxFlowState.type_ of
TransactionType_Purchase:
begin
frmActions.richEdtFlow.Lines.Add(
'# WE''RE NOT QUITE SURE WHETHER WE GOT PAID OR NOT :/');
frmActions.richEdtFlow.Lines.Add(
'# CHECK THE LAST TRANSACTION ON THE EFTPOS ITSELF FROM THE APPROPRIATE MENU ITEM.');
frmActions.richEdtFlow.Lines.Add(
'# IF YOU CONFIRM THAT THE CUSTOMER PAID, CLOSE THE ORDER.');
frmActions.richEdtFlow.Lines.Add(
'# OTHERWISE, RETRY THE PAYMENT FROM SCRATCH.');
end;
TransactionType_Refund:
begin
frmActions.richEdtFlow.Lines.Add(
'# WE''RE NOT QUITE SURE WHETHER THE REFUND WENT THROUGH OR NOT :/');
frmActions.richEdtFlow.Lines.Add(
'# CHECK THE LAST TRANSACTION ON THE EFTPOS ITSELF FROM THE APPROPRIATE MENU ITEM.');
frmActions.richEdtFlow.Lines.Add(
'# YOU CAN THE TAKE THE APPROPRIATE ACTION.');
end;
end;
end;
end;
end;
frmActions.richEdtFlow.Lines.Add(
'# --------------- STATUS ------------------');
frmActions.richEdtFlow.Lines.Add(
'# ' + _posId + ' <-> Eftpos: ' + _eftposAddress + ' #');
frmActions.richEdtFlow.Lines.Add(
'# SPI STATUS: ' + ComWrapper.GetSpiStatusEnumName(Spi.CurrentStatus) +
' FLOW: ' + ComWrapper.GetSpiFlowEnumName(Spi.CurrentFlow) + ' #');
frmActions.richEdtFlow.Lines.Add(
'# ----------------TABLES-------------------');
frmActions.richEdtFlow.Lines.Add(
'# Open Tables: ' + IntToStr(tableToBillMappingDict.Count));
frmActions.richEdtFlow.Lines.Add(
'# Bills in Store: ' + IntToStr(billsStoreDict.Count));
frmActions.richEdtFlow.Lines.Add(
'# Assembly Bills: ' + IntToStr(assemblyBillDataStoreDict.Count));
frmActions.richEdtFlow.Lines.Add(
'# -----------------------------------------');
frmActions.richEdtFlow.Lines.Add(
'# POS: v' + ComWrapper.GetPosVersion + ' Spi: v' +
ComWrapper.GetSpiVersion);
end;
procedure PrintStatusAndActions();
begin
frmMain.lblStatus.Caption := ComWrapper.GetSpiStatusEnumName
(Spi.CurrentStatus) + ':' + ComWrapper.GetSpiFlowEnumName(Spi.CurrentFlow);
case Spi.CurrentStatus of
SpiStatus_Unpaired:
case Spi.CurrentFlow of
SpiFlow_Idle:
begin
if Assigned(frmActions) then
begin
frmActions.lblFlowMessage.Caption := 'Unpaired';
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK-Unpaired';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
frmMain.lblStatus.Color := clRed;
exit;
end;
end;
SpiFlow_Pairing:
begin
if (Spi.CurrentPairingFlowState.AwaitingCheckFromPos) then
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Confirm Code';
frmActions.btnAction2.Visible := True;
frmActions.btnAction2.Caption := 'Cancel Pairing';
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
exit;
end
else if (not Spi.CurrentPairingFlowState.Finished) then
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Cancel Pairing';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
exit;
end
else
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
end;
end;
SpiFlow_Transaction:
begin
exit;
end;
else
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
frmActions.richEdtFlow.Lines.Clear;
frmActions.richEdtFlow.Lines.Add('# .. Unexpected Flow .. ' +
ComWrapper.GetSpiFlowEnumName(Spi.CurrentFlow));
exit;
end;
end;
SpiStatus_PairedConnecting:
case Spi.CurrentFlow of
SpiFlow_Idle:
begin
frmMain.btnPair.Caption := 'UnPair';
frmMain.pnlTableActions.Visible := True;
frmMain.pnlOtherActions.Visible := True;
frmMain.lblStatus.Color := clYellow;
frmActions.lblFlowMessage.Caption := '# --> SPI Status Changed: ' +
ComWrapper.GetSpiStatusEnumName(spi.CurrentStatus);
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
exit;
end;
SpiFlow_Transaction:
begin
if (Spi.CurrentTxFlowState.AwaitingSignatureCheck) then
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Accept Signature';
frmActions.btnAction2.Visible := True;
frmActions.btnAction2.Caption := 'Decline Signature';
frmActions.btnAction3.Visible := True;
frmActions.btnAction3.Caption := 'Cancel';
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
exit;
end
else if (not Spi.CurrentTxFlowState.Finished) then
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Cancel';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
exit;
end
else
begin
case Spi.CurrentTxFlowState.Success of
SuccessState_Success:
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
exit;
end;
SuccessState_Failed:
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Retry';
frmActions.btnAction2.Visible := True;
frmActions.btnAction2.Caption := 'Cancel';
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
exit;
end;
else
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
exit;
end;
end;
end;
end;
SpiFlow_Pairing:
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
exit;
end;
else
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
frmActions.richEdtFlow.Lines.Clear;
frmActions.richEdtFlow.Lines.Add('# .. Unexpected Flow .. ' +
ComWrapper.GetSpiFlowEnumName(Spi.CurrentFlow));
exit;
end;
SpiStatus_PairedConnected:
case Spi.CurrentFlow of
SpiFlow_Idle:
begin
frmMain.btnPair.Caption := 'UnPair';
frmMain.pnlTableActions.Visible := True;
frmMain.pnlOtherActions.Visible := True;
frmMain.lblStatus.Color := clGreen;
frmActions.lblFlowMessage.Caption := '# --> SPI Status Changed: ' +
ComWrapper.GetSpiStatusEnumName(spi.CurrentStatus);
if (frmActions.btnAction1.Caption = 'Retry') then
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
end;
exit;
end;
SpiFlow_Transaction:
begin
if (Spi.CurrentTxFlowState.AwaitingSignatureCheck) then
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Accept Signature';
frmActions.btnAction2.Visible := True;
frmActions.btnAction2.Caption := 'Decline Signature';
frmActions.btnAction3.Visible := True;
frmActions.btnAction3.Caption := 'Cancel';
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
exit;
end
else if (not Spi.CurrentTxFlowState.Finished) then
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Cancel';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
exit;
end
else
begin
case Spi.CurrentTxFlowState.Success of
SuccessState_Success:
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
exit;
end;
SuccessState_Failed:
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Retry';
frmActions.btnAction2.Visible := True;
frmActions.btnAction2.Caption := 'Cancel';
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
exit;
end;
else
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
exit;
end;
end;
end;
end;
SpiFlow_Pairing:
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
exit;
end;
else
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
frmActions.richEdtFlow.Lines.Clear;
frmActions.richEdtFlow.Lines.Add('# .. Unexpected Flow .. ' +
ComWrapper.GetSpiFlowEnumName(Spi.CurrentFlow));
exit;
end;
else
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
frmActions.richEdtFlow.Lines.Clear;
frmActions.richEdtFlow.Lines.Add('# .. Unexpected Flow .. ' +
ComWrapper.GetSpiFlowEnumName(Spi.CurrentFlow));
exit;
end;
end;
procedure TxFlowStateChanged(e: SPIClient_TLB.TransactionFlowState); stdcall;
begin
if (not Assigned(frmActions)) then
begin
frmActions := frmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.Show;
frmActions.richEdtFlow.Lines.Clear();
PrintFlowInfo;
TMyWorkerThread.Create(false);
end;
procedure PairingFlowStateChanged(e: SPIClient_TLB.PairingFlowState); stdcall;
begin
if (not Assigned(frmActions)) then
begin
frmActions := TfrmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.Show;
frmActions.richEdtFlow.Lines.Clear();
frmActions.lblFlowMessage.Caption := e.Message;
if (e.ConfirmationCode <> '') then
begin
frmActions.richEdtFlow.Lines.Add('# Confirmation Code: ' +
e.ConfirmationCode);
end;
PrintFlowInfo;
TMyWorkerThread.Create(false);
end;
procedure SecretsChanged(e: SPIClient_TLB.Secrets); stdcall;
begin
SpiSecrets := e;
frmMain.btnSecretsClick(frmMain.btnSecrets);
end;
procedure SpiStatusChanged(e: SPIClient_TLB.SpiStatusEventArgs); stdcall;
begin
if (not Assigned(frmActions)) then
begin
frmActions := TfrmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.Show;
frmActions.lblFlowMessage.Caption := 'It''s trying to connect';
if (Spi.CurrentFlow = SpiFlow_Idle) then
frmActions.richEdtFlow.Lines.Clear();
PrintFlowInfo;
TMyWorkerThread.Create(false);
end;
procedure TMyWorkerThread.Execute;
begin
Synchronize(procedure begin
PrintStatusAndActions;
end
);
end;
procedure PayAtTableGetBillDetails(billStatusInfo: SPIClient_TLB.BillStatusInfo;
out billStatus: SPIClient_TLB.BillStatusResponse) stdcall;
var
billData, billIdStr, tableIdStr, operatorIdStr: WideString;
exit1: Boolean;
begin
billStatus := CreateComObject(CLASS_BillStatusResponse)
AS SPIClient_TLB.BillStatusResponse;
exit1 := False;
billIdStr := billStatusInfo.BillId;
tableIdStr := billStatusInfo.TableId;
operatorIdStr := billStatusInfo.OperatorId;
if (billIdStr = '') then
begin
//We were not given a billId, just a tableId.
//This means that we are being asked for the bill by its table number.
//Let's see if we have it.
if (not tableToBillMappingDict.ContainsKey(tableIdStr)) then
begin
//We didn't find a bill for this table.
//We just tell the Eftpos that.
billStatus.Result := BillRetrievalResult_INVALID_TABLE_ID;
exit1 := True;
end
else
begin
//We have a billId for this Table.
//et's set it so we can retrieve it.
billIdStr := tableToBillMappingDict[tableIdStr];
end;
end;
if (not exit1) then
begin
if (not billsStoreDict.ContainsKey(billIdStr)) then
begin
//We could not find the billId that was asked for.
//We just tell the Eftpos that.
billStatus.Result := BillRetrievalResult_INVALID_BILL_ID;
end
else
begin
billStatus.Result := BillRetrievalResult_SUCCESS;
billStatus.BillId := billIdStr;
billStatus.TableId := tableIdStr;
billStatus.TotalAmount := billsStoreDict[billIdStr].TotalAmount;
billStatus.OutstandingAmount :=
billsStoreDict[billIdStr].OutstandingAmount;
assemblyBillDataStoreDict.TryGetValue(billIdStr, billData);
billStatus.BillData := billData;
end;
end;
end;
procedure PayAtTableBillPaymentReceived(billPaymentInfo:
SPIClient_TLB.BillPaymentInfo; out billStatus:
SPIClient_TLB.BillStatusResponse) stdcall;
var
updatedBillDataStr: WideString;
billPayment: SPIClient_TLB.BillPayment;
totalAmount, outstandingAmount, tippedAmount: Single;
begin
billStatus := CreateComObject(CLASS_BillStatusResponse)
AS SPIClient_TLB.BillStatusResponse;
billPayment := CreateComObject(CLASS_BillPayment)
AS SPIClient_TLB.BillPayment;
billPayment := billPaymentInfo.BillPayment;
updatedBillDataStr := billPaymentInfo.UpdatedBillData;
if (not billsStoreDict.ContainsKey(billPayment.BillId)) then
begin
billStatus.Result := BillRetrievalResult_INVALID_BILL_ID;
end
else
begin
if (not Assigned(frmActions)) then
begin
frmActions := TfrmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.richEdtFlow.Lines.Add('# Got a ' +
ComWrapper.GetPaymentTypeEnumName(billPayment.PaymentType) +
' Payment against bill ' + billPayment.BillId + ' for table ' +
billPayment.TableId);
billsStoreDict[billPayment.BillId].OutstandingAmount :=
billsStoreDict[billPayment.BillId].OutstandingAmount -
billPayment.PurchaseAmount;
billsStoreDict[billPayment.BillId].tippedAmount :=
billsStoreDict[billPayment.BillId].tippedAmount + billPayment.TipAmount;
totalAmount := billsStoreDict[billPayment.BillId].TotalAmount / 100;
outstandingAmount :=
billsStoreDict[billPayment.BillId].OutstandingAmount / 100;
tippedAmount := billsStoreDict[billPayment.BillId].tippedAmount / 100;
frmActions.richEdtFlow.Lines.Add('Updated Bill: ' +
billsStoreDict[billPayment.BillId].BillId + ' - Table:$' +
billsStoreDict[billPayment.BillId].TableId + ' Total:$' +
CurrToStr(totalAmount) + ' Outstanding:$' + CurrToStr(outstandingAmount) +
' Tips:$' + CurrToStr(tippedAmount));
if(not assemblyBillDataStoreDict.ContainsKey(billPayment.BillId)) Then
begin
assemblyBillDataStoreDict.Add(billPayment.BillId, updatedBillDataStr);
end
else
begin
assemblyBillDataStoreDict[billPayment.BillId] := updatedBillDataStr;
end;
billStatus.Result := BillRetrievalResult_SUCCESS;
billStatus.TotalAmount := billsStoreDict[billPayment.BillId].TotalAmount;
billStatus.OutstandingAmount :=
billsStoreDict[billPayment.BillId].OutstandingAmount;
frmActions.Show;
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
frmMain.Enabled := False;
end;
end;
procedure Start;
begin
LoadPersistedState;
_posId := frmMain.edtPosID.Text;
_eftposAddress := frmMain.edtEftposAddress.Text;
Spi := ComWrapper.SpiInit(_posId, _eftposAddress, SpiSecrets);
SpiPayAtTable := Spi.EnablePayAtTable;
SpiPayAtTable.Config.LabelTableId := 'Table Number';
ComWrapper.Main_2(Spi, SpiPayAtTable, LongInt(@TxFlowStateChanged),
LongInt(@PairingFlowStateChanged), LongInt(@SecretsChanged),
LongInt(@SpiStatusChanged), LongInt(@PayAtTableGetBillDetails),
LongInt(@PayAtTableBillPaymentReceived));
Spi.Start;
TMyWorkerThread.Create(false);
end;
procedure TfrmMain.btnOpenClick(Sender: TObject);
begin
if (not Assigned(frmActions)) then
begin
frmActions := frmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.Show;
frmActions.richEdtFlow.Lines.Clear();
frmActions.lblFlowMessage.Caption :=
'Please enter the table id you would like to open';
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Open';
frmActions.btnAction2.Visible := True;
frmActions.btnAction2.Caption := 'Cancel';
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := True;
frmActions.lblTableId.Caption := 'Table Id:';
frmActions.edtTableId.Visible := True;
frmActions.edtTableId.Text := '';
frmMain.Enabled := False;
end;
procedure TfrmMain.btnCloseClick(Sender: TObject);
begin
if (not Assigned(frmActions)) then
begin
frmActions := frmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.Show;
frmActions.richEdtFlow.Lines.Clear();
frmActions.lblFlowMessage.Caption :=
'Please enter the table id you would like to close';
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Close';
frmActions.btnAction2.Visible := True;
frmActions.btnAction2.Caption := 'Cancel';
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := True;
frmActions.lblTableId.Caption := 'Table Id:';
frmActions.edtTableId.Visible := True;
frmActions.edtTableId.Text := '';
frmMain.Enabled := False;
end;
procedure TfrmMain.btnGetBillClick(Sender: TObject);
begin
if (not Assigned(frmActions)) then
begin
frmActions := frmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.Show;
frmActions.richEdtFlow.Lines.Clear();
frmActions.lblFlowMessage.Caption :=
'Please enter the table id you would like to print bill';
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Get Bill';
frmActions.btnAction2.Visible := True;
frmActions.btnAction2.Caption := 'Cancel';
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := True;
frmActions.lblTableId.Caption := 'Table Id:';
frmActions.edtTableId.Visible := True;
frmActions.edtTableId.Text := '';
frmMain.Enabled := False;
end;
procedure TfrmMain.btnListTablesClick(Sender: TObject);
var
i: Integer;
openTables, openBills, openAssemblyBill: WideString;
Key: WideString;
begin
if (not Assigned(frmActions)) then
begin
frmActions := frmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.Show;
frmActions.richEdtFlow.Lines.Clear();
frmActions.lblFlowMessage.Caption := 'List of Tables';
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
frmMain.Enabled := False;
if (tableToBillMappingDict.Count > 0) then
begin
for Key in tableToBillMappingDict.Keys do
begin
if (openTables <> '') then
begin
openTables := opentables + ',';
end;
openTables := openTables + Key;
end;
frmActions.richEdtFlow.Lines.Add('# Open Tables: ' + openTables);
end
else
begin
frmActions.richEdtFlow.Lines.Add('# No Open Tables.');
end;
if (billsStoreDict.Count > 0) then
begin
for Key in billsStoreDict.Keys do
begin
if (openBills <> '') then
begin
openBills := openBills + ',';
end;
openBills := openBills + Key;
end;
frmActions.richEdtFlow.Lines.Add('# My Bills Store: ' + openBills);
end;
if (assemblyBillDataStoreDict.Count > 0) then
begin
for Key in assemblyBillDataStoreDict.Keys do
begin
if (openAssemblyBill <> '') then
begin
openAssemblyBill := openAssemblyBill + ',';
end;
openAssemblyBill := openAssemblyBill + Key;
end;
frmActions.richEdtFlow.Lines.Add('# Assembly Bills Data: ' +
openAssemblyBill);
end;
end;
procedure TfrmMain.btnAddClick(Sender: TObject);
begin
if (not Assigned(frmActions)) then
begin
frmActions := frmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.Show;
frmActions.richEdtFlow.Lines.Clear();
frmActions.lblFlowMessage.Caption :=
'Please enter the table id you would like to add';
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Add';
frmActions.btnAction2.Visible := True;
frmActions.btnAction2.Caption := 'Cancel';
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := True;
frmActions.edtAmount.Visible := True;
frmActions.edtAmount.Text := '0';
frmActions.lblTableId.Visible := True;
frmActions.lblTableId.Caption := 'Table Id:';
frmActions.edtTableId.Text := '';
frmActions.edtTableId.Visible := True;
frmActions.edtTableId.Text := '';
frmMain.Enabled := False;
end;
procedure TfrmMain.btnPrintBillClick(Sender: TObject);
begin
if (not Assigned(frmActions)) then
begin
frmActions := frmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.Show;
frmActions.richEdtFlow.Lines.Clear();
frmActions.lblFlowMessage.Caption :=
'Please enter the bill id you would like to print bill for in cents';
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Print Bill';
frmActions.btnAction2.Visible := True;
frmActions.btnAction2.Caption := 'Cancel';
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := True;
frmActions.lblTableId.Caption := 'Bill Id:';
frmActions.edtTableId.Visible := True;
frmActions.edtTableId.Text := '';
frmMain.Enabled := False;
end;
procedure TfrmMain.btnPairClick(Sender: TObject);
begin
if (btnPair.Caption = 'Pair') then
begin
Spi.Pair;
btnSecrets.Visible := True;
edtPosID.Enabled := False;
edtEftposAddress.Enabled := False;
frmMain.lblStatus.Color := clYellow;
end
else if (btnPair.Caption = 'UnPair') then
begin
Spi.Unpair;
frmMain.btnPair.Caption := 'Pair';
frmMain.pnlTableActions.Visible := False;
frmMain.pnlOtherActions.Visible := False;
edtSecrets.Text := '';
lblStatus.Color := clRed;
end;
end;
procedure TfrmMain.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if (FormExists(frmActions)) then
begin
frmActions.Close;
end;
PersistState;
Action := caFree;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
ComWrapper := CreateComObject(CLASS_ComWrapper) AS SPIClient_TLB.ComWrapper;
Spi := CreateComObject(CLASS_Spi) AS SPIClient_TLB.Spi;
SpiSecrets := CreateComObject(CLASS_Secrets) AS SPIClient_TLB.Secrets;
SpiPayAtTable := CreateComObject(CLASS_SpiPayAtTable)
AS SPIClient_TLB.SpiPayAtTable;
SpiSecrets := nil;
frmMain.edtPosID.Text := 'DELPHIPOS';
lblStatus.Color := clRed;
end;
procedure TfrmMain.btnPurchaseClick(Sender: TObject);
begin
if (not Assigned(frmActions)) then
begin
frmActions := frmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.Show;
frmActions.richEdtFlow.Lines.Clear();
frmActions.lblFlowMessage.Caption :=
'Please enter the amount you would like to purchase for in cents';
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Purchase';
frmActions.btnAction2.Visible := True;
frmActions.btnAction2.Caption := 'Cancel';
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := True;
frmActions.edtAmount.Visible := True;
frmActions.edtAmount.Text := '0';
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
frmMain.Enabled := False;
end;
procedure TfrmMain.btnRefundClick(Sender: TObject);
begin
if (not Assigned(frmActions)) then
begin
frmActions := frmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.Show;
frmActions.richEdtFlow.Lines.Clear();
frmActions.lblFlowMessage.Caption :=
'Please enter the amount you would like to refund for in cents';
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Refund';
frmActions.btnAction2.Visible := True;
frmActions.btnAction2.Caption := 'Cancel';
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := True;
frmActions.edtAmount.Visible := True;
frmActions.edtAmount.Text := '0';
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
frmMain.Enabled := False;
end;
procedure TfrmMain.btnSaveClick(Sender: TObject);
begin
Start;
btnSave.Enabled := False;
if (edtPosID.Text = '') or (edtEftposAddress.Text = '') then
begin
showmessage('Please fill the parameters');
exit;
end;
Spi.SetPosId(edtPosID.Text);
Spi.SetEftposAddress(edtEftposAddress.Text);
frmMain.pnlStatus.Visible := True;
end;
procedure TfrmMain.btnSecretsClick(Sender: TObject);
begin
if (not Assigned(frmActions)) then
begin
frmActions := frmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.richEdtFlow.Clear;
if (SpiSecrets <> nil) then
begin
frmActions.richEdtFlow.Lines.Add('Pos Id: ' + _posId);
frmActions.richEdtFlow.Lines.Add('Eftpos Address: ' + _eftposAddress);
frmActions.richEdtFlow.Lines.Add('Secrets: ' + SpiSecrets.encKey + ':' +
SpiSecrets.hmacKey);
end
else
begin
frmActions.richEdtFlow.Lines.Add('I have no secrets!');
end;
frmActions.Show;
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
frmMain.Enabled := False;
end;
procedure TfrmMain.btnSettleClick(Sender: TObject);
var
settleres: SPIClient_TLB.InitiateTxResult;
begin
if (not Assigned(frmActions)) then
begin
frmActions := frmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.Show;
frmActions.richEdtFlow.Lines.Clear();
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Cancel';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
frmMain.Enabled := False;
settleres := CreateComObject(CLASS_InitiateTxResult)
AS SPIClient_TLB.InitiateTxResult;
settleres := Spi.InitiateSettleTx(ComWrapper.Get_Id('settle'));
if (settleres.Initiated) then
begin
frmActions.richEdtFlow.Lines.Add
('# Settle Initiated. Will be updated with Progress.');
end
else
begin
frmActions.richEdtFlow.Lines.Add('# Could not initiate settlement: ' +
settleres.Message + '. Please Retry.');
end;
end;
procedure TfrmMain.OpenTable;
var
newBill: TBill;
billId, tableId: WideString;
begin
frmActions.richEdtFlow.Lines.Clear();
tableId := frmActions.edtTableId.Text;
if (tableToBillMappingDict.ContainsKey(tableId)) then
begin
billId := tableToBillMappingDict[tableId];
frmActions.richEdtFlow.Lines.Add('Table Already Open: ' +
BillToString(billsStoreDict[billId]));
end
else
begin
newBill := TBill.Create;
newBill.BillId := ComWrapper.NewBillId;
newBill.TableId := frmActions.edtTableId.Text;
billsStoreDict.Add(newBill.BillId, newBill);
tableToBillMappingDict.Add(newBill.TableId, newBill.BillId);
frmActions.richEdtFlow.Lines.Add('Opened: ' + BillToString(newBill));
end;
frmActions.Show;
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
frmMain.Enabled := False;
end;
procedure TfrmMain.CloseTable;
var
billId, tableId: WideString;
begin
frmActions.richEdtFlow.Lines.Clear();
tableId := frmActions.edtTableId.Text;
if (not tableToBillMappingDict.ContainsKey(tableId)) then
begin
frmActions.richEdtFlow.Lines.Add('Table not Open.');
end
else
begin
billId := tableToBillMappingDict[tableId];
if (billsStoreDict[billId].OutstandingAmount > 0) then
begin
frmActions.richEdtFlow.Lines.Add('Bill not Paid Yet: ' +
BillToString(billsStoreDict[billId]));
end
else
begin
tableToBillMappingDict.Remove(tableId);
assemblyBillDataStoreDict.Remove(billId);
frmActions.richEdtFlow.Lines.Add('Closed: ' +
BillToString(billsStoreDict[billId]));
end;
end;
frmActions.Show;
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
frmMain.Enabled := False;
end;
procedure TfrmMain.AddToTable;
var
billId, tableId: WideString;
amountCents: Integer;
begin
frmActions.richEdtFlow.Lines.Clear();
tableId := frmActions.edtTableId.Text;
integer.TryParse(frmActions.edtAmount.Text, amountCents);
if (not tableToBillMappingDict.ContainsKey(tableId)) then
begin
frmActions.richEdtFlow.Lines.Add('Table not Open.');
end
else
begin
billId := tableToBillMappingDict[tableId];
billsStoreDict[billId].TotalAmount := billsStoreDict[billId].TotalAmount +
amountCents;
billsStoreDict[billId].OutstandingAmount :=
billsStoreDict[billId].OutstandingAmount + amountCents;
frmActions.richEdtFlow.Lines.Add('Updated: ' +
BillToString(billsStoreDict[billId]));
end;
frmActions.Show;
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
frmMain.Enabled := False;
end;
procedure TfrmMain.PrintBill(billId: WideString);
begin
frmActions.richEdtFlow.Lines.Clear();
if (billId = '') then
begin
billId := frmActions.edtTableId.Text;
end;
if (not billsStoreDict.ContainsKey(billId)) then
begin
frmActions.richEdtFlow.Lines.Add('Bill not Open.');
end
else
begin
frmActions.richEdtFlow.Lines.Add('Bill: ' +
BillToString(billsStoreDict[billId]));
end;
frmActions.Show;
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
frmMain.Enabled := False;
end;
procedure TfrmMain.GetBill;
var
tableId: WideString;
begin
frmActions.richEdtFlow.Lines.Clear();
tableId := frmActions.edtTableId.Text;
if (not tableToBillMappingDict.ContainsKey(tableId)) then
begin
frmActions.richEdtFlow.Lines.Add('Table not Open.');
end
else
begin
PrintBill(tableToBillMappingDict[tableId]);
end;
frmActions.Show;
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.lblTableId.Visible := False;
frmActions.edtTableId.Visible := False;
frmMain.Enabled := False;
end;
end.
|
program test;
type
nodePtr = ^listElement;
listElement = record
val : Integer;
Prev : nodePtr;
Next : nodePtr;
end;
List = RECORD
first: nodePtr;
last: nodePtr;
END;
function NewNode(val : Integer) : nodePtr;
var temp : nodePtr;
begin
New(temp);
temp^.val := val;
temp^.prev := Nil;
temp^.next := Nil;
NewNode := temp;
end;
procedure initList(var l : List);
begin
l.first := Nil;
l.last := Nil;
end;
procedure Prepend(var l : List; val : Integer);
var n : nodePtr;
begin
n := NewNode(val);
if (l.first = Nil) then
begin
l.first := n;
l.last := n;
end
else
begin
n^.next := l.first;
l.first^.prev := n;
l.first := n;
end;
end;
procedure Prepend2(var l : List; node : nodePtr);
begin
if(l.first = Nil) then
begin
l.first := node;
l.last := node;
end
else
begin
node^.prev := Nil;
node^.next := l.first;
l.first^.prev := node;
l.first := node;
end;
end;
procedure Append(var l : List; val : Integer);
var n : nodePtr;
begin
n := NewNode(val);
if (l.first = Nil) then
begin
l.first := n;
l.last := n;
end
else
begin
n^.prev := l.last;
l.last^.next := n;
l.last := n;
end;
end;
procedure Reverse(var l : List);
var n : nodePtr;
var temp : List;
begin
initList(temp);
n := l.last;
while n <> Nil do
begin
Append(temp,n^.val);
n := n^.prev;
end;
l := temp;
end;
procedure PrintList(l : List);
var n : nodePtr;
begin
n := l.first;
write('List: ');
while n <> Nil do
begin
Write(n^.val);
n := n^.next;
end;
WriteLn;
end;
var l : List;
begin
initList(l);
Append(l,1);
Append(l,2);
Append(l,3);
Append(l,4);
Append(l,5);
Prepend(l,1);
Prepend(l,7);
PrintList(l);
Reverse(l);
PrintList(l);
end. |
unit RashChart;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, TeEngine, Series, DB, MemDS, DBAccess, Ora, ExtCtrls, TeeProcs,
Chart, DBChart, StdCtrls, Mask, ToolEdit, Math, UDbFunc;
type
TRashChartForm = class(TForm)
Chart: TDBChart;
qChart: TOraQuery;
pnlFilters: TPanel;
pnlChartDate: TPanel;
lblBeginDate: TLabel;
lblEndDate: TLabel;
deBeginDate: TDateEdit;
deEndDate: TDateEdit;
OutSeries: TLineSeries;
OutReducedSeries: TLineSeries;
DiffSeries: TLineSeries;
TempSeries: TLineSeries;
lblTitleChart: TLabel;
procedure FormShow(Sender: TObject);
procedure deBeginDateChange(Sender: TObject);
private
FFuelId: integer;
procedure SetFuelId(const Value: integer);
public
property FuelId: integer read FFuelId write SetFuelId;
procedure RefreshData;
end;
var
RashChartForm: TRashChartForm;
implementation
{$R *.dfm}
procedure TRashChartForm.FormShow(Sender: TObject);
begin
RefreshData;
end;
procedure TRashChartForm.RefreshData;
begin
qChart.Close;
qChart.ParamByName('BeginDate').AsDateTime := deBeginDate.Date;
qChart.ParamByName('EndDate').AsDateTime := deEndDate.Date;
qChart.ParamByName('fuel_id').AsInteger := FuelId;
qChart.Open;
end;
procedure TRashChartForm.deBeginDateChange(Sender: TObject);
begin
RefreshData;
end;
procedure TRashChartForm.SetFuelId(const Value: integer);
begin
lblTitleChart.Caption := Format('Разница при отпуске топлива %s',[GetNpGName(Value)]);
FFuelId := Value;
end;
end.
|
program HowToUseAnimationWithMultipleSprites;
uses
SwinGame, sgTypes;
procedure Main();
var
myFrog, myLizard: Sprite;
begin
OpenAudio();
OpenGraphicsWindow('Dance', 800, 600);
LoadResourceBundle('dance_bundle.txt');
myFrog := CreateSprite(BitmapNamed('FrogBmp'), AnimationScriptNamed('WalkingScript'));
SpriteStartAnimation(myFrog, 'Dance');
SpriteSetX(myFrog, 496);
SpriteSetY(myFrog, 250);
myLizard := CreateSprite(BitmapNamed('LizardBmp'), AnimationScriptNamed('WalkingScript'));
SpriteStartAnimation(myLizard, 'Dance');
SpriteSetX(myLizard, 238);
SpriteSetY(myLizard, 272);
repeat
ClearScreen(ColorWhite);
DrawSprite(myFrog);
DrawSprite(myLizard);
RefreshScreen(60);
UpdateSprite(myFrog);
UpdateSprite(myLizard);
ProcessEvents();
until WindowCloseRequested();
FreeSprite(myLizard);
FreeSprite(myFrog);
CloseAudio();
ReleaseAllResources();
end;
begin
Main();
end. |
unit uAssociatedIcons;
interface
uses
Winapi.Windows,
Winapi.ActiveX,
Winapi.ShlObj,
System.Classes,
System.SysUtils,
System.Win.Registry,
Vcl.Graphics,
Vcl.Forms,
Dmitry.Utils.ShellIcons,
uConstants,
uRWLock,
uMemory;
type
TAssociatedIcons = record
Icon: TIcon;
Ext: String;
SelfIcon: Boolean;
Size: Integer;
end;
TAIcons = class(TObject)
private
FAssociatedIcons: array of TAssociatedIcons;
FIDesktopFolder: IShellFolder;
UnLoadingListEXT : TStringList;
FSync: IReadWriteSync;
procedure Initialize;
public
class function Instance: TAIcons;
constructor Create;
destructor Destroy; override;
function IsExt(Ext: string; Size: Integer): Boolean;
function AddIconByExt(FileName, Ext: string; Size: Integer): Integer;
function GetIconByExt(FileName: String; IsFolder: Boolean; Size: Integer; Default: Boolean): TIcon;
function GetShellImage(Path: String; Size: Integer): TIcon;
function IsVarIcon(FileName: String; Size: Integer): Boolean;
procedure Clear;
function SetPath(const Value: string): PItemIDList;
end;
function VarIco(Ext: string): Boolean;
function IsVideoFile(FileName: string): Boolean;
implementation
uses ExplorerTypes;
var
AIcons: TAIcons = nil;
function IsVideoFile(FileName: string): Boolean;
begin
Result := Pos(AnsiLowerCase(ExtractFileExt(FileName)), cVideoFileExtensions) > 0;
end;
{ TAIcons }
function VarIco(Ext: string): Boolean;
var
Reg: TRegistry;
S: string;
I: integer;
begin
Result := False;
if (Ext = '') or (Ext = '.scr') or (Ext = '.exe') then
begin
Result := True;
Exit;
end;
Reg := TRegistry.Create(KEY_READ);
try
Reg.RootKey := HKEY_CLASSES_ROOT;
if not Reg.OpenKey('\' + Ext, False) then
Exit;
S := Reg.ReadString('');
Reg.CloseKey;
if not Reg.OpenKey('\' + S + '\DefaultIcon', False) then
Exit;
S := Reg.ReadString('');
for I := Length(S) downto 1 do
if (S[I] = '''') or (S[I] = '"') or (S[I] = ' ') then
Delete(S, I, 1);
if S = '%1' then
Result := True;
finally
F(Reg);
end;
end;
function TAIcons.SetPath(const Value: string): PItemIDList;
var
P: PWideChar;
Flags,
NumChars: LongWord;
begin
Result := nil;
NumChars := Length(Value);
Flags := 0;
P := StringToOleStr(Value);
if not Succeeded(FIDesktopFolder.ParseDisplayName(Application.Handle,nil,P,NumChars,Result,Flags)) then
result := nil;
end;
function TAIcons.GetShellImage(Path: String; Size: integer): TIcon;
begin
Result := TIcon.Create;
Result.Handle := ExtractShellIcon(Path, Size);
end;
function TAIcons.AddIconByExt(FileName, EXT: string; Size : integer) : integer;
begin
FSync.BeginWrite;
try
Result := Length(FAssociatedIcons) - 1;
SetLength(FAssociatedIcons, Length(FAssociatedIcons) + 1);
FAssociatedIcons[Length(FAssociatedIcons) - 1].Ext := Ext;
FAssociatedIcons[Length(FAssociatedIcons) - 1].SelfIcon := VarIco(Ext);
FAssociatedIcons[Length(FAssociatedIcons) - 1].Icon := GetShellImage(FileName, Size);
FAssociatedIcons[Length(FAssociatedIcons) - 1].Size := Size;
finally
FSync.EndWrite;
end;
end;
constructor TAIcons.Create;
begin
if SHGetDesktopFolder(FIDesktopFolder) <> NOERROR then
raise Exception.Create('Error in call SHGetDesktopFolder!');
inherited;
FSync := CreateRWLock;
UnLoadingListEXT := TStringList.Create;
Initialize;
end;
destructor TAIcons.Destroy;
var
I: Integer;
begin
AIcons := nil;
for I := 0 to Length(FAssociatedIcons) - 1 do
FAssociatedIcons[I].Icon.Free;
SetLength(FAssociatedIcons, 0);
UnLoadingListEXT.Free;
FSync := nil;
inherited;
end;
function TAIcons.GetIconByExt(FileName: string; IsFolder: Boolean; Size: Integer; Default: Boolean): TIcon;
var
N, I: Integer;
Ext: string;
begin
Result := nil;
N := 0;
if IsFolder then
if Copy(FileName, 1, 2) = '\\' then
Default := True;
if IsFolder then
Ext := ''
else
Ext := AnsiLowerCase(ExtractFileExt(FileName));
if not IsExt(EXT, Size) and not default then
N := AddIconByExt(FileName, Ext, Size);
FSync.BeginRead;
try
for I := N to Length(FAssociatedIcons) - 1 do
if (FAssociatedIcons[I].Ext = Ext) and (FAssociatedIcons[I].Size = Size) then
begin
if (not FAssociatedIcons[I].SelfIcon) or default then
begin
if Size = 48 then
Result := TIcon48.Create
else
Result := TIcon.Create;
Result.Assign(FAssociatedIcons[I].Icon);
end else
Result := GetShellImage(FileName, Size);
Break;
end;
finally
FSync.EndRead;
end;
end;
function TAIcons.IsExt(Ext: string; Size: Integer): Boolean;
var
I: Integer;
begin
Result := False;
FSync.BeginRead;
try
for I := 0 to length(FAssociatedIcons) - 1 do
if (FAssociatedIcons[I].Ext = Ext) and (FAssociatedIcons[i].Size = Size) then
begin
Result := True;
Break;
end;
finally
FSync.EndRead;
end;
end;
function TAIcons.IsVarIcon(FileName: string; Size: Integer): Boolean;
var
I: Integer;
Ext: string;
begin
Result := False;
if Result then
Exit;
FSync.BeginRead;
try
Ext := AnsiLowerCase(ExtractFileExt(FileName));
for I := 0 to Length(FAssociatedIcons)-1 do
if (FAssociatedIcons[i].Ext = Ext) and (FAssociatedIcons[i].Size = Size) then
begin
Result := FAssociatedIcons[I].SelfIcon;
Exit;
end;
finally
FSync.EndRead;
end;
FSync.BeginWrite;
try
SetLength(FAssociatedIcons, Length(FAssociatedIcons) + 1);
FAssociatedIcons[Length(FAssociatedIcons) - 1].Ext := Ext;
FAssociatedIcons[Length(FAssociatedIcons) - 1].SelfIcon := VarIco(Ext);
if FAssociatedIcons[Length(FAssociatedIcons) - 1].SelfIcon then
begin
Result := True;
Exit;
end;
FAssociatedIcons[Length(FAssociatedIcons) - 1].Icon := GetShellImage(FileName, Size);
FAssociatedIcons[Length(FAssociatedIcons) - 1].Size := Size;
finally
FSync.EndWrite;
end;
end;
procedure TAIcons.Clear;
var
I: Integer;
begin
FSync.BeginWrite;
try
for I := 0 to length(FAssociatedIcons)-1 do
begin
if not FAssociatedIcons[I].SelfIcon then
FAssociatedIcons[I].Icon.Free;
end;
SetLength(FAssociatedIcons, 0);
Initialize;
finally
FSync.EndWrite;
end;
end;
procedure TAIcons.Initialize;
begin
SetLength(FAssociatedIcons, 3 * 4);
FAssociatedIcons[0].Ext := '';
FindIcon(HInstance, 'Directory', 16, 32, FAssociatedIcons[0].Icon);
FAssociatedIcons[0].SelfIcon := True;
FAssociatedIcons[0].Size := 16;
FAssociatedIcons[1].Ext := '';
FindIcon(HInstance, 'DIRECTORY', 32, 32, FAssociatedIcons[1].Icon);
FAssociatedIcons[1].SelfIcon := True;
FAssociatedIcons[1].Size := 32;
FAssociatedIcons[2].Ext := '';
FindIcon(HInstance, 'DIRECTORY', 48, 32, FAssociatedIcons[2].Icon);
FAssociatedIcons[2].SelfIcon := True;
FAssociatedIcons[2].Size := 48;
FAssociatedIcons[3].Ext := '.exe';
FindIcon(HInstance, 'EXEFILE', 16, 4, FAssociatedIcons[3].Icon);
FAssociatedIcons[3].SelfIcon := True;
FAssociatedIcons[3].Size := 16;
FAssociatedIcons[4].Ext := '.exe';
FindIcon(HInstance, 'EXEFILE', 32, 4, FAssociatedIcons[4].Icon);
FAssociatedIcons[4].SelfIcon := True;
FAssociatedIcons[4].Size := 32;
FAssociatedIcons[5].Ext := '.exe';
FindIcon(HInstance, 'EXEFILE', 48, 4, FAssociatedIcons[5].Icon);
FAssociatedIcons[5].SelfIcon := True;
FAssociatedIcons[5].Size := 48;
FAssociatedIcons[6].Ext := '.___';
FindIcon(HInstance, 'SIMPLEFILE', 16, 32, FAssociatedIcons[6].Icon);
FAssociatedIcons[6].SelfIcon := True;
FAssociatedIcons[6].Size := 16;
FAssociatedIcons[7].Ext := '.___';
FindIcon(HInstance, 'SIMPLEFILE', 32, 32, FAssociatedIcons[7].Icon);
FAssociatedIcons[7].SelfIcon := True;
FAssociatedIcons[7].Size := 32;
FAssociatedIcons[8].Ext := '.___';
FindIcon(HInstance, 'SIMPLEFILE', 48, 32, FAssociatedIcons[8].Icon);
FAssociatedIcons[8].SelfIcon := True;
FAssociatedIcons[8].Size := 48;
FAssociatedIcons[9].Ext := '.lnk';
FindIcon(HInstance, 'SIMPLEFILE', 16, 32, FAssociatedIcons[9].Icon);
FAssociatedIcons[9].SelfIcon := True;
FAssociatedIcons[9].Size := 48;
FAssociatedIcons[10].Ext := '.lnk';
FindIcon(HInstance, 'SIMPLEFILE', 32, 32, FAssociatedIcons[10].Icon);
FAssociatedIcons[10].SelfIcon := True;
FAssociatedIcons[10].Size := 32;
FAssociatedIcons[11].Ext := '.lnk';
FindIcon(HInstance, 'SIMPLEFILE', 48, 32, FAssociatedIcons[11].Icon); ;
FAssociatedIcons[11].SelfIcon := True;
FAssociatedIcons[11].Size := 16;
end;
class function TAIcons.Instance: TAIcons;
begin
if AIcons = nil then
AIcons := TAIcons.Create;
Result := AIcons;
end;
initialization
finalization
F(AIcons);
end.
|
unit fmSolverOptions;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls, Mask, ToolEdit, cxControls,
cxContainer, cxMCListBox, RXSplit;
type
TfmSolverOpt = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
bbOk: TBitBtn;
bbCancel: TBitBtn;
GroupBox1: TGroupBox;
rbCritStrict: TRadioButton;
rbCritAllow: TRadioButton;
rbCritAuto: TRadioButton;
gbDebug: TGroupBox;
edDir: TDirectoryEdit;
rbDebugNone: TRadioButton;
rbDebugNormal: TRadioButton;
rbDebugFull: TRadioButton;
Panel3: TPanel;
RxSplitter1: TRxSplitter;
lbDDMIs: TcxMCListBox;
Panel4: TPanel;
rgScope: TRadioGroup;
procedure FormCreate(Sender: TObject);
procedure rbDebugNoneClick(Sender: TObject);
procedure rgScopeClick(Sender: TObject);
private
{ Private declarations }
procedure PopulateDDMIListBox;
public
{ Public declarations }
end;
var
fmSolverOpt: TfmSolverOpt;
implementation
{$R *.dfm}
uses Solver;
procedure TfmSolverOpt.FormCreate(Sender: TObject);
var aDir: string;
begin
GetDir(0, aDir);
edDir.Text := aDir;
PopulateDDMIListBox;
end;
procedure TfmSolverOpt.rbDebugNoneClick(Sender: TObject);
begin
edDir.Enabled := not (rbDebugNone.Checked);
end;
procedure TfmSolverOpt.rgScopeClick(Sender: TObject);
begin
if rgScope.ItemIndex = 2 then
Panel3.Visible := true
else
Panel3.Visible := false;
end;
procedure TfmSolverOpt.PopulateDDMIListBox;
var i: integer;
aDDMI: pDDMIElem;
aTxt: string;
begin
for i:= 0 to globSolver.DDMIList.Count - 1 do begin
aDDMI := pDDMIElem(globSolver.DDMIList.Items[i]);
aTxt:=Format('%d;%d;%s;%s;%s', [aDDMI^.ddmi_nr,
Integer(aDDMI^.shift_no),
aDDMI^.dem_naziv,
aDDMI^.depa_opis,
aDDMI^.shift_desc]);
if aDDMI^.shift_no <> C_ODS_SHIFT_NO then
lbDDMIs.AddItem(aTxt, nil);
end;
end;
end.
|
{ ***************************************************************************
Copyright (c) 2016-2020 Kike Pérez
Unit : Quick.Logger.Provider.GrayLog
Description : Log GrayLog Provider
Author : Kike Pérez
Version : 1.2
Created : 15/03/2019
Modified : 25/04/2020
This file is part of QuickLogger: https://github.com/exilon/QuickLogger
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Logger.Provider.GrayLog;
{$i QuickLib.inc}
interface
uses
Classes,
SysUtils,
DateUtils,
{$IFDEF FPC}
fpjson,
fpjsonrtti,
{$ELSE}
{$IFDEF DELPHIXE8_UP}
System.JSON,
{$ELSE}
Data.DBXJSON,
{$ENDIF}
{$ENDIF}
Quick.HttpClient,
Quick.Commons,
Quick.Logger;
type
TLogGrayLogProvider = class (TLogProviderBase)
private
fHTTPClient : TJsonHTTPClient;
fURL : string;
fFullURL : string;
fGrayLogVersion : string;
fShortMessageAsEventType : Boolean;
fConnectionTimeout : Integer;
fResponseTimeout : Integer;
fUserAgent : string;
function LogToGELF(cLogItem: TLogItem): string;
function EventTypeToSysLogLevel(aEventType : TEventType) : Integer;
public
constructor Create; override;
destructor Destroy; override;
property URL : string read fURL write fURL;
property GrayLogVersion : string read fGrayLogVersion write fGrayLogVersion;
property ShortMessageAsEventType : Boolean read fShortMessageAsEventType write fShortMessageAsEventType;
property UserAgent : string read fUserAgent write fUserAgent;
property JsonOutputOptions : TJsonOutputOptions read fJsonOutputOptions write fJsonOutputOptions;
procedure Init; override;
procedure Restart; override;
procedure WriteLog(cLogItem : TLogItem); override;
end;
var
GlobalLogGrayLogProvider : TLogGrayLogProvider;
implementation
const
DEF_HTTPCONNECTION_TIMEOUT = 60000;
DEF_HTTPRESPONSE_TIMEOUT = 60000;
type
TSyslogSeverity = (slEmergency, {0 - emergency - system unusable}
slAlert, {1 - action must be taken immediately }
slCritical, { 2 - critical conditions }
slError, {3 - error conditions }
slWarning, {4 - warning conditions }
slNotice, {5 - normal but signification condition }
slInformational, {6 - informational }
slDebug); {7 - debug-level messages }
constructor TLogGrayLogProvider.Create;
begin
inherited;
LogLevel := LOG_ALL;
fURL := 'http://localhost:12201';
fGrayLogVersion := '2.1';
fShortMessageAsEventType := False;
fJsonOutputOptions.UseUTCTime := False;
fConnectionTimeout := DEF_HTTPCONNECTION_TIMEOUT;
fResponseTimeout := DEF_HTTPRESPONSE_TIMEOUT;
fUserAgent := DEF_USER_AGENT;
IncludedInfo := [iiAppName,iiHost,iiEnvironment];
end;
destructor TLogGrayLogProvider.Destroy;
begin
if Assigned(fHTTPClient) then FreeAndNil(fHTTPClient);
inherited;
end;
procedure TLogGrayLogProvider.Init;
begin
fFullURL := Format('%s/gelf',[fURL]);
fHTTPClient := TJsonHTTPClient.Create;
fHTTPClient.ConnectionTimeout := fConnectionTimeout;
fHTTPClient.ResponseTimeout := fResponseTimeout;
fHTTPClient.ContentType := 'application/json';
fHTTPClient.UserAgent := fUserAgent;
fHTTPClient.HandleRedirects := True;
inherited;
end;
function TLogGrayLogProvider.EventTypeToSysLogLevel(aEventType : TEventType) : Integer;
begin
case aEventType of
etHeader: Result := Integer(TSyslogSeverity.slInformational);
etInfo: Result := Integer(TSyslogSeverity.slInformational);
etSuccess: Result := Integer(TSyslogSeverity.slNotice);
etWarning: Result := Integer(TSyslogSeverity.slWarning);
etError: Result := Integer(TSyslogSeverity.slError);
etCritical: Result := Integer(TSyslogSeverity.slCritical);
etException: Result := Integer(TSyslogSeverity.slAlert);
etDebug: Result := Integer(TSyslogSeverity.slDebug);
etTrace: Result := Integer(TSyslogSeverity.slInformational);
etDone: Result := Integer(TSyslogSeverity.slNotice);
etCustom1: Result := Integer(TSyslogSeverity.slEmergency);
etCustom2: Result := Integer(TSyslogSeverity.slInformational);
else Result := Integer(TSyslogSeverity.slInformational);
end;
end;
function TLogGrayLogProvider.LogToGELF(cLogItem: TLogItem): string;
var
json : TJSONObject;
tagName : string;
tagValue : string;
begin
json := TJSONObject.Create;
try
json.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('version',fGrayLogVersion);
json.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('host',SystemInfo.HostName);
if fShortMessageAsEventType then
begin
json.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('short_message',EventTypeName[cLogItem.EventType]);
json.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('full_message',cLogItem.Msg);
end
else
begin
json.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('type',EventTypeName[cLogItem.EventType]);
json.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('short_message',cLogItem.Msg);
end;
{$IFDEF FPC}
json.Add('timestamp',TJSONInt64Number.Create(DateTimeToUnix(cLogItem.EventDate)));
json.Add('level',TJSONInt64Number.Create(EventTypeToSysLogLevel(cLogItem.EventType)));
{$ELSE}
{$IFDEF DELPHIXE7_UP}
json.AddPair('timestamp',TJSONNumber.Create(DateTimeToUnix(cLogItem.EventDate,fJsonOutputOptions.UseUTCTime)));
{$ELSE}
json.AddPair('timestamp',TJSONNumber.Create(DateTimeToUnix(cLogItem.EventDate)));
{$ENDIF}
json.AddPair('level',TJSONNumber.Create(EventTypeToSysLogLevel(cLogItem.EventType)));
{$ENDIF}
if iiAppName in IncludedInfo then json.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('_application',AppName);
if iiEnvironment in IncludedInfo then json.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('_environment',Environment);
if iiPlatform in IncludedInfo then json.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('_platform',PlatformInfo);
if iiOSVersion in IncludedInfo then json.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('_OS',SystemInfo.OSVersion);
if iiUserName in IncludedInfo then json.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('_user',SystemInfo.UserName);
if iiThreadId in IncludedInfo then json.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('_treadid',cLogItem.ThreadId.ToString);
if iiProcessId in IncludedInfo then json.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('_pid',SystemInfo.ProcessId.ToString);
for tagName in IncludedTags do
begin
if fCustomTags.TryGetValue(tagName,tagValue) then json.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}(tagName,tagValue);
end;
{$IFDEF DELPHIXE8_UP}
Result := json.ToJSON
{$ELSE}
{$IFDEF FPC}
Result := json.AsJSON;
{$ELSE}
Result := json.ToString;
{$ENDIF}
{$ENDIF}
finally
json.Free;
end;
end;
procedure TLogGrayLogProvider.Restart;
begin
Stop;
if Assigned(fHTTPClient) then FreeAndNil(fHTTPClient);
Init;
end;
procedure TLogGrayLogProvider.WriteLog(cLogItem : TLogItem);
var
resp : IHttpRequestResponse;
begin
if CustomMsgOutput then resp := fHTTPClient.Post(fFullURL,LogItemToFormat(cLogItem))
else resp := fHTTPClient.Post(fFullURL,LogToGELF(cLogItem));
if not (resp.StatusCode in [200,201,202]) then
raise ELogger.Create(Format('[TLogGrayLogProvider] : Response %d : %s trying to post event',[resp.StatusCode,resp.StatusText]));
end;
initialization
GlobalLogGrayLogProvider := TLogGrayLogProvider.Create;
finalization
if Assigned(GlobalLogGrayLogProvider) and (GlobalLogGrayLogProvider.RefCount = 0) then GlobalLogGrayLogProvider.Free;
end.
|
unit ThPathUtils;
interface
uses
SysUtils, Classes;
function ThAppendPath(const inPre, inSuff: string): string;
function ThPathToUrl(const inPath: string): string;
function ThUrlToPath(const inUrl: string): string;
function ThEscapePath(const inPath: string): string;
function ThIsFullPath(const inPath: string): Boolean;
procedure ThMemCopyFile(const inSrc, inDst: string);
const
cThFrontSlash = '/';
cThBackSlash = '\';
{$ifdef LINUX}
cThFileDelim = cThFrontSlash;
{$else}
cThFileDelim = cThBackSlash;
{$endif}
implementation
function ThAppendPath(const inPre, inSuff: string): string;
const
cDoubleDelim = cThFileDelim + cThFileDelim;
begin
if inPre = '' then
Result := inSuff
else
Result := StringReplace(inPre + cThFileDelim + inSuff,
cDoubleDelim, cThFileDelim, [ rfReplaceAll ]);
end;
function ThPathToUrl(const inPath: string): string;
begin
{$ifdef LINUX}
Result := inPath;
{$else}
Result := StringReplace(inPath, cThBackSlash, cThFrontSlash,
[ rfReplaceAll ]);
{$endif}
end;
function ThUrlToPath(const inUrl: string): string;
begin
{$ifdef LINUX}
Result := inPath;
{$else}
Result := StringReplace(inUrl, cThFrontSlash, cThBackSlash,
[ rfReplaceAll ]);
{$endif}
end;
function ThEscapePath(const inPath: string): string;
const
cDoubleBackslash = cThBackSlash + cThBackSlash;
begin
Result := StringReplace(inPath, cThBackSlash,
cDoubleBackslash, [ rfReplaceAll ]);
end;
function ThIsFullPath(const inPath: string): Boolean;
begin
Result := ExtractFileDrive(inPath) <> '';
end;
procedure ThMemCopyFile(const inSrc, inDst: string);
var
s: TMemoryStream;
begin
s := TMemoryStream.Create;
try
s.LoadFromFile(inSrc);
s.Position := 0;
s.SaveToFile(inDst);
finally
s.Free;
end;
end;
end.
|
{ ZADANIE 25
* Vytvorte program, ktorý zo súboru/maturita/data/studbod.txt načíta
* mená žiakov a počty bodov, ktoré žiaci dosiahli v teste a potom
* vypíše mená tých, ktorých výsledok bol lepší ako priemer.
* }
program LepsiAkoPriemer;
uses crt, sysutils;
type ziak = record {typ record je nehomogenny udajovy typ kde spajame niekolko (roznych) typov do jedneho, pracujeme s nim ako s ostatnymi premennymi}
meno, priezvisko: String;
pocetBodov: integer
end;
var subor: text;
riadok: String;
i, j, sucetBodov: integer;
priemer: real;
ziaci: array [1..30] of ziak; {array zaznamov ziak}
begin
clrscr;
assign(subor, 'maturita/data/studbod.txt'); {studbod.txt je v zlozke data, ktora je v zlozke maturita a ta je v zloze kde sa nachadza projekt}
reset(subor);
i := 0;
while not eof(subor) do
begin
i := i + 1;
with ziaci[i] do {ku jednotlivim prvkom zaznamu sa dostavame cez prikad with alebo cez bodku = nazovZaznamu.prvokVZazname}
begin
meno := '';
priezvisko := '';
end;
readln(subor, riadok);
for j := 1 to length(riadok) do
begin
if riadok[j] = ' ' then {zisti ci sa nachadza na medzere ' '}
if ziaci[i].meno = '' then ziaci[i].meno := copy(riadok, 1, j - 1) {ak je meno prazdny retazec tak priradi menu cast z riadku}
else if ziaci[i].priezvisko = '' then {ak je priezvisko prazdny retazec tak priradi menu cast z riadku}
begin
ziaci[i].priezvisko := copy(riadok, length(ziaci[i].meno) + 2, j - length(ziaci[i].meno) - 2); {priradenie casti retazcov}
ziaci[i].pocetBodov := StrToInt(copy(riadok, j + 1, length(riadok) - j));
end;
end;
end;
sucetBodov := 0;
for j := 1 to i do
sucetBodov := sucetBodov + ziaci[j].pocetBodov; {spocita vsetky body}
priemer := sucetBodov / i; {vypocita priemer}
writeln('Priemer bodov = ', priemer:0:2); {vypise priemer}
writeln();
for j := 1 to i do
if ziaci[j].pocetBodov > priemer then {ak je pocet bodov ziaka vacsi ako premer tak vypise jeho meno}
writeln(ziaci[j].priezvisko, ' ', ziaci[j].meno);
close(subor);
readln;
end.
|
unit Constants;
interface
const
LATIN_WORD_LETTERS = ['-', 'A'..'Z', 'a'..'z'];
ROME_DIGITS = ['I', 'i', 'V', 'v', 'X', 'x'];
CYRILLIC_WORD_LETTERS = ['À'..'ß','à'..'ÿ'];
STR_FILTERNAME_DIRECTSOUND = 'DirectSound';
DIC_SEPARATOR = '_____';
DIR_DIC = 'dicts\';
FILENAME_MUELLER_DICT = 'mueller-base';
FILENAME_FREQ_DICT = 'freq';
FILENAME_POST_DICT = 'posts';
FILENAME_PREF_DICT = 'prefs';
FILENAME_ALIAS_DICT = 'alias';
FILENAME_ADDITIONAL_DICT = 'additional';
FILENAME_TRANSLATED = 'translated.txt';
FILENAME_SETTINGS = 'settings.ini';
INI_VOICE_SECTION = 'voice';
INI_VOICE_NAME = 'name';
WORD_COLORS: array[0..3] of String =
('green', 'orange', 'blue', 'red');
ALERT_PREFIX_GOTO = 'goto:';
ALERT_PREFIX_SPEAK = 'speak:';
ALERT_PREFIX_FIND = 'find:';
ALERT_PREFIX_NOTIFICATION = 'notification:';
NOTIFICATION_PHRASE = 'phrase';
NOTIFICATION_MAIN = 'main';
LINK_GOOGLE_MASK = 'http://translate.google.ru/#en|ru|%s';
LINK_URBANDIC_MASK = 'http://www.urbandictionary.com/define.php?term=%s';
LINK_WIKTIONARY_MASK = 'http://en.wiktionary.org/wiki/%s';
LINK_WIKIPEDIA_MASK = 'http://en.wikipedia.org/wiki/%s';
COLOR_VIDEOWINDOW_BACKGROUND = $111111;
MAX_TRANSLATE_SYMBOLS = 300;
VIDEO_UNITS_IN_ONE_MILLISECOND = 10000;
SUBTITLE_SEEK_PREFIX_TIME = VIDEO_UNITS_IN_ONE_MILLISECOND * 1000 div 5; // 1/5 of second
DELIMITER_ALIAS = '=';
DELIMITER_DIC_REFERENCE1 = ' îò ';
DELIMITER_DIC_REFERENCE2 = ' = ';
DELIMITER_DIC_REFERENCE3 = ' ñì. ';
TIME_DIFF_REWIND = 5000; //ms
TIME_DIFF_FORWARD = 5000; //ms
TIME_WAIT_UNTIL_LOAD = 20; // 1/2 sec
FN_NAME_TRANSLATE = 'translate';
FN_NAME_FINDWORD = 'findWord';
FN_GET_TRANSLATOR_OBJECT = 'GetTranslatorObject';
STR_FILTERNAME_VOBSUB = 'VobSub';
implementation
end.
|
//------------------------------------------------------------------------------
//InterOptions UNIT
//------------------------------------------------------------------------------
// What it does-
// This unit is used to gain access to configuration variables loaded from
// Inter.ini.
//
// Changes -
// January 7th, 2007 - RaX - Broken out from ServerOptions.
//
//------------------------------------------------------------------------------
unit InterOptions;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
IniFiles;
type
//------------------------------------------------------------------------------
//TInterOptions CLASS
//------------------------------------------------------------------------------
TInterOptions = class(TMemIniFile)
private
//private variables
fPort : Word;
fEnabled : boolean;
fWANIP : String;
fLANIP : String;
fKey : String;
fIndySchedulerType : Byte;
fIndyThreadPoolSize : Word;
//Gets/Sets
procedure SetPort(Value : Word);
procedure SetWANIP(Value : String);
procedure SetLANIP(Value : String);
public
//Server
property Enabled : boolean read fEnabled;
//Communication
property Port : Word read fPort write SetPort;
property WANIP : String read fWANIP write SetWANIP;
property LANIP : String read fLANIP write SetLANIP;
//Security
property Key : String read fKey;
//Options
//Performance
property IndySchedulerType : Byte read fIndySchedulerType;
property IndyThreadPoolSize : Word read fIndyThreadPoolSize;
//Public methods
procedure Load;
procedure Save;
end;
//------------------------------------------------------------------------------
implementation
uses
Classes,
SysUtils,
Math,
NetworkConstants;
//------------------------------------------------------------------------------
//Load() PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// This routine is called to load the ini file values from file itself.
// This routine contains multiple subroutines. Each one loads a different
// portion of the ini. All changes to said routines should be documented in
// THIS changes block.
//
// Changes -
// September 21st, 2006 - RaX - Created Header.
//
//------------------------------------------------------------------------------
procedure TInterOptions.Load;
var
Section : TStringList;
//--------------------------------------------------------------------------
//LoadServer SUB PROCEDURE
//--------------------------------------------------------------------------
procedure LoadServer;
begin
ReadSectionValues('Server', Section);
fEnabled := StrToBoolDef(Section.Values['Enabled'] ,true);
end;{Subroutine LoadServer}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//LoadCommunication SUB PROCEDURE
//--------------------------------------------------------------------------
procedure LoadCommunication;
begin
ReadSectionValues('Communication', Section);
fPort := EnsureRange(StrToIntDef(Section.Values['Port'], 4000), 1, MAX_PORT);
if Section.Values['WANIP'] = '' then
begin
Section.Values['WANIP'] := '127.0.0.1';
end;
fWANIP := Section.Values['WANIP'];
if Section.Values['LANIP'] = '' then
begin
Section.Values['LANIP'] := '127.0.0.1';
end;
fLANIP := Section.Values['LANIP'];
end;{Subroutine LoadCommunication}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//LoadSecurity SUB PROCEDURE
//--------------------------------------------------------------------------
procedure LoadSecurity;
begin
ReadSectionValues('Security', Section);
fKey := Section.Values['Key'];
end;{Subroutine LoadSecurity}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//LoadOptions SUB PROCEDURE
//--------------------------------------------------------------------------
procedure LoadOptions;
begin
ReadSectionValues('Options', Section);
end;{Subroutine LoadOptions}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//LoadPerformance SUB PROCEDURE
//--------------------------------------------------------------------------
procedure LoadPerformance;
begin
ReadSectionValues('Performance', Section);
fIndySchedulerType := EnsureRange(StrToIntDef(Section.Values['Indy Scheduler Type'], 0), 0, 1);
fIndyThreadPoolSize := EnsureRange(StrToIntDef(Section.Values['Indy Thread Pool Size'], 1), 1, High(Word));
end;{Subroutine LoadPerformance}
//--------------------------------------------------------------------------
begin
Section := TStringList.Create;
Section.QuoteChar := '"';
Section.Delimiter := ',';
LoadServer;
LoadCommunication;
LoadSecurity;
LoadOptions;
LoadPerformance;
Section.Free;
end;{Load}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Save() PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// This routine saves all configuration values defined here to the .ini
// file.
//
// Changes -
// September 21st, 2006 - RaX - Created Header.
//
//------------------------------------------------------------------------------
procedure TInterOptions.Save;
begin
//Server
WriteString('Server','Enabled',BoolToStr(Enabled));
//Communication
WriteString('Communication','WANIP',WANIP);
WriteString('Communication','LANIP',LANIP);
WriteString('Communication','Port', IntToStr(Port));
//Security
WriteString('Security','Key',Key);
//Options
//Performance
WriteString('Performance','Indy Scheduler Type',IntToStr(IndySchedulerType));
WriteString('Performance','Indy Thread Pool Size',IntToStr(IndyThreadPoolSize));
UpdateFile;
end;{Save}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//SetPort() PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Property Set Routine for InterPort. Ensures that if the Inter port is
// changed for whatever reason, that it gets written to the .ini immediately.
// The same is true for all communication variables.
//
// Changes -
// September 21st, 2006 - RaX - Created Header.
//
//------------------------------------------------------------------------------
procedure TInterOptions.SetPort(Value : word);
begin
if fPort <> Value then
begin
fPort := Value;
WriteString('Communication', 'Port', IntToStr(Port));
end;
end;{SetPort}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//SetWANIP() PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Property Set Routine for WAN IP, then write to .ini
// Changes -
// November 29th, 2006 - RaX - Created.
// March 13th, 2007 - Aeomin - Modify Header
//
//------------------------------------------------------------------------------
procedure TInterOptions.SetWANIP(Value : String);
begin
if fWANIP <> Value then
begin
fWANIP := Value;
WriteString('Communication', 'WANIP', WANIP);
end;
end;{SetWANIP}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//SetLANIP() PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Property Set Routine for LAN IP, then write to .ini
// Changes -
// November 29th, 2006 - RaX - Created.
// March 13th, 2007 - Aeomin - Modify Header
//
//------------------------------------------------------------------------------
procedure TInterOptions.SetLANIP(Value : String);
begin
if fWANIP <> Value then
begin
fWANIP := Value;
WriteString('Communication', 'LANIP', LANIP);
end;
end;{SetLANIP}
//------------------------------------------------------------------------------
end{ServerOptions}.
|
//------------------------------------------------------------------------------
//Helios Program
//------------------------------------------------------------------------------
// What it does-
// Helios is a cross-compatible(Windows & Linux), multi-threaded,
// multi-database, Ragnarok Online Server Emulator.
//
// License -
//------------------------------------------------------------------------------
// Project Helios - Copyright (c) 2005-2008
//
// Contributors(A-Z) -
// Matthew Mazanec (Tsusai - tsusai at gmail dot com)
// Robert Ditthardt (RaX - onerax at gmail dot com)
// Lin Ling (Aeomin - aeomin [AT] gmail [DOT] com)
// Christopher Wilding (ChrstphrR (CR) - chrstphrr at tubbybears dot net)
//
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Project Helios nor the names of its contributors
// may be used to endorse or promote products derived from this
// software without specific prior written permission.
// * Redistributions in any COMMERCIAL form, not limited to programs
// in other programming or human languages, derivatives, and anything
// your head can think of on how to make money off our code, is
// PROHIBITED WITHOUT EXPLICIT PERMISSION FROM THE AUTHORS.
// * All Third Party licensing and rules still apply and are not and
// cannot be superceded by this license.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------
//
// Changes -
// September 20th, 2006 - RaX - Created Header.
// November 11th, 2006 - Tsusai - Updated License.
// [2007/03/24] CR - Partially updated Contributors, minor indent changes.
//------------------------------------------------------------------------------
program Helios;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
{$APPTYPE CONSOLE}
uses
{madListHardware,
madListProcesses,
madListModules,}
{*These definitions make it possible to step through programs in windows and
compile for linux, at the same time*}
//------------------------------------------------------------------------------
// Windows Definitions
//------------------------------------------------------------------------------
{$IFDEF MSWINDOWS}
{$R *.res}
//Link special resource file for x64
{$IFDEF WIN64}
{$R Helios64.res}
{$ENDIF}
//Console Related Units
CRTWrapper in 'Common\Console\CRTWrapper.pas',
WinConsole in 'Common\Console\WinCRT\WinConsole.pas',
Terminal in 'Common\Console\Terminal.pas',
//Login Server
LoginServer in 'Servers\Login\LoginServer.pas',
LoginAccountInfo in 'Servers\Login\LoginAccountInfo.pas',
//Character Server
CharacterServer in 'Servers\Character\CharacterServer.pas',
CharacterServerInfo in 'Servers\Character\CharacterServerInfo.pas',
CharaLoginCommunication in 'Servers\Character\CharaLoginCommunication.pas',
CharAccountInfo in 'Servers\Character\CharAccountInfo.pas',
//InterServer
InterServer in 'Servers\Inter\InterServer.pas',
InterSend in 'Servers\Inter\InterSend.pas',
InterRecv in 'Servers\Inter\InterRecv.pas',
//Zone Server
ZoneCharaCommunication in 'Servers\Zone\ZoneCharaCommunication.pas',
ZoneInterCommunication in 'Servers\Zone\ZoneInterCommunication.pas',
ZoneServer in 'Servers\Zone\ZoneServer.pas',
ZoneServerInfo in 'Servers\Zone\ZoneServerInfo.pas',
ZoneRecv in 'Servers\Zone\ZoneRecv.pas',
ZoneSend in 'Servers\Zone\ZoneSend.pas',
GMCommands in 'Servers\Zone\GMCommands.pas',
GMCommandExe in 'Servers\Zone\GMCommandExe.pas',
//Constants
GameConstants in 'Constants\GameConstants.pas',
DatabaseConstants in 'Constants\DatabaseConstants.pas',
NetworkConstants in 'Constants\NetworkConstants.pas',
LuaVarConstants in 'Constants\LuaVarConstants.pas',
ErrorConstants in 'Constants\ErrorConstants.pas',
//Game Objects
Account in 'Common\Classes\Account.pas',
Character in 'Common\Classes\Beings\Character.pas',
Being in 'Common\Classes\Beings\Being.pas',
Map in 'Common\Classes\Map.pas',
InstanceMap in 'Common\Classes\InstanceMap.pas',
NPC in 'Common\Classes\Beings\NPC.pas',
Mob in 'Common\Classes\Beings\Mob.pas',
Mailbox in 'Common\Classes\Mailbox.pas',
Packets in 'Common\Classes\Packets.pas',
GameObject in 'Common\Classes\GameObject.pas',
AIBeing in 'Common\Classes\Beings\AIbeing.pas',
ChatRoom in 'Common\Classes\ChatRoom.pas',
//AI
AI in 'Common\Classes\AI\AI.pas',
MobAI in 'Common\Classes\AI\MobAI.pas',
//Items
Item in 'Common\Classes\Items\Item.pas',
EquipmentItem in 'Common\Classes\Items\EquipmentItem.pas',
UseableItem in 'Common\Classes\Items\UseableItem.pas',
MiscItem in 'Common\Classes\Items\MiscItem.pas',
Inventory in 'Common\Classes\Inventory.pas',
ItemInstance in 'Common\Classes\Items\ItemInstance.pas',
Equipment in 'Common\Classes\Items\Equipment.pas',
//Lua
LuaPas in 'Common\ThirdParty\LuaPas.pas',
LuaCoreRoutines in 'Servers\Zone\Lua\LuaCoreRoutines.pas',
LuaItemCommands in 'Servers\Zone\Lua\Item\LuaItemCommands.pas',
LuaNPCCore in 'Servers\Zone\Lua\NPC\LuaNPCCore.pas',
LuaNPCCommands in 'Servers\Zone\Lua\NPC\LuaNPCCommands.pas',
LuaTypes in 'Servers\Zone\Lua\LuaTypes.pas',
LuaUtils in 'Common\ThirdParty\LuaUtils.pas',
LuaTCharacter in 'Common\Classes\Beings\Lua\LuaTCharacter.pas',
//Lists
BeingList in 'Common\Classes\Lists\BeingList.pas',
MapList in 'Common\Classes\Lists\MapList.pas',
List32 in 'Common\ThirdParty\List32.pas',
PointList in 'Common\Classes\Lists\PointList.pas',
EventList in 'Common\Classes\Events\EventList.pas',
InventoryList in 'Common\Classes\Lists\InventoryList.pas',
ParameterList in 'Common\Classes\Lists\ParameterList.pas',
//Events
Event in 'Common\Classes\Events\Event.pas',
DelayDisconnectEvent in 'Common\Classes\Events\DelayDisconnectEvent.pas',
MovementEvent in 'Common\Classes\Events\MovementEvent.pas',
BeingEventThread in 'Common\Classes\Events\BeingEventThread.pas',
OnTouchCellEvent in 'Common\Classes\Events\OnTouchCellEvent.pas',
AddFriendEvent in 'Common\Classes\Events\AddFriendEvent.pas',
AttackEvent in 'Common\Classes\Events\AttackEvent.pas',
GroundItemRemovalEventThread in 'Common\Classes\Events\GroundItemRemovalEventThread.pas',
MobMovementEvent in 'Common\Classes\Events\MobMovementEvent.pas',
//Database
Database in 'Common\Classes\Database\Database.pas',
AccountQueries in 'Common\Classes\Database\AccountQueries.pas',
CharacterQueries in 'Common\Classes\Database\CharacterQueries.pas',
CharacterConstantQueries in 'Common\Classes\Database\CharacterConstantQueries.pas',
FriendQueries in 'Common\Classes\Database\FriendQueries.pas',
MapQueries in 'Common\Classes\Database\MapQueries.pas',
ItemQueries in 'Common\Classes\Database\ItemQueries.pas',
MobQueries in 'Common\Classes\Database\MobQueries.pas',
QueryBase in 'Common\Classes\Database\QueryBase.pas',
MailQueries in 'Common\Classes\Database\MailQueries.pas',
//Configuration
HeliosOptions in 'Common\Config\HeliosOptions.pas',
LoginOptions in 'Common\Config\LoginOptions.pas',
CharaOptions in 'Common\Config\CharaOptions.pas',
InterOptions in 'Common\Config\InterOptions.pas',
ZoneOptions in 'Common\Config\ZoneOptions.pas',
DatabaseOptions in 'Common\Config\DatabaseOptions.pas',
ConsoleOptions in 'Common\Config\ConsoleOptions.pas',
GMCommandsOptions in 'Common\Config\GMCommandsOptions.pas',
//Types
MapTypes in 'Common\MapTypes.pas',
ItemTypes in 'Common\ItemTypes.pas',
GameTypes in 'Common\GameTypes.pas',
//Other
AreaLoopEvents in 'Common\AreaLoopEvents.pas',
BufferIO in 'Common\BufferIO.pas',
Commands in 'Common\Classes\Commands.pas',
CommClient in 'Common\Classes\CommClient.pas',
Globals in 'Common\Globals.pas',
{$IFNDEF FPC} //If we aren't using Lazarus to compile, use madshi components
madLinkDisAsm,
madExcept,
{$ENDIF}
PacketTypes in 'Common\PacketTypes.pas',
Server in 'Servers\Server.pas',
ServerInfo in 'Common\Classes\ServerInfo.pas',
TCPServerRoutines in 'Common\TCPServerRoutines.pas',
Version in 'Common\Version.pas',
WinLinux in 'Common\WinLinux.pas',
{$ENDIF}
//------------------------------------------------------------------------------
// Linux Definitions
//------------------------------------------------------------------------------
{$IFDEF LINUX}
{$IFDEF FPC}
//Special Threads Unit.
cthreads,
{$ENDIF}
//Console Related Units
Terminal in 'Common/Console/Terminal.pas',
CRTWrapper in 'Common/Console/CRTWrapper.pas',
//LinCRT in 'Common/Console/LinCRT/LinCRT.pas',
//NCurses in 'Common/Console/LinCRT/NCurses.pas',
//Login Server
LoginServer in 'Servers/Login/LoginServer.pas',
LoginAccountInfo in 'Servers/Login/LoginAccountInfo.pas',
//Character Server
CharacterServer in 'Servers/Character/CharacterServer.pas',
CharacterServerInfo in 'Servers/Character/CharacterServerInfo.pas',
CharaLoginCommunication in 'Servers/Character/CharaLoginCommunication.pas',
CharAccountInfo in 'Servers/Character/CharAccountInfo.pas',
//InterServer
InterServer in 'Servers/Inter/InterServer.pas',
InterSend in 'Servers/Inter/InterSend.pas',
InterRecv in 'Servers/Inter/InterRecv.pas',
//Zone Server
ZoneCharaCommunication in 'Servers/Zone/ZoneCharaCommunication.pas',
ZoneInterCommunication in 'Servers/Zone/ZoneInterCommunication.pas',
ZoneServer in 'Servers/Zone/ZoneServer.pas',
ZoneServerInfo in 'Servers/Zone/ZoneServerInfo.pas',
ZoneRecv in 'Servers/Zone/ZoneRecv.pas',
ZoneSend in 'Servers/Zone/ZoneSend.pas',
GMCommands in 'Servers/Zone/GMCommands.pas',
GMCommandExe in 'Servers/Zone/GMCommandExe.pas',
//Constants
GameConstants in 'Constants/GameConstants.pas',
DatabaseConstants in 'Constants/DatabaseConstants.pas',
NetworkConstants in 'Constants/NetworkConstants.pas',
LuaVarConstants in 'Constants/LuaVarConstants.pas',
ErrorConstants in 'Constants/ErrorConstants.pas',
//Game Objects
Account in 'Common/Classes/Account.pas',
Character in 'Common/Classes/Beings/Character.pas',
Being in 'Common/Classes/Beings/Being.pas',
Map in 'Common/Classes/Map.pas',
InstanceMap in 'Common/Classes/InstanceMap.pas',
NPC in 'Common/Classes/Beings/NPC.pas',
Mob in 'Common/Classes/Beings/Mob.pas',
Mailbox in 'Common/Classes/Mailbox.pas',
Packets in 'Common/Classes/Packets.pas',
GameObject in 'Common/Classes/GameObject.pas',
AIBeing in 'Common/Classes/Beings/AIBeing.pas',
ChatRoom in 'Common/Classes/ChatRoom.pas',
//AI
AI in 'Common/Classes/AI/AI.pas',
MobAI in 'Common/Classes/AI/MobAI.pas',
//Items
Item in 'Common/Classes/Items/Item.pas',
EquipmentItem in 'Common/Classes/Items/EquipmentItem.pas',
UseableItem in 'Common/Classes/Items/UseableItem.pas',
MiscItem in 'Common/Classes/Items/MiscItem.pas',
Inventory in 'Common/Classes/Inventory.pas',
ItemInstance in 'Common/Classes/Items/ItemInstance.pas',
Equipment in 'Common/Classes/Items/Equipment.pas',
//Lua
LuaPas in 'Common/ThirdParty/LuaPas.pas',
LuaCoreRoutines in 'Servers/Zone/Lua/LuaCoreRoutines.pas',
LuaItemCommands in 'Servers/Zone/Lua/Item/LuaItemCommands.pas',
LuaNPCCore in 'Servers/Zone/Lua/NPC/LuaNPCCore.pas',
LuaNPCCommands in 'Servers/Zone/Lua/NPC/LuaNPCCommands.pas',
LuaTypes in 'Servers/Zone/Lua/LuaTypes.pas',
//Lists
BeingList in 'Common/Classes/Lists/BeingList.pas',
MapList in 'Common/Classes/Lists/MapList.pas',
List32 in 'Common/ThirdParty/List32.pas',
PointList in 'Common/Classes/Lists/PointList.pas',
EventList in 'Common/Classes/Events/EventList.pas',
InventoryList in 'Common/Classes/Lists/InventoryList.pas',
ParameterList in 'Common/Classes/Lists/ParameterList.pas',
//Events
Event in 'Common/Classes/Events/Event.pas',
DelayDisconnectEvent in 'Common/Classes/Events/DelayDisconnectEvent.pas',
MovementEvent in 'Common/Classes/Events/MovementEvent.pas',
BeingEventThread in 'Common/Classes/Events/BeingEventThread.pas',
OnTouchCellEvent in 'Common/Classes/Events/OnTouchCellEvent.pas',
AddFriendEvent in 'Common/Classes/Events/AddFriendEvent.pas',
AttackEvent in 'Common/Classes/Events/AttackEvent.pas',
GroundItemRemovalEventThread in 'Common/Classes/Events/GroundItemRemovalEventThread.pas',
MobMovementEvent in 'Common/Classes/Events/MobMovementEvent.pas',
//Database
Database in 'Common/Classes/Database/Database.pas',
AccountQueries in 'Common/Classes/Database/AccountQueries.pas',
CharacterQueries in 'Common/Classes/Database/CharacterQueries.pas',
CharacterConstantQueries in 'Common/Classes/Database/CharacterConstantQueries.pas',
FriendQueries in 'Common/Classes/Database/FriendQueries.pas',
MapQueries in 'Common/Classes/Database/MapQueries.pas',
ItemQueries in 'Common/Classes/Database/ItemQueries.pas',
MobQueries in 'Common/Classes/Database/MobQueries.pas',
QueryBase in 'Common/Classes/Database/QueryBase.pas',
MailQueries in 'Common/Classes/Database/MailQueries.pas',
//Configuration
HeliosOptions in 'Common/Config/HeliosOptions.pas',
LoginOptions in 'Common/Config/LoginOptions.pas',
CharaOptions in 'Common/Config/CharaOptions.pas',
InterOptions in 'Common/Config/InterOptions.pas',
ZoneOptions in 'Common/Config/ZoneOptions.pas',
DatabaseOptions in 'Common/Config/DatabaseOptions.pas',
ConsoleOptions in 'Common/Config/ConsoleOptions.pas',
GMCommandsOptions in 'Common/Config/GMCommandsOptions.pas',
//Types
MapTypes in 'Common/MapTypes.pas',
ItemTypes in 'Common/ItemTypes.pas',
GameTypes in 'Common/GameTypes.pas',
//Other
AreaLoopEvents in 'Common/AreaLoopEvents.pas',
BufferIO in 'Common/BufferIO.pas',
Commands in 'Common/Classes/Commands.pas',
CommClient in 'Common/Classes/CommClient.pas',
Globals in 'Common/Globals.pas',
PacketTypes in 'Common/PacketTypes.pas',
Server in 'Servers/Server.pas',
ServerInfo in 'Common/Classes/ServerInfo.pas',
TCPServerRoutines in 'Common/TCPServerRoutines.pas',
Version in 'Common/Version.pas',
WinLinux in 'Common/WinLinux.pas',
{$ENDIF}
//------------------------------------------------------------------------------
// Definitions for both.
//------------------------------------------------------------------------------
//Main Unit
Main in 'Main.pas',
SysUtils, indylaz, zcomponent, zcore;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Helios Main Routine
// What it does -
// This main routine keeps the console window open until a server
// administrator sends it a command to shutdown.
//
// Notes -
// -To keep Helios in a Form-like organization, we've created TMainProc,
// which replaces the Main Form. This also gives us the option to make
// Helios log to a file instead of the screen by keeping all of our visual
// related routines in one place =).
// -HeliosVersion is located in Version (only one place to change)
// -This routine contains the loop that keeps the application open. On
// termination of that loop, the program will shut down.
// Changes -
// September 21st, 2006 - RaX - Created Header.
//------------------------------------------------------------------------------
var
AnInput : string;
begin
try
//Tsusai 7/8/06 : Randomize added. Learned from Prometheus.
Randomize;
//Allow Helios to capture termination messages
SetupTerminationCapturing;
//setup our paths before anything else is done.
AppPath := ExtractFilePath(ParamStr(0));
ExeName := ExtractFileNameMod(ParamStr(0));
//Create our main process.
MainProc := TMainProc.Create(nil); //Form replacement
//Setup console interface and command parser.
//This has to be set up here because It relies on the options in MainProc.
Console := TConsole.Create;
//Show our header ONCE
MainProc.DisplayHeader;
//Initialize our Main Process
MainProc.Startup; //Form Create replacement
{Begin Main Loop}
{Must keep application alive!}
while MainProc.Run do
begin
Console.ReadLn(AnInput);
end;
{End Main Loop}
finally
//Terminate the process cleanly.
TerminateApplication;
end;
end{Helios}.
|
unit uNewtonHelper;
{$I ..\Include\IntXLib.inc}
interface
uses
Math,
uXBits,
uConstants,
uDigitOpHelper,
uDigitHelper,
uIMultiplier,
uMultiplyManager,
uIntXLibTypes;
type
/// <summary>
/// Contains helping methods for fast division
/// using Newton approximation approach and fast multiplication.
/// </summary>
TNewtonHelper = class sealed(TObject)
public
/// <summary>
/// Generates integer opposite to the given one using approximation.
/// Uses algorithm from Knuth vol. 2 3rd Edition (4.3.3).
/// </summary>
/// <param name="digitsPtr">Initial big integer digits.</param>
/// <param name="mlength">Initial big integer length.</param>
/// <param name="maxLength">Precision length.</param>
/// <param name="bufferPtr">Buffer in which shifted big integer may be stored.</param>
/// <param name="newLength">Resulting big integer length.</param>
/// <param name="rightShift">How much resulting big integer is shifted to the left (or: must be shifted to the right).</param>
/// <returns>Resulting big integer digits.</returns>
class function GetIntegerOpposite(digitsPtr: PCardinal;
mlength, maxLength: UInt32; bufferPtr: PCardinal; out newLength: UInt32;
out rightShift: UInt64): TIntXLibUInt32Array; static;
end;
implementation
class function TNewtonHelper.GetIntegerOpposite(digitsPtr: PCardinal;
mlength, maxLength: UInt32; bufferPtr: PCardinal; out newLength: UInt32;
out rightShift: UInt64): TIntXLibUInt32Array;
var
msb, LeftShift, lengthLog2, lengthLog2Bits, nextBufferTempShift, k: Integer;
newLengthMax, resultLength, resultLengthSqr, resultLengthSqrBuf,
bufferDigitN1, bufferDigitN2, nextBufferTempStorage, nextBufferLength,
shiftOffset: UInt32;
bitsAfterDotResult, bitsAfterDotResultSqr, bitsAfterDotNextBuffer,
bitShift: UInt64;
resultDigits, resultDigitsSqr, resultDigitsSqrBuf,
tempDigits: TIntXLibUInt32Array;
resultPtrFixed, resultSqrPtrFixed, resultSqrBufPtr, resultPtr, resultSqrPtr,
nextBufferPtr, tempPtr: PCardinal;
multiplier: IIMultiplier;
begin
msb := TBits.msb(digitsPtr[mlength - 1]);
rightShift := UInt64(mlength - 1) * TConstants.DigitBitCount + UInt64(msb) +
UInt32(1);
if (msb <> 2) then
begin
LeftShift := (2 - msb + TConstants.DigitBitCount)
mod TConstants.DigitBitCount;
mlength := TDigitOpHelper.ShiftRight(digitsPtr, mlength, (bufferPtr + 1),
(TConstants.DigitBitCount - LeftShift), True) + UInt32(1);
end
else
begin
bufferPtr := digitsPtr;
end;
// Calculate possible result length
lengthLog2 := TBits.CeilLog2(maxLength);
newLengthMax := UInt32(1) shl (lengthLog2 + 1);
lengthLog2Bits := lengthLog2 + TBits.msb(TConstants.DigitBitCount);
// Create result digits
SetLength(resultDigits, newLengthMax);
// Create temporary digits for squared result (twice more size)
SetLength(resultDigitsSqr, newLengthMax);
// Create temporary digits for squared result * buffer
SetLength(resultDigitsSqrBuf, (newLengthMax + mlength));
// We will always use current multiplier
multiplier := TMultiplyManager.GetCurrentMultiplier();
resultPtrFixed := @resultDigits[0];
resultSqrPtrFixed := @resultDigitsSqr[0];
resultSqrBufPtr := @resultDigitsSqrBuf[0];
resultPtr := resultPtrFixed;
resultSqrPtr := resultSqrPtrFixed;
// Cache two first digits
bufferDigitN1 := bufferPtr[mlength - 1];
bufferDigitN2 := bufferPtr[mlength - 2];
// Prepare result.
// Initially result = floor(32 / (4*v1 + 2*v2 + v3)) / 4
// (last division is not floored - here we emulate fixed point)
resultDigits[0] := 32 div bufferDigitN1;
resultLength := 1;
// Prepare variables
nextBufferTempStorage := 0;
nextBufferLength := UInt32(1);
nextBufferPtr := @nextBufferTempStorage;
// Iterate 'till result will be precise enough
k := 0;
while k < (lengthLog2Bits) do
begin
// Get result squared
resultLengthSqr := multiplier.Multiply(resultPtr, resultLength, resultPtr,
resultLength, resultSqrPtr);
// Calculate current result bits after dot
bitsAfterDotResult := (UInt64(1) shl k) + UInt64(1);
bitsAfterDotResultSqr := bitsAfterDotResult shl 1;
// Here we will get the next portion of data from bufferPtr
if (k < 4) then
begin
// For now buffer intermediate has length 1 and we will use this fact
nextBufferTempShift := 1 shl (k + 1);
nextBufferTempStorage := bufferDigitN1 shl nextBufferTempShift or
bufferDigitN2 shr (TConstants.DigitBitCount - nextBufferTempShift);
// Calculate amount of bits after dot (simple formula here)
bitsAfterDotNextBuffer := UInt64(nextBufferTempShift) + UInt64(3);
end
else
begin
// Determine length to get from bufferPtr
nextBufferLength := Min(Int64(UInt32(1) shl (k - 4)) + UInt32(1),
mlength);
nextBufferPtr := bufferPtr + (mlength - nextBufferLength);
// Calculate amount of bits after dot (simple formula here)
bitsAfterDotNextBuffer := UInt64(nextBufferLength - UInt32(1)) *
TConstants.DigitBitCount + UInt64(3);
end;
// Multiply result 2 and nextBuffer + calculate new amount of bits after dot
resultLengthSqrBuf := multiplier.Multiply(resultSqrPtr, resultLengthSqr,
nextBufferPtr, nextBufferLength, resultSqrBufPtr);
bitsAfterDotNextBuffer := bitsAfterDotNextBuffer + bitsAfterDotResultSqr;
// Now calculate 2 * result - resultSqrBufPtr
Dec(bitsAfterDotResult);
Dec(bitsAfterDotResultSqr);
// Shift result on a needed amount of bits to the left
bitShift := bitsAfterDotResultSqr - bitsAfterDotResult;
shiftOffset := UInt32(bitShift div TConstants.DigitBitCount);
resultLength := shiftOffset + UInt32(1) + TDigitOpHelper.ShiftRight
(resultPtr, resultLength, resultSqrPtr + shiftOffset + UInt32(1),
TConstants.DigitBitCount -
Integer(bitShift mod TConstants.DigitBitCount), True);
// Swap resultPtr and resultSqrPtr pointers
tempPtr := resultPtr;
resultPtr := resultSqrPtr;
resultSqrPtr := tempPtr;
tempDigits := resultDigits;
resultDigits := resultDigitsSqr;
resultDigitsSqr := tempDigits;
TDigitHelper.SetBlockDigits(resultPtr, shiftOffset, UInt32(0));
bitShift := bitsAfterDotNextBuffer - bitsAfterDotResultSqr;
shiftOffset := UInt32(bitShift div TConstants.DigitBitCount);
if (shiftOffset < resultLengthSqrBuf) then
begin
// Shift resultSqrBufPtr on a needed amount of bits to the right
resultLengthSqrBuf := TDigitOpHelper.ShiftRight
(resultSqrBufPtr + shiftOffset, resultLengthSqrBuf - shiftOffset,
resultSqrBufPtr, Integer(bitShift mod TConstants.DigitBitCount), False);
// Now perform actual subtraction
resultLength := TDigitOpHelper.Sub(resultPtr, resultLength,
resultSqrBufPtr, resultLengthSqrBuf, resultPtr);
end
else
begin
// Actually we can assume resultSqrBufPtr = 0 here and have nothing to do
end;
Inc(k);
end;
rightShift := rightShift + (UInt64(1) shl lengthLog2Bits) + UInt64(1);
newLength := resultLength;
result := resultDigits;
end;
end.
|
program Jakkat;
{$mode objfpc}
uses GetOpts, Parser, SysUtils;
var
defs: TParserDefinitions;
parsr: TParser;
path: string;
paths: array of string;
outfilename: string;
f: TextFile;
procedure Usage;
begin
writeln('TODO: usage');
halt(255);
end;
procedure ParseCommandLineOptions;
const
optString = 'D:w::h';
var
c : char;
begin
c := #0;
repeat
c := GetOpt(optString);
case c of
EndOfOptions: break;
'D': begin
if pos('=', optArg) > 0 then
defs.Definition[copy(optArg, 1, pos('=', optArg) - 1)] :=
copy(optArg, pos('=', optArg) + 1, length(optArg));
end;
'w': begin
outfilename := optarg;
end;
'h': Usage;
'?': Usage;
end;
until c = EndOfOptions;
while optind <= paramcount do begin
SetLength(paths, length(paths) + 1);
paths[length(paths) - 1] := paramstr(optind);
inc(optind);
end;
end;
BEGIN
defs := TParserDefinitions.New;
outfilename := '';
ParseCommandLineOptions;
(* reentrant parser *)
(*
things to parse:
[x=y] define; y is a string constant
[x:=a+b] define with TFPExpressionParser enabled over a+b
{file} include file
{3xfile} include file 3 times
{13xfile$x=y$a:=x+y}
include file with defines
<x> expand define
*)
parsr := TParser.New(defs);
defs.Free;
for path in paths do begin
parsr.Enter(path);
end;
if length(outfilename) > 0 then
AssignFile(f, outfilename)
else
AssignFile(f, '');
Rewrite(f);
write(f, parsr.Buffer);
CloseFile(f);
parsr.Free;
END.
|
{
"name": "Wadiya is a Comet!",
"description":"Wadiya is a Comet! Waiya but filled with water! Big Naval battles ",
"version":"1.0",
"creator":"TheRealF",
"planets": [
{
"name": "Wadiya",
"mass": 5000,
"position_x": 37500,
"position_y": -6200,
"velocity_x": 18.708784103393555,
"velocity_y": 113.15800476074219,
"required_thrust_to_move": 3,
"starting_planet": true,
"respawn": false,
"start_destroyed": false,
"min_spawn_delay": 0,
"max_spawn_delay": 0,
"planet": {
"seed": 356356192,
"radius": 550,
"heightRange": 0,
"waterHeight": 70,
"waterDepth": 100,
"temperature": 0,
"metalDensity": 100,
"metalClusters": 92,
"metalSpotLimit": -1,
"biomeScale": 50,
"biome": "earth",
"symmetryType": "none",
"symmetricalMetal": false,
"symmetricalStarts": false,
"numArmies": 2,
"landingZonesPerArmy": 0,
"landingZoneSize": 0
}
}
]
} |
unit SDUSystemTrayIcon;
// Description: System Tray Icon
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
// This just uses the later structures for "TNotifyIconData_...", which should
// be harmless with earlier versions - the shell just ignores the extra data
// Note: To get the version ID of the shell, use 'shell32.dll' and the version
// ID lib code from SDUGeneral
uses
Menus,
SysUtils, // Required for Exceptions
Windows, // Required for hIcon
Graphics, // Required for TIcon
Controls, // Required for TImageList
ExtCtrls, // Required for TTimer
Classes, // Required for TComponent
Messages, // Required for TMessage
imgList; // Required for TChangeLink
type
// Exceptions...
ESDUSystemTrayIconError = Exception;
ESDUSystemTrayIconNotActive = ESDUSystemTrayIconError;
TSDUSystemTrayIconBubbleIcon = (shbiNone, shbiInfo, shbiWarning, shbiError);
{$IFDEF WIN32}
WParameter = LongInt;
{$ELSE}
WParameter = Word;
{$ENDIF}
LParameter = LongInt;
TSDUSystemTrayIcon = class(TComponent)
private
// Various which may be set by user
FActive: boolean;
FMinimizeToIcon: boolean;
FPopupMenuMenu: TPopupMenu;
FTip: string;
FIcon: TIcon;
FAnimationIcons: TImageList;
FAnimateIcon: boolean;
FOnClick: TNotifyEvent;
FOnDblClick: TNotifyEvent;
FOnContextPopup: TContextPopupEvent;
FOnBalloonShow: TNotifyEvent;
FOnBalloonHide: TNotifyEvent;
FOnBalloonTimeout: TNotifyEvent;
FOnBalloonUserClick: TNotifyEvent;
// Internal state
FAnimationChangeLink: TChangeLink;
FhWindow: HWND;
FAnimationPos: integer;
FAnimationTimer: TTimer;
FOldAppProc: Pointer;
FOldWindowProc: Pointer;
FNewAppProc: Pointer;
FNewWindowProc: Pointer;
FSystemShuttingDown: boolean;
FActiveBeforeQES: boolean;
protected
procedure SetActive(status: boolean);
procedure SetAnimateIcon(animate: boolean);
procedure SetTip(tip: string);
procedure SetIcon(icon: TIcon);
procedure SetAnimationIcons(Value: TImageList);
function GetAnimationDelay(): integer;
procedure SetAnimationDelay(delay: integer);
procedure TimerFired(Sender: TObject);
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure AddOrRemoveTrayIcon();
procedure UpdateTrayIcon(); overload;
procedure UpdateTrayIcon(dwMessage: cardinal); overload;
procedure TrayIconCallback(var msg: TMessage);
procedure AnimationListChanged(Sender: TObject);
procedure CheckActive();
procedure NewAppProc(var msg: TMessage);
procedure NewWindowProc(var msg: TMessage);
procedure TrapWindowMessages();
procedure TrapWindowMessages_AppProc();
procedure TrapWindowMessages_WindowProc();
procedure UntrapWindowMessages();
procedure UntrapWindowMessages_AppProc();
procedure UntrapWindowMessages_WindowProc();
procedure Loaded(); override;
procedure DebugWM(wmFrom: string; msg: TMessage);
// AppWM - Set to TRUE for app WM, FALSE for window WM
function ProcessWM(AppProcNotWindowProc: boolean; var msg: TMessage): boolean;
function IsOnMainForm(): boolean;
function TheMainHandle(): THandle;
public
// Procedures made public for developer convenience
procedure DoMinimizeToIcon();
procedure DoRestore();
published
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure BubbleMessage(Title: AnsiChar; Info: AnsiChar; Icon: TSDUSystemTrayIconBubbleIcon = shbiNone; Timeout: integer = 15000);
property Active: boolean read FActive write SetActive;
property MinimizeToIcon: boolean read FMinimizeToIcon write FMinimizeToIcon;
property PopupMenu: TPopupMenu read FPopupMenuMenu write FPopupMenuMenu;
property Tip: string read FTip write SetTip;
property Icon: TIcon read FIcon write SetIcon;
property AnimationIcons: TImageList read FAnimationIcons write SetAnimationIcons;
property AnimateIcon: boolean read FAnimateIcon write SetAnimateIcon;
property AnimationDelay: integer read GetAnimationDelay write SetAnimationDelay;
property OnClick: TNotifyEvent read FOnClick write FOnClick;
property OnDblClick: TNotifyEvent read FOnDblClick write FOnDblClick;
property OnContextPopup: TContextPopupEvent read FOnContextPopup write FOnContextPopup;
property OnBalloonShow: TNotifyEvent read FOnBalloonShow write FOnBalloonShow;
property OnBalloonHide: TNotifyEvent read FOnBalloonHide write FOnBalloonHide;
property OnBalloonTimeout: TNotifyEvent read FOnBalloonTimeout write FOnBalloonTimeout;
property OnBalloonUserClick: TNotifyEvent read FOnBalloonUserClick write FOnBalloonUserClick;
end;
procedure Register;
implementation
uses
{$IFDEF SDUSystemTrayIcon_DEBUG}
{$IFDEF GEXPERTS}
DbugIntf,
{$ELSE}
SDULogger_U,
{$ENDIF}
{$ENDIF}
Forms,
SDUGeneral,
SDUSystemTrayIconShellAPI;
const
EXCPT_SYSTEMTRAYICON_NOT_ACTIVE = 'System tray icon must be set to Active before use.';
WM_SDU_SYSTEMTRAYICON = WM_USER + 1;
{$IFDEF SDUSystemTrayIcon_DEBUG}
{$IFNDEF GEXPERTS}
procedure SendDebug(x: string);
var
logObj: TSDULogger;
begin
logObj:= TSDULogger.Create('C:\SDUSystemTrayIconDebug.txt');
try
logObj.LogMessage(x);
finally
logObj.Free();
end;
end;
{$ENDIF}
{$ELSE}
procedure SendDebug(x: string);
begin
// Do nothing
end;
{$ENDIF}
// ----------------------------------------------------------------------------
procedure Register;
begin
RegisterComponents('SDeanUtils', [TSDUSystemTrayIcon]);
end;
// ----------------------------------------------------------------------------
constructor TSDUSystemTrayIcon.Create(AOwner : TComponent);
begin
inherited;
FActive:= FALSE;
FMinimizeToIcon := FALSE;
FPopupMenuMenu:= nil;
FTip:= '';
FIcon:= TIcon.Create();
FAnimationIcons := nil;
FAnimateIcon:= FALSE;
FOnClick:= nil;
FOnDblClick:= nil;
// Internal state
// Delphi 6 and later moved AllocateHWnd to "Classes"
{$IFDEF VER130}
FhWindow:= AllocateHWnd(self.TrayIconCallback); // Allocate a new window, specifying
// the callback function for window
// messages
{$ELSE}
FhWindow:= Classes.AllocateHWnd(self.TrayIconCallback); // Allocate a new window, specifying
// the callback function for window
// messages
{$ENDIF}
FAnimationTimer:= TTimer.Create(self);
FAnimationTimer.Enabled := FALSE;
FAnimationTimer.OnTimer := TimerFired;
FAnimationTimer.Interval := 1000;
FAnimationPos:= 0;
FAnimationChangeLink := TChangeLink.Create();
FAnimationChangeLink.OnChange := self.AnimationListChanged;
FOldAppProc := nil;
FOldWindowProc := nil;
FNewAppProc := nil;
FNewWindowProc := nil;
FSystemShuttingDown := FALSE;
FActiveBeforeQES := Active;
end;
// ----------------------------------------------------------------------------
destructor TSDUSystemTrayIcon.Destroy;
begin
Active := FALSE;
if not(csDesigning in ComponentState) then
begin
UntrapWindowMessages();
end;
// Delphi 6 and later moved AllocateHWnd to "Classes"
{$IFDEF VER130}
DeAllocateHWnd(FhWindow);
{$ELSE}
Classes.DeAllocateHWnd(FhWindow);
{$ENDIF}
FAnimationTimer.Enabled := FALSE;
FAnimationTimer.Free();
FAnimationChangeLink.Free();
FIcon.Free();
inherited;
end;
// ----------------------------------------------------------------------------
// Note: This cannot be done in the constructor
procedure TSDUSystemTrayIcon.Loaded();
//var
// showWindowStatus: integer;
// si: TStartupInfo;
begin
inherited;
{
// THIS COMMENTED OUT CODE HAS NO EFFECT WHEN UNCOMMENTED - THE MAINFORM ISN'T
// SETUP WHEN THIS EXECUTES
if not(csDesigning in ComponentState) then
begin
if ((CmdShow = SW_SHOWMINIMIZED) or (CmdShow = SW_SHOWMINNOACTIVE)) then
begin
SendDebug('Start minimized!');
SendDebug('Start xxminimized!');
if Application.MainForm = nil then
begin
SendDebug('MAINFORM NIL!');
end;
SendDebug('owner: '+inttostr(integer(owner)));
SendDebug('Application.MainForm: '+inttostr(integer(Application.MainForm)));
if (Application.MainForm = owner) then
begin
SendDebug('Start zzminimized!');
showWindowStatus := CmdShow;
if (showWindowStatus = SW_SHOWDEFAULT) then
begin
GetStartupInfo(si);
showWindowStatus := si.wShowWindow;
end;
if (
(showWindowStatus = SW_MINIMIZE) or
(showWindowStatus = SW_SHOWMINIMIZED) or
(showWindowStatus = SW_SHOWMINNOACTIVE)
) then
begin
SendDebug('Start minimized!');
Showwindow(TheMainHandle(), SW_HIDE);
Application.ShowMainForm := FALSE;
Application.MainForm.visible := FALSE;
// Hide();
SendDebug('SETTING HIDDEN ------------------');
end;
end;
// MinimizeToIcon();
end;
end;
}
end;
// ----------------------------------------------------------------------------
function TSDUSystemTrayIcon.TheMainHandle(): THandle;
var
useHandle: THandle;
begin
useHandle := Application.Handle;
// Delphi 2007 and later only
{$IFDEF VER180}
if (
Application.MainFormOnTaskBar and
Assigned(Application.MainForm) and
Application.MainForm.HandleAllocated
) then
begin
useHandle := Application.MainFormHandle;
end;
// useHandle := Application.Handle;
{$ENDIF}
Result := useHandle;
end;
// ----------------------------------------------------------------------------
procedure TSDUSystemTrayIcon.DoMinimizeToIcon();
begin
SendDebug('DoMinimizeToIcon');
if Active then
begin
// Set the window procedure back to the old window procedure
if (Owner <> nil) then
begin
if (Owner is TWinControl) then
begin
// If our owner is the main form, it's an Application.Minimize
if IsOnMainForm() then
begin
Application.MainForm.Visible := FALSE;
ShowWindow(TheMainHandle(), SW_HIDE);
// ShowWindow(Application.Handle, SW_HIDE);
// ShowWindow(Application.MainForm.Handle, SW_HIDE);
// ShowWindow(Application.MainFormHandle, SW_HIDE);
// Application.ShowMainForm := FALSE; NO! We don't do this - may be wanted by app...
end
else
// Otherwise, just hide the owner
begin
ShowWindow(TWinControl(Owner).Handle, SW_HIDE);
end;
end;
end;
end;
end;
// ----------------------------------------------------------------------------
procedure TSDUSystemTrayIcon.DoRestore();
begin
SendDebug('DoRestore');
if (Owner <> nil) then
begin
if (Owner is TForm) then
begin
TForm(Owner).Show();
TForm(Owner).WindowState := wsNormal;
end;
end;
Application.Restore();
// Only requrid if we're the main form
if IsOnMainForm() then
begin
ShowWindow(TheMainHandle(), SW_RESTORE);
end;
//Application.ShowMainForm := TRUE; NO! We didn't do this on minimise...
Application.BringToFront();
end;
// ----------------------------------------------------------------------------
procedure TSDUSystemTrayIcon.CheckActive();
begin
if not(Active) then
begin
raise ESDUSystemTrayIconNotActive.Create(EXCPT_SYSTEMTRAYICON_NOT_ACTIVE);
end;
end;
// ----------------------------------------------------------------------------
procedure TSDUSystemTrayIcon.AnimationListChanged(Sender: TObject);
begin
FAnimationPos := 0;
end;
// ----------------------------------------------------------------------------
procedure TSDUSystemTrayIcon.TrayIconCallback(var msg: TMessage);
var
csrPos: TPoint;
bHandled: boolean;
begin
DebugWM('TrayIconCallback', msg);
case msg.Msg of
WM_QUERYENDSESSION:
begin
// As far as our (invisible) window is concerned; the system can
// shutdown at any time
msg.Result := 1;
end;
WM_SDU_SYSTEMTRAYICON:
begin
case msg.LParam of
// From:
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/shell/reference/functions/shell_notifyicon.asp
//
// "*) If a user selects a notify icon's shortcut menu with the keyboard, the version 5.0 Shell sends the associated application a WM_CONTEXTMENU message. Earlier versions send WM_RBUTTONDOWN and WM_RBUTTONUP messages.
// *) If a user selects a notify icon with the keyboard and activates it with the SPACEBAR or ENTER key, the version 5.0 Shell sends the associated application an NIN_KEYSELECT notification. Earlier versions send WM_RBUTTONDOWN and WM_RBUTTONUP messages.
// *) If a user selects a notify icon with the mouse and activates it with the ENTER key, the version 5.0 Shell sends the associated application an NIN_SELECT notification. Earlier versions send WM_RBUTTONDOWN and WM_RBUTTONUP messages."
WM_RBUTTONUP,
WM_CONTEXTMENU,
NIN_KEYSELECT,
NIN_SELECT:
begin
GetCursorPos(csrPos); // Get the cursor position on screen
bHandled := False;
if Assigned(FOnContextPopup) then
begin
FOnContextPopup(Self, csrPos, bHandled);
end;
msg.Result := Ord(bHandled);
if not(bHandled) then
begin
if Assigned(PopupMenu) then
begin
if PopupMenu.AutoPopup then
begin
SetForegroundWindow(TheMainHandle()); // Set the foreground window
// as the application - see MS KB Q135788
Application.ProcessMessages();
// ? - SendCancelMode(nil);
PopupMenu.PopupComponent := Self;
PopupMenu.Popup(csrPos.X, csrPos.Y); // Popup TPopupMenu
PostMessage(TheMainHandle(), WM_NULL, 0, 0); // Post a WM_NULL message; this
// will make sure the menu closes
// when it loses focus - see MS KB Q135788
msg.Result := 1;
end;
end;
end;
end;
WM_LBUTTONDBLCLK:
begin
if Assigned(OnDblClick) then
begin
OnDblClick(self);
end;
end;
WM_LBUTTONDOWN:
begin
if Assigned(OnClick) then
begin
OnClick(self);
end;
end;
NIN_BALLOONSHOW:
begin
if Assigned(OnBalloonShow) then
begin
OnBalloonShow(self);
end;
end;
NIN_BALLOONHIDE:
begin
if Assigned(OnBalloonHide) then
begin
OnBalloonHide(self);
end;
end;
NIN_BALLOONTIMEOUT:
begin
if Assigned(OnBalloonTimeout) then
begin
OnBalloonTimeout(self);
end;
end;
NIN_BALLOONUSERCLICK:
begin
if Assigned(OnBalloonUserClick) then
begin
OnBalloonUserClick(self);
end;
end;
//WM_LBUTTONDOWN : showmessage('WM_LBUTTONDOWN');
//WM_LBUTTONUP : showmessage('WM_LBUTTONUP');
//WM_MBUTTONCLK : showmessage('WM_MBUTTONCLK');
//WM_MBUTTONDBLCLK : showmessage('WM_MBUTTONDBLCLK');
//WM_MBUTTONDOWN : showmessage('WM_MBUTTONDOWN');
//WM_MBUTTONUP : showmessage('WM_MBUTTONUP');
//WM_RBUTTONDBLCLK : showmessage('WM_RBUTTONDBLCLK');
//WM_RBUTTONDOWN : showmessage('WM_RBUTTONDOWN');
//WM_RBUTTONUP : showmessage('WM_RBUTTONUP');
//WM_MOUSEMOVE : showmessage('WM_MOUSEMOVE');
//WM_MOUSEWHEEL : showmessage('WM_MOUSEWHEEL');
//WM_RBUTTONDBLCLK : showmessage('WM_RBUTTONDBLCLK');
//WM_RBUTTONDOWN : showmessage('WM_RBUTTONDOWN');
//etc...
end;
end; // WM_SDU_SYSTEMTRAYICON case
end; // case msg.Msg of
end;
// ----------------------------------------------------------------------------
procedure TSDUSystemTrayIcon.SetActive(status: boolean);
begin
if (status <> FActive) then
begin
SendDebug('System tray icon component state changing to: '+SDUBoolToStr(status));
FActive := status;
if not(csdesigning in ComponentState) then
begin
AddOrRemoveTrayIcon();
if status then
begin
TrapWindowMessages();
end
else
begin
UntrapWindowMessages();
end;
FAnimationPos := 0;
FAnimationTimer.Enabled := (Active and AnimateIcon);
end;
end;
end;
// ----------------------------------------------------------------------------
procedure TSDUSystemTrayIcon.SetAnimateIcon(animate: boolean);
begin
FAnimateIcon := animate;
if (
Active and
not(csdesigning in ComponentState)
) then
begin
FAnimationTimer.Enabled := animate;
UpdateTrayIcon();
end;
end;
// ----------------------------------------------------------------------------
procedure TSDUSystemTrayIcon.SetTip(tip: string);
begin
FTip := tip;
if (
Active and
not(csdesigning in ComponentState)
) then
begin
UpdateTrayIcon();
end;
end;
// ----------------------------------------------------------------------------
procedure TSDUSystemTrayIcon.SetIcon(icon: TIcon);
begin
if (icon <> nil) then
begin
FIcon.Assign(icon);
if (
Active and
not(csdesigning in ComponentState)
) then
begin
UpdateTrayIcon();
end;
end;
end;
// ----------------------------------------------------------------------------
// Taken from ComCtrls.pas (TListView)
procedure TSDUSystemTrayIcon.SetAnimationIcons(Value: TImageList);
begin
if (AnimationIcons <> Value) then
begin
if (AnimationIcons <> nil) then
begin
AnimationIcons.UnRegisterChanges(FAnimationChangeLink);
end;
FAnimationIcons := Value;
if (AnimationIcons <> nil) then
begin
AnimationIcons.RegisterChanges(FAnimationChangeLink);
AnimationIcons.FreeNotification(Self);
end
else
begin
Active := FALSE;
end;
if (
Active and
not(csdesigning in ComponentState)
) then
begin
UpdateTrayIcon();
end;
end;
end;
// ----------------------------------------------------------------------------
function TSDUSystemTrayIcon.GetAnimationDelay(): integer;
begin
Result := FAnimationTimer.Interval;
end;
// ----------------------------------------------------------------------------
procedure TSDUSystemTrayIcon.SetAnimationDelay(delay: integer);
begin
FAnimationTimer.Interval := delay;
if (
Active and
not(csdesigning in ComponentState)
) then
begin
UpdateTrayIcon();
end;
end;
// ----------------------------------------------------------------------------
procedure TSDUSystemTrayIcon.TimerFired(Sender: TObject);
begin
inc(FAnimationPos);
if (FAnimationPos > (AnimationIcons.Count-1)) then
begin
FAnimationPos := 0;
end;
if (
Active and
not(csdesigning in ComponentState)
) then
begin
UpdateTrayIcon();
end;
end;
// ----------------------------------------------------------------------------
// Taken from ComCtrls.pas
procedure TSDUSystemTrayIcon.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (
(Operation = opRemove) and
(AComponent = AnimationIcons)
) then
begin
AnimationIcons := nil;
end;
end;
// ----------------------------------------------------------------------------
procedure TSDUSystemTrayIcon.AddOrRemoveTrayIcon();
begin
if Active then
begin
UpdateTrayIcon(NIM_ADD);
end
else
begin
UpdateTrayIcon(NIM_DELETE);
end;
end;
// ----------------------------------------------------------------------------
procedure TSDUSystemTrayIcon.UpdateTrayIcon();
begin
UpdateTrayIcon(NIM_MODIFY);
end;
// ----------------------------------------------------------------------------
procedure TSDUSystemTrayIcon.UpdateTrayIcon(dwMessage: cardinal);
var
{ done 1 -otdk -crefactor : use _NOTIFYICONDATA_v5W for widechar }
trayIcon: TNotifyIconData_v5w;
tmpIcon: TIcon;
begin
tmpIcon:= TIcon.Create();
try
if (
Active or
(dwMessage = NIM_DELETE)
) then
begin
trayIcon.cbSize := sizeof(trayIcon); // Size of struct
trayIcon.hWnd:= FhWindow; // Handle to window which will receive callbacks
trayIcon.uID:= 0;
trayIcon.uFlags:= NIF_ICON or NIF_TIP or NIF_MESSAGE;
trayIcon.uCallbackMessage := WM_SDU_SYSTEMTRAYICON; // The message the icon answers to
// Fallback to application's icon
trayIcon.hIcon:= Application.Icon.Handle;
if not(AnimateIcon) then
begin
if not(FIcon.Empty) then
begin
trayIcon.hIcon:= FIcon.Handle;
end;
end
else
begin
if Assigned(FAnimationIcons) then
begin
// Sanity check...
if (FAnimationPos > (FAnimationIcons.Count-1)) then
begin
FAnimationPos := 0;
end;
if (FAnimationPos <= (FAnimationIcons.Count-1)) then
begin
FAnimationIcons.GetIcon(FAnimationPos, tmpIcon);
trayIcon.hIcon:= tmpIcon.Handle;
end;
end;
end;
// From the Microsoft help:
// "Pointer to a null-terminated string with the text for a standard
// ToolTip. It can have a maximum of 64 characters including the
// terminating NULL.
// For Version 5.0 and later, szTip can have a maximum of 128
// characters, including the terminating NULL."
StrPLCopy(trayIcon.szTip, fTip, (sizeof(trayIcon.szTip)-1));
Shell_NotifyIcon(dwMessage, @trayIcon);
end;
finally
tmpIcon.Free();
end;
end;
// ----------------------------------------------------------------------------
procedure TSDUSystemTrayIcon.BubbleMessage(Title: AnsiChar; Info: AnsiChar; Icon: TSDUSystemTrayIconBubbleIcon; Timeout: integer);
var
trayIcon: TNotifyIconData_v2;
begin
CheckActive();
trayIcon.cbSize := sizeof(trayIcon); // Size of struct
trayIcon.hWnd:= FhWindow; // Handle to window which will receive callbacks
trayIcon.uID:= 0;
trayIcon.uFlags:= NIF_INFO;
case Icon of
shbiNone: trayIcon.dwInfoFlags := NIIF_NONE;
shbiInfo: trayIcon.dwInfoFlags := NIIF_INFO;
shbiWarning: trayIcon.dwInfoFlags := NIIF_WARNING;
shbiError: trayIcon.dwInfoFlags := NIIF_ERROR;
else
trayIcon.dwInfoFlags := NIIF_NONE;
end;
StrPLCopy(trayIcon.szInfoTitle, Title, (sizeof(trayIcon.szInfoTitle)-1));
StrPLCopy(trayIcon.szInfo, Info, (sizeof(trayIcon.szInfo)-1));
// trayIcon.TimeoutVersion.uTimeout := Timeout;
trayIcon.TimeoutVersion.uTimeout := Timeout or NOTIFYICON_VERSION;
Shell_NotifyIcon(NIM_MODIFY, @trayIcon);
end;
// ----------------------------------------------------------------------------
// See: Trapping Windows Messages in Delphi
// http://community.borland.com/article/0,1410,16487,00.html
procedure TSDUSystemTrayIcon.TrapWindowMessages();
begin
TrapWindowMessages_AppProc();
TrapWindowMessages_WindowProc();
end;
procedure TSDUSystemTrayIcon.TrapWindowMessages_AppProc();
begin
// Set the new app procedure for the control and remember the old app procedure.
// Delphi 6 and later moved MakeObjectInstance to "Classes"
{$IFDEF VER130}
FNewAppProc := Forms.MakeObjectInstance(self.NewAppProc);
{$ELSE}
FNewAppProc := Classes.MakeObjectInstance(self.NewAppProc);
{$ENDIF}
FOldAppProc := Pointer(SetWindowLong(
Application.Handle,
GWL_WNDPROC,
LongInt(FNewAppProc)
));
end;
procedure TSDUSystemTrayIcon.TrapWindowMessages_WindowProc();
begin
// Set the new app procedure for the control and remember the old window procedure.
if (Owner <> nil) then
begin
if (Owner is TWinControl) then
begin
// Set the new app procedure for the control and remember the old app procedure.
// Delphi 6 and later moved MakeObjectInstance to "Classes"
{$IFDEF VER130}
FNewWindowProc := Forms.MakeObjectInstance(self.NewWindowProc);
{$ELSE}
FNewWindowProc := Classes.MakeObjectInstance(self.NewWindowProc);
{$ENDIF}
FOldWindowProc := Pointer(SetWindowLong(
TWinControl(Owner).Handle,
GWL_WNDPROC,
LongInt(FNewWindowProc)
));
end;
end;
end;
// ----------------------------------------------------------------------------
// See: Trapping Windows Messages in Delphi
// http://community.borland.com/article/0,1410,16487,00.html
procedure TSDUSystemTrayIcon.UntrapWindowMessages();
begin
UntrapWindowMessages_AppProc();
UntrapWindowMessages_WindowProc();
end;
procedure TSDUSystemTrayIcon.UntrapWindowMessages_AppProc();
begin
// Set the app procedure back to the old app procedure
if (FOldAppProc <> nil) then
begin
SetWindowLong(
Application.Handle,
GWL_WNDPROC,
LongInt(FOldAppProc)
);
if (FNewAppProc <> nil) then
begin
// Delphi 6 and later moved FreeObjectInstance to "Classes"
{$IFDEF VER130}
Forms.FreeObjectInstance(FNewAppProc);
{$ELSE}
Classes.FreeObjectInstance(FNewAppProc);
{$ENDIF}
end;
end;
FOldAppProc := nil;
FNewAppProc := nil;
end;
procedure TSDUSystemTrayIcon.UntrapWindowMessages_WindowProc();
begin
// Set the window procedure back to the old window procedure
if (FOldWindowProc <> nil) then
begin
if (Owner <> nil) then
begin
if (Owner is TWinControl) then
begin
SetWindowLong(
TWinControl(Owner).Handle,
GWL_WNDPROC,
LongInt(FOldWindowProc)
);
if (FNewWindowProc <> nil) then
begin
// Delphi 6 and later moved FreeObjectInstance to "Classes"
{$IFDEF VER130}
Forms.FreeObjectInstance(FNewWindowProc);
{$ELSE}
Classes.FreeObjectInstance(FNewWindowProc);
{$ENDIF}
end;
end;
end;
end;
FOldWindowProc := nil;
FNewWindowProc := nil;
end;
// ----------------------------------------------------------------------------
// Dump debug information out about certain window messaes received
procedure TSDUSystemTrayIcon.DebugWM(wmFrom: string; msg: TMessage);
var
si: TStartupInfo;
showWindowStatus: integer;
begin
wmFrom := '------------- '+wmFrom+' -------------';
// Debug out the window message details
case msg.Msg of
WM_ENDSESSION:
begin
SendDebug(wmFrom);
SendDebug('WM_ENDSESSION');
SendDebug(' - Shuting down: '+SDUBoolToStr(TWMEndSession(msg).EndSession));
end;
WM_SHOWWINDOW:
begin
SendDebug(wmFrom);
showWindowStatus := msg.LParam;
if (msg.LParam = SW_SHOWDEFAULT) then
begin
GetStartupInfo(si);
showWindowStatus := si.wShowWindow;
end;
SendDebug('WM_SHOWWINDOW');
SendDebug(' - showWindowStatus: '+inttostr(showWindowStatus));
SendDebug(' - SW_MINIMIZE : '+SDUBoolToStr(showWindowStatus = SW_MINIMIZE));
SendDebug(' - SW_SHOWMINIMIZED : '+SDUBoolToStr(showWindowStatus = SW_SHOWMINIMIZED));
SendDebug(' - SW_SHOWMINNOACTIVE: '+SDUBoolToStr(showWindowStatus = SW_SHOWMINNOACTIVE));
end;
WM_SIZE:
begin
SendDebug(wmFrom);
SendDebug('WM_SIZE');
SendDebug(' - SIZE_MINIMIZED: '+SDUBoolToStr(msg.WParam = SIZE_MINIMIZED));
end;
WM_SYSCOMMAND:
begin
SendDebug(wmFrom);
SendDebug('WM_SYSCOMMAND');
SendDebug(' - SC_CLOSE : '+SDUBoolToStr(msg.WParam = SC_CLOSE));
SendDebug(' - SC_MINIMIZE: '+SDUBoolToStr(msg.WParam = SC_MINIMIZE));
SendDebug(' - SC_ICON : '+SDUBoolToStr(msg.WParam = SC_ICON));
end;
// CM_RECREATEWND:
// begin
// SendDebug(wmFrom);
// SendDebug('CM_RECREATEWND');
// end;
WM_NCPAINT,
WM_GETTEXT,
WM_ERASEBKGND,
WM_PAINT,
WM_NCHITTEST,
WM_SETCURSOR,
WM_MOUSEMOVE,
WM_MOUSEACTIVATE:
begin
// Ignore
end;
else
begin
SendDebug(wmFrom);
SendDebug(SDUWMToString(msg.Msg));
end;
end;
end;
// ----------------------------------------------------------------------------
function TSDUSystemTrayIcon.ProcessWM(AppProcNotWindowProc: boolean; var msg: TMessage): boolean;
var
// si: TStartupInfo;
// showWindowStatus: integer;
minOrClose: boolean;
intercept: boolean;
begin
minOrClose := FALSE;
intercept := FALSE;
// Process the message of your choice here
case msg.Msg of
{
WM_SHOWWINDOW: begin
if (Msg.lParam = 0) and (Msg.wParam = 1) then
begin
// Show the taskbar icon (Windows may have shown it already)
ShowWindow(TheMainHandle(), SW_RESTORE);
// Bring the taskbar icon and the main form to the foreground
SetForegroundWindow(TheMainHandle());
SetForegroundWindow((Owner as TWinControl).Handle);
end;
end;
}
{
WM_WINDOWPOSCHANGED: begin
// Bring any modal forms owned by the main form to the foreground
if Assigned(Screen.ActiveControl) then
SetFocus(Screen.ActiveControl.Handle);
end;
}
{
WM_SHOWWINDOW:
begin
showWindowStatus := msg.LParam;
if (msg.LParam = SW_SHOWDEFAULT) then
begin
GetStartupInfo(si);
showWindowStatus := si.wShowWindow;
end;
minOrClose := (
(showWindowStatus = SW_MINIMIZE) or
(showWindowStatus = SW_SHOWMINIMIZED) or
(showWindowStatus = SW_SHOWMINNOACTIVE)
);
minOrClose := FALSE;
end;
WM_WINDOWPOSCHANGED:
begin
end;
}
WM_SIZE:
begin
minOrClose := MinimizeToIcon and (msg.WParam = SIZE_MINIMIZED);
end;
{
WM_CLOSE:
begin
minOrClose := CloseToIcon;
intercept := CloseToIcon;
end;
}
{
WM_SYSCOMMAND:
begin
minOrClose := (
(msg.WParam = SC_CLOSE) or
(msg.WParam = SC_MINIMIZE) or
(msg.WParam = SC_ICON)
);
intercept := (msg.WParam = SC_CLOSE);
minOrClose := FALSE;
intercept := FALSE;
end;
}
// Enabling this causes the main menu to disappear!
// WM_DESTROY:
// begin
// UntrapWindowMessages_WindowProc();
// FReceivedWM_DESTROY := TRUE;
// end;
// WM_WINDOWPOSCHANGING:
// begin
// if FReceivedWM_DESTROY then
// begin
// TrapWindowMessages_WindowProc();
// end;
// end;
end;
if minOrClose then
begin
DoMinimizeToIcon();
end;
Result := intercept or minOrClose;
// Result := FALSE;
if Result then
begin
SendDebug('+++ Window message processed +++');
end;
end;
// ----------------------------------------------------------------------------
// Application window message received
procedure TSDUSystemTrayIcon.NewAppProc(var msg: TMessage);
var
handled: boolean;
begin
DebugWM('NewAppProc', msg);
handled := FALSE;
if IsOnMainForm() then
begin
handled := ProcessWM(TRUE, msg);
end;
if handled then
begin
msg.Result := 1;
end
else
begin
// Call the old Window procedure to allow processing of the message.
msg.Result := CallWindowProc(
FOldAppProc,
Application.Handle,
msg.Msg,
msg.WParam,
msg.LParam
);
end;
end;
// ----------------------------------------------------------------------------
function TSDUSystemTrayIcon.IsOnMainForm(): boolean;
begin
Result :=
(owner <> nil) and
{$IF CompilerVersion >= 18.5}
(
// If Application.MainFormOnTaskbar is set, use the form name,
// otherwise check exactly
(
Application.MainFormOnTaskbar and
(application.mainform <> nil) and
(application.mainform.name = owner.name)
) or
(
not(Application.MainFormOnTaskbar) and
// (application.mainform = owner)
(application.mainform <> nil) and
(application.mainform.name = owner.name)
)
)
{$ELSE}
(application.mainform = owner)
{$IFEND}
;
end;
// ----------------------------------------------------------------------------
// Window window message received
procedure TSDUSystemTrayIcon.NewWindowProc(var msg: TMessage);
var
handled: boolean;
begin
DebugWM('NewWindowProc', msg);
handled := FALSE;
// Note: This is NOT the same as IsOnMainForm(...) in the previous version
{$IF CompilerVersion >= 18.5}
if (owner <> nil) and
(
// If Application.MainFormOnTaskbar is set, use the form name,
// otherwise check exactly
(
Application.MainFormOnTaskbar and
(application.mainform <> nil) and
(application.mainform.name = owner.name)
) or
(
not(Application.MainFormOnTaskbar) and
// (application.mainform <> owner)
(application.mainform <> nil) and
(application.mainform.name <> self.name)
)
) then
{$ELSE}
if ((owner <> nil) and (application.mainform <> owner)) then
{$IFEND}
begin
handled := ProcessWM(FALSE, msg);
end;
if handled then
begin
msg.Result := 1;
end
else
begin
// Call the old Window procedure to allow processing of the message.
msg.Result := CallWindowProc(
FOldWindowProc,
TWinControl(Owner).Handle,
msg.Msg,
msg.WParam,
msg.LParam
);
end;
end;
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
END.
|
unit UFrmCadastroEmpresaMatriz;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UFrmCRUD, Menus, Buttons, StdCtrls, ExtCtrls
, UEmpresaMatriz
, UUtilitarios
, URegraCRUDPais
, URegraCRUDCidade
, URegraCRUDEstado
, URegraCRUDEmpresaMatriz
;
type
TFrmCadastroEmpresa = class(TFrmCRUD)
gbInformacoes: TGroupBox;
edNome: TLabeledEdit;
edInscricaoEstadual: TLabeledEdit;
Enderešo: TGroupBox;
edLogradouro: TLabeledEdit;
edNumero: TLabeledEdit;
edBairro: TLabeledEdit;
edCnpj: TLabeledEdit;
edTelefone: TLabeledEdit;
lblCidade: TLabel;
edCidade: TEdit;
btnLocalizarCidade: TButton;
stNomeCidade: TStaticText;
lbEmpresaMatriz: TLabel;
edEmpresaMatriz: TEdit;
btnLocalizarEmpresaMatriz: TButton;
stNomeEmpresaMatriz: TStaticText;
procedure btnLocalizarCidadeClick(Sender: TObject);
procedure edCidadeExit(Sender: TObject);
procedure btnLocalizarEmpresaMatrizClick(Sender: TObject);
procedure edEmpresaMatrizExit(Sender: TObject);
protected
FEMPRESA : TEmpresa;
FRegraCRUDEmpresa : TregraCRUDEEmpresaMatriz;
FRegraCRUDCidade : TRegraCRUDCidade;
FRegraCRUDPais : TRegraCRUDPais;
FRegraCRUDEstado : TRegraCRUDEstado;
procedure Inicializa; override;
procedure Finaliza; override;
procedure PreencheEntidade; override;
procedure PreencheFormulario; override;
procedure PosicionaCursorPrimeiroCampo; override;
procedure HabilitaCampos(const ceTipoOperacaoUsuario: TTipoOperacaoUsuario); override;
private
{ Private declarations }
public
{ Public declarations }
end;
var
FrmCadastroEmpresa: TFrmCadastroEmpresa;
implementation
uses
UOpcaoPesquisa
, UEntidade
, UFrmPesquisa
, UCidade
, UDialogo
;
{$R *.dfm}
procedure TFrmCadastroEmpresa.btnLocalizarCidadeClick(Sender: TObject);
begin
inherited;
edCidade.Text := TfrmPesquisa.MostrarPesquisa(TOpcaoPesquisa
.Create
.DefineVisao(VW_CIDADE)
.DefineNomeCampoRetorno(VW_CIDADE_ID)
.DefineNomePesquisa(STR_CIDADE)
.AdicionaFiltro(VW_CIDADE_NOME));
if Trim(edCidade.Text) <> EmptyStr then
edCidade.OnExit(btnLocalizarCidade);
end;
procedure TFrmCadastroEmpresa.btnLocalizarEmpresaMatrizClick(Sender: TObject);
begin
inherited;
edEmpresaMatriz.Text := TfrmPesquisa.MostrarPesquisa(TOpcaoPesquisa
.Create
.DefineVisao(VW_EMPRESA)
.DefineNomeCampoRetorno(VW_EMPRESA_ID)
.DefineNomePesquisa(STR_EMPRESAMATRIZ)
.AdicionaFiltro(VW_EMPRESA_NOME));
if Trim(edEmpresaMatriz.Text) <> EmptyStr then
edEmpresaMatriz.OnExit(btnLocalizarEmpresaMatriz);
end;
procedure TFrmCadastroEmpresa.edCidadeExit(Sender: TObject);
begin
inherited;
stNomeCidade.Caption := EmptyStr;
if Trim(edCidade.Text) <> EmptyStr then
try
FRegraCRUDCidade.ValidaExistencia(StrToIntDef(edCidade.Text, 0));
FEMPRESA.CIDADE := TCIDADE(
FRegraCRUDCidade.Retorna(StrToIntDef(edCidade.Text, 0)));
stNomeCidade.Caption := FEMPRESA.CIDADE.NOME;
except
on E: Exception do
begin
TDialogo.Excecao(E);
edCidade.SetFocus;
end;
end;
end;
procedure TFrmCadastroEmpresa.edEmpresaMatrizExit(Sender: TObject);
var
loEMPRESA_MATRIZ: TEMPRESA;
begin
inherited;
stNomeEmpresaMatriz.Caption := EmptyStr;
if Trim(edEmpresaMatriz.Text) <> EmptyStr then
try
FRegraCRUDEmpresa.ValidaExistencia(StrToIntDef(edEmpresaMatriz.Text, 0));
loEMPRESA_MATRIZ := TEMPRESA(
FRegraCRUDEmpresa.Retorna(StrToIntDef(edEmpresaMatriz.Text, 0)));
stNomeEmpresaMatriz.Caption := loEMPRESA_MATRIZ.NOME;
FEMPRESA.ID_EMPRESA_MATRIZ := loEMPRESA_MATRIZ.ID;
except
on E: Exception do
begin
TDialogo.Excecao(E);
edCidade.SetFocus;
end;
end;
end;
procedure TFrmCadastroEmpresa.Finaliza;
begin
inherited;
FreeAndNil(FRegraCRUDCidade);
FreeAndNil(FRegraCRUDPais);
FreeAndNil(FRegraCRUDEstado);
end;
procedure TFrmCadastroEmpresa.HabilitaCampos(
const ceTipoOperacaoUsuario: TTipoOperacaoUsuario);
begin
inherited;
gbInformacoes.Enabled := FTipoOperacaoUsuario In [touInsercao, touAtualizacao];
end;
procedure TFrmCadastroEmpresa.Inicializa;
begin
inherited;
DefineEntidade(@FEMPRESA, TEmpresa);
DefineRegraCRUD(@FRegraCRUDEmpresa, TregraCRUDEEmpresaMatriz);
AdicionaOpcaoPesquisa(TOpcaoPesquisa
.Create
.AdicionaFiltro(FLD_EMPRESA_NOME)
.DefineNomeCampoRetorno(FLD_ENTIDADE_ID)
.DefineNomePesquisa(STR_EMPRESAMATRIZ)
.DefineVisao(TBL_EMPRESA));
FRegraCRUDCidade := TRegraCRUDCidade.Create;
FRegraCRUDEstado := TRegraCRUDEstado.Create;
FRegraCRUDPais := TRegraCRUDPais.Create;
end;
procedure TFrmCadastroEmpresa.PosicionaCursorPrimeiroCampo;
begin
inherited;
edNome.SetFocus;
end;
procedure TFrmCadastroEmpresa.PreencheEntidade;
begin
inherited;
FEMPRESA.NOME := edNome.Text;
FEMPRESA.IE := StrToIntDef(edInscricaoEstadual.Text, 0);
FEMPRESA.CNPJ := edCnpj.Text;
FEMPRESA.TELEFONE := edTelefone.Text;
FEMPRESA.LOGRADOURO := edLogradouro.Text;
FEMPRESA.NUMERO := StrToIntDef(edNumero.Text, 0);
FEMPRESA.BAIRRO := edBairro.Text;
FEMPRESA.ID_EMPRESA_MATRIZ := StrToIntDef(edEmpresaMatriz.Text, -1);
end;
procedure TFrmCadastroEmpresa.PreencheFormulario;
var
loEMPRESA_MATRIZ : TEmpresa;
begin
inherited;
edNome.Text := FEMPRESA.NOME;
edInscricaoEstadual.Text := IntToStr(FEMPRESA.IE);
edCnpj.Text := FEMPRESA.CNPJ;
edTelefone.Text := FEMPRESA.TELEFONE;
edLogradouro.Text := FEMPRESA.LOGRADOURO;
edNumero.Text := IntToStr(FEMPRESA.NUMERO);
edBairro.Text := FEMPRESA.BAIRRO;
edCidade.Text := IntToStr(FEMPRESA.CIDADE.ID);
stNomeCidade.Caption := FEMPRESA.CIDADE.NOME;
if FEMPRESA.ID_EMPRESA_MATRIZ > 0 then
begin
loEMPRESA_MATRIZ := TEMPRESA(
FRegraCRUDEmpresa.Retorna(FEMPRESA.ID_EMPRESA_MATRIZ));
edEmpresaMatriz.Text := IntToStr(loEMPRESA_MATRIZ.ID);
stNomeEmpresaMatriz.Caption := loEMPRESA_MATRIZ.NOME;
end;
end;
end.
|
unit fmSolveResults;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls;
type
TfmResults = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
memo: TMemo;
bbClose: TBitBtn;
private
{ Private declarations }
public
{ Public declarations }
procedure Header;
procedure Footer;
end;
var
fmResults: TfmResults;
implementation
{$R *.dfm}
uses Solver, DateUtils;
procedure TfmResults.Header;
var aMsg: string;
aDat1, aDat2: string;
begin
memo.Clear;
with globSolver do begin
aDat1 := FormatDateTime('dd mmmm yyyy', Plan.FirstDay);
aDat2 := FormatDateTime('dd mmmm yyyy', Plan.LastDay);
aMsg := Format('Razreševanje razporeda za %d dni (%s do %s).',
[Plan.DayCount, aDat1, aDat2]);
memo.Lines.Add(aMsg);
aDat1 := FormatDateTime('hh:mm:ss.zzz', Date + Time);
aMsg := Format ('Začetek razreševanja ob %s', [aDat1]);
memo.Lines.Add(aMsg);
memo.Lines.Add('=====================================================');
end;
end;
procedure TfmResults.Footer;
var aMsg: string;
aDat1: string;
begin
aDat1 := FormatDateTime('hh:mm:ss.zzz', Date + Time);
aMsg := Format ('Konec razreševanja ob %s', [aDat1]);
memo.Lines.Add('=====================================================');
memo.Lines.Add(aMsg);
end;
end.
|
unit UnitListarPortasAtivas;
interface
uses
Windows,
winsock,
tlhelp32,
UnitFuncoesDiversas;
//resourcestring
const
ResTCPStateClosed = 'CLOSED';
ResTCPStateListen = 'LISTEN';
ResTCPStateSynSent = 'SYNSENT';
ResTCPStateSynRcvd = 'SYNRCVD';
ResTCPStateEst = 'ESTABLISHED';
ResTCPStateFW1 = 'FIN_WAIT1';
ResTCPStateFW2 = 'FIN_WAIT2';
ResTCPStateCloseWait = 'CLOSE_WAIT';
ResTCPStateClosing = 'CLOSING';
ResTCPStateLastAck = 'LAST_ACK';
ResTCPStateTimeWait = 'TIME_WAIT';
ResTCPStateDeleteTCB = 'DELETE_TCB';
const
TCP_STATES: array[1..12] of widestring = (ResTCPStateClosed,
ResTCPStateListen,
ResTCPStateSynSent,
ResTCPStateSynRcvd,
ResTCPStateEst,
ResTCPStateFW1,
ResTCPStateFW2,
ResTCPStateCloseWait,
ResTCPStateClosing,
ResTCPStateLastAck,
ResTCPStateTimeWait,
ResTCPStateDeleteTCB);
type
TCP_TABLE_CLASS = (TCP_TABLE_BASIC_LISTENER, TCP_TABLE_BASIC_CONNECTIONS,
TCP_TABLE_BASIC_ALL, TCP_TABLE_OWNER_PID_LISTENER,
TCP_TABLE_OWNER_PID_CONNECTIONS, TCP_TABLE_OWNER_PID_ALL,
TCP_TABLE_OWNER_MODULE_LISTENER, TCP_TABLE_OWNER_MODULE_CONNECTIONS,
TCP_TABLE_OWNER_MODULE_ALL);
UDP_TABLE_CLASS = (UDP_TABLE_BASIC, UDP_TABLE_OWNER_PID, UDP_TABLE_OWNER_MODULE);
PMIB_TCPROW = ^MIB_TCPROW;
MIB_TCPROW = packed record
dwState: DWORD;
dwLocalAddr: DWORD;
dwLocalPort: DWORD;
dwRemoteAddr: DWORD;
dwRemotePort: DWORD;
end;
PMIB_TCPROW_OWNER_PID = ^MIB_TCPROW_OWNER_PID;
MIB_TCPROW_OWNER_PID = packed record
dwState: DWORD;
dwLocalAddr: DWORD;
dwLocalPort: DWORD;
dwRemoteAddr: DWORD;
dwRemotePort: DWORD;
dwOwnerPID: DWORD;
end;
PMIB_UDPROW_OWNER_PID = ^MIB_UDPROW_OWNER_PID;
MIB_UDPROW_OWNER_PID = packed record
dwLocalAddr: DWORD;
dwLocalPort: DWORD;
dwOwnerPID: DWORD;
end;
PMIB_TCPTABLE_OWNER_PID = ^MIB_TCPTABLE_OWNER_PID;
MIB_TCPTABLE_OWNER_PID = packed record
dwNumEntries: DWORD;
table: array [0..0] of MIB_TCPROW_OWNER_PID;
end;
PMIB_UDPTABLE_OWNER_PID = ^MIB_UDPTABLE_OWNER_PID;
MIB_UDPTABLE_OWNER_PID = packed record
dwNumEntries: DWORD;
table: array [0..0] of MIB_UDPROW_OWNER_PID;
end;
TAllocateAndGetTcpExTableFromStack = function (pTcpTable: PMIB_TCPTABLE_OWNER_PID;bOrder: BOOL;heap: THandle;
zero: DWORD;flags: DWORD):DWORD;stdcall;
TAllocateAndGetUdpExTableFromStack = function (pTcpTable: PMIB_TCPTABLE_OWNER_PID;bOrder: BOOL;heap: THandle;
zero: DWORD;flags: DWORD):DWORD;stdcall;
TSendTcpEntry = function (pTCPRow: PMIB_TCPROW):DWORD;stdcall;
TGetExtendedTcpTable = function (pTcpTable: PMIB_TCPTABLE_OWNER_PID;pdwSize: PDWORD;bOrder: BOOL;ulAf: ULONG;
TableClass: TCP_TABLE_CLASS;Reserved: ULONG):DWORD;stdcall;
TGetExtendedUdpTable = function (pTcpTable: PMIB_UDPTABLE_OWNER_PID;pdwSize: PDWORD;bOrder: BOOL;ulAf: ULONG;
TableClass: UDP_TABLE_CLASS;Reserved: ULONG):DWORD;stdcall;
const
MIB_TCP_STATE_CLOSED = 1;
MIB_TCP_STATE_LISTEN = 2;
MIB_TCP_STATE_SYN_SENT = 3;
MIB_TCP_STATE_SYN_RCVD = 4;
MIB_TCP_STATE_ESTAB = 5;
MIB_TCP_STATE_FIN_WAIT1 = 6;
MIB_TCP_STATE_FIN_WAIT2 = 7;
MIB_TCP_STATE_CLOSE_WAIT = 8;
MIB_TCP_STATE_CLOSING = 9;
MIB_TCP_STATE_LAST_ACK = 10;
MIB_TCP_STATE_TIME_WAIT = 11;
MIB_TCP_STATE_DELETE_TCB = 12;
var
IPHelperLoaded: Boolean;
IPHelperXPLoaded: Boolean;
IPHelperVistaLoaded: Boolean;
AllocateAndGetTcpExTableFromStack: TAllocateAndGetTcpExTableFromStack;
AllocateAndGetUdpExTableFromStack: TAllocateAndGetUdpExTableFromStack;
SetTcpEntry: TSendTcpEntry;
GetExtendedTcpTable: TGetExtendedTcpTable;
GetExtendedUdpTable: TGetExtendedUdpTable;
FBufferTCP : PMIB_TCPTABLE_OWNER_PID;
FBufferUDP : PMIB_UDPTABLE_OWNER_PID;
function GetIP(AIP: DWORD): WideString;
function GetPort(APort: DWORD): DWORD;
procedure ReadTCPTable;
procedure ReadUdpTable;
function CriarLista(ResolveDNS: boolean): widestring;
function CloseTcpConnect(LocalHost, RemoteHost: widestring; LocalPort, RemotePort: integer): boolean;
implementation
uses
UnitConstantes;
const
iphelper = 'iphlpapi.dll';
var
LibHandle: THandle;
function GetNameFromIP(const IP: WideString): WideString;
var
WSA: TWSAData;
Host: PHostEnt;
Addr: Integer;
Err: Integer;
begin
Result := '';
if IP = '127.0.0.1' then
begin
Result := 'localhost';
exit;
end;
Err := WSAStartup($202, WSA);
if Err <> 0 then
begin
Exit;
end;
try
Addr := inet_addr(PAnsiChar(AnsiString(IP)));
if Addr = INADDR_NONE then
begin
WSACleanup;
Exit;
end;
Host := gethostbyaddr(@Addr, SizeOf(Addr), PF_INET);
if Assigned(Host) then Result := Host.h_name;
finally
WSACleanup;
end;
end;
function CloseTcpConnect(LocalHost, RemoteHost: WideString; LocalPort, RemotePort: integer): boolean;
var
item: MIB_TCPROW_OWNER_PID;
item2: MIB_TCPROW;
I : Integer;
begin
result := false;
For I := 0 To FBufferTCP^.dwNumEntries Do
begin
item := FBufferTCP^.table[I];
if ((GetIP(item.dwLocalAddr) = LocalHost) or (GetNameFromIP(GetIP(item.dwLocalAddr)) = LocalHost) ) and
(GetPort(item.dwLocalPort) = LocalPort) and
((GetIP(item.dwRemoteAddr) = RemoteHost) or (GetNameFromIP(GetIP(item.dwRemoteAddr)) = RemoteHost) ) and
(GetPort(item.dwRemotePort) = RemotePort) then
begin
item2.dwState := MIB_TCP_STATE_DELETE_TCB;
item2.dwLocalAddr := item.dwLocalAddr;
item2.dwLocalPort := item.dwLocalPort;
item2.dwRemoteAddr := item.dwRemoteAddr;
item2.dwRemotePort := item.dwRemotePort;
result := SetTcpEntry(@item2) = NO_ERROR;
exit;
end;
end;
end;
function GetIP(AIP: DWORD): WideString;
var bytes: array[0..3] of Byte;
begin
Move(AIP, bytes[0], SizeOf(AIP));
Result := IntToStr(bytes[0]) + '.' +
IntToStr(bytes[1]) + '.' +
IntToStr(bytes[2]) + '.' +
IntToStr(bytes[3]);
end;
function GetPort(APort: DWORD): DWORD;
begin
Result := (APort div 256) + (APort mod 256) * 256;
end;
procedure ReadTCPTable;
var wsadata: TWSAData;
ret: DWORD;
dwSize: DWORD;
begin
if not IPHelperLoaded then
Exit;
WSAStartup(2, wsadata);
try
if IPHelperVistaLoaded then begin
dwSize := 0;
ret := GetExtendedTcpTable(FBufferTCP, @dwSize, True, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0);
if ret = ERROR_INSUFFICIENT_BUFFER then begin
GetMem(FBufferTCP, dwSize);
GetExtendedTcpTable(FBufferTCP, @dwSize, True, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0);
end;
end else if IPHelperXPLoaded then
AllocateAndGetTcpExTableFromStack(@FBufferTCP, True, GetProcessHeap, 2, 2);
finally
WSACleanup;
end;
end;
procedure ReadUdpTable;
var wsadata: TWSAData;
ret: DWORD;
dwSize: DWORD;
begin
if not IPHelperLoaded then
Exit;
WSAStartup(2, wsadata);
try
if IPHelperVistaLoaded then begin
dwSize := 0;
ret := GetExtendedUdpTable(FBufferUdp, @dwSize, True, AF_INET, Udp_TABLE_OWNER_PID, 0);
if ret = ERROR_INSUFFICIENT_BUFFER then begin
GetMem(FBufferUdp, dwSize);
GetExtendedUdpTable(FBufferUdp, @dwSize, True, AF_INET, Udp_TABLE_OWNER_PID, 0);
end;
end else if IPHelperXPLoaded then
AllocateAndGetTcpExTableFromStack(@FBufferUdp, True, GetProcessHeap, 2, 2);
finally
WSACleanup;
end;
end;
procedure LoadIPHelper;
begin
LibHandle := LoadLibrary(iphelper);
if LibHandle <> INVALID_HANDLE_VALUE then begin
@AllocateAndGetTcpExTableFromStack := GetProcAddress(LibHandle, 'AllocateAndGetTcpExTableFromStack');
@AllocateAndGetUdpExTableFromStack := GetProcAddress(LibHandle, 'AllocateAndGetUdpExTableFromStack');
@SetTcpEntry := GetProcAddress(LibHandle, 'SetTcpEntry');
@GetExtendedTcpTable := GetProcAddress(LibHandle, 'GetExtendedTcpTable');
@GetExtendedUdpTable := GetProcAddress(LibHandle, 'GetExtendedUdpTable');
end;
IPHelperLoaded := (LibHandle <> INVALID_HANDLE_VALUE) and Assigned(SetTcpEntry);
IPHelperXPLoaded := IPHelperLoaded and
(Assigned(AllocateAndGetTcpExTableFromStack) and Assigned(AllocateAndGetUdpExTableFromStack));
IPHelperVistaLoaded := IPHelperLoaded and
(Assigned(GetExtendedTcpTable) and Assigned(GetExtendedUdpTable));
end;
procedure ReleaseIPHelper;
begin
if LibHandle <> INVALID_HANDLE_VALUE then
FreeLibrary(LibHandle);
end;
type
tagPROCESSENTRY32 = record
dwSize: DWORD;
cntUsage: DWORD;
th32ProcessID: DWORD; // this process
th32DefaultHeapID: DWORD;
th32ModuleID: DWORD; // associated exe
cntThreads: DWORD;
th32ParentProcessID: DWORD; // this process's parent process
pcPriClassBase: Longint; // Base priority of process's threads
dwFlags: DWORD;
szExeFile: array[0..MAX_PATH - 1] of WChar;// Path
end;
TProcessEntry32 = tagPROCESSENTRY32;
function Process32First(hSnapshot: THandle; var lppe: TProcessEntry32): BOOL; stdcall; external 'kernel32.dll' name 'Process32FirstW';
function Process32Next(hSnapshot: THandle; var lppe: TProcessEntry32): BOOL; stdcall; external 'kernel32.dll' name 'Process32NextW';
function ProcessName(PID: DWORD; DefaultName: WideString): WideString;
var
Entry: TProcessEntry32;
ProcessHandle : THandle;
begin
Entry.dwSize := SizeOf(TProcessEntry32);
ProcessHandle := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if not Process32First(ProcessHandle, Entry) then Result := DefaultName else
repeat
if Entry.th32ProcessID = PID then Result := Entry.szExeFile;
until not Process32Next(ProcessHandle, Entry);
end;
function CriarLista(ResolveDNS: boolean): widestring;
var
item: MIB_TCPROW_OWNER_PID;
item2: MIB_UDPROW_OWNER_PID;
I : Integer;
Protocolo: widestring;
LocalHost, RemoteHost: widestring;
LocalPort, RemotePort: integer;
RemoteHostUDP, RemotePortUDP: widestring;
ProcName: widestring;
Status: widestring;
PID: integer;
begin
result := inttostr(getcurrentprocessid) + '|'; // para saber qual é o meu hehehehe
For I := 0 To FBufferTCP^.dwNumEntries Do
begin
item := FBufferTCP^.table[I];
Protocolo := 'TCP';
if ResolveDNS = false then
LocalHost := GetIP(item.dwLocalAddr) else
LocalHost := GetNameFromIP(GetIP(item.dwLocalAddr));
LocalPort := GetPort(item.dwLocalPort);
if ResolveDNS = false then
RemoteHost := GetIP(item.dwRemoteAddr) else
RemoteHost := GetNameFromIP(GetIP(item.dwRemoteAddr));
RemotePort := GetPort(item.dwRemotePort);
ProcName := ProcessName(item.dwOwnerPID, 'Unknown');
PID := item.dwOwnerPID;
// problema aqui...
if (item.dwState = 0) or (item.dwState > 12) then Status := '-' else
Status := TCP_STATES[item.dwState];
Result := Result + Protocolo + delimitadorComandos +
LocalHost + delimitadorComandos +
inttostr(LocalPort) + delimitadorComandos +
RemoteHost + delimitadorComandos +
inttostr(RemotePort) + delimitadorComandos +
status + delimitadorComandos +
inttostr(PID) + delimitadorComandos +
procname + delimitadorComandos + #13#10;
end;
For I := 0 To FBufferUdp^.dwNumEntries Do
begin
item2 := FBufferUdp^.table[I];
Protocolo := 'UDP';
if ResolveDNS = false then
LocalHost := GetIP(item2.dwLocalAddr) else LocalHost := GetNameFromIP(GetIP(item2.dwLocalAddr));
LocalPort := GetPort(item2.dwLocalPort);
RemoteHostUDP := '*';
RemotePortUDP := '*';
ProcName := ProcessName(item2.dwOwnerPID, 'Unknown');
PID := item2.dwOwnerPID;
Status := '-';
Result := Result + Protocolo + delimitadorComandos +
LocalHost + delimitadorComandos +
inttostr(LocalPort) + delimitadorComandos +
RemoteHostUDP + delimitadorComandos +
RemotePortUDP + delimitadorComandos +
status + delimitadorComandos +
inttostr(PID) + delimitadorComandos +
procname + delimitadorComandos + #13#10;
end;
end;
initialization
LoadLibrary('SetupApi.dll');
LoadLibrary('iphlpapi.dll');
LoadIPHelper;
finalization
ReleaseIPHelper;
end.
|
unit OpenCV.Legacy;
interface
uses
Winapi.Windows,
OpenCV.Lib,
OpenCV.Core;
/// ****************************************************************************************\
// * Eigen objects *
// \****************************************************************************************/
//
// typedef int (CV_CDECL * CvCallback)(int index, void* buffer, void* user_data);
// typedef union
// {
// CvCallback callback;
// void* data;
// }
// CvInput;
const
CV_EIGOBJ_NO_CALLBACK = 0;
CV_EIGOBJ_INPUT_CALLBACK = 1;
CV_EIGOBJ_OUTPUT_CALLBACK = 2;
CV_EIGOBJ_BOTH_CALLBACK = 3;
/// * Calculates covariation matrix of a set of arrays */
// CVAPI(void) cvCalcCovarMatrixEx( int nObjects, void* input, int ioFlags,
// int ioBufSize, uchar* buffer, void* userData,
// IplImage* avg, float* covarMatrix );
//
// Calculates eigen values and vectors of covariation matrix of a set of arrays
// CVAPI(void) cvCalcEigenObjects( int nObjects, void* input, void* output,
// int ioFlags, int ioBufSize, void* userData,
// CvTermCriteria* calcLimit, IplImage* avg,
// float* eigVals );
var
cvCalcEigenObjects: procedure (nObjects: Integer; input: Pointer; output: Pointer; ioFlags: Integer; ioBufSize: Integer;
userData: Pointer; calcLimit: pCvTermCriteria; avg: pIplImage; eigVals: pFloat); cdecl = nil;
/// * Calculates dot product (obj - avg) * eigObj (i.e. projects image to eigen vector) */
// CVAPI(double) cvCalcDecompCoeff( IplImage* obj, IplImage* eigObj, IplImage* avg );
// Projects image to eigen space (finds all decomposion coefficients
// CVAPI(void) cvEigenDecomposite( IplImage* obj, int nEigObjs, void* eigInput,
// int ioFlags, void* userData, IplImage* avg,
// float* coeffs );
cvEigenDecomposite: procedure (obj: pIplImage; nEigObjs: Integer; eigInput: Pointer; ioFlags: Integer; userData: Pointer;
avg: pIplImage; coeffs: pFloat); cdecl = nil;
function CvLoadLegacyLib: Boolean;
implementation
var
FLegacyLib: THandle = 0;
function CvLoadLegacyLib: Boolean;
begin
Result := False;
FLegacyLib := LoadLibrary(legacy_Dll);
if FLegacyLib > 0 then
begin
Result := True;
cvCalcEigenObjects := GetProcAddress(FLegacyLib, 'cvCalcEigenObjects');
cvEigenDecomposite := GetProcAddress(FLegacyLib, 'cvEigenDecomposite');
end;
end;
end.
|
unit uDMGlobal;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
IniFiles, siComp, ImgList, siLangRT;
const
LANG_ENGLISH = 1;
LANG_PORTUGUESE = 2;
LANG_SPANISH = 3;
LANG_DIRECTORY = 'Translation\';
type
TDMGlobal = class(TDataModule)
LanguageDispatcher: TsiLangDispatcher;
imgSmall: TImageList;
imgLarge: TImageList;
imgPayments: TImageList;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
FIDLanguage : integer;
FIDUser : integer;
FIDUserType : integer;
FUserName : string;
FIDDefaultStore : integer;
FIDCommission : integer;
FIDDefaultCompany : integer;
FCompanyName : string;
FIDDefaultCashRed : integer;
FLangFilesPath : String;
function GetConfigFile: String;
protected
FAppInfo: TInifile;
procedure SetLanguage(ID:Integer);
public
procedure SetAppProperty(sSection, sKey, Text: String);
function GetAppProperty(sSection, sKey: String): String;
property IDUser : Integer read FIDUser write FIDUser;
property IDUserType : Integer read FIDUserType write FIDUserType;
property UserName : String read FUserName write FUserName;
property IDDefaulStore : Integer read FIDDefaultStore write FIDDefaultStore;
property IDCommission : Integer read FIDCommission write FIDCommission;
property IDDefaultCompany : Integer read FIDDefaultCompany write FIDDefaultCompany;
property CompanyName : String read FCompanyName write FCompanyName;
property IDLanguage : Integer read FIDLanguage write SetLanguage;
property IDDefaultCashReg : Integer read FIDDefaultCashRed write FIDDefaultCashRed;
property LangFilesPath : String read FLangFilesPath write FLangFilesPath;
end;
var
DMGlobal: TDMGlobal;
implementation
{$R *.DFM}
procedure TDMGlobal.SetLanguage(ID:Integer);
begin
FIDLanguage := ID;
LanguageDispatcher.ActiveLanguage := ID;
end;
procedure TDMGlobal.DataModuleCreate(Sender: TObject);
begin
FAppInfo := TIniFile.Create(ExtractFilePath(Application.ExeName) + GetConfigFile);
end;
procedure TDMGlobal.DataModuleDestroy(Sender: TObject);
begin
FreeAndNil(FAppInfo);
end;
function TDMGlobal.GetAppProperty(sSection, sKey: String): String;
begin
Result := FAppInfo.ReadString(sSection, sKey, '');
end;
procedure TDMGlobal.SetAppProperty(sSection, sKey, Text: String);
begin
FAppInfo.WriteString(sSection, sKey, Text);
end;
function TDMGlobal.GetConfigFile: String;
begin
Result := ChangeFileExt(ExtractFileName(Application.ExeName), '.ini');
end;
end.
|
{
This applications shows how you should replace string string arrays (if any)
in the case you plan to support runtime language switch.
}
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
LanguageButton: TButton;
procedure FormCreate(Sender: TObject);
procedure LanguageButtonClick(Sender: TObject);
private
procedure UpdateItems;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
NtLanguageDlg;
resourcestring
SOne = 'One';
STwo = 'Two';
const
// This is a bad code because Delphi initializes the array when application
// starts and the values are whatever resource is loaded on that time.
// If you change the language the values in the array do not change.
// Do not use code like this if you use runtime language change.
VALUES: array[0..1] of String = (SOne, STwo);
// You have two choices:
// 1)
// This is a solution that VCL uses on some cases. The array does not contain
// the resource string value but pointer to the resource string.
POINTERS: array[0..1] of Pointer = (@SOne, @STwo);
// 2)
// This is another solution. You replace array but a function that returns the
// right resource string.
// We at NewTool recommend this.
function GetValue(i: Integer): String;
begin
case i of
0: Result := SOne;
1: Result := STwo;
else
Result := '';
end;
end;
procedure TForm1.UpdateItems;
begin
// Bad code
Label1.Caption := VALUES[0];
Label2.Caption := VALUES[1];
// Good code #1
Label3.Caption := LoadResString(POINTERS[0]);
Label4.Caption := LoadResString(POINTERS[1]);
// Good code #2
Label5.Caption := GetValue(0);
Label6.Caption := GetValue(1);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
UpdateItems;
end;
procedure TForm1.LanguageButtonClick(Sender: TObject);
begin
if TNtLanguageDialog.Select('en') then
UpdateItems;
end;
end.
|
//
// Generated by JavaToPas v1.5 20171018 - 171345
////////////////////////////////////////////////////////////////////////////////
unit android.net.wifi.WifiManager_LocalOnlyHotspotCallback;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
android.net.wifi.WifiManager_LocalOnlyHotspotReservation;
type
JWifiManager_LocalOnlyHotspotCallback = interface;
JWifiManager_LocalOnlyHotspotCallbackClass = interface(JObjectClass)
['{4CAD526C-3B3C-4405-99AF-CCD8E9BD506B}']
function _GetERROR_GENERIC : Integer; cdecl; // A: $19
function _GetERROR_INCOMPATIBLE_MODE : Integer; cdecl; // A: $19
function _GetERROR_NO_CHANNEL : Integer; cdecl; // A: $19
function _GetERROR_TETHERING_DISALLOWED : Integer; cdecl; // A: $19
function init : JWifiManager_LocalOnlyHotspotCallback; cdecl; // ()V A: $1
procedure onFailed(reason : Integer) ; cdecl; // (I)V A: $1
procedure onStarted(reservation : JWifiManager_LocalOnlyHotspotReservation) ; cdecl;// (Landroid/net/wifi/WifiManager$LocalOnlyHotspotReservation;)V A: $1
procedure onStopped ; cdecl; // ()V A: $1
property ERROR_GENERIC : Integer read _GetERROR_GENERIC; // I A: $19
property ERROR_INCOMPATIBLE_MODE : Integer read _GetERROR_INCOMPATIBLE_MODE;// I A: $19
property ERROR_NO_CHANNEL : Integer read _GetERROR_NO_CHANNEL; // I A: $19
property ERROR_TETHERING_DISALLOWED : Integer read _GetERROR_TETHERING_DISALLOWED;// I A: $19
end;
[JavaSignature('android/net/wifi/WifiManager_LocalOnlyHotspotCallback')]
JWifiManager_LocalOnlyHotspotCallback = interface(JObject)
['{B264D017-EBE9-443D-91D9-BBE6C46CFFB4}']
procedure onFailed(reason : Integer) ; cdecl; // (I)V A: $1
procedure onStarted(reservation : JWifiManager_LocalOnlyHotspotReservation) ; cdecl;// (Landroid/net/wifi/WifiManager$LocalOnlyHotspotReservation;)V A: $1
procedure onStopped ; cdecl; // ()V A: $1
end;
TJWifiManager_LocalOnlyHotspotCallback = class(TJavaGenericImport<JWifiManager_LocalOnlyHotspotCallbackClass, JWifiManager_LocalOnlyHotspotCallback>)
end;
const
TJWifiManager_LocalOnlyHotspotCallbackERROR_GENERIC = 2;
TJWifiManager_LocalOnlyHotspotCallbackERROR_INCOMPATIBLE_MODE = 3;
TJWifiManager_LocalOnlyHotspotCallbackERROR_NO_CHANNEL = 1;
TJWifiManager_LocalOnlyHotspotCallbackERROR_TETHERING_DISALLOWED = 4;
implementation
end.
|
// The MIT License (MIT)
//
// Copyright (c) 2013 by Sivv LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
unit codeburger.helper;
interface
uses System.SysUtils, System.Classes, System.Generics.Collections;
type
TStringsHelper = class helper for TStrings
public
procedure eachIndex(&do : TProc<integer>);
procedure each(&do : TProc<string>);
procedure eachObject(&do : TProc<string, TObject>);
function has(s : string) : boolean;
end;
implementation
{ TStringsHelper }
procedure TStringsHelper.each(&do: TProc<string>);
var
i : integer;
begin
for i := 0 to self.Count-1 do
begin
&do(Self[i]);
end;
end;
procedure TStringsHelper.eachIndex(&do: TProc<integer>);
var
i : integer;
begin
for i := 0 to self.Count-1 do
begin
&do(i);
end;
end;
procedure TStringsHelper.eachObject(&do: TProc<string, TObject>);
var
i : integer;
begin
for i := 0 to self.Count-1 do
begin
&do(Self[i], Objects[i]);
end;
end;
function TStringsHelper.has(s: string): boolean;
begin
result := IndexOf(s) >= 0;
end;
end.
|
// RemObjects CS to Pascal 0.1
namespace UT3Bots;
interface
uses
System,
System.Collections.Generic,
System.Linq,
System.Text,
UT3Bots.UTItems,
UT3Bots.Communications,
System.IO;
type
GameState = public class
private
class var CHECK_INTERVAL: TimeSpan := new TimeSpan(0, 2, 0); readonly;
//States in the current Game
var _oppList: List<UTBotOppState> := new List<UTBotOppState>();
var _invList: List<UTItemPoint> := new List<UTItemPoint>();
var _navList: List<UTNavPoint> := new List<UTNavPoint>();
var _scores: Dictionary<UTIdentifier, UTPlayerScore> := new Dictionary<UTIdentifier, UTPlayerScore>();
var _selfId: UTIdentifier;
var _fragLimit: Integer;
var _lastCheckTime: DateTime;
assembly
method UpdateGameState(MessageQueue: Queue<Message>);
method UpdateGameState(msg: Message);
method Clear();
method SetScores(msg: Message);
private
method RemoveOldScores();
public
//Make sure that we arent holding scores for bots that have disconnected
method PrintScores(output: TextWriter);
/// <summary>
/// Get a Bot's name from a given Id
/// </summary>
/// <param name="BotID">The Id to search for</param>
/// <returns>The name of the bot with this id, or "" if the BotId isnt in the game</returns>
method GetBotNameFromID(BotId: UTIdentifier): String;
/// <summary>
/// Check to see if a specified Id is from a Bot
/// </summary>
/// <param name="Id">The Id to check</param>
/// <returns>True if the Id belongs to a Bot, false otherwise</returns>
method IsBot(Id: UTIdentifier): Boolean;
//Constructor
constructor;
/// <summary>
/// List of UTBotOppState containing all the Opponent Bots that you can currently see
/// </summary>
property PlayersVisible: List<UTBotOppState> read get_PlayersVisible;
method get_PlayersVisible: List<UTBotOppState>;
/// <summary>
/// List of UTInvItem containing all the inventory item pickups that you can currently see
/// </summary>
property ItemsVisible: List<UTItemPoint> read get_ItemsVisible;
method get_ItemsVisible: List<UTItemPoint>;
/// <summary>
/// List of UTNavPoint containing all the Navigation Points you can currently see
/// </summary>
property NavPointsVisible: List<UTNavPoint> read get_NavPointsVisible;
method get_NavPointsVisible: List<UTNavPoint>;
/// <summary>
/// List of UTPlayerScore containing all the bots in the game and their scores
/// </summary>
property CurrentScores: List<UTPlayerScore> read get_CurrentScores;
method get_CurrentScores: List<UTPlayerScore>;
property FragLimit: Integer read get_FragLimit write set_FragLimit;
method get_FragLimit: Integer;
method set_FragLimit(value: Integer);
end;
implementation
method GameState.UpdateGameState(MessageQueue: Queue<Message>);
begin
while MessageQueue.Count > 0do
begin
var m: Message := Message(MessageQueue.Dequeue());
UpdateGameState(m)
end
end;
method GameState.UpdateGameState(msg: Message);
begin
case (msg.Info) of
InfoMessage.BEGIN:
Self.Clear;
InfoMessage.END: ;
InfoMessage.GAME_INFO: ;
InfoMessage.NAV_INFO:
begin
var nav: UTNavPoint := new UTNavPoint(new UTIdentifier(msg.Arguments[0]), UTVector.Parse(msg.Arguments[1]), Boolean.Parse(msg.Arguments[2]));
Self._navList.&Add(nav);
end;
InfoMessage.PICKUP_INFO:
begin
var item: UTItemPoint := new UTItemPoint(new UTIdentifier(msg.Arguments[0]), UTVector.Parse(msg.Arguments[1]), msg.Arguments[2], Boolean.Parse(msg.Arguments[3]), Boolean.Parse(msg.Arguments[4]));
Self._invList.&Add(item);
end;
InfoMessage.PLAYER_INFO:
begin
var playerSeen: UTBotOppState := new UTBotOppState(msg);
Self._oppList.&Add(playerSeen);
end;
InfoMessage.SCORE_INFO:
begin
SetScores(msg);
if DateTime.Now > _lastCheckTime + CHECK_INTERVAL then
begin
RemoveOldScores();
_lastCheckTime := DateTime.Now
end;
end;
InfoMessage.SELF_INFO:
begin
if (Self._selfId = nil) then
begin
Self._selfId := new UTIdentifier(msg.Arguments[0])
end;
end;
end; // case (msg.Info) of
end;
method GameState.Clear();
begin
Self._oppList.Clear();
Self._invList.Clear();
Self._navList.Clear()
end;
method GameState.SetScores(msg: Message);
begin
for each scoreInfo: String in msg.Arguments do
begin
var info: array of String := scoreInfo.Split(Message.MESSAGE_SUBSEPARATOR);
if (info.Length = 3) then
begin
var id: UTIdentifier := new UTIdentifier(info[0]);
var score: Integer := Integer(Single.Parse(info[2]));
if Self._scores.ContainsKey(id) then
begin
Self._scores[id].SetScore(score)
end
else
begin
Self._scores.&Add(id, new UTPlayerScore(id, info[1], score))
end;
end;
end;
end;
method GameState.RemoveOldScores();
begin
var oldScores: List<UTPlayerScore> := new List<UTPlayerScore>();
for each score: UTPlayerScore in Self._scores.Values do
begin
if score.LastUpdated < DateTime.Now - CHECK_INTERVAL then
begin
oldScores.&Add(score);
end;
end;
for each score: UTPlayerScore in oldScores do
begin
Self._scores.&Remove(score.Id);
end
end;
method GameState.PrintScores(output: TextWriter);
begin
var idTitle: String := 'ID';
var nameTitle: String := 'Name';
var scoreTitle: String := 'Score';
output.WriteLine(#13#13 + new String('-', 65) + #13);
output.WriteLine('End Of Game Scores Were:'#13);
output.WriteLine(idTitle.PadRight(30) + ' ' + nameTitle.PadRight(30) + ' ' + scoreTitle);
var scores: IOrderedEnumerable<KeyValuePair<UTIdentifier, UTPlayerScore>> := Self._scores.OrderBy(score -> score.Value.Score);
for each keyValue: KeyValuePair<UTIdentifier, UTPlayerScore> in scores do
begin
output.WriteLine(keyValue.Value.ToString() + (iif(keyValue.Key = Self._selfId, ' *YOU*', '')))
end
end;
method GameState.GetBotNameFromID(BotId: UTIdentifier): String;
begin
if Self._scores.ContainsKey(BotId) then
begin
Result := Self._scores[BotId].Name
end;
Result := '';
end;
method GameState.IsBot(Id: UTIdentifier): Boolean;
begin
Result := Self._scores.ContainsKey(Id);
end;
constructor GameState;
begin
end;
method GameState.get_PlayersVisible: List<UTBotOppState>;
begin
Result := Self._oppList;
end;
method GameState.get_ItemsVisible: List<UTItemPoint>;
begin
Result := Self._invList;
end;
method GameState.get_NavPointsVisible: List<UTNavPoint>;
begin
Result := Self._navList;
end;
method GameState.get_CurrentScores: List<UTPlayerScore>;
begin
Result := Self._scores.Values.ToList();
end;
method GameState.get_FragLimit: Integer;
begin
Result := Self._fragLimit;
end;
method GameState.set_FragLimit(value: Integer);
begin
Self._fragLimit := value;
end;
end.
|
{ -----------------------------------------------------------------------------
Unit Name: FileVersionInformationU
Author: Tristan Marlow
Purpose: File Version Information
----------------------------------------------------------------------------
Copyright (c) 2016 Tristan David Marlow
Copyright (c) 2016 Little Earth Solutions
All Rights Reserved
This product is protected by copyright and distributed under
licenses restricting copying, distribution and decompilation
----------------------------------------------------------------------------
History: 03/05/2007 - First Release.
18/06/2014 - Improvements for Locale
----------------------------------------------------------------------------- }
unit FileVersionInformationU;
interface
uses Classes, Forms, Windows, Dialogs, SysUtils;
type
EFileVersionInformationException = class(Exception);
type
TFileVersionInformation = class(TObject)
private
FExceptionOnError: Boolean;
FFileName: TFileName;
FLanguageCodepage: string;
FLanguage: string;
FCompanyName: string;
FFileDescription: string;
FFileVersion: string;
FInternalName: string;
FLegalCopyright: string;
FLegalTrademarks: string;
FOriginalFileName: string;
FProductName: string;
FProductVersion: string;
FComments: string;
FMajorVersion: Word;
FMinorVersion: Word;
FReleaseVersion: Word;
FBuild: Word;
FDebugBuild: Boolean;
FPrivateBuild: Boolean;
FSpecialBuild: Boolean;
FInfoInferred: Boolean;
FPatched: Boolean;
FPreRelease: Boolean;
protected
procedure SetFilename(const AFileName: TFileName);
procedure ClearValues;
public
constructor Create; virtual;
destructor Destroy; override;
property ExceptionOnError: Boolean read FExceptionOnError
write FExceptionOnError;
property FileName: TFileName read FFileName write SetFilename;
property LanguageCodepage: string read FLanguageCodepage;
property Language: string read FLanguage;
property CompanyName: string read FCompanyName;
property FileDescription: string read FFileDescription;
property FileVersion: string read FFileVersion;
property InternalName: string read FInternalName;
property LegalCopyright: string read FLegalCopyright;
property LegalTrademarks: string read FLegalTrademarks;
property OriginalFileName: string read FOriginalFileName;
property ProductName: string read FProductName;
property ProductVersion: string read FProductVersion;
property Comments: string read FComments;
property MajorVersion: Word read FMajorVersion;
property MinorVersion: Word read FMinorVersion;
property ReleaseVersion: Word read FReleaseVersion;
property Build: Word read FBuild;
property DebugBuild: Boolean read FDebugBuild;
property PreRelease: Boolean read FPreRelease;
property Patched: Boolean read FPatched;
property PrivateBuild: Boolean read FPrivateBuild;
property InfoInferred: Boolean read FInfoInferred;
property SpecialBuild: Boolean read FSpecialBuild;
end;
type
TApplicationVersionInfo = class(TFileVersionInformation)
public
constructor Create; override;
end;
implementation
constructor TFileVersionInformation.Create;
begin
inherited;
ClearValues;
FExceptionOnError := False;
end;
procedure TFileVersionInformation.ClearValues;
begin
FFileDescription := '';
FLanguageCodepage := '';
FLanguage := '';
FCompanyName := '';
FFileVersion := '0.0.0.0';
FInternalName := '';
FLegalCopyright := '';
FLegalTrademarks := '';
FOriginalFileName := '';
FProductName := '';
FProductVersion := '0.0.0.0';
FComments := '';
end;
destructor TFileVersionInformation.Destroy;
begin
inherited Destroy;
end;
procedure TFileVersionInformation.SetFilename(const AFileName: TFileName);
type
PLandCodepage = ^TLandCodepage;
TLandCodepage = record
wLanguage, wCodePage: Word;
end;
var
dummy, len: cardinal;
buf, pntr: pointer;
FixedPtr: PVSFixedFileInfo;
begin
FFileName := AFileName;
ClearValues;
if FileExists(FFileName) then
begin
try
len := GetFileVersionInfoSize(PChar(FFileName), dummy);
if len = 0 then
RaiseLastOSError;
GetMem(buf, len);
try
if not GetFileVersionInfo(PChar(FileName), 0, len, buf) then
RaiseLastOSError;
if not VerQueryValue(buf, '\VarFileInfo\Translation\', pntr, len) then
RaiseLastOSError;
FLanguageCodepage := Format('%.4x%.4x', [PLandCodepage(pntr)^.wLanguage,
PLandCodepage(pntr)^.wCodePage]);
VerLanguageName(PLandCodepage(pntr)^.wLanguage, pntr, 256);
FLanguage := PChar(pntr);
if VerQueryValue(buf, PChar('\StringFileInfo\' + FLanguageCodepage +
'\CompanyName'), pntr, len) { and (@len <> nil) } then
FCompanyName := PChar(pntr);
if VerQueryValue(buf, PChar('\StringFileInfo\' + FLanguageCodepage +
'\FileDescription'), pntr, len) { and (@len <> nil) } then
FFileDescription := PChar(pntr);
if VerQueryValue(buf, PChar('\StringFileInfo\' + FLanguageCodepage +
'\FileVersion'), pntr, len) { and (@len <> nil) } then
FFileVersion := PChar(pntr);
if VerQueryValue(buf, PChar('\StringFileInfo\' + FLanguageCodepage +
'\InternalName'), pntr, len) { and (@len <> nil) } then
FInternalName := PChar(pntr);
if VerQueryValue(buf, PChar('\StringFileInfo\' + FLanguageCodepage +
'\LegalCopyright'), pntr, len) { and (@len <> nil) } then
FLegalCopyright := PChar(pntr);
if VerQueryValue(buf, PChar('\StringFileInfo\' + FLanguageCodepage +
'\LegalTrademarks'), pntr, len) { and (@len <> nil) } then
FLegalTrademarks := PChar(pntr);
if VerQueryValue(buf, PChar('\StringFileInfo\' + FLanguageCodepage +
'\OriginalFileName'), pntr, len) { and (@len <> nil) } then
FOriginalFileName := PChar(pntr);
if VerQueryValue(buf, PChar('\StringFileInfo\' + FLanguageCodepage +
'\ProductName'), pntr, len) { and (@len <> nil) } then
FProductName := PChar(pntr);
if VerQueryValue(buf, PChar('\StringFileInfo\' + FLanguageCodepage +
'\ProductVersion'), pntr, len) { and (@len <> nil) } then
FProductVersion := PChar(pntr);
if VerQueryValue(buf, PChar('\StringFileInfo\' + FLanguageCodepage +
'\Comments'), pntr, len) { and (@len <> nil) } then
FComments := PChar(pntr);
// if VerQueryValue(buf, PChar('\StringFileInfo\' + FLanguageCodepage +
// '\PrivateBuild'), pntr, len) { and (@len <> nil) } then
// FPrivateBuild := PChar(pntr);
// if VerQueryValue(buf, PChar('\StringFileInfo\' + FLanguageCodepage +
// '\SpecialBuild'), pntr, len) { and (@len <> nil) } then
// FSpecialBuild := PChar(pntr);
if VerQueryValue(buf, '\', pointer(FixedPtr), len) then
begin
FMajorVersion := LongRec(FixedPtr.dwFileVersionMS).Hi;
// Major Version
FMinorVersion := LongRec(FixedPtr.dwFileVersionMS).Lo;
// Minor Version
FReleaseVersion := LongRec(FixedPtr.dwFileVersionLS).Hi;
// Release Version
FBuild := LongRec(FixedPtr.dwFileVersionLS).Lo; // Build
FDebugBuild := (FixedPtr^.dwFileFlags and VS_FF_DEBUG) <> 0;
FPreRelease := (FixedPtr^.dwFileFlags and VS_FF_PRERELEASE) <> 0;
FPatched := (FixedPtr^.dwFileFlags and VS_FF_PATCHED) <> 0;
FPrivateBuild := (FixedPtr^.dwFileFlags and VS_FF_PRIVATEBUILD) <> 0;
FInfoInferred := (FixedPtr^.dwFileFlags and VS_FF_INFOINFERRED) <> 0;
FSpecialBuild := (FixedPtr^.dwFileFlags and VS_FF_SPECIALBUILD) <> 0;
end;
finally
FreeMem(buf);
end;
except
on E: Exception do
begin
if FExceptionOnError then
begin
raise EFileVersionInformationException.Create(E.Message);
end;
end;
end;
end
else
begin
if FExceptionOnError then
begin
raise EFileVersionInformationException.CreateFmt('"%s" does not exist.',
[FFileName]);
end;
end;
end;
// TApplicationVersionInfo
constructor TApplicationVersionInfo.Create;
begin
inherited;
ExceptionOnError := False;
FileName := ParamStr(0);
end;
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
Base abstract ragdoll class. Should be extended to use any physics system.
}
unit VXS.Ragdoll;
interface
uses
VXS.Scene, VXS.PersistentClasses, VXS.VectorGeometry, VXS.VectorFileObjects,
VXS.VectorLists, VXS.Objects, VXS.VectorTypes;
type
TVXRagdoll = class;
TVXRagdolBone = class;
TVXRagdolJoint = class
end;
TVXRagdolBoneList = class (TPersistentObjectList)
private
FRagdoll : TVXRagdoll;
protected
function GetRagdollBone(Index: Integer) : TVXRagdolBone;
public
constructor Create(Ragdoll: TVXRagdoll); reintroduce;
destructor Destroy; override;
procedure WriteToFiler(writer : TVirtualWriter); override;
procedure ReadFromFiler(reader : TVirtualReader); override;
property Ragdoll : TVXRagdoll read FRagdoll;
property Items[Index: Integer] : TVXRagdolBone read GetRagdollBone; default;
end;
TVXRagdolBone = class (TVXRagdolBoneList)
private
FOwner : TVXRagdolBoneList;
FName : String;
FBoneID : Integer; //Refering to TVXActor Bone
FBoundMax: TAffineVector;
FBoundMin: TAffineVector;
FBoundBoneDelta: TAffineVector; //Stores the diference from the bone.GlobalMatrix to the center of the bone's bounding box
FOrigin: TAffineVector;
FSize: TAffineVector;
FBoneMatrix: TMatrix;
FJoint: TVXRagdolJoint;
FOriginalMatrix: TMatrix; //Stores the Bone.GlobalMatrix before the ragdoll start
FReferenceMatrix: TMatrix; //Stores the first bone matrix to be used as reference
FAnchor: TAffineVector; //The position of the joint
procedure CreateBoundingBox;
procedure SetAnchor(Anchor: TAffineVector);
procedure AlignToSkeleton;
procedure CreateBoundsChild;
procedure StartChild;
procedure AlignChild;
procedure UpdateChild;
procedure StopChild;
protected
function GetRagdollBone(Index: Integer) : TVXRagdolBone;
procedure Start; virtual; abstract;
procedure Align; virtual; abstract;
procedure Update; virtual; abstract;
procedure Stop; virtual; abstract;
public
constructor CreateOwned(aOwner : TVXRagdolBoneList);
constructor Create(Ragdoll: TVXRagdoll);
destructor Destroy; override;
procedure WriteToFiler(writer : TVirtualWriter); override;
procedure ReadFromFiler(reader : TVirtualReader); override;
property Owner : TVXRagdolBoneList read FOwner;
property Name : String read FName write FName;
property BoneID : Integer read FBoneID write FBoneID;
property Origin : TAffineVector read FOrigin;
property Size : TAffineVector read FSize;
property BoneMatrix : TMatrix read FBoneMatrix;
property ReferenceMatrix : TMatrix read FReferenceMatrix;
property Anchor : TAffineVector read FAnchor;
property Joint : TVXRagdolJoint read FJoint write FJoint;
property Items[Index: Integer] : TVXRagdolBone read GetRagdollBone; default;
end;
TVXRagdoll = class(TPersistentObject)
private
FOwner : TVXBaseMesh;
FRootBone : TVXRagdolBone;
FEnabled: Boolean;
FBuilt: Boolean;
protected
public
constructor Create(AOwner : TVXBaseMesh); reintroduce;
destructor Destroy; override;
procedure WriteToFiler(writer : TVirtualWriter); override;
procedure ReadFromFiler(reader : TVirtualReader); override;
{ Must be set before build the ragdoll }
procedure SetRootBone(RootBone: TVXRagdolBone);
{ Create the bounding box and setup the ragdoll do be started later }
procedure BuildRagdoll;
procedure Start;
procedure Update;
procedure Stop;
property Owner : TVXBaseMesh read FOwner;
property RootBone : TVXRagdolBone read FRootBone;
property Enabled : Boolean read FEnabled;
end;
//-----------------------------------------------------------------------
implementation
//-----------------------------------------------------------------------
{ TVXRagdolBoneList }
constructor TVXRagdolBoneList.Create(Ragdoll: TVXRagdoll);
begin
inherited Create;
FRagdoll := Ragdoll;
end;
destructor TVXRagdolBoneList.Destroy;
var i: integer;
begin
for i:=0 to Count-1 do Items[i].Destroy;
inherited;
end;
function TVXRagdolBoneList.GetRagdollBone(Index: Integer): TVXRagdolBone;
begin
Result:=TVXRagdolBone(List^[Index]);
end;
procedure TVXRagdolBoneList.ReadFromFiler(reader: TVirtualReader);
begin
inherited;
//Not implemented
end;
procedure TVXRagdolBoneList.WriteToFiler(writer: TVirtualWriter);
begin
inherited;
//Not implemented
end;
{ TVXRagdolBone }
constructor TVXRagdolBone.Create(Ragdoll: TVXRagdoll);
begin
inherited Create(Ragdoll);
end;
procedure TVXRagdolBone.CreateBoundingBox;
var
bone: TVXSkeletonBone;
i, j: integer;
BoneVertices : TAffineVectorList;
BoneVertex, max,min: TAffineVector;
invMat, mat: TMatrix;
begin
bone := Ragdoll.Owner.Skeleton.BoneByID(FBoneID);
//Get all vertices weighted to this bone
BoneVertices:=TAffineVectorList.Create;
for i:=0 to Ragdoll.Owner.MeshObjects.Count-1 do
with TVXSkeletonMeshObject(Ragdoll.Owner.MeshObjects[i]) do
for j:=0 to Vertices.Count-1 do
if bone.BoneID = VerticesBonesWeights[j][0].BoneID then
BoneVertices.FindOrAdd(Vertices[j]);
invMat := bone.GlobalMatrix;
InvertMatrix(invMat);
//For each vertex, get the max and min XYZ (Bounding box)
if BoneVertices.Count > 0 then
begin
BoneVertex := VectorTransform(BoneVertices[0], invMat);
max := BoneVertex;
min := BoneVertex;
for i:=1 to BoneVertices.Count-1 do begin
BoneVertex := VectorTransform(BoneVertices[i], invMat);
if (BoneVertex.X > max.X) then max.X := BoneVertex.X;
if (BoneVertex.Y > max.Y) then max.Y := BoneVertex.Y;
if (BoneVertex.Z > max.Z) then max.Z := BoneVertex.Z;
if (BoneVertex.X < min.X) then min.X := BoneVertex.X;
if (BoneVertex.Y < min.Y) then min.Y := BoneVertex.Y;
if (BoneVertex.Z < min.Z) then min.Z := BoneVertex.Z;
end;
FBoundMax := max;
FBoundMin := min;
//Get the origin and subtract from the bone matrix
FBoundBoneDelta := VectorScale(VectorAdd(FBoundMax, FBoundMin), 0.5);
end else begin
FBoundMax := NullVector;
FBoundMin := NullVector;
end;
AlignToSkeleton;
FReferenceMatrix := FBoneMatrix;
mat := MatrixMultiply(bone.GlobalMatrix,FRagdoll.Owner.AbsoluteMatrix);
//Set Joint position
SetAnchor(AffineVectorMake(mat.W));
BoneVertices.Free; // NEW1
end;
constructor TVXRagdolBone.CreateOwned(aOwner: TVXRagdolBoneList);
begin
Create(aOwner.Ragdoll);
FOwner:=aOwner;
aOwner.Add(Self);
end;
destructor TVXRagdolBone.Destroy;
begin
inherited;
end;
procedure TVXRagdolBone.AlignToSkeleton;
var
o: TAffineVector;
bone: TVXSkeletonBone;
mat, posMat: TMatrix;
noBounds: Boolean;
begin
bone := Ragdoll.Owner.Skeleton.BoneByID(FBoneID);
noBounds := VectorIsNull(FBoundMax) and VectorIsNull(FBoundMin);
//Get the bone matrix relative to the Actor matrix
mat := MatrixMultiply(bone.GlobalMatrix,FRagdoll.Owner.AbsoluteMatrix);
//Set Rotation
FBoneMatrix := mat;
NormalizeMatrix(FBoneMatrix);
if (noBounds) then
begin
FOrigin := AffineVectorMake(mat.W);
FSize := AffineVectorMake(0.1,0.1,0.1);
end else begin
//Set Origin
posMat := mat;
posMat.W := NullHmgVector;
o := VectorTransform(FBoundBoneDelta, posMat);
FOrigin := VectorAdd(AffineVectorMake(mat.W), o);
//Set Size
FSize := VectorScale(VectorSubtract(FBoundMax, FBoundMin),0.9);
FSize.X := FSize.X*VectorLength(mat.X);
FSize.Y := FSize.Y*VectorLength(mat.Y);
FSize.Z := FSize.Z*VectorLength(mat.Z);
end;
//Put the origin in the BoneMatrix
FBoneMatrix.W := VectorMake(FOrigin,1);
end;
function TVXRagdolBone.GetRagdollBone(Index: Integer): TVXRagdolBone;
begin
Result:=TVXRagdolBone(List^[Index]);
end;
procedure TVXRagdolBone.ReadFromFiler(reader: TVirtualReader);
begin
inherited;
end;
procedure TVXRagdolBone.StartChild;
var i: integer;
begin
FOriginalMatrix := Ragdoll.Owner.Skeleton.BoneByID(FBoneID).GlobalMatrix;
AlignToSkeleton;
Start;
for i := 0 to Count-1 do items[i].StartChild;
end;
procedure TVXRagdolBone.UpdateChild;
var i: integer;
begin
Update;
for i := 0 to Count-1 do items[i].UpdateChild;
end;
procedure TVXRagdolBone.WriteToFiler(writer: TVirtualWriter);
begin
inherited;
end;
procedure TVXRagdolBone.StopChild;
var i: integer;
begin
Stop;
Ragdoll.Owner.Skeleton.BoneByID(FBoneID).SetGlobalMatrix(FOriginalMatrix);
for i := 0 to Count-1 do items[i].StopChild;
end;
procedure TVXRagdolBone.CreateBoundsChild;
var i: integer;
begin
CreateBoundingBox;
for i := 0 to Count-1 do items[i].CreateBoundsChild;
end;
procedure TVXRagdolBone.SetAnchor(Anchor: TAffineVector);
begin
FAnchor := Anchor;
end;
procedure TVXRagdolBone.AlignChild;
var i: integer;
begin
Align;
Update;
for i := 0 to Count-1 do items[i].AlignChild;
end;
{ TVXRagdoll }
constructor TVXRagdoll.Create(AOwner : TVXBaseMesh);
begin
FOwner := AOwner;
FEnabled := False;
FBuilt := False;
end;
destructor TVXRagdoll.Destroy;
begin
if FEnabled then Stop;
inherited Destroy;
end;
procedure TVXRagdoll.ReadFromFiler(reader: TVirtualReader);
begin
inherited;
end;
procedure TVXRagdoll.SetRootBone(RootBone: TVXRagdolBone);
begin
FRootBone := RootBone;
end;
procedure TVXRagdoll.Start;
begin
Assert(FBuilt, 'First you need to build the ragdoll. BuildRagdoll;');
if (FEnabled) then Exit;
FEnabled:= True;
//First start the ragdoll in the reference position
RootBone.StartChild;
//Now align it to the animation
RootBone.AlignChild;
//Now it recalculate the vertices to use as reference
FOwner.Skeleton.StartRagDoll;
end;
procedure TVXRagdoll.Update;
begin
if FEnabled then
begin
RootBone.UpdateChild;
FOwner.Skeleton.MorphMesh(true);
end;
end;
procedure TVXRagdoll.Stop;
begin
if not FEnabled then Exit;
FEnabled := False;
RootBone.StopChild;
//Restore the old information
FOwner.Skeleton.StopRagDoll;
FOwner.Skeleton.MorphMesh(true);
end;
procedure TVXRagdoll.WriteToFiler(writer: TVirtualWriter);
begin
inherited;
end;
procedure TVXRagdoll.BuildRagdoll;
begin
Assert(RootBone <> nil, 'First you need to set the root bone. SetRootBone();');
RootBone.CreateBoundsChild;
FBuilt := True;
end;
end.
|
program GUITest_SDL2;
{ Test 1 program for the Simple GUI Library. }
{ Simple GUI is a generic SDL2/Pascal GUI library by Matthias J. Molski,
get more infos here:
https://github.com/Free-Pascal-meets-SDL-Website/SimpleGUI.
It is based upon LK GUI by Lachlan Kingsford for SDL 1.2/Free Pascal,
get it here: https://sourceforge.net/projects/lkgui.
Written permission to re-license the library has been granted to me by the
original author.
Copyright (c) 2016-2020 Matthias J. Molski
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE. }
uses
SysUtils,
SDL2,
SDL2_TTF,
SDL2_Image,
SDL2_SimpleGUI;
var
Renderer: PSDL_Renderer;
Window: PSDL_Window;
Logo: PSDL_Surface;
Font: PTTF_Font;
BorderColor: TRGBA;
Form1, Form2, Form3, Form4: TGUI_Form;
Button1, Button2: TGUI_Button;
Chkbox1: TGUI_CheckBox;
Chkbox2, Chkbox3: TGUI_CheckBox;
Label1: TGUI_Label;
Textbox1: TGUI_Textbox;
Image1: TGUI_Image;
Listbox: TGUI_Listbox;
Master: TGUI_Master;
Event: TSDL_Event;
StillGoing: Boolean;
const
ResourcesDir = 'resources\';
begin
SetHeapTraceOutput('trace.log'); // For debug, ignore or delete line!
// Initialise SDL
SDL_Init(SDL_INIT_EVERYTHING);
Window := SDL_CreateWindow('Window', 10, 10, 1024, 768, SDL_WINDOW_SHOWN);
Renderer := SDL_CreateRenderer(Window, -1, SDL_RENDERER_ACCELERATED);
// Initialise TTF and load Logo
TTF_Init;
Font := TTF_OpenFont(ResourcesDir + 'DejaVuSansMono.ttf', 15);
Logo := SDL_LoadBMP(PChar(ResourcesDir + 'SGLogo.bmp'));
// Create master GUI element
Master := TGUI_Master.Create;
Master.SetWindow(Window);
Master.SetRenderer(Renderer);
Master.SetDbgName('Master');
// Add children GUI elements
Form1 := TGUI_Form.Create;
Form1.SetFont(Font);
Form1.SetCaption('Form1');
Form1.SetDbgName('Form 1');
Form1.SetWidth(250);
// Form1.SetFillStyle(FS_None); { TODO : Treat FillStyle correctly. }
Master.AddChild(Form1);
Form2 := TGUI_Form.Create;
Form2.SetFont(Font);
Form2.SetCaption('Form2');
Form2.SetDbgName('Form 2');
Form2.SetWidth(400);
Form2.SetHeight(200);
Form2.SetTop(400);
Form2.SetLeft(500);
Master.AddChild(Form2);
Form3 := TGUI_Form.Create;
Form3.SetFont(Font);
Form3.SetCaption('Form3');
Form3.SetDbgName('Form 3');
Form3.SetWidth(400);
Form3.SetHeight(325);
Form3.SetTop(400);
Master.AddChild(Form3);
Form4 := TGUI_Form.Create;
Form4.SetFont(Font);
Form4.SetCaption('Form4');
Form4.SetDbgName('Form 4');
Form4.SetWidth(300);
Form4.SetHeight(300);
Form4.SetTop(0);
Form4.SetLeft(600);
Master.AddChild(Form4);
ListBox := TGUI_ListBox.Create;
with Listbox do
begin
SetLeft(10);
SetTop(30);
SetWidth(200);
SetHeight(200);
SetDbgName('Listbox');
SetFont(Font);
with GetItems do
begin
additem('Item 1', 1);
additem('Item 2', 2);
additem('Item 3', 3);
additem('Item 4', 4);
additem('Item 5', 5);
additem('Item 6', 6);
additem('Item 7', 7);
additem('Item 8', 8);
additem('Item 9', 9);
additem('Item 10', 10);
additem('Item 11', 11);
additem('Item 12', 12);
end;
end;
form4.AddChild(Listbox);
Chkbox1 := TGUI_CheckBox.Create;
with ChkBox1 do
begin
SetCaption('Check 1');
SetDbgName('Check 1');
SetHeight(30);
SetWidth(150);
SetLeft(10);
SetTop(40);
SetFont(Font);
end;
Form2.AddChild(ChkBox1);
Chkbox2 := TGUI_CheckBox.Create;
with ChkBox2 do
begin
SetCaption('Exclusive 1');
SetDbgName('Check 2');
SetHeight(30);
SetWidth(150);
SetLeft(10);
SetTop(80);
SetFont(Font);
SetExcGroup(1);
end;
Form2.AddChild(ChkBox2);
Chkbox3 := TGUI_CheckBox.Create;
with ChkBox3 do
begin
SetCaption('Exclusive 2');
SetDbgName('Check 3');
SetHeight(30);
SetWidth(150);
SetLeft(160);
SetTop(80);
SetFont(Font);
SetExcGroup(1);
end;
Form2.AddChild(ChkBox3);
Button1 := TGUI_Button.Create;
with Button1 do
begin
SetFont(Font);
SetWidth(100);
SetHeight(20);
SetLeft(10);
SetTop(100);
SetCaption('Button 1');
SetDbgName('Button 1');
end;
Form1.AddChild(Button1);
Button2 := TGUI_Button.Create;
with Button2 do
begin
SetFont(Font);
SetWidth(100);
SetHeight(20);
SetLeft(140);
SetTop(100);
SetCaption('Button 2');
SetDbgName('Button 2');
end;
Label1 := TGUI_Label.Create;
with Label1 do
begin
SetFont(Font);
SetWidth(200);
SetHeight(30);
SetLeft(10);
SetTop(40);
SetCaption('Press ESC to quit.');
SetDbgName('Label 1');
end;
Form1.AddChild(Label1);
TextBox1 := TGUI_TextBox.Create;
with TextBox1 do
begin
SetFont(Font);
SetWidth(230);
SetHeight(25);
SetLeft(10);
SetTop(150);
SetCaption('Textbox 1');
SetDbgName('Textbox 1');
end;
Form1.AddChild(TextBox1);
Image1 := TGUI_Image.Create;
with Image1 do
begin
SetWidth(400-2);
SetHeight(300-2);
SetLeft(1);
SetTop(25);
SetSource(Logo);
SetDbgName('Image1');
end;
Form3.AddChild(Image1);
Form1.AddChild(Button2);
stillgoing := True;
while StillGoing = True do
begin
while SDL_PollEvent(@Event) > 0 do
begin
case Event.Type_ of
SDL_QUITEV:
begin
stillgoing := False;
end;
SDL_KEYDOWN, SDL_KEYUP, SDL_MOUSEMOTION, SDL_MOUSEBUTTONDOWN,
SDL_MOUSEBUTTONUP, SDL_TEXTINPUT:
begin
if Event.key.keysym.sym = SDLK_ESCAPE then
StillGoing := False;
Master.InjectSDLEvent(@Event);
end;
end;
end;
Master.Paint;
SDL_RenderPresent(Renderer);
end;
FreeAndNil(Master);
SDL_FreeSurface(Logo);
SDL_DestroyRenderer(Renderer);
SDL_DestroyWindow(Window);
TTF_CloseFont(Font);
SDL_Quit;
end.
|
unit Unit1;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Classes,
System.Math,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Vcl.Imaging.Jpeg,
GLScene, GLObjects, GLCadencer, GLTexture, GLCgShader,
GLWin32Viewer, CgGL, GLVectorFileObjects, GLAsyncTimer, GLVectorGeometry,
GLMaterial, GLCoordinates, GLCrossPlatform, GLBaseClasses, GLBehaviours,
GLFileMD2, GLFileTGA, GLFile3DS;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
CgBumpShader: TCgShader;
GLMaterialLibrary1: TGLMaterialLibrary;
GLCadencer1: TGLCadencer;
GLCamera1: TGLCamera;
GLDummyCube1: TGLDummyCube;
GLLightSource1: TGLLightSource;
AsyncTimer1: TGLAsyncTimer;
GLFreeForm1: TGLFreeForm;
CheckBox1: TCheckBox;
procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure CgBumpShaderApplyVP(CgProgram: TCgProgram; Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure CgBumpShaderInitialize(CgShader: TCustomCgShader);
procedure CgBumpShaderApplyFP(CgProgram: TCgProgram; Sender: TObject);
procedure CgBumpShaderUnApplyFP(CgProgram: TCgProgram);
procedure AsyncTimer1Timer(Sender: TObject);
procedure FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
procedure GLCadencer1Progress(Sender: TObject;
const deltaTime, newTime: Double);
procedure CheckBox1Click(Sender: TObject);
private
public
mx, my: Integer;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
var
i: Integer;
begin
// Load the vertex and fragment Cg programs
CgBumpShader.VertexProgram.LoadFromFile('NormalMapp_vp.cg');
CgBumpShader.FragmentProgram.LoadFromFile('NormalMapp_fp.cg');
GLFreeForm1.LoadFromFile('Head256.3ds');
// Load the texture
for i := 0 to GLFreeForm1.MeshObjects.Count - 1 do
begin
GLFreeForm1.MeshObjects[i].BuildTangentSpace;
GLFreeForm1.MeshObjects[i].TangentsTexCoordIndex := 1;
GLFreeForm1.MeshObjects[i].BinormalsTexCoordIndex := 2;
end;
{ }
GLMaterialLibrary1.Materials[0].Material.TextureEx.Add;
GLMaterialLibrary1.Materials[0].Material.TextureEx.Add;
GLMaterialLibrary1.Materials[0].Material.TextureEx.Add;
GLMaterialLibrary1.Materials[0].Material.TextureEx[0]
.Texture.Disabled := False;
GLMaterialLibrary1.Materials[0].Material.TextureEx[0].Texture.TextureMode :=
tmModulate;
GLMaterialLibrary1.Materials[0].Material.TextureEx[0]
.Texture.Image.LoadFromFile('Head256.tga');
GLMaterialLibrary1.Materials[0].Material.TextureEx[1]
.Texture.Disabled := False;
GLMaterialLibrary1.Materials[0].Material.TextureEx[1].Texture.TextureMode :=
tmModulate;
GLMaterialLibrary1.Materials[0].Material.TextureEx[1]
.Texture.Image.LoadFromFile('HeadN256.tga');
GLMaterialLibrary1.Materials[0].Material.TextureEx[2]
.Texture.Disabled := False;
GLMaterialLibrary1.Materials[0].Material.TextureEx[2].Texture.TextureMode :=
tmModulate;
GLMaterialLibrary1.Materials[0].Material.TextureEx[2]
.Texture.Image.LoadFromFile('HeadS256.tga');
{ }
end;
procedure TForm1.CgBumpShaderApplyVP(CgProgram: TCgProgram; Sender: TObject);
var
ap: array [0 .. 2] of single;
begin
// Apply the per frame uniform parameters
with CgProgram do
begin
ap[0] := GLLightSource1.AbsolutePosition.X;
ap[1] := GLLightSource1.AbsolutePosition.Y;
ap[2] := GLLightSource1.AbsolutePosition.Z;
ParamByName('modelViewProj').SetAsStateMatrix
(CG_GL_MODELVIEW_PROJECTION_MATRIX, CG_GL_MATRIX_IDENTITY);
ParamByName('modelView').SetAsStateMatrix(CG_GL_MODELVIEW_MATRIX,
CG_GL_MATRIX_IDENTITY);
// ParamByName('vLightPosition').SetAsVector(ap);
ap[0] := GLCamera1.AbsolutePosition.X;
ap[1] := GLCamera1.AbsolutePosition.Y;
ap[2] := GLCamera1.AbsolutePosition.Z;
// ParamByName('vEyePosition').SetAsVector(ap);
ParamByName('bumpScale').SetAsScalar(1);
// ParamByName('ModelViewIT').SetAsStateMatrix( CG_GL_MODELVIEW_MATRIX, CG_GL_MATRIX_INVERSE_TRANSPOSE);
end;
end;
procedure TForm1.CgBumpShaderInitialize(CgShader: TCustomCgShader);
var
am: array [0 .. 2] of single;
begin
// Set up the LightDiffuseColor parameter
am[0] := GLLightSource1.Diffuse.Red;
am[1] := GLLightSource1.Diffuse.Green;
am[2] := GLLightSource1.Diffuse.Blue;
// CgBumpShader.FragmentProgram.ParamByName('LightDiffuseColor').SetAsVector(am);
end;
procedure TForm1.CgBumpShaderApplyFP(CgProgram: TCgProgram; Sender: TObject);
var
am: array [0 .. 2] of single;
begin
// Set up the LightDiffuseColor parameter
// am[0]:=GLLightSource1.Diffuse.Red;
// am[1]:=GLLightSource1.Diffuse.Green;
// am[2]:=GLLightSource1.Diffuse.Blue;
// CgBumpShader.FragmentProgram.ParamByName('LightDiffuseColor').SetAsVector(am);
// Enable the LightDiffuseColor for use in the fragment
// program
// CgProgram.ParamByName('LightDiffuseColor').EnableClientState;
end;
procedure TForm1.CgBumpShaderUnApplyFP(CgProgram: TCgProgram);
begin
// Disable the LightDiffuseColor
// CgProgram.ParamByName('LightDiffuseColor').DisableClientState;
end;
procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
mx := X;
my := Y;
end;
procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
begin
if ssLeft in Shift then
GLCamera1.MoveAroundTarget(my - Y, mx - X);
mx := X;
my := Y;
end;
procedure TForm1.AsyncTimer1Timer(Sender: TObject);
begin
Form1.Caption := Format('Cg Normal/Bump Blinn Shading Demo - %.2f 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.GLCadencer1Progress(Sender: TObject;
const deltaTime, newTime: Double);
var
am: array [0 .. 2] of single;
begin
// Set up the texture sampler parameter
{ am[0]:=GLLightSource1.Diffuse.Red;
am[1]:=GLLightSource1.Diffuse.Green;
am[2]:=GLLightSource1.Diffuse.Blue;
CgBumpShader.FragmentProgram.ParamByName('LightDiffuseColor').SetAsVector(am);
CgBumpShader.VertexProgram.ParamByName('modelViewProjMatrix').SetAsStateMatrix( CG_GL_MODELVIEW_PROJECTION_MATRIX, CG_GL_MATRIX_IDENTITY);
CgBumpShader.VertexProgram.ParamByName('vLightPosition').SetAsVector(GLLightSource1.Position.AsAffineVector);
{ }
end;
procedure TForm1.CheckBox1Click(Sender: TObject);
begin
If CheckBox1.Checked then
begin
CgBumpShader.Enabled := True;
GLFreeForm1.Material.LibMaterialName :=
GLMaterialLibrary1.Materials[0].Name;
end
Else
begin
CgBumpShader.Enabled := False;
GLFreeForm1.Material.LibMaterialName := '';
end;
end;
end.
|
//
// Generated by JavaToPas v1.5 20180804 - 082550
////////////////////////////////////////////////////////////////////////////////
unit android.app.ApplicationErrorReport_RunningServiceInfo;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
Androidapi.JNI.os,
android.util.Printer;
type
JApplicationErrorReport_RunningServiceInfo = interface;
JApplicationErrorReport_RunningServiceInfoClass = interface(JObjectClass)
['{C8A932EE-8C36-405E-BB8D-EDEF509E97E6}']
function _GetdurationMillis : Int64; cdecl; // A: $1
function _GetserviceDetails : JString; cdecl; // A: $1
function init : JApplicationErrorReport_RunningServiceInfo; cdecl; overload;// ()V A: $1
function init(&in : JParcel) : JApplicationErrorReport_RunningServiceInfo; cdecl; overload;// (Landroid/os/Parcel;)V A: $1
procedure _SetdurationMillis(Value : Int64) ; cdecl; // A: $1
procedure _SetserviceDetails(Value : JString) ; cdecl; // A: $1
procedure dump(pw : JPrinter; prefix : JString) ; cdecl; // (Landroid/util/Printer;Ljava/lang/String;)V A: $1
procedure writeToParcel(dest : JParcel; flags : Integer) ; cdecl; // (Landroid/os/Parcel;I)V A: $1
property durationMillis : Int64 read _GetdurationMillis write _SetdurationMillis;// J A: $1
property serviceDetails : JString read _GetserviceDetails write _SetserviceDetails;// Ljava/lang/String; A: $1
end;
[JavaSignature('android/app/ApplicationErrorReport_RunningServiceInfo')]
JApplicationErrorReport_RunningServiceInfo = interface(JObject)
['{96309F1A-FAE0-4687-B912-2899AA9BC16B}']
function _GetdurationMillis : Int64; cdecl; // A: $1
function _GetserviceDetails : JString; cdecl; // A: $1
procedure _SetdurationMillis(Value : Int64) ; cdecl; // A: $1
procedure _SetserviceDetails(Value : JString) ; cdecl; // A: $1
procedure dump(pw : JPrinter; prefix : JString) ; cdecl; // (Landroid/util/Printer;Ljava/lang/String;)V A: $1
procedure writeToParcel(dest : JParcel; flags : Integer) ; cdecl; // (Landroid/os/Parcel;I)V A: $1
property durationMillis : Int64 read _GetdurationMillis write _SetdurationMillis;// J A: $1
property serviceDetails : JString read _GetserviceDetails write _SetserviceDetails;// Ljava/lang/String; A: $1
end;
TJApplicationErrorReport_RunningServiceInfo = class(TJavaGenericImport<JApplicationErrorReport_RunningServiceInfoClass, JApplicationErrorReport_RunningServiceInfo>)
end;
implementation
end.
|
{*******************************************************}
{ }
{ 软件名称 W.MIS CLIENT MODEL }
{ 版权所有 (C) 2003, 2004 Esquel.IT }
{ 单元名称 UAppOption.pas }
{ 创建日期 2004-8-3 11:01:18 }
{ 创建人员 wuwj }
{ }
{*******************************************************}
unit UAppOption;
{* 应用程序选项设置类单元 }
interface
uses Classes, StdCtrls, SysUtils, Dialogs, StrUtils, Windows;
type
TOption = class (TComponent)
public
procedure LoadFromFile(filePath:string); virtual;
procedure SaveToFile(filePath:string); virtual;
end;
TAppOption = class (TOption)
private
FInitiFileName: String;
FQueryShowCHN: Boolean;
FShowStatusBar: Boolean;
FShowToolBar: Boolean;
FSkinFile: string;
FSkinFilePath: string;
FSkinList: string;
FUseXPStyle: Boolean;
FCurrent_Department: string;
{* 当前部门}
function GetSkinFileFullName: string;
function GetUseXPStyle: Boolean;
procedure SetQueryShowCHN(Value: Boolean);
procedure setShowStatusBar(Value: Boolean);
procedure SetShowToolBar(Value: Boolean);
procedure SetSkinFile(Value: string);
procedure SetSkinFilePath(const Value: string);
procedure SetSkinList(Value: string);
procedure SetUseXPStyle(Value: Boolean);
public
procedure InitiOption;
procedure SaveOption;
property SkinFileFullName: string read GetSkinFileFullName;
published
property IFQueryShowCHN: Boolean read FQueryShowCHN write SetQueryShowCHN;
property InitiFileName: string read FInitiFileName write FInitiFileName;
property ShowStatusBar:Boolean read FShowStatusBar write setShowStatusBar;
property ShowToolBar:Boolean read FShowToolBar write SetShowToolBar;
property SkinFile: string read FSkinFile write SetSkinFile;
property SkinFilePath: string read FSkinFilePath write SetSkinFilePath;
property SkinList: string read FSkinList write SetSkinList;
property UseXPStyle: Boolean read GetUseXPStyle write SetUseXPStyle default false;
property Current_Department: string read FCurrent_Department write FCurrent_Department;
end;
function AppOption:TAppOption;
implementation
var
FAppOption:TAppOption;
{ TAppOption }
procedure TAppOption.InitiOption;
begin
LoadFromFile(InitiFileName);
end;
procedure TAppOption.SaveOption;
begin
SaveToFile(InitiFileName);
end;
function TAppOption.GetSkinFileFullName: string;
begin
if RightStr(FSkinFilePath,1)<>'\' then
Result:=FSkinFilePath+'\'+FSkinFile
else
Result:=FSkinFilePath+FSkinFile;
end;
function TAppOption.GetUseXPStyle: Boolean;
begin
result:=FUseXPStyle and (Win32Platform = VER_PLATFORM_WIN32_NT)
end;
procedure TAppOption.SetSkinFile(Value: string);
begin
FSkinFile:=Value;
end;
procedure TAppOption.SetSkinFilePath(const Value: string);
begin
if FSkinFilePath <> Value then
FSkinFilePath := Value;
end;
procedure TAppOption.SetSkinList(Value: string);
begin
FSkinList:=value;
end;
procedure TAppOption.SetUseXPStyle(Value: Boolean);
begin
FUseXPStyle:=value;
end;
procedure TAPPOption.SetQueryShowCHN(Value: Boolean);
begin
FQueryShowCHN :=value;
// TODO -cMM: TOption.SetQueryShowCHN default body inserted
end;
procedure TAppOption.setShowStatusBar(Value: Boolean);
begin
FShowStatusBar := Value;
end;
procedure TAppOption.SetShowToolBar(Value: Boolean);
begin
FShowToolBar := Value;
end;
function AppOption:TAppOption;
begin
if FAppOption=nil then
begin
FAppOption:=TAppOption.Create(nil);
FAppOption.ShowToolBar:=true;
FAppOption.ShowStatusBar:=true;
end;
Result:=FAppOption;
end;
{ TOption }
procedure TOption.LoadFromFile(filePath:string);
var
Fs: TFileStream;
begin
if not FileExists(FilePath) then
AppOption.SaveToFile(FilePath);
try
Fs:=Tfilestream.Create(Filepath, Fmopenread);
try
Classes.RegisterClass(TAppOption);
Fs.Readcomponent(Appoption);
finally
Fs.Free;
end;
except
AppOption.SaveToFile(FilePath);
end;
end;
procedure TOption.SaveToFile(filePath:string);
var
fs: TFileStream;
begin
Classes.RegisterClass(TAppOption);
Fs:=Tfilestream.Create(Filepath,Fmcreate);
try
fs.WriteComponent(AppOption);
finally
fs.Free;
end;
end;
initialization
FAppOption:=nil;
finalization
FAppOption.Free;
end.
|
unit MVVM.Rtti;
interface
uses
System.Rtti,
System.TypInfo,
System.Classes;
type
TRttiPropertyHelper = class helper for TRttiProperty
private
function GetSetterField : TRttiField;
function GetGetterField : TRttiField;
public
property SetterField : TRttiField read GetSetterField;
property GetterField : TRttiField read GetGetterField;
function SetterMethod (Instance : TObject) : TRttiMethod;
function GetterMethod (Instance : TObject) : TRttiMethod;
end;
RttiUtils = record
public
class function GetInterfaceTypeInfo(const GUID: TGUID): PTypeInfo; static;
class function CreateComponent_From_RttiInstance(ARttiInstance: TRttiInstanceType; const ACreateParams: array of TValue): TComponent; static;
end;
implementation
uses
System.SysUtils;
const
{$IF SizeOf(Pointer) = 4}
PROPSLOT_MASK_F = $000000FF;
{$ELSEIF SizeOf(Pointer) = 8}
PROPSLOT_MASK_F = $00000000000000FF;
{$ENDIF}
function IsField(P: Pointer): Boolean; inline;
begin
Result := (IntPtr(P) and PROPSLOT_MASK) = PROPSLOT_FIELD;
end;
function GetCodePointer(Instance: TObject; P: Pointer): Pointer; inline;
begin
if (IntPtr(P) and PROPSLOT_MASK) = PROPSLOT_VIRTUAL then // Virtual Method
Result := PPointer(PNativeUInt(Instance)^ + (UIntPtr(P) and $FFFF))^
else // Static method
Result := P;
end;
function GetPropGetterMethod(Instance: TObject; AProp : TRttiProperty) : TRttiMethod;
var
LPropInfo : PPropInfo;
LMethod: TRttiMethod;
LCodeAddress : Pointer;
LType : TRttiType;
LocalContext: TRttiContext;
begin
Result:=nil;
if (AProp.IsReadable) and (AProp.ClassNameIs('TRttiInstancePropertyEx')) then
begin
//get the PPropInfo pointer
LPropInfo:=TRttiInstanceProperty(AProp).PropInfo;
if (LPropInfo<>nil) and (LPropInfo.GetProc<>nil) and not IsField(LPropInfo.GetProc) then
begin
//get the real address of the ,ethod
LCodeAddress := GetCodePointer(Instance, LPropInfo^.GetProc);
//get the Typeinfo for the current instance
LType:= LocalContext.GetType(Instance.ClassType);
//iterate over the methods of the instance
for LMethod in LType.GetMethods do
begin
//compare the address of the currrent method against the address of the getter
if LMethod.CodeAddress=LCodeAddress then
Exit(LMethod);
end;
end;
end;
end;
function GetPropSetterMethod(Instance: TObject; AProp : TRttiProperty) : TRttiMethod;
var
LPropInfo : PPropInfo;
LMethod: TRttiMethod;
LCodeAddress : Pointer;
LType : TRttiType;
LocalContext: TRttiContext;
begin
Result:=nil;
if (AProp.IsWritable) and (AProp.ClassNameIs('TRttiInstancePropertyEx')) then
begin
//get the PPropInfo pointer
LPropInfo:=TRttiInstanceProperty(AProp).PropInfo;
if (LPropInfo<>nil) and (LPropInfo.SetProc<>nil) and not IsField(LPropInfo.SetProc) then
begin
LCodeAddress := GetCodePointer(Instance, LPropInfo^.SetProc);
//get the Typeinfo for the current instance
LType:= LocalContext.GetType(Instance.ClassType);
//iterate over the methods
for LMethod in LType.GetMethods do
begin
//compare the address of the currrent method against the address of the setter
if LMethod.CodeAddress=LCodeAddress then
Exit(LMethod);
end;
end;
end;
end;
function GetPropGetterField(AProp : TRttiProperty) : TRttiField;
var
LPropInfo : PPropInfo;
LField: TRttiField;
LOffset : Integer;
begin
Result:=nil;
//Is a readable property?
if (AProp.IsReadable) and (AProp.ClassNameIs('TRttiInstancePropertyEx')) then
begin
//get the propinfo of the porperty
LPropInfo:=TRttiInstanceProperty(AProp).PropInfo;
//check if the GetProc represent a field
if (LPropInfo<>nil) and (LPropInfo.GetProc<>nil) and IsField(LPropInfo.GetProc) then
begin
//get the offset of the field
LOffset:= IntPtr(LPropInfo.GetProc) and PROPSLOT_MASK_F;
//iterate over the fields of the class
for LField in AProp.Parent.GetFields do
//compare the offset the current field with the offset of the getter
if LField.Offset=LOffset then
Exit(LField);
end;
end;
end;
function GetPropSetterField(AProp : TRttiProperty) : TRttiField;
var
LPropInfo : PPropInfo;
LField: TRttiField;
LOffset : Integer;
begin
Result:=nil;
//Is a writable property?
if (AProp.IsWritable) and (AProp.ClassNameIs('TRttiInstancePropertyEx')) then
begin
//get the propinfo of the porperty
LPropInfo:=TRttiInstanceProperty(AProp).PropInfo;
//check if the GetProc represent a field
if (LPropInfo<>nil) and (LPropInfo.SetProc<>nil) and IsField(LPropInfo.SetProc) then
begin
//get the offset of the field
LOffset:= IntPtr(LPropInfo.SetProc) and PROPSLOT_MASK_F;
//iterate over the fields of the class
for LField in AProp.Parent.GetFields do
//compare the offset the current field with the offset of the setter
if LField.Offset=LOffset then
Exit(LField);
end;
end;
end;
{ TRttiPropertyHelper }
function TRttiPropertyHelper.GetGetterField: TRttiField;
begin
Result:= GetPropGetterField(Self);
end;
function TRttiPropertyHelper.GetSetterField: TRttiField;
begin
Result:= GetPropSetterField(Self);
end;
function TRttiPropertyHelper.GetterMethod(Instance: TObject): TRttiMethod;
begin
Result:= GetPropGetterMethod(Instance, Self);
end;
function TRttiPropertyHelper.SetterMethod(Instance: TObject): TRttiMethod;
begin
Result:= GetPropSetterMethod(Instance, Self);
end;
{ RttiUtils }
class function RttiUtils.CreateComponent_From_RttiInstance(ARttiInstance: TRttiInstanceType; const ACreateParams: array of TValue): TComponent;
var
LCreateMethod: TRttiMethod;
begin
// Loop for all methods
LCreateMethod := nil;
for LCreateMethod in ARttiInstance.GetMethods do
begin
if (LCreateMethod.HasExtendedInfo) and (LCreateMethod.IsConstructor) and (Length(LCreateMethod.GetParameters) = Length(ACreateParams)) then
begin
break;
end;
end;
if not Assigned(LCreateMethod) then
raise Exception.Create('Constructor not found for class: ' + ARttiInstance.QualifiedClassName);
Result := LCreateMethod.Invoke(ARttiInstance.MetaclassType, ACreateParams).AsObject as TComponent;
end;
class function RttiUtils.GetInterfaceTypeInfo(const GUID: TGUID): PTypeInfo;
var
Ctx: TRttiContext;
AType: TRttiType;
begin
Result := nil;
Ctx := TRttiContext.Create;
try
for AType in Ctx.GetTypes do
if (AType.TypeKind = tkInterface) and IsEqualGUID(GetTypeData(AType.Handle)^.GUID, GUID) then
begin
Result := PTypeInfo(AType); // .Handle;
break;
end;
finally
Ctx.Free;
end;
end;
end.
|
unit Banco;
{$mode objfpc}{$H+}
interface
uses
HTTPDefs, BrookRESTActions, BrookUtils;
type
TBancoOptions = class(TBrookOptionsAction)
end;
TBancoRetrieve = class(TBrookRetrieveAction)
procedure Request({%H-}ARequest: TRequest; AResponse: TResponse); override;
end;
TBancoShow = class(TBrookShowAction)
end;
TBancoCreate = class(TBrookCreateAction)
end;
TBancoUpdate = class(TBrookUpdateAction)
end;
TBancoDestroy = class(TBrookDestroyAction)
end;
implementation
procedure TBancoRetrieve.Request(ARequest: TRequest; AResponse: TResponse);
var
Campo: String;
Filtro: String;
begin
Campo := Values['campo'].AsString;
Filtro := Values['filtro'].AsString;
Values.Clear;
Table.Where(Campo + ' LIKE "%' + Filtro + '%"');
inherited Request(ARequest, AResponse);
end;
initialization
TBancoOptions.Register('banco', '/banco');
TBancoRetrieve.Register('banco', '/banco/:campo/:filtro/');
TBancoShow.Register('banco', '/banco/:id');
TBancoCreate.Register('banco', '/banco');
TBancoUpdate.Register('banco', '/banco/:id');
TBancoDestroy.Register('banco', '/banco/:id');
end.
|
unit RawDocument;
interface
uses
Classes, Forms, Types,
LrDocument;
type
TRawDocument = class(TLrDocument)
private
FStrings: TStringList;
FEditPos: TPoint;
protected
function GetExtension: string; override;
function GetFilter: string; override;
procedure SetStrings(const Value: TStringList);
public
constructor Create(inManager: TLrDocumentManager;
const inPath: string = ''); override;
destructor Destroy; override;
procedure Open; override;
procedure PerformAction(inAction: TLrDocumentAction); override;
procedure Save; override;
property EditPos: TPoint read FEditPos write FEditPos;
property Strings: TStringList read FStrings write SetStrings;
end;
implementation
{ TRawDocument }
constructor TRawDocument.Create(inManager: TLrDocumentManager;
const inPath: string);
begin
inherited;
FStrings := TStringList.Create;
end;
destructor TRawDocument.Destroy;
begin
FStrings.Free;
inherited;
end;
procedure TRawDocument.SetStrings(const Value: TStringList);
begin
FStrings.Assign(Value);
end;
function TRawDocument.GetExtension: string;
begin
Result := '.php';
end;
function TRawDocument.GetFilter: string;
begin
Result := 'Php Files (*.php)|*.php|Any File (*.*)|*.*';
end;
procedure TRawDocument.Open;
begin
if not Untitled then
Strings.LoadFromFile(Path);
end;
procedure TRawDocument.Save;
begin
inherited;
Strings.SaveToFile(Path);
end;
procedure TRawDocument.PerformAction(inAction: TLrDocumentAction);
begin
inherited;
if inAction.Name = 'PublishAction' then
begin
end;
end;
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
Support for MP3 format.
}
unit VXS.FileMP3;
interface
{$I VXScene.inc}
uses
System.Classes,
VXS.ApplicationFileIO,
VXS.SoundFileObjects;
type
{ Support for MP3 format.
*Partial* support only, access to PCMData is NOT supported. }
TVXMP3File = class(TVXSoundFile)
private
data: array of Byte; // used to store MP3 bitstream
protected
public
function CreateCopy(AOwner: TPersistent): TVXDataFile; override;
class function Capabilities: TVXDataFileCapabilities; override;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
procedure PlayOnWaveOut; override;
function WAVData: Pointer; override;
function WAVDataSize: Integer; override;
function PCMData: Pointer; override;
function LengthInBytes: Integer; override;
end;
//=============================================================
implementation
//=============================================================
// ------------------
// ------------------ TVXMP3File ------------------
// ------------------
function TVXMP3File.CreateCopy(AOwner: TPersistent): TVXDataFile;
begin
Result := inherited CreateCopy(AOwner);
if Assigned(Result) then
begin
TVXMP3File(Result).data := Copy(data);
end;
end;
class function TVXMP3File.Capabilities: TVXDataFileCapabilities;
begin
Result := [dfcRead, dfcWrite];
end;
procedure TVXMP3File.LoadFromStream(Stream: TStream);
begin
// MP3 isn't actually, just loaded directly...
Assert(Assigned(Stream));
SetLength(data, Stream.Size);
if Length(data) > 0 then
Stream.Read(data[0], Length(data));
end;
procedure TVXMP3File.SaveToStream(Stream: TStream);
begin
if Length(data) > 0 then
Stream.Write(data[0], Length(data));
end;
procedure TVXMP3File.PlayOnWaveOut;
begin
Assert(False, 'MP3 playback on WaveOut not supported.');
end;
function TVXMP3File.WAVData: Pointer;
begin
if Length(data) > 0 then
Result := @data[0]
else
Result := nil;
end;
function TVXMP3File.WAVDataSize: Integer;
begin
Result := Length(data);
end;
function TVXMP3File.PCMData: Pointer;
begin
Result := nil;
end;
function TVXMP3File.LengthInBytes: Integer;
begin
Result := 0;
end;
//------------------------------------------------------------------
initialization
//------------------------------------------------------------------
RegisterSoundFileFormat('mp3', 'MPEG Layer3 files', TVXMP3File);
end.
|
unit OthelloBoard;
interface
uses FMX.Objects3D, System.Classes, FMX.MaterialSources, FMX.Dialogs, OthelloCounters, System.UITypes;
type
TOthelloTile = class;
TOthelloTileClick = procedure(Sender : TOthelloTile) of object;
TOthelloTile = class(TRectangle3D)
private
FX: Integer;
FY: Integer;
public
constructor Create(aOwner : TComponent; aX, aY : Integer); reintroduce;
published
property X : Integer read FX;
property Y : Integer read FY;
end;
TOthelloBoard = class(TDummy)
strict private
GridSize: Integer;
TileSize: Single;
procedure InternalOnTileClick(Sender: TObject);
private
Tiles: Array of Array of TOthelloTile;
BoardEdge: TRectangle3D;
BoardEdgeColor: TColorMaterialSource;
FOnTileClick: TOthelloTileClick;
public
constructor Create(aOwner : TComponent; aGridSize: Integer; aTileSize: Single;
aLightMaterial, aDarkMaterial: TMaterialSource); reintroduce;
destructor Destroy; override;
property OnTileClick : TOthelloTileClick read FOnTileClick write FOnTileClick;
end;
implementation
uses OthelloGame;
constructor TOthelloBoard.Create(aOwner: TComponent; aGridSize: Integer; aTileSize: Single;
aLightMaterial, aDarkMaterial: TMaterialSource);
var
i: Integer;
j: Integer;
Rect : TOthelloTile;
begin
inherited Create(aOwner);
GridSize := aGridSize;
TileSize := aTileSize;
SetLength(Tiles, GridSize, GridSize);
for i := 0 to High(Tiles) do
for j := 0 to High(Tiles) do
begin
Rect := TOthelloTile.Create(Self,i,j);
Rect.Parent := Self;
Rect.Position.X := i * TileSize;
Rect.Position.Y := j * TileSize;
Rect.Width := TileSize;
Rect.Height := TileSize;
Rect.Depth := 0.5;
Rect.OnClick := InternalOnTileClick;
if ((i MOD 2 = 0) AND (j MOD 2 = 0)) OR ((i MOD 2 <> 0) AND (j MOD 2 <> 0)) then
begin
Rect.MaterialSource := aLightMaterial;
Rect.MaterialShaftSource := aDarkMaterial;
end
else
begin
Rect.MaterialSource := aDarkMaterial;
Rect.MaterialShaftSource := aLightMaterial;
end;
Tiles[i][j] := Rect;
end;
BoardEdgeColor := TColorMaterialSource.Create(Self);
BoardEdgeColor.Color := TAlphaColorRec.Black;
BoardEdge := TRectangle3D.Create(Self);
BoardEdge.Parent := Self;
BoardEdge.Width := TileSize*GridSize*1.1;
BoardEdge.Height := TileSize*GridSize*1.1;
BoardEdge.Position.X := ((TileSize*GridSize)-1)/2;
BoardEdge.Position.Y := ((TileSize*GridSize)-1)/2;
BoardEdge.Position.Z := 0.2;
BoardEdge.Depth := 0.5;
BoardEdge.MaterialSource := BoardEdgeColor;
end;
destructor TOthelloBoard.Destroy;
var
i: Integer;
j: Integer;
begin
for i := 0 to High(Tiles) do
for j := 0 to High(Tiles) do begin
Tiles[i][j].DisposeOf;
Tiles[i][j] := nil;
end;
SetLength(Tiles,0,0);
inherited;
end;
procedure TOthelloBoard.InternalOnTileClick(Sender: TObject);
var
i: Integer;
j: Integer;
begin
for i := 0 to High(Tiles) do
for j := 0 to High(Tiles) do
begin
if Tiles[i][j] = TOthelloTile(Sender) then begin
if Assigned(OnTileClick) then begin
OnTileClick( Tiles[i][j] );
Exit;
end;
end;
end;
end;
{ TOthelloTile }
constructor TOthelloTile.Create(aOwner: TComponent; aX, aY: Integer);
begin
Inherited Create(aOwner);
FX := aX;
FY := aY;
end;
end.
|
unit TurboAjaxDocument;
interface
uses
SysUtils, Classes,
htTag, htDocument,
LrDocument, TurboPhpDocument,
Design, Project;
type
TTurboAjaxDocument = class(TTurboPhpDocument)
public
class function DocumentDescription: string;
class function DocumentExt: string;
protected
function CreateMarkup: TTurboMarkup; override;
procedure CustomizeMarkup(inMarkup: TTurboMarkup); override;
public
constructor Create; override;
end;
implementation
uses
Globals;
{ TTurboAjaxDocument }
class function TTurboAjaxDocument.DocumentDescription: string;
begin
Result := 'TurboAjax Pages';
end;
class function TTurboAjaxDocument.DocumentExt: string;
begin
Result := '.tajx';
end;
constructor TTurboAjaxDocument.Create;
begin
inherited;
EnableSaveAs(DocumentDescription, DocumentExt);
end;
function TTurboAjaxDocument.CreateMarkup: TTurboMarkup;
begin
Result := inherited CreateMarkup;
end;
procedure TTurboAjaxDocument.CustomizeMarkup(inMarkup: TTurboMarkup);
function Include(const inSrc: string): ThtTag;
begin
Result := ThtTag.Create();
Result.Content.LoadFromFile(inSrc);
end;
{
function JsIncludeTag(const inSrc: string): ThtTag;
begin
Result := ThtTag.Create('script');
Result.Attributes['type'] := 'text/javascript';
Result.Attributes['language'] := 'javascript';
Result.Attributes['src'] := inSrc;
end;
function StyleLinkTag(const inSrc: string): ThtTag;
begin
Result := ThtTag.Create('link');
Result.Attributes['type'] := 'text/css';
Result.Attributes['rel'] := 'stylesheet';
Result.Attributes['href'] := inSrc;
end;
}
begin
inMarkup.Includes.Add(Include(TemplatesHome + 'dojoboiler.html'));
inMarkup.Script.Add(' dojo.hostenv.modulesLoadedListeners.push(init);');
{
with inMarkup do
begin
Includes.Add(StyleLinkTag('lib/Grid.css'));
Includes.Add(JsIncludeTag('lib/Grid.js'));
Includes.Add(JsIncludeTag('lib/turbo_ajax_server.php?client'));
Includes.Add(JsIncludeTag('support/' + ChangeFileExt(PublishName, '.js')));
Includes.Add(JsIncludeTag('lib/tpGrid.js'));
end;
}
end;
end.
|
unit MainUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Menus, ComCtrls, StdCtrls, Grids, DBGrids, DB, IBCustomDataSet,
IBQuery, consts, IBSQL, ShellApi, IniFiles,
cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage,
cxEdit, cxDBData, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGridLevel, cxClasses, cxControls, cxGridCustomView,
cxGrid, SysAdmin, Buttons;
type
TMainForm = class(TForm)
StatusBar: TStatusBar;
MainPageControl: TPageControl;
AcceptPage: TTabSheet;
SettingsPage: TTabSheet;
GroupBox1: TGroupBox;
OpenUpdateButton: TButton;
AcceptUpdateButton: TButton;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
HistoryQuery: TIBQuery;
HistoryDataSource: TDataSource;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
SystemNameLabel: TLabel;
UpdateVersionLabel: TLabel;
UpdateDateLabel: TLabel;
OpenDialog: TOpenDialog;
WorkSQL: TIBSQL;
GetSystemNameQuery: TIBQuery;
GetSystemNameQueryNAME_SYSTEM: TIBStringField;
GetSystemNameQueryE_MAIL: TIBStringField;
WorkQuery: TIBQuery;
GetSystemNameQueryLAST_UPDATE: TIntegerField;
Label4: TLabel;
LastUpdateLabel: TLabel;
LogEdit: TRichEdit;
Label5: TLabel;
SystemsQuery: TIBQuery;
SystemsDataSource: TDataSource;
SystemsQueryID_SYSTEM: TIntegerField;
SystemsQueryNAME_SYSTEM: TIBStringField;
SystemsQueryE_MAIL: TIBStringField;
Label6: TLabel;
ConnectionEdit: TEdit;
SaveOptionsButton: TButton;
cxGrid1DBTableView1: TcxGridDBTableView;
cxGrid1Level1: TcxGridLevel;
cxGrid1: TcxGrid;
cxGrid1DBTableView1DBColumn1: TcxGridDBColumn;
cxGrid1DBTableView1DBColumn2: TcxGridDBColumn;
cxGrid1DBTableView1DBColumn3: TcxGridDBColumn;
cxGrid1DBTableView1DBColumn4: TcxGridDBColumn;
PopupMenu1: TPopupMenu;
N1: TMenuItem;
cxGrid1DBTableView1DBColumn5: TcxGridDBColumn;
HistoryQueryID_SYSTEM: TIntegerField;
HistoryQueryVERSION_NUMBER: TIntegerField;
HistoryQueryVERSION_DATE: TDateField;
HistoryQueryACCEPT_DATETIME: TDateTimeField;
HistoryQuerySYSTEM_NAME: TIBStringField;
HistoryQuerySERVER_NAME: TIBStringField;
cxGrid2: TcxGrid;
cxGridDBTableView1: TcxGridDBTableView;
cxGridDBColumn1: TcxGridDBColumn;
cxGridDBColumn2: TcxGridDBColumn;
cxGridLevel1: TcxGridLevel;
SaveDialog: TSaveDialog;
HistoryQueryACCEPT_LOG: TBlobField;
SysAdminButton: TBitBtn;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure N6Click(Sender: TObject);
procedure TabSheet1Show(Sender: TObject);
procedure OpenUpdateButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure AcceptUpdateButtonClick(Sender: TObject);
procedure TabSheet2Show(Sender: TObject);
procedure SaveOptionsButtonClick(Sender: TObject);
procedure N1Click(Sender: TObject);
procedure SysAdminButtonClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
public
UpdateVersion : Integer;
UpdateSystem : Integer;
UpdateDate : TDate;
UpdateFileName : String;
end;
var
MainForm: TMainForm;
implementation
uses DMUnit, ProcessUnit;
{$R *.dfm}
procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if MessageDlg('Выйти из программы?', mtConfirmation, [mbYes, mbNo], 0) <> mrYes
then begin
Action := caNone;
exit;
end;
end;
procedure TMainForm.N6Click(Sender: TObject);
begin
Close;
end;
procedure TMainForm.TabSheet1Show(Sender: TObject);
begin
HistoryQuery.Close;
HistoryQuery.Open;
end;
procedure TMainForm.OpenUpdateButtonClick(Sender: TObject);
var
Signature : String;
InF, OutF : File;
i, len : Integer;
ProcessForm : TProcessForm;
Buf : array of byte;
begin
OpenDialog.InitialDir := Dm.ProgramPath;
if OpenDialog.Execute then begin
UpdateFileName := OpenDialog.FileName;
// Decoding input file
AssignFile(InF, OpenDialog.FileName);
Reset(InF, 1);
len := FileSize(inF);
SetLength(buf, len);
for i := 0 to len -1 do begin
BlockRead(inF, Buf[i], 1);
end;
CloseFile(inF);
ProcessForm :=TProcessForm.Create(Self);
ProcessForm.Progress.Max := len;
ProcessForm.Caption := 'Идет декодирование исходного файла...';
ProcessForm.Show;
for i := 0 to len - 1 do begin
Buf[i] := Buf[i] xor 147;
if i mod 100 = 0 then begin
ProcessForm.Progress.Position := i;
ProcessForm.Step;
if ProcessForm.Stop then begin
ProcessForm.Hide;
Screen.Cursor := crDefault;
exit;
end;
end;
end;
AssignFile(OutF, Dm.ProgramPath + 'decoded');
Rewrite(OutF, 1);
for i := 0 to len -1 do begin
BlockWrite(OutF, Buf[i], 1);
end;
CloseFile(OutF);
ProcessForm.Hide;
Screen.Cursor := crDefault;
ProcessForm.Free;
UpdateFileName := Dm.ProgramPath + 'decoded';
try
WorkSQL.Close;
WorkSQL.SQL.LoadFromFile(UpdateFileName);
DeleteFile(UpdateFileName);
Signature := Copy(WorkSQL.SQL.Strings[0], 0, 4);
if Signature <> '3030' then begin
MessageDlg('Выбранный файл не является файлом обновления БД!', mtError, [mbOk], 0);
WorkSQL.Close;
Exit;
end;
Signature := Copy(WorkSQL.SQL.Strings[0], 6, 8);
UpdateSystem := StrToInt(Signature);
Signature := Copy(WorkSQL.SQL.Strings[0], 15, 8);
UpdateVersion:= StrToInt(Signature);
Signature := Copy(WorkSQL.SQL.Strings[0], 24, 10);
UpdateDate := StrToDate(Signature);
GetSystemNameQuery.Close;
GetSystemNameQuery.Params.ParamValues['ID_SYSTEM'] := UpdateSystem;
GetSystemNameQuery.Open;
if (GetSystemNameQuery.IsEmpty) then begin
UpdateVersion := -1;
MessageDlg('В вашей БД не удалось обнаружить систему, для которой предназначено выбранное обновление!', mtError, [mbOk], 0);
exit;
end;
SystemNameLabel.Caption := GetSystemNameQueryNAME_SYSTEM.Value;
LastUpdateLabel.Caption := GetSystemNameQueryLAST_UPDATE.AsString;
UpdateVersionLabel.Caption := IntToStr(UpdateVersion);
UpdateDateLabel.Caption := DateToStr(UpdateDate);
WorkSQL.SQL[0] := 'SET SQL DIALECT 3; SET NAMES WIN1251; ' + ' CONNECT ' + QuotedStr(DM.DBPath) + ' USER ' + QuotedStr(DM.CurrentLogin) + ' password ' + QuotedStr(DM.CurrentPassword) + ';';
WorkSQL.SQL.Add('EXECUTE PROCEDURE SYS_VERSION_HISTORY_INSERT(' + IntToStr(UpdateSystem) + ',' + IntToStr(UpdateVersion) + ',' + QuotedStr(DateToStr(UpdateDate)) + ',' + QuotedStr('NOW') + '); Commit Work;');
except on e : Exception
do begin
MessageDlg('Возникла ошибка: ' + E.Message, mtError, [mbOk], 0);
UpdateVersion := -1;
end
end;
end;
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
HistoryQuery.Transaction := DM.ReadTransaction;
GetSystemNameQuery.Transaction := DM.ReadTransaction;
SystemsQuery.Transaction := DM.ReadTransaction;
WorkSQL.Transaction := DM.WriteTransaction;
WorkQuery.Transaction := DM.WriteTransaction;
UpdateVersion := -1;
ConnectionEdit.Text := DM.DBPath;
end;
procedure TMainForm.AcceptUpdateButtonClick(Sender: TObject);
var
ReportFile : String;
Rlst: LongBool;
StartUpInfo: TStartUpInfo;
ProcessInfo: TProcessInformation;
//Error: integer;
ExitCode: Cardinal;
begin
if UpdateVersion = -1 then begin
MessageDlg('Сперва необходимо открыть обновление!', mtError, [mbOk], 0);
exit;
end;
if not FileExists(Dm.ProgramPath + 'ibescript.exe') then begin
MessageDlg('Не найден файл "ibescript.exe"!', mtError, [mbOk], 0);
exit;
end;
if UpdateVersion - 1 <> GetSystemNameQueryLAST_UPDATE.Value then begin
MessageDlg('Для системы "' +SystemNameLabel.Caption +
'" установлено обновление №' +
GetSystemNameQueryLAST_UPDATE.AsString + '. ' +
'Можно применить только обновление №' +
IntToStr(GetSystemNameQueryLAST_UPDATE.value + 1) + '!', mtError, [mbOk], 0);
exit;
end;
WorkSQL.SQL.SaveToFile(Dm.ProgramPath + 'script');
ReportFile := Dm.ProgramPath + SystemNameLabel.Caption + '_' + UpdateVersionLabel.Caption + '_' + UpdateDateLabel.Caption + '.log';
FillChar(StartUpInfo, SizeOf(TStartUpInfo), 0);
with StartUpInfo do
begin
cb := SizeOf(TStartUpInfo);
dwFlags := STARTF_USESHOWWINDOW or STARTF_FORCEONFEEDBACK;
wShowWindow := SW_SHOWNORMAL;
end;
Rlst := CreateProcess(PAnsiChar(Dm.ProgramPath + 'ibescript.exe'), PAnsiChar(' "' + Dm.ProgramPath + 'script" ' + ' "' + Dm.ProgramPath + 'script"' + ' -N -S -E -V"' + ReportFile + '"') , nil, nil, false, NORMAL_PRIORITY_CLASS, nil, nil, StartUpInfo, ProcessInfo);
if Rlst then
with ProcessInfo do begin
WaitForInputIdle(hProcess, INFINITE); // ждем завершения инициализации
WaitforSingleObject(ProcessInfo.hProcess, INFINITE); // ждем завершения процесса
GetExitCodeProcess(ProcessInfo.hProcess, ExitCode); // получаем код завершения
CloseHandle(hThread); // закрываем дескриптор процесса
CloseHandle(hProcess); // закрываем дескриптор потока
end;
//else
// Error := GetLastError;
LogEdit.Lines.LoadFromFile(ReportFile);
WorkQuery.Close;
if DM.WriteTransaction.Active then
DM.WriteTransaction.Rollback;
WorkQuery.Transaction.StartTransaction;
WorkQuery.Params.ParamValues['ACCEPT_LOG'] := LogEdit.Lines.Text;
WorkQuery.Params.ParamValues['Id_System'] := UpdateSystem;
WorkQuery.Params.ParamValues['Version_Number'] := UpdateVersion;
WorkQuery.ExecSQL;
WorkQuery.Transaction.Commit;
UpdateVersion:= -1;
SystemNameLabel.Caption := '---';
LastUpdateLabel.Caption := '---';
UpdateVersionLabel.Caption := '---';
UpdateDateLabel.Caption := '---';
if not Dm.DontKillLog then
DeleteFile(Dm.ProgramPath + 'script');
if Pos('Script executed successfully', LogEdit.Text) <> 0 then
MessageDlg('Файл обновления был применен без ошибок! Ошибки не были обнаружены. Отчет о выполнении сохранен в файле "' + ReportFile + '". Теперь необходимо обновить исполняемые файлы, отчеты и прочее.', mtInformation, [mbOk], 0)
else
MessageDlg('Файл обновления был применен с ошибками, обязательно передайте разработчикам отчет о выполнении, который сохранен в файле "' + ReportFile + '". Теперь необходимо обновить исполняемые файлы, отчеты и прочее.', mtError, [mbOk], 0);
end;
procedure TMainForm.TabSheet2Show(Sender: TObject);
begin
SystemsQuery.Close;
SystemsQuery.Open;
end;
procedure TMainForm.SaveOptionsButtonClick(Sender: TObject);
var
IniFile : TIniFile;
begin
IniFile := TIniFile.Create(DM.ProgramPath + 'update.ini');
IniFile.WriteString('Database', 'Path', ConnectionEdit.Text);
IniFile.Free;
MessageDlg('Чтобы изменения вступили в действие необходимо перезапустить программу!', mtInformation, [mbOk], 0);
end;
procedure TMainForm.N1Click(Sender: TObject);
begin
if SaveDialog.Execute then begin
if (FileSearch(SaveDialog.FileName,'') <> '') and (MessageDlg('Файл уже существует. Перезаписать?', mtConfirmation, [mbYes, mbNo],0) = mrNo)
then
exit
else
HistoryQueryACCEPT_LOG.SaveToFile(SaveDialog.FileName);
end;
end;
procedure TMainForm.SysAdminButtonClick(Sender: TObject);
begin
AdminShowUsers(Self);
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
FinalizeAdminSystem;
end;
end.
|
unit ExtractionFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls,
InflatablesList_Types,
InflatablesList_Manager;
type
TfrmExtractionFrame = class(TFrame)
pnlMain: TPanel;
lblExtractFrom: TLabel;
cmbExtractFrom: TComboBox;
lblExtractMethod: TLabel;
cmbExtractMethod: TComboBox;
leExtractionData: TLabeledEdit;
leNegativeTag: TLabeledEdit;
bvlExtrSeparator: TBevel;
private
fILManager: TILManager;
{
a pointer is allowed here, as it is not pointing to item in listed object,
but to a storage in parsing form (ie. it is comletely local)
}
fExtractSett: PILItemShopParsingExtrSett;
protected
procedure FrameClear;
procedure FrameSave;
procedure FrameLoad;
public
procedure Initialize(ILManager: TILManager);
procedure Finalize;
procedure Save;
procedure Load;
procedure SetExtractSett(ExtractSett: PILItemShopParsingExtrSett; ProcessChange: Boolean);
end;
implementation
{$R *.dfm}
procedure TfrmExtractionFrame.FrameClear;
begin
If cmbExtractFrom.Items.Count > 0 then
cmbExtractFrom.ItemIndex := 0;
If cmbExtractMethod.Items.Count > 0 then
cmbExtractMethod.ItemIndex := 0;
leExtractionData.Text := '';
leNegativeTag.Text := '';
end;
//------------------------------------------------------------------------------
procedure TfrmExtractionFrame.FrameSave;
begin
If Assigned(fExtractSett) then
begin
fExtractSett^.ExtractFrom := TILItemShopParsingExtrFrom(cmbExtractFrom.ItemIndex);
fExtractSett^.ExtractionMethod := TILItemShopParsingExtrMethod(cmbExtractMethod.ItemIndex);
fExtractSett^.ExtractionData := leExtractionData.Text;
fExtractSett^.NegativeTag := leNegativeTag.Text;
UniqueString(fExtractSett^.ExtractionData);
UniqueString(fExtractSett^.NegativeTag);
end;
end;
//------------------------------------------------------------------------------
procedure TfrmExtractionFrame.FrameLoad;
begin
If Assigned(fExtractSett) then
begin
cmbExtractFrom.ItemIndex := Ord(fExtractSett^.ExtractFrom);
cmbExtractMethod.ItemIndex := Ord(fExtractSett^.ExtractionMethod);
leExtractionData.Text := fExtractSett^.ExtractionData;
leNegativeTag.Text := fExtractSett^.NegativeTag;
end;
end;
//==============================================================================
procedure TfrmExtractionFrame.Initialize(ILManager: TILManager);
var
i: Integer;
begin
fILManager := ILManager;
// fill drop lists...
// extract from
cmbExtractFrom.Items.BeginUpdate;
try
cmbExtractFrom.Items.Clear;
For i := Ord(Low(TILItemShopParsingExtrFrom)) to Ord(High(TILItemShopParsingExtrFrom)) do
cmbExtractFrom.Items.Add(fILManager.DataProvider.
GetShopParsingExtractFromString(TILItemShopParsingExtrFrom(i)));
finally
cmbExtractFrom.Items.EndUpdate;
end;
If cmbExtractFrom.Items.Count > 0 then
cmbExtractFrom.ItemIndex := 0;
// extraction method
cmbExtractMethod.Items.BeginUpdate;
try
cmbExtractMethod.Items.Clear;
For i := Ord(Low(TILItemShopParsingExtrMethod)) to Ord(High(TILItemShopParsingExtrMethod)) do
cmbExtractMethod.Items.Add(fILManager.DataProvider.
GetShopParsingExtractMethodString(TILItemShopParsingExtrMethod(i)));
finally
cmbExtractMethod.Items.EndUpdate;
end;
If cmbExtractMethod.Items.Count > 0 then
cmbExtractMethod.ItemIndex := 0;
end;
//------------------------------------------------------------------------------
procedure TfrmExtractionFrame.Finalize;
begin
//nothing to do here
end;
//------------------------------------------------------------------------------
procedure TfrmExtractionFrame.Save;
begin
FrameSave;
end;
//------------------------------------------------------------------------------
procedure TfrmExtractionFrame.Load;
begin
If Assigned(fExtractSett) then
FrameLoad
else
FrameClear;
end;
//------------------------------------------------------------------------------
procedure TfrmExtractionFrame.SetExtractSett(ExtractSett: PILItemShopParsingExtrSett; ProcessChange: Boolean);
begin
If ProcessChange then
begin
If Assigned(fExtractSett) then
FrameSave;
If Assigned(ExtractSett) then
begin
fExtractSett := ExtractSett;
FrameLoad;
end
else
begin
fExtractSett := nil;
FrameClear;
end;
Visible := Assigned(fExtractSett);
Enabled := Assigned(fExtractSett);
end
else fExtractSett := ExtractSett;
end;
end.
|
unit strings; { String handling primitives. }
{ These should be recoded in C instead of using the p2c code. }
interface
procedure scan1 (s: string; p: integer; var n: integer);
{ Read an integer at position p of s }
function startsWith (s1, s2: string): boolean;
function pos1(c: char; s: string): integer;
function posNot (c: char; var s: string): integer;
procedure insertChar (c: char; var s: string; p: integer);
function substr (var s: string; start, count: integer): string;
procedure getNum(line: string; var k: integer);
procedure getTwoNums(var line: string; var k1, k2: integer);
procedure toUpper(var s: string);
procedure delete1 (var s: string; p: integer);
procedure predelete (var s: string; l: integer);
procedure shorten (var s: string; new_length: integer);
function nextWordBound(s: string; trigger: char; p: integer): integer;
{ find end of first word starting with trigger after s[p] }
implementation
procedure scan1 (s: string; p: integer; var n: integer);
begin if length(s)<p then
writeln('scan1: string too short');
predelete(s,p-1); getNum(s,n);
end;
function pos1(c: char; s: string): integer;
begin pos1:= pos(c, s); end;
procedure delete1 (var s: string; p: integer);
begin if length(s)<p then
writeln('delete1: string too short');
delete(s,p,1);
end;
procedure predelete (var s: string; l: integer);
begin if length(s)<l then
writeln('predelete: string too short');
delete(s,1,l);
end;
procedure shorten (var s: string; new_length: integer);
begin if length(s)<new_length then
writeln('shorten: string too short');
s[0] := char(new_length);
end;
function posNot(c: char; var s: string): integer;
var i, l: integer;
begin l:=length(s);
for i:=1 to l do if s[i]<>c then
begin posnot:=i; exit; end;
posnot:=0;
end;
procedure strval(line: string; var num, p: integer);
begin val(line,num,p); end;
procedure getNum(line: string; var k: integer);
var code: integer;
begin strval(line,k,code);
if code>0 then strval(copy(line,1,code-1),k,code);
end;
procedure getTwoNums(var line: string; var k1, k2: integer);
var num, code, p: integer;
begin
strval(line,num,p); strval(copy(line,1,p-1),k1,code);
strval(copy(line,p+1,255),k2,code);
if code>0 then strval(copy(line,1,code-1),k2,code);
end;
procedure toUpper (var s: string);
var i: integer;
begin
for i:=1 to length(s) do s[i]:=upcase(s[i]);
end;
function startsWith (s1, s2: string): boolean;
var i, l1, l2: integer;
begin l1:=length(s1); l2:=length(s2);
startsWith := false; if l1<l2 then exit;
for i:=1 to l2 do if s1[i]<>s2[i] then exit;
startsWith := true;
end;
procedure insertChar (c: char; var s: string; p: integer);
begin if length(s)<p-1 then
writeln('insertchar: string too short');
insert(c,s,p);
end;
function substr (var s: string; start, count: integer): string;
begin if length(s)<start+count-1 then
writeln('insertchar: string too short');
substr := copy(s,start,count);
end;
function nextWordBound(s: string; trigger: char; p: integer): integer;
begin
repeat p:=p+1 until (p>length(s)) or (s[p]=trigger);
while (p<length(s)) and (s[p+1]<>' ') do p:=p+1;
nextWordBound:=p;
end;
end.
|
unit eGroup;
interface
uses
API_ORM,
eCommon,
eLink,
eRecord;
type
TGroupList = class;
TGroup = class(TEntity)
private
FChildGroupList: TGroupList;
FLinkList: TLinkList;
FParentGroupID: Integer;
FRecordList: TRecordList;
FRootChain: string;
function GetChildGroupList: TGroupList;
function GetLinkList: TLinkList;
function GetRecordList: TRecordList;
public
class function GetStructure: TSructure; override;
procedure AddLink(const aJobID, aLevel: Integer; const aURL: string;
aPostData: string = ''; aHeaders: string = '');
procedure AddRecord(const aKey, aValue: string);
property ChildGroupList: TGroupList read GetChildGroupList;
property LinkList: TLinkList read GetLinkList;
property RecordList: TRecordList read GetRecordList;
published
property ParentGroupID: Integer read FParentGroupID write FParentGroupID;
property RootChain: string read FRootChain write FRootChain;
end;
TGroupList = class(TEntityAbstractList<TGroup>)
end;
implementation
procedure TGroup.AddLink(const aJobID, aLevel: Integer; const aURL: string;
aPostData: string = ''; aHeaders: string = '');
var
Link: TLink;
begin
Link := TLink.Create(FDBEngine);
Link.JobID := aJobID;
Link.Level := aLevel;
Link.URL := aURL;
Link.HandledTypeID := 1;
LinkList.Add(Link);
end;
function TGroup.GetLinkList: TLinkList;
begin
if not Assigned(FLinkList) then
FLinkList := TLinkList.Create(Self);
Result := FLinkList;
end;
function TGroup.GetChildGroupList: TGroupList;
begin
if not Assigned(FChildGroupList) then
FChildGroupList := TGroupList.Create(Self);
Result := FChildGroupList;
end;
function TGroup.GetRecordList: TRecordList;
begin
if not Assigned(FRecordList) then
FRecordList := TRecordList.Create(Self);
Result := FRecordList;
end;
procedure TGroup.AddRecord(const aKey, aValue: string);
var
Rec: TRecord;
begin
Rec := TRecord.Create(FDBEngine);
Rec.Key := aKey;
Rec.Value := aValue;
RecordList.Add(Rec);
end;
class function TGroup.GetStructure: TSructure;
begin
Result.TableName := 'CORE_GROUPS';
AddForeignKey(Result.ForeignKeyArr, 'PARENT_GROUP_ID', TGroup, 'ID')
end;
end.
|
namespace TicTacToe;
interface
uses
Foundation;
type
ComputerPlayer = public class
private
fBoard: Board;
fComputerPlayer: String;
fForkSquares: Array[1..9] of NSInteger;
method playerAtCoordinates(x: Int32; y: Int32): String;
method OpponentInPosition(x, y : Int32):Boolean;
method ComputerInPosition(x, y : Int32):Boolean;
method OpponentInSquare(a : Int32):Boolean;
method ComputerInSquare(a : Int32):Boolean;
method EmptySquare(a : Int32):Boolean;
method XforPos(p : Int32):Int32;
method YforPos(p : Int32):Int32;
method WinningSquare(a: Int32; b: Int32; c: Int32): Int32;
method BlockingSquare(a: Int32; b: Int32; c: Int32): Int32;
method CheckFork(a: Int32; b: Int32; c: Int32);
method CheckForkBlock(a: Int32; b: Int32; c: Int32);
method CanPlay(a: Int32):Boolean;
method CanWin: Boolean;
method CanBlock: Boolean;
method CanFork: Boolean;
method CanBlockFork: Boolean;
method CanGoInCentre: Boolean;
method CanGoInOppositeCorner: Boolean;
method CanGoInEmptyCorner: Boolean;
method CanGoInEmptySide: Boolean;
protected
public
method makeBestMove(aPlayer: String; aBoard:Board);
method SetGridInfo(x, y : Int32; aPlayer:String);
end;
{ To make this clearer, the grid (which is in 2x2 array on the board) is referred to by number representing each of the nine squares, as follows:
1 | 2 | 3
---------
4 | 5 | 6
---------
7 | 8 | 9
The board calls makeBestMove which will work out the best location to go, and the board will go in this location.
This calls a series of possible moves in the order most likely to win the game (or at least, not lose).}
implementation
method ComputerPlayer.playerAtCoordinates(x, y: Int32): String;
begin
result := fBoard.GridInfo[x,y]:substringToIndex(1);
end;
method ComputerPlayer.OpponentInPosition(x, y : Int32):Boolean;
begin
result:=assigned(fBoard.GridInfo[x,y]) and (playerAtCoordinates(x, y) <> fComputerPlayer);
end;
method ComputerPlayer.ComputerInPosition(x, y : Int32):Boolean;
begin
result:=assigned(fBoard.GridInfo[x,y]) and (playerAtCoordinates(x, y) = fComputerPlayer);
end;
method ComputerPlayer.OpponentInSquare(a: Int32): Boolean;
begin
var x : Int32 := XforPos(a);
var y : Int32 := YforPos(a);
exit OpponentInPosition(x ,y);
end;
method ComputerPlayer.ComputerInSquare(a: Int32): Boolean;
begin
var x : Int32 := XforPos(a);
var y : Int32 := YforPos(a);
exit ComputerInPosition(x ,y);
end;
method ComputerPlayer.EmptySquare(a : Int32):Boolean;
begin
var x : Int32 := XforPos(a);
var y : Int32 := YforPos(a);
exit not assigned(fBoard.GridInfo[x,y]);
end;
method ComputerPlayer.XforPos(p: Int32): Int32;
begin
if p in [1,2,3] then exit 0
else if p in [4,5,6] then exit 1
else if p in [7,8,9] then exit 2;
end;
method ComputerPlayer.YforPos(p: Int32): Int32;
begin
if p in [1,4,7] then exit 0
else if p in [2,5,8] then exit 1
else if p in [3,6,9] then exit 2;
end;
method ComputerPlayer.WinningSquare(a,b,c : Int32):Int32; //lookup to see if one of the squares in the triple is available to win
begin
if ComputerInSquare(a) and ComputerInSquare(b) and EmptySquare(c) then exit c
else if ComputerInSquare(a) and ComputerInSquare(c) and EmptySquare(b) then exit b
else if ComputerInSquare(b) and ComputerInSquare(c) and EmptySquare(a) then exit a
else exit 0;
end;
method ComputerPlayer.BlockingSquare(a,b,c : Int32):Int32;//lookup to see if one of the three is available for opponent to win
begin
if OpponentInSquare(a) and OpponentInSquare(b) and EmptySquare(c) then exit c
else if OpponentInSquare(a) and OpponentInSquare(c) and EmptySquare(b) then exit b
else if OpponentInSquare(b) and OpponentInSquare(c) and EmptySquare(a) then exit a
else exit 0;
end;
method ComputerPlayer.CheckFork(a: Int32; b: Int32; c: Int32);
begin
if ComputerInSquare(a) and EmptySquare(b) and EmptySquare(c) then begin
inc(fForkSquares[b]);
inc(fForkSquares[c]);
end;
if ComputerInSquare(b) and EmptySquare(a) and EmptySquare(c) then begin
inc(fForkSquares[a]);
inc(fForkSquares[c]);
end;
if ComputerInSquare(c) and EmptySquare(b) and EmptySquare(a) then begin
inc(fForkSquares[b]);
inc(fForkSquares[a]);
end;
end;
method ComputerPlayer.CheckForkBlock(a: Int32; b: Int32; c: Int32);
begin
if OpponentInSquare(a) and EmptySquare(b) and EmptySquare(c) then begin
inc(fForkSquares[b]);
inc(fForkSquares[c]);
end;
if OpponentInSquare(b) and EmptySquare(a) and EmptySquare(c) then begin
inc(fForkSquares[a]);
inc(fForkSquares[c]);
end;
if OpponentInSquare(c) and EmptySquare(b) and EmptySquare(a) then begin
inc(fForkSquares[b]);
inc(fForkSquares[a]);
end;
end;
method ComputerPlayer.CanPlay(a : Int32):Boolean;
begin
if a=0 then exit false;
var x : Int32 := XforPos(a);
var y : Int32 := YforPos(a);
if not assigned(fBoard.GridInfo[x,y]) then begin
fBoard.markGrid(x, y, fComputerPlayer);
result:=True;
end else result:=false;
end;
method ComputerPlayer.CanWin:Boolean;//User isn't concentrating
begin
//the number triple is a potential winning line (there aren't many)
result:=CanPlay(WinningSquare(1,2,3)) or
CanPlay(WinningSquare(4,5,6)) or
CanPlay(WinningSquare(7,8,9)) or
CanPlay(WinningSquare(1,4,7)) or
CanPlay(WinningSquare(2,5,8)) or
CanPlay(WinningSquare(3,6,9)) or
CanPlay(WinningSquare(1,5,9)) or
CanPlay(WinningSquare(3,5,7));
end;
method ComputerPlayer.CanBlock:Boolean;//Stop the user winning
begin
result:=CanPlay(BlockingSquare(1,2,3)) or
CanPlay(BlockingSquare(4,5,6)) or
CanPlay(BlockingSquare(7,8,9)) or
CanPlay(BlockingSquare(1,4,7)) or
CanPlay(BlockingSquare(2,5,8)) or
CanPlay(BlockingSquare(3,6,9)) or
CanPlay(BlockingSquare(1,5,9)) or
CanPlay(BlockingSquare(3,5,7));
end;
method ComputerPlayer.CanFork:Boolean;
begin
//a fork is where the same square appears in two triples that could be a winning line
//so we need to find the empty square numbers a triple has the computer in the one square and the other two are empty
//then see if a number appears more than once in the array, which means it is a pivot for the fork
for i:Int32 :=1 to 9 do fForkSquares[i]:=0;
CheckFork(1,2,3);
CheckFork(4,5,6);
CheckFork(7,8,9);
CheckFork(1,4,7);
CheckFork(2,5,8);
CheckFork(3,6,9);
CheckFork(1,5,9);
CheckFork(3,5,7);
//now check if any are 2 or more and select first one available
for i:Int32 :=1 to 9 do
if ((fForkSquares[i]>1) and CanPlay(i)) then exit true;
exit false;
end;
method ComputerPlayer.CanBlockFork:Boolean;
begin
//Same as for a fork, but for the opponent, we need to prevent it
for i:Int32 :=1 to 9 do fForkSquares[i]:=0;
CheckForkBlock(1,2,3);
CheckForkBlock(4,5,6);
CheckForkBlock(7,8,9);
CheckForkBlock(1,4,7);
CheckForkBlock(2,5,8);
CheckForkBlock(3,6,9);
CheckForkBlock(1,5,9);
CheckForkBlock(3,5,7);
//now check if any are 2 or more and select first one available
for i:Int32 :=1 to 9 do
if ((fForkSquares[i]>1) and CanPlay(i)) then exit true;
exit false;
end;
method ComputerPlayer.CanGoInCentre:Boolean;
begin
result:=CanPlay(5);
end;
method ComputerPlayer.CanGoInOppositeCorner:Boolean;
begin
result:=(OpponentInSquare(1) and CanPlay(9))or
(OpponentInSquare(3) and CanPlay(7))or
(OpponentInSquare(7) and CanPlay(3))or
(OpponentInSquare(9) and CanPlay(1));
end;
method ComputerPlayer.CanGoInEmptyCorner:Boolean;
begin
result:=CanPlay(1) or CanPlay(3) or CanPlay(7) or CanPlay(7);
end;
method ComputerPlayer.CanGoInEmptySide:Boolean;
begin
result:=CanPlay(2) or CanPlay(4) or CanPlay(6) or CanPlay(8);
end;
method ComputerPlayer.makeBestMove(aPlayer: String; aBoard:Board);
begin
fComputerPlayer := aPlayer;
fBoard := aBoard;
if CanWin or
CanBlock or
CanFork or
CanBlockFork or
CanGoInCentre or
CanGoInOppositeCorner or
CanGoInEmptyCorner or
CanGoInEmptySide then;
end;
method ComputerPlayer.SetGridInfo(x: Int32; y: Int32; aPlayer: String);
begin
fBoard.markGrid(x, y, aPlayer);
end;
end.
|
unit uFrmPreSaleItemDiscount;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, PaideTodosGeral, siComp, siLangRT, StdCtrls, Buttons, ExtCtrls, Math;
type
TFrmPreSaleItemDiscount = class(TFrmParentAll)
btApply: TButton;
Label2: TLabel;
cmbCalcType: TComboBox;
edtValue: TEdit;
lblValue: TLabel;
Label1: TLabel;
edtSellingPrice: TEdit;
Label3: TLabel;
edtNewPrice: TEdit;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure cmbCalcTypeChange(Sender: TObject);
procedure edtValueChange(Sender: TObject);
procedure edtValueKeyPress(Sender: TObject; var Key: Char);
procedure btApplyClick(Sender: TObject);
private
fDiscountApplied: Boolean;
fSellingPrice : Currency;
function ValidadeDiscount:Boolean;
function ApplyDiscount(fType:Integer; Value:Currency):Currency;
public
property DiscountApplied: Boolean read fDiscountApplied;
function Start(SellingPrice:Currency):Currency;
end;
implementation
uses uNumericFunctions, uDMGlobal, uCharFunctions, uMsgBox, uMsgConstant, uDM;
{$R *.dfm}
{ TFrmPreSaleItemDiscount }
function TFrmPreSaleItemDiscount.Start(SellingPrice: Currency): Currency;
begin
fDiscountApplied := false;
fSellingPrice := SellingPrice;
// Antonio M F Souza November 27, 2012: edtSellingPrice.Text := MyFloatToStr(SellingPrice, DM.FQtyDecimalFormat);
edtSellingPrice.Text := MyFloatToStr(SellingPrice, getDisplayFormat(CountDecimalPlaces(sellingPrice)));
ShowModal;
if (ModalResult = mrOK) then begin
Result := ApplyDiscount(cmbCalcType.ItemIndex, MyStrToMoney(edtValue.Text));
fDiscountApplied := true;
end
else
Result := fSellingPrice;
end;
procedure TFrmPreSaleItemDiscount.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
procedure TFrmPreSaleItemDiscount.cmbCalcTypeChange(Sender: TObject);
begin
inherited;
lblValue.Caption:= cmbCalcType.Items[cmbCalcType.ItemIndex];
if edtValue.Text <> '' then
edtNewPrice.Text := MyFloatToStr(ApplyDiscount(cmbCalcType.ItemIndex, MyStrToMoney(edtValue.Text)), DM.FQtyDecimalFormat);
end;
procedure TFrmPreSaleItemDiscount.edtValueChange(Sender: TObject);
begin
inherited;
edtNewPrice.Text := MyFloatToStr(ApplyDiscount(cmbCalcType.ItemIndex, MyStrToMoney(edtValue.Text)), DM.FQtyDecimalFormat);;
end;
procedure TFrmPreSaleItemDiscount.edtValueKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
Key := ValidateCurrency(Key);
if Key = ThousandSeparator then
begin
Key:=#0;
MessageBeep($FFFFFFFF);
end;
end;
function TFrmPreSaleItemDiscount.ValidadeDiscount: Boolean;
begin
Result := True;
if (cmbCalcType.ItemIndex = 0) and (MyStrToMoney(edtValue.Text) > 99) then
begin
MsgBox(MSG_INF_DISCOUNT_LIMT_REACHED, vbOKOnly + vbInformation);
Result := False;
end;
end;
procedure TFrmPreSaleItemDiscount.btApplyClick(Sender: TObject);
begin
inherited;
if not ValidadeDiscount then
ModalResult := mrNone;
end;
function TFrmPreSaleItemDiscount.ApplyDiscount(fType: Integer;
Value: Currency): Currency;
var
roundValue: extended;
roundSellingPrice: extended;
begin
// Antonio M F Souza November 11, 2012
//roundValue := forceRoundInThirdPosition(value, 2);
//roundSellingPrice := forceRoundInThirdPosition(fSellingPrice, 2);
if fType = 0 then
Result := fSellingPrice - (fSellingPrice * (Value/power(10, CountDecimalPlaces(value))))
// Antonio M F Souza November 11, 2012: Result := fSellingPrice - (fSellingPrice * (Value/power(10, DM.FQtyDecimal)))
// result := roundSellingPrice - (roundSellingPrice * ( roundValue / power(10, dm.FQtyDecimal)))
else
Result := fSellingPrice - Value;
// Antonio M F Souza November 11, 2012: Result := fSellingPrice - Value;
// result := roundSellingPrice - roundValue;
end;
end.
|
unit uVSSimpleExpress;
{违标简单表达式单元}
interface
uses
classes,Windows,SysUtils,Forms,DateUtils,
uVSConst,uLKJRuntimeFile,uVSAnalysisResultList;
type
TCustomGetValueEvent = function(RecHead:RLKJRTFileHeadInfo;
RecRow:TLKJRuntimeFileRec):Variant of object;
//////////////////////////////////////////////////////////////////////////////
//TVSExpression违标条件表达式基类,所有表达式从次继承
//////////////////////////////////////////////////////////////////////////////
TVSExpression = class
private
{$region '私有变量'}
m_State : TVSCState; //条件的当前状态
m_LastState : TVSCState; //前一个匹配状态
m_pLastData : Pointer; //上一条数据
m_pFitData : Pointer; //第一个适合状态的数据
m_pAcceptData : Pointer; //第一个接收状态的数据
m_strTitle : string; //用于输出日志的表达式定义
m_bSaveFirstFit : boolean; //定义是要保存第一个匹配中还是最后一个匹配中的数据
m_strExpressID : string; //ID,作为唯一标识用
{$endregion '私有变量'}
protected
function GetLastState: TVSCState;
function GetState: TVSCState;virtual;
function GetLastData: Pointer;virtual;
procedure SetState(const Value: TVSCState);virtual;
procedure SetAcceptData(const Value: Pointer);virtual;
function GetAcceptData: Pointer;virtual; //第一个可能适合的值
procedure SetLastData(const Value: Pointer);virtual;
public
{$region '构造、析构'}
constructor Create();virtual;
destructor Destroy();override;
{$endregion '构造、析构'}
public
//获取状态的文字说明
class function GetStateText(s : TVSCState) : string;
//获取运行记录的列的文字说明
class function GetColumnText(c : Integer) : string;
//获取指定机车标压
class function GetStandardPressure(RecHead:RLKJRTFileHeadInfo):integer;
//获取当前记录指定违标项的值
class function GetRecValue(RecField : Integer;RecHead:RLKJRTFileHeadInfo;RecRow:TLKJRuntimeFileRec):Variant;
//比对单条运行记录,并返回比对结果
function Match(RecHead:RLKJRTFileHeadInfo;RecRow:TLKJRuntimeFileRec;RewList:TList): TVSCState;virtual;
//清空出LastData外其它值
procedure Reset;virtual;
//清空包括LastData的值
procedure Init;virtual;
//重新初始化状态,用于外部赋值与自己赋值相隔开
procedure InitState(Value : TVSCState);virtual;
//获取实际的数据
function GetData : Pointer;virtual;
function GetBeginData : Pointer;virtual;
function GetEndData : Pointer;virtual;
public
{$region '属性'}
//前一个匹配状态
property LastState : TVSCState read m_LastState write m_LastState;
//当前匹配状态
property State : TVSCState read m_State write SetState;
//第一个接收数据
property AcceptData : Pointer read m_pAcceptData write SetAcceptData;
//上一个数据
property LastData : Pointer read m_pLastData write SetLastData;
//第一个FIT数据
property FitData : Pointer read m_pFitData write m_pFitData;
//用于输出日志的表达式定义
property Title : string read m_strTitle write m_strTitle;
//定义是要保存第一个匹配中还是最后一个匹配中的数据
property SaveFirstFit : boolean read m_bSaveFirstFit write m_bSaveFirstFit;
//ID,作为唯一标识用
property ExpressID : string read m_strExpressID write m_strExpressID;
{$endregion '属性'}
end;
//////////////////////////////////////////////////////////////////////////////
//TVSCompExpression 比对表达式 例如:限速 < 80
//////////////////////////////////////////////////////////////////////////////
TVSCompExpression = class(TVSExpression)
private
m_nKey : integer; //操作数
m_OperatorSignal : TVSOperator; //操作符
m_Value : Variant; //被操作符
m_OnCustomGetValue : TCustomGetValueEvent; //比对之前由用户操作
public
//比对运行记录与表达式定义,
function Match(RecHead:RLKJRTFileHeadInfo;RecRow:TLKJRuntimeFileRec;RewList:TList): TVSCState;override;
//操作数
property Key : Integer read m_nKey write m_nKey;
//操作符
property OperatorSignal : TVSOperator read m_OperatorSignal write m_OperatorSignal;
//被操作符
property Value : Variant read m_Value write m_Value;
//比对之前由用户操作
property OnCustomGetValue : TCustomGetValueEvent read m_OnCustomGetValue write m_OnCustomGetValue;
end;
TInOrNotIn = (tInNotIn,tInNotNot);
//////////////////////////////////////////////////////////////////////////////
//TVSInExpression In表达式 例如:10在10、20、30内
//////////////////////////////////////////////////////////////////////////////
TVSInExpression = class(TVSExpression)
private
m_nKey : integer;
m_OperatorSignal : TInOrNotIn;
m_Value : TStrings;
public
{$region '构造、析构'}
constructor Create();override;
destructor Destroy();override;
{$endregion '构造、析构'}
public
//比对运行记录与表达式定义,
function Match(RecHead:RLKJRTFileHeadInfo;RecRow:TLKJRuntimeFileRec;RewList:TList): TVSCState;override;
public
//操作数
property Key : Integer read m_nKey write m_nKey;
property OperatorSignal : TInOrNotIn read m_OperatorSignal write m_OperatorSignal;
//被操作符
property Value : TStrings read m_Value write m_Value;
end;
//////////////////////////////////////////////////////////////////////////////
//TVSOrderExpression 顺序表达式 例如:速度下降
//////////////////////////////////////////////////////////////////////////////
TVSOrderExpression = class(TVSExpression)
private
m_nKey : Integer; //操作数
m_Order : TVSOrder; //顺序
public
constructor Create(); override;
public
//比对运行记录与表达式定义,
function Match(RecHead:RLKJRTFileHeadInfo;RecRow:TLKJRuntimeFileRec;RewList:TList): TVSCState;override;
//趋势项代码
property Key : Integer read m_nKey write m_nKey;
//趋势值
property Order : TVSOrder read m_Order write m_Order;
end;
//////////////////////////////////////////////////////////////////////////////
//TVSOffsetExpression 顺序差值表达式 例如:管压下降80kpa
/////// ///////////////////////////////////////////////////////////////////////
TVSOffsetExpression = class(TVSExpression)
private
m_nKey : Integer; //操作数
m_Order : TVSOrder; //顺序
m_nValue : Integer; //临界值 (增加多少或减少多少)
m_bIncludeEqual : boolean; //是否包括等于
m_breakLimit : Integer;
public
constructor Create();override;
//比对运行记录与表达式定义,
function Match(RecHead:RLKJRTFileHeadInfo;RecRow:TLKJRuntimeFileRec;RewList:TList): TVSCState;override;
//操作数
property Key : Integer read m_nKey write m_nKey;
//顺序
property Order : TVSOrder read m_Order write m_Order;
//临界值 (增加多少或减少多少)
property Value : Integer read m_nValue write m_nValue;
//是否包括等于
property IncludeEqual : boolean read m_bIncludeEqual write m_bIncludeEqual;
//数值跳变上限,跳变超限则Reset
property BreakLimit : Integer read m_breakLimit write m_breakLimit;
end;
//////////////////////////////////////////////////////////////////////////////
//TVSOffsetExExpression 顺序差值表达式 在 TVSOffsetExpression基础上增加差值上限
//如差值大于上限则不属于要求范围
//////////////////////////////////////////////////////////////////////////////
TVSOffsetExExpression = class(TVSExpression)
private
m_nKey : Integer; //操作数
m_Order : TVSOrder; //顺序
m_nValue : Integer; //临界值 (增加多少或减少多少)
m_bIncludeEqual : boolean; //是否包括等于
m_breakLimit : Integer;
m_nMaxValue : Integer; //差值上限
public
constructor Create();override;
//比对运行记录与表达式定义,
function Match(RecHead:RLKJRTFileHeadInfo;RecRow:TLKJRuntimeFileRec;RewList:TList): TVSCState;override;
//操作数
property Key : Integer read m_nKey write m_nKey;
//顺序
property Order : TVSOrder read m_Order write m_Order;
//临界值 (增加多少或减少多少)
property Value : Integer read m_nValue write m_nValue;
//差值上限
property MaxValue : Integer read m_nMaxValue write m_nMaxValue;
//是否包括等于
property IncludeEqual : boolean read m_bIncludeEqual write m_bIncludeEqual;
//数值跳变上限,跳变超限则Reset
property BreakLimit : Integer read m_breakLimit write m_breakLimit;
end;
//////////////////////////////////////////////////////////////////////////////
//TVSCompBehindExpression 后置比对表达式 用于比对前面表达式的结果
//////////////////////////////////////////////////////////////////////////////
TVSCompBehindExpression = class(TVSExpression)
private
m_Key : Integer; //比对字段
m_OperatorSignal : TVSOperator; //比对方式
m_CompDataType : TVSDataType; //比对数据
m_nValue : Integer; //比对差值
m_FrontExp : TVSExpression; //前一个简单表达式
m_BehindExp : TVSExpression; //后一个简单表达式
public
//比对运行记录与表达式定义,
function Match(RecHead:RLKJRTFileHeadInfo;RecRow:TLKJRuntimeFileRec;RewList:TList): TVSCState;override;
//比对字段
property Key : Integer read m_Key write m_Key;
//比对方式
property OperatorSignal : TVSOperator read m_OperatorSignal write m_OperatorSignal;
//比对数据
property CompDataType : TVSDataType read m_CompDataType write m_CompDataType;
//比对差值
property Value : Integer read m_nValue write m_nValue;
//前一个简单表达式
property FrontExp : TVSExpression read m_FrontExp write m_FrontExp;
//后一个简单表达式
property BehindExp : TVSExpression read m_BehindExp write m_BehindExp;
end;
TVSCompExpExpression = class(TVSExpression)
private
m_Key : Integer; //比对字段
m_OperatorSignal : TVSOperator; //比对方式
m_CompDataType : TVSDataType; //比对数据
m_nValue : Integer; //比对差值
m_Expression : TVSExpression;
public
//比对运行记录与表达式定义,
function Match(RecHead:RLKJRTFileHeadInfo;RecRow:TLKJRuntimeFileRec;RewList:TList): TVSCState;override;
public
//比对字段
property Key : Integer read m_Key write m_Key;
//比对方式
property OperatorSignal : TVSOperator read m_OperatorSignal write m_OperatorSignal;
//比对数据
property CompDataType : TVSDataType read m_CompDataType write m_CompDataType;
//比对差值
property Value : Integer read m_nValue write m_nValue;
//表达式
property Expression : TVSExpression read m_Expression write m_Expression;
end;
/////////////////////////////////////////////////////////////////////////
///TVSSimpleIntervalExpression 获到在一个范围内从第一个或最后一个某一条件
///开始到范围结束的表达式,从指定条件开始,到范围结束返回值为Matching其他
///返回为Unmatch
/////////////////////////////////////////////////////////////////////////
TVSSimpleIntervalExpression = class(TVSExpression)
private
m_StartKey : Integer; //开始条件
m_EndKey : Integer; //结束条件
m_Expression : TVSExpression; //实际比对表达式
m_StartValue : Variant;
m_EndValue : Variant;
m_StartPos : Integer; //查找到的范围开始索引
m_EndPos : Integer; //查找到的范围结束索引
m_IsScaned : Boolean; //已经扫描过标志
public
constructor Create();override;
destructor Destroy; override;
public
//清空出LastData外其它值
procedure Reset;override;
//清空包括LastData的值
procedure Init;override;
function GetData : Pointer;override;
function Match(RecHead:RLKJRTFileHeadInfo;RecRow:TLKJRuntimeFileRec;RewList:TList): TVSCState;override;
property StartKey : Integer read m_StartKey write m_StartKey;
property EndKey : Integer read m_EndKey write m_EndKey;
property StartValue : Variant read m_StartValue write m_StartValue;
property EndValue : Variant read m_EndValue write m_EndValue;
property Expression : TVSExpression read m_Expression write m_Expression;
end;
TVSConditionTimesExpression = class(TVSExpression)
private
m_Expression : TVSExpression;
m_InputTimes : Integer;
m_Times : Integer;
m_OperatorSignal : TVSOperator; //比对方式
public
constructor Create();override;
destructor Destroy; override;
procedure Reset;override;
procedure Init;override;
function GetData : Pointer;override;
function Match(RecHead:RLKJRTFileHeadInfo;RecRow:TLKJRuntimeFileRec;RewList:TList): TVSCState;override;
public
property OperatorSignal : TVSOperator read m_OperatorSignal write m_OperatorSignal;
property InputTimes : Integer read m_InputTimes write m_InputTimes;
property Expression : TVSExpression read m_Expression write m_Expression;
end;
///////////////////////////////////////////////////////////////////////////
///TVSSimpleConditionExpression 当满足Expression后一直返回Matched,未满足前
///持续返回UnMatch
///////////////////////////////////////////////////////////////////////////
TVSSimpleConditionExpression = class(TVSExpression)
private
m_Expression : TVSExpression;
m_ConditionIsTrue : Boolean;
public
constructor Create();override;
destructor Destroy; override;
procedure Reset;override;
procedure Init;override;
function GetData : Pointer;override;
function Match(RecHead:RLKJRTFileHeadInfo;RecRow:TLKJRuntimeFileRec;RewList:TList): TVSCState;override;
property Expression : TVSExpression read m_Expression write m_Expression;
end;
var
nJGID : integer;
implementation
uses
uVSLog;
{$region 'TVSExpression 实现'}
constructor TVSExpression.Create;
begin
m_State := vscUnMatch;
m_LastState := vscUnMatch;
m_pLastData := nil;
m_pFitData := nil;
m_pAcceptData := nil;
m_strTitle := '';
m_bSaveFirstFit := true;
end;
destructor TVSExpression.Destroy;
begin
inherited;
end;
function TVSExpression.GetAcceptData: Pointer;
begin
Result := m_pAcceptData;
end;
function TVSExpression.GetBeginData: Pointer;
begin
Result := GetData;
end;
class function TVSExpression.GetColumnText(c: Integer): string;
begin
Result := '异常列';
case c of
CommonRec_Column_GuanYa : Result := '管压';
CommonRec_Column_GangYa : Result := '缸压';
CommonRec_Column_Sudu : Result := '速度';
CommonRec_Column_WorkZero : Result := '工况零位';
CommonRec_Column_HandPos : Result := '工况前后';
CommonRec_Column_WorkDrag : Result := '手柄位置';
CommonRec_Column_DTEvent : Result := '时间';
CommonRec_Column_Distance : Result := '信号机距离';
CommonRec_Column_LampSign : Result := '信号灯';
CommonRec_Column_SpeedLimit : Result := '限速';
CommonRec_Head_TotalWeight: Result := '总重';
end;
end;
function TVSExpression.GetData: Pointer;
begin
Result := m_pFitData;
end;
function TVSExpression.GetEndData: Pointer;
begin
Result := GetData;
end;
function TVSExpression.GetLastData: Pointer;
begin
Result := m_pLastData;
end;
function TVSExpression.GetLastState: TVSCState;
begin
Result := m_LastState;
end;
class function TVSExpression.GetRecValue(RecField: Integer;
RecHead: RLKJRTFileHeadInfo; RecRow: TLKJRuntimeFileRec): Variant;
var
dt : TDateTime;
h,m,s,ms:word;
begin
Result := 0;
case RecField of
CommonRec_Head_KeHuo :
begin
result := RecHead.TrainType;
exit;
end;
CommonRec_Head_TotalWeight://总重
begin
result := RecHead.nTotalWeight;
exit;
end;
CommonRec_Head_CheCi: //车次
begin
result := RecHead.nTrainNo;
exit;
end;
CommonRec_Head_LiangShu: //辆数
begin
result := RecHead.nSum;
exit;
end;
CommonRec_Head_LocalType: //车型
begin
result := RecHead.nLocoType;
exit;
end;
CommonRec_Head_LocalID: //车号
begin
result := RecHead.nLocoID;
exit;
end;
CommonRec_Head_Factory: //监控厂家
begin
result := RecHead.Factory;
exit;
end;
end;
if RecRow = nil then
begin
//异常
PostMessage(ErrorHandle,WM_ERROR_GETVALUE,RecField,0);
exit;
end;
case RecField of
CommonRec_Column_GuanYa :
begin
result := TLKJCommonRec(RecRow).CommonRec.nLieGuanPressure;
exit;
end;
CommonRec_Column_JGPressure :
begin
case nJGID of
1 :
Result := TLKJCommonRec(RecRow).CommonRec.nJG1Pressure;
2 :
Result := TLKJCommonRec(RecRow).CommonRec.nJG2Pressure;
end;
Exit;
end;
CommonRec_Column_Sudu :
begin
result := TLKJCommonRec(RecRow).CommonRec.nSpeed;
exit;
end;
CommonRec_Column_WorkZero :
begin
result := TLKJCommonRec(RecRow).CommonRec.WorkZero;
exit;
end;
CommonRec_Column_HandPos :
begin
result := TLKJCommonRec(RecRow).CommonRec.HandPos;
exit;
end;
CommonRec_Column_WorkDrag :
begin
result := TLKJCommonRec(RecRow).CommonRec.WorkDrag;
exit;
end;
CommonRec_Column_DTEvent :
begin
try
dt := TLKJCommonRec(RecRow).CommonRec.DTEvent;
DecodeTime(dt,h,m,s,ms);
result := h * SecsPerMin*MinsPerHour + m*SecsPerMin + s;
except
PostMessage(ErrorHandle,WM_ERROR_GETVALUE,RecField,1);
result := 0;
end;
exit;
end;
CommonRec_Column_Coord :
begin
result := TLKJCommonRec(RecRow).CommonRec.nCoord;
exit;
end;
CommonRec_Column_Distance: //信号机距离;
begin
result := TLKJCommonRec(RecRow).CommonRec.nDistance;
exit;
end;
CommonRec_Column_LampSign : //信号灯类型;
begin
result := TLKJCommonRec(RecRow).CommonRec.LampSign;
exit;
end;
CommonRec_Column_SpeedLimit : //信号灯类型;
begin
result := TLKJCommonRec(RecRow).CommonRec.nLimitSpeed;
exit;
end;
CommonRec_Event_Column : //事件编号
begin
result := TLKJCommonRec(RecRow).CommonRec.nEvent;
exit;
end;
CommonRec_Column_GangYa: //缸压
begin
result := TLKJCommonRec(RecRow).CommonRec.nGangPressure;
exit;
end;
CommonRec_Column_Other: //其它
begin
result := TLKJCommonRec(RecRow).CommonRec.strOther;
exit;
end;
CommonRec_Column_StartStation : //终点站
begin
result := TLKJCommonRec(RecRow).CommonRec.nStation;
exit;
end;
CommonRec_Column_EndStation : //终点站
begin
result := TLKJCommonRec(RecRow).CommonRec.nToStation;
exit;
end;
CommonRec_Column_LampNumber :
begin
Result := TLKJCommonRec(RecRow).CommonRec.nLampNo;
Exit;
end;
CommonRec_Column_Rotate :
begin
Result := TLKJCommonRec(RecRow).CommonRec.nRotate;
Exit;
end;
CommonRec_Column_ZT :
begin
Result := TLKJCommonRec(RecRow).CommonRec.JKZT;
Exit;
end;
end;
end;
class function TVSExpression.GetStandardPressure(
RecHead: RLKJRTFileHeadInfo): integer;
begin
Result := SYSTEM_STANDARDPRESSURE_KE;
if RecHead.TrainType = ttCargo then
begin
Result := SYSTEM_STANDARDPRESSURE_HUO;
if UpperCase(Trim(RecHead.strTrainHead)) = 'X' then
begin
Result := SYSTEM_STANDARDPRESSURE_XING;
end;
end;
end;
function TVSExpression.GetState: TVSCState;
begin
Result := m_State;
end;
class function TVSExpression.GetStateText(s : TVSCState): string;
begin
Result := '异常状态';
case s of
vscAccept: result := '接受';
vscMatching: result := '匹配中';
vscMatched: result := '已匹配';
vscUnMatch: result := '未匹配';
end;
end;
procedure TVSExpression.Init;
begin
m_State := vscUnMatch;
m_LastState := vscUnMatch;
m_pLastData := nil;
m_pFitData := nil;
m_pAcceptData := nil;
end;
procedure TVSExpression.InitState(Value : TVSCState);
begin
State := Value;
end;
function TVSExpression.Match(RecHead: RLKJRTFileHeadInfo;
RecRow: TLKJRuntimeFileRec;RewList:TList): TVSCState;
begin
//比对结果赋值到表达式状态
VSLog.AddExpress(self,RecHead,RecRow);
//保存数据到上一次数据
m_pLastData := RecRow;
end;
procedure TVSExpression.Reset;
begin
m_State := vscUnMatch;
m_LastState := vscUnMatch;
m_pAcceptData := nil;
m_pFitData := nil;
end;
procedure TVSExpression.SetAcceptData(const Value: Pointer);
begin
m_pAcceptData := Value;
end;
procedure TVSExpression.SetLastData(const Value: Pointer);
begin
m_pLastData := Value;
end;
procedure TVSExpression.SetState(const Value: TVSCState);
begin
m_LastState := m_State;
m_State := Value;
end;
{$endregion}
{$region 'TVSCompExpression 实现'}
//比对运行记录与表达式定义,
function TVSCompExpression.Match(RecHead: RLKJRTFileHeadInfo;
RecRow: TLKJRuntimeFileRec;RewList:TList): TVSCState;
const
SPVAILD =20; //标压的有效范围
var
inputValue : Variant; //当前据说的值
transValue : Variant; //管压经过翻译后的值
bFlag : Boolean; //比对结果
begin
case Key of
CommonRec_Column_VscMatched :
begin
Result := vscMatched;
m_pFitData := RewList.Items[0];
State := Result;
Exit;
end;
CommonRec_Column_VscUnMatch :
begin
Result := vscUnMatch;
State := Result;
Exit;
end;
end;
transValue := Value;
//比对结果
bFlag := false;
//后去输入的值
if Assigned(m_OnCustomGetValue) then
transValue := m_OnCustomGetValue(RecHead,RecRow);
inputValue := GetRecValue(Key,RecHead,RecRow);
if ((Key = CommonRec_Column_GuanYa)or(Key = CommonRec_Column_JGPressure))
and (Value = SYSTEM_STANDARDPRESSURE ) AND (OperatorSignal=vspEqual) then
begin
if inputValue >= GetStandardPressure(RecHead) - SPVAILD then
begin
bFlag := true;
end;
end
else begin
if ((Key = CommonRec_Column_GuanYa)or(Key = CommonRec_Column_JGPressure)) and (Value >10000 ) then
begin
{$region '标压比对特殊处理'}
transValue := Value - SYSTEM_STANDARDPRESSURE + GetStandardPressure(RecHead);
{$endregion '翻译标压及标压差值'}
end;
{$region '比对输入值与标准值'}
case OperatorSignal of
vspMore: //大于
begin
if inputValue > transValue then
bFlag := true;
end;
vspLess:
begin
if inputValue < transValue then
bFlag := true;
end;
vspEqual:
begin
if inputValue = transValue then
bFlag := true;
end;
vspNoMore:
begin
if inputValue <= transValue then
bFlag := true;
end;
vspNoLess:
begin
if inputValue >= transValue then
bFlag := true;
end;
vspNoEqual:
begin
if inputValue <> transValue then
bFlag := true;
end;
vspLeftLike:
begin
if Copy(transValue,0,Pos('?',transValue)-1) = Copy(inputValue,0,Pos('?',transValue)-1) then
begin
if length(transValue) = length(inputValue) then
begin
bFlag := true;
end;
end;
end;
vspLeftNotLike:
begin
if length(transValue) <> length(inputValue) then
begin
bFlag := true;
end
else begin
if Copy(transValue,0,Pos('?',transValue)-1) <> Copy(inputValue,0,Pos('?',transValue)-1) then
begin
bFlag := true;
end;
end;
end;
end;
{$endregion '比对输入值与标准值'}
end;
//如果上一次已经匹配过则判断上一次数据和此次数据是否相等,不等则返回不匹配
if (m_pLastData <> nil) and (OperatorSignal = vspEqual) and ((State = vscMatching) or (State = vscMatched)) then
begin
if GetRecValue(Key,RecHead,m_pLastData) <> inputValue then
begin
bFlag := false;
end;
end;
{$region '状态判断'}
//比对通过
if bFlag then
begin
{$region '比对通过'}
//当前一次状态为不匹配,则将状态置为适合,且记录第一次适合的数据
if (State = vscUnMatch) or (State = vscAccept) then
begin
m_pFitData := RecRow;
end;
//保存最后一个匹配值
if not SaveFirstFit then
m_pFitData := RecRow;
Result := vscMatching;
{$endregion '比对通过'}
end
else begin
{$region '比对不通过'}
//当前一次状态为适合,则将状态置为匹配,否则状态置为不匹配
if State = vscMatching then
Result := vscMatched
else
Result := vscUnMatch;
{$endregion '比对不通过'}
end;
{$endregion '状态判断'}
State := Result;
inherited Match(RecHead,RecRow,RewList);
end;
{$endregion 'TVSCompExpression 实现'}
{$region 'TVSOrderExpression 实现'}
{ TVSOrderExpression }
//比对运行记录与表达式定义,
constructor TVSOrderExpression.Create;
begin
m_nKey := 0;
inherited;
end;
function TVSOrderExpression.Match(RecHead: RLKJRTFileHeadInfo;
RecRow: TLKJRuntimeFileRec;RewList:TList): TVSCState;
var
inputValue : Variant; //输入的值
lastValue : Variant; //上一个值
begin
Result := vscUnMatch;
//获取输入值
inputValue := GetRecValue(Key,RecHead,RecRow);
//获取上一个值
if (m_pLastData <> nil) then
begin
lastValue := GetRecValue(Key,RecHead,TLKJRuntimeFileRec(m_pLastData));
end;
//判断排序规则
case order of
vsoArc:
begin
{$region '需要上升的数据'}
//当为第一条数据时,直接置为接收状态
if m_pLastData = nil then
begin
m_pLastData := RecRow;
m_pAcceptData := RecRow;
Result := vscAccept;
end
else begin
if inputValue >= lastValue then
begin
{$region '当传入的值处于上升趋势'}
if inputValue = lastValue then
begin
{$region '两次值相等时'}
//上一次为不匹配,此次为接受且记录第一个接收的值
if State = vscUnMatch then
begin
m_pAcceptData := RecRow;
Result := vscAccept;
end;
//上一次为接收,此次仍为接受
if State = vscAccept then
begin
Result := vscAccept;
end;
//上一次为匹配中,此次仍为接受
if State = vscMatching then
begin
Result := vscMatching;
end;
{$endregion '两次值相等时'}
end
else begin
{$region '当传入的值为上升时,状态置为匹配中'}
//当上一次为未匹配则此次为接受中,且记录第一个接收的值及第一个匹配中的值
if State = vscUnMatch then
begin
m_pAcceptData := RecRow;
m_pFitData := RecRow;
end;
//当上一次为接受中则此次为匹配中,且记录第一个匹配中的值
if State = vscAccept then
begin
m_pFitData := RecRow;
end;
Result := vscMatching;
{$endregion '当传入的值为上升时,状态置为匹配中'}
end;
{$endregion '当传入的值处于上升趋势'}
end
else begin
{$region '当传入的值为下降时'}
if State = vscMatching then
begin
Result := vscMatched;
end else
Result := vscUnMatch;
{$endregion '当传入的值为下降时'}
end;
end;
{$endregion 需要上升的数据}
end;
vsoDesc:
begin
{$region '需要下降的数据'}
//当为第一条数据时,直接置为接收状态
if m_pLastData = nil then
begin
m_pLastData := RecRow;
m_pAcceptData := RecRow;
Result := vscAccept;
end
else begin
if inputValue <= lastValue then
begin
{$region '当传入的值处于下降趋势'}
if inputValue = lastValue then
begin
{$region '两次值相等时'}
//上一次为不匹配,此次为接受且记录第一个接收的值
if State = vscUnMatch then
begin
m_pAcceptData := RecRow;
Result := vscAccept;
end;
//上一次为接收,此次仍为接受
if State = vscAccept then
begin
Result := vscAccept;
end;
//上一次为匹配中,此次仍为接受
if State = vscMatching then
begin
Result := vscMatching;
end;
{$endregion '两次值相等时'}
end
else begin
{$region '当传入的值为下降时,状态置为匹配中'}
//当上一次为未匹配则此次为接受中,且记录第一个接收的值及第一个匹配中的值
if State = vscUnMatch then
begin
m_pAcceptData := RecRow;
m_pFitData := RecRow;
end;
//当上一次为接受中则此次为匹配中,且记录第一个匹配中的值
if State = vscAccept then
begin
m_pFitData := RecRow;
end;
Result := vscMatching;
{$endregion '当传入的值为上升时,状态置为匹配中'}
end;
{$endregion '当传入的值处于下降趋势'}
end
else begin
{$region '当传入的值为上升时'}
if State = vscMatching then
begin
Result := vscMatched;
end else
Result := vscUnMatch;
{$endregion '当传入的值为上升时'}
end;
end;
{$endregion 需要下降的数据}
end;
end;
State := Result;
inherited Match(RecHead,RecRow,RewList);
end;
{$endregion 'TVSOrderExpression 实现'}
{$region 'TVSOffsetExpression 实现'}
{ TVSOffsetExpression }
constructor TVSOffsetExpression.Create;
begin
inherited;
m_bIncludeEqual := true;
m_breakLimit := 0;
end;
function TVSOffsetExpression.Match(RecHead: RLKJRTFileHeadInfo;
RecRow: TLKJRuntimeFileRec;RewList:TList): TVSCState;
var
inputValue : Variant; //输入值
lastValue : Variant; //上一个值
acceptValue : Variant; //接收的值
bFlag : boolean; //比对结果
begin
Result := vscUnMatch;
//获取输入值
inputValue := GetRecValue(Key,RecHead,RecRow);
//获取上一个值
if (m_pLastData <> nil) then
begin
lastValue := GetRecValue(Key,RecHead,TLKJRuntimeFileRec(m_pLastData));
end;
//如果数据跳变超过上限,则复位
if m_breakLimit <> 0 then
begin
if Abs(inputValue - lastValue) > m_breakLimit then
begin
Reset();
Exit;
end;
end;
case order of
vsoArc:
begin
{$region '需要上升趋势判断'}
//第一次记录直接置为接收且保存第一次接收状态的数据
if (m_pLastData = nil) or (m_pAcceptData = nil) then
begin
if m_pLastData = nil then
m_pLastData := RecRow;
if m_pAcceptData = nil then
m_pAcceptData := RecRow;
Result := vscAccept;
end
else begin
//获取第一次接受的值
acceptValue := GetRecValue(Key,RecHead,TLKJRuntimeFileRec(m_pAcceptData));
if inputValue >= lastValue then
begin
{$region '当接收到上升趋势的数据时'}
//判断是否上升了指定的值
bFlag := (inputValue - acceptValue) > m_nValue;
if (m_bIncludeEqual) then
bFlag := (inputValue - acceptValue) >= m_nValue;
if bFlag then
begin
{$region '结果匹配,记录状态为匹配中'}
//上一次为未匹配则本次为接受状态,且记录第一次接受和匹配的值
if State = vscUnMatch then
begin
m_pAcceptData := RecRow;
m_pFitData := RecRow;
end;
//上一次为接受则本次仍为接受状态,且记录第一次匹配的值
if (State = vscAccept) then
begin
m_pFitData := RecRow;
end;
Result := vscMatching;
{$endregion '结果匹配,记录状态为匹配中'}
end
else begin
{$region '结果不匹,记录状态为接收'}
if State = vscUnMatch then
begin
m_pAcceptData := RecRow;
end;
Result := vscAccept;
{$endregion '结果不匹,记录状态为接收'}
end;
{$endregion '当接收到上升趋势的数据时'}
end
else begin
{$region '当接收到下降趋势的数据时'}
if State = vscMatching then
begin
Result := vscMatched;
end
else
Result := vscUnMatch;
{$endregion '当接收到下降趋势的数据时'}
end;
end;
{$endregion '需要上升趋势判断'}
end;
vsoDesc:
begin
{$region '需要下降趋势判断'}
//第一次记录直接置为接收且保存第一次接收状态的数据
if (m_pLastData = nil) or (m_pAcceptData = nil) then
begin
if m_pLastData = nil then
m_pLastData := RecRow;
if m_pAcceptData = nil then
m_pAcceptData := RecRow;
Result := vscAccept;
end
else begin
//获取接受状态的值
acceptValue := GetRecValue(Key,RecHead,TLKJRuntimeFileRec(m_pAcceptData));
if inputValue <= lastValue then
begin
{$region '当接受到下降趋势的值'}
bFlag := (acceptValue - inputValue) > m_nValue;
if (m_bIncludeEqual) then
bFlag := (acceptValue - inputValue) >= m_nValue;
if bFlag then
begin
{$region '结果匹配,记录状态为匹配中'}
//上次状态为未匹配则记录记录第一次接受及匹配中的值
if (State = vscUnMatch)then
begin
m_pAcceptData := RecRow;
m_pFitData := RecRow;
end;
//上一次状态为接受则记录第一次匹配中的值
if (State = vscAccept) then
begin
m_pFitData := RecRow;
end;
Result := vscMatching;
{$endregion '结果匹配,记录状态为匹配中'}
end
else
begin
{$region '结果不匹配,记录状态为接受中'}
if State = vscUnMatch then
begin
m_pAcceptData := RecRow;
end;
Result := vscAccept;
{$endregion '结果不匹配,记录状态为接受中'}
end;
{$endregion '当接受到下降趋势的值'}
end
else begin
{$region '当接受到上升趋势的值'}
if State = vscMatching then
begin
Result := vscMatched;
end
else
Result := vscUnMatch;
{$endregion '当接受到上升趋势的值'}
end;
end;
{$endregion '需要下降趋势判断'}
end;
end;
State := Result;
inherited Match(RecHead,RecRow,RewList);
end;
{ TVSCombExpression }
{$endregion 'TVSOffsetExpression 实现'}
{$region 'TVSCompBehindExpression 实现'}
{ TVSCompBehindExpression }
function TVSCompBehindExpression.Match(RecHead: RLKJRTFileHeadInfo;RecRow:TLKJRuntimeFileRec;RewList:TList): TVSCState;
var
frontValue : Variant; //前面的值
behindValue : Variant; //后面的值
bFlag : boolean; //比对结果
begin
frontValue := 0;
behindValue := 0;
if (m_CompDataType=vsdtAccept) then
begin
{$region '比对接受的值'}
frontValue := GetRecValue(Key,recHead,TLKJRuntimeFileRec(m_FrontExp.m_pAcceptData));
behindValue := GetRecValue(Key,recHead,TLKJRuntimeFileRec(m_BehindExp.m_pAcceptData));
{$endregion '比对接受的值'}
end;
if (m_CompDataType=vsdtMatcing) then
begin
if (m_FrontExp.GetData = nil) or (m_BehindExp.GetData = nil) then
begin
Result := vscUnMatch;
State := Result;
inherited Match(RecHead,RecRow,RewList);
exit;
end;
{$region '比对匹配的值'}
frontValue := GetRecValue(Key,recHead,TLKJRuntimeFileRec(m_FrontExp.GetData));
behindValue := GetRecValue(Key,recHead,TLKJRuntimeFileRec(m_BehindExp.GetData));
{$endregion '比对匹配的值'}
end;
if (m_CompDataType=vsdtLast) then
begin
{$region '比对上一个的值'}
frontValue := GetRecValue(Key,recHead,TLKJRuntimeFileRec(m_FrontExp.LastData));
behindValue := GetRecValue(Key,recHead,TLKJRuntimeFileRec(m_BehindExp.LastData));
{$endregion '比对上一个的值'}
end;
bFlag := false;
case m_OperatorSignal of
{$region '比对结果,采用绝对值差值比较'}
vspMore : bFlag := (Abs(behindValue - frontValue) > Value);
vspLess : bFlag := (Abs(frontValue - behindValue) < Value);
vspEqual : bFlag := (behindValue = (frontValue + Value));
vspNoMore: bFlag := (Abs(frontValue - behindValue) <= Value);
vspNoLess : bFlag := (Abs(frontValue - behindValue) >= Value);
vspNoEqual: bFlag := (behindValue <> (frontValue + Value));
{$endregion '比对结果,采用绝对值差值比较'}
end;
Result := vscUnMatch;
if bFlag then
Result := vscMatched;
State := Result;
inherited Match(RecHead,RecRow,RewList);
end;
{ TVSInExpression }
constructor TVSInExpression.Create;
begin
inherited;
m_Value := TStringList.Create;
end;
destructor TVSInExpression.Destroy;
begin
m_Value.Free;
inherited;
end;
function TVSInExpression.Match(RecHead: RLKJRTFileHeadInfo;
RecRow: TLKJRuntimeFileRec; RewList: TList): TVSCState;
var
ValueIndex : Integer;
inputValue : Variant; //当前据说的值
bFlag : boolean;
begin
bFlag := false;
if m_OperatorSignal = tInNotNot then
begin
bFlag := true;
end;
inputValue := GetRecValue(Key,RecHead,RecRow);
ValueIndex := m_Value.IndexOf(string(inputValue));
if ValueIndex <> -1 then
begin
bFlag := True;
if m_OperatorSignal = tInNotNot then
begin
bFlag := false;
end;
end;
////
// for i := 0 to m_Value.Count - 1 do
// begin
// if Value[i] = string(inputValue) then
// begin
// bFlag := true;
// if m_OperatorSignal = tInNotNot then
// begin
// bFlag := false;
// end;
// break;
// end;
// end;
//比对通过
if bFlag then
begin
{$region '比对通过'}
//当前一次状态为不匹配,则将状态置为适合,且记录第一次适合的数据
if (State = vscUnMatch) or (State = vscAccept) then
begin
m_pFitData := RecRow;
end;
//保存最后一个匹配值
if not SaveFirstFit then
m_pFitData := RecRow;
Result := vscMatching;
{$endregion '比对通过'}
end
else begin
{$region '比对不通过'}
//当前一次状态为适合,则将状态置为匹配,否则状态置为不匹配
if State = vscMatching then
Result := vscMatched
else
Result := vscUnMatch;
{$endregion '比对不通过'}
end;
{$endregion '状态判断'}
State := Result;
inherited Match(RecHead,RecRow,RewList);
end;
{ TVSCompExpExpression }
function TVSCompExpExpression.Match(RecHead: RLKJRTFileHeadInfo;
RecRow: TLKJRuntimeFileRec; RewList: TList): TVSCState;
const
SPVAILD =20; //标压的有效范围
var
inputValue : Variant;
transValue : Variant; //管压经过翻译后的值
bFlag : boolean;
begin
Result := vscUnMatch;
bFlag := false;
transValue := Value;
case m_CompDataType of
vsdtAccept:
begin
if m_Expression.AcceptData = nil then
begin
MessageBeep(0);
exit;
end;
inputValue := GetRecValue(Key,RecHead,m_Expression.AcceptData);
end;
vsdtMatcing:
begin
if m_Expression.GetData = nil then
exit;
inputValue := GetRecValue(Key,RecHead, m_Expression.GetData);
end;
vsdtLast:
begin
if m_Expression.LastData = nil then
exit;
inputValue := GetRecValue(Key,RecHead,m_Expression.LastData);
end;
end;
if (Key = CommonRec_Column_GuanYa) and (Value = SYSTEM_STANDARDPRESSURE ) AND (OperatorSignal=vspEqual) then
begin
if inputValue >= GetStandardPressure(RecHead) - SPVAILD then
begin
bFlag := true;
end;
end
else begin
if (Key = CommonRec_Column_GuanYa) and (Value >10000 ) then
begin
{$region '标压比对特殊处理'}
transValue := Value - SYSTEM_STANDARDPRESSURE + GetStandardPressure(RecHead);
{$endregion '翻译标压及标压差值'}
end;
{$region '比对输入值与标准值'}
case OperatorSignal of
vspMore: //大于
begin
if inputValue > transValue then
bFlag := true;
end;
vspLess:
begin
if inputValue < transValue then
bFlag := true;
end;
vspEqual:
begin
if inputValue = transValue then
bFlag := true;
end;
vspNoMore:
begin
if inputValue <= transValue then
bFlag := true;
end;
vspNoLess:
begin
if inputValue >= transValue then
bFlag := true;
end;
vspNoEqual:
begin
if inputValue <> transValue then
bFlag := true;
end;
end;
{$endregion '比对输入值与标准值'}
end;
if bFlag then
begin
Result := vscMatched;
FitData := nil;
case m_CompDataType of
vsdtAccept:
begin
FitData := m_Expression.AcceptData;
end;
vsdtMatcing:
begin
FitData := m_Expression.FitData;
end;
vsdtLast:
begin
FitData := m_Expression.LastData;
end;
end;
end;
State := Result;
inherited Match(RecHead,RecRow,RewList);
end;
{ TVSSimpleIntervalExpression }
constructor TVSSimpleIntervalExpression.create;
begin
inherited;
m_StartKey := -1;
m_EndKey := -1;
m_IsScaned := False;
m_StartPos := -1;
m_EndPos := -1;
end;
destructor TVSSimpleIntervalExpression.Destroy;
begin
if m_Expression <> nil then
FreeAndNil(m_Expression);
inherited;
end;
function TVSSimpleIntervalExpression.GetData: Pointer;
begin
result := nil;
if m_Expression <> nil then
Result := m_Expression.GetData;
end;
procedure TVSSimpleIntervalExpression.Init;
begin
inherited;
m_IsScaned := False;
m_StartPos := -1;
m_EndPos := -1;
m_Expression.Init;
end;
function TVSSimpleIntervalExpression.Match(RecHead: RLKJRTFileHeadInfo;
RecRow: TLKJRuntimeFileRec; RewList: TList): TVSCState;
var
i : Integer;
RecIndex : Integer;
rec : TLKJCommonRec;
begin
Result := vscUnMatch;
RecIndex := RewList.IndexOf(RecRow);
if m_IsScaned then
begin
if (m_StartPos = -1) then
Exit;
if (RecIndex > m_StartPos) and (RecIndex < m_EndPos) then
Result := m_Expression.Match(RecHead,RecRow,RewList);
Exit;
end;
m_IsScaned := True;
for i := 0 to RewList.Count - 1 do
begin
rec := TLKJCommonRec(RewList[i]);
if m_StartValue = GetRecValue(StartKey,RecHead,rec) then
begin
m_StartPos := i;
Break;
end;
end;
for i := 0 to RewList.Count - 1 do
begin
rec := TLKJCommonRec(RewList[i]);
if i = RewList.Count - 1 then
m_EndPos := i
else
if m_EndPos = GetRecValue(EndKey,RecHead,rec) then
begin
m_EndPos := i;
Break;
end;
end;
if (m_StartPos = -1) then
Exit;
if (RecIndex > m_StartPos) and (RecIndex < m_EndPos) then
Result := m_Expression.Match(RecHead,RecRow,RewList);
end;
procedure TVSSimpleIntervalExpression.Reset;
begin
inherited;
m_Expression.Reset;
end;
{ TVSConditionTimesExpression }
constructor TVSConditionTimesExpression.Create;
begin
inherited;
m_Times := 0;
end;
destructor TVSConditionTimesExpression.Destroy;
begin
if m_Expression <> nil then
FreeAndNil(m_Expression);
inherited;
end;
function TVSConditionTimesExpression.GetData: Pointer;
begin
Result := m_Expression.GetData;
end;
procedure TVSConditionTimesExpression.Init;
begin
inherited;
m_Times := 0;
m_Expression.Init();
end;
function TVSConditionTimesExpression.Match(RecHead: RLKJRTFileHeadInfo;
RecRow: TLKJRuntimeFileRec; RewList: TList): TVSCState;
var
Rtl : TVSCState;
bFlag : Boolean;
begin
try
Result := vscUnMatch;
if LastState = vscMatched then
m_Expression.Reset;
Rtl := m_Expression.Match(RecHead,RecRow,RewList);
if Rtl = vscMatched then
begin
Inc(m_Times);
end;
bFlag := False;
case m_OperatorSignal of
vspMore:
begin
if m_Times > m_InputTimes then
bFlag := True;
end;
vspLess:
begin
if m_Times < m_InputTimes then
bFlag := True;
end;
vspEqual:
begin
if m_Times = m_InputTimes then
bFlag := True;
end;
vspNoMore:
begin
if m_Times <= m_InputTimes then
bFlag := True;
end;
vspNoLess:
begin
if m_Times >= m_InputTimes then
bFlag := True;
end;
vspNoEqual:
begin
if m_Times <> m_InputTimes then
bFlag := True;
end;
end;
if bFlag then
begin
State := vscMatching;
Result := State;
Exit;
end
else
begin
if State = vscMatching then
begin
Result := vscMatched;
State := Result;
end;
end;
finally
LastState := State;
inherited Match(RecHead,RecRow,RewList);
end;
end;
procedure TVSConditionTimesExpression.Reset;
begin
inherited;
m_Times := 0;
m_Expression.Reset;
end;
{ TVSSimpleConditionExpression }
constructor TVSSimpleConditionExpression.Create;
begin
inherited;
m_ConditionIsTrue := False;
end;
destructor TVSSimpleConditionExpression.Destroy;
begin
if m_Expression <> nil then
FreeAndNil(m_Expression);
inherited;
end;
function TVSSimpleConditionExpression.GetData: Pointer;
begin
Result := m_Expression.GetData;
end;
procedure TVSSimpleConditionExpression.Init;
begin
inherited;
m_ConditionIsTrue := False;
m_Expression.Init();
end;
function TVSSimpleConditionExpression.Match(RecHead: RLKJRTFileHeadInfo;
RecRow: TLKJRuntimeFileRec; RewList: TList): TVSCState;
var
Rlt : TVSCState;
begin
Result := vscUnMatch;
if m_ConditionIsTrue then
begin
Result := vscMatched;
Exit;
end;
Rlt := m_Expression.Match(RecHead,RecRow,RewList);
Self.State := m_Expression.State;
if Rlt = vscMatched then
begin
m_ConditionIsTrue := True;
Result := vscMatched;
end;
end;
procedure TVSSimpleConditionExpression.Reset;
begin
inherited;
m_ConditionIsTrue := False;
m_Expression.Reset;
end;
{ TVSOffsetExExpression }
constructor TVSOffsetExExpression.Create;
begin
inherited;
m_bIncludeEqual := true;
m_breakLimit := 0;
end;
function TVSOffsetExExpression.Match(RecHead: RLKJRTFileHeadInfo;
RecRow: TLKJRuntimeFileRec; RewList: TList): TVSCState;
var
inputValue : Variant; //输入值
lastValue : Variant; //上一个值
acceptValue : Variant; //接收的值
bFlag : boolean; //比对结果
begin
Result := vscUnMatch;
//获取输入值
inputValue := GetRecValue(Key,RecHead,RecRow);
//获取上一个值
if (m_pLastData <> nil) then
begin
lastValue := GetRecValue(Key,RecHead,TLKJRuntimeFileRec(m_pLastData));
end;
//如果数据跳变超过上限,则复位
if m_breakLimit <> 0 then
begin
if Abs(inputValue - lastValue) > m_breakLimit then
begin
Reset();
Exit;
end;
end;
case order of
vsoArc:
begin
{$region '需要上升趋势判断'}
//第一次记录直接置为接收且保存第一次接收状态的数据
if (m_pLastData = nil) or (m_pAcceptData = nil) then
begin
if m_pLastData = nil then
m_pLastData := RecRow;
if m_pAcceptData = nil then
m_pAcceptData := RecRow;
Result := vscAccept;
end
else begin
//获取第一次接受的值
acceptValue := GetRecValue(Key,RecHead,TLKJRuntimeFileRec(m_pAcceptData));
if inputValue >= lastValue then
begin
{$region '当接收到上升趋势的数据时'}
//判断是否上升了指定的值
bFlag := (inputValue - acceptValue) > m_nValue;
if (m_bIncludeEqual) then
bFlag := (inputValue - acceptValue) >= m_nValue;
if bFlag then
begin
{$region '结果匹配,记录状态为匹配中'}
//上一次为未匹配则本次为接受状态,且记录第一次接受和匹配的值
if State = vscUnMatch then
begin
m_pAcceptData := RecRow;
m_pFitData := RecRow;
end;
//上一次为接受则本次仍为接受状态,且记录第一次匹配的值
if (State = vscAccept) then
begin
m_pFitData := RecRow;
end;
Result := vscMatching;
{$endregion '结果匹配,记录状态为匹配中'}
end
else begin
{$region '结果不匹,记录状态为接收'}
if State = vscUnMatch then
begin
m_pAcceptData := RecRow;
end;
Result := vscAccept;
{$endregion '结果不匹,记录状态为接收'}
end;
{$endregion '当接收到上升趋势的数据时'}
end
else begin
{$region '当接收到下降趋势的数据时'}
bFlag := (acceptValue - lastValue) < m_nMaxValue;
if bFlag then
begin
if State = vscMatching then
begin
Result := vscMatched;
end
else
Result := vscUnMatch;
end
else
begin
Result := vscUnMatch;
end;
{$endregion '当接收到下降趋势的数据时'}
end;
end;
{$endregion '需要上升趋势判断'}
end;
vsoDesc:
begin
{$region '需要下降趋势判断'}
//第一次记录直接置为接收且保存第一次接收状态的数据
if (m_pLastData = nil) or (m_pAcceptData = nil) then
begin
if m_pLastData = nil then
m_pLastData := RecRow;
if m_pAcceptData = nil then
m_pAcceptData := RecRow;
Result := vscAccept;
end
else begin
//获取接受状态的值
acceptValue := GetRecValue(Key,RecHead,TLKJRuntimeFileRec(m_pAcceptData));
if inputValue <= lastValue then
begin
{$region '当接受到下降趋势的值'}
bFlag := (acceptValue - inputValue) > m_nValue;
if (m_bIncludeEqual) then
bFlag := (acceptValue - inputValue) >= m_nValue;
if bFlag then
begin
{$region '结果匹配,记录状态为匹配中'}
//上次状态为未匹配则记录记录第一次接受及匹配中的值
if (State = vscUnMatch)then
begin
m_pAcceptData := RecRow;
m_pFitData := RecRow;
end;
//上一次状态为接受则记录第一次匹配中的值
if (State = vscAccept) then
begin
m_pFitData := RecRow;
end;
Result := vscMatching;
{$endregion '结果匹配,记录状态为匹配中'}
end
else
begin
{$region '结果不匹配,记录状态为接受中'}
if State = vscUnMatch then
begin
m_pAcceptData := RecRow;
end;
Result := vscAccept;
{$endregion '结果不匹配,记录状态为接受中'}
end;
{$endregion '当接受到下降趋势的值'}
end
else begin
{$region '当接受到上升趋势的值'}
bFlag := (lastValue - acceptValue) < m_nMaxValue;
if bFlag then
begin
if State = vscMatching then
begin
Result := vscMatched;
end
else
Result := vscUnMatch;
end
else
begin
Result := vscUnMatch;
end;
{$endregion '当接受到上升趋势的值'}
end;
end;
{$endregion '需要下降趋势判断'}
end;
end;
State := Result;
inherited Match(RecHead,RecRow,RewList);
end;
end.
|
unit VSoft.AntPatterns2;
interface
uses
Generics.Collections,
VSoft.AntPatterns;
type
TTestRec = record
path : string;
isDir : boolean;
constructor Create(const APath : string; const AIsDir : boolean);
end;
TAntPattern2 = class(TAntPattern)
private
FFiles : TList<TTestRec>;
protected
// walk a 'virtual' file system.. not ideal as we're not really testing the walk function
// but creating a virtual file system is just too much work for this simple lib!
procedure Walk(const path: string; const walker: TWalkerFunc); override;
public
constructor Create(const rootDirectory : string; const files : TList<TTestRec>);
end;
implementation
uses
System.SysUtils;
{ TAntPattern }
constructor TAntPattern2.Create(const rootDirectory: string; const files: TList<TTestRec>);
begin
inherited Create(rootDirectory);
FFiles := files;;
end;
procedure TAntPattern2.Walk(const path: string; const walker: TWalkerFunc);
var
skipWhileDir : string;
fileRec : TTestRec;
begin
skipWhileDir := '';
for fileRec in FFiles do
begin
if skipWhileDir <> '' then
begin
if (not fileRec.isDir) and SameText(skipWhileDir, ExtractFilePath(fileRec.path)) then
continue;
skipWhileDir := '';
end;
if walker(fileRec.path, fileRec.isDir) then
skipWhileDir := ExtractFilePath(fileRec.path);
end;
end;
{ TTestRec }
constructor TTestRec.Create(const APath: string; const AIsDir: boolean);
begin
path := APath;
isDir := AIsDir;
end;
end.
|
{*******************************************************}
{ }
{ Tachyon Unit }
{ Vector Raster Geographic Information Synthesis }
{ VOICE .. Tracer }
{ GRIP ICE .. Tongs }
{ Digital Terrain Mapping }
{ Image Locatable Holographics }
{ SOS MAP }
{ Surreal Object Synthesis Multimedia Analysis Product }
{ Fractal3D Life MOW }
{ Copyright (c) 1995,2006 Ivan Lee Herring }
{ }
{*******************************************************}
unit nLifeMain;
{renamed neuralife 26mar01
59417
733772
17557
933376
16618 60857
241028 748528
3061 17633
546816 1110016
}
(*MATFA BOIDS
ufrmBoids in 'ufrmBoids.pas' {frmBoids},
uBoids in 'uBoids.pas',
uBoidEngine in 'uBoidEngine.pas',
ufrmAbout in 'ufrmAbout.pas' {frmAbout},
StrFunctions in 'StrFunctions.pas',
uTMovable in 'uTMovable.pas',
uTMovableEngine in 'uTMovableEngine.pas',
ufrmSettings in 'ufrmSettings.pas' {frmSettings};
TV,{:Array3924;}
TV7848,{:Array7848;}
TV15696,{:Array15696;
SetLength(Aa,156,96);
SetLength(Image,156,96);
SetLength(Image78,78,48);
SetLength(TV15696,156,96);
ImageByte:Byte;
FOR I := 0 TO 155 DO FOR J := 0 TO 95 DO
begin
read( fil, ImageByte );
Image[I,J]:=ImageByte;
end;
FOR I := 0 TO 155 DO FOR J := 0 TO 95 DO
begin
ImageByte:=Image[I,J];
write( fil, ImageByte );
end; } *)
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Buttons,
Vcl.ExtCtrls, Vcl.Menus, Vcl.StdCtrls;
type
TLifeMainForm = class(TForm)
ButtonPanel: TPanel;
LifeBtn: TSpeedButton;
GRFBtn: TSpeedButton;
TermitesBtn: TSpeedButton;
Birds: TSpeedButton;
HelpBtn: TSpeedButton;
AboutBtn: TSpeedButton;
AntsBtn: TSpeedButton;
LifeHints: TPanel;
Fish: TSpeedButton;
LifeEditorBtn: TSpeedButton;
LifeColorChoiceBtn: TSpeedButton;
TorsoBtn: TSpeedButton;
MainMenu1: TMainMenu;
Life1: TMenuItem;
Edit1: TMenuItem;
Colors1: TMenuItem;
GRF1: TMenuItem;
Term1: TMenuItem;
Antz1: TMenuItem;
Bird1: TMenuItem;
Fish1: TMenuItem;
Bod1: TMenuItem;
Help1: TMenuItem;
About1: TMenuItem;
ExitBtn: TSpeedButton;
Tools1: TMenuItem;
ToolsBtn: TSpeedButton;
procedure DisplaySplashScreen;
procedure FormCreate(Sender: TObject);
procedure ShowHint(Sender: TObject);
procedure LifeBtnClick(Sender: TObject);
procedure GRFBtnClick(Sender: TObject);
procedure TermitesBtnClick(Sender: TObject);
procedure AntsBtnClick(Sender: TObject);
procedure BirdsClick(Sender: TObject);
procedure HelpBtnClick(Sender: TObject);
procedure AboutBtnClick(Sender: TObject);
procedure LifeEditorBtnClick(Sender: TObject);
procedure LifeColorChoiceBtnClick(Sender: TObject);
procedure TorsoBtnClick(Sender: TObject);
procedure ExitBtnClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure ToolsBtnClick(Sender: TObject);
procedure Bod1Click(Sender: TObject);
procedure Tools1Click(Sender: TObject);
procedure Bird1Click(Sender: TObject);
procedure FishClick(Sender: TObject);
procedure Fish1Click(Sender: TObject);
procedure GRF1Click(Sender: TObject);
procedure Antz1Click(Sender: TObject);
procedure Term1Click(Sender: TObject);
procedure Life1Click(Sender: TObject);
private
public
end;
var
LifeMainForm: TLifeMainForm;
implementation
uses
nUGlobal,
AllSplash, {Life Main 0 } {SystemInfoForm 13000.... }
GlsAbout,{AboutBoids 222 }
ncLife,{1000} nColors,{3000} nEditor,{4000} nEP,{4500}
nlife3d,{ 1800} nLifeFiles,{2001}{aUniversesForm 1856 }
nGRF,{5000} nGSRShow,
nTermite,{ 6000 }
nAntsFarm,{ 7000}
nTorso,{ 9000 }
{nDolphin,}
GlsUvMapFrm,
GlsTreeFrm, { 9900 }
GlsBirdFrm, {8000, but uses its own help file}
{AAADemoForm 8050 }
nUBirdDX,{ 8000 also } GlsFrenzy{ 8100 };
{$R *.DFM}
procedure TLifeMainForm.DisplaySplashScreen;
begin
SplashScreen := TSplashScreen.Create(Application);
SplashScreen.SplashSet(5,2000);
SplashScreen.Show;
SplashScreen.Refresh;
end;
procedure TLifeMainForm.FormCreate(Sender: TObject);
begin {Menu}
/// DisplaySplashScreen;
{LOAD FRACTALS.F3D and SET these}
{ if FileExists(ExtractFilePath(ParamStr(0)) + 'nlife.pof') then
begin
DoLoader;
LifeHints.Caption := HiddenString;
end else
}
begin
nLifeDir := ExtractFilePath(ParamStr(0));
ProLoaded := ExtractFilePath(ParamStr(0));
Desolate := clSilver;
Growing := clYellow;
Full := clGreen;
Overpopulated := clRed;
HiddenString := 'Life Copyright, 2003: Ivan Lee Herring';
StartedNameNumber := 'Not Registered'; {F3197432-460875}
Started := Now;
Colorreg := 3;
NumberEditStored:=427;
MaxRandomCellsEditStored:=1000;
LifeMainFormX := 10;
life3dFormX:=123;
life3dFormY:=123;
aUniversesFormX:=123;
aUniversesFormY:=123;
LifeFormX := 123;
EPFormX := 123;
ColorsFormX := 123;
EditorFormX := 123;
AboutFormX := 123;
GRFFormX := 123;
TermiteFormX := 123;
AntsFarmX := 123;
BirdsFormX := 123;
DXTorsoFormX := 123;
NewRulesFormX := 123;
FamilyFormY := 123;
LifeFilesFormX := 123;
GSRShowFormX := 123;
BirdDXFormX := 123;
FrenzyFormY := 123;
frmBoidsY := 123;
frmBoidsX := 123;
SystemInfoFormX := 123;
MessageX := 123;
MessageY := 123;
SystemInfoFormY := 123;
FrenzyFormX := 123;
BirdDXFormY := 123;
GSRShowFormY := 123;
LifeFilesFormY := 123;
FamilyFormX := 123;
LifeMainFormY := 10;
LifeFormY := 123;
EPFormY := 123;
ColorsFormY := 123;
EditorFormY := 123;
AboutFormY := 123;
GRFFormY := 123;
TermiteFormY := 123;
AntsFarmY := 123;
BirdsFormY := 123;
DXTorsoFormY := 123;
NewRulesFormY := 123;
{ DisplayButtonsOn:=True;
DisplayBoth:=True;}
GetPreferences;
/// DoSaver;
end;
top := LifeMainFormY;
left := LifeMainFormX;
BirdLifeDir := ExtractFilePath(ParamStr(0));
{ Height:= 88;
Width:= 400; }
ReallyGone := False;
{ FrenzyFilesLoaded := False; }
Application.OnHint := ShowHint;
Application.HelpFile := ExtractFilePath(ParamStr(0)) + 'Nlife.hlp';
HasTrueColors := myLoadImage;
{If (Not myLoadImage) then Application.Terminate;}
SetLength(Universal,2,26);
end;
procedure TLifeMainForm.FormShow(Sender: TObject);
begin
Application.OnHint := LifeMainForm.ShowHint;
end;
procedure TLifeMainForm.ShowHint(Sender: TObject);
begin
LifeHints.Caption := Application.Hint;
end;
procedure TLifeMainForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
{ If ColorFormInitialized then DColorForm.Scene.free;}
{Get the X,Y locations}
LifeMainFormY := LifeMainForm.top;
LifeMainFormX := LifeMainForm.left;
bIamDone := True;
RabbitsRunning := False;
BirdLandDX := True;
OrthoClor := True;
AntiOrtho := True;
ReallyGone := True;
Application.ProcessMessages;
Application.ProcessMessages;
AAABirdForm.ReallyClose;
BirdDXForm.ReallyClose;
FrenzyForm.ReallyClose; {BirdsForm.ReallyClose;}{frmBoids.ReallyClose; }
GSRShowForm.ReallyClose;
GRFForm.ReallyClose;
LifeForm.ReallyClose;
ColorsForm.ReallyClose;
EditorPlacer.ReallyClose;
EditorForm.ReallyClose; {NewRulesForm.ReallyClose;}
LifeFilesForm.ReallyClose;{AboutLife.ReallyClose;}
{TermiteMoundForm.ReallyClose;}
TermitesForm.ReallyClose;
{AntMoundForm.ReallyClose; }
AntsForm.ReallyClose;
{DXPDXTorsoFormYForm.ReallyClose;}
DoSaver;
Application.ProcessMessages;
Application.ProcessMessages;
Action := caFree;
{CanClose:=True;}
end;
procedure TLifeMainForm.ExitBtnClick(Sender: TObject);
begin
bIamDone := True;
Application.ProcessMessages;
RabbitsRunning := False;
Application.ProcessMessages;
BirdLandDX := True;
Application.ProcessMessages;
OrthoClor := True;
Application.ProcessMessages;
AntiOrtho := True;
Application.ProcessMessages;
Close;
end;
procedure TLifeMainForm.LifeBtnClick(Sender: TObject);
begin
alife3dForm.Show;{1800}
end;
procedure TLifeMainForm.Life1Click(Sender: TObject);
begin
LifeForm.Show;{1000}
end;
procedure TLifeMainForm.LifeEditorBtnClick(Sender: TObject);
begin
EditorForm.Show;
end;
procedure TLifeMainForm.LifeColorChoiceBtnClick(Sender: TObject);
begin
ColorsForm.Show;{2 and 3 D}
end;
procedure TLifeMainForm.TermitesBtnClick(Sender: TObject);
begin
TermitesForm.Show; {3 D not done}
end;
procedure TLifeMainForm.Term1Click(Sender: TObject);
begin
TermitesForm.Show;
end;
procedure TLifeMainForm.AntsBtnClick(Sender: TObject);
begin
AntsForm.Show; {3 D not done}
end;
procedure TLifeMainForm.Antz1Click(Sender: TObject);
begin
AntsForm.Show;
end;
procedure TLifeMainForm.GRFBtnClick(Sender: TObject);
begin
GRFForm.Show; //3 D not done
end;
procedure TLifeMainForm.GRF1Click(Sender: TObject);
begin
GRFForm.Show;
end;
procedure TLifeMainForm.BirdsClick(Sender: TObject);
begin
AAABirdForm.Show;{8000 in its own help file}
end;
procedure TLifeMainForm.Bird1Click(Sender: TObject);
begin //old ~2D birds 8000
BirdDXForm.Show;
end;
procedure TLifeMainForm.FishClick(Sender: TObject);
begin
//Fish 3d 16000 Tropical Fish tank
end;
procedure TLifeMainForm.Fish1Click(Sender: TObject);
begin
//2d Fish herring / Dolphins / Whales 15000
end;
procedure TLifeMainForm.TorsoBtnClick(Sender: TObject);
begin
DXTorsoForm.Show; //3d PP Mazed Mobiles 10000
end;
procedure TLifeMainForm.Bod1Click(Sender: TObject);
begin
DXTorsoForm.Show; //3d PP Torso... 9000
end;
procedure TLifeMainForm.ToolsBtnClick(Sender: TObject);
begin
GLS3dUvForm.Show; // Tools 3D Editor / Texture Painter Help 14000
end;
procedure TLifeMainForm.Tools1Click(Sender: TObject);
begin
ATreeForm.Show; //9900 Trees for Birds
end;
procedure TLifeMainForm.HelpBtnClick(Sender: TObject);
begin
Application.HelpContext(0);
end;
procedure TLifeMainForm.AboutBtnClick(Sender: TObject);
begin
AboutBoids.Show;
end;
end.
|
unit mainclass;
{$mode objfpc}{$H+}
interface
uses
Sysutils;
CONST
PWLOWERCASESTRINGS: String = 'abcdefghijklmnopqrstuvwxyz';
PWUPPERCASESTRINGS: String = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
PWNUMBERS: String = '0123456789';
PWSPECIAL = '$@&#!+%.,;-=';
PROJECTNAME = 'Advanced Password Generator V1.1.4';
PROJECTURL = 'https://sourceforge.net/projects/apwg/';
WIKIURL = 'https://sourceforge.net/p/apwg/wiki/Home/';
COPYRIGHT = 'Copyright (c) 2014 by Viktor Tassi';
type
TApwGen = record
MinSize : Integer;// = 8;
MaxSize : Integer;// = 8;
LowerCases : Boolean;// = True;
UpperCases : Boolean;// = True;
Numbers : Boolean;// = False;
Specials : Boolean;
AllUnique : Boolean;// = True;
CustomChars : String;// = '';
end;
function GeneratePWD(var Apwgen:TApwGen):String;
procedure ReRandomize;
var
ApwGen: TApwGen =( Minsize:8;
MaxSize:8;
LowerCases:True;
UpperCases:True;
Numbers:True;
Specials:False;
AllUnique:True;
CustomChars:''
);
implementation
{ TApwGen }
function GeneratePWD(var Apwgen:TApwGen): String;
var
chars, tmp : String;
i, j, k, pwlen : Integer;
c: char;
begin
result := '';
chars :='';
if Apwgen.Minsize < 0 then
Apwgen.MinSize:=0;
if Apwgen.MaxSize < Apwgen.MinSize then
Apwgen.MaxSize:= Apwgen.MinSize;
if Apwgen.MinSize <1 then exit;
if Apwgen.LowerCases then
chars:=chars+PWLOWERCASESTRINGS;
if Apwgen.UpperCases then
chars:=chars+PWUPPERCASESTRINGS;
if Apwgen.Numbers then
chars:=chars+PWNUMBERS;
if Apwgen.Specials then
chars:=chars+PWSPECIAL;
if Apwgen.CustomChars <> '' then
chars := chars+Apwgen.CustomChars;
if chars = '' then exit;
//Dedup
tmp := chars;
chars := '';
for i := 1 to length(tmp) do
if ansipos(tmp[i],chars) = 0 then
chars:= chars+tmp[i];
ReRandomize;
//Shuffle
if length(chars)>2 then
for k:=3 to random(4096)+1 do;
for i := length(chars) downto 2 do
begin
c:= chars[i];
j:= Succ(Random(length(chars)));
chars[i] := chars[j];
chars[j] := c;
end;
if Apwgen.MinSize <> Apwgen.MaxSize then
pwlen := random(Apwgen.MaxSize - Apwgen.MinSize) + Apwgen.MinSize
else
pwlen := Apwgen.MinSize;
for i := 1 to pwlen do begin
ReRandomize;
tmp := chars[random(length(chars))+1];
if Apwgen.AllUnique then
if ansipos(tmp,result) > 0 then
for j := 1 to length(chars) do begin
tmp := chars[random(length(chars))+1];
if ansipos(tmp,result) = 0 then break;
end;
result := result + tmp;
end;
end;
procedure ReRandomize;
var
g:TGuid;
begin
CreateGUID(g);
RandSeed:= RandSeed XOR g.clock_seq_low XOR g.Data1 XOR g.Data2;
end;
end.
|
{
Copyright (c) 2020 Adrian Siekierka
Based on a reconstruction of code from ZZT,
Copyright 1991 Epic MegaGames, used with permission.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
}
unit Sounds;
interface
type
TDrumData = record
Len: integer;
Data: array[1 .. 15] of word;
end;
var
SoundEnabled: boolean;
SoundBlockQueueing: boolean;
SoundCurrentPriority: integer;
SoundDurationMultiplier: byte;
SoundDurationCounter: byte;
SoundBuffer: string;
SoundNewVector: pointer;
SoundOldVector: pointer;
SoundBufferPos: integer;
SoundIsPlaying: boolean;
TimerTicks: word;
{$IFDEF ZETAEMU}
ZetaDetected: boolean;
{$ENDIF}
procedure AccurateDelayCalibrate;
procedure AccurateDelay(ms: word);
procedure SoundQueue(priority: integer; pattern: string);
procedure SoundClearQueue;
function SoundHasTimeElapsed(var counter: integer; duration: integer): boolean;
procedure SoundUninstall;
function SoundParse(input: string): string;
implementation
uses
{$IFDEF ZETAEMU}
ZetaSupp,
{$ENDIF}
Crt, Dos;
const
DELAY_LOOP_MAX_ITERATIONS = $7FFFFFFF;
SoundParseNoteTable: array['A' .. 'G'] of byte = (9, 11, 0, 2, 4, 5, 7);
{$I SNDFREQ.INC}
{$IFNDEF FPC}
var
DelayLoopIterations: longint;
function AccurateDelayLoop(iterations: longint; var monitor: word): longint;
begin
inline(
$8B/$BE/monitor/ { MOV DI, SS:[monitor] }
$8B/$86/monitor+2/ { MOV AX, SS:[monitor+2] }
$8E/$C0/ { MOV ES, AX }
$8B/$86/iterations/ { MOV AX, SS:[iterations] }
$8B/$96/iterations+2/ { MOV DX, SS:[iterations+2] }
$8B/$1D/ { MOV BX, [ES:DI] }
{ loop: }
$90/$90/ { NOP x 2 }
$83/$E8/$01/ { SUB AX, 1 }
$83/$DA/$00/ { SBB DX, 0 }
$72/$04/ { JC done }
$3B/$1D/ { CMP BX, [ES:DI] }
$74/$F2/ { JE loop }
{ done: }
$89/$86/AccurateDelayLoop/ { MOV AX, SS:[AccurateDelayLoop] }
$89/$96/AccurateDelayLoop+2 { MOV DX, SS:[AccurateDelayLoop+2] }
);
end;
procedure AccurateDelayCalibrate;
var
iterations: longint;
ticks: word;
begin
ticks := TimerTicks;
repeat until TimerTicks <> ticks;
iterations := AccurateDelayLoop(DELAY_LOOP_MAX_ITERATIONS, TimerTicks);
DelayLoopIterations := (DELAY_LOOP_MAX_ITERATIONS - iterations) div 55;
end;
procedure AccurateDelay(ms: word);
var
iterations: longint;
unchanged: word;
begin
{$IFDEF ZETAEMU}
if ZetaDetected then begin
ZetaDelay(ms);
exit;
end;
{$ENDIF}
iterations := DelayLoopIterations * ms;
if iterations <> 0 then
iterations := AccurateDelayLoop(iterations, unchanged);
end;
{$ELSE}
procedure AccurateDelayCalibrate;
begin
{ I'm not sure if Free Pascal lets you do this, though. }
end;
procedure AccurateDelay(ms: word);
begin
{ Free Pascal contains properly calibrated delay logic. }
{$IFDEF ZETAEMU}
if ZetaDetected then begin
ZetaDelay(ms);
exit;
end;
{$ENDIF}
Delay(ms);
end;
{$ENDIF}
procedure SoundQueue(priority: integer; pattern: string);
begin
if not SoundBlockQueueing and
(not SoundIsPlaying or (((priority >= SoundCurrentPriority) and (SoundCurrentPriority <> -1)) or (priority = -1))) then
begin
if (priority >= 0) or not SoundIsPlaying then begin
SoundCurrentPriority := priority;
SoundBuffer := pattern;
SoundBufferPos := 1;
SoundDurationCounter := 1;
end else begin
SoundBuffer := Copy(SoundBuffer, SoundBufferPos, Length(SoundBuffer) - SoundBufferPos + 1);
SoundBufferPos := 1;
if (Length(SoundBuffer) + Length(pattern)) < 255 then begin
SoundBuffer := SoundBuffer + pattern;
end;
end;
SoundIsPlaying := true;
end;
end;
procedure SoundClearQueue;
begin
SoundBuffer := '';
SoundIsPlaying := false;
NoSound;
end;
procedure SoundPlayDrum(var drum: TDrumData);
var
i: integer;
begin
for i := 1 to drum.Len do begin
Sound(drum.Data[i]);
{$IFDEF ZETAEMU}
if ZetaDetected then Delay(1) else
{$ENDIF}
AccurateDelay(1);
end;
NoSound;
end;
function SoundHasTimeElapsed(var counter: integer; duration: integer): boolean;
var
hSecsDiff: word;
hSecsTotal: integer;
begin
hSecsTotal := (LongInt(TimerTicks) * 11) shr 1;
hSecsDiff := hSecsTotal - counter;
if hSecsDiff >= duration then begin
SoundHasTimeElapsed := true;
counter := hSecsTotal;
end else begin
SoundHasTimeElapsed := false;
end;
end;
procedure SoundTimerHandler;
interrupt;
begin
Inc(TimerTicks);
if not SoundEnabled then begin
SoundIsPlaying := false;
NoSound;
end else if SoundIsPlaying then begin
Dec(SoundDurationCounter);
if SoundDurationCounter <= 0 then begin
NoSound;
if SoundBufferPos >= Length(SoundBuffer) then begin
NoSound;
SoundIsPlaying := false;
end else begin
if (SoundBuffer[SoundBufferPos] >= #16) and (SoundBuffer[SoundBufferPos] < #112) then
Sound(SoundFreqTable[Ord(SoundBuffer[SoundBufferPos])])
else if (SoundBuffer[SoundBufferPos] >= #240) and (SoundBuffer[SoundBufferPos] < #250) then
SoundPlayDrum(SoundDrumTable[Ord(SoundBuffer[SoundBufferPos]) - 240])
else
NoSound;
Inc(SoundBufferPos);
SoundDurationCounter := SoundDurationMultiplier * Ord(SoundBuffer[SoundBufferPos]);
Inc(SoundBufferPos);
end;
end;
end;
end;
procedure SoundUninstall;
begin
SetIntVec($1C, SoundOldVector);
end;
function SoundParse(input: string): string;
var
noteOctave: integer;
noteDuration: integer;
output: string;
noteTone: integer;
inPos: byte;
begin
output := '';
noteOctave := 3;
noteDuration := 1;
inPos := 1;
while inPos <= Length(input) do begin
noteTone := -1;
case UpCase(input[inPos]) of
'T': begin
noteDuration := 1;
Inc(inPos);
end;
'S': begin
noteDuration := 2;
Inc(inPos);
end;
'I': begin
noteDuration := 4;
Inc(inPos);
end;
'Q': begin
noteDuration := 8;
Inc(inPos);
end;
'H': begin
noteDuration := 16;
Inc(inPos);
end;
'W': begin
noteDuration := 32;
Inc(inPos);
end;
'.': begin
noteDuration := (noteDuration * 3) div 2;
Inc(inPos);
end;
'3': begin
noteDuration := noteDuration div 3;
Inc(inPos);
end;
'+': begin
if noteOctave < 6 then
Inc(noteOctave);
Inc(inPos);
end;
'-': begin
if noteOctave > 1 then
Dec(noteOctave);
Inc(inPos);
end;
'A'..'G': begin
noteTone := SoundParseNoteTable[UpCase(input[inPos])];
Inc(inPos);
if inPos <= Length(input) then case UpCase(input[inPos]) of
'!': begin
Dec(noteTone);
Inc(inPos);
end;
'#': begin
Inc(noteTone);
Inc(inPos);
end;
end;
output := output + Chr((noteOctave shl 4) + noteTone) + Chr(noteDuration);
end;
'X': begin
output := output + #0 + Chr(noteDuration);
Inc(inPos);
end;
{$IFNDEF FPC}
'0'..'9': begin
{$ELSE}
{ FPC does not like overlapping case labels. }
'0'..'2','4'..'9': begin
{$ENDIF}
output := output + Chr(Ord(input[inPos]) + $F0 - Ord('0')) + Chr(noteDuration);
Inc(inPos);
end;
else Inc(inPos) end;
end;
SoundParse := output;
end;
begin
TimerTicks := 0;
SoundEnabled := true;
SoundBlockQueueing := false;
SoundClearQueue;
SoundDurationMultiplier := 1;
SoundIsPlaying := false;
TimerTicks := 0;
SoundNewVector := @SoundTimerHandler;
GetIntVec($1C, SoundOldVector);
SetIntVec($1C, SoundNewVector);
{$IFNDEF FPC}
DelayLoopIterations := 0;
AccurateDelayCalibrate;
{$ENDIF}
{$IFDEF ZETAEMU}
ZetaDetected := ZetaDetect;
{$ENDIF}
end.
|
unit untEnderecoMDL;
interface
uses
System.Generics.Collections;
type
TEnderecoMDL = class
private
FLogradouro: string;
FBairro: string;
FPrincipal: Boolean;
FCep: string;
FNumero: string;
FMunicipio: string;
FComplemento: string;
FTipo: Integer;
FPais: string;
FEstado: string;
procedure SetBairro(const Value: string);
procedure SetCep(const Value: string);
procedure SetComplemento(const Value: string);
procedure SetEstado(const Value: string);
procedure SetLogradouro(const Value: string);
procedure SetMunicipio(const Value: string);
procedure SetNumero(const Value: string);
procedure SetPais(const Value: string);
procedure SetPrincipal(const Value: Boolean);
procedure SetTipo(const Value: Integer);
public
property Bairro: string read FBairro write SetBairro;
property Cep: string read FCep write SetCep;
property Complemento: string read FComplemento write SetComplemento;
property Estado: string read FEstado write SetEstado;
property Logradouro: string read FLogradouro write SetLogradouro;
property Municipio: string read FMunicipio write SetMunicipio;
property Numero: string read FNumero write SetNumero;
property Pais: string read FPais write SetPais;
property Principal: Boolean read FPrincipal write SetPrincipal;
property Tipo: Integer read FTipo write SetTipo;
end;
implementation
{ TEnderecoMDL }
procedure TEnderecoMDL.SetBairro(const Value: string);
begin
FBairro := Value;
end;
procedure TEnderecoMDL.SetCep(const Value: string);
begin
FCep := Value;
end;
procedure TEnderecoMDL.SetComplemento(const Value: string);
begin
FComplemento := Value;
end;
procedure TEnderecoMDL.SetEstado(const Value: string);
begin
FEstado := Value;
end;
procedure TEnderecoMDL.SetLogradouro(const Value: string);
begin
FLogradouro := Value;
end;
procedure TEnderecoMDL.SetMunicipio(const Value: string);
begin
FMunicipio := Value;
end;
procedure TEnderecoMDL.SetNumero(const Value: string);
begin
FNumero := Value;
end;
procedure TEnderecoMDL.SetPais(const Value: string);
begin
FPais := Value;
end;
procedure TEnderecoMDL.SetPrincipal(const Value: Boolean);
begin
FPrincipal := Value;
end;
procedure TEnderecoMDL.SetTipo(const Value: Integer);
begin
FTipo := Value;
end;
end.
|
unit uInstallCloseRelatedApplications;
interface
{$WARN SYMBOL_PLATFORM OFF}
uses
System.Classes,
System.SysUtils,
Dmitry.Utils.System,
uMemory,
uMemoryEx,
uActions,
uInstallUtils,
uInstallScope;
const
InstallPoints_Related_Apps = 1024 * 1024;
type
TInstallCloseRelatedApplications = class(TInstallAction)
private
function NotifyUserAboutClosingApplication(AppList: TStrings): Boolean;
public
function CalculateTotalPoints: Int64; override;
procedure Execute(Callback: TActionCallback); override;
end;
implementation
uses
uFormBusyApplications;
{ TInstallCloseRelatedApplications }
function TInstallCloseRelatedApplications.CalculateTotalPoints: Int64;
begin
Result := InstallPoints_Related_Apps;
end;
procedure TInstallCloseRelatedApplications.Execute(Callback: TActionCallback);
var
I: Integer;
DiskObject: TDiskObject;
ObjectPath: string;
Dlls, Applications: TStrings;
begin
Dlls := TStringList.Create;
Applications := TStringList.Create;
try
for I := 0 to CurrentInstall.Files.Count - 1 do
begin
DiskObject := CurrentInstall.Files[I];
ObjectPath := ResolveInstallPath(IncludeTrailingBackslash(DiskObject.FinalDestination) + DiskObject.Name);
if AnsiLowerCase(ExtractFileExt(ObjectPath)) = '.dll' then
Dlls.Add(ObjectPath);
end;
FindModuleUsages(Dlls, Applications);
while Applications.Count > 0 do
begin
if not NotifyUserAboutClosingApplication(Applications) then
begin
Terminate;
Break;
end;
FindModuleUsages(Dlls, Applications);
end;
finally
F(Dlls);
F(Applications);
end;
end;
function TInstallCloseRelatedApplications.NotifyUserAboutClosingApplication(
AppList: TStrings): Boolean;
var
ApplicationForm: TFormBusyApplications;
IsApplicationClosed: Boolean;
begin
TThread.Synchronize(nil,
procedure
begin
ApplicationForm := TFormBusyApplications.Create(nil);
try
IsApplicationClosed := ApplicationForm.Execute(AppList);
finally
R(ApplicationForm);
end;
end
);
Result := IsApplicationClosed;
end;
end.
|
unit ParsingForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, ExtCtrls, Menus,
ComparatorFrame, ExtractionFrame,
InflatablesList_Types,
InflatablesList_HTML_ElementFinder,
InflatablesList_ItemShopParsingSettings,
InflatablesList_Manager;
type
TILItemShopParsingEntry = record
Extraction: TILItemShopParsingExtrSettList;
Finder: TILElementFinder;
end;
const
IL_WM_USER_LVITEMSELECTED = WM_USER + 234;
type
TfParsingForm = class(TForm)
gbFinderSettings: TGroupBox;
lblStages: TLabel;
lbStages: TListBox;
lblStageElements: TLabel;
tvStageElements: TTreeView;
lblAttrComps: TLabel;
tvAttrComps: TTreeView;
lblTextComps: TLabel;
tvTextComps: TTreeView;
gbSelectedDetails: TGroupBox;
frmComparatorFrame: TfrmComparatorFrame;
gbExtracSettings: TGroupBox;
lblExtrIdx: TLabel;
btnExtrNext: TButton;
btnExtrPrev: TButton;
btnExtrAdd: TButton;
btnExtrRemove: TButton;
frmExtractionFrame: TfrmExtractionFrame;
pmnStages: TPopupMenu;
mniSG_Add: TMenuItem;
mniSG_Remove: TMenuItem;
pmnElements: TPopupMenu;
mniEL_Add: TMenuItem;
mniEL_Remove: TMenuItem;
pmnAttributes: TPopupMenu;
mniAT_AddComp: TMenuItem;
mniAT_AddGroup: TMenuItem;
mniAT_Remove: TMenuItem;
pmnTexts: TPopupMenu;
mniTX_AddComp: TMenuItem;
mniTX_AddGroup: TMenuItem;
mniTX_Remove: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure lbStagesClick(Sender: TObject);
procedure lbStagesMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure pmnStagesPopup(Sender: TObject);
procedure mniSG_AddClick(Sender: TObject);
procedure mniSG_RemoveClick(Sender: TObject);
procedure tvStageElementsSelect;
procedure tvStageElementsClick(Sender: TObject);
procedure tvStageElementsChange(Sender: TObject; Node: TTreeNode);
procedure tvStageElementsEnter(Sender: TObject);
procedure pmnElementsPopup(Sender: TObject);
procedure mniEL_AddClick(Sender: TObject);
procedure mniEL_RemoveClick(Sender: TObject);
procedure tvAttrCompsSelect;
procedure tvAttrCompsClick(Sender: TObject);
procedure tvAttrCompsChange(Sender: TObject; Node: TTreeNode);
procedure tvAttrCompsEnter(Sender: TObject);
procedure pmnAttributesPopup(Sender: TObject);
procedure mniAT_AddCompClick(Sender: TObject);
procedure mniAT_AddGroupClick(Sender: TObject);
procedure mniAT_RemoveClick(Sender: TObject);
procedure tvTextCompsSelect;
procedure tvTextCompsClick(Sender: TObject);
procedure tvTextCompsChange(Sender: TObject; Node: TTreeNode);
procedure tvTextCompsEnter(Sender: TObject);
procedure pmnTextsPopup(Sender: TObject);
procedure mniTX_AddCompClick(Sender: TObject);
procedure mniTX_AddGroupClick(Sender: TObject);
procedure mniTX_RemoveClick(Sender: TObject);
procedure btnExtrAddClick(Sender: TObject);
procedure btnExtrRemoveClick(Sender: TObject);
procedure btnExtrPrevClick(Sender: TObject);
procedure btnExtrNextClick(Sender: TObject);
private
fILManager: TILManager;
fCurrentParsingEntry: TILItemShopParsingEntry;
fExtractionSettIndex: Integer;
protected
// frame events
procedure FrameChangeHandler(Sender: TObject);
// other methods
procedure FillStageElements(Stage: TILElementFinderStage);
procedure FillAttributes(Attr: TILAttributeComparatorGroup);
procedure FillTexts(Text: TILTextComparatorGroup);
procedure ShowComparator(Comparator: TILComparatorBase);
procedure SetExtractionIndex(NewIndex: Integer);
procedure ShowExtractionIndex;
procedure ListViewItemSelected(var Msg: TMessage); message IL_WM_USER_LVITEMSELECTED;
public
procedure Initialize(ILManager: TILManager);
procedure Finalize;
procedure ShowParsingSettings(const Caption: String; ParsingSettings: TILItemShopParsingSettings; OnPrice: Boolean);
end;
var
fParsingForm: TfParsingForm;
implementation
uses
InflatablesList_Utils;
{$R *.dfm}
const
IL_MSG_PARAM_LIST_IDX_ELEMENTS = 1;
IL_MSG_PARAM_LIST_IDX_ATTRIBUTES = 2;
IL_MSG_PARAM_LIST_IDX_TEXTS = 3;
procedure TfParsingForm.FrameChangeHandler(Sender: TObject);
var
Node: TTreeNode;
begin
// change texts in all nodes...
// texts
Node := tvTextComps.Selected;
while Assigned(Node) do
begin
If TObject(Node.Data) is TILFinderBaseClass then
Node.Text := TILFinderBaseClass(Node.Data).AsString;
Node := Node.Parent;
end;
// attributes
Node := tvAttrComps.Selected;
while Assigned(Node) do
begin
If TObject(Node.Data) is TILFinderBaseClass then
Node.Text := TILFinderBaseClass(Node.Data).AsString;
Node := Node.Parent;
end;
// stage elements
Node := tvStageElements.Selected;
while Assigned(Node) do
begin
If TObject(Node.Data) is TILFinderBaseClass then
Node.Text := TILFinderBaseClass(Node.Data).AsString;
Node := Node.Parent;
end;
// stages
If lbStages.ItemIndex >= 0 then
If lbStages.Items.Objects[lbStages.ItemIndex] is TILFinderBaseClass then
lbStages.Items[lbStages.ItemIndex] := TILFinderBaseClass(
lbStages.Items.Objects[lbStages.ItemIndex]).AsString;
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.FillStageElements(Stage: TILElementFinderStage);
var
i: Integer;
Node: TTreeNode;
begin
tvStageElements.Enabled := Assigned(Stage);
tvStageElements.Items.BeginUpdate;
try
tvStageElements.Items.Clear;
If Assigned(Stage) then
begin
For i := 0 to Pred(Stage.Count) do
begin
Node := tvStageElements.Items.AddChildObject(nil,Stage[i].AsString,Stage[i]);
tvStageElements.Items.AddChildObject(Node,Stage[i].TagName.AsString,Stage[i].TagName);
tvStageElements.Items.AddChildObject(Node,Stage[i].Attributes.AsString,Stage[i].Attributes);
tvStageElements.Items.AddChildObject(Node,Stage[i].Text.AsString,Stage[i].Text);
Node.Expand(True);
end;
If tvStageElements.Items.Count > 0 then
tvStageElements.Select(tvStageElements.Items[0]);
end;
finally
tvStageElements.Items.EndUpdate;
end;
tvStageElements.OnClick(nil);
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.FillAttributes(Attr: TILAttributeComparatorGroup);
var
i: Integer;
procedure FillComparatorLocal(Comparator: TILAttributeComparatorBase; ParentNode: TTreeNode);
var
ii: Integer;
Node: TTreeNode;
begin
If Comparator is TILAttributeComparatorGroup then
begin
Node := tvAttrComps.Items.AddChildObject(ParentNode,Comparator.AsString,Comparator);
For ii := 0 to Pred(TILAttributeComparatorGroup(Comparator).Count) do
FillComparatorLocal(TILAttributeComparatorGroup(Comparator)[ii],Node);
Node.Expand(True);
end
else If Comparator is TILAttributeComparator then
begin
Node := tvAttrComps.Items.AddChildObject(ParentNode,Comparator.AsString,Comparator);
tvAttrComps.Items.AddChildObject(Node,
TILAttributeComparator(Comparator).Name.AsString,TILAttributeComparator(Comparator).Name);
tvAttrComps.Items.AddChildObject(Node,
TILAttributeComparator(Comparator).Value.AsString,TILAttributeComparator(Comparator).Value);
Node.Expand(True);
end;
end;
begin
tvAttrComps.Enabled := Assigned(Attr);
tvAttrComps.Items.BeginUpdate;
try
tvAttrComps.Items.Clear;
If Assigned(Attr) then
begin
tvAttrComps.Color := clWindow;
// recursively go trough the text comparators
For i := 0 to Pred(Attr.Count) do
FillComparatorLocal(Attr[i],nil);
If tvAttrComps.Items.Count > 0 then
tvAttrComps.Select(tvAttrComps.Items[0]);
end
else tvTextComps.Color := $00F8F8F8;
finally
tvAttrComps.Items.EndUpdate;
end;
tvAttrComps.OnClick(nil);
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.FillTexts(Text: TILTextComparatorGroup);
var
i: Integer;
procedure FillComparatorLocal(Comparator: TILTextComparatorBase; ParentNode: TTreeNode);
var
ii: Integer;
Node: TTreeNode;
begin
If Comparator is TILTextComparatorGroup then
begin
Node := tvTextComps.Items.AddChildObject(ParentNode,Comparator.AsString,Comparator);
For ii := 0 to Pred(TILTextComparatorGroup(Comparator).Count) do
FillComparatorLocal(TILTextComparatorGroup(Comparator)[ii],Node);
Node.Expand(True);
end
else If Comparator is TILTextComparator then
begin
tvTextComps.Items.AddChildObject(ParentNode,Comparator.AsString,Comparator);
end;
end;
begin
tvTextComps.Enabled := Assigned(Text);
tvTextComps.Items.BeginUpdate;
try
tvTextComps.Items.Clear;
If Assigned(Text) then
begin
tvTextComps.Color := clWindow;
// recursively go trough the text comparators
For i := 0 to Pred(Text.Count) do
FillComparatorLocal(Text[i],nil);
If tvTextComps.Items.Count > 0 then
tvTextComps.Select(tvTextComps.Items[0]);
end
else tvTextComps.Color := $00F8F8F8;
finally
tvTextComps.Items.EndUpdate;
end;
tvTextComps.OnClick(nil);
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.ShowComparator(Comparator: TILComparatorBase);
begin
If Comparator is TILAttributeComparatorGroup then
begin
// attributes
tvAttrComps.Enabled := True;
tvAttrComps.Color := clWindow;
tvTextComps.Enabled := True;
tvTextComps.Color := clWindow;
FillAttributes(TILAttributeComparatorGroup(Comparator));
end
else If Comparator is TILTextComparatorGroup then
begin
// tag name or text
tvAttrComps.Items.Clear;
tvAttrComps.Enabled := False;
tvAttrComps.Color := $00F8F8F8;
tvTextComps.Enabled := True;
tvTextComps.Color := clWindow;
FillTexts(TILTextComparatorGroup(Comparator));
end
else
begin
// any other (eg. element comparator), clear and disable treeviews
tvAttrComps.Items.Clear;
tvAttrComps.Enabled := False;
tvAttrComps.Color := $00F8F8F8;
tvTextComps.Items.Clear;
tvTextComps.Enabled := False;
tvTextComps.Color := $00F8F8F8;
end;
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.SetExtractionIndex(NewIndex: Integer);
begin
If (NewIndex >= Low(fCurrentParsingEntry.Extraction)) and
(NewIndex <= High(fCurrentParsingEntry.Extraction)) then
begin
fExtractionSettIndex := NewIndex;
frmExtractionFrame.SetExtractSett(Addr(fCurrentParsingEntry.Extraction[fExtractionSettIndex]),True);
ShowExtractionIndex;
end
else
begin
fExtractionSettIndex := -1;
frmExtractionFrame.SetExtractSett(nil,True);
ShowExtractionIndex;
end;
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.ShowExtractionIndex;
begin
If (fExtractionSettIndex >= 0) and (Length(fCurrentParsingEntry.Extraction) > 0) then
lblExtrIdx.Caption := IL_Format('%d/%d',[fExtractionSettIndex + 1,Length(fCurrentParsingEntry.Extraction)])
else
lblExtrIdx.Caption := '-';
btnExtrRemove.Enabled := fExtractionSettIndex >= 0;
btnExtrPrev.Enabled := (fExtractionSettIndex >= 0) and (fExtractionSettIndex > Low(fCurrentParsingEntry.Extraction));
btnExtrNext.Enabled := (fExtractionSettIndex >= 0) and (fExtractionSettIndex < High(fCurrentParsingEntry.Extraction));
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.ListViewItemSelected(var Msg: TMessage);
begin
If Msg.Msg = IL_WM_USER_LVITEMSELECTED then
case Msg.LParam of
IL_MSG_PARAM_LIST_IDX_ELEMENTS: tvStageElementsSelect;
IL_MSG_PARAM_LIST_IDX_ATTRIBUTES: tvAttrCompsSelect;
IL_MSG_PARAM_LIST_IDX_TEXTS: tvTextCompsSelect;
end;
end;
//==============================================================================
procedure TfParsingForm.Initialize(ILManager: TILManager);
begin
fILManager := ILManager;
frmComparatorFrame.Initialize(fIlManager);
frmComparatorFrame.OnChange := FrameChangeHandler;
frmExtractionFrame.Initialize(fIlManager);
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.Finalize;
begin
frmExtractionFrame.Finalize;
frmComparatorFrame.OnChange := nil;
frmComparatorFrame.Finalize;
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.ShowParsingSettings(const Caption: String; ParsingSettings: TILItemShopParsingSettings; OnPrice: Boolean);
var
i: Integer;
begin
Self.Caption := Caption;
If OnPrice then
begin
SetLength(fCurrentParsingEntry.Extraction,ParsingSettings.PriceExtractionSettingsCount);
For i := Low(fCurrentParsingEntry.Extraction) to High(fCurrentParsingEntry.Extraction) do
fCurrentParsingEntry.Extraction[i] := IL_ThreadSafeCopy(ParsingSettings.PriceExtractionSettings[i]);
fCurrentParsingEntry.Finder := ParsingSettings.PriceFinder;
end
else
begin
SetLength(fCurrentParsingEntry.Extraction,ParsingSettings.AvailExtractionSettingsCount);
For i := Low(fCurrentParsingEntry.Extraction) to High(fCurrentParsingEntry.Extraction) do
fCurrentParsingEntry.Extraction[i] := IL_ThreadSafeCopy(ParsingSettings.AvailExtractionSettings[i]);
fCurrentParsingEntry.Finder := ParsingSettings.AvailFinder;
end;
// fill list of stages
lbStages.Items.BeginUpdate;
try
lbStages.Clear;
For i := 0 to Pred(TILElementFinder(fCurrentParsingEntry.Finder).StageCount) do
lbStages.Items.AddObject(fCurrentParsingEntry.Finder.Stages[i].AsString,fCurrentParsingEntry.Finder.Stages[i])
finally
lbStages.Items.EndUpdate;
end;
If lbStages.Count > 0 then
lbStages.ItemIndex := 0;
lbStages.OnClick(nil);
// set extraction frame
fExtractionSettIndex := -1;
If Length(fCurrentParsingEntry.Extraction) > 0 then
SetExtractionIndex(0)
else
SetExtractionIndex(-1);
ShowModal;
// do cleanup
frmComparatorFrame.SetComparator(nil,True);
frmExtractionFrame.SetExtractSett(nil,True);
lbStages.Clear;
tvStageElements.Items.Clear;
tvAttrComps.Items.Clear;
tvTextComps.Items.Clear;
// get results
If OnPrice then
begin
ParsingSettings.PriceExtractionSettingsClear;
For i := Low(fCurrentParsingEntry.Extraction) to High(fCurrentParsingEntry.Extraction) do
begin
ParsingSettings.PriceExtractionSettingsAdd;
ParsingSettings.PriceExtractionSettings[i] := fCurrentParsingEntry.Extraction[i];
end;
end
else
begin
ParsingSettings.AvailExtractionSettingsClear;
For i := Low(fCurrentParsingEntry.Extraction) to High(fCurrentParsingEntry.Extraction) do
begin
ParsingSettings.AvailExtractionSettingsAdd;
ParsingSettings.AvailExtractionSettings[i] := fCurrentParsingEntry.Extraction[i];
end;
end;
end;
//==============================================================================
procedure TfParsingForm.FormCreate(Sender: TObject);
begin
tvStageElements.DoubleBuffered := True;
tvAttrComps.DoubleBuffered := True;
tvTextComps.DoubleBuffered := True;
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.lbStagesClick(Sender: TObject);
begin
If lbStages.ItemIndex >= 0 then
begin
If lbStages.Items.Objects[lbStages.ItemIndex] is TILElementFinderStage then
FillStageElements(TILElementFinderStage(lbStages.Items.Objects[lbStages.ItemIndex]))
else
FillStageElements(nil);
end
else FillStageElements(nil);
frmComparatorFrame.SetComparator(nil,True);
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.lbStagesMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
Index: Integer;
begin
If Button = mbRight then
begin
Index := lbStages.ItemAtPos(Point(X,Y),True);
If Index >= 0 then
begin
lbStages.ItemIndex := Index;
lbStages.OnClick(nil);
end;
end;
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.pmnStagesPopup(Sender: TObject);
begin
mniSG_Remove.Enabled := lbStages.ItemIndex >= 0;
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.mniSG_AddClick(Sender: TObject);
var
Temp: TILElementFinderStage;
begin
Temp := fCurrentParsingEntry.Finder.StageAdd;
lbStages.Items.AddObject(Temp.AsString,Temp);
If lbStages.Items.Count > 0 then
begin
lbStages.ItemIndex := Pred(lbStages.Count);
lbStages.OnClick(nil);
FrameChangeHandler(nil);
end;
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.mniSG_RemoveClick(Sender: TObject);
var
Index: Integer;
begin
If lbStages.ItemIndex >= 0 then
If MessageDlg(IL_Format('Are you sure you want to delete stage "%s"?',
[lbStages.Items[lbStages.ItemIndex]]),mtConfirmation,[mbYes,mbNo],0) = mrYes then
begin
Index := lbStages.ItemIndex;
If lbStages.ItemIndex < Pred(lbStages.Count) then
lbStages.ItemIndex := lbStages.ItemIndex + 1
else If lbStages.ItemIndex > 0 then
lbStages.ItemIndex := lbStages.ItemIndex - 1
else
lbStages.ItemIndex := -1;
lbStages.OnClick(nil);
lbStages.Items.Delete(Index);
fCurrentParsingEntry.Finder.StageDelete(Index);
FrameChangeHandler(nil);
end;
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.tvStageElementsSelect;
begin
If Assigned(tvStageElements.Selected) then
begin
If TObject(tvStageElements.Selected.Data) is TILComparatorBase then
ShowComparator(TILComparatorBase(tvStageElements.Selected.Data))
else
ShowComparator(nil);
end
else ShowComparator(nil);
If tvStageElements.Focused then
begin
If Assigned(tvStageElements.Selected) and (TObject(tvStageElements.Selected.Data) is TILFinderBaseClass) then
frmComparatorFrame.SetComparator(TILComparatorBase(tvStageElements.Selected.Data),True)
else
frmComparatorFrame.SetComparator(nil,True);
end;
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.tvStageElementsClick(Sender: TObject);
begin
//this deffers reaction to change and prevents flickering
PostMessage(Handle,IL_WM_USER_LVITEMSELECTED,0,IL_MSG_PARAM_LIST_IDX_ELEMENTS);
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.tvStageElementsChange(Sender: TObject; Node: TTreeNode);
begin
tvStageElements.OnClick(nil);
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.tvStageElementsEnter(Sender: TObject);
begin
tvStageElements.OnClick(nil);
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.pmnElementsPopup(Sender: TObject);
begin
If Assigned(tvStageElements.Selected) then
mniEL_Remove.Enabled := TObject(tvStageElements.Selected.Data) is TILElementComparator
else
mniEL_Remove.Enabled := False;
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.mniEL_AddClick(Sender: TObject);
var
Temp: TILElementComparator;
Node: TTreeNode;
begin
Temp := fCurrentParsingEntry.Finder[lbStages.ItemIndex].AddComparator;
Node := tvStageElements.Items.AddChildObject(nil,Temp.AsString,Temp);
tvStageElements.Items.AddChildObject(Node,Temp.TagName.AsString,Temp.TagName);
tvStageElements.Items.AddChildObject(Node,Temp.Attributes.AsString,Temp.Attributes);
tvStageElements.Items.AddChildObject(Node,Temp.Text.AsString,Temp.Text);
Node.Expand(True);
FrameChangeHandler(nil);
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.mniEL_RemoveClick(Sender: TObject);
var
Node: TTreeNode;
Temp: TILElementComparator;
begin
If Assigned(tvStageElements.Selected) then
If TObject(tvStageElements.Selected.Data) is TILElementComparator then
begin
Node := tvStageElements.Selected;
Temp := TILElementComparator(tvStageElements.Selected.Data);
If MessageDlg(IL_Format('Are you sure you want to delete element option "%s"?',
[Temp.AsString]),mtConfirmation,[mbYes,mbNo],0) = mrYes then
begin
tvStageElements.Items.Delete(Node);
tvStageElements.OnClick(nil);
fCurrentParsingEntry.Finder[lbStages.ItemIndex].Remove(Temp);
FrameChangeHandler(nil);
end;
end;
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.tvAttrCompsSelect;
begin
If Assigned(tvAttrComps.Selected) then
begin
If TObject(tvAttrComps.Selected.Data) is TILTextComparatorGroup then
FillTexts(TILTextComparatorGroup(tvAttrComps.Selected.Data))
else
FillTexts(nil);
end
else FillTexts(nil);
If tvAttrComps.Focused then
begin
If Assigned(tvAttrComps.Selected) and (TObject(tvAttrComps.Selected.Data) is TILComparatorBase) then
frmComparatorFrame.SetComparator(TILComparatorBase(tvAttrComps.Selected.Data),True)
else
frmComparatorFrame.SetComparator(nil,True);
end;
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.tvAttrCompsClick(Sender: TObject);
begin
PostMessage(Handle,IL_WM_USER_LVITEMSELECTED,0,IL_MSG_PARAM_LIST_IDX_ATTRIBUTES);
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.tvAttrCompsChange(Sender: TObject; Node: TTreeNode);
begin
tvAttrComps.OnClick(nil);
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.tvAttrCompsEnter(Sender: TObject);
begin
tvAttrComps.OnClick(nil);
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.pmnAttributesPopup(Sender: TObject);
begin
If Assigned(tvAttrComps.Selected) then
mniAT_Remove.Enabled := TObject(tvAttrComps.Selected.Data) is TILAttributeComparatorBase
else
mniAT_Remove.Enabled := False;
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.mniAT_AddCompClick(Sender: TObject);
var
Group: TILAttributeComparatorGroup;
Temp: TILAttributeComparator;
Node: TTreeNode;
begin
Group := TObject(tvStageElements.Selected.Data) as TILAttributeComparatorGroup;
Node := nil;
If Assigned(tvAttrComps.Selected) then
If TObject(tvAttrComps.Selected.Data) is TILAttributeComparatorGroup then
begin
Group := TILAttributeComparatorGroup(tvAttrComps.Selected.Data);
Node := tvAttrComps.Selected;
end;
Temp := Group.AddComparator;
Node := tvAttrComps.Items.AddChildObject(Node,Temp.AsString,Temp);
tvAttrComps.Items.AddChildObject(Node,Temp.Name.AsString,Temp.Name);
tvAttrComps.Items.AddChildObject(Node,Temp.Value.AsString,Temp.Value);
Node.Expand(True);
tvAttrComps.Select(Node);
FrameChangeHandler(nil);
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.mniAT_AddGroupClick(Sender: TObject);
var
Group: TILAttributeComparatorGroup;
Temp: TILAttributeComparatorGroup;
Node: TTreeNode;
begin
Group := TObject(tvStageElements.Selected.Data) as TILAttributeComparatorGroup;
Node := nil;
If Assigned(tvAttrComps.Selected) then
If TObject(tvAttrComps.Selected.Data) is TILAttributeComparatorGroup then
begin
Group := TILAttributeComparatorGroup(tvAttrComps.Selected.Data);
Node := tvAttrComps.Selected;
end;
Temp := Group.AddGroup;
Node := tvAttrComps.Items.AddChildObject(Node,Temp.AsString,Temp);
Node.Expand(True);
tvAttrComps.Select(Node);
FrameChangeHandler(nil);
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.mniAT_RemoveClick(Sender: TObject);
var
Group: TILAttributeComparatorGroup;
ToDelete: TObject;
begin
If Assigned(tvAttrComps.Selected) then
begin
Group := TObject(tvStageElements.Selected.Data) as TILAttributeComparatorGroup;
If Assigned(tvAttrComps.Selected.Parent) then
If TObject(tvAttrComps.Selected.Parent.Data) is TILAttributeComparatorGroup then
Group := TILAttributeComparatorGroup(tvAttrComps.Selected.Parent.Data);
If MessageDlg(IL_Format('Are you sure you want to delete node "%s"?',
[tvAttrComps.Selected.Text]),mtConfirmation,[mbYes,mbNo],0) = mrYes then
begin
ToDelete := TObject(tvAttrComps.Selected.Data);
tvAttrComps.Items.Delete(tvAttrComps.Selected);
tvAttrComps.OnClick(nil);
Group.Remove(ToDelete);
FrameChangeHandler(nil);
end;
end;
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.tvTextCompsSelect;
begin
If tvTextComps.Focused then
begin
If Assigned(tvTextComps.Selected) and (TObject(tvTextComps.Selected.Data) is TILComparatorBase) then
frmComparatorFrame.SetComparator(TILComparatorBase(tvTextComps.Selected.Data),True)
else
frmComparatorFrame.SetComparator(nil,True);
end;
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.tvTextCompsClick(Sender: TObject);
begin
PostMessage(Handle,IL_WM_USER_LVITEMSELECTED,0,IL_MSG_PARAM_LIST_IDX_TEXTS);
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.tvTextCompsChange(Sender: TObject; Node: TTreeNode);
begin
tvTextComps.OnClick(nil);
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.tvTextCompsEnter(Sender: TObject);
begin
tvTextComps.OnClick(nil);
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.pmnTextsPopup(Sender: TObject);
begin
begin
If Assigned(tvTextComps.Selected) then
mniTX_Remove.Enabled := TObject(tvTextComps.Selected.Data) is TILTextComparatorBase
else
mniTX_Remove.Enabled := False;
end;
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.mniTX_AddCompClick(Sender: TObject);
var
Group: TILTextComparatorGroup;
Temp: TILTextComparator;
Node: TTreeNode;
begin
If Assigned(tvAttrComps.Selected) then
Group := TObject(tvAttrComps.Selected.Data) as TILTextComparatorGroup
else
Group := TObject(tvStageElements.Selected.Data) as TILTextComparatorGroup;
Node := nil;
If Assigned(tvTextComps.Selected) then
If TObject(tvTextComps.Selected.Data) is TILTextComparatorGroup then
begin
Group := TILTextComparatorGroup(tvTextComps.Selected.Data);
Node := tvTextComps.Selected;
end;
Temp := Group.AddComparator;
Node := tvTextComps.Items.AddChildObject(Node,Temp.AsString,Temp);
Node.Expand(True);
tvTextComps.Select(Node);
FrameChangeHandler(nil);
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.mniTX_AddGroupClick(Sender: TObject);
var
Group: TILTextComparatorGroup;
Temp: TILTextComparatorGroup;
Node: TTreeNode;
begin
If Assigned(tvAttrComps.Selected) then
Group := TObject(tvAttrComps.Selected.Data) as TILTextComparatorGroup
else
Group := TObject(tvStageElements.Selected.Data) as TILTextComparatorGroup;
Node := nil;
If Assigned(tvTextComps.Selected) then
If TObject(tvTextComps.Selected.Data) is TILTextComparatorGroup then
begin
Group := TILTextComparatorGroup(tvTextComps.Selected.Data);
Node := tvTextComps.Selected;
end;
Temp := Group.AddGroup;
Node := tvTextComps.Items.AddChildObject(Node,Temp.AsString,Temp);
Node.Expand(True);
tvTextComps.Select(Node);
FrameChangeHandler(nil);
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.mniTX_RemoveClick(Sender: TObject);
var
Group: TILTextComparatorGroup;
ToDelete: TObject;
begin
If Assigned(tvTextComps.Selected) then
begin
If Assigned(tvAttrComps.Selected) then
Group := TObject(tvAttrComps.Selected.Data) as TILTextComparatorGroup
else
Group := TObject(tvStageElements.Selected.Data) as TILTextComparatorGroup;
If Assigned(tvTextComps.Selected.Parent) then
If TObject(tvTextComps.Selected.Parent.Data) is TILTextComparatorGroup then
Group := TILTextComparatorGroup(tvTextComps.Selected.Parent.Data);
If MessageDlg(IL_Format('Are you sure you want to delete node "%s"?',
[tvTextComps.Selected.Text]),mtConfirmation,[mbYes,mbNo],0) = mrYes then
begin
ToDelete := TObject(tvTextComps.Selected.Data);
tvTextComps.Items.Delete(tvTextComps.Selected);
tvTextComps.OnClick(nil);
Group.Remove(ToDelete);
FrameChangeHandler(nil);
end;
end;
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.btnExtrAddClick(Sender: TObject);
begin
frmExtractionFrame.Save;
frmExtractionFrame.SetExtractSett(nil,False);
SetLength(fCurrentParsingEntry.Extraction,Length(fCurrentParsingEntry.Extraction) + 1);
// following also calls frmExtractionFrame.SetExtractSett
SetExtractionIndex(High(fCurrentParsingEntry.Extraction));
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.btnExtrRemoveClick(Sender: TObject);
var
Index: Integer;
i: Integer;
begin
If Length(fCurrentParsingEntry.Extraction) > 0 then
If MessageDlg('Are you sure you want to delete this extraction setting?',mtConfirmation,[mbYes,mbNo],0) = mrYes then
begin
frmExtractionFrame.Save;
frmExtractionFrame.SetExtractSett(nil,False);
Index := fExtractionSettIndex;
If Length(fCurrentParsingEntry.Extraction) <= 1 then
fExtractionSettIndex := -1
else If fExtractionSettIndex >= High(fCurrentParsingEntry.Extraction) then
fExtractionSettIndex := fExtractionSettIndex - 1;
For i := Index to Pred(High(fCurrentParsingEntry.Extraction)) do
fCurrentParsingEntry.Extraction[i] := fCurrentParsingEntry.Extraction[i + 1];
SetLength(fCurrentParsingEntry.Extraction,Length(fCurrentParsingEntry.Extraction) - 1);
SetExtractionIndex(fExtractionSettIndex); // will also call frmExtractionFrame.SetExtractSett
end;
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.btnExtrPrevClick(Sender: TObject);
begin
SetExtractionIndex(fExtractionSettIndex - 1);
end;
//------------------------------------------------------------------------------
procedure TfParsingForm.btnExtrNextClick(Sender: TObject);
begin
SetExtractionIndex(fExtractionSettIndex + 1);
end;
end.
|
program selection_sort;
const
N = 10;
type
array1d = Array[1..N] of Integer;
{ Start pf procedure switchElements }
procedure switchElements(var el1, el2 : Integer);
var
temp : Integer;
begin
temp := el1;
el1 := el2;
el2 := temp;
end;
{ End of procedure switchElements }
{ Start of procedure fillArray }
procedure fillArray(var arrFill : array1d);
var
i : Integer;
begin
WriteLn('Filling array elements...');
Randomize;
for i := 1 to N do begin
arrFill[i] := Random(1000);
end;
WriteLn();
end;
{ End of procedure fillArray }
{ Start of procedure listArray }
procedure listArray(arr : array1d);
var
i : Integer;
begin
WriteLn('Array elements:');
for i := 1 to N do begin
Write(arr[i], ' ');
end;
WriteLn();
WriteLn();
end;
{ End of procedure listArray }
{ Start of procedure selectionSort }
procedure selectionSort(var arrSort : array1d);
var
i, j : Integer; // Loop variable
minEl : Integer; // Variable for lowest value element
begin
WriteLn('Sorting array elements...');
for i := 1 to N-1 do begin
minEl := i;
for j := i+1 to N do begin
if arrSort[j] < arrSort[minEl] then begin
minEl := j;
end;
end;
if minEl <> i then begin
switchElements(arrSort[minEl], arrSort[i]);
end;
end;
WriteLn('Done sorting array!');
WriteLn();
end;
{ End of procedure selectionSort }
{ Start of function isSorted }
function isSorted(arr : array1d):Boolean;
var
i : Integer;
s : Boolean;
begin
s := true;
for i := 1 to N-1 do begin
if arr[i] > arr[i+1] then begin
s := false;
end;
end;
isSorted := s;
if isSorted then begin
WriteLn('Array is sorted!');
end else begin
WriteLn('Array is NOT sorted!');
end;
WriteLn();
end;
{ End of function isSorted }
var
array1 : array1d;
begin
fillArray(array1);
listArray(array1);
selectionSort(array1);
listArray(array1);
isSorted(array1);
Write('Press <Enter> to close the program...');
ReadLn();
end.
|
unit FormStud_Add_Edit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit,
StdCtrls, cxControls, cxGroupBox, cxButtons, cnConsts, cxMaskEdit,
cnConsts_Messages, cxButtonEdit, uPrK_Loader, uPrK_Resources, ibase,
cxLabel, cxCurrencyEdit, cxCheckBox;
type
TfrmFormStud_Add_Edit = class(TForm)
OkButton: TcxButton;
CancelButton: TcxButton;
cxGroupBox1: TcxGroupBox;
NameLabel: TLabel;
ShortNameLabel: TLabel;
Name_Edit: TcxTextEdit;
ShortName_Edit: TcxTextEdit;
FORM_Kat_Edit: TcxButtonEdit;
Kod_edit: TcxCurrencyEdit;
kod_label: TcxLabel;
cxCheckBox1: TcxCheckBox;
procedure OkButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
procedure Name_EditKeyPress(Sender: TObject; var Key: Char);
procedure ShortName_EditKeyPress(Sender: TObject; var Key: Char);
procedure FormShow(Sender: TObject);
procedure ID_SP_FORM_OBUCH_KATEGORY_editPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
procedure Kod_editKeyPress(Sender: TObject; var Key: Char);
procedure Edit_kod_edit;
private
PLanguageIndex : byte;
procedure FormIniLanguage();
public
ID_NAME : int64;
DB_Handle : TISC_DB_HANDLE;
constructor Create(AOwner:TComponent; LanguageIndex : byte);reintroduce;
end;
implementation
{$R *.dfm}
constructor TfrmFormStud_Add_Edit.Create(AOwner:TComponent; LanguageIndex : byte);
begin
Screen.Cursor:=crHourGlass;
inherited Create(AOwner);
PLanguageIndex:= LanguageIndex;
FormIniLanguage();
Screen.Cursor:=crDefault;
end;
procedure TfrmFormStud_Add_Edit.FormIniLanguage;
begin
NameLabel.caption := cnConsts.cn_FullName[PLanguageIndex];
ShortNameLabel.caption := cnConsts.cn_ShortName[PLanguageIndex];
kod_label.Caption := cn_roles_Kod[PLanguageIndex];
OkButton.Caption := cnConsts.cn_Accept[PLanguageIndex];
OkButton.Hint := cnConsts.cn_Accept[PLanguageIndex];
CancelButton.Caption := cnConsts.cn_Cancel[PLanguageIndex];
CancelButton.Hint := cnConsts.cn_Cancel[PLanguageIndex];
cxCheckBox1.Properties.Caption := cnConsts.cn_is_deleted_Column[PLanguageIndex];
end;
procedure TfrmFormStud_Add_Edit.OkButtonClick(Sender: TObject);
begin
Edit_kod_edit;
If Name_Edit.Text = '' then
begin
showmessage(cnConsts_Messages.cn_Name_Need[PLanguageIndex]);
Name_Edit.SetFocus;
exit;
end;
If ShortName_Edit.Text = '' then
begin
showmessage(cnConsts_Messages.cn_ShortName_Need[PLanguageIndex]);
ShortName_Edit.SetFocus;
exit;
end;
If FORM_KAT_Edit.Text = '' then
begin
showmessage(cn_Some_Need[PLanguageIndex]);
FORM_KAT_Edit.SetFocus;
exit;
end;
If Kod_edit.Text = '' then
Begin
ShowMessage(cn_Some_Need[PLanguageIndex]);
Kod_edit.SetFocus;
exit;
End;
ModalResult:=mrOk;
end;
procedure TfrmFormStud_Add_Edit.CancelButtonClick(Sender: TObject);
begin
close;
end;
procedure TfrmFormStud_Add_Edit.Name_EditKeyPress(Sender: TObject;
var Key: Char);
begin
if key = #13 then FORM_Kat_Edit.SetFocus;
end;
procedure TfrmFormStud_Add_Edit.ShortName_EditKeyPress(Sender: TObject;
var Key: Char);
begin
if key = #13 then Kod_edit.SetFocus;
end;
procedure TfrmFormStud_Add_Edit.FormShow(Sender: TObject);
begin
Name_Edit.SetFocus;
end;
procedure TfrmFormStud_Add_Edit.ID_SP_FORM_OBUCH_KATEGORY_editPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
res: Variant;
begin
res:= uPrK_Loader.ShowPrkSprav(self,DB_Handle,PrK_SP_FORM_OBUCH_KATEGORY,fsNormal);
if VarArrayDimCount(Res)>0 then
begin
ID_NAME := res[0];
FORM_KAT_Edit.Text := res[1];
ShortName_Edit.SetFocus;
end;
end;
procedure TfrmFormStud_Add_Edit.Edit_kod_edit;
Begin
If Kod_edit.text='' then Kod_edit.Value:=0;
If length(kod_edit.Text)>2 then Kod_edit.Text:=copy(kod_edit.Text,1,2);
End;
procedure TfrmFormStud_Add_Edit.Kod_editKeyPress(Sender: TObject;
var Key: Char);
begin
If key = #13 then
Begin
OkButton.SetFocus;
edit_kod_edit;
End;
end;
end.
|
unit NfeLocalEntrega;
{$mode objfpc}{$H+}
interface
uses
HTTPDefs, BrookRESTActions, BrookUtils, FPJson, SysUtils, BrookHTTPConsts;
type
TNfeLocalEntregaOptions = class(TBrookOptionsAction)
end;
TNfeLocalEntregaRetrieve = class(TBrookRetrieveAction)
procedure Request({%H-}ARequest: TRequest; AResponse: TResponse); override;
end;
TNfeLocalEntregaShow = class(TBrookShowAction)
end;
TNfeLocalEntregaCreate = class(TBrookCreateAction)
end;
TNfeLocalEntregaUpdate = class(TBrookUpdateAction)
end;
TNfeLocalEntregaDestroy = class(TBrookDestroyAction)
end;
implementation
procedure TNfeLocalEntregaRetrieve.Request(ARequest: TRequest; AResponse: TResponse);
var
VRow: TJSONObject;
Campo: String;
Filtro: String;
begin
Campo := Values['campo'].AsString;
Filtro := Values['filtro'].AsString;
Values.Clear;
Table.Where(Campo + ' = "' + Filtro + '"');
if Execute then
begin
Table.GetRow(VRow);
try
Write(VRow.AsJSON);
finally
FreeAndNil(VRow);
end;
end
else
begin
AResponse.Code := BROOK_HTTP_STATUS_CODE_NOT_FOUND;
AResponse.CodeText := BROOK_HTTP_REASON_PHRASE_NOT_FOUND;
end;
//inherited Request(ARequest, AResponse);
end;
initialization
TNfeLocalEntregaOptions.Register('nfe_local_entrega', '/nfe_local_entrega');
TNfeLocalEntregaRetrieve.Register('nfe_local_entrega', '/nfe_local_entrega/:campo/:filtro/');
TNfeLocalEntregaShow.Register('nfe_local_entrega', '/nfe_local_entrega/:id');
TNfeLocalEntregaCreate.Register('nfe_local_entrega', '/nfe_local_entrega');
TNfeLocalEntregaUpdate.Register('nfe_local_entrega', '/nfe_local_entrega/:id');
TNfeLocalEntregaDestroy.Register('nfe_local_entrega', '/nfe_local_entrega/:id');
end.
|
unit ConnectSettings;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Simplex.Types;
type
TfrmConnectSettings = class(TForm)
GroupBox1: TGroupBox;
btnOK: TButton;
btnCancel: TButton;
cbxSecurityPolicy: TComboBox;
lblSecurityPolicy: TLabel;
lblAuthentication: TLabel;
cbxAuthentication: TComboBox;
lblUserName: TLabel;
edtUserName: TEdit;
lblPassword: TLabel;
edtPassword: TEdit;
procedure cbxAuthenticationChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
function GetConnectSettings(AOwner: TComponent; out ASecurityMode: SpxMessageSecurityMode;
out ASecurityPolicyUri: SpxString; var AClientConfig: SpxClientConfig): Boolean;
implementation
{$R *.dfm}
function GetConnectSettings(AOwner: TComponent; out ASecurityMode: SpxMessageSecurityMode;
out ASecurityPolicyUri: SpxString; var AClientConfig: SpxClientConfig): Boolean;
var frmConnectSettings: TfrmConnectSettings;
begin
Result := False;
frmConnectSettings := TfrmConnectSettings.Create(AOwner);
try
if (frmConnectSettings.ShowModal() <> mrOK) then Exit;
ASecurityMode := SpxMessageSecurityMode_None;
ASecurityPolicyUri := SpxSecurityPolicy_None;
AClientConfig.CertificateFileName := '';
AClientConfig.PrivateKeyFileName := '';
AClientConfig.TrustedCertificatesFolder := '';
AClientConfig.ServerCertificateFileName := '';
AClientConfig.Authentication.AuthenticationType := SpxAuthenticationType_Anonymous;
AClientConfig.Authentication.UserName := '';
AClientConfig.Authentication.Password := '';
if (frmConnectSettings.cbxSecurityPolicy.ItemIndex > 0) then
begin
ASecurityMode := SpxMessageSecurityMode_SignAndEncrypt;
ASecurityPolicyUri := SpxSecurityPolicy_Basic128Rsa15;
AClientConfig.CertificateFileName := 'Certificates\ClientCertificate.der';
AClientConfig.PrivateKeyFileName := 'Certificates\ClientPrivateKey.pem';
AClientConfig.TrustedCertificatesFolder := 'Certificates\TrustedCertificates';
AClientConfig.ServerCertificateFileName := 'Certificates\TrustedCertificates\ServerCertificate.der';
end;
if (frmConnectSettings.cbxAuthentication.ItemIndex > 0) then
begin
AClientConfig.Authentication.AuthenticationType := SpxAuthenticationType_UserName;
AClientConfig.Authentication.UserName := frmConnectSettings.edtUserName.Text;
AClientConfig.Authentication.Password := frmConnectSettings.edtPassword.Text;
end;
Result := True;
finally
FreeAndNil(frmConnectSettings);
end;
end;
procedure TfrmConnectSettings.cbxAuthenticationChange(Sender: TObject);
begin
lblUserName.Enabled := cbxAuthentication.ItemIndex > 0;
edtUserName.Enabled := lblUserName.Enabled;
lblPassword.Enabled := cbxAuthentication.ItemIndex > 0;
edtPassword.Enabled := lblPassword.Enabled;
end;
end.
|
unit uDlgSelectObjectTypeToLink;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uBASE_DialogForm, Menus, cxLookAndFeelPainters, DB, ADODB,
StdCtrls, cxButtons, ExtCtrls, cxStyles, cxCustomData, cxGraphics,
cxFilter, cxData, cxDataStorage, cxEdit, cxDBData, cxGridLevel,
cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxGrid;
type
TdlgSelectObjectTypeToLink = class(TBASE_DialogForm)
Query: TADOQuery;
DataSource: TDataSource;
view: TcxGridDBTableView;
GridLevel: TcxGridLevel;
Grid: TcxGrid;
view_: TcxGridDBColumn;
view_1: TcxGridDBColumn;
viewDBColumn: TcxGridDBColumn;
viewDBColumn1: TcxGridDBColumn;
view_2: TcxGridDBColumn;
viewDBColumn2: TcxGridDBColumn;
view_3: TcxGridDBColumn;
viewDBColumn11: TcxGridDBColumn;
viewDBColumn21: TcxGridDBColumn;
private
FObjectID: integer;
procedure SetObjectID(const Value: integer);
function GetSelectedObjectID: variant;
{ Private declarations }
protected
procedure Check; override;
public
property ObjectID: integer read FObjectID write SetObjectID;
property SelectedObjectID: variant read GetSelectedObjectID;
end;
var
dlgSelectObjectTypeToLink: TdlgSelectObjectTypeToLink;
implementation
uses uMain, uCommonUtils;
{$R *.dfm}
{ TBASE_DialogForm1 }
procedure TdlgSelectObjectTypeToLink.Check;
begin
if VarIsNullMy(SelectedObjectID) then begin
ShowError('Ошибка выбора', 'Необходимо выбрать тип объекта', Handle);
abort;
end;
end;
function TdlgSelectObjectTypeToLink.GetSelectedObjectID: variant;
begin
result:=Query['Парам1'];
end;
procedure TdlgSelectObjectTypeToLink.SetObjectID(const Value: integer);
begin
FObjectID:=Value;
Query.SQL.Text:=format('sp_Атрибут_ПоОбъектуТипуДанных_получить @код_Объект = %d, @ТипДанных = 18', [Value]);
Query.Open;
end;
end.
|
{------------------------------------------------------------------------------------}
{program p031_000 exercises production #031 }
{statement -> compound_statement }
{------------------------------------------------------------------------------------}
{Author: Thomas R. Turner }
{E-Mail: trturner@uco.edu }
{Date: January, 2012 }
{------------------------------------------------------------------------------------}
{Copyright January, 2012 by Thomas R. Turner }
{Do not reproduce without permission from Thomas R. Turner. }
{------------------------------------------------------------------------------------}
program p031_000;
var cash:real;
begin{p031_000}
writestring('How much cash do you have? ');
readreal(cash);
readln;
if cash<100.0 then
begin
writestring('You wicked and slothful person.');
writeln;
writestring('I''d never go out with you.');
writeln
end
else
begin
writestring('Come on, honey, let''s have a good time tonight!');
writeln
end;
writestring('See you later!');
writeln
end{p031_000}.
|
unit UTypes;
interface
const
{ Ошибки при вычислении выражения }
errRANK = 1;
errBRACKETS = 2;
errNOT_ENOUGH_OPERANDS = 4;
errBAD_OPERANDS = 8;
errTG_PI_2 = 16;
errCTG0 = 32;
errASIN = 64;
errACOS = 128;
errLN = 256;
errLG = 512;
errLOG = 1024;
errFACT = 2048;
errDIV0 = 4096;
type
{ Арифметическая операция }
TCalcOperation = (opNONE, opADD, opSUB, opMUL, opDIV, opPOWER, opROOT,
opCOS, opSIN, opSQRT, opSQR, opLOG, opLN, opLG, op1DIVX);
{ Элемент истории вычисленных операций }
THistoryItem = packed record
operation: TCalcOperation;
operandA, operandB, res: Extended;
end;
{ Сохраняемая в файл запись истории }
THistoryCell = packed record
code: Integer;
date: TDateTime;
item: THistoryItem;
end;
{ Массив элементов истории }
THistoryArray = array of THistoryItem;
{ Система счисления }
TCountSystem = (csBIN, csOCT, csDEC, csHEX);
{ Число и его представления в системах счисления }
TNumber = record
hex: String;
dec: String;
oct: String;
bin: String;
end;
{ Последняя выполненная операция }
TLastButton = (lbTEXT, lbBACK, lbBUTTON);
{ Элемент истории ввода выражения }
TLocalHistory = record
textShot: String;
selStartShot: Integer;
end;
{ Массив сообщений об ошибках }
TErrorsArray = array of String;
{ Возвращает строку с одной из системы счисления из записи TNumber }
function hexFromNumber(number: TNumber):String;
function decFromNumber(number: TNumber):String;
function octFromNumber(number: TNumber):String;
function binFromNumber(number: TNumber):String;
{ Переводит номер ошибки в массив сообщений об ошибках }
function errorToArray(error: Integer):TErrorsArray;
{ Переводит операцию в строку }
function operationToString(operation: TCalcOperation):String;
{ Переводит массив сообщений об ошибках в одну строку }
function arrayToString(errors: TErrorsArray):String;
{ Переводит элемент истории в строку }
function historyItemToString(historyItem: THistoryItem):String;
{ Удаляет лишние нули из строки }
function deleteTrash(str: String): String;
{ Конструктор THistoryItem }
function toHistoryItem(operation: TCalcOperation; operandA, operandB, res: Extended):THistoryItem;
implementation
uses
SysUtils;
{ Возвращает число в шестнадцатеричной системе счисления из записи TNumber }
function hexFromNumber(number: TNumber):String;
var
i: Integer;
begin
result := number.hex;
i := length(result) + 1;
while i > 0 do
begin
dec(i, 2);
insert(' ', result, i);
end;
if result = ' ' then
result := '0';
end;
{ Возвращает число в десятеричной системе счисления из записи TNumber }
function decFromNumber(number: TNumber):String;
var
i: Integer;
begin
result := number.dec;
i := length(result) + 1;
while i > 0 do
begin
dec(i, 3);
insert(' ', result, i);
end;
if result = ' ' then
result := '0';
end;
{ Возвращает число в восьмеричной системе счисления из записи TNumber }
function octFromNumber(number: TNumber):String;
var
i: Integer;
begin
result := number.oct;
i := length(result) + 1;
while i > 0 do
begin
dec(i, 3);
insert(' ', result, i);
end;
if result = ' ' then
result := '0';
end;
{ Возвращает число в двоичной системе счисления из записи TNumber }
function binFromNumber(number: TNumber):String;
var
i: Integer;
begin
result := number.bin;
i := length(result) + 1;
while i > 0 do
begin
dec(i, 8);
insert(' ', result, i);
end;
while (length(result) > 0) and (result[1] = ' ') do
delete(result, 1, 1);
if length(result) > 35 then
begin
delete(result, length(result) - 35, 1);
insert(#13, result, length(result) - 34);
end;
if result = '' then
result := '0';
end;
{ Добавляет элемент в конец динамического массива }
procedure arrayAdd(var errors: TErrorsArray; str: String);
begin
SetLength(errors, length(errors) + 1);
errors[length(errors) - 1] := str;
end;
{ Переводит номер ошибки в массив сообщений об ошибках }
function errorToArray(error: Integer):TErrorsArray;
begin
SetLength(result, 0);
if error and 1 <> 0 then
arrayAdd(result, 'Неверный ранг выражения');
if error and 2 <> 0 then
arrayAdd(result, 'Недостаточно скобок в выражении');
if error and 4 <> 0 then
arrayAdd(result, 'Недостаточно операндов');
if error and 8 <> 0 then
arrayAdd(result, 'Неверный формат записи операндов');
if error and 16 <> 0 then
arrayAdd(result, 'tg Pi/2');
if error and 32 <> 0 then
arrayAdd(result, 'ctg 0');
if error and 64 <> 0 then
arrayAdd(result, 'asin');
if error and 128 <> 0 then
arrayAdd(result, 'acos');
if error and 256 <> 0 then
arrayAdd(result, 'Ln(x), x <= 0');
if error and 512 <> 0 then
arrayAdd(result, 'Lg(x), x <= 0');
if error and 1024 <> 0 then
arrayAdd(result, 'Log(x), x <= 0');
if error and 2048 <> 0 then
arrayAdd(result, 'x! , x > 10');
if error and 4096 <> 0 then
arrayAdd(result, 'Деление на ноль');
end;
{ Переводит операцию в строку }
function operationToString(operation: TCalcOperation):String;
begin
case operation of
opADD:
result := ' +';
opSUB:
result := ' -';
opMUL:
result := ' *';
opDIV:
result := ' /';
opPOWER:
result := ' ^';
opROOT:
result := ' ^(1/';
else
result := '';
end;
end;
{ Переводит массив сообщений об ошибках в одну строку }
function arrayToString(errors: TErrorsArray):String;
var
i: Integer;
begin
result := errors[0];
for i := 1 to length(errors) - 1 do
result := result + #13 + #10 + errors[i];
end;
{ Переводит элемент истории в строку }
function historyItemToString(historyItem: THistoryItem):String;
begin
with historyItem do
begin
case operation of
opADD:
result := deleteTrash(FloatToStrF(operandB, ffFixed, 5, 5)) + ' + ' + deleteTrash(FloatToStrF(operandA, ffFixed, 5, 5));
opSUB:
result := deleteTrash(FloatToStrF(operandB, ffFixed, 5, 5)) + ' - ' + deleteTrash(FloatToStrF(operandA, ffFixed, 5, 5));
opMUL:
result := deleteTrash(FloatToStrF(operandB, ffFixed, 5, 5)) + ' * ' + deleteTrash(FloatToStrF(operandA, ffFixed, 5, 5));
opDIV:
result := deleteTrash(FloatToStrF(operandB, ffFixed, 5, 5)) + ' / ' + deleteTrash(FloatToStrF(operandA, ffFixed, 5, 5));
opPOWER:
result := deleteTrash(FloatToStrF(operandB, ffFixed, 5, 5)) + ' ^ ' + deleteTrash(FloatToStrF(operandA, ffFixed, 5, 5));
opROOT:
result := deleteTrash(FloatToStrF(operandB, ffFixed, 5, 5)) + ' ^ (1 / ' + deleteTrash(FloatToStrF(operandA, ffFixed, 5, 5)) + ')';
opCOS:
result := 'cos(' + deleteTrash(FloatToStrF(operandA, ffFixed, 5, 5)) + ')';
opSIN:
result := 'sin(' + deleteTrash(FloatToStrF(operandA, ffFixed, 5, 5)) + ')';
opSQRT:
result := 'sqrt(' + deleteTrash(FloatToStrF(operandA, ffFixed, 5, 5)) + ')';
opSQR:
result := 'sqr(' + deleteTrash(FloatToStrF(operandA, ffFixed, 5, 5)) + ')';
opLOG:
result := 'log(' + deleteTrash(FloatToStrF(operandA, ffFixed, 5, 5)) + ')';
opLN:
result := 'ln(' + deleteTrash(FloatToStrF(operandA, ffFixed, 5, 5)) + ')';
opLG:
result := 'lg(' + deleteTrash(FloatToStrF(operandA, ffFixed, 5, 5)) + ')';
op1DIVX:
result := '1 / ' + deleteTrash(FloatToStrF(operandA, ffFixed, 5, 5));
end;
end;
end;
function deleteTrash(str: String): String;
begin
result := str;
while (pos('.', result) <> 0) and (pos('E', result) = 0) and (length(result) >= 1) and (result[length(result)] = '0') do
delete(result, length(result), 1);
if (length(result) >= 1) and (result[length(result)] = '.') then
delete(result, length(result), 1);
end;
{ Конструктор THistoryItem }
function toHistoryItem(operation: TCalcOperation; operandA, operandB, res: Extended):THistoryItem;
begin
result.operation := operation;
result.operandA := operandA;
result.operandB := operandB;
result.res := res;
end;
end.
|
{===============================================================================
Projeto Sintegra
****************
Biblioteca de Componente para geração do arquivo Sintegra
Site: http://www.sultan.welter.pro.br
Direitos Autorais Reservados (c) 2004 Régys Borges da Silveira
Esta biblioteca é software livre; você pode redistribuí-la e/ou modificá-la sob
os termos da Licença Pública Geral Menor do GNU conforme publicada pela Free
Software Foundation; tanto a versão 2.1 da Licença, ou (a seu critério) qualquer
versão posterior.
Esta biblioteca é distribuído na expectativa de que seja útil, porém, SEM
NENHUMA GARANTIA; nem mesmo a garantia implícita de COMERCIABILIDADE OU
ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral Menor do
GNU para mais detalhes.
Você deve ter recebido uma cópia da Licença Pública Geral Menor do GNU junto com
esta biblioteca; se não, escreva para a Free Software Foundation, Inc., no
endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA.
================================================================================
Contato:
Autor...: Régys Borges da Silveira
Email...: regyssilveira@hotmail.com
================================================================================
Colaboração:
Marcelo Welter <marcelo@welter.pro.br>
===============================================================================}
unit Sintegra;
interface
uses
SysUtils, Controls, Classes, Windows, Forms;
type
ESintegraException = class(Exception);
TEventoErro = procedure(aErro: string) of object;
TCodIdentificaOper = (opeInterestaduais, opeInterestSubTributaria, opeTotal);
TCodFinalidade = (finNormal, finRetificacaoTotal, finRetificacaoAditiva, finDesfazimento);
TModDocumento = (modMaqRegistradora, modPDV, modECF);
TSitNotaFiscal = (nfNormal, nfCancelado, nfExtNormal, nfExtCancelado);
TTipoEmitente = (tpeProprio, tpeTerceiros);
TTipoPosse = (tpo1, tpo2, tpo3);
TModalidadeFrete = (frCIF, frFOB, frOUTRO);
ISintegra_Reg70_unico = interface(IInterface)
['{96006577-18BD-4444-A582-B6E57E2A9CF2}']
function GetBaseCalcICMS: Currency;
function GetCFOP: string;
function GetCNPJEmitente: string;
function GetDataEmisao: TDate;
function GetInscEstEmitente: string;
function GetIsentaNTributada: Currency;
function GetModelo: SmallInt;
function GetModFrete: TModalidadeFrete;
function GetNumero: Integer;
function GetOutras: Currency;
function GetSerie: string;
function GetSituacao: TSitNotaFiscal;
function GetSubSerie: string;
function GetUF: string;
function GetValorICMS: Currency;
function GetValorTotal: Currency;
procedure SetBaseCalcICMS(const Value: Currency);
procedure SetCFOP(const Value: string);
procedure SetCNPJEmitente(const Value: string);
procedure SetDataEmisao(const Value: TDate);
procedure SetInscEstEmitente(const Value: string);
procedure SetIsentaNTributada(const Value: Currency);
procedure SetModelo(const Value: SmallInt);
procedure SetModFrete(const Value: TModalidadeFrete);
procedure SetNumero(const Value: Integer);
procedure SetOutras(const Value: Currency);
procedure SetSerie(const Value: string);
procedure SetSituacao(const Value: TSitNotaFiscal);
procedure SetSubSerie(const Value: string);
procedure SetUF(const Value: string);
procedure SetValorICMS(const Value: Currency);
procedure SetValorTotal(const Value: Currency);
property CNPJEmitente: string read GetCNPJEmitente write SetCNPJEmitente;
property InscEstEmitente: string read GetInscEstEmitente write SetInscEstEmitente;
property DataEmisao: TDate read GetDataEmisao write SetDataEmisao;
property UF: string read GetUF write SetUF;
property Modelo: SmallInt read GetModelo write SetModelo;
property Serie: string read GetSerie write SetSerie;
property SubSerie: string read GetSubSerie write SetSubSerie;
property Numero: Integer read GetNumero write SetNumero;
property CFOP: string read GetCFOP write SetCFOP;
property ValorTotal: Currency read GetValorTotal write SetValorTotal;
property BaseCalcICMS: Currency read GetBaseCalcICMS write SetBaseCalcICMS;
property ValorICMS: Currency read GetValorICMS write SetValorICMS;
property IsentaNTributada: Currency read GetIsentaNTributada write SetIsentaNTributada;
property Outras: Currency read GetOutras write SetOutras;
property ModFrete: TModalidadeFrete read GetModFrete write SetModFrete;
property Situacao: TSitNotaFiscal read GetSituacao write SetSituacao;
end;
ISintegra_Reg70_Lista = interface(IInterface)
['{943AEAD3-C1D8-4C14-B03D-414830F8A93C}']
function GetItem(Index: Integer): ISintegra_Reg70_unico;
procedure SetItem(Index: Integer; const Value: ISintegra_Reg70_unico);
function Add: ISintegra_Reg70_unico;
procedure Delete(Index: integer);
function Count: Integer;
procedure Clear;
property Items[Index: Integer]: ISintegra_Reg70_unico read GetItem write SetItem;
end;
ISintegra_Reg71_unico = interface(IInterface)
['{96006577-18BD-4444-A582-B6E57E2A9CF2}']
function GetCNPJRemetDest: string;
function GetCNPJTomador: string;
function GetDataEmissao: TDate;
function GetInscEstRemetDest: string;
function GetInscEstTomador: string;
function GetModelo: SmallInt;
function GetNFDataEmissao: TDate;
function GetNFModelo: SmallInt;
function GetNFNumero: Integer;
function GetNFSerie: string;
function GetNFValorTotal: Currency;
function GetNumero: Integer;
function GetSerie: string;
function GetSubSerie: string;
function GetUFRemetDest: string;
function GetUFTomador: string;
procedure SetCNPJRemetDest(const Value: string);
procedure SetCNPJTomador(const Value: string);
procedure SetDataEmissao(const Value: TDate);
procedure SetInscEstRemetDest(const Value: string);
procedure SetInscEstTomador(const Value: string);
procedure SetModelo(const Value: SmallInt);
procedure SetNFDataEmissao(const Value: TDate);
procedure SetNFModelo(const Value: SmallInt);
procedure SetNFNumero(const Value: Integer);
procedure SetNFSerie(const Value: string);
procedure SetNFValorTotal(const Value: Currency);
procedure SetNumero(const Value: Integer);
procedure SetSerie(const Value: string);
procedure SetSubSerie(const Value: string);
procedure SetUFRemetDest(const Value: string);
procedure SetUFTomador(const Value: string);
property DataEmissao: TDate read GetDataEmissao write SetDataEmissao;
property Modelo: SmallInt read GetModelo write SetModelo;
property Serie: string read GetSerie write SetSerie;
property SubSerie: string read GetSubSerie write SetSubSerie;
property Numero: Integer read GetNumero write SetNumero;
property CNPJTomador: string read GetCNPJTomador write SetCNPJTomador;
property InscEstTomador: string read GetInscEstTomador write SetInscEstTomador;
property UFTomador: string read GetUFTomador write SetUFTomador;
property CNPJRemetDest: string read GetCNPJRemetDest write SetCNPJRemetDest;
property InscEstRemetDest: string read GetInscEstRemetDest write SetInscEstRemetDest;
property UFRemetDest: string read GetUFRemetDest write SetUFRemetDest;
property NFDataEmissao: TDate read GetNFDataEmissao write SetNFDataEmissao;
property NFModelo: SmallInt read GetNFModelo write SetNFModelo;
property NFSerie: string read GetNFSerie write SetNFSerie;
property NFNumero: Integer read GetNFNumero write SetNFNumero;
property NFValorTotal: Currency read GetNFValorTotal write SetNFValorTotal;
end;
ISintegra_Reg71_Lista = interface(IInterface)
['{943AEAD3-C1D8-4C14-B03D-414830F8A93C}']
function GetItem(Index: Integer): ISintegra_Reg71_unico;
procedure SetItem(Index: Integer; const Value: ISintegra_Reg71_unico);
function Add: ISintegra_Reg71_unico;
procedure Delete(Index: integer);
function Count: Integer;
procedure Clear;
property Items[Index: Integer]: ISintegra_Reg71_unico read GetItem write SetItem;
end;
ISintegra_Reg74_Unico = interface(IInterface)
['{A9FD144C-BE79-4E13-A1E9-CB99D2626E4D}']
function GetCNPJ: string;
function GetCodPRoduto: string;
function GetDataInventario: TDate;
function GetInscEstadual: string;
function GetQuantidade: Extended;
function GetTipoPosse: TTipoPosse;
function GetUF: string;
function GetValorTotal: Currency;
procedure SetCNPJ(const Valor: string);
procedure SetCodPRoduto(const Valor: string);
procedure SetDataInventario(const Valor: TDate);
procedure SetInscEstadual(const Valor: string);
procedure SetQuantidade(const Valor: Extended);
procedure SetTipoPosse(const Valor: TTipoPosse);
procedure SetUF(const Valor: string);
procedure SetValorTotal(const Valor: Currency);
property TipoPosse: TTipoPosse read GetTipoPosse write SetTipoPosse;
property CNPJ: string read GetCNPJ write SetCNPJ;
property InscEstadual: string read GetInscEstadual write SetInscEstadual;
property UF: string read GetUF write SetUF;
property DataInventario: TDate read GetDataInventario write SetDataInventario;
property CodPRoduto: string read GetCodPRoduto write SetCodPRoduto;
property Quantidade: Extended read GetQuantidade write SetQuantidade;
property ValorTotal: Currency read GetValorTotal write SetValorTotal;
end;
ISintegra_Reg74_Lista = interface(IInterface)
['{CD2F0EE7-C5BE-41E2-A9FB-E8839E9260CF}']
function GetItem(Index: Integer): ISintegra_Reg74_unico;
procedure SetItem(Index: Integer; const Value: ISintegra_Reg74_unico);
function Add: ISintegra_Reg74_unico;
procedure Delete(Index: integer);
function Count: Integer;
procedure Clear;
property Items[Index: Integer]: ISintegra_Reg74_unico read GetItem write SetItem;
end;
ISintegra_Reg75_unico = interface(IInterface)
['{86306321-1EE9-442D-8585-D9B5B9187572}']
function GetAliquotaICMS: Currency;
function GetAliquotaIPI: Currency;
function GetBaseICMSST: Currency;
function GetCodNCM: string;
function GetCodProduto: string;
function GetDescricaoProd: string;
function GetReducaoBaseCalc: Currency;
function GetUnidade: string;
function GetValidadeFinal: TDate;
function GetValidadeInicial: TDate;
procedure SetAliquotaICMS(const Valor: Currency);
procedure SetAliquotaIPI(const Valor: Currency);
procedure SetBaseICMSST(const Valor: Currency);
procedure SetCodNCM(const Valor: string);
procedure SetCodProduto(const Valor: string);
procedure SetDescricaoProd(const Valor: string);
procedure SetReducaoBaseCalc(const Valor: Currency);
procedure SetUnidade(const Valor: string);
procedure SetValidadeFinal(const Valor: TDate);
procedure SetValidadeInicial(const Valor: TDate);
property ValidadeInicial: TDate read GetValidadeInicial write SetValidadeInicial;
property ValidadeFinal: TDate read GetValidadeFinal write SetValidadeFinal;
property CodProduto: string read GetCodProduto write SetCodProduto;
property CodNCM: string read GetCodNCM write SetCodNCM;
property DescricaoProd: string read GetDescricaoProd write SetDescricaoProd;
property Unidade: string read GetUnidade write SetUnidade;
property AliquotaIPI: Currency read GetAliquotaIPI write SetAliquotaIPI;
property AliquotaICMS: Currency read GetAliquotaICMS write SetAliquotaICMS;
property ReducaoBaseCalc: Currency read GetReducaoBaseCalc write SetReducaoBaseCalc;
property BaseICMSST: Currency read GetBaseICMSST write SetBaseICMSST;
end;
ISintegra_Reg75_Lista = interface(IInterface)
['{7621A167-AB53-4CF2-8AB3-E538F4648E60}']
function GetItem(Index: Integer): ISintegra_Reg75_unico;
procedure SetItem(Index: Integer; const Value: ISintegra_Reg75_unico);
function Add: ISintegra_Reg75_unico;
procedure Delete(Index: integer);
function Count: Integer;
procedure Clear;
property Items[Index: Integer]: ISintegra_Reg75_unico read GetItem write SetItem;
end;
ISintegra_Reg60R_unico = interface(IInterface)
['{A846B50C-E2A0-4B4A-887C-E30CD6DE0B46}']
function GetAno: SmallInt;
function GetCodProduto: string;
function GetMes: SmallInt;
function GetQuantidade: Extended;
function GetSitTributaria: string;
function GetValorAcumICMS: Currency;
function GetValorAcumProduto: Currency;
procedure SetAno(const Valor: SmallInt);
procedure SetCodProduto(const Valor: string);
procedure SetMes(const Valor: SmallInt);
procedure SetQuantidade(const Valor: Extended);
procedure SetSitTributaria(const Valor: string);
procedure SetValorAcumICMS(const Valor: Currency);
procedure SetValorAcumProduto(const Valor: Currency);
property Mes: SmallInt read GetMes write SetMes;
property ANo: SmallInt read GetAno write SetAno;
property CodProduto: string read GetCodProduto write SetCodProduto;
property Quantidade: Extended read GetQuantidade write SetQuantidade;
property ValorAcumProduto: Currency read GetValorAcumProduto write SetValorAcumProduto;
property ValorAcumICMS: Currency read GetValorAcumICMS write SetValorAcumICMS;
property SitTributaria: string read GetSitTributaria write SetSitTributaria;
end;
ISintegra_Reg60R_Lista = interface(IInterface)
['{4AF3F1E1-F645-45EF-8A23-5F0437E93C58}']
function GetItem(Index: Integer): ISintegra_Reg60R_unico;
procedure SetItem(Index: Integer; const Value: ISintegra_Reg60R_unico);
function Add: ISintegra_Reg60R_unico;
procedure Delete(Index: integer);
function Count: Integer;
procedure Clear;
property Items[Index: Integer]: ISintegra_Reg60R_unico read GetItem write SetItem;
end;
ISintegra_Reg60A_unico = interface(IInterface)
['{EDEFBBD5-CFD3-45E4-BB64-9FCB0A500330}']
function GetSitTributaria: string;
procedure SetSitTributaria(const Valor: string);
function GetValorAcumulado: Currency;
procedure SetValorAcumulado(const Valor: Currency);
property SitTributaria: string read GetSitTributaria write SetSitTributaria;
property ValorAcumulado: Currency read GetValorAcumulado write SetValorAcumulado;
end;
ISintegra_Reg60A_Lista = interface(IInterface)
['{C6B68871-908B-4CD7-BF4C-1AA16BA2CD71}']
function GetItem(Index: Integer): ISintegra_Reg60A_unico;
procedure SetItem(Index: Integer; const Value: ISintegra_Reg60A_unico);
function Total: Currency;
function Add: ISintegra_Reg60A_unico;
procedure Delete(Index: integer);
function Count: Integer;
procedure Clear;
property Items[Index: Integer]: ISintegra_Reg60A_unico read GetItem write SetItem;
end;
ISintegra_Reg60M_unico = interface(IInterface)
['{1EA59280-823F-4149-81DA-5992AD482562}']
function GetDataEmissao: TDate;
procedure SetDataEmissao(const Valor: TDate);
function GetNumSerieEquip: string;
procedure SetNumSerieEquip(const Valor: string);
function GetNumSequencial: Integer;
procedure SetNumSequencial(const Valor: Integer);
function GetModDocFiscal: TModDocumento;
procedure SetModDocFiscal(const Valor: TModDocumento);
function GetCOOInicial: Integer;
procedure SetCOOInicial(const Valor: Integer);
function GetCOOFinal: Integer;
procedure SetCOOFinal(const Valor: Integer);
function GetContReducaoZ: Integer;
procedure SetContReducaoZ(const Valor: Integer);
function GetContReinicioOper: Integer;
procedure SetContReinicioOper(const Valor: Integer);
function GetVendaBruta: Currency;
procedure SetVendaBruta(const Valor: Currency);
function GetGTFinal: Currency;
procedure SetGTFinal(const Valor: Currency);
function GetAliquotas: ISintegra_Reg60A_Lista;
procedure SetAliquotas(const Valor: ISintegra_Reg60A_Lista);
property DataEmissao: TDate read GetDataEmissao write SetDataEmissao;
property NumSerieEquip: string read GetNumSerieEquip write SetNumSerieEquip;
property NumSequencial: Integer read GetNumSequencial write SetNumSequencial;
property ModDocFiscal: TModDocumento read GetModDocFiscal write SetModDocFiscal;
property COOInicial: Integer read GetCOOInicial write SetCOOInicial;
property COOFinal: Integer read GetCOOFinal write SetCOOFinal;
property ContReducaoZ: Integer read GetContReducaoZ write SetContReducaoZ;
property ContReinicioOper: Integer read GetContReinicioOper write SetContReinicioOper;
property VendaBruta: Currency read GetVendaBruta write SetVendaBruta;
property GTFinal: Currency read GetGTFinal write SetGTFinal;
property Registro60A: ISintegra_Reg60A_Lista read GetAliquotas write SetAliquotas;
end;
ISintegra_Reg60M_Lista = interface(IInterface)
['{5497071C-DC2B-4E69-90FB-354C041EB46F}']
function GetItem(Index: Integer): ISintegra_Reg60M_unico;
procedure SetItem(Index: Integer; const Value: ISintegra_Reg60M_unico);
function Add: ISintegra_Reg60M_unico;
procedure Delete(Index: integer);
function Count: Integer;
procedure Clear;
property Items[Index: Integer]: ISintegra_Reg60M_unico read GetItem write SetItem;
end;
TSintegraObject = class(TPersistent, IInterface)
private
fContador: Integer;
fOwner: TObject;
protected
function QueryInterface(const IID: TGUID; out Obj): HResult; virtual; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
public
constructor Create(aOwner: TObject);
property Owner: TObject read fOwner;
end;
TSintegraEmpresa = class(TSintegraObject)
private
FempRazaoSocial: string[35];
FempCNPJ: string[14];
FempInscEstadual: string[14];
FempMunicipio: string[30];
FempUF: string[2];
FempFax: string[10];
FempResponsavel: string[28];
FempEndereco: string[34];
FempComplemento: string[22];
FempNumero: 0..99999;
FempBairro: string[15];
FempCEP: string[8];
FempFone: string[12];
FContribuinteIPI: Boolean;
FSubstitutoTributario: Boolean;
function GetempRazaoSocial: string;
procedure SetempRazaoSocial(const Valor: string);
function GetempCNPJ: string;
procedure SetempCNPJ(const Valor: string);
function GetempInscEstadual: string;
procedure SetempInscEstadual(const Valor: string);
function GetempMunicipio: string;
procedure SetempMunicipio(const Valor: string);
function GetempUF: string;
procedure SetempUF(const Valor: string);
function GetempFax: string;
procedure SetempFax(const Valor: string);
function GetempResponsavel: string;
procedure SetempResponsavel(const Valor: string);
function GetempEndereco: string;
procedure SetempEndereco(const Valor: string);
function GetempComplemento: string;
procedure SetempComplemento(const Valor: string);
function GetempNumero: Integer;
procedure SetempNumero(const Valor: Integer);
function GetempBairro: string;
procedure SetempBairro(const Valor: string);
function GetempCEP: string;
procedure SetempCEP(const Valor: string);
function GetempFone: string;
procedure SetempFone(const Valor: string);
function GetempContribuinteIPI: Boolean;
procedure SetempContribuinteIPI(const Valor: Boolean);
function GetempSubstitutoTributario: Boolean;
procedure SetempSubstitutoTributario(const Valor: Boolean);
published
property RazaoSocial: string read GetempRazaoSocial write SetempRazaoSocial;
property CNPJ: string read GetempCNPJ write SetempCNPJ;
property InscEstadual: string read GetempInscEstadual write SetempInscEstadual;
property Endereco: string read GetempEndereco write SetempEndereco;
property Complemento: string read GetempComplemento write SetempComplemento;
property Numero: Integer read GetempNumero write SetempNumero default 0;
property Bairro: string read GetempBairro write SetempBairro;
property Municipio: string read GetempMunicipio write SetempMunicipio;
property CEP: string read GetempCEP write SetempCEP;
property UF: string read GetempUF write SetempUF;
property Fax: string read GetempFax write SetempFax;
property Fone: string read GetempFone write SetempFone;
property Responsavel: string read GetempResponsavel write SetempResponsavel;
property ContribuinteIPI: Boolean read GetempContribuinteIPI write SetempContribuinteIPI default False;
property SubstitutoTributario: Boolean read GetempSubstitutoTributario write SetempSubstitutoTributario default False;
end;
TSintegra = class(TComponent)
private
FValidacaoOK: Boolean;
FOnErro: TEventoErro;
fDataInicial: TDate;
fDataFinal: TDate;
fNaturezaOperacao: TCodIdentificaOper;
fFinalidade: TCodFinalidade;
fEmpresa: TSintegraEmpresa;
fRegistro60: ISintegra_Reg60M_Lista;
fRegistro60R: ISintegra_Reg60R_Lista;
function GetDataInicial: TDate;
procedure SetDataInicial(const Valor: TDate);
function GetDataFinal: TDate;
procedure SetDataFinal(const Valor: TDate);
function GetNaturezaOperacao: TCodIdentificaOper;
procedure SetNaturezaOperacao(const Valor: TCodIdentificaOper);
function GetFinalidade: TCodFinalidade;
procedure SetFinalidade(const Valor: TCodFinalidade);
function GetEmpresa: TSintegraEmpresa;
procedure SetEmpresa(const Valor: TSintegraEmpresa);
function GetRegistro60: ISintegra_Reg60M_Lista;
procedure SetRegistro60(const Valor: ISintegra_Reg60M_Lista);
function GetResumoMensal60: ISintegra_Reg60R_Lista;
procedure SetResumoMensal60(const Valor: ISintegra_Reg60R_Lista);
function GerarCabecalho: String;
function GerarRegistro60: String;
function GerarRegistro90: String;
function VerificarProdutoCorrespondente(aProduto: string): Boolean;
function ProcurarProduto(aProduto: string): Boolean;
function GetOnErro: TEventoErro;
procedure SetOnErro(const Value: TEventoErro);
procedure GerarErro(aErro: string);
public
constructor Create(AOwner: TComponent); override;
procedure LimparRegistros;
function GerarArquivo(aArquivo: string; aConfirma: Boolean = True): Boolean;
published
property OnErro: TEventoErro read GetOnErro write SetOnErro;
property DataInicial: TDate read GetDataInicial write SetDataInicial;
property DataFinal: TDate read GetDataFinal write SetDataFinal;
property NaturezaOperacao: TCodIdentificaOper read GetNaturezaOperacao write SetNaturezaOperacao default opeTotal;
property Finalidade: TCodFinalidade read GetFinalidade write SetFinalidade default finNormal;
property Empresa: TSintegraEmpresa read GetEmpresa write SetEmpresa;
property Registro60: ISintegra_Reg60M_Lista read GetRegistro60 write SetRegistro60;
property Registro60R: ISintegra_Reg60R_Lista read GetResumoMensal60 write SetResumoMensal60;
end;
procedure Register;
implementation
uses Registro60, Funcoes;
procedure Register;
begin
RegisterComponents('Sintegra', [TSintegra]);
end;
{ TSintegraObject }
function TSintegraObject._AddRef: Integer;
begin
Inc(fContador);
Result := fContador;
end;
function TSintegraObject._Release: Integer;
begin
Dec(fContador);
Result := fContador;
end;
constructor TSintegraObject.Create(aOwner: TObject);
begin
fContador := 0;
fOwner := aOwner;
end;
function TSintegraObject.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
if GetInterface(IID, Obj) then
Result := 0
else
Result := E_NOINTERFACE;
end;
{ TSintegraEmpresa }
function TSintegraEmpresa.GetempRazaoSocial: string;
begin
Result := FempRazaoSocial;
end;
procedure TSintegraEmpresa.SetempRazaoSocial(const Valor: string);
begin
FempRazaoSocial := Valor;
end;
function TSintegraEmpresa.GetempCNPJ: string;
begin
Result := FempCNPJ;
end;
procedure TSintegraEmpresa.SetempCNPJ(const Valor: string);
begin
FempCNPJ := Valor;
end;
function TSintegraEmpresa.GetempInscEstadual: string;
begin
Result := FempInscEstadual;
end;
procedure TSintegraEmpresa.SetempInscEstadual(const Valor: string);
begin
FempInscEstadual := Valor;
end;
function TSintegraEmpresa.GetempMunicipio: string;
begin
Result := FempMunicipio;
end;
procedure TSintegraEmpresa.SetempMunicipio(const Valor: string);
begin
FempMunicipio := Valor;
end;
function TSintegraEmpresa.GetempUF: string;
begin
Result := FempUF;
end;
procedure TSintegraEmpresa.SetempUF(const Valor: string);
begin
FempUF := UpperCase(Valor);
end;
function TSintegraEmpresa.GetempFax: string;
begin
Result := FempFax;
end;
procedure TSintegraEmpresa.SetempFax(const Valor: string);
begin
FempFax := Valor;
end;
function TSintegraEmpresa.GetempResponsavel: string;
begin
Result := FempResponsavel;
end;
procedure TSintegraEmpresa.SetempResponsavel(const Valor: string);
begin
FempResponsavel := Valor;
end;
function TSintegraEmpresa.GetempEndereco: string;
begin
Result := FempEndereco;
end;
procedure TSintegraEmpresa.SetempEndereco(const Valor: string);
begin
FempEndereco := Valor;
end;
function TSintegraEmpresa.GetempComplemento: string;
begin
Result := FempComplemento;
end;
procedure TSintegraEmpresa.SetempComplemento(const Valor: string);
begin
FempComplemento := Valor;
end;
function TSintegraEmpresa.GetempNumero: Integer;
begin
Result := FempNumero;
end;
procedure TSintegraEmpresa.SetempNumero(const Valor: Integer);
begin
FempNumero := Valor;
end;
function TSintegraEmpresa.GetempBairro: string;
begin
Result := FempBairro;
end;
procedure TSintegraEmpresa.SetempBairro(const Valor: string);
begin
FempBairro := Valor;
end;
function TSintegraEmpresa.GetempCEP: string;
begin
Result := FempCEP;
end;
procedure TSintegraEmpresa.SetempCEP(const Valor: string);
begin
FempCEP := Valor;
end;
function TSintegraEmpresa.GetempFone: string;
begin
Result := FempFone;
end;
procedure TSintegraEmpresa.SetempFone(const Valor: string);
begin
FempFone := Valor;
end;
function TSintegraEmpresa.GetempContribuinteIPI: Boolean;
begin
Result := FContribuinteIPI;
end;
procedure TSintegraEmpresa.SetempContribuinteIPI(const Valor: Boolean);
begin
FContribuinteIPI := Valor
end;
function TSintegraEmpresa.GetempSubstitutoTributario: Boolean;
begin
Result := FSubstitutoTributario
end;
procedure TSintegraEmpresa.SetempSubstitutoTributario(const Valor: Boolean);
begin
FSubstitutoTributario := Valor;
end;
{ TSintegra }
constructor TSintegra.Create;
begin
inherited;
FValidacaoOK := True;
fDataInicial := 0;
fDataFinal := 0;
fEmpresa := TSintegraEmpresa.Create(Self);
fRegistro60 := TSintegraReg60M_Lista.Create(Self);
fRegistro60R := TSintegraReg60R_Lista.Create(Self);
end;
function TSintegra.GetDataInicial: TDate;
begin
Result := fDataInicial;
end;
procedure TSintegra.SetDataInicial(const Valor: TDate);
begin
fDataInicial := Valor;
end;
function TSintegra.GetDataFinal: TDate;
begin
Result := fDataFinal;
end;
procedure TSintegra.SetDataFinal(const Valor: TDate);
begin
fDataFinal := Valor;
end;
function TSintegra.GetNaturezaOperacao: TCodIdentificaOper;
begin
Result := fNaturezaOperacao;
end;
procedure TSintegra.SetNaturezaOperacao(const Valor: TCodIdentificaOper);
begin
fNaturezaOperacao := Valor;
end;
function TSintegra.GetFinalidade: TCodFinalidade;
begin
Result := fFinalidade;
end;
procedure TSintegra.SetFinalidade(const Valor: TCodFinalidade);
begin
fFinalidade := Valor;
end;
function TSintegra.GetEmpresa: TSintegraEmpresa;
begin
Result := fEmpresa;
end;
procedure TSintegra.SetEmpresa(const Valor: TSintegraEmpresa);
begin
fEmpresa := Valor;
end;
function TSintegra.GetRegistro60: ISintegra_Reg60M_Lista;
begin
Result := fRegistro60;
end;
procedure TSintegra.SetRegistro60(const Valor: ISintegra_Reg60M_Lista);
begin
fRegistro60 := Valor;
end;
function TSintegra.GetResumoMensal60: ISintegra_Reg60R_Lista;
begin
Result := fRegistro60R;
end;
procedure TSintegra.SetResumoMensal60(const Valor: ISintegra_Reg60R_Lista);
begin
fRegistro60R := Valor;
end;
function TSintegra.ProcurarProduto(aProduto: string): Boolean;
var
i: integer;
Encontrado: Boolean;
begin
{Verifica se o produto existe no Registro 75 }
i := 0;
Encontrado := False;
{while (not Encontrado) and (i < Registro75.Count) do
begin
Encontrado := Registro75.Items[i].CodProduto = aProduto;
inc(i, 1);
end;}
Result := Encontrado;
end;
function TSintegra.VerificarProdutoCorrespondente(aProduto: string): Boolean;
var
i, a: Integer;
Encontrado: Boolean;
begin
{*****************************************************************************
- O registro 75 deve ter algum correspondente nos registros
54, 60D, 60I, 60R, 74, 77
*****************************************************************************}
Encontrado := False;
if Assigned(Registro60) and (not Encontrado) then
begin
i := 0;
while (not Encontrado) and (i < Registro60.Count) do
begin
{ Registro 60D }
{ if Assigned(Registro60.Items[i].Registro60D) then
begin
a := 0;
while (not Encontrado) and (a < Registro60.Items[i].Registro60D.Count) do
begin
Encontrado := Registro60.Items[i].Registro60D.Items[a].CodProduto = aProduto;
inc(a);
end;
end; }
inc(i);
end;
end;
{ Registro 60R }
if Assigned(Registro60R) and (not Encontrado) then
begin
i := 0;
while (not Encontrado) and (i < Registro60R.Count) do
begin
Encontrado := Registro60R.Items[i].CodProduto = aProduto;
inc(i);
end;
end;
Result := Encontrado;
end;
function TSintegra.GetOnErro: TEventoErro;
begin
Result := FOnErro;
end;
procedure TSintegra.SetOnErro(const Value: TEventoErro);
begin
FOnErro := Value;
end;
procedure TSintegra.LimparRegistros;
begin
Registro60.Clear;
Registro60R.Clear;
end;
{ Cabecalho do arquivo referente aos dados da empresa }
function TSintegra.GerarCabecalho: string;
var
aComplemento: string;
Ano, Mes, Dia: Word;
begin
if DataInicial = 0 then
GerarErro('Geração: Informe a Data Inicial do arquivo');
if Datafinal = 0 then
GerarErro('Geração: Informe a Data final do arquivo');
DecodeDate(DataInicial, Ano, Mes, Dia);
if Ano < 1993 then
GerarErro('Geração: O ano da data inicial do arquivo deve ser superior a 1993');
if DataFinal > Date then
GerarErro('Registro 10: Data final não pode ser maior que a Data atual');
if Dia <> 1 then
GerarErro('Registro 10: Data inicial deve corresponder ao primeiro dia do mês informado!');
if Trim(Empresa.RazaoSocial) = '' then
GerarErro('Registro 10: Não informado: Razão Social');
if Trim(Empresa.Municipio) = '' then
GerarErro('Registro 10: Não informado: Municipio');
if Trim(Empresa.UF) = '' then
GerarErro('Registro 10: Não informado: Estado (UF)');
if Trim(Empresa.CNPJ) = '' then
GerarErro('Registro 10: Não informado: CNPJ/CPF');
if Trim(Empresa.InscEstadual) = '' then
GerarErro('Registro 10: Não informado: Inscrição Estadual');
if not (VerificarUF(Empresa.UF)) then
GerarErro(Format('Registro 10: UF "%s" digitado inválido', [Empresa.UF]))
else if not VerificarInscEstadual(Empresa.InscEstadual, Empresa.UF) then
GerarErro('Registro 10: Inscrição Estadual informada inválida');
if Empresa.Fone = '' then
GerarErro('Registro 11: Não informado: Telefone para contado');
if Empresa.CEP <> '' then
if not (VerificarCEP(Empresa.CEP, Empresa.UF)) then
GerarErro('Registro 11: CEP Informado não é válido');
if (Trim(Empresa.Complemento) = '') and (Empresa.Numero = 0) then
aComplemento := 'SEM NUMERO';
Result :=
'10' +
LFill(Empresa.CNPJ, '0', 14) +
RFill(Empresa.InscEstadual, ' ', 14) +
RFill(Empresa.RazaoSocial, ' ', 35) +
RFill(Empresa.Municipio, ' ', 30) +
Empresa.UF +
LFill(Empresa.Fax, '0', 10) +
FormatDateTime('YYYYMMDD', DataInicial) +
FormatDateTime('YYYYMMDD', DataFinal) +
'3' +
RetornarNatureza(NaturezaOperacao) +
RetornarFinalidade(Finalidade) + #13#10 +
'11' +
RFill(Empresa.Endereco, ' ', 34) +
LFill(FloatToStr(Empresa.Numero), '0', 5) +
RFill(aComplemento, ' ', 22) +
RFill(Empresa.Bairro, ' ', 15) +
LFill(Empresa.CEP, '0', 8) +
RFill(Empresa.Responsavel, ' ', 28) +
LFill(Empresa.Fone, '0', 12);
end;
{ registro do fim do arquivo }
function TSintegra.GerarRegistro90: string;
var
i, ToTReg, TotReg60: Integer;
Inicio, Linha: string;
fLista: TStringList;
procedure VerificaLinha;
begin
if Length(Linha) = 90 then
Linha := Linha + #13#10;
end;
begin
{*****************************************************************************
* A quantidade de registros 90 deve ser informada usando as 6 ultimas
posicoes do registro alinhado a direita Ex: ' 1';
* Podem ser usados 9 contadores por registro 90 sendo 2 posicoes
para o codigo do registro ex: 50, 54, etc e 8 posicoes para a quantidade
de registros;
* o contador 99 deve informar a quantidade total incluindo
os registros 10, 11, e 90 e deve ser informado somente no
ultimo registro 90 caso haja mais de um registro 90;
*****************************************************************************}
flista := TStringList.Create;
ToTReg := 3;
TotReg60 := 0;
Inicio := '90' +
LFill(Empresa.CNPJ, '0', 14) +
RFill(Empresa.InscEstadual, ' ', 14);
// total de registros 60
if (Assigned(Registro60)) and (Registro60.Count > 0) then
begin
TotReg60 := Registro60.Count;
if Assigned(Registro60R) and (Registro60R.Count > 0) then
TotReg60 := TotReg60 + Registro60R.Count;
for i := 0 to Registro60.Count - 1 do
begin
if Assigned(Registro60.Items[i].Registro60A) then
TotReg60 := TotReg60 + Registro60.Items[i].Registro60A.Count;
{ if Assigned(Registro60.Items[i].Registro60D) then
TotReg60 := TotReg60 + Registro60.Items[i].Registro60D.Count;
if Assigned(Registro60.Items[i].Registro60I) then
TotReg60 := TotReg60 + Registro60.Items[i].Registro60I.Count; }
end;
end;
TotReg := TotReg + TotReg60;
if TotReg60 > 0 then
begin
Linha := Linha + FormatFloat('"60"00000000', TotReg60);
VerificaLinha;
end;
Linha := Linha + FormatFloat('"99"00000000', ToTReg);
fLista.Add(Linha);
Linha := '';
for i := 0 to fLista.Count - 1 do
begin
if Length(fLista.Strings[i]) = 90 then
begin
Linha := Linha + Inicio +
fLista.Strings[i] +
FormatFloat('000000', fLista.Count) + #13#10;
end
else
begin
Linha := Linha + Inicio +
RFill(fLista.Strings[i], ' ', 90) +
FormatFloat('000000', fLista.Count);
end;
end;
fLista.Free;
Result := Trim(Linha);
end;
function TSintegra.GerarRegistro60: string;
var
aRegistro: TStringList;
iReg60, a: Integer;
dDataResumo: TDate;
begin
aRegistro := TStringList.Create;
for iReg60 := 0 to Registro60.Count - 1 do
begin
// Verifica se o valor informado no 60M e difrente da soma dos 60A
// ***Retirado***
//if Registro60.Items[iReg60].VendaBruta <> Registro60.Items[iReg60].Registro60A.Total then
// GerarErro('Registro 60A: Valor acumulado difere da somas das aliquotas informadas!');
// Verifica se o valor informado no 60M e difrente da soma dos 60D
// Somente quando for gerar o resumo diario 60D
{if Registro60.Items[iReg60].Registro60D.Count > 0 then
if Registro60.Items[iReg60].VendaBruta <> Registro60.Items[iReg60].Registro60D.TotalAcumulado then
GerarErro('Registro60D: Valor acumulado difere da somas dos resumos informados!'); }
aRegistro.Add('60M' +
FormatDateTime('yyyymmdd', Registro60.Items[iReg60].DataEmissao) +
RFill(Registro60.Items[iReg60].NumSerieEquip, ' ', 20) +
FormatFloat('000', Registro60.Items[iReg60].NumSequencial) +
RetornarModDocumento(Registro60.Items[iReg60].ModDocFiscal) +
FormatFloat('000000', Registro60.Items[iReg60].COOInicial) +
FormatFloat('000000', Registro60.Items[iReg60].COOFinal) +
FormatFloat('000000', Registro60.Items[iReg60].ContReducaoZ) +
FormatFloat('000', Registro60.Items[iReg60].ContReinicioOper) +
LFill(FormatFloat('#0', Trunc(Registro60.Items[iReg60].VendaBruta * 100)), '0', 16) +
LFill(FormatFloat('#0', Trunc(Registro60.Items[iReg60].GTFinal * 100)), '0', 16) +
StringOfChar(' ', 37)
);
// obrigatorio quando se gera o registro 60M
for a := 0 to Registro60.Items[iReg60].Registro60A.Count - 1 do
begin
aRegistro.Add('60A' +
FormatDateTime('yyyymmdd', Registro60.Items[iReg60].DataEmissao) +
RFill(Registro60.Items[iReg60].NumSerieEquip, ' ', 20) +
RFill(Registro60.Items[iReg60].Registro60A.Items[a].SitTributaria, ' ', 4) +
LFill(FormatFloat('#0', Trunc(Registro60.Items[iReg60].Registro60A.Items[a].ValorAcumulado * 100)), '0', 12) +
StringOfChar(' ', 79)
);
end;
end;
// Registro 60R Opcional (depende de legislacao da UF)
if (Assigned(Registro60R)) and (Registro60R.Count > 0) then
begin
{if (not (Assigned(Registro75))) or (Registro75.Count = 0) then
GerarErro('Registro 75: Nenhum registro 75 foi assinalado!'); }
for a := 0 to Registro60R.Count - 1 do
begin
dDataResumo := StrToDate('01/' + IntTosTr(Registro60R.Items[a].Mes) + '/' + IntTosTr(Registro60R.Items[a].Ano));
if (dDataResumo < DataInicial) or (dDataResumo > DataFinal) then
GerarErro(Format('Registro 60R: Mês/Ano "%s" fora do período informado "%s à %s"!', [FormatDateTime('mm/yyyy', dDataResumo), DateToStr(DataInicial), DateToStr(DataFinal)]));
// Verifica se o produto esta cadastrado no registro 75
// ***Retirado***
//if not (ProcurarProduto(Registro60R.Items[a].CodProduto)) then
// GerarErro(Format('Registro 60R: Produto "%s" não assinalado no registro 75!', [Registro60R.Items[a].CodProduto]));
aRegistro.Add('60R' +
FormatFloat('00', Registro60R.Items[a].Mes) +
FormatFloat('0000', Registro60R.Items[a].ANo) +
RFill(Registro60R.Items[a].CodProduto, ' ', 14) +
LFill(FormatFloat('#0', Trunc(Registro60R.Items[a].Quantidade * 1000)), '0', 13) +
LFill(FormatFloat('#0', Trunc(Registro60R.Items[a].ValorAcumProduto * 100)), '0', 16) +
LFill(FormatFloat('#0', Trunc(Registro60R.Items[a].ValorAcumICMS * 100)), '0', 16) +
RFill(Registro60R.Items[a].SitTributaria, ' ', 4) +
StringOfChar(' ', 54)
);
end;
end;
Result := aRegistro.Text;
Result := Copy(Result, 0, Length(Result) - 2);
FreeAndNil(aRegistro);
end;
procedure TSintegra.GerarErro(aErro: string);
begin
FOnErro(aErro);
FValidacaoOK := False;
end;
function TSintegra.GerarArquivo(aArquivo: string; aConfirma: Boolean = True): Boolean;
var
Arquivo: TStringList;
sLinha: String;
begin
FValidacaoOK := True;
{ Verifica se o nome do arquivo foi passado }
if Trim(aArquivo) = '' then
raise ESintegraException.Create('Informe o nome do arquivo a ser gerado!');
{ Criacao do arquivo }
try
Arquivo := TStringList.Create;
Arquivo.Add(GerarCabecalho);
sLinha := GerarRegistro60;
if Trim(sLinha) <> '' then
Arquivo.Add(sLinha);
{ Geração do Fim do arquivo }
Arquivo.Add(GerarRegistro90);
if (Arquivo.Count > 0) and (FValidacaoOK) then
Arquivo.SaveToFile(aArquivo);
Result := FValidacaoOK;
FreeAndNil(Arquivo);
except
on E: Exception do
begin
Result := False;
Application.MessageBox(PAnsiChar(E.Message), 'Criação do arquivo', MB_ICONERROR + MB_OK);
end;
end;
end;
end.
|
{
Lua4Lazarus Sample1: User Define Object.
}
unit sample1_Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, db, dbf, Forms, StdCtrls;
type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
Dbf1: TDbf;
Memo1: TMemo;
Memo2: TMemo;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
Form1: TForm1;
implementation
uses
Lua54, l4l_object, l4l_strings, l4l_myutils;
{$R *.lfm}
type
{ TLuaDbf }
TLuaDbf = class(TLuaObject)
private
function GetActive: boolean;
procedure SetActive(const AValue: boolean);
function GetEof: boolean;
protected
public
constructor Create(L : Plua_State); override;
destructor Destroy; override;
published
function l4l_Next: integer;
function l4l_FieldByName: integer;
property l4l_Active: boolean read GetActive write SetActive;
property l4l_eof: boolean read GetEof;
end;
function CreateDbfObject(L : Plua_State) : Integer; cdecl;
begin
l4l_PushLuaObject(TLuaDbf.Create(L));
Result := 1;
end;
{ TForm1 }
procedure TForm1.FormCreate(Sender: TObject);
begin
dbf1.FilePath := 'db/'; // \lazarus\components\lazreport\samples\editor\db
dbf1.TableName := 'disco.dbf';
end;
function print_func(L : Plua_State) : Integer; cdecl;
var
i, c: integer;
begin
c:= lua_gettop(L);
for i:= 1 to c do
Form1.Memo2.Lines.Add(lua_tostring(L, i));
Form1.Memo2.SelStart:= 0;
Form1.Memo2.SelLength:= 0;
Result := 0;
end;
function Alloc({%H-}ud, ptr: Pointer; {%H-}osize, nsize: size_t) : Pointer; cdecl;
begin
try
Result:= ptr;
ReallocMem(Result, nSize);
except
Result:= nil;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
L: Plua_State;
s: string;
begin
Memo2.Clear;
L:= lua_newstate(@alloc, nil);
try
luaL_openlibs(L);
lua_register(L, 'print', @print_func);
lua_register(L, 'CreateStringsObject', @CreateStringsObject);
lua_register(L, 'CreateDbfObject', @CreateDbfObject);
//l4l_PushLuaObject(TLuaDbf.Create(L)); lua_setglobal(L, 'dbf'); // set global value.
l4l_PushLuaObject(TLuaMyUtilsObject.Create(L)); lua_setglobal(L, 'MyUtils'); // set global value.
try
s:= Memo1.Text;
if luaL_loadbuffer(L, PChar(s), Length(s), 'sample1') <> 0 then
Raise Exception.Create('');
if lua_pcall(L, 0, 0, 0) <> 0 then
Raise Exception.Create('');
except
Form1.Memo2.Lines.Add(lua_tostring(L, -1));
Form1.Memo2.SelStart:= 0;
Form1.Memo2.SelLength:= 0;
end;
finally
lua_close(L);
end;
end;
{ TLuaDbf }
constructor TLuaDbf.Create(L: Plua_State);
begin
inherited Create(L);
Form1.Dbf1.Close;
end;
destructor TLuaDbf.Destroy;
begin
Form1.Dbf1.Close;
inherited Destroy;
end;
function TLuaDbf.l4l_Next: integer;
begin
Form1.Dbf1.Next;
Result := 0;
end;
function TLuaDbf.l4l_FieldByName: integer;
var
s: string;
f: TField;
begin
s:= lua_tostring(LS, 1);
f:= Form1.Dbf1.FieldByName(s);
case f.DataType of
ftSmallint, ftInteger, ftWord: lua_pushinteger(LS, f.AsInteger);
ftFloat: lua_pushnumber(LS, f.AsFloat);
ftBoolean: lua_pushboolean(LS, f.AsBoolean);
else
lua_pushstring(LS, f.AsString);
end;
Result := 1;
end;
function TLuaDbf.GetActive: boolean;
begin
Result:=Form1.Dbf1.Active;
end;
procedure TLuaDbf.SetActive(const AValue: boolean);
begin
Form1.Dbf1.Active:=AValue;
end;
function TLuaDbf.GetEof: boolean;
begin
Result:=Form1.Dbf1.EOF;
end;
end.
|
unit ProcessQueue;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
IBX.IBDatabase, ExtCtrls, IBX.IBQuery;
type
TQueueEvent = procedure(Sender: TObject; Process: integer; Params: string) of object;
TEventPriority = integer;
TEventProcess = integer;
TEventSpecific = char;
type
TProcessQueue = class(TComponent)
private
FRestartDelay: integer;
FInterbaseDB: TIBDatabase;
FActive: boolean;
FEventRunning: boolean;
FOnQueueEvent: TQueueEvent;
CheckTimer: TTimer;
IBT_Queue: TIBTransaction;
IBQ_Select: TIBQuery;
IBQ_Write: TIBQuery;
procedure SetActive(value: boolean);
function NextEvent: boolean;
procedure SetInterbaseDB(value: TIBDatabase);
procedure CheckTimerTimer(Sender: TObject);
procedure SetRestartDelay(value: integer);
{ Private-Deklarationen }
protected
{ Protected-Deklarationen }
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AddEvent(EventPriority: TEventPriority; EventProcess: TEventProcess; EventSpecific: TEventSpecific;
EventParams: string);
function CheckEvent(EventProcess: TEventProcess): integer;
function GetTopEvent(var EventID: integer; var EventProcess: TEventProcess; var EventParams: string): boolean;
function GetEventByID(EventID: integer; var EventPriority: TEventPriority; var EventProcess: TEventProcess;
var EventParams: string): boolean;
procedure DelEvent(EventID: integer);
function EventsLeft: integer;
procedure ClearQueue;
procedure ValidateQueue;
procedure Check;
function PriorityNow: TEventSpecific;
property EventRunning: boolean read FEventRunning;
{ Public-Deklarationen }
published
property InterbaseDB: TIBDatabase read FInterbaseDB write SetInterbaseDB;
property Active: boolean read FActive write SetActive default false;
property RestartDelay: integer read FRestartDelay write SetRestartDelay;
property OnQeueEvent: TQueueEvent read FOnQueueEvent write FOnQueueEvent;
{ Published-Deklarationen }
end;
const
prWaitForNone = 99;
prUltraHigh = 90;
prVeryHigh = 60;
prHigh = 50;
prStandard = 40;
prLow = 30;
prVeryLow = 10;
prWaitForAll = 1;
spNight = 'N';
spDay = 'D';
spAnytime = 'A';
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('ASS', [TProcessQueue]);
end;
constructor TProcessQueue.Create(AOwner: TComponent);
begin
inherited;
IBT_Queue := TIBTransaction.Create(self);
IBQ_Select := TIBQuery.Create(self);
IBQ_Write := TIBQuery.Create(self);
CheckTimer := TTimer.Create(self);
IBT_Queue.DefaultDatabase := FInterbaseDB;
IBQ_Write.Database := FInterbaseDB;
IBQ_Write.Transaction := IBT_Queue;
IBQ_Select.Database := FInterbaseDB;
IBQ_Select.Transaction := IBT_Queue;
CheckTimer.Interval := 1000;
//CheckTimer.Enabled := FActive;
CheckTimer.Enabled := true;
CheckTimer.OnTimer := CheckTimerTimer;
end;
destructor TProcessQueue.Destroy;
begin
IBQ_Write.Free;
IBQ_Select.Free;
IBT_Queue.Free;
CheckTimer.Free;
inherited;
end;
procedure TProcessQueue.CheckTimerTimer(Sender: TObject);
begin
if not FActive then
exit;
CheckTimer.Enabled := false;
try
CheckTimer.Tag := CheckTimer.Tag + 1;
// In der Funktion NextEvent wird die Anforderung auch ausgeführt
if NextEvent then
CheckTimer.Interval := 10
else
CheckTimer.Interval := FRestartDelay;
if CheckTimer.Tag > ((6 * 3600 * 1000) div FRestartDelay) then
ValidateQueue;
finally
CheckTimer.Enabled := Active;
end;
end;
procedure TProcessQueue.SetRestartDelay(value: integer);
begin
//CheckTimer.Enabled := false;
CheckTimer.Interval := value;
//CheckTimer.Enabled := FActive;
FRestartDelay := value;
end;
procedure TProcessQueue.SetInterbaseDB(value: TIBDatabase);
begin
IBT_Queue.DefaultDatabase := value;
IBQ_Select.Database := value;
IBQ_Select.Transaction := IBT_Queue;
IBQ_Write.Database := value;
IBQ_Write.Transaction := IBT_Queue;
FInterbaseDB := value;
end;
procedure TProcessQueue.SetActive(value: boolean);
begin
//CheckTimer.Enabled := value;
FActive := value;
end;
function TProcessQueue.NextEvent: boolean;
var
ID: integer;
Process: integer;
Params: string;
begin
// Gibt zurück, ob es noch weitere Events gibt
result := false;
FEventRunning := true;
try
if Assigned(FOnQueueEvent) then
begin
if not(self.ComponentState = [csDesigning]) then
begin
// VAR-Parameter für GetTopEvent
ID := 0;
Process := 0;
Params := '';
result := GetTopEvent(ID, Process, Params);
if Process <> 0 then
begin
FOnQueueEvent(self, Process, Params);
end;
if ID > 0 then
DelEvent(ID);
end;
end;
finally
FEventRunning := false;
end;
end;
procedure TProcessQueue.AddEvent(EventPriority: TEventPriority; EventProcess: TEventProcess;
EventSpecific: TEventSpecific; EventParams: string);
begin
if CheckEvent(EventProcess) <> 0 then
begin
exit;
end;
IBT_Queue.StartTransaction;
IBQ_Write.SQL.Clear;
IBQ_Write.SQL.Add('INSERT INTO PROCESSQUEUE (');
IBQ_Write.SQL.Add('PQ_ID, PQ_PRIORITY, PQ_TIME, PQ_PROCESS, PQ_SPECIFIC, PQ_PARAMS');
IBQ_Write.SQL.Add(') VALUES (');
IBQ_Write.SQL.Add('GEN_ID(PQ_ID,1), :PQ_PRIORITY, "NOW", :PQ_PROCESS, :PQ_SPECIFIC, :PQ_PARAMS');
IBQ_Write.SQL.Add(')');
IBQ_Write.ParamByName('PQ_PRIORITY').AsInteger := EventPriority;
IBQ_Write.ParamByName('PQ_PROCESS').AsInteger := EventProcess;
IBQ_Write.ParamByName('PQ_SPECIFIC').AsString := EventSpecific;
IBQ_Write.ParamByName('PQ_PARAMS').AsString := EventParams;
IBQ_Write.ExecSQL;
IBT_Queue.Commit;
end;
procedure TProcessQueue.Check;
begin
CheckTimerTimer(self);
end;
function TProcessQueue.CheckEvent(EventProcess: TEventProcess): integer;
begin
result := 0;
IBT_Queue.StartTransaction;
IBQ_Select.SQL.Clear;
IBQ_Select.SQL.Add
('SELECT * FROM PROCESSQUEUE WHERE PQ_PROCESS = :PQ_PROCESS ORDER BY PQ_PRIORITY DESCENDING, PQ_TIME');
IBQ_Select.ParamByName('PQ_PROCESS').AsInteger := EventProcess;
IBQ_Select.Open;
if not IBQ_Select.Eof then
result := IBQ_Select.FieldByName('PQ_ID').AsInteger;
IBQ_Select.Close;
IBT_Queue.Commit;
end;
function TProcessQueue.GetTopEvent(var EventID: integer; var EventProcess: TEventProcess;
var EventParams: string): boolean;
begin
// Gibt zurück ob es noch weitere gibt
IBT_Queue.StartTransaction;
IBQ_Select.SQL.Clear;
IBQ_Select.SQL.Add('SELECT FIRST 2 * FROM PROCESSQUEUE');
IBQ_Select.SQL.Add('WHERE PQ_SPECIFIC = "' + PriorityNow + '"');
IBQ_Select.SQL.Add('OR PQ_SPECIFIC = "A"');
IBQ_Select.SQL.Add('ORDER BY PQ_PRIORITY DESCENDING, PQ_TIME, PQ_ID');
IBQ_Select.Open;
IBQ_Select.FetchAll;
EventID := IBQ_Select.FieldByName('PQ_ID').AsInteger;
EventProcess := IBQ_Select.FieldByName('PQ_PROCESS').AsInteger;
EventParams := IBQ_Select.FieldByName('PQ_PARAMS').AsString;
result := IBQ_Select.RecordCount > 1;
IBQ_Select.Close;
IBT_Queue.Commit;
end;
function TProcessQueue.GetEventByID(EventID: integer; var EventPriority: TEventPriority;
var EventProcess: TEventProcess; var EventParams: string): boolean;
begin
IBT_Queue.StartTransaction;
IBQ_Select.SQL.Clear;
IBQ_Select.SQL.Add('SELECT * FROM PROCESSQUEUE WHERE PQ_ID = :PQ_ID');
IBQ_Select.ParamByName('PQ_ID').AsInteger := EventID;
IBQ_Select.Open;
if not IBQ_Select.Eof then
begin
result := true;
EventPriority := IBQ_Select.FieldByName('PQ_PRIORITY').AsInteger;
EventProcess := IBQ_Select.FieldByName('PQ_PROCESS').AsInteger;
EventParams := IBQ_Select.FieldByName('PQ_PARAMS').AsString;
end
else
begin
result := false;
EventPriority := 0;
EventProcess := 0;
EventParams := '';
end;
IBQ_Select.Close;
IBT_Queue.Commit;
end;
procedure TProcessQueue.DelEvent(EventID: integer);
begin
IBT_Queue.StartTransaction;
IBQ_Write.SQL.Clear;
IBQ_Write.SQL.Add('DELETE FROM PROCESSQUEUE WHERE PQ_ID = :PQ_ID');
IBQ_Write.ParamByName('PQ_ID').AsInteger := EventID;
IBQ_Write.ExecSQL;
IBT_Queue.Commit;
end;
function TProcessQueue.EventsLeft: integer;
begin
IBT_Queue.StartTransaction;
IBQ_Select.SQL.Clear;
IBQ_Select.SQL.Add('SELECT COUNT(*) EVENTSLEFT FROM PROCESSQUEUE');
IBQ_Select.SQL.Add('WHERE PQ_SPECIFIC = "' + PriorityNow + '"');
IBQ_Select.SQL.Add('OR PQ_SPECIFIC = "A"');
IBQ_Select.Open;
result := IBQ_Select.FieldByName('EVENTSLEFT').AsInteger;
IBQ_Select.Close;
IBT_Queue.Commit;
end;
procedure TProcessQueue.ClearQueue;
begin
IBT_Queue.StartTransaction;
IBQ_Write.SQL.Clear;
IBQ_Write.SQL.Add('DELETE FROM PROCESSQUEUE');
IBQ_Write.ExecSQL;
IBT_Queue.Commit;
end;
function TProcessQueue.PriorityNow: TEventSpecific;
var
TN, TS, TE: TDateTime;
begin
TN := time;
TS := StrToTime('06:00:00');
TE := StrToTime('22:00:00');
if (TS < TN) and (TN < TE) then
result := spDay
else
result := spNight;
end;
procedure TProcessQueue.ValidateQueue;
begin
// In dieser Methode werden alle Einträge gelöscht, die älter als zwei
// Tage sind.
// Der Sinn ist mir nicht wirklich klar. Die Methode wird aufgerufen, nachdem
// Prozesse ausgeführt wurden. Sollte also immer leer sein. (abgesehen von Nacht-Prozessen)
IBT_Queue.StartTransaction;
IBQ_Write.SQL.Clear;
IBQ_Write.SQL.Add('DELETE FROM PROCESSQUEUE WHERE PQ_TIME < ("NOW" - 2)');
IBQ_Write.ExecSQL;
IBT_Queue.Commit;
end;
end.
|
UNIT TAU_GAME_MAIN;
{$MODE OBJFPC}
{$H+}
{$INCLUDE TAU_SIGNAL}
INTERFACE
USES
SDL,
SDL_IMAGE,
TETRIS_BOARD;
CONST
GAME_STATE_INGAME = 1;
GAME_STATE_PAUSE_STATETIMER = 2;
TYPE
TTauGameMain = CLASS
PRIVATE
b_ok : boolean;
b_pause : boolean;
b_gameover : boolean;
i_state : integer;
f_backgroundoffsetX : real;
f_backgroundoffsetY : real;
f_pausetimer : real;
i_pausestate : integer;
i_downpartDisapInd : integer;
i_menuoption : integer;
f_downpartDisapTimer : real;
b_drawdetails : boolean;
srf_backgroundGrid : PSDL_Surface;
srf_backgroundBoard : PSDL_Surface;
srf_backgroundOverlay: PSDL_Surface;
srf_backgroundPause0 : PSDL_Surface;
srf_backgroundPause1 : PSDL_Surface;
srf_square : PSDL_Surface;
srf_charsheet : PSDL_Surface;
srf_backgroundDetails: PSDL_Surface;
srf_blockcounter : PSDL_Surface;
board : TTetrisBoard;
pauseStringMovText : string;
pauseStringMovInd : integer;
PROCEDURE Ren_Text(str: string; x, y: integer; pwin: PSDL_Surface);
PROCEDURE ResetGame();
FUNCTION Tick_Ingame(pwin: PSDL_Surface): tausignal;
PROCEDURE Draw_Background(pwin: PSDL_Surface);
PROCEDURE Draw_Board(pwin: PSDL_Surface);
PROCEDURE Draw_Overlay(pwin: PSDL_Surface);
PROCEDURE Draw_Scoreboard(pwin: PSDL_Surface);
PROCEDURE Draw_PauseScreen(pwin: PSDL_Surface);
PROCEDURE Draw_Downpart(pwin: PSDL_Surface);
PROCEDURE Draw_Rightpart(pwin:PSDL_Surface);
PUBLIC
CONSTRUCTOR Create();
DESTRUCTOR Destroy(); OVERRIDE;
FUNCTION Tick(pwin: PSDL_Surface): tausignal;
FUNCTION IsOk(): boolean;
END;
IMPLEMENTATION
CONSTRUCTOR TTauGameMain.Create();
VAR
srf_temp: PSDL_Surface;
BEGIN
b_pause := FALSE;
b_ok := TRUE;
i_state := GAME_STATE_INGAME;
i_pausestate := 0;
i_downpartDisapInd := 1;
srf_backgroundGrid := NIL;
b_drawdetails := FALSE;
b_gameover := FALSE;
f_backgroundoffsetX := 0.0;
f_backgroundoffsetY := 0.0;
f_pausetimer := 0.0;
f_downpartDisapTimer := 0.0;
board := TTetrisBoard.Create();
srf_temp := NIL;
srf_backgroundBoard := NIL;
srf_backgroundOverlay := NIL;
srf_backgroundGrid := NIL;
srf_square := NIL;
srf_backgroundDetails := NIL;
srf_blockcounter := NIL;
pauseStringMovInd := 1;
pauseStringMovText := '$Z ';
i_menuoption := 0;
srf_temp := IMG_Load('data/tex/char/0.png');
srf_charsheet := SDL_DisplayFormat(srf_temp);
SDL_FreeSurface(srf_temp);
{ Мрежа }
srf_temp := IMG_Load('data/tex/grid.bmp');
srf_backgroundGrid := SDL_DisplayFormat(srf_temp);
SDL_FreeSurface(srf_temp);
{ Табла }
srf_temp := IMG_Load('data/tex/board.bmp');
srf_backgroundBoard := SDL_DisplayFormat(srf_temp);
SDL_FreeSurface(srf_temp);
SDL_SetAlpha(srf_backgroundBoard, SDL_SRCALPHA, $F0);
srf_temp := IMG_Load('data/tex/rect.bmp');
srf_blockcounter := SDL_DisplayFormat(srf_temp);
SDL_FreeSurface(srf_temp);
{ Прекривач }
srf_temp := IMG_Load('data/tex/overlay.png');
srf_backgroundOverlay := SDL_DisplayFormatAlpha(srf_temp);
SDL_FreeSurface(srf_temp);
srf_temp := IMG_Load('data/tex/overlay_details.png');
srf_backgroundDetails := SDL_DisplayFormatAlpha(srf_temp);
SDL_FreeSurface(srf_temp);
srf_temp := IMG_Load('data/tex/pause0.png');
srf_backgroundPause0 := SDL_DisplayFormatAlpha(srf_temp);
SDL_FreeSurface(srf_temp);
srf_temp := IMG_Load('data/tex/pause1.png');
srf_backgroundPause1 := SDL_DisplayFormatAlpha(srf_temp);
SDL_FreeSurface(srf_temp);
srf_temp := IMG_Load('data/tex/square.bmp');
srf_square := SDL_DisplayFormatAlpha(srf_temp);
SDL_FreeSurface(srf_temp);
IF ((srf_backgroundGrid = NIL) OR (srf_backgroundBoard = NIL) OR (srf_backgroundOverlay = NIL)) THEN
BEGIN
WriteLn('! data/tex/{?}');
b_ok := FALSE;
END;
END;
DESTRUCTOR TTauGameMain.Destroy();
BEGIN
board.Free();
SDL_FreeSurface(srf_backgroundDetails);
SDL_FreeSurface(srf_charsheet);
SDL_FreeSurface(srf_square);
SDL_FreeSurface(srf_backgroundOverlay);
SDL_FreeSurface(srf_backgroundBoard);
SDL_FreeSurface(srf_backgroundGrid);
SDL_FreeSurface(srf_blockcounter);
END;
PROCEDURE TTauGameMain.ResetGame();
BEGIN
board.Reset();
END;
FUNCTION TTauGameMain.Tick(pwin: PSDL_Surface): tausignal;
VAR
ts: tausignal;
BEGIN
ts := TAU_SIG_VOID;
CASE i_state OF
GAME_STATE_INGAME:
BEGIN
ts := Tick_Ingame(pwin);
END;
END;
Tick := ts;
END;
PROCEDURE TTauGameMain.Ren_Text(str: string; x, y: integer; pwin: PSDL_Surface);
VAR
i, ind: integer;
xx, yy: integer;
d, dp : TSDL_Rect;
BEGIN
xx := x;
yy := y;
i := 1;
WHILE (i <= Length(str)) DO
BEGIN
ind := Ord(str[i]);
IF (str[i] = '$') THEN
BEGIN
IF (str[i+1] = 'c') THEN
BEGIN
ind := 1;
end
ELSE IF (str[i+1] = 'C') THEN
BEGIN
ind := 0;
END
ELSE IF (str[i+1] = 's') THEN
BEGIN
ind := 17;
end
ELSE IF (str[i+1] = 'S') THEN
BEGIN
ind := 16;
END
ELSE IF (str[i+1] = 'N') THEN
BEGIN
ind := 255;
END
ELSE IF (str[i+1] = 'Z') THEN
BEGIN
ind := 254;
END
ELSE IF (str[i+1] = 'D') THEN
BEGIN
ind := 253;
END
ELSE IF (str[i+1] = 'b') THEN
BEGIN
ind := Ord('v') + 16;
END
ELSE IF (str[i+1] = 'l') THEN
BEGIN
ind := Ord('l') + 16 * 2;
END
ELSE IF (str[i+1] = 'x') THEN
BEGIN
ind := (Ord('s') + 16);
END
ELSE IF (str[i+1] = '3') THEN
BEGIN
ind := 225-16+10;
END
ELSE IF (str[i+1] = '2') THEN
BEGIN
ind := 194-16;
END
ELSE IF (str[i+1] = '1') THEN
BEGIN
ind := 193-16;
END
ELSE IF (str[i+1] = '0') THEN
BEGIN
ind := 192-16;
END;
i := i + 1;
END;
d.x := xx;
d.y := yy;
d.w := 16;
d.h := 16;
dp.x := (ind MOD 16) * 16;
dp.y := (ind DIV 16) * 16;
dp.w := 16;
dp.h := 16;
SDL_BlitSurface(srf_charsheet, @dp, pwin, @d);
xx := xx + 16;
i := i +1;
END;
END;
FUNCTION TTauGameMain.IsOk(): boolean;
BEGIN
IsOk := b_ok;
END;
FUNCTION TTauGameMain.Tick_Ingame(pwin: PSDL_Surface): tausignal;
VAR
ts: tausignal;
e: TSDL_Event;
y: integer;
srf: PSDL_Surface;
BEGIN
ts := TAU_SIG_VOID;
f_downpartDisapTimer := f_downpartDisapTimer + 0.1;
board.SpeedUp((SDL_GetKeyState(NIL)[SDLK_DOWN] <> 0));
IF (NOT b_pause) THEN
BEGIN
f_pausetimer := 0.0;
f_backgroundoffsetX := sin((SDL_GetTicks() / 23.0)/256.0) * 40.0;
f_backgroundoffsetY := cos((SDL_GetTicks() / 7.0)/256.0) * 40.0;
END
ELSE
BEGIN
f_pausetimer := f_pausetimer + 1.0;
IF (f_pausetimer > GAME_STATE_PAUSE_STATETIMER) THEN
BEGIN
f_pausetimer := 0.0;
i_pausestate := i_pausestate + 1;
IF (i_pausestate > 1) THEN
BEGIN
i_pausestate := 0;
END;
END;
SDL_Delay(32);
END;
WHILE (SDL_PollEvent(@e) <> 0) DO
BEGIN
IF (e.type_ = SDL_QUITEV) THEN
BEGIN
ts := TAU_SIG_QUIT;
END;
IF (e.type_ = SDL_KEYDOWN) THEN
BEGIN
CASE (e.key.keysym.sym) OF
SDLK_PAUSE:
BEGIN
b_pause := NOT b_pause;
END;
SDLK_F1:
BEGIN
b_drawdetails := NOT b_drawdetails;
END;
SDLK_SPACE:
BEGIN
IF (NOT b_pause) THEN
board.CurPiece_DropDown();
END;
SDLK_LEFT:
BEGIN
IF (NOT b_pause) THEN
BEGIN
board.CurPiece_MoveX(-1);
END
ELSE
BEGIN
IF (i_menuoption = 0) THEN i_menuoption := 2
ELSE IF (i_menuoption = 1) THEN i_menuoption := 0
ELSE IF (i_menuoption = 2) THEN i_menuoption := 1;
END;
END;
SDLK_RIGHT:
BEGIN
IF (NOT b_pause) THEN
board.CurPiece_MoveX(+1)
ELSE
BEGIN
IF (i_menuoption = 0) THEN i_menuoption := 1
ELSE IF (i_menuoption = 1) THEN i_menuoption := 2
ELSE IF (i_menuoption = 2) THEN i_menuoption := 0;
END;
END;
SDLK_z:
BEGIN
IF (NOT b_pause) THEN
board.Piece_Rot(0, -1);
END;
SDLK_x:
BEGIN
IF (NOT b_pause) THEN
board.Piece_Rot(0, +1);
END;
SDLK_a:
BEGIN
IF (NOT b_pause) THEN
board.Piece_Rot(1, -1);
END;
SDLK_s:
BEGIN
IF (NOT b_pause) THEN
board.Piece_Rot(1, +1);
END;
SDLK_RETURN:
BEGIN
IF (b_pause) THEN
IF (i_menuoption = 0) THEN b_pause := FALSE
ELSE IF (i_menuoption = 1) THEN ResetGame()
ELSE IF (i_menuoption = 2) THEN ts := TAU_SIG_QUIT;
END;
END;
END;
END;
IF (board.GetGameOver()) THEN
BEGIN
b_pause := TRUE;
b_gameover := TRUE;
END;
Draw_Background(pwin);
Draw_Overlay(pwin);
Draw_Scoreboard(pwin);
Draw_Board(pwin);
Draw_Rightpart(pwin);
IF( b_pause) THEN
BEGIN
srf := srf_backgroundPause0;
IF (i_pausestate = 1) THEN
BEGIN
srf := srf_backgroundPause1;
END;
SDL_BlitSurface(srf, NIL, pwin, NIL);
END;
IF (b_drawdetails) THEN
BEGIN
SDL_BlitSurface(srf_backgroundDetails, NIL, pwin, NIL);
END;
IF (NOT b_pause) THEN
BEGIN
board.Tick();
END
ELSE
BEGIN
Draw_PauseScreen(pwin);
pauseStringMovInd := pauseStringMovInd + 1;
IF (pauseStringMovInd < (Length(pauseStringMovText) + 1)) THEN
BEGIN
pauseStringMovText[pauseStringMovInd - 1] := ' ';
pauseStringMovText[pauseStringMovInd + 0] := '$';
pauseStringMovText[pauseStringMovInd + 1] := 'Z';
END
ELSE
BEGIN
pauseStringMovText[pauseStringMovInd + 0] := ' ';
pauseStringMovText[pauseStringMovInd + 1] := ' ';
pauseStringMovText[1] := '$';
pauseStringMovText[2] := 'Z';
pauseStringMovInd := 1;
END;
END;
Draw_Downpart(pwin);
Ren_Text(' TETRIS? ', 560 + 6, 0, pwin);
Ren_Text(' ', 560 + 6, 16, pwin);
IF (b_drawdetails) THEN
BEGIN
y := 0;
Ren_Text('$3$3$3$3$3$3$2$2$2$2$2$2$1$1$1$1$1 ', 0, y, pwin); y := y + 16;
Ren_Text('+------------------------------------------------+', 0, y, pwin); y := y + 16;
Ren_Text('| Igra napisana u Paskalu. |', 0, y, pwin); y := y + 16;
Ren_Text('| Autor: Aleksandar Uro$sevi$c |', 0, y, pwin); y := y + 16;
Ren_Text('| |', 0, y, pwin); y := y + 16;
Ren_Text('| Zapo$xeto u maju, zavrseno ko zna kada. |', 0, y, pwin); y := y + 16;
Ren_Text('| |', 0, y, pwin); y := y + 16;
Ren_Text('| Name$beno bilo kome. |', 0, y, pwin); y := y + 16;
Ren_Text('| Softver moxete davati kome god xelite, i |', 0, y, pwin); y := y + 16;
Ren_Text('| prijate$lima i neprijate$lima. Radite $sta god |', 0, y, pwin); y := y + 16;
Ren_Text('| xelite sa ovim softverom. |', 0, y, pwin); y := y + 16;
Ren_Text('| |', 0, y, pwin); y := y + 16;
Ren_Text('| Jedi pite sa sirom |', 0, y, pwin); y := y + 16;
Ren_Text('| Xivot je proces$D|', 0, y, pwin); y := y + 16;
Ren_Text('+------------------------------------------------+', 0, y, pwin); y := y + 16;
END;
Tick_Ingame := ts;
END;
PROCEDURE TTauGameMain.Draw_Rightpart(pwin:PSDL_Surface);
VAR
s: string;
a: arrCount;
d: TSDL_Rect;
BEGIN
a := board.GetBlockCounter();
d.x := 0;
d.y := 0;
d.w := 1;
d.h := 1;
SDL_BlitSurface(srf_blockcounter, NIL, pwin, @d);
Ren_Text ('Tetramino: ', 8, 8 + 16 * (0), pwin);
Str(a[1], s); s := s + ' '; Ren_Text (s, 8, 8 + 16 * 1, pwin);
Str(a[2], s); s := s + ' '; Ren_Text (s, 8, 8 + 16 * 2, pwin);
Str(a[3], s); s := s + ' '; Ren_Text (s, 8, 8 + 16 * 3, pwin);
Str(a[4], s); s := s + ' '; Ren_Text (s, 8, 8 + 16 * 4, pwin);
Str(a[5], s); s := s + ' '; Ren_Text (s, 8, 8 + 16 * 5, pwin);
Str(a[6], s); s := s + ' '; Ren_Text (s, 8, 8 + 16 * 6, pwin);
Str(a[7], s); s := s + ' '; Ren_Text (s, 8, 8 + 16 * 7, pwin);
END;
PROCEDURE TTauGameMain.Draw_Downpart(pwin: PSDL_Surface);
VAR
str: string;
BEGIN
str := ' Aleksandar Uro$sevi$c$N ';
IF (f_downpartDisapTimer > 0.4) THEN
BEGIN
IF (str[i_downpartDisapInd] = '$') THEN
BEGIN
i_downpartDisapInd := i_downpartDisapInd + 1;
END;
i_downpartDisapInd := i_downpartDisapInd + 1;
f_downpartDisapTimer := -0.4 - Random(2);
END;
IF (i_downpartDisapInd > Length(str)) THEN
BEGIN
i_downpartDisapInd := 1;
END;
IF (str[i_downpartDisapInd] = '$') THEN
BEGIN
Delete(str, i_downpartDisapInd, 1);
END;
str[i_downpartDisapInd] := ' ';
Ren_Text(str, 0, 600-16, pwin);
END;
PROCEDURE TTauGameMain.Draw_Scoreboard(pwin: PSDL_Surface);
VAR
d: TSDL_Rect;
s: string;
psts: playerstats;
BEGIN
d.x := (800 div 2) + ((TETRIS_BOARD_WIDTH * 32) div 2);
d.y := 16*2;
d.w := 1;
d.h := 1;
SDL_BlitSurface(srf_square, NIL, pwin, @d);
psts := board.GetPlayerstats();
Str(psts.i_lines, s);
Ren_Text('LINIJE: ' + s, d.x+16, d.y + 16, pwin);
Str(psts.i_score, s);
Ren_Text('BODOVI: ' + s, d.x+16, d.y + 32, pwin);
Ren_Text('SLEDE$CA: ', d.x+16, d.y + 128, pwin);
board.DrawReserve(pwin);
END;
PROCEDURE TTauGameMain.Draw_Board(pwin: PSDL_Surface);
VAR
d: TSDL_Rect;
BEGIN
d.x := TETRIS_BOARD_RENDER_OFFSETX;
d.y := -6;
d.w := 1;
d.h := 1;
SDL_BlitSurface(srf_backgroundBoard, NIL, pwin, @d);
board.Draw(pwin);
END;
PROCEDURE TTauGameMain.Draw_Overlay(pwin: PSDL_Surface);
VAR
d: TSDL_Rect;
BEGIN
d.x := 0;
d.y := 0;
d.w := 1;
d.h := 1;
SDL_BlitSurface(srf_backgroundOverlay, NIL, pwin, @d);
END;
PROCEDURE TTauGameMain.Draw_PauseScreen(pwin: PSDL_Surface);
VAR
str: string;
str2: string;
BEGIN
str := ' $0$0$0$1$2$3$3::[PAUZA]::$3$3$2$1$0$0$0 ';
Ren_Text(str, TETRIS_BOARD_RENDER_OFFSETX + TETRIS_BOARD_WIDTH * 16 - (Length(str) DIV 2) * 16 + (((Length(str) MOD 2)* 16) DIV 2), 600-16*4, pwin);
str2 := ' [nastavi]; restart; isk$lu$xi ';
IF (i_menuoption = 1) THEN str2 := ' nastavi; [restart]; isk$lu$xi '
ELSE IF (i_menuoption = 2) THEN str2 := ' nastavi; restart; [isk$lu$xi] ';
Ren_Text(str2, 0, 600-16*3, pwin);
Ren_Text(pauseStringMovText, 0, 600-16*2, pwin);
END;
PROCEDURE TTauGameMain.Draw_Background(pwin: PSDL_Surface);
VAR
d: TSDL_Rect;
x, y: integer;
sx, sy: integer;
BEGIN
sx := Trunc(-f_backgroundoffsetX)-128;
sy := Trunc(-f_backgroundoffsetY)-128;
x := sx;
y := sy;
d.x := 0;
d.y := 0;
d.w := 0;
d.h := 0;
WHILE (y < 600) DO
BEGIN
d.y := y;
x := sx;
WHILE (x < 800) DO
BEGIN
d.x := x;
IF (SDL_BlitSurface(srf_backgroundGrid, NIL, pwin, @d) <> 0) THEN
BEGIN
WriteLn('! REN ' + SDL_GetError());
END;
x := x + srf_backgroundGrid^.w;
END;
y := y + srf_backgroundGrid^.h;
END;
END;
END.
|
//
// Generated by JavaToPas v1.5 20180804 - 082445
////////////////////////////////////////////////////////////////////////////////
unit android.service.autofill.RegexValidator;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
Androidapi.JNI.os,
android.view.autofill.AutofillId,
java.util.regex.Matcher;
type
JRegexValidator = interface;
JRegexValidatorClass = interface(JObjectClass)
['{17B941B3-B998-41E5-89B8-DF89D1937660}']
function _GetCREATOR : JParcelable_Creator; cdecl; // A: $19
function describeContents : Integer; cdecl; // ()I A: $1
function init(id : JAutofillId; regex : JPattern) : JRegexValidator; cdecl; // (Landroid/view/autofill/AutofillId;Ljava/util/regex/Pattern;)V A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
procedure writeToParcel(parcel : JParcel; flags : Integer) ; cdecl; // (Landroid/os/Parcel;I)V A: $1
property CREATOR : JParcelable_Creator read _GetCREATOR; // Landroid/os/Parcelable$Creator; A: $19
end;
[JavaSignature('android/service/autofill/RegexValidator')]
JRegexValidator = interface(JObject)
['{75077921-6CEA-4A14-97E8-F79F5E2BF838}']
function describeContents : Integer; cdecl; // ()I A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
procedure writeToParcel(parcel : JParcel; flags : Integer) ; cdecl; // (Landroid/os/Parcel;I)V A: $1
end;
TJRegexValidator = class(TJavaGenericImport<JRegexValidatorClass, JRegexValidator>)
end;
implementation
end.
|
unit EraConv;
// -----------------------------------------------------------------------------
// EraConvコンポーネント ver.1.2.0 for Delphi
// Copyright (c) みず
// -----------------------------------------------------------------------------
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
type
TEraConv = class(TComponent)
private
{ Private 宣言 }
FDate: TDate; // 西暦の日付
FEraname: String; // 元号
FEYear, FEMonth, FEDay: Word; // 年号
protected
{ Protected 宣言 }
procedure SetDate(const Value: TDate);
public
{ Public 宣言 }
property Eraname: String read FEraname;
property EYear: Word read FEYear;
property EMonth: Word read FEMonth;
property EDay: Word read FEDay;
constructor Create(AOwner: TComponent); override;
function EraToAd(var Ad: TDate; EraStr: String; Y, M, D: Word): Boolean;
published
{ Published 宣言 }
property Date: TDate read FDate write SetDate;
end;
procedure Register;
const
Reg = 3; // ##### 現在登録されている元号の数 - 1 #####
var
Era: array[0..Reg] of String;
Erastart: array[0..Reg] of TDate;
implementation
procedure Register;
begin
RegisterComponents('MIZU', [TEraConv]);
end;
{ TEraConv }
constructor TEraConv.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDate := SysUtils.Date;
end;
function TEraConv.EraToAd(var Ad: TDate; EraStr: String; Y, M,
D: Word): Boolean;
var
Lp: Integer;
Ys, Ms, Ds: Word;
begin
Result := False;
Ad := SysUtils.Date;
if (Y >= 1) and (M >=1) and (M <= 12) and (D >= 1) and (D <= 31) then
begin
for Lp := 0 to Reg do
if Era[Lp] = EraStr then
begin
DecodeDate(Erastart[Lp], Ys, Ms, Ds);
Ad := EncodeDate(Y + Ys - 1, M, D);
Result := True;
end; // +++ if Era[Lp]...
end; // +++ if (Y...
end;
procedure TEraConv.SetDate(const Value: TDate);
var
Y, M, D: Word;
Y2, M2, D2: Word;
InputDate: TDate;
Lp: Integer;
begin
InputDate := Value;
if Value < Erastart[0] then InputDate := Erastart[0];
DecodeDate(InputDate, Y, M, D);
FEMonth := M;
FEDay := D;
for Lp := 0 to Reg do
if Erastart[Lp] <= InputDate then
begin
FEraname := Era[Lp];
DecodeDate(Erastart[Lp], Y2, M2, D2);
FEYear := Y - Y2 + 1;
end;
FDate := InputDate;
end;
initialization
Era[0] := '明治';
Era[1] := '大正';
Era[2] := '昭和';
Era[3] := '平成';
Erastart[0] := EncodeDate(1868,9,8);
Erastart[1] := EncodeDate(1912,7,30);
Erastart[2] := EncodeDate(1926,12,25);
Erastart[3] := EncodeDate(1989,1,8);
end.
|
unit uin;
// Генерация и хранение уникальных идентификаторов
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
// Класс создающий и отслеживающий неповторяющиеся идентификаторы
type
TUin=class
private
Number: Integer; // Следующий доступный идентификатор
Erased: Array of Integer; // Список удаленных идентификаторов
public
constructor Create(); // Конструктор
destructor Destroy(); override; // Деструктор
function GetNewId(): Integer; // Получение нового неповторяющегося идентификатора
procedure AddErasedId(Id: Integer); // Возврат ненужного идентификатора
procedure Init(); // Начальное состояние генератора
end;
//////////////////////////////////////////////////////////////////////////////////////
implementation
// Начальное состояние генератора
procedure TUin.Init();
begin
// Обнуляем данные
SetLength(Erased, 0);
Number:=0;
end;
//////////////////////////////////////////////////////////////////////////////////////
// Возврат ненужного идентификатора
procedure TUin.AddErasedId(Id: Integer);
var
count: Integer;
begin
// Количество идентификаторов
Count:=length(Erased);
SetLength(Erased, count+1);
Erased[count]:=Id;
end;
//////////////////////////////////////////////////////////////////////////////////////
// Получение нового неповторяющегося идентификатора
function TUin.GetNewId(): Integer;
var
count: Integer;
begin
// Если среди удаленных идентификаторов?
count:=Length(Erased);
if count>0 then
begin
// Отдадим удаленный ранее идентификатор
Dec(count);
Result:=Erased[count];
SetLength(Erased, count);
Exit;
end;
// Новый идентификатор
Result:=Number;
Inc(Number);
end;
//////////////////////////////////////////////////////////////////////////////////////
// Деструктор
destructor TUin.Destroy();
begin
// Поля
SetLength(Erased, 0);
// Предок
Inherited Destroy;
end;
//////////////////////////////////////////////////////////////////////////////////////
// Конструктор
constructor TUin.Create();
begin
// Предок
Inherited Create;
// Начальное значение
Number:=0;
// Удаленные идентификаторы
SetLength(Erased, 0);
end;
//////////////////////////////////////////////////////////////////////////////////////
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.